bib2html.py: Print entry type
[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_links(entry):
128 doi = format_field(entry, 'doi', pre='<a href="http://dx.doi.org/', post='">[DOI]</a>')
129 webpdf = format_field(entry, 'webpdf', pre='<a href="', post='">[PDF]</a>')
130 weblink = format_field(entry, 'weblink', pre='<a href="', post='">[link]</a>')
131 url = format_field(entry, 'url', pre='<a href="', post='">[url]</a>')
132 webslides = format_field(entry, 'webslides', pre='<a href="', post='">[slides]</a>')
133 weberrata = format_field(entry, 'weberrata', pre='<a href="',
134 post='">[errata]</a>')
135 return " ".join([doi, webpdf, weblink, url, webslides, weberrata])
136
137 def format_entry(entry):
138 lines = []
139 lines.append(format_field(entry, 'title', pre="<b>", post="</b>"))
140 lines.append(format_field_span('author', format_authors(entry)))
141
142 if entry.type=='article':
143 lines.extend(format_details_article(entry))
144 elif entry.type=='inproceedings':
145 lines.extend(format_details_inproceedings(entry))
146 elif entry.type=='book':
147 lines.extend(format_details_book(entry))
148 elif entry.type in ['mastersthesis', 'phdthesis']:
149 lines.extend(format_details_thesis(entry))
150 else:
151 lines.append("Unknown type <b>'" + entry.type + "'</b>")
152
153 lines.append(format_field(entry, 'webnote'))
154 lines.append(format_links(entry))
155
156 lines = filter(lambda l: l != "", lines)
157 return "<br/>\n".join(lines)
158
159
160 def entryDateSortKey(p):
161 k, e = p
162
163 if 'date' in e.fields:
164 return e.fields['date']
165
166 month2num = { 'jan' : '01', 'feb' : '02', 'mar' : '03', \
167 'apr' : '04', 'may' : '05', 'jun' : '06', \
168 'jul' : '07', 'aug' : '08', 'sep' : '09', \
169 'oct' : '10', 'nov' : '11', 'dec' : '12'}
170
171 if not 'month' in e.fields:
172 return e.fields['year']
173
174 month = e.fields['month'].lower()[0:3]
175 if month in month2num:
176 month = month2num[month]
177 else:
178 month = ""
179
180 return e.fields['year'] + "-" + month
181
182
183 def entryGetYear(e):
184 if 'year' in e.fields:
185 return e.fields['year']
186
187 if 'date' in e.fields:
188 dt = dateutil.parser.isoparse(e.fields['date'])
189 return str(dt.year)
190
191 return None
192
193
194 def usage():
195 """Print usage text of this program"""
196
197 print("""Usage:
198 {0} -i FILE
199 {0} -h
200
201 OPTIONS:
202 -h print this text
203 -i .bib file
204 """.format(sys.argv[0]))
205
206 if __name__ == "__main__":
207
208 bibfile = None
209
210 try:
211 opts, args = getopt.getopt(sys.argv[1:], "hi:")
212
213 for opt, arg in opts:
214 if opt == "-h":
215 usage()
216 sys.exit(os.EX_OK)
217 elif opt == "-i":
218 bibfile = arg
219 else:
220 print("Unknown option '", opt, "'.")
221
222 except getopt.GetoptError as e:
223 print("Error parsing arguments:", e)
224 usage()
225
226 if bibfile == None:
227 print("You need to specify a bibfile")
228 usage()
229 sys.exit(os.EX_USAGE)
230
231
232 from pybtex.database.input import bibtex
233 parser = bibtex.Parser()
234
235 from pybtex.style.formatting.unsrt import Style
236
237 bib_data = parser.parse_file(bibfile)
238 entries = bib_data.entries
239
240 years = list(set([entryGetYear(e) for e in entries.values()]))
241 years.sort(reverse=True)
242
243 for year in years:
244
245 print("<h2>" + year + "</h2>")
246
247 iteritems = list(entries.items())
248 iteritems.sort(key=entryDateSortKey, reverse=True)
249 for key, entry in iteritems:
250
251 if entryGetYear(entry) != year:
252 continue
253
254 print("<div class=bibentry>")
255 print("<a class=bibentry_key id={}>[{}]</a><br/><span class=bibentry_type>{}</span><br/>".format(key, key, entry.type))
256 e = format_entry(entry)
257 print(e)
258
259 print("</div>\n")