-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathplot.py
187 lines (166 loc) · 7.5 KB
/
plot.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
"""Plotting module"""
# pylint: disable=C0415
import os
from pathlib import Path
from functools import lru_cache
from time import sleep
import ast
from tqdm import tqdm
import folium
import spacy
from folium.plugins import MarkerCluster
# from geograpy import places
from geopy.geocoders import Nominatim
NER = spacy.load("en_core_web_sm")
class Map:
"""Map that handles plotting"""
def __init__(self, tweets_file_param, dist_dir_param):
self.tweets_file = tweets_file_param
self.geolocator = Nominatim(user_agent="LiveActionMap")
self.map = folium.Map(location=(48.3794, 31.1656), zoom_start=6)
self.dist_file = os.path.join(dist_dir_param, 'map.html')
self.dist_dir = dist_dir_param
Path(self.dist_dir).mkdir(parents=True, exist_ok=True)
def get_places(self):
"""Get places method"""
places = []
with open(self.tweets_file, "r", encoding="utf-8") as input_file:
raw_text = input_file.readlines()
for tweet_data in raw_text:
if "'id':" not in tweet_data:
continue
tweet_data = ast.literal_eval(tweet_data)
tweet = tweet_data['text'].strip()
if tweet:
text = NER(tweet)
for word in text.ents:
if word.label_ in ('GPE', 'LOC'):
# print(word.text,word.label_,end=", ")
places.append({
"place": word.text,
"link": tweet_data['link'],
"tweet": tweet
})
return places
@staticmethod
def _get_cities_and_regions(words):
from geograpy import places
places = places.PlaceContext(words)
places.set_countries()
places.set_regions()
places.set_cities()
return places.cities + places.regions
@lru_cache(maxsize=None)
def _get_geolocation(self, query):
return self.geolocator.geocode(query)
@lru_cache(maxsize=None)
def _get_reverse_geolocation(self, lat, lon):
return self.geolocator.reverse([lat, lon]).raw
def generate_map(self, use_filter=True):
# pylint: disable=R0914, R0912, R0915
"""Generating map"""
marker_cluster = MarkerCluster().add_to(self.map)
places = self.get_places()
if not use_filter:
# TODO `places` is an array of json,
# but the following function expects an array of strings
places = self._get_cities_and_regions(places)
print("Adding markers... (This may take a while)")
with tqdm(sorted(places, key=lambda k: k['place'])) as t_variable:
retry = []
for tweet_place in t_variable:
link = tweet_place['link']
tweet = tweet_place['tweet']
place = tweet_place['place']
place = place.replace("#", "")
if place.lower() == "Ukraine".lower():
continue
t_variable.set_description(f"{place}")
# pylint: disable = W0702
try:
geodata = self._get_geolocation(place)
except:
print("Failed to geolocate", place)
retry.append(tweet_place)
continue
if geodata is not None:
geodata = geodata.raw
location = (geodata["lat"], geodata["lon"])
rev = self._get_reverse_geolocation(
geodata["lat"], geodata["lon"])
summary = tweet[0:100] + "..."
popup = f"{summary}<br><a href={link} target=\"_blank\">Tweet</a>"
if use_filter:
if rev['address']['country_code'] == 'ua':
folium.Marker(location=location,
icon=folium.Icon(color="red", icon="exclamation-sign"),
popup=popup).add_to(marker_cluster)
else:
folium.Marker(location=location,
icon=folium.Icon(color="red", icon="exclamation-sign"),
popup=popup).add_to(marker_cluster)
if retry:
sleep(10)
print("Retrying failed geolocations...")
with tqdm(sorted(retry, key=lambda k: k['place'])) as r_variable:
for tweet_place in r_variable:
link = tweet_place['link']
tweet = tweet_place['tweet']
place = tweet_place['place']
place = place.replace("#", "")
if place.lower() == "Ukraine".lower():
continue
t_variable.set_description(f"{place}")
# pylint: disable = W0702
try:
geodata = self._get_geolocation(place)
except:
continue
if geodata is not None:
geodata = geodata.raw
location = (geodata["lat"], geodata["lon"])
rev = self._get_reverse_geolocation(
geodata["lat"], geodata["lon"])
popup = f"{tweet}<br><a href={link} target=\"_blank\">Tweet</a>"
if use_filter:
if rev['address']['country_code'] == 'ua':
folium.Marker(location=location,
icon=folium.Icon(color="red",
icon="exclamation-sign"),
popup=popup).add_to(marker_cluster)
else:
folium.Marker(location=location,
icon=folium.Icon(color="red",
icon="exclamation-sign"),
popup=popup).add_to(marker_cluster)
def add_borders(self):
"""Add borders"""
import json
import requests
url = (
"https://raw.githubusercontent.com/python-visualization/folium/main/examples/data"
)
style1 = {'fillColor': '#FF00003F', 'color': '#ff0000'}
country_borders = f"{url}/world-countries.json"
geo_json_data = json.loads(requests.get(country_borders).text)
# Add ukraine borders
folium.GeoJson(geo_json_data['features'][165],
style_function=lambda x: style1).add_to(self.map)
def save_map(self):
"""Saving map persistent memory"""
from shutil import copy
copy(os.path.join("template", "main.css"), self.dist_dir)
copy(os.path.join("template", "index.html"), self.dist_dir)
copy(os.path.join("template", "favicon.png"), self.dist_dir)
copy(os.path.join("images", "map.PNG"), self.dist_dir)
self.map.save(self.dist_file)
def __del__(self):
del self.map
del self.geolocator
if __name__ == "__main__":
TWEETS_FILE = "temp/tweets.txt"
DIST_DIR = "dist"
uk = Map(TWEETS_FILE, DIST_DIR)
uk.generate_map()
uk.add_borders()
uk.save_map()