Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -16,7 +16,7 @@ DATASETS = ["MGGroup/Treaties", "MGGroup/InvestmentGuide"]
|
|
| 16 |
DESCRIPTION = """
|
| 17 |
<div style="text-align: left; border-left: 4px solid #2196F3; padding-left: 15px; margin-bottom: 20px;">
|
| 18 |
<h3 style="margin-top: 0;">MG TaxAI | 跨境财税合规实验室 (Beta)</h3>
|
| 19 |
-
<p>
|
| 20 |
</div>
|
| 21 |
"""
|
| 22 |
|
|
@@ -26,38 +26,39 @@ def fetch_dataset_context(query):
|
|
| 26 |
combined_text = ""
|
| 27 |
sources = []
|
| 28 |
|
| 29 |
-
# 提取查询关键词:
|
| 30 |
keywords = re.findall(r'[\u4e00-\u9fa5]+|[a-zA-Z0-9]+', query)
|
| 31 |
if not keywords: return "", []
|
| 32 |
|
| 33 |
for repo in DATASETS:
|
| 34 |
try:
|
| 35 |
-
# 获取数据集下所有文件(
|
| 36 |
files = api.list_repo_files(repo_id=repo, repo_type="dataset")
|
| 37 |
|
| 38 |
matched = []
|
| 39 |
for f in files:
|
| 40 |
if not f.lower().endswith(".pdf"): continue
|
| 41 |
|
| 42 |
-
#
|
| 43 |
-
#
|
| 44 |
path_lower = f.lower()
|
| 45 |
if any(k.lower() in path_lower for k in keywords):
|
| 46 |
matched.append(f)
|
| 47 |
|
| 48 |
-
#
|
| 49 |
for f_path in matched[:2]:
|
| 50 |
temp_path = hf_hub_download(repo_id=repo, filename=f_path, repo_type="dataset", token=HF_TOKEN)
|
| 51 |
doc = fitz.open(temp_path)
|
| 52 |
|
| 53 |
-
#
|
| 54 |
-
|
| 55 |
-
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
|
|
|
|
| 61 |
doc.close()
|
| 62 |
os.remove(temp_path)
|
| 63 |
except Exception as e:
|
|
@@ -67,6 +68,7 @@ def fetch_dataset_context(query):
|
|
| 67 |
return combined_text, sources
|
| 68 |
|
| 69 |
def find_local_context(query):
|
|
|
|
| 70 |
base_dir = "./treaties"
|
| 71 |
if not os.path.exists(base_dir): return "", []
|
| 72 |
sources = []
|
|
@@ -78,13 +80,12 @@ def find_local_context(query):
|
|
| 78 |
if any(k.lower() in f.lower() for k in keywords):
|
| 79 |
selected = f; break
|
| 80 |
if not selected: return "", []
|
| 81 |
-
|
| 82 |
path = os.path.join(base_dir, selected)
|
| 83 |
texts = []
|
| 84 |
for pdf in [f for f in os.listdir(path) if f.endswith(".pdf")]:
|
| 85 |
doc = fitz.open(os.path.join(path, pdf))
|
| 86 |
texts.append(f"\n[来源: 本地库-{pdf}]\n" + "".join([page.get_text() for page in doc[:20]]))
|
| 87 |
-
sources.append(f"📦 本地库
|
| 88 |
doc.close()
|
| 89 |
return "\n".join(texts), sources
|
| 90 |
except: return "", []
|
|
@@ -101,20 +102,20 @@ def call_gemini(messages):
|
|
| 101 |
except: return "⚠️ 响应超时,请重试。"
|
| 102 |
|
| 103 |
def respond(message, history, system_message, max_tokens, temperature, top_p):
|
| 104 |
-
# 1.
|
| 105 |
knowledge, sources = fetch_dataset_context(message)
|
| 106 |
|
| 107 |
-
# 2.
|
| 108 |
if not knowledge:
|
| 109 |
knowledge, sources = find_local_context(message)
|
| 110 |
|
| 111 |
-
# 3. 构造来源标签
|
| 112 |
if sources:
|
| 113 |
source_label = "### 📚 知识溯源已关联:\n" + "\n".join([f"- {s}" for s in sources])
|
| 114 |
else:
|
| 115 |
-
source_label = "💡 *未匹配到
|
| 116 |
|
| 117 |
-
# 4.
|
| 118 |
messages = [{"role": "system", "content": f"{system_message}\n\n【MG核心智库参考资料】:\n{knowledge}"}]
|
| 119 |
for user_msg, assistant_msg in history:
|
| 120 |
if user_msg: messages.append({"role": "user", "content": user_msg})
|
|
@@ -122,8 +123,6 @@ def respond(message, history, system_message, max_tokens, temperature, top_p):
|
|
| 122 |
messages.append({"role": "user", "content": message})
|
| 123 |
|
| 124 |
reply = call_gemini(messages)
|
| 125 |
-
|
| 126 |
-
# 最终输出:来源标签 + 回复内容
|
| 127 |
yield f"{source_label}\n\n---\n\n{reply}"
|
| 128 |
|
| 129 |
demo = gr.ChatInterface(
|
|
@@ -132,8 +131,8 @@ demo = gr.ChatInterface(
|
|
| 132 |
theme="soft",
|
| 133 |
css=".gradio-container {max-width: 950px !important}",
|
| 134 |
additional_inputs=[
|
| 135 |
-
gr.Textbox(value="你代表 MG Consult,是国际税收专家。请严格基于资料
|
| 136 |
-
gr.Slider(512, 4096, 2048, label="回复长度"),
|
| 137 |
gr.Slider(0, 1, 0.05, label="严谨度"),
|
| 138 |
gr.Slider(0, 1, 0.95, label="采样率"),
|
| 139 |
],
|
|
|
|
| 16 |
DESCRIPTION = """
|
| 17 |
<div style="text-align: left; border-left: 4px solid #2196F3; padding-left: 15px; margin-bottom: 20px;">
|
| 18 |
<h3 style="margin-top: 0;">MG TaxAI | 跨境财税合规实验室 (Beta)</h3>
|
| 19 |
+
<p>系统已升级<b>全路径检索引擎</b>,支持穿透多层文件夹匹配「协定库」与「投资指南」。</p>
|
| 20 |
</div>
|
| 21 |
"""
|
| 22 |
|
|
|
|
| 26 |
combined_text = ""
|
| 27 |
sources = []
|
| 28 |
|
| 29 |
+
# 提取查询关键词:中文、英文、数字
|
| 30 |
keywords = re.findall(r'[\u4e00-\u9fa5]+|[a-zA-Z0-9]+', query)
|
| 31 |
if not keywords: return "", []
|
| 32 |
|
| 33 |
for repo in DATASETS:
|
| 34 |
try:
|
| 35 |
+
# 获取数据集下所有文件(含子目录)
|
| 36 |
files = api.list_repo_files(repo_id=repo, repo_type="dataset")
|
| 37 |
|
| 38 |
matched = []
|
| 39 |
for f in files:
|
| 40 |
if not f.lower().endswith(".pdf"): continue
|
| 41 |
|
| 42 |
+
# 【强化逻辑】:扫描整个路径字符串
|
| 43 |
+
# 即使文件名叫 1.pdf,只要文件夹叫“丹麦”,就能对上
|
| 44 |
path_lower = f.lower()
|
| 45 |
if any(k.lower() in path_lower for k in keywords):
|
| 46 |
matched.append(f)
|
| 47 |
|
| 48 |
+
# 每个库最多取 2 本最相关的书,防止上下文过长
|
| 49 |
for f_path in matched[:2]:
|
| 50 |
temp_path = hf_hub_download(repo_id=repo, filename=f_path, repo_type="dataset", token=HF_TOKEN)
|
| 51 |
doc = fitz.open(temp_path)
|
| 52 |
|
| 53 |
+
# 记录来源:取最后两级路径,方便辨认国家
|
| 54 |
+
path_parts = f_path.split('/')
|
| 55 |
+
display_name = "/".join(path_parts[-2:]) if len(path_parts) > 1 else f_path
|
| 56 |
|
| 57 |
+
combined_text += f"\n[来源: {repo}/{f_path}]\n"
|
| 58 |
+
# 读取前 40 页,Gemini 3 吞吐量大,可以多给点
|
| 59 |
+
combined_text += "".join([page.get_text() for page in doc[:40]])
|
| 60 |
|
| 61 |
+
sources.append(f"📊 智库数据集: {display_name}")
|
| 62 |
doc.close()
|
| 63 |
os.remove(temp_path)
|
| 64 |
except Exception as e:
|
|
|
|
| 68 |
return combined_text, sources
|
| 69 |
|
| 70 |
def find_local_context(query):
|
| 71 |
+
# 保留原有的本地兜底逻辑,确保绝对不瘫痪
|
| 72 |
base_dir = "./treaties"
|
| 73 |
if not os.path.exists(base_dir): return "", []
|
| 74 |
sources = []
|
|
|
|
| 80 |
if any(k.lower() in f.lower() for k in keywords):
|
| 81 |
selected = f; break
|
| 82 |
if not selected: return "", []
|
|
|
|
| 83 |
path = os.path.join(base_dir, selected)
|
| 84 |
texts = []
|
| 85 |
for pdf in [f for f in os.listdir(path) if f.endswith(".pdf")]:
|
| 86 |
doc = fitz.open(os.path.join(path, pdf))
|
| 87 |
texts.append(f"\n[来源: 本地库-{pdf}]\n" + "".join([page.get_text() for page in doc[:20]]))
|
| 88 |
+
sources.append(f"📦 本地库备份: {selected}/{pdf}")
|
| 89 |
doc.close()
|
| 90 |
return "\n".join(texts), sources
|
| 91 |
except: return "", []
|
|
|
|
| 102 |
except: return "⚠️ 响应超时,请重试。"
|
| 103 |
|
| 104 |
def respond(message, history, system_message, max_tokens, temperature, top_p):
|
| 105 |
+
# 1. 深度扫描 Dataset
|
| 106 |
knowledge, sources = fetch_dataset_context(message)
|
| 107 |
|
| 108 |
+
# 2. Dataset 没中,扫描本地
|
| 109 |
if not knowledge:
|
| 110 |
knowledge, sources = find_local_context(message)
|
| 111 |
|
| 112 |
+
# 3. 构造界面显示的来源标签
|
| 113 |
if sources:
|
| 114 |
source_label = "### 📚 知识溯源已关联:\n" + "\n".join([f"- {s}" for s in sources])
|
| 115 |
else:
|
| 116 |
+
source_label = "💡 *未匹配到私有库文档,当前基于通用财税知识回答*"
|
| 117 |
|
| 118 |
+
# 4. 提交给 Gemini
|
| 119 |
messages = [{"role": "system", "content": f"{system_message}\n\n【MG核心智库参考资料】:\n{knowledge}"}]
|
| 120 |
for user_msg, assistant_msg in history:
|
| 121 |
if user_msg: messages.append({"role": "user", "content": user_msg})
|
|
|
|
| 123 |
messages.append({"role": "user", "content": message})
|
| 124 |
|
| 125 |
reply = call_gemini(messages)
|
|
|
|
|
|
|
| 126 |
yield f"{source_label}\n\n---\n\n{reply}"
|
| 127 |
|
| 128 |
demo = gr.ChatInterface(
|
|
|
|
| 131 |
theme="soft",
|
| 132 |
css=".gradio-container {max-width: 950px !important}",
|
| 133 |
additional_inputs=[
|
| 134 |
+
gr.Textbox(value="你代表 MG Consult,是国际税收专家。请严格基于参考资料提供建议。", label="系统指令"),
|
| 135 |
+
gr.Slider(512, 4096, 2048, label="回复长度限制"),
|
| 136 |
gr.Slider(0, 1, 0.05, label="严谨度"),
|
| 137 |
gr.Slider(0, 1, 0.95, label="采样率"),
|
| 138 |
],
|