-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcoordinates_sandbox.py
393 lines (294 loc) · 9.78 KB
/
coordinates_sandbox.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
# -*- coding: utf-8 -*-
"""coordinates_sandbox.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1qL4oUxKeCUrs84ajTC0fntzvH5_MdiGE
"""
# !pip install google_streetview
import google_streetview.api
# from google.colab import files as FILE
import requests
import os
import re
import json
import torch
from IPython.display import Image
# %cd /content/gdrive/MyDrive
# !git clone https://github.com/ultralytics/yolov5
# %cd yolov5
# !pip install -r requirements.txt
import glob
import sys
# !pip install polyline
import folium
import polyline
# Commented out IPython magic to ensure Python compatibility.
# %pwd
# cd ..
# Commented out IPython magic to ensure Python compatibility.
# %pwd
# !pip install firebase_admin
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
# Fetch the service account key JSON file contents
cred = credentials.Certificate('firebase key/pthl-database-8cb58653e903.json')
# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://pthl-database-default-rtdb.firebaseio.com/'
})
# As an admin, the app has access to read and write all data, regradless of Security Rules
ref = db.reference('restricted_access/secret_document')
# print(ref.get())
# coordinates_start="https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=AIzaSyC9Q1u6PExObkUUWKFDcWlXTf0S34niKTM"
# coordnates_end="https://maps.googleapis.com/maps/api/geocode/json?address=1159+N+Rengstorff+Ave,+Mountain+View,+CA&key=AIzaSyC9Q1u6PExObkUUWKFDcWlXTf0S34niKTM"
def address(add):
s=''
for i in range(len(add)):
if(add[i]==' '):
s=s+'+'
else:
s=s+add[i]
return s
def location(add):
new_add=address(add)
coordinates_start="https://maps.googleapis.com/maps/api/geocode/json?address="+new_add+"&key=AIzaSyC9Q1u6PExObkUUWKFDcWlXTf0S34niKTM"
start=requests.get(url=coordinates_start)
start=start.json()
start=start['results'][0]['geometry']['location']
start_lat=start['lat']
start_lng=start['lng']
return str(start_lat),str(start_lng)
# starting_Add=input("Enter a starting add:")
# destination_Add=input("Enter a destination add:")
# # anand vihar delhi
# # sector 128 noida
# s_lat,s_lng=location(starting_Add)
# d_lat,d_lng=location(destination_Add)
# print(s_lat,s_lng,'\n',d_lat,d_lng)
# #s_lat, s_lng, d_lat, d_lng = str(28.5188852), str(77.3646787 ) , str(28.5384252) , str(77.3346996)
# routes_data
def getroutes(s_lat,s_lng,d_lat,d_lng):
URL = "https://router.project-osrm.org/route/v1/driving/"+s_lng+","+s_lat+";"+d_lng+","+d_lat+"?annotations=nodes&alternatives=3" #lng first
r = requests.get(url = URL)
print(URL)
data = r.json()
print("data")
print(data)
print()
print(s_lat,s_lng)
print()
data = data['routes']
# global routes_data
routes_data = r.json()
# for i in data:
# print(i)
# print(len(data))
num_of_routes = len(data)
routes = []
for i in range(num_of_routes):
routes.append(data[i]['legs'][0]['annotation'])
print(routes,routes_data)
return routes,routes_data
# for i in routes:
# print(i)
# getroutes(s_lat,s_lng,d_lat,d_lng)
ref = db.reference("/Pothole-coordinates/")
snapshot = ref.get()
prev_coordinates = []
for key, val in snapshot.items():
prev_coordinates.append(val)
def find_in_prev(s):
ans = []
for i in prev_coordinates:
if (i.find(s) != -1):
ans.append(i)
return ans
def make_url_body(nodes_array):
url_body = "[out:json];("
url_bodytail = ");(._;>;);out;"
for i in nodes_array:
url_body += "node(" + str(i) + ");"
return url_body + url_bodytail
# URL = "https://overpass-api.de/api/interpreter/"
# coordinates = []
# prev_count = []
# for i in routes:
# param = make_url_body(i['nodes'])
# # print(param)
# r = requests.post(url = URL, data = param)
# data = r.json()
# data = data['elements']
# curr_coordinates = []
# curr_prev_count = 0
# i_lat = 0
# i_lon = 0
# for j in data:
# i_lat = j['lat']
# i_lon = j['lon']
# s = str(i_lat) + "," + str(i_lon)
# ans = find_in_prev(s)
# if(not ans):
# curr_coordinates.append(s)
# else:
# pthlcnt = int(ans[0][ans[0].find('"count":') + 9 : ans[0].find('}')])
# curr_prev_count = curr_prev_count + pthlcnt
# coordinates.append(curr_coordinates)
# prev_count.append(curr_prev_count)
# #print(len(coordinates[0]))
# print(len(coordinates[0]))
# print(prev_count[0])
# gsv_path = r"/gsv_images/"
# if not os.path.exists(gsv_path):
# os.makedirs(gsv_path)
# gsv_files = list(glob.glob(gsv_path + "*"))
# gsv_files_len = len(gsv_files)
# k = gsv_files_len + 1
# for i in range(len(coordinates)):
# api_list=[]
# image_links = []
# api_results=[]
# n = len(coordinates[i])
# for j in range(n):
# params = {
# 'size': '600x600', # max 640x640 pixels
# 'location': coordinates[i][j],
# 'heading': '45;90;-90', #indicates the compass heading of the camera. Accepted values are from 0 to 360
# 'pitch': '-0.76', #(default is 0) specifies the up or down angle of the camera relative to the Street View vehicle.
# 'key': 'AIzaSyC9Q1u6PExObkUUWKFDcWlXTf0S34niKTM',
# 'return_error_code': 'true'
# }
# api = google_streetview.helpers.api_list(params)
# api_list.append(api)
# for j in range(n):
# api_result = google_streetview.api.results(api_list[j])
# api_results.append(api_result)
# for j in range(n):
# link = api_results[j].links
# image_links.append(link)
# for j in range(n):
# req = requests.get(image_links[j][0])
# if (req.status_code == 200):
# img_data = req.content
# if not os.path.exists('/gsv_images/gsv'+str(k)+'/'):
# os.makedirs('/gsv_images/gsv'+str(k)+'/')
# with open('/gsv_images/gsv'+str(k)+'/google_view_image_GA' + str(j)+ '-co-'+ str(coordinates[i][j]) + '.jpeg', 'wb+') as handler:
# handler.write(img_data)
# k = k + 1
# k = gsv_files_len + 1
# for i in range(len(coordinates)):
# if os.path.exists('/gsv_images/gsv'+str(k)+'/'):
# !python C:/Users/aditr/Downloads/Major_trial/yolov5/detect.py --weights C:/Users/aditr/Downloads/Major_trial/yolov5/runs/train/exp8/weights/best.pt --img 600 --conf 0.25 --source {"/gsv_images/gsv"+str(k)+"/"} --save-txt
# k = k + 1
# print(gsv_files_len)
def log_coordinates(di):
ref = db.reference("/Pothole-coordinates/")
json_obj = json.dumps(di)
ref.push(json_obj)
return 0
def get_pothole_count(basepath):
x = 0
basepath = basepath + r"/labels/"
for i in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath, i)):
with open(os.path.join(basepath, i), 'r') as fp:
q = len(fp.readlines())
x = x + q
if(q > 0):
start_idx= i.find("-co-") + 4
end_idx = i.find(".txt")
pthls = i[start_idx : end_idx]
pthl_dict = {'coordinates': pthls,
'count': q
}
log_coordinates(pthl_dict)
return x
def find_in_list(li, itm):
ans = False
for i in li:
if(itm == i):
ans = True
return ans
def push_no_pothole(basepath):
labels = []
labelpath = basepath + r"/labels/"
for i in os.listdir(labelpath):
if os.path.isfile(os.path.join(labelpath, i)):
with open(os.path.join(labelpath, i), 'r') as fp:
q = len(fp.readlines())
if(q > 0):
end_idx = i.find(".txt")
i_name = i[:end_idx]
i_name = i_name + r'.jpeg'
labels.append(i_name)
#print(labels)
for i in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath, i)):
if(not find_in_list(labels,i)):
start_idx= i.find("-co-") + 4
end_idx = i.find(".jpeg")
pthls = i[start_idx : end_idx]
pthl_dict = {'coordinates': pthls,
'count': 0
}
log_coordinates(pthl_dict)
# basepath = r"yolov5/runs/detect/"
# files = list(glob.glob(basepath + "*"))
# #files.sort(key = os.path.getctime)
# files = files[::-1]
# print(len(files))
# j = 0
# potholes_in_route = []
# for i in range(len(coordinates)):
# print(files[j])
# s = get_pothole_count(files[j])
# push_no_pothole(files[j])
# s = s + prev_count[i]
# potholes_in_route.append(s)
# j = j + 1
# potholes_in_route = potholes_in_route[::-1]
# for i in potholes_in_route:
# print(i)
# min = sys.maxsize
# min_index = -1
# for i in range(len(potholes_in_route)):
# if potholes_in_route[i]<min:
# min = potholes_in_route[i]
# min_index = i
# best_route = routes_data['routes'][min_index]['geometry']
def get_route(given_route,s_lat,s_lng,d_lat,d_lng,min_index,routes_data):
routes = polyline.decode(given_route)
start_point = [float(s_lat), float(s_lng)]
end_point = [float(d_lat),float(d_lng)]
distance = routes_data['routes'][min_index]['distance']
out = {
'route':routes,
'start_point':start_point,
'end_point':end_point,
'distance':distance
}
# out_json = json.dumps(out)
# return out_json
print(routes)
return out
def get_map(route):
m = folium.Map(location=[(route['start_point'][0] + route['end_point'][0])/2,(route['start_point'][1] + route['end_point'][1])/2],
zoom_start=11)
folium.PolyLine(
route['route'],
weight=8,
color='blue',
opacity=0.6
).add_to(m)
folium.Marker(
location=route['start_point'],
icon=folium.Icon(icon='play', color='green')
).add_to(m)
folium.Marker(
location=route['end_point'],
icon=folium.Icon(icon='stop', color='red')
).add_to(m)
m.save('templates/map.html')
return m
# get_map(get_route(best_route))
# x = get_map(get_route(best_route))