Update app.py
Browse files
app.py
CHANGED
|
@@ -1,472 +1,232 @@
|
|
| 1 |
-
|
| 2 |
-
import os, io, re, json, base64, traceback, typing as T
|
| 3 |
-
import numpy as np
|
| 4 |
-
import pandas as pd
|
| 5 |
import gradio as gr
|
| 6 |
-
|
| 7 |
-
# ---------- PDF & OCR ----------
|
| 8 |
-
from pypdf import PdfReader
|
| 9 |
import pdfplumber
|
| 10 |
from pdf2image import convert_from_bytes
|
| 11 |
-
import pytesseract
|
| 12 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
from rapidfuzz import fuzz, process
|
| 16 |
-
|
| 17 |
-
# ---------- Matplotlib(権限エラー対策) ----------
|
| 18 |
-
os.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib")
|
| 19 |
-
import matplotlib
|
| 20 |
-
matplotlib.use("Agg")
|
| 21 |
-
import matplotlib.pyplot as plt
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
("経営者能力", "監査・内部統制の重大な不備 件数(過去3年)"),
|
| 38 |
-
("経営者能力", "重大コンプライアンス件数(過去3年)"),
|
| 39 |
-
("経営者能力", "社外取締役比率(%)"),
|
| 40 |
-
("経営者能力", "代表者の業界経験年数"),
|
| 41 |
-
("経営者能力", "現預金(円)"),
|
| 42 |
-
("経営者能力", "月商(円)"),
|
| 43 |
-
("経営者能力", "担保余力評価額(円)"),
|
| 44 |
-
("経営者能力", "倒産歴の有無(TRUE/FALSE)"),
|
| 45 |
-
("経営者能力", "倒産からの経過年数"),
|
| 46 |
-
("経営者能力", "重大事件・事故件数(過去10年)"),
|
| 47 |
-
("成長率", "売上_期3(最新期)"),
|
| 48 |
-
("成長率", "売上_期2"),
|
| 49 |
-
("成長率", "売上_期1(最古期)"),
|
| 50 |
-
("成長率", "営業利益_期3(最新期)"),
|
| 51 |
-
("成長率", "営業利益_期2"),
|
| 52 |
-
("成長率", "営業利益_期1(最古期)"),
|
| 53 |
-
("成長率", "主力商品数"),
|
| 54 |
-
("成長率", "成長中主力商品数"),
|
| 55 |
-
("安定性", "自己資本比率(%)"),
|
| 56 |
-
("安定性", "利益剰余金(円)"),
|
| 57 |
-
("安定性", "支払遅延件数(直近12ヶ月)"),
|
| 58 |
-
("安定性", "不渡り件数(直近12ヶ月)"),
|
| 59 |
-
("安定性", "平均支払遅延日数"),
|
| 60 |
-
("安定性", "メインバンク明確か(TRUE/FALSE)"),
|
| 61 |
-
("安定性", "借入先数"),
|
| 62 |
-
("安定性", "メインバンク借入シェア(%)"),
|
| 63 |
-
("安定性", "コミットメントライン等の長期与信枠あり(TRUE/FALSE)"),
|
| 64 |
-
("安定性", "担保余力評価額(円)"),
|
| 65 |
-
("安定性", "月商(円)_再掲"),
|
| 66 |
-
("安定性", "主要顧客上位1社売上比率(%)"),
|
| 67 |
-
("安定性", "主要顧客上位3社売上比率(%)"),
|
| 68 |
-
("安定性", "主要顧客の平均信用スコア(0-100)"),
|
| 69 |
-
("安定性", "不良債権件数(直近12ヶ月)"),
|
| 70 |
-
("安定性", "業歴(年)"),
|
| 71 |
-
("公平性・総合世評", "有価証券報告書提出企業か(TRUE/FALSE)"),
|
| 72 |
-
("公平性・総合世評", "決算公告や官報での公開あり(TRUE/FALSE)"),
|
| 73 |
-
("公平性・総合世評", "HP/IRサイトで財務資料公開あり(TRUE/FALSE)"),
|
| 74 |
-
("公平性・総合世評", "直近更新が定め通りか(TRUE/FALSE)"),
|
| 75 |
-
]
|
| 76 |
-
def template_df() -> pd.DataFrame:
|
| 77 |
-
return pd.DataFrame([(c,i,"") for c,i in _TEMPLATE_ROWS], columns=["カテゴリー","入力項目","値"])
|
| 78 |
-
|
| 79 |
-
# ========================= スコア(既存ロジック要約) =========================
|
| 80 |
-
def _clamp(v,a,b): return max(a, min(b, v))
|
| 81 |
-
def _to_float(x):
|
| 82 |
-
if x is None: return None
|
| 83 |
-
try: return float(str(x).replace(",","").replace("▲","-").replace("△","-").replace("%","").strip())
|
| 84 |
-
except: return None
|
| 85 |
-
def _to_bool(x):
|
| 86 |
-
if x is None: return None
|
| 87 |
-
s = str(x).strip().lower()
|
| 88 |
-
if s in ("true","t","1","yes","y","有","あり"): return True
|
| 89 |
-
if s in ("false","f","0","no","n","無","なし"): return False
|
| 90 |
-
return None
|
| 91 |
-
def _ramp(x, good, bad, lo=0.0, hi=10.0, neutral=None):
|
| 92 |
-
if x is None: return neutral if neutral is not None else (lo+hi)/2.0
|
| 93 |
-
if good > bad:
|
| 94 |
-
if x <= bad: return lo
|
| 95 |
-
if x >= good: return hi
|
| 96 |
-
return lo + (hi-lo) * (x-bad)/(good-bad)
|
| 97 |
-
else:
|
| 98 |
-
if x >= bad: return lo
|
| 99 |
-
if x <= good: return hi
|
| 100 |
-
return lo + (hi-lo) * (x-good)/(bad-good)
|
| 101 |
-
|
| 102 |
-
_WEIGHTS = {
|
| 103 |
-
("経営者能力","経営姿勢"):8, ("経営者能力","事業経験"):5, ("経営者能力","資産担保力"):6, ("経営者能力","減点事項"):7,
|
| 104 |
-
("成長率","売上高伸長性"):10, ("成長率","利益伸長性"):10, ("成長率","商品"):6,
|
| 105 |
-
("安定性","自己資本"):8, ("安定性","決済振り"):10, ("安定性","金融取引"):6, ("安定性","資産担保余力"):6,
|
| 106 |
-
("安定性","取引先"):6, ("安定性","業歴"):4,
|
| 107 |
-
("公平性・総合世評","ディスクロージャー"):8
|
| 108 |
-
}
|
| 109 |
-
_WEIGHT_NORM = 100.0 / float(sum(_WEIGHTS.values()))
|
| 110 |
-
|
| 111 |
-
def score_external_from_df(df: pd.DataFrame) -> dict:
|
| 112 |
-
def ref(label: str):
|
| 113 |
-
m = df["入力項目"].eq(label)
|
| 114 |
-
return df.loc[m,"値"].values[0] if m.any() else None
|
| 115 |
-
items=[]
|
| 116 |
-
def add(cat,name,raw,w,reason):
|
| 117 |
-
items.append({
|
| 118 |
-
"category":cat,"name":name,"raw":round(raw,2),
|
| 119 |
-
"weight":round(w*_WEIGHT_NORM,2),
|
| 120 |
-
"score":round((raw/10.0)*w*_WEIGHT_NORM,2),
|
| 121 |
-
"reason":reason
|
| 122 |
-
})
|
| 123 |
-
yoy3=_to_float(ref("予実達成率_3年平均(%)"))
|
| 124 |
-
indep=_to_float(ref("社外取締役比率(%)"))
|
| 125 |
-
expy=_to_float(ref("代表者の業界経験年数"))
|
| 126 |
-
cash=_to_float(ref("現預金(円)"))
|
| 127 |
-
sales_m=_to_float(ref("月商(円)"))
|
| 128 |
-
coll=_to_float(ref("担保余力評価額(円)"))
|
| 129 |
-
equity=_to_float(ref("自己資本比率(%)"))
|
| 130 |
-
delay=_to_float(ref("支払遅延件数(直近12ヶ月)"))
|
| 131 |
-
boun=_to_float(ref("不渡り件数(直近12ヶ月)"))
|
| 132 |
-
delaydays=_to_float(ref("平均支払遅延日数"))
|
| 133 |
-
mainb=_to_bool(ref("メインバンク明確か(TRUE/FALSE)"))
|
| 134 |
-
hasline=_to_bool(ref("コミットメントライン等の長期与信枠あり(TRUE/FALSE)"))
|
| 135 |
-
top1=_to_float(ref("主要顧客上位1社売上比率(%)"))
|
| 136 |
-
cust=_to_float(ref("主要顧客の平均信用スコア(0-100)"))
|
| 137 |
-
npl=_to_float(ref("不良債権件数(直近12ヶ月)"))
|
| 138 |
-
years=_to_float(ref("業歴(年)"))
|
| 139 |
-
hassec=_to_bool(ref("有価証券報告書提出企業か(TRUE/FALSE)"))
|
| 140 |
-
puboff=_to_bool(ref("決算公告や官報での公開あり(TRUE/FALSE)"))
|
| 141 |
-
pubweb=_to_bool(ref("HP/IRサイトで財務資料公開あり(TRUE/FALSE)"))
|
| 142 |
-
upd=_to_bool(ref("直近更新が定め通りか(TRUE/FALSE)"))
|
| 143 |
-
|
| 144 |
-
cash_ms = (cash/(sales_m or 1)) if cash and sales_m else None
|
| 145 |
-
coll_ms = (coll/(sales_m or 1)) if coll and sales_m else None
|
| 146 |
-
|
| 147 |
-
add("経営者能力","経営姿勢", (_ramp(yoy3,90,50)+_ramp(indep,33,0))/2, _WEIGHTS[("経営者能力","経営姿勢")], f"予実{yoy3 or '—'}%/社外{indep or '—'}%")
|
| 148 |
-
add("経営者能力","事業経験", _ramp(expy if expy is not None else 5.0, 15, 0), _WEIGHTS[("経営者能力","事業経験")], f"経験{expy or '—'}年")
|
| 149 |
-
add("経営者能力","資産担保力", _ramp(cash_ms,1.5,0.2), _WEIGHTS[("経営者能力","資産担保力")], f"現預金/月商≈{round(cash_ms,2) if cash_ms else '—'}")
|
| 150 |
-
add("経営者能力","減点事項", 10.0, _WEIGHTS[("経営者能力","減点事項")], "重大事故/倒産情報不明→中立")
|
| 151 |
-
|
| 152 |
-
add("成長率","売上高伸長性", 5.0, _WEIGHTS[("成長率","売上高伸長性")], "詳細不明→中立")
|
| 153 |
-
add("成長率","利益伸長性", 5.0, _WEIGHTS[("成長率","利益伸長性")], "詳細不明→中立")
|
| 154 |
-
add("成長率","商品", 5.0, _WEIGHTS[("成長率","商品")], "不明→中立")
|
| 155 |
-
|
| 156 |
-
add("安定性","自己資本", _ramp(equity,40,5), _WEIGHTS[("安定性","自己資本")], f"自己資本比率{equity or '—'}%")
|
| 157 |
-
if delay is not None or boun is not None or delaydays is not None:
|
| 158 |
-
pay = ( _ramp(-(delay or 0),0,-6) + _ramp(-(boun or 0),0,-1) + _ramp(-(delaydays or 0),0,-30) )/3
|
| 159 |
-
reason=f"遅延{int(delay or 0)}/不渡{int(boun or 0)}/平均{int(delaydays or 0)}日"
|
| 160 |
-
else:
|
| 161 |
-
pay = _ramp(cash_ms,1.0,0.2); reason=f"代理:現預金/月商≈{round(cash_ms,2) if cash_ms else '—'}"
|
| 162 |
-
add("安定性","決済振り", pay, _WEIGHTS[("安定性","決済振り")], reason)
|
| 163 |
-
|
| 164 |
-
mb = 5.0 + (2.0 if mainb else -0.5 if mainb is False else 0) + (1.0 if hasline else 0)
|
| 165 |
-
add("安定性","金融取引", _clamp(mb,0,10), _WEIGHTS[("安定性","金融取引")], f"メイン{'有' if mainb else '無' if mainb is False else '—'}/与信枠{'有' if hasline else '無' if hasline is False else '—'}")
|
| 166 |
-
add("安定性","資産担保余力", _ramp(coll_ms,4.0,0.0), _WEIGHTS[("安定性","資産担保余力")], f"担保/月商≈{round(coll_ms,2) if coll_ms else '—'}")
|
| 167 |
-
add("安定性","取引先", ( _ramp(-(top1 or 50),0,-80) + _ramp(cust,80,50) + _ramp(-(npl or 1),0,-3) )/3, _WEIGHTS[("安定性","取引先")], f"上位1社{top1 or '—'}%/信用{cust or '—'}/不良{int(npl or 0)}")
|
| 168 |
-
add("安定性","業歴", _ramp(_to_float(ref("業歴(年)")),20,1), _WEIGHTS[("安定性","業歴")], f"{ref('業歴(年)') or '—'}年")
|
| 169 |
-
|
| 170 |
-
dis = 0.0 + (10.0 if hassec else 7.0 if (puboff or pubweb) else 4.0) + (1.0 if upd else 0.0)
|
| 171 |
-
add("公平性・総合���評","ディスクロージャー", _clamp(dis,0,10), _WEIGHTS[("公平性","ディスクロージャー")] if ("公平性","ディスクロージャー") in _WEIGHTS else 8, "公開度合い")
|
| 172 |
-
|
| 173 |
-
total = round(sum(x["score"] for x in items),1)
|
| 174 |
-
return {"external_total": total, "items": items}
|
| 175 |
-
|
| 176 |
-
# ========================= PDF → テキスト(ローカル) =========================
|
| 177 |
-
def text_by_pypdf(pdf_bytes: bytes) -> str:
|
| 178 |
try:
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
-
def text_by_pdfplumber(pdf_bytes: bytes) -> str:
|
| 184 |
try:
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
return "
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
for i, img in enumerate(pages[:max_pages]):
|
| 196 |
-
texts.append(pytesseract.image_to_string(img, lang="jpn+eng"))
|
| 197 |
-
return "\n".join(texts)
|
| 198 |
-
|
| 199 |
-
def read_pdf_text(pdf_bytes: bytes, force_ocr: bool, logs: list[str]) -> str:
|
| 200 |
-
if force_ocr:
|
| 201 |
-
log(logs,"OCRを強制します。")
|
| 202 |
-
return text_by_ocr(pdf_bytes)
|
| 203 |
-
t1 = text_by_pypdf(pdf_bytes)
|
| 204 |
-
t2 = text_by_pdfplumber(pdf_bytes)
|
| 205 |
-
text = max([t1,t2], key=lambda s: len(s or ""))
|
| 206 |
-
if len((text or "").strip()) < 200:
|
| 207 |
-
log(logs, f"テキスト抽出が希薄({len(text.strip())}文字)。OCRにフォールバック。")
|
| 208 |
-
try: return text_by_ocr(pdf_bytes)
|
| 209 |
-
except Exception as e: log(logs, f"OCR失敗: {e}")
|
| 210 |
-
else:
|
| 211 |
-
log(logs, f"テキスト抽出成功({len(text.strip())}文字)。")
|
| 212 |
-
return text or ""
|
| 213 |
-
|
| 214 |
-
# ========================= OpenAI Vision でのAI抽出 =========================
|
| 215 |
-
SYSTEM_PROMPT = (
|
| 216 |
-
"あなたは日本語の与信アナリストです。画像化された決算書/財務資料のページから、"
|
| 217 |
-
"指定の項目値を厳密なJSONで抽出します。わからない項目は空文字にしてください。"
|
| 218 |
-
"金額は半角数字にしてカンマはあってもなくても構いません。割合は%を除いた数値。"
|
| 219 |
-
)
|
| 220 |
-
|
| 221 |
-
# 返却スキーマ:入力項目→値
|
| 222 |
-
ALL_FIELDS = [i for _, i in _TEMPLATE_ROWS]
|
| 223 |
-
|
| 224 |
-
def images_from_pdf(pdf_bytes: bytes, dpi: int = 180, max_pages: int = 6) -> list[Image.Image]:
|
| 225 |
-
return convert_from_bytes(pdf_bytes, dpi=dpi)[:max_pages]
|
| 226 |
-
|
| 227 |
-
def b64_png(img: Image.Image) -> str:
|
| 228 |
-
buf = io.BytesIO()
|
| 229 |
-
img.save(buf, format="PNG")
|
| 230 |
-
return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("ascii")
|
| 231 |
-
|
| 232 |
-
def openai_extract_from_images(images: list[Image.Image], logs: list[str]) -> dict[str,str]:
|
| 233 |
-
api_key = os.getenv("OPENAI_API_KEY")
|
| 234 |
-
if not api_key:
|
| 235 |
-
log(logs, "OPENAI_API_KEY が未設定のためAI抽出はスキップします。")
|
| 236 |
-
return {}
|
| 237 |
-
client = OpenAI(api_key=api_key)
|
| 238 |
-
|
| 239 |
-
# ページを2枚ずつバッチ処理(トークン節約)
|
| 240 |
-
out: dict[str,str] = {}
|
| 241 |
-
for i in range(0, len(images), 2):
|
| 242 |
-
batch = images[i:i+2]
|
| 243 |
-
content = [{"type":"text","text":"以下の決算書画像から指定の項目を抽出して。JSONだけ返答。"}]
|
| 244 |
-
for img in batch:
|
| 245 |
-
content.append({"type":"image_url","image_url":{"url": b64_png(img)}})
|
| 246 |
-
# JSONスキーマ
|
| 247 |
-
json_schema = {
|
| 248 |
-
"name": "corp_fields",
|
| 249 |
-
"schema": {
|
| 250 |
-
"type": "object",
|
| 251 |
-
"properties": {f: {"type": "string"} for f in ALL_FIELDS},
|
| 252 |
-
"additionalProperties": False
|
| 253 |
-
},
|
| 254 |
-
"strict": True
|
| 255 |
-
}
|
| 256 |
-
try:
|
| 257 |
-
resp = client.chat.completions.create(
|
| 258 |
-
model="gpt-4o-mini",
|
| 259 |
-
messages=[
|
| 260 |
-
{"role":"system","content":SYSTEM_PROMPT},
|
| 261 |
-
{"role":"user","content":content}
|
| 262 |
-
],
|
| 263 |
-
response_format={"type":"json_schema","json_schema":json_schema},
|
| 264 |
-
temperature=0
|
| 265 |
-
)
|
| 266 |
-
txt = resp.choices[0].message.content.strip()
|
| 267 |
-
part = json.loads(txt)
|
| 268 |
-
out.update({k:(v or "") for k,v in part.items()})
|
| 269 |
-
log(logs, f"OpenAIバッチ{i//2+1}: {len(part)}項目を抽出")
|
| 270 |
-
except Exception as e:
|
| 271 |
-
log(logs, f"OpenAI呼び出し失敗(バッチ{i//2+1}): {e}")
|
| 272 |
-
return out
|
| 273 |
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
return df
|
| 311 |
-
|
| 312 |
-
# ========================= 可視化 =========================
|
| 313 |
-
def radar_plot(ext: dict) -> plt.Figure:
|
| 314 |
-
by = {}
|
| 315 |
-
for it in ext.get("items", []):
|
| 316 |
-
by[it["category"]] = by.get(it["category"], 0) + it["score"]
|
| 317 |
-
labels = list(by.keys()) or ["経営者能力","成長率","安定性","公平性"]
|
| 318 |
-
vals = [by.get(k,0) for k in labels]
|
| 319 |
-
N=len(labels)
|
| 320 |
-
angles = np.linspace(0, 2*np.pi, N, endpoint=False).tolist()
|
| 321 |
-
vals += vals[:1]; angles += angles[:1]
|
| 322 |
-
fig = plt.figure(figsize=(5,5))
|
| 323 |
-
ax = plt.subplot(111, polar=True)
|
| 324 |
-
ax.plot(angles, vals, linewidth=2)
|
| 325 |
-
ax.fill(angles, vals, alpha=0.25)
|
| 326 |
-
ax.set_thetagrids(np.degrees(angles[:-1]), labels, fontsize=10)
|
| 327 |
-
ax.set_title("カテゴリ別スコア合算")
|
| 328 |
-
return fig
|
| 329 |
-
|
| 330 |
-
def gauge_plot(ext: dict) -> plt.Figure:
|
| 331 |
-
total = ext.get("external_total", 0)
|
| 332 |
-
fig = plt.figure(figsize=(5,1.2))
|
| 333 |
-
ax = fig.add_axes([0.05,0.25,0.9,0.5])
|
| 334 |
-
ax.barh([0], [total], height=0.3)
|
| 335 |
-
ax.set_xlim(0,100); ax.set_yticks([]); ax.set_xlabel("総合スコア")
|
| 336 |
-
for s in ax.spines.values(): s.set_visible(False)
|
| 337 |
-
ax.text(min(100,total)+1,0,str(total), va="center")
|
| 338 |
-
return fig
|
| 339 |
-
|
| 340 |
-
# ========================= 推奨値(簡略) =========================
|
| 341 |
-
def recommend(df: pd.DataFrame, ext: dict) -> dict:
|
| 342 |
-
def get(lbl):
|
| 343 |
-
m = df["入力項目"].eq(lbl)
|
| 344 |
-
return df.loc[m,"値"].values[0] if m.any() else ""
|
| 345 |
-
monthly_sales = safe_float(get("月商(円)") or get("月商(円)_再掲"))
|
| 346 |
-
collateral = safe_float(get("担保余力評価額(円)"))
|
| 347 |
-
total = ext.get("external_total", 0.0)
|
| 348 |
-
grade = "A" if total>=80 else "B" if total>=65 else "C" if total>=50 else "D"
|
| 349 |
-
factor = 1.6 if grade=="A" else 1.3 if grade=="B" else 1.0 if grade=="C" else 0.6
|
| 350 |
-
limit_by_sales = (monthly_sales or 0) * factor if monthly_sales else 0
|
| 351 |
-
limit_by_coll = (collateral or 0) * 0.6 if collateral else float("inf")
|
| 352 |
-
credit_limit = round(min(limit_by_sales or 0, limit_by_coll if np.isfinite(limit_by_coll) else limit_by_sales))
|
| 353 |
-
return {"grade":grade, "credit_limit_jpy": credit_limit}
|
| 354 |
-
|
| 355 |
-
# ========================= パイプライン =========================
|
| 356 |
-
def run_pipeline(filepaths: list[str] | None, company_name: str, force_ocr: bool, use_openai: bool):
|
| 357 |
-
logs=[]
|
| 358 |
-
base = template_df()
|
| 359 |
-
|
| 360 |
-
if not filepaths:
|
| 361 |
-
log(logs,"PDF未指定:空テンプレを表示します。")
|
| 362 |
-
df = base.copy()
|
| 363 |
-
else:
|
| 364 |
-
# 複数PDFをマージ
|
| 365 |
-
merged = ""
|
| 366 |
-
ai_map: dict[str,str] = {}
|
| 367 |
-
for p in filepaths:
|
| 368 |
-
with open(p, "rb") as f:
|
| 369 |
-
pdf_bytes = f.read()
|
| 370 |
-
|
| 371 |
-
if use_openai and os.getenv("OPENAI_API_KEY"):
|
| 372 |
try:
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
ai_map.update(part)
|
| 376 |
except Exception as e:
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
with gr.Row():
|
| 426 |
-
with gr.Column(scale=
|
| 427 |
-
company = gr.Textbox(label="企業名(任意)", placeholder="例:株式会社
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
with gr.Tab("テンプレ編集"):
|
| 439 |
-
grid = gr.Dataframe(headers=["カテゴリー","入力項目","値"], datatype=["str","str","str"],
|
| 440 |
-
row_count=(len(_TEMPLATE_ROWS),"fixed"), col_count=(3,"fixed"),
|
| 441 |
-
interactive=True, label="抽出結果(編集可)")
|
| 442 |
-
|
| 443 |
-
with gr.Tab("評価結果(詳細JSON)"):
|
| 444 |
-
ext_json = gr.JSON(label="外部スコア")
|
| 445 |
-
recs_json = gr.JSON(label="推奨(簡易)")
|
| 446 |
-
json_download = gr.File(label="結果JSONダウンロード", interactive=False)
|
| 447 |
-
|
| 448 |
-
with gr.Tab("抽出ログ / デバッグ"):
|
| 449 |
-
log_box = gr.Code(label="ログ", language="markdown")
|
| 450 |
-
|
| 451 |
-
def on_run(filepaths, company, use_openai, progress=gr.Progress()):
|
| 452 |
-
try:
|
| 453 |
-
progress(0.1, desc="解析中…")
|
| 454 |
-
df, ext, recs, out_json_path, radar_fig, gauge_fig, logs = run_pipeline(filepaths, company, False, use_openai)
|
| 455 |
-
progress(1.0, desc="完了")
|
| 456 |
-
return df, ext, recs, gr.File.update(value=out_json_path, visible=True), radar_fig, gauge_fig, logs
|
| 457 |
-
except Exception as e:
|
| 458 |
-
tb = traceback.format_exc()
|
| 459 |
-
return template_df(), {}, {}, gr.File.update(value=None, visible=False), plt.figure(), plt.figure(), f"Error: {e}\n\n{tb}"
|
| 460 |
-
|
| 461 |
-
run_btn.click(on_run, inputs=[files, company, use_openai],
|
| 462 |
-
outputs=[grid, ext_json, recs_json, json_download, radar, total_gauge, log_box])
|
| 463 |
-
|
| 464 |
-
def on_recalc(df, company):
|
| 465 |
-
out_df, ext, recs, out_json_path, radar_fig, gauge_fig = recompute(pd.DataFrame(df), company)
|
| 466 |
-
return out_df, ext, recs, gr.File.update(value=out_json_path, visible=True), radar_fig, gauge_fig
|
| 467 |
-
|
| 468 |
-
recalc_btn.click(on_recalc, inputs=[grid, company],
|
| 469 |
-
outputs=[grid, ext_json, recs_json, json_download, radar, total_gauge])
|
| 470 |
|
| 471 |
if __name__ == "__main__":
|
| 472 |
-
|
|
|
|
|
|
| 1 |
+
import os, io, base64, json, re, tempfile, traceback
|
|
|
|
|
|
|
|
|
|
| 2 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 3 |
import pdfplumber
|
| 4 |
from pdf2image import convert_from_bytes
|
|
|
|
| 5 |
from PIL import Image
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
from openai import OpenAI
|
| 9 |
|
| 10 |
+
# ========= ユーティリティ =========
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
def _b64(img: Image.Image, fmt="JPEG", quality=85) -> str:
|
| 13 |
+
buf = io.BytesIO()
|
| 14 |
+
img.save(buf, format=fmt, optimize=True, quality=quality)
|
| 15 |
+
return base64.b64encode(buf.getvalue()).decode("utf-8")
|
| 16 |
+
|
| 17 |
+
def pdf_to_images_b64(pdf_bytes: bytes, dpi: int = 200, max_pages: int = 6):
|
| 18 |
+
"""PDFを画像にレンダリング(先頭max_pages)。"""
|
| 19 |
+
pages = convert_from_bytes(pdf_bytes, dpi=dpi, fmt="jpeg", thread_count=2)
|
| 20 |
+
out = []
|
| 21 |
+
for i, im in enumerate(pages[:max_pages]):
|
| 22 |
+
out.append(_b64(im))
|
| 23 |
+
return out
|
| 24 |
|
| 25 |
+
def extract_text_pdf(pdf_bytes: bytes, max_pages: int = 8) -> str:
|
| 26 |
+
"""pdfplumberでテキスト抽出(テキストPDF向け)。"""
|
| 27 |
+
texts = []
|
| 28 |
+
with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:
|
| 29 |
+
for page in pdf.pages[:max_pages]:
|
| 30 |
+
t = page.extract_text() or ""
|
| 31 |
+
texts.append(t)
|
| 32 |
+
return "\n\n".join(texts).strip()
|
| 33 |
+
|
| 34 |
+
def parse_json_safe(s: str):
|
| 35 |
+
"""LLMの出力からJSONを安全に取り出す。失敗時はrawで返す。"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
try:
|
| 37 |
+
return json.loads(s)
|
| 38 |
+
except Exception:
|
| 39 |
+
m = re.search(r"\{[\s\S]*\}", s)
|
| 40 |
+
if m:
|
| 41 |
+
try:
|
| 42 |
+
return json.loads(m.group(0))
|
| 43 |
+
except Exception:
|
| 44 |
+
pass
|
| 45 |
+
return {"raw": s}
|
| 46 |
+
|
| 47 |
+
def vision_prompt(company_hint: str) -> str:
|
| 48 |
+
return f"""あなたは財務PDFの情報抽出アシスタントです。
|
| 49 |
+
画像化された決算書PDFのページ(数枚)と、抽出したテキスト断片を渡します。
|
| 50 |
+
以下のJSONスキーマで出力してください。未知は null に、単位は数値に正規化してください。
|
| 51 |
+
|
| 52 |
+
出力JSONスキーマ:
|
| 53 |
+
{{
|
| 54 |
+
"company": string | null,
|
| 55 |
+
"fiscal_year": string | null, // 例: 2024-03
|
| 56 |
+
"revenue": number | null, // 売上高(円)
|
| 57 |
+
"operating_income": number | null, // 営業利益(円)
|
| 58 |
+
"ordinary_income": number | null, // 経常利益(円)
|
| 59 |
+
"net_income": number | null, // 当期純利益(円)
|
| 60 |
+
"total_assets": number | null,
|
| 61 |
+
"net_assets": number | null,
|
| 62 |
+
"notes": string | null // 取得根拠や補足
|
| 63 |
+
}}
|
| 64 |
+
|
| 65 |
+
ヒントとなる企業名(任意入力): {company_hint or "(未指定)"}
|
| 66 |
+
|
| 67 |
+
出力は**JSONのみ**を返してください。"""
|
| 68 |
+
|
| 69 |
+
def ensure_api_key() -> str:
|
| 70 |
+
key = os.getenv("OPENAI_API_KEY") or ""
|
| 71 |
+
if not key:
|
| 72 |
+
raise RuntimeError("Space Secrets に OPENAI_API_KEY が設定されていません。Settings → Variables で追加してください。")
|
| 73 |
+
return key
|
| 74 |
+
|
| 75 |
+
def call_openai_vision(images_b64, text_snippet, prompt, model="gpt-4o-mini"):
|
| 76 |
+
# Chat Completions(Vision)
|
| 77 |
+
client = OpenAI() # OPENAI_API_KEY は環境変数から自動解決
|
| 78 |
+
content = [{"type": "text", "text": prompt}]
|
| 79 |
+
# 画像を添付
|
| 80 |
+
for b64 in images_b64:
|
| 81 |
+
content.append({
|
| 82 |
+
"type": "image_url",
|
| 83 |
+
"image_url": {"url": f"data:image/jpeg;base64,{b64}"}
|
| 84 |
+
})
|
| 85 |
+
# 長すぎるテキストは圧縮
|
| 86 |
+
if text_snippet:
|
| 87 |
+
snippet = text_snippet[:8000]
|
| 88 |
+
content.append({"type": "text", "text": f"テキスト抽出(先頭8000文字):\n{snippet}"})
|
| 89 |
+
|
| 90 |
+
resp = client.chat.completions.create(
|
| 91 |
+
model=model,
|
| 92 |
+
messages=[{"role": "user", "content": content}],
|
| 93 |
+
temperature=0.2,
|
| 94 |
+
)
|
| 95 |
+
return resp.choices[0].message.content
|
| 96 |
+
|
| 97 |
+
# ========= 解析本体 =========
|
| 98 |
+
|
| 99 |
+
def analyze_pdfs(company, use_openai_vision, files):
|
| 100 |
+
logs = []
|
| 101 |
+
results = []
|
| 102 |
|
|
|
|
| 103 |
try:
|
| 104 |
+
ensure_api_key()
|
| 105 |
+
except Exception as e:
|
| 106 |
+
# APIキー未設定などの致命的エラーは即返す
|
| 107 |
+
err = f"設定エラー: {e}"
|
| 108 |
+
return gr.update(label="抽出結果(JSON)", value={"error": err}), gr.update(value=f"❌ {err}")
|
| 109 |
+
|
| 110 |
+
if not files:
|
| 111 |
+
return gr.update(value={"error": "PDFが未指定です"}), "PDFをアップロードしてください。"
|
| 112 |
+
|
| 113 |
+
progress = tqdm(total=len(files), desc="解析中")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
try:
|
| 116 |
+
for f in files:
|
| 117 |
+
# Gradio (type="bytes") を想定。filepath の場合は読み直し。
|
| 118 |
+
if isinstance(f, bytes):
|
| 119 |
+
pdf_bytes = f
|
| 120 |
+
name = "uploaded.pdf"
|
| 121 |
+
elif isinstance(f, str):
|
| 122 |
+
name = os.path.basename(f)
|
| 123 |
+
with open(f, "rb") as rf:
|
| 124 |
+
pdf_bytes = rf.read()
|
| 125 |
+
else:
|
| 126 |
+
# gr.File オブジェクト(.name, .read)系にも対応
|
| 127 |
+
name = getattr(f, "name", "uploaded.pdf")
|
| 128 |
+
try:
|
| 129 |
+
pdf_bytes = f.read() if hasattr(f, "read") else f
|
| 130 |
+
except Exception:
|
| 131 |
+
pdf_bytes = b""
|
| 132 |
+
|
| 133 |
+
file_log = [f"--- {name} ---"]
|
| 134 |
+
|
| 135 |
+
if not pdf_bytes:
|
| 136 |
+
file_log.append("⚠️ PDFの読み込みに失敗しました。")
|
| 137 |
+
logs.append("\n".join(file_log))
|
| 138 |
+
continue
|
| 139 |
+
|
| 140 |
+
# 1) テキスト抽出(テキストPDF向け)
|
| 141 |
+
try:
|
| 142 |
+
text_raw = extract_text_pdf(pdf_bytes)
|
| 143 |
+
file_log.append(f"テキスト抽出 文字数: {len(text_raw)}")
|
| 144 |
+
except Exception as e:
|
| 145 |
+
text_raw = ""
|
| 146 |
+
file_log.append(f"テキスト抽出失敗: {e}")
|
| 147 |
+
|
| 148 |
+
# 2) 画像化(Vision用)
|
| 149 |
+
images_b64 = []
|
| 150 |
+
if use_openai_vision:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
try:
|
| 152 |
+
images_b64 = pdf_to_images_b64(pdf_bytes, dpi=200, max_pages=6)
|
| 153 |
+
file_log.append(f"画像化: {len(images_b64)}ページ")
|
|
|
|
| 154 |
except Exception as e:
|
| 155 |
+
file_log.append(f"画像化失敗: {e}")
|
| 156 |
+
|
| 157 |
+
# 3) OpenAI Vision 解析 or テキストのみ抽出(フォールバック)
|
| 158 |
+
try:
|
| 159 |
+
if use_openai_vision and images_b64:
|
| 160 |
+
prompt = vision_prompt(company)
|
| 161 |
+
llm_out = call_openai_vision(images_b64, text_raw, prompt)
|
| 162 |
+
data = parse_json_safe(llm_out)
|
| 163 |
+
data["_source"] = name
|
| 164 |
+
results.append(data)
|
| 165 |
+
file_log.append("Vision解析: ✅")
|
| 166 |
+
else:
|
| 167 |
+
# Visionオフ or 画像化失敗 → テキストのみの簡易抽出
|
| 168 |
+
# (必要最低限のプレースホルダ抽出)
|
| 169 |
+
guess = {
|
| 170 |
+
"company": company or None,
|
| 171 |
+
"fiscal_year": None,
|
| 172 |
+
"revenue": None,
|
| 173 |
+
"operating_income": None,
|
| 174 |
+
"ordinary_income": None,
|
| 175 |
+
"net_income": None,
|
| 176 |
+
"total_assets": None,
|
| 177 |
+
"net_assets": None,
|
| 178 |
+
"notes": "Vision未使用または画像化失敗。テキストのみ。",
|
| 179 |
+
"_source": name,
|
| 180 |
+
}
|
| 181 |
+
results.append(guess)
|
| 182 |
+
file_log.append("Vision未使用/失敗: テキストのみで簡易出力 ✅")
|
| 183 |
+
except Exception as e:
|
| 184 |
+
file_log.append(f"LLM解析失敗: {e}\n{traceback.format_exc()}")
|
| 185 |
+
|
| 186 |
+
logs.append("\n".join(file_log))
|
| 187 |
+
progress.update(1)
|
| 188 |
+
|
| 189 |
+
finally:
|
| 190 |
+
progress.close()
|
| 191 |
+
|
| 192 |
+
# DataFrame & CSV
|
| 193 |
+
df = pd.DataFrame(results)
|
| 194 |
+
csv_path = os.path.join(tempfile.gettempdir(), "extracted.csv")
|
| 195 |
+
try:
|
| 196 |
+
df.to_csv(csv_path, index=False)
|
| 197 |
+
download_md = f"[📥 CSVをダウンロード]({csv_path})"
|
| 198 |
+
except Exception:
|
| 199 |
+
download_md = "(CSV生成に失敗)"
|
| 200 |
+
|
| 201 |
+
# 右側カード上部 = 結果JSON(複数PDFなら配列)
|
| 202 |
+
json_value = results[0] if len(results) == 1 else results
|
| 203 |
+
json_component = gr.JSON(label="抽出結果(JSON)", value=json_value)
|
| 204 |
+
|
| 205 |
+
# 右側カード下部 = ログ + ダウンロードリンク
|
| 206 |
+
log_text = "解析ログ\n" + "\n\n".join(logs) + f"\n\n{download_md}"
|
| 207 |
+
return json_component, log_text
|
| 208 |
+
|
| 209 |
+
# ========= UI =========
|
| 210 |
+
|
| 211 |
+
with gr.Blocks(theme=gr.themes.Soft(), css="""
|
| 212 |
+
#app {max-width: 1180px; margin: 0 auto;}
|
| 213 |
+
.small {font-size: 12px; opacity: .8}
|
| 214 |
+
""") as demo:
|
| 215 |
+
gr.Markdown("## 📈 企業スコアリング(PDF解析 × OpenAI Vision)\nPDFを投げる → 画像レンダリング + LLMで抽出 → JSONに正規化")
|
| 216 |
|
| 217 |
with gr.Row():
|
| 218 |
+
with gr.Column(scale=5):
|
| 219 |
+
company = gr.Textbox(label="企業名(任意)", placeholder="例:株式会社○○")
|
| 220 |
+
use_vision = gr.Checkbox(value=True, label="OpenAIでPDFをAI解析(Vision)")
|
| 221 |
+
files = gr.File(label="決算書PDF(複数可)", file_count="multiple", type="bytes")
|
| 222 |
+
run_btn = gr.Button("🔎 PDFを解析してテンプレに反映", variant="primary")
|
| 223 |
+
gr.Markdown("**Tips**: Settings → Variables に `OPENAI_API_KEY` を必ず設定してください。", elem_classes=["small"])
|
| 224 |
+
with gr.Column(scale=5):
|
| 225 |
+
out_json = gr.JSON(label="抽出結果(JSON)")
|
| 226 |
+
out_log = gr.Markdown(label="ログ / デバッグ")
|
| 227 |
+
|
| 228 |
+
run_btn.click(analyze_pdfs, inputs=[company, use_vision, files], outputs=[out_json, out_log])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
|
| 230 |
if __name__ == "__main__":
|
| 231 |
+
# Spaces では自動で起動されるが、ローカルでも動くように
|
| 232 |
+
demo.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")))
|