bib2html.py: Add incollection bibtype
[shutils.git] / bib2html.py
1 #!/usr/bin/env python3
2 """Creates a webpage with all entries of a .bib file"""
3
4 __version__ = "1.1"
5
6 __author__ = "Stefan Huber"
7 __email__ = "shuber@sthu.org"
8 __copyright__ = "Copyright 2013, Stefan Huber"
9
10 __license__ = "MIT"
11
12 # Permission is hereby granted, free of charge, to any person
13 # obtaining a copy of this software and associated documentation
14 # files (the "Software"), to deal in the Software without
15 # restriction, including without limitation the rights to use,
16 # copy, modify, merge, publish, distribute, sublicense, and/or sell
17 # copies of the Software, and to permit persons to whom the
18 # Software is furnished to do so, subject to the following
19 # conditions:
20 #
21 # The above copyright notice and this permission notice shall be
22 # included in all copies or substantial portions of the Software.
23 #
24 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
26 # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
28 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
29 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
30 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
31 # OTHER DEALINGS IN THE SOFTWARE.
32
33
34 import os, sys, getopt, re
35
36
37 def format_latex(text):
38 # Get rid of matching dollar signs
39 text = re.sub(r'\$([^\$]*)\$', r'\1', text)
40 return text.replace('\mathcal', '').replace('{', '').replace('}', '').replace('\\', '')
41
42 def format_field_span(type, value):
43 return "<span class=bibentry_" + type + ">" + format_latex(value) + "</span>"
44
45 def format_field(bibentry, field, pre='', post=''):
46 if field in bibentry.fields:
47 if bibentry.fields[field] != "":
48 return format_field_span(field, pre + bibentry.fields[field] + post)
49 return ""
50
51 def format_author(a):
52 return ' '.join(' '.join(p) for p in (a.first_names, a.middle_names, a.prelast_names, a.last_names, a.lineage_names) if p)
53
54 def format_authors(entry):
55 return ", ".join([format_author(a) for a in entry.persons['author']])
56
57
58 def format_details_article(entry):
59
60 where = format_field(entry, 'journal')
61
62 line = []
63 line.append(format_field(entry, 'pages', pre='pp. '))
64 line.append(format_field(entry, 'volume', pre='vol. ') + \
65 format_field(entry, 'number', pre='(', post=')'))
66 line.append(format_field(entry, 'month', post=' ') + \
67 format_field(entry, 'year'))
68 line = filter(lambda l: l != "", line)
69
70 return [where, ", ".join(line)]
71
72 def format_details_inproceedings(entry):
73 where = format_field(entry, 'booktitle')
74
75 line = []
76 line.append(format_field(entry, 'pages', pre='pp. '))
77 line.append(format_field(entry, 'address'))
78 line.append(format_field(entry, 'month', post=' ') + \
79 format_field(entry, 'year'))
80 line = filter(lambda l: l != "", line)
81 return [where, ", ".join(line)]
82
83 def format_details_thesis(entry):
84 line = []
85 line.append(format_field(entry, 'school'))
86 line.append(format_field(entry, 'month', post=' ') + \
87 format_field(entry, 'year'))
88 line = filter(lambda l: l != "", line)
89 return [", ".join(line)]
90
91 def format_details_book(entry):
92 line = []
93 line.append(format_field(entry, 'publisher'))
94 line.append(format_field(entry, 'isbn', pre='ISBN '))
95 line.append(format_field(entry, 'month', post=' ') + \
96 format_field(entry, 'year'))
97 line = filter(lambda l: l != "", line)
98 return [", ".join(line)]
99
100 def format_links(entry):
101 doi = format_field(entry, 'doi', pre='<a href="http://dx.doi.org/', post='">[DOI]</a>')
102 webpdf = format_field(entry, 'webpdf', pre='<a href="', post='">[PDF]</a>')
103 weblink = format_field(entry, 'weblink', pre='<a href="', post='">[link]</a>')
104 webslides = format_field(entry, 'webslides', pre='<a href="', post='">[slides]</a>')
105 weberrata = format_field(entry, 'weberrata', pre='<a href="',
106 post='">[errata]</a>')
107 return " ".join([doi, webpdf, weblink, webslides, weberrata])
108
109 def format_entry(entry):
110 lines = []
111 lines.append(format_field(entry, 'title', pre="<b>", post="</b>"))
112 lines.append(format_field_span('author', format_authors(entry)))
113
114 if entry.type=='article':
115 lines.extend(format_details_article(entry))
116 elif entry.type=='inproceedings':
117 lines.extend(format_details_inproceedings(entry))
118 elif entry.type=='book':
119 lines.extend(format_details_book(entry))
120 elif entry.type in ['mastersthesis', 'phdthesis']:
121 lines.extend(format_details_thesis(entry))
122 else:
123 lines.append("Unknown type <b>'" + entry.type + "'</b>")
124
125 lines.append(format_field(entry, 'webnote'))
126 lines.append(format_links(entry))
127
128 lines = filter(lambda l: l != "", lines)
129 return "<br/>\n".join(lines)
130
131
132 def entryDateSortKey(p):
133 k, e = p
134
135 month2num = { 'jan' : '01', 'feb' : '02', 'mar' : '03', \
136 'apr' : '04', 'may' : '05', 'jun' : '06', \
137 'jul' : '07', 'aug' : '08', 'sep' : '09', \
138 'oct' : '10', 'nov' : '11', 'dec' : '12'}
139
140 if not 'month' in e.fields:
141 return e.fields['year']
142
143 month = e.fields['month'].lower()[0:3]
144 if month in month2num:
145 month = month2num[month]
146 else:
147 month = ""
148
149 return e.fields['year'] + "-" + month
150
151
152 def usage():
153 """Print usage text of this program"""
154
155 print("""Usage:
156 {0} -i FILE
157 {0} -h
158
159 OPTIONS:
160 -h print this text
161 -i .bib file
162 """.format(sys.argv[0]))
163
164 if __name__ == "__main__":
165
166 bibfile = None
167
168 try:
169 opts, args = getopt.getopt(sys.argv[1:], "hi:")
170
171 for opt, arg in opts:
172 if opt == "-h":
173 usage()
174 sys.exit(os.EX_OK)
175 elif opt == "-i":
176 bibfile = arg
177 else:
178 print("Unknown option '", opt, "'.")
179
180 except getopt.GetoptError as e:
181 print("Error parsing arguments:", e)
182 usage()
183
184 if bibfile == None:
185 print("You need to specify a bibfile")
186 usage()
187 sys.exit(os.EX_USAGE)
188
189
190 from pybtex.database.input import bibtex
191 parser = bibtex.Parser()
192
193 from pybtex.style.formatting.unsrt import Style
194
195 bib_data = parser.parse_file(bibfile)
196 entries = bib_data.entries
197
198 years = list(set([ b.fields['year'] for b in entries.values() ]))
199 years.sort(reverse=True)
200
201 for year in years:
202
203 print("<h2>" + year + "</h2>")
204
205 iteritems = list(entries.items())
206 iteritems.sort(key=entryDateSortKey, reverse=True)
207 for key, entry in iteritems:
208
209 if entry.fields['year'] != year:
210 continue
211
212 print("<div class=bibentry>")
213 print("<a class=bibentry_key id=" + key + ">[" + key + "]</a><br/>")
214
215 e = format_entry(entry)
216 print(e)
217
218 print("</div>\n")
219