Add bib2html.py
authorStefan Huber <shuber@sthu.org>
Wed, 16 Oct 2013 12:36:55 +0000 (14:36 +0200)
committerStefan Huber <shuber@sthu.org>
Wed, 16 Oct 2013 12:36:55 +0000 (14:36 +0200)
bib2html.py [new file with mode: 0755]

diff --git a/bib2html.py b/bib2html.py
new file mode 100755 (executable)
index 0000000..28abd58
--- /dev/null
@@ -0,0 +1,209 @@
+#!/usr/bin/env python2
+"""Creates a webpage with all entries of a .bib file"""
+
+__version__ = "1.0"
+
+__author__ = "Stefan Huber"
+__email__ = "shuber@sthu.org"
+__copyright__ = "Copyright 2013, Stefan Huber"
+
+__license__ = "MIT"
+
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without
+# restriction, including without limitation the rights to use,
+# copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the
+# Software is furnished to do so, subject to the following
+# conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+# OTHER DEALINGS IN THE SOFTWARE.
+
+
+import os, sys, getopt
+
+
+def format_latex(text):
+    return text.replace('{', '').replace('}', '').replace('\\', '')
+
+def format_field_span(type, value):
+    return "<span class=bibentry_" + type + ">" + format_latex(value) + "</span>"
+
+def format_field(bibentry, field, pre='', post=''):
+    if field in bibentry.fields:
+        return format_field_span(field, pre + bibentry.fields[field] + post)
+    return ""
+
+def format_author(a):
+    return  ' '.join(' '.join(p) for p in (a.first(), a.middle(), a.prelast(), a.last(), a.lineage()) if p)
+
+def format_authors(entry):
+    return ", ".join([format_author(a) for a in entry.persons['author']])
+
+
+def format_details_article(entry):
+
+    where = format_field(entry, 'journal')
+
+    line = []
+    line.append(format_field(entry, 'pages', pre='pp. '))
+    line.append(format_field(entry, 'volume', pre='vol. ') + \
+            format_field(entry, 'number', pre='(', post=')'))
+    line.append(format_field(entry, 'month', post=' ') + \
+            format_field(entry, 'year'))
+    line = filter(lambda l: l != "", line)
+
+    return [where, ", ".join(line)]
+
+def format_details_inproceedings(entry):
+    where = format_field(entry, 'booktitle')
+
+    line = []
+    line.append(format_field(entry, 'pages', pre='pp. '))
+    line.append(format_field(entry, 'address'))
+    line.append(format_field(entry, 'month', post=' ') + \
+            format_field(entry, 'year'))
+    line = filter(lambda l: l != "", line)
+    return [where, ", ".join(line)]
+
+def format_details_thesis(entry):
+    line = []
+    line.append(format_field(entry, 'school'))
+    line.append(format_field(entry, 'month', post=' ') + \
+            format_field(entry, 'year'))
+    line = filter(lambda l: l != "", line)
+    return [", ".join(line)]
+
+def format_details_book(entry):
+    line = []
+    line.append(format_field(entry, 'publisher'))
+    line.append(format_field(entry, 'isbn', pre='ISBN '))
+    line.append(format_field(entry, 'month', post=' ') + \
+            format_field(entry, 'year'))
+    line = filter(lambda l: l != "", line)
+    return [", ".join(line)]
+
+def format_links(entry):
+    webpdf = format_field(entry, 'webpdf', pre='<a href="', post='">[PDF]</a>')
+    weblink = format_field(entry, 'weblink', pre='<a href="', post='">[link]</a>')
+    webslides = format_field(entry, 'webslides', pre='<a href="', post='">[slides]</a>')
+    weberrata = format_field(entry, 'weberrata', pre='<a href="',
+            post='">[errata]</a>')
+    return " ".join([webpdf, weblink, webslides, weberrata])
+
+def format_entry(entry):
+    lines = []
+    lines.append(format_field(entry, 'title', pre="<b>", post="</b>"))
+    lines.append(format_field_span('author', format_authors(entry)))
+
+    if entry.type=='article':
+        lines.extend(format_details_article(entry))
+    elif entry.type=='inproceedings':
+        lines.extend(format_details_inproceedings(entry))
+    elif entry.type=='book':
+        lines.extend(format_details_book(entry))
+    elif entry.type in ['mastersthesis', 'phdthesis']:
+        lines.extend(format_details_thesis(entry))
+    else:
+        lines.append("Unknown type <b>'" + entry.type + "'</b>")
+
+    lines.append(format_field(entry, 'webnote'))
+    lines.append(format_links(entry))
+
+    lines = filter(lambda l: l != "", lines)
+    return "<br/>\n".join(lines)
+
+
+def entryCompareDate(p1, p2):
+    k1, e1 = p1
+    k2, e2 = p2
+
+
+    def toStr(e):
+        month = { 'jan' : '01', 'feb' : '02', 'mar' : '03', \
+                'apr' : '04', 'may' : '05', 'jun' : '06', \
+                'jul' : '07', 'aug' : '08', 'sep' : '09', \
+                'oct' : '10', 'nov' : '11', 'dec' : '12'}
+        return e.fields['year'] + "-" + month[e.fields['month'].lower()[0:3]]
+
+    return cmp(toStr(e1), toStr(e2))
+
+
+def usage():
+    """Print usage text of this program"""
+
+    print("""Usage:
+  {0} -i FILE
+  {0} -h
+
+OPTIONS:
+  -h       print this text
+  -i       .bib file
+""".format(sys.argv[0]))
+
+if __name__ == "__main__":
+
+    bibfile = None
+
+    try:
+        opts, args = getopt.getopt(sys.argv[1:], "hi:")
+
+        for opt, arg in opts:
+            if opt == "-h":
+                usage()
+                sys.exit(os.EX_OK)
+            elif opt == "-i":
+                bibfile = arg
+            else:
+                print("Unknown option '", opt, "'.")
+
+    except getopt.GetoptError as e:
+        print("Error parsing arguments:", e)
+        usage()
+
+    if bibfile == None:
+        print("You need to specify a bibfile")
+        usage()
+        sys.exit(os.EX_USAGE)
+
+
+    from pybtex.database.input import bibtex
+    parser = bibtex.Parser()
+
+    from pybtex.style.formatting.unsrt import Style
+
+    bib_data = parser.parse_file(bibfile)
+    entries = bib_data.entries
+
+    years = list(set([ b.fields['year'] for b in entries.values() ]))
+    years.sort(reverse=True)
+
+    for year in years:
+
+        print("<h2>" + year + "</h2>")
+
+        iteritems = list(entries.iteritems())
+        iteritems.sort(cmp=entryCompareDate, reverse=True)
+        for key, entry in iteritems:
+
+            if entry.fields['year'] != year:
+                continue
+
+            print("<div class=bibentry>")
+            print("<a class=bibentry_key id=" + key + ">[" + key + "]</a><br/>")
+
+            print(format_entry(entry).encode('utf8'))
+
+            print("</div>\n")
+