Spaces:
Sleeping

Corin1998 commited on
Commit
46bb2b4
·
verified ·
1 Parent(s): 91c5ba5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +229 -215
app.py CHANGED
@@ -1,244 +1,258 @@
1
- import base64
 
 
2
  import io
 
3
  import json
4
- import logging
5
- import os
6
- import traceback
7
- from typing import List, Optional, Tuple
8
 
9
  import gradio as gr
10
- import pdfplumber
11
- import pytesseract
12
- from pdf2image import convert_from_bytes
13
- from PIL import Image
14
  from openai import OpenAI
 
15
 
16
- # ===== ログ =====
17
- logging.basicConfig(
18
- level=logging.INFO,
19
- format="%(asctime)s [%(levelname)s] %(message)s",
20
- )
21
- logger = logging.getLogger("app")
22
-
23
- # ===== OpenAI クライアント(遅延生成+互換チェック)=====
24
- _client: Optional[OpenAI] = None
25
-
26
- def get_openai_client() -> OpenAI:
27
- api_key = os.getenv("OPENAI_API_KEY")
28
- if not api_key:
29
- raise RuntimeError("OPENAI_API_KEY が未設定です(Spaces → Settings → Variables で設定)")
30
- global _client
31
- if _client is None:
32
- try:
33
- _client = OpenAI(api_key=api_key, timeout=60) # httpx==0.27系で安定
34
- except TypeError as e:
35
- # httpx 0.28 と SDK の非互換時はここに来る
36
- raise RuntimeError(
37
- "OpenAI SDK と httpx の互換性エラー。requirements.txt を "
38
- "`httpx==0.27.2` / `httpcore==1.0.5` に固定してください。"
39
- ) from e
40
- return _client
41
-
42
- # ===== PDF ユーティリティ =====
43
- def pdf_bytes_to_images(
44
- pdf_bytes: bytes, dpi: int = 200, max_pages: int = 8
45
- ) -> List[Image.Image]:
46
- """
47
- PDF を PIL.Image の配列に変換(先頭 max_pages ページまで)
48
- """
49
- images: List[Image.Image] = convert_from_bytes(
50
- pdf_bytes,
51
- dpi=dpi,
52
- fmt="png",
53
- first_page=1,
54
- last_page=None, # すべて → 後でスライス
55
- use_pdftocairo=True,
56
- )
57
- return images[:max_pages]
58
 
59
- def images_to_b64(images: List[Image.Image]) -> List[str]:
60
- out: List[str] = []
61
- for im in images:
 
 
 
 
62
  buf = io.BytesIO()
63
- im.save(buf, format="PNG")
64
- out.append(base64.b64encode(buf.getvalue()).decode("utf-8"))
65
  return out
66
 
67
- def extract_text_locally(pdf_bytes: bytes, do_ocr: bool) -> str:
68
- """
69
- ローカル抽出(pdfplumber → テキスト)。必要なら OCR も併用。
70
- """
71
- texts: List[str] = []
72
 
73
- # 1) PDF埋め込みテキスト
74
- try:
75
- with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:
76
- for i, page in enumerate(pdf.pages[:8]):
77
- t = page.extract_text() or ""
78
- if t.strip():
79
- texts.append(t)
80
- except Exception as e:
81
- logger.warning("pdfplumber でのテキスト抽出に失敗: %s", e)
82
 
83
- # 2) OCR(指定時)
84
- if do_ocr:
85
- try:
86
- imgs = pdf_bytes_to_images(pdf_bytes, dpi=250, max_pages=6)
87
- ocr_texts = []
88
- for im in imgs:
89
- # 日本語+英語(packages.txt で tesseract-ocr-jpn を入れている)
90
- ocr_texts.append(pytesseract.image_to_string(im, lang="jpn+eng"))
91
- if ocr_texts:
92
- texts.append("\n\n".join(ocr_texts))
93
- except Exception as e:
94
- logger.warning("OCR に失敗: %s", e)
95
-
96
- return "\n\n".join(texts).strip()
97
-
98
- # ===== OpenAI Vision =====
99
- def analyze_with_openai_vision(
100
- images_b64: List[str], company_name: str, local_text_hint: str = ""
101
- ) -> Tuple[str, dict]:
102
- """
103
- 画像(base64)とテキストヒント(任意)を GPT-4o-mini に投げて構造化 JSON を返す。
104
- """
105
- if not images_b64:
106
- raise RuntimeError("入力画像がありません(PDFのページが0枚でした)")
107
-
108
- client = get_openai_client()
109
- model = os.getenv("OPENAI_VISION_MODEL", "gpt-4o-mini")
110
-
111
- # 画像 + テキストヒント
112
- user_content = []
113
- instruction = (
114
- "以下は日本語の決算書(BS/PL など)の画像で��。"
115
- "主要な財務項目(売上高、営業利益、経常利益、当期純利益、総資産、自己資本、"
116
- "ROE/ROA、営業CF/投資CF/財務CF など)を抽出し、"
117
- "JSON で返してください。単位は分かる限り数値化(千円/百万円 等の倍率も反映)し、"
118
- "不明な値は null。必ず JSON のみを返すこと。"
119
- )
120
- if company_name.strip():
121
- instruction += f"\n会社名: {company_name.strip()}"
122
- if local_text_hint.strip():
123
- instruction += f"\n補助テキスト(OCR/埋め込み抽出):\n{local_text_hint[:4000]}"
124
 
125
- user_content.append({"type": "text", "text": instruction})
126
- for b64 in images_b64:
127
- user_content.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}})
 
 
 
 
 
 
128
 
129
  resp = client.chat.completions.create(
130
- model=model,
131
- temperature=0.0,
132
  messages=[
133
- {"role": "system", "content": "You are a meticulous financial analyst. Output JSON only."},
134
- {"role": "user", "content": user_content},
135
  ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  )
137
- text = (resp.choices[0].message.content or "").strip()
138
-
139
- # JSONパース(コードフェンス/余白除去)
140
- def try_parse(s: str) -> dict:
141
- s = s.strip()
142
- if s.startswith("```"):
143
- s = s.split("```")[1] if "```" in s else s
144
- # 先頭に json 指定があるケース
145
- s = s.replace("json\n", "").replace("Json\n", "").replace("JSON\n", "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  try:
147
- return json.loads(s)
 
 
 
148
  except Exception:
149
- # 先頭/末尾の余��な文を削るラフなリカバリ
150
- left = s.find("{")
151
- right = s.rfind("}")
152
- if left != -1 and right != -1:
153
- return json.loads(s[left : right + 1])
154
- raise
155
-
156
- data = try_parse(text)
157
- pretty = json.dumps(data, ensure_ascii=False, indent=2)
158
- return pretty, data
159
-
160
- # ===== UI コールバック =====
161
- def on_parse(
162
- company_name: str,
163
- use_openai: bool,
164
- files: List[bytes],
165
- force_ocr: bool,
166
- ) -> Tuple[str, str]:
167
- """
168
- 返り値: (右上のMarkdown, 右下のMarkdown)
169
- """
 
 
 
 
170
  try:
171
- if not files:
172
- return "⚠️ PDF が選択されていません。", ""
173
-
174
- # 複数PDF -> 画像連結(上限ページあり)
175
- all_images: List[Image.Image] = []
176
- texts_hint: List[str] = []
177
-
178
- for idx, pdf_bytes in enumerate(files):
179
- # ローカルテキスト抽出(pdfplumber + 任意OCR)
180
- texts_hint.append(extract_text_locally(pdf_bytes, do_ocr=force_ocr))
181
-
182
- # 画像化
183
- imgs = pdf_bytes_to_images(pdf_bytes, dpi=220, max_pages=6)
184
- all_images.extend(imgs)
185
-
186
- images_b64 = images_to_b64(all_images)
187
- logger.info("Pages prepared: %d", len(images_b64))
188
-
189
- # 解析
190
- if use_openai:
191
- pretty_json, data = analyze_with_openai_vision(
192
- images_b64, company_name, "\n\n".join(texts_hint)
193
- )
194
- return f"✅ 解析成功\n\n```json\n{pretty_json}\n```", "詳細JSONは上段をご確認ください。"
195
  else:
196
- # ローカルのみ(簡易):抽出テキストをそのまま表示
197
- merged_text = "\n\n---\n\n".join(texts_hint).strip()
198
- if not merged_text:
199
- merged_text = "(ローカル抽出結果は空でした)"
200
- return "⚙️ ローカル抽出のみ(OpenAI未使用)", f"```\n{merged_text[:8000]}\n```"
 
 
 
 
201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  except Exception as e:
203
- tb = traceback.format_exc()
204
- logger.exception("解析に失敗: %s", e)
205
- msg_top = (
206
- "❌ 解析に失敗しました。\n\n"
207
- f"**Error:** `{type(e).__name__}: {e}`\n\n"
208
- "<details><summary>Traceback</summary>\n\n"
209
- f"```\n{tb}\n```\n"
210
- "</details>"
211
- )
212
- return msg_top, "右下は空です。"
213
-
214
- # ===== Gradio UI =====
215
- with gr.Blocks(css="""
216
- :root { --radius-lg: 12px; }
217
- #top { max-width: 1100px; margin: 0 auto; }
218
- """, fill_height=True) as demo:
219
- gr.Markdown("## 🧮 企業スコアリング(PDF解析 × OpenAI Vision)", elem_id="top")
220
  with gr.Row():
221
- with gr.Column(scale=7):
222
  company = gr.Textbox(label="企業名(任意)", placeholder="例:株式会社OO")
223
- use_openai = gr.Checkbox(label="OpenAIでPDFをAI解析(Vision)", value=True)
224
- files = gr.File(label="決算書PDF(複数可)", file_count="multiple", type="binary")
225
- force_ocr = gr.Checkbox(label="OCRを強制(スキャンPDF向け/やや遅い)", value=False)
226
- btn = gr.Button("🧩 PDFを解析してテンプレに反映", variant="primary")
227
- note = gr.Markdown("※ PDF→画像→OpenAI Vision(gpt-4o-mini)で主要数値を抽出します。")
228
-
229
- with gr.Column(scale=5):
230
- out_top = gr.Markdown("(ここに解析結果やJSONが表示されます)")
231
- out_bottom = gr.Markdown("(ログ/補助情報)")
232
-
233
- btn.click(
234
- fn=on_parse,
235
- inputs=[company, use_openai, files, force_ocr],
236
- outputs=[out_top, out_bottom],
237
- show_api=False,
238
- concurrency_limit=1,
239
- api_name="parse",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  )
241
 
242
  if __name__ == "__main__":
243
- # Spaces では不要だがローカル動作用
244
- demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)
 
1
+ # app.py
2
+ from __future__ import annotations
3
+ import os
4
  import io
5
+ import base64
6
  import json
7
+ from typing import List, Dict, Any, Tuple
 
 
 
8
 
9
  import gradio as gr
10
+ import pandas as pd
11
+ from pdf2image import convert_from_path
 
 
12
  from openai import OpenAI
13
+ import plotly.graph_objects as go
14
 
15
+ from scorer import score_company
16
+
17
+ OPENAI_MODEL_VISION = os.environ.get("OPENAI_VISION_MODEL", "gpt-4o-mini")
18
+ OPENAI_MODEL_TEXT = os.environ.get("OPENAI_TEXT_MODEL", "gpt-4o-mini")
19
+
20
+ # OpenAI クライアント(proxies 等は渡さない)
21
+ client = OpenAI()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # ---------- PDF → images ----------
24
+ def pdf_to_images(pdf_path: str, dpi: int = 220, max_pages: int = 8) -> List[bytes]:
25
+ pages = convert_from_path(pdf_path, dpi=dpi, fmt="png")
26
+ out = []
27
+ for i, p in enumerate(pages):
28
+ if i >= max_pages:
29
+ break
30
  buf = io.BytesIO()
31
+ p.save(buf, format="PNG")
32
+ out.append(buf.getvalue())
33
  return out
34
 
35
+ def b64(img_bytes: bytes) -> str:
36
+ return base64.b64encode(img_bytes).decode("utf-8")
 
 
 
37
 
38
+ # ---------- Vision 抽出 ----------
39
+ SYSTEM_JSON = """あなたは有能な財務アナリストです。
40
+ 与えられた決算書画像から、次の厳密な JSON 構造のみを日本語の単位を付けずに返してください。
41
+ 数値は半角数値、分からない項目は null。
 
 
 
 
 
42
 
43
+ {
44
+ "company": {"name": null},
45
+ "period": {"start_date": null, "end_date": null},
46
+ "balance_sheet": {
47
+ "total_assets": null, "total_liabilities": null, "total_equity": null,
48
+ "current_assets": null, "fixed_assets": null,
49
+ "current_liabilities": null, "long_term_liabilities": null
50
+ },
51
+ "income_statement": {
52
+ "sales": null, "cost_of_sales": null, "gross_profit": null,
53
+ "operating_expenses": null, "operating_income": null,
54
+ "ordinary_income": null, "net_income": null
55
+ },
56
+ "cash_flows": {
57
+ "operating_cash_flow": null, "investing_cash_flow": null, "financing_cash_flow": null
58
+ }
59
+ }
60
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ def extract_with_vision(image_bytes_list: List[bytes], company_hint: str = "") -> Dict[str, Any]:
63
+ content = [{"type": "text", "text": SYSTEM_JSON}]
64
+ if company_hint:
65
+ content.append({"type": "text", "text": f"会社名の候補: {company_hint}"})
66
+ for img in image_bytes_list:
67
+ content.append({
68
+ "type": "input_image",
69
+ "image_url": f"data:image/png;base64,{b64(img)}"
70
+ })
71
 
72
  resp = client.chat.completions.create(
73
+ model=OPENAI_MODEL_VISION,
 
74
  messages=[
75
+ {"role": "system", "content": "返答は必ず有効な JSON オブジェクトのみ。説明文は出力しない。"},
76
+ {"role": "user", "content": content}
77
  ],
78
+ response_format={"type": "json_object"},
79
+ temperature=0.1,
80
+ )
81
+ js = resp.choices[0].message.content
82
+ data = json.loads(js)
83
+ return data
84
+
85
+ # ---------- AI 診断 ----------
86
+ def ai_diagnosis(fin: Dict[str, Any], score: Dict[str, Any]) -> str:
87
+ prompt = f"""
88
+ 以下は企業の主要財務データとスコアリング結果です。日本語で、要点を簡潔に「3つの良い点」「3つの懸念点」「総評(100〜150字)」「改善アクション(箇条書き3つ)」を出力してください。
89
+ - 数値は可能なら%や倍数で示す
90
+ - 過度な断定は避ける
91
+ - JSON ではなく Markdown 箇条書きで返す
92
+
93
+ [財務データ(JSON)]:
94
+ {json.dumps(fin, ensure_ascii=False)}
95
+
96
+ [スコア]:
97
+ 総合スコア={score.get('total_score')} / グレード={score.get('grade')}
98
+ 詳細={json.dumps(score.get('details', []), ensure_ascii=False)}
99
+ """
100
+ resp = client.chat.completions.create(
101
+ model=OPENAI_MODEL_TEXT,
102
+ messages=[{"role": "system", "content": "公平で実務的な財務アナリストとして日本語で回答。"},
103
+ {"role": "user", "content": prompt}],
104
+ temperature=0.3,
105
  )
106
+ return resp.choices[0].message.content
107
+
108
+ # ---------- DataFrame <-> dict ----------
109
+ def fin_to_df(fin: Dict[str, Any]) -> pd.DataFrame:
110
+ rows = []
111
+ def add(block: str, d: Dict[str, Any]):
112
+ for k, v in (d or {}).items():
113
+ rows.append({"category": block, "item": k, "value": v})
114
+ add("balance_sheet", fin.get("balance_sheet"))
115
+ add("income_statement", fin.get("income_statement"))
116
+ add("cash_flows", fin.get("cash_flows"))
117
+ return pd.DataFrame(rows, columns=["category", "item", "value"])
118
+
119
+ def df_to_fin(df: pd.DataFrame) -> Dict[str, Any]:
120
+ df = df.copy()
121
+ out = {
122
+ "balance_sheet": {},
123
+ "income_statement": {},
124
+ "cash_flows": {}
125
+ }
126
+ for _, r in df.iterrows():
127
+ cat = str(r["category"])
128
+ item = str(r["item"])
129
+ val = r["value"]
130
  try:
131
+ if val is None or val == "":
132
+ parsed = None
133
+ else:
134
+ parsed = float(val)
135
  except Exception:
136
+ parsed = None
137
+ if cat in out:
138
+ out[cat][item] = parsed
139
+ return out
140
+
141
+ # ---------- プロット ----------
142
+ def radar_from_score(score: Dict[str, Any]) -> go.Figure:
143
+ labels = [r["metric"] for r in score["details"]]
144
+ values = [r["score"] for r in score["details"]]
145
+ fig = go.Figure()
146
+ fig.add_trace(go.Scatterpolar(r=values + values[:1], theta=labels + labels[:1], fill='toself', name='スコア'))
147
+ fig.update_layout(
148
+ polar=dict(radialaxis=dict(visible=True, range=[0, 100])),
149
+ showlegend=False,
150
+ margin=dict(l=20, r=20, t=30, b=20),
151
+ height=380,
152
+ title=f"総合スコア: {score['total_score']}(グレード: {score['grade']})"
153
+ )
154
+ return fig
155
+
156
+ # ---------- Gradio コールバック ----------
157
+ def analyze(company: str, use_vision: bool, files: List[str]) -> Tuple[str, pd.DataFrame, str, go.Figure, str]:
158
+ if not files:
159
+ raise gr.Error("PDF をアップロードしてください。")
160
+
161
  try:
162
+ # とりあえず最初のPDFだけ、必要なら複数→先頭8ページまで集約
163
+ imgs: List[bytes] = []
164
+ for path in files:
165
+ imgs.extend(pdf_to_images(path, dpi=220, max_pages=6))
166
+ if use_vision:
167
+ fin_all = extract_with_vision(imgs, company_hint=company or "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  else:
169
+ # 何も選ばれていない場合の簡易ダミー(Vision 利用が推奨)
170
+ fin_all = {
171
+ "company": {"name": company or None},
172
+ "period": {"start_date": None, "end_date": None},
173
+ "balance_sheet": {}, "income_statement": {}, "cash_flows": {}
174
+ }
175
+
176
+ # 表に反映
177
+ df = fin_to_df(fin_all)
178
 
179
+ # スコア
180
+ score = score_company(fin_all)
181
+ fig = radar_from_score(score)
182
+
183
+ # 右上の JSON 表示
184
+ fin_json = json.dumps(fin_all, ensure_ascii=False, indent=2)
185
+
186
+ # AI 所見
187
+ insight = ai_diagnosis(fin_all, score)
188
+
189
+ return fin_json, df, json.dumps(score, ensure_ascii=False, indent=2), fig, insight
190
+
191
+ except gr.Error:
192
+ raise
193
  except Exception as e:
194
+ raise gr.Error(f"解析に失敗しました: {e}")
195
+
196
+ def recalc(df: pd.DataFrame) -> Tuple[str, go.Figure, str]:
197
+ fin = df_to_fin(df)
198
+ score = score_company(fin)
199
+ fig = radar_from_score(score)
200
+ return json.dumps(score, ensure_ascii=False, indent=2), fig, json.dumps(fin, ensure_ascii=False, indent=2)
201
+
202
+ # ---------- UI ----------
203
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"), fill_height=True) as demo:
204
+ gr.Markdown("## 🧮 企業スコアリング(PDF解析 × OpenAI Vision)")
 
 
 
 
 
 
205
  with gr.Row():
206
+ with gr.Column(scale=1):
207
  company = gr.Textbox(label="企業名(任意)", placeholder="例:株式会社OO")
208
+ use_vision = gr.Checkbox(value=True, label="OpenAIでPDFをAI解析(Vision)")
209
+ files = gr.File(label="決算書PDF(複数可)", file_count="multiple", type="filepath")
210
+ run_btn = gr.Button("📄 PDFを解析してテンプレに反映", variant="primary")
211
+ recalc_btn = gr.Button("🔁 この表の値で再計算")
212
+
213
+ gr.Markdown("※ PDF→画像→OpenAI Vision で主要数値を抽出します。")
214
+
215
+ with gr.Column(scale=1):
216
+ status = gr.HTML("<span style='color:green;font-weight:bold'>✔ 解析結果</span>")
217
+ fin_json = gr.Code(label="抽出JSON", language="json")
218
+
219
+ with gr.Tabs():
220
+ with gr.Tab("抽出結果(表で編集可)"):
221
+ df_out = gr.Dataframe(headers=["category", "item", "value"], interactive=True, wrap=True)
222
+
223
+ with gr.Tab("スコアリング"):
224
+ score_json = gr.Code(label="スコア(JSON)", language="json")
225
+ chart = gr.Plot(label="スコアレーダー")
226
+
227
+ with gr.Tab("AI診断(日本語)"):
228
+ insight_md = gr.Markdown()
229
+
230
+ with gr.Tab("ダウンロード"):
231
+ # JSON/CSVの簡易ダウンロード
232
+ export_fin = gr.JSON(label="財務データ(JSON)プレビュー")
233
+ export_score = gr.JSON(label="スコア(JSON)プレビュー")
234
+ def _dl_fin(fin_text):
235
+ try: return json.loads(fin_text)
236
+ except: return {}
237
+ def _dl_score(score_text):
238
+ try: return json.loads(score_text)
239
+ except: return {}
240
+ fin_json.change(_dl_fin, fin_json, export_fin, queue=False)
241
+ score_json.change(_dl_score, score_json, export_score, queue=False)
242
+
243
+ # イベント
244
+ run_btn.click(
245
+ analyze,
246
+ inputs=[company, use_vision, files],
247
+ outputs=[fin_json, df_out, score_json, chart, insight_md]
248
+ )
249
+
250
+ recalc_btn.click(
251
+ recalc,
252
+ inputs=[df_out],
253
+ outputs=[score_json, chart, fin_json]
254
  )
255
 
256
  if __name__ == "__main__":
257
+ # Spaces 上では不要だがローカル動作用
258
+ demo.launch(server_name="0.0.0.0", server_port=7860)