-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuild_Website.py
6526 lines (6045 loc) · 315 KB
/
Build_Website.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
"""
Taxonomy Monograph Builder
"""
# built-in dependencies
import datetime
import random
import os
import shutil
import re
import math
import collections
from typing import Optional, Tuple, TextIO
import numpy
# local dependencies
import TMB_Import
import TMB_Create_Maps
from TMB_Error import report_error
import TMB_Error
from TMB_Common import *
import TMB_Initialize
import TMB_Classes
import TMB_Create_Graphs
import TMB_TaxKeyGen
import TMB_Measurements
from TMB_SpeciesXRef import init_species_crossref, find_species_by_name
import phy2html
WEBOUT_PATH = "webout/"
MEDIA_PATH = "media/"
TMP_PATH = "temp/"
TMP_MAP_PATH = TMP_PATH + "maps/"
FOSSIL_IMAGE = " <span class=\"fossil-img\">☠</span>"
STAR = "<sup>*</sup>"
DAGGER = "<sup>†</sup>"
DOUBLEDAGGER = "<sup>‡</sup>"
CitationStyle = int
AUTHOR_NOPAREN = 0 # Smith 1970
AUTHOR_PAREN = 1 # Smith (1970)
AUTHOR_TAXON = 2 # Smith, 1970 <-- this one is needed for taxonomic name authority
# this flag is to hide/display new materials still in progress from the general release
SHOW_NEW = True
# this flag can be used to suppress redrawing all of the maps, which is fairly time-consuming
DRAW_MAPS = True
# this flag suppresses creation of output files, allowing data integrity checking without the output time cost
CHECK_DATA = False
# this flag creates the location web pages only; it is for checking changes and not general use
CHECK_LOCATIONS = False
# this flag controls whether additional location data should be fetched from iNaturalist
INCLUDE_INAT = True
# Suppress some of the more time-consuming output; only meant for when testing others elements
OUTPUT_REFS = True
OUTPUT_LOCS = True
# these flags control creating print and web output, respectively
OUTPUT_PRINT = False
OUTPUT_WEB = True
# randSeed = random.randint(0, 10000)
def init_data() -> TMB_Initialize.InitializationData:
return TMB_Initialize.INIT_DATA
def remove_html(x: str) -> str:
"""
remove any stray html tags from string before using as title of html document
"""
regex = r"<.+?>"
return re.sub(regex, "", x)
def common_header_part1(outfile: TextIO, title: str, indexpath: str = "") -> None:
"""
part 1 of the common header for all webout html files
"""
outfile.write("<!DOCTYPE HTML>\n")
outfile.write("<html lang=\"en\">\n")
outfile.write(" <head>\n")
outfile.write(" <!-- Google tag (gtag.js) -->\n")
outfile.write(" <script async src=\"https://www.googletagmanager.com/gtag/js?id=G-94FNMMTWTQ\"></script>\n")
outfile.write(" <script>\n")
outfile.write(" window.dataLayer = window.dataLayer || [];\n")
outfile.write(" function gtag(){dataLayer.push(arguments);}\n")
outfile.write(" gtag('js', new Date());\n")
outfile.write(" gtag('config', 'G-94FNMMTWTQ');\n")
outfile.write(" </script>\n")
outfile.write(" <meta charset=\"utf-8\" />\n")
outfile.write(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n")
outfile.write(" <title>" + remove_html(title) + "</title>\n")
outfile.write(" <meta name=\"description\" content=\"Fiddler Crabs\" />\n")
outfile.write(" <link rel=\"icon\" sizes=\"128x128\" href=\"" + indexpath +
"favicon128.png\" type=\"image/png\" />\n")
outfile.write(" <link rel=\"icon\" sizes=\"96x96\" href=\"" + indexpath +
"favicon96.png\" type=\"image/png\" />\n")
outfile.write(" <link rel=\"icon\" sizes=\"72x72\" href=\"" + indexpath +
"favicon72.png\" type=\"image/png\" />\n")
outfile.write(" <link rel=\"icon\" sizes=\"48x48\" href=\"" + indexpath +
"favicon48.png\" type=\"image/png\" />\n")
outfile.write(" <link rel=\"icon\" sizes=\"32x32\" href=\"" + indexpath +
"favicon32.png\" type=\"image/png\" />\n")
outfile.write(" <link rel=\"icon\" sizes=\"24x24\" href=\"" + indexpath +
"favicon24.png\" type=\"image/png\" />\n")
outfile.write(" <link rel=\"icon\" sizes=\"16x16\" href=\"" + indexpath +
"favicon16.png\" type=\"image/png\" />\n")
outfile.write(" <link rel=\"apple-touch-icon-precomposed\" href=\"" + indexpath +
"apple-touch-icon-precomposed.png\">\n")
outfile.write(" <link rel=\"apple-touch-icon-precomposed\" sizes=\"72x72\" "
"href=\"" + indexpath + "apple-touch-icon-72x72-precomposed.png\">\n")
outfile.write(" <link rel=\"apple-touch-icon-precomposed\" sizes=\"114x114\" "
"href=\"" + indexpath + "apple-touch-icon-114x114-precomposed.png\">\n")
outfile.write(" <link rel=\"apple-touch-icon-precomposed\" sizes=\"144x144\" "
"href=\"" + indexpath + "apple-touch-icon-144x144-precomposed.png\">\n")
outfile.write(" <link rel=\"stylesheet\" href=\"" + indexpath + "uca_style.css\" />\n")
outfile.write(" <script defer src=\"" + indexpath + "js/solid.min.js\"></script>\n")
outfile.write(" <script defer src=\"" + indexpath + "js/regular.min.js\"></script>\n")
outfile.write(" <script defer src=\"" + indexpath + "js/brands.min.js\"></script>\n")
outfile.write(" <script defer src=\"" + indexpath + "js/fontawesome.min.js\"></script>\n")
outfile.write(" <link rel=\"stylesheet\" href=\"" + indexpath +
"images/flag-icon-css/css/flag-icons.min.css\" />\n")
outfile.write(" <link rel=\"author\" href=\"" + init_data().site_author_email + "\" />\n")
def common_header_part2(outfile: TextIO, indexpath: str = "", include_map: bool = False) -> None:
"""
part 2 of the common header for all webout html files
"""
outfile.write(" </head>\n")
outfile.write("\n")
if include_map:
outfile.write(" <body onload=\"initialize()\">\n")
else:
outfile.write(" <body>\n")
outfile.write(" <div id=\"skip-links\" role=\"complementary\" aria-label=\"Skip links menu\">")
outfile.write("<a href=\"#Main\" tabindex=\"1\">Skip to content</a></div>\n")
outfile.write(" <div id=\"home\">\n")
outfile.write(" <a href=\"" + indexpath + "index.html\" class=\"home-title\">Fiddler Crabs</a>\n")
outfile.write(" <a href=\"" + indexpath +
"index.html\" class=\"home-link\">" + fetch_fa_glyph("home") + "Home</a>\n")
# outfile.write(" <a href=\"" + indexpath +
# "blog\" class=\"home-link\">" + fetch_fa_glyph("blog") + "Blog</a>\n")
outfile.write(" </div>\n")
def start_google_map_header(outfile: TextIO) -> None:
"""
start of common header entries for webout html files which contain Google maps elements
"""
outfile.write(" <script type=\"text/javascript\"\n")
outfile.write(" src=\"https://maps.googleapis.com/maps/api/js?"
"key=AIzaSyAaITaFdh_own-ULkURNKtyeh2ZR_cpR74&sensor=false\">\n")
outfile.write(" </script>\n")
outfile.write(" <script type=\"text/javascript\">\n")
outfile.write(" function initialize() {\n")
outfile.write(" var mapOptions = {\n")
outfile.write(" center: new google.maps.LatLng(0,0),\n")
outfile.write(" zoom: 1,\n")
outfile.write(" disableDefaultUI: true,\n")
outfile.write(" panControl: false,\n")
outfile.write(" zoomControl: true,\n")
outfile.write(" mapTypeControl: true,\n")
outfile.write(" scaleControl: false,\n")
outfile.write(" streetViewControl: false,\n")
outfile.write(" overviewMapControl: false,\n")
outfile.write(" mapTypeId: google.maps.MapTypeId.TERRAIN\n")
outfile.write(" };\n")
def end_google_map_header(outfile: TextIO) -> None:
"""
end of common header entries for webout html files which contain Google maps elements
"""
outfile.write(" }\n")
outfile.write(" </script>\n")
def write_google_map_range_header(outfile: TextIO, map_name: str) -> None:
"""
common header entries for webout html files which contain Google maps elements - range map version
"""
outfile.write(" var range_map = new google.maps.Map(document.getElementById(\"range_map_canvas\"),"
"mapOptions);\n")
outfile.write(" var range_layer = new google.maps.KmlLayer(\"" + init_data().site_url() + "/maps/" +
rangemap_name(map_name) + ".kmz\",{suppressInfoWindows: true});\n")
outfile.write(" range_layer.setMap(range_map);\n")
# def write_google_map_point_header(outfile: TextIO, map_name: str,
# location: Optional[TMB_Classes.LocationClass]) -> None:
# """
# common header entries for webout html files which contain Google maps elements - point map version
# """
# do_bounds = False
# preserve = ""
# if location is not None:
# if location.sw_lon is not None:
# do_bounds = True
# preserve = ", preserveViewport: true"
#
# outfile.write(" var point_map = new google.maps.Map(document.getElementById(\"point_map_canvas\"),"
# "mapOptions);\n")
# outfile.write(" var point_layer = "
# "new google.maps.KmlLayer(\"" + init_data().site_url() + "/maps/" + pointmap_name(map_name) +
# ".kmz\",{suppressInfoWindows: false" + preserve + "});\n")
# outfile.write(" point_layer.setMap(point_map);\n")
# if do_bounds:
# outfile.write(" var necorner = new google.maps.LatLng(" +
# str(location.ne_lat) + ", " + str(location.ne_lon) + ");\n")
# outfile.write(" var swcorner = new google.maps.LatLng(" +
# str(location.sw_lat) + ", " + str(location.sw_lon) + ");\n")
# outfile.write(" var bounds = new google.maps.LatLngBounds(swcorner, necorner);\n")
# outfile.write(" point_map.fitBounds(bounds);\n")
def write_google_map_point_header(outfile: TextIO, map_name: str) -> None:
"""
common header entries for webout html files which contain Google maps elements - point map version
"""
outfile.write(" var point_map = new google.maps.Map(document.getElementById(\"point_map_canvas\"),"
"mapOptions);\n")
outfile.write(" var point_layer = "
"new google.maps.KmlLayer(\"" + init_data().site_url() + "/maps/" + pointmap_name(map_name) +
".kmz\",{suppressInfoWindows: false});\n")
outfile.write(" point_layer.setMap(point_map);\n")
def start_google_chart_header(outfile: TextIO) -> None:
"""
start of common header entries for webout html files which contain Google chart elements
"""
outfile.write(" <script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>\n")
outfile.write(" <script type=\"text/javascript\">\n")
outfile.write(" google.load(\"visualization\", \"1\", {packages:[\"corechart\"]});\n")
outfile.write(" google.setOnLoadCallback(drawChart);\n")
outfile.write(" function drawChart() {\n")
def end_google_chart_header(outfile: TextIO) -> None:
"""
end of common header entries for webout html files which contain Google maps elements - range map version
"""
outfile.write(" }\n")
outfile.write(" </script>\n")
def common_html_header(outfile: TextIO, title: str, indexpath: str = "") -> None:
"""
write common header for webout html files without special scripts
"""
common_header_part1(outfile, title, indexpath=indexpath)
common_header_part2(outfile, indexpath=indexpath)
def common_html_footer(outfile: TextIO, indexpath: str = "") -> None:
"""
common footer and closing elements for all webout html files
"""
outfile.write("\n")
outfile.write(" <footer>\n")
outfile.write(" <figure id=\"footmap\"><script type=\"text/javascript\" "
"src=\"//rf.revolvermaps.com/0/0/4.js?i=5f9t1sywiez&m=0&h=75&c=ff0000&r=30\" "
"async=\"async\"></script><figcaption>Visitors</figcaption></figure>\n")
outfile.write(" <p id=\"citation\"><a href=\"" + indexpath + init_data().cite_url +
"\">" + fetch_fa_glyph("site cite") + "How to cite this site</a></p>\n")
outfile.write(" <p id=\"contact\">Questions or comments about the site? Contact "
"<a href=\"mailto:" + init_data().site_author_email + "\">" + fetch_fa_glyph("mail") +
"Dr. Michael S. Rosenberg</a></p>\n")
outfile.write(" <p id=\"copyright\">Release: " + init_data().version +
" — Copyright © 2003–" + str(init_data().current_year) +
" All Rights Reserved</p>\n")
outfile.write(" </footer>\n")
outfile.write(" </body>\n")
outfile.write("</html>\n")
def start_page_division(outfile: TextIO, page_class: str) -> None:
"""
write start page information for print output
"""
outfile.write(" <div class=\"" + page_class + "\">\n")
def end_page_division(outfile: TextIO) -> None:
"""
write end page information for print output
"""
outfile.write(" </div>\n")
def create_blank_index(fname: str) -> None:
"""
create a blank index.html file for webout directories to prevent browsers from listing containing files
"""
with open(fname, "w") as outfile:
outfile.write("<!DOCTYPE HTML>\n")
outfile.write("<html lang=\"en\">\n")
outfile.write(" <head>\n")
outfile.write(" <meta charset=\"utf-8\" />\n")
outfile.write(" <title>n/a</title>\n")
outfile.write(" <meta name=\"description\" content=\"n/a\" />\n")
outfile.write(" </head>\n")
outfile.write(" <body>\n")
outfile.write(" </body>\n")
outfile.write("</html>\n")
def fetch_fa_glyph(glyph: Optional[str]) -> str:
"""
decorate text with a fontawesome glyph
centralized function to create fontawesome decoration based on specified glyph keyword/style
"""
if glyph is None:
return ""
else:
x = "<span role=\"presentation\" class=\"fa"
if glyph == "home":
x += " fa-home\" aria-hidden"
elif glyph == "blog":
x += " fa-pencil-alt\" aria-hidden"
elif glyph == "mail":
x += " fa-envelope\" aria-hidden"
elif glyph == "site cite":
x += " fa-pencil-alt\" aria-hidden"
elif glyph == "index":
x += " fa-list\" aria-hidden"
elif glyph == "summary charts":
x += " fa-chart-line\" aria-hidden"
elif glyph == "location":
x += " fa-map-marker-alt\" aria-hidden"
elif glyph == "citation":
x += " fa-edit\" aria-hidden"
elif glyph == "specimen":
x += " fa-flask\" aria-hidden"
elif glyph == "sequence":
x += " fa-dna\" aria-hidden"
elif glyph == "original":
x += " fa-arrow-alt-left\" aria-hidden"
elif glyph == "computed":
x += " fa-cogs\" aria-hidden"
elif glyph == "geography":
x += "r fa-map\" aria-hidden"
elif glyph == "synonymy":
x += " fa-exchange\" aria-hidden"
elif glyph == "specific name":
x += " fa-window-minimize\" aria-hidden"
elif glyph == "info":
x += " fa-info-circle\" aria-hidden"
elif glyph == "accepted species":
x += " fa-check-circle\" aria-hidden"
elif glyph == "download":
x += " fa-download\" aria-hidden"
elif glyph == "file download":
x += " fa-file-download\" aria-hidden"
elif glyph == "maps":
x += "r fa-map\" aria-hidden"
elif glyph == "photo":
x += " fa-camera-alt\" aria-hidden"
elif glyph == "video":
x += " fa-video\" aria-hidden"
elif glyph == "references":
x += " fa-book\" aria-hidden"
elif glyph == "art":
x += " fa-paint-brush\" aria-hidden"
elif glyph == "measure":
x += "r fa-ruler\" aria-hidden"
elif glyph == "handedness":
x += " fa-hands\" aria-hidden"
elif glyph == "list pdf":
x += "-li far fa-file-pdf\" aria-hidden"
elif glyph == "list github":
x += "-li fab fa-github\" aria-hidden"
elif glyph == "list systematics":
x += "-li fa fa-signal fa-rotate-270\" aria-hidden"
elif glyph == "list phylogeny":
x += "-li fa fa-share-alt fa-rotate-270\" aria-hidden"
elif glyph == "list species":
x += "-li fa fa-list\" aria-hidden"
elif glyph == "list common":
x += "-li far fa-comments\" aria-hidden"
elif glyph == "list ranges":
x += "-li far fa-map\" aria-hidden"
elif glyph == "list morphology":
x += "-li far fa-heart\" aria-hidden"
elif glyph == "list references":
x += "-li fa fa-book\" aria-hidden"
elif glyph == "list lifecycle":
x += "-li fa fa-sync\" aria-hidden"
elif glyph == "list photo":
x += "-li fa fa-camera-alt\" aria-hidden"
elif glyph == "list video":
x += "-li fa fa-video\" aria-hidden"
elif glyph == "list art":
x += "-li fa fa-paint-brush\" aria-hidden"
elif glyph == "list site cite":
x += "-li fa fa-pencil-alt\" aria-hidden"
elif glyph == "list unusual dev":
x += "-li fa fa-transgender-alt\" aria-hidden"
elif glyph == "bad location":
x += " fa-exclamation-triangle\" style=\"color: red\" title=\"Problematic Location: Outside range of " \
"all fiddler crabs or this particular species.\""
elif glyph == "questionable id":
x += " fa-question-circle\" style=\"color: goldenrod\" title=\"Questionable ID: Species identity " \
"uncertain.\""
elif glyph == "tax key":
x += " fa-key\" ara-hidden"
elif glyph == "location marker":
x += "r fa-map-marked-alt\" ara-hidden"
else:
report_error("missing glyph: " + glyph)
return ""
return x + "></span> "
def rel_link_prefix(do_print: bool, prefix: str = "") -> str:
if do_print:
return "#"
else:
return prefix
def abs_link_prefix(do_absolute: bool) -> str:
if do_absolute:
return init_data().site_url() + "/"
else:
return ""
def format_reference_full(ref: TMB_Classes.ReferenceClass, do_print: bool) -> str:
if ref.cite_key == "<pending>":
return ref.formatted_html
else:
try:
return ("<a href=\"" + rel_link_prefix(do_print, "references/") + ref.cite_key + ".html\">" +
ref.formatted_html + "</a>")
except LookupError:
report_error("missing label: " + ref.cite_key)
return ref.cite_key
def format_reference_cite(ref: TMB_Classes.ReferenceClass, do_print: bool, author_style: CitationStyle,
path: str = "") -> str:
if author_style == AUTHOR_PAREN: # Smith (1900)
outstr = ref.citation
elif author_style == AUTHOR_NOPAREN: # Smith 1900
outstr = ref.author() + " " + str(ref.year())
elif author_style == AUTHOR_TAXON: # Smith, 1900
if ref.taxon_author is not None: # used to avoid et al. or for papers with slightly unusual authority
outstr = ref.taxon_author
else:
outstr = ref.author() + ", " + str(ref.year())
else:
outstr = ref.citation
if ref.cite_key == "<pending>":
return outstr
else:
try:
return ("<a href=\"" + rel_link_prefix(do_print, path + "references/") + ref.cite_key +
".html\">" + outstr + "</a>")
except LookupError:
report_error("missing label: " + ref.cite_key)
return ref.cite_key
def replace_species_in_string(instr: str, include_link: bool = False, do_print: bool = False, path: str = "") -> str:
search_str = r"{{(?P<species>.+?)}}"
# for every species tagged in the string
for match in re.finditer(search_str, instr):
# look up full species name
name = match.group("species")
if name.startswith("+"):
include_authority = True
name = name[1:]
else:
include_authority = False
s = find_species_by_name(name)
if include_link:
name_str = create_species_link(s.genus, s.species, do_print, s.status, path=path)
else:
name_str = "<em class=\"species\">" + s.binomial() + "</em>"
if include_authority:
a = " " + s.authority()
else:
a = ""
instr = re.sub(search_str, name_str + a, instr, 1)
return instr
def replace_species_references(in_list: list) -> list:
out_list = []
for line in in_list:
out_list.append(replace_species_in_string(line))
return out_list
def replace_reference_in_string(instr: str, refdict: dict, do_print: bool, path: str = "") -> str:
search_str = r"\[\[(?P<key>.+?),(?P<format>.+?)\]\]"
# for every citation reference in the string
for match in re.finditer(search_str, instr):
# create the new link text
ref = refdict[match.group("key")]
if match.group("format") == ".out":
link_str = format_reference_cite(ref, do_print, AUTHOR_PAREN, path=path)
elif match.group("format") == ".in":
link_str = format_reference_cite(ref, do_print, AUTHOR_NOPAREN, path=path)
else:
link_str = "<a href=\"" + rel_link_prefix(do_print, path + "references/") + ref.cite_key + ".html\">" + \
match.group("format") + "</a>"
# replace the cross-reference with the correct text
instr = re.sub(search_str, link_str, instr, 1)
return instr
def replace_references(in_list: list, refdict: dict, do_print: bool, path: str = "") -> list:
out_list = []
for line in in_list:
out_list.append(replace_reference_in_string(line, refdict, do_print, path))
return out_list
def connect_type_references(species: list, refdict: dict) -> None:
"""
function to replace species type reference keys with point to reference object
"""
for s in species:
s.type_reference = refdict[s.type_reference]
def clean_reference_html(ref: str) -> str:
"""
add slightly better formatting to html formatted references
in particular, replace hyphens with n-dashes for commonly seen ranges
"""
# replace hyphens with an n-dash in page ranges
sstr = r"((?:Pp\. |:)[\D]?[\d]+)(-)([\D]?[\d]+)"
ref = re.sub(sstr, r"\1–\3", ref)
# replace hyphens with an n-dash in volume ranges
sstr = r"(\([\d]+)(-)([\d]+\))"
ref = re.sub(sstr, r"\1–\3", ref)
# remove (?) from entries with unknown years
ref = ref.replace(" (?) ", " ")
return ref
def clean_references(references: list) -> None:
for ref in references:
ref.formatted_html = clean_reference_html(ref.formatted_html)
def format_language(x: str) -> str:
"""
beautify language listings for references by adding flag icons for each language and replacing the word
'and' with an ampersand
"""
# language_replace_list = [
# [" and ", " & "],
# ["German", "<span class=\"flag-icon flag-icon-de\"></span> German"],
# ["Spanish", "<span class=\"flag-icon flag-icon-es\"></span> Spanish"],
# ["Russian", "<span class=\"flag-icon flag-icon-ru\"></span> Russian"],
# ["French", "<span class=\"flag-icon flag-icon-fr\"></span> French"],
# ["Portuguese", "<span class=\"flag-icon flag-icon-pt\"></span> Portuguese"],
# ["Danish", "<span class=\"flag-icon flag-icon-dk\"></span> Danish"],
# ["Dutch", "<span class=\"flag-icon flag-icon-nl\"></span> Dutch"],
# ["Japanese", "<span class=\"flag-icon flag-icon-jp\"></span> Japanese"],
# ["Chinese", "<span class=\"flag-icon flag-icon-cn\"></span> Chinese"],
# ["English", "<span class=\"flag-icon flag-icon-us\"></span> English"],
# ["Thai", "<span class=\"flag-icon flag-icon-th\"></span> Thai"],
# ["Latin", "<span class=\"flag-icon flag-icon-va\"></span> Latin"],
# ["Italian", "<span class=\"flag-icon flag-icon-it\"></span> Italian"],
# ["Vietnamese", "<span class=\"flag-icon flag-icon-vn\"></span> Vietnamese"],
# ["Korean", "<span class=\"flag-icon flag-icon-kr\"></span> Korean"],
# ["Polish", "<span class=\"flag-icon flag-icon-pl\"></span> Polish"],
# ["Arabic", "<span class=\"flag-icon flag-icon-sa\"></span> Arabic"],
# ["Indonesian", "<span class=\"flag-icon flag-icon-id\"></span> Indonesian"],
# ["Afrikaans", "<span class=\"flag-icon flag-icon-za\"></span> Afrikaans"],
# ["Malay", "<span class=\"flag-icon flag-icon-my\"></span> Malay"],
# ["Malagasy", "<span class=\"flag-icon flag-icon-mg\"></span> Malagasy"],
# ["Persian", "<span class=\"flag-icon flag-icon-ir\"></span> Persian"],
# ["Burmese", "<span class=\"flag-icon flag-icon-mm\"></span> Burmese"]
# ]
language_replace_list = [
[" and ", " & "],
["German", "<span class=\"fi fi-de\"></span> German"],
["Spanish", "<span class=\"fi fi-es\"></span> Spanish"],
["Russian", "<span class=\"fi fi-ru\"></span> Russian"],
["French", "<span class=\"fi fi-fr\"></span> French"],
["Portuguese", "<span class=\"fi fi-pt\"></span> Portuguese"],
["Danish", "<span class=\"fi fi-dk\"></span> Danish"],
["Dutch", "<span class=\"fi fi-nl\"></span> Dutch"],
["Japanese", "<span class=\"fi fi-jp\"></span> Japanese"],
["Chinese", "<span class=\"fi fi-cn\"></span> Chinese"],
["English", "<span class=\"fi fi-us\"></span> English"],
["Thai", "<span class=\"fi fi-th\"></span> Thai"],
["Latin", "<span class=\"fi fi-va\"></span> Latin"],
["Italian", "<span class=\"fi fi-it\"></span> Italian"],
["Vietnamese", "<span class=\"fi fi-vn\"></span> Vietnamese"],
["Korean", "<span class=\"fi fi-kr\"></span> Korean"],
["Polish", "<span class=\"fi fi-pl\"></span> Polish"],
["Arabic", "<span class=\"fi fi-sa\"></span> Arabic"],
["Indonesian", "<span class=\"fi fi-id\"></span> Indonesian"],
["Afrikaans", "<span class=\"fi fi-za\"></span> Afrikaans"],
["Malay", "<span class=\"fi fi-my\"></span> Malay"],
["Malagasy", "<span class=\"fi fi-mg\"></span> Malagasy"],
["Persian", "<span class=\"fi fi-ir\"></span> Persian"],
["Burmese", "<span class=\"fi fi-mm\"></span> Burmese"]
]
for r in language_replace_list:
x = x.replace(r[0], r[1])
return x
def write_reference_summary(outfile: TextIO, do_print: bool, nrefs: int, year_data: list, year_data_1900: list,
cite_count: int, languages, languages_by_year: dict) -> None:
if do_print:
start_page_division(outfile, "")
else:
common_header_part1(outfile, "Fiddler Crab Reference Summary")
start_google_chart_header(outfile)
outfile.write(" var data1 = google.visualization.arrayToDataTable([\n")
outfile.write(" ['Year', 'Cumulative Publications'],\n")
for y in year_data:
outfile.write(" ['" + str(y[0]) + "', " + str(y[2]) + "],\n")
outfile.write(" ]);\n")
outfile.write("\n")
outfile.write(" var data2 = google.visualization.arrayToDataTable([\n")
outfile.write(" ['Year', 'Publications'],\n")
for y in year_data:
outfile.write(" ['" + str(y[0]) + "', " + str(y[1]) + "],\n")
outfile.write(" ]);\n")
outfile.write("\n")
"""
outfile.write(" var data3 = google.visualization.arrayToDataTable([\n")
outfile.write(" ['Year', 'Citations in DB', 'Pending'],\n")
for y in yearData:
outfile.write(" ['"+str(y[0])+"', "+str(y[3])+", "+str(y[1]-y[3])+"],\n")
outfile.write(" ]);\n")
outfile.write("\n")
"""
outfile.write(" var data4 = google.visualization.arrayToDataTable([\n")
outfile.write(" ['Year', 'Publications'],\n")
for y in year_data_1900:
outfile.write(" ['" + str(y[0]) + "', " + str(y[1]) + "],\n")
outfile.write(" ]);\n")
outfile.write("\n")
outfile.write(" var data5 = google.visualization.arrayToDataTable([\n")
outfile.write(" ['Year', 'Citations in DB', 'Pending'],\n")
for y in year_data_1900:
outfile.write(" ['" + str(y[0]) + "', " + str(y[2]) + ", " + str(y[1]-y[2]) + "],\n")
outfile.write(" ]);\n")
outfile.write(" var data6 = google.visualization.arrayToDataTable([\n")
outfile.write(" ['Language', 'Count'],\n")
langlist = list(languages.keys())
langlist.sort()
for lang in langlist:
outfile.write(" ['" + lang + "', " + str(languages[lang]) + "],\n")
outfile.write(" ]);\n")
outfile.write("\n")
outfile.write(" var options1 = {\n")
outfile.write(" title: \"Cumulative References by Year\", \n")
outfile.write(" legend: { position: 'none' }\n")
outfile.write(" };\n")
outfile.write("\n")
outfile.write(" var options2 = {\n")
outfile.write(" title: \"References by Year\", \n")
outfile.write(" legend: { position: 'none' }\n")
outfile.write(" };\n")
outfile.write("\n")
"""
outfile.write(" var options3 = {\n")
outfile.write(" title: \"References with Citation Data in Database\", \n")
outfile.write(" legend: { position: 'bottom' },\n")
outfile.write(" isStacked: true\n")
outfile.write(" };\n")
outfile.write("\n")
"""
outfile.write(" var options4 = {\n")
outfile.write(" title: \"References by Year (since 1900)\", \n")
outfile.write(" legend: { position: 'none' },\n")
outfile.write(" bar: { groupWidth: '80%' }\n")
outfile.write(" };\n")
outfile.write("\n")
outfile.write(" var options5 = {\n")
outfile.write(" title: \"References with Citation Data in Database (since 1900; all pre-1900 "
"literature is complete)\", \n")
outfile.write(" legend: { position: 'bottom' },\n")
outfile.write(" isStacked: true,\n")
outfile.write(" bar: { groupWidth: '80%' }\n")
outfile.write(" };\n")
outfile.write("\n")
outfile.write(" var options6 = {\n")
outfile.write(" title: \"Primary Language of References\", \n")
outfile.write(" titleTextStle: { fontSize: '16' },\n")
# outfile.write(" isStacked: true,\n")
# outfile.write(" bar: { groupWidth: '80%' }\n")
outfile.write(" };\n")
outfile.write("\n")
outfile.write(" var chart = new google.visualization.LineChart"
"(document.getElementById('chart_div'));\n")
outfile.write(" chart.draw(data1, options1);\n")
outfile.write(" var chart2 = new google.visualization.ColumnChart"
"(document.getElementById('chart2_div'));\n")
outfile.write(" chart2.draw(data2, options2);\n")
# outfile.write(" var chart3 = new google.visualization.ColumnChart
# "(document.getElementById('chart3_div'));\n")
# outfile.write(" chart3.draw(data3, options3);\n")
outfile.write(" var chart4 = new google.visualization.ColumnChart"
"(document.getElementById('chart4_div'));\n")
outfile.write(" chart4.draw(data4, options4);\n")
outfile.write(" var chart5 = new google.visualization.ColumnChart"
"(document.getElementById('chart5_div'));\n")
outfile.write(" chart5.draw(data5, options5);\n")
outfile.write(" var chart6 = new google.visualization.PieChart"
"(document.getElementById('chart6_div'));\n")
outfile.write(" chart6.draw(data6, options6);\n")
end_google_chart_header(outfile)
common_header_part2(outfile)
outfile.write(" <header id=\"" + init_data().ref_sum_url + "\">\n")
outfile.write(" <h1 class=\"bookmark1\">Summary of References</h1>\n")
if not do_print:
outfile.write(" <nav>\n")
outfile.write(" <ul>\n")
outfile.write(" <li><a href=\"" + rel_link_prefix(do_print) + init_data().ref_url +
"\">" + fetch_fa_glyph("index") + "Full Reference List</a></li>\n")
outfile.write(" </ul>\n")
outfile.write(" </nav>\n")
outfile.write(" </header>\n")
outfile.write("\n")
outfile.write(" <p>\n")
outfile.write(" A summary of the references in the database (last updated {}).\n".
format(datetime.date.isoformat(datetime.date.today())))
outfile.write(" " + str(cite_count) + " of " + str(nrefs) +
" references have had citation data recorded.\n")
outfile.write(" See also the <a href=\"" + rel_link_prefix(do_print, "names/") + init_data().name_sum_url +
"\">name summary page</a> for information on reference patterns to specific species.\n")
outfile.write(" </p>\n")
if do_print:
# pie chart of languages
filename = "language_pie.png"
TMB_Create_Graphs.create_pie_chart_file(filename, languages, init_data().graph_font)
outfile.write(" <h3 class=\"nobookmark\">Primary Language of References</h3>\n")
outfile.write(" <figure class=\"graph\">\n")
outfile.write(" <img src=\"" + TMP_PATH + filename + "\" class=\"pie_chart\" />\n")
outfile.write(" </figure>\n")
# bar chart of languages by year
filename = "year_language_bar.png"
TMB_Create_Graphs.create_language_bar_chart_file(filename, languages_by_year, init_data().graph_font)
outfile.write(" <h3 class=\"nobookmark\">Proportion of References in Primary Language each Year</h3>\n")
outfile.write(" <figure class=\"graph\">\n")
outfile.write(" <img src=\"" + TMP_PATH + filename + "\" class=\"bar_chart\" />\n")
outfile.write(" </figure>\n")
# pubs per year bar chart
miny = init_data().current_year
maxy = init_data().start_year
for y in year_data:
miny = min(miny, y[0])
maxy = max(maxy, y[0])
filename = "pubs_per_year_bar.png"
TMB_Create_Graphs.create_bar_chart_file(filename, year_data, miny, maxy, 1, init_data().graph_font)
outfile.write(" <h3 class=\"nobookmark\">References by Year</h3>\n")
outfile.write(" <figure class=\"graph\">\n")
outfile.write(" <img src=\"" + TMP_PATH + filename + "\" class=\"bar_chart\" />\n")
outfile.write(" </figure>\n")
# pubs per year since 1900 bar chart
filename = "pubs_per_year_1900_bar.png"
TMB_Create_Graphs.create_bar_chart_file(filename, year_data_1900, 1900, maxy, 1, init_data().graph_font)
outfile.write(" <h3 class=\"nobookmark\">References by Year (since 1900)</h3>\n")
outfile.write(" <figure class=\"graph\">\n")
outfile.write(" <img src=\"" + TMP_PATH + filename + "\" class=\"bar_chart\" />\n")
outfile.write(" </figure>\n")
# citation data in database
filename = "pubs_per_year_1900_complete_bar.png"
tmp_dat = []
for y in year_data_1900:
tmp_dat.append([y[2], y[1] - y[2]])
dat_info = [["Citations in DB", 0], ["Pending", 1]]
TMB_Create_Graphs.create_stacked_bar_chart_file(filename, tmp_dat, 1900, maxy, dat_info, init_data().graph_font)
outfile.write(" <h3 class=\"nobookmark\">References with Citation Data in Database (since 1900; all "
"pre-1900 literature is complete)</h3>\n")
outfile.write(" <figure class=\"graph\">\n")
outfile.write(" <img src=\"" + TMP_PATH + filename + "\" class=\"bar_chart\" />\n")
outfile.write(" </figure>\n")
# cumulative publications line chart
filename = "cumulative_pubs_line.png"
TMB_Create_Graphs.create_line_chart_file(filename, year_data, miny, maxy, 2, init_data().graph_font)
outfile.write(" <h3 class=\"nobookmark\">Cumulative References by Year</h3>\n")
outfile.write(" <figure class=\"graph\">\n")
outfile.write(" <img src=\"" + TMP_PATH + filename + "\" class=\"line_chart\" />\n")
outfile.write(" </figure>\n")
end_page_division(outfile)
else:
outfile.write(" <div id=\"chart6_div\"></div>\n")
outfile.write(" <div id=\"chart2_div\"></div>\n")
outfile.write(" <div id=\"chart4_div\"></div>\n")
# outfile.write(" <div id=\"chart3_div\"></div>\n")
outfile.write(" <div id=\"chart5_div\"></div>\n")
outfile.write(" <div id=\"chart_div\"></div>\n")
common_html_footer(outfile)
def write_reference_bibliography(outfile: TextIO, do_print: bool, reflist: list) -> None:
if do_print:
start_page_division(outfile, "index_page")
else:
common_html_header(outfile, "Fiddler Crab Publications")
outfile.write(" <header id=\"" + init_data().ref_url + "\">\n")
outfile.write(" <h1 class=\"bookmark1\">Full Reference List</h1>\n")
if not do_print:
outfile.write(" <nav>\n")
outfile.write(" <ul>\n")
outfile.write(" <li><a href=\"" + rel_link_prefix(do_print) + init_data().ref_sum_url +
"\">" + fetch_fa_glyph("summary charts") + "Reference/Citation Summary</a></li>\n")
outfile.write(" </ul>\n")
outfile.write(" </nav>\n")
outfile.write(" </header>\n")
outfile.write("\n")
outfile.write(" <p>\n")
outfile.write(" Following is a fairly comprehensive list of papers, books, and theses that deal or refer "
"to fiddler crabs. The list currently contains {:0,} references "
"(last updated {}).\n".format(len(reflist), datetime.date.isoformat(datetime.date.today())))
outfile.write(" </p>\n")
outfile.write(" <p>\n")
outfile.write(" The references can also be downloaded as "
"<a href=\"" + abs_link_prefix(do_print) + "references/Uca_references.enlx\">compressed Endnote</a>, "
"<a href=\"" + abs_link_prefix(do_print) + "references/Uca_references_RIS.txt\">RIS (text)</a>, or "
"<a href=\"" + abs_link_prefix(do_print) + "references/Uca_references_RIS.xml\">RIS (XML)</a>.\n")
outfile.write(" </p>\n")
outfile.write(" <p>\n")
outfile.write(" Linked references contain information on every name applied to fiddler crabs within "
"the publication, including context and the correct name as we currently understand it. These "
"data are in the process of being compiled (chronologically for all publications I have access "
"to a copy of), with most references still incomplete.\n")
outfile.write(" </p>\n")
outfile.write(" <p>\n")
outfile.write(" In a list of this size, there are bound to be errors, omissions, and mistaken "
"inclusions. Please feel free to send me corrections.\n")
outfile.write(" </p>\n")
outfile.write("\n")
outfile.write(" <section class=\"spsection\">\n")
outfile.write(" <div class=\"reference_list\">\n")
outfile.write(" <ul>\n")
# for ref in tqdm(reflist):
for ref in reflist:
outfile.write(" <li>" + format_reference_full(ref, do_print) + "</li>\n")
outfile.write(" </ul>\n")
outfile.write(" </div>\n")
outfile.write(" </section>\n")
if do_print:
end_page_division(outfile)
else:
common_html_footer(outfile)
def create_name_table(citelist: list) -> dict:
name_refs = {}
for c in citelist:
nstr = c.name_key
if "." in nstr:
nstr = nstr[:nstr.find(".")]
i = int(nstr)
if c.cite_key in name_refs:
namelist = name_refs[c.cite_key]
else:
namelist = {}
namelist[i] = c.name
if "." in c.name_key:
namelist[c.name_key] = [c.name, c.application]
name_refs[c.cite_key] = namelist
return name_refs
def match_num_ref(x: str, y: str) -> bool:
if (("." in x) and ("." in y)) or (("." not in x) and ("." not in y)):
return x == y
elif "." in x:
return x[:x.find(".")] == y
else:
return y[:y.find(".")] == x
def compute_applied_name_contexts(citelist: list) -> None:
"""
function to gather list of primary contexts referred to by other citation entries
"""
for i, cite in enumerate(citelist):
if (cite.context == "specimen") or (cite.context == "location") or (cite.context == "sequence"):
cite.applied_cites = {cite}
elif cite.context == "citation":
for j in range(i): # only look at entries up to the current one
tmp = citelist[j]
if (tmp.cite_key == cite.application) and match_num_ref(tmp.name_key, cite.cite_n):
if (tmp.context == "specimen") or (tmp.context == "location") or (tmp.context == "sequence"):
cite.applied_cites |= {tmp}
if len(cite.applied_cites) == 0:
cite.applied_cites = None
# for testing purposes only
# if cite.applied_cites is None:
# print(cite.cite_key, cite.name_key, cite.context, "No application")
# else:
# for c in cite.applied_cites:
# print(cite.cite_key, cite.name_key, cite.context, c.cite_key, c.name_key, c.context)
# input()
def compute_species_from_citation_linking(citelist: list) -> None:
"""
function to update correct species citations through cross-references to earlier works
"""
# for i, cite in enumerate(tqdm(citelist)):
unrecorded_xrefs = []
recorded_refs = set()
for i, cite in enumerate(citelist):
recorded_refs.add(cite.cite_key)
if cite.actual == "=":
cname = ""
crossnames = collections.Counter()
for j in range(i): # only look at entries up to the current one
tmp = citelist[j]
if (tmp.cite_key == cite.application) and match_num_ref(tmp.name_key, cite.cite_n):
cname = tmp.name
crossnames.update([tmp.actual])
if len(crossnames) == 0:
unrecorded_xrefs.append([cite.cite_key, cite.application, cite.name_key, cite.cite_n])
elif len(crossnames) == 1:
cite.actual = list(crossnames.keys())[0]
else:
# find name(s) with largest count
mcnt = max(crossnames.values())
keylist = []
for key in crossnames:
if crossnames[key] == mcnt:
keylist.append(key)
if len(keylist) == 1:
cite.actual = keylist[0]
else:
cite_name = cite.name.lower()
while cite_name.find(" ") > -1:
cite_name = cite_name[cite_name.find(" ")+1:]
while cname.find(" ") > -1:
cname = cname[cname.find(" ")+1:]
if cite_name in keylist:
cite.actual = cite_name
elif cname in keylist:
cite.actual = cname
else:
cite.actual = keylist[0]
if cite.name_note == ".":
cite.name_note = "in part"
else:
cite.name_note = "in part; " + cite.name_note
for x in unrecorded_xrefs:
if x[1] in recorded_refs:
report_error("Reference {} ({}) does not appear until after citation from {} ({})".format(x[1], x[3],
x[0], x[2]))
def create_species_link(genus: str, species: str, do_print: bool, status: str = "", path: str = "") -> str:
if status == "fossil":
sc = FOSSIL_IMAGE
else:
sc = ""
return ("<a href=\"" + rel_link_prefix(do_print, path) + "u_" + species + ".html\"><em class=\"species\">" + genus +
" " + species + "</em>" + sc + "</a>")
def rank_tags(x: str) -> Tuple[str, str]:
if ("genus" in x) or ("species" in x):
return "<em class=\"species\">", "</em>"
else:
return "", ""
def create_taxon_link(rank: str, name: str, do_print: bool, same_page: bool = False, path: str = "",
include_rank: bool = True) -> str:
"""
create a link to a higher-order taxonomic entry
"""
start_tag, end_tag = rank_tags(rank)