Spaces:
Sleeping

Corin1998 commited on
Commit
ca92ff6
·
verified ·
1 Parent(s): 99300ad

Update ui/dash.py

Browse files
Files changed (1) hide show
  1. ui/dash.py +21 -32
ui/dash.py CHANGED
@@ -1,8 +1,7 @@
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
@@ -12,7 +11,6 @@ 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
- # 業界ベンチ(JFC資料を参考にした代表値。必要に応じ CSV 化可能)
16
  BENCH = {
17
  "製造業": {"current_ratio":1.5, "equity_ratio":0.35, "operating_margin":0.06, "inventory_days":70},
18
  "卸売業": {"current_ratio":1.3, "equity_ratio":0.30, "operating_margin":0.03, "inventory_days":45},
@@ -31,11 +29,11 @@ def _bar_figure(scores: Dict[str, float]) -> go.Figure:
31
  fig = go.Figure(go.Bar(
32
  x=vals, y=cats, orientation="h",
33
  text=[f"{v:.1f}" for v in vals], textposition="outside",
34
- marker=dict(line=dict(width=0.5, color="rgba(0,0,0,0.3)"))
35
  ))
36
  fig.update_layout(
37
  xaxis=dict(range=[0,100], gridcolor="rgba(0,0,0,0.05)"),
38
- height=320, margin=dict(l=100, r=20, t=10, b=10),
39
  template="plotly_white"
40
  )
41
  return fig
@@ -43,10 +41,10 @@ def _bar_figure(scores: Dict[str, float]) -> go.Figure:
43
  def _env_diag():
44
  import sys, pkgutil
45
  pkgs = sorted([m.name for m in pkgutil.iter_modules()
46
- if m.name.startswith(("gradio","uvicorn","fastapi","pdf","pandas"))])
47
- return {"python": sys.version, "packages": pkgs}
48
 
49
- def _run_pipeline(pdf_file, unit_sel, company_name, industry_name, products):
50
  if pdf_file is None:
51
  raise gr.Error("PDFをアップロードしてください。")
52
  path = getattr(pdf_file, "name", None)
@@ -54,7 +52,7 @@ def _run_pipeline(pdf_file, unit_sel, company_name, industry_name, products):
54
  raise gr.Error("ファイルパスが取得できませんでした。もう一度アップロードしてください。")
55
 
56
  unit_hint = None if unit_sel == "自動判定" else unit_sel
57
- parsed = parse_financials(path, unit_hint=unit_hint)
58
  fig = parsed["fig"]
59
  ratios = compute_ratios(fig)
60
 
@@ -71,11 +69,7 @@ def _run_pipeline(pdf_file, unit_sel, company_name, industry_name, products):
71
  ext = None
72
  ext_total = None
73
 
74
- # ハイブリッド(簡易)
75
- if ext_total is not None:
76
- hybrid = round((ext_total*0.5 + ai["ai_total"]*0.5), 1)
77
- else:
78
- hybrid = ai["ai_total"]
79
 
80
  scores = {
81
  "与信": credit["credit_total"],
@@ -86,7 +80,6 @@ def _run_pipeline(pdf_file, unit_sel, company_name, industry_name, products):
86
  "ハイブリッド": hybrid,
87
  }
88
 
89
- # スコア表
90
  df_scores = pd.DataFrame([
91
  ["AI", ai["ai_total"], ""],
92
  ["外部(財務)", ext_total, ""],
@@ -96,7 +89,6 @@ def _run_pipeline(pdf_file, unit_sel, company_name, industry_name, products):
96
  ["ハイブリッド", hybrid, ""],
97
  ], columns=["スコア", "点数", "補足"])
98
 
99
- # 財務指標(主要)
100
  df_fin = pd.DataFrame([
101
  ["流動比率", ratios["current_ratio"] and f"{ratios['current_ratio']*100:.1f}%"],
102
  ["当座比率", ratios["quick_ratio"] and f"{ratios['quick_ratio']*100:.1f}%"],
@@ -115,9 +107,8 @@ def _run_pipeline(pdf_file, unit_sel, company_name, industry_name, products):
115
  ["1人当たり純利益", (fig.get("employees") and ratios["profit_per_employee"] is not None) and f"{ratios['profit_per_employee']:,.0f} 円"],
116
  ], columns=["指標","値"]).fillna("—")
117
 
118
- # 業界比較
119
- b = BENCH.get(industry_name or "", None)
120
- if b:
121
  df_cmp = pd.DataFrame([
122
  ["流動比率", df_fin.loc[df_fin["指標"]=="流動比率","値"].values[0], f"{b['current_ratio']*100:.1f}%"],
123
  ["自己資本比率", df_fin.loc[df_fin["指標"]=="自己資本比率","値"].values[0], f"{b['equity_ratio']*100:.1f}%"],
@@ -125,17 +116,12 @@ def _run_pipeline(pdf_file, unit_sel, company_name, industry_name, products):
125
  ["棚卸回転日数", df_fin.loc[df_fin["指標"]=="棚卸回転日数","値"].values[0], f"{b['inventory_days']:.0f} 日"],
126
  ], columns=["指標","対象企業","業界平均"])
127
  else:
128
- df_cmp = pd.DataFrame([["(業界未選択)", "", ""]], columns=["指標","対象企業","業界平均"])
129
 
130
- # 生データ
131
- raw_rows = []
132
- for k, v in fig.items():
133
- raw_rows.append([k, (None if v is None else f"{v:,.0f} 円")])
134
  df_raw = pd.DataFrame(raw_rows, columns=["項目","値"])
135
 
136
- # サマリ
137
  summary = summarize(company_name or "", ai, ext_total, credit, loan, invest)
138
-
139
  return _bar_figure(scores), df_scores, df_fin, df_cmp, df_raw, summary
140
 
141
  def build_interface() -> gr.Blocks:
@@ -143,12 +129,16 @@ def build_interface() -> gr.Blocks:
143
  gr.Markdown("## 企業スコア(PDF読込→財務→与信/融資/投資/AI)")
144
 
145
  with gr.Row():
146
- pdf = gr.File(label="決算書PDF", file_count="single", file_types=[".pdf"], elem_id="pdf")
147
  unit = gr.Radio(["円","千円","百万円","億円","自動判定"], value="自動判定", label="単位")
148
- company = gr.Textbox(label="会社名(任意)", placeholder="例)Alpha株式会社")
149
  with gr.Row():
150
- industry = gr.Dropdown(list(BENCH.keys()), label="業界(JFCベンチ比較)", allow_custom_value=True, value=None, info="プルダウン未選択でも可")
151
- products = gr.Textbox(label="主要プロダクト(任意、カンマ区切り)", placeholder="例)SaaS, 受託開発 など")
 
 
 
 
152
  run = gr.Button("解析する", variant="primary")
153
 
154
  with gr.Tab("スコア概要"):
@@ -170,8 +160,7 @@ def build_interface() -> gr.Blocks:
170
 
171
  run.click(
172
  _run_pipeline,
173
- inputs=[pdf, unit, company, industry, products],
174
  outputs=[plot, score_table, fin_table, cmp_table, raw_table, summary]
175
  )
176
-
177
  return demo
 
1
  # ui/dash.py
2
  from __future__ import annotations
3
  import os
4
+ from typing import Dict, Any
 
5
  import gradio as gr
6
  import pandas as pd
7
  import plotly.graph_objects as go
 
11
  from app.policies import ai_score, credit_score, loan_score, invest_score, summarize
12
  from app.bridge_external import external_from_figures
13
 
 
14
  BENCH = {
15
  "製造業": {"current_ratio":1.5, "equity_ratio":0.35, "operating_margin":0.06, "inventory_days":70},
16
  "卸売業": {"current_ratio":1.3, "equity_ratio":0.30, "operating_margin":0.03, "inventory_days":45},
 
29
  fig = go.Figure(go.Bar(
30
  x=vals, y=cats, orientation="h",
31
  text=[f"{v:.1f}" for v in vals], textposition="outside",
32
+ marker=dict(line=dict(width=0.4, color="rgba(0,0,0,0.3)"))
33
  ))
34
  fig.update_layout(
35
  xaxis=dict(range=[0,100], gridcolor="rgba(0,0,0,0.05)"),
36
+ height=320, margin=dict(l=110, r=20, t=10, b=10),
37
  template="plotly_white"
38
  )
39
  return fig
 
41
  def _env_diag():
42
  import sys, pkgutil
43
  pkgs = sorted([m.name for m in pkgutil.iter_modules()
44
+ if m.name.startswith(("gradio","uvicorn","fastapi","pdf","pandas","openai","fitz","PyMuPDF"))])
45
+ return {"python": sys.version, "packages": pkgs, "OPENAI_API_KEY_set": bool(os.getenv("OPENAI_API_KEY"))}
46
 
47
+ def _run_pipeline(pdf_file, unit_sel, company_name, industry_name, products, engine_sel):
48
  if pdf_file is None:
49
  raise gr.Error("PDFをアップロードしてください。")
50
  path = getattr(pdf_file, "name", None)
 
52
  raise gr.Error("ファイルパスが取得できませんでした。もう一度アップロードしてください。")
53
 
54
  unit_hint = None if unit_sel == "自動判定" else unit_sel
55
+ parsed = parse_financials(path, unit_hint=unit_hint, engine=engine_sel, company_hint=company_name)
56
  fig = parsed["fig"]
57
  ratios = compute_ratios(fig)
58
 
 
69
  ext = None
70
  ext_total = None
71
 
72
+ hybrid = round(((ext_total or 0)*0.5 + ai["ai_total"]*0.5), 1)
 
 
 
 
73
 
74
  scores = {
75
  "与信": credit["credit_total"],
 
80
  "ハイブリッド": hybrid,
81
  }
82
 
 
83
  df_scores = pd.DataFrame([
84
  ["AI", ai["ai_total"], ""],
85
  ["外部(財務)", ext_total, ""],
 
89
  ["ハイブリッド", hybrid, ""],
90
  ], columns=["スコア", "点数", "補足"])
91
 
 
92
  df_fin = pd.DataFrame([
93
  ["流動比率", ratios["current_ratio"] and f"{ratios['current_ratio']*100:.1f}%"],
94
  ["当座比率", ratios["quick_ratio"] and f"{ratios['quick_ratio']*100:.1f}%"],
 
107
  ["1人当たり純利益", (fig.get("employees") and ratios["profit_per_employee"] is not None) and f"{ratios['profit_per_employee']:,.0f} 円"],
108
  ], columns=["指標","値"]).fillna("—")
109
 
110
+ if industry_name and industry_name in BENCH:
111
+ b = BENCH[industry_name]
 
112
  df_cmp = pd.DataFrame([
113
  ["流動比率", df_fin.loc[df_fin["指標"]=="流動比率","値"].values[0], f"{b['current_ratio']*100:.1f}%"],
114
  ["自己資本比率", df_fin.loc[df_fin["指標"]=="自己資本比率","値"].values[0], f"{b['equity_ratio']*100:.1f}%"],
 
116
  ["棚卸回転日数", df_fin.loc[df_fin["指標"]=="棚卸回転日数","値"].values[0], f"{b['inventory_days']:.0f} 日"],
117
  ], columns=["指標","対象企業","業界平均"])
118
  else:
119
+ df_cmp = pd.DataFrame([["(業界未選択)","",""]], columns=["指標","対象企業","業界平均"])
120
 
121
+ raw_rows = [[k, (None if v is None else f"{v:,.0f} 円")] for k, v in fig.items()]
 
 
 
122
  df_raw = pd.DataFrame(raw_rows, columns=["項目","値"])
123
 
 
124
  summary = summarize(company_name or "", ai, ext_total, credit, loan, invest)
 
125
  return _bar_figure(scores), df_scores, df_fin, df_cmp, df_raw, summary
126
 
127
  def build_interface() -> gr.Blocks:
 
129
  gr.Markdown("## 企業スコア(PDF読込→財務→与信/融資/投資/AI)")
130
 
131
  with gr.Row():
132
+ pdf = gr.File(label="決算書PDF", file_count="single", file_types=[".pdf"])
133
  unit = gr.Radio(["円","千円","百万円","億円","自動判定"], value="自動判定", label="単位")
134
+ engine = gr.Dropdown(["auto","LLM","ルール"], value="auto", label="抽出エンジン")
135
  with gr.Row():
136
+ company = gr.Textbox(label="会社名(任意)", placeholder="例)Alpha株式会社")
137
+ industry = gr.Dropdown(list(BENCH.keys()), label="業界(JFCベンチ比較)", allow_custom_value=True)
138
+ products = gr.Textbox(label="主要プロダクト(任意、カンマ区切り)", placeholder="例)SaaS, 受託開発")
139
+ if not os.getenv("OPENAI_API_KEY"):
140
+ gr.Markdown("> ⚠️ **OPENAI_API_KEY が未設定**:LLM抽出(Vision)は使用できません。ルール抽出で動作します。", elem_classes=["warning"])
141
+
142
  run = gr.Button("解析する", variant="primary")
143
 
144
  with gr.Tab("スコア概要"):
 
160
 
161
  run.click(
162
  _run_pipeline,
163
+ inputs=[pdf, unit, company, industry, products, engine],
164
  outputs=[plot, score_table, fin_table, cmp_table, raw_table, summary]
165
  )
 
166
  return demo