-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathmenotexport.py
1679 lines (1352 loc) · 53.9 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.
Update time: 2018-06-24 13:21:26.
Update time: 2018-07-28 19:46:44.
Update time: 2018-08-06 21:42:33.
TODO:
* add python 3 compatibility. If seems that pdfminer support 3 now:
https://github.com/pdfminer/pdfminer.six
* Possible to remove pandas dependency? -- Done in v1.5.1
* multi-thread or -process something to speed up
'''
__version__='Menotexport v1.5.1'
#---------------------Imports---------------------
import sys,os
import sqlite3
import argparse
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 import extracthl2
from lib.tools import printHeader, printInd, printNumHeader, makedirs
#from html2text import html2text
from bs4 import BeautifulSoup
from datetime import datetime
import re
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
#---------Regex pattern for matching dois---------
DOI_PATTERN=re.compile(r'(?:doi:)?\s?(10.[1-9][0-9]{3}/.*$)',
re.DOTALL|re.UNICODE)
# Sometimes citation imported via a .bib or .ris file may contain
# a note field (`annote = {{some note}} `for .bib, `N1 - some note` for .ris).
# It can be doi strings:
# * doi: 10.1021/ed020p517.1
# * 10.1021/ed020p517.1
# It can also be ISBN strings: e.g. ISBN 978.....
# It can also be PMID strings: e.g. PMID: xxxx
# It could be something else, whatever the citation provider decides to put in.
# So to distinguish them from actuall notes made by users, below is a list
# of regex patterns trying to catch some recognizable patterns and exclude
# them from the notes.
NOTE_EXCLUDE_PATTERNS=[
DOI_PATTERN,
]
class DocAnno(object):
def __init__(self,docid,meta,highlights=None,notes=None):
'''Obj to hold annotations (highlights+notes) in a doc.
'''
self.docid=docid
self.meta=meta
# Get file paths and names, a doc can have multiple files associated
self.path=meta['path'] # always a list if not None
if self.path is None:
self.hasfile=False
self.filename=None
self.path=[None,] # if DocNotes exists but no file, to make
# the iteration below possible
else:
self.hasfile=True
self.filename=[os.path.split(pii)[1] for pii in self.path]
#----------Create a fileanno obj for each file----------
self.file_annos={}
if len(self.path)>1:
self.has_multifile=True
else:
self.has_multifile=False
for ii, pii in enumerate(self.path):
hlii=highlights.get(pii,{})
ntii=notes.get(pii,{})
metaii=meta.copy()
metaii['path']=pii
annoii=FileAnno(docid,metaii,highlights=hlii,notes=ntii)
self.file_annos[pii]=annoii
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'] # a string or None
if self.path is None:
self.hasfile=False
self.filename=None
else:
self.hasfile=True
self.filename=os.path.split(self.path)[1]
if highlights is None:
self.hlpages=[]
elif isinstance(highlights, dict):
self.hlpages=highlights.keys()
self.hlpages.sort()
else:
raise Exception("highlights type wrong")
if notes is None:
self.ntpages=[]
elif isinstance(notes, dict):
self.ntpages=notes.keys()
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 WHERE Profiles.isSelf="true"
'''
query_fallback=\
'''SELECT Profiles.firstName, Profiles.lastName
FROM Profiles
'''
ret=db.execute(query).fetchall()
if len(ret)==0:
ret=db.execute(query_fallback).fetchall()
return ' '.join(filter(None,ret[0]))
def getProfileNames(db):
'''Get user (including co-authors) names'''
query =\
'''SELECT Profiles.uuid,
Profiles.firstName,
Profiles.lastName
FROM Profiles
'''
ret=db.execute(query).fetchall()
data=dict([(ii[0],' '.join(filter(None,ii[1:]))) for ii in ret])
return data
def getMetaData(db, docid):
'''Get meta-data of a doc by documentId.
'''
# fetch column from Document table
query_base=\
'''SELECT Documents.%s
FROM Documents
WHERE (Documents.id=%s)
'''
query_tags=\
'''
SELECT DocumentTags.tag
FROM DocumentTags
WHERE (DocumentTags.documentId=%s)
''' %docid
query_firstnames=\
'''
SELECT DocumentContributors.firstNames
FROM DocumentContributors
WHERE (DocumentContributors.documentId=%s)
''' %docid
query_lastnames=\
'''
SELECT DocumentContributors.lastName
FROM DocumentContributors
WHERE (DocumentContributors.documentId=%s)
''' %docid
query_keywords=\
'''
SELECT DocumentKeywords.keyword
FROM DocumentKeywords
WHERE (DocumentKeywords.documentId=%s)
''' %docid
query_folder=\
'''
SELECT Folders.name
FROM Folders
LEFT JOIN DocumentFolders
ON Folders.id=DocumentFolders.folderid
WHERE (DocumentFolders.documentId=%s)
''' %docid
def fetchField(db,query):
aa=db.execute(query).fetchall()
bb=[ii[0] for ii in aa]
if len(bb)==1:
return bb[0]
elif len(bb)==0:
return None
else:
return bb
#------------------Get file meta data------------------
fields=['id','citationkey','title','issue','pages',\
'publication','volume','year','doi','abstract',\
'arxivId','chapter','city','country','edition','institution',\
'isbn','issn','month','day','publisher','series','type',\
'read','favourite']
result={}
# query single-worded fields, e.g. year, city
for kii in fields:
vii=fetchField(db,query_base %(kii,docid))
result[kii]=vii
result['tags']=fetchField(db,query_tags)
result['firstnames']=fetchField(db,query_firstnames)
result['lastname']=fetchField(db,query_lastnames)
result['keywords']=fetchField(db,query_keywords)
result['folder']=fetchField(db,query_folder)
#-----------------Append user name-----------------
result['user_name']=getUserName(db)
#------------------Add local url------------------
result['path']=getFilePath(db,docid) # None or list
#-----Add folder to tags, if not there already-----
folder=result['folder']
result['folder']=folder or 'Canonical' # if no folder name, a canonical doc
tags=result['tags']
tags=tags or []
# Now I decide not to do this
'''
if folder is not None:
if tags is None:
if isinstance(folder,list):
tags=folder
else:
tags=[folder,]
elif isinstance(tags,list) and isinstance(folder,list):
tags.extend(folder)
tags=list(set(tags))
elif isinstance(tags,list) and not isinstance(folder,list):
tags.append(folder)
tags=list(set(tags))
elif not isinstance(tags,list) and isinstance(folder,list):
tags=folder+[tags,]
tags=list(set(tags))
elif not isinstance(tags,list) and not isinstance(folder,list):
tags=[tags, folder]
tags=list(set(tags))
else:
# there shouldn't be anything else, should it?
#pass
tags=[]
else:
tags=tags or []
'''
if not isinstance(tags,list):
tags=[tags,]
tags.sort()
result['tags']=tags
return result
def removeTrashedDocs(db, docids):
'''Remove ids of docs that are in Trash.
Ids of trashed docs will still appear in a folder, and will lead to
duplicates in the export.
'''
query_delete=\
'''
SELECT Documents.deletionPending
FROM Documents
WHERE (Documents.id=%s)
'''
results=[]
for idii in docids:
is_del=db.execute(query_delete %idii).fetchall()[0][0]
if not is_del=='true':
results.append(idii)
return results
#---------------Get file path of PDF(s) using documentId---------------
def getFilePath(db,docid,verbose=True):
'''Get file path of PDF(s) using documentId
Return <pth>: None or a LIST of file paths. If a single path, a len-1 list.
'''
query=\
'''SELECT Files.localUrl
FROM Files
LEFT JOIN DocumentFiles
ON DocumentFiles.hash=Files.hash
LEFT JOIN Documents
ON Documents.id=DocumentFiles.documentId
WHERE (Documents.id=%s)
''' %docid
ret=db.execute(query)
data=ret.fetchall()
if len(data)==0:
return None
else:
pth=[converturl2abspath(urlii[0]) for urlii in data]
return pth
#----------Extract highlights coordinates and related meta data-------
def getHighlights(db,filterdocid,results=None):
'''Extract highlights coordinates and related meta data.
<db>: sqlite3.connection to Mendeley sqlite database.
<filterdocid>: int, id of document to query.
<results>: dict or None, optional dictionary to hold the results. If None,
create a new empty dict.
Return: <results>: dictionary containing the query results, with
the following structure:
results={documentId1:
{'highlights': {path1: {page1: [hl1, hl2,...],
page2: [hl1, hl2,...],
...}
path2: {page1: [hl1, hl2,...],
page2: [hl1, hl2,...],
...}
}
'notes': {path1: {page1: [nt1, nt2,...],
page4: [nt1, nt2,...],
...}
...}
'meta': {'title': title,
'tags': [tag1, tag2,...],
'cite': citationkey,
...
}
documentId2: ...
}
where hl1={'rect': bbox,\
'cdate': cdate,\
'color': color,
'page':pg,
'author':'highlight author',\
'path':pth
}
note={'rect': bbox,\
'author':'note author',\
'content':docnote,\
'cdate': datetime.now(),\
'page':pg,
'path':pth
}
Update time: 2016-02-24 00:36:33.
Update time: 2018-06-27 21:45:27.
Update time: 2018-07-28 20:00:11.
'''
# For Mendeley versions newer than 1.16.1 (include), with highlight colors
query_new =\
'''SELECT Files.localUrl, FileHighlightRects.page,
FileHighlightRects.x1, FileHighlightRects.y1,
FileHighlightRects.x2, FileHighlightRects.y2,
FileHighlights.createdTime,
FileHighlights.author,
Profiles.firstName,
Profiles.lastName,
FileHighlights.color
FROM Files
LEFT JOIN FileHighlights
ON FileHighlights.fileHash=Files.hash
LEFT JOIN FileHighlightRects
ON FileHighlightRects.highlightId=FileHighlights.id
LEFT JOIN Profiles
ON Profiles.uuid=FileHighlights.profileUuid
WHERE (FileHighlightRects.page IS NOT NULL) AND
(FileHighlights.documentId=%s)
''' %filterdocid
# For Mendeley versions older than 1.16.1, no highlight colors
query_old =\
'''SELECT Files.localUrl, FileHighlightRects.page,
FileHighlightRects.x1, FileHighlightRects.y1,
FileHighlightRects.x2, FileHighlightRects.y2,
FileHighlights.createdTime,
FileHighlights.author,
Profiles.firstName,
Profiles.lastName
FROM Files
LEFT JOIN FileHighlights
ON FileHighlights.fileHash=Files.hash
LEFT JOIN FileHighlightRects
ON FileHighlightRects.highlightId=FileHighlights.id
LEFT JOIN Profiles
ON Profiles.uuid=FileHighlights.profileUuid
WHERE (FileHighlightRects.page IS NOT NULL) AND
(FileHighlights.documentId=%s)
''' %filterdocid
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.
# Fix incorrect storage ordering in Mendeley:
if bbox[0] > bbox[2]: bbox[0], bbox[2] = bbox[2], bbox[0]
if bbox[1] > bbox[3]: bbox[1], bbox[3] = bbox[3], bbox[1]
cdate = convert2datetime(r[6])
# Changes suggested by matteosecli: retrieve author of highlight:
author=r[7]
if not author.strip():
author=' '.join(filter(None,r[8:10]))
color=r[10] if hascolor else None
hlight = {'rect': bbox,\
'cdate': cdate,\
'color': color,
'page': pg,
'author': author,
'path': pth # distinguish between multi-attachments
}
#------------Save to dict------------
# any better way of doing this sht?
if filterdocid in results:
if 'highlights' in results[filterdocid]:
if pth in results[filterdocid]['highlights']:
if pg in results[filterdocid]['highlights'][pth]:
results[filterdocid]['highlights'][pth][pg].append(hlight)
else:
results[filterdocid]['highlights'][pth][pg]=[hlight,]
else:
results[filterdocid]['highlights'][pth]={pg:[hlight,]}
else:
results[filterdocid]['highlights']={pth:{pg:[hlight,]}}
else:
results[filterdocid]={'highlights':{pth:{pg:[hlight,]}}}
return results
#-------------------Get sticky notes-------------------
def getNotes(db,filterdocid,results=None):
'''Extract notes and related meta data
<db>: sqlite3.connection to Mendeley sqlite database.
<filterdocid>: int, id of document to query.
<results>: dict or None, optional dictionary to hold the results. If None,
create a new empty dict.
Return: <results>: dictionary containing the query results. See
more in the doc of getHighlights()
Update time: 2016-04-12 20:39:15.
Update time: 2018-06-27 21:52:04.
Update time: 2018-07-28 20:01:40.
'''
query=\
'''SELECT Files.localUrl, FileNotes.page,
FileNotes.x, FileNotes.y,
FileNotes.note,
FileNotes.modifiedTime,
FileNotes.author,
Profiles.firstName,
Profiles.lastName
FROM Files
LEFT JOIN FileNotes
ON FileNotes.fileHash=Files.hash
LEFT JOIN Profiles
ON Profiles.uuid=FileNotes.profileUuid
WHERE (FileNotes.page IS NOT NULL) AND
(FileNotes.documentId=%s)
''' %filterdocid
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, size does not matter
txt = r[4]
cdate = convert2datetime(r[5])
# Changes suggested by matteosecli: retrieve author of note:
author=r[6]
if not author.strip():
author=' '.join(filter(None,r[7:9]))
note = {'rect': bbox,\
'author':author,\
'content':txt,\
'cdate': cdate,\
'page':pg,
'path':pth,
'isgeneralnote': False
}
#------------Save to dict------------
if filterdocid in results:
if 'notes' in results[filterdocid]:
if pth in results[filterdocid]['notes']:
if pg in results[filterdocid]['notes'][pth]:
results[filterdocid]['notes'][pth][pg].append(note)
else:
results[filterdocid]['notes'][pth][pg]=[note,]
else:
results[filterdocid]['notes'][pth]={pg:[note,]}
else:
results[filterdocid]['notes']={pth:{pg:[note,]}}
else:
results[filterdocid]={'notes':{pth:{pg:[note,]}}}
return results
#-------------------Get side-bar notes-------------------
def getDocNotes(db,filterdocid,results=None):
'''Extract side-bar notes and related meta data
<db>: sqlite3.connection to Mendeley sqlite database.
<filterdocid>: int, id of document to query.
<results>: dict or None, optional dictionary to hold the results. If None,
create a new empty dict.
Return: <results>: dictionary containing the query results. with
See the doc in getHighlights().
Update time: 2016-04-12 20:44:38.
Update time: 2018-06-27 21:56:51.
Update time: 2018-07-28 20:02:10.
'''
# Some versions of Mendeley saves notes in DocumentsNotes
query=\
'''SELECT DocumentNotes.text,
DocumentNotes.documentId,
DocumentNotes.baseNote
FROM DocumentNotes
WHERE (DocumentNotes.documentId IS NOT NULL) AND
(DocumentNotes.documentId=%s)
''' %filterdocid
# Some versions (not sure which exactly) of Mendeley saves
# notes in Documents.note
query2=\
'''SELECT Documents.note
FROM Documents
WHERE (Documents.note IS NOT NULL) AND
(Documents.id=%s)
''' %filterdocid
# regex to transform Mendeley's old note formatting to html
# e.g. <m:bold>Bold</m:bold> to <bold>Bold</bold>
pattern=re.compile(r'<(/?)m:(bold|italic|underline|center|left|right|linebreak)(/?)>',
re.DOTALL | re.UNICODE)
subfunc=lambda match: u'<%s%s%s>' %match.groups()
if results is None:
results={}
#------------------Get notes------------------
ret=[]
try:
ret1 = db.execute(query).fetchall()
ret.extend(ret1)
except:
pass
try:
ret2 = db.execute(query2).fetchall()
ret.extend(ret2)
except:
pass
username=getUserName(db)
for ii,rii in enumerate(ret):
docnote=rii[0]
if len(docnote)==0:
# skip u''
continue
# skip things that are not user notes. See def of NOTE_EXCLUDE_PATTERNS
skip=False
for patternii in NOTE_EXCLUDE_PATTERNS:
if patternii.match(docnote) is not None:
skip=True
break
if skip:
continue
docid=filterdocid
try:
basenote=rii[2]
except:
basenote=None
pg=1
if docnote is not None and basenote is not None\
and docnote!=basenote:
docnote=basenote+'\n\n'+docnote
#--------Convert old <m:tag> to html <tag>--------
docnote=re.sub(pattern,subfunc,docnote)
#--------------------Parse html--------------------
soup=BeautifulSoup(docnote,'html.parser')
# replace <br> tags with newline
for br in soup.find_all('br'):
br.replace_with('\n')
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
pth=getFilePath(db,docid) # a list, could be more than 1, or None
# If no attachment, use None as path
if pth is None:
# make it compatible with the for loop below
pth=[None,]
bbox = [50, 700, 80, 730]
# needs a rectangle, size does not matter
note = {'rect': bbox,
'author': username,
'content':docnote,
'cdate': datetime.now(),
'page':pg,
'path':pth,
'isgeneralnote': True
}
#-------------------Save to dict-------------------
# if multiple attachments, add to each of them
for pthii in pth:
if docid in results:
if 'notes' in results[docid]:
if pthii in results[docid]['notes']:
if pg in results[docid]['notes'][pthii]:
results[docid]['notes'][pthii][pg].insert(0,note)
else:
results[docid]['notes'][pthii][pg]=[note,]
else:
results[docid]['notes'][pthii]={pg:[note,]}
else:
results[docid]['notes']={pthii:{pg:[note,]}}
else:
results[docid]={'notes':{pthii:{pg:[note,]}}}
return results
#-------------Reformat annotations to a dict of DocAnno objs-------------
def reformatAnno(annodict):
'''Reformat annotations to a dict of DocAnno objs
<annodict>: dict, annotation dict. See doc in getHighlights().
Return <result>: dict, keys: documentId; value: DocAnno objs.
'''
result={}
for kk,vv in annodict.items():
annoii=DocAnno(kk,vv['meta'],\
highlights=vv.get('highlights',{}),\
notes=vv.get('notes',{}))
result[kk]=annoii
return result
def getOtherDocs(db,folderid,annodocids,verbose=True):
'''Get a list of doc meta-data not in annotation list.
<annodocids>: list, doc documentId.
Deprecated. No longer in use.
'''
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)
otherdocids.sort()
#------------------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.
Deprecated, no longer in use.
'''
#------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
Update time: 2018-07-28 20:11:09.
'''
query=\
'''SELECT Documents.id
FROM Documents
LEFT JOIN DocumentFolders
ON Documents.id=DocumentFolders.documentId
WHERE (DocumentFolders.folderid=%s)
''' %folderid
ret=db.execute(query)
data=ret.fetchall()
docids=[ii[0] for ii in data]
docids.sort()
return docids
def getCanonicals(db,verbose=True):
query=\
'''SELECT Documents.id
FROM Documents
LEFT JOIN DocumentFolders
ON DocumentFolders.documentId=Documents.id
WHERE (DocumentFolders.folderId IS NULL)
'''
ret=db.execute(query)
data=ret.fetchall()
return [int(ii[0]) for ii in data]
#--------------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.
'''
# get all folders with id, name, parentid
query=\
'''SELECT Folders.id,
Folders.name,
Folders.parentID
FROM Folders
'''
# get folder by name
query1=\
'''SELECT Folders.id,
Folders.name,
Folders.parentID
FROM Folders
WHERE (Folders.name="%s")
'''%folder
#-----------------Get all folders-----------------
ret=db.execute(query)
data=ret.fetchall()
# dict, key: folderid, value: (folder_name, parent_id)
df=dict([(ii[0],ii[1:]) for ii in data])
allfolderids=[ii[0] for ii in data]
#---------------Select target folder---------------
if folder is None:
folderids=allfolderids
if type(folder) is str:
folderids=db.execute(query1).fetchall()
folderids=[ii[0] for ii in folderids]
elif isinstance(folder, (tuple,list)):
# get folder from gui
#seldf=df[(df.folderid==folder[0]) & (df.folder==folder[1])]
#folderids=fetchField(seldf,'folderid')
folderids=[folder[0]]
#----------------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>: dict, key: folderid, value: (folder_name, parent_id).
<folderid>: int, folder id
'''
getParentId=lambda df,id: df[id][1]
results=[]
for idii in df:
fii,pii=df[idii]
cid=idii
while True:
pid=getParentId(df,cid)