forked from jonathansick/ads_bibdesk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
arxivbibdesk.py
executable file
·1884 lines (1651 loc) · 71.4 KB
/
arxivbibdesk.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 python2.7
"""
ADS to BibDesk -- frictionless import of ADS publications into BibDesk
Copyright (C) 2014 Rui Pereira <[email protected]> and
Jonathan Sick <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Based on ADS to Bibdesk automator action by
Jonathan Sick, [email protected], August 2007
Input may be one of the following:
- ADS abstract page URL
- ADS bibcode
- arXiv abstract page
- arXiv identifier
"""
import cdsbibdesk
import datetime
import difflib
import fnmatch
import glob
import logging
import math
import optparse
import os
import pprint
import re
import socket
import sys
import tempfile
import time
# cgi.parse_qs is deprecated since 2.6
# but OS X 10.5 only has 2.5
import cgi
import urllib2
import urlparse
import subprocess as sp
try:
import AppKit
except ImportError:
# is this not the system python?
syspath = eval(sp.Popen('/usr/bin/python -c "import sys; print(sys.path)"',
shell=True, stdout=sp.PIPE).stdout.read())
for p in syspath:
if os.path.isdir(p) and glob.glob(os.path.join(p, '*AppKit*')):
sys.path.insert(0, p)
break
# retry
try:
import AppKit
except ImportError:
import webbrowser
url = 'http://pythonhosted.org/pyobjc/install.html'
msg = 'Please install PyObjC...'
print msg
sp.call(r'osascript -e "tell application \"System Events\" to '
'display dialog \"%s\" buttons {\"OK\"} default button \"OK\""'
% msg, shell=True, stdout=open('/dev/null', 'w'))
# open browser in PyObjC install page
webbrowser.open(url)
sys.exit()
from HTMLParser import HTMLParser, HTMLParseError
from htmlentitydefs import name2codepoint
# default timeout for url calls
socket.setdefaulttimeout(30)
VERSION = "1.3"
#DEBUG=True #unused
def main():
"""Parse options and launch main loop"""
usage = """Usage: %prog [options] [article_token or pdf_directory]
adsbibdesk helps you add astrophysics articles listed on NASA/ADS
and arXiv.org to your BibDesk database. There are three modes
in this command line interface:
1. Article mode, for adding single papers to BibDesk given tokens.
2. PDF Ingest mode, where PDFs in a directory are analyzed and added to
BibDesk with ADS meta data.
3. Pre-print Update mode, for updating arXiv pre-prints automatically
with newer bibcodes.
In article mode, adsbibdesk accepts many kinds of article tokens:
- the URL of an ADS or arXiv article page,
- the ADS bibcode of an article (e.g. 1998ApJ...500..525S), or
- the arXiv identifier of an article (e.g. 0911.4956).
(Example: `adsbibdesk 1998ApJ...500..525S`)
In PDF Ingest mode, you specify a directory containing PDFs instead of
an article token (Example: `adsbibdesk -p pdfs` will ingest PDFs from
the pdfs/ directory).
In Pre-print Update mode, every article with an arXiv bibcode will be
updated if it has a new bibcode."""
DEBUG=True
epilog = "For more information, visit www.jonathansick.ca/adsbibdesk" \
" email jonathansick at mac.com or tweet @jonathansick"
parser = optparse.OptionParser(usage=usage, version=VERSION,
epilog=epilog)
parser.add_option(
'-d', '--debug',
dest="debug", default=False, action="store_true",
help="Debug mode; prints extra statements")
parser.add_option(
'-k', '--citekey',
default=False, action="store_true",
help="Do not check title similarity to decide if the paper is new in the database")
parser.add_option(
'-b', '--fetch_bibtex',
default=False, action="store_true",
help="Do not check title similarity to decide if the paper is new in the database")
parser.add_option(
'-w', '--overwrite',
default=False, action="store_true",
help="Do not check title similarity to decide if the paper is new in the database")
parser.add_option(
'-o', '--only_pdf',
default=False, action='store_true',
help="Download and open PDF for the selected [article_token].")
pdf_ingest_group = optparse.OptionGroup(parser, "PDF Ingest Mode",
description=None)
pdf_ingest_group.add_option(
'-p', '--ingest_pdfs',
dest="ingest_pdfs", default=False, action="store_true",
help="Ingest a folder of PDFs."
" Positional argument should be directory"
" containing PDFs."
" e.g., `adsbibdesk -p .` for the current directory")
pdf_ingest_group.add_option(
'-r', '--recursive',
dest='recursive', action="store_true",
help="Search for PDFs recursively in the directory tree.")
parser.add_option_group(pdf_ingest_group)
arxiv_update_group = optparse.OptionGroup(parser, "Pre-print Update Mode",
description=None)
arxiv_update_group.add_option(
'-u', '--update_arxiv',
default=False, action="store_true",
help='Check arXiv pre-prints for updated bibcodes')
arxiv_update_group.add_option(
'-f', '--from_date',
help='MM/YY date of publication from which to start updating arXiv')
arxiv_update_group.add_option(
'-t', '--to_date',
help='MM/YY date of publication up to which update arXiv')
parser.add_option_group(arxiv_update_group)
###################################
options, args = parser.parse_args()
###################################
# Get preferences from (optional) config file
prefs = Preferences()
# inject options into preferences for later reference
prefs['options'] = options.__dict__
if options.debug:
prefs['debug'] = True
DEBUG=True
# Logging saves to log file on when in DEBUG mode
# Always prints to STDOUT as well
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(name)s %(levelname)s %(message)s',
filename=prefs['log_path'])
if not prefs['debug']:
logging.getLogger('').setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
logging.getLogger('').addHandler(ch)
logging.info("Starting ADS to BibDesk")
logging.debug("ADS to BibDesk version %s" % VERSION)
logging.debug("Python: %s", sys.version)
# Launch the specific workflow
if options.ingest_pdfs:
ingest_pdfs(options, args, prefs)
elif options.only_pdf:
# short-circuit process_articles
# since BibDesk is not needed
# FIXME smells like a refactor
process_token(args[0], prefs, None)
elif options.update_arxiv:
update_arxiv(options, prefs)
else:
process_articles(args, prefs)
def process_articles(args, prefs, delay=15):
"""Workflow for processing article tokens and running process_token()
to add the article to BibDesk.
"""
# FIXME is there ever actually a case where args is None?
if args:
article_tokens = list(args)
else:
# Try to use standard input
article_tokens = [s.strip() for s in sys.stdin.readlines()
if s.strip()]
# AppKit hook for BibDesk
bibdesk = BibDesk()
for article_token in article_tokens:
try:
process_token(article_token, prefs, bibdesk)
except ADSException, err:
logging.debug('%s failed - %s' % (article_token, err))
if len(article_tokens) > 1 and article_token != article_tokens[-1]:
time.sleep(delay)
bibdesk.app.dealloc()
# FIXME this function needs to be refactored
def process_token(article_token, prefs, bibdesk):
"""Process a single article token from the user, adding it to BibDesk.
Parameters
----------
article_token : str
Any user-supplied `str` token.
prefs : :class:`Preferences`
A `Preferences` instance.
bibdesk : :class:`BibDesk`
A `BibDesk` AppKit hook instance.
"""
# Determine what we're dealing with
# The goal is to get a URL into ADS
logging.debug("process_token found article token %s", article_token)
connector = ADSConnector(article_token, prefs)
# ADSConnector will take care of the cases in which is arXiv instead of ADS
# at the end it will generate a connector.bib with the bibtex info
ads_parser = ADSHTMLParser(prefs=prefs)
#overwrite=prefs['overwrite']
overwrite=prefs['options']['overwrite']
citekey=prefs['options']['citekey']
print_bibtex=prefs['options']['fetch_bibtex']
# print 'connector.ads_read', connector.ads_read
if isinstance(connector.ads_read, basestring):
# parse the ADS HTML file
# print 'HTML from ADS'
#logging.debug('usr: %s', connector.ads_read)
ads_parser.parse(connector.ads_read)
elif connector.ads_read and getattr(connector, 'bibtex') is not None:
# print 'connector into ads_parser'
logging.debug('parsed from arXiv or CDS - fill in ads_parser info')
#ads_parser.bib = connector.bib
ads_parser.bibtex = connector.bibtex
ads_parser.arxivid = ads_parser.bibtex.Eprint
ads_parser.author = ads_parser.bibtex.Author.split(' and ')
ads_parser.title = ads_parser.bibtex.Title
ads_parser.abstract = ads_parser.bibtex.Abstract
ads_parser.comment = ads_parser.bibtex.AdsComment
# original URL where we *should* have gotten the info
ads_parser.bibtex.AdsURL = connector.ads_url
#ads_parser.pdf_link = connector.pdf_link
# inject arXiv mirror into ArXivURL
if 'arxiv_mirror' in prefs and prefs['arxiv_mirror']:
tmpurl = urlparse.urlsplit(ads_parser.bibtex.ArXivURL)
ads_parser.bibtex.ArXivURL = urlparse.urlunsplit(
(tmpurl.scheme,
prefs['arxiv_mirror'],
tmpurl.path, tmpurl.query,
tmpurl.fragment))
# link for PDF download
print ads_parser.bibtex.info['link']
try:
if "http:" in ads_parser.bibtex.info['link']:
ads_parser.links = {'confnote': ads_parser.bibtex.info['link']}
else:
link = [l.get('href', '') for l in ads_parser.bibtex.info['link']
if l.get('title') == 'pdf'][0]
ads_parser.links = {'preprint': link}
except IndexError:
logging.debug("process_token could not find preprint PDF link")
notify('PDF is missing','','')
pass
elif connector.ads_read is None:
logging.debug("process_token skipping %s", article_token)
return False
# get PDF first
pdf = ads_parser.get_pdf()
# TODO refactor this out into a 'show_pdf' function
if prefs['options'].get('only_pdf'):
if not pdf.endswith('.pdf'):
return False
# just open PDF
reader = ('pdf_reader' in prefs and
prefs['pdf_reader'] is not None) and \
prefs['pdf_reader'] or 'Finder'
app = AppKit.NSAppleScript.alloc()
app.initWithSource_(
'tell application "%s" '
'to open ("%s" as POSIX file)' % (reader, pdf)).\
executeAndReturnError_(None)
# get name of the used viewer
# (Finder may be defaulted to something else than Preview)
if reader == 'Finder':
reader = app.initWithSource_(
'return name of (info for (path to frontmost application))').\
executeAndReturnError_(None)[0].stringValue()
logging.debug('opening %s with %s' % (pdf, reader))
if 'skim' in reader.lower():
time.sleep(1) # give it time to open
app.initWithSource_(
'tell application "%s" to set view settings '
'of first document to {auto scales:true}'
% reader).executeAndReturnError_(None)
app.dealloc()
return True
# search for already existing publication
# with exactly the same title and first author
# match title and first author using fuzzy string comparison
# FIXME put cutoff into preferences; could be related to problems
# FIXME refactor this out
print 'Check for duplicates'
found = difflib.get_close_matches(
ads_parser.title, bibdesk.titles,
n=1, cutoff=.9)
kept_pdfs = []
kept_fields = {}
# first author is the same
#overwrite=False
print 'Overwrite flag:', overwrite
print 'Items with possible overlap: ', len(found)
if len(found)>0:
notify('Almost same title already present in Bibdesk!', article_token, ads_parser.title)
if not overwrite:
notify("Will do nothing!","","")
if overwrite and len(found)>0 and difflib.SequenceMatcher(
None,
bibdesk.authors(bibdesk.pid(found[0]))[0],
ads_parser.author[0]).ratio() > .1:
# further comparison on abstract
abstract = bibdesk('abstract', bibdesk.pid(found[0])).stringValue()
if not abstract or difflib.SequenceMatcher(
None, abstract,
ads_parser.abstract).ratio() > .6:
pid = bibdesk.pid(found[0])
# keep all fields for later comparison
# (especially rating + read bool)
kept_fields = dict((k, v) for k, v in
zip(bibdesk('return name of fields', pid, True),
bibdesk('return value of fields', pid, True))
# Adscomment may be arXiv only
if k != 'Adscomment')
# plus BibDesk annotation
kept_fields['BibDeskAnnotation'] = bibdesk(
'return its note', pid).stringValue()
kept_pdfs += bibdesk.safe_delete(pid)
notify('Duplicate publication removed',
article_token, ads_parser.title)
bibdesk.refresh()
else:
if len(found)>0:
print("Warning: authors are similar", ads_parser.author[0],bibdesk.authors(bibdesk.pid(found[0]))[0])
# FIXME refactor out this bibdesk import code?
if overwrite or len(found)==0:
print "Import in BibDesk"
print "------BIBTEX DATA------"
print vars(ads_parser)
print "------------------"
#print ads_parser.bibtex.__str__()
if hasattr(ads_parser.bibtex, 'bib' ):
print 'ads_parser.bibtex.bib EXISTS'
print "------BIBTEX SEQUENCE------"
print('ads_parser.bibtex.bib', ads_parser.bibtex.bib)
print "---------------------------"
# add new entry
if hasattr(ads_parser.bibtex, 'bib' ):
# ads_parser.bibtex.bib already contains the bibtex string
# this is the case for papers imported from arXiv API (because the API gives no bibtex)
pub = bibdesk(
'import from "%s"' % ads_parser.bibtex.bib.
replace('\\', r'\\').replace('"', r'\"'))
else:
# the bibtex string needs to be made from the data in the ads_parser.bibtex
# this needs to be able to tell if the item has to get a link to inspires or CDS
_string = 'import from "%s"' % ads_parser.bibtex.__str__().\
replace('\\', r'\\').replace('"', r'\"')
logging.debug('Tell Bibdesk %s' % _string)
pub = bibdesk(_string)
# pub id
pub = pub.descriptorAtIndex_(1).descriptorAtIndex_(3).stringValue()
print pub
logging.debug('using automatic cite-key %s' % pub)
if citekey:
# automatic cite key (following the auto-file format!)
bibdesk('set cite key to generated cite key', pub)
# abstract
if ads_parser.abstract.startswith('http://'):
# old scanned articles
bibdesk(
'make new linked URL at end of linked URLs '
'with data "%s"' % ads_parser.abstract, pub)
else:
bibdesk(
'set abstract to "%s"'
% ads_parser.abstract.replace('\\', r'\\').replace('"', r'\"'),
pub)
doi = bibdesk('value of field "doi"', pub).stringValue()
if pdf.endswith('.pdf'):
# register PDF into BibDesk
bibdesk('add POSIX file "%s" to beginning of linked files' % pdf, pub)
# automatic file name
bibdesk('auto file', pub)
elif 'http' in pdf and not doi:
# URL for electronic version - only add it if no DOI link present
# (they are very probably the same)
bibdesk(
'make new linked URL at end of linked URLs with data "%s"'
% pdf, pub)
# add URLs as linked URL if not there yet
urls = bibdesk(
'value of fields whose name ends with "url"',
pub, strlist=True)
urlspub = bibdesk('linked URLs', pub, strlist=True)
for u in [u for u in urls if u not in urlspub]:
bibdesk(
'make new linked URL at end of linked URLs with data "%s"'
% u, pub)
# add old annotated files
for kept_pdf in kept_pdfs:
bibdesk('add POSIX file "%s" to end of linked files' % kept_pdf, pub)
# re-insert custom fields
bibdesk(
'set its note to "%s"' % kept_fields.pop('BibDeskAnnotation', ''),
pub)
newFields = bibdesk('return name of fields', pub, True)
for k, v in kept_fields.iteritems():
if k not in newFields:
bibdesk('set value of field "%s" to "%s"' % (k, v), pub)
notify('New publication added',
bibdesk('cite key', pub).stringValue(),
ads_parser.title)
def ingest_pdfs(options, args, prefs):
"""Workflow for attempting to ingest a directory of PDFs into BibDesk.
This workflow attempts to scape DOIs from the PDF text, which are then
added to BibDesk using the usual `process_token` function.
"""
assert len(args) == 1, "Please pass a path to a directory"
pdf_dir = args[0]
assert os.path.exists(pdf_dir) is True, "%s does not exist" % pdf_dir
print "Searching", pdf_dir
if options.recursive:
# Recursive glob solution from
# http://stackoverflow.com/a/2186565
pdf_paths = []
for root, dirnames, filenames in os.walk(pdf_dir):
for filename in fnmatch.filter(filenames, '*.pdf'):
pdf_paths.append(os.path.join(root, filename))
else:
pdf_paths = glob.glob(os.path.join(pdf_dir, "*.pdf"))
# Process each PDF, looking for a DOI
grabber = PDFDOIGrabber()
found = []
for i, pdf_path in enumerate(pdf_paths):
dois = grabber.search(pdf_path)
if not dois:
logging.info(
"%i of %i: no DOIs for %s"
% (i + 1, len(pdf_paths), pdf_path))
else:
found.extend(dois)
for doi in dois:
logging.info(
"%i of %i: %s = %s"
% (i + 1, len(pdf_paths), os.path.basename(pdf_path), doi))
# let process_articles inject everything
if found:
logging.info('Adding %i articles to BibDesk...' % len(found))
process_articles(found, prefs)
def update_arxiv(options, prefs):
"""
Workflow for updating arXiv pre-prints automatically with newer bibcodes.
"""
assert options.from_date is None or \
re.match('^\d{2}/\d{2}$', options.from_date) is not None, \
'--from_date needs to be in MM/YY format'
assert options.to_date is None or \
re.match('^\d{2}/\d{2}$', options.to_date) is not None, \
'--to_date needs to be in MM/YY format'
def b2d(bibtex):
"""BibTex -> publication date"""
m = re.search('Month = \{?(\w*)\}?', bibtex).group(1)
y = re.search('Year = \{?(\d{4})\}?', bibtex).group(1)
return datetime.datetime.strptime(m + y, '%b%Y')
def recent(added, fdate, tdate):
fromdate = fdate is not None and \
datetime.datetime.strptime(fdate, '%m/%y')\
or datetime.datetime(1900, 1, 1)
todate = tdate is not None and \
datetime.datetime.strptime(tdate, '%m/%y')\
or datetime.datetime(3000, 1, 1)
return fromdate <= added <= todate
# frontmost opened BibDesk document
bibdesk = BibDesk()
ids = []
# check for adsurl containing arxiv or astro.ph bibcodes
arxiv = bibdesk(
'return publications whose '
'(value of field "Adsurl" contains "arXiv") or '
'(value of field "Adsurl" contains "astro.ph")')
if arxiv.numberOfItems():
# extract arxiv id from the ADS url
ids = [u.split('bib_query?')[-1].split('abs/')[-1] for u in
bibdesk(
'tell publications whose '
'(value of field "Adsurl" contains "arXiv") or '
'(value of field "Adsurl" contains "astro.ph") '
'to return value of field "Adsurl"', strlist=True)]
dates = [b2d(b) for b in
bibdesk(
'tell publications whose '
'(value of field "Adsurl" contains "arXiv") or '
'(value of field "Adsurl" contains "astro.ph") '
'to return bibtex string', strlist=True)]
# arxiv ids to search
ids = [b for d, b in zip(dates, ids)
if recent(d, options.from_date, options.to_date)]
bibdesk.app.dealloc()
if not ids:
print 'Nothing to update!'
sys.exit()
else:
n = len(ids)
t = math.ceil(n * 15. / 60.)
if t > 1:
time_unit = "minutes"
else:
time_unit = "minute"
logging.info('Checking %i arXiv entries for changes...' % n)
logging.info(
'(to prevent ADS flooding this will take a while, '
'check back in around %i %s)' % (t, time_unit))
changed = []
for n, i in enumerate(ids):
# sleep for 15 seconds, to prevent ADS flooding
time.sleep(15)
logging.debug("arxiv id %s" % i)
# these are ADS bibcodes by default
adsURL = urlparse.urlunsplit(
('http', prefs['ads_mirror'],
'cgi-bin/bib_query', i, ''))
logging.debug("adsURL %s" % adsURL)
# parse the ADS HTML file
ads_parser = ADSHTMLParser(prefs=prefs)
try:
ads_parser.parse_at_url(adsURL)
except ADSException, err:
logging.debug('%s update failed: %s' % (i, err))
continue
logging.debug("ads.bibtex %s" % ads_parser.bibtex)
if ads_parser.bibtex is None: # ADSHTMLParser failed
logging.debug("FAILURE: ads.bibtex is None!")
continue
if ads_parser.bibtex.bibcode != i:
logging.info(
'%i. %s has become %s'
% (n + 1, i, ads_parser.bibtex.bibcode))
changed.append(i)
else:
logging.info('%i. %s has not changed' % (n + 1, i))
continue
# run changed entries through the main loop
if changed and raw_input(
'Updating %i entries, continue? (y/[n]) '
% len(changed)) in ('Y', 'y'):
logging.info(
'(to prevent ADS flooding, we will wait for a while '
'between each update, so go grab a coffee)')
process_articles(changed, prefs)
elif not changed:
logging.info('Nothing to update!')
def notify(title, subtitle, desc, sticky=False):
"""Publish a notification to Notification Center
Adaptation of original by Moises Aranas
https://github.com/maranas/pyNotificationCenter
"""
try:
import objc
notification = objc.lookUpClass('NSUserNotification').alloc().init()
notification.setTitle_(title)
notification.setInformativeText_(desc)
notification.setSubtitle_(subtitle)
objc.lookUpClass('NSUserNotificationCenter').\
defaultUserNotificationCenter().scheduleNotification_(notification)
notification.dealloc()
# this will be either ImportError or objc.nosuchclass_error
except Exception:
# revert to growl
if subtitle:
desc = subtitle + ': ' + desc
growl_notify(title, desc, sticky)
def growl_notify(title, desc, sticky=False):
title = title.replace('"', r'\"')
desc = desc.replace('"', r'\"')
# http://bylr.net/3/2011/09/applescript-and-growl/
# is growl running?
app = AppKit.NSAppleScript.alloc()
growl = app.initWithSource_(
'tell application "System Events" to return '
'processes whose creator type contains "GRRR"').\
executeAndReturnError_(None)[0]
if growl.numberOfItems():
growlapp = growl.descriptorAtIndex_(1).descriptorAtIndex_(3).\
stringValue()
# register
app.initWithSource_(
'tell application "%s" to register as '
'application "BibDesk" '
'all notifications {"BibDesk notification"} '
'default notifications {"BibDesk notification"}'
% growlapp).executeAndReturnError_(None)
# and notify
app.initWithSource_(
'tell application "%s" to notify with name '
'"BibDesk notification" application name "BibDesk" '
'priority 0 title "%s" description "%s" %s'
% (growlapp, title, desc, "with sticky" if sticky else '')).\
executeAndReturnError_(None)
app.dealloc()
def has_annotationss(f):
return sp.Popen(
"strings %s | grep -E 'Contents[ ]{0,1}\('" % f,
shell=True, stdout=sp.PIPE,
stderr=open('/dev/null', 'w')).stdout.read() != ''
def get_redirect(url):
"""Utility function to intercept final URL of HTTP redirection"""
try:
out = urllib2.urlopen(url)
except urllib2.URLError, out:
pass
return out.geturl()
class PDFDOIGrabber(object):
"""Converts PDFs to text and attempts to match all DOIs"""
def __init__(self):
super(PDFDOIGrabber, self).__init__()
regstr = r'(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?!["&\'<>\)\.,])\S)+)'
self.pattern = re.compile(regstr)
def search(self, pdfPath):
"""Return a list of DOIs in the text of the PDF at `pdfPath`"""
json_path = os.path.splitext(pdfPath)[0] + ".json"
if os.path.exists(json_path):
os.remove(json_path)
sp.call('pdf2json -q "%s" "%s"' % (pdfPath, json_path), shell=True)
data = open(json_path, 'r').read()
doi_matches = self.pattern.findall(data)
if os.path.exists(json_path):
os.remove(json_path)
# strings can find some stuff that pdf2json does not
if not doi_matches:
data = sp.Popen(
"strings %s" % pdfPath,
shell=True, stdout=sp.PIPE,
stderr=open('/dev/null', 'w')).stdout.read()
doi_matches = self.pattern.findall(data)
return list(set(doi_matches))
class ADSConnector(object):
"""Receives input (token), derives an ADS url, and attempts to connect
to the corresponding ADS abstract page with urllib2.urlopen().
Tokens are tested in order of:
- CDS preprint number
- arxiv identifiers
- bibcodes / digital object identifier (DOI)
- ADS urls
- arxiv urls
"""
def __init__(self, token, prefs):
super(ADSConnector, self).__init__()
self.token = str(token)
self.prefs = prefs
self.ads_url = None # string URL to ADS
self.ads_read = None # a urllib2.urlopen connection to ADS
self.url_parts = urlparse.urlsplit(token) # supposing it is a URL
if self._is_CDS():
logging.debug("ADSConnector found CDS ID %s", self.token)
notify('CDS page found for', self.token,
'Parsing the XML page...')
cds_entry = cdsbibdesk.CDSParser()
cds_entry.parse_at_id(self.token)
self.bibtex = cds_entry.bib
self.ads_url = cds_entry.ads_url
self.ads_read = True
logging.debug(self.ads_url)
#print "getattr"
#print getattr(cds_entry, 'bib')
#self.pdf_link = cds_entry.pdf_link
#cds_entry.bibtex =
if self._is_arxiv():
logging.debug("ADSConnector found on arXiv API the arXiv ID %s", self.token)
# Try to open the ADS page
#if not self._read(self.ads_url):
# parse arxiv instead:
#logging.debug('ADS page (%s) not found for %s' %
# (self.ads_url, self.token))
notify('Parsing the arXiv page for', self.token, '')
arxiv_bib = ArXivParser()
try:
logging.debug("searching on arXiv API with parse_at_id for %s", self.arxiv_id)
arxiv_bib.parse_at_id(self.arxiv_id)
# this defines properties arxiv_bib.info an arxiv_bib.bib with
# a dictionary of the bibtex and a objects-based bibtex entry
# e.g arxiv_bib.bib.Title
# finally it can be casted as a string, which is the bibtex entry
# itself. I will achieve (hopefully) such string by ar CDS query
logging.debug(
"arXiv page (%s) parsed for %s"
% (arxiv_bib.url, self.token))
#logging.debug('bibtex=',arxiv_bib.bib)
except ArXivException, err:
logging.debug("arXiv API failed, you're in trouble...")
raise ADSException(err)
# dummy ads_read and bibtex
self.ads_read = True
self.bibtex = arxiv_bib
is_Inspires_DOI = self._is_Inspires_DOI()
if is_Inspires_DOI:
from xml.etree import ElementTree
# change self.token into a RECID
logging.debug(' token from DOI %s' % self.token )
url_by_DOI = 'https://inspirehep.net/search?ln=en&p=doi+'+self.token+'&of=xm'
_xml=ElementTree.fromstring(urllib2.urlopen(url_by_DOI).read())
'https://inspirehep.net/search?ln=en&p=recid+'+self.token+'&of=xm'
self.token = cdsbibdesk.find_recid_in_xml(_xml)
logging.debug(' new token %s' % self.token )
# print "is_Inspires_RECID"
is_Inspires_RECID = self._is_Inspires_RECID()
if is_Inspires_RECID: # RECID or DOI
logging.debug("ADSConnector found on Inspires through the RECID or DOI %s", self.token)
notify('Inspires data found for', self.token,
'Parsing the XML and BibTeX output page...')
# Obtain Inspires Bibtex
logging.debug("fetching BibTeX from Inspires web pages for %s" % self.arxiv_id)
try:
url_string = "https://labs.inspirehep.net/api/literature/"+ self.token
request = urllib2.Request(url_string, headers={"accept" : "application/x-bibtex"})
contents = urllib2.urlopen(request).read()
logging.debug(contents)
logging.debug(type(contents))
if len(contents)>0:
bibtex_string = contents
#if print_bibtex:
print bibtex_string
except (urllib2.HTTPError, urllib2.URLError), err:
logging.debug("fetching BibTeX from Inspires failed on URL: %s", url_string)
#logging.debug(err.code,err.args)
# populate the attributes as if it were a CDS or arxiv_bib
cds_entry = cdsbibdesk.CDSParser()
cds_entry.parse_at_id(self.token,server='Inspires')
self.bibtex = cds_entry.bib
self.ads_url = cds_entry.ads_url
self.ads_read = True
logging.debug(self.ads_url)
logging.debug(
"Inspires page (%s) parsed for %s"
% (url_string, self.token))
if hasattr(self.bibtex, 'bib' ):
logging.debug(self.bibtex.bib)
#Disable ***all** ADS feature, arXiv, DOI, ...
'''
if self._is_arxiv_via_ADS() and not self.ads_read :
logging.debug("ADSConnector found on old ADS the arXiv ID %s", self.token)
# Try to open the ADS page
if not self._read(self.ads_url):
# parse arxiv instead:
logging.debug('ADS page (%s) not found for %s' %
(self.ads_url, self.token))
notify('ADS page not found', self.token,
'Parsing the arXiv page...')
arxiv_bib = ArXivParser()
try:
logging.debug("searching for %s", self.arxiv_id)
arxiv_bib.parse_at_id(self.arxiv_id)
# this defines properties arxiv_bib.info an arxiv_bib.bib with
# a dictionary of the bibtex and a objects-based bibtex entry
# e.g arxiv_bib.bib.Title
# finally it can be casted as a string, which is the bibtex entry
# itself. I will achieve (hopefully) such string by ar CDS query
logging.debug(
"arXiv page (%s) parsed for %s"
% (arxiv_bib.url, self.token))
except ArXivException, err:
logging.debug("ADS and arXiv failed, you're in trouble...")
raise ADSException(err)
# dummy ads_read and bibtex
self.ads_read = True
self.bibtex = arxiv_bib
# A bibcode from ADS?
elif not self.url_parts.scheme and self._is_bibcode():
logging.debug("ADSConnector found bibcode/DOI %s", self.token)
else:
# If the path lacks http://, tack it on because
# the token *must* be a URL now
if not self.token.startswith("http://"):
self.token = 'http://' + self.token
# supposing it is a URL
self.url_parts = urlparse.urlsplit(self.token)
# An abstract page at any ADS mirror site?
if self.url_parts.netloc in self.prefs.adsmirrors \
and self._is_ads_page():
logging.debug("ADSConnector found ADS page %s", self.token)
'''
def _is_CDS(self):
"""Try to classify the token as CDS article by getting the recid:
:return: True if CDS recid is recovered
"""
from xml.etree import ElementTree
url = 'https://cds.cern.ch/search?ln=en&p=reportnumber%3A"' + self.token + '"&action_search=Search&op1=a&m1=a&p1=&f1=&c=CERN+Document+Server&sf=&so=d&rm=&rg=10&sc=1&of=xm'
try:
xml = ElementTree.fromstring(urllib2.urlopen(url).read())
except (urllib2.HTTPError, urllib2.URLError), err:
logging.debug("ArXivParser failed on URL: %s", url)
raise ArXivException(err)
if xml.find(".//*[@tag='001']")>0:
return True
return False
# TODO: DOI from Inspires
#https://labs.inspirehep.net/api/literature?q=doi=10.1063/1.3293892
# or directly in BibTex
# curl -H "accept: application/x-bibtex" https://labs.inspirehep.net/api/literature?q=doi=10.1063/1.3293892
# TODO recid from Inspires
#curl -H "accept: application/x-bibtex" https://labs.inspirehep.net/api/literature/123456
def _is_Inspires_RECID(self):
try:
url_string = "https://inspirehep.net/api/literature/"+ self.token
request = urllib2.Request(url_string, headers={"accept" : "application/x-bibtex"})
contents = urllib2.urlopen(request).read()
logging.debug(contents)
logging.debug(type(contents))
if len(contents)>0:
return True
except (urllib2.HTTPError, urllib2.URLError), err:
logging.debug("RECID search failed on URL: %s", url_string)
return False
def _is_Inspires_DOI(self):
try:
url_string = 'https://inspirehep.net/api/literature?q=doi='+ self.token
request = urllib2.Request(url_string, headers={"accept" : "application/x-bibtex"})
contents = urllib2.urlopen(request).read()
logging.debug(contents)
logging.debug(type(contents))
if len(contents)>0:
return True
except (urllib2.HTTPError, urllib2.URLError), err:
logging.debug("RECID search failed on URL: %s", url_string)
return False
def _is_arxiv_via_ADS(self): # DEPRECATED
"""Try to classify the token as an arxiv article, either:
- new style (YYMM.NNNN), or
- old style (astro-ph/YYMMNNN)
:return: True if ADS page is recovered
"""
arxiv_pattern = re.compile('(\d{4,6}\.\d{4,6}|astro\-ph/\d{7})')
arxiv_matches = arxiv_pattern.findall(self.token)
if len(arxiv_matches) == 1:
self.arxiv_id = arxiv_matches[0]
self.ads_url = urlparse.urlunsplit((
'http',
self.prefs['ads_mirror'],
'cgi-bin/bib_query',
'arXiv:%s' % self.arxiv_id, ''))
logging.debug('arxiv_id: %s', self.arxiv_id)
logging.debug('ads_url: %s', self.ads_url)
return True
else:
self.arxiv_id = None
return False
def _is_arxiv(self):
"""Try to classify the token as an arxiv article, either:
- new style (YYMM.NNNN), or
- old style (astro-ph/YYMMNNN)
:return: True if arXiv API page is recovered
"""
arxiv_pattern = re.compile('(\d{4,6}\.\d{4,6}|.*\-.*/\d{7})')
arxiv_matches = arxiv_pattern.findall(self.token)
logging.debug(arxiv_matches)
if len(arxiv_matches) == 1:
self.arxiv_id = arxiv_matches[0]
self.arXivAPI_url = urlparse.urlunsplit( ('https','export.arxiv.org','api/query','search_query=id:'+self.arxiv_id,'') )
logging.debug('arxiv_id: %s', self.arxiv_id)
logging.debug('ads_url: %s', self.arXivAPI_url)
return True
else:
self.arxiv_id = None
return False
def _is_bibcode(self):
"""Test if the token corresponds to an ADS bibcode or DOI"""
self.ads_url = urlparse.urlunsplit((
'http', self.prefs['ads_mirror'],
'doi/%s' % self.token, '', ''))
read = self._read(self.ads_url)