SShen11's picture
Update app.py
00cf76c verified
Raw History Blame Contribute Delete
39.7 kB
import gradio as gr
import requests
import json
import geopandas as gpd
import pandas as pd
import numpy as np
from shapely import geometry
from shapely.geometry import Point, Polygon
import time
from tqdm import tqdm
import os
import matplotlib
import cconv
import geopandas
import matplotlib.pyplot as plt
from shapely.affinity import scale
requests.packages.urllib3.disable_warnings()
from datetime import datetime
import math
import random
import plot_map
import foodlist
import POI_baidu_distribution
import isochrone_get
import seaborn as sns
from shapely.geometry import Polygon, MultiPolygon
plot_map.set_mapboxtoken('pk.eyJ1IjoibGxsMzE5OTciLCJhIjoiY2w4anl6b2k5MGRxbjN4bXB1YzV6c3loaCJ9.ec49ySYxrKQWc5uyNHrzdA')#必须在里面设置你申请的token,直接复制此行代码无效!
plot_map.set_imgsavepath(os.getcwd())
run_count=0
run_count1=0
run_count2=0
run_count3=0
def isochrone(contours_minutes, travel_mode_all, *coordinates_all):
global run_count
run_count += 1
print("等时圈分析已运行{}次".format(run_count))
contours_minutes_all = ",".join(contours_minutes)
def coords_trans(*coords):
coords_all_wgs84 = []
for coord_tuple in coords:
for coord in coord_tuple:
if coord:
try:
lng, lat = coord.split(',')
lng_i, lat_i = cconv.bd09_to_wgs84(float(lng), float(lat))
string_i = str(lng_i) + "," + str(lat_i)
coords_all_wgs84.append(string_i)
except (ValueError, AttributeError):
print(f"Error processing coordinate: {coord}")
return coords_all_wgs84
coords_all_wgs84 = coords_trans(coordinates_all)
long84=[]
lat84=[]
for coods84 in coords_all_wgs84:
long84.append(coods84.split(",")[0])
lat84.append(coods84.split(",")[1])
min_lat=float(min(lat84))
min_long=float(min(long84))
max_long=float(max(long84))
max_lat=float(max(lat84))
long_bounds=max_long-min_long
lat_bounds=max_lat-min_lat
coords_lat_average=(min_lat+max_lat)/2
coords_delta_x=111*1000*0.01*math.cos(math.radians(coords_lat_average))
long_meterdif=long_bounds*coords_delta_x/0.01
lat_meterdif=lat_bounds/111*1000
print(long_meterdif)
print(lat_meterdif)
if lat_meterdif <3000 and long_meterdif <3000:
merge_polygon_gdf_all=isochrone_get.get_polygon_gdf(coords_all_wgs84,contours_minutes_all,travel_mode_all)
fig = plt.figure(figsize=(14,10),dpi = 100)
ax = fig.add_subplot(111)
walking_indeices = merge_polygon_gdf_all.index[merge_polygon_gdf_all["travel_mode"] == "walking"].tolist()
cycle_indeices = merge_polygon_gdf_all.index[merge_polygon_gdf_all["travel_mode"] == "cycling"].tolist()
for idx, geom in merge_polygon_gdf_all['geometry'].items():
if isinstance(geom, Polygon):
if idx in walking_indeices:
patch = ax.add_patch(plt.Polygon(geom.exterior, facecolor=(0,0,0,0), edgecolor='black', linewidth=0.5))#添加图形
elif idx in cycle_indeices:
patch = ax.add_patch(plt.Polygon(geom.exterior, facecolor=(0,0,0,0), edgecolor='grey', linewidth=0.5))
else:
patch = ax.add_patch(plt.Polygon(geom.exterior, facecolor=(0,0,0,0), edgecolor='blue', linewidth=0.5))
elif isinstance(geom, MultiPolygon):
for poly in geom:
if idx in walking_indeices:
patch = ax.add_patch(plt.Polygon(poly.exterior, facecolor=(0,0,0,0), edgecolor='black', linewidth=0.5))#添加图形
elif idx in cycle_indeices:
patch = ax.add_patch(plt.Polygon(poly.exterior, facecolor=(0,0,0,0), edgecolor='grey', linewidth=0.5))
else:
patch = ax.add_patch(plt.Polygon(poly.exterior, facecolor=(0,0,0,0), edgecolor='blue', linewidth=0.5))
scale_factor = 2
bigger_polygon = merge_polygon_gdf_all.geometry.apply(lambda x: scale(x, xfact=scale_factor, yfact=scale_factor))
rec_bounds=bigger_polygon.total_bounds
bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
difference_x = bounds[2] - bounds[0]
difference_y = bounds[3] - bounds[1]
target_scale=29.7/21
recent_scale=difference_x/difference_y
print(recent_scale)
if recent_scale>target_scale:
target_Dy=difference_x*21/29.7
bounds[3]=bounds[3]+(target_Dy-difference_y)/2
bounds[1]=bounds[1]-(target_Dy-difference_y)/2
elif recent_scale<target_scale:
target_Dx=difference_y*29.7/21
bounds[2]=bounds[2]+(target_Dx-difference_x)/2
bounds[0]=bounds[0]-(target_Dx-difference_x)/2
else:
pass
new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
ax.set_xlim(new_bounds[0],new_bounds[2])
ax.set_ylim(new_bounds[1],new_bounds[3])
plt.grid(True)
new_dif_x=new_bounds[2]-new_bounds[0]
new_dif_y=new_bounds[3]-new_bounds[1]
unit_x=new_dif_x/14
unit_y=new_dif_y/10
list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
plt.xticks(list_new_x)
plt.yticks(list_new_y)
plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
for coord_str in coords_all_wgs84:
lng, lat = map(float, coord_str.split(','))
rounded_lng = round(lng, 5)
rounded_lat = round(lat, 5)
plt.scatter(rounded_lng, rounded_lat, color='black', marker='o',s=50,zorder=3)
radius_circle=unit_x/4
layer_num=2
centroid_x=new_bounds[0]+unit_x
centroid_y=new_bounds[1]+unit_y
centroid_forcircle=(centroid_x,centroid_y)
circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
ax.add_patch(circle)
x_dataforline=[centroid_x,centroid_x]
y_dataforline=[centroid_y,centroid_y+radius_circle]
line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
x_datafortext=centroid_x
y_datafortext=centroid_y+radius_circle
ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
lat_average=(new_bounds[1]+new_bounds[3])/2
bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
text_y=bar_startpt[1]+radius_circle
teztsize=10
layer_num=2
delta_x=111*1000*0.01*math.cos(math.radians(lat_average))
unit_distance=unit_x*delta_x/0.01
if unit_distance/2>100:
nereast_num=int(unit_distance/100)*100
lon_randon=unit_x*nereast_num/unit_distance
barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
barran_ypt=(bar_startpt[1],bar_startpt[1])
barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
barran3_ypt=(bar_startpt[1],bar_startpt[1])
barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
else:
num=100
lon100=unit_x*num/unit_distance
bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
bar100_ypt=(bar_startpt[1],bar_startpt[1])
bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
bar300_ypt=(bar_startpt[1],bar_startpt[1])
bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
plt.grid(True,zorder=1,alpha=0.5)
now = datetime.now()
timestamp = now.strftime("%Y%m%d%H%M%S")
file_name = f"saveisochrone_{timestamp}.jpg"
file_path = os.path.join(os.getcwd(), file_name)
svg_name=f"saveisochrone_{timestamp}.svg"
svg_path=os.path.join(os.getcwd(),svg_name)
plt.savefig(file_path, dpi=300)
svgfile=fig.savefig(svg_path, format='svg', transparent=True)
return [file_path,svg_name,run_count,'区域选择符合限制']
else:
blankfig=plt.figure(figsize=(14,10),dpi = 100)
ax = blankfig.add_subplot(111)
now = datetime.now()
timestamp = now.strftime("%Y%m%d%H%M%S")
poi_file_name = f"savepoi_{timestamp}.jpg"
poi_file_path = os.path.join(os.getcwd(), poi_file_name)
svg_poiname=f"savepoi_{timestamp}.svg"
svg_poipath=os.path.join(os.getcwd(),svg_poiname)
poi_dis_file=plt.savefig(poi_file_path, dpi=300)
svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
return [poi_file_name,svg_poiname,run_count,"区域过大,超过3KM限制"]
def random_foodchoice(loc_gradio,category_gradio,walking_min):
global run_count1
run_count1 += 1
print("午餐骰子已运行{}次".format(run_count1))
poi_categories = {'正餐': ['中餐厅','外国餐厅','小吃快餐店','其他'],
'下午茶': ['蛋糕甜品店','咖啡厅','奶茶','其他']} #
cent = loc_gradio.split(",")[1] + "," + loc_gradio.split(",")[0]
query = '美食'
category = category_gradio
gdf_all_points=geopandas.GeoDataFrame()
if category == "正餐":
for tag in poi_categories[category]:
gdf_cent = foodlist.get_data(query, tag, cent)
print("--{}--的--{}--数据加载完毕,共抓取到{}个店".format(query,tag,len(gdf_cent)))
try:
gdf_cent = gdf_cent[gdf_cent['tag'].isin(["中餐厅", "外国餐厅", "小吃快餐店"])]
gdf_all_points = pd.concat([gdf_cent, gdf_all_points], ignore_index=True)
except :
print("请无视:由于网络/ak额度/此处没有该类型的POI 等原因,没有获取到数据")
continue
elif category == "下午茶":
for tag in poi_categories[category]:
gdf_cent = foodlist.get_data(query, tag, cent)
print("--{}--的--{}--数据加载完毕,共抓取到{}个店".format(query,tag,len(gdf_cent)))
try:
gdf_cent = gdf_cent[gdf_cent['tag'].isin(["蛋糕甜品店", "咖啡厅", "奶茶"])]
gdf_all_points = pd.concat([gdf_cent, gdf_all_points], ignore_index=True)
except :
print("请无视:由于网络/ak额度/此处没有该类型的POI 等原因,没有获取到数据")
continue
gdf_all_points
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)
print("全部数据加载完毕,共有{}个poi点,去重后共有{}个poi点".format(len(gdf_all_points),len(gdf_drop_points)))
output_points = gdf_drop_points.drop(columns ='tag_drop')
output_points = output_points.set_crs(crs= "EPSG:4326")
lng , lat = cconv.bd09_to_wgs84(float(loc_gradio.split(",")[0]),float(loc_gradio.split(",")[1]))
coordinates = str(lng) + "," + str(lat)
travel_mode = "walking"
contours_minutes =str(walking_min)
gdf_isochrone = foodlist.get_isochrone_from_mapbox(travel_mode,coordinates,contours_minutes)
gdf_isochrone = gdf_isochrone.set_crs(crs= "EPSG:4326")
gdf_within = gpd.sjoin(output_points, gdf_isochrone, predicate='within')
gdf_within = gdf_within.reset_index()
print("有{}家待选店铺".format(len(gdf_within)))
if len(gdf_within) == 0:
final_out="None"
messagebox="sorry~这附近好像没有可以觅食的地方哦,换个地方试试吧"
else:
output_name_list = list(gdf_within['name'])
final_one = random.choice(output_name_list)
row_address = gdf_within[gdf_within['name']==final_one]
final_address = row_address['address'].values[0]
row_rating = gdf_within[gdf_within['name']==final_one]
final_rating = row_rating['overall_rating'].values[0]
row_label = gdf_within[gdf_within['name']==final_one]
final_label = row_label['label'].values[0]
row_price = gdf_within[gdf_within['name']==final_one]
final_price = row_label['price'].values[0]
row_hours = gdf_within[gdf_within['name']==final_one]
final_hours = row_label['shop_hours'].values[0]
final_out="今天去吃 【{}】 ,位置在 【{}】\n 【其他相关信息】:{} {} {}".format(final_one,final_address,final_rating,final_label,final_hours)
messagebox="运算正常"
return [final_out,run_count1,messagebox]
def POI_distribution(location1,location2,categories):
global run_count2
run_count2 += 1
print("POI分布图已运行{}次".format(run_count2))
min_long=float(location1.split(",")[0])
min_lat=float(location1.split(",")[1])
max_long=float(location2.split(",")[0])
max_lat=float(location2.split(",")[1])
long_bounds=max_long-min_long
lat_bounds=max_lat-min_lat
coords_lat_average=(min_lat+max_lat)/2
coords_delta_x=111*1000*0.01*math.cos(math.radians(coords_lat_average))
long_meterdif=long_bounds*coords_delta_x/0.01
lat_meterdif=lat_bounds/111*1000
print(long_meterdif)
print(lat_meterdif)
if lat_meterdif <3000 and long_meterdif <3000:
location=[location1,location2]
gdf_output=POI_baidu_distribution.POI_get(location,categories)
if len(gdf_output)==0:
blankfig=plt.figure(figsize=(14,10),dpi = 100)
ax = blankfig.add_subplot(111)
now = datetime.now()
timestamp = now.strftime("%Y%m%d%H%M%S")
poi_file_name = f"savepoi_{timestamp}.jpg"
poi_file_path = os.path.join(os.getcwd(), poi_file_name)
svg_poiname=f"savepoi_{timestamp}.svg"
svg_poipath=os.path.join(os.getcwd(),svg_poiname)
poi_dis_file=plt.savefig(poi_file_path, dpi=300)
svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
message_box="区域内没有该类型POI点"
return [poi_file_name,svg_poiname,run_count2,'区域选择符合限制',message_box]
else:
message_box="POI获取正常"
# matplotlib.rc("font",family='DengXian')
fig = plt.figure(figsize=(14,10),dpi = 100)
ax = fig.add_subplot(111)
wgsmin_long, wgsmin_lat=cconv.bd09_to_wgs84(min_long,min_lat)
wgsmax_long,wgsmax_lat=cconv.bd09_to_wgs84(max_long,max_lat)
scale_factor = 3
rec_bounds = [wgsmin_long - (wgsmax_long - wgsmin_long)/scale_factor,
wgsmin_lat - (wgsmax_lat -wgsmin_lat)/scale_factor,
wgsmax_long + (wgsmax_long - wgsmin_long)/scale_factor,
wgsmax_lat + (wgsmax_lat - wgsmin_lat)/scale_factor]
bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
difference_x = bounds[2] - bounds[0]
difference_y = bounds[3] - bounds[1]
target_scale=29.7/21
recent_scale=difference_x/difference_y
print(recent_scale)
if recent_scale>target_scale:
target_Dy=difference_x*21/29.7
bounds[3]=bounds[3]+(target_Dy-difference_y)/2
bounds[1]=bounds[1]-(target_Dy-difference_y)/2
elif recent_scale<target_scale:
target_Dx=difference_y*29.7/21
bounds[2]=bounds[2]+(target_Dx-difference_x)/2
bounds[0]=bounds[0]-(target_Dx-difference_x)/2
else:
pass
new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
ax.set_xlim(new_bounds[0],new_bounds[2])
ax.set_ylim(new_bounds[1],new_bounds[3])
new_dif_x=new_bounds[2]-new_bounds[0]
new_dif_y=new_bounds[3]-new_bounds[1]
unit_x=new_dif_x/14
unit_y=new_dif_y/10
list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
plt.xticks(list_new_x)
plt.yticks(list_new_y)
plt.grid(True,zorder=1,alpha=0.5)
plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
grouped = gdf_output.groupby('category_english')
for group_name, group_data in grouped:
ax.scatter(group_data.geometry.x, group_data.geometry.y, label=group_name, alpha=0.5,zorder=2)
rec_xy=(wgsmin_long,wgsmin_lat)
rec_width=wgsmax_long-wgsmin_long
rec_height=wgsmax_lat- wgsmin_lat
seclected_area=plt.Rectangle(rec_xy, rec_width, rec_height, edgecolor='black',facecolor='none',linestyle='--',linewidth=0.5,zorder=3,alpha=0.8)
ax.add_patch(seclected_area)
radius_circle=unit_x/4
layer_num=2
centroid_x=new_bounds[0]+unit_x
centroid_y=new_bounds[1]+unit_y
centroid_forcircle=(centroid_x,centroid_y)
circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
ax.add_patch(circle)
x_dataforline=[centroid_x,centroid_x]
y_dataforline=[centroid_y,centroid_y+radius_circle]
line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
x_datafortext=centroid_x
y_datafortext=centroid_y+radius_circle
ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
lat_average=(new_bounds[1]+new_bounds[3])/2
bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
text_y=bar_startpt[1]+radius_circle
teztsize=10
layer_num=2
delta_x=111*1000*0.01*math.cos(math.radians(lat_average))
unit_distance=unit_x*delta_x/0.01
if unit_distance/2>100:
nereast_num=int(unit_distance/100)*100
lon_randon=unit_x*nereast_num/unit_distance
barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
barran_ypt=(bar_startpt[1],bar_startpt[1])
barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
barran3_ypt=(bar_startpt[1],bar_startpt[1])
barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
ax.legend(title='category_english', loc='upper right')
else:
num=100
lon100=unit_x*num/unit_distance
bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
bar100_ypt=(bar_startpt[1],bar_startpt[1])
bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
bar300_ypt=(bar_startpt[1],bar_startpt[1])
bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
ax.legend(title='category_english', loc='upper right')
now = datetime.now()
timestamp = now.strftime("%Y%m%d%H%M%S")
poi_file_name = f"savepoi_{timestamp}.jpg"
poi_file_path = os.path.join(os.getcwd(), poi_file_name)
svg_poiname=f"savepoi_{timestamp}.svg"
svg_poipath=os.path.join(os.getcwd(),svg_poiname)
poi_dis_file=plt.savefig(poi_file_path, dpi=300)
svgpoifile=fig.savefig(svg_poipath, format='svg', transparent=True)
return [poi_file_name,svg_poiname,run_count2,'区域选择符合限制',message_box]
else:
blankfig=plt.figure(figsize=(14,10),dpi = 100)
ax = blankfig.add_subplot(111)
now = datetime.now()
timestamp = now.strftime("%Y%m%d%H%M%S")
poi_file_name = f"savepoi_{timestamp}.jpg"
poi_file_path = os.path.join(os.getcwd(), poi_file_name)
svg_poiname=f"savepoi_{timestamp}.svg"
svg_poipath=os.path.join(os.getcwd(),svg_poiname)
poi_dis_file=plt.savefig(poi_file_path, dpi=300)
svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
message_box="None"
return [poi_file_name,svg_poiname,run_count2,"区域过大,超过3KM限制",message_box]
def POI_kernel(location1,location2,category):
global run_count3
run_count3 += 1
print("POI密度分析已运行{}次".format(run_count3))
min_long=float(location1.split(",")[0])
min_lat=float(location1.split(",")[1])
max_long=float(location2.split(",")[0])
max_lat=float(location2.split(",")[1])
long_bounds=max_long-min_long
lat_bounds=max_lat-min_lat
coords_lat_average=(min_lat+max_lat)/2
coords_delta_x=111*1000*0.01*math.cos(math.radians(coords_lat_average))
long_meterdif=long_bounds*coords_delta_x/0.01
lat_meterdif=lat_bounds/111*1000
print(long_meterdif)
print(lat_meterdif)
if lat_meterdif <3000 and long_meterdif <3000:
categories=[category]
location=[location1,location2]
gdf_output=POI_baidu_distribution.POI_get(location,categories)#获得所有的点
if len(gdf_output)==0:
blankfig=plt.figure(figsize=(14,10),dpi = 100)
ax = blankfig.add_subplot(111)
now = datetime.now()
timestamp = now.strftime("%Y%m%d%H%M%S")
poi_file_name = f"savepoi_{timestamp}.jpg"
poi_file_path = os.path.join(os.getcwd(), poi_file_name)
svg_poiname=f"savepoi_{timestamp}.svg"
svg_poipath=os.path.join(os.getcwd(),svg_poiname)
poi_dis_file=plt.savefig(poi_file_path, dpi=300)
svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
message_box="区域内没有该类型POI点"
return [poi_file_name,svg_poiname,run_count2,'区域选择符合限制',message_box]
else:
message_box="POI获取正常"
# matplotlib.rc("font",family='DengXian')
fig = plt.figure(figsize=(14,10),dpi = 100)
ax = fig.add_subplot(111)
wgsmin_long, wgsmin_lat=cconv.bd09_to_wgs84(min_long,min_lat)
wgsmax_long,wgsmax_lat=cconv.bd09_to_wgs84(max_long,max_lat)
scale_factor = 3
rec_bounds = [wgsmin_long - (wgsmax_long - wgsmin_long)/scale_factor,
wgsmin_lat - (wgsmax_lat -wgsmin_lat)/scale_factor,
wgsmax_long + (wgsmax_long - wgsmin_long)/scale_factor,
wgsmax_lat + (wgsmax_lat - wgsmin_lat)/scale_factor]
bounds=[rec_bounds[0],rec_bounds[1],rec_bounds[2],rec_bounds[3]]
difference_x = bounds[2] - bounds[0]
difference_y = bounds[3] - bounds[1]
target_scale=29.7/21
recent_scale=difference_x/difference_y
print(recent_scale)
if recent_scale>target_scale:
target_Dy=difference_x*21/29.7
bounds[3]=bounds[3]+(target_Dy-difference_y)/2
bounds[1]=bounds[1]-(target_Dy-difference_y)/2
elif recent_scale<target_scale:
target_Dx=difference_y*29.7/21
bounds[2]=bounds[2]+(target_Dx-difference_x)/2
bounds[0]=bounds[0]-(target_Dx-difference_x)/2
else:
pass
new_bounds = [round(bounds[0],6), round(bounds[1],6), round(bounds[2],6), round(bounds[3],6)]
ax.set_xlim(new_bounds[0],new_bounds[2])
ax.set_ylim(new_bounds[1],new_bounds[3])
new_dif_x=new_bounds[2]-new_bounds[0]
new_dif_y=new_bounds[3]-new_bounds[1]
unit_x=new_dif_x/14
unit_y=new_dif_y/10
list_new_x=[new_bounds[0]+unit_x*i for i in range(14)]
list_new_y=[new_bounds[1]+unit_y*i for i in range(10)]
plt.xticks(list_new_x)
plt.yticks(list_new_y)
plt.grid(True,zorder=1,alpha=0.5)
plot_map.plot_map(plt,new_bounds,zoom =16,style = 4)
grouped = gdf_output.groupby('category_english')
for group_name, group_data in grouped:
ax.scatter(group_data.geometry.x, group_data.geometry.y, label=group_name, alpha=0.5,zorder=2)
sns.kdeplot(gdf_output,x="lng_wgs84",y="lat_wgs84",fill=True,alpha=.5,hue='category_english',legend=True,color="grey")
radius_circle=unit_x/4
layer_num=2
centroid_x=new_bounds[0]+unit_x
centroid_y=new_bounds[1]+unit_y
centroid_forcircle=(centroid_x,centroid_y)
circle=plt.Circle(centroid_forcircle,radius=radius_circle,edgecolor='black',facecolor=(0, 0, 0, 0),linewidth=1,zorder=layer_num)
ax.add_patch(circle)
x_dataforline=[centroid_x,centroid_x]
y_dataforline=[centroid_y,centroid_y+radius_circle]
line_new=ax.plot(x_dataforline,y_dataforline,color='black',linewidth=2,zorder=layer_num)
x_datafortext=centroid_x
y_datafortext=centroid_y+radius_circle
ax.text(x_datafortext,y_datafortext, 'N', color='black', fontsize=10, ha='center', va='bottom',zorder=layer_num)
lat_average=(new_bounds[1]+new_bounds[3])/2
bar_startpt=(new_bounds[0]+unit_x*2,new_bounds[1]+unit_y)
text_y=bar_startpt[1]+radius_circle
teztsize=10
layer_num=2
delta_x=111*1000*0.01*math.cos(math.radians(lat_average))
unit_distance=unit_x*delta_x/0.01
if unit_distance/2>100:
nereast_num=int(unit_distance/100)*100
lon_randon=unit_x*nereast_num/unit_distance
barran_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon)
barran_ypt=(bar_startpt[1],bar_startpt[1])
barran=ax.plot(barran_xpt,barran_ypt,color='black',linewidth=5,zorder=3)
barran3_xpt=(bar_startpt[0],bar_startpt[0]+lon_randon*3)
barran3_ypt=(bar_startpt[1],bar_startpt[1])
barran3 = ax.plot(barran3_xpt, barran3_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
ax.text(barran_xpt[1],text_y, f"{nereast_num}M", color='black', fontsize=teztsize, ha='center', va='bottom')
ax.text(barran3_xpt[1],text_y, f"{nereast_num*3}M", color='black', fontsize=teztsize, ha='center', va='bottom')
ax.legend(title='category_english',loc='upper right')
else:
num=100
lon100=unit_x*num/unit_distance
bar100_xpt=(bar_startpt[0],bar_startpt[0]+lon100)
bar100_ypt=(bar_startpt[1],bar_startpt[1])
bar100=ax.plot(bar100_xpt,bar100_ypt,color='black',linewidth=5,zorder=3)
bar300_xpt=(bar_startpt[0],bar_startpt[0]+lon100*3)
bar300_ypt=(bar_startpt[1],bar_startpt[1])
bar300 = ax.plot(bar300_xpt, bar300_ypt, color='black', linewidth=5, zorder=2, alpha=0.5)
ax.text(bar_startpt[0],text_y, '0M', color='black', fontsize=teztsize, ha='center', va='bottom')
ax.text(bar100_xpt[1],text_y, '100M', color='black', fontsize=teztsize, ha='center', va='bottom')
ax.text(bar300_xpt[1],text_y, '300M', color='black', fontsize=teztsize, ha='center', va='bottom')
ax.legend(title='category_english',loc='upper right')
now = datetime.now()
timestamp = now.strftime("%Y%m%d%H%M%S")
poiker_file_name = f"savepoiker_{timestamp}.jpg"
poiker_file_path = os.path.join(os.getcwd(), poiker_file_name)
svgker_name=f"savepoiker_{timestamp}.svg"
svgker_path=os.path.join(os.getcwd(),svgker_name)
poi_ker_file= plt.savefig(poiker_file_path, dpi=300)
svgkerfile=fig.savefig(svgker_path, format='svg', transparent=True)
print(f"文件保存路径:{poiker_file_path}")
return [poiker_file_name,svgker_name,run_count3,'区域选择符合限制', message_box]
else:
blankfig=plt.figure(figsize=(14,10),dpi = 100)
ax = blankfig.add_subplot(111)
now = datetime.now()
timestamp = now.strftime("%Y%m%d%H%M%S")
poi_file_name = f"savepoi_{timestamp}.jpg"
poi_file_path = os.path.join(os.getcwd(), poi_file_name)
svg_poiname=f"savepoi_{timestamp}.svg"
svg_poipath=os.path.join(os.getcwd(),svg_poiname)
poi_dis_file=plt.savefig(poi_file_path, dpi=300)
svgpoifile=blankfig.savefig(svg_poipath, format='svg', transparent=True)
message_box="None"
return [poi_file_name,svg_poiname,run_count3,"区域过大,超过3KM限制",message_box]
with gr.Blocks() as demo:
gr.Markdown(
"""
# UrbanFlow-DataAnalysis
使用说明和更多关于UrbanFlow的详情请查看链接:[UrbanFlow-DataAnalysis使用说明](https://gdz6btft72.feishu.cn/docx/E0pxd8pXpo4wOQxZ8eic7iSqnXc)
如果您遇到排队较长或出图缓慢的情况,可以使用下列备用连接:[备用链接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)
"""
)
with gr.Tab("等时圈分析"):
with gr.Row():
with gr.Column():
gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取坐标点,并输入最多六个角点坐标来对您想生成等时圈的区域进行控制")
with gr.Row():
co_input = [gr.Textbox(label=f"坐标角点参数 {i}", placeholder=f"请输入参数 {i}") for i in range(1, 7)]
drop1 = gr.CheckboxGroup(["walking","cycling","driving"], label="选择出行方式")
#box2=gr.Textbox()
drop2 = gr.CheckboxGroup(["5","10","15","20","25","30"], label="选择时间(min)")
report=gr.Textbox(label="报错提醒")
with gr.Column():
output_img = gr.Image()
output_svgpath = gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
output_count=gr.Textbox(label="本页面已提供一键生图次数")
cal_btn = gr.Button("Calculate")
# sav_svg = gr.DownloadButton("Save as SVG")
cal_btn.click(fn=isochrone, inputs=[drop2]+[drop1]+co_input, outputs=[output_img,output_svgpath,output_count,report])
# sav_svg.click(fn=isochrone,inputs=[drop2]+[drop1]+co_input,outputs=[output_svgpath])
gr.Markdown("""
## 输入参数示例
""")
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"]]
gr.Examples(examples=examples_index,inputs=[drop2]+[drop1]+co_input,outputs=output_img,fn=isochrone,label="examples")
with gr.Tab("POI分布图"):
with gr.Row():
with gr.Column():
gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
with gr.Row():
POI_input1 = [gr.Textbox(label=f"左下角角点坐标", placeholder="请输入<左下角>角点坐标"),
gr.Textbox(label=f"右上角角点坐标", placeholder="请输入<右上角>角点坐标")
]
with gr.Row():
POI_input2=gr.CheckboxGroup(["住宅区","公共服务设施-文化设施","公共服务设施-学校","公共服务设施-体育设施","公共服务设施-医疗卫生","商业服务设施-餐饮","商业服务设施-酒店","商业服务设施-购物中心","商业服务设施-超市&便利店","商业服务设施-公司企业","商业服务设施-娱乐康体","交通设施-公共交通站点","交通设施-停车场","绿地-公园","绿地-旅游景点","生活服务"],label="请选择您需要的POI类型")
with gr.Row():
with gr.Column():
report=gr.Textbox(label="区域限制报错提醒")
report2=gr.Textbox(label="POI数据获取报错提醒")
with gr.Column():
POI_output1=gr.Image(label="POI分布图")
POI_output2=gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
output_count=gr.Textbox(label="本页面已提供一键生图次数")
cal_btn = gr.Button("Calculate")
cal_btn.click(fn=POI_distribution, inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2,output_count,report,report2])
gr.Markdown("""
## 输入参数示例
""")
examples_index=[["113.923428,22.491367","113.930983,22.495825",['商业服务设施-娱乐康体','公共服务设施-学校']],["113.930938,22.522402","113.942185,22.531515",['公共服务设施-学校','商业服务设施-餐饮']]]
gr.Examples(examples=examples_index,inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2],fn=POI_distribution,label="examples")
with gr.Tab("POI密度图"):
with gr.Row():
with gr.Column():
gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
with gr.Row():
POI_input1 = [gr.Textbox(label=f"左下角角点坐标", placeholder="请输入<左下角>角点坐标"),
gr.Textbox(label=f"右上角角点坐标", placeholder="请输入<右上角>角点坐标")
]
POI_input2=gr.Radio(["住宅区","公共服务设施-文化设施","公共服务设施-学校","公共服务设施-体育设施","公共服务设施-医疗卫生","商业服务设施-餐饮","商业服务设施-酒店","商业服务设施-购物中心","商业服务设施-超市&便利店","商业服务设施-公司企业","商业服务设施-娱乐康体","交通设施-公共交通站点","交通设施-停车场","绿地-公园","绿地-旅游景点","生活服务"],label="请选择您需要的POI类型")
with gr.Row():
with gr.Column():
report=gr.Textbox(label="区域限制报错提醒")
report2=gr.Textbox(label="POI数据获取报错提醒")
with gr.Column():
POI_output1=gr.Image(label="POI密度图")
POI_output2=gr.File(label="下载可编辑文件(可用Adobe Illustrator打开)", file_count="single", file_types=[".svg"])
output_count=gr.Textbox(label="本页面已提供一键生图次数")
cal_btn = gr.Button("Calculate")
cal_btn.click(fn=POI_kernel, inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2,output_count,report,report2])
gr.Markdown("""
## 输入参数示例
""")
examples_index=[["113.923428,22.491367","113.930983,22.495825",'商业服务设施-娱乐康体'],["113.930938,22.522402","113.942185,22.531515",'商业服务设施-餐饮']]
gr.Examples(examples=examples_index,inputs=POI_input1+[POI_input2], outputs=[POI_output1,POI_output2],fn=POI_kernel,label="examples")
with gr.Tab("今天吃什么"):
with gr.Row():
with gr.Column():
gr.Markdown("您可以从https://api.map.baidu.com/lbsapi/getpoint/index.html 百度坐标拾取系统获取您的当前坐标点")
foodlist_input1 = gr.Textbox(label="您所在位置的坐标点",placeholder="输入您所在位置的坐标点")
foodlist_input2=gr.Radio(["正餐","下午茶"],label="餐食类型")
foodlist_input3=gr.Slider(label="您愿意步行的距离(min)",minimum=0, maximum=10, step=1)
foodlist_btn=gr.Button("开始丢骰子")
foodlist_output=gr.Textbox(label="今天吃什么",lines=5)
with gr.Row():
output_count=gr.Textbox(label="本页面已提供一键生图次数")
textbox=gr.Textbox(label="报错提醒")
foodlist_btn.click(fn=random_foodchoice,inputs=[foodlist_input1,foodlist_input2,foodlist_input3],outputs=[foodlist_output,output_count,textbox])
gr.Markdown("""
## 输入参数示例
""")
examples_index=[["113.924838,22.492807","正餐","10"],["113.924838,22.492807","下午茶","5"]]
gr.Examples(examples=examples_index,inputs=[foodlist_input1,foodlist_input2,foodlist_input3],outputs=foodlist_output,fn=random_foodchoice,label="examples")
demo.launch(share=True)