Corin1998 commited on
Commit
ed7ad22
·
verified ·
1 Parent(s): 469e060

Upload 8 files

Browse files
Files changed (1) hide show
  1. app.py +213 -2
app.py CHANGED
@@ -1,3 +1,214 @@
 
 
 
 
 
1
  import gradio as gr
2
- with gr.Blocks() as demo:
3
- gr.Markdown("Hello from Gradio Space ✅")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py — Failsafe boot for Hugging Face Spaces (Gradio SDK)
2
+ from __future__ import annotations
3
+ import os, json, yaml, subprocess, sys, pathlib, traceback
4
+ from typing import List, Dict
5
+
6
  import gradio as gr
7
+
8
+ CFG_ERR = None
9
+
10
+ # ---- load config with fallback ----
11
+ DEFAULT_CFG = {
12
+ "app_name": "IR/ESG RAG Bot (OpenAI, 8 languages)",
13
+ "embedding_model": "text-embedding-3-large",
14
+ "normalize_embeddings": True,
15
+ "chunk": {"target_chars": 1400, "overlap_chars": 180},
16
+ "retrieval": {"top_k": 6, "score_threshold": 0.15, "mmr_lambda": 0.3},
17
+ "llm": {
18
+ "model": "gpt-4o-mini",
19
+ "max_output_tokens": 700,
20
+ "temperature": 0.2,
21
+ "system_prompt": (
22
+ "あなたは上場企業のIR・ESG開示に特化したRAGアシスタントです。"
23
+ "回答は常に根拠(文書名・ページ)を箇条書きで示し、文書外の推測や断定は避けます。"
24
+ "数値は年度と単位を明記し、最新年度を優先してください。"
25
+ ),
26
+ },
27
+ "languages": {
28
+ "preferred": ["ja", "en", "zh", "ko", "fr", "de", "es", "it"],
29
+ "labels": {
30
+ "ja": "日本語", "en": "English", "zh": "中文", "ko": "한국어",
31
+ "fr": "Français", "de": "Deutsch", "es": "Español", "it": "Italiano",
32
+ },
33
+ },
34
+ }
35
+
36
+ CFG_PATH = "config.yaml"
37
+ try:
38
+ if os.path.exists(CFG_PATH):
39
+ with open(CFG_PATH, encoding="utf-8") as f:
40
+ CFG = yaml.safe_load(f) or {}
41
+ # merge defaults (shallow)
42
+ def _merge(dst, src):
43
+ for k, v in src.items():
44
+ if k not in dst:
45
+ dst[k] = v
46
+ _merge(CFG, DEFAULT_CFG)
47
+ for sec in ("chunk", "retrieval", "llm", "languages"):
48
+ if sec in DEFAULT_CFG:
49
+ if sec not in CFG or not isinstance(CFG[sec], dict):
50
+ CFG[sec] = DEFAULT_CFG[sec]
51
+ else:
52
+ _merge(CFG[sec], DEFAULT_CFG[sec])
53
+ else:
54
+ CFG = DEFAULT_CFG
55
+ CFG_ERR = "config.yaml が見つかりません。デフォルト設定で起動しました。"
56
+ except Exception as e:
57
+ CFG = DEFAULT_CFG
58
+ CFG_ERR = "config.yaml 読み込みエラー: " + str(e)
59
+
60
+ INDEX_PATH = pathlib.Path("data/index/faiss.index")
61
+ META_PATH = pathlib.Path("data/index/meta.jsonl")
62
+
63
+ # ---- Lazy imports ----
64
+ def _lazy_imports():
65
+ global faiss, np, embed_texts, chat, detect_out_of_scope, sanitize, compliance_block, SCOPE_HINT
66
+ import faiss # pip: faiss-cpu
67
+ import numpy as np
68
+ from openai_client import embed_texts, chat
69
+ from guardrails import detect_out_of_scope, sanitize, compliance_block, SCOPE_HINT
70
+ return faiss, np, embed_texts, chat, detect_out_of_scope, sanitize, compliance_block, SCOPE_HINT
71
+
72
+ def _index_exists() -> bool:
73
+ return INDEX_PATH.exists() and META_PATH.exists()
74
+
75
+ def _check_api_key() -> bool:
76
+ return bool(os.getenv("OPENAI_API_KEY"))
77
+
78
+ # ---- Globals (Lazy) ----
79
+ _INDEX = None
80
+ _METAS = None
81
+
82
+ def _ensure_index_loaded():
83
+ global _INDEX, _METAS
84
+ if _INDEX is not None and _METAS is not None:
85
+ return
86
+ if not _index_exists():
87
+ raise RuntimeError("index_not_ready")
88
+ faiss, *_ = _lazy_imports()
89
+ _INDEX = faiss.read_index(str(INDEX_PATH))
90
+ _METAS = [json.loads(l) for l in open(META_PATH, encoding="utf-8")]
91
+
92
+ def _embed_query(q: str):
93
+ _, np, embed_texts, *_ = _lazy_imports()
94
+ v = np.array(embed_texts([q], CFG["embedding_model"])[0], dtype="float32")
95
+ v = v / (np.linalg.norm(v) + 1e-12)
96
+ return v[None, :]
97
+
98
+ def _search(q: str):
99
+ faiss, np, *_ = _lazy_imports()
100
+ _ensure_index_loaded()
101
+ TOP_K = CFG["retrieval"]["top_k"]
102
+ SCORE_TH = CFG["retrieval"]["score_threshold"]
103
+ qv = _embed_query(q)
104
+ sims, idxs = _INDEX.search(qv, TOP_K * 4)
105
+ sims, idxs = sims[0], idxs[0]
106
+ picked, seen = [], set()
107
+ for score, idx in zip(sims, idxs):
108
+ if score < SCORE_TH:
109
+ continue
110
+ c = _METAS[idx]
111
+ key = (c["source"], c["page"])
112
+ if key in seen:
113
+ continue
114
+ seen.add(key)
115
+ picked.append({**c, "score": float(score)})
116
+ if len(picked) >= TOP_K:
117
+ break
118
+ return picked
119
+
120
+ def _format_context(chunks: List[Dict]) -> str:
121
+ return "\n".join([f"- 出典: {c['source']} p.{c['page']} | 抜粋: {c['text'][:180].replace('\n',' ')}…" for c in chunks])
122
+
123
+ # ---- Handlers ----
124
+ def rebuild_index() -> str:
125
+ if not _check_api_key():
126
+ return "OPENAI_API_KEY が未設定です。Spaces → Settings → Secrets で登録してください。"
127
+ pdf_dir = pathlib.Path("data/pdf")
128
+ pdf_dir.mkdir(parents=True, exist_ok=True)
129
+ if not list(pdf_dir.glob("*.pdf")):
130
+ return "data/pdf/ にPDFがありません。PDFを置いて再実行してください。"
131
+ try:
132
+ out = subprocess.run([sys.executable, "ingest.py"], capture_output=True, text=True, check=True)
133
+ # キャッシュ破棄
134
+ global _INDEX, _METAS
135
+ _INDEX = None
136
+ _METAS = None
137
+ return "✅ インデックス生成完了\n```\n" + (out.stdout[-1200:] or "") + "\n```"
138
+ except subprocess.CalledProcessError as e:
139
+ return f"❌ インデックス生成に失敗\nstdout:\n{e.stdout}\n\nstderr:\n{e.stderr}"
140
+ except Exception as e:
141
+ return "❌ 予期せぬエラー: " + str(e) + "\n" + traceback.format_exc()[-1200:]
142
+
143
+ _LANG_INSTRUCTIONS = {
144
+ "ja": "回答は日本語で出力してください。",
145
+ "en": "Answer in English.",
146
+ "zh": "请用中文回答。",
147
+ "ko": "한국어로 답변하세요.",
148
+ "fr": "Répondez en français.",
149
+ "de": "Bitte auf Deutsch antworten.",
150
+ "es": "Responde en español.",
151
+ "it": "Rispondi in italiano.",
152
+ }
153
+
154
+ def generate_answer(q: str, lang: str):
155
+ q = (q or "").strip()
156
+ if not q:
157
+ return "質問を入力してください。", {}
158
+ try:
159
+ _, _, _, chat, detect_out_of_scope, sanitize, compliance_block, SCOPE_HINT = _lazy_imports()
160
+ if detect_out_of_scope(q):
161
+ return f"{SCOPE_HINT}\nIR/ESG関連の事項についてお尋ねください。", {}
162
+ chunks = _search(q)
163
+ context = _format_context(chunks)
164
+ lang_note = _LANG_INSTRUCTIONS.get(lang, "Answer in the user's language.")
165
+ user_prompt = (
166
+ "以下のコンテキストのみを根拠に、簡潔かつ正確に回答してください。\n"
167
+ "必ず箇条書きで根拠(文書名とページ)を列挙してください。\n"
168
+ f"{lang_note}\n\n[コンテキスト]\n{context}\n\n[質問]\n{q}"
169
+ )
170
+ messages = [
171
+ {"role": "system", "content": CFG["llm"]["system_prompt"]},
172
+ {"role": "user", "content": user_prompt},
173
+ ]
174
+ text = chat(messages, model=CFG["llm"]["model"],
175
+ max_output_tokens=CFG["llm"]["max_output_tokens"],
176
+ temperature=CFG["llm"]["temperature"])
177
+ text = sanitize(text) + "\n\n" + compliance_block()
178
+ citations = [{"source": c["source"], "page": c["page"], "score": round(c["score"], 3)} for c in chunks]
179
+ return text, {"citations": citations}
180
+ except RuntimeError as e:
181
+ if str(e) == "index_not_ready":
182
+ return ("⚠️ インデックスがまだありません。\n"
183
+ "1) data/pdf/ にPDFを置く\n"
184
+ "2) 『インデックス再構築』ボタンを押す(OpenAI APIキー必須)\n"), {}
185
+ raise
186
+ except Exception as e:
187
+ return "❌ 実行時エラー: " + str(e) + "\n" + traceback.format_exc()[-1200:], {}
188
+
189
+ # ---- UI ----
190
+ LANGS = CFG["languages"]["preferred"]
191
+ LABELS = CFG["languages"].get("labels", {l: l for l in LANGS})
192
+
193
+ with gr.Blocks(fill_height=True, title=CFG.get("app_name", "RAG Bot")) as demo:
194
+ gr.Markdown("# IR・ESG開示RAG(OpenAI API)— 8言語対応")
195
+ # config.yaml の読み込みエラー・警告を上部に可視化
196
+ if CFG_ERR:
197
+ gr.Markdown(f"**構成警告**: {CFG_ERR}")
198
+
199
+ with gr.Row():
200
+ q = gr.Textbox(label="質問 / Question", lines=3, placeholder="例: 2024年度のGHG排出量(スコープ1-3)は?")
201
+ with gr.Row():
202
+ lang = gr.Dropdown(choices=LANGS, value=LANGS[0], label="回答言語 / Output language")
203
+ with gr.Row():
204
+ ask = gr.Button("回答する / Answer", variant="primary")
205
+ rebuild = gr.Button("インデックス再構築(ingest.py 実行)")
206
+ ans = gr.Markdown()
207
+ cites = gr.JSON(label="根拠メタデータ / Citations")
208
+ log = gr.Markdown()
209
+
210
+ ask.click(fn=generate_answer, inputs=[q, lang], outputs=[ans, cites])
211
+ rebuild.click(fn=rebuild_index, outputs=[log])
212
+
213
+ # Gradio SDK はこの変数を自動検出して起動します
214
+ demo