Corin1998 commited on
Commit
19256c1
·
verified ·
1 Parent(s): b0b5cb4

Update ui/ui_app.py

Browse files
Files changed (1) hide show
  1. ui/ui_app.py +199 -20
ui/ui_app.py CHANGED
@@ -1,55 +1,234 @@
1
- # ui/ui_app.py の run_analyze を丸ごと置換
2
- def run_analyze(company: str, use_vision: bool, files: list[str], force_ocr: bool = False):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  if not files:
4
  raise gr.Error("PDF をアップロードしてください。")
5
 
 
6
  try:
7
  images, raw_text, business_text, dbg = parse_pdf(files, force_ocr=force_ocr)
8
  except ExtractError as e:
9
- # 環境起因など致命的なものはここでユーザーに明示
10
  raise gr.Error(f"PDF読み込みに失敗: {e}")
11
 
12
- # --- Vision / Text フォールバック ---
13
  try:
14
  if use_vision and images:
15
  fin = extract_financials(images, None, company or "")
16
  else:
17
  fin = extract_financials(None, raw_text, company or "")
18
  except Exception:
19
- # Vision失敗→テキストへ
20
  try:
21
  fin = extract_financials(None, raw_text, company or "")
22
  except Exception as e:
23
  raise gr.Error(f"AI抽出に失敗: {e}")
24
 
25
  df = fin_to_df(fin)
26
- score_internal = score_company(fin) # 既存社内ルール
27
- fig = radar(score_internal)
28
 
29
- # 外部評価(定量化): 既存の external_scoring を利用
30
  try:
31
- external_score = score_external_from_df(df) # ← 名前はあなたの実装に合わせて
32
- except Exception:
33
- external_score = {"external_total": None, "items": []}
34
 
35
- # AI 所見(中立・定量KPI+市場/製品の補足)
36
  try:
37
- insight = make_ai_memo(
38
  company=company or "",
39
  fin=fin,
40
- score_internal=score_internal,
41
- score_external=external_score,
42
  business_text=business_text
43
  )
44
  except Exception as e:
45
- insight = f"AI所見の生成に失敗: {e}"
46
 
47
- # 右ペインやタブへ返す
48
  return (
49
  json.dumps(fin, ensure_ascii=False, indent=2),
50
  df,
51
- json.dumps(score_internal, ensure_ascii=False, indent=2),
52
  fig,
53
- insight,
54
- dbg # 抽出ログ/デバッグ表示用(ui 側で Textbox/Code に出す)
 
55
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ui/ui_app.py
2
+ from __future__ import annotations
3
+ import os, io, json, base64, traceback
4
+ import gradio as gr
5
+ import pandas as pd
6
+ import plotly.graph_objects as go
7
+
8
+ from core.extract import parse_pdf, ExtractError
9
+ from core.scoring import score_company
10
+ from core.external_scoring import score_external_from_df
11
+ from core.ai_judgement import make_ai_memo
12
+
13
+ # ================= 共通ユーティリティ =================
14
+
15
+ def _b64(img_bytes):
16
+ return base64.b64encode(img_bytes).decode("utf-8")
17
+
18
+ def fin_to_df(fin):
19
+ rows = []
20
+ def add(cat, d):
21
+ for k, v in (d or {}).items():
22
+ rows.append({"category": cat, "item": k, "value": v})
23
+ add("balance_sheet", fin.get("balance_sheet"))
24
+ add("income_statement", fin.get("income_statement"))
25
+ add("cash_flows", fin.get("cash_flows"))
26
+ return pd.DataFrame(rows, columns=["category", "item", "value"])
27
+
28
+ def df_to_fin(df):
29
+ out = {"balance_sheet": {}, "income_statement": {}, "cash_flows": {}}
30
+ for _, r in df.iterrows():
31
+ cat, item, val = str(r["category"]), str(r["item"]), r["value"]
32
+ try:
33
+ parsed = None if val in (None, "", "null") else float(str(val).replace(",",""))
34
+ except Exception:
35
+ parsed = None
36
+ if cat in out:
37
+ out[cat][item] = parsed
38
+ return out
39
+
40
+ def radar(score):
41
+ labels = [d["metric"] for d in score["details"]]
42
+ values = [d["score"] for d in score["details"]]
43
+ fig = go.Figure()
44
+ fig.add_trace(go.Scatterpolar(r=values + values[:1], theta=labels + labels[:1], fill="toself"))
45
+ fig.update_layout(
46
+ polar=dict(radialaxis=dict(visible=True, range=[0, 100])),
47
+ showlegend=False,
48
+ margin=dict(l=20, r=20, t=30, b=20),
49
+ height=380,
50
+ title=f"総合スコア: {score['total_score']}(グレード: {score['grade']})"
51
+ )
52
+ return fig
53
+
54
+ # ================ OpenAI 抽出(Vision / Text) =================
55
+
56
+ OPENAI_MODEL_VISION = os.environ.get("OPENAI_VISION_MODEL", "gpt-4o-mini")
57
+ OPENAI_MODEL_TEXT = os.environ.get("OPENAI_TEXT_MODEL", "gpt-4o-mini")
58
+
59
+ SYSTEM_JSON = """あなたは有能な財務アナリストです。
60
+ 与えられた決算書(画像またはテキスト)から、次の厳密な JSON 構造のみを日本語の単位なし・半角数値で返してください。分からない項目は null。
61
+ {
62
+ "company": {"name": null},
63
+ "period": {"start_date": null, "end_date": null},
64
+ "balance_sheet": {
65
+ "total_assets": null, "total_liabilities": null, "total_equity": null,
66
+ "current_assets": null, "fixed_assets": null,
67
+ "current_liabilities": null, "long_term_liabilities": null
68
+ },
69
+ "income_statement": {
70
+ "sales": null, "cost_of_sales": null, "gross_profit": null,
71
+ "operating_expenses": null, "operating_income": null,
72
+ "ordinary_income": null, "net_income": null
73
+ },
74
+ "cash_flows": {
75
+ "operating_cash_flow": null, "investing_cash_flow": null, "financing_cash_flow": null
76
+ }
77
+ }
78
+ """
79
+
80
+ def _openai_client():
81
+ # openai==1.x の公式クライアント。proxies を渡さない(互換性エラー回避)。
82
+ from openai import OpenAI
83
+ key = os.environ.get("OPENAI_API_KEY")
84
+ if not key:
85
+ raise gr.Error("OPENAI_API_KEY が未設定です。Spaces → Settings → **Variables and secrets** に `OPENAI_API_KEY` を追加してください。")
86
+ return OpenAI(api_key=key, timeout=30)
87
+
88
+ def extract_financials(images, text_blob, company_hint):
89
+ client = _openai_client()
90
+ if images:
91
+ content = [{"type": "text", "text": SYSTEM_JSON}]
92
+ if company_hint:
93
+ content.append({"type": "text", "text": f"会社名の候補: {company_hint}"})
94
+ for im in images:
95
+ content.append({"type": "input_image", "image_url": f"data:image/png;base64,{_b64(im)}"})
96
+ resp = client.chat.completions.create(
97
+ model=OPENAI_MODEL_VISION,
98
+ messages=[
99
+ {"role": "system", "content": "返答は必ず有効な JSON オブジェクトのみ。説明を含めない。"},
100
+ {"role": "user", "content": content},
101
+ ],
102
+ response_format={"type": "json_object"},
103
+ temperature=0.1,
104
+ )
105
+ return json.loads(resp.choices[0].message.content)
106
+ else:
107
+ prompt = f"{SYSTEM_JSON}\n\n以下は決算書のテキストです。上記の JSON だけを返してください。\n\n{text_blob or ''}"
108
+ resp = client.chat.completions.create(
109
+ model=OPENAI_MODEL_TEXT,
110
+ messages=[
111
+ {"role": "system", "content": "返答は必ず有効な JSON オブジェクトのみ。"},
112
+ {"role": "user", "content": prompt},
113
+ ],
114
+ response_format={"type": "json_object"},
115
+ temperature=0.1,
116
+ )
117
+ return json.loads(resp.choices[0].message.content)
118
+
119
+ # ================== ハンドラ(型ヒントなしで安定化) ==================
120
+
121
+ def run_analyze(company, use_vision, files, force_ocr):
122
  if not files:
123
  raise gr.Error("PDF をアップロードしてください。")
124
 
125
+ # 1) PDF抽出(テキスト→足りなければ画像化)
126
  try:
127
  images, raw_text, business_text, dbg = parse_pdf(files, force_ocr=force_ocr)
128
  except ExtractError as e:
 
129
  raise gr.Error(f"PDF読み込みに失敗: {e}")
130
 
131
+ # 2) Vision 優先 失敗ならテキスト
132
  try:
133
  if use_vision and images:
134
  fin = extract_financials(images, None, company or "")
135
  else:
136
  fin = extract_financials(None, raw_text, company or "")
137
  except Exception:
 
138
  try:
139
  fin = extract_financials(None, raw_text, company or "")
140
  except Exception as e:
141
  raise gr.Error(f"AI抽出に失敗: {e}")
142
 
143
  df = fin_to_df(fin)
144
+ score_int = score_company(fin)
145
+ fig = radar(score_int)
146
 
147
+ # 3) 外部評価(定量化)
148
  try:
149
+ score_ext = score_external_from_df(df)
150
+ except Exception as e:
151
+ score_ext = {"name": "外部評価(失敗)", "external_total": None, "items": [], "notes": str(e)}
152
 
153
+ # 4) AI 所見(中立)
154
  try:
155
+ memo = make_ai_memo(
156
  company=company or "",
157
  fin=fin,
158
+ score_internal=score_int,
159
+ score_external=score_ext,
160
  business_text=business_text
161
  )
162
  except Exception as e:
163
+ memo = f"AI所見の生成に失敗: {e}"
164
 
 
165
  return (
166
  json.dumps(fin, ensure_ascii=False, indent=2),
167
  df,
168
+ json.dumps(score_int, ensure_ascii=False, indent=2),
169
  fig,
170
+ memo,
171
+ json.dumps(score_ext, ensure_ascii=False, indent=2),
172
+ dbg
173
  )
174
+
175
+ def run_recalc(df):
176
+ try:
177
+ fin = df_to_fin(df)
178
+ score_int = score_company(fin)
179
+ fig = radar(score_int)
180
+ return (
181
+ json.dumps(score_int, ensure_ascii=False, indent=2),
182
+ fig,
183
+ json.dumps(fin, ensure_ascii=False, indent=2)
184
+ )
185
+ except Exception as e:
186
+ tb = traceback.format_exc(limit=6)
187
+ raise gr.Error(f"再計算に失敗しました: {e}\n\n<pre style='white-space:pre-wrap'>{tb}</pre>")
188
+
189
+ # ================== UI 組み立て ==================
190
+
191
+ def build_ui():
192
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"), fill_height=True, analytics_enabled=False) as demo:
193
+ gr.Markdown("## 🧮 企業スコアリング(PDF解析 × OpenAI Vision)")
194
+
195
+ with gr.Row():
196
+ with gr.Column(scale=1):
197
+ company = gr.Textbox(label="企業名(任意)", placeholder="例:株式会社OO")
198
+ use_vision = gr.Checkbox(value=True, label="OpenAIでPDFをAI解析(Vision)")
199
+ force_ocr = gr.Checkbox(value=False, label="OCRを強制(スキャンPDF向け)")
200
+ files = gr.File(label="決算書PDF(複数可)", file_count="multiple", type="filepath")
201
+ run_btn = gr.Button("📄 PDFを解析してテンプレに反映", variant="primary")
202
+ recalc_btn = gr.Button("🔁 この表の値で再計算")
203
+ gr.Markdown("※ 画像化やVisionに失敗した場合はテキスト抽出に自動フォールバックします。")
204
+
205
+ with gr.Column(scale=1):
206
+ fin_json = gr.Code(label="抽出JSON(編集不可)", language="json", interactive=False)
207
+
208
+ with gr.Tabs():
209
+ with gr.Tab("抽出結果(表で編集可)"):
210
+ df_out = gr.Dataframe(headers=["category", "item", "value"], interactive=True, wrap=True)
211
+ with gr.Tab("スコアリング(内部ルール)"):
212
+ score_json = gr.Code(label="スコア(JSON)", language="json")
213
+ chart = gr.Plot(label="スコアレーダー")
214
+ with gr.Tab("AI診断(中立・日本語)"):
215
+ insight_md = gr.Markdown()
216
+ with gr.Tab("外部評価(定量化)"):
217
+ ext_json = gr.Code(label="外部評価JSON", language="json")
218
+ with gr.Tab("抽出ログ/デバッグ"):
219
+ debug_out = gr.Code(label="ログ", language="text")
220
+
221
+ run_btn.click(
222
+ run_analyze,
223
+ inputs=[company, use_vision, files, force_ocr],
224
+ outputs=[fin_json, df_out, score_json, chart, insight_md, ext_json, debug_out],
225
+ concurrency_limit=1
226
+ )
227
+ recalc_btn.click(
228
+ run_recalc,
229
+ inputs=[df_out],
230
+ outputs=[score_json, chart, fin_json],
231
+ concurrency_limit=1
232
+ )
233
+
234
+ return demo