Spaces:
Sleeping

Corin1998 commited on
Commit
82ef141
·
verified ·
1 Parent(s): 6280ef2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +272 -365
app.py CHANGED
@@ -1,25 +1,37 @@
1
  from __future__ import annotations
2
- import os, io, re, json, typing as T, traceback
3
  import numpy as np
4
  import pandas as pd
5
  import gradio as gr
6
 
 
7
  from pypdf import PdfReader
8
  import pdfplumber
9
  from pdf2image import convert_from_bytes
10
  import pytesseract
11
  from PIL import Image
 
 
12
  from rapidfuzz import fuzz, process
13
 
 
 
 
 
 
 
 
 
 
14
  # ========================= 基本ユーティリティ =========================
15
- def log_append(logs: list[str], msg: str):
16
  logs.append(msg)
17
 
18
  def safe_float(x):
19
  try: return float(str(x).replace(",", "").replace("%","%").replace("%","").strip())
20
  except: return None
21
 
22
- # ========================= 評価テンプレ/スコア(前回ロジックほぼ維持) =========================
23
  _TEMPLATE_ROWS = [
24
  ("経営者能力", "予実達成率_3年平均(%)"),
25
  ("経営者能力", "監査・内部統制の重大な不備 件数(過去3年)"),
@@ -61,11 +73,10 @@ _TEMPLATE_ROWS = [
61
  ("公平性・総合世評", "HP/IRサイトで財務資料公開あり(TRUE/FALSE)"),
62
  ("公平性・総合世評", "直近更新が定め通りか(TRUE/FALSE)"),
63
  ]
64
- def get_external_template_df():
65
  return pd.DataFrame([(c,i,"") for c,i in _TEMPLATE_ROWS], columns=["カテゴリー","入力項目","値"])
66
 
67
- # (前回のスコア計算ロジックを短縮してそのまま使用)
68
- # --- 省略せずに内包 ---
69
  def _clamp(v,a,b): return max(a, min(b, v))
70
  def _to_float(x):
71
  if x is None: return None
@@ -77,9 +88,6 @@ def _to_bool(x):
77
  if s in ("true","t","1","yes","y","有","あり"): return True
78
  if s in ("false","f","0","no","n","無","なし"): return False
79
  return None
80
- def _ratio(a,b):
81
- if a is None or b is None or b == 0: return None
82
- return a/b
83
  def _ramp(x, good, bad, lo=0.0, hi=10.0, neutral=None):
84
  if x is None: return neutral if neutral is not None else (lo+hi)/2.0
85
  if good > bad:
@@ -92,20 +100,11 @@ def _ramp(x, good, bad, lo=0.0, hi=10.0, neutral=None):
92
  return lo + (hi-lo) * (x-good)/(bad-good)
93
 
94
  _WEIGHTS = {
95
- ("経営者能力", "経営姿勢"): 8,
96
- ("経営者能力", "事業経験"): 5,
97
- ("経営者能力", "資産担保力"): 6,
98
- ("経営者能力", "減点事項"): 7,
99
- ("成長率", "売上高伸長性"): 10,
100
- ("成長率", "利益伸長性"): 10,
101
- ("成長率", "商品"): 6,
102
- ("安定性", "自己資本"): 8,
103
- ("安定性", "決済振り"): 10,
104
- ("安定性", "金融取引"): 6,
105
- ("安定性", "資産担保余力"): 6,
106
- ("安定性", "取引先"): 6,
107
- ("安定性", "業歴"): 4,
108
- ("公平性・総合世評", "ディスクロージャー"): 8,
109
  }
110
  _WEIGHT_NORM = 100.0 / float(sum(_WEIGHTS.values()))
111
 
@@ -113,311 +112,205 @@ def score_external_from_df(df: pd.DataFrame) -> dict:
113
  def ref(label: str):
114
  m = df["入力項目"].eq(label)
115
  return df.loc[m,"値"].values[0] if m.any() else None
116
- items = []
117
- def _add(cat, name, raw, w, reason):
118
  items.append({
119
- "category": cat, "name": name, "raw": round(raw,2),
120
- "weight": round(w*_WEIGHT_NORM,2),
121
- "score": round((raw/10.0)*w*_WEIGHT_NORM,2),
122
- "reason": reason
123
  })
124
- # --- 参照値 ---
125
  yoy3=_to_float(ref("予実達成率_3年平均(%)"))
126
- audit_bad=_to_float(ref("監査・内部統制の重大な不備 件数(過去3年)"))
127
- comp_bad=_to_float(ref("重大コンプライアンス件数(過去3年)"))
128
  indep=_to_float(ref("社外取締役比率(%)"))
129
- exp_years=_to_float(ref("代表者の業界経験年数"))
130
  cash=_to_float(ref("現預金(円)"))
131
  sales_m=_to_float(ref("月商(円)"))
132
- collat=_to_float(ref("担保余力評価額(円)"))
133
- has_bk=_to_bool(ref("倒産歴の有無(TRUE/FALSE)"))
134
- bk_years=_to_float(ref("倒産からの経過年数"))
135
- incidents=_to_float(ref("重大事件・事故件数(過去10年)"))
136
- s1=_to_float(ref("売上_期1(最古期)")); s2=_to_float(ref("売上_期2")); s3=_to_float(ref("売上_期3(最新期)"))
137
- p1=_to_float(ref("営業利益_期1(最古期)")); p2=_to_float(ref("営業利益_期2")); p3=_to_float(ref("営業利益_期3(最新期)"))
138
  equity=_to_float(ref("自己資本比率(%)"))
139
- delay_cnt=_to_float(ref("支払遅延件数(直近12ヶ月)"))
140
- boun_cnt=_to_float(ref("不渡り件数(直近12ヶ月)"))
141
- delay_days=_to_float(ref("平均支払遅延日数"))
142
- mainbank=_to_bool(ref("メインバンク明確か(TRUE/FALSE)"))
143
- lenders=_to_float(ref("借入先数"))
144
- main_share=_to_float(ref("メインバンク借入シェア(%)"))
145
- has_line=_to_bool(ref("コミットメントライン等の長期与信枠あり(TRUE/FALSE)"))
146
- sales_m2=_to_float(ref("月商(円)_再掲")) or sales_m
147
  top1=_to_float(ref("主要顧客上位1社売上比率(%)"))
148
- cust_score=_to_float(ref("主要顧客の平均信用スコア(0-100)"))
149
- npl_cnt=_to_float(ref("不良債権件数(直近12ヶ月)"))
150
  years=_to_float(ref("業歴(年)"))
151
- has_sec=_to_bool(ref("有価証券報告書提出企業か(TRUE/FALSE)"))
152
- pub_off=_to_bool(ref("決算公告や官報での公開あり(TRUE/FALSE)"))
153
- pub_web=_to_bool(ref("HP/IRサイトで財務資料公開あり(TRUE/FALSE)"))
154
- upd_on=_to_bool(ref("直近更新が定め通りか(TRUE/FALSE)"))
155
-
156
- def cagr(v1, v3):
157
- if v1 is None or v3 is None or v1 <= 0: return None
158
- return (v3/v1)**(1/2) - 1.0
159
- cash_to_ms = (cash/(sales_m2 or 1)) if cash is not None and sales_m2 else None
160
- coll_to_ms = (collat/(sales_m2 or 1)) if collat is not None and sales_m2 else None
161
- s_cagr = cagr(s1, s3); p_cagr = cagr(p1, p3)
162
-
163
- mg_att = (_ramp(yoy3, 90,50)+_ramp(0 if not audit_bad else -audit_bad,0,-3)+_ramp(0 if not comp_bad else -comp_bad,0,-2)+_ramp(indep,33,0))/4
164
- mg_exp = _ramp(exp_years if exp_years is not None else 5.0, 15, 0)
165
- mg_asset = _ramp(cash_to_ms, 1.5, 0.2)
166
- if incidents and incidents>0: pen=0.0; rs="重大事故多→大減点"
167
- elif has_bk: pen=6.0 if (bk_years and bk_years>=10) else 3.0; rs=f"倒産歴 {bk_years or '不明'}年"
168
- else: pen=10.0; rs="事故/倒産なし"
169
-
170
- items=[]
171
- def _add(cat,name,raw,w,rs): items.append({"category":cat,"name":name,"raw":round(raw,2),"weight":round(w*_WEIGHT_NORM,2),"score":round((raw/10.0)*w*_WEIGHT_NORM,2),"reason":rs})
172
- _add("経営者能力","経営姿勢",mg_att,_WEIGHTS[("経営者能力","経営姿勢")],f"予実{yoy3 or '—'}%/監査{audit_bad or 0}/違反{comp_bad or 0}/社外{indep or '—'}%")
173
- _add("経営者能力","事業経験",mg_exp,_WEIGHTS[("経営者能力","事業経験")],f"経験{exp_years if exp_years is not None else '不明→中立'}年")
174
- _add("経営者能力","資産担保力",mg_asset,_WEIGHTS[("経営者能力","資産担保力")],f"現預金/月商≈{round(cash_to_ms,2) if cash_to_ms else '—'}")
175
- _add("経営者能力","減点事項",pen,_WEIGHTS[("経営者能力","減点事項")],rs)
176
- _add("成長率","売上高伸長性",_ramp(s_cagr,0.08,-0.05),_WEIGHTS[("成長率","売上高伸長性")],f"CAGR売上{round((s_cagr or 0)*100,1) if s_cagr is not None else '—'}%")
177
- _add("成長率","利益伸長性",_ramp(p_cagr,0.08,-0.05),_WEIGHTS[("成長率","利益伸長性")],f"CAGR営業{round((p_cagr or 0)*100,1) if p_cagr is not None else '—'}%")
178
- _add("成長率","商品",5.0,_WEIGHTS[("成長率","商品")],"不明→中立")
179
- _add("安定性","自己資本",_ramp(equity,40,5),_WEIGHTS[("安定性","自己資本")],f"自己資本比率{equity or '—'}%")
180
- if delay_cnt is not None or boun_cnt is not None or delay_days is not None:
181
- sc=( _ramp(- (delay_cnt or 0),0,-6) + _ramp(- (boun_cnt or 0),0,-1) + _ramp(- (delay_days or 0),0,-30) )/3
182
- rs=f"遅延{int(delay_cnt or 0)}/不渡{int(boun_cnt or 0)}/平均{int(delay_days or 0)}日"
183
  else:
184
- sc=_ramp(cash_to_ms,1.0,0.2); rs=f"代理:現預金/月商≈{round(cash_to_ms,2) if cash_to_ms else '—'}"
185
- _add("安定性","決済振り", sc, _WEIGHTS[("安定性","決済振り")], rs)
186
- sc_mb = 5.0 + (2.0 if mainbank else -0.5 if mainbank is False else 0) + (1.0 if has_line else 0)
187
- sc_mb = _clamp(sc_mb,0,10)
188
- _add("安定性","金融取引", sc_mb, _WEIGHTS[("安定性","金融取引")],
189
- f"メイン{'有' if mainbank else '無' if mainbank is False else '—'}/与信枠{'有' if has_line else '無' if has_line is False else '—'}")
190
- _add("安定性","資産担保余力", _ramp(coll_to_ms,4.0,0.0), _WEIGHTS[("安定性","資産担保余力")], f"担保/月商≈{round(coll_to_ms,2) if coll_to_ms else '—'}")
191
- _add("安定性","取引先", ( _ramp(- (top1 or 50),0,-80) + _ramp(cust_score,80,50) + _ramp(- (npl_cnt or 1),0,-3) )/3,
192
- _WEIGHTS[("安定性","取引先")], f"上位1社{top1 or '—'}%/信用{cust_score or '—'}/不良{int(npl_cnt or 0)}")
193
- _add("安定性","業歴", _ramp(years,20,1), _WEIGHTS[("安定性","業歴")], f"{years or '—'}年")
194
- sc_dis = 0.0 + (10.0 if has_sec else 7.0 if (pub_off or pub_web) else 4.0) + (1.0 if upd_on else 0.0)
195
- sc_dis = _clamp(sc_dis,0,10)
196
- _add("公平性・総合世評","ディスクロージャー", sc_dis, _WEIGHTS[("公平性・総合世評","ディスクロージャー")],
197
- f"{'有報' if has_sec else '公開あり' if (pub_off or pub_web) else '公開乏しい'} / 更新{'◯' if upd_on else '—'}")
198
  total = round(sum(x["score"] for x in items),1)
199
- return {"name":"企業評価(外部)","external_total": total, "items": items}
200
 
201
- def suggest_credit_lending_invest(df: pd.DataFrame, ext: dict) -> dict:
202
- def get(lbl):
203
- m = df["入力項目"].eq(lbl);
204
- return df.loc[m,"値"].values[0] if m.any() else ""
205
- monthly_sales = safe_float(get("月商(円)") or get("月商(円)_再掲"))
206
- collateral = safe_float(get("担保余力評価額(円)"))
207
- s3 = safe_float(get("売上_期3(最新期)"))
208
- ext_total = ext.get("external_total", 0.0)
209
- grade = "A" if ext_total>=80 else "B" if ext_total>=65 else "C" if ext_total>=50 else "D"
210
- factor = 1.6 if grade=="A" else 1.3 if grade=="B" else 1.0 if grade=="C" else 0.6
211
- limit_by_sales = (monthly_sales or 0) * factor if monthly_sales else None
212
- limit_by_coll = (collateral or 0) * 0.6 if collateral else None
213
- limits = [v for v in [limit_by_sales, limit_by_coll] if v]
214
- credit_limit = max(0, min(limits)) if limits else (monthly_sales or 0) * 0.8
215
- site = "Net 60" if grade=="A" else "Net 45" if grade=="B" else "Net 30" if grade=="C" else "Prepaid or Net 15"
216
- freq = "半期" if grade in ("A","B") else "四半期" if grade=="C" else "毎月"
217
- loan_months = 6 if grade=="A" else 4 if grade=="B" else 3 if grade=="C" else 1.5
218
- loan_limit = (monthly_sales or 0) * loan_months
219
- term_years = 3 if grade=="A" else 2 if grade=="B" else 1 if grade=="C" else 0.5
220
- interest = 1.2 if grade=="A" else 1.6 if grade=="B" else 2.4 if grade=="C" else 3.5
221
- rev_mult = 1.2 + (ext_total/100)*1.8
222
- est_valuation = (s3 or 0) * rev_mult if s3 else None
223
- invest_reco = "強い投資対象" if grade=="A" else "投資検討" if grade=="B" else "条件付き" if grade=="C" else "見送り推奨"
224
- suggested_ticket = (est_valuation or 0) * (0.02 if grade in ("A","B") else 0.005)
225
- return {
226
- "grade": grade,
227
- "credit": {"recommended_limit_jpy": round(credit_limit or 0), "recommended_terms": site, "monitoring_frequency": freq},
228
- "lending": {"loan_limit_jpy": round(loan_limit or 0), "term_years": term_years, "apr_percent_estimate": interest},
229
- "investment": {"est_valuation_jpy": round(est_valuation or 0), "suggested_ticket_jpy": round(suggested_ticket or 0), "recommendation": invest_reco}
230
- }
231
-
232
- def ai_summary_if_available(df: pd.DataFrame, ext: dict) -> dict:
233
- api_key = os.getenv("OPENAI_API_KEY")
234
- if not api_key: return {"enabled": False, "note": "OPENAI_API_KEY 未設定"}
235
- try:
236
- from openai import OpenAI
237
- client = OpenAI(api_key=api_key)
238
- payload = df.to_dict(orient="records")
239
- prompt = ("以下は企業評価テンプレ(日本語)。欠損は空文字。"
240
- "(1) management/growth/stability/fairness 各0-100点と一言コメント、"
241
- "(2) 総評(3行以内)を JSON で返して。")
242
- resp = client.chat.completions.create(
243
- model="gpt-4o-mini",
244
- messages=[{"role":"system","content":"You are a concise risk analyst."},
245
- {"role":"user","content": prompt+"\n\n"+json.dumps(payload,ensure_ascii=False)}],
246
- temperature=0.2,
247
- )
248
- txt = resp.choices[0].message.content.strip()
249
- m = re.search(r"\{.*\}", txt, re.S)
250
- return {"enabled": True, **(json.loads(m.group()) if m else {"raw": txt})}
251
- except Exception as e:
252
- return {"enabled": False, "error": str(e)[:200]}
253
-
254
- # ========================= PDF抽出(テキスト→OCR フォールバック) =========================
255
- JNUM = r"[0-90-9\-,.\-]+"
256
- def read_text_by_pypdf(pdf_bytes: bytes) -> str:
257
  try:
258
  r = PdfReader(io.BytesIO(pdf_bytes))
259
- texts=[]
260
- for p in r.pages:
261
- try: texts.append(p.extract_text() or "")
262
- except: texts.append("")
263
- return "\n".join(texts)
264
- except Exception:
265
- return ""
266
 
267
- def read_text_by_pdfplumber(pdf_bytes: bytes) -> str:
268
  try:
269
  texts=[]
270
  with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:
271
  for page in pdf.pages:
272
- t = page.extract_text(x_tolerance=2, y_tolerance=2) or ""
273
- texts.append(t)
274
  return "\n".join(texts)
275
- except Exception:
276
- return ""
277
 
278
- def read_text_by_ocr(pdf_bytes: bytes, max_pages: int = 40, dpi: int = 250) -> str:
279
  pages = convert_from_bytes(pdf_bytes, dpi=dpi, fmt="png")
280
  texts=[]
281
- for idx, img in enumerate(pages[:max_pages]):
282
- t = pytesseract.image_to_string(img, lang="jpn+eng")
283
- texts.append(t)
284
  return "\n".join(texts)
285
 
286
  def read_pdf_text(pdf_bytes: bytes, force_ocr: bool, logs: list[str]) -> str:
287
  if force_ocr:
288
- log_append(logs, "OCR(強制)で抽出します。")
289
- return read_text_by_ocr(pdf_bytes)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
 
291
- # まずテキスト方式
292
- text1 = read_text_by_pypdf(pdf_bytes)
293
- text2 = read_text_by_pdfplumber(pdf_bytes)
294
- text = max([text1, text2], key=lambda s: len(s))
295
 
296
- if len(text.strip()) < 200: # 文字数が少なければ画像PDFの可能性が高い
297
- log_append(logs, f"テキスト抽出が希薄({len(text.strip())}文字)。OCRにフォールバックします。")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  try:
299
- return read_text_by_ocr(pdf_bytes)
 
 
 
 
 
 
 
 
 
 
 
 
300
  except Exception as e:
301
- log_append(logs, f"OCR失敗: {e}")
302
- else:
303
- log_append(logs, f"テキスト抽出成功({len(text.strip())}文字)。")
304
- return text
305
 
306
- # ========================= パーサ(精度改善) =========================
307
- # 代表的キーワード辞書
308
  FIELD_HINTS = {
309
- "自己資本比率(%)": ["自己資本比率","自己資本 比率","Equity ratio"],
310
- "現預金(円)": ["現預金","現金及び預金","現金預金","Cash and deposits"],
311
- "月商(円)": ["月商","平均月商","Monthly sales"],
312
- "担保余力評価額(円)": ["担保余力","担保評価","Collateral"],
313
- "売上_期3(最新期)": ["売上高","売上 期3","Net sales"],
314
- "売上_期2": ["売上 期2"],
315
- "売上_期1(最古期)": ["売上 期1"],
316
  "営業利益_期3(最新期)": ["営業利益","Operating income"],
317
- "営業利益_期2": ["営業利益 期2"],
318
- "営業利益_期1(最古期)": ["営業利益 期1"],
319
- "代表者の業界経験��数": ["業界経験","代表者 経験"],
320
- "予実達成率_3年平均(%)": ["予実達成率","予算実績達成率"],
321
- "社外取締役比率(%)": ["社外取締役比率","独立社外取締役"],
322
- "支払遅延件数(直近12ヶ月)": ["支払遅延件数","遅延件数"],
323
- "不渡り件数(直近12ヶ月)": ["不渡り件数","不渡り"],
324
- "平均支払遅延日数": ["平均支払遅延日数","平均遅延日数"],
325
- "借入先数": ["借入先数","金融機関数"],
326
- "メインバンク借入シェア(%)": ["メインバンク借入シェア","メインバンク シェア"],
327
- "主要顧客上位1社売上比率(%)": ["上位1社 売上比率","主要顧客 上位1社"],
328
- "主要顧客上位3社売上比率(%)": ["上位3社 売上比率"],
329
- "主要顧客の平均信用スコア(0-100)": ["顧客 信用スコア","顧客スコア"],
330
- "不良債権件数(直近12ヶ月)": ["不良債権件数","延滞債権件数"],
331
  "利益剰余金(円)": ["利益剰余金","Retained earnings"],
332
- "業歴(年)": ["創業","業歴","沿革"],
333
- }
334
- BOOL_HINTS = {
335
- "倒産歴の有無(TRUE/FALSE)": ["倒産歴","破産歴","倒産"],
336
- "メインバンク明確か(TRUE/FALSE)": ["メインバンク"],
337
- "コミットメントライン等の長期与信枠あり(TRUE/FALSE)": ["コミットメントライン","長期与信枠"],
338
- "有価証券報告書提出企業か(TRUE/FALSE)": ["有価証券報告書","EDINET"],
339
- "決算公告や官報での公開あり(TRUE/FALSE)": ["決算公告","官報"],
340
- "HP/IRサイトで財務資料公開あり(TRUE/FALSE)": ["IRサイト","財務資料 公開","決算短信"],
341
- "直近更新が定め通りか(TRUE/FALSE)": ["更新","直近更新"],
342
- }
343
- COUNT_HINTS = {
344
- "監査・内部統制の重大な不備 件数(過去3年)": ["監査 不備","内部統制 重大"],
345
- "重大コンプライアンス件数(過去3年)": ["重大コンプライアンス","重大 コンプラ"],
346
- "重大事件・事故件数(過去10年)": ["重大事故","重大 事件","重大 インシデント"],
347
  }
348
 
349
- def _first_number_in(s: str) -> float|None:
350
- if not s: return None
351
- s2 = s.replace(",", "").replace(",","").replace("%","%")
352
- m = re.search(r"-?\d+(?:\.\d+)?", s2)
353
- return float(m.group()) if m else None
354
 
355
- def parse_text_to_df(text: str, logs: list[str]) -> pd.DataFrame:
356
- df = get_external_template_df()
357
  lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
358
-
359
- # 高速インデックス(全文検索 → ライン)
360
  joined = "\n".join(lines)
361
-
362
- def find_value_by_keywords(keywords: list[str], prefer_percent=False) -> str|None:
363
- # 1) ダイレクトに近い行を fuzzy で拾う
364
- cand = process.extractOne(
365
- " ".join(keywords), lines,
366
- scorer=fuzz.partial_ratio
367
- )
368
  line = cand[0] if cand and cand[1] >= 80 else None
369
- # 2) 見つからなければ全文から最初の一致
370
  if not line:
371
- for kw in keywords:
372
- m = re.search(rf"{re.escape(kw)}.{0,40}?(-?\d[\d,\.]*\s*%?)", joined)
373
- if m:
374
- line = m.group(0); break
375
- if not line: return None
376
- if prefer_percent:
377
- m = re.search(r"-?\d[\d,\.]*\s*%?", line)
378
- return m.group().replace("%","") if m else None
379
- v = _first_number_in(line)
380
- return str(v) if v is not None else None
381
-
382
- # 数値項目
383
- for field, kws in FIELD_HINTS.items():
384
- prefer_pct = field.endswith("(%)")
385
- v = find_value_by_keywords(kws, prefer_percent=prefer_pct)
386
- if v is not None:
387
- df.loc[df["入力項目"].eq(field),"値"] = v
388
-
389
- # カウント
390
- for field, kws in COUNT_HINTS.items():
391
- v = find_value_by_keywords(kws, prefer_percent=False)
392
- if v is not None:
393
- try: df.loc[df["入力項目"].eq(field),"値"] = str(int(float(v)))
394
- except: pass
395
-
396
- # ブール
397
- for field, kws in BOOL_HINTS.items():
398
- # キーワードがあれば「あり」と仮定(否定語が近傍にあれば無し)
399
- hit = None
400
- for kw in kws:
401
- m = re.search(rf"{re.escape(kw)}.{0,20}", joined)
402
- if m:
403
- frag = m.group(0)
404
- if any(x in frag for x in ["無","なし","無し","No","NO","false","False"]):
405
- hit = "FALSE"
406
- else:
407
- hit = "TRUE"
408
- break
409
- if hit:
410
- df.loc[df["入力項目"].eq(field),"値"] = hit
411
-
412
- log_append(logs, "粗抽出テンプレを作成しました。未充足セルは表で編集してください。")
413
  return df
414
 
415
- # ========================= 推奨まとめの可視化 =========================
416
- import matplotlib
417
- matplotlib.use("Agg")
418
- import matplotlib.pyplot as plt
419
-
420
- def radar_from_items(ext: dict) -> plt.Figure:
421
  by = {}
422
  for it in ext.get("items", []):
423
  by[it["category"]] = by.get(it["category"], 0) + it["score"]
@@ -434,132 +327,146 @@ def radar_from_items(ext: dict) -> plt.Figure:
434
  ax.set_title("カテゴリ別スコア合算")
435
  return fig
436
 
437
- def gauge_total(ext: dict) -> plt.Figure:
438
  total = ext.get("external_total", 0)
439
  fig = plt.figure(figsize=(5,1.2))
440
  ax = fig.add_axes([0.05,0.25,0.9,0.5])
441
  ax.barh([0], [total], height=0.3)
442
- ax.set_xlim(0,100)
443
- ax.set_yticks([]); ax.set_xlabel("総合スコア")
444
- for spine in ax.spines.values(): spine.set_visible(False)
445
- ax.text(total+1,0,str(total), va="center")
446
  return fig
447
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
448
  # ========================= パイプライン =========================
449
- def run_pipeline(filepaths: list[str] | None, company_name: str, force_ocr: bool) -> tuple[pd.DataFrame, dict, dict, str, str, plt.Figure, plt.Figure]:
450
  logs=[]
451
- base_df = get_external_template_df()
452
 
453
- if filepaths:
454
- texts=[]
 
 
 
 
 
455
  for p in filepaths:
456
  with open(p, "rb") as f:
457
  pdf_bytes = f.read()
458
- t = read_pdf_text(pdf_bytes, force_ocr=force_ocr, logs=logs)
459
- texts.append(t)
460
- text = "\n\n".join(texts)
461
- df = parse_text_to_df(text, logs)
462
- # テンプレにマージ(空白以外を反映)
463
- out = base_df.copy()
464
- for _, row in df.iterrows():
465
- m = out["入力項目"].eq(row["入力項目"])
466
- if row["値"] not in ("", None):
467
- out.loc[m,"値"] = row["値"]
468
- df = out
469
- else:
470
- df = base_df.copy()
471
- log_append(logs, "PDF未指定:空テンプレを表示します。")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472
 
473
  ext = score_external_from_df(df)
474
- recs = suggest_credit_lending_invest(df, ext)
475
- ai = ai_summary_if_available(df, ext)
 
 
476
 
477
- result_json = json.dumps({"company": company_name or "", "external_scoring": ext, "recommendations": recs, "ai": ai}, ensure_ascii=False, indent=2)
 
478
  log_text = "\n".join(logs) or "ログなし"
479
- return df, ext, recs, result_json, log_text, radar_from_items(ext), gauge_total(ext)
480
 
481
- def recompute_from_grid(df: pd.DataFrame, company_name: str) -> tuple[pd.DataFrame, dict, dict, str, plt.Figure, plt.Figure]:
482
  ext = score_external_from_df(df)
483
- recs = suggest_credit_lending_invest(df, ext)
484
- ai = ai_summary_if_available(df, ext)
485
- result_json = json.dumps({"company": company_name or "", "external_scoring": ext, "recommendations": recs, "ai": ai}, ensure_ascii=False, indent=2)
486
- return df, ext, recs, result_json, radar_from_items(ext), gauge_total(ext)
 
487
 
488
- # ========================= UI/UX(改善) =========================
489
  theme = gr.themes.Soft()
 
 
490
 
491
- with gr.Blocks(theme=theme, title="企業スコアリング(PDF解析+OCR/ルール/AI)") as demo:
492
- gr.Markdown("### 📊 企業スコアリング(PDF解析 × ルールベース + OpenAI任意)\n1) PDFを投げる → 2) 自動抽出 → 3) 必要箇所を直して再計算")
493
  with gr.Row():
494
  with gr.Column(scale=3):
495
  company = gr.Textbox(label="企業名(任意)", placeholder="例:株式会社〇〇")
496
- force_ocr = gr.Checkbox(label="OCRを強制(スキャンPDF向け/やや遅い)", value=False)
497
- files = gr.File(
498
- label="決算書PDF(複数可)",
499
- file_count="multiple",
500
- file_types=[".pdf"],
501
- type="filepath" # ★ ここを bytes ではなく filepath に固定(以前の Error の主因)
502
- )
503
  run_btn = gr.Button("① PDFを解析してテンプレに反映", variant="primary")
504
  recalc_btn = gr.Button("② この表の値で再計算", variant="secondary")
 
505
  with gr.Column(scale=2):
506
  total_gauge = gr.Plot(label="総合スコア(0-100)")
507
  radar = gr.Plot(label="カテゴリ別レーダー")
508
 
509
  with gr.Tab("テンプレ編集"):
510
- grid = gr.Dataframe(
511
- headers=["カテゴリー","入力項目","値"],
512
- datatype=["str","str","str"],
513
- wrap=True,
514
- row_count=(len(_TEMPLATE_ROWS),"fixed"),
515
- col_count=(3,"fixed"),
516
- interactive=True,
517
- label="抽出結果(編集可)"
518
- )
519
 
520
  with gr.Tab("評価結果(詳細JSON)"):
521
  ext_json = gr.JSON(label="外部スコア")
522
- recs_json = gr.JSON(label="与信/融資/投資 推奨")
523
  json_download = gr.File(label="結果JSONダウンロード", interactive=False)
524
 
525
  with gr.Tab("抽出ログ / デバッグ"):
526
- log_md = gr.Code(label="ログ", language="markdown")
527
 
528
- # ① PDF→解析
529
- def on_run(filepaths, company, force_ocr, progress=gr.Progress()):
530
  try:
531
- progress(0.1, desc="PDF読み込み中…")
532
- df, ext, recs, result_json, log_text, radar_fig, gauge_fig = run_pipeline(filepaths, company, force_ocr)
533
- progress(0.8, desc="スコア計算中…")
534
- # 保存
535
- out = "/tmp/result.json"
536
- with open(out,"w",encoding="utf-8") as f:
537
- f.write(result_json)
538
  progress(1.0, desc="完了")
539
- return (df, ext, recs, gr.File.update(value=out, visible=True), log_text, radar_fig, gauge_fig)
540
  except Exception as e:
541
  tb = traceback.format_exc()
542
- return (get_external_template_df(), {}, {}, gr.File.update(value=None, visible=False), f"Error: {e}\n\n{tb}", plt.figure(), plt.figure())
543
 
544
- run_btn.click(
545
- on_run,
546
- inputs=[files, company, force_ocr],
547
- outputs=[grid, ext_json, recs_json, json_download, log_md, radar, total_gauge]
548
- )
549
 
550
- # ② 再計算
551
  def on_recalc(df, company):
552
- out_df, ext, recs, result_json, radar_fig, gauge_fig = recompute_from_grid(pd.DataFrame(df), company)
553
- out = "/tmp/result.json"
554
- with open(out,"w",encoding="utf-8") as f:
555
- f.write(result_json)
556
- return (out_df, ext, recs, gr.File.update(value=out, visible=True), radar_fig, gauge_fig)
557
-
558
- recalc_btn.click(
559
- on_recalc,
560
- inputs=[grid, company],
561
- outputs=[grid, ext_json, recs_json, json_download, radar, total_gauge]
562
- )
563
 
564
  if __name__ == "__main__":
565
  demo.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT","7860")))
 
1
  from __future__ import annotations
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
+ # ---------- Scoring utils ----------
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
+ # ---------- OpenAI ----------
24
+ from openai import OpenAI
25
+
26
  # ========================= 基本ユーティリティ =========================
27
+ def log(logs: list[str], msg: str):
28
  logs.append(msg)
29
 
30
  def safe_float(x):
31
  try: return float(str(x).replace(",", "").replace("%","%").replace("%","").strip())
32
  except: return None
33
 
34
+ # ========================= テンプレ定義 =========================
35
  _TEMPLATE_ROWS = [
36
  ("経営者能力", "予実達成率_3年平均(%)"),
37
  ("経営者能力", "監査・内部統制の重大な不備 件数(過去3年)"),
 
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
 
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:
 
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
 
 
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
  r = PdfReader(io.BytesIO(pdf_bytes))
180
+ return "\n".join(p.extract_text() or "" for p in r.pages)
181
+ except: return ""
 
 
 
 
 
182
 
183
+ def text_by_pdfplumber(pdf_bytes: bytes) -> str:
184
  try:
185
  texts=[]
186
  with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:
187
  for page in pdf.pages:
188
+ texts.append(page.extract_text(x_tolerance=2, y_tolerance=2) or "")
 
189
  return "\n".join(texts)
190
+ except: return ""
 
191
 
192
+ def text_by_ocr(pdf_bytes: bytes, dpi: int = 220, max_pages: int = 30) -> str:
193
  pages = convert_from_bytes(pdf_bytes, dpi=dpi, fmt="png")
194
  texts=[]
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
  FIELD_HINTS = {
277
+ "自己資本比率(%)": ["自己資本比率","Equity ratio"],
278
+ "現預金(円)": ["現金及び預金","現預金","Cash and deposits"],
279
+ "月商(円)": ["月商","Monthly sales"],
280
+ "担保余力評価額(円)": ["担保余力","Collateral"],
281
+ "売上_期3(最新期)": ["売上高","Net sales"],
 
 
282
  "営業利益_期3(最新期)": ["営業利益","Operating income"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  "利益剰余金(円)": ["利益剰余金","Retained earnings"],
284
+ "業歴(年)": ["創業","沿革","業歴"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
  }
286
 
287
+ def _first_number(s: str) -> str|None:
288
+ s = s.replace(",", "").replace("%","%")
289
+ m = re.search(r"-?\d+(?:\.\d+)?%?", s)
290
+ if not m: return None
291
+ return m.group().replace("%","")
292
 
293
+ def rough_parse_to_df(text: str, logs: list[str]) -> pd.DataFrame:
294
+ df = template_df()
295
  lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
 
 
296
  joined = "\n".join(lines)
297
+ for field, keys in FIELD_HINTS.items():
298
+ # fuzzy
299
+ cand = process.extractOne(" ".join(keys), lines, scorer=fuzz.partial_ratio)
 
 
 
 
300
  line = cand[0] if cand and cand[1] >= 80 else None
 
301
  if not line:
302
+ for kw in keys:
303
+ m = re.search(rf"{re.escape(kw)}.{0,40}?(-?\d[\d,\.%]*)", joined)
304
+ if m: line = m.group(0); break
305
+ if line:
306
+ v = _first_number(line)
307
+ if v is not None:
308
+ df.loc[df["入力項目"].eq(field),"値"] = v
309
+ log(logs, "ローカル抽出(pypdf/pdfplumber/OCR)を実行しました。")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"]
 
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
+ imgs = images_from_pdf(pdf_bytes, dpi=180, max_pages=6)
374
+ part = openai_extract_from_images(imgs, logs)
375
+ ai_map.update(part)
376
+ except Exception as e:
377
+ log(logs, f"OpenAI解析失敗: {e} → ローカル抽出にフォールバック")
378
+ merged += "\n" + read_pdf_text(pdf_bytes, force_ocr, logs)
379
+ else:
380
+ merged += "\n" + read_pdf_text(pdf_bytes, force_ocr, logs)
381
+
382
+ if ai_map:
383
+ log(logs, f"OpenAI抽出で {len([v for v in ai_map.values() if v])} 項目を取得。")
384
+ df = base.copy()
385
+ for k,v in ai_map.items():
386
+ df.loc[df["入力項目"].eq(k),"値"] = v or ""
387
+ # AIで埋まらなかった残りはローカル抽出で補完
388
+ remain = [r for r in df.to_dict("records") if not r["値"]]
389
+ if remain and merged.strip()=="":
390
+ # まだローカル抽出していなければPDF→テキスト
391
+ for p in filepaths:
392
+ with open(p,"rb") as f: merged += "\n" + read_pdf_text(f.read(), force_ocr, logs)
393
+ if merged.strip():
394
+ df_local = rough_parse_to_df(merged, logs)
395
+ for _, row in df_local.iterrows():
396
+ if not df.loc[df["入力項目"].eq(row["入力項目"]),"値"].values[0]:
397
+ df.loc[df["入力項目"].eq(row["入力項目"]),"値"] = row["値"]
398
+ else:
399
+ df = rough_parse_to_df(merged, logs)
400
 
401
  ext = score_external_from_df(df)
402
+ recs = recommend(df, ext)
403
+ result_json = json.dumps({"company": company_name or "", "external_scoring": ext, "recommendations": recs}, ensure_ascii=False, indent=2)
404
+ out_json_path = "/tmp/result.json"
405
+ with open(out_json_path,"w",encoding="utf-8") as f: f.write(result_json)
406
 
407
+ radar = radar_plot(ext)
408
+ gauge = gauge_plot(ext)
409
  log_text = "\n".join(logs) or "ログなし"
410
+ return df, ext, recs, out_json_path, radar, gauge, log_text
411
 
412
+ def recompute(df: pd.DataFrame, company_name: str):
413
  ext = score_external_from_df(df)
414
+ recs = recommend(df, ext)
415
+ out_json_path = "/tmp/result.json"
416
+ with open(out_json_path,"w",encoding="utf-8") as f:
417
+ f.write(json.dumps({"company": company_name or "", "external_scoring": ext, "recommendations": recs}, ensure_ascii=False, indent=2))
418
+ return df, ext, recs, out_json_path, radar_plot(ext), gauge_plot(ext)
419
 
420
+ # ========================= UI =========================
421
  theme = gr.themes.Soft()
422
+ with gr.Blocks(theme=theme, title="企業スコアリング(PDF×AI)") as demo:
423
+ gr.Markdown("### 📊 企業スコアリング(PDF解析 × OpenAI Vision)\nPDFを投入 → AI/ローカルで抽出 → 必要箇所を編集して再計算")
424
 
 
 
425
  with gr.Row():
426
  with gr.Column(scale=3):
427
  company = gr.Textbox(label="企業名(任意)", placeholder="例:株式会社〇〇")
428
+ use_openai = gr.Checkbox(label="OpenAIでPDFをAI解析(Vision)", value=True)
429
+ force_ocr = gr.Checkbox(label="OCRを強制(スキャンPDF向け)", value=False, visible=False)
430
+ files = gr.File(label="決算書PDF(複数可)", file_count="multiple", file_types=[".pdf"], type="filepath")
 
 
 
 
431
  run_btn = gr.Button("① PDFを解析してテンプレに反映", variant="primary")
432
  recalc_btn = gr.Button("② この表の値で再計算", variant="secondary")
433
+
434
  with gr.Column(scale=2):
435
  total_gauge = gr.Plot(label="総合スコア(0-100)")
436
  radar = gr.Plot(label="カテゴリ別レーダー")
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
  demo.launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT","7860")))