-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcode_DataBase.py
2996 lines (2395 loc) · 126 KB
/
code_DataBase.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 basic Python libraries
import os
import csv
import zipfile
import io
import sys
from copy import deepcopy
from collections import defaultdict
import datetime
import code_Filter
import json
import piexif
from math import floor
from natsort import natsorted
from PyQt5.QtWidgets import (
QApplication,
QMessageBox
)
class DataBase():
# this is the class that will store all our data and the data-seeking logic
def __init__(self):
self.allSpeciesList = []
self.familyList = []
self.orderList = []
self.masterFamilyOrderList = []
self.masterLocationList = []
self.regionList = []
self.countryList = []
self.stateList = []
self.countyList = []
self.locationList = []
self.validPhotoSpecies = []
self.cameraList = []
self.lensList = []
self.shutterSpeedList = []
self.apertureList = []
self.focalLengthList=[]
self.isoList = []
self.sightingList = []
self.eBirdFileOpenFlag = False
self.photoDataFileOpenFlag = False
self.photosNeedSaving = False
self.countryStateCodeFileFound = False
self.speciesDict = defaultdict()
self.yearDict = defaultdict()
self.monthDict = defaultdict()
self.dateDict = defaultdict()
self.countryDict = defaultdict()
self.stateDict = defaultdict()
self.countyDict = defaultdict()
self.locationDict = defaultdict()
self.checklistDict = defaultdict()
self.familySpeciesDict = defaultdict()
self.orderSpeciesDict = defaultdict()
self.bblCodeDict = defaultdict()
self.photoDataFile = ""
self.startupFolder = ""
self.monthNameDict = ({
"01":"Jan",
"02":"Feb",
"03":"Mar",
"04":"Apr",
"05":"May",
"06":"Jun",
"07":"Jul",
"08":"Aug",
"09":"Sep",
"10":"Oct",
"11":"Nov",
"12":"Dec"
})
self.monthNumberDict = ({
"Jan":"01",
"Feb":"02",
"Mar":"03",
"Apr":"04",
"May":"05",
"Jun":"06",
"Jul":"07",
"Aug":"08",
"Sep":"09",
"Oct":"10",
"Nov":"11",
"Dec":"12"
})
self.regionNameDict = ({
"ABA":"ABA Area",
"AOU":"AOU Area",
"NAM":"North America",
"SAM":"South America",
"AFR":"Africa",
"EUR":"Europe",
"ASI":"Asia",
"SPO":"South Polar",
"WHE":"Western Hemisphere",
"EHE":"Eastern Hemisphere",
"WIN":"West Indies",
"CAM":"Central America",
"USL":"USA Lower 48",
"AUA":"Australasia (ABA)",
"AUE":"Australasia (eBird)",
"AUS":"Australia and Territories"
})
self.regionCodeDict = ({
"ABA Area":"ABA",
"AOU Area":"AOU",
"North America":"NAM",
"South America":"SAM",
"Africa":"AFR",
"Europe":"EUR",
"Asia":"ASI",
"South Polar":"SPO",
"Western Hemisphere":"WHE",
"Eastern Hemisphere":"EHE",
"West Indies":"WIN",
"Central America":"CAM",
"USA Lower 48":"USL",
"Australasia (ABA)":"AUA",
"Australasia (eBird)":"AUE",
"Australia and Territories":"AUS"
})
# look for json files. They must be in the same directory as the script directory
if getattr(sys, 'frozen', False):
# frozen
scriptDirectory = os.path.dirname(sys.executable)
else:
# unfrozen
scriptDirectory = os.path.dirname(os.path.realpath(__file__))
# format file names so we can find them regardless of whether we're frozen
stateJsonFile = os.path.join(scriptDirectory, "us-states.json")
countyJsonFile = os.path.join(scriptDirectory, "us-counties-lower48.json")
countryJsonFile = os.path.join(scriptDirectory, "world-countries.json")
# load us-states json shape file for later use with choropleths
self.state_geo = json.loads(open(stateJsonFile).read())
# # create list of US state abbreviations for later use with choropleths
# self.stateCodeList = set()
# for s in self.state_geo["features"]:
# self.stateCodeList.add(s["id"])
# self.stateCodeList = list(self.stateCodeList)
# load us-counties-lower48 json shape file for later use with choropleths
self.county_geo = json.loads(open(countyJsonFile).read())
# save county code data for easy lookup when processing eBird data file
self.countyCodeDict = defaultdict()
self.countyCodeList = set()
for c in self.county_geo["features"]:
# save master list of all US county codes for use with choropleths
self.countyCodeList.add(c["id"])
if c["properties"]["name"] not in self.countyCodeDict.keys():
self.countyCodeDict[c["properties"]["name"]] = [[c["id"],c["properties"]["state"]]]
else:
self.countyCodeDict[c["properties"]["name"]].append([c["id"],c["properties"]["state"]])
# self.countyCodeList = list(self.countyCodeList)
# load world-countries json shape file for later use with choropleths
self.country_geo = json.loads(open(countryJsonFile).read())
def matchPhoto(self, file):
# method to suggest a commonName, date, time, and location for a photo
# get just the filename portion from the full-path filename
fileName = os.path.basename(file)
# get the EXIF data from the file, if possible
try:
photoExif = piexif.load(file)
except:
photoExif = ""
# get photo date from EXIF
try:
photoDateTime = photoExif["Exif"][piexif.ExifIFD.DateTimeOriginal].decode("utf-8")
# parse EXIF data for date/time components
photoDate = photoDateTime[0:4] + "-" + photoDateTime[5:7] + "-" + photoDateTime[8:10]
photoTime = photoDateTime[11:13] + ":" + photoDateTime[14:16]
except:
photoDate = ""
photoTime = ""
# use date and time to select a sighting location from db
filter = code_Filter.Filter()
filter.setStartDate(photoDate)
filter.setEndDate(photoDate)
filter.setTime(photoTime)
locations = self.GetLocations(filter, "OnlyLocations")
# if we find only one location, return it
if len(locations) == 1:
photoLocation = locations[0]
else:
photoLocation = ""
# if no single location matched the photo, but we have a date, find which checklist is closest to the photo datetime
if photoLocation == "" and photoDate != "":
# try finding a checklist with the right date
filter = code_Filter.Filter()
filter.setStartDate(photoDate)
filter.setEndDate(photoDate)
locations = self.GetLocations(filter, "OnlyLocations")
if len(locations) == 1:
photoLocation = locations[0]
possibleStartTimes = self.GetStartTimes(filter)
if len(possibleStartTimes) > 0:
photoTime = possibleStartTimes[0]
# if more than one location was found, find which was visited closest to the photo time
elif len(locations) > 1 and photoTime != "":
filter = code_Filter.Filter()
filter.setStartDate(photoDate)
filter.setEndDate(photoDate)
checklists = self.GetChecklists(filter)
# create list to store location and checklist time for closest one to our photo's datetime
# third list entry starts with total minutes in a day (most gap possible)
checklistTimeDifference = ["", "", 24 * 60]
photoMinutesSinceMidnight = 60 * int(photoTime[0:2]) + int(photoTime[3:5])
for c in checklists:
checklistTime = c[5]
checklistDuration = c[7]
if checklistDuration == "":
checklistDuration = "0"
checklistStartMinSinceMidnight = 60 * int(checklistTime[0:2]) + int(checklistTime[3:5])
checklistEndMinSinceMidnight = checklistStartMinSinceMidnight + int(checklistDuration)
# check if this checklist's time is closer to our photo's time than any other checklist looped through so far
# If so, save its data into checklistTimeDifference
if abs(photoMinutesSinceMidnight - checklistStartMinSinceMidnight) < checklistTimeDifference[2]:
checklistTimeDifference = [c[3], c[5], abs(photoMinutesSinceMidnight - checklistStartMinSinceMidnight)]
if abs(photoMinutesSinceMidnight - checklistEndMinSinceMidnight) < checklistTimeDifference[2]:
checklistTimeDifference = [c[3], c[5], abs(photoMinutesSinceMidnight - checklistEndMinSinceMidnight)]
if checklistTimeDifference[0] != "":
photoLocation = checklistTimeDifference[0]
photoTime = checklistTimeDifference[1]
# try to use file name to match commonName using date, time, and location found already
if photoLocation != "" and photoDate != "" and photoTime != "":
filter = code_Filter.Filter()
filter.setLocationType("Location")
filter.setLocationName(photoLocation)
filter.setStartDate(photoDate)
filter.setEndDate(photoDate)
filter.setTime(photoTime)
possibleCommonNames = self.GetSpecies(filter)
# set up translation table to remove inconvenient characters from file name
# and possiblecommonNames
translation_table = dict.fromkeys(map(ord, "0123456789-' "), None)
# make file name lower case and remove inconvenient characters
fileName = str(fileName)
fileName = fileName.lower()
fileName = fileName.translate(translation_table)
# create list to store most likely commonName and number of matching characters
mostLikelyCommonName = [0, "", ""]
# cycle through possibleCommonNames, testing them piece by piece
# to find which matches the most number of consecutive characters
for pcn in possibleCommonNames:
lowerCasePcn = pcn.lower()
lowerCasePcn = lowerCasePcn.translate(translation_table)
possibleCommonNameLength = len(lowerCasePcn)
for i in range(possibleCommonNameLength):
for ii in range(i + 1, possibleCommonNameLength + 1):
if lowerCasePcn[i:ii] in fileName:
if len(lowerCasePcn[i:ii]) > mostLikelyCommonName[0]:
mostLikelyCommonName[0] = len(lowerCasePcn[i:ii])
mostLikelyCommonName[1] = pcn
mostLikelyCommonName[2] = lowerCasePcn[i:ii]
if len(lowerCasePcn[i:ii]) == len(lowerCasePcn):
# matched the full possible name, so stop checking
break
photoCommonName = mostLikelyCommonName[1]
else:
photoCommonName = ""
photoMatchData = {}
photoMatchData["photoLocation"] = photoLocation
photoMatchData["photoDate"] = photoDate
photoMatchData["photoTime"] = photoTime
photoMatchData["photoCommonName"] = photoCommonName
return(photoMatchData)
def removeUnfoundPhotos(self):
count = 0
# method to remove photos from database
# create filter with no settings to retrieve every photo in db
filter = code_Filter.Filter()
# get all sightings with photos
sightings = self.GetSightingsWithPhotos(filter)
for s in sightings:
for p in s["photos"]:
if not os.path.isfile(p):
s["photos"].remove(p)
count += 1
# return the number of removed files
return(count)
def removePhotoFromDatabase(self, location, date, time, commonName, photoFileName):
# method to remove photos from database
filter = code_Filter.Filter()
filter.setLocationType("Location")
filter.setLocationName(location)
if date != "":
filter.setStartDate(date)
filter.setEndDate(date)
if time != "":
filter.setTime(time)
filter.setSpeciesName(commonName)
# get sightings that match the filter. Should only be a single sighting.
sightings = self.GetSightingsWithPhotos(filter)
for s in sightings:
if "photos" in s.keys():
for p in s["photos"]:
if p["fileName"] == photoFileName:
s["photos"].remove(p)
# if we've removed all the photos for this sighting, we need to remove the "photos" entry in the dict
if len(s["photos"]) == 0:
s.pop("photos", None)
def getPhotoData(self, fileName):
photoData = {}
# try to get EXIF data
try:
exif_dict = piexif.load(fileName)
except:
exif_dict = ""
try:
photoCamera = exif_dict["0th"][piexif.ImageIFD.Model].decode("utf-8")
except:
photoCamera = ""
try:
photoLens = exif_dict["Exif"][piexif.ExifIFD.LensModel].decode("utf-8")
except:
photoLens = ""
try:
shutterSpeedFraction = exif_dict["Exif"][piexif.ExifIFD.ExposureTime]
photoShutterSpeed = floor(shutterSpeedFraction[1]/shutterSpeedFraction[0])
photoShutterSpeed = "1/" + str(photoShutterSpeed)
except:
photoShutterSpeed = ""
try:
photoAperture = exif_dict["Exif"][piexif.ExifIFD.FNumber]
photoAperture = round(photoAperture[0] / photoAperture[1], 1)
except:
photoAperture = ""
try:
photoISO = exif_dict["Exif"][piexif.ExifIFD.ISOSpeedRatings]
except:
photoISO = ""
try:
photoFocalLength = exif_dict["Exif"][piexif.ExifIFD.FocalLength]
photoFocalLength = floor(photoFocalLength[0] / photoFocalLength[1])
photoFocalLength = str(photoFocalLength) + " mm"
except:
photoFocalLength = ""
# get photo date from EXIF
try:
photoDateTime = exif_dict["Exif"][piexif.ExifIFD.DateTimeOriginal].decode("utf-8")
#parse EXIF data for date/time components
photoExifDate = photoDateTime[0:4] + "-" + photoDateTime[5:7] + "-" + photoDateTime[8:10]
photoExifTime = photoDateTime[11:13] + ":" + photoDateTime[14:16]
except:
photoExifDate = "Date unknown"
photoExifTime = "Time unknown"
photoData["fileName"] = fileName
photoData["camera"] = photoCamera
photoData["lens"] = photoLens
photoData["shutterSpeed"] = str(photoShutterSpeed)
photoData["aperture"] = str(photoAperture)
photoData["iso"] = str(photoISO)
photoData["focalLength"] = str(photoFocalLength)
photoData["time"] = photoExifTime
photoData["date"] = photoExifDate
photoData["rating"] = "0"
return(photoData)
def addPhotoToDatabase(self, filter, photoData):
# check that file still exists before proceeding
if os.path.isfile(photoData["fileName"]):
# get sightings that match the filter. Should only be a single sighting.
sightings = self.GetSightings(filter)
if len(sightings) > 0:
s = sightings[0]
if "photos" not in s.keys():
s["photos"] = [photoData]
else:
if photoData not in s["photos"]:
s["photos"].append(photoData)
# add photoData to db lists
self.addPhotoDataToDb(photoData)
def writePhotoDataToFile(self, fileName):
# get all sightings with photos
filter = code_Filter.Filter()
sightings = self.GetSightingsWithPhotos(filter)
# set up writing CSV to fileName
with open(fileName, mode='w') as photoDataFile:
photoDataWriter = csv.writer(photoDataFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
photoDataWriter.writerow(["ChecklistID", "CommonName", "FileName", "Camera", "Lens", "ShutterSpeed", "Aperture", "ISO", "FocalLength", "Rating"])
for s in sightings:
for p in s["photos"]:
try:
photoDataWriter.writerow([
s["checklistID"],
s["commonName"],
p["fileName"],
p["camera"],
p["lens"],
p["shutterSpeed"],
p["aperture"],
p["iso"],
p["focalLength"],
p["rating"]
])
except IOError as err:
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setText("Error occurred while saving the photo data to disk.\n" + s["commonName"] + " " + s["checklistID"] + "\n"+ str(err))
msg.setWindowTitle("Save Error")
msg.setStandardButtons(QMessageBox.Ok)
msg.exec_()
def readPhotoDataFromFile(self, fileName):
with open(fileName, mode='r') as photoDataFile:
csv_reader = csv.DictReader(photoDataFile)
try:
for row in csv_reader:
photoData = {}
filter = code_Filter.Filter()
filter.setChecklistID(row["ChecklistID"])
filter.setSpeciesName(row["CommonName"])
photoData["fileName"] = row["FileName"]
photoData["camera"] = row["Camera"]
photoData["lens"] = row["Lens"]
photoData["shutterSpeed"] = row["ShutterSpeed"]
photoData["aperture"] = row["Aperture"]
photoData["iso"] = row["ISO"]
photoData["focalLength"] = row["FocalLength"]
if "Rating" in row.keys():
if row["Rating"] in ["0", "1", "2", "3", "4", "5"]:
photoData["rating"] = row["Rating"]
else:
photoData["rating"] = "0"
else:
photoData["rating"] = "0"
self.addPhotoToDatabase(filter, photoData)
except:
pass
self.photoDataFileOpenFlag = True
def refreshPhotoLists(self):
self.cameraList = []
self.lensList = []
self.shutterSpeedList = []
self.apertureList = []
self.focalLengthList=[]
self.isoList = []
cameraSet = set()
lensSet = set()
shutterSpeedSet = set()
apertureSet= set()
focalLengthSet = set()
isoSet = set()
for s in self.sightingList:
if "photos" in s.keys():
for p in s["photos"]:
if p["camera"] != "":
cameraSet.add(p["camera"])
if p["lens"] != "":
lensSet.add(p["lens"])
if p["shutterSpeed"] != "":
shutterSpeedSet.add(p["shutterSpeed"])
if p["aperture"] != "":
apertureSet.add(p["aperture"])
if p["iso"] != "":
isoSet.add(p["iso"])
if p["focalLength"] != "":
focalLengthSet.add(p["focalLength"])
self.cameraList = list(cameraSet)
self.lensList = list(lensSet)
self.shutterSpeedList = natsorted(list(shutterSpeedSet), reverse=True)
self.apertureList = natsorted(list(apertureSet))
self.isoList = natsorted(list(isoSet))
self.focalLengthList = natsorted(list(focalLengthSet))
def CountSpecies(self, speciesList):
# method to count true species in a list. Entries with parens, /, or sp. or hybrids should not be counted,
# unless no non-paren entries exist for that species.append
speciesSet = set()
# use a set (which deletes duplicates) to hold species names
# remove parens from species names if they exist
for s in speciesList:
if "(" in s and " x " not in s:
speciesSet.add(s.split(" (")[0])
elif "sp." in s:
pass
elif "/" in s:
pass
elif " x " in s:
pass
else:
speciesSet.add(s)
# count the species, including species whose parens have been removed
count = len(speciesSet)
return(count)
def ReadCountryStateCodeFile(self, dataFile):
# initialize variable used to store CSV file's data
countryCodeData = []
# open the country and state code data file
# and read its lines into a list for future searching
with open(dataFile, 'r', errors='replace') as csvfile:
csvdata = csv.reader(csvfile, delimiter=',', quotechar='"')
for line in csvdata:
countryCodeData.append(line)
csvfile.close()
# clear the countryList and stateList because we'll use longer names
self.countryList = []
self.stateList = []
# search through each location in the master location file
# append the long country and state names when found in the country state code data
for l in self.masterLocationList:
# # append two place holders in the masterLocationList for long country and state names
# l.append("")
# l.append("")
#
for c in countryCodeData:
# find the long country name by looking for a perfect match of "cc-" for the state code
# this match is actually for the country because states have characters
# after the - character
if l["countryCode"] + "-" == c[1]:
# when found, save the long country name to the masterLocationList
l["countryName"] = c[2]
self.countryList.append(c[2])
# look for a perfect match for the state code
if l["stateCode"] == c[1]:
# when found, save the long state name to the masterLocationList
l["stateName"] = c[2]
self.stateList.append(c[2])
# no need to keep searching. We've found our long names.
break
# get rid of duplicates in master country and state lists using the set command
self.countryList = list(set(self.countryList))
self.stateList = list(set(self.stateList))
# sort the master country and state lists
self.countryList.sort()
self.stateList.sort()
self.countryCodeData = countryCodeData
self.countryStateCodeFileFound = True
def ReadDataFile(self, DataFile):
self.ClearDatabase()
# extract data from zip file if user has chosen a zip file
if os.path.splitext(DataFile[0])[1] == ".zip":
filehandle = open(DataFile[0], 'rb')
zfile = zipfile.ZipFile(filehandle)
try:
csvfile = io.StringIO(zfile.read("MyEBirdData.csv").decode('utf-8'))
except (KeyError):
QApplication.restoreOverrideCursor()
self.eBirdFileOpenFlag = False
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setText("The file failed to load.\n\nPlease check that it is a valid eBird data file.\n")
msg.setWindowTitle("File failed to load")
msg.setStandardButtons(QMessageBox.Ok)
msg.exec_()
return
# use csv reader to process csv file if user has selected a csv file
if os.path.splitext(DataFile[0])[1] == ".csv":
csvfile = open(DataFile[0], 'r')
# process CSV values from csvfile.
csvdata = csv.DictReader(csvfile)
# initialize temporary list variable to hold location data
thisMasterLocationEntry = []
for line in csvdata:
# convert date format from mm-dd-yyyy to yyyy-mm-dd for international standard and sorting ability
# THIS IS NO LONGER NECESSARY, AS IN MARCH 2019 EBIRD CHANGED THE DATA FORMAT TO THE ONE WE PREFER
# line[10] = line[10][6:] + "-" + line[10][0:2] + "-" + line[10][3:5]
# append state name in parentheses to county name to differentiate between
# counties that have the same name but are in different states
if line["County"] != "":
line["County"] = line["County"] + " (" + line["State/Province"] + ")"
# add blank elements to list so we can later add family and order names if taxonomic file exists
# also add blank line for subspecies name
# store full name (maybe a subspecies) in sighting
subspeciesName = deepcopy(line["Common Name"])
line["Subspecies"] = subspeciesName
# remove any subspecies data in parentheses in species name
# but keep "(hybrid)" if it's in the name
if "(" in line["Common Name"]:
if "hybrid" not in line["Common Name"]:
line["Common Name"] = line["Common Name"][:line["Common Name"].index("(") - 1]
# convert 12-hour time format to 24-hour format for easier sorting and display
time = line["Time"]
if "AM" in time:
time = line["Time"][0:5]
if "PM" in time:
time = line["Time"][0:5]
hour = int(line["Time"][0:2])
hour = str(hour + 12)
if hour == "24":
hour = "12"
time = hour + line["Time"][2:5]
line["Time"] = time
# add sighting to the main database for use by later searches etc.
# this sightingList will be used in nearly every search performed by user
# convert line's CSV data into our own dictionary to remove spaces, abbreviations, etc.
thisSightingDict = defaultdict(
checklistID=line["Submission ID"],
commonName=line["Common Name"],
scientificName=line["Scientific Name"],
subspeciesName=line["Subspecies"],
taxonomicOrder=line["Taxonomic Order"],
count=line["Count"],
country=line["State/Province"][0:2],
state=line["State/Province"],
county=line["County"],
location=line["Location"],
latitude=line["Latitude"],
longitude=line["Longitude"],
date=line["Date"],
time=line["Time"],
protocol=line["Protocol"],
duration=line["Duration (Min)"],
allObsReported=line["All Obs Reported"],
distance=line["Distance Traveled (km)"],
areaCovered=line["Area Covered (ha)"],
observers=line["Number of Observers"],
breedingCode=line["Breeding Code"],
checklistComments=line["Checklist Comments"],
regionCodes=[]
)
if thisSightingDict["areaCovered"] is None:
thisSightingDict["areaCovered"] = ""
if thisSightingDict["distance"] is None:
thisSightingDict["distance"] = ""
if thisSightingDict["observers"] is None:
thisSightingDict["observers"] = ""
if thisSightingDict["breedingCode"] is None:
thisSightingDict["breedingCode"] = ""
if "Observation Details" in line.keys():
thisSightingDict["speciesComments"]=line["Observation Details"]
if "Species Comments" in line.keys():
thisSightingDict["speciesComments"]=line["Species Comments"]
if thisSightingDict["speciesComments"] is None:
thisSightingDict["speciesComments"] = ""
if thisSightingDict["checklistComments"] is None:
thisSightingDict["checklistComments"] = ""
thisSightingDict["family"] = ""
thisSightingDict["order"] = ""
# If a US sighting, use countyCodeDict to assign the unique 5-digit FIPS code for the county
# we'll use this for choropleths
if thisSightingDict["country"] == "US" and thisSightingDict["state"] not in ["US-HI", "US-AK"]:
countyNameWithoutParentheses = thisSightingDict["county"].split(" (")[0]
if countyNameWithoutParentheses != "":
for c in self.countyCodeDict[countyNameWithoutParentheses]:
if c[1] == thisSightingDict["state"][3:5]:
thisSightingDict["countyCode"] = c[0]
# add abbreviations for the regions recognized by eBird
# ----------------------------------------
# add ABA if in US, Canada, or St. Pierre et Miquelon, but exclude Hawaii
if thisSightingDict["country"] in ["US", "CA", "PM"]:
if thisSightingDict["state"] != "US-HI":
thisSightingDict["regionCodes"].append("ABA")
# ----------------------------------------
# add AOU if if in US, Canada, St. Pierre et Miquelon, Mexico, Central America
if thisSightingDict["country"] in [
"US", "CA", "PM", "MX", "GT", "SV", "HN", "CR", "PA",
"CU", "HT", "DO", "JM", "KY", "PR", "VG", "VI", "AI",
"MF", "BL", "BQ", "KN", "AG", "MS", "GP", "DM", "BS",
"BB", "GD", "LC", "VC", "BM", "CP", "NI"
]:
thisSightingDict["regionCodes"].append("AOU")
if thisSightingDict["state"] in [
"CO-SAP", "UM-67", "UM-71"
]:
thisSightingDict["regionCodes"].append("AOU")
# ----------------------------------------
# add USL if if in Lower 48 US states listing region as designated by eBird
if thisSightingDict["country"] == "US":
if thisSightingDict["state"] not in ["US-AK", "US-HI"]:
thisSightingDict["regionCodes"].append("USL")
#---------------------------------------
# add AFR if if in Africa
if thisSightingDict["country"] in [
"DZ", "AO", "SH", "BJ", "BW", "BF", "BI", "CM", "CV", "CF", "TD",
"KM", "CG", "CD", "DJ", "GQ", "ER", "SZ", "ET", "GA", "GM",
"GH", "GN", "GW", "CI", "KE", "LS", "LR", "LY", "MG", "MW", "ML",
"MR", "MU", "YT", "MA", "MZ", "NA", "NE", "NG", "ST", "RE", "RW",
"ST", "SN", "SC", "SL", "SO", "ZA", "SS", "SH", "SD", "SZ", "TZ",
"TG", "TN", "UG", "CD", "ZM", "TZ", "ZW"
]:
thisSightingDict["regionCodes"].append("AFR")
if thisSightingDict["state"] == "ES-CN":
thisSightingDict["regionCodes"].append("AFR")
if thisSightingDict["country"] == "EG":
if thisSightingDict["state"] not in ["EG-PTS", "EG-JS", "EG-SIN"]:
thisSightingDict["regionCodes"].append("AFR")
# ----------------------------------------
# add ASI if if in Asia
if thisSightingDict["country"] in [
"AF", "AM", "AZ", "BH", "BD", "BT", "BN", "KH", "CN", "CX", "CC",
"IO", "GE", "HK", "IN", "IR", "IQ", "IL", "JP", "JO",
"KW", "KG", "LA", "LB", "MO", "MY", "MV", "MN", "MM", "NP", "KP",
"OM", "PK", "PS", "PH", "QA", "SA", "SG", "KR", "LK", "SY", "TW",
"TJ", "TH", "TM", "AE", "UZ", "VN", "YE", "SD", "SZ", "TZ",
"TG", "TN", "UG", "CD", "ZM", "TZ", "ZW"
]:
thisSightingDict["regionCodes"].append("ASI")
if thisSightingDict["country"] == "TR":
if thisSightingDict["state"] not in ["TR-22", "TR-39", "TR-59"]:
thisSightingDict["regionCodes"].append("ASI")
if thisSightingDict["country"] == "KZ":
if thisSightingDict["state"] not in ["KZ-ATY", "KZ-ZAP"]:
thisSightingDict["regionCodes"].append("ASI")
if thisSightingDict["country"] == "ID":
if thisSightingDict["state"] != "ID-IJ":
thisSightingDict["regionCodes"].append("ASI")
if thisSightingDict["country"] == "EG":
if thisSightingDict["state"] in ["EG-PTS", "EG-JS", "EG-SIN"]:
thisSightingDict["regionCodes"].append("ASI")
if thisSightingDict["country"] == "RU":
if thisSightingDict["state"] in [
"RU-YAN", "RU-KHM", "RU-TYU", "RU-OMS", "RU-TOM", "RU-NVS",
"RU-ALT", "RU-KEM", "RU-AL", "RU-KK", "RU-KYA", "RU-TY",
"RU-IRK", "RU-SA", "RU-BU", "RU-ZAB", "RU-AMU", "RU-KHA",
"RU-YEV", "RU-PRI", "RU-MAG", "RU-CHU", "RU-KAM", "RU-SAK"
]:
thisSightingDict["regionCodes"].append("ASI")
# ----------------------------------------
# add ATL if if in Atlantic listing region
# Note that pelagic sightings more than 200 miles from a state
# will not be counted here because I don't know how to calculate
# if a log/lat sighting is 200 miles from a state
if thisSightingDict["country"] in [
"BM", "FK", "SH"
]:
thisSightingDict["regionCodes"].append("ATL")
# ----------------------------------------
# add AUE if if in Australasia (eBird) listing region
if thisSightingDict["country"] in [
"AU", "AC", "NF", "NZ", "SB", "VU", "NC", "PG",
]:
thisSightingDict["regionCodes"].append("AUE")
if thisSightingDict["state"] in [
"ID-IJ", "ID-MA"
]:
thisSightingDict["regionCodes"].append("AUE")
# ----------------------------------------
# add AUA if if in Australasia (ABA) listing region
if thisSightingDict["country"] in [
"AU", "ID"
]:
thisSightingDict["regionCodes"].append("AUA")
# ----------------------------------------
# add AUS if if in Australia listing region as designated by eBird
if thisSightingDict["country"] in [
"AU", "HM", "CX", "CC", "NF", "AC"
]:
thisSightingDict["regionCodes"].append("AUS")
# ----------------------------------------
# add EUR if if in Europe listing region as designated by eBird
if thisSightingDict["country"] in [
"AL", "AD", "AT", "BY", "BE", "BA", "BG", "HR", "CY", "CZ", "DK",
"EE", "FO", "FI", "FR", "DE", "GI", "GR", "HU", "IS", "IE", "IM",
"IT", "RS", "LV", "LI", "LT", "LU", "MK", "MT", "MD", "MC", "ME",
"NL", "NO", "PL", "PT", "RO", "RU", "SM", "RS", "SK", "SI",
"SE", "CH", "UA", "GB", "VA", "JE"
]:
thisSightingDict["regionCodes"].append("EUR")
# include Spain, but not Canaries
if thisSightingDict["country"] == "ES":
if thisSightingDict["state"] != "ES-CN":
thisSightingDict["regionCodes"].append("EUR")
# include Russia, but exclude Asian regions of Russia
if thisSightingDict["country"] == "RU":
if thisSightingDict["state"] not in [
"RU-YAN", "RU-KHM", "RU-TYU", "RU-OMS", "RU-TOM", "RU-NVS",
"RU-ALT", "RU-KEM", "RU-AL", "RU-KK", "RU-KYA", "RU-TY",
"RU-IRK", "RU-SA", "RU-BU", "RU-ZAB", "RU-AMU", "RU-KHA",
"RU-YEV", "RU-PRI", "RU-MAG", "RU-CHU", "RU-KAM", "RU-SAK"
]:
thisSightingDict["regionCodes"].append("EUR")
# include European areas of Turkey
if thisSightingDict["state"] in ["TR-22", "TR-39", "TR-59"]:
thisSightingDict["regionCodes"].append("EUR")
# include European areas of Kazakhstan
if thisSightingDict["state"] in ["KZ-ATY", "KZ-ZAP"]:
thisSightingDict["regionCodes"].append("EUR")
# ----------------------------------------
# add NAM if if in North America listing region as designated by eBird
if thisSightingDict["country"] in [
"CA", "PM", "MX", "GT", "SV", "HN", "CR", "PA",
"CU", "HT", "DO", "JM", "KY", "PR", "VG", "VI", "AI",
"MF", "BL", "BQ", "KN", "AG", "MS", "GP", "DM", "BS",
"BB", "GD", "LC", "VC", "BM", "CP", "GL", "NI"
]:
thisSightingDict["regionCodes"].append("NAM")
if thisSightingDict["state"] in [
"CO-SAP"
]:
thisSightingDict["regionCodes"].append("NAM")
if thisSightingDict["country"] == "US":
if thisSightingDict["state"] != "US-HI":
thisSightingDict["regionCodes"].append("NAM")
# ----------------------------------------
# add SAM if if in South America listing region as designated by eBird
if thisSightingDict["country"] in [
"AR", "BO", "BR", "CL", "CO", "FK", "GF",
"GY", "GY", "PY", "PE", "SR", "UY", "VE", "TT", "CW", "AW"
]:
thisSightingDict["regionCodes"].append("SAM")
if thisSightingDict["state"] in [
"BQ-BO"
]:
thisSightingDict["regionCodes"].append("SAM")
if thisSightingDict["country"] == "EC" and thisSightingDict["state"] != "EC-W":
thisSightingDict["regionCodes"].append("SAM")
# ----------------------------------------
# add WIN if if in West Indies listing region as designated by eBird
if thisSightingDict["country"] in [
"AI", "AG", "AW", "BS", "BB", "VG", "KY", "VI"
"CU", "DM", "DO", "GD", "GP", "HT", "JM", "MQ",
"MS", "AN", "PR", "KN", "LC", "VC", "TT", "TC"
]:
thisSightingDict["regionCodes"].append("WIN")
if thisSightingDict["state"] == "CO-SAP":
thisSightingDict["regionCodes"].append("WIN")
# ----------------------------------------
# add CAM if if in Central America listing region as designated by eBird