-
Notifications
You must be signed in to change notification settings - Fork 1
/
generateTagClusters.py
1713 lines (1637 loc) · 92.3 KB
/
generateTagClusters.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf8
# generateTagClusters
from nt import abort
"""
generateTagClusters.py
- will read in geotagged (lat/lng) decimal degree point data
- will generate HDBSCAN Cluster Hierarchy
- will output Alpha Shapes/Delauney for cluster cut at specific distance
"""
__author__ = "Alexander Dunkel"
__license__ = "GNU GPLv3"
__version__ = "0.9.1"
import csv
import os
os.system('mode con: cols=197 lines=40')
import sys
import re
from glob import glob
from _csv import QUOTE_MINIMAL
from collections import defaultdict
from collections import Counter
from collections import namedtuple
import collections
import tkinter as tk
from tkinter.messagebox import showerror
import tkinter.messagebox
import def_functions
import datetime
import warnings
from unicodedata import name as unicode_name
#Cluster stuff
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
plt.ion() #enable interactive mode for pyplot (not necessary?!)
import seaborn as sns
import sklearn.datasets as data
import pandas as pd
import hdbscan
from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)
import time
from time import sleep
import copy
#enable for map display
#from mpl_toolkits.basemap import Basemap
#from PIL import Image
import fiona #Fiona needed for reading Shapefile
from fiona.crs import from_epsg
import shapely.geometry as geometry
import pyproj #import Proj, transform
#https://gis.stackexchange.com/questions/127427/transforming-shapely-polygon-and-multipolygon-objects
from shapely.ops import transform
#from shapely.geometry import Polygon
#from shapely.geometry import shape
#from shapely.geometry import Point
from decimal import Decimal
#alternative Shapefile module pure Python
#https://github.com/GeospatialPython/pyshp#writing-shapefiles
#import shapefile
######################
####config section####
######################
log_file = "02_Output/log.txt"
log_texts_list = []
def print_store_log(text,end=None):
if end is None:
addEnd = False
end = '\n'
else:
addEnd = True
#watch out for non-printable characters in console
try:
print(text,end=end)
except UnicodeEncodeError:
print("#".join(re.findall("[a-zA-Z]+", text)))
log_texts_list.append(text + end)
##Load Filterlists
SortOutAlways_file = "00_Config/SortOutAlways.txt"
SortOutAlways_inStr_file = "00_Config/SortOutAlways_inStr.txt"
SortOutAlways_set = set()
SortOutAlways_inStr_set = set()
if not os.path.isfile(SortOutAlways_file):
print(f'{SortOutAlways_file} not found.')
#else read logfile
else:
with open(SortOutAlways_file, newline='', encoding='utf8') as f: #read each unsorted file and sort lines based on datetime (as string)
SortOutAlways_set = set([line.lower().rstrip('\r\n') for line in f])
print(f'Loaded {len(SortOutAlways_set)} stoplist items.')
if not os.path.isfile(SortOutAlways_inStr_file):
print(f'{SortOutAlways_inStr_file} not found.')
#else read logfile
else:
with open(SortOutAlways_inStr_file, newline='', encoding='utf8') as f: #read each unsorted file and sort lines based on datetime (as string)
SortOutAlways_inStr_set = set([line.lower().rstrip('\r\n') for line in f])
print(f'Loaded {len(SortOutAlways_inStr_set)} inStr stoplist items.')
writeGISCompLine = True # writes placeholder entry after headerline for avoiding GIS import format issues
#Choose one of four options for Input data type:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', "--source", default= "fromFlickr_CSV") # naming it "source"
parser.add_argument('-r', "--removeLongTail", type=def_functions.str2bool, nargs='?', const=True,default= True)
parser.add_argument('-e', "--EPSG")
parser.add_argument('-t', "--clusterTags", type=def_functions.str2bool, nargs='?', const=True,default= True)
parser.add_argument('-p', "--clusterPhotos", type=def_functions.str2bool, nargs='?', const=True,default= True)
parser.add_argument('-c', "--localSaturationCheck", type=def_functions.str2bool, nargs='?', const=True, default= False)
parser.add_argument('-j', "--tokenizeJapanese", type=def_functions.str2bool, nargs='?', const=True, default= False)
parser.add_argument('-o', "--clusterEmojis", type=def_functions.str2bool, nargs='?', const=True, default= False)
parser.add_argument('-m', "--topicModeling", type=def_functions.str2bool, nargs='?', const=True, default= False)
parser.add_argument('-w', "--writeCleanedData", type=def_functions.str2bool, nargs='?', const=True, default= True)
args = parser.parse_args() # returns data from the options specified (source)
DSource = args.source
clusterTags = args.clusterTags
clusterPhotos = args.clusterPhotos
removeLongTail = args.removeLongTail
clusterEmojis = args.clusterEmojis
topicModeling = args.topicModeling
writeCleanedData = args.writeCleanedData
localSaturationCheck = args.localSaturationCheck
if args.EPSG is None:
overrideCRS = None
else:
#try loading Custom CRS at beginning
crs_proj = pyproj.Proj(init='epsg:{0}'.format(overrideCRS))
print("Custom CRS set: " + str(crs_proj.srs))
epsg_code = overrideCRS
tokenizeJapanese = args.tokenizeJapanese
if tokenizeJapanese:
from jNlp.jTokenize import jTokenize
#print(str(removeLongTail))
pathname = os.getcwd()
if not os.path.exists(pathname + '/02_Output/'):
os.makedirs(pathname + '/02_Output/')
print("Folder /02_Output was created")
#if not os.path.exists(pathname + '/Output/ClusterImg/'):
# os.makedirs(pathname + '/Output/ClusterImg/')
# print("Folder /Output/ClusterImg/ was created")
# READ All JSON in Current Folder and join to list
#partnum = 0
guid_list = set() #global list of guids
count_glob = 0
partcount = 0
#filenameprev = ""
if (DSource == "fromFlickr_CSV"):
filelist = glob('01_Input/*.txt')
timestamp_columnNameID = 8 #DateTaken
GMTTimetransform = 0
guid_columnNameID = 5 #guid
Sourcecode = 2
quoting_opt = csv.QUOTE_NONE
elif (DSource == "fromInstagram_PGlbsnEmoji") or (DSource == "fromLBSN"):
filelist = glob('01_Input/*.csv')
timestamp_columnNameID = 7 #DateTaken
GMTTimetransform = 0
guid_columnNameID = 2 #guid
Sourcecode = 1
quoting_opt = csv.QUOTE_ALL
elif (DSource == "fromSensorData_InfWuerz"):
filelist = glob('01_Input/*.csv')
timestamp_columnNameID = 2 #DateTaken
GMTTimetransform = 0
guid_columnNameID = 1 #guid
Sourcecode = 11
quoting_opt = csv.QUOTE_NONE
else:
sys.exit("Source not supported yet.")
print('\n')
print_store_log("########## STEP 1 of 6: Data Cleanup ##########")
if (len(filelist) == 0):
sys.exit("No *.json/csv/txt files found.")
else:
if clusterTags or clusterEmojis:
inputtext = input("Files to process: " + str(len(filelist)) + ". \nOptional: Enter a Number for the variety of Tags to process (Default is 1000)\nPress Enter to proceed.. \n")
if inputtext == "" or not inputtext.isdigit():
tmax = 1000
else:
tmax = int(inputtext)
skippedCount = 0
appendToAlreadyExist = False
count_non_geotagged = 0
count_outside_shape = 0
count_tags_global = 0
count_emojis_global = 0
count_tags_skipped = 0
shapeFileExcludelocIDhash = set()
shapeFileIncludedlocIDhash = set()
#initialize global variables for analysis bounds (lat, lng coordinates)
limLatMin = None
limLatMax = None
limLngMin = None
limLngMax = None
def setLatLngBounds(Lat,Lng):
global limLatMin, limLatMax, limLngMin, limLngMax
if limLatMin is None or (Lat < limLatMin and not Lat == 0):
limLatMin = Lat
if limLatMax is None or (Lat > limLatMax and not Lat == 0):
limLatMax = Lat
if limLngMin is None or (Lng < limLngMin and not Lng == 0):
limLngMin = Lng
if limLngMax is None or (Lng > limLngMax and not Lng == 0):
limLngMax = Lng
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
LocationsPerUserID_dict = defaultdict(set)
UserLocationTagList_dict = defaultdict(set)
if topicModeling:
UserTopicList_dict = defaultdict(set)
UserPhotoIDS_dict = defaultdict(set)
UserPhotoFirstThumb_dict = defaultdict(str)
UserLocationWordList_dict = defaultdict(set)
UserLocationsFirstPhoto_dict = defaultdict(set)
if clusterEmojis:
overallNumOfEmojis_global = collections.Counter()
#UserDict_TagCounters = defaultdict(set)
UserDict_TagCounters_global = defaultdict(set)
#UserIDsPerLocation_dict = defaultdict(set)
#PhotoLocDict = defaultdict(set)
distinctLocations_set = set()
count_loc = 0
for file_name in filelist:
#filename = "02_Output/" + os.path.basename(file_name)
#with open(filename, 'a', encoding='utf8') as file:
# file.write("ID_Date,SOURCE,Latitude,Longitude,PhotoID,Owner,UserID,Name,URL,DateTaken,UploadDate,Views,Tags,MTags,Likes,Comments,Shortcode,Type,LocName,LocID" + '\n')
# file.write('"2000-01-01 00:00:00","TESTLINE","43.2544706","28.023467","24PHOTOID3534","testowner","812643S9812644","testcaption","https://scontent.cdninstagram.com/t/s640x640/22344798_1757535311005731_6649353052090269696_n.jpg","2000-01-01 00:00:00","2000-01-01 00:00:00","22",";blacksea;romania;ig;seaside;mareaneagra;travel;getfit;trip;travelog;sun;beachy;avenit;mytinyatlas;islandhopping;flashesofdelight;beachvibes;beautiful;waves;barbershop;sea;love;photooftheday;picoftheday;vsco;vscocam;snapshot;instatravel;instamood;ich;io;summer;photography;europa;happy;end;je;lacrusesc;contrejour;chiaroscuro;morninsunshine;treadmill;gainz;workout;sunshine;getstrong;eu;rumunsko;calatoriecupasiune;superduper;selfie;lazyday;","TESTMTAG","50","25","BaE5OZpgfRu","Image","Sunshine Boulevard Sunshine Boulevard Sunshine Bou","821648SS21642"' +'\n')
photolist = [] # clear photolist for every file
##f_count += 1
##if f_count > 25:
## break
# guid_list.clear() #duplicate detection only for last 500k items
with open(file_name, newline='', encoding='utf8') as f: # On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller.
partcount += 1
if (DSource == "fromInstagram_LocMedia_CSV" or DSource == "fromLBSN" or DSource == "fromInstagram_UserMedia_CSV" or DSource == "fromFlickr_CSV" or DSource == "fromInstagram_PGlbsnEmoji" or DSource == "fromSensorData_InfWuerz"):
photolist = csv.reader(f, delimiter=',', quotechar='"', quoting=quoting_opt) #QUOTE_NONE is important because media saved from php/Flickr does not contain any " check; only ',' are replaced
next(photolist, None) # skip headerline
elif (DSource == "fromInstagram_HashMedia_JSON"):
photolist = photolist + json.loads(f.read())
#PhotosPerDayLists = defaultdict(list)
#keyCreatedHash = set()
for item in photolist:
if (DSource == "fromInstagram_LocMedia_CSV"):
if len(item) < 15:
#skip
skippedCount += 1
continue
else:
photo_source = Sourcecode #LocamediaCode
photo_guid = item[0] #guid
photo_userid = item[2]
#photo_owner = item[7] ##!!!
photo_shortcode = item[5]
photo_uploadDate = item[3] # format datetime as string
photo_idDate = photo_uploadDate #use upload date as sorting ID
photo_caption = item[7]
photo_likes = item[12]
photo_tags = ";" + item[8] + ";"
photo_thumbnail = item[6]
photo_comments = item[13]
photo_mediatype = item[4]
photo_locID = item[14]
photo_locName = item[1]
#assign lat/lng coordinates from dict
if (photo_locID in loc_dict):
photo_latitude = loc_dict[photo_locID][0]
photo_longitude = loc_dict[photo_locID][1]
#setLatLngBounds(photo_latitude,photo_longitude)
if shapefileIntersect:
#skip all outside shapefile
if photo_locID in shapeFileExcludelocIDhash:
count_outside_shape += 1
continue
if not photo_locID in shapeFileIncludedlocIDhash:
LngLatPoint = Point(photo_longitude, photo_latitude)
if not LngLatPoint.within(shp_geom):
count_outside_shape += 1
shapeFileExcludelocIDhash.add(photo_locID)
continue
else:
shapeFileIncludedlocIDhash.add(photo_locID)
else:
if excludeWhereMissingGeocode:
skippedCount += 1
continue #skip non-geotagged medias
else:
photo_latitude = ""
photo_longitude = ""
#assign usernames from dict
if photo_userid in user_dict:
photo_owner = user_dict[photo_userid]
elif photo_userid in netlytics_usernameid_dict:
photo_owner = netlytics_usernameid_dict[photo_userid]
else:
photo_owner = ""
#empty for instagram:
photo_mTags = ""
photo_dateTaken = ""
photo_views = ""
elif DSource == "fromInstagram_UserMedia_CSV":
if len(item) < 15:
#skip
skippedCount += 1
continue
else:
photo_source = Sourcecode #LocMediaCode
photo_guid = item[0].split("_")[0] #guid
photo_userid = item[0].split("_")[1] #userid
photo_owner = item[1] ##!!!
photo_shortcode = item[6]
photo_uploadDate = item[4] # format datetime as string
photo_idDate = photo_uploadDate #use upload date as sorting ID
photo_caption = item[8]
photo_likes = item[13]
photo_tags = ";" + item[9] + ";"
photo_thumbnail = item[7]
photo_comments = item[14]
photo_mediatype = item[5]
photo_locID = item[2]
if photo_locID == "":
count_non_geotagged += 1
continue #skip non-geotagged medias
photo_locName = item[3]
#assign lat/lng coordinates from dict
if (photo_locID in loc_dict):
photo_latitude = loc_dict[photo_locID][0]
photo_longitude = loc_dict[photo_locID][1]
if shapefileIntersect:
#skip all outside shapefile
if photo_locID in shapeFileExcludelocIDhash:
count_outside_shape += 1
continue
if not photo_locID in shapeFileIncludedlocIDhash:
LngLatPoint = Point(photo_longitude, photo_latitude)
if not LngLatPoint.within(shp_geom):
count_outside_shape += 1
shapeFileExcludelocIDhash.add(photo_locID)
continue
else:
shapeFileIncludedlocIDhash.add(photo_locID)
else:
if excludeWhereMissingGeocode:
skippedCount += 1
continue #skip non-geotagged medias
else:
photo_latitude = ""
photo_longitude = ""
#empty for Instagram:
photo_mTags = ""
photo_dateTaken = ""
photo_views = ""
elif DSource == "fromFlickr_CSV":
if len(item) < 12:
#skip
skippedCount += 1
continue
else:
photo_source = Sourcecode #LocMediaCode
photo_guid = item[5] #photoID
photo_userid = item[7] #userid
photo_owner = item[6] ##!!!
photo_shortcode = ""
photo_uploadDate = datetime.datetime.strptime(item[9],'%m/%d/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S') # format datetime as string
photo_dateTaken = datetime.datetime.strptime(item[8] ,'%m/%d/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
photo_idDate = photo_dateTaken #use date taken date as sorting ID
photo_caption = item[3]
photo_likes = ""
#Filter tags based on two stoplists
if clusterTags or topicModeling:
photo_tags = set(filter(None, item[11].lower().split(";"))) #filter empty strings from photo_tags list and convert to set (hash) with unique values
#Filter tags based on two stoplists
photo_tags, count_tags, count_skipped = def_functions.filterTags(photo_tags,SortOutAlways_set,SortOutAlways_inStr_set)
count_tags_global += count_tags
count_tags_skipped += count_skipped
else:
photo_tags = set()
#if not "water" in photo_tags:
# continue
photo_thumbnail = item[4]
photo_comments = ""
photo_mediatype = ""
photo_locName = ""
if is_number(item[1]):
photo_latitude = Decimal(item[1])
else:
skippedCount += 1
continue
if is_number(item[2]):
photo_longitude = Decimal(item[2])
else:
skippedCount += 1
continue
setLatLngBounds(photo_latitude,photo_longitude)
photo_locID = str(photo_latitude) + ':' + str(photo_longitude) #create loc_id from lat/lng
photo_mTags = "" #not used currently but available
photo_views = item[10]
elif (DSource == "fromInstagram_HashMedia_JSON"):
photo_source = Sourcecode #HashMediaCode
if item.get('owner'):
photo_userid = item["owner"]["id"]
else:
# skip problematic entries
skippedCount += 1
continue
if item.get('edge_liked_by'):
photo_likes = item["edge_liked_by"]["count"]
else:
photo_likes = ""
if item.get('edge_media_to_caption') and not len(item.get("edge_media_to_caption", {}).get("edges")) == 0:
photo_caption = item["edge_media_to_caption"]["edges"][0]["node"]["text"].replace('\n', ' ').replace('\r', '')
else:
photo_caption = ""
if item.get('edge_media_to_comment'):
photo_comments = item["edge_media_to_comment"]["count"]
else:
photo_comments = ""
if item.get('id'):
photo_guid = item["id"]
else:
# skip problematic entries
skippedCount += 1
continue
if item.get('is_video'):
photo_mediatype = "video"
else:
photo_mediatype = "image"
if item.get('location'):
photo_locID = item["location"]["id"]
photo_locName = item["location"]["name"]
else:
# skip non geotagged
count_non_geotagged += 1
continue
if item.get('shortcode'):
photo_shortcode = item["shortcode"]
else:
photo_shortcode = ""
if item.get('tags'):
photo_tags =';'.join(item["tags"]).replace('\n', ' ').replace('\r', '')
photo_tags = ";%s;" % (photo_tags.replace(",", ";"))
else:
photo_tags = ""
if item.get('taken_at_timestamp'):
pdate = datetime.datetime.fromtimestamp(int(item["taken_at_timestamp"])) + timedelta(hours = GMTTimetransform) #GMT conversion
photo_uploadDate = pdate.strftime('%Y-%m-%d %H:%M:%S') # format datetime as string
photo_idDate = photo_uploadDate
else:
# skip problematic entries
skippedCount += 1
continue
if item.get('thumbnail_src'):
photo_thumbnail = item["thumbnail_src"]
else:
photo_thumbnail = ""
#assign lat/lng coordinates from dict
if (photo_locID in loc_dict):
photo_latitude = loc_dict[photo_locID][0]
photo_longitude = loc_dict[photo_locID][1]
if shapefileIntersect:
#skip all outside shapefile
if photo_locID in shapeFileExcludelocIDhash:
count_outside_shape += 1
continue
if not photo_locID in shapeFileIncludedlocIDhash:
LngLatPoint = Point(photo_longitude, photo_latitude)
if not LngLatPoint.within(shp_geom):
count_outside_shape += 1
shapeFileExcludelocIDhash.add(photo_locID)
continue
else:
shapeFileIncludedlocIDhash.add(photo_locID)
else:
if excludeWhereMissingGeocode:
#count_non_geotagged += 1
skippedCount += 1
continue #skip non-geotagged medias
else:
photo_latitude = ""
photo_longitude = ""
#assign usernames from dict
if photo_userid in user_dict:
photo_owner = user_dict[photo_userid]
elif photo_userid in netlytics_usernameid_dict:
photo_owner = netlytics_usernameid_dict[photo_userid]
else:
photo_owner = ""
#empty for instagram:
photo_mTags = ""
photo_dateTaken = ""
photo_views = ""
elif DSource == "fromInstagram_PGlbsnEmoji":
if len(item) < 15:
#skip
skippedCount += 1
continue
else:
photo_source = Sourcecode #LocMediaCode
photo_guid = item[1] #guid
photo_userid = item[7] #guid
photo_owner = ""#item[1] ##!!!
photo_shortcode = item[18]
photo_uploadDate = item[8] #guid
photo_idDate = photo_uploadDate #use upload date as sorting ID
photo_caption = item[9]
photo_likes = item[13]
#photo_tags = ";" + item[11] + ";"
tags_filtered = def_functions.extract_emojis(photo_caption)
if not len(tags_filtered) == 0:
count_tags_global += len(tags_filtered)
photo_tags = set(tags_filtered)
else:
photo_tags = set()
#photo_emojis = extract_emojis(photo_caption)
photo_thumbnail = item[17]
photo_comments = item[14]
photo_mediatype = item[19]
photo_locName = item[4] #guid
if item[2] == "" or item[3] == "":
count_non_geotagged += 1
continue #skip non-geotagged medias
else:
photo_latitude = Decimal(item[2]) #guid
photo_longitude = Decimal(item[3]) #guid
setLatLngBounds(photo_latitude,photo_longitude)
photo_locID = str(photo_latitude) + ':' + str(photo_longitude) #create loc_id from lat/lng
#empty for Instagram:
photo_mTags = ""
photo_dateTaken = ""
photo_views = 0
elif DSource == "fromLBSN":
if len(item) < 15:
#skip
skippedCount += 1
continue
else:
photo_source = Sourcecode #LocMediaCode
photo_guid = item[1] #guid
photo_userid = item[7] #guid
photo_owner = ""#item[1] ##!!!
photo_shortcode = None#item[18]
photo_uploadDate = item[8] #guid
photo_idDate = None#photo_uploadDate #use upload date as sorting ID
if clusterTags or clusterEmojis or topicModeling:
photo_caption = item[9]
else:
photo_caption = ""
photo_likes = None#item[13]
photo_tags = set()
if clusterTags or topicModeling:
photo_tags = set(filter(None, item[11][1:-1].lower().split(","))) #[1:-1] removes curly brackets, second [1:-1] removes quotes
#Filter tags based on two stoplists
photo_tags,count_tags,count_skipped = def_functions.filterTags(photo_tags,SortOutAlways_set,SortOutAlways_inStr_set)
count_tags_global += count_tags
count_tags_skipped += count_skipped
if clusterEmojis:
emojis_filtered = set(def_functions.extract_emojis(photo_caption))
if not len(emojis_filtered) == 0:
count_emojis_global += len(emojis_filtered)
overallNumOfEmojis_global.update(emojis_filtered)
photo_tags = set.union(emojis_filtered)
#photo_tags = ";" + item[11] + ";"
photo_thumbnail = None#item[17]
photo_comments = None#item[14]
photo_mediatype = None#item[19]
photo_locName = item[4] #guid
if item[2] == "" or item[3] == "":
count_non_geotagged += 1
continue #skip non-geotagged medias
else:
photo_latitude = Decimal(item[2]) #guid
photo_longitude = Decimal(item[3]) #guid
setLatLngBounds(photo_latitude,photo_longitude)
photo_locID = str(photo_latitude) + ':' + str(photo_longitude) #create loc_id from lat/lng
#empty for Instagram:
photo_mTags = ""
photo_dateTaken = ""
photo_views = 0
elif DSource == "fromSensorData_InfWuerz":
if len(item) < 5:
#skip
skippedCount += 1
continue
else:
photo_source = Sourcecode #LocMediaCode
photo_guid = item[1] #guid
photo_userid = item[4] #meta_device_id
photo_owner = ""#item[1] ##!!!
photo_shortcode = ""
photo_uploadDate = item[3] #meta_timestamp_received
photo_idDate = item[2] #meta_timestamp_recorded
photo_caption = item[8]
if not len(photo_caption) == 0:
removeSpecialChars = photo_caption.translate ({ord(c): " " for c in "?.!/;:,[]()'-&#"})
wordlist = [word for word in removeSpecialChars.lower().split(' ') if not word == "" and len(word) > 1]
photo_tags = set(wordlist)
else:
photo_tags = set()
photo_tags_filtered = set()
for tag in photo_tags:
count_tags_global += 1
#exclude numbers and those tags that are in SortOutAlways_set
if tag.isdigit() or tag in SortOutAlways_set:
count_tags_skipped += 1
continue
for inStr in SortOutAlways_inStr_set:
if inStr in tag:
count_tags_skipped += 1
break
else:
photo_tags_filtered.add(tag)
photo_tags = photo_tags_filtered
if item[6] == "" or item[7] == "":
count_non_geotagged += 1
continue #skip non-geotagged medias
else:
photo_latitude = Decimal(item[7]) #guid
photo_longitude = Decimal(item[6]) #guid
setLatLngBounds(photo_latitude,photo_longitude)
photo_locID = str(photo_latitude) + ':' + str(photo_longitude) #create loc_id from lat/lng
#empty for SensorWuerz:
photo_likes = ""
photo_thumbnail = ""
photo_comments = ""
photo_mediatype = ""
photo_locName = ""
photo_mTags = ""
photo_dateTaken = ""
photo_views = 0
#this code will union all tags of a single user for each location
#further information is derived from the first image for each user-location
photo_locIDUserID = photo_locID + '::' + str(photo_userid) #create userid_loc_id
distinctLocations_set.add(photo_locID)
if not photo_userid in LocationsPerUserID_dict or not photo_locID in LocationsPerUserID_dict[photo_userid]:
LocationsPerUserID_dict[photo_userid] |= {photo_locID} # Bit wise or and assignment in one step. -> assign locID to UserDict list if not already contained
count_loc += 1
UserLocationsFirstPhoto_dict[photo_locIDUserID] = (photo_source,
photo_guid,
photo_owner,
photo_userid,
photo_caption,
photo_thumbnail,
photo_dateTaken,
photo_uploadDate,
photo_views,
photo_tags,
photo_mTags,
photo_likes,
photo_comments,
photo_shortcode,
photo_mediatype,
photo_locName,
photo_locID)
UserLocationTagList_dict[photo_locIDUserID] |= photo_tags #union tags per userid/unique location
removeSpecialChars = photo_caption.translate ({ord(c): " " for c in "?.!/;:,[]()'-&#"})
if tokenizeJapanese:
wordlist = [word for word in jTokenize(input_sentence) for input_sentence in removeSpecialChars.split(' ')]
else:
wordlist = [word for word in removeSpecialChars.split(' ') if len(word) > 2] #first replace specia characters in caption, then split by space-character
UserLocationWordList_dict[photo_locIDUserID] |= set(wordlist) #union words per userid/unique location
count_glob += 1
##Calculate toplists
if photo_tags:
UserDict_TagCounters_global[photo_userid].update(photo_tags) #add tagcount of this media to overall tagcount or this user, initialize counter for user if not already done
print("Cleaned output to " + "%02d" % (count_loc,) + " photolocations from " + "%02d" % (count_glob,)+ " (File " + str(partcount) + " of " + str(len(filelist)) + ") - Skipped Media: " + str(skippedCount) + " - Skipped Tags: " + str(count_tags_skipped) +" of " + str(count_tags_global), end='\r')
log_texts_list.append("Cleaned output to " + "%02d" % (count_loc,) + " photolocations from " + "%02d" % (count_glob,)+ " (File " + str(partcount) + " of " + str(len(filelist)) + ") - Skipped Media: " + str(skippedCount) + " - Skipped Tags: " + str(count_tags_skipped) +" of " + str(count_tags_global))
total_distinct_locations = len(distinctLocations_set)
print_store_log("\nTotal users: " + str(len(LocationsPerUserID_dict)))
print_store_log("Total photos: " + str(count_glob))
print_store_log("Total distinct locations: " + str(total_distinct_locations))
print_store_log("Total tags: " + str(count_tags_global))
print_store_log("Total emojis: " + str(count_emojis_global))
#boundary:
print_store_log("Bounds are: Min " + str(float(limLngMin)) + " " + str(float(limLatMin)) + " Max " + str(float(limLngMax)) + " " + str(float(limLatMax)))
#cleanedPhotoList = []
#create structure for tuple with naming for easy referencing
cleanedPhotoLocation_tuple = namedtuple('cleanedPhotoLocation_tuple', 'source lat lng photo_guid photo_owner userid photo_caption photo_dateTaken photo_uploadDate photo_views photo_tags photo_thumbnail photo_mTags photo_likes photo_comments photo_shortcode photo_mediatype photo_locName photo_locID')
cleanedPhotoDict = defaultdict(cleanedPhotoLocation_tuple)
with open("02_Output/Output_cleaned.txt", 'w', encoding='utf8') as csvfile:
csvfile.write("SOURCE,Latitude,Longitude,PhotoID,Owner,UserID,Name,DateTaken,UploadDate,Views,Tags,URL,MTags,Likes,Comments,Shortcode,Type,LocName,LocID," + '\n')
datawriter = csv.writer(csvfile, delimiter=',', lineterminator='\n', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
for user_key, locationhash in LocationsPerUserID_dict.items():
for location in locationhash:
locIDUserID = str(location) + '::' + str(user_key)
photo_latlng = location.split(':')
photo = UserLocationsFirstPhoto_dict.get(locIDUserID,(" "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "))
#create tuple with cleaned photo data
cleanedPhotoLocation = cleanedPhotoLocation_tuple(photo[0],#Source = 0
float(photo_latlng[0]), #Lat = 1
float(photo_latlng[1]), #Lng = 2
photo[1],#photo_guid = 3
photo[2],#photo_owner = 4
user_key, #userid = 5
UserLocationWordList_dict.get(locIDUserID,("",)),#photo_caption = 6
photo[6],#photo_dateTaken = 7
photo[7],#photo_uploadDate = 8
int(photo[8]),#photo_views = 9
UserLocationTagList_dict.get(locIDUserID,("",)),#photo_tags = 10
photo[5],#photo_thumbnail = 11
photo[10],#photo_mTags = 12
photo[11],#photo_likes = 13
photo[12],#photo_comments = 14
photo[13],#photo_shortcode = 15
photo[14],#photo_mediatype = 16
photo[15],#photo_locName = 17
photo[16]#photo_locID = 18
)
if writeCleanedData:
###optional Write Cleaned Data to CSV/TXT
datawriter.writerow([cleanedPhotoLocation.source,#Source = 0
cleanedPhotoLocation.lat, #Lat = 1
cleanedPhotoLocation.lng, #Lng = 2
cleanedPhotoLocation.photo_guid,#photo_guid = 3
cleanedPhotoLocation.photo_owner,#photo_owner = 4
cleanedPhotoLocation.userid, #userid = 5
";".join(cleanedPhotoLocation.photo_caption),#photo_caption = 6
cleanedPhotoLocation.photo_dateTaken,#photo_dateTaken = 7
cleanedPhotoLocation.photo_uploadDate,#photo_uploadDate = 8
cleanedPhotoLocation.photo_views,#photo_views = 9
";".join(cleanedPhotoLocation.photo_tags),#photo_tags = 10
cleanedPhotoLocation.photo_thumbnail,#photo_thumbnail = 11
cleanedPhotoLocation.photo_mTags,#photo_mTags = 12
cleanedPhotoLocation.photo_likes,#photo_likes = 13
cleanedPhotoLocation.photo_comments,#photo_comments = 14
cleanedPhotoLocation.photo_shortcode,#photo_shortcode = 15
cleanedPhotoLocation.photo_mediatype,#photo_mediatype = 16
cleanedPhotoLocation.photo_locName,#photo_locName = 17
cleanedPhotoLocation.photo_locID]#photo_locID = 18
)
##optional Write Cleaned Search Terms to CSV for Topic Modeling
#topics = cleanedPhotoLocation.photo_caption.union(cleanedPhotoLocation.photo_tags)
if topicModeling:
if not len(cleanedPhotoLocation.photo_tags) == 0:
UserTopicList_dict[user_key] |= cleanedPhotoLocation.photo_tags
UserPhotoIDS_dict[user_key] |= {cleanedPhotoLocation.photo_guid} # Bit wise or and assignment in one step. -> assign PhotoGuid to UserDict list if not already contained
#UserPhotoFirstThumb_dict[user_key] = photo[5]
cleanedPhotoDict[cleanedPhotoLocation.photo_guid] = cleanedPhotoLocation
if topicModeling:
#export list of cleaned topics on a per user basis for LDA/TSNE etc.
with open("02_Output/Output_usertopics.csv", 'w', encoding='utf8') as csvfile:
csvfile.write("TOPICS,PhotoIDs" + '\n')
datawriter = csv.writer(csvfile, delimiter=',', lineterminator='\n', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
for user_key, topics in UserTopicList_dict.items():
datawriter.writerow([" ".join(topics),"{" + ",".join(UserPhotoIDS_dict.get(user_key,None)) + "}"])
now = time.time()
abort = False
if clusterTags or clusterEmojis:
print_store_log("########## STEP 2 of 6: Tag Ranking ##########")
overallNumOfUsersPerTag_global = collections.Counter()
for user_key, taghash in UserDict_TagCounters_global.items():
#taghash contains unique values (= strings) for each user, thus summing up these taghashes counts each user only once per tag
overallNumOfUsersPerTag_global.update(taghash)
topTagsList = overallNumOfUsersPerTag_global.most_common(tmax)
#remove all tags that are used by less than two photographers
if removeLongTail is True:
indexMin = next((i for i, (t1, t2) in enumerate(topTagsList) if t2 < 2), None)
if indexMin:
lenBefore = len(topTagsList)
del topTagsList[indexMin:]
lenAfter = len(topTagsList)
tmax = lenAfter
if not lenBefore == lenAfter:
print("Filtered " + str(lenBefore - lenAfter) + " Tags that were only used by less than 2 users.")
singleMostUsedtag = topTagsList[0]
if clusterTags:
#optional write toptags to file
toptags = ''.join("%s,%i" % v + '\n' for v in topTagsList)
with open("02_Output/Output_toptags.txt", 'w', encoding="utf8") as file: #overwrite
file.write(toptags)
#optional write topemojis to file
if clusterEmojis:
topEmojisList = overallNumOfEmojis_global.most_common()
globalEmojiSet = {tuple[0] for tuple in topEmojisList}
topemojis = ''.join("%s,%i" % v + '\n' for v in topEmojisList)
with open("02_Output/Output_topemojis.txt", 'w', encoding="utf8") as file: #overwrite
file.write(topemojis)
print_store_log("########## STEP 3 of 6: Tag Location Clustering ##########")
#prepare some variables
tnum = 0
first = True
label_size = 10
#plt.rcParams['xtick.labelsize'] = label_size
#plt.rcParams['ytick.labelsize'] = label_size
plot_kwds = {'alpha' : 0.5, 's' : 10, 'linewidths':0}
sys.stdout.flush()
proceedClusting = False
distY = 0
distX = 0
imgRatio = 0
#Optional: set global plotting bounds
#plt.gca().set_xlim([limXMin, limXMax])
#plt.gca().set_ylim([limYMin, limYMax])
cleanedPhotoList = list(cleanedPhotoDict.values())
df = pd.DataFrame(cleanedPhotoList)
points = df.as_matrix(['lng','lat'])
limYMin,limYMax,limXMin,limXMax = def_functions.getRectangleBounds(points)
bound_points_shapely = geometry.MultiPoint([(limXMin, limYMin), (limXMax, limYMax)])
distYLat = limYMax - limYMin
distXLng = limXMax - limXMin
#distYLat = def_functions.haversine(limXMin,limYMax,limXMin,limYMin)
#distXLng = def_functions.haversine(limXMax,limYMin,limXMin,limYMin)
#imgRatio = distXLng/(distYLat*2)
imgRatio = distXLng/(distYLat*2)
distY = def_functions.haversine(limXMin, limYMin, limXMin, limYMax)
distX = def_functions.haversine(limXMin, limYMin, limXMax, limYMin)
clusterTreeCuttingDist = (min(distX,distY)/100)*7 #4% of research area width/height (max) = default value #223.245922725 #= 0.000035 radians dist
#print("distYLat DDegrees: " + str(limYMax - limYMin) + " distXLng DDegrees: " + str(limXMax - limXMin) + " Bsp:" + str(points[0]))
#print("DDegree Buffer dist: " + str(max(distXLng,distYLat)/200) + " Cluster Dist: " + str(clusterTreeCuttingDist) + " Alpha: " + str(clusterTreeCuttingDist*10))
#input_lon_center = bound_points_shapely.centroid.coords[0][0] #True centroid (coords may be multipoint)
#input_lat_center = bound_points_shapely.centroid.coords[0][1]
#epsg_code = def_functions.convert_wgs_to_utm(input_lon_center, input_lat_center)
#crs_wgs = pyproj.Proj(init='epsg:4326')
#crs_proj = pyproj.Proj(init='epsg:{0}'.format(epsg_code))
#x, y = pyproj.transform(crs_wgs, crs_proj, Decimal(points[0][0]), Decimal(points[0][1]))
#print("distY Meters: " + str(distY) + " distX Meters: " + str(distX) + " Bsp:" + str(x) + " " + str(y))
#print("Meters Buffer dist: " + str(clusterTreeCuttingDist/4) + " Cluster Dist: " + str(clusterTreeCuttingDist) + " Alpha: " + str(clusterTreeCuttingDist*100))
#Tkinter Stuff
#####################################################################################################################################################
#def center(win):
# """
# centers a tkinter window
# :param win: the root or Toplevel window to center
# """
# win.update_idletasks()
# width = win.winfo_width()
# frm_width = win.winfo_rootx() - win.winfo_x()
# win_width = width + 2 * frm_width
# height = win.winfo_height()
# titlebar_height = win.winfo_rooty() - win.winfo_y()
# win_height = height + titlebar_height + frm_width
# x = win.winfo_screenwidth() // 2 - win_width // 2
# y = win.winfo_screenheight() // 2 - win_height // 2
# win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
# win.deiconify()
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.overrideredirect(True) #this is needed to make the root disappear
self.geometry('%dx%d+%d+%d' % (0, 0, 0, 0))
#create separate floating window
self.floater = FloatingWindow(self)
class FloatingWindow(tk.Toplevel):
#global app
def __init__(self, *args, **kwargs):
tk.Toplevel.__init__(self, *args, **kwargs)
self.overrideredirect(True)
self.configure(background='gray7')
#self.label = tk.Label(self, text="Click on the grip to move")
self.grip = tk.Label(self, bitmap="gray25")
self.grip.pack(side="left", fill="y")
#self.label.pack(side="right", fill="both", expand=True)
self.grip.bind("<ButtonPress-1>", self.StartMove)
self.grip.bind("<ButtonRelease-1>", self.StopMove)
self.grip.bind("<B1-Motion>", self.OnMotion)
#center Floating Window
w = self.winfo_reqwidth()
h = self.winfo_reqheight()
ws = self.winfo_screenwidth()
hs = self.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
self.geometry('+%d+%d' % (x, y))
def StartMove(self, event):
self.x = event.x
self.y = event.y
def StopMove(self, event):
self.x = None
self.y = None
def OnMotion(self, event):
deltax = event.x - self.x
deltay = event.y - self.y
x = self.winfo_x() + deltax
y = self.winfo_y() + deltay
self.geometry("+%s+%s" % (x, y))
app = App()
#necessary override for error reporting during tkinter mode
import traceback
def report_callback_exception(self, exc, val, tb):
#exc_type, exc_obj, tb = sys.exc_info()
#f = tb.tb_frame
#lineno = tb.tb_lineno
#filename = f.f_code.co_filename
#linecache.checkcache(filename)
#line = linecache.getline(filename, lineno, f.f_globals)
#showerror("Error",'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj))
showerror("Error", message=str(val))
exc_type, exc_value, exc_traceback = sys.exc_info()
print("*** print_tb:")
traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
print("*** print_exception:")
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=2, file=sys.stdout)
print("*** print_exc:")
traceback.print_exc()
print("*** format_exc, first and last line:")
formatted_lines = traceback.format_exc().splitlines()
print(formatted_lines[0])
print(formatted_lines[-1])
print("*** format_exception:")
print(repr(traceback.format_exception(exc_type, exc_value,
exc_traceback)))
print("*** extract_tb:")
print(repr(traceback.extract_tb(exc_traceback)))
print("*** format_tb:")
print(repr(traceback.format_tb(exc_traceback)))
print("*** tb_lineno:", exc_traceback.tb_lineno)
tk.Tk.report_callback_exception = report_callback_exception
#the following code part is a bit garbled due to using TKinter interface
######################################################################################################################################################
######################################################################################################################################################
######################################################################################################################################################
#definition of global vars for interface and graph design
canvasWidth = 1320
canvasHeight = 440
floaterX = 0
floaterY = 0
#Cluster preparation
sns.set_context('poster')
sns.set_style('white')
#sns.set_color_codes()
#matplotlib.style.use('ggplot')
plt.style.use('ggplot')
graphFrame = None
lastselectionList = []
currentDisplayTag = None
genPreviewMap = tk.IntVar(value = 0)
createMinimumSpanningTree = False
autoselectClusters = False
#definition of global figure for reusing windows
fig1 = None
fig2 = None
fig3 = None
fig4 = None
def quitTkinter():
#exits Tkinter gui and continues with code execution after mainloop()
#global app
#app.floater.destroy()
#tkinter.messagebox.showinfo("Closing App", "Closing App")
#plt.quit()
global abort
abort = True
app.update() #see https://stackoverflow.com/questions/35040168/python-tkinter-error-cant-evoke-event-command
app.destroy()
app.quit() ##root.quit() causes mainloop to exit, see https://stackoverflow.com/questions/2307464/what-is-the-difference-between-root-destroy-and-root-quit
def proceedWithCluster():
global proceedClusting
global fig1
proceedClusting = True
#def vis_tag(tag):
#tkinter.messagebox.showinfo("Proceed", "Proceed")
#if plt.figure(1):
# plt.figure(1).clf()
app.update() #see https://stackoverflow.com/questions/35040168/python-tkinter-error-cant-evoke-event-command