forked from Xunius/Menotexport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmenotexport.py
1493 lines (1231 loc) · 50.3 KB
/
menotexport.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/python
'''
- Bulk export annotated PDFs from Mendeley, with notes and highlights.
- Extract mendeley notes and highlights and save into text file(s).
- Group highlights and notes by tags, and export to a text file.
- PDFs without annotations are also exported.
- Export meta-data and annotations to .bib file, in a default format or in one suitable
for Zotero import.
# Copyright 2016 Guang-zhi XU
#
# This file is distributed under the terms of the
# GPLv3 licence. See the LICENSE file for details.
# You may use, distribute and modify this code under the
# terms of the GPLv3 license.
Update time: 2016-04-15 16:25:00.
Update time: 2016-06-22 16:26:11.
'''
__version__='Menotexport v1.4.4'
#---------------------Imports---------------------
import sys,os
import sqlite3
import argparse
import pandas as pd
from lib import extracttags
from lib import extractnt
from lib import exportpdf
from lib import exportannotation
from lib import export2bib
from lib import export2ris
from lib.tools import printHeader, printInd, printNumHeader
#from html2text import html2text
from bs4 import BeautifulSoup
from datetime import datetime
if sys.version_info[0]>=3:
#---------------------Python3---------------------
from urllib.parse import unquote
from urllib.parse import urlparse
else:
#--------------------Python2.7--------------------
from urllib import unquote
from urlparse import urlparse
#-------Fetch a column from pandas dataframe-------
fetchField=lambda x, f: x[f].unique().tolist()
class FileAnno(object):
def __init__(self,docid,meta,highlights=None,notes=None):
'''Obj to hold annotations (highlights+notes) in a single PDF.
'''
self.docid=docid
self.meta=meta
self.highlights=highlights
self.notes=notes
self.path=meta['path']
_dir, self.filename=os.path.split(self.path)
if _dir=='/pseudo_path':
self.hasfile=False
else:
self.hasfile=True
if highlights is None:
self.hlpages=[]
elif type(highlights) is dict:
self.hlpages=highlights.keys()
self.hlpages.sort()
elif type(highlights) is list:
self.hlpages=[ii.page for ii in highlights]
self.hlpages.sort()
else:
raise Exception("highlights type wrong")
if notes is None:
self.ntpages=[]
elif type(notes) is dict:
self.ntpages=notes.keys()
self.ntpages.sort()
elif type(notes) is list:
self.ntpages=[ii.page for ii in notes]
self.ntpages.sort()
else:
raise Exception("notes type wrong")
self.pages=list(set(self.hlpages+self.ntpages))
self.pages.sort()
def convert2datetime(s):
return datetime.strptime(s,'%Y-%m-%dT%H:%M:%SZ')
def converturl2abspath(url):
'''Convert a url string to an absolute path
This is necessary for filenames with unicode strings.
'''
#--------------------For linux--------------------
path = unquote(str(urlparse(url).path)).decode("utf8")
path=os.path.abspath(path)
if os.path.exists(path):
return path
else:
#-------------------For windowes-------------------
if url[5:8]==u'///':
url=u'file://'+url[8:]
path=urlparse(url)
path=os.path.join(path.netloc,path.path)
path=unquote(str(path)).decode('utf8')
path=os.path.abspath(path)
return path
def getUserName(db):
'''Query db to get user name'''
query=\
'''SELECT Profiles.firstName, Profiles.lastName
FROM Profiles
'''
ret=db.execute(query)
ret=[ii for ii in ret]
return ' '.join(ret[0])
def getMetaData(db, docid):
'''Get meta-data of a doc by documentId.
'''
query=\
'''SELECT Documents.id,
Documents.citationkey,
Documents.title,
Documents.issue,
Documents.pages,
Documents.publication,
Documents.volume,
Documents.year,
Documents.doi,
Documents.abstract,
Documents.arxivId,
Documents.chapter,
Documents.city,
Documents.country,
Documents.edition,
Documents.institution,
Documents.isbn,
Documents.issn,
Documents.month,
Documents.day,
Documents.publisher,
Documents.series,
Documents.type,
Documents.read,
Documents.favourite,
DocumentTags.tag,
DocumentContributors.firstNames,
DocumentContributors.lastName,
DocumentKeywords.keyword
FROM Documents
LEFT JOIN DocumentTags
ON DocumentTags.documentId=Documents.id
LEFT JOIN DocumentContributors
ON DocumentContributors.documentId=Documents.id
LEFT JOIN DocumentKeywords
ON DocumentKeywords.documentId=Documents.id
'''
#------------------Get file meta data------------------
ret=db.execute(query)
data=ret.fetchall()
fields=['docid','citationkey','title','issue','pages',\
'publication','volume','year','doi','abstract',\
'arxivId','chapter','city','country','edition','institution',\
'isbn','issn','month','day','publisher','series','type',\
'read','favourite','tags','firstnames','lastname','keywords']
df=pd.DataFrame(data=data,columns=fields)
docdata=df[df.docid==docid]
result={}
for ff in fields:
fieldii=fetchField(docdata,ff)
result[ff]=fieldii[0] if len(fieldii)==1 else fieldii
#-----------------Append user name-----------------
username=getUserName(db)
result['user_name']=username
return result
#---------------Get file path of a PDF using documentId---------------
def getFilePath(db,docid,verbose=True):
'''Get file path of a PDF using documentId
'''
query=\
'''SELECT Files.localUrl,
DocumentFiles.hash,
Documents.id
FROM Files
LEFT JOIN DocumentFiles
ON DocumentFiles.hash=Files.hash
LEFT JOIN Documents
ON Documents.id=DocumentFiles.documentId
'''
ret=db.execute(query)
data=ret.fetchall()
df=pd.DataFrame(data=data,columns=['url','hash','docid'])
#-----------------Search file path-----------------
pathdata=df[df.docid==docid]
if len(pathdata)==0:
return None
else:
url=fetchField(pathdata,'url')[0]
pth = converturl2abspath(url)
return pth
def getHighlights(db,results=None,folderid=None,foldername=None,filterdocid=None):
'''Extract the coordinates of highlights from the Mendeley database
and put results into a dictionary.
<db>: sqlite3.connection to Mendeley sqlite database.
<results>: dict or None, optional dictionary to hold the results.
<folderid>: int, id of given folder. If None, don't do folder filtering.
<foldername>: str, name of folder corresponding to <folderid>. Used to
populate meta data.
<filterdocid>: int, id of document to query. If None, don't do docid filtering.
Return: <results>: dictionary containing the query results, with
the following structure:
results={documentId1: {'highlights': {page1: [hl1, hl2,...],
page2: [hl1, hl2,...],
...}
'notes': {page1: [nt1, nt2,...],
page4: [nt1, nt2,...],
...}
'meta': {'title': title,
'tags': [tag1, tag2,...],
'cite': citationkey,
'path': abspath,
...
}
documentId2: ...
}
where hl1={'rect': bbox,
'cdate': cdate,
'page':pg}
note={'rect': bbox,
'author':author,
'content':txt,
'cdate': cdate,
'page':pg}
Update time: 2016-02-24 00:36:33.
'''
query_new =\
'''SELECT Files.localUrl, FileHighlightRects.page,
FileHighlightRects.x1, FileHighlightRects.y1,
FileHighlightRects.x2, FileHighlightRects.y2,
FileHighlights.createdTime,
FileHighlights.documentId,
DocumentFolders.folderid,
Folders.name,
FileHighlights.color
FROM Files
LEFT JOIN FileHighlights
ON FileHighlights.fileHash=Files.hash
LEFT JOIN FileHighlightRects
ON FileHighlightRects.highlightId=FileHighlights.id
LEFT JOIN DocumentFolders
ON DocumentFolders.documentId=FileHighlights.documentId
LEFT JOIN Folders
ON Folders.id=DocumentFolders.folderid
WHERE (FileHighlightRects.page IS NOT NULL)
'''
query_old =\
'''SELECT Files.localUrl, FileHighlightRects.page,
FileHighlightRects.x1, FileHighlightRects.y1,
FileHighlightRects.x2, FileHighlightRects.y2,
FileHighlights.createdTime,
FileHighlights.documentId,
DocumentFolders.folderid,
Folders.name
FROM Files
LEFT JOIN FileHighlights
ON FileHighlights.fileHash=Files.hash
LEFT JOIN FileHighlightRects
ON FileHighlightRects.highlightId=FileHighlights.id
LEFT JOIN DocumentFolders
ON DocumentFolders.documentId=FileHighlights.documentId
LEFT JOIN Folders
ON Folders.id=DocumentFolders.folderid
WHERE (FileHighlightRects.page IS NOT NULL)
'''
query_canonical_new =\
'''SELECT Files.localUrl, FileHighlightRects.page,
FileHighlightRects.x1, FileHighlightRects.y1,
FileHighlightRects.x2, FileHighlightRects.y2,
FileHighlights.createdTime,
FileHighlights.documentId,
FileHighlights.color
FROM Files
LEFT JOIN FileHighlights
ON FileHighlights.fileHash=Files.hash
LEFT JOIN FileHighlightRects
ON FileHighlightRects.highlightId=FileHighlights.id
WHERE (FileHighlightRects.page IS NOT NULL)
'''
query_canonical_old =\
'''SELECT Files.localUrl, FileHighlightRects.page,
FileHighlightRects.x1, FileHighlightRects.y1,
FileHighlightRects.x2, FileHighlightRects.y2,
FileHighlights.createdTime,
FileHighlights.documentId
FROM Files
LEFT JOIN FileHighlights
ON FileHighlights.fileHash=Files.hash
LEFT JOIN FileHighlightRects
ON FileHighlightRects.highlightId=FileHighlights.id
WHERE (FileHighlightRects.page IS NOT NULL)
'''
if folderid is not None and filterdocid is None:
fstr='(Folders.id="%s")' %folderid
query_new=query_new+' AND\n'+fstr
query_old=query_old+' AND\n'+fstr
if filterdocid is not None:
fstr='(FileHighlights.documentId="%s")' %filterdocid
query_new=query_canonical_new+' AND\n'+fstr
query_old=query_canonical_old+' AND\n'+fstr
if results is None:
results={}
#------------------Get highlights------------------
try:
ret = db.execute(query_new)
hascolor=True
except:
ret = db.execute(query_old)
hascolor=False
for ii,r in enumerate(ret):
pth = converturl2abspath(r[0])
pg = r[1]
bbox = [r[2], r[3], r[4], r[5]]
# [x1,y1,x2,y2], (x1,y1) being bottom-left,
# (x2,y2) being top-right. Origin at bottom-left
cdate = convert2datetime(r[6])
docid=r[7]
if filterdocid is None:
folder=r[9]
if hascolor:
color=r[10]
else:
color=None
else:
folder=None
if hascolor:
color=r[8]
else:
color=None
hlight = {'rect': bbox,\
'cdate': cdate,\
'color': color,
'page':pg\
}
#------------Save to dict------------
if docid in results:
if 'highlights' in results[docid]:
if pg in results[docid]['highlights']:
results[docid]['highlights'][pg].append(hlight)
else:
results[docid]['highlights'][pg]=[hlight,]
else:
results[docid]['highlights']={pg:[hlight,]}
else:
meta=getMetaData(db, docid)
if folder is not None:
if meta['tags'] is None:
tags=[folder,]
elif type(meta['tags']) is list and folder not in meta['tags']:
tags=meta['tags']+[folder,]
elif type(meta['tags']) is list and folder in meta['tags']:
tags=meta['tags']
else:
#tags=[meta['tags'],folder]
# there shouldn't be anything else, should it?
#pass
tags=[]
else:
tags=meta['tags'] or []
meta['tags']=tags
meta['path']=pth
meta['folder']='' if folder is None else foldername
results[docid]={'highlights':{pg:[hlight,]}}
results[docid]['meta']=meta
return results
#-------------------Get sticky notes-------------------
def getNotes(db,results=None,folderid=None,foldername=None,filterdocid=None):
'''Extract notes from the Mendeley database
<db>: sqlite3.connection to Mendeley sqlite database.
<results>: dict or None, optional dictionary to hold the results.
<folderid>: int, id of given folder. If None, don't do folder filtering.
<foldername>: str, name of folder corresponding to <folderid>. Used to
populate meta data.
<filterdocid>: int, id of document to query. If None, don't do docid filtering.
Return: <results>: dictionary containing the query results. See
more in the doc of getHighlights()
Update time: 2016-04-12 20:39:15.
'''
query=\
'''SELECT Files.localUrl, FileNotes.page,
FileNotes.x, FileNotes.y,
FileNotes.author, FileNotes.note,
FileNotes.modifiedTime,
FileNotes.documentId,
DocumentFolders.folderid,
Folders.name
FROM Files
LEFT JOIN FileNotes
ON FileNotes.fileHash=Files.hash
LEFT JOIN DocumentFolders
ON DocumentFolders.documentId=FileNotes.documentId
LEFT JOIN Folders
ON Folders.id=DocumentFolders.folderid
WHERE (FileNotes.page IS NOT NULL)
'''
query_canonical=\
'''SELECT Files.localUrl, FileNotes.page,
FileNotes.x, FileNotes.y,
FileNotes.author, FileNotes.note,
FileNotes.modifiedTime,
FileNotes.documentId
FROM Files
LEFT JOIN FileNotes
ON FileNotes.fileHash=Files.hash
WHERE (FileNotes.page IS NOT NULL)
'''
if folderid is not None and filterdocid is None:
fstr='(Folders.id="%s")' %folderid
query=query+' AND\n'+fstr
if filterdocid is not None:
fstr='(FileNotes.documentId="%s")' %filterdocid
query=query_canonical+' AND\n'+fstr
if results is None:
results={}
#------------------Get notes------------------
ret = db.execute(query)
for ii,r in enumerate(ret):
pth = converturl2abspath(r[0])
pg = r[1]
bbox = [r[2], r[3], r[2]+30, r[3]+30]
# needs a rectangle however size does not matter
author=r[4]
txt = r[5]
cdate = convert2datetime(r[6])
docid=r[7]
if filterdocid is None:
folder=r[9]
else:
folder=None
note = {'rect': bbox,\
'author':author,\
'content':txt,\
'cdate': cdate,\
'page':pg\
}
#------------Save to dict------------
if docid in results:
if 'notes' in results[docid]:
if pg in results[docid]['notes']:
results[docid]['notes'][pg].append(note)
else:
results[docid]['notes'][pg]=[note,]
else:
results[docid]['notes']={pg:[note,]}
else:
meta=getMetaData(db, docid)
if folder is not None:
if meta['tags'] is None:
tags=[folder,]
elif type(meta['tags']) is list and folder not in meta['tags']:
tags=meta['tags']+[folder,]
elif type(meta['tags']) is list and folder in meta['tags']:
tags=meta['tags']
else:
#tags=[meta['tags'],folder]
# see above
#pass
tags=[]
else:
tags=meta['tags'] or []
meta['tags']=tags
meta['path']=pth
meta['folder']='' if folder is None else foldername
results[docid]={'notes':{pg:[note,]}}
results[docid]['meta']=meta
return results
#-------------------Get side-bar notes-------------------
def getDocNotes(db,results=None,folderid=None,foldername=None,filterdocid=None):
'''Extract side-bar notes from the Mendeley database
<db>: sqlite3.connection to Mendeley sqlite database.
<results>: dict or None, optional dictionary to hold the results.
<folderid>: int, id of given folder. If None, don't do folder filtering.
<foldername>: str, name of folder corresponding to <folderid>. Used to
populate meta data.
<filterdocid>: int, id of document to query. If None, don't do docid filtering.
Return: <results>: dictionary containing the query results. with
See the doc in getHighlights().
Update time: 2016-04-12 20:44:38.
'''
query=\
'''SELECT DocumentNotes.text,
DocumentNotes.documentId,
DocumentNotes.baseNote,
DocumentFiles.hash,
Documents.title,
DocumentFolders.folderid,
Folders.name
FROM DocumentNotes
LEFT JOIN DocumentFolders
ON DocumentFolders.documentId=DocumentNotes.documentId
LEFT JOIN Folders
ON Folders.id=DocumentFolders.folderid
LEFT JOIN DocumentFiles
ON DocumentFiles.documentId=DocumentNotes.documentId
LEFT JOIN Documents
ON Documents.id=DocumentNotes.documentId
WHERE (DocumentNotes.documentId IS NOT NULL)
'''
query_canonical=\
'''SELECT DocumentNotes.text,
DocumentNotes.documentId,
DocumentNotes.baseNote,
DocumentFiles.hash,
Documents.title
FROM DocumentNotes
LEFT JOIN DocumentFiles
ON DocumentFiles.documentId=DocumentNotes.documentId
LEFT JOIN Documents
ON Documents.id=DocumentNotes.documentId
WHERE (DocumentNotes.documentId IS NOT NULL)
'''
if filterdocid is None and folderid is not None:
fstr='(Folders.id="%s")' %folderid
query=query+' AND\n'+fstr
if filterdocid is not None:
fstr='(Documents.id="%s")' %filterdocid
query=query_canonical+' AND\n'+fstr
if results is None:
results={}
#------------------Get notes------------------
ret = db.execute(query)
for ii,r in enumerate(ret):
docnote=r[0]
docid=r[1]
basenote=r[2]
title=r[4]
if filterdocid is None:
folder=r[6]
else:
folder=None
#dochash=r[5]
pg=1
if docnote is not None and basenote is not None\
and docnote!=basenote:
docnote=basenote+'\n\n'+docnote
#--------------------Parse html--------------------
soup=BeautifulSoup(docnote,'html.parser')
docnote=soup.get_text()
'''
parser=html2text.HTML2Text()
parser.ignore_links=True
docnote=parser.handle(docnote)
'''
# Try get file path
pth=getFilePath(db,docid) or '/pseudo_path/%s.pdf' %title
bbox = [50, 700, 80, 730]
# needs a rectangle however size does not matter
note = {'rect': bbox,\
'author':'Mendeley user',\
'content':docnote,\
'cdate': datetime.now(),\
'page':pg\
}
#-------------------Save to dict-------------------
if docid in results:
if 'notes' in results[docid]:
if pg in results[docid]['notes']:
results[docid]['notes'][pg].insert(0,note)
else:
results[docid]['notes'][pg]=[note,]
else:
results[docid]['notes']={pg:[note,]}
else:
meta=getMetaData(db, docid)
if folder is not None:
if meta['tags'] is None:
tags=[folder,]
elif type(meta['tags']) is list and folder not in meta['tags']:
tags=meta['tags']+[folder,]
elif type(meta['tags']) is list and folder in meta['tags']:
tags=meta['tags']
else:
#tags=[meta['tags'],folder]
#pass
tags=[]
else:
tags=meta['tags'] or []
meta['tags']=tags
meta['path']=pth
meta['folder']='' if folder is None else foldername
results[docid]={'notes':{pg:[note,]}}
results[docid]['meta']=meta
return results
#-------------Reformat annotations to a list of FileAnnos-------------
def reformatAnno(annodict):
'''Reformat annotations to a dict of FileAnnos
<annodict>: dict, annotation dict. See doc in getHighlights().
Return <annos>: dict, keys: documentId; value: FileAnno objs.
'''
result={}
for kk,vv in annodict.items():
annoii=FileAnno(kk,vv['meta'],\
highlights=vv.get('highlights',{}),\
notes=vv.get('notes',{}))
result[kk]=annoii
return result
#---------Get a list of doc meta-data not in annotation list----------
def getOtherDocs(db,folderid,foldername,annodocids,verbose=True):
'''Get a list of doc meta-data not in annotation list.
<annodocids>: list, doc documentId.
'''
folderdocids=getFolderDocList(db,folderid)
if not set(annodocids).issubset(set(folderdocids)):
raise Exception("Exception")
#------Docids in folder and not in annodocids------
otherdocids=set(folderdocids).difference((annodocids))
otherdocids=list(otherdocids)
#------------------Get meta data------------------
result=[]
for ii in otherdocids:
docii=getMetaData(db,ii)
docii['path']=getFilePath(db,ii) #Local file path, can be None
docii['folder']=foldername
result.append(docii)
return result
#---------Get a list of doc meta-data not in annotation list----------
def getOtherCanonicalDocs(db,alldocids,annodocids,verbose=True):
'''Get a list of doc meta-data not in annotation list.
<annodocids>: list, doc documentId.
'''
#------Docids in folder and not in annodocids------
otherdocids=set(alldocids).difference((annodocids))
otherdocids=list(otherdocids)
#------------------Get meta data------------------
result=[]
for ii in otherdocids:
docii=getMetaData(db,ii)
docii['path']=getFilePath(db,ii) #Local file path, can be None
docii['folder']='Canonical'
result.append(docii)
return result
#----------Get a list of docids from a folder--------------
def getFolderDocList(db,folderid,verbose=True):
'''Get a list of docids from a folder
'''
query=\
'''SELECT Documents.id,
DocumentFolders.folderid,
Folders.name
FROM Documents
LEFT JOIN DocumentFolders
ON Documents.id=DocumentFolders.documentId
LEFT JOIN Folders
ON Folders.id=DocumentFolders.folderid
'''
if folderid is not None:
fstr='(Folders.id="%s")' %folderid
fstr='WHERE '+fstr
query=query+' '+fstr
#------------------Get docids------------------
ret=db.execute(query)
data=ret.fetchall()
df=pd.DataFrame(data=data,columns=['docid','folderid','folder'])
docids=fetchField(df,'docid')
return docids
#--------------Get canonical document ids----------------
def getCanonicals(db,verbose=True):
query=\
'''SELECT Documents.id,
DocumentFolders.folderId
FROM Documents
LEFT JOIN DocumentFolders
ON DocumentFolders.documentId=Documents.id
WHERE (DocumentFolders.folderId IS NULL)
'''
ret=db.execute(query)
data=ret.fetchall()
df=pd.DataFrame(data=data,columns=['docid','folderid'])
canonical_doc_ids=fetchField(df,'docid')
return [int(ii) for ii in canonical_doc_ids]
#--------------Get folder id and name list in database----------------
def getFolderList(db,folder,verbose=True):
'''Get folder id and name list in database
<folder>: select folder from database.
If None, select all folders/subfolders.
If str, select folder <folder>, and all subfolders. If folder
name conflicts, select the one with higher level.
If a tuple of (id, folder), select folder with name <folder>
and folder id <id>, to avoid name conflicts.
Return: <folders>: list, with elements of (id, folder_tree).
where <folder_tree> is a str of folder name with tree structure, e.g.
test/testsub/testsub2.
Update time: 2016-06-16 19:38:15.
'''
query=\
'''SELECT Folders.id,
Folders.name,
Folders.parentID
FROM Folders
'''
#-----------------Get all folders-----------------
ret=db.execute(query)
data=ret.fetchall()
df=pd.DataFrame(data=data,columns=['folderid','folder','parentID'])
allfolderids=fetchField(df,'folderid')
#---------------Select target folder---------------
if folder is None:
folderids=allfolderids
if type(folder) is str:
# Select the given folder, if more than 1 name match, select the
# one with lowest parentID.
seldf=df[df.folder==folder].sort_values('parentID')
folderids=fetchField(seldf,'folderid')
elif type(folder) is tuple or type(folder) is list:
seldf=df[(df.folderid==folder[0]) & (df.folder==folder[1])]
folderids=fetchField(seldf,'folderid')
#----------------Get all subfolders----------------
if folder is not None:
folderids2=[]
for ff in folderids:
folderids2.append(ff)
subfs=getSubFolders(df,ff)
folderids2.extend(subfs)
else:
folderids2=folderids
#---------------Remove empty folders---------------
folderids2=[ff for ff in folderids2 if not isFolderEmpty(db,ff)]
#---Get names and tree structure of all non-empty folders---
folders=[]
for ff in folderids2:
folders.append(getFolderTree(df,ff))
#----------------------Return----------------------
if folder is None:
return folders
else:
if len(folders)==0:
print("Given folder name not found in database or folder is empty.")
return []
else:
return folders
#--------------------Check a folder is empty or not--------------------
def isFolderEmpty(db,folderid,verbose=True):
'''Check a folder is empty or not
'''
query=\
'''SELECT Documents.title,
DocumentFolders.folderid,
Folders.name
FROM Documents
LEFT JOIN DocumentFolders
ON Documents.id=DocumentFolders.documentId
LEFT JOIN Folders
ON Folders.id=DocumentFolders.folderid
'''
fstr='(Folders.id="%s")' %folderid
fstr='WHERE '+fstr
query=query+' '+fstr
ret=db.execute(query)
data=ret.fetchall()
if len(data)==0:
return True
else:
return False
#-------------------Get subfolders of a given folder-------------------
def getSubFolders(df,folderid,verbose=True):
'''Get subfolders of a given folder
<df>: dataframe, contains all folders (including empty ones) id, name and parentID.
<folderid>: int, folder id
'''
getParentId=lambda df,id: fetchField(df[df.folderid==id],'parentID')[0]
results=[]
for ii in range(len(df)):
idii,fii,pii=df.loc[ii]
cid=idii
while True:
pid=getParentId(df,cid)
if pid==-1 or pid==0:
break
if pid==folderid:
results.append(idii)
break
else:
cid=pid
results.sort()
return results
#-------------Get folder tree structure of a given folder-------------
def getFolderTree(df,folderid,verbose=True):
'''Get folder tree structure of a given folder
<df>: dataframe, contains all folders (including empty ones) id, name and parentID.
<folderid>: int, folder id
'''
getFolderName=lambda df,id: fetchField(df[df.folderid==id],'folder')[0]
getParentId=lambda df,id: fetchField(df[df.folderid==id],'parentID')[0]
folder=getFolderName(df,folderid)
#------------Back track tree structure------------
cid=folderid
while True:
pid=getParentId(df,cid)
if pid==-1 or pid==0:
break
else:
pfolder=getFolderName(df,pid)
folder=u'%s/%s' %(pfolder,folder)
cid=pid
return folderid,folder
def extractAnnos(annotations,action,verbose):
faillist=[]
annotations2={} #keys: docid, values: extracted annotations
#-----------Loop through documents---------------
num=len(annotations)
docids=annotations.keys()
for ii,idii in enumerate(docids):
annoii=annotations[idii]
fii=annoii.path
fnameii=annoii.filename
if verbose:
printNumHeader('Processing file:',ii+1,num,3)
printInd(fnameii,4)
if 'm' in action:
from lib import extracthl2
try:
#------ Check if pdftotext is available--------
if extracthl2.checkPdftotext():
if verbose:
printInd('Retrieving highlights using pdftotext ...',4,prefix='# <Menotexport>:')
hltexts=extracthl2.extractHighlights2(fii,annoii,verbose)
else:
if verbose:
printInd('Retrieving highlights using pdfminer ...',4,prefix='# <Menotexport>:')
hltexts=extracthl2.extractHighlights(fii,annoii,verbose)
except:
faillist.append(fnameii)
hltexts=[]
else:
hltexts=[]
if 'n' in action:
if verbose:
printInd('Retrieving notes...',4,prefix='# <Menotexport>:')
try:
nttexts=extractnt.extractNotes(fii,annoii,verbose)
except:
faillist.append(fnameii)
nttexts=[]
else:
nttexts=[]
#------------Attach ori texts to notes------------
nttexts=extractnt.attachRefTextsToNotes(nttexts,hltexts)
annoii.highlights=hltexts
annoii.notes=nttexts
annotations2[idii]=annoii