Spaces:
Sleeping

hiroki0008 commited on
Commit
18f56a2
·
verified ·
1 Parent(s): 9e10dc0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -42
app.py CHANGED
@@ -3,7 +3,6 @@ import re
3
  import time
4
  import zipfile
5
  import unicodedata
6
- from io import BytesIO
7
  from urllib.parse import urljoin, urlparse, parse_qs, unquote
8
 
9
  import gradio as gr
@@ -12,7 +11,7 @@ import pandas as pd
12
  from bs4 import BeautifulSoup
13
 
14
  PUBLIC_URL = "https://www.fit-portal.go.jp/PublicInfo"
15
- OUTDIR = "data_fit" # Spacesの永続領域(リポジトリ直下)に保存
16
 
17
  # -------------------- ユーティリティ --------------------
18
 
@@ -77,6 +76,7 @@ def collect_pref_links(session: requests.Session) -> list[dict]:
77
 
78
  def download_one(session: requests.Session, url: str, outdir: str, pref: str) -> str:
79
  os.makedirs(outdir, exist_ok=True)
 
80
  qs = parse_qs(urlparse(url).query)
81
  file_id = (qs.get("file", ["unknown"])[0])[:18]
82
  with session.get(url, timeout=180, stream=True) as r:
@@ -89,10 +89,12 @@ def download_one(session: requests.Session, url: str, outdir: str, pref: str) ->
89
  f.write(chunk)
90
  return path
91
 
 
92
  def load_excel(xls_path: str, sheet_pref: str | None, pref_name: str, use_header: bool) -> pd.DataFrame | None:
93
  """
94
- use_header=True のときのみ上3行を列名として使用
95
  use_header=False のときは列名なし(skiprows=3)
 
96
  """
97
  sheet = pick_sheet_name(xls_path, sheet_pref)
98
  if not sheet:
@@ -100,22 +102,69 @@ def load_excel(xls_path: str, sheet_pref: str | None, pref_name: str, use_header
100
  try:
101
  if use_header:
102
  df = pd.read_excel(xls_path, sheet_name=sheet, engine="openpyxl",
103
- header=[0,1,2], dtype=str)
 
 
104
  else:
105
- # 3行スキップしてデータだけ読み込む(列名は後で統一)
106
  df = pd.read_excel(xls_path, sheet_name=sheet, engine="openpyxl",
107
  header=None, skiprows=3, dtype=str)
 
108
 
109
  # 前後空白トリム
110
  for c in df.select_dtypes(include=["object"]).columns:
111
  df[c] = df[c].str.strip()
 
 
112
  df.insert(0, "都道府県", pref_name)
113
  df.insert(1, "元ファイル", os.path.basename(xls_path))
114
  df.insert(2, "読込シート", sheet)
 
 
 
 
 
 
 
 
 
115
  return df
116
- except Exception:
 
117
  return None
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
  def zip_paths(paths: list[str], out_zip: str) -> str:
121
  with zipfile.ZipFile(out_zip, "w", compression=zipfile.ZIP_DEFLATED) as z:
@@ -126,19 +175,20 @@ def zip_paths(paths: list[str], out_zip: str) -> str:
126
 
127
  # -------------------- メイン実行(Gradioから呼ぶ) --------------------
128
 
129
- def run_job(sheet_name, sleep_sec, limit, re_download, progress=gr.Progress(track_tqdm=False)):
130
  """
131
  sheet_name: "代表地番" 等。空欄なら自動
132
  sleep_sec: ダウンロード間隔
133
  limit: 先頭N件のみ(テスト用)
134
  re_download: 既存ファイルがあっても再取��する
 
 
135
  """
136
  progress(0, desc="初期化中…")
137
 
138
- # polite headers(UA指摘を避けるため)
139
  session = requests.Session()
140
  session.headers.update({
141
- "User-Agent": "Mozilla/5.0 (compatible; FITCollector/1.0; +https://huggingface.co/spaces)",
142
  "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
143
  })
144
 
@@ -159,8 +209,7 @@ def run_job(sheet_name, sleep_sec, limit, re_download, progress=gr.Progress(trac
159
  progress(0.1 + 0.6 * i / max(1, len(links)),
160
  desc=f"ダウンロード {i}/{len(links)}: {item['pref']}")
161
  try:
162
- # 既存ファイルを利用する(高速化)
163
- # 同一prefの既存xlsxがあればそれを優先(緩めの一致)
164
  existing = None
165
  if not re_download and os.path.isdir(OUTDIR):
166
  for fn in os.listdir(OUTDIR):
@@ -180,56 +229,62 @@ def run_job(sheet_name, sleep_sec, limit, re_download, progress=gr.Progress(trac
180
  return ("ダウンロードに失敗しました。ネットワークやサイト側制限をご確認ください。",
181
  None, None, None, None)
182
 
183
- # 3) 結合
184
  frames = []
185
  for i, it in enumerate(downloaded, start=1):
186
  progress(0.72 + 0.18 * i / max(1, len(downloaded)),
187
  desc=f"読み込み {i}/{len(downloaded)}: {os.path.basename(it['path'])}")
188
- df = load_excel(it["path"],
189
- sheet_name if sheet_name else None,
190
- it["pref"],
191
- use_header=(i==1))
 
 
192
  if df is not None and len(df) > 0:
193
  frames.append(df)
194
 
195
- # 2件目以降は列名が無いため、1件目の列名を上書き
196
- if len(frames) > 1:
197
- frames[1:] = [f.set_axis(frames[0].columns, axis=1) for f in frames[1:]]
198
-
199
-
200
  if not frames:
201
  return ("Excelは取得できましたが、読み込めるデータがありませんでした(シート名の指定を見直してください)。",
202
  None, None, None, None)
203
 
 
 
 
 
 
204
  combined = pd.concat(frames, ignore_index=True)
205
 
206
- # 4) 出力
 
 
 
 
207
  os.makedirs(OUTDIR, exist_ok=True)
208
  out_xlsx = os.path.join(OUTDIR, "combined_fit.xlsx")
209
  out_parq = os.path.join(OUTDIR, "combined_fit.parquet")
210
-
211
  with pd.ExcelWriter(out_xlsx, engine="openpyxl") as w:
212
  combined.to_excel(w, index=False, sheet_name="combined")
213
  combined.to_parquet(out_parq, index=False)
214
 
215
- # 5) 付帯:生ファイル一式のZIP
216
- # ダウンロードした都道府県別Excelも渡したいニーズ向け
217
  raw_zip = os.path.join(OUTDIR, "raw_excels.zip")
218
  zip_paths([it["path"] for it in downloaded], raw_zip)
219
 
220
- # 6) 進捗完了
221
- progress(1.0, desc=f"完了({len(combined):,} 行)")
222
-
223
- # Gradio File はパスを返せばダウンロード可能
224
- msg = f"✅ 結合完了: 行数 = {len(combined):,}\n" \
225
- f"・Excel: combined_fit.xlsx\n" \
226
- f"・Parquet: combined_fit.parquet\n" \
227
- f"・Raw ZIP: raw_excels.zip\n"
228
-
229
- # 先頭数行のプレビューCSV(軽量)
230
  preview_csv = os.path.join(OUTDIR, "combined_head.csv")
231
  combined.head(1000).to_csv(preview_csv, index=False)
232
 
 
 
 
 
 
 
 
 
 
 
 
233
  return (msg, out_xlsx, out_parq, raw_zip, preview_csv)
234
 
235
  # -------------------- Gradio UI --------------------
@@ -238,9 +293,8 @@ with gr.Blocks(title="FIT 公表(都道府県別Excel)一括取得&結合"
238
  gr.Markdown(
239
  """
240
  # FIT 公表(都道府県別Excel)一括取得 & 結合
241
- - 公表ページから都道府県別のExcelを取得し、縦結合します。
242
- - サーバ負荷配慮のため**間隔(sleep)**を入れています���
243
- - 出力:`combined_fit.xlsx` / `combined_fit.parquet` / 生ファイル一式`raw_excels.zip`
244
  """
245
  )
246
  with gr.Row():
@@ -249,6 +303,9 @@ with gr.Blocks(title="FIT 公表(都道府県別Excel)一括取得&結合"
249
  with gr.Row():
250
  limit = gr.Number(value=None, precision=0, label="先頭N県のみ(テスト用・空欄は全県)")
251
  reget = gr.Checkbox(label="既存ファイルがあっても再ダウンロードする", value=False)
 
 
 
252
 
253
  run_btn = gr.Button("実行", variant="primary")
254
  out_msg = gr.Markdown()
@@ -257,10 +314,11 @@ with gr.Blocks(title="FIT 公表(都道府県別Excel)一括取得&結合"
257
  out_zip = gr.File(label="取得した都道府県Excel一式(zip)")
258
  out_preview = gr.File(label="先頭1000行プレビュー(CSV)")
259
 
260
- run_btn.click(fn=run_job,
261
- inputs=[sheet, sleep, limit, reget],
262
- outputs=[out_msg, out_xlsx, out_parq, out_zip, out_preview])
 
 
263
 
264
  if __name__ == "__main__":
265
- # queue を有効にして複数ユーザーでも安定実行
266
  demo.queue(max_size=20).launch()
 
3
  import time
4
  import zipfile
5
  import unicodedata
 
6
  from urllib.parse import urljoin, urlparse, parse_qs, unquote
7
 
8
  import gradio as gr
 
11
  from bs4 import BeautifulSoup
12
 
13
  PUBLIC_URL = "https://www.fit-portal.go.jp/PublicInfo"
14
+ OUTDIR = "data_fit" # 保存先
15
 
16
  # -------------------- ユーティリティ --------------------
17
 
 
76
 
77
  def download_one(session: requests.Session, url: str, outdir: str, pref: str) -> str:
78
  os.makedirs(outdir, exist_ok=True)
79
+ from urllib.parse import urlparse, parse_qs
80
  qs = parse_qs(urlparse(url).query)
81
  file_id = (qs.get("file", ["unknown"])[0])[:18]
82
  with session.get(url, timeout=180, stream=True) as r:
 
89
  f.write(chunk)
90
  return path
91
 
92
+ # ---- 3段ヘッダー対応:1枚目のみ利用、他は削除(skiprows) ----
93
  def load_excel(xls_path: str, sheet_pref: str | None, pref_name: str, use_header: bool) -> pd.DataFrame | None:
94
  """
95
+ use_header=True のときのみ上3行を列名として使用(MultiIndex)
96
  use_header=False のときは列名なし(skiprows=3)
97
+ いずれも先頭にメタ列(都道府県/元ファイル/読込シート)を付加
98
  """
99
  sheet = pick_sheet_name(xls_path, sheet_pref)
100
  if not sheet:
 
102
  try:
103
  if use_header:
104
  df = pd.read_excel(xls_path, sheet_name=sheet, engine="openpyxl",
105
+ header=[0, 1, 2], dtype=str)
106
+ # 後でMultiIndex列を維持するため、元の列名を保存
107
+ orig_cols = list(df.columns)
108
  else:
 
109
  df = pd.read_excel(xls_path, sheet_name=sheet, engine="openpyxl",
110
  header=None, skiprows=3, dtype=str)
111
+ orig_cols = None # 後で1枚目の列名を適用
112
 
113
  # 前後空白トリム
114
  for c in df.select_dtypes(include=["object"]).columns:
115
  df[c] = df[c].str.strip()
116
+
117
+ # メタ情報列を追加
118
  df.insert(0, "都道府県", pref_name)
119
  df.insert(1, "元ファイル", os.path.basename(xls_path))
120
  df.insert(2, "読込シート", sheet)
121
+
122
+ # 1枚目は MultiIndex 列をメタ列も含めて設定しておく
123
+ if use_header and isinstance(pd.Index(orig_cols), pd.MultiIndex):
124
+ meta = [
125
+ ("meta", "都道府県", ""),
126
+ ("meta", "元ファイル", ""),
127
+ ("meta", "読込シート", ""),
128
+ ]
129
+ df.columns = pd.MultiIndex.from_tuples(meta + list(orig_cols))
130
  return df
131
+ except Exception as e:
132
+ print(f"[WARN] 読み込み失敗: {xls_path} ({e})")
133
  return None
134
 
135
+ # ---- 3段 → 1段 へフラット化 ----
136
+ def flatten_columns(cols, sep: str = "_") -> list[str]:
137
+ """
138
+ MultiIndex 列を '上位_中位_下位' の1段に変換。
139
+ None / NaN / 空白は除去。重複名は .1, .2... を付与。
140
+ """
141
+ # 1) 一旦すべて文字列へ
142
+ def as_str(x):
143
+ s = "" if x is None else str(x)
144
+ s = s.strip()
145
+ return "" if s.lower() == "nan" else s
146
+
147
+ flat = []
148
+ if isinstance(cols, pd.MultiIndex):
149
+ for tpl in cols:
150
+ parts = [as_str(p) for p in tpl]
151
+ parts = [p for p in parts if p] # 空除去
152
+ name = sep.join(parts) if parts else "col"
153
+ flat.append(name)
154
+ else:
155
+ flat = [as_str(c) or "col" for c in cols]
156
+
157
+ # 2) 重複名に連番を付与
158
+ seen = {}
159
+ uniq = []
160
+ for c in flat:
161
+ if c not in seen:
162
+ seen[c] = 0
163
+ uniq.append(c)
164
+ else:
165
+ seen[c] += 1
166
+ uniq.append(f"{c}.{seen[c]}")
167
+ return uniq
168
 
169
  def zip_paths(paths: list[str], out_zip: str) -> str:
170
  with zipfile.ZipFile(out_zip, "w", compression=zipfile.ZIP_DEFLATED) as z:
 
175
 
176
  # -------------------- メイン実行(Gradioから呼ぶ) --------------------
177
 
178
+ def run_job(sheet_name, sleep_sec, limit, re_download, do_flatten, sep, progress=gr.Progress(track_tqdm=False)):
179
  """
180
  sheet_name: "代表地番" 等。空欄なら自動
181
  sleep_sec: ダウンロード間隔
182
  limit: 先頭N件のみ(テスト用)
183
  re_download: 既存ファイルがあっても再取��する
184
+ do_flatten: 列名を1段にフラット化する
185
+ sep: フラット化時のセパレータ
186
  """
187
  progress(0, desc="初期化中…")
188
 
 
189
  session = requests.Session()
190
  session.headers.update({
191
+ "User-Agent": "Mozilla/5.0 (compatible; FITCollector/1.1; +https://huggingface.co/spaces)",
192
  "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
193
  })
194
 
 
209
  progress(0.1 + 0.6 * i / max(1, len(links)),
210
  desc=f"ダウンロード {i}/{len(links)}: {item['pref']}")
211
  try:
212
+ # 既存ファイルを利用(高速化)
 
213
  existing = None
214
  if not re_download and os.path.isdir(OUTDIR):
215
  for fn in os.listdir(OUTDIR):
 
229
  return ("ダウンロードに失敗しました。ネットワークやサイト側制限をご確認ください。",
230
  None, None, None, None)
231
 
232
+ # 3) 読み込み
233
  frames = []
234
  for i, it in enumerate(downloaded, start=1):
235
  progress(0.72 + 0.18 * i / max(1, len(downloaded)),
236
  desc=f"読み込み {i}/{len(downloaded)}: {os.path.basename(it['path'])}")
237
+ df = load_excel(
238
+ it["path"],
239
+ sheet_name if sheet_name else None,
240
+ it["pref"],
241
+ use_header=(i == 1) # 1枚目だけ上3行を列名に
242
+ )
243
  if df is not None and len(df) > 0:
244
  frames.append(df)
245
 
 
 
 
 
 
246
  if not frames:
247
  return ("Excelは取得できましたが、読み込めるデータがありませんでした(シート名の指定を見直してください)。",
248
  None, None, None, None)
249
 
250
+ # 2枚目以降は列名が無いので、1枚目の列名を適用
251
+ if len(frames) > 1:
252
+ frames[1:] = [f.set_axis(frames[0].columns, axis=1) for f in frames[1:]]
253
+
254
+ # 4) 縦結合
255
  combined = pd.concat(frames, ignore_index=True)
256
 
257
+ # 5) 列名のフラット化(推奨)
258
+ if do_flatten:
259
+ combined.columns = flatten_columns(combined.columns, sep=sep or "_")
260
+
261
+ # 6) 出力
262
  os.makedirs(OUTDIR, exist_ok=True)
263
  out_xlsx = os.path.join(OUTDIR, "combined_fit.xlsx")
264
  out_parq = os.path.join(OUTDIR, "combined_fit.parquet")
 
265
  with pd.ExcelWriter(out_xlsx, engine="openpyxl") as w:
266
  combined.to_excel(w, index=False, sheet_name="combined")
267
  combined.to_parquet(out_parq, index=False)
268
 
269
+ # 7) 生ファイル一式のZIP
 
270
  raw_zip = os.path.join(OUTDIR, "raw_excels.zip")
271
  zip_paths([it["path"] for it in downloaded], raw_zip)
272
 
273
+ # 8) プレビュー
 
 
 
 
 
 
 
 
 
274
  preview_csv = os.path.join(OUTDIR, "combined_head.csv")
275
  combined.head(1000).to_csv(preview_csv, index=False)
276
 
277
+ progress(1.0, desc=f"完了({len(combined):,} 行)")
278
+
279
+ msg = (
280
+ f"✅ 結合完了: 行数 = {len(combined):,}\n"
281
+ f"・Excel: combined_fit.xlsx\n"
282
+ f"・Parquet: combined_fit.parquet\n"
283
+ f"・Raw ZIP: raw_excels.zip\n"
284
+ f"・プレビュー: combined_head.csv\n"
285
+ f"・列名フラット化: {'ON' if do_flatten else 'OFF'}(区切り: '{sep or '_'}')"
286
+ )
287
+
288
  return (msg, out_xlsx, out_parq, raw_zip, preview_csv)
289
 
290
  # -------------------- Gradio UI --------------------
 
293
  gr.Markdown(
294
  """
295
  # FIT 公表(都道府県別Excel)一括取得 & 結合
296
+ - 公表ページから都道府県別のExcelを取得し、**1枚目のみ上3行を列名**として採用、**2枚目以降は列名を削除**して縦結合します。
297
+ - 列名はオプションで**フラット化**(例:`大分類_中分類_小分類`)できます(推奨)。
 
298
  """
299
  )
300
  with gr.Row():
 
303
  with gr.Row():
304
  limit = gr.Number(value=None, precision=0, label="先頭N県のみ(テスト用・空欄は全県)")
305
  reget = gr.Checkbox(label="既存ファイルがあっても再ダウンロードする", value=False)
306
+ with gr.Accordion("列名オプション", open=True):
307
+ do_flatten = gr.Checkbox(label="列名を1段にフラット化(推奨)", value=True)
308
+ sep = gr.Textbox(label="フラット化セパレータ", value="_", placeholder="例)_, /, | など")
309
 
310
  run_btn = gr.Button("実行", variant="primary")
311
  out_msg = gr.Markdown()
 
314
  out_zip = gr.File(label="取得した都道府県Excel一式(zip)")
315
  out_preview = gr.File(label="先頭1000行プレビュー(CSV)")
316
 
317
+ run_btn.click(
318
+ fn=run_job,
319
+ inputs=[sheet, sleep, limit, reget, do_flatten, sep],
320
+ outputs=[out_msg, out_xlsx, out_parq, out_zip, out_preview]
321
+ )
322
 
323
  if __name__ == "__main__":
 
324
  demo.queue(max_size=20).launch()