Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -32,6 +32,9 @@ CACHE_DIR = "data/cache"
|
|
| 32 |
os.makedirs(CACHE_DIR, exist_ok=True)
|
| 33 |
CACHE_PATH = os.path.join(CACHE_DIR, "geocode_cache.csv")
|
| 34 |
|
|
|
|
|
|
|
|
|
|
| 35 |
# ----------------------------
|
| 36 |
# キャッシュ
|
| 37 |
# ----------------------------
|
|
@@ -39,7 +42,11 @@ def load_cache():
|
|
| 39 |
if os.path.exists(CACHE_PATH):
|
| 40 |
try:
|
| 41 |
df = pd.read_csv(CACHE_PATH)
|
|
|
|
| 42 |
if set(["address_input", "lat", "lon", "CF"]).issubset(df.columns):
|
|
|
|
|
|
|
|
|
|
| 43 |
return df
|
| 44 |
except Exception:
|
| 45 |
pass
|
|
@@ -90,17 +97,18 @@ def geocode_with_cache(addresses, CFs, use_internet=True):
|
|
| 90 |
|
| 91 |
for a, cf in zip(addresses, CFs):
|
| 92 |
a = "" if (a is None or (isinstance(a, float) and np.isnan(a))) else str(a).strip()
|
| 93 |
-
|
|
|
|
| 94 |
|
| 95 |
# cache hit
|
| 96 |
if a in cache_map:
|
| 97 |
-
lat, lon,
|
| 98 |
if pd.notna(lat) and pd.notna(lon):
|
| 99 |
-
results.append({"address_input": a, "CF":
|
| 100 |
continue
|
| 101 |
|
| 102 |
if not use_internet:
|
| 103 |
-
results.append({"address_input": a, "CF":
|
| 104 |
continue
|
| 105 |
|
| 106 |
lat, lon = gsi_geocode_once(a, session)
|
|
@@ -109,93 +117,107 @@ def geocode_with_cache(addresses, CFs, use_internet=True):
|
|
| 109 |
if GEOCODE_DELAY_SEC > 0:
|
| 110 |
time.sleep(GEOCODE_DELAY_SEC)
|
| 111 |
|
| 112 |
-
# キャッシュ更新
|
| 113 |
cache = cache[cache["address_input"] != a]
|
| 114 |
cache = pd.concat(
|
| 115 |
-
[cache, pd.DataFrame([{"address_input": a, "lat": lat, "lon": lon, "CF":
|
| 116 |
ignore_index=True
|
| 117 |
)
|
| 118 |
save_cache(cache)
|
| 119 |
-
results.append({"address_input": a, "CF":
|
| 120 |
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
# ----------------------------
|
| 124 |
# Kepler.gl HTML 生成(ポイントのみ)
|
| 125 |
# ----------------------------
|
| 126 |
-
def
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
tmp = tempfile.NamedTemporaryFile(suffix=".html", delete=False)
|
| 130 |
-
tmp.write(html.encode("utf-8"))
|
| 131 |
-
tmp.flush()
|
| 132 |
-
tmp.close()
|
| 133 |
-
# Gradioは "file=/abs/path" の形式でローカルファイルを配信できます
|
| 134 |
-
return f'<iframe src="file={tmp.name}" width="100%" height="{height}" style="border:0;"></iframe>'
|
| 135 |
|
| 136 |
def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
|
| 137 |
df_valid = df_points.dropna(subset=["lat", "lon"]).copy()
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
else:
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
}
|
| 180 |
-
|
| 181 |
-
|
|
|
|
| 182 |
},
|
| 183 |
-
"
|
| 184 |
-
"mapStyle": {"styleType":"light","topLayerGroups":{},"visibleLayerGroups":{"label":True,"road":True,"border":False,"building":False,"water":True,"land":True}},
|
| 185 |
},
|
| 186 |
-
|
| 187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
m.add_data(data=df_valid[["lat","lon","address_input","CF"]], name="points")
|
| 189 |
|
| 190 |
-
#
|
| 191 |
-
import tempfile
|
| 192 |
with tempfile.NamedTemporaryFile(suffix=".html", delete=False) as f:
|
| 193 |
path = f.name
|
| 194 |
m.save_to_html(file_name=path, read_only=True)
|
| 195 |
-
|
| 196 |
-
html = fh.read()
|
| 197 |
-
return _iframe_from_html_string(html, height=height)
|
| 198 |
-
|
| 199 |
|
| 200 |
# ----------------------------
|
| 201 |
# 実行パイプライン(ポイントのみ)
|
|
@@ -218,16 +240,18 @@ def run(excel_file, sheet_name, header_row, address_col, power_col, use_inet):
|
|
| 218 |
empty_df = pd.DataFrame(columns=["address_input", "CF", "lat", "lon"])
|
| 219 |
return "", empty_df, f"Excel の読み込みに失敗しました: {e}"
|
| 220 |
|
|
|
|
| 221 |
addr_series = df.iloc[:, address_col] if isinstance(address_col, int) else df[address_col]
|
| 222 |
-
cf_series
|
| 223 |
|
| 224 |
addresses = addr_series.astype(str).tolist()
|
| 225 |
-
cfs
|
| 226 |
|
| 227 |
geo_df = geocode_with_cache(addresses, cfs, use_internet=bool(use_inet))
|
|
|
|
| 228 |
table_df = geo_df[["address_input", "CF", "lat", "lon"]].copy()
|
| 229 |
|
| 230 |
-
# GeoDataFrame
|
| 231 |
geometry = [
|
| 232 |
Point(lon, lat) if (pd.notna(lat) and pd.notna(lon)) else None
|
| 233 |
for lat, lon in zip(geo_df["lat"], geo_df["lon"])
|
|
@@ -240,9 +264,11 @@ def run(excel_file, sheet_name, header_row, address_col, power_col, use_inet):
|
|
| 240 |
except Exception as e:
|
| 241 |
html = f"<p>Kepler.gl描画に失敗しました: {e}</p>"
|
| 242 |
|
| 243 |
-
# 情報
|
| 244 |
info = []
|
| 245 |
info.append(f"ポイント数(有効座標): {int(gdf_pts.geometry.notnull().sum())} / {len(gdf_pts)}")
|
|
|
|
|
|
|
| 246 |
|
| 247 |
return html, table_df, "\n".join(info)
|
| 248 |
|
|
@@ -270,7 +296,7 @@ with gr.Blocks(title="Excel住所 → Kepler.gl(ポイントのみ)") as dem
|
|
| 270 |
|
| 271 |
out_html = gr.HTML(label="インタラクティブ地図(Kepler.gl:ポイントのみ)")
|
| 272 |
out_table = gr.Dataframe(label="ジオコーディング結果(住所・緯度・経度・CF)", wrap=True)
|
| 273 |
-
out_info = gr.Textbox(label="メタ情報", lines=
|
| 274 |
|
| 275 |
def _parse(x):
|
| 276 |
try:
|
|
|
|
| 32 |
os.makedirs(CACHE_DIR, exist_ok=True)
|
| 33 |
CACHE_PATH = os.path.join(CACHE_DIR, "geocode_cache.csv")
|
| 34 |
|
| 35 |
+
# Mapbox トークン(背景地図用)
|
| 36 |
+
MAPBOX_TOKEN = os.environ.get("MAPBOX_API_KEY", "")
|
| 37 |
+
|
| 38 |
# ----------------------------
|
| 39 |
# キャッシュ
|
| 40 |
# ----------------------------
|
|
|
|
| 42 |
if os.path.exists(CACHE_PATH):
|
| 43 |
try:
|
| 44 |
df = pd.read_csv(CACHE_PATH)
|
| 45 |
+
# CF は数値として扱う
|
| 46 |
if set(["address_input", "lat", "lon", "CF"]).issubset(df.columns):
|
| 47 |
+
df["CF"] = pd.to_numeric(df["CF"], errors="coerce")
|
| 48 |
+
df["lat"] = pd.to_numeric(df["lat"], errors="coerce")
|
| 49 |
+
df["lon"] = pd.to_numeric(df["lon"], errors="coerce")
|
| 50 |
return df
|
| 51 |
except Exception:
|
| 52 |
pass
|
|
|
|
| 97 |
|
| 98 |
for a, cf in zip(addresses, CFs):
|
| 99 |
a = "" if (a is None or (isinstance(a, float) and np.isnan(a))) else str(a).strip()
|
| 100 |
+
# CF は数値化(失敗時 NaN)
|
| 101 |
+
cf_num = pd.to_numeric(cf, errors="coerce")
|
| 102 |
|
| 103 |
# cache hit
|
| 104 |
if a in cache_map:
|
| 105 |
+
lat, lon, cached_cf = cache_map[a]
|
| 106 |
if pd.notna(lat) and pd.notna(lon):
|
| 107 |
+
results.append({"address_input": a, "CF": cf_num, "lat": float(lat), "lon": float(lon)})
|
| 108 |
continue
|
| 109 |
|
| 110 |
if not use_internet:
|
| 111 |
+
results.append({"address_input": a, "CF": cf_num, "lat": np.nan, "lon": np.nan})
|
| 112 |
continue
|
| 113 |
|
| 114 |
lat, lon = gsi_geocode_once(a, session)
|
|
|
|
| 117 |
if GEOCODE_DELAY_SEC > 0:
|
| 118 |
time.sleep(GEOCODE_DELAY_SEC)
|
| 119 |
|
| 120 |
+
# キャッシュ更新(同一住所を差し替え)
|
| 121 |
cache = cache[cache["address_input"] != a]
|
| 122 |
cache = pd.concat(
|
| 123 |
+
[cache, pd.DataFrame([{"address_input": a, "lat": lat, "lon": lon, "CF": cf_num}])],
|
| 124 |
ignore_index=True
|
| 125 |
)
|
| 126 |
save_cache(cache)
|
| 127 |
+
results.append({"address_input": a, "CF": cf_num, "lat": lat, "lon": lon})
|
| 128 |
|
| 129 |
+
df = pd.DataFrame(results)
|
| 130 |
+
# 明示的に型を整える
|
| 131 |
+
df["lat"] = pd.to_numeric(df["lat"], errors="coerce")
|
| 132 |
+
df["lon"] = pd.to_numeric(df["lon"], errors="coerce")
|
| 133 |
+
df["CF"] = pd.to_numeric(df["CF"], errors="coerce")
|
| 134 |
+
return df
|
| 135 |
|
| 136 |
# ----------------------------
|
| 137 |
# Kepler.gl HTML 生成(ポイントのみ)
|
| 138 |
# ----------------------------
|
| 139 |
+
def _iframe_from_html_path(path: str, height: int = 640) -> str:
|
| 140 |
+
# Gradio は "file=/abs/path" の形式でローカルファイルを配信できる
|
| 141 |
+
return f'<iframe src="file={path}" width="100%" height="{height}" style="border:0;"></iframe>'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
def make_kepler_html(df_points: pd.DataFrame, height: int = 640) -> str:
|
| 144 |
df_valid = df_points.dropna(subset=["lat", "lon"]).copy()
|
| 145 |
+
# 数値列保証
|
| 146 |
+
df_valid["lat"] = pd.to_numeric(df_valid["lat"], errors="coerce")
|
| 147 |
+
df_valid["lon"] = pd.to_numeric(df_valid["lon"], errors="coerce")
|
| 148 |
+
if "CF" in df_valid.columns:
|
| 149 |
+
df_valid["CF"] = pd.to_numeric(df_valid["CF"], errors="coerce")
|
| 150 |
+
|
| 151 |
+
# Kepler 設定
|
| 152 |
+
map_state = {"bearing": 0, "pitch": 0, "zoom": 6}
|
| 153 |
+
if not df_valid.empty:
|
| 154 |
+
map_state["latitude"] = float(df_valid["lat"].median())
|
| 155 |
+
map_state["longitude"] = float(df_valid["lon"].median())
|
| 156 |
else:
|
| 157 |
+
map_state.update({"latitude": 35.0, "longitude": 135.0, "zoom": 4})
|
| 158 |
+
|
| 159 |
+
layer_config = {
|
| 160 |
+
"id": "point_layer",
|
| 161 |
+
"type": "point",
|
| 162 |
+
"config": {
|
| 163 |
+
"dataId": "points",
|
| 164 |
+
"label": "Points",
|
| 165 |
+
"color": [18, 147, 154],
|
| 166 |
+
"columns": {"lat": "lat", "lng": "lon"},
|
| 167 |
+
"isVisible": True,
|
| 168 |
+
"visConfig": {"radius": 10, "opacity": 0.9, "outline": False},
|
| 169 |
+
},
|
| 170 |
+
"visualChannels": {
|
| 171 |
+
"sizeScale": "sqrt"
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
# CF が数値で入っていればサイズ連動
|
| 176 |
+
if "CF" in df_valid.columns and df_valid["CF"].notna().any():
|
| 177 |
+
layer_config["visualChannels"]["sizeField"] = {"name": "CF", "type": "real"}
|
| 178 |
+
|
| 179 |
+
config = {
|
| 180 |
+
"version": "v1",
|
| 181 |
+
"config": {
|
| 182 |
+
"visState": {
|
| 183 |
+
"filters": [],
|
| 184 |
+
"layers": [layer_config],
|
| 185 |
+
"interactionConfig": {
|
| 186 |
+
"tooltip": {
|
| 187 |
+
"enabled": True,
|
| 188 |
+
"fieldsToShow": {
|
| 189 |
+
"points": [
|
| 190 |
+
{"name":"address_input","format":None},
|
| 191 |
+
{"name":"CF","format":None},
|
| 192 |
+
{"name":"lat","format":None},
|
| 193 |
+
{"name":"lon","format":None},
|
| 194 |
+
]
|
| 195 |
+
},
|
| 196 |
+
"compareMode": False,
|
| 197 |
+
"compareType": "absolute",
|
| 198 |
+
}
|
| 199 |
},
|
| 200 |
+
"layerBlending": "normal",
|
|
|
|
| 201 |
},
|
| 202 |
+
"mapState": map_state,
|
| 203 |
+
# styleType は token が無いと背景が真っ白になり得る
|
| 204 |
+
"mapStyle": {
|
| 205 |
+
"styleType": "light",
|
| 206 |
+
"topLayerGroups": {},
|
| 207 |
+
"visibleLayerGroups": {"label": True, "road": True, "border": False, "building": False, "water": True, "land": True}
|
| 208 |
+
},
|
| 209 |
+
},
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
m = KeplerGl(height=height, data={}, config=config, mapbox_api_key=MAPBOX_TOKEN)
|
| 213 |
+
if not df_valid.empty:
|
| 214 |
m.add_data(data=df_valid[["lat","lon","address_input","CF"]], name="points")
|
| 215 |
|
| 216 |
+
# 一時HTMLに保存して iframe 埋め込み
|
|
|
|
| 217 |
with tempfile.NamedTemporaryFile(suffix=".html", delete=False) as f:
|
| 218 |
path = f.name
|
| 219 |
m.save_to_html(file_name=path, read_only=True)
|
| 220 |
+
return _iframe_from_html_path(path, height=height)
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
# ----------------------------
|
| 223 |
# 実行パイプライン(ポイントのみ)
|
|
|
|
| 240 |
empty_df = pd.DataFrame(columns=["address_input", "CF", "lat", "lon"])
|
| 241 |
return "", empty_df, f"Excel の読み込みに失敗しました: {e}"
|
| 242 |
|
| 243 |
+
# 列の参照(番号/名前の両対応)
|
| 244 |
addr_series = df.iloc[:, address_col] if isinstance(address_col, int) else df[address_col]
|
| 245 |
+
cf_series = df.iloc[:, power_col] if isinstance(power_col, int) else df[power_col]
|
| 246 |
|
| 247 |
addresses = addr_series.astype(str).tolist()
|
| 248 |
+
cfs = cf_series.tolist()
|
| 249 |
|
| 250 |
geo_df = geocode_with_cache(addresses, cfs, use_internet=bool(use_inet))
|
| 251 |
+
# 出力テーブル
|
| 252 |
table_df = geo_df[["address_input", "CF", "lat", "lon"]].copy()
|
| 253 |
|
| 254 |
+
# GeoDataFrame(将来拡張用)
|
| 255 |
geometry = [
|
| 256 |
Point(lon, lat) if (pd.notna(lat) and pd.notna(lon)) else None
|
| 257 |
for lat, lon in zip(geo_df["lat"], geo_df["lon"])
|
|
|
|
| 264 |
except Exception as e:
|
| 265 |
html = f"<p>Kepler.gl描画に失敗しました: {e}</p>"
|
| 266 |
|
| 267 |
+
# 情報
|
| 268 |
info = []
|
| 269 |
info.append(f"ポイント数(有効座標): {int(gdf_pts.geometry.notnull().sum())} / {len(gdf_pts)}")
|
| 270 |
+
if not MAPBOX_TOKEN:
|
| 271 |
+
info.append("⚠ 背景地図の表示には MAPBOX_API_KEY の設定を推奨(未設定だと背景が真っ白になる場合があります)")
|
| 272 |
|
| 273 |
return html, table_df, "\n".join(info)
|
| 274 |
|
|
|
|
| 296 |
|
| 297 |
out_html = gr.HTML(label="インタラクティブ地図(Kepler.gl:ポイントのみ)")
|
| 298 |
out_table = gr.Dataframe(label="ジオコーディング結果(住所・緯度・経度・CF)", wrap=True)
|
| 299 |
+
out_info = gr.Textbox(label="メタ情報", lines=3)
|
| 300 |
|
| 301 |
def _parse(x):
|
| 302 |
try:
|