Spaces:
Sleeping

Corin1998 commited on
Commit
756a78e
·
verified ·
1 Parent(s): dcaa126

Update ui/dash.py

Browse files
Files changed (1) hide show
  1. ui/dash.py +9 -49
ui/dash.py CHANGED
@@ -12,9 +12,7 @@ import gradio as gr
12
  import pandas as pd
13
 
14
 
15
- # ---------- Theme: Gradio v4 で安全なショートカットのみ使用 ----------
16
  def _theme():
17
- # Soft テーマに fall-back しつつ、CSSトークンだけ最低限上書き
18
  try:
19
  base = gr.themes.Soft(radius_size="md", text_size="sm", spacing_size="md")
20
  except Exception:
@@ -33,16 +31,12 @@ def _theme():
33
  )
34
 
35
 
36
- # ---------- Util ----------
37
  def _empty_df(cols: list[str]) -> pd.DataFrame:
38
  return pd.DataFrame([], columns=cols)
39
 
40
 
41
  def _bar_data(scores: Dict[str, float]) -> pd.DataFrame:
42
- order = [
43
- "与信", "融資", "投資", "AI", "外部(財務)", "ハイブリッド", "総合"
44
- ]
45
- # 既存キーとのマッピングを広く受ける
46
  alias = {
47
  "credit": "与信",
48
  "lending": "融資",
@@ -59,14 +53,12 @@ def _bar_data(scores: Dict[str, float]) -> pd.DataFrame:
59
  name = alias.get(k, k)
60
  if name in out and isinstance(v, (int, float)):
61
  out[name] = float(v)
62
-
63
  rows = []
64
  for k in order:
65
  val = out.get(k)
66
  if isinstance(val, (int, float)):
67
  rows.append({"指標": k, "スコア": max(0, min(100, float(val)))})
68
  if not rows:
69
- # 最低限の骨組み
70
  rows = [{"指標": n, "スコア": 0.0} for n in order[:5]]
71
  return pd.DataFrame(rows)
72
 
@@ -77,7 +69,6 @@ def _safe_to_df(obj: Any, fallback_cols: list[str]) -> pd.DataFrame:
77
  if isinstance(obj, (list, tuple)) and obj and isinstance(obj[0], dict):
78
  return pd.DataFrame(obj)
79
  if isinstance(obj, dict):
80
- # dict of lists も受ける
81
  try:
82
  return pd.DataFrame(obj)
83
  except Exception:
@@ -101,39 +92,29 @@ def _env_diag():
101
  }
102
 
103
 
104
- # ---------- Callback(重い処理はここでのみ実行) ----------
105
  def _on_analyze(
106
  pdf: gr.File | None,
107
  unit: str,
108
  company: str,
109
  industry: str,
110
  notes: str,
111
- ) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame, str, Dict[str, Any]]:
112
- """
113
- 返り値:
114
- (scores_bar_df, main_df, ratios_df, kpis_df, summary_md, debug_json)
115
- """
116
  debug: Dict[str, Any] = {"stage": "start", "unit": unit, "industry": industry}
117
  try:
118
  if not pdf:
119
  raise RuntimeError("PDFが未選択です。ファイルをアップロードしてください。")
120
 
121
- # run_full_pipeline を遅延 import(存在しない場合でも例外で落ちずに情報表示)
122
  pipeline = import_module("app.services.pipeline")
123
  run_full_pipeline = getattr(pipeline, "run_full_pipeline", None)
124
  if run_full_pipeline is None:
125
- raise ImportError(
126
- "app.services.pipeline.run_full_pipeline が見つかりません。"
127
- )
128
 
129
- # gr.File は dict/obj のことがあるので path を安全に取得
130
  pdf_path = getattr(pdf, "name", None) or getattr(pdf, "path", None)
131
  if not pdf_path and isinstance(pdf, dict):
132
  pdf_path = pdf.get("name") or pdf.get("path")
133
  if not pdf_path:
134
  raise RuntimeError("PDFファイルのパスを取得できませんでした。")
135
 
136
- # パイプライン実行
137
  debug["stage"] = "pipeline_call"
138
  result = run_full_pipeline(
139
  pdf_path=pdf_path,
@@ -144,36 +125,28 @@ def _on_analyze(
144
  )
145
  debug["result_keys"] = list(result.keys()) if isinstance(result, dict) else type(result).__name__
146
 
147
- # Duck typing で拾う
148
  scores = {}
149
  tables = {}
150
  summary = ""
151
 
152
  if isinstance(result, dict):
153
- # スコア候補
154
  for key in ("scores", "score", "scorecard"):
155
  if key in result and isinstance(result[key], dict):
156
  scores = result[key]
157
  break
158
- # テーブル候補
159
  for key in ("tables", "dataframes", "dfs"):
160
  if key in result and isinstance(result[key], dict):
161
  tables = result[key]
162
  break
163
- # サマリ候補
164
  for key in ("summary", "report", "comment"):
165
  if key in result and isinstance(result[key], str):
166
  summary = result[key]
167
  break
168
 
169
- # バー用
170
  df_bar = _bar_data(scores)
171
-
172
- # 各テーブル(無ければ空)
173
  main_df = _safe_to_df(tables.get("main") if isinstance(tables, dict) else None, ["指標", "値"])
174
  ratios_df = _safe_to_df(tables.get("ratios") if isinstance(tables, dict) else None, ["比率", "値"])
175
  kpis_df = _safe_to_df(tables.get("kpis") if isinstance(tables, dict) else None, ["KPI", "値"])
176
-
177
  if not summary:
178
  summary = "※ パイプラインからのサマリが見つかりませんでした。"
179
 
@@ -181,7 +154,6 @@ def _on_analyze(
181
  return df_bar, main_df, ratios_df, kpis_df, summary, debug
182
 
183
  except Exception as e:
184
- # 例外でも UI は出す
185
  tb = traceback.format_exc()
186
  debug["error"] = str(e)
187
  debug["traceback"] = tb
@@ -207,30 +179,21 @@ def _on_clear():
207
  )
208
 
209
 
210
- # ---------- UI ----------
211
  def build_interface() -> gr.Blocks:
212
- with gr.Blocks(theme=_theme(), fill_height=True, css="""
213
- .gradio-container { max-width: 1200px !important; margin: 0 auto; }
214
- """) as demo:
215
 
216
  gr.Markdown("## 企業スコア(PDF読込→財務→与信/融資/投資/AI)")
217
 
218
  with gr.Row():
219
  pdf = gr.File(label="決算書PDF(単独/連結どちらでも)", file_types=[".pdf"], type="filepath")
220
  unit = gr.Radio(
221
- ["auto", "円", "千円", "百万円", "億円"],
222
- value="auto",
223
- label="単位",
224
- info="自動判定 or 明示選択",
225
  )
226
 
227
  with gr.Row():
228
  company = gr.Textbox(label="会社名(任意)", placeholder="例:ミヤ株式会社")
229
  industry = gr.Dropdown(
230
- choices=[
231
- "任意", "製造業", "建設業", "情報通信業", "卸売業", "小売業",
232
- "運輸業", "不動産業", "サービス業", "金融・保険業", "飲食/宿泊"
233
- ],
234
  value="任意",
235
  label="業種(任意)",
236
  )
@@ -247,7 +210,6 @@ def build_interface() -> gr.Blocks:
247
  y="スコア",
248
  y_lim=(0, 100),
249
  tooltip=["指標", "スコア"],
250
- height=320,
251
  vertical=True,
252
  interactive=False,
253
  )
@@ -258,21 +220,21 @@ def build_interface() -> gr.Blocks:
258
  value=_empty_df(["指標", "値"]),
259
  wrap=True,
260
  interactive=False,
261
- height=360,
262
  )
263
  with gr.Tab("財務分析(比率)"):
264
  ratios_tbl = gr.Dataframe(
265
  value=_empty_df(["比率", "値"]),
266
  wrap=True,
267
  interactive=False,
268
- height=360,
269
  )
270
  with gr.Tab("KPI / 参考"):
271
  kpis_tbl = gr.Dataframe(
272
  value=_empty_df(["KPI", "値"]),
273
  wrap=True,
274
  interactive=False,
275
- height=360,
276
  )
277
  with gr.Tab("サマリ"):
278
  summary_md = gr.Markdown("ここにAIによる要約・見解が表示されます。")
@@ -280,11 +242,9 @@ def build_interface() -> gr.Blocks:
280
  with gr.Tab("デバッグ"):
281
  debug_json = gr.JSON(label="debug")
282
 
283
- # 起動診断(軽量)
284
  with gr.Accordion("起動診断", open=False):
285
  diag = gr.JSON(value=_env_diag(), label="環境")
286
 
287
- # 配線(重い処理はここで)
288
  run_btn.click(
289
  _on_analyze,
290
  inputs=[pdf, unit, company, industry, notes],
 
12
  import pandas as pd
13
 
14
 
 
15
  def _theme():
 
16
  try:
17
  base = gr.themes.Soft(radius_size="md", text_size="sm", spacing_size="md")
18
  except Exception:
 
31
  )
32
 
33
 
 
34
  def _empty_df(cols: list[str]) -> pd.DataFrame:
35
  return pd.DataFrame([], columns=cols)
36
 
37
 
38
  def _bar_data(scores: Dict[str, float]) -> pd.DataFrame:
39
+ order = ["与信", "融資", "投資", "AI", "外部(財務)", "ハイブリッド", "総合"]
 
 
 
40
  alias = {
41
  "credit": "与信",
42
  "lending": "融資",
 
53
  name = alias.get(k, k)
54
  if name in out and isinstance(v, (int, float)):
55
  out[name] = float(v)
 
56
  rows = []
57
  for k in order:
58
  val = out.get(k)
59
  if isinstance(val, (int, float)):
60
  rows.append({"指標": k, "スコア": max(0, min(100, float(val)))})
61
  if not rows:
 
62
  rows = [{"指標": n, "スコア": 0.0} for n in order[:5]]
63
  return pd.DataFrame(rows)
64
 
 
69
  if isinstance(obj, (list, tuple)) and obj and isinstance(obj[0], dict):
70
  return pd.DataFrame(obj)
71
  if isinstance(obj, dict):
 
72
  try:
73
  return pd.DataFrame(obj)
74
  except Exception:
 
92
  }
93
 
94
 
 
95
  def _on_analyze(
96
  pdf: gr.File | None,
97
  unit: str,
98
  company: str,
99
  industry: str,
100
  notes: str,
101
+ ):
 
 
 
 
102
  debug: Dict[str, Any] = {"stage": "start", "unit": unit, "industry": industry}
103
  try:
104
  if not pdf:
105
  raise RuntimeError("PDFが未選択です。ファイルをアップロードしてください。")
106
 
 
107
  pipeline = import_module("app.services.pipeline")
108
  run_full_pipeline = getattr(pipeline, "run_full_pipeline", None)
109
  if run_full_pipeline is None:
110
+ raise ImportError("app.services.pipeline.run_full_pipeline が見つかりません。")
 
 
111
 
 
112
  pdf_path = getattr(pdf, "name", None) or getattr(pdf, "path", None)
113
  if not pdf_path and isinstance(pdf, dict):
114
  pdf_path = pdf.get("name") or pdf.get("path")
115
  if not pdf_path:
116
  raise RuntimeError("PDFファイルのパスを取得できませんでした。")
117
 
 
118
  debug["stage"] = "pipeline_call"
119
  result = run_full_pipeline(
120
  pdf_path=pdf_path,
 
125
  )
126
  debug["result_keys"] = list(result.keys()) if isinstance(result, dict) else type(result).__name__
127
 
 
128
  scores = {}
129
  tables = {}
130
  summary = ""
131
 
132
  if isinstance(result, dict):
 
133
  for key in ("scores", "score", "scorecard"):
134
  if key in result and isinstance(result[key], dict):
135
  scores = result[key]
136
  break
 
137
  for key in ("tables", "dataframes", "dfs"):
138
  if key in result and isinstance(result[key], dict):
139
  tables = result[key]
140
  break
 
141
  for key in ("summary", "report", "comment"):
142
  if key in result and isinstance(result[key], str):
143
  summary = result[key]
144
  break
145
 
 
146
  df_bar = _bar_data(scores)
 
 
147
  main_df = _safe_to_df(tables.get("main") if isinstance(tables, dict) else None, ["指標", "値"])
148
  ratios_df = _safe_to_df(tables.get("ratios") if isinstance(tables, dict) else None, ["比率", "値"])
149
  kpis_df = _safe_to_df(tables.get("kpis") if isinstance(tables, dict) else None, ["KPI", "値"])
 
150
  if not summary:
151
  summary = "※ パイプラインからのサマリが見つかりませんでした。"
152
 
 
154
  return df_bar, main_df, ratios_df, kpis_df, summary, debug
155
 
156
  except Exception as e:
 
157
  tb = traceback.format_exc()
158
  debug["error"] = str(e)
159
  debug["traceback"] = tb
 
179
  )
180
 
181
 
 
182
  def build_interface() -> gr.Blocks:
183
+ with gr.Blocks(theme=_theme(), css=".gradio-container{max-width:1200px;margin:0 auto;}") as demo:
 
 
184
 
185
  gr.Markdown("## 企業スコア(PDF読込→財務→与信/融資/投資/AI)")
186
 
187
  with gr.Row():
188
  pdf = gr.File(label="決算書PDF(単独/連結どちらでも)", file_types=[".pdf"], type="filepath")
189
  unit = gr.Radio(
190
+ ["auto", "円", "千円", "百万円", "億円"], value="auto", label="単位", info="自動判定 or 明示選択"
 
 
 
191
  )
192
 
193
  with gr.Row():
194
  company = gr.Textbox(label="会社名(任意)", placeholder="例:ミヤ株式会社")
195
  industry = gr.Dropdown(
196
+ choices=["任意", "製造業", "建設業", "情報通信業", "卸売業", "小売業", "運輸業", "不動産業", "サービス業", "金融・保険業", "飲食/宿泊"],
 
 
 
197
  value="任意",
198
  label="業種(任意)",
199
  )
 
210
  y="スコア",
211
  y_lim=(0, 100),
212
  tooltip=["指標", "スコア"],
 
213
  vertical=True,
214
  interactive=False,
215
  )
 
220
  value=_empty_df(["指標", "値"]),
221
  wrap=True,
222
  interactive=False,
223
+ label="主要項目",
224
  )
225
  with gr.Tab("財務分析(比率)"):
226
  ratios_tbl = gr.Dataframe(
227
  value=_empty_df(["比率", "値"]),
228
  wrap=True,
229
  interactive=False,
230
+ label="比率",
231
  )
232
  with gr.Tab("KPI / 参考"):
233
  kpis_tbl = gr.Dataframe(
234
  value=_empty_df(["KPI", "値"]),
235
  wrap=True,
236
  interactive=False,
237
+ label="KPI",
238
  )
239
  with gr.Tab("サマリ"):
240
  summary_md = gr.Markdown("ここにAIによる要約・見解が表示されます。")
 
242
  with gr.Tab("デバッグ"):
243
  debug_json = gr.JSON(label="debug")
244
 
 
245
  with gr.Accordion("起動診断", open=False):
246
  diag = gr.JSON(value=_env_diag(), label="環境")
247
 
 
248
  run_btn.click(
249
  _on_analyze,
250
  inputs=[pdf, unit, company, industry, notes],