-
Notifications
You must be signed in to change notification settings - Fork 1
/
__main__.py
1910 lines (1818 loc) · 108 KB
/
__main__.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: utf-8 -*-
"""
Tag Maps Clustering
- 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.32"
import io
import logging
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
#from .utils import *
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
#needed for anonymization (Topic Clustering)
import hashlib
#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 decimal import Decimal
#alternative Shapefile module pure Python
#https://github.com/GeospatialPython/pyshp#writing-shapefiles
#import shapefile
##Emojitest
#n = '❤️👨⚕️'
#n = '😍,146'
##print(n.encode("utf-8"))
###n = '👨⚕️' #medical emoji with zero-width joiner (http://www.unicode.org/emoji/charts/emoji-zwj-sequences.html)
#nlist = Utils.extract_emojis(n)
#with open("emojifile.txt", "w", encoding='utf-8') as emojifile:
# emojifile.write("Original: " + n + '\n')
# for xstr in nlist:
# emojifile.write('Emoji Extract: U+%04x' % ord(xstr) + '\n')
# emojifile.write(xstr + '\n')
# for _c in n:
# emojifile.write(str(unicode_name(_c)) + '\n')
# emojifile.write('Each Codepoint: U+%04x' % ord(_c) + '\n')
#initialize global variables for analysis bounds (lat, lng coordinates)
limLatMin = None
limLatMax = None
limLngMin = None
limLngMax = None
abort = False
#definition of global figure for reusing windows
fig1 = None
fig2 = None
fig3 = None
fig4 = None
proceedClusting = False
currentDisplayTag = None
imgRatio = 0
floaterX = 0
floaterY = 0
clusterTreeCuttingDist = 0
topTagsList = []
lastselectionList = []
tnum = 0
tkScalebar = None
cleanedPhotoList = []
def main():
from tagmaps.classes.utils import Utils
from tagmaps.config.config import BaseConfig
######################
####config section####
######################
log = set_logger()
logging.getLogger("fiona.collection").disabled = True
#log_texts_list = []
#def log.info(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)
##args
config = BaseConfig()
config.parse_args()
config.load_filterlists()
#manually filter places or correct lat/lng
SortOutPlaces_file = "00_Config/SortOutPlaces.txt"
CorrectPlaceLatLng_file = "00_Config/CorrectPlaceLatLng.txt"
SortOutPlaces_set = set()
CorrectPlaceLatLng_dict = dict()
SortOutPlaces = False
if os.path.isfile(SortOutPlaces_file):
if config.ignore_stoplists == False:
with open(SortOutPlaces_file, newline='', encoding='utf8') as f:
f.readline()
#placeid
SortOutPlaces_set = set([line.rstrip('\r\n').split(",")[0] for line in f if len(line) > 0])
SortOutPlaces = True
print(f'Loaded {len(SortOutPlaces_set)} stoplist places.')
CorrectPlaces = False
if os.path.isfile(CorrectPlaceLatLng_file):
if config.ignore_place_corrections == False:
with open(CorrectPlaceLatLng_file, newline='', encoding='utf8') as f:
f.readline()
for line in f:
if len(line) > 0:
linesplit = line.rstrip('\r\n').split(",")
if len(linesplit) > 1:
#placeid = #lat,lng
CorrectPlaceLatLng_dict[linesplit[0]] = (linesplit[1],linesplit[2])
CorrectPlaces = True
print(f'Loaded {len(CorrectPlaceLatLng_dict)} place lat/lng corrections.')
###SHAPEFILESTUFF###
if config.shapefile_intersect:
if config.shapefile_path == "":
sys.exit(f'No Shapefile-Path specified. Exiting..')
from shapely.geometry import Polygon
from shapely.geometry import shape
from shapely.geometry import Point
PShape = fiona.open(config.shapefile_path)
######Single Polygon:######
first = PShape.next()
print("Loaded Shapefile with " + str(len(first['geometry']['coordinates'][0])) + " Vertices.") # (GeoJSON format)
shp_geom = shape(first['geometry']) #shape(first)
######Multipolygon:######
#vcount = PShape.next()['geometry']['coordinates'] #needed for count of vertices
#geom = MultiPolygon([shape(pol['geometry']) for pol in PShape])
#shp_geom = geom
#print("Loaded Shapefile with Vertices ", sum([len(poly[0]) for poly in vcount])) # (GeoJSON format)
###END SHAPEFILESTUFF###
if config.tokenize_japanese:
from jNlp.jTokenize import jTokenize
#print(str(config.remove_long_tail))
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 (config.d_source == "fromFlickr_CSV"):
filelist = glob('01_Input/*.txt')
GMTTimetransform = 0
guid_columnNameID = 5 #guid
Sourcecode = 2
quoting_opt = csv.QUOTE_NONE
elif (config.d_source == "fromInstagram_PGlbsnEmoji") or (config.d_source == "fromLBSN") or (config.d_source == "fromLBSN_old"):
filelist = glob('01_Input/*.csv')
guid_columnNameID = 1 #guid
quoting_opt = csv.QUOTE_MINIMAL
elif (config.d_source == "fromSensorData_InfWuerz"):
filelist = glob('01_Input/*.csv')
GMTTimetransform = 0
guid_columnNameID = 1 #guid
Sourcecode = 11
quoting_opt = csv.QUOTE_NONE
else:
sys.exit("Source not supported yet.")
print('\n')
log.info("########## STEP 1 of 6: Data Cleanup ##########")
if (len(filelist) == 0):
sys.exit(f'No *.json/csv/txt files found.')
else:
if config.cluster_tags or config.cluster_emoji:
inputtext = input(f'Files to process: {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()
TotalTagCount_Counter_global = collections.Counter()
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
photoIDHash = set()
LocationsPerUserID_dict = defaultdict(set)
UserLocationTagList_dict = defaultdict(set)
if config.topic_modeling:
UserTopicList_dict = defaultdict(set)
UserPhotoIDS_dict = defaultdict(set)
UserPhotoFirstThumb_dict = defaultdict(str)
UserLocationWordList_dict = defaultdict(set)
UserLocationsFirstPhoto_dict = defaultdict(set)
if config.cluster_emoji:
overallNumOfEmojis_global = collections.Counter()
#UserDict_TagCounters = defaultdict(set)
UserDict_TagCounters_global = defaultdict(set)
#UserIDsPerLocation_dict = defaultdict(set)
#PhotoLocDict = defaultdict(set)
distinctLocations_set = set()
distinctUserLocations_set = set()
count_loc = 0
now = time.time()
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 (config.d_source == "fromInstagram_LocMedia_CSV" or config.d_source == "fromLBSN" or config.d_source == "fromLBSN_old" or config.d_source == "fromInstagram_UserMedia_CSV" or config.d_source == "fromFlickr_CSV" or config.d_source == "fromInstagram_PGlbsnEmoji" or config.d_source == "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 (config.d_source == "fromInstagram_HashMedia_JSON"):
photolist = photolist + json.loads(f.read())
#PhotosPerDayLists = defaultdict(list)
#keyCreatedHash = set()
for item in photolist:
#duplicate check based on GUID
if item[guid_columnNameID] in photoIDHash:
skippedCount += 1
continue
else:
photoIDHash.add(item[guid_columnNameID])
if (config.d_source == "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 config.shapefile_intersect:
#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 config.d_source == "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 config.shapefile_intersect:
#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 config.d_source == "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 config.cluster_tags or config.topic_modeling:
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 = Utils.filterTags(photo_tags,config.sort_out_always_set,config.sort_out_always_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 (config.d_source == "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 config.shapefile_intersect:
#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 config.d_source == "fromInstagram_PGlbsnEmoji":
if len(item) < 15:
#skip
skippedCount += 1
continue
else:
photo_source = item[0]
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 = Utils.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 config.d_source == "fromLBSN":
if len(item) < 15:
#skip
skippedCount += 1
continue
else:
photo_source = item[0] #LocMediaCode
photo_guid = item[1] #guid
photo_userid = item[4] #guid
photo_owner = ""#item[1] ##!!!
photo_shortcode = None#item[18]
photo_uploadDate = item[6] #guid
photo_idDate = None#photo_uploadDate #use upload date as sorting ID
#Process Spatial Query first (if skipping necessary)
if SortOutPlaces:
if not item[19] == "":
if item[19] in SortOutPlaces_set:
skippedCount += 1
continue
if item[2] == "" or item[3] == "":
count_non_geotagged += 1
continue #skip non-geotagged medias
else:
if CorrectPlaces and not item[19] and item[19] in CorrectPlaceLatLng_dict:
photo_latitude = Decimal(CorrectPlaceLatLng_dict[item[19]][0]) #correct lat/lng
photo_longitude = Decimal(CorrectPlaceLatLng_dict[item[19]][1]) #correct lat/lng
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
#assign lat/lng coordinates from dict
if config.shapefile_intersect:
#skip all outside shapefile
if photo_locID in shapeFileExcludelocIDhash:
skippedCount += 1
continue
if not photo_locID in shapeFileIncludedlocIDhash:
LngLatPoint = Point(photo_longitude, photo_latitude)
if not LngLatPoint.within(shp_geom):
skippedCount += 1
shapeFileExcludelocIDhash.add(photo_locID)
continue
else:
shapeFileIncludedlocIDhash.add(photo_locID)
if config.cluster_tags or config.cluster_emoji or config.topic_modeling:
photo_caption = item[14]
else:
photo_caption = ""
photo_likes = 0
if not item[9] == "":
try:
photo_likes = int(item[9])
except TypeError:
pass
photo_tags = set()
if config.cluster_tags or config.topic_modeling:
photo_tags = set(filter(None, item[11].lower().split(";"))) #[1:-1] removes curly brackets, second [1:-1] removes quotes
#Filter tags based on two stoplists
if config.ignore_stoplists:
count_tags = len(photo_tags)
count_skipped = 0
else:
photo_tags,count_tags,count_skipped = Utils.filterTags(photo_tags,config.sort_out_always_set,config.sort_out_always_instr_set)
count_tags_global += count_tags
count_tags_skipped += count_skipped
if config.cluster_emoji:
emojis_filtered = set(Utils.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
#empty for Instagram:
photo_mTags = ""
photo_dateTaken = ""
photo_views = 0
if not item[8] == "":
try:
photo_views = int(item[8])
except TypeError:
pass
elif config.d_source == "fromLBSN_old":
if len(item) < 15:
#skip
skippedCount += 1
continue
else:
photo_source = item[0] #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
#Process Spatial Query first (if skipping necessary)
if SortOutPlaces:
if not item[4] == "":
if item[4] in SortOutPlaces_set:
skippedCount += 1
continue
if item[2] == "" or item[3] == "":
count_non_geotagged += 1
continue #skip non-geotagged medias
else:
if CorrectPlaces and not item[4] and item[4] in CorrectPlaceLatLng_dict:
photo_latitude = Decimal(CorrectPlaceLatLng_dict[item[4]][0]) #correct lat/lng
photo_longitude = Decimal(CorrectPlaceLatLng_dict[item[4]][1]) #correct lat/lng
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
#assign lat/lng coordinates from dict
if config.shapefile_intersect:
#skip all outside shapefile
if photo_locID in shapeFileExcludelocIDhash:
skippedCount += 1
continue
if not photo_locID in shapeFileIncludedlocIDhash:
LngLatPoint = Point(photo_longitude, photo_latitude)
if not LngLatPoint.within(shp_geom):
skippedCount += 1
shapeFileExcludelocIDhash.add(photo_locID)
continue
else:
shapeFileIncludedlocIDhash.add(photo_locID)
if config.cluster_tags or config.cluster_emoji or config.topic_modeling:
photo_caption = item[9]
else:
photo_caption = ""
photo_likes = 0
if not item[9] == "":
try:
photo_likes = int(item[13])
except TypeError:
pass
except ValueError:
pass
photo_tags = set()
if config.cluster_tags or config.topic_modeling:
photo_tags = set(filter(None, item[11].strip('"').lstrip('{').rstrip('}').lower().split(","))) #[1:-1] removes curly brackets, second [1:-1] removes quotes
#Filter tags based on two stoplists
if config.ignore_stoplists:
count_tags = len(photo_tags)
count_skipped = 0
else:
photo_tags,count_tags,count_skipped = Utils.filterTags(photo_tags,config.sort_out_always_set,config.sort_out_always_instr_set)
count_tags_global += count_tags
count_tags_skipped += count_skipped
if config.cluster_emoji:
emojis_filtered = set(Utils.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
#empty for Instagram:
photo_mTags = ""
photo_dateTaken = ""
photo_views = 0
#if not item[8] == "":
# try:
# photo_views = int(item[8])
# except TypeError:
# pass
elif config.d_source == "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 config.sort_out_always_set
if tag.isdigit() or tag in config.sort_out_always_set:
count_tags_skipped += 1
continue
for inStr in config.sort_out_always_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)
#print(f'Added: {photo_locID} to distinctLocations_set (len: {len(distinctLocations_set)})')
distinctUserLocations_set.add(photo_locIDUserID)
#print(f'Added: {photo_locIDUserID} to distinctUserLocations_set (len: {len(distinctUserLocations_set)})')
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 config.tokenize_japanese:
wordlist = [word for word in jTokenize(input_sentence) for input_sentence in removeSpecialChars.split(' ')]
else:
wordlist = [word for word in removeSpecialChars.lower().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
TotalTagCount_Counter_global.update(photo_tags)
msg = f'Cleaned output to {len(distinctLocations_set):02d} distinct locations from {count_glob:02d} photos (File {partcount} of {len(filelist)}) - Skipped Media: {skippedCount} - Skipped Tags: {count_tags_skipped} of {count_tags_global}'
print(msg, end='\r')
#else:
# #Append last message directly to log file
# log.propagate = False
# log.info(msg)
# log.propagate = True
total_distinct_locations = len(distinctLocations_set)
log.info(f'\nTotal users: {len(LocationsPerUserID_dict)} (UC)')
log.info(f'Total photos: {count_glob:02d} (PC)')
log.info(f'Total tags (PTC): {count_tags_global}')
log.info(f'Total emojis (PEC): {count_emojis_global}')
log.info(f'Total user photo locations (UPL): {len(distinctUserLocations_set)}')
#boundary:
log.info(f'Bounds are: Min {float(limLngMin)} {float(limLatMin)} Max {float(limLngMax)} {float(limLatMax)}')
#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
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 config.write_cleaned_data:
###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 config.topic_modeling:
if not len(cleanedPhotoLocation.photo_tags) == 0:
UserTopicList_dict[user_key] |= cleanedPhotoLocation.photo_tags
UserTopicList_dict[user_key] |= cleanedPhotoLocation.photo_caption #also use descriptions for Topic Modeling
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 config.topic_modeling:
#export list of cleaned topics on a per user basis for LDA/TSNE etc.
with open("02_Output/Output_usertopics_anonymized.csv", 'w', encoding='utf8') as csvfile:
csvfile.write("TOPICS,PhotoIDs,UserID" + '\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([hashlib.sha3_256(photoid.encode("utf8")).hexdigest() for photoid in UserPhotoIDS_dict.get(user_key,None)]) + "}",hashlib.sha3_256(user_key.encode("utf8")).hexdigest()])
with open("02_Output/Output_usertopics.csv", 'w', encoding='utf8') as csvfile:
csvfile.write("TOPICS,PhotoIDs,UserID" + '\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)) + "}",str(user_key)])
if (config.cluster_tags or config.cluster_emoji):
log.info("########## 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)
global topTagsList
log.info(f"Total unique tags: {len(overallNumOfUsersPerTag_global)}")
topTagsList = overallNumOfUsersPerTag_global.most_common(tmax)
#remove all tags that are used by less than x {config.limit_bottom_user_count} photographers
if config.remove_long_tail is True:
indexMin = next((i for i, (t1, t2) in enumerate(topTagsList) if t2 < config.limit_bottom_user_count), None)
if indexMin:
lenBefore = len(topTagsList)
del topTagsList[indexMin:]
lenAfter = len(topTagsList)
tmax = lenAfter
if not lenBefore == lenAfter:
log.info(f'Long tail removal: Filtered {lenBefore - lenAfter} Tags that were used by less than {config.limit_bottom_user_count} users.')
# Calculate Total Tags for selected topTagsList (Long Tail Stat)
totalTagCount = 0
for tag in topTagsList:
count = TotalTagCount_Counter_global.get(tag[0])
if count:
totalTagCount += count
#print(TotalTagCount_Counter_global.most_common(3))
log.info(f'Total tags count for selected Tags List (Top {tmax}): {totalTagCount}.')
#optional write topemojis to file
globalEmojiSet = {}
if config.cluster_emoji:
topEmojisList = overallNumOfEmojis_global.most_common()
globalEmojiSet = {tuple[0] for tuple in topEmojisList}
if (not len(globalEmojiSet) == 0):
topemojis = ''.join("%s,%i" % v + '\n' for v in topEmojisList)
with open("02_Output/Output_topemojis.txt", 'w', encoding="utf8") as file: #overwrite