-
Notifications
You must be signed in to change notification settings - Fork 19
/
zot.py
executable file
·2453 lines (1975 loc) · 93.9 KB
/
zot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
"""Add a fast, interactive Zotero bibiography to your website.
This tool will retrieve a set of collections and format an interactive
bibliography in HTML5. The bibliography contains BibTeX records and
abstracts that can be revealed upon clicking. The output is ready
to be included in other websites (there are options), and it can be
easily styles using CSS (see style.css).
The primary way to configure a web bibliography is via a settings file.
The file settings.py is loaded by default, if present.
See settings_example.py for documentation.
Latest versions: https://github.com/davidswelt/zot_bib_web
Documentation: http://zot-bib-web.readthedocs.io
(C) 2014,2015,2016,2017,2019 David Reitter
Released under the GNU General Public License, V.3 or later.
For usage, see: zot.py --help
"""
# zot_bib_web
from __future__ import print_function
from __future__ import unicode_literals
#############################################################################
# See settings_example.py for configuration information
# Create settings.py to supply your configuration.
# The following items are defaults.
verbosity = 0 #: How much diagnostic output to print
titlestring = 'Bibliography' #: The title shown for the bibliography document
bib_style = 'apa' #: Style. 'apa', 'mla', or any other style known to Zotero
write_full_html_header = True #: If True, a standalone HTML file is written (default).
stylesheet_url = "site/style.css" #: URL to the style file on the web server.
outputfile = 'zotero-bib.html' #: The resulting HTML document will be in this file.
file_outputdir = '' #: Directory used for attachments that come with the bibliography items.
file_output_path = "" #: URL to the directory for attachments when on the server.
jquery_path = "site/jquery.min.js" #: URL to jQuery on the server
# jquery_path = "../wp-includes/js/jquery/jquery.js" # wordpress location
number_bib_items = False #: If True, enumerate bibliographic items within a category as a list.
show_copy_button = True #: If True, show a button that copies text to clipboard.
clipboard_js_path = "site/clipboard.min.js" #: URL to Clipboard.min.js on the server.
copy_button_path = "site/clippy.svg" #: URL to clippy.svg on the server.
show_search_box = True #: Show a search box
#: List of shortcuts.
#: Permissible values include the strings ``'collection', 'year', 'type', 'venue', and 'venue_short'``,
#: or objects made with the function :func:`shortcut`.
show_shortcuts = ['collection']
#: List of Links.
#: Possible values: ``'abstract', 'url', 'BIB', 'Wikipedia', 'EndNote', 'RIS', 'MLA', 'Cite.MLA', 'Cite.APA', 'Cite.<STYLE>'``
show_links = ['abstract', 'url', 'BIB', 'Wikipedia', 'EndNote']
file_link_button_label = "PDF" #: Set to None for label specific to the document (link, PS, PDF)
omit_COinS = False #: If True, do not include COInS metadata
smart_selections = True #: If True, prevent user from selecting/copying text that shouldn't be copied.
__all__ = ['titlestring', 'bib_style',
'sort_criteria', 'show_top_section_headings',
'number_bib_items',
'show_shortcuts', 'shortcut', 'show_links',
'omit_COinS', 'smart_selections',
'outputfile', 'write_full_html_header', 'stylesheet_url', 'jquery_path',
'show_copy_button', 'clipboard_js_path', 'copy_button_path', 'show_search_box',
'content_filter', 'no_cache',
'language_code', 'sortkeyname_order', 'link_translations']
def fix_bibtex_reference(bib, _thisatom):
"Fix reference style for BIB entries: use authorYEARfirstword convention."
sub = re.sub(r'(?<=[a-z\s]{)(?P<name>[^_\s,]+)_(?P<firstword>[^_\s,]+)_(?P<year>[^_\s,]+)(?=\s*,\s*[\r\n])',
"\g<name>\g<year>\g<firstword>", bib, count=1)
return sub or bib
#: Content filter for viewable or downloadable bibliographic content.
#: Dict mapping strings to functions.
#: Currently, only the function `fix_bibtex_reference` is supported,
#: which changes bibtex reference symbols to the format nameYEARfirstword, e.g.
#: smith2000towards.
content_filter = {'bib': fix_bibtex_reference}
#: List of strings giving a hierarchy of subsections and ordering within them.
#: Possible values include 'collection', 'year', 'type'.
#: Prepend an item with '-', e.g., '-year' to sort in descending order.
sort_criteria = ['collection', '-year', 'type']
#: Number of first sort_criteria to show as section headings
#: E.g., if 1, the first element from :data:`sort_criteria` will be shown as section
#: heading, and the rest without section headings (but ordered).
show_top_section_headings = 1
no_cache = False #: If True, avoid use of cache
interactive_debugging = False
language_code = 'en'
""" Language code used for :data:`sortkeyname_order` and :data:`link_translations`
Define labels for article types and their ordering
Dict, keys are language codes (indicating target language),
values are dicts mapping fields to lists.
Fields indicate bib item fiels such as 'type' or 'date'.
In the Zotero database, these may be in libraryCatalog or itemType.
Lists are lists ordered by sort order.
Each list element is a tuple of the form (value, label), where
value indicates a value appropriate for the field, and the
label is what is shown for that value in section headings and shortcuts.
Example::
'en' -> 'type' -> [('journalArticle', 'Journal Articles'), ...]
'en' -> 'date' -> [('in preparation', 'in prep.'), ...]
Example::
sortkeyname_order['en']['type'] = [
('journalArticle', 'Journal Articles'),
('archivalConferencePaper', 'Archival Conference Publications'),
('conferencePaper', 'Conference and Workshop Papers'),
('book', 'Books'),
('bookSection', 'Book Chapters'),
('edited-volume', "Edited Volumes"),
('thesis', 'Theses'),
('report', 'Tech Reports'),
('attachment', 'Document'),
('webpage', 'Web Site'),
('presentation', 'Talks'),
('computerProgram', 'Computer Programs')]
"""
sortkeyname_order = {}
sortkeyname_order['en'] = {}
sortkeyname_order['en']['type'] = [
('journalArticle', 'Journal Articles'),
('archivalConferencePaper', 'Archival Conference Publications'),
('conferencePaper', 'Conference and Workshop Papers'),
('book', 'Books'),
('bookSection', 'Book Chapters'),
('edited-volume', "Edited Volumes"),
('thesis', 'Theses'),
('report', 'Tech Reports'),
('attachment', 'Document'),
('webpage', 'Web Site'),
('presentation', 'Talks'),
('computerProgram', 'Computer Programs')]
sortkeyname_order['en']['date'] = sortkeyname_order['en']['year'] = [
(None, None), # sort all other values here
('in preparation', None),
('submitted', None),
('in review', None),
('accepted', None),
('to appear', None),
('in press', None)]
sortkeyname_order['de'] = {}
sortkeyname_order['de']['type'] = [
('journalArticle', 'Journal-Artikel'),
('archivalConferencePaper', u'Konferenz-Veröffentlichungen'),
('conferencePaper', 'Konferenz- und Workshop-Papiere'),
('book', u'Bücher'),
('bookSection', 'Kapitel'),
('edited-volume', "Sammlungen (als Herausgeber)"),
('thesis', 'Dissertationen'),
('report', 'Technische Mitteilungen'),
('presentation', u'Vorträge'),
('computerProgram', 'Software')]
#: Internationalization of link buttons (see also :py:data:`show_links`)
#: Dict, keys are language codes (indicating target language),
#: values are dicts giving translation lexicons.
#: Translation lexicons translate from English (keys) to the target language.
link_translations = {}
link_translations['de'] = {'abstract': 'Abstrakt', 'pdf': 'Volltext'}
##### legacy settings
order_by = None # order in each category: e.g., 'dateAdded', 'dateModified', 'title', 'creator', 'type', 'date', 'publisher', 'publication', 'journalAbbreviation', 'language', 'accessDate', 'libraryCatalog', 'callNumber', 'rights', 'addedBy', 'numItems'
# Note: this does not seem to work with current the Zotero API.
# If set, overrides sort_criteria
sort_order = 'desc' # "desc" or "asc"
catchallcollection = None
library_id = None
library_type = 'group'
api_key = None
toplevelfilter = None
#############################################################################
__version__ = "2.1.0"
#############################################################################
import sys
import errno
import re
def flexprint(*args, **kwargs):
global verbosity
level = 0 # default importance - print unless "quiet"
if 'level' in kwargs:
level = kwargs['level']
del kwargs['level']
if verbosity < - level:
return
try:
print(*args, **kwargs)
except UnicodeEncodeError:
f = kwargs['file'] if 'file' in kwargs else sys.stdout
for o in args:
print("{}".format(o).encode(f.encoding, errors="ignore"), **kwargs)
def default(dict, **kwargs):
for k,v in kwargs.items():
if not k in dict:
dict[k] = v
def warning(*objs, **kwargs):
default(kwargs, level=1, file=sys.stderr)
warn("WARNING: ", *objs, **kwargs)
def error(*objs, **kwargs):
default(kwargs, level=2, file=sys.stderr)
warn("ERROR: ", *objs, **kwargs)
def log(*objs, **kwargs):
default(kwargs, level=-1)
warn(*objs, **kwargs)
def progress(*objs, **kwargs):
default(kwargs, level=0)
warn(*objs, **kwargs)
def warn(*objs, **kwargs):
global outputfile
default(kwargs, level=1, file=sys.stderr)
flexprint(*objs, **kwargs)
if __name__ == '__main__': # not for documentation-building
from pyzotero import zotero, zotero_errors
def check_requirements ():
try:
v = float("%d.%02d%02d" % tuple(map(int, zotero.__version__.split(r'.'))))
if v < 1.0103:
warning("Pyzotero version is incompatible. Upgrade to 1.1.3 or later.")
sys.exit(1)
except SystemExit as e:
raise e
except:
warning("Pyzotero version could not be validated. 1.1.3 or later required.")
# redirect warnings (needed for InsecurePlatformWarning on Macs with standard Python)
import logging
logging.basicConfig(filename='zot_warnings.log', level=logging.NOTSET)
logging.captureWarnings(False)
import codecs
from texconv import tex2unicode
import base64
import os
from collections import namedtuple, defaultdict
import argparse
class Settings:
# To do: move settings into an object of class Settings
@staticmethod
def load_settings(file=None):
loadfile = file or "settings.py"
try:
# from settings import *
try:
import importlib
settings = importlib.machinery.SourceFileLoader("settings", loadfile).load_module()
except (AttributeError, ImportError):
# Python 2.7
import imp
settings = imp.load_source("settings", loadfile)
# import settings into local namespace:
unknown_symbols = []
for k, v in settings.__dict__.items():
if not "__" in k: # even if default is not defined (e.g., function definitions for content_filter)
if not k in globals() and not callable(v): # functions are usually harmless.
unknown_symbols += [k]
globals()[k] = v
# print(k,v)
if unknown_symbols:
warning("Settings file sets unknown configuration symbol%s %s." % ("s" if len(unknown_symbols)>1 else "", ", ".join(unknown_symbols)))
progress("Loaded settings from %s." % os.path.abspath(loadfile))
except ImportError:
pass
except (OSError, IOError) as e: # no settings file
if file:
if e.errno == errno.ENOENT:
error("%s file (--settings) not found." % file)
sys.exit(1)
else:
error("%s file (--settings) could not be read or processed (IOError)." % loadfile)
raise e
@staticmethod
def make_arg_parser():
global __doc__
parser = argparse.ArgumentParser(description=__doc__)
__doc__ = "" # don't include twice in documentation
parser.add_argument('COLLECTION', type=str, nargs='?',
help='Start at this collection')
parser.add_argument('--settings', '-s', dest='settingsfile',
action='store', default=None,
help='load settings from FILE. See settings_example.py.')
ug = parser.add_mutually_exclusive_group(required=False)
ug.add_argument('--user', action='store', dest='user', help="load a user library [user_library(...)]")
ug.add_argument('--group', action='store', dest='group', help="load a group library [group_library(...)]")
parser.add_argument('--api_key', action='store', dest='api_key', help="set Zotero API key [user_library(..., api_key=...)]")
parser.add_argument('--output', '-o', dest='output', type=str, action='store',
help='Output to this file [outputfile]')
parser.add_argument('--verbose', default=0, action='count', dest='verbosity', help="output more information")
parser.add_argument('--quiet', default=0, action='store_const', const=-2, dest='verbosity', help="output no information")
df = parser.add_mutually_exclusive_group(required=False)
df.add_argument('--div', default=None, action='store_false', dest='full', help="output an HTML fragment [write_full_html_header=False]")
df.add_argument('--full', default=None, action='store_true', dest='full', help="output full html [write_full_html_header=True]")
parser.add_argument('--no_cache', '-n', action='store_true', dest='no_cache', default=None,
help="do not use cache [no_cache]")
if __name__ == '__main__':
v = "ZBW %s - Pyzotero %s - Python %s"%(__version__, zotero.__version__, sys.version)
parser.add_argument('--version', '-v', version=v, action='version')
parser.add_argument('--interactive', '-i', action='store_true', dest='interactive', default=None,
help=argparse.SUPPRESS)
return parser
@staticmethod
def read_args_and_init():
global interactive_debugging
global write_full_html_header, stylesheet_url, outputfile, jquery_path
global clipboard_js_path, copy_button_path, no_cache, toplevelfilter
global api_key
global outputfile
global verbosity
parser = Settings.make_arg_parser()
args = parser.parse_args()
verbosity = args.verbosity or verbosity
outputfile = args.output or outputfile # set early because log() needs it
if args.settingsfile:
Settings.load_settings(args.settingsfile)
else:
Settings.load_settings()
import_legacy_configuration()
outputfile = args.output or outputfile # again, because parms take precedence
write_full_html_header = args.full if args.full != None else write_full_html_header
no_cache = args.no_cache if args.no_cache != None else no_cache
interactive_debugging = args.interactive if args.interactive != None else interactive_debugging
if args.user:
toplevelfilter = None
user_collection(args.user, api_key=args.api_key, collection=args.COLLECTION)
if args.group:
group_collection(args.group, api_key=args.api_key, collection=args.COLLECTION)
# api_key = args.api_key or api_key # for use as default by commands in settings file
###########
if not include_collections:
if len(sys.argv) > 1:
if args.user or args.group:
error("No collections found in given libraries.")
else:
error(
"You must give --user or --group, or add user_collection(..) or group_collection(..) in settings.py.")
else:
parser.print_usage(file=sys.stderr)
sys.exit(1)
make_arg_parser = Settings.make_arg_parser # for Sphinx-argparse
###########
def flexible_html_regex(r): # To Do: request non-HTML output from Zotero instead
r = re.escape(r)
r = r.replace("\\&", r"(&|\\&)")
r = r.replace("\\<", r"(<|\\<)")
r = r.replace("\\>", r"(>|\\>)")
r = r.replace(" ", r"\s+")
r = r.replace(u" ", r"[\s ]+") # repl string was "ur" - todo: check
return r
def url_regex(prefix=""):
"""Regex for matching URLs.
Copied from: https://daringfireball.net/2010/07/improved_regex_for_matching_urls
"""
return r"(?xi)" + prefix + r"""
\b
( # Capture 1: entire matched URL
(?:
[a-z][\w-]+: # URL protocol and colon
(?:
/{1,3} # 1-3 slashes
| # or
[a-z0-9%] # Single letter or digit or '%'
# (Trying not to match e.g. "URI::Escape")
)
| # or
www\d{0,3}[.] # "www.", "www1.", "www2." … "www999."
| # or
[a-z0-9.\-]+[.][a-z]{2,4}/ # looks like domain name followed by a slash
)
(?: # One or more:
[^\s()<>]+ # Run of non-space, non-()<>
| # or
\(([^\s()<>]+|(\([^\s()<>]+\)))*\) # balanced parens, up to 2 levels
)+
(?: # End with:
\(([^\s()<>]+|(\([^\s()<>]+\)))*\) # balanced parens, up to 2 levels
| # or
[^\s`!()\[\]{};:'".,<>?«»“”‘’] # not a space or one of these punct char
)
)"""
def cleanup_lines(string):
"Remove double line feeds to protect from <P> insertion in Wordpress."
# Wordpress likes to insert <P>, which is not a good idea here.
return re.sub(r'\n\s*\n', '\n', string, flags=re.DOTALL)
def generate_base_html():
global language_code
# smart selections prevents viewers from copying certain buttons
# this way, a nice, clean bibliography can be copied right from a browser window
# this is achieved by displaying the buttons dynamically.
# caveat - are there accessibility implications?
possible_items = ['PDF', 'PS', 'DOC', 'link', 'Wikipedia', 'BIB', 'RIS', 'EndNote', 'Abstract',
'File'] # see also button_label_for_object
possible_items += ['cite_' + s[5:] for s in show_links if s.startswith("cite.")]
blinkitem_css = ""
# blinkitem_css += "a.shortened::before {%s}\n"%('content:"\\229E"' if smart_selections else "") # hex(8862)
# Set some (default) styles
# note - the final style in the style sheet is manipulated by changeCSS
# this is selected (hack, hack) by index
style_html = """
.bibshowhide {display:none;}
.bib-venue-short, .bib-venue {display:none;}"""
if smart_selections:
style_html += '.bib-venue-short::before, .bib-venue::before, .blink a::before {content: attr(data-before);}'
style_html += blinkitem_css + ".blink {margin:0;margin-right:15px;padding:0;display:none;}"
style_html = '<style type="text/css" id="zoterostylesheet" ' + (
"" if write_full_html_header else "scoped") + '>' + style_html + '</style>'
script_html = ''
jqready = ''
jqready += "jQuery('.blink a').click(showThis);"
if show_copy_button:
if jquery_path and clipboard_js_path and copy_button_path:
script_html += '<script type="text/javascript" src="%s"></script>' % clipboard_js_path
jqready += """
jQuery("div.bib").add("div.cite").append('\\n<button class="btn"><img src="%s" width=13 alt="Copy to clipboard"></button>');
new Clipboard('.btn',{
text: function(trigger) {
var prevCol = trigger.parentNode.style.color;
trigger.parentNode.style.color="grey";
setTimeout(function(){trigger.parentNode.style.color=prevCol;}, 200);
return trigger.parentNode.childNodes[0].textContent;}});""" % copy_button_path
else:
warning("show_search_box set, but jquery_path, clipboard_js_path or copy_button_path undefined.")
if smart_selections:
jqready += """
jQuery(".bib-venue-short").each(function(){$(this).attr('data-before', $(this).html()); $(this).html("")});
jQuery(".blink a").each(function(){$(this).attr('data-before', $(this).html()); $(this).html("")});
"""
if jquery_path:
script_html += '<script type="text/javascript" src="' + jquery_path + '"></script>'
script_html += '<script type="text/javascript">jQuery(document).ready(function () {%s});' % jqready
script_html += """
function dwnD(data) {
filename = "article.ris"
var pom = document.createElement('a');
var isSafari = navigator.vendor && navigator.vendor.indexOf('Apple') > -1 && navigator.userAgent && !navigator.userAgent.match('CriOS');
var mime = (isSafari?"text/plain":"application/x-research-info-systems");
pom.href = window.URL.createObjectURL(new Blob([atob(data)], {type: mime+";charset=utf-8"}));
pom.download = filename;
document.body.appendChild(pom);
pom.click();
setTimeout(function(){document.body.removeChild(pom);}, 100);
return(void(0));}
function showThis(e) {
elem = e.target;
if (elem.parentNode) {
var elems = elem.parentNode.parentNode.getElementsByTagName('*');
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + 'bibshowhide' + ' ') > -1)
{ if (elems[i].parentNode != elem.parentNode)
elems[i].style.display = 'none';
}}
elems = elem.parentNode.getElementsByTagName('*');
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + 'bibshowhide' + ' ') > -1)
{ elems[i].style.display = 'block';
hideagain = elems[i];
e.stopPropagation();
turnoff = function(e){
if (! jQuery.contains(this, e.target))
this.style.display = 'none';
else
jQuery(document).one("click",turnoff_b); // rebind itself
}
turnoff_b = turnoff.bind(elems[i])
jQuery(document).one("click",turnoff_b);
return(void(0));
}}}
return(void(0));}
function changeCSS() {
if (!document.styleSheets) return;
var theRules = new Array();
//ss = document.styleSheets[document.styleSheets.length-1];
var ss = document.getElementById('zoterostylesheet');
if (ss) {
ss = ss.sheet
if (ss.cssRules)
theRules = ss.cssRules
else if (ss.rules)
theRules = ss.rules
else return;
theRules[theRules.length-1].style.display = 'inline';
}
}
changeCSS();
</script>"""
credits_html = u'<div id="zbw_credits" style="text-align:right;">A <a href="https://github.com/davidswelt/zot_bib_web">zot_bib_web</a> bibliography.</div>'
script_html = cleanup_lines(script_html)
html_header = u''
html_footer = u''
if write_full_html_header:
if stylesheet_url:
style_html = u"<link rel=\"stylesheet\" type=\"text/css\" href=\"%s\">" % stylesheet_url + style_html
html_header += u'<!DOCTYPE html><html lang="%s"><head><meta charset="UTF-8"><title>' % language_code + titlestring + u'</title>' + style_html + u'</head><body>'
html_header += u'<div class="bibliography">' + script_html
html_footer += credits_html + u'</div>'
if titlestring:
html_header += '<h1 class="title">' + titlestring + "</h1>\n";
html_footer += u'</body></html>'
else:
html_header += u'<div class="bibliography">' + style_html + script_html
html_footer += credits_html + u'</div>'
search_box = ""
if show_search_box or show_shortcuts:
if jquery_path:
search_box = ''
if show_search_box:
search_box += '<form id="pubSearchBox" name="pubSearchBox" style="visibility:hidden;"><input id="pubSearchInputBox" type="text" name="keyword" placeholder="keywords"> <input id="pubSearchButton" type="button" value="Search" onClick="searchF()"></form><h2 id="searchTermSectionTitle" class="collectiontitle"></h2>'
if show_search_box or show_shortcuts:
search_box += """<script type="text/javascript">
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
jQuery( document ).ready(function() {
jQuery('#pubSearchBox,#bib-preamble').css("visibility","visible");
var kw = getURLParameter("keyword");
if (kw) {
jQuery('#pubSearchInputBox').val(kw);
searchF([kw]);
}
});
jQuery.expr[":"].icontains = jQuery.expr.createPseudo(function(arg) {
return function( elem ) {
return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};});
function searchF(searchTerms, shown, disjunctive) {
var i=document.pubSearchBox.keyword.value;
searchTerms = searchTerms || (i!=""&&i.split(" "));
shown = shown || searchTerms;
jQuery(".bib-item").css("display", "none");
var q = ".bib-item";
if (disjunctive)
{ for (x in searchTerms) {jQuery(".bib-item:icontains('"+searchTerms[x]+"')").css("display", "block");}
}
else
{ jQuery.each(searchTerms, function(i,x) {q = q + ":icontains('"+x+"')";});
jQuery(q).css("display", "block");}
jQuery("#searchTermSectionTitle").html(searchTerms.length>0?"<a href='#' onclick='searchF([]);'>✕</a> "+shown:"");
jQuery(".collectiontitle").parent(".full-bib-section,.short-bib-section").css("display", "block");
jQuery(".collectiontitle").parent(".full-bib-section,.short-bib-section").each(function(){
var y = jQuery(this).find(".bib-item:visible");
if (y.length==0) {jQuery(this).css("display","none");}
});
}
jQuery(function() { // <== Doc ready
// stackoverflow q 3971524
var inputVal = jQuery("#pubSearchInputBox").val(),
timer,
checkForChange = function() {
var self = this; // or just use .bind(this)
if (timer) { clearTimeout(timer); }
// check for change of the text field after each key up
timer = setTimeout(function() {
if(self.value != inputVal) {
searchF();
inputVal = self.value
}
}, 250);
};
jQuery("#pubSearchInputBox").bind('keyup paste cut', checkForChange);
});</script>"""
else:
warning("show_search_box or show_shortcut are set, but jquery_path undefined.")
return html_header, search_box, html_footer
try:
from dateutil.parser import parse
except ImportError:
parse = False
pass
def parse_date(value):
"""Parse a date in English.
Cheap substitute for dateutil.parser.
Returns: a tuple of a sortable value and a year (int)."""
value = re.sub(r'(\s|\.|st|nd|rd|th|,)', '-', value)
value = value.replace('--', '-')
year = value
m = re.match(r'\s*(.*)\s*([0-9][0-9][0-9][0-9])\s*(.*)', value)
if m:
year = m.group(2)
if not m.group(1) == '': # year not already at beginning of string?
value = m.group(2) + '-' + m.group(1) + m.group(3) # rough approximation
else:
nums = re.split(r'[\s/\.]', value)
if len(nums) > 1:
value = "-".join(reversed(nums))
if len(nums) > 0:
year = nums[0]
for i, mo in enumerate(re.split(r' ', "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec")):
value = value.replace(mo, str(i + 1))
value = re.sub(r'\b([0-9])\b', r'0\1', value)
value = re.sub(r'-$', '', value)
return value, year
SortAndValue = namedtuple('SortAndValue', ['sort', 'value'])
def sortkeyname(field, value):
global sortkeyname_dict
# field may be a single field, or a list of fields
# value corresponds to field
sort_prefix = ""
# value may be none (e.g., for venue)
# In that case, we will resort to the default entry in sortkeyname
if value and not is_string(value): # isinstance(value, list):
# it's a path of something
# sorting by all the numbers (if available).
# e.g., 10.13, and displaying the last entry
if 'collection' == field:
return SortAndValue(u".".join([u"%s" % sortkeyname(field, value2).sort for value2 in value]),
sortkeyname(field, value[-1]).value)
else:
return SortAndValue(
u".".join([u"%s" % sortkeyname(field2, value2).sort for field2, value2 in zip(field, value)]), \
sortkeyname(field[-1], value[-1]).value)
if field == "collection":
if Coll.hideSectionTitle(value):
sort_prefix, name, value = u"", u"", value
else:
name = Coll.findName(value) # value is an ID
sort_prefix, _, value = collname_split(name)
if field == "date":
if parse:
try:
dt = parse(value, fuzzy=True)
sort_prefix = dt.isoformat()
value = str(dt.year)
except ValueError: # dateutil couldn't do it
sort_prefix, value = parse_date(value)
else:
sort_prefix, value = parse_date(value)
if field in sortkeyname_dict:
if value in sortkeyname_dict[field]:
s, value = sortkeyname_dict[field][value] # this is (sort_number, label)
sort_prefix = "%s" % s + " " + sort_prefix
elif None in sortkeyname_dict[field]: # default for unknown values
sort_prefix = "%s" % (sortkeyname_dict[field][None][0]) + " " + sort_prefix
sort_prefix = sort_prefix or ""
value = value or ""
return SortAndValue(" ".join([sort_prefix, value.lower()]), value) # sort by value
sort_reverse = []
def import_legacy_configuration():
global order_by
global sort_criteria
global sort_reverse
global catchallcollection
global show_links
if library_id and library_type:
if library_type == 'group':
group_collection(library_id, api_key=api_key, collection=toplevelfilter, top_level=False)
elif library_type == 'user':
user_collection(library_id, api_key=api_key, collection=toplevelfilter, top_level=False)
if catchallcollection:
warn('catchallcollection setting no longer available. Ignoring.\n'
'Use & modifier for collection name (e.g., "& Miscellaneous") and,\n'
'if necessary, the new group_collection or user_collection statement, e.g.:\n'
'user_collection(library_id, collection = ["%s"])' % catchallcollection)
if order_by: # set by user (legacy setting)
sort_critera = ['collection', order_by]
else:
order_by = 'date'
# find sort order for each criterion
sort_reverse = []
for i, c in enumerate(sort_criteria):
if c[0] == '-':
sort_criteria[i] = c[1:]
sort_reverse += [True]
else:
sort_reverse += [False]
show_links = [i.lower() for i in show_links]
def index_configuration():
global sortkeyname_order
global sortkeyname_dict
global language_code
# Not using OrderedDict (Python 2.7), because it does not actually
# indicate the index of an item by itself
if not language_code in sortkeyname_order:
language_code = 'en' # fallback - should be present.
def enumerate_by_value(kv_list):
"Enumerate items in a k,v list; identical values will have same numbers."
# Users might reuse section titles and we want to sort within whole sections.
count=0
d={}
for k,v in kv_list:
if v not in d:
d[v] = count
count += 1
yield d[v], k, v
# use val as default if it is given as None
sortkeyname_dict = {
key: {val: ("%03d" % idx, mappedVal or val) for idx, val, mappedVal in enumerate_by_value(list(the_list))} for
key, the_list in sortkeyname_order[language_code].items()}
class ZotItem:
__classversion__ = 7
def __init__(self, entries):
self.__version__ = ZotItem.__classversion__
self.key = None
self.creators = None
self.event = None
self.section_keyword = set()
self.url = None
self.collection = []
self.type = None
self.date = None
self.libraryCatalog = None # special setting, overrides u'itemType' for our purposes
self.note = None
self.journalAbbreviation = None
self.conferenceName = None
self.meetingName = None
self.title = "" # client code expects title to be always set.
self.publicationTitle = None
self.shortTitle = None
self.series = None
self.extra = None
self.uniqueID = None # will be set by detect_and_merge_doubles
self.filename = None
self.parentItem = None
self.tags = []
self.__dict__.update(entries)
# Will be set later - None is a good default
self.bib = None
self.ris = None
self.html = None
self.coins = None
self.plain = None
self.wikipedia = None
self.saved_filename = None
self.attachments = []
# populate calculated values
self.year = self.getYear()
# allow libraryCatalog to override itemType
self.type = self.libraryCatalog or self.itemType
def addAttachment(self, zotItem):
self.attachments += [zotItem]
def access(self, key, default=""):
if key == 'year':
if self.year:
return str(self.year)
if self.date:
return self.date
if key == 'venue':
return self.venue()
if key == 'venue_short':
return self.venue_short()
if key == 'tags':
return self.getTags()
if key in self.__dict__ and self.__dict__[key]:
return self.__dict__[key]
return default # default
# raise RuntimeError("access: field %s not found."%key)
def getYear(self):
if self.date:
m = re.search('[0-9][0-9][0-9][0-9]', self.date)
if m:
return int(m.group(0))
return None
def venue(self):
return self.publicationTitle or self.conferenceName
def venue_short(self):
def maybeshorten(txt):
if txt:
m = re.search(r'\(\s*([A-Za-z/]+(\-[A-Za-z]+)?)\s*\-?\s*[0-9]*\s*\)', txt)
if m:
return m.group(1)
m = re.match(r'^([A-Za-z/]+(\-[A-Za-z]+)?)\s*\-?\s*[0-9]*$', txt)
if m and len(m.group(1)) < 11:
return m.group(1)
if len(txt) < 11:
return txt # return whole conference if short
# print(pprint.pformat(self.__dict__))
return self.journalAbbreviation or maybeshorten(self.conferenceName) or maybeshorten(
self.meetingName) or maybeshorten(self.publicationTitle) or maybeshorten(self.shortTitle) or maybeshorten(
self.series)
# or self.shortTitle or self.series
def addSectionKeyword(self, s):
if not s in self.section_keyword:
self.section_keyword.add(s)
def getTags(self):
return [entry[u'tag'] for entry in self.tags]
def write_bib(items, outfile):
file = codecs.open(outfile, "w", "utf-8")
for item in items:
file.write(item)
file.close()
# Atom bib entry:
# {u'publisher': u'Routledge Psychology Press', u'author': [{u'given': u'David', u'family': u'Reitter'}], u'collection-title': u'Frontiers of Cognitive Psychology', u'issued': {u'raw': u'January 2017'}, u'title': u'Alignment in Web-based Dialogue: Who Aligns, and how Automatic is it? Studies in Big-Data Computational Psycholinguistics', u'editor': [{u'given': u'Michael N.', u'family': u'Jones'}], u'container-title': u'Big Data in Cognitive Science', u'type': u'chapter', u'id': u'1217393/IVR7H8TD'}
def format_bib(bib):
return bib.replace("},", "},\n")
def format_ris(bib):
return bib.replace("\n", "\\n").replace("\r", "\\r")
def extract_abstract(bib):
m = re.match(r'(.*)abstract\s*=\s*{?(.*?)}\s*(,|})(.*)', bib, re.DOTALL | re.IGNORECASE)
if m:
a = m.group(2)
b = m.group(1) + m.group(4)
a = a.replace("{", "")
a = a.replace("}", "")
a = a.replace("\?&", "&")
a = a.replace("&", "&")
a = a.replace("<", "<")
a = a.replace(">", ">")
a = a.replace("\\textless", "<")
a = a.replace("\\textgreater", ">")
a = a.replace("\\textbar", "|")
return tex2unicode(a), b
return None, bib
def write_some_html(body, outfile, html_header, html_footer, title=None):
content = html_header
if title:
content += '<h1 class="title">' + title + '</h1>'
content += body + html_footer
if outfile=='-':
sys.stdout.write(content.encode("utf-8"))
log("Output written to stdout.")
else:
file = codecs.open(outfile, mode="w", encoding="utf-8")
file.write(content)
file.close()
progress("Output written to %s." % outfile)
def tryreplacing(source, strings, repl):
for s in strings:
if s in source:
repl2 = repl.replace("\\0", s)
return source.replace(s, repl2)
r = flexible_html_regex(s)
if re.search(r, source):
repl2 = repl.replace("\\0", s)
return re.sub(r, repl2, source)
# warn("not successful: ", source, strings)
return source
def urlize(text):
"""
Convert any URLs in text into clickable links.