Spaces:
Sleeping

Corin1998 commited on
Commit
f048e16
·
verified ·
1 Parent(s): 81af755

Upload llm_extract.py

Browse files
Files changed (1) hide show
  1. llm_extract.py +132 -92
llm_extract.py CHANGED
@@ -9,10 +9,8 @@ from pydantic import ValidationError
9
 
10
  from schemas import FinancialExtract, MultipleSuggestion
11
 
12
-
13
  VISION_MODEL = os.environ.get("OPENAI_VISION_MODEL", "gpt-4o-mini")
14
- TEXT_MODEL = os.environ.get("OPENAI_TEXT_MODEL", "gpt-4o-mini")
15
-
16
 
17
  def get_client() -> OpenAI:
18
  key = os.environ.get("OPENAI_API_KEY")
@@ -20,145 +18,187 @@ def get_client() -> OpenAI:
20
  raise RuntimeError("OPENAI_API_KEY が未設定です。Spaces → Settings → Variables and secrets で追加してください。")
21
  return OpenAI(api_key=key, timeout=120)
22
 
23
-
24
  def upload_file_to_openai(client: OpenAI, filename: str, file_bytes: bytes) -> str:
25
  """Upload file bytes to OpenAI Files API and return file_id."""
26
  from io import BytesIO
27
  bio = BytesIO(file_bytes)
28
- # Prefer 'vision', fallback to 'assistants' for SDK compatibility
29
  try:
30
- f = client.files.create(file=("uploaded", bio), purpose="vision")
31
  except Exception:
32
- f = client.files.create(file=("uploaded", bio), purpose="assistants")
 
33
  return f.id
34
 
35
-
36
  def _financial_schema_json():
37
- # Pydantic -> JSON Schema
38
  return FinancialExtract.model_json_schema()
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- def extract_financials_from_files(client: OpenAI, file_ids: List[str], company_hint: Optional[str],
42
- currency_hint: Optional[str], model: str = VISION_MODEL,
43
- debug: bool = False) -> FinancialExtract:
44
- """Use vision model to read statements and produce normalized financials (latest + previous)."""
45
  system = (
46
  "You are a meticulous financial analyst. Read the provided financial statement files "
47
  "and extract the latest two fiscal periods' key items with units normalized to the statement currency. "
48
- "If multiple statements exist, prefer consolidated figures. "
49
- "Return strictly valid JSON that conforms to the provided JSON schema. "
50
- "If any item is missing, set it to null rather than guessing."
51
  )
52
- user_text = (
53
  "Extract the company name, currency, fiscal year end, and the latest two periods' numbers "
54
  "(revenue, COGS, EBIT, depreciation, EBITDA, net income, cash, receivables, inventory, payables, "
55
  "current assets, current liabilities, total assets, total equity, total debt, interest expense). "
56
- "If both annual and quarterly are present, prefer annual. "
57
- "Do not compute new numbers except EBITDA = EBIT + depreciation when both are available."
58
  )
59
  if company_hint:
60
- user_text += f"\nCompany hint: {company_hint}"
61
  if currency_hint:
62
- user_text += f"\nCurrency hint: {currency_hint}"
63
-
64
- # Using the Responses API with Structured Outputs JSON schema
65
- resp = client.responses.create(
66
- model=model,
67
- input=[
68
- {
69
- "role": "system",
70
- "content": [{"type": "input_text", "text": system}],
71
- },
72
- {
73
- "role": "user",
74
- "content": [{"type": "input_text", "text": user_text}] + [
75
- {"type": "input_file", "file_id": fid} for fid in file_ids
76
- ],
77
- },
78
- ],
79
- response_format={
80
- "type": "json_schema",
81
- "json_schema": {
82
- "name": "FinancialExtract",
83
- "schema": _financial_schema_json(),
84
- "strict": True,
85
- },
86
- },
87
- max_output_tokens=2048,
88
- )
89
 
 
90
  try:
91
- raw = resp.output_text
92
- except Exception:
93
- try:
94
- raw = resp.output[0].content[0].text
95
- except Exception:
96
- raw = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
  if not raw:
99
  raise RuntimeError("LLMからの応答が空でした。")
100
 
 
101
  try:
102
  data = json.loads(raw)
103
- except json.JSONDecodeError as e:
104
- if not debug:
105
- raw2 = raw.strip()
106
- if raw2.startswith("```"):
107
- raw2 = raw2.strip("`").split("\n", 1)[-1]
108
- data = json.loads(raw2)
109
- else:
110
- raise
111
 
 
112
  try:
113
- extract = FinancialExtract.model_validate(data)
114
  except ValidationError as ve:
115
  raise RuntimeError(f"構造化出力の検証に失敗: {ve}")
116
 
117
- return extract
118
-
119
-
120
- def suggest_multiples_with_llm(client: OpenAI, text_model: str, industry: str, region: str = "JP", debug: bool = False) -> Optional[MultipleSuggestion]:
121
- """Ask a small text model to propose reasonable valuation multiples for the given industry/region."""
 
 
 
122
  if not industry:
123
  return None
124
 
125
  system = "You are an equity analyst. Provide conservative valuation multiple estimates for the given industry and region."
126
  user = (
127
  f"Industry: {industry}\nRegion: {region}\n"
128
- "Return a short JSON with keys: revenue_multiple (float), ebitda_multiple (float). "
129
- "Use public-market small/mid-cap ranges where applicable and be conservative."
130
- )
131
-
132
- resp = client.responses.create(
133
- model=text_model,
134
- input=[
135
- {"role": "system", "content": [{"type": "input_text", "text": system}]},
136
- {"role": "user", "content": [{"type": "input_text", "text": user}]},
137
- ],
138
- response_format={
139
- "type": "json_schema",
140
- "json_schema": {
141
- "name": "MultipleSuggestion",
142
- "schema": MultipleSuggestion.model_json_schema(),
143
- "strict": True,
144
- },
145
- },
146
- max_output_tokens=200,
147
  )
148
 
 
149
  try:
150
- raw = resp.output_text
151
- except Exception:
152
- try:
153
- raw = resp.output[0].content[0].text
154
- except Exception:
155
- raw = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
 
157
  if not raw:
158
  return None
159
 
160
  try:
161
  data = json.loads(raw)
 
 
 
 
162
  return MultipleSuggestion.model_validate(data)
163
  except Exception:
164
  if debug:
 
9
 
10
  from schemas import FinancialExtract, MultipleSuggestion
11
 
 
12
  VISION_MODEL = os.environ.get("OPENAI_VISION_MODEL", "gpt-4o-mini")
13
+ TEXT_MODEL = os.environ.get("OPENAI_TEXT_MODEL", "gpt-4o-mini")
 
14
 
15
  def get_client() -> OpenAI:
16
  key = os.environ.get("OPENAI_API_KEY")
 
18
  raise RuntimeError("OPENAI_API_KEY が未設定です。Spaces → Settings → Variables and secrets で追加してください。")
19
  return OpenAI(api_key=key, timeout=120)
20
 
 
21
  def upload_file_to_openai(client: OpenAI, filename: str, file_bytes: bytes) -> str:
22
  """Upload file bytes to OpenAI Files API and return file_id."""
23
  from io import BytesIO
24
  bio = BytesIO(file_bytes)
 
25
  try:
26
+ f = client.files.create(file=(filename or "uploaded", bio), purpose="vision")
27
  except Exception:
28
+ # ゲートウェイによっては "assistants" のみ許可されている場合がある
29
+ f = client.files.create(file=(filename or "uploaded", bio), purpose="assistants")
30
  return f.id
31
 
 
32
  def _financial_schema_json():
 
33
  return FinancialExtract.model_json_schema()
34
 
35
+ def _safe_get_output_text(resp) -> str:
36
+ """SDK差異を吸収してテキスト本文を取り出す"""
37
+ try:
38
+ return resp.output_text
39
+ except Exception:
40
+ try:
41
+ return resp.output[0].content[0].text
42
+ except Exception:
43
+ return ""
44
+
45
+ def _strip_code_fences(s: str) -> str:
46
+ s2 = s.strip()
47
+ if s2.startswith("```"):
48
+ s2 = s2.strip("`")
49
+ if "\n" in s2:
50
+ s2 = s2.split("\n", 1)[-1]
51
+ if s2.endswith("```"):
52
+ s2 = s2[:-3]
53
+ return s2.strip()
54
+
55
+ def extract_financials_from_files(
56
+ client: OpenAI,
57
+ file_ids: List[str],
58
+ company_hint: Optional[str],
59
+ currency_hint: Optional[str],
60
+ model: str = VISION_MODEL,
61
+ debug: bool = False,
62
+ ) -> FinancialExtract:
63
+ """Visionで決算書を読み、最新2期の標準化数値を返す。`response_format` 非対応環境でも動くようフォールバック。"""
64
+ schema = _financial_schema_json()
65
 
 
 
 
 
66
  system = (
67
  "You are a meticulous financial analyst. Read the provided financial statement files "
68
  "and extract the latest two fiscal periods' key items with units normalized to the statement currency. "
69
+ "Prefer consolidated and annual figures when both are present."
 
 
70
  )
71
+ base_user = (
72
  "Extract the company name, currency, fiscal year end, and the latest two periods' numbers "
73
  "(revenue, COGS, EBIT, depreciation, EBITDA, net income, cash, receivables, inventory, payables, "
74
  "current assets, current liabilities, total assets, total equity, total debt, interest expense). "
75
+ "Return STRICT JSON ONLY, no prose or code fences."
 
76
  )
77
  if company_hint:
78
+ base_user += f"\nCompany hint: {company_hint}"
79
  if currency_hint:
80
+ base_user += f"\nCurrency hint: {currency_hint}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
+ # まずは Structured Outputs(JSON Schema) を試す
83
  try:
84
+ resp = client.responses.create(
85
+ model=model,
86
+ input=[
87
+ {"role": "system", "content": [{"type": "input_text", "text": system}]},
88
+ {
89
+ "role": "user",
90
+ "content": [{"type": "input_text", "text": base_user}] + [
91
+ {"type": "input_file", "file_id": fid} for fid in file_ids
92
+ ],
93
+ },
94
+ ],
95
+ response_format={
96
+ "type": "json_schema",
97
+ "json_schema": {"name": "FinancialExtract", "schema": schema, "strict": True},
98
+ },
99
+ max_output_tokens=2048,
100
+ )
101
+ raw = _safe_get_output_text(resp)
102
+ except TypeError:
103
+ # 互換フォールバック:JSONスキーマをプロンプトに埋め込み、純JSONのみを返すよう強制
104
+ user_with_schema = (
105
+ base_user
106
+ + "\nYou MUST return a single JSON object that VALIDATES against this JSON Schema (no extra keys):\n"
107
+ + json.dumps(schema, ensure_ascii=False)
108
+ )
109
+ resp = client.responses.create(
110
+ model=model,
111
+ input=[
112
+ {"role": "system", "content": [{"type": "input_text", "text": system}]},
113
+ {
114
+ "role": "user",
115
+ "content": [{"type": "input_text", "text": user_with_schema}] + [
116
+ {"type": "input_file", "file_id": fid} for fid in file_ids
117
+ ],
118
+ },
119
+ ],
120
+ max_output_tokens=2048,
121
+ )
122
+ raw = _safe_get_output_text(resp)
123
 
124
  if not raw:
125
  raise RuntimeError("LLMからの応答が空でした。")
126
 
127
+ # JSON整形
128
  try:
129
  data = json.loads(raw)
130
+ except json.JSONDecodeError:
131
+ raw2 = _strip_code_fences(raw)
132
+ data = json.loads(raw2)
 
 
 
 
 
133
 
134
+ # Pydantic で最終検証
135
  try:
136
+ return FinancialExtract.model_validate(data)
137
  except ValidationError as ve:
138
  raise RuntimeError(f"構造化出力の検証に失敗: {ve}")
139
 
140
+ def suggest_multiples_with_llm(
141
+ client: OpenAI,
142
+ text_model: str,
143
+ industry: str,
144
+ region: str = "JP",
145
+ debug: bool = False,
146
+ ) -> Optional[MultipleSuggestion]:
147
+ """業種/地域に応じた保守的な倍率を返す。`response_format` 非対応環境でも動くようフォールバック。"""
148
  if not industry:
149
  return None
150
 
151
  system = "You are an equity analyst. Provide conservative valuation multiple estimates for the given industry and region."
152
  user = (
153
  f"Industry: {industry}\nRegion: {region}\n"
154
+ "Return STRICT JSON with keys: revenue_multiple (float), ebitda_multiple (float). No prose."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  )
156
 
157
+ # JSON Schema を使う実装を先に試す
158
  try:
159
+ resp = client.responses.create(
160
+ model=text_model,
161
+ input=[
162
+ {"role": "system", "content": [{"type": "input_text", "text": system}]},
163
+ {"role": "user", "content": [{"type": "input_text", "text": user}]},
164
+ ],
165
+ response_format={
166
+ "type": "json_schema",
167
+ "json_schema": {
168
+ "name": "MultipleSuggestion",
169
+ "schema": MultipleSuggestion.model_json_schema(),
170
+ "strict": True,
171
+ },
172
+ },
173
+ max_output_tokens=200,
174
+ )
175
+ raw = _safe_get_output_text(resp)
176
+ except TypeError:
177
+ # 互換フォールバック:スキーマをプロンプトに埋め込む
178
+ user2 = (
179
+ user
180
+ + "\nYou MUST return a single JSON object that VALIDATES against this JSON Schema (no extra keys):\n"
181
+ + json.dumps(MultipleSuggestion.model_json_schema(), ensure_ascii=False)
182
+ )
183
+ resp = client.responses.create(
184
+ model=text_model,
185
+ input=[
186
+ {"role": "system", "content": [{"type": "input_text", "text": system}]},
187
+ {"role": "user", "content": [{"type": "input_text", "text": user2}]},
188
+ ],
189
+ max_output_tokens=200,
190
+ )
191
+ raw = _safe_get_output_text(resp)
192
 
193
  if not raw:
194
  return None
195
 
196
  try:
197
  data = json.loads(raw)
198
+ except json.JSONDecodeError:
199
+ data = json.loads(_strip_code_fences(raw))
200
+
201
+ try:
202
  return MultipleSuggestion.model_validate(data)
203
  except Exception:
204
  if debug: