forked from SavinaRoja/OpenAccess_EPUB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.py
1798 lines (1631 loc) · 83.9 KB
/
content.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
import xml.dom.minidom as minidom
import xml.dom
import logging
import os, os.path
import utils
class OPSContent(object):
'''A class for instantiating content xml documents in the OPS Preferred
Vocabulary'''
def __init__(self, documentstring, doi, outdirect, document):
print('Generating OPS content...')
self.inputstring = documentstring
self.doc = minidom.parse(self.inputstring)
#Get string from outdirect sans "journal."
self.doi = doi
self.jid = self.doi.split('journal.')[1] #journal id string
self.syn_frag = 'synop.{0}.xml'.format(self.jid) + '#{0}'
self.main_frag = 'main.{0}.xml'.format(self.jid) + '#{0}'
self.bib_frag = 'biblio.{0}.xml'.format(self.jid) + '#{0}'
self.tab_frag = 'tables.{0}.xml'.format(self.jid) + '#{0}'
self.outdir = os.path.join(outdirect, 'OPS')
self.outputs = {'Synopsis': os.path.join(outdirect, 'OPS', 'synop.{0}.xml'.format(self.jid)),
'Main': os.path.join(outdirect, 'OPS', 'main.{0}.xml'.format(self.jid)),
'Biblio': os.path.join(outdirect, 'OPS', 'biblio.{0}.xml'.format(self.jid)),
'Tables': os.path.join(outdirect, 'OPS', 'tables.{0}.xml'.format(self.jid))}
self.metadata = document.front
self.backdata = document.back
self.createSynopsis(self.metadata, self.backdata)
self.createMain()
try:
back = self.doc.getElementsByTagName('back')[0]
except IndexError:
pass
else:
self.createBiblio(self.doc, back)
def createSynopsis(self, meta, back):
'''Create an output file containing a representation of the article
synopsis'''
#Initiate the document, returns the document and its body element
synop, synbody = self.initiateDocument('Synopsis file')
#Create the title for the article
title = synbody.appendChild(synop.createElement('h1'))
title.setAttribute('id', 'title')
title.setAttribute('class', 'article-title')
title.childNodes = meta.article_meta.article_title.childNodes
#Affiliation index to be generated as authors parsed
affiliation_index = []
#Create authors
self.synopsisAuthors(meta, synbody, synop)
#Create a node for the affiliation text
aff_node = synop.createElement('p')
art_affs = meta.article_meta.art_affs
if art_affs:
for item in art_affs:
if 'aff' in item.rid:
sup = synop.createElement('sup')
sup.setAttribute('id', item.rid)
sup.appendChild(synop.createTextNode(str(art_affs.index(item) + 1)))
aff_node.appendChild(sup)
aff_node.appendChild(synop.createTextNode(item.address))
synbody.appendChild(aff_node)
#Create the Abstract if it exists
try:
abstract = meta.article_meta.abstracts['default']
except KeyError:
pass
else:
abstitle = synbody.appendChild(synop.createElement('h2'))
abstitle.appendChild(synop.createTextNode('Abstract'))
synbody.appendChild(abstract)
abstract.tagName = 'div'
abstract.setAttribute('id', 'abstract')
abstract.setAttribute('class', 'abstract')
for title in abstract.getElementsByTagName('title'):
title.tagName = 'h3'
for sec in abstract.getElementsByTagName('sec'):
sec.tagName = 'div'
self.postNodeHandling(abstract, synop)
#Create the Author's Summary if it exists
try:
summary = meta.article_meta.abstracts['summary']
except KeyError:
pass
else:
summary_title = synbody.appendChild(synop.createElement('h2'))
summary_title.appendChild(synop.createTextNode('Author Summary'))
for title in summary.getElementsByTagName('title'):
if utils.serializeText(title, stringlist = []) == 'Author Summary':
summary.removeChild(title)
synbody.appendChild(summary)
summary.tagName = 'div'
summary.removeAttribute('abstract-type')
summary.setAttribute('id', 'author-summary')
summary.setAttribute('class', 'summary')
for title in abstract.getElementsByTagName('title'):
title.tagName = 'h3'
for sec in abstract.getElementsByTagName('sec'):
sec.tagName = 'div'
#for para in abstract.getElementsByTagName('p'):
# para.tagName = 'big'
self.postNodeHandling(abstract, synop)
#We can create the <div class="articleInfo">
#We will put metadata in it.
articleInfo = synbody.appendChild(synop.createElement('div'))
articleInfo.setAttribute('class', 'articleInfo')
articleInfo.setAttribute('id', 'articleInfo')
#Citation text should be first, but I am unsure of PLoS's rules for it
#For now I will just place the DOI
citation = articleInfo.appendChild(synop.createElement('p'))
label = citation.appendChild(synop.createElement('b'))
label.appendChild(synop.createTextNode('Citation: '))
citation.appendChild(synop.createTextNode('doi:{0}'.format(self.doi)))
#Handle Editors
for editor in meta.article_meta.art_edits:
name = editor.get_name()
role = editor.role
affs = editor.affiliation
ped = articleInfo.appendChild(synop.createElement('p'))
label = ped.appendChild(synop.createElement('b'))
if role:
label.appendChild(synop.createTextNode('{0}: '.format(role)))
else:
label.appendChild(synop.createTextNode('Editor: '))
ped.appendChild(synop.createTextNode(u'{0}, '.format(name)))
first_aff = True
for aff in affs:
for item in meta.article_meta.art_affs:
if item.rid == aff:
address = item.address
if first_aff:
ped.appendChild(synop.createTextNode(u'{0}'.format(address)))
first_aff = False
else:
ped.appendChild(synop.createTextNode(u'; {0}'.format(address)))
#Create a node for the dates
datep = articleInfo.appendChild(synop.createElement('p'))
datep.setAttribute('id', 'dates')
hist = meta.article_meta.history
dates = meta.article_meta.art_dates
if hist:
datelist = [('Received', hist['received']),
('Accepted', hist['accepted']),
('Published', dates['epub'])]
else:
datelist = [('Published', dates['epub'])]
for _bold, _data in datelist:
bold = datep.appendChild(synop.createElement('b'))
bold.appendChild(synop.createTextNode('{0} '.format(_bold)))
datestring = _data.niceString()
datep.appendChild(synop.createTextNode('{0} '.format(datestring)))
#Create a node for the Copyright text:
copp = articleInfo.appendChild(synop.createElement('p'))
copp.setAttribute('id', 'copyright')
copybold = copp.appendChild(synop.createElement('b'))
copybold.appendChild(synop.createTextNode('Copyright: '))
copystr = u'{0} {1}'.format(u'\u00A9',
meta.article_meta.art_copyright_year)
copp.appendChild(synop.createTextNode(copystr))
copp.childNodes += meta.article_meta.art_copyright_statement.childNodes
#Create a node for the Funding text
if back and back.funding:
fundp = articleInfo.appendChild(synop.createElement('p'))
fundp.setAttribute('id', 'funding')
fundbold = fundp.appendChild(synop.createElement('b'))
fundbold.appendChild(synop.createTextNode('Funding: '))
fundp.appendChild(synop.createTextNode(back.funding))
#Create a node for the Competing Interests text
if back and back.competing_interests:
compip = articleInfo.appendChild(synop.createElement('p'))
compip.setAttribute('id', 'competing-interests')
compibold = compip.appendChild(synop.createElement('b'))
compibold.appendChild(synop.createTextNode('Competing Interests: '))
compip.appendChild(synop.createTextNode(back.competing_interests))
#Create a node for the Abbreviations if it exists, we will interpret
#the data in Back.glossary to generate this text
if back and back.glossary:
try:
title = back.glossary.getElementsByTagName('title')[0]
except IndexError:
pass
else:
if title.firstChild.data == 'Abbreviations':
ap = articleInfo.appendChild(synop.createElement('p'))
ap.setAttribute('id', 'abbreviations')
apb = ap.appendChild(synop.createElement('b'))
apb.appendChild(synop.createTextNode('Abbreviations: '))
first = True
for item in back.glossary.getElementsByTagName('def-item'):
if first:
first = False
else:
ap.appendChild(synop.createTextNode('; '))
term = item.getElementsByTagName('term')[0]
idef = item.getElementsByTagName('def')[0]
defp = idef.getElementsByTagName('p')[0]
for c in term.childNodes:
ap.appendChild(c.cloneNode(deep=True))
ap.appendChild(synop.createTextNode(','))
for c in defp.childNodes:
ap.appendChild(c.cloneNode(deep=True))
#Create a node for the correspondence text
corr_line = articleInfo.appendChild(synop.createElement('p'))
art_corresps = meta.article_meta.art_corresps
correspondence_nodes = meta.article_meta.correspondences
try:
corr_line.setAttribute('id', art_corresps[0].rid)
except IndexError:
pass
else:
for correspondence in correspondence_nodes:
corr_line.childNodes += correspondence.childNodes
#corr_line.appendChild(synop.createTextNode(corresp_text))
#Handle conversion of ext-link to <a>
ext_links = synop.getElementsByTagName('ext-link')
for ext_link in ext_links:
ext_link.tagName = u'a'
ext_link.removeAttribute('ext-link-type')
href = ext_link.getAttribute('xlink:href')
ext_link.removeAttribute('xlink:href')
ext_link.removeAttribute('xlink:type')
ext_link.setAttribute('href', href)
#Generate an articleInfo segment for the author notes current affs
anca = meta.article_meta.author_notes_current_affs
for id in sorted(anca.iterkeys()):
label, data = anca[id]
cap = articleInfo.appendChild(data)
cap.setAttribute('id', id)
cab = cap.insertBefore(synop.createElement('b'), cap.firstChild)
cab.appendChild(synop.createTextNode(label))
#If there are other footnotes in Author notes, eg. <fn fn-typ="other"
#Place them here.
ano = meta.article_meta.author_notes_other
for id in sorted(ano.iterkeys()):
cap = articleInfo.appendChild(ano[id])
cap.setAttribute('id', id)
#Create the Editor's abstract if it exists
try:
editor_abs = meta.article_meta.abstracts['editor']
except KeyError:
pass
else:
for child in editor_abs.childNodes:
try:
if child.tagName == u'title':
title = child
break
except AttributeError:
pass
synbody.appendChild(title)
title.tagName = u'h2'
synbody.appendChild(editor_abs)
editor_abs.tagName = 'div'
editor_abs.removeAttribute('abstract-type')
editor_abs.setAttribute('id','editor_abstract')
editor_abs.setAttribute('class', 'editorsAbstract')
for title in editor_abs.getElementsByTagName('title'):
title.tagName = 'h3'
for sec in editor_abs.getElementsByTagName('sec'):
sec.tagName = 'div'
#for para in editor_abs.getElementsByTagName('p'):
# para.tagName = 'big'
self.postNodeHandling(editor_abs, synop)
self.postNodeHandling(synbody, synop)
with open(self.outputs['Synopsis'],'wb') as out:
out.write(synop.toprettyxml(encoding = 'utf-8'))
def createMain(self):
'''Create an output file containing the main article body content'''
doc = self.doc
#Initiate the document, returns the document and its body element
main, mainbody = self.initiateDocument('Main file')
body = doc.getElementsByTagName('body')[0]
#Here we copy the entirety of the body element over to our main document
for item in body.childNodes:
mainbody.appendChild(item.cloneNode(deep=True))
#Process figures
self.figNodeHandler(mainbody, main) #Convert <fig> to <img>
#Process tables
tab_doc, tab_docbody = self.initiateDocument('HTML Versions of Tables')
self.tableWrapNodeHandler(mainbody, main, tab_docbody) #Convert <table-wrap>
self.postNodeHandling(tab_docbody, tab_doc)
#Process ref-list nodes
self.refListHandler(mainbody, main)
#Process boxed-text
self.boxedTextNodeHandler(mainbody)
#Process supplementary-materials
self.supplementaryMaterialNodeHandler(mainbody, main)
#Process Acknowledgments
self.acknowledgments(mainbody, main)
#Process Author Contributions
self.authorContributions(mainbody, main)
#General processing
self.postNodeHandling(mainbody, main, ignorelist=[])
#Conversion of existing <div><title/></div> to <div><h#/></div>
self.divTitleFormat(mainbody, depth = 0) #Convert <title> to <h#>...
#If any tables were in the article, make the tables.xml
if tab_docbody.getElementsByTagName('table'):
with open(self.outputs['Tables'],'wb') as output:
output.write(tab_doc.toprettyxml(encoding = 'utf-8'))
#Write the document
with open(self.outputs['Main'],'wb') as out:
out.write(main.toprettyxml(encoding = 'utf-8'))
def createBiblio(self, doc, back):
'''Create an output file containing the article bibliography'''
#Initiate the document, returns the document and its body element
biblio, bibbody = self.initiateDocument('Bibliography file')
back = doc.getElementsByTagName('back')[0]
try:
bibbody.appendChild(back.getElementsByTagName('ref-list')[0])
except IndexError:
pass
else:
self.refListHandler(bibbody, biblio)
bibbody.getElementsByTagName('div')[0].setAttribute('id', 'references')
self.postNodeHandling(bibbody, biblio, ignorelist=[])
with open(self.outputs['Biblio'],'wb') as out:
out.write(biblio.toprettyxml(encoding = 'utf-8'))
def synopsisAuthors(self, meta, topnode, doc):
'''Creates the text in synopsis for displaying the authors'''
authors = meta.article_meta.art_auths
auth_node = topnode.appendChild(doc.createElement('h3'))
first = True
for author in authors:
if not first:
auth_node.appendChild(doc.createTextNode(', '))
else:
first = False
name = author.get_name()
auth_node.appendChild(doc.createTextNode(name))
for xref in author.xrefs:
rid = xref.getAttribute('rid')
try:
s = utils.getTagText(xref.getElementsByTagName('sup')[0])
except IndexError:
s = u'!'
if not s:
s = u''
sup = auth_node.appendChild(doc.createElement('sup'))
a = sup.appendChild(doc.createElement('a'))
a.setAttribute('href', self.syn_frag.format(rid))
a.appendChild(doc.createTextNode(s))
def acknowledgments(self, topnode, doc):
'''Takes the optional acknowledgments element from the back data
and adds it to the document, it belongs right after Supporting
Information and before Author Contributions'''
try:
ack = self.backdata.ack
except AttributeError:
#An article that has no <back> element
pass
else:
if ack:
topnode.appendChild(ack)
ack.tagName = 'div'
ack.setAttribute('id', 'acknowledgments')
ack_title = doc.createElement('h2')
ack_title.appendChild(doc.createTextNode('Acknowledgments'))
ack.insertBefore(ack_title, ack.firstChild)
def authorContributions(self, topnode, doc):
'''Takes the optional Author Contributions element from metadata and
adds it to the document, it belongs between Acknowledgments and
References.'''
anc = self.metadata.article_meta.author_notes_contributions
if anc:
topnode.appendChild(anc)
anc.tagName = 'div'
anc.removeAttribute('fn-type')
anc.setAttribute('id', 'contributions')
anc_title = doc.createElement('h2')
anc_title.appendChild(doc.createTextNode('Author Contibutions'))
anc.insertBefore(anc_title, anc.firstChild)
def parseRef(self, fromnode, doc):
'''Interprets the references in the article back reference list into
comprehensible xml'''
#Create a paragraph tag to contain the reference text data
ref_par = doc.createElement('p')
#Set the fragment identifier for the paragraph tag
ref_par.setAttribute('id', fromnode.getAttribute('id'))
#Pull the label node into a node_list
label = fromnode.getElementsByTagName('label')[0]
try:
#Collect the citation tag and its citation type
citation = fromnode.getElementsByTagName('citation')[0]
except IndexError:
#The article may have used <nlm-citation>
citation = fromnode.getElementsByTagName('nlm-citation')[0]
citation_type = citation.getAttribute('citation-type')
#A list of known citation types used by PLoS
citation_types = ['book', 'confproc', 'gov', 'journal', 'other', 'web',
'']
if citation_type not in citation_types:
print('Unkown citation-type value: {0}'.format(citation_type))
#Collect possible tag texts, then decide later how to format
#article-title is treated specially because of its potential complexity
tags = ['source', 'year', 'publisher-loc', 'publisher-name', 'comment',
'page-count', 'fpage', 'lpage', 'month', 'volume',
'day', 'issue', 'edition', 'page-range', 'conf-name',
'conf-date', 'conf-loc', 'supplement']
try:
art_tit = citation.getElementsByTagName('article-title')[0]
except IndexError:
art_tit = None
cite_tags = {}
for each in tags:
try:
t = citation.getElementsByTagName(each)[0]
except IndexError:
t = None
if t:
cite_tags[each] = utils.getTagText(t)
else:
cite_tags[each] = ''
if citation_type == u'journal':
#The base strings with some punctuation; to be formatted with data
frs = u'{0}. {1} {2} ' # first reference string
srs = u' {0} {1}{2}{3} {4}' # second reference string
#A journal citation looks roughly like this
#Label. Authors (Year) Article Title. Source Volume: Supplement?
#Pages. Comment FIND ONLINE
lbl = utils.getTagText(label) # lbl
auth = u'' # auth
first = True
first_auth = None
for name in citation.getElementsByTagName('name'):
surname = name.getElementsByTagName('surname')[0]
try:
given = name.getElementsByTagName('given-names')[0]
except IndexError:
given = ''
if first:
first_auth = utils.getTagText(surname)
first = False
else:
auth += ', '
auth += utils.getTagText(surname)
if given:
auth += u' {0}'.format(utils.getTagText(given))
#If there is an <etal> tag, add it to the auth string
if citation.getElementsByTagName('etal'):
auth += ', et al.'
year = cite_tags['year'] # year
if year:
year = '({0})'.format(year)
#Format the first reference string with our data
frs = frs.format(lbl, auth, year)
#Append the first reference string to reference paragraph
ref_par.appendChild(doc.createTextNode(frs))
#Give all the article title children to reference paragraph
if art_tit:
ref_par.childNodes += art_tit.childNodes
#Begin collecting data for second reference string
src = cite_tags['source'] # src
if src:
src += ' '
vol = cite_tags['volume'] # vol
if cite_tags['issue']: # If issue has a value, we add it to vol
vol += u'({0})'.format(cite_tags['issue'])
if vol:
vol += ': '
if cite_tags['supplement']:
supp = cite_tags['supplement'] + ' ' # supp
else:
supp = '' # supp
fpage, lpage = cite_tags['fpage'],cite_tags['lpage']
if fpage and lpage:
pgs = u'{0}-{1}'.format(fpage, lpage) # pgs
else:
pgs = fpage + lpage # pgs
if pgs:
pgs += '.'
com = cite_tags['comment'] # com
srs = srs.format(src, vol, supp, pgs, com)
ref_par.appendChild(doc.createTextNode(srs))
if com == 'doi:': # PLoS put in a direct dx.doi link
ext_link = citation.getElementsByTagName('ext-link')[0]
ext_link_text = utils.getTagText(ext_link)
href = ext_link.getAttribute('xlink:href')
alink = doc.createElement('a')
alink.appendChild(doc.createTextNode(ext_link_text))
alink.setAttribute('href', href)
ref_par.appendChild(alink)
else:
alink = doc.createElement('a')
alink.appendChild(doc.createTextNode('Find This Article Online'))
j_title = self.metadata.journal_meta.title[0]
pj= {'PLoS Genetics': u'http://www.plosgenetics.org/{0}{1}{2}{3}',
'PLoS ONE': u'http://www.plosone.org/{0}{1}{2}{3}',
'PLoS Biology': u'http://www.plosbiology.org/{0}{1}{2}{3}',
'PLoS Computational Biology': u'http://www.ploscompbiol.org/{0}{1}{2}{3}',
'PLoS Pathogens': u'http://www.plospathogens.org/{0}{1}{2}{3}',
'PLoS Medicine': u'http://www.plosmedicine.org/{0}{1}{2}{3}',
'PLoS Neglected Tropical Diseases':
u'http://www.plosntds.org/{0}{1}{2}{3}'}
if art_tit:
art_tit_form = utils.serializeText(art_tit, stringlist=[]).replace(' ', '%20')
href = pj[j_title].format(u'article/findArticle.action?author=',
first_auth, u'&title=', art_tit_form)
alink.setAttribute('href', href)
ref_par.appendChild(alink)
elif citation_type == u'confproc':
#The base strings with some punctuation; to be formatted with data
frs = u'{0}. {1} ' # first reference string
srs = u' {0} {1}{2}{3}' # second reference string
#A confproc citation looks roughly like this
#Label. Editors Article Title. Conference Name; Conference Date;
#Conference Location. (Year) Comment.
lbl = utils.getTagText(label) # lbl
auth = u'' # auth
first = True
for name in citation.getElementsByTagName('name'):
surname = name.getElementsByTagName('surname')[0]
try:
given = name.getElementsByTagName('given-names')[0]
except IndexError:
given = ''
if first:
first = False
else:
auth += ', '
auth += utils.getTagText(surname)
if given:
auth += u' {0}'.format(utils.getTagText(given))
#If there is an <etal> tag, add it to the auth string
if citation.getElementsByTagName('etal'):
auth += ', et al.'
#Format the first reference string with our data
frs = frs.format(lbl, auth)
#Append the first reference string to reference paragraph
ref_par.appendChild(doc.createTextNode(frs))
#Give all the article title children to reference paragraph
if art_tit:
ref_par.childNodes += art_tit.childNodes
cname = cite_tags['conf-name'] # cname
if cname:
cname += '; '
cdate = cite_tags['conf-date'] # cdate
if cdate:
cdate += '; '
cloc = cite_tags['conf-loc'] # cloc
if cloc:
cloc += '; '
year = cite_tags['year'] # year
if year:
year = '({0}) '.format(year)
srs = srs.format(cname, cdate, cloc, year)
ref_par.appendChild(doc.createTextNode(srs))
try:
com = citation.getElementsByTagName('comment')[0]
except IndexError:
ref_par.appendChild(doc.createTextNode('.'))
else:
for ext_link in com.getElementsByTagName('ext-link'):
ext_link.removeAttribute('ext-link-type')
ext_link.removeAttribute('xlink:type')
href = ext_link.getAttribute('xlink:href')
ext_link.removeAttribute('xlink:href')
ext_link.tagName = 'a'
ext_link.setAttribute('href', href)
ref_par.childNodes += com.childNodes
elif citation_type == u'other':
ref_string = u'{0}. '.format(utils.getTagText(label))
ref_string += self.refOther(citation, stringlist = [])
ref_par.appendChild(doc.createTextNode(ref_string[:-2]))
return ref_par
def refOther(self, node, stringlist = []):
'''Attempts to broadly handle Other citation types and produce a
human-intelligible string output'''
for item in node.childNodes:
if item.nodeType == item.TEXT_NODE and not item.data == u'\n':
if item.data.lstrip():
if item.parentNode.tagName == u'year':
stringlist.append(u'({0})'.format(item.data))
stringlist.append(u', ')
elif item.parentNode.tagName == u'source':
stringlist.append(u'[{0}]'.format(item.data))
stringlist.append(u', ')
elif item.parentNode.tagName == u'article-title':
stringlist.append(u'\"{0}\"'.format(item.data))
stringlist.append(u', ')
else:
stringlist.append(item.data)
stringlist.append(u', ')
else:
self.refOther(item, stringlist)
return u''.join(stringlist)
def postNodeHandling(self, topnode, doc, ignorelist = []):
'''A wrapper function for all of the node handlers. Conceptually,
this function should be called after special cases have been handled
such as in figures, tables, and references. This function provides
simple access to the entire cohort of default nodeHandlers which may
be utilized after special cases have been handled. Passing a list of
string tagNames allows those tags to be ignored'''
handlers = {'bold': self.boldNodeHandler(topnode),
'italic': self.italicNodeHandler(topnode),
'monospace': self.monospaceNodeHandler(topnode),
'sub': self.subNodeHandler(topnode),
'sup': self.supNodeHandler(topnode),
'underline': self.underlineNodeHandler(topnode),
'xref': self.xrefNodeHandler(topnode),
'sec': self.secNodeHandler(topnode),
#'ref-list': self.refListHandler(topnode, doc),
'named-content': self.namedContentNodeHandler(topnode),
'inline-formula': self.inlineFormulaNodeHandler(topnode, doc),
'disp-formula': self.dispFormulaNodeHandler(topnode, doc),
'disp-quote': self.dispQuoteNodeHandler(topnode, doc),
'ext-link': self.extLinkNodeHandler(topnode),
'sc': self.smallCapsNodeHandler(topnode),
'list': self.listNodeHandler(topnode, doc),
'graphic': self.graphicNodeHandler(topnode),
'email': self.emailNodeHandler(topnode),
'fn': self.fnNodeHandler(topnode)}
for tagname in handlers:
if tagname not in ignorelist:
handlers[tagname]
def refListHandler(self, topnode, doc):
'''This method has two primary significant uses: it is used to generate
the bibliographical references section at the end of an article, and at
times when a Suggested Reading list is offered in the text. In the
latter case, it is typical to see fewer metadata items and the presence
of a <comment> tag to illustrate why it is recommended.
Because the tags used to represent metadata by and large cannot be
interpreted in ePub, current practice involves removing the original
ref-list node and replacing it with a rendered string andlinks to
locate the resource online.'''
try:
ref_lists = topnode.getElementsByTagName('ref-list')
except AttributeError:
for item in topnode:
self.figNodeHandler(item, doc)
else:
for rl in ref_lists:
#We can mutate the title node to <h2>
try:
title = rl.getElementsByTagName('title')[0]
except IndexError:
pass
else:
title.tagName = 'h2'
#Then we want to handle each ref in the ref-list
ref_ps = []
for ref in rl.getElementsByTagName('ref'):
ref_ps.append(self.parseRef(ref, doc))
rl.removeChild(ref)
#Now that we have our title text and a list of rendered
#paragraph tags from our ref tags, we mutate the original tag
rl.tagName = 'div'
rl.setAttribute('class', 'ref-list')
#Add all the ref paragraphs as children
for each in ref_ps:
rl.appendChild(each)
def figNodeHandler(self, topnode, doc):
'''Handles conversion of <fig> tags under the provided topnode. Also
handles Nodelists by calling itself on each Node in the NodeList.'''
try:
fig_nodes = topnode.getElementsByTagName('fig')
except AttributeError:
for item in topnode:
self.figNodeHandler(item, doc)
else:
for fig_node in fig_nodes:
#These are in order
fig_object_id = fig_node.getElementsByTagName('object-id') #zero or more
fig_label = fig_node.getElementsByTagName('label') #zero or one
fig_caption = fig_node.getElementsByTagName('caption') #zero or one
#Accessibility Elements ; Any combination of
fig_alt_text = fig_node.getElementsByTagName('alt-text')
fig_long_desc = fig_node.getElementsByTagName('long-desc')
#Address Linking Elements ; Any combination of
fig_email = fig_node.getElementsByTagName('email')
fig_ext_link = fig_node.getElementsByTagName('ext-link')
fig_uri = fig_node.getElementsByTagName('uri')
#Document location information
fig_parent = fig_node.parentNode
orig_parent = fig_node.parentNode
fig_sibling = fig_node.nextSibling
#There is a bizarre circumstance where some figures are placed
#In an invalid position for ePub xml
#Here is a fix for it
if fig_parent.tagName == 'body':
fig_div = doc.createElement('div')
fig_parent.insertBefore(fig_div, fig_node)
fig_div.appendChild(fig_node)
fig_parent = fig_div # this equates to fig_node.parentNode
#This should provide the fragment identifier
fig_id = fig_node.getAttribute('id')
if fig_alt_text: #Extract the alt-text if list non-empty
fig_alt_text_text = utils.getTagData(fig_alt_text)
else:
fig_alt_text_text = 'A figure'
if fig_long_desc:
fig_long_desc_text = utils.getTagData(fig_long_desc)
else:
fig_long_desc_text = None
#In this case, we will create an <img> node to replace <fig>
img_node = doc.createElement('img')
#The following code block uses the fragment identifier to
#locate the correct source file based on PLoS convention
name = fig_id.split('-')[-1]
startpath = os.getcwd()
os.chdir(self.outdir)
for path, _subdirs, filenames in os.walk('images-{0}'.format(self.jid)):
for filename in filenames:
if os.path.splitext(filename)[0] == name:
img_src = os.path.join(path, filename)
os.chdir(startpath)
#Now we can begin to process to output
try:
img_node.setAttribute('src', img_src)
except NameError:
logging.error('Image source not found')
img_node.setAttribute('src', 'not_found')
img_node.setAttribute('id', fig_id)
img_node.setAttribute('alt', fig_alt_text_text)
#The handling of longdesc is important to accessibility
#Due to the current workflow, we will be storing the text of
#longdesc in the optional title attribute of <img>
#A more optimal strategy would be to place it in its own text
#file, we need to change the generation of the OPF to do this
#See http://idpf.org/epub/20/spec/OPS_2.0.1_draft.htm#Section2.3.4
if fig_long_desc_text:
img_node.setAttribute('title', fig_long_desc_text)
#Replace the fig_node with img_node
fig_parent.replaceChild(img_node, fig_node)
#Handle the figure caption if it exists
if fig_caption:
fig_caption_node = fig_caption[0] #Should only be one if nonzero
#We want to handle the <title> in our caption/div as a special case
#For this reason, figNodeHandler should be called before divTitleFormat
for _title in fig_caption_node.getElementsByTagName('title'):
_title.tagName = u'b'
#Modify this <caption> in situ to <div class="caption">
fig_caption_node.tagName = u'div'
fig_caption_node.setAttribute('class', 'caption')
if fig_label: #Extract the label text if list non-empty
fig_label_text = utils.getTagData(fig_label)
#Format the text to bold and prepend to caption children
bold_label_text = doc.createElement('b')
bold_label_text.appendChild(doc.createTextNode(fig_label_text + '.'))
fig_caption_node.insertBefore(bold_label_text, fig_caption_node.firstChild)
#Place after the image node
orig_parent.insertBefore(fig_caption_node, fig_sibling)
#Handle email
for email in fig_email:
email.tagName = 'a'
text = each.getTagData
email.setAttribute('href','mailto:{0}'.format(text))
if fig_sibling:
fig_parent.insertBefore(email, fig_sibling)
else:
fig_parent.appendChild(email)
#ext-links are currently ignored
#uris are currently ignored
#Fig may contain many more elements which are currently ignored
#See http://dtd.nlm.nih.gov/publishing/tag-library/2.0/n-un80.html
#For more details on what could be potentially handled
def inlineFormulaNodeHandler(self, topnode, doc):
'''Handles <inline-formula> nodes for ePub formatting. At the moment,
there is no way to support MathML (without manual curation) which
would be more optimal for accessibility. If PLoS eventually publishes
the MathML (or SVG) then that option should be handled. For now, the
rasterized images will be placed in-line. This accepts either Nodes or
NodeLists and handles all instances of <inline-formula> beneath them'''
try:
inline_formulas = topnode.getElementsByTagName('inline-formula')
except AttributeError:
for item in topnode:
self.inlineFormulaNodeHandler(topnode, doc)
else:
#There is a potential for complexity of content within the
#<inline-formula> tag. I have supplied methods for collecting the
#complex matter, but do not yet implement its inclusion
for if_node in inline_formulas:
parent = if_node.parentNode
sibling = if_node.nextSibling
#Potential Attributes
if_alt_form_of = if_node.getAttribute('alternate-form-of')
try:
if_node.removeAttribute('alternate-form-of')
except xml.dom.NotFoundErr:
pass
if_id = if_node.getAttribute('id')
#Handle the conversion of emphasis elements
#if_node = utils.getFormattedNode(if_node)
#Potential contents
if_private_char = if_node.getElementsByTagName('private-char')
if_tex_math = if_node.getElementsByTagName('tex-math')
if_mml_math = if_node.getElementsByTagName('mml:math')
if_inline_formula = if_node.getElementsByTagName('inline-formula')
if_sub = if_node.getElementsByTagName('sub')
if_sup = if_node.getElementsByTagName('sup')
#Collect the inline-graphic element, which we will try to use
#in order to create an image node
if_inline_graphic = if_node.getElementsByTagName('inline-graphic')
img = None
if if_inline_graphic:
ig_node = if_inline_graphic[0]
xlink_href_id = ig_node.getAttribute('xlink:href')
name = xlink_href_id.split('.')[-1]
img = None
startpath = os.getcwd()
os.chdir(self.outdir)
for path, _subdirs, filenames in os.walk('images-{0}'.format(self.jid)):
for filename in filenames:
if os.path.splitext(filename)[0] == name:
img = os.path.join(path, filename)
os.chdir(startpath)
if img:
imgnode = doc.createElement('img')
imgnode.setAttribute('src', img)
imgnode.setAttribute('alt', 'An inline formula')
parent.insertBefore(imgnode, sibling)
parent.removeChild(if_node)
def dispFormulaNodeHandler(self, topnode, doc):
'''Handles disp-formula nodes'''
try:
disp_formulas = topnode.getElementsByTagName('disp-formula')
except AttributeError:
for item in topnode:
self.dispFormulaNodeHandler(item, doc)
else:
for disp in disp_formulas:
attrs = {'id': None, 'alternate-form-of': None}
for attr in attrs:
attrs[attr] = disp.getAttribute(attr)
try:
graphic = disp.getElementsByTagName('graphic')[0]
except IndexError:
logging.error('disp-formula element does not contain graphic element')
else:
graphic_xlink_href = graphic.getAttribute('xlink:href')
if not graphic_xlink_href:
logging.error('graphic xlink:href attribute not present for disp-formula')
else:
name = graphic_xlink_href.split('.')[-1]
img = None
startpath = os.getcwd()
os.chdir(self.outdir)
for path, _subdirs, filenames in os.walk('images-{0}'.format(self.jid)):
for filename in filenames:
if os.path.splitext(filename)[0] == name:
img = os.path.join(path, filename)
os.chdir(startpath)
#Convert <label> to <b class="disp-form-label">
#Also move it up a level, after the formula
for item in disp.getElementsByTagName('label'):
disp.parentNode.insertBefore(item, disp.nextSibling)
item.tagName = 'b'
item.setAttribute('class', 'disp-formula-label')
img_node = doc.createElement('img')
img_node.setAttribute('src', img)
img_node.setAttribute('alt', 'A display formula')
img_node.setAttribute('class', 'disp-formula')
parent = disp.parentNode
parent.insertBefore(img_node, disp)
parent.removeChild(disp)
def tableWrapNodeHandler(self, topnode, doc, tabdoc):
'''Handles conversion of <table-wrap> tags under the provided topnode.
Also handles NodeLists by calling itself on each Node in the NodeList.
Must be compliant with the Journal Publishing Tag Set 2.0 and produce
OPS 2.0.1 compliant output. HTML versions of tables will be exported to
tables.xml and must be fully HTML compliant'''
try:
table_wraps = topnode.getElementsByTagName('table-wrap')
except AttributeError:
for item in topnode:
self.tableWrapNodeHandler(item, doc)
else:
for tab_wrap in table_wraps:
#These are in order
tab_object_id = tab_wrap.getElementsByTagName('object-id') #zero or more
tab_label = tab_wrap.getElementsByTagName('label') #zero or one
tab_caption = tab_wrap.getElementsByTagName('caption') #zero or one
#Accessibility Elements ; Any combination of
tab_alt_text = tab_wrap.getElementsByTagName('alt-text')
tab_long_desc = tab_wrap.getElementsByTagName('long-desc')
#Address Linking Elements ; Any combination of
tab_email = tab_wrap.getElementsByTagName('email')
tab_ext_link = tab_wrap.getElementsByTagName('ext-link')
tab_uri = tab_wrap.getElementsByTagName('uri')
#Document location information
tab_parent = tab_wrap.parentNode
tab_sibling = tab_wrap.nextSibling
#This should provide the fragment identifier
tab_id = tab_wrap.getAttribute('id')
if tab_alt_text: #Extract the alt-text if list non-empty
tab_alt_text_text = utils.getTagData(tab_alt_text)
else:
tab_alt_text_text = 'A figure'
if tab_long_desc:
tab_long_desc_text = utils.getTagData(tab_long_desc)
else:
tab_long_desc_text = None
#In this case, we will create an <img> node to replace <table-wrap>
img_node = doc.createElement('img')
#The following code block uses the fragment identifier to
#locate the correct source file based on PLoS convention
name = tab_id.split('-')[-1]
startpath = os.getcwd()
os.chdir(self.outdir)
for path, _subdirs, filenames in os.walk('images-{0}'.format(self.jid)):
for filename in filenames:
if os.path.splitext(filename)[0] == name:
img_src = os.path.join(path, filename)
os.chdir(startpath)
#Now we can begin to process to output
try:
img_node.setAttribute('src', img_src)
except NameError:
print('Image source not found')
img_node.setAttribute('src', 'not_found')
img_node.setAttribute('alt', tab_alt_text_text)
#The handling of longdesc is important to accessibility
#Due to the current workflow, we will be storing the text of
#longdesc in the optional title attribute of <img>
#A more optimal strategy would be to place it in its own text
#file, we need to change the generation of the OPF to do this
#See http://idpf.org/epub/20/spec/OPS_2.0.1_draft.htm#Section2.3.4
if tab_long_desc_text:
img_node.setAttribute('title', tab_long_desc_text)
#Replace the tab_wrap_node with img_node
tab_parent.replaceChild(img_node, tab_wrap)
#Handle the table caption if it exists
tab_caption_title_node = None