onefan commited on
Commit
b895f32
·
verified ·
1 Parent(s): 6842c6c

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -749
app.py DELETED
@@ -1,749 +0,0 @@
1
- import gradio as gr
2
- import requests
3
- import json
4
- import geopandas as gpd
5
- import pandas as pd
6
- import numpy as np
7
- from shapely import geometry
8
- from shapely.geometry import Point, Polygon
9
- from shapely.geometry import Polygon, MultiPolygon
10
- import time
11
- from tqdm import tqdm
12
- import os
13
- import matplotlib
14
-
15
- import cconv
16
- import geopandas
17
- import contextily as cx
18
- import matplotlib.pyplot as plt
19
- from shapely.affinity import scale
20
-
21
- requests.packages.urllib3.disable_warnings()
22
- from datetime import datetime
23
- import math
24
- import random
25
- import plot_map
26
- import foodlist
27
- import POI_baidu_distribution
28
- import isochrone_get
29
- import seaborn as sns
30
-
31
- plot_map.set_mapboxtoken('pk.eyJ1IjoibGxsMzE5OTciLCJhIjoiY2w4anl6b2k5MGRxbjN4bXB1YzV6c3loaCJ9.ec49ySYxrKQWc5uyNHrzdA')
32
- plot_map.set_imgsavepath(os.getcwd())
33
-
34
- run_count=0
35
- run_count1=0
36
- run_count2=0
37
- run_count3=0
38
- def isochrone(contours_minutes, travel_mode_all, *coordinates_all):
39
- global run_count
40
- run_count += 1
41
- contours_minutes_all = ",".join(contours_minutes)
42
- def coords_trans(*coords):
43
- coords_all_wgs84 = []
44
- for coord_tuple in coords:
45
- for coord in coord_tuple:
46
- if coord:
47
- try:
48
- lng, lat = coord.split(',')
49
- lng_i, lat_i = cconv.bd09_to_wgs84(float(lng), float(lat))
50
- string_i = str(lng_i) + "," + str(lat_i)
51
- coords_all_wgs84.append(string_i)
52
- except (ValueError, AttributeError):
53
- print(f"Error processing coordinate: {coord}")
54
- return coords_all_wgs84
55
- coords_all_wgs84 = coords_trans(coordinates_all)
56
- long84=[]
57
- lat84=[]
58
- for coods84 in coords_all_wgs84:
59
- long84.append(coods84.split(",")[0])
60
- lat84.append(coods84.split(",")[1])
61
- min_lat=float(min(lat84))
62
- min_long=float(min(long84))
63
- max_long=float(max(long84))
64
- max_lat=float(max(lat84))
65
- long_bounds=max_long-min_long
66
- lat_bounds=max_lat-min_lat
67
- coords_lat_average=(min_lat+max_lat)/2
68
- coords_delta_x=abs(111*1000*0.01*math.cos(coords_lat_average))
69
- long_meterdif=long_bounds*coords_delta_x/0.01
70
- lat_meterdif=lat_bounds/111*1000
71
- print(long_meterdif)
72
- print(lat_meterdif)
73
- if lat_meterdif <3000 and long_meterdif <3000:
74
- merge_polygon_gdf_all=isochrone_get.get_polygon_gdf(coords_all_wgs84,contours_minutes_all,travel_mode_all)
75
-
76
- fig = plt.figure(figsize=(14,10),dpi = 100)
77
- ax = fig.add_subplot(111)
78
- walking_indeices = merge_polygon_gdf_all.index[merge_polygon_gdf_all["travel_mode"] == "walking"].tolist()
79
- cycle_indeices = merge_polygon_gdf_all.index[merge_polygon_gdf_all["travel_mode"] == "cycling"].tolist()
80
- for idx, geom in merge_polygon_gdf_all['geometry'].items():
81
- if isinstance(geom, Polygon):
82
- if idx in walking_indeices:
83
- patch = ax.add_patch(plt.Polygon(geom.exterior, facecolor=(0,0,0,0), edgecolor='black', linewidth=0.5))
84
- elif idx in cycle_indeices:
85
- patch = ax.add_patch(plt.Polygon(geom.exterior, facecolor=(0,0,0,0), edgecolor='grey', linewidth=0.5))
86
- else:
87
- patch = ax.add_patch(plt.Polygon(geom.exterior, facecolor=(0,0,0,0), edgecolor='blue', linewidth=0.5))
88
- elif isinstance(geom, MultiPolygon):
89
- for poly in geom:
90
- if idx in walking_indeices:
91
- patch = ax.add_patch(plt.Polygon(poly.exterior, facecolor=(0,0,0,0), edgecolor='black', linewidth=0.5))
92
- elif idx in cycle_indeices:
93
- patch = ax.add_patch(plt.Polygon(poly.exterior, facecolor=(0,0,0,0), edgecolor='grey', linewidth=0.5))
94
- else:
95
- patch = ax.add_patch(plt.Polygon(poly.exterior, facecolor=(0,0,0,0), edgecolor='blue', linewidth=0.5))
96
- scale_factor = 2
97
- bigger_polygon = merge_polygon_gdf_all.geometry.apply(lambda x: scale(x, xfact=scale_factor, yfact=scale_factor))
98
- rec_bounds=bigger_polygon.total_bounds
99
- bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
100
- difference_x = bounds[2] - bounds[0]
101
- difference_y = bounds[3] - bounds[1]
102
- target_scale=29.7/21
103
- recent_scale=difference_x/difference_y
104
- print(recent_scale)
105
- if recent_scale>target_scale:
106
- target_Dy=difference_x*21/29.7
107
- bounds[3]=bounds[3]+(target_Dy-difference_y)/2
108
- bounds[1]=bounds[1]-(target_Dy-difference_y)/2
109
- elif recent_scale<target_scale:
110
- target_Dx=difference_y*29.7/21
111
- bounds[2]=bounds[2]+(target_Dx-difference_x)/2
112
- bounds[0]=bounds[0]-(target_Dx-difference_x)/2
113
- else:
114
- pass
115
- new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
116
- ax.set_xlim(new_bounds[0],new_bounds[2])
117
- ax.set_ylim(new_bounds[1],new_bounds[3])
118
- plt.grid(True)
119
- new_dif_x=new_bounds[2]-new_bounds[0]
120
- new_dif_y=new_bounds[3]-new_bounds[1]
121
- unit_x=new_dif_x/14
122
- unit_y=new_dif_y/10
123
- list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
124
- list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
125
- plt.xticks(list_new_x)
126
- plt.yticks(list_new_y)
127
- plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
128
- for coord_str in coords_all_wgs84:
129
- lng, lat = map(float, coord_str.split(','))
130
- rounded_lng = round(lng, 5)
131
- rounded_lat = round(lat, 5)
132
- plt.scatter(rounded_lng, rounded_lat, color='black', marker='o',s=50,zorder=3)
133
- radius_circle=unit_x/4
134
- layer_num=2
135
- centroid_x=new_bounds[0]+unit_x
136
- centroid_y=new_bounds[1]+unit_y
137
- centroid_forcircle=(centroid_x,centroid_y)
138
- circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
139
- ax.add_patch(circle)
140
- x_dataforline=[centroid_x,centroid_x]
141
- y_dataforline=[centroid_y,centroid_y+radius_circle]
142
- line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
143
- x_datafortext=centroid_x
144
- y_datafortext=centroid_y+radius_circle
145
- ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
146
- lat_average=(new_bounds[1]+new_bounds[3])/2
147
- bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
148
- text_y=bar_startpt[1]+radius_circle
149
- teztsize=10
150
- layer_num=2
151
- delta_x=abs(111*1000*0.01*math.cos(lat_average))
152
- unit_distance=unit_x*delta_x/0.01
153
- if unit_distance/2>100:
154
- nereast_num=int(unit_distance/100)*100
155
- lon_randon=unit_x*nereast_num/unit_distance
156
- barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
157
- barran_ypt=(bar_startpt[1],bar_startpt[1])
158
- barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
159
- barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
160
- barran3_ypt=(bar_startpt[1],bar_startpt[1])
161
- barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
162
- ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
163
- ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
164
- ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
165
- else:
166
-
167
- num=100
168
- lon100=unit_x*num/unit_distance
169
- bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
170
- bar100_ypt=(bar_startpt[1],bar_startpt[1])
171
- bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
172
- bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
173
- bar300_ypt=(bar_startpt[1],bar_startpt[1])
174
- bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
175
- ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
176
- ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
177
- ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
178
-
179
- plt.grid(True,zorder=1,alpha=0.5)
180
-
181
- now = datetime.now()
182
- timestamp = now.strftime("%Y%m%d%H%M%S")
183
- file_name = f"saveisochrone_{timestamp}.jpg"
184
- file_path = os.path.join(os.getcwd(), file_name)
185
- svg_name=f"saveisochrone_{timestamp}.svg"
186
- svg_path=os.path.join(os.getcwd(),svg_name)
187
- plt.savefig(file_path, dpi=300)
188
- svgfile=fig.savefig(svg_path, format='svg', transparent=True)
189
- return [file_path,svg_name,run_count,'区域选择符合限制']
190
-
191
- else:
192
- blankfig=plt.figure(figsize=(14,10),dpi = 100)
193
- ax = blankfig.add_subplot(111)
194
- now = datetime.now()
195
- timestamp = now.strftime("%Y%m%d%H%M%S")
196
- # 构造文件名(图像)
197
- poi_file_name = f"savepoi_{timestamp}.jpg"
198
- poi_file_path = os.path.join(os.getcwd(), poi_file_name)
199
- # # 构造文件名(svg)
200
- svg_poiname=f"savepoi_{timestamp}.svg"
201
- svg_poipath=os.path.join(os.getcwd(),svg_poiname)
202
- # 保存文件
203
- poi_dis_file=plt.savefig(poi_file_path, dpi=300)
204
- svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
205
-
206
- return [poi_file_name,svg_poiname,run_count,"区域过大,超过3KM限制"]
207
-
208
-
209
-
210
- def random_foodchoice(loc_gradio,category_gradio,walking_min):
211
- global run_count1
212
- run_count1 += 1
213
- poi_categories = {'正餐': ['中餐厅','外国餐厅','小吃快餐店','其他'],
214
- '下���茶': ['蛋糕甜品店','咖啡厅','奶茶','其他']} #
215
-
216
- cent = loc_gradio.split(",")[1] + "," + loc_gradio.split(",")[0]
217
- query = '美食'
218
- category = category_gradio
219
- gdf_all_points=geopandas.GeoDataFrame()
220
- if category == "正餐":
221
- for tag in poi_categories[category]:
222
- gdf_cent = foodlist.get_data(query, tag, cent)
223
- print("--{}--的--{}--数据加载完毕,共抓取到{}个店".format(query,tag,len(gdf_cent)))
224
- try:
225
- gdf_cent = gdf_cent[gdf_cent['tag'].isin(["中餐厅", "外国餐厅", "小吃快餐店"])]
226
- gdf_all_points = pd.concat([gdf_cent, gdf_all_points], ignore_index=True)
227
- except :
228
- print("请无视:由于网络/ak额度/此处没有该类型的POI 等原因,没有获取到数据")
229
- continue
230
-
231
- elif category == "下午茶":
232
- for tag in poi_categories[category]:
233
- gdf_cent = foodlist.get_data(query, tag, cent)
234
- print("--{}--的--{}--数据加载完毕,共抓取到{}个店".format(query,tag,len(gdf_cent)))
235
- try:
236
- gdf_cent = gdf_cent[gdf_cent['tag'].isin(["蛋糕甜品店", "咖啡厅", "奶茶"])]
237
- gdf_all_points = pd.concat([gdf_cent, gdf_all_points], ignore_index=True)
238
- except :
239
- print("请无视:由于网络/ak额度/此处没有该类型的POI 等原因,没有获取到数据")
240
- continue
241
- gdf_all_points
242
- gdf_drop_points = gdf_all_points.drop_duplicates(subset=['name','lng_bd', 'lat_bd', 'lng_wgs84', 'lat_wgs84', 'address','province', 'city', 'area','uid'],ignore_index = True)
243
- print("全部数据加载完毕,共有{}个poi点,去重后共有{}个poi点".format(len(gdf_all_points),len(gdf_drop_points)))
244
- output_points = gdf_drop_points.drop(columns ='tag_drop')
245
- output_points = output_points.set_crs(crs= "EPSG:4326")
246
- lng , lat = cconv.bd09_to_wgs84(float(loc_gradio.split(",")[0]),float(loc_gradio.split(",")[1]))
247
- coordinates = str(lng) + "," + str(lat)
248
-
249
- travel_mode = "walking"
250
- contours_minutes =str(walking_min)
251
-
252
- gdf_isochrone = foodlist.get_isochrone_from_mapbox(travel_mode,coordinates,contours_minutes)
253
- gdf_isochrone = gdf_isochrone.set_crs(crs= "EPSG:4326")
254
- gdf_within = gpd.sjoin(output_points, gdf_isochrone, predicate='within')
255
- gdf_within = gdf_within.reset_index()
256
- print("有{}家待选店铺".format(len(gdf_within)))
257
- if len(gdf_within) == 0:
258
- final_out="None"
259
- messagebox="sorry~这附近好像没有可以觅食的地方哦,换个地方试试吧"
260
- else:
261
- output_name_list = list(gdf_within['name'])
262
- final_one = random.choice(output_name_list)
263
- row_address = gdf_within[gdf_within['name']==final_one]
264
- final_address = row_address['address'].values[0]
265
- row_rating = gdf_within[gdf_within['name']==final_one]
266
- final_rating = row_rating['overall_rating'].values[0]
267
- row_label = gdf_within[gdf_within['name']==final_one]
268
- final_label = row_label['label'].values[0]
269
- row_price = gdf_within[gdf_within['name']==final_one]
270
- final_price = row_label['price'].values[0]
271
- row_hours = gdf_within[gdf_within['name']==final_one]
272
- final_hours = row_label['shop_hours'].values[0]
273
- final_out="今天去吃 【{}】 ,位置在 【{}】\n 【其他相关信息】:{} {} {}".format(final_one,final_address,final_rating,final_label,final_hours)
274
- messagebox="运算正常"
275
- return [final_out,run_count1,messagebox]
276
-
277
-
278
- def POI_distribution(location1,location2,categories):
279
- global run_count2
280
- run_count2 += 1
281
- min_long=float(location1.split(",")[0])
282
- min_lat=float(location1.split(",")[1])
283
- max_long=float(location2.split(",")[0])
284
- max_lat=float(location2.split(",")[1])
285
- long_bounds=max_long-min_long
286
- lat_bounds=max_lat-min_lat
287
-
288
- coords_lat_average=(min_lat+max_lat)/2
289
- coords_delta_x=abs(111*1000*0.01*math.cos(coords_lat_average))
290
- long_meterdif=long_bounds*coords_delta_x/0.01
291
- lat_meterdif=lat_bounds/111*1000
292
-
293
- print(long_meterdif)
294
- print(lat_meterdif)
295
-
296
- if lat_meterdif <3000 and long_meterdif <3000:
297
-
298
- location=[location1,location2]
299
- gdf_output=POI_baidu_distribution.POI_get(location,categories)
300
-
301
- if len(gdf_output)==0:
302
- blankfig=plt.figure(figsize=(14,10),dpi = 100)
303
- ax = blankfig.add_subplot(111)
304
- #给文件命名
305
- # 获取当前日期时间信息
306
- now = datetime.now()
307
- timestamp = now.strftime("%Y%m%d%H%M%S")
308
- # 构造文件名(图像)
309
- poi_file_name = f"savepoi_{timestamp}.jpg"
310
- poi_file_path = os.path.join(os.getcwd(), poi_file_name)
311
- # # 构造文件名(svg)
312
- svg_poiname=f"savepoi_{timestamp}.svg"
313
- svg_poipath=os.path.join(os.getcwd(),svg_poiname)
314
- # 保存文件
315
- poi_dis_file=plt.savefig(poi_file_path, dpi=300)
316
- svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
317
- message_box="区域内没有该类型POI点"
318
- return [poi_file_name,svg_poiname,run_count2,'区域选择符合限制',message_box]
319
- else:
320
- message_box="POI获取正常"
321
-
322
- fig = plt.figure(figsize=(14,10),dpi = 100)
323
- ax = fig.add_subplot(111)
324
-
325
- wgsmin_long, wgsmin_lat=cconv.bd09_to_wgs84(min_long,min_lat)
326
- wgsmax_long,wgsmax_lat=cconv.bd09_to_wgs84(max_long,max_lat)
327
- scale_factor = 3
328
-
329
- rec_bounds = [wgsmin_long - (wgsmax_long - wgsmin_long)/scale_factor,
330
- wgsmin_lat - (wgsmax_lat -wgsmin_lat)/scale_factor,
331
- wgsmax_long + (wgsmax_long - wgsmin_long)/scale_factor,
332
- wgsmax_lat + (wgsmax_lat - wgsmin_lat)/scale_factor]
333
-
334
- # points_bounds = gdf_output.total_bounds
335
- # scale_factor = 3
336
- # rec_bounds = [points_bounds[0] - (points_bounds[2] - points_bounds[0])/scale_factor,
337
- # points_bounds[1] - (points_bounds[3] - points_bounds[1])/scale_factor,
338
- # points_bounds[2] + (points_bounds[2] - points_bounds[0])/scale_factor,
339
- # points_bounds[3] + (points_bounds[3] - points_bounds[1])/scale_factor]
340
-
341
- bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
342
- difference_x = bounds[2] - bounds[0]
343
- difference_y = bounds[3] - bounds[1]
344
- target_scale=29.7/21
345
- recent_scale=difference_x/difference_y
346
- print(recent_scale)
347
- if recent_scale>target_scale:
348
- target_Dy=difference_x*21/29.7
349
- bounds[3]=bounds[3]+(target_Dy-difference_y)/2
350
- bounds[1]=bounds[1]-(target_Dy-difference_y)/2
351
- elif recent_scale<target_scale:
352
- target_Dx=difference_y*29.7/21
353
- bounds[2]=bounds[2]+(target_Dx-difference_x)/2
354
- bounds[0]=bounds[0]-(target_Dx-difference_x)/2
355
- else:
356
- pass
357
- new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
358
-
359
- ax.set_xlim(new_bounds[0],new_bounds[2])
360
- ax.set_ylim(new_bounds[1],new_bounds[3])
361
-
362
- new_dif_x=new_bounds[2]-new_bounds[0]
363
- new_dif_y=new_bounds[3]-new_bounds[1]
364
- unit_x=new_dif_x/14
365
- unit_y=new_dif_y/10
366
- list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
367
- list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
368
- plt.xticks(list_new_x)
369
- plt.yticks(list_new_y)
370
- plt.grid(True,zorder=1,alpha=0.5)
371
- plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
372
- grouped = gdf_output.groupby('category_english')
373
- for group_name, group_data in grouped:
374
- ax.scatter(group_data.geometry.x, group_data.geometry.y, label=group_name, alpha=0.5,zorder=2)
375
-
376
- rec_xy=(wgsmin_long,wgsmin_lat)
377
- rec_width=wgsmax_long-wgsmin_long
378
- rec_height=wgsmax_lat- wgsmin_lat
379
- seclected_area=plt.Rectangle(rec_xy, rec_width, rec_height, edgecolor='black',facecolor='none',linestyle='--',linewidth=0.5,zorder=3,alpha=0.8)
380
- ax.add_patch(seclected_area)
381
- # rec_xy=(points_bounds[0],points_bounds[1])
382
- # rec_width=points_bounds[2]-points_bounds[0]
383
- # rec_height=points_bounds[3]-points_bounds[1]
384
- # seclected_area=plt.Rectangle(rec_xy, rec_width, rec_height, edgecolor='black',facecolor='none',linestyle='--',linewidth=0.5,zorder=3,alpha=0.8)
385
- # ax.add_patch(seclected_area)
386
-
387
- radius_circle=unit_x/4
388
- layer_num=2
389
- centroid_x=new_bounds[0]+unit_x
390
- centroid_y=new_bounds[1]+unit_y
391
- centroid_forcircle=(centroid_x,centroid_y)
392
- circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
393
- ax.add_patch(circle)
394
- x_dataforline=[centroid_x,centroid_x]
395
- y_dataforline=[centroid_y,centroid_y+radius_circle]
396
- line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
397
- x_datafortext=centroid_x
398
- y_datafortext=centroid_y+radius_circle
399
- ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
400
- lat_average=(new_bounds[1]+new_bounds[3])/2
401
- bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
402
- text_y=bar_startpt[1]+radius_circle
403
- teztsize=10
404
- layer_num=2
405
-
406
- delta_x=abs(111*1000*0.01*math.cos(lat_average))
407
-
408
- unit_distance=unit_x*delta_x/0.01
409
- if unit_distance/2>100:
410
- nereast_num=int(unit_distance/100)*100
411
- lon_randon=unit_x*nereast_num/unit_distance
412
- barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
413
- barran_ypt=(bar_startpt[1],bar_startpt[1])
414
- barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
415
- barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
416
- barran3_ypt=(bar_startpt[1],bar_startpt[1])
417
- barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
418
- ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
419
- ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
420
- ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
421
- else:
422
- num=100
423
- lon100=unit_x*num/unit_distance
424
- bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
425
- bar100_ypt=(bar_startpt[1],bar_startpt[1])
426
- bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
427
- bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
428
- bar300_ypt=(bar_startpt[1],bar_startpt[1])
429
- bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
430
- ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
431
- ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
432
- ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
433
- ax.legend(title='category_english', loc='upper right')
434
-
435
-
436
-
437
- now = datetime.now()
438
- timestamp = now.strftime("%Y%m%d%H%M%S")
439
- poi_file_name = f"savepoi_{timestamp}.jpg"
440
- poi_file_path = os.path.join(os.getcwd(), poi_file_name)
441
- svg_poiname=f"savepoi_{timestamp}.svg"
442
- svg_poipath=os.path.join(os.getcwd(),svg_poiname)
443
- poi_dis_file=plt.savefig(poi_file_path, dpi=300)
444
- svgpoifile=fig.savefig(svg_poipath, format='svg', transparent=True)
445
-
446
- return [poi_file_name,svg_poiname,run_count2,'区域选择符合限制',message_box]
447
-
448
- else:
449
- blankfig=plt.figure(figsize=(14,10),dpi = 100)
450
- ax = blankfig.add_subplot(111)
451
- now = datetime.now()
452
- timestamp = now.strftime("%Y%m%d%H%M%S")
453
- poi_file_name = f"savepoi_{timestamp}.jpg"
454
- poi_file_path = os.path.join(os.getcwd(), poi_file_name)
455
- svg_poiname=f"savepoi_{timestamp}.svg"
456
- svg_poipath=os.path.join(os.getcwd(),svg_poiname)
457
- poi_dis_file=plt.savefig(poi_file_path, dpi=300)
458
- svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
459
- message_box="None"
460
-
461
- return [poi_file_name,svg_poiname,run_count2,"区域过大,超过3KM限制",message_box]
462
-
463
-
464
- def POI_kernel(location1,location2,category):
465
-
466
- global run_count3
467
- run_count3 += 1
468
- min_long=float(location1.split(",")[0])
469
- min_lat=float(location1.split(",")[1])
470
- max_long=float(location2.split(",")[0])
471
- max_lat=float(location2.split(",")[1])
472
- long_bounds=max_long-min_long
473
- lat_bounds=max_lat-min_lat
474
- coords_lat_average=(min_lat+max_lat)/2
475
- coords_delta_x=abs(111*1000*0.01*math.cos(coords_lat_average))
476
- long_meterdif=long_bounds*coords_delta_x/0.01
477
- lat_meterdif=lat_bounds/111*1000
478
-
479
- print(long_meterdif)
480
- print(lat_meterdif)
481
-
482
- if lat_meterdif <3000 and long_meterdif <3000:
483
-
484
- categories=[category]
485
- location=[location1,location2]
486
- gdf_output=POI_baidu_distribution.POI_get(location,categories)
487
-
488
- if len(gdf_output)==0:
489
- blankfig=plt.figure(figsize=(14,10),dpi = 100)
490
- ax = blankfig.add_subplot(111)
491
- #给文件命名
492
- # 获取当前日期时间信息
493
- now = datetime.now()
494
- timestamp = now.strftime("%Y%m%d%H%M%S")
495
- # 构造文件名(图像)
496
- poi_file_name = f"savepoi_{timestamp}.jpg"
497
- poi_file_path = os.path.join(os.getcwd(), poi_file_name)
498
- # # 构造文件名(svg)
499
- svg_poiname=f"savepoi_{timestamp}.svg"
500
- svg_poipath=os.path.join(os.getcwd(),svg_poiname)
501
- # 保存文件
502
- poi_dis_file=plt.savefig(poi_file_path, dpi=300)
503
- svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
504
- message_box="区域内没有该类型POI点"
505
- return [poi_file_name,svg_poiname,run_count3,'区域选择符合限制',message_box]
506
- else:
507
- message_box="POI获取正常"
508
-
509
- fig = plt.figure(figsize=(14,10),dpi = 100)
510
- ax = fig.add_subplot(111)
511
- # points_bounds = gdf_output.total_bounds
512
- # scale_factor = 3
513
-
514
- # rec_bounds = [points_bounds[0] - (points_bounds[2] - points_bounds[0])/scale_factor,
515
- # points_bounds[1] - (points_bounds[3] - points_bounds[1])/scale_factor,
516
- # points_bounds[2] + (points_bounds[2] - points_bounds[0])/scale_factor,
517
- # points_bounds[3] + (points_bounds[3] - points_bounds[1])/scale_factor]
518
-
519
- wgsmin_long, wgsmin_lat=cconv.bd09_to_wgs84(min_long,min_lat)
520
- wgsmax_long,wgsmax_lat=cconv.bd09_to_wgs84(max_long,max_lat)
521
- scale_factor = 3
522
- rec_bounds = [wgsmin_long - (wgsmax_long - wgsmin_long)/scale_factor,
523
- wgsmin_lat - (wgsmax_lat -wgsmin_lat)/scale_factor,
524
- wgsmax_long + (wgsmax_long - wgsmin_long)/scale_factor,
525
- wgsmax_lat + (wgsmax_lat - wgsmin_lat)/scale_factor]
526
-
527
- bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
528
- difference_x = bounds[2] - bounds[0]
529
- difference_y = bounds[3] - bounds[1]
530
- target_scale=29.7/21
531
- recent_scale=difference_x/difference_y
532
- print(recent_scale)
533
- if recent_scale>target_scale:
534
- target_Dy=difference_x*21/29.7
535
- bounds[3]=bounds[3]+(target_Dy-difference_y)/2
536
- bounds[1]=bounds[1]-(target_Dy-difference_y)/2
537
- elif recent_scale<target_scale:
538
- target_Dx=difference_y*29.7/21
539
- bounds[2]=bounds[2]+(target_Dx-difference_x)/2
540
- bounds[0]=bounds[0]-(target_Dx-difference_x)/2
541
- else:
542
- pass
543
- new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
544
-
545
- ax.set_xlim(new_bounds[0],new_bounds[2])
546
- ax.set_ylim(new_bounds[1],new_bounds[3])
547
-
548
- new_dif_x=new_bounds[2]-new_bounds[0]
549
- new_dif_y=new_bounds[3]-new_bounds[1]
550
- unit_x=new_dif_x/14
551
- unit_y=new_dif_y/10
552
- list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
553
- list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
554
- plt.xticks(list_new_x)
555
- plt.yticks(list_new_y)
556
-
557
- plt.grid(True,zorder=1,alpha=0.5)
558
-
559
- plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
560
- grouped = gdf_output.groupby('category_english')
561
- for group_name, group_data in grouped:
562
- ax.scatter(group_data.geometry.x, group_data.geometry.y, label=group_name, alpha=0.5,zorder=2)
563
-
564
- sns.kdeplot(gdf_output,x="lng_wgs84",y="lat_wgs84",fill=True,alpha=.5,hue='category_us',legend=False,color="grey") #thresh=0, levels=100, cmap="mako"
565
-
566
- radius_circle=unit_x/4
567
- layer_num=2
568
- centroid_x=new_bounds[0]+unit_x
569
- centroid_y=new_bounds[1]+unit_y
570
- centroid_forcircle=(centroid_x,centroid_y)
571
- circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
572
- ax.add_patch(circle)
573
-
574
- x_dataforline=[centroid_x,centroid_x]
575
- y_dataforline=[centroid_y,centroid_y+radius_circle]
576
- line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
577
- x_datafortext=centroid_x
578
- y_datafortext=centroid_y+radius_circle
579
- ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
580
- lat_average=(new_bounds[1]+new_bounds[3])/2
581
- bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
582
- text_y=bar_startpt[1]+radius_circle
583
- teztsize=10
584
- layer_num=2
585
- delta_x=abs(111*1000*0.01*math.cos(lat_average))
586
- unit_distance=unit_x*delta_x/0.01
587
- if unit_distance/2>100:
588
- nereast_num=int(unit_distance/100)*100
589
- lon_randon=unit_x*nereast_num/unit_distance
590
- barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
591
- barran_ypt=(bar_startpt[1],bar_startpt[1])
592
- barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
593
-
594
- barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
595
- barran3_ypt=(bar_startpt[1],bar_startpt[1])
596
- barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
597
- ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
598
- ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
599
- ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
600
- else:
601
- num=100
602
- lon100=unit_x*num/unit_distance
603
- bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
604
- bar100_ypt=(bar_startpt[1],bar_startpt[1])
605
- bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
606
- bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
607
- bar300_ypt=(bar_startpt[1],bar_startpt[1])
608
- bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
609
- ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
610
- ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
611
- ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
612
- ax.legend(title='Category')
613
-
614
-
615
- now = datetime.now()
616
- timestamp = now.strftime("%Y%m%d%H%M%S")
617
- poiker_file_name = f"savepoiker_{timestamp}.jpg"
618
- poiker_file_path = os.path.join(os.getcwd(), poiker_file_name)
619
- svgker_name=f"savepoiker_{timestamp}.svg"
620
- svgker_path=os.path.join(os.getcwd(),svgker_name)
621
- poi_ker_file= plt.savefig(poiker_file_path, dpi=300)
622
- svgkerfile=fig.savefig(svgker_path, format='svg', transparent=True)
623
- print(f"文件保存路径:{poiker_file_path}")
624
- return [poiker_file_name,svgker_name,run_count3, '区域选择符合限制',message_box]
625
-
626
- else:
627
- blankfig=plt.figure(figsize=(14,10),dpi = 100)
628
- ax = blankfig.add_subplot(111)
629
- now = datetime.now()
630
- timestamp = now.strftime("%Y%m%d%H%M%S")
631
- poi_file_name = f"savepoi_{timestamp}.jpg"
632
- poi_file_path = os.path.join(os.getcwd(), poi_file_name)
633
- svg_poiname=f"savepoi_{timestamp}.svg"
634
- svg_poipath=os.path.join(os.getcwd(),svg_poiname)
635
- poi_dis_file=plt.savefig(poi_file_path, dpi=300)
636
- svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
637
- message_box="None"
638
- return [poi_file_name,svg_poiname,run_count3,"区域过大,超过3KM限制",message_box]
639
-
640
-
641
- with gr.Blocks() as demo:
642
- gr.Markdown(
643
- """
644
- # UrbanFlow-DataAnalysis
645
- 使用说明和更多关于UrbanFlow的详情请查看链接:[UrbanFlow-DataAnalysis使用说明](https://gdz6btft72.feishu.cn/docx/E0pxd8pXpo4wOQxZ8eic7iSqnXc)
646
- 如果您遇到排队较长或出图缓慢的情况,可以使用下列备用连接:[备用链接1](https://hf-mirror.com/spaces/onefan/UrbanFlow-DataAnalysis-Public) [备用链接2](https://hf-mirror.com/spaces/Mammmmmm/UrbanFlow-DataAnalysis-Public) [备用链接3](https://hf-mirror.com/spaces/Aryayaya/UrbanFlow-DataAnalysis-Public)
647
- """
648
- )
649
- with gr.Tab("等时圈分析"):
650
- with gr.Row():
651
- with gr.Column():
652
- gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取坐标点,并输入最多六个角点坐标来对您想生成等时圈的区域进行控制")
653
- with gr.Row():
654
- co_input = [gr.Textbox(label=f"坐标角点参数 {i}", placeholder=f"请输入参数 {i}") for i in range(1, 7)]
655
- drop1 = gr.CheckboxGroup(["walking","cycling","driving"], label="选择出行方式")
656
- drop2 = gr.CheckboxGroup(["5","10","15","20","25","30"], label="选择时间(min)")
657
- report=gr.Textbox(label="报错提醒")
658
- with gr.Column():
659
- output_img = gr.Image()
660
- output_svgpath = gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
661
- output_count=gr.Textbox(label="本页面已提供一键生图次数")
662
- cal_btn = gr.Button("Calculate")
663
- cal_btn.click(fn=isochrone, inputs=[drop2]+[drop1]+co_input, outputs=[output_img,output_svgpath,output_count,report])
664
-
665
- gr.Markdown("""
666
- ## 输入参数示例
667
- """)
668
- examples_index=[[["5"],["walking"],"113.924838,22.492807","","","",""],[["5"],["walking","cycling"],"113.923916,22.493438","113.924122,22.492887","113.924383,22.492348","113.924621,22.491827",""],[["5","10"],["walking"],"113.92366,22.493743","113.922101,22.494373","113.922159,22.494469","113.922272,22.494665","113.92242,22.494982"]]
669
- gr.Examples(examples=examples_index,inputs=[drop2]+[drop1]+co_input,outputs=output_img,fn=isochrone,label="examples")
670
-
671
- with gr.Tab("POI分布图"):
672
- with gr.Row():
673
- with gr.Column():
674
- gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
675
- with gr.Row():
676
- POI_input1 = [gr.Textbox(label=f"左��角角点坐标", placeholder="请输入<左下角>角点坐标"),
677
- gr.Textbox(label=f"右上角角点坐标", placeholder="请输入<右上角>角点坐标")
678
- ]
679
- with gr.Row():
680
- POI_input2=gr.CheckboxGroup(["住宅区","公共服务设施-文化设施","公共服务设施-学校","公共服务设施-体育设施","公共服务设施-医疗卫生","商业服务设施-餐饮","商业服务设施-酒店","商业服务设施-购物中心","商业服务设施-超市&便利店","商业服务设施-公司企业","商业服务设施-娱乐康体","交通设施-公共交通站点","交通设施-停车场","绿地-公园","绿地-旅游景点","生活服务"],label="请选择您需要的POI类型")
681
- with gr.Row():
682
- with gr.Column():
683
- report=gr.Textbox(label="区域限制报错提醒")
684
- report2=gr.Textbox(label="POI数据获取报错提醒")
685
-
686
- with gr.Column():
687
- POI_output1=gr.Image(label="POI分布图")
688
- POI_output2=gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
689
- output_count=gr.Textbox(label="本页面已提供一键生图次数")
690
-
691
- cal_btn = gr.Button("Calculate")
692
- cal_btn.click(fn=POI_distribution, inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2,output_count,report,report2])
693
- gr.Markdown("""
694
- ## 输入参数示例
695
- """)
696
- examples_index=[["113.923428,22.491367","113.930983,22.495825",['商业服务设施-娱乐康体','公共服务设施-学校']],["113.930938,22.522402","113.942185,22.531515",['公共服务设施-学校','商业服务设施-餐饮']]]
697
- gr.Examples(examples=examples_index,inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2],fn=POI_distribution,label="examples")
698
-
699
-
700
- with gr.Tab("POI密度图"):
701
- with gr.Row():
702
- with gr.Column():
703
- gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
704
- with gr.Row():
705
- POI_input1 = [gr.Textbox(label=f"左下角角点坐标", placeholder="请输入<左下角>角点坐标"),
706
- gr.Textbox(label=f"右上角角点坐标", placeholder="请输入<右上角>角点坐标")
707
- ]
708
- POI_input2=gr.Radio(["住宅区","公共服务设施-文化设施","公共服务设施-学校","公共服务设施-体育设施","公共服务设施-医疗卫生","商业服务设施-餐饮","商业服务设施-酒店","商业服务设施-购物中心","商业服务设施-超市&便利店","商业服务设施-公司企业","商业服务设施-娱乐康体","交通设施-公共交通站点","交通设施-停车场","绿地-公园","绿地-旅游景点","生活服务"],label="请选择您需要的POI类型")
709
- with gr.Row():
710
- with gr.Column():
711
- report=gr.Textbox(label="区域限制报错提醒")
712
- report2=gr.Textbox(label="POI数据获取报错提醒")
713
-
714
- with gr.Column():
715
- POI_output1=gr.Image(label="POI密度图")
716
- POI_output2=gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
717
- output_count=gr.Textbox(label="本页面已提供一键生图次数")
718
-
719
- cal_btn = gr.Button("Calculate")
720
- cal_btn.click(fn=POI_kernel, inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2,output_count,report,report2])
721
- gr.Markdown("""
722
- ## 输入参数示例
723
- """)
724
- examples_index=[["113.923428,22.491367","113.930983,22.495825",'商业服务设施-娱乐康体'],["113.930938,22.522402","113.942185,22.531515",'商业服务设施-餐饮']]
725
- gr.Examples(examples=examples_index,inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2],fn=POI_kernel,label="examples")
726
-
727
-
728
- with gr.Tab("今天吃什么"):
729
- with gr.Row():
730
- with gr.Column():
731
- gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
732
- foodlist_input1 = gr.Textbox(label="您所在位置的坐标点",placeholder="输入您所在位置的坐标点")
733
- foodlist_input2=gr.Radio(["正餐","下午茶"],label="餐食类型")
734
- foodlist_input3=gr.Slider(label="您愿意步行的距离(min)",minimum=0, maximum=10, step=1)
735
- foodlist_btn=gr.Button("开始丢骰子")
736
- foodlist_output=gr.Textbox(label="今天吃什么",lines=5)
737
- with gr.Row():
738
- output_count=gr.Textbox(label="本页面已提供店铺查询服务次数")
739
- textbox=gr.Textbox(label="报错提醒")
740
- foodlist_btn.click(fn=random_foodchoice,inputs=[foodlist_input1,foodlist_input2,foodlist_input3],outputs=[foodlist_output,output_count,textbox])
741
- gr.Markdown("""
742
- ## 输入参数示例
743
- """)
744
- examples_index=[["113.924838,22.492807","正餐","10"],["113.924838,22.492807","下午茶","5"]]
745
- gr.Examples(examples=examples_index,inputs=[foodlist_input1,foodlist_input2,foodlist_input3],outputs=foodlist_output,fn=random_foodchoice,label="examples")
746
-
747
-
748
- demo.launch(share=True)
749
-