Update ui/ui_app.py
Browse files- ui/ui_app.py +74 -32
ui/ui_app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
-
import json, traceback
|
| 3 |
from typing import Any, Dict, List
|
| 4 |
import gradio as gr
|
| 5 |
import pandas as pd
|
|
@@ -8,8 +8,11 @@ import plotly.graph_objects as go
|
|
| 8 |
from core.pdf_io import pdf_to_images, pdf_to_text
|
| 9 |
from core.extract import extract_financials
|
| 10 |
from core.scoring import score_company
|
|
|
|
|
|
|
| 11 |
from core.openai_client import VISION_MODEL, TEXT_MODEL, get_client
|
| 12 |
|
|
|
|
| 13 |
def fin_to_df(fin: Dict[str, Any]) -> pd.DataFrame:
|
| 14 |
rows = []
|
| 15 |
def add(cat, d):
|
|
@@ -56,50 +59,64 @@ def health() -> str:
|
|
| 56 |
msgs.append(f"ℹ️ Vision={VISION_MODEL} / Text={TEXT_MODEL}")
|
| 57 |
return "<br>".join(msgs)
|
| 58 |
|
| 59 |
-
|
|
|
|
| 60 |
if not files:
|
| 61 |
raise gr.Error("PDF をアップロードしてください。")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
try:
|
| 63 |
imgs: List[bytes] = []
|
| 64 |
for p in files:
|
| 65 |
imgs += pdf_to_images(p, dpi=200, max_pages=6)
|
| 66 |
-
|
| 67 |
except Exception:
|
| 68 |
-
# 画像化やVisionがNGなら素早くテキスト抽出にフォールバック
|
| 69 |
text_blob = ""
|
| 70 |
for p in files:
|
| 71 |
text_blob += pdf_to_text(p) + "\n\n"
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
|
|
|
| 76 |
fig = radar(score)
|
| 77 |
|
| 78 |
-
# AI所見(
|
| 79 |
try:
|
| 80 |
client = get_client()
|
| 81 |
-
prompt = f"""
|
| 82 |
-
-
|
| 83 |
-
-
|
| 84 |
-
- 総評(100字以内)
|
| 85 |
|
| 86 |
-
[財務データ]
|
| 87 |
-
{json.dumps(
|
| 88 |
|
| 89 |
-
[スコア]
|
| 90 |
{json.dumps(score, ensure_ascii=False)}
|
| 91 |
"""
|
| 92 |
resp = client.chat.completions.create(
|
| 93 |
model=TEXT_MODEL,
|
| 94 |
-
messages=[{"role":
|
| 95 |
-
{"role":
|
| 96 |
-
temperature=0.
|
| 97 |
)
|
| 98 |
insight = resp.choices[0].message.content
|
| 99 |
except Exception as e:
|
| 100 |
insight = f"AI所見の生成に失敗: {e}"
|
| 101 |
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
| 103 |
df,
|
| 104 |
json.dumps(score, ensure_ascii=False, indent=2),
|
| 105 |
fig,
|
|
@@ -107,7 +124,7 @@ def run_analyze(company: str, use_vision: bool, files: list[str]):
|
|
| 107 |
|
| 108 |
def run_recalc(df: pd.DataFrame):
|
| 109 |
try:
|
| 110 |
-
fin = df_to_fin(df)
|
| 111 |
score = score_company(fin)
|
| 112 |
fig = radar(score)
|
| 113 |
return (json.dumps(score, ensure_ascii=False, indent=2),
|
|
@@ -117,6 +134,17 @@ def run_recalc(df: pd.DataFrame):
|
|
| 117 |
tb = traceback.format_exc(limit=6)
|
| 118 |
raise gr.Error(f"再計算に失敗しました: {e}\n\n<pre style='white-space:pre-wrap'>{tb}</pre>")
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
def build_ui() -> gr.Blocks:
|
| 121 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"),
|
| 122 |
fill_height=True, analytics_enabled=False) as demo:
|
|
@@ -125,31 +153,45 @@ def build_ui() -> gr.Blocks:
|
|
| 125 |
with gr.Column(scale=1):
|
| 126 |
company = gr.Textbox(label="企業名(任意)", placeholder="例:株式会社OO")
|
| 127 |
use_vision = gr.Checkbox(value=True, label="OpenAIでPDFをAI解析(Vision)")
|
|
|
|
|
|
|
| 128 |
files = gr.File(label="決算書PDF(複数可)", file_count="multiple", type="filepath")
|
| 129 |
-
run_btn = gr.Button("📄
|
| 130 |
-
recalc_btn = gr.Button("🔁
|
| 131 |
health_btn = gr.Button("🩺 環境チェック")
|
| 132 |
health_out = gr.HTML()
|
| 133 |
-
gr.Markdown("※ 画像化やVisionに失敗した場合は、テキスト抽出に自動フォールバックします。")
|
| 134 |
|
| 135 |
with gr.Column(scale=1):
|
| 136 |
-
|
|
|
|
| 137 |
|
| 138 |
with gr.Tabs():
|
| 139 |
-
with gr.Tab("抽出結果(表で編集可)"):
|
|
|
|
| 140 |
df_out = gr.Dataframe(headers=["category", "item", "value"], interactive=True, wrap=True)
|
| 141 |
-
with gr.Tab("スコアリング"):
|
| 142 |
score_json = gr.Code(label="スコア(JSON)", language="json")
|
| 143 |
chart = gr.Plot(label="スコアレーダー")
|
| 144 |
-
with gr.Tab("AI
|
| 145 |
insight_md = gr.Markdown()
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
concurrency_limit=1)
|
| 151 |
-
|
|
|
|
| 152 |
concurrency_limit=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
health_btn.click(health, outputs=health_out, concurrency_limit=1)
|
| 154 |
|
| 155 |
return demo
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
+
import json, traceback, base64
|
| 3 |
from typing import Any, Dict, List
|
| 4 |
import gradio as gr
|
| 5 |
import pandas as pd
|
|
|
|
| 8 |
from core.pdf_io import pdf_to_images, pdf_to_text
|
| 9 |
from core.extract import extract_financials
|
| 10 |
from core.scoring import score_company
|
| 11 |
+
from core.external_score import get_external_template_df, fill_missing_with_external, score_external_from_df
|
| 12 |
+
from core.units import detect_unit, unit_factor, scale_financials_yen
|
| 13 |
from core.openai_client import VISION_MODEL, TEXT_MODEL, get_client
|
| 14 |
|
| 15 |
+
# ===== helpers =====
|
| 16 |
def fin_to_df(fin: Dict[str, Any]) -> pd.DataFrame:
|
| 17 |
rows = []
|
| 18 |
def add(cat, d):
|
|
|
|
| 59 |
msgs.append(f"ℹ️ Vision={VISION_MODEL} / Text={TEXT_MODEL}")
|
| 60 |
return "<br>".join(msgs)
|
| 61 |
|
| 62 |
+
# ===== main actions =====
|
| 63 |
+
def run_analyze(company: str, use_vision: bool, unit_sel: str, files: list[str]):
|
| 64 |
if not files:
|
| 65 |
raise gr.Error("PDF をアップロードしてください。")
|
| 66 |
+
|
| 67 |
+
# 1) 単位の自動推定(先頭数ページのテキスト)
|
| 68 |
+
first_text = pdf_to_text(files[0], pages=2)
|
| 69 |
+
detected = detect_unit(first_text) or "円"
|
| 70 |
+
unit_label = unit_sel if unit_sel != "自動推定" else detected
|
| 71 |
+
factor = unit_factor(unit_label)
|
| 72 |
+
|
| 73 |
+
# 2) Vision(失敗時はテキストモデル)で抽出
|
| 74 |
try:
|
| 75 |
imgs: List[bytes] = []
|
| 76 |
for p in files:
|
| 77 |
imgs += pdf_to_images(p, dpi=200, max_pages=6)
|
| 78 |
+
fin_raw = extract_financials(imgs if use_vision else None, None, company or "")
|
| 79 |
except Exception:
|
|
|
|
| 80 |
text_blob = ""
|
| 81 |
for p in files:
|
| 82 |
text_blob += pdf_to_text(p) + "\n\n"
|
| 83 |
+
fin_raw = extract_financials(None, text_blob, company or "")
|
| 84 |
+
|
| 85 |
+
# 3) 円換算
|
| 86 |
+
fin_yen = scale_financials_yen(fin_raw, factor=factor)
|
| 87 |
|
| 88 |
+
# 4) 内部スコア
|
| 89 |
+
df = fin_to_df(fin_yen)
|
| 90 |
+
score = score_company(fin_yen)
|
| 91 |
fig = radar(score)
|
| 92 |
|
| 93 |
+
# 5) AI所見(中立性を強化)
|
| 94 |
try:
|
| 95 |
client = get_client()
|
| 96 |
+
prompt = f"""あなたは独立の財務アナリストです。主観や推測を避け、事実と比率を根拠に短くコメントしてください。
|
| 97 |
+
- 書き方: 箇条書き、断定的表現・煽り表現は禁止。将来予測はしない。
|
| 98 |
+
- 必ず根拠(指標名と値)を各行に併記する。
|
|
|
|
| 99 |
|
| 100 |
+
[財務データ(円換算)]
|
| 101 |
+
{json.dumps(fin_yen, ensure_ascii=False)}
|
| 102 |
|
| 103 |
+
[社内スコア]
|
| 104 |
{json.dumps(score, ensure_ascii=False)}
|
| 105 |
"""
|
| 106 |
resp = client.chat.completions.create(
|
| 107 |
model=TEXT_MODEL,
|
| 108 |
+
messages=[{"role":"system","content":"中立・簡潔・根拠明示。"},
|
| 109 |
+
{"role":"user","content": prompt}],
|
| 110 |
+
temperature=0.2,
|
| 111 |
)
|
| 112 |
insight = resp.choices[0].message.content
|
| 113 |
except Exception as e:
|
| 114 |
insight = f"AI所見の生成に失敗: {e}"
|
| 115 |
|
| 116 |
+
unit_info = f"PDF表記の単位: <b>{detected}</b> / 適用単位: <b>{unit_label}</b>(円換算係数={factor:g})"
|
| 117 |
+
return (unit_info,
|
| 118 |
+
json.dumps(fin_raw, ensure_ascii=False, indent=2), # 参照用(換算前)
|
| 119 |
+
json.dumps(fin_yen, ensure_ascii=False, indent=2), # 実計算に使用
|
| 120 |
df,
|
| 121 |
json.dumps(score, ensure_ascii=False, indent=2),
|
| 122 |
fig,
|
|
|
|
| 124 |
|
| 125 |
def run_recalc(df: pd.DataFrame):
|
| 126 |
try:
|
| 127 |
+
fin = df_to_fin(df) # ここは既に円換算された表が編集される想定
|
| 128 |
score = score_company(fin)
|
| 129 |
fig = radar(score)
|
| 130 |
return (json.dumps(score, ensure_ascii=False, indent=2),
|
|
|
|
| 134 |
tb = traceback.format_exc(limit=6)
|
| 135 |
raise gr.Error(f"再計算に失敗しました: {e}\n\n<pre style='white-space:pre-wrap'>{tb}</pre>")
|
| 136 |
|
| 137 |
+
# ===== 外部評価 =====
|
| 138 |
+
def open_external_template():
|
| 139 |
+
df = get_external_template_df()
|
| 140 |
+
df = fill_missing_with_external(df)
|
| 141 |
+
return df
|
| 142 |
+
|
| 143 |
+
def calc_external(df_ext: pd.DataFrame):
|
| 144 |
+
res = score_external_from_df(df_ext)
|
| 145 |
+
return json.dumps(res, ensure_ascii=False, indent=2)
|
| 146 |
+
|
| 147 |
+
# ===== UI =====
|
| 148 |
def build_ui() -> gr.Blocks:
|
| 149 |
with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo"),
|
| 150 |
fill_height=True, analytics_enabled=False) as demo:
|
|
|
|
| 153 |
with gr.Column(scale=1):
|
| 154 |
company = gr.Textbox(label="企業名(任意)", placeholder="例:株式会社OO")
|
| 155 |
use_vision = gr.Checkbox(value=True, label="OpenAIでPDFをAI解析(Vision)")
|
| 156 |
+
unit_sel = gr.Dropdown(choices=["自動推定","円","千円","百万円","千万円","億円"],
|
| 157 |
+
value="自動推定", label="金額単位(PDF記載)")
|
| 158 |
files = gr.File(label="決算書PDF(複数可)", file_count="multiple", type="filepath")
|
| 159 |
+
run_btn = gr.Button("📄 解析して反映", variant="primary")
|
| 160 |
+
recalc_btn = gr.Button("🔁 表の値で再計算")
|
| 161 |
health_btn = gr.Button("🩺 環境チェック")
|
| 162 |
health_out = gr.HTML()
|
|
|
|
| 163 |
|
| 164 |
with gr.Column(scale=1):
|
| 165 |
+
unit_html = gr.HTML(label="単位情報")
|
| 166 |
+
fin_json_raw = gr.Code(label="抽出JSON(換算前)", language="json", interactive=False)
|
| 167 |
|
| 168 |
with gr.Tabs():
|
| 169 |
+
with gr.Tab("抽出結果(円換算・表で編集可)"):
|
| 170 |
+
fin_json_yen = gr.Code(label="抽出JSON(円換算)", language="json")
|
| 171 |
df_out = gr.Dataframe(headers=["category", "item", "value"], interactive=True, wrap=True)
|
| 172 |
+
with gr.Tab("スコアリング(社内ルール)"):
|
| 173 |
score_json = gr.Code(label="スコア(JSON)", language="json")
|
| 174 |
chart = gr.Plot(label="スコアレーダー")
|
| 175 |
+
with gr.Tab("AI所見(中立)"):
|
| 176 |
insight_md = gr.Markdown()
|
| 177 |
+
with gr.Tab("外部評価(テンプレ&採点)"):
|
| 178 |
+
with gr.Row():
|
| 179 |
+
open_t = gr.Button("📋 テンプレを開く")
|
| 180 |
+
calc_t = gr.Button("🧮 外部スコア計算")
|
| 181 |
+
df_ext = gr.Dataframe(headers=["カテゴリー","入力項目","値"], interactive=True, wrap=True)
|
| 182 |
+
ext_json = gr.Code(label="外部評価(JSON)", language="json")
|
| 183 |
+
|
| 184 |
+
run_btn.click(run_analyze,
|
| 185 |
+
inputs=[company, use_vision, unit_sel, files],
|
| 186 |
+
outputs=[unit_html, fin_json_raw, fin_json_yen, df_out, score_json, chart, insight_md],
|
| 187 |
concurrency_limit=1)
|
| 188 |
+
|
| 189 |
+
recalc_btn.click(run_recalc, inputs=[df_out], outputs=[score_json, chart, fin_json_yen],
|
| 190 |
concurrency_limit=1)
|
| 191 |
+
|
| 192 |
+
open_t.click(open_external_template, outputs=[df_ext], concurrency_limit=1)
|
| 193 |
+
calc_t.click(calc_external, inputs=[df_ext], outputs=[ext_json], concurrency_limit=1)
|
| 194 |
+
|
| 195 |
health_btn.click(health, outputs=health_out, concurrency_limit=1)
|
| 196 |
|
| 197 |
return demo
|