Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223243 unmodified lines28293031323334353637383940414243444546471 unmodified line495051525354555657585960616263646566676869707172737475767778798081822 unmodified lines8586878889909192939495# app.py# HF Spaces (Gradio) で japan_ver85.shp を単純にプロットするアプリ# 使い方:# - 「Shapefile (ZIP)」に .shp/.shx/.dbf/.prj を ZIP にまとめたファイルをアップロード# - そのまま「描画」ボタンを押すと境界線のみを静的プロット表示import osimport ioimport geopandas as gpdimport matplotlib.pyplot as pltimport gradio as grDEFAULT_ZIP = "data/japan_ver85.zip" # リポジトリに置いた場合のデフォルトdef load_gdf_from_zip(zip_path: str) -> gpd.GeoDataFrame:"""Shapefile を ZIP から読み込む。"""# pyogrio が入っていれば engine="pyogrio" が高速gdf = gpd.read_file(f"zip://{zip_path}") # , engine="pyogrio"# 座標系が設定されていれば WGS84 へ(なくてもそのままプロット可)try:if gdf.crs:gdf = gdf.to_crs("EPSG:4326")3 unmodified linesdef plot_boundary(gdf: gpd.GeoDataFrame, linewidth: float = 0.6, figsize=(7,7)):"""GeoDataFrame の境界線のみを静的にプロットし、PNGバイナリを返す"""fig, ax = plt.subplots(figsize=figsize)gdf.boundary.plot(ax=ax, linewidth=linewidth)ax.set_axis_off()plt.tight_layout()buf = io.BytesIO()fig.savefig(buf, format="png", dpi=200)plt.close(fig)buf.seek(0)return bufdef run(zip_file, line_width, width_px):# 1) 読み込み元の決定if zip_file is not None and hasattr(zip_file, "name") and os.path.exists(zip_file.name):zip_path = zip_file.nameelif os.path.exists(DEFAULT_ZIP):1 unmodified lineelse:return None, "Shapefile の ZIP をアップロードするか、data/japan_ver85.zip を配置してください。"# 2) 読み込みtry:gdf = load_gdf_from_zip(zip_path)except Exception as e:return None, f"読み込みに失敗しました: {e}"# 3) プロットtry:img = plot_boundary(gdf, linewidth=line_width)except Exception as e:return None, f"描画に失敗しました: {e}"# 4) 出力(画像 + ちょっとした情報)info = []info.append(f"レコード数: {len(gdf)}")if gdf.crs:info.append(f"CRS: {gdf.crs}")# 主な列名(多すぎると邪魔なので先頭10件)cols = list(map(str, gdf.columns))info.append("列名(先頭10): " + ", ".join(cols[:10]))return img, "\n".join(info)with gr.Blocks(title="Japan Shapefile Plotter") as demo:gr.Markdown("## japan_ver85.shp(ZIP)を単純にプロット")gr.Markdown("- **Shapefile を ZIP**(`.shp/.shx/.dbf/.prj` 等を1つに)でアップロードしてください。\n""- 何もアップロードしない場合は `data/japan_ver85.zip` を読み込みます(置いてある場合)。")with gr.Row():zip_in = gr.File(label="Shapefile (ZIP)", file_count="single", file_types=[".zip"])2 unmodified lineswidth_px = gr.Slider(400, 1600, value=900, step=50, label="画像幅(px)(注: PNGは実質dpi依存)")run_btn = gr.Button("描画")out_img = gr.Image(label="静的プロット(境界線)", type="pil")out_txt = gr.Textbox(label="メタ情報", lines=4)run_btn.click(fn=run, inputs=[zip_in, line_width, width_px], outputs=[out_img, out_txt])if __name__ == "__main__":# Spaces では基本これでOKdemo.launch()1234567891011121314153 unmodified lines1920212223242526272829303132333435363738391 unmodified line4142434445464748495051525354555657585960616263646566672 unmodified lines70717273747576777879# app.pyimport osimport ioimport geopandas as gpdimport matplotlib.pyplot as pltimport gradio as grfrom PIL import Image # ★ 追加DEFAULT_ZIP = "data/japan_ver85.zip"def load_gdf_from_zip(zip_path: str) -> gpd.GeoDataFrame:gdf = gpd.read_file(f"zip://{zip_path}") # , engine="pyogrio"try:if gdf.crs:gdf = gdf.to_crs("EPSG:4326")3 unmodified linesdef plot_boundary(gdf: gpd.GeoDataFrame, linewidth: float = 0.6, figsize=(7,7)):"""GeoDataFrame の境界線のみを静的にプロットし、PIL.Image を返す"""fig, ax = plt.subplots(figsize=figsize)gdf.boundary.plot(ax=ax, linewidth=linewidth)ax.set_axis_off()plt.tight_layout()buf = io.BytesIO()fig.savefig(buf, format="png", dpi=200)plt.close(fig)buf.seek(0)img = Image.open(buf) # ★ BytesIO → PIL.Image に変換return imgdef run(zip_file, line_width, width_px):if zip_file is not None and hasattr(zip_file, "name") and os.path.exists(zip_file.name):zip_path = zip_file.nameelif os.path.exists(DEFAULT_ZIP):1 unmodified lineelse:return None, "Shapefile の ZIP をアップロードするか、data/japan_ver85.zip を配置してください。"try:gdf = load_gdf_from_zip(zip_path)except Exception as e:return None, f"読み込みに失敗しました: {e}"try:# width_px は PNG の実寸に直接効かないので、必要なら figsize/dpi を調整してくださいimg = plot_boundary(gdf, linewidth=line_width)except Exception as e:return None, f"描画に失敗しました: {e}"info = []info.append(f"レコード数: {len(gdf)}")if gdf.crs:info.append(f"CRS: {gdf.crs}")cols = list(map(str, gdf.columns))info.append("列名(先頭10): " + ", ".join(cols[:10]))return img, "\n".join(info)with gr.Blocks(title="Japan Shapefile Plotter") as demo:gr.Markdown("## japan_ver85.shp(ZIP)を単純にプロット")with gr.Row():zip_in = gr.File(label="Shapefile (ZIP)", file_count="single", file_types=[".zip"])2 unmodified lineswidth_px = gr.Slider(400, 1600, value=900, step=50, label="画像幅(px)(注: PNGは実質dpi依存)")run_btn = gr.Button("描画")out_img = gr.Image(label="静的プロット(境界線)", type="pil") # ★ PIL を受け取るout_txt = gr.Textbox(label="メタ情報", lines=4)run_btn.click(fn=run, inputs=[zip_in, line_width, width_px], outputs=[out_img, out_txt])if __name__ == "__main__":demo.launch()
app.py+8-24