Spaces:
Sleeping

Corin1998 commited on
Commit
92a0478
·
verified ·
1 Parent(s): 8e91222

Update ui/ui_app.py

Browse files
Files changed (1) hide show
  1. ui/ui_app.py +155 -52
ui/ui_app.py CHANGED
@@ -1,21 +1,84 @@
1
- import json, traceback
 
 
 
2
  import gradio as gr
3
  import pandas as pd
4
  import plotly.graph_objects as go
5
 
6
- from core.pdf_utils import pdf_to_images, pdf_to_text
7
- from core.ai_client import extract_financials, short_insight
8
  from core.scorer import score_company
9
- from core.health import health_html
10
 
11
- def fin_to_df(fin: dict) -> pd.DataFrame:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  rows = []
13
- for cat in ("balance_sheet","income_statement","cash_flows"):
14
- for k, v in (fin.get(cat) or {}).items():
15
  rows.append({"category": cat, "item": k, "value": v})
16
- return pd.DataFrame(rows, columns=["category","item","value"])
 
 
 
17
 
18
- def df_to_fin(df: pd.DataFrame) -> dict:
19
  out = {"balance_sheet": {}, "income_statement": {}, "cash_flows": {}}
20
  for _, r in df.iterrows():
21
  cat, item, val = str(r["category"]), str(r["item"]), r["value"]
@@ -27,33 +90,34 @@ def df_to_fin(df: pd.DataFrame) -> dict:
27
  out[cat][item] = parsed
28
  return out
29
 
30
- def radar(score: dict) -> go.Figure:
31
  labels = [d["metric"] for d in score["details"]]
32
  values = [d["score"] for d in score["details"]]
33
  fig = go.Figure()
34
  fig.add_trace(go.Scatterpolar(r=values + values[:1], theta=labels + labels[:1], fill="toself"))
35
- fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0, 100])),
36
- showlegend=False, margin=dict(l=20,r=20,t=30,b=20), height=380,
37
- title=f"総合スコア: {score['total_score']}(グレード: {score['grade']})")
 
 
38
  return fig
39
 
40
  def run_analyze(company: str, use_vision: bool, files: list[str]):
41
  if not files:
42
  raise gr.Error("PDF をアップロードしてください。")
43
 
44
- # 1) 画像化→Vision をまず試す。失敗したら 2) テキスト抽出に自動フォールバック
45
- fin = None
46
- errs = []
47
  try:
48
  if use_vision:
49
- imgs = []
 
 
50
  for p in files:
51
- imgs += pdf_to_images(p, dpi=220, max_pages=6)
52
- fin = extract_financials(imgs, None, company or "")
53
- except Exception as e:
54
- errs.append(f"[Visionスキップ] {e}")
55
-
56
- if fin is None:
57
  text_blob = ""
58
  for p in files:
59
  text_blob += pdf_to_text(p) + "\n\n"
@@ -62,68 +126,107 @@ def run_analyze(company: str, use_vision: bool, files: list[str]):
62
  df = fin_to_df(fin)
63
  score = score_company(fin)
64
  fig = radar(score)
65
- insight = short_insight(fin, score)
66
 
67
- debug = "<br>".join(errs) if errs else "OK"
68
- return (json.dumps(fin, ensure_ascii=False, indent=2),
69
- df,
70
- json.dumps(score, ensure_ascii=False, indent=2),
71
- fig,
72
- insight,
73
- debug)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  def run_recalc(df: pd.DataFrame):
76
  try:
77
  fin = df_to_fin(df)
78
  score = score_company(fin)
79
  fig = radar(score)
80
- return (json.dumps(score, ensure_ascii=False, indent=2), fig, json.dumps(fin, ensure_ascii=False, indent=2))
 
 
 
 
81
  except Exception as e:
82
  tb = traceback.format_exc(limit=6)
83
  raise gr.Error(f"再計算に失敗しました: {e}\n\n<pre style='white-space:pre-wrap'>{tb}</pre>")
84
 
85
  def create_demo():
86
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"), fill_height=True, analytics_enabled=False) as demo:
 
87
  gr.Markdown("## 🧮 企業スコアリング(PDF解析 × OpenAI)")
88
  with gr.Row():
89
  with gr.Column(scale=1):
90
  company = gr.Textbox(label="企業名(任意)", placeholder="例:株式会社OO")
91
  use_vision = gr.Checkbox(value=True, label="OpenAIでPDFをAI解析(Vision)")
92
  files = gr.File(label="決算書PDF(複数可)", file_count="multiple", type="filepath")
93
- run_btn = gr.Button("📄 PDFを解析してテンプレに反映", variant="primary")
94
- recalc_btn = gr.Button("🔁 この表の値で再計算")
95
- health_btn = gr.Button("🩺 環境チェック")
96
- health_out = gr.HTML()
97
- gr.Markdown("※ 画像化/Visionに失敗しても**自動でテキスト抽出にフォールバック**します。")
98
 
99
  with gr.Column(scale=1):
100
  fin_json = gr.Code(label="抽出JSON", language="json", interactive=False)
101
 
102
  with gr.Tabs():
103
  with gr.Tab("抽出結果(表で編集可)"):
104
- df_out = gr.Dataframe(headers=["category", "item", "value"], interactive=True, wrap=True)
 
 
 
 
 
 
 
105
  with gr.Tab("スコアリング"):
106
  score_json = gr.Code(label="スコア(JSON)", language="json")
107
  chart = gr.Plot(label="スコアレーダー")
108
  with gr.Tab("AI診断(日本語)"):
109
  insight_md = gr.Markdown()
110
- with gr.Tab("デバッグ情報"):
111
- debug_md = gr.Markdown()
112
- health_live = gr.HTML(value=health_html())
113
-
114
- run_btn.click(run_analyze, inputs=[company, use_vision, files],
115
- outputs=[fin_json, df_out, score_json, chart, insight_md, debug_md],
116
- concurrency_limit=1)
117
-
118
- recalc_btn.click(run_recalc, inputs=[df_out], outputs=[score_json, chart, fin_json], concurrency_limit=1)
119
- health_btn.click(health_html, outputs=health_out, concurrency_limit=1)
120
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  return demo
122
 
 
 
 
123
  def main():
124
- demo = create_demo()
125
- # DeprecationWarning を避けるため queue() は使わない(重い処理のみイベント側で制限)
126
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
 
127
 
128
  if __name__ == "__main__":
129
  main()
 
1
+ from __future__ import annotations
2
+ import os, io, base64, json, traceback
3
+ from typing import List, Dict, Any
4
+
5
  import gradio as gr
6
  import pandas as pd
7
  import plotly.graph_objects as go
8
 
9
+ from core.ai_client import get_client, VISION_MODEL, TEXT_MODEL
10
+ from core.pdf_utils import has_poppler, pdf_to_images, pdf_to_text
11
  from core.scorer import score_company
 
12
 
13
+ # Gradio の解析情報や分析の送信を無効化(念のため)
14
+ os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
15
+
16
+ SYSTEM_JSON = """あなたは有能な財務アナリストです。
17
+ 与えられた決算書(画像またはテキスト)から、次の厳密な JSON 構造のみを日本語の単位なし・半角数値で返してください。分からない項目は null。
18
+ {
19
+ "company": {"name": null},
20
+ "period": {"start_date": null, "end_date": null},
21
+ "balance_sheet": {
22
+ "total_assets": null, "total_liabilities": null, "total_equity": null,
23
+ "current_assets": null, "fixed_assets": null,
24
+ "current_liabilities": null, "long_term_liabilities": null
25
+ },
26
+ "income_statement": {
27
+ "sales": null, "cost_of_sales": null, "gross_profit": null,
28
+ "operating_expenses": null, "operating_income": null,
29
+ "ordinary_income": null, "net_income": null
30
+ },
31
+ "cash_flows": {
32
+ "operating_cash_flow": null, "investing_cash_flow": null, "financing_cash_flow": null
33
+ }
34
+ }
35
+ """
36
+
37
+ def _b64(img: bytes) -> str:
38
+ return base64.b64encode(img).decode("utf-8")
39
+
40
+ def extract_financials(images: List[bytes] | None, text_blob: str | None, company_hint: str) -> Dict[str, Any]:
41
+ client = get_client()
42
+ if images:
43
+ content = [{"type": "text", "text": SYSTEM_JSON}]
44
+ if company_hint:
45
+ content.append({"type": "text", "text": f"会社名の候補: {company_hint}"})
46
+ for im in images:
47
+ content.append({"type": "input_image", "image_url": f"data:image/png;base64,{_b64(im)}"})
48
+ resp = client.chat.completions.create(
49
+ model=VISION_MODEL,
50
+ messages=[
51
+ {"role": "system", "content": "返答は必ず有効な JSON オブジェクトのみ。説明を含めない。"},
52
+ {"role": "user", "content": content},
53
+ ],
54
+ response_format={"type": "json_object"},
55
+ temperature=0.1,
56
+ )
57
+ return json.loads(resp.choices[0].message.content)
58
+ else:
59
+ prompt = f"{SYSTEM_JSON}\n\n以下は決算書のテキストです。上記の JSON だけを返してください。\n\n{text_blob or ''}"
60
+ resp = client.chat.completions.create(
61
+ model=TEXT_MODEL,
62
+ messages=[
63
+ {"role": "system", "content": "返答は必ず有効な JSON オブジェクトのみ。"},
64
+ {"role": "user", "content": prompt},
65
+ ],
66
+ response_format={"type": "json_object"},
67
+ temperature=0.1,
68
+ )
69
+ return json.loads(resp.choices[0].message.content)
70
+
71
+ def fin_to_df(fin: Dict[str, Any]) -> pd.DataFrame:
72
  rows = []
73
+ def add(cat, d):
74
+ for k, v in (d or {}).items():
75
  rows.append({"category": cat, "item": k, "value": v})
76
+ add("balance_sheet", fin.get("balance_sheet"))
77
+ add("income_statement", fin.get("income_statement"))
78
+ add("cash_flows", fin.get("cash_flows"))
79
+ return pd.DataFrame(rows, columns=["category", "item", "value"])
80
 
81
+ def df_to_fin(df: pd.DataFrame) -> Dict[str, Any]:
82
  out = {"balance_sheet": {}, "income_statement": {}, "cash_flows": {}}
83
  for _, r in df.iterrows():
84
  cat, item, val = str(r["category"]), str(r["item"]), r["value"]
 
90
  out[cat][item] = parsed
91
  return out
92
 
93
+ def radar(score: Dict[str, Any]) -> go.Figure:
94
  labels = [d["metric"] for d in score["details"]]
95
  values = [d["score"] for d in score["details"]]
96
  fig = go.Figure()
97
  fig.add_trace(go.Scatterpolar(r=values + values[:1], theta=labels + labels[:1], fill="toself"))
98
+ fig.update_layout(
99
+ polar=dict(radialaxis=dict(visible=True, range=[0, 100])),
100
+ showlegend=False, margin=dict(l=20, r=20, t=30, b=20), height=380,
101
+ title=f"総合スコア: {score['total_score']}(グレード: {score['grade']})"
102
+ )
103
  return fig
104
 
105
  def run_analyze(company: str, use_vision: bool, files: list[str]):
106
  if not files:
107
  raise gr.Error("PDF をアップロードしてください。")
108
 
109
+ # 画像→Vision、失敗したらテキスト→Text にフォールバック(例外は UI に吸収)
 
 
110
  try:
111
  if use_vision:
112
+ if not has_poppler():
113
+ raise RuntimeError("Poppler が見つかりません(pdf2image が使えません)")
114
+ all_images: List[bytes] = []
115
  for p in files:
116
+ all_images += pdf_to_images(p, dpi=220, max_pages=6)
117
+ fin = extract_financials(all_images, None, company or "")
118
+ else:
119
+ raise RuntimeError("Vision 無効")
120
+ except Exception:
 
121
  text_blob = ""
122
  for p in files:
123
  text_blob += pdf_to_text(p) + "\n\n"
 
126
  df = fin_to_df(fin)
127
  score = score_company(fin)
128
  fig = radar(score)
 
129
 
130
+ # AI所見(失敗しても UI は返す)
131
+ try:
132
+ client = get_client()
133
+ prompt = f"""次の財務データとスコア結果から、箇条書きで短く日本語でコメントしてください。
134
+ - 良い点 3つ
135
+ - 懸念点 3つ
136
+ - 総評(100字以内)
137
+
138
+ [財務データ]
139
+ {json.dumps(fin, ensure_ascii=False)}
140
+
141
+ [スコア]
142
+ {json.dumps(score, ensure_ascii=False)}
143
+ """
144
+ resp = client.chat.completions.create(
145
+ model=TEXT_MODEL,
146
+ messages=[{"role": "system", "content": "簡潔で公正な財務アナリスト。"},
147
+ {"role": "user", "content": prompt}],
148
+ temperature=0.3,
149
+ )
150
+ insight = resp.choices[0].message.content
151
+ except Exception as e:
152
+ insight = f"AI所見の生成に失敗: {e}"
153
+
154
+ return (
155
+ json.dumps(fin, ensure_ascii=False, indent=2),
156
+ df,
157
+ json.dumps(score, ensure_ascii=False, indent=2),
158
+ fig,
159
+ insight
160
+ )
161
 
162
  def run_recalc(df: pd.DataFrame):
163
  try:
164
  fin = df_to_fin(df)
165
  score = score_company(fin)
166
  fig = radar(score)
167
+ return (
168
+ json.dumps(score, ensure_ascii=False, indent=2),
169
+ fig,
170
+ json.dumps(fin, ensure_ascii=False, indent=2)
171
+ )
172
  except Exception as e:
173
  tb = traceback.format_exc(limit=6)
174
  raise gr.Error(f"再計算に失敗しました: {e}\n\n<pre style='white-space:pre-wrap'>{tb}</pre>")
175
 
176
  def create_demo():
177
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"),
178
+ fill_height=True, analytics_enabled=False) as demo:
179
  gr.Markdown("## 🧮 企業スコアリング(PDF解析 × OpenAI)")
180
  with gr.Row():
181
  with gr.Column(scale=1):
182
  company = gr.Textbox(label="企業名(任意)", placeholder="例:株式会社OO")
183
  use_vision = gr.Checkbox(value=True, label="OpenAIでPDFをAI解析(Vision)")
184
  files = gr.File(label="決算書PDF(複数可)", file_count="multiple", type="filepath")
185
+ run_btn = gr.Button("📄 解析する", variant="primary")
186
+ recalc_btn = gr.Button("🔁 表の値で再計算")
 
 
 
187
 
188
  with gr.Column(scale=1):
189
  fin_json = gr.Code(label="抽出JSON", language="json", interactive=False)
190
 
191
  with gr.Tabs():
192
  with gr.Tab("抽出結果(表で編集可)"):
193
+ # ★ スキーマを明示して API 情報生成で落ちないようにする
194
+ df_out = gr.Dataframe(
195
+ headers=["category", "item", "value"],
196
+ datatype=["str", "str", "number"],
197
+ col_count=(3, "fixed"),
198
+ row_count=(1, "dynamic"),
199
+ interactive=True
200
+ )
201
  with gr.Tab("スコアリング"):
202
  score_json = gr.Code(label="スコア(JSON)", language="json")
203
  chart = gr.Plot(label="スコアレーダー")
204
  with gr.Tab("AI診断(日本語)"):
205
  insight_md = gr.Markdown()
 
 
 
 
 
 
 
 
 
 
206
 
207
+ run_btn.click(
208
+ run_analyze,
209
+ inputs=[company, use_vision, files],
210
+ outputs=[fin_json, df_out, score_json, chart, insight_md],
211
+ concurrency_limit=2
212
+ )
213
+ recalc_btn.click(
214
+ run_recalc,
215
+ inputs=[df_out],
216
+ outputs=[score_json, chart, fin_json],
217
+ concurrency_limit=2
218
+ )
219
  return demo
220
 
221
+ # Spaces/コンテナ両対応
222
+ demo = create_demo()
223
+
224
  def main():
225
+ # Spaces などローカル疎通ができない環境では share=True が必須
226
+ share_default = os.getenv("GRADIO_SHARE", "1") # "1"=True / "0"=False
227
+ share = (share_default != "0")
228
+ port = int(os.getenv("PORT", "7860"))
229
+ demo.launch(server_name="0.0.0.0", server_port=port, share=share, max_threads=8)
230
 
231
  if __name__ == "__main__":
232
  main()