Spaces:
Sleeping

Corin1998 commited on
Commit
263d5be
·
verified ·
1 Parent(s): 2136ade

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +371 -385
app.py CHANGED
@@ -1,18 +1,26 @@
1
  from __future__ import annotations
2
- import os, io, re, json, math, typing as T
3
- import pandas as pd
4
  import numpy as np
 
5
  import gradio as gr
6
- from pypdf import PdfReader
7
 
8
- # ========= あなたの評価ロジック(原文ほぼそのまま) =========
9
- from typing import Dict, Any, List, Tuple
10
- __all__ = [
11
- "get_external_template_df",
12
- "fill_missing_with_external",
13
- "score_external_from_df",
14
- ]
15
- _TEMPLATE_ROWS: List[Tuple[str, str]] = [
 
 
 
 
 
 
 
 
 
16
  ("経営者能力", "予実達成率_3年平均(%)"),
17
  ("経営者能力", "監査・内部統制の重大な不備 件数(過去3年)"),
18
  ("経営者能力", "重大コンプライアンス件数(過去3年)"),
@@ -53,38 +61,16 @@ _TEMPLATE_ROWS: List[Tuple[str, str]] = [
53
  ("公平性・総合世評", "HP/IRサイトで財務資料公開あり(TRUE/FALSE)"),
54
  ("公平性・総合世評", "直近更新が定め通りか(TRUE/FALSE)"),
55
  ]
56
-
57
- def get_external_template_df() -> pd.DataFrame:
58
  return pd.DataFrame([(c,i,"") for c,i in _TEMPLATE_ROWS], columns=["カテゴリー","入力項目","値"])
59
 
60
- def fill_missing_with_external(df: pd.DataFrame, company: str = "", country: str = "") -> pd.DataFrame:
61
- # 将来用にフックのみ
62
- return df.copy()
63
-
64
- _WEIGHTS = {
65
- ("経営者能力", "経営姿勢"): 8,
66
- ("経営者能力", "事業経験"): 5,
67
- ("経営者能力", "資産担保力"): 6,
68
- ("経営者能力", "減点事項"): 7,
69
- ("成長率", "売上高伸長性"): 10,
70
- ("成長率", "利益伸長性"): 10,
71
- ("成長率", "商品"): 6,
72
- ("安定性", "自己資本"): 8,
73
- ("安定性", "決済振り"): 10,
74
- ("安定性", "金融取引"): 6,
75
- ("安定性", "資産担保余力"): 6,
76
- ("安定性", "取引先"): 6,
77
- ("安定性", "業歴"): 4,
78
- ("公平性・総合世評", "ディスクロージャー"): 8,
79
- }
80
- _WEIGHT_NORM = 100.0 / float(sum(_WEIGHTS.values()))
81
  def _clamp(v,a,b): return max(a, min(b, v))
82
  def _to_float(x):
83
  if x is None: return None
84
- try:
85
- return float(str(x).replace(",","").replace("▲","-").replace("△","-").replace("%","").strip())
86
- except Exception:
87
- return None
88
  def _to_bool(x):
89
  if x is None: return None
90
  s = str(x).strip().lower()
@@ -104,35 +90,52 @@ def _ramp(x, good, bad, lo=0.0, hi=10.0, neutral=None):
104
  if x >= bad: return lo
105
  if x <= good: return hi
106
  return lo + (hi-lo) * (x-good)/(bad-good)
107
- def score_external_from_df(df: pd.DataFrame) -> Dict[str, Any]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  def ref(label: str):
109
  m = df["入力項目"].eq(label)
110
- return df.loc[m, "値"].values[0] if m.any() else None
111
  items = []
112
- def _add(items, cat, name, raw, weight, reason):
113
  items.append({
114
  "category": cat, "name": name, "raw": round(raw,2),
115
- "weight": round(weight*_WEIGHT_NORM,2),
116
- "score": round((raw/10.0)*weight*_WEIGHT_NORM,2),
117
  "reason": reason
118
  })
119
-
120
- yoy3 = _to_float(ref("予実達成率_3年平均(%)"))
121
- audit_bad = _to_float(ref("監査・内部統制の重大な不備 件数(過去3年)"))
122
- comp_bad = _to_float(ref("重大コンプライアンス件数(過��3年)"))
123
- indep = _to_float(ref("社外取締役比率(%)"))
124
- exp_years = _to_float(ref("代表者の業界経験年数"))
125
- cash = _to_float(ref("現預金(円)"))
126
- sales_m = _to_float(ref("月商(円)"))
127
- collat = _to_float(ref("担保余力評価額(円)"))
128
- has_bk = _to_bool( ref("倒産歴の有無(TRUE/FALSE)") )
129
- bk_years = _to_float(ref("倒産からの経過年数"))
130
- incidents = _to_float(ref("重大事件・事故件数(過去10年)"))
131
-
132
  s1=_to_float(ref("売上_期1(最古期)")); s2=_to_float(ref("売上_期2")); s3=_to_float(ref("売上_期3(最新期)"))
133
  p1=_to_float(ref("営業利益_期1(最古期)")); p2=_to_float(ref("営業利益_期2")); p3=_to_float(ref("営業利益_期3(最新期)"))
134
-
135
- equity = _to_float(ref("自己資本比率(%)"))
136
  delay_cnt=_to_float(ref("支払遅延件数(直近12ヶ月)"))
137
  boun_cnt=_to_float(ref("不渡り件数(直近12ヶ月)"))
138
  delay_days=_to_float(ref("平均支払遅延日数"))
@@ -150,106 +153,167 @@ def score_external_from_df(df: pd.DataFrame) -> Dict[str, Any]:
150
  pub_web=_to_bool(ref("HP/IRサイトで財務資料公開あり(TRUE/FALSE)"))
151
  upd_on=_to_bool(ref("直近更新が定め通りか(TRUE/FALSE)"))
152
 
153
- cash_to_ms = _ratio(cash, sales_m2)
154
- coll_to_ms = _ratio(collat, sales_m2)
155
  def cagr(v1, v3):
156
  if v1 is None or v3 is None or v1 <= 0: return None
157
- try: return (v3/v1)**(1/2) - 1.0
158
- except Exception: return None
 
159
  s_cagr = cagr(s1, s3); p_cagr = cagr(p1, p3)
160
 
161
- # 経営者能力
162
  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
163
- _add(items, "経営者能力", "経営姿勢", mg_att, _WEIGHTS[("経営者能力","経営姿勢")],
164
- f"予実{yoy3 or '—'}%/監査{audit_bad or 0}/違反{comp_bad or 0}/社外{indep or '—'}%")
165
-
166
  mg_exp = _ramp(exp_years if exp_years is not None else 5.0, 15, 0)
167
- _add(items, "経営者能力", "事業経験", mg_exp, _WEIGHTS[("経営者能力","事業経験")], f"経験{exp_years if exp_years is not None else '不明→中立'}年")
168
-
169
  mg_asset = _ramp(cash_to_ms, 1.5, 0.2)
170
- _add(items, "経営者能力", "資産担保力", mg_asset, _WEIGHTS[("経営者能力","資産担保力")], f"現預金/月商≈{round(cash_to_ms,2) if cash_to_ms else '—'}")
171
-
172
- if incidents and incidents>0:
173
- pen=0.0; rs=f"重大事故{int(incidents)}件→大幅減点"
174
- elif has_bk:
175
- pen=6.0 if (bk_years and bk_years>=10) else 3.0
176
- rs=f"倒産歴あり({bk_years or '不明'}年)"
177
- else:
178
- pen=10.0; rs="事故/倒産なし"
179
- _add(items,"経営者能力","減点事項",pen,_WEIGHTS[("経営者能力","減点事項")],rs)
180
-
181
- # 成長率
182
- _add(items,"成長率","売上高伸長性", _ramp(s_cagr,0.08,-0.05), _WEIGHTS[("成長率","売上高伸長性")], f"CAGR売上{round((s_cagr or 0)*100,1) if s_cagr is not None else '—'}%")
183
- _add(items,"成長率","利益伸長性", _ramp(p_cagr,0.08,-0.05), _WEIGHTS[("成長率","利益伸長性")], f"CAGR営業{round((p_cagr or 0)*100,1) if p_cagr is not None else '—'}%")
184
- _add(items,"成長率","商品", 5.0, _WEIGHTS[("成長率","商品")], "不明→中立")
185
-
186
- # 安定性
187
- _add(items,"安定性","自己資本", _ramp(equity,40,5), _WEIGHTS[("安定性","自己資本")], f"自己資本比率{equity or '—'}%")
188
  if delay_cnt is not None or boun_cnt is not None or delay_days is not None:
189
  sc=( _ramp(- (delay_cnt or 0),0,-6) + _ramp(- (boun_cnt or 0),0,-1) + _ramp(- (delay_days or 0),0,-30) )/3
190
  rs=f"遅延{int(delay_cnt or 0)}/不渡{int(boun_cnt or 0)}/平均{int(delay_days or 0)}日"
191
  else:
192
  sc=_ramp(cash_to_ms,1.0,0.2); rs=f"代理:現預金/月商≈{round(cash_to_ms,2) if cash_to_ms else '—'}"
193
- _add(items,"安定性","決済振り", sc, _WEIGHTS[("安定性","決済振り")], rs)
194
-
195
- sc_mb = 5.0
196
- sc_mb += 2.0 if mainbank else -0.5 if mainbank is False else 0
197
- sc_mb += 1.0 if has_line else 0
198
  sc_mb = _clamp(sc_mb,0,10)
199
- _add(items,"安定性","金融取引", sc_mb, _WEIGHTS[("安定性","金融取引")],
200
  f"メイン{'有' if mainbank else '無' if mainbank is False else '—'}/与信枠{'有' if has_line else '無' if has_line is False else '—'}")
201
-
202
- _add(items,"安定性","資産担保余力", _ramp(coll_to_ms,4.0,0.0), _WEIGHTS[("安定性","資産担保余力")], f"担保/月商≈{round(coll_to_ms,2) if coll_to_ms else '—'}")
203
- _add(items,"安定性","取引先", ( _ramp(- (top1 or 50),0,-80) + _ramp(cust_score,80,50) + _ramp(- (npl_cnt or 1),0,-3) )/3,
204
  _WEIGHTS[("安定性","取引先")], f"上位1社{top1 or '—'}%/信用{cust_score or '—'}/不良{int(npl_cnt or 0)}")
205
- _add(items,"安定性","業歴", _ramp(years,20,1), _WEIGHTS[("安定性","業歴")], f"{years or '—'}年")
206
-
207
- # 公平性
208
- sc_dis = 0.0
209
- sc_dis += 10.0 if has_sec else 7.0 if (pub_off or pub_web) else 4.0
210
- if upd_on: sc_dis += 1.0
211
  sc_dis = _clamp(sc_dis,0,10)
212
- _add(items,"公平性・総合世評","ディスクロージャー", sc_dis, _WEIGHTS[("公平性・総合世評","ディスクロージャー")],
213
  f"{'有報' if has_sec else '公開あり' if (pub_off or pub_web) else '公開乏しい'} / 更新{'◯' if upd_on else '—'}")
214
-
215
  total = round(sum(x["score"] for x in items),1)
216
- return {"name":"企業評価(外部)","external_total": total, "items": items,
217
- "notes":"欠損は中立、連続スコア×重み(自動正規化)"}
218
 
219
- # ========= PDF → DataFrame 粗抽出(編集前提) =========
220
- JNUM = r"[-−–]?\s?\d{1,3}(?:,\d{3})*(?:\.\d+)?"
221
- PCT = rf"{JNUM}\s*%"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
 
223
- def _first_num(s: str) -> T.Optional[float]:
224
- if s is None: return None
225
- m = re.search(rf"{JNUM}", s.replace(",", ""))
226
- if m:
227
- try:
228
- return float(m.group().replace(",", "").replace("−","-").replace("–","-").strip())
229
- except Exception:
230
- return None
231
- return None
 
 
 
 
 
 
 
 
 
 
 
 
232
 
233
- def read_pdf_text(pdf_bytes: bytes) -> str:
234
- r = PdfReader(io.BytesIO(pdf_bytes))
235
- texts = []
236
- for p in r.pages:
237
- try:
238
- texts.append(p.extract_text() or "")
239
- except Exception:
240
- texts.append("")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  return "\n".join(texts)
242
 
243
- # ラベル → キーワード(簡易)
244
- FIELD_HINTS: dict[str,list[str]] = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  "自己資本比率(%)": ["自己資本比率","自己資本 比率","Equity ratio"],
246
  "現預金(円)": ["現預金","現金及び預金","現金預金","Cash and deposits"],
247
  "月商(円)": ["月商","平均月商","Monthly sales"],
248
  "担保余力評価額(円)": ["担保余力","担保評価","Collateral"],
249
- "売上_期3(最新期)": ["売上高","売上 期3","売上(最新)","Net sales"],
250
  "売上_期2": ["売上 期2"],
251
- "売上_期1(最古期)": ["売上 期1","売上(最古)"],
252
- "営業利益_期3(最新期)": ["営業利益","営業利益 期3","Operating income"],
253
  "営業利益_期2": ["営業利益 期2"],
254
  "営業利益_期1(最古期)": ["営業利益 期1"],
255
  "代表者の業界経験年数": ["業界経験","代表者 経験"],
@@ -261,13 +325,13 @@ FIELD_HINTS: dict[str,list[str]] = {
261
  "借入先数": ["借入先数","金融機関数"],
262
  "メインバンク借入シェア(%)": ["メインバンク借入シェア","メインバンク シェア"],
263
  "主要顧客上位1社売上比率(%)": ["上位1社 売上比率","主要顧客 上位1社"],
264
- "主要顧客上位3社売上比率(%)": ["上位3社 売上比率","主要顧客 上位3社"],
265
  "主要顧客の平均信用スコア(0-100)": ["顧客 信用スコア","顧客スコア"],
266
  "不良債権件数(直近12ヶ月)": ["不良債権件数","延滞債権件数"],
267
  "利益剰余金(円)": ["利益剰余金","Retained earnings"],
268
- "業歴(年)": ["創業","業歴"],
269
  }
270
- BOOL_HINTS: dict[str,list[str]] = {
271
  "倒産歴の有無(TRUE/FALSE)": ["倒産歴","破産歴","倒産"],
272
  "メインバンク明確か(TRUE/FALSE)": ["メインバンク"],
273
  "コミットメントライン等の長期与信枠あり(TRUE/FALSE)": ["コミットメントライン","長期与信枠"],
@@ -276,304 +340,226 @@ BOOL_HINTS: dict[str,list[str]] = {
276
  "HP/IRサイトで財務資料公開あり(TRUE/FALSE)": ["IRサイト","財務資料 公開","決算短信"],
277
  "直近更新が定め通りか(TRUE/FALSE)": ["更新","直近更新"],
278
  }
279
- COUNT_HINTS: dict[str,list[str]] = {
280
  "監査・内部統制の重大な不備 件数(過去3年)": ["監査 不備","内部統制 重大"],
281
  "重大コンプライアンス件数(過去3年)": ["重大コンプライアンス","重大 コンプラ"],
282
  "重大事件・事故件数(過去10年)": ["重大事故","重大 事件","重大 インシデント"],
283
  }
284
 
285
- def parse_text_to_df(text: str) -> pd.DataFrame:
 
 
 
 
 
 
286
  df = get_external_template_df()
287
- lines = text.splitlines()
288
 
289
- def find_first_by_keywords(keywords: list[str]) -> str|None:
290
- for kw in keywords:
291
- for ln in lines:
292
- if kw in ln:
293
- return ln
294
- return None
295
 
296
- # 数値
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
  for field, kws in FIELD_HINTS.items():
298
- ln = find_first_by_keywords(kws)
299
- if ln:
300
- if field.endswith("(%)"):
301
- m = re.search(PCT, ln.replace("%","%"))
302
- val = None
303
- if m: val = m.group().replace("%","")
304
- else: val = _first_num(ln)
305
- else:
306
- val = _first_num(ln)
307
- if val is not None:
308
- df.loc[df["入力項目"].eq(field),"値"] = str(val)
309
 
310
  # カウント
311
  for field, kws in COUNT_HINTS.items():
312
- ln = find_first_by_keywords(kws)
313
- if ln:
314
- val = _first_num(ln) or 0
315
- df.loc[df["入力項目"].eq(field),"値"] = str(int(val))
316
 
317
  # ブール
318
  for field, kws in BOOL_HINTS.items():
319
- ln = find_first_by_keywords(kws)
320
- if ln:
321
- v = "TRUE" if any(s in ln for s in ["有","あり","Yes","YES","true","True"]) and not ("無" in ln or "なし" in ln) else ""
322
- if v:
323
- df.loc[df["入力項目"].eq(field),"値"] = v
324
-
 
 
 
 
 
 
 
 
 
325
  return df
326
 
327
- # ========= 与信/融資/投資のルールベース提案 =========
328
- def safe_float(x):
329
- try:
330
- return float(str(x).replace(",",""))
331
- except:
332
- return None
333
-
334
- def suggest_credit_lending_invest(df: pd.DataFrame, ext: dict) -> dict:
335
- def get(lbl):
336
- m = df["入力項目"].eq(lbl);
337
- return df.loc[m,"値"].values[0] if m.any() else ""
338
-
339
- monthly_sales = safe_float(get("月商(円)") or get("月商(円)_再掲"))
340
- cash = safe_float(get("現預金(円)"))
341
- collateral = safe_float(get("担保余力評価額(円)"))
342
- equity_pct = safe_float(get("自己資本比率(%)"))
343
- s3 = safe_float(get("売上_期3(最新期)"))
344
- p3 = safe_float(get("営業利益_期3(最新期)"))
345
- top1 = safe_float(get("主要顧客上位1社売上比率(%)"))
346
- years = safe_float(get("業歴(年)"))
347
-
348
- ext_total = ext.get("external_total", 0.0)
349
- # リスクグレード(A〜D)
350
- if ext_total >= 80: grade="A"
351
- elif ext_total >= 65: grade="B"
352
- elif ext_total >= 50: grade="C"
353
- else: grade="D"
354
-
355
- # 与信限度額:月商×係数 と 担保余力の一部 の小さい方
356
- factor = 1.6 if grade=="A" else 1.3 if grade=="B" else 1.0 if grade=="C" else 0.6
357
- limit_by_sales = (monthly_sales or 0) * factor if monthly_sales else None
358
- limit_by_coll = (collateral or 0) * 0.6 if collateral else None
359
-
360
- limits = [v for v in [limit_by_sales, limit_by_coll] if v]
361
- credit_limit = max(0, min(limits)) if limits else (monthly_sales or 0) * 0.8
362
-
363
- # サイト(支払条件)
364
- if grade=="A": site="Net 60"
365
- elif grade=="B": site="Net 45"
366
- elif grade=="C": site="Net 30"
367
- else: site="Prepaid or Net 15"
368
-
369
- # モニタリング頻度
370
- freq = "半期" if grade in ("A","B") else "四半期" if grade=="C" else "毎月"
371
-
372
- # 融資:上限=月商の3〜6ヶ月目安(グレードで変動)。金利と期間もグレード連動。
373
- loan_months = 6 if grade=="A" else 4 if grade=="B" else 3 if grade=="C" else 1.5
374
- loan_limit = (monthly_sales or 0) * loan_months
375
- term_years = 3 if grade=="A" else 2 if grade=="B" else 1 if grade=="C" else 0.5
376
- interest = 1.2 if grade=="A" else 1.6 if grade=="B" else 2.4 if grade=="C" else 3.5 # 想定実質年率(%)の目安
377
-
378
- # 投資:簡易評価額(売上倍率×売上)。倍率は成長と安定から。
379
- rev_mult = 1.2 + (ext_total/100)*1.8 # 1.2〜3.0倍
380
- est_valuation = (s3 or 0) * rev_mult if s3 else None
381
- invest_reco = "強い投資対象" if grade=="A" else "投資検討" if grade=="B" else "条件付き" if grade=="C" else "見送り推奨"
382
- suggested_ticket = (est_valuation or 0) * (0.02 if grade in ("A","B") else 0.005)
383
 
384
- return {
385
- "grade": grade,
386
- "credit": {
387
- "evaluation": f"総合{grade}",
388
- "recommended_limit_jpy": round(credit_limit) if credit_limit else 0,
389
- "recommended_terms": site,
390
- "monitoring_frequency": freq,
391
- },
392
- "lending": {
393
- "loan_limit_jpy": round(loan_limit) if loan_limit else 0,
394
- "term_years": term_years,
395
- "apr_percent_estimate": interest,
396
- "borrower_rating": grade
397
- },
398
- "investment": {
399
- "est_valuation_jpy": round(est_valuation) if est_valuation else 0,
400
- "suggested_ticket_jpy": round(suggested_ticket) if suggested_ticket else 0,
401
- "recommendation": invest_reco
402
- }
403
- }
404
 
405
- # ========= OpenAI(任意)でのサマリー採点 =========
406
- def ai_summary_if_available(df: pd.DataFrame, ext: dict) -> dict:
407
- api_key = os.getenv("OPENAI_API_KEY")
408
- if not api_key:
409
- return {"enabled": False, "note": "OPENAI_API_KEY 未設定のためルールベースのみで評価しました。"}
410
- try:
411
- from openai import OpenAI
412
- client = OpenAI(api_key=api_key)
413
- # 入力を軽量JSON化
414
- payload = df.to_dict(orient="records")
415
- prompt = (
416
- "以下は企業の評価入力テンプレート(日本語ラベル)です。"
417
- "欠損は空文字。これを踏まえ、(1)管理者能力/成長率/安定性/公平性の4カテゴリに対して0-100点のAI採点と一言コメント、"
418
- "(2)総評(3行以内)、のみをJSONで返してください。"
419
- "キー: categories: {management,growth,stability,fairness}, each {score,comment}, overall {summary} "
420
- "日本語で簡潔に。"
421
- )
422
- resp = client.chat.completions.create(
423
- model="gpt-4o-mini",
424
- messages=[
425
- {"role":"system","content":"You are a concise risk analyst."},
426
- {"role":"user","content": prompt + "\n\n" + json.dumps(payload, ensure_ascii=False)}
427
- ],
428
- temperature=0.2,
429
- )
430
- txt = resp.choices[0].message.content.strip()
431
- # JSON抽出(ガード)
432
- m = re.search(r"\{.*\}", txt, re.S)
433
- ai = json.loads(m.group()) if m else {"raw": txt}
434
- ai["enabled"] = True
435
- return ai
436
- except Exception as e:
437
- return {"enabled": False, "error": str(e)[:200]}
438
 
439
- # ========= Gradio UI ロジック =========
440
- def run_pipeline(files: list[gr.File] | None, company_name: str) -> tuple[pd.DataFrame, dict, dict, str]:
441
- # 1) テンプレ作成
442
  base_df = get_external_template_df()
443
 
444
- # 2) PDFテキスト抽出 → 粗パース → テンプレに流し込み
445
- if files:
446
- merged_texts = []
447
- for f in files:
448
- try:
449
  pdf_bytes = f.read()
450
- except Exception:
451
- with open(f.name,"rb") as rf:
452
- pdf_bytes = rf.read()
453
- merged_texts.append(read_pdf_text(pdf_bytes))
454
- text = "\n\n".join(merged_texts)
455
- parsed_df = parse_text_to_df(text)
456
- # 空欄はそのまま残す(後でUIで編集可能)
457
- df = base_df.copy()
458
- for _, row in parsed_df.iterrows():
459
- m = df["入力項目"].eq(row["入力項目"])
460
  if row["値"] not in ("", None):
461
- df.loc[m,"値"] = row["値"]
 
462
  else:
463
  df = base_df.copy()
 
464
 
465
- # 3) 外部スコア
466
  ext = score_external_from_df(df)
467
-
468
- # 4) 与信/融資/投資(ルールベース)
469
  recs = suggest_credit_lending_invest(df, ext)
470
-
471
- # 5) AI要約(任意)
472
  ai = ai_summary_if_available(df, ext)
473
 
474
- # 6) JSON 出力文字列
475
- out_json = json.dumps({
476
- "company": company_name or "",
477
- "external_scoring": ext,
478
- "recommendations": recs,
479
- "ai": ai
480
- }, ensure_ascii=False, indent=2)
481
-
482
- return df, ext, recs, out_json
483
 
484
- def recompute_from_grid(df: pd.DataFrame, company_name: str) -> tuple[pd.DataFrame, dict, dict, str]:
485
- # DataFrame(編集後)をそのまま採点
486
- df = df.copy()
487
  ext = score_external_from_df(df)
488
  recs = suggest_credit_lending_invest(df, ext)
489
  ai = ai_summary_if_available(df, ext)
490
- out_json = json.dumps({
491
- "company": company_name or "",
492
- "external_scoring": ext,
493
- "recommendations": recs,
494
- "ai": ai
495
- }, ensure_ascii=False, indent=2)
496
- return df, ext, recs, out_json
497
-
498
- # 簡易レーダー(matplotlib)
499
- import matplotlib
500
- matplotlib.use("Agg")
501
- import matplotlib.pyplot as plt
502
- def radar_from_items(ext: dict) -> plt.Figure:
503
- # カテゴリ合算
504
- by = {}
505
- for it in ext["items"]:
506
- by[it["category"]] = by.get(it["category"], 0) + it["score"]
507
- labels = list(by.keys())
508
- vals = [by[k] for k in labels]
509
- if not labels:
510
- labels = ["経営者能力","成長率","安定性","公平性"]
511
- vals = [0,0,0,0]
512
- # レーダー
513
- N = len(labels)
514
- angles = np.linspace(0, 2*np.pi, N, endpoint=False).tolist()
515
- vals += vals[:1]
516
- angles += angles[:1]
517
- fig = plt.figure(figsize=(5,5))
518
- ax = plt.subplot(111, polar=True)
519
- ax.plot(angles, vals, linewidth=2)
520
- ax.fill(angles, vals, alpha=0.25)
521
- ax.set_thetagrids(np.degrees(angles[:-1]), labels, fontsize=10)
522
- ax.set_title("カテゴリ別スコア(合算)")
523
- return fig
524
 
525
- # ========= Gradio UI =========
526
- with gr.Blocks(title="企業スコアリング(PDF→評価)") as demo:
527
- gr.Markdown("## 企業スコアリング(PDF解析 × ルールベース+OpenAI任意)")
528
  with gr.Row():
529
- company = gr.Textbox(label="企業名(任意)", placeholder="例:株式会社〇〇")
530
- files = gr.File(file_count="multiple", file_types=[".pdf"], label="決算書PDFをアップロード")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
 
532
- run_btn = gr.Button("① PDFを解析してテンプレに反映")
533
- grid = gr.Dataframe(headers=["カテゴリー","入力項目","値"], datatype=["str","str","str"],
534
- wrap=True, row_count=(len(_TEMPLATE_ROWS), "fixed"), col_count=(3,"fixed"), label="編集可能テンプレート")
 
535
 
536
- with gr.Row():
537
- recalc_btn = gr.Button("② この表で採点・評価を再計算", variant="primary")
538
- dl_json = gr.File(label="結果JSONダウンロード", interactive=False)
539
-
540
- with gr.Tab("外部スコア結果"):
541
- ext_json = gr.JSON(label="外部スコア(詳細)")
542
- chart = gr.Plot(label="カテゴリ別レーダー")
543
-
544
- with gr.Tab("与信/融資/投資 推奨"):
545
- recs_json = gr.JSON(label="推奨(与信/融資/投資)")
546
-
547
- # ① PDF→テンプレ反映&採点
548
- def handle_run(files, company):
549
- df, ext, recs, out_json = run_pipeline(files, company)
550
- # ダウンロード用ファイルを書く
551
- path = "/tmp/result.json"
552
- with open(path,"w",encoding="utf-8") as f:
553
- f.write(out_json)
554
- fig = radar_from_items(ext)
555
- return df, ext, recs, gr.File.update(value=path, visible=True), fig
556
 
557
  run_btn.click(
558
- handle_run,
559
- inputs=[files, company],
560
- outputs=[grid, ext_json, recs_json, dl_json, chart]
561
  )
562
 
563
- # ② 表を直接編集して再計算
564
- def handle_recalc(df, company):
565
- out_df, ext, recs, out_json = recompute_from_grid(pd.DataFrame(df), company)
566
- path = "/tmp/result.json"
567
- with open(path,"w",encoding="utf-8") as f:
568
- f.write(out_json)
569
- fig = radar_from_items(ext)
570
- return out_df, ext, recs, gr.File.update(value=path, visible=True), fig
571
 
572
  recalc_btn.click(
573
- handle_recalc,
574
  inputs=[grid, company],
575
- outputs=[grid, ext_json, recs_json, dl_json, chart]
576
  )
577
 
578
  if __name__ == "__main__":
579
- 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, 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年)"),
26
  ("経営者能力", "重大コンプライアンス件数(過去3年)"),
 
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
72
+ try: return float(str(x).replace(",","").replace("▲","-").replace("△","-").replace("%","").strip())
73
+ except: return None
 
 
74
  def _to_bool(x):
75
  if x is None: return None
76
  s = str(x).strip().lower()
 
90
  if x >= bad: return lo
91
  if x <= good: return hi
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
+
112
+ 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("平均支払遅延日数"))
 
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
  "代表者の業界経験年数": ["業界経験","代表者 経験"],
 
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)": ["コミットメントライン","長期与信枠"],
 
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"]
424
+ labels = list(by.keys()) or ["経営者能力","成長率","安定性","公平性"]
425
+ vals = [by.get(k,0) for k in labels]
426
+ N=len(labels)
427
+ angles = np.linspace(0, 2*np.pi, N, endpoint=False).tolist()
428
+ vals += vals[:1]; angles += angles[:1]
429
+ fig = plt.figure(figsize=(5,5))
430
+ ax = plt.subplot(111, polar=True)
431
+ ax.plot(angles, vals, linewidth=2)
432
+ ax.fill(angles, vals, alpha=0.25)
433
+ ax.set_thetagrids(np.degrees(angles[:-1]), labels, fontsize=10)
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")))