SShen11 commited on
Commit
2dd62aa
·
verified ·
1 Parent(s): c3447c3

Upload app2.py

Browse files
Files changed (1) hide show
  1. app2.py +675 -0
app2.py ADDED
@@ -0,0 +1,675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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=150
35
+ run_count1=150
36
+ run_count2=150
37
+ run_count3=150
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
+ matplotlib.rc("font",family='DengXian')
301
+
302
+
303
+ fig = plt.figure(figsize=(14,10),dpi = 100)
304
+ ax = fig.add_subplot(111)
305
+ points_bounds = gdf_output.total_bounds
306
+
307
+ scale_factor = 3
308
+ rec_bounds = [points_bounds[0] - (points_bounds[2] - points_bounds[0])/scale_factor,
309
+ points_bounds[1] - (points_bounds[3] - points_bounds[1])/scale_factor,
310
+ points_bounds[2] + (points_bounds[2] - points_bounds[0])/scale_factor,
311
+ points_bounds[3] + (points_bounds[3] - points_bounds[1])/scale_factor]
312
+ bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
313
+ difference_x = bounds[2] - bounds[0]
314
+ difference_y = bounds[3] - bounds[1]
315
+ target_scale=29.7/21
316
+ recent_scale=difference_x/difference_y
317
+ print(recent_scale)
318
+ if recent_scale>target_scale:
319
+ target_Dy=difference_x*21/29.7
320
+ bounds[3]=bounds[3]+(target_Dy-difference_y)/2
321
+ bounds[1]=bounds[1]-(target_Dy-difference_y)/2
322
+ elif recent_scale<target_scale:
323
+ target_Dx=difference_y*29.7/21
324
+ bounds[2]=bounds[2]+(target_Dx-difference_x)/2
325
+ bounds[0]=bounds[0]-(target_Dx-difference_x)/2
326
+ else:
327
+ pass
328
+ new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
329
+
330
+ ax.set_xlim(new_bounds[0],new_bounds[2])
331
+ ax.set_ylim(new_bounds[1],new_bounds[3])
332
+
333
+ new_dif_x=new_bounds[2]-new_bounds[0]
334
+ new_dif_y=new_bounds[3]-new_bounds[1]
335
+ unit_x=new_dif_x/14
336
+ unit_y=new_dif_y/10
337
+ list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
338
+ list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
339
+ plt.xticks(list_new_x)
340
+ plt.yticks(list_new_y)
341
+ plt.grid(True,zorder=1,alpha=0.5)
342
+ plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
343
+ grouped = gdf_output.groupby('category_english')
344
+ for group_name, group_data in grouped:
345
+ ax.scatter(group_data.geometry.x, group_data.geometry.y, label=group_name, alpha=0.5,zorder=2)
346
+ rec_xy=(points_bounds[0],points_bounds[1])
347
+ rec_width=points_bounds[2]-points_bounds[0]
348
+ rec_height=points_bounds[3]-points_bounds[1]
349
+ seclected_area=plt.Rectangle(rec_xy, rec_width, rec_height, edgecolor='black',facecolor='none',linestyle='--',linewidth=0.5,zorder=3,alpha=0.8)
350
+ ax.add_patch(seclected_area)
351
+
352
+ radius_circle=unit_x/4
353
+ layer_num=2
354
+ centroid_x=new_bounds[0]+unit_x
355
+ centroid_y=new_bounds[1]+unit_y
356
+ centroid_forcircle=(centroid_x,centroid_y)
357
+ circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
358
+ ax.add_patch(circle)
359
+ x_dataforline=[centroid_x,centroid_x]
360
+ y_dataforline=[centroid_y,centroid_y+radius_circle]
361
+ line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
362
+ x_datafortext=centroid_x
363
+ y_datafortext=centroid_y+radius_circle
364
+ ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
365
+ lat_average=(new_bounds[1]+new_bounds[3])/2
366
+ bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
367
+ text_y=bar_startpt[1]+radius_circle
368
+ teztsize=10
369
+ layer_num=2
370
+
371
+ delta_x=abs(111*1000*0.01*math.cos(lat_average))
372
+
373
+ unit_distance=unit_x*delta_x/0.01
374
+ if unit_distance/2>100:
375
+ nereast_num=int(unit_distance/100)*100
376
+ lon_randon=unit_x*nereast_num/unit_distance
377
+ barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
378
+ barran_ypt=(bar_startpt[1],bar_startpt[1])
379
+ barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
380
+ barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
381
+ barran3_ypt=(bar_startpt[1],bar_startpt[1])
382
+ barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
383
+ ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
384
+ ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
385
+ ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
386
+ else:
387
+ num=100
388
+ lon100=unit_x*num/unit_distance
389
+ bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
390
+ bar100_ypt=(bar_startpt[1],bar_startpt[1])
391
+ bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
392
+ bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
393
+ bar300_ypt=(bar_startpt[1],bar_startpt[1])
394
+ bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
395
+ ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
396
+ ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
397
+ ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
398
+ ax.legend(title='Category')
399
+
400
+
401
+
402
+ now = datetime.now()
403
+ timestamp = now.strftime("%Y%m%d%H%M%S")
404
+ poi_file_name = f"savepoi_{timestamp}.jpg"
405
+ poi_file_path = os.path.join(os.getcwd(), poi_file_name)
406
+ svg_poiname=f"savepoi_{timestamp}.svg"
407
+ svg_poipath=os.path.join(os.getcwd(),svg_poiname)
408
+ poi_dis_file=plt.savefig(poi_file_path, dpi=300)
409
+ svgpoifile=fig.savefig(svg_poipath, format='svg', transparent=True)
410
+
411
+ return [poi_file_name,svg_poiname,run_count2,'区域选择符合限制']
412
+
413
+ else:
414
+ blankfig=plt.figure(figsize=(14,10),dpi = 100)
415
+ ax = blankfig.add_subplot(111)
416
+ now = datetime.now()
417
+ timestamp = now.strftime("%Y%m%d%H%M%S")
418
+ poi_file_name = f"savepoi_{timestamp}.jpg"
419
+ poi_file_path = os.path.join(os.getcwd(), poi_file_name)
420
+ svg_poiname=f"savepoi_{timestamp}.svg"
421
+ svg_poipath=os.path.join(os.getcwd(),svg_poiname)
422
+ poi_dis_file=plt.savefig(poi_file_path, dpi=300)
423
+ svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
424
+
425
+ return [poi_file_name,svg_poiname,run_count,"区域过大,超过3KM限制"]
426
+
427
+
428
+ def POI_kernel(location1,location2,category):
429
+
430
+ global run_count3
431
+ run_count3 += 1
432
+ min_long=float(location1.split(",")[0])
433
+ min_lat=float(location1.split(",")[1])
434
+ max_long=float(location2.split(",")[0])
435
+ max_lat=float(location2.split(",")[1])
436
+ long_bounds=max_long-min_long
437
+ lat_bounds=max_lat-min_lat
438
+ coords_lat_average=(min_lat+max_lat)/2
439
+ coords_delta_x=abs(111*1000*0.01*math.cos(coords_lat_average))
440
+ long_meterdif=long_bounds*coords_delta_x/0.01
441
+ lat_meterdif=lat_bounds/111*1000
442
+
443
+ print(long_meterdif)
444
+ print(lat_meterdif)
445
+
446
+ if lat_meterdif <3000 and long_meterdif <3000:
447
+
448
+ categories=[category]
449
+ location=[location1,location2]
450
+ gdf_output=POI_baidu_distribution.POI_get(location,categories)
451
+
452
+ fig = plt.figure(figsize=(14,10),dpi = 100)
453
+ ax = fig.add_subplot(111)
454
+ points_bounds = gdf_output.total_bounds
455
+ scale_factor = 3
456
+
457
+ rec_bounds = [points_bounds[0] - (points_bounds[2] - points_bounds[0])/scale_factor,
458
+ points_bounds[1] - (points_bounds[3] - points_bounds[1])/scale_factor,
459
+ points_bounds[2] + (points_bounds[2] - points_bounds[0])/scale_factor,
460
+ points_bounds[3] + (points_bounds[3] - points_bounds[1])/scale_factor]
461
+ bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
462
+ difference_x = bounds[2] - bounds[0]
463
+ difference_y = bounds[3] - bounds[1]
464
+ target_scale=29.7/21
465
+ recent_scale=difference_x/difference_y
466
+ print(recent_scale)
467
+ if recent_scale>target_scale:
468
+ target_Dy=difference_x*21/29.7
469
+ bounds[3]=bounds[3]+(target_Dy-difference_y)/2
470
+ bounds[1]=bounds[1]-(target_Dy-difference_y)/2
471
+ elif recent_scale<target_scale:
472
+ target_Dx=difference_y*29.7/21
473
+ bounds[2]=bounds[2]+(target_Dx-difference_x)/2
474
+ bounds[0]=bounds[0]-(target_Dx-difference_x)/2
475
+ else:
476
+ pass
477
+ new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
478
+
479
+ ax.set_xlim(new_bounds[0],new_bounds[2])
480
+ ax.set_ylim(new_bounds[1],new_bounds[3])
481
+
482
+ new_dif_x=new_bounds[2]-new_bounds[0]
483
+ new_dif_y=new_bounds[3]-new_bounds[1]
484
+ unit_x=new_dif_x/14
485
+ unit_y=new_dif_y/10
486
+ list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
487
+ list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
488
+ plt.xticks(list_new_x)
489
+ plt.yticks(list_new_y)
490
+
491
+ plt.grid(True,zorder=1,alpha=0.5)
492
+
493
+ plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
494
+ grouped = gdf_output.groupby('category_english')
495
+ for group_name, group_data in grouped:
496
+ ax.scatter(group_data.geometry.x, group_data.geometry.y, label=group_name, alpha=0.5,zorder=2)
497
+
498
+ 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"
499
+
500
+ radius_circle=unit_x/4
501
+ layer_num=2
502
+ centroid_x=new_bounds[0]+unit_x
503
+ centroid_y=new_bounds[1]+unit_y
504
+ centroid_forcircle=(centroid_x,centroid_y)
505
+ circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
506
+ ax.add_patch(circle)
507
+
508
+ x_dataforline=[centroid_x,centroid_x]
509
+ y_dataforline=[centroid_y,centroid_y+radius_circle]
510
+ line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
511
+ x_datafortext=centroid_x
512
+ y_datafortext=centroid_y+radius_circle
513
+ ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
514
+ lat_average=(new_bounds[1]+new_bounds[3])/2
515
+ bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
516
+ text_y=bar_startpt[1]+radius_circle
517
+ teztsize=10
518
+ layer_num=2
519
+ delta_x=abs(111*1000*0.01*math.cos(lat_average))
520
+ unit_distance=unit_x*delta_x/0.01
521
+ if unit_distance/2>100:
522
+ nereast_num=int(unit_distance/100)*100
523
+ lon_randon=unit_x*nereast_num/unit_distance
524
+ barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
525
+ barran_ypt=(bar_startpt[1],bar_startpt[1])
526
+ barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
527
+
528
+ barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
529
+ barran3_ypt=(bar_startpt[1],bar_startpt[1])
530
+ barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
531
+ ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
532
+ ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
533
+ ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
534
+ else:
535
+ num=100
536
+ lon100=unit_x*num/unit_distance
537
+ bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
538
+ bar100_ypt=(bar_startpt[1],bar_startpt[1])
539
+ bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
540
+ bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
541
+ bar300_ypt=(bar_startpt[1],bar_startpt[1])
542
+ bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
543
+ ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
544
+ ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
545
+ ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
546
+ ax.legend(title='Category')
547
+
548
+
549
+ now = datetime.now()
550
+ timestamp = now.strftime("%Y%m%d%H%M%S")
551
+ poiker_file_name = f"savepoiker_{timestamp}.jpg"
552
+ poiker_file_path = os.path.join(os.getcwd(), poiker_file_name)
553
+ svgker_name=f"savepoiker_{timestamp}.svg"
554
+ svgker_path=os.path.join(os.getcwd(),svgker_name)
555
+ poi_ker_file= plt.savefig(poiker_file_path, dpi=300)
556
+ svgkerfile=fig.savefig(svgker_path, format='svg', transparent=True)
557
+ print(f"文件保存路径:{poiker_file_path}")
558
+ return [poiker_file_name,svgker_name,run_count, '区域选择符合限制']
559
+
560
+ else:
561
+ blankfig=plt.figure(figsize=(14,10),dpi = 100)
562
+ ax = blankfig.add_subplot(111)
563
+ now = datetime.now()
564
+ timestamp = now.strftime("%Y%m%d%H%M%S")
565
+ poi_file_name = f"savepoi_{timestamp}.jpg"
566
+ poi_file_path = os.path.join(os.getcwd(), poi_file_name)
567
+ svg_poiname=f"savepoi_{timestamp}.svg"
568
+ svg_poipath=os.path.join(os.getcwd(),svg_poiname)
569
+ poi_dis_file=plt.savefig(poi_file_path, dpi=300)
570
+ svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
571
+ return [poi_file_name,svg_poiname,run_count3,"区域过大,超过3KM限制"]
572
+
573
+
574
+ with gr.Blocks() as demo:
575
+ gr.Markdown(
576
+ """
577
+ # UrbanFlow-DataAnalysis
578
+ 使用说明和更多关于UrbanFlow的详情请查看链接:[UrbanFlow-DataAnalysis使用说明](https://gdz6btft72.feishu.cn/docx/E0pxd8pXpo4wOQxZ8eic7iSqnXc)
579
+ 如果您遇到排队较长或出图缓慢的情况,可以使用下列备用连接:[备用链接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)
580
+ """
581
+ )
582
+ with gr.Tab("等时圈分析"):
583
+ with gr.Row():
584
+ with gr.Column():
585
+ gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取坐标点,并输入最多六个角点坐标来对您想生成等时圈的区域进行控制")
586
+ with gr.Row():
587
+ co_input = [gr.Textbox(label=f"坐标角点参数 {i}", placeholder=f"请输入参数 {i}") for i in range(1, 7)]
588
+ drop1 = gr.CheckboxGroup(["walking","cycling","driving"], label="选择出行方式")
589
+ drop2 = gr.CheckboxGroup(["5","10","15","20","25","30"], label="选择时间(min)")
590
+ report=gr.Textbox(label="报错提醒")
591
+ with gr.Column():
592
+ output_img = gr.Image()
593
+ output_svgpath = gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
594
+ output_count=gr.Textbox(label="本页面已提供一键生图次数")
595
+ cal_btn = gr.Button("Calculate")
596
+ cal_btn.click(fn=isochrone, inputs=[drop2]+[drop1]+co_input, outputs=[output_img,output_svgpath,output_count,report])
597
+
598
+ gr.Markdown("""
599
+ ## 输入参数示例
600
+ 根据不同的场景需求输入参数生成等时圈,这里为您列举常见的三种参��示例,关于这三种参数示例的具体情况请点击下方链接
601
+ https://gdz6btft72.feishu.cn/docx/Win9dA3CwoFpPWxZdmJcJ9ganMh
602
+ """)
603
+ 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"]]
604
+ gr.Examples(examples=examples_index,inputs=[drop2]+[drop1]+co_input,outputs=output_img,fn=isochrone,label="examples")
605
+
606
+ with gr.Tab("POI分布图"):
607
+ with gr.Row():
608
+ with gr.Column():
609
+ gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
610
+ with gr.Row():
611
+ POI_input1 = [gr.Textbox(label=f"左下角角点坐标", placeholder="请输入<左下>角角点坐标"),
612
+ gr.Textbox(label=f"右上角角点坐标", placeholder="请输入<右上>角角点坐标")
613
+ ]
614
+ POI_input2=gr.CheckboxGroup(["住宅区","公共服务设施-文化设施","公共服务设施-学校","公共服务设施-体育设施","公共服务设施-医疗卫生","商业服务设施-餐饮","商业服务设施-酒店","商业服务设施-购物中心","商业服务设施-超市&便利店","商业服务设施-公司企业","商业服务设施-娱乐康体","交通设施-公共交通站点","交通设施-停车场","绿地-公园","绿地-旅游景点","生活服务"],label="请选择您需要的POI类型")
615
+ report=gr.Textbox(label="报错提醒")
616
+ with gr.Column():
617
+ POI_output1=gr.Image(label="POI分布图")
618
+ POI_output2=gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
619
+ output_count=gr.Textbox(label="本页面已提供一键生图次数")
620
+
621
+ cal_btn = gr.Button("Calculate")
622
+ cal_btn.click(fn=POI_distribution, inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2,output_count,report])
623
+ gr.Markdown("""
624
+ ## 输入参数示例
625
+ """)
626
+ examples_index=[["113.923428,22.491367","113.930983,22.495825",['商业服务设施-娱乐康体','公共服务设施-学校']],["113.930938,22.522402","113.942185,22.531515",['公共服务设施-学校','商业服务设施-餐饮']]]
627
+ gr.Examples(examples=examples_index,inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2],fn=POI_distribution,label="examples")
628
+
629
+
630
+ with gr.Tab("POI密度图"):
631
+ with gr.Row():
632
+ with gr.Column():
633
+ gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
634
+ with gr.Row():
635
+ POI_input1 = [gr.Textbox(label=f"左下角角点坐标", placeholder="请输入<左下>角角点坐标"),
636
+ gr.Textbox(label=f"右上角角点坐标", placeholder="请输入<右上>角角点坐标")
637
+ ]
638
+ POI_input2=gr.Radio(["住宅区","公共服务设施-文化设施","公共服务设施-学校","公共服务设施-体育设施","公共服务设施-医疗卫生","商业服务设施-餐饮","商业服务设施-酒店","商业服务设施-购物中心","商业服务设施-超市&便利店","商业服务设施-公司企业","商业服务设施-娱乐康体","交通设施-公共交通站点","交通设施-停车场","绿地-公园","绿地-旅游景点","生活服务"],label="请选择您需要的POI类型")
639
+ report=gr.Textbox(label="报错提醒")
640
+ with gr.Column():
641
+ POI_output1=gr.Image(label="POI分布图")
642
+ POI_output2=gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
643
+ output_count=gr.Textbox(label="本页面已提供一键生图次数")
644
+
645
+ cal_btn = gr.Button("Calculate")
646
+ cal_btn.click(fn=POI_kernel, inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2,output_count,report])
647
+ gr.Markdown("""
648
+ ## 输入参数示例
649
+ """)
650
+ examples_index=[["113.923428,22.491367","113.930983,22.495825",'商业服务设施-娱乐康体'],["113.930938,22.522402","113.942185,22.531515",'商业服务设施-餐饮']]
651
+ gr.Examples(examples=examples_index,inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2],fn=POI_kernel,label="examples")
652
+
653
+
654
+ with gr.Tab("今天吃什么"):
655
+ with gr.Row():
656
+ with gr.Column():
657
+ gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
658
+ foodlist_input1 = gr.Textbox(label="您所在位置的坐标点",placeholder="输入您所在位置的坐标点")
659
+ foodlist_input2=gr.Radio(["正餐","下午茶"],label="餐食类型")
660
+ foodlist_input3=gr.Slider(label="您愿意步行的距离(min)",minimum=0, maximum=10, step=1)
661
+ foodlist_btn=gr.Button("开始丢骰子")
662
+ foodlist_output=gr.Textbox(label="今天吃什么",lines=5)
663
+ with gr.Row():
664
+ output_count=gr.Textbox(label="本页面已提供店铺查询服务次数")
665
+ textbox=gr.Textbox(label="报错提醒")
666
+ foodlist_btn.click(fn=random_foodchoice,inputs=[foodlist_input1,foodlist_input2,foodlist_input3],outputs=[foodlist_output,output_count,textbox])
667
+ gr.Markdown("""
668
+ ## 输入参数示例
669
+ """)
670
+ examples_index=[["113.924838,22.492807","正餐","10"],["113.924838,22.492807","下午茶","5"]]
671
+ gr.Examples(examples=examples_index,inputs=[foodlist_input1,foodlist_input2,foodlist_input3],outputs=foodlist_output,fn=random_foodchoice,label="examples")
672
+
673
+
674
+ demo.launch(share=True)
675
+