Spaces:
Sleeping

Corin1998 commited on
Commit
4f310cc
·
verified ·
1 Parent(s): e661df7

Update ui/dash.py

Browse files
Files changed (1) hide show
  1. ui/dash.py +64 -192
ui/dash.py CHANGED
@@ -1,211 +1,83 @@
1
  # ui/dash.py
2
  from __future__ import annotations
3
- import os
4
- import math
5
- from typing import Dict, Any, Tuple
6
  import gradio as gr
7
  import pandas as pd
8
- import plotly.graph_objects as go
 
 
 
9
 
10
- from app.parsers.finstat import parse_financials
11
- from app.ratios import compute_ratios
12
- from app.policies import ai_score, credit_score, loan_score, invest_score, summarize
13
- from app.bridge_external import external_from_figures
14
 
15
- # ui/dash.py(先頭のimport群)
16
- import gradio as gr
17
- import pandas as pd
18
-
19
- from app.parsers.finstat import parse_financials # PDF→表(正規化済み)
20
- from app.derive.financials import build_ratios_table, build_kpis_table
21
- from app.scoring import (
22
- get_external_template_df,
23
- fill_missing_with_external,
24
- score_external_from_df,
25
- ai_score_company,
26
- hybrid_score,
27
- make_summary,
28
- score_credit,
29
- score_lending,
30
- score_investment,
31
- )
32
- from app.services.pipeline import run_full_pipeline # PDF→一括推論
33
-
34
-
35
- # 業界ベンチ(JFC資料を参考にした代表値。必要に応じ CSV 化可能)
36
- BENCH = {
37
- "製造業": {"current_ratio":1.5, "equity_ratio":0.35, "operating_margin":0.06, "inventory_days":70},
38
- "卸売業": {"current_ratio":1.3, "equity_ratio":0.30, "operating_margin":0.03, "inventory_days":45},
39
- "小売業": {"current_ratio":1.2, "equity_ratio":0.28, "operating_margin":0.03, "inventory_days":35},
40
- "建設業": {"current_ratio":1.5, "equity_ratio":0.35, "operating_margin":0.05, "inventory_days":30},
41
- "情報通信": {"current_ratio":1.8, "equity_ratio":0.40, "operating_margin":0.10, "inventory_days":15},
42
- "サービス": {"current_ratio":1.4, "equity_ratio":0.32, "operating_margin":0.05, "inventory_days":25},
43
- }
44
-
45
- def _fmt_pct(x):
46
- return ("" if x is None else f"{x*100:.1f}%")
47
-
48
- def _bar_figure(scores: Dict[str, float]) -> go.Figure:
49
- cats = list(scores.keys())
50
- vals = [scores[k] for k in cats]
51
- fig = go.Figure(go.Bar(
52
- x=vals, y=cats, orientation="h",
53
- text=[f"{v:.1f}" for v in vals], textposition="outside",
54
- marker=dict(line=dict(width=0.5, color="rgba(0,0,0,0.3)"))
55
- ))
56
- fig.update_layout(
57
- xaxis=dict(range=[0,100], gridcolor="rgba(0,0,0,0.05)"),
58
- height=320, margin=dict(l=100, r=20, t=10, b=10),
59
- template="plotly_white"
60
- )
61
- return fig
62
-
63
- def _env_diag():
64
- import sys, pkgutil
65
- pkgs = sorted([m.name for m in pkgutil.iter_modules()
66
- if m.name.startswith(("gradio","uvicorn","fastapi","pdf","pandas"))])
67
- return {"python": sys.version, "packages": pkgs}
68
-
69
- def _run_pipeline(pdf_file, unit_sel, company_name, industry_name, products):
70
- if pdf_file is None:
71
- raise gr.Error("PDFをアップロードしてください。")
72
- path = getattr(pdf_file, "name", None)
73
- if not path:
74
- raise gr.Error("ファイルパスが取得できませんでした。もう一度アップロードしてください。")
75
-
76
- unit_hint = None if unit_sel == "自動判定" else unit_sel
77
- parsed = parse_financials(path, unit_hint=unit_hint)
78
- fig = parsed["fig"]
79
- ratios = compute_ratios(fig)
80
-
81
- meta = {"industry": industry_name or "", "products": products or ""}
82
- ai = ai_score(meta, ratios, fig)
83
- credit = credit_score(fig, ratios)
84
- loan = loan_score(fig, ratios)
85
- invest = invest_score(meta, ratios, fig, ai)
86
-
87
- try:
88
- ext = external_from_figures(fig)
89
- ext_total = ext.get("external_total")
90
- except Exception:
91
- ext = None
92
- ext_total = None
93
-
94
- # ハイブリッド(簡易)
95
- if ext_total is not None:
96
- hybrid = round((ext_total*0.5 + ai["ai_total"]*0.5), 1)
97
- else:
98
- hybrid = ai["ai_total"]
99
-
100
- scores = {
101
- "与信": credit["credit_total"],
102
- "融資": loan["loan_total"],
103
- "投資": invest["invest_total"],
104
- "AI": ai["ai_total"],
105
- "外部(財務)": (ext_total or 0.0),
106
- "ハイブリッド": hybrid,
107
- }
108
-
109
- # スコア表
110
- df_scores = pd.DataFrame([
111
- ["AI", ai["ai_total"], ""],
112
- ["外部(財務)", ext_total, ""],
113
- ["与信", credit["credit_total"], f"月間上限≈{credit['recommended_monthly_limit']:,}円 / {credit['level']}"],
114
- ["融資", loan["loan_total"], f"余力≈{loan['lending_capacity_estimate']:,}円 / {loan['level']}"],
115
- ["投資", invest["invest_total"], f"時価総額≈{(invest['implied_valuation'] and format(invest['implied_valuation'],',')) or '—'} / {invest['level']}"],
116
- ["ハイブリッド", hybrid, ""],
117
- ], columns=["スコア", "点数", "補足"])
118
-
119
- # 財務指標(主要)
120
- df_fin = pd.DataFrame([
121
- ["流動比率", ratios["current_ratio"] and f"{ratios['current_ratio']*100:.1f}%"],
122
- ["当座比率", ratios["quick_ratio"] and f"{ratios['quick_ratio']*100:.1f}%"],
123
- ["現金比率", ratios["cash_ratio"] and f"{ratios['cash_ratio']*100:.1f}%"],
124
- ["自己資本比率", ratios["equity_ratio"] and f"{ratios['equity_ratio']*100:.1f}%"],
125
- ["D/Eレシオ", ratios["de_ratio"] and f"{ratios['de_ratio']:.2f}"],
126
- ["売上総利益率", _fmt_pct(ratios["gross_margin"])],
127
- ["営業利益率", _fmt_pct(ratios["operating_margin"])],
128
- ["純利益率", _fmt_pct(ratios["net_margin"])],
129
- ["ROA", _fmt_pct(ratios["roa"])],
130
- ["ROE", _fmt_pct(ratios["roe"])],
131
- ["売掛回転日数", ratios["ar_days"] and f"{ratios['ar_days']:.0f} 日"],
132
- ["棚卸回転日数", ratios["inventory_days"] and f"{ratios['inventory_days']:.0f} 日"],
133
- ["買掛回転日数", ratios["ap_days"] and f"{ratios['ap_days']:.0f} 日"],
134
- ["1人当たり売上高", (fig.get("sales") and fig.get("employees")) and f"{(ratios['sales_per_employee']):,.0f} 円"],
135
- ["1人当たり純利益", (fig.get("employees") and ratios["profit_per_employee"] is not None) and f"{ratios['profit_per_employee']:,.0f} 円"],
136
- ], columns=["指標","値"]).fillna("—")
137
-
138
- # 業界比較
139
- b = BENCH.get(industry_name or "", None)
140
- if b:
141
- df_cmp = pd.DataFrame([
142
- ["流動比率", df_fin.loc[df_fin["指標"]=="流動比率","値"].values[0], f"{b['current_ratio']*100:.1f}%"],
143
- ["自己資本比率", df_fin.loc[df_fin["指標"]=="自己資本比率","値"].values[0], f"{b['equity_ratio']*100:.1f}%"],
144
- ["営業利益率", df_fin.loc[df_fin["指標"]=="営業利益率","値"].values[0], f"{b['operating_margin']*100:.1f}%"],
145
- ["棚卸回転日数", df_fin.loc[df_fin["指標"]=="棚卸回転日数","値"].values[0], f"{b['inventory_days']:.0f} 日"],
146
- ], columns=["指標","対象企業","業界平均"])
147
- else:
148
- df_cmp = pd.DataFrame([["(業界未選択)", "", ""]], columns=["指標","対象企業","業界平均"])
149
-
150
- # 生データ
151
- raw_rows = []
152
- for k, v in fig.items():
153
- raw_rows.append([k, (None if v is None else f"{v:,.0f} 円")])
154
- df_raw = pd.DataFrame(raw_rows, columns=["項目","値"])
155
-
156
- # サマリ
157
- summary = summarize(company_name or "", ai, ext_total, credit, loan, invest)
158
-
159
- return _bar_figure(scores), df_scores, df_fin, df_cmp, df_raw, summary
160
-
161
- def build_interface() -> gr.Blocks:
162
- theme = gr.themes.Soft(
163
- radius_size="8px",
164
- text_size="sm",
165
- ).set(
166
  body_text_color="#111",
167
  block_title_text_color="#111",
168
- background_fill_primary="#fafafa",
169
  block_background_fill="#ffffff",
170
  )
171
- with gr.Blocks(theme=theme, css="""
172
- .bar-row .label { color:#222 !important; }
173
- .bar-row .value { color:#222 !important; }
174
- .metric-card { background:#fff; border:1px solid #eee; }
 
 
 
 
 
 
 
 
 
 
 
175
  """) as demo:
176
- with gr.Blocks(title="Company Health Score (PDF→各評価)", theme=gr.themes.Soft()) as demo:
177
- gr.Markdown("## 企業スコア(PDF読込→財務→与信/融資/投資/AI)")
178
 
179
  with gr.Row():
180
- pdf = gr.File(label="決算書PDF", file_count="single", file_types=[".pdf"], elem_id="pdf")
181
- unit = gr.Radio(["円","千円","百万円","億円","自動判定"], value="自動判定", label="単位")
182
- company = gr.Textbox(label="会社名(任意)", placeholder="例)Alpha株式会社")
183
- with gr.Row():
184
- industry = gr.Dropdown(list(BENCH.keys()), label="業界(JFCベンチ比較)", allow_custom_value=True, value=None, info="プルダウン未選択でも可")
185
- products = gr.Textbox(label="主要プロダクト(任意、カンマ区切り)", placeholder="例)SaaS, 受託開発 など")
186
- run = gr.Button("解析する", variant="primary")
187
-
188
- with gr.Tab("スコア概要"):
189
- plot = gr.Plot(label="総合スコア(0-100)")
190
- score_table = gr.Dataframe(headers=["スコア","点数","補足"], interactive=False, wrap=True)
191
 
192
- with gr.Tab("財務分析(主要)"):
193
- fin_table = gr.Dataframe(headers=["指標","値"], interactive=False, wrap=True)
194
- cmp_table = gr.Dataframe(headers=["指標","対象企業","業界平均"], interactive=False, wrap=True)
195
 
196
- with gr.Tab("抽出値(サマリ)"):
197
- raw_table = gr.Dataframe(headers=["項目","値"], interactive=False, wrap=True)
198
 
199
- with gr.Tab("サマリ(文章)"):
200
- summary = gr.Markdown()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
  with gr.Accordion("起動診断", open=False):
203
- gr.JSON(value=_env_diag(), label="環境")
204
-
205
- run.click(
206
- _run_pipeline,
207
- inputs=[pdf, unit, company, industry, products],
208
- outputs=[plot, score_table, fin_table, cmp_table, raw_table, summary]
209
- )
210
-
211
  return demo
 
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
+ return gr.themes.Soft(radius_size="8px", text_size="sm").set(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  body_text_color="#111",
15
  block_title_text_color="#111",
16
+ background_fill_primary="#f7f8fa",
17
  block_background_fill="#ffffff",
18
  )
19
+
20
+ def _bars(scores: dict) -> pd.DataFrame:
21
+ rows = [
22
+ ("与信", scores["credit"]["score"]),
23
+ ("融資", scores["lending"]["score"]),
24
+ ("投資", scores["investment"]["score"]),
25
+ ("AI", scores["ai"]["ai_total"]),
26
+ ("外部(財務)", scores["external"]["external_total"]),
27
+ ("ハイブリッド", scores["hybrid"]["hybrid_total"]),
28
+ ]
29
+ return pd.DataFrame(rows, columns=["項目","スコア(0-100)"])
30
+
31
+ def build_interface() -> gr.Blocks:
32
+ with gr.Blocks(theme=_theme(), css="""
33
+ .bar-row td{padding:6px 8px;}
34
  """) as demo:
35
+ gr.Markdown("## 企業スコア(PDF 読込→財務→与信/融資/投資/AI)")
 
36
 
37
  with gr.Row():
38
+ pdf = gr.File(label="決算書PDF", file_types=[".pdf"])
39
+ unit = gr.Radio(["自動","円","千円","百万円","億円"], value="自動", label="単位")
40
+ c_name = gr.Textbox(label="会社名(任意)")
41
+ industry = gr.Dropdown(choices=INDUSTRY_OPTIONS, value="その他/未選択", label="業界(比較用)")
42
+ products = gr.Textbox(label="主要プロダクト/事業(AI用、任意)")
 
 
 
 
 
 
43
 
44
+ run_btn = gr.Button("解析してスコアリング", variant="primary")
45
+ gr.Markdown("### スコア概要(バー)")
 
46
 
47
+ bars = gr.Dataframe(headers=["項目","スコア(0-100)"], interactive=False, wrap=True, elem_classes=["bar-row"])
48
+ summary = gr.Markdown("")
49
 
50
+ with gr.Row():
51
+ fin_tbl = gr.Dataframe(label="財務(抽出値)", interactive=False, wrap=True)
52
+ ratio_tbl = gr.Dataframe(label="財務分析(主要)", interactive=False, wrap=True)
53
+ kpi_tbl = gr.Dataframe(label="KPI(人員効率など)", interactive=False, wrap=True)
54
+
55
+ with gr.Accordion("詳細(与信/融資/投資/AI/外部のJSON)", open=False):
56
+ dbg = gr.JSON()
57
+
58
+ def _run(pdf_file, unit_sel, c, ind, prod):
59
+ path = ensure_file(pdf_file)
60
+ u = None if unit_sel=="自動" else unit_sel
61
+ out = run_full_pipeline(path, unit_hint=u, company_name=c or "", industry=ind or "", products=prod or "")
62
+ df_fin = out["financials"].reset_index()
63
+ df_fin.columns = ["科目","値"]
64
+ df_rat = out["ratios"].reset_index()
65
+ df_rat.columns = ["指標","値"]
66
+ df_kpi = out["kpis"].reset_index()
67
+ df_kpi.columns = ["KPI","値"]
68
+
69
+ s = out["scores"]
70
+ bar_df = _bars(s)
71
+ summ = make_summary(c or "対象企業", s["external"], s["ai"], s["hybrid"])
72
+ return bar_df, summ, df_fin, df_rat, df_kpi, s
73
+
74
+ run_btn.click(_run, [pdf, unit, c_name, industry, products], [bars, summary, fin_tbl, ratio_tbl, kpi_tbl, dbg])
75
 
76
  with gr.Accordion("起動診断", open=False):
77
+ import sys, pkgutil
78
+ env = {
79
+ "python": sys.version,
80
+ "packages": sorted([m.name for m in pkgutil.iter_modules() if m.name.startswith(("gradio","uvicorn","fastapi","pdf","pandas","openai"))]),
81
+ }
82
+ gr.JSON(env, label="環境")
 
 
83
  return demo