Spaces:
Sleeping

Corin1998 commited on
Commit
717be57
·
verified ·
1 Parent(s): 61bd43f

Update ui/dash.py

Browse files
Files changed (1) hide show
  1. ui/dash.py +265 -70
ui/dash.py CHANGED
@@ -1,105 +1,300 @@
1
  # ui/dash.py
2
  from __future__ import annotations
 
 
 
 
 
 
 
 
3
  import gradio as gr
4
  import pandas as pd
5
- from app.core.utils import ensure_file
6
- from app.services.pipeline import run_full_pipeline
7
- from app.core.policies import INDUSTRY_BENCH
8
- from app.scoring import make_summary
9
 
10
- INDUSTRY_OPTIONS = list(INDUSTRY_BENCH.keys()) + ["その他/未選択"]
11
 
 
12
  def _theme():
13
- # 有効なサイズショートカット: "none", "xs", "sm", "md", "lg", "xl", "xxl"
14
  try:
15
- base = gr.themes.Soft(
16
- radius_size="md", # ← "8px" ではなくショートカットを使う
17
- text_size="sm",
18
- spacing_size="md",
19
- )
20
  except Exception:
21
- # 古い/新しい Gradio でも安全に動くフォールバック
22
  base = gr.themes.Soft()
23
-
24
- # 色などの見た目は set で調整してOK(px指定はしない)
25
  return base.set(
26
  body_background_fill="#f7f9fb",
27
  body_text_color="#0f172a",
28
  block_background_fill="#ffffff",
29
- block_border_width="1px",
30
  block_border_color="#e2e8f0",
31
- block_shadow="none",
32
  input_background_fill="#ffffff",
33
  input_border_color="#cbd5e1",
34
  input_border_width="1px",
35
  button_primary_background_fill="#2563eb",
36
  button_primary_background_fill_hover="#1d4ed8",
37
- button_secondary_background_fill="#f1f5f9",
38
- button_secondary_background_fill_hover="#e2e8f0",
39
  )
40
 
41
 
42
- def _bars(scores: dict) -> pd.DataFrame:
43
- rows = [
44
- ("与信", scores["credit"]["score"]),
45
- ("融資", scores["lending"]["score"]),
46
- ("投資", scores["investment"]["score"]),
47
- ("AI", scores["ai"]["ai_total"]),
48
- ("外部(財務)", scores["external"]["external_total"]),
49
- ("ハイブリッド", scores["hybrid"]["hybrid_total"]),
50
  ]
51
- return pd.DataFrame(rows, columns=["項目","スコア(0-100)"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  def build_interface() -> gr.Blocks:
54
- with gr.Blocks(theme=_theme(), css="""
55
- .bar-row td{padding:6px 8px;}
56
  """) as demo:
57
- gr.Markdown("## 企業スコア(PDF 読込→財務→与信/融資/投資/AI)")
58
 
59
- with gr.Row():
60
- pdf = gr.File(label="決算書PDF", file_types=[".pdf"])
61
- unit = gr.Radio(["自動","円","千円","百万円","億円"], value="自動", label="単位")
62
- c_name = gr.Textbox(label="会社名(任意)")
63
- industry = gr.Dropdown(choices=INDUSTRY_OPTIONS, value="その他/未選択", label="業界(比較用)")
64
- products = gr.Textbox(label="主要プロダクト/事業(AI用、任意)")
65
 
66
- run_btn = gr.Button("解析してスコアリング", variant="primary")
67
- gr.Markdown("### スコア概要(バー)")
 
 
 
 
 
 
68
 
69
- bars = gr.Dataframe(headers=["項目","スコア(0-100)"], interactive=False, wrap=True, elem_classes=["bar-row"])
70
- summary = gr.Markdown("")
 
 
 
 
 
 
 
 
 
71
 
72
  with gr.Row():
73
- fin_tbl = gr.Dataframe(label="財務(抽出値)", interactive=False, wrap=True)
74
- ratio_tbl = gr.Dataframe(label="財務分析(主要)", interactive=False, wrap=True)
75
- kpi_tbl = gr.Dataframe(label="KPI(人員効率など)", interactive=False, wrap=True)
76
-
77
- with gr.Accordion("詳細(与信/融資/投資/AI/外部のJSON)", open=False):
78
- dbg = gr.JSON()
79
-
80
- def _run(pdf_file, unit_sel, c, ind, prod):
81
- path = ensure_file(pdf_file)
82
- u = None if unit_sel=="自動" else unit_sel
83
- out = run_full_pipeline(path, unit_hint=u, company_name=c or "", industry=ind or "", products=prod or "")
84
- df_fin = out["financials"].reset_index()
85
- df_fin.columns = ["科目","値"]
86
- df_rat = out["ratios"].reset_index()
87
- df_rat.columns = ["指標","値"]
88
- df_kpi = out["kpis"].reset_index()
89
- df_kpi.columns = ["KPI","値"]
90
-
91
- s = out["scores"]
92
- bar_df = _bars(s)
93
- summ = make_summary(c or "対象企業", s["external"], s["ai"], s["hybrid"])
94
- return bar_df, summ, df_fin, df_rat, df_kpi, s
95
-
96
- run_btn.click(_run, [pdf, unit, c_name, industry, products], [bars, summary, fin_tbl, ratio_tbl, kpi_tbl, dbg])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
 
 
 
 
98
  with gr.Accordion("起動診断", open=False):
99
- import sys, pkgutil
100
- env = {
101
- "python": sys.version,
102
- "packages": sorted([m.name for m in pkgutil.iter_modules() if m.name.startswith(("gradio","uvicorn","fastapi","pdf","pandas","openai"))]),
103
- }
104
- gr.JSON(env, label="環境")
 
 
 
 
 
 
 
 
 
105
  return demo
 
1
  # ui/dash.py
2
  from __future__ import annotations
3
+
4
+ import html
5
+ import io
6
+ import json
7
+ import traceback
8
+ from importlib import import_module
9
+ from typing import Any, Dict, Optional, Tuple
10
+
11
  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:
 
21
  base = gr.themes.Soft()
 
 
22
  return base.set(
23
  body_background_fill="#f7f9fb",
24
  body_text_color="#0f172a",
25
  block_background_fill="#ffffff",
 
26
  block_border_color="#e2e8f0",
27
+ block_border_width="1px",
28
  input_background_fill="#ffffff",
29
  input_border_color="#cbd5e1",
30
  input_border_width="1px",
31
  button_primary_background_fill="#2563eb",
32
  button_primary_background_fill_hover="#1d4ed8",
 
 
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": "融資",
49
+ "loan": "融資",
50
+ "investment": "投資",
51
+ "ai": "AI",
52
+ "external": "外部(財務)",
53
+ "hybrid": "ハイブリッド",
54
+ "overall": "総合",
55
+ "total": "総合",
56
+ }
57
+ out: Dict[str, float] = {k: None for k in order} # type: ignore
58
+ for k, v in (scores or {}).items():
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
+
73
+
74
+ def _safe_to_df(obj: Any, fallback_cols: list[str]) -> pd.DataFrame:
75
+ if isinstance(obj, pd.DataFrame):
76
+ return obj
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:
84
+ pass
85
+ return _empty_df(fallback_cols)
86
+
87
+
88
+ def _env_diag():
89
+ import sys, pkgutil, platform, gradio
90
+ return {
91
+ "python": sys.version,
92
+ "platform": platform.platform(),
93
+ "gradio": gradio.__version__,
94
+ "packages": sorted(
95
+ [
96
+ m.name
97
+ for m in pkgutil.iter_modules()
98
+ if m.name.startswith(("gradio", "uvicorn", "fastapi", "pandas", "pdf"))
99
+ ]
100
+ ),
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,
140
+ unit=None if unit == "auto" else unit,
141
+ company_name=(company or "").strip() or None,
142
+ industry=(industry or "").strip() or None,
143
+ user_notes=notes or None,
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
+
180
+ debug["stage"] = "ok"
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
188
+ df_bar = _bar_data({})
189
+ return (
190
+ df_bar,
191
+ _empty_df(["指標", "値"]),
192
+ _empty_df(["比率", "値"]),
193
+ _empty_df(["KPI", "値"]),
194
+ f"❌ 解析に失敗しました。\n\n```\n{tb}\n```",
195
+ debug,
196
+ )
197
+
198
+
199
+ def _on_clear():
200
+ return (
201
+ _bar_data({}),
202
+ _empty_df(["指標", "値"]),
203
+ _empty_df(["比率", "値"]),
204
+ _empty_df(["KPI", "値"]),
205
+ "クリアしました。",
206
+ {"stage": "cleared"},
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
+ )
237
+ notes = gr.Textbox(label="補足(任意:決算期や特記事項)")
238
 
239
  with gr.Row():
240
+ run_btn = gr.Button("解析してスコアリング", variant="primary")
241
+ clear_btn = gr.Button("クリア")
242
+
243
+ gr.Markdown("### スコア概要")
244
+ score_bar = gr.BarPlot(
245
+ value=_bar_data({}),
246
+ x="指標",
247
+ y="スコア",
248
+ y_lim=(0, 100),
249
+ tooltip=["指標", "スコア"],
250
+ height=320,
251
+ vertical=True,
252
+ interactive=False,
253
+ )
254
+
255
+ with gr.Tabs():
256
+ with gr.Tab("財務分析(主要)"):
257
+ main_tbl = gr.Dataframe(
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による要約・見解が表示されます。")
279
 
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],
291
+ outputs=[score_bar, main_tbl, ratios_tbl, kpis_tbl, summary_md, debug_json],
292
+ show_progress="full",
293
+ )
294
+ clear_btn.click(
295
+ _on_clear,
296
+ inputs=[],
297
+ outputs=[score_bar, main_tbl, ratios_tbl, kpis_tbl, summary_md, debug_json],
298
+ )
299
+
300
  return demo