Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,6 +4,7 @@
|
|
| 4 |
import os
|
| 5 |
import time
|
| 6 |
import tempfile
|
|
|
|
| 7 |
import requests
|
| 8 |
import pandas as pd
|
| 9 |
import numpy as np
|
|
@@ -11,7 +12,7 @@ import geopandas as gpd
|
|
| 11 |
from shapely.geometry import Point
|
| 12 |
import gradio as gr
|
| 13 |
from keplergl import KeplerGl
|
| 14 |
-
import html as _html # srcdoc
|
| 15 |
|
| 16 |
# ----------------------------
|
| 17 |
# 設定
|
|
@@ -28,9 +29,6 @@ CACHE_DIR = "data/cache"
|
|
| 28 |
os.makedirs(CACHE_DIR, exist_ok=True)
|
| 29 |
CACHE_PATH = os.path.join(CACHE_DIR, "geocode_cache.csv")
|
| 30 |
|
| 31 |
-
# Mapbox トークン(背景地図)
|
| 32 |
-
MAPBOX_TOKEN = os.environ.get("MAPBOX_API_KEY", "")
|
| 33 |
-
|
| 34 |
# ----------------------------
|
| 35 |
# キャッシュ
|
| 36 |
# ----------------------------
|
|
@@ -69,6 +67,7 @@ def gsi_geocode_once(address: str, session: requests.Session) -> tuple[float, fl
|
|
| 69 |
try:
|
| 70 |
if not address or str(address).strip() == "" or str(address).strip().lower() in ("nan", "none"):
|
| 71 |
return (np.nan, np.nan)
|
|
|
|
| 72 |
resp = session.get(GSI_GEOCODE_URL, params={"q": address}, timeout=GSI_TIMEOUT_SEC)
|
| 73 |
if not resp.ok:
|
| 74 |
return (np.nan, np.nan)
|
|
@@ -125,17 +124,43 @@ def geocode_with_cache(addresses, CFs, use_internet=True):
|
|
| 125 |
return df
|
| 126 |
|
| 127 |
# ----------------------------
|
| 128 |
-
# Kepler.gl HTML 生成(srcdoc
|
| 129 |
# ----------------------------
|
| 130 |
def _iframe_from_srcdoc(html_text: str, height: int = 640) -> str:
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
| 133 |
escaped = _html.escape(html_text, quote=True)
|
| 134 |
return (
|
| 135 |
f'<iframe style="border:0;width:100%;height:{height}px" '
|
| 136 |
f'sandbox="allow-scripts allow-same-origin" srcdoc="{escaped}"></iframe>'
|
| 137 |
)
|
| 138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
|
| 140 |
df_valid = df_points.dropna(subset=["lat", "lon"]).copy()
|
| 141 |
df_valid["lat"] = pd.to_numeric(df_valid["lat"], errors="coerce")
|
|
@@ -143,6 +168,7 @@ def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
|
|
| 143 |
if "CF" in df_valid.columns:
|
| 144 |
df_valid["CF"] = pd.to_numeric(df_valid["CF"], errors="coerce")
|
| 145 |
|
|
|
|
| 146 |
map_state = {"bearing": 0, "pitch": 0, "zoom": 6}
|
| 147 |
if not df_valid.empty:
|
| 148 |
map_state["latitude"] = float(df_valid["lat"].median())
|
|
@@ -150,6 +176,7 @@ def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
|
|
| 150 |
else:
|
| 151 |
map_state.update({"latitude": 35.0, "longitude": 135.0, "zoom": 4})
|
| 152 |
|
|
|
|
| 153 |
layer_config = {
|
| 154 |
"id": "point_layer",
|
| 155 |
"type": "point",
|
|
@@ -166,6 +193,24 @@ def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
|
|
| 166 |
if "CF" in df_valid.columns and df_valid["CF"].notna().any():
|
| 167 |
layer_config["visualChannels"]["sizeField"] = {"name": "CF", "type": "real"}
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
config = {
|
| 170 |
"version": "v1",
|
| 171 |
"config": {
|
|
@@ -191,23 +236,34 @@ def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
|
|
| 191 |
},
|
| 192 |
"mapState": map_state,
|
| 193 |
"mapStyle": {
|
| 194 |
-
"styleType": "
|
| 195 |
"topLayerGroups": {},
|
| 196 |
-
"visibleLayerGroups": {"label": True, "road": True, "border": False, "building": False, "water": True, "land": True}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
},
|
| 198 |
},
|
| 199 |
}
|
| 200 |
|
| 201 |
-
|
|
|
|
| 202 |
if not df_valid.empty:
|
| 203 |
m.add_data(data=df_valid[["lat","lon","address_input","CF"]], name="points")
|
| 204 |
|
| 205 |
-
#
|
| 206 |
with tempfile.NamedTemporaryFile(suffix=".html", delete=False) as f:
|
| 207 |
path = f.name
|
| 208 |
m.save_to_html(file_name=path, read_only=True)
|
| 209 |
with open(path, "r", encoding="utf-8") as fh:
|
| 210 |
kepler_html = fh.read()
|
|
|
|
|
|
|
| 211 |
return _iframe_from_srcdoc(kepler_html, height=height)
|
| 212 |
|
| 213 |
# ----------------------------
|
|
@@ -220,6 +276,7 @@ def _parse_indexer(x):
|
|
| 220 |
return x
|
| 221 |
|
| 222 |
def run(excel_file, sheet_name, header_row, address_col, power_col, use_inet):
|
|
|
|
| 223 |
if excel_file is None or not hasattr(excel_file, "name"):
|
| 224 |
table_df = pd.DataFrame(columns=["address_input", "CF", "lat", "lon"])
|
| 225 |
return "", table_df, "Excelファイルを指定してください。"
|
|
@@ -230,6 +287,7 @@ def run(excel_file, sheet_name, header_row, address_col, power_col, use_inet):
|
|
| 230 |
empty_df = pd.DataFrame(columns=["address_input", "CF", "lat", "lon"])
|
| 231 |
return "", empty_df, f"Excel の読み込みに失敗しました: {e}"
|
| 232 |
|
|
|
|
| 233 |
addr_series = df.iloc[:, address_col] if isinstance(address_col, int) else df[address_col]
|
| 234 |
cf_series = df.iloc[:, power_col] if isinstance(power_col, int) else df[power_col]
|
| 235 |
|
|
@@ -239,21 +297,22 @@ def run(excel_file, sheet_name, header_row, address_col, power_col, use_inet):
|
|
| 239 |
geo_df = geocode_with_cache(addresses, cfs, use_internet=bool(use_inet))
|
| 240 |
table_df = geo_df[["address_input", "CF", "lat", "lon"]].copy()
|
| 241 |
|
|
|
|
| 242 |
geometry = [
|
| 243 |
Point(lon, lat) if (pd.notna(lat) and pd.notna(lon)) else None
|
| 244 |
for lat, lon in zip(geo_df["lat"], geo_df["lon"])
|
| 245 |
]
|
| 246 |
gdf_pts = gpd.GeoDataFrame(geo_df, geometry=geometry, crs="EPSG:4326")
|
| 247 |
|
|
|
|
| 248 |
try:
|
| 249 |
html_iframe = make_kepler_html(table_df, height=640)
|
| 250 |
except Exception as e:
|
| 251 |
html_iframe = f"<p>Kepler.gl描画に失敗しました: {e}</p>"
|
| 252 |
|
|
|
|
| 253 |
info = []
|
| 254 |
info.append(f"ポイント数(有効座標): {int(gdf_pts.geometry.notnull().sum())} / {len(gdf_pts)}")
|
| 255 |
-
if not MAPBOX_TOKEN:
|
| 256 |
-
info.append("⚠ 背景地図タイル表示のため MAPBOX_API_KEY の設定を推奨(未設定だと背景が真っ白になる場合があります)")
|
| 257 |
|
| 258 |
return html_iframe, table_df, "\n".join(info)
|
| 259 |
|
|
@@ -261,7 +320,7 @@ def run(excel_file, sheet_name, header_row, address_col, power_col, use_inet):
|
|
| 261 |
# Gradio UI(ポイントのみ)
|
| 262 |
# ----------------------------
|
| 263 |
with gr.Blocks(title="Excel住所 → Kepler.gl(ポイントのみ)") as demo:
|
| 264 |
-
gr.Markdown("## Excelの住所を国土地理院APIでジオコーディング → Kepler.gl に **ポイントのみ** を描画")
|
| 265 |
|
| 266 |
with gr.Row():
|
| 267 |
xlsx_in = gr.File(label="Excelファイル(住所付き)", file_count="single", file_types=[".xlsx", ".xls"])
|
|
@@ -281,7 +340,7 @@ with gr.Blocks(title="Excel住所 → Kepler.gl(ポイントのみ)") as dem
|
|
| 281 |
|
| 282 |
out_html = gr.HTML(label="インタラクティブ地図(Kepler.gl:ポイントのみ)")
|
| 283 |
out_table = gr.Dataframe(label="ジオコーディング結果(住所・緯度・経度・CF)", wrap=True)
|
| 284 |
-
out_info = gr.Textbox(label="メタ情報", lines=
|
| 285 |
|
| 286 |
def _parse(x):
|
| 287 |
try:
|
|
|
|
| 4 |
import os
|
| 5 |
import time
|
| 6 |
import tempfile
|
| 7 |
+
import re
|
| 8 |
import requests
|
| 9 |
import pandas as pd
|
| 10 |
import numpy as np
|
|
|
|
| 12 |
from shapely.geometry import Point
|
| 13 |
import gradio as gr
|
| 14 |
from keplergl import KeplerGl
|
| 15 |
+
import html as _html # for srcdoc escaping
|
| 16 |
|
| 17 |
# ----------------------------
|
| 18 |
# 設定
|
|
|
|
| 29 |
os.makedirs(CACHE_DIR, exist_ok=True)
|
| 30 |
CACHE_PATH = os.path.join(CACHE_DIR, "geocode_cache.csv")
|
| 31 |
|
|
|
|
|
|
|
|
|
|
| 32 |
# ----------------------------
|
| 33 |
# キャッシュ
|
| 34 |
# ----------------------------
|
|
|
|
| 67 |
try:
|
| 68 |
if not address or str(address).strip() == "" or str(address).strip().lower() in ("nan", "none"):
|
| 69 |
return (np.nan, np.nan)
|
| 70 |
+
|
| 71 |
resp = session.get(GSI_GEOCODE_URL, params={"q": address}, timeout=GSI_TIMEOUT_SEC)
|
| 72 |
if not resp.ok:
|
| 73 |
return (np.nan, np.nan)
|
|
|
|
| 124 |
return df
|
| 125 |
|
| 126 |
# ----------------------------
|
| 127 |
+
# Kepler.gl HTML 生成(srcdoc + MapLibre 置換)
|
| 128 |
# ----------------------------
|
| 129 |
def _iframe_from_srcdoc(html_text: str, height: int = 640) -> str:
|
| 130 |
+
"""
|
| 131 |
+
ローカルファイル参照を使わず、生成HTMLを直接 <iframe srcdoc="..."> で埋め込む。
|
| 132 |
+
Gradio の HTML コンポーネントに安全に渡せるようエスケープして返す。
|
| 133 |
+
"""
|
| 134 |
escaped = _html.escape(html_text, quote=True)
|
| 135 |
return (
|
| 136 |
f'<iframe style="border:0;width:100%;height:{height}px" '
|
| 137 |
f'sandbox="allow-scripts allow-same-origin" srcdoc="{escaped}"></iframe>'
|
| 138 |
)
|
| 139 |
|
| 140 |
+
def _patch_to_maplibre(html_text: str) -> str:
|
| 141 |
+
"""
|
| 142 |
+
keplergl が出力する HTML の Mapbox GL 参照を MapLibre GL に置換。
|
| 143 |
+
さらに window.mapboxgl -> window.maplibregl の互換エイリアスを注入。
|
| 144 |
+
"""
|
| 145 |
+
# CSS/JS の置換(Mapbox CDN → unpkg の MapLibre)
|
| 146 |
+
html_text = re.sub(
|
| 147 |
+
r"https://api\.tiles\.mapbox\.com/mapbox-gl-js/v[\d.]+/mapbox-gl\.css",
|
| 148 |
+
"https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.css",
|
| 149 |
+
html_text
|
| 150 |
+
)
|
| 151 |
+
html_text = re.sub(
|
| 152 |
+
r"https://api\.tiles\.mapbox\.com/mapbox-gl-js/v[\d.]+/mapbox-gl\.js",
|
| 153 |
+
"https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.js",
|
| 154 |
+
html_text
|
| 155 |
+
)
|
| 156 |
+
# 互換エイリアスが未挿入なら </head> 直前に追加
|
| 157 |
+
if "window.mapboxgl = window.maplibregl" not in html_text:
|
| 158 |
+
html_text = html_text.replace(
|
| 159 |
+
"</head>",
|
| 160 |
+
"<script>window.mapboxgl = window.maplibregl;</script></head>"
|
| 161 |
+
)
|
| 162 |
+
return html_text
|
| 163 |
+
|
| 164 |
def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
|
| 165 |
df_valid = df_points.dropna(subset=["lat", "lon"]).copy()
|
| 166 |
df_valid["lat"] = pd.to_numeric(df_valid["lat"], errors="coerce")
|
|
|
|
| 168 |
if "CF" in df_valid.columns:
|
| 169 |
df_valid["CF"] = pd.to_numeric(df_valid["CF"], errors="coerce")
|
| 170 |
|
| 171 |
+
# 地図中心
|
| 172 |
map_state = {"bearing": 0, "pitch": 0, "zoom": 6}
|
| 173 |
if not df_valid.empty:
|
| 174 |
map_state["latitude"] = float(df_valid["lat"].median())
|
|
|
|
| 176 |
else:
|
| 177 |
map_state.update({"latitude": 35.0, "longitude": 135.0, "zoom": 4})
|
| 178 |
|
| 179 |
+
# ポイントレイヤ
|
| 180 |
layer_config = {
|
| 181 |
"id": "point_layer",
|
| 182 |
"type": "point",
|
|
|
|
| 193 |
if "CF" in df_valid.columns and df_valid["CF"].notna().any():
|
| 194 |
layer_config["visualChannels"]["sizeField"] = {"name": "CF", "type": "real"}
|
| 195 |
|
| 196 |
+
# --- 無料ベースマップ(地理院タイル:標準地図) ---
|
| 197 |
+
gsi_raster_style = {
|
| 198 |
+
"version": 8,
|
| 199 |
+
"sources": {
|
| 200 |
+
"gsi": {
|
| 201 |
+
"type": "raster",
|
| 202 |
+
"tiles": [
|
| 203 |
+
"https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png"
|
| 204 |
+
],
|
| 205 |
+
"tileSize": 256,
|
| 206 |
+
"attribution": "© <a href='https://www.gsi.go.jp/' target='_blank'>GSI</a>"
|
| 207 |
+
}
|
| 208 |
+
},
|
| 209 |
+
"layers": [
|
| 210 |
+
{"id": "gsi", "type": "raster", "source": "gsi", "minzoom": 0, "maxzoom": 18}
|
| 211 |
+
]
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
config = {
|
| 215 |
"version": "v1",
|
| 216 |
"config": {
|
|
|
|
| 236 |
},
|
| 237 |
"mapState": map_state,
|
| 238 |
"mapStyle": {
|
| 239 |
+
"styleType": "gsi_std", # ← カスタムスタイルを指定
|
| 240 |
"topLayerGroups": {},
|
| 241 |
+
"visibleLayerGroups": {"label": True, "road": True, "border": False, "building": False, "water": True, "land": True},
|
| 242 |
+
"mapStyles": {
|
| 243 |
+
"gsi_std": {
|
| 244 |
+
"id": "gsi_std",
|
| 245 |
+
"label": "GSI Standard",
|
| 246 |
+
"style": gsi_raster_style,
|
| 247 |
+
"accessToken": None
|
| 248 |
+
}
|
| 249 |
+
}
|
| 250 |
},
|
| 251 |
},
|
| 252 |
}
|
| 253 |
|
| 254 |
+
# KeplerGl インスタンス(Mapbox トークン不要)
|
| 255 |
+
m = KeplerGl(height=height, data={}, config=config, mapbox_api_key="")
|
| 256 |
if not df_valid.empty:
|
| 257 |
m.add_data(data=df_valid[["lat","lon","address_input","CF"]], name="points")
|
| 258 |
|
| 259 |
+
# HTML 保存 → 読み込み → MapLibre 置換 → srcdoc 埋め込み
|
| 260 |
with tempfile.NamedTemporaryFile(suffix=".html", delete=False) as f:
|
| 261 |
path = f.name
|
| 262 |
m.save_to_html(file_name=path, read_only=True)
|
| 263 |
with open(path, "r", encoding="utf-8") as fh:
|
| 264 |
kepler_html = fh.read()
|
| 265 |
+
|
| 266 |
+
kepler_html = _patch_to_maplibre(kepler_html)
|
| 267 |
return _iframe_from_srcdoc(kepler_html, height=height)
|
| 268 |
|
| 269 |
# ----------------------------
|
|
|
|
| 276 |
return x
|
| 277 |
|
| 278 |
def run(excel_file, sheet_name, header_row, address_col, power_col, use_inet):
|
| 279 |
+
# Excel 読み込み
|
| 280 |
if excel_file is None or not hasattr(excel_file, "name"):
|
| 281 |
table_df = pd.DataFrame(columns=["address_input", "CF", "lat", "lon"])
|
| 282 |
return "", table_df, "Excelファイルを指定してください。"
|
|
|
|
| 287 |
empty_df = pd.DataFrame(columns=["address_input", "CF", "lat", "lon"])
|
| 288 |
return "", empty_df, f"Excel の読み込みに失敗しました: {e}"
|
| 289 |
|
| 290 |
+
# 列の参照(番号/名前の両対応)
|
| 291 |
addr_series = df.iloc[:, address_col] if isinstance(address_col, int) else df[address_col]
|
| 292 |
cf_series = df.iloc[:, power_col] if isinstance(power_col, int) else df[power_col]
|
| 293 |
|
|
|
|
| 297 |
geo_df = geocode_with_cache(addresses, cfs, use_internet=bool(use_inet))
|
| 298 |
table_df = geo_df[["address_input", "CF", "lat", "lon"]].copy()
|
| 299 |
|
| 300 |
+
# GeoDataFrame(将来拡張用)
|
| 301 |
geometry = [
|
| 302 |
Point(lon, lat) if (pd.notna(lat) and pd.notna(lon)) else None
|
| 303 |
for lat, lon in zip(geo_df["lat"], geo_df["lon"])
|
| 304 |
]
|
| 305 |
gdf_pts = gpd.GeoDataFrame(geo_df, geometry=geometry, crs="EPSG:4326")
|
| 306 |
|
| 307 |
+
# Kepler.gl(ポイントのみ)
|
| 308 |
try:
|
| 309 |
html_iframe = make_kepler_html(table_df, height=640)
|
| 310 |
except Exception as e:
|
| 311 |
html_iframe = f"<p>Kepler.gl描画に失敗しました: {e}</p>"
|
| 312 |
|
| 313 |
+
# 情報
|
| 314 |
info = []
|
| 315 |
info.append(f"ポイント数(有効座標): {int(gdf_pts.geometry.notnull().sum())} / {len(gdf_pts)}")
|
|
|
|
|
|
|
| 316 |
|
| 317 |
return html_iframe, table_df, "\n".join(info)
|
| 318 |
|
|
|
|
| 320 |
# Gradio UI(ポイントのみ)
|
| 321 |
# ----------------------------
|
| 322 |
with gr.Blocks(title="Excel住所 → Kepler.gl(ポイントのみ)") as demo:
|
| 323 |
+
gr.Markdown("## Excelの住所を国土地理院APIでジオコーディング → Kepler.gl に **ポイントのみ** を描画(Mapbox不要・無料タイル)")
|
| 324 |
|
| 325 |
with gr.Row():
|
| 326 |
xlsx_in = gr.File(label="Excelファイル(住所付き)", file_count="single", file_types=[".xlsx", ".xls"])
|
|
|
|
| 340 |
|
| 341 |
out_html = gr.HTML(label="インタラクティブ地図(Kepler.gl:ポイントのみ)")
|
| 342 |
out_table = gr.Dataframe(label="ジオコーディング結果(住所・緯度・経度・CF)", wrap=True)
|
| 343 |
+
out_info = gr.Textbox(label="メタ情報", lines=2)
|
| 344 |
|
| 345 |
def _parse(x):
|
| 346 |
try:
|