Spaces:
Sleeping

Corin1998 commited on
Commit
690d599
·
verified ·
1 Parent(s): 03176b4

Update app/parsers/finstat.py

Browse files
Files changed (1) hide show
  1. app/parsers/finstat.py +79 -63
app/parsers/finstat.py CHANGED
@@ -1,13 +1,13 @@
1
  # app/parsers/finstat.py
2
  from __future__ import annotations
3
- from typing import Dict, Any, List, Tuple, Optional
4
  import re
 
 
5
  import pdfplumber
6
 
7
- from app.llm_reader import llm_parse_financials, _has_openai # LLM抽出
8
-
9
  _UNIT_PAT = re.compile(r"単位[::]\s*(千円|百万円|万円|億円|円)")
10
  _UNIT_MUL = {"円": 1, "千円": 1_000, "万円": 10_000, "百万円": 1_000_000, "億円": 100_000_000}
 
11
  _NUM = re.compile(r"[-+]?\d{1,3}(?:,\d{3})*(?:\.\d+)?")
12
 
13
  _LABELS = {
@@ -31,97 +31,113 @@ _LABELS = {
31
  "employees": [r"従業員(数|人員)"],
32
  }
33
 
34
- def _to_float(s: str) -> Optional[float]:
35
- if s is None: return None
36
- s = str(s)
37
- s = s.replace("▲","-")
38
- m = _NUM.search(s)
39
- if not m: return None
40
- try: return float(m.group(0).replace(",",""))
41
- except Exception: return None
42
-
43
- def _detect_unit(texts: List[str], unit_hint: Optional[str]) -> Tuple[str, int]:
44
  if unit_hint and unit_hint != "自動判定":
45
  return unit_hint, _UNIT_MUL[unit_hint]
46
  joined = "\n".join(texts)
47
  m = _UNIT_PAT.search(joined)
48
  if m:
49
  u = m.group(1)
50
- return u, _UNIT_MUL.get(u,1)
51
- # おおまか推定(数が大きい場合は千円/百万円を仮定)
 
 
 
 
52
  return "百万円", 1_000_000
53
 
54
- def _extract_tables(page) -> List[List[str]]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  out = []
56
- for tbl in (page.extract_tables() or []):
57
- for row in tbl:
58
- out.append([("" if c is None else str(c)).strip() for c in row])
 
 
 
 
 
59
  return out
60
 
61
  def _guess_value(rows: List[List[str]], patterns: List[str]) -> Optional[float]:
 
62
  for r in rows:
63
  for j, cell in enumerate(r):
64
- if any(re.search(p, cell) for p in patterns):
65
- # 右側の数値を優先
66
- for k in range(len(r)-1, j, -1):
67
  v = _to_float(r[k])
68
  if v is not None:
69
  return v
 
70
  return None
71
 
72
- def _scan_text(text: str, patterns: List[str]) -> Optional[float]:
73
- for line in text.splitlines():
74
- for p in patterns:
75
  if re.search(p, line):
76
  v = _to_float(line)
77
- if v is not None: return v
 
78
  return None
79
 
80
- def _parse_rule(pdf_path: str, unit_hint: Optional[str]) -> Dict[str, Any]:
 
 
 
 
 
 
 
81
  texts: List[str] = []
82
- rows: List[List[str]] = []
83
  with pdfplumber.open(pdf_path) as pdf:
84
  for p in pdf.pages:
85
  t = p.extract_text() or ""
86
  texts.append(t)
87
- rows += _extract_tables(p)
 
88
  unit_name, mul = _detect_unit(texts, unit_hint)
89
- joined = "\n".join(texts)
90
- fig = {k: None for k in _LABELS.keys()}
 
 
 
 
 
 
91
  for key, pats in _LABELS.items():
92
- v = _guess_value(rows, pats)
93
  if v is None:
94
- v = _scan_text(joined, pats)
 
95
  fig[key] = None if v is None else v * mul
 
 
96
  if fig.get("ibd") is None:
97
- st = fig.get("st_borrow") or 0
98
- lt = fig.get("lt_borrow") or 0
99
- v = st + lt
100
- fig["ibd"] = v if v>0 else None
101
- return {"unit_name": unit_name, "unit_multiplier": mul, "fig": fig}
 
 
102
 
103
- def parse_financials(
104
- pdf_path: str,
105
- unit_hint: Optional[str] = None,
106
- engine: str = "auto", # "auto" / "LLM" / "ルール"
107
- company_hint: Optional[str] = None,
108
- ) -> Dict[str, Any]:
109
- """
110
- 戻り値: {'unit_name','unit_multiplier','fig': {...(円)}}
111
- """
112
- engine = (engine or "auto").lower()
113
- # 1) 指定LLM
114
- if engine in ("llm","vision"):
115
- return llm_parse_financials(pdf_path, company_hint=company_hint)
116
-
117
- # 2) ルール or 自動
118
- if engine == "ルール":
119
- return _parse_rule(pdf_path, unit_hint)
120
-
121
- # 3) auto: LLM優先 → 失敗時にルール
122
- if _has_openai():
123
- try:
124
- return llm_parse_financials(pdf_path, company_hint=company_hint)
125
- except Exception:
126
- pass
127
- return _parse_rule(pdf_path, unit_hint)
 
1
  # app/parsers/finstat.py
2
  from __future__ import annotations
 
3
  import re
4
+ import io
5
+ from typing import Dict, Any, Tuple, Optional, List
6
  import pdfplumber
7
 
 
 
8
  _UNIT_PAT = re.compile(r"単位[::]\s*(千円|百万円|万円|億円|円)")
9
  _UNIT_MUL = {"円": 1, "千円": 1_000, "万円": 10_000, "百万円": 1_000_000, "億円": 100_000_000}
10
+
11
  _NUM = re.compile(r"[-+]?\d{1,3}(?:,\d{3})*(?:\.\d+)?")
12
 
13
  _LABELS = {
 
31
  "employees": [r"従業員(数|人員)"],
32
  }
33
 
34
+ def _detect_unit(texts: List[str], unit_hint: str | None) -> Tuple[str, int]:
 
 
 
 
 
 
 
 
 
35
  if unit_hint and unit_hint != "自動判定":
36
  return unit_hint, _UNIT_MUL[unit_hint]
37
  joined = "\n".join(texts)
38
  m = _UNIT_PAT.search(joined)
39
  if m:
40
  u = m.group(1)
41
+ return u, _UNIT_MUL.get(u, 1)
42
+ # 数字規模から推定(雑だが実用的)
43
+ hits = _NUM.findall(joined.replace(",", ""))
44
+ # 1,234,567,890 クラスが多ければ円/千円、6桁程度が多ければ百万円想定
45
+ if len(hits) > 50:
46
+ return "千円", 1_000
47
  return "百万円", 1_000_000
48
 
49
+ def _to_float(s: str) -> Optional[float]:
50
+ if s is None:
51
+ return None
52
+ s = str(s)
53
+ m = _NUM.search(s.replace("▲", "-"))
54
+ if not m:
55
+ return None
56
+ try:
57
+ return float(m.group(0).replace(",", ""))
58
+ except Exception:
59
+ return None
60
+
61
+ def _match_label(s: str, patterns: List[str]) -> bool:
62
+ for p in patterns:
63
+ if re.search(p, s):
64
+ return True
65
+ return False
66
+
67
+ def _extract_from_tables(page) -> List[List[str]]:
68
  out = []
69
+ try:
70
+ for tbl in (page.extract_tables() or []):
71
+ for row in tbl:
72
+ if not row:
73
+ continue
74
+ out.append([("" if c is None else str(c)).strip() for c in row])
75
+ except Exception:
76
+ pass
77
  return out
78
 
79
  def _guess_value(rows: List[List[str]], patterns: List[str]) -> Optional[float]:
80
+ # テーブル優先:ラベル列にマッチし、右端 or 直後の数値を拾う
81
  for r in rows:
82
  for j, cell in enumerate(r):
83
+ if any(_match_label(cell, patterns) for _ in patterns):
84
+ # 右側優先
85
+ for k in range(len(r) - 1, j, -1):
86
  v = _to_float(r[k])
87
  if v is not None:
88
  return v
89
+ # 同じ列の下行も探す
90
  return None
91
 
92
+ def _scan_text_for_label(text: str, patterns: List[str]) -> Optional[float]:
93
+ for p in patterns:
94
+ for line in text.splitlines():
95
  if re.search(p, line):
96
  v = _to_float(line)
97
+ if v is not None:
98
+ return v
99
  return None
100
 
101
+ def parse_financials(pdf_path: str, unit_hint: str | None = None) -> Dict[str, Any]:
102
+ """
103
+ 戻り値: {
104
+ 'unit_name': '百万円',
105
+ 'unit_multiplier': 1_000_000,
106
+ 'fig': { 'sales': ..., 'op_profit': ..., ... (円換算)}
107
+ }
108
+ """
109
  texts: List[str] = []
110
+ tables: List[List[List[str]]] = []
111
  with pdfplumber.open(pdf_path) as pdf:
112
  for p in pdf.pages:
113
  t = p.extract_text() or ""
114
  texts.append(t)
115
+ tables.append(_extract_from_tables(p))
116
+
117
  unit_name, mul = _detect_unit(texts, unit_hint)
118
+
119
+ # ページ毎のテーブルを平坦化
120
+ flat_rows: List[List[str]] = [r for page in tables for r in page]
121
+ joined_text = "\n".join(texts)
122
+
123
+ fig: Dict[str, Optional[float]] = {k: None for k in _LABELS.keys()}
124
+
125
+ # 1) テーブルから
126
  for key, pats in _LABELS.items():
127
+ v = _guess_value(flat_rows, pats)
128
  if v is None:
129
+ # 2) テキストから
130
+ v = _scan_text_for_label(joined_text, pats)
131
  fig[key] = None if v is None else v * mul
132
+
133
+ # 有利子負債が分解されていれば合算
134
  if fig.get("ibd") is None:
135
+ v = 0.0
136
+ c = 0
137
+ for k in ("st_borrow", "lt_borrow"):
138
+ if fig.get(k) is not None:
139
+ v += fig[k]
140
+ c += 1
141
+ fig["ibd"] = (v if c else None)
142
 
143
+ return {"unit_name": unit_name, "unit_multiplier": mul, "fig": fig}