Spaces:
Sleeping

hiroki0008 commited on
Commit
7cd3fef
·
verified ·
1 Parent(s): 447ac56

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -33
app.py CHANGED
@@ -3,8 +3,9 @@
3
 
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,8 +13,6 @@ import geopandas as gpd
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
- import urllib.parse
17
 
18
  # ----------------------------
19
  # 設定
@@ -95,7 +94,7 @@ def geocode_with_cache(addresses, CFs, use_internet=True):
95
 
96
  # cache hit
97
  if a in cache_map:
98
- lat, lon, cached_cf = cache_map[a]
99
  if pd.notna(lat) and pd.notna(lon):
100
  results.append({"address_input": a, "CF": cf_num, "lat": float(lat), "lon": float(lon)})
101
  continue
@@ -125,17 +124,15 @@ def geocode_with_cache(addresses, CFs, use_internet=True):
125
  return df
126
 
127
  # ----------------------------
128
- # Kepler.gl HTML 生成(srcdoc + MapLibre 置換)
129
  # ----------------------------
130
  def _iframe_from_dataurl(html_text: str, height: int = 640) -> str:
131
- # URL エンコードして data:URL にする(script 実行OK / 外部CDNも読み込める)
132
  data_url = "data:text/html;charset=utf-8," + urllib.parse.quote(html_text)
133
- return (
134
- f'<iframe src="{data_url}" '
135
- f'style="border:0;width:100%;height:{height}px"></iframe>'
136
- )
137
 
138
  def _inject_relaxed_csp(html_text: str) -> str:
 
139
  csp = (
140
  "<meta http-equiv=\"Content-Security-Policy\" "
141
  "content=\"default-src * data: blob: 'unsafe-inline' 'unsafe-eval'; "
@@ -147,10 +144,9 @@ def _inject_relaxed_csp(html_text: str) -> str:
147
 
148
  def _patch_to_maplibre(html_text: str) -> str:
149
  """
150
- keplergl が出力する HTML の Mapbox GL 参照を MapLibre GL に置換。
151
- さらに window.mapboxgl -> window.maplibregl の互換エイリアスを注入。
152
  """
153
- # CSS/JS の置換(Mapbox CDN → unpkg の MapLibre)
154
  html_text = re.sub(
155
  r"https://api\.tiles\.mapbox\.com/mapbox-gl-js/v[\d.]+/mapbox-gl\.css",
156
  "https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.css",
@@ -161,7 +157,6 @@ def _patch_to_maplibre(html_text: str) -> str:
161
  "https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.js",
162
  html_text
163
  )
164
- # 互換エイリアスが未挿入なら </head> 直前に追加
165
  if "window.mapboxgl = window.maplibregl" not in html_text:
166
  html_text = html_text.replace(
167
  "</head>",
@@ -169,6 +164,9 @@ def _patch_to_maplibre(html_text: str) -> str:
169
  )
170
  return html_text
171
 
 
 
 
172
  def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
173
  df_valid = df_points.dropna(subset=["lat", "lon"]).copy()
174
  df_valid["lat"] = pd.to_numeric(df_valid["lat"], errors="coerce")
@@ -201,7 +199,7 @@ def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
201
  if "CF" in df_valid.columns and df_valid["CF"].notna().any():
202
  layer_config["visualChannels"]["sizeField"] = {"name": "CF", "type": "real"}
203
 
204
- # --- 無料ベースマップ(地理院タイル:標準地図) ---
205
  gsi_raster_style = {
206
  "version": 8,
207
  "sources": {
@@ -230,10 +228,10 @@ def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
230
  "enabled": True,
231
  "fieldsToShow": {
232
  "points": [
233
- {"name":"address_input","format":None},
234
- {"name":"CF","format":None},
235
- {"name":"lat","format":None},
236
- {"name":"lon","format":None},
237
  ]
238
  },
239
  "compareMode": False,
@@ -244,7 +242,7 @@ def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
244
  },
245
  "mapState": map_state,
246
  "mapStyle": {
247
- "styleType": "gsi_std", # ← カスタムスタイルを指定
248
  "topLayerGroups": {},
249
  "visibleLayerGroups": {"label": True, "road": True, "border": False, "building": False, "water": True, "land": True},
250
  "mapStyles": {
@@ -259,16 +257,29 @@ def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
259
  },
260
  }
261
 
262
- # KeplerGl インスタンス(Mapbox トークン不要)
263
  m = KeplerGl(height=height, data={}, config=config, mapbox_api_key="")
264
  if not df_valid.empty:
265
- m.add_data(data=df_valid[["lat","lon","address_input","CF"]], name="points")
266
 
267
- # HTML 保存 → 読み込み → MapLibre 置換 → srcdoc 埋め込み
268
- with open(path, "r", encoding="utf-8") as fh:
269
- kepler_html = fh.read()
 
 
 
 
 
 
 
 
 
 
 
270
  kepler_html = _patch_to_maplibre(kepler_html)
271
- kepler_html = _inject_relaxed_csp(kepler_html) # 必要に応じて
 
 
272
  return _iframe_from_dataurl(kepler_html, height=height)
273
 
274
  # ----------------------------
@@ -281,7 +292,6 @@ def _parse_indexer(x):
281
  return x
282
 
283
  def run(excel_file, sheet_name, header_row, address_col, power_col, use_inet):
284
- # Excel 読み込み
285
  if excel_file is None or not hasattr(excel_file, "name"):
286
  table_df = pd.DataFrame(columns=["address_input", "CF", "lat", "lon"])
287
  return "", table_df, "Excelファイルを指定してください。"
@@ -292,7 +302,6 @@ def run(excel_file, sheet_name, header_row, address_col, power_col, use_inet):
292
  empty_df = pd.DataFrame(columns=["address_input", "CF", "lat", "lon"])
293
  return "", empty_df, f"Excel の読み込みに失敗しました: {e}"
294
 
295
- # 列の参照(番号/名前の両対応)
296
  addr_series = df.iloc[:, address_col] if isinstance(address_col, int) else df[address_col]
297
  cf_series = df.iloc[:, power_col] if isinstance(power_col, int) else df[power_col]
298
 
@@ -302,20 +311,17 @@ def run(excel_file, sheet_name, header_row, address_col, power_col, use_inet):
302
  geo_df = geocode_with_cache(addresses, cfs, use_internet=bool(use_inet))
303
  table_df = geo_df[["address_input", "CF", "lat", "lon"]].copy()
304
 
305
- # GeoDataFrame(将来拡張用)
306
  geometry = [
307
  Point(lon, lat) if (pd.notna(lat) and pd.notna(lon)) else None
308
  for lat, lon in zip(geo_df["lat"], geo_df["lon"])
309
  ]
310
  gdf_pts = gpd.GeoDataFrame(geo_df, geometry=geometry, crs="EPSG:4326")
311
 
312
- # Kepler.gl(ポイントのみ)
313
  try:
314
  html_iframe = make_kepler_html(table_df, height=640)
315
  except Exception as e:
316
  html_iframe = f"<p>Kepler.gl描画に失敗しました: {e}</p>"
317
 
318
- # 情報
319
  info = []
320
  info.append(f"ポイント数(有効座標): {int(gdf_pts.geometry.notnull().sum())} / {len(gdf_pts)}")
321
 
@@ -324,8 +330,8 @@ def run(excel_file, sheet_name, header_row, address_col, power_col, use_inet):
324
  # ----------------------------
325
  # Gradio UI(ポイントのみ)
326
  # ----------------------------
327
- with gr.Blocks(title="Excel住所 → Kepler.gl(ポイントのみ)") as demo:
328
- gr.Markdown("## Excelの住所を国土地理院APIでジオコーディング → Kepler.gl に **ポイントのみ** を描画(Mapbox不要・無料タイル)")
329
 
330
  with gr.Row():
331
  xlsx_in = gr.File(label="Excelファイル(住所付き)", file_count="single", file_types=[".xlsx", ".xls"])
 
3
 
4
  import os
5
  import time
 
6
  import re
7
+ import urllib.parse
8
+ import tempfile
9
  import requests
10
  import pandas as pd
11
  import numpy as np
 
13
  from shapely.geometry import Point
14
  import gradio as gr
15
  from keplergl import KeplerGl
 
 
16
 
17
  # ----------------------------
18
  # 設定
 
94
 
95
  # cache hit
96
  if a in cache_map:
97
+ lat, lon, _cached_cf = cache_map[a]
98
  if pd.notna(lat) and pd.notna(lon):
99
  results.append({"address_input": a, "CF": cf_num, "lat": float(lat), "lon": float(lon)})
100
  continue
 
124
  return df
125
 
126
  # ----------------------------
127
+ # 埋め込みヘルパ
128
  # ----------------------------
129
  def _iframe_from_dataurl(html_text: str, height: int = 640) -> str:
130
+ """data:URL で iframe に埋め込む(JS 実行可、エスケープ不要)"""
131
  data_url = "data:text/html;charset=utf-8," + urllib.parse.quote(html_text)
132
+ return f'<iframe src="{data_url}" style="border:0;width:100%;height:{height}px"></iframe>'
 
 
 
133
 
134
  def _inject_relaxed_csp(html_text: str) -> str:
135
+ """親ページのCSPに阻害される場合の緩和(ローカル用途想定)"""
136
  csp = (
137
  "<meta http-equiv=\"Content-Security-Policy\" "
138
  "content=\"default-src * data: blob: 'unsafe-inline' 'unsafe-eval'; "
 
144
 
145
  def _patch_to_maplibre(html_text: str) -> str:
146
  """
147
+ keplergl の保存 HTML 内の Mapbox GL 参照を MapLibre GL に置換し、
148
+ window.mapboxgl 互換エイリアスを注入。
149
  """
 
150
  html_text = re.sub(
151
  r"https://api\.tiles\.mapbox\.com/mapbox-gl-js/v[\d.]+/mapbox-gl\.css",
152
  "https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.css",
 
157
  "https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.js",
158
  html_text
159
  )
 
160
  if "window.mapboxgl = window.maplibregl" not in html_text:
161
  html_text = html_text.replace(
162
  "</head>",
 
164
  )
165
  return html_text
166
 
167
+ # ----------------------------
168
+ # Kepler.gl HTML 生成(MapLibre + 地理院タイル)
169
+ # ----------------------------
170
  def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
171
  df_valid = df_points.dropna(subset=["lat", "lon"]).copy()
172
  df_valid["lat"] = pd.to_numeric(df_valid["lat"], errors="coerce")
 
199
  if "CF" in df_valid.columns and df_valid["CF"].notna().any():
200
  layer_config["visualChannels"]["sizeField"] = {"name": "CF", "type": "real"}
201
 
202
+ # 地理院タイル(標準地図)を Mapbox Style v8 互換で直書き
203
  gsi_raster_style = {
204
  "version": 8,
205
  "sources": {
 
228
  "enabled": True,
229
  "fieldsToShow": {
230
  "points": [
231
+ {"name": "address_input", "format": None},
232
+ {"name": "CF", "format": None},
233
+ {"name": "lat", "format": None},
234
+ {"name": "lon", "format": None},
235
  ]
236
  },
237
  "compareMode": False,
 
242
  },
243
  "mapState": map_state,
244
  "mapStyle": {
245
+ "styleType": "gsi_std",
246
  "topLayerGroups": {},
247
  "visibleLayerGroups": {"label": True, "road": True, "border": False, "building": False, "water": True, "land": True},
248
  "mapStyles": {
 
257
  },
258
  }
259
 
260
+ # Kepler インスタンス(Mapbox トークン不要)
261
  m = KeplerGl(height=height, data={}, config=config, mapbox_api_key="")
262
  if not df_valid.empty:
263
+ m.add_data(data=df_valid[["lat", "lon", "address_input", "CF"]], name="points")
264
 
265
+ # --- HTML 保存 → 読込(path を必ず定義) ---
266
+ fd, path = tempfile.mkstemp(suffix=".html")
267
+ try:
268
+ os.close(fd) # Windows ロック回避
269
+ m.save_to_html(file_name=path, read_only=True)
270
+ with open(path, "r", encoding="utf-8") as fh:
271
+ kepler_html = fh.read()
272
+ finally:
273
+ try:
274
+ os.remove(path)
275
+ except Exception:
276
+ pass
277
+
278
+ # MapLibre 置換 & CSP 緩和(必要環境向け)
279
  kepler_html = _patch_to_maplibre(kepler_html)
280
+ kepler_html = _inject_relaxed_csp(kepler_html)
281
+
282
+ # data:URL で埋め込み
283
  return _iframe_from_dataurl(kepler_html, height=height)
284
 
285
  # ----------------------------
 
292
  return x
293
 
294
  def run(excel_file, sheet_name, header_row, address_col, power_col, use_inet):
 
295
  if excel_file is None or not hasattr(excel_file, "name"):
296
  table_df = pd.DataFrame(columns=["address_input", "CF", "lat", "lon"])
297
  return "", table_df, "Excelファイルを指定してください。"
 
302
  empty_df = pd.DataFrame(columns=["address_input", "CF", "lat", "lon"])
303
  return "", empty_df, f"Excel の読み込みに失敗しました: {e}"
304
 
 
305
  addr_series = df.iloc[:, address_col] if isinstance(address_col, int) else df[address_col]
306
  cf_series = df.iloc[:, power_col] if isinstance(power_col, int) else df[power_col]
307
 
 
311
  geo_df = geocode_with_cache(addresses, cfs, use_internet=bool(use_inet))
312
  table_df = geo_df[["address_input", "CF", "lat", "lon"]].copy()
313
 
 
314
  geometry = [
315
  Point(lon, lat) if (pd.notna(lat) and pd.notna(lon)) else None
316
  for lat, lon in zip(geo_df["lat"], geo_df["lon"])
317
  ]
318
  gdf_pts = gpd.GeoDataFrame(geo_df, geometry=geometry, crs="EPSG:4326")
319
 
 
320
  try:
321
  html_iframe = make_kepler_html(table_df, height=640)
322
  except Exception as e:
323
  html_iframe = f"<p>Kepler.gl描画に失敗しました: {e}</p>"
324
 
 
325
  info = []
326
  info.append(f"ポイント数(有効座標): {int(gdf_pts.geometry.notnull().sum())} / {len(gdf_pts)}")
327
 
 
330
  # ----------------------------
331
  # Gradio UI(ポイントのみ)
332
  # ----------------------------
333
+ with gr.Blocks(title="Excel住所 → Kepler.gl(無料タイル・MapLibre)") as demo:
334
+ gr.Markdown("## Excelの住所を国土地理院APIでジオコーディング → Kepler.gl に **ポイントのみ** を描画(Mapbox不要)")
335
 
336
  with gr.Row():
337
  xlsx_in = gr.File(label="Excelファイル(住所付き)", file_count="single", file_types=[".xlsx", ".xls"])