bib2html.py: Add support for patents
[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 import dateutil.parser
36
37
38 def format_latex(text):
39 # Get rid of matching dollar signs
40 text = re.sub(r'\$([^\$]*)\$', r'\1', text)
41
42 # Replace text
43 subst = {
44 '\\"a': 'ä',
45 '\\"o': 'ö',
46 '\\"u': 'u',
47 '\mathcal': '',
48 '{': '',
49 '}': '',
50 '\\': '',
51 '~': ' ',
52 '---': '–',
53 '--': '–',
54 }
55
56 for a, b in subst.items():
57 text = text.replace(a, b)
58
59 return text
60
61 def format_field_span(type, value):
62 return "<span class=bibentry_" + type + ">" + format_latex(value) + "</span>"
63
64 def format_field(bibentry, field, pre='', post=''):
65 if field in bibentry.fields:
66 if bibentry.fields[field] != "":
67 return format_field_span(field, pre + bibentry.fields[field] + post)
68 return ""
69
70 def format_author(a):
71 return ' '.join(' '.join(p) for p in (a.first_names, a.middle_names, a.prelast_names, a.last_names, a.lineage_names) if p)
72
73 def format_authors(entry):
74 return ", ".join([format_author(a) for a in entry.persons['author']])
75
76
77 def format_details_article(entry):
78
79 where = format_field(entry, 'journal')
80
81 line = []
82 line.append(format_field(entry, 'pages', pre='pp. '))
83 line.append(format_field(entry, 'volume', pre='vol. ') + \
84 format_field(entry, 'number', pre='(', post=')'))
85 line.append(format_field(entry, 'month', post=' ') + \
86 format_field(entry, 'year'))
87 line.append(format_field(entry, 'note'))
88
89 line = filter(lambda l: l != "", line)
90 return [where, ", ".join(line)]
91
92 def format_details_inproceedings(entry):
93 where = format_field(entry, 'booktitle')
94
95 line = []
96 line.append(format_field(entry, 'pages', pre='pp. '))
97 line.append(format_field(entry, 'address'))
98 line.append(format_field(entry, 'month', post=' ') + \
99 format_field(entry, 'year'))
100 line.append(format_field(entry, 'isbn', pre='ISBN '))
101 line.append(format_field(entry, 'note'))
102
103 line = filter(lambda l: l != "", line)
104 return [where, ", ".join(line)]
105
106 def format_details_thesis(entry):
107 line = []
108 line.append(format_field(entry, 'school'))
109 line.append(format_field(entry, 'month', post=' ') + \
110 format_field(entry, 'year'))
111 line.append(format_field(entry, 'note'))
112
113 line = filter(lambda l: l != "", line)
114 return [", ".join(line)]
115
116 def format_details_book(entry):
117 line = []
118 line.append(format_field(entry, 'publisher'))
119 line.append(format_field(entry, 'isbn', pre='ISBN '))
120 line.append(format_field(entry, 'month', post=' ') + \
121 format_field(entry, 'year'))
122 line.append(format_field(entry, 'note'))
123
124 line = filter(lambda l: l != "", line)
125 return [", ".join(line)]
126
127 def format_details_patent(entry):
128 line = []
129 line.append(format_field(entry, 'number', pre='Pat. '))
130 line.append(format_field(entry, 'month', post=' ') + \
131 format_field(entry, 'year'))
132 line.append(format_field(entry, 'note'))
133
134 line = filter(lambda l: l != "", line)
135 return [", ".join(line)]
136
137 def format_links(entry):
138 doi = format_field(entry, 'doi', pre='<a href="http://dx.doi.org/', post='">[DOI]</a>')
139 webpdf = format_field(entry, 'webpdf', pre='<a href="', post='">[PDF]</a>')
140 weblink = format_field(entry, 'weblink', pre='<a href="', post='">[link]</a>')
141 url = format_field(entry, 'url', pre='<a href="', post='">[url]</a>')
142 webslides = format_field(entry, 'webslides', pre='<a href="', post='">[slides]</a>')
143 weberrata = format_field(entry, 'weberrata', pre='<a href="',
144 post='">[errata]</a>')
145 return " ".join([doi, webpdf, weblink, url, webslides, weberrata])
146
147 def format_entry(entry):
148 lines = []
149 lines.append(format_field(entry, 'title', pre="<b>", post="</b>"))
150 lines.append(format_field_span('author', format_authors(entry)))
151
152 if entry.type=='article':
153 lines.extend(format_details_article(entry))
154 elif entry.type=='inproceedings':
155 lines.extend(format_details_inproceedings(entry))
156 elif entry.type=='book':
157 lines.extend(format_details_book(entry))
158 elif entry.type=='patent':
159 lines.extend(format_details_patent(entry))
160 elif entry.type in ['mastersthesis', 'phdthesis']:
161 lines.extend(format_details_thesis(entry))
162 else:
163 lines.append("Unknown type <b>'" + entry.type + "'</b>")
164
165 lines.append(format_field(entry, 'webnote'))
166 lines.append(format_links(entry))
167
168 lines = filter(lambda l: l != "", lines)
169 return "<br/>\n".join(lines)
170
171
172 def entryDateSortKey(p):
173 k, e = p
174
175 if 'date' in e.fields:
176 return e.fields['date']
177
178 month2num = { 'jan' : '01', 'feb' : '02', 'mar' : '03', \
179 'apr' : '04', 'may' : '05', 'jun' : '06', \
180 'jul' : '07', 'aug' : '08', 'sep' : '09', \
181 'oct' : '10', 'nov' : '11', 'dec' : '12'}
182
183 if not 'month' in e.fields:
184 return e.fields['year']
185
186 month = e.fields['month'].lower()[0:3]
187 if month in month2num:
188 month = month2num[month]
189 else:
190 month = ""
191
192 return e.fields['year'] + "-" + month
193
194
195 def entryGetYear(e):
196 if 'year' in e.fields:
197 return e.fields['year']
198
199 if 'date' in e.fields:
200 dt = dateutil.parser.isoparse(e.fields['date'])
201 return str(dt.year)
202
203 return None
204
205
206 def usage():
207 """Print usage text of this program"""
208
209 print("""Usage:
210 {0} -i FILE
211 {0} -h
212
213 OPTIONS:
214 -h print this text
215 -i .bib file
216 """.format(sys.argv[0]))
217
218 if __name__ == "__main__":
219
220 bibfile = None
221
222 try:
223 opts, args = getopt.getopt(sys.argv[1:], "hi:")
224
225 for opt, arg in opts:
226 if opt == "-h":
227 usage()
228 sys.exit(os.EX_OK)
229 elif opt == "-i":
230 bibfile = arg
231 else:
232 print("Unknown option '", opt, "'.")
233
234 except getopt.GetoptError as e:
235 print("Error parsing arguments:", e)
236 usage()
237
238 if bibfile == None:
239 print("You need to specify a bibfile")
240 usage()
241 sys.exit(os.EX_USAGE)
242
243
244 from pybtex.database.input import bibtex
245 parser = bibtex.Parser()
246
247 from pybtex.style.formatting.unsrt import Style
248
249 bib_data = parser.parse_file(bibfile)
250 entries = bib_data.entries
251
252 years = list(set([entryGetYear(e) for e in entries.values()]))
253 years.sort(reverse=True)
254
255 for year in years:
256
257 print("<h2>" + year + "</h2>")
258
259 iteritems = list(entries.items())
260 iteritems.sort(key=entryDateSortKey, reverse=True)
261 for key, entry in iteritems:
262
263 if entryGetYear(entry) != year:
264 continue
265
266 print("<div class=bibentry>")
267 print("<a class=bibentry_key id={}>[{}]</a><br/><span class=bibentry_type>{}</span><br/>".format(key, key, entry.type))
268 e = format_entry(entry)
269 print(e)
270
271 print("</div>\n")