Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os, re, base64
|
|
|
|
|
|
|
| 2 |
from langchain_core.documents import Document
|
| 3 |
from langchain_chroma import Chroma
|
| 4 |
-
from langchain_huggingface import HuggingFaceEmbeddings
|
| 5 |
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 6 |
-
import chromadb
|
| 7 |
-
import gradio as gr
|
| 8 |
|
| 9 |
# === 記憶模組相容多版本 ===
|
| 10 |
try:
|
|
@@ -17,71 +29,88 @@ except ImportError:
|
|
| 17 |
|
| 18 |
|
| 19 |
# =============================================
|
| 20 |
-
# 1️⃣
|
| 21 |
# =============================================
|
| 22 |
embedding = HuggingFaceEmbeddings(model_name="BAAI/bge-small-zh-v1.5")
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
# =============================================
|
| 25 |
-
# 2️⃣
|
| 26 |
# =============================================
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
|
| 34 |
-
text = f.read()
|
| 35 |
|
| 36 |
-
pattern = r"(Q[::].*?)(?=Q[::]|$)"
|
| 37 |
-
qas = re.findall(pattern, text, flags=re.S)
|
| 38 |
-
qa_docs = {"證券": [], "期貨": [], "複委託": []}
|
| 39 |
-
for qa in qas:
|
| 40 |
-
if "證券" in qa:
|
| 41 |
-
qa_docs["證券"].append(Document(page_content=qa.strip()))
|
| 42 |
-
elif "期貨" in qa:
|
| 43 |
-
qa_docs["期貨"].append(Document(page_content=qa.strip()))
|
| 44 |
-
elif "複委託" in qa:
|
| 45 |
-
qa_docs["複委託"].append(Document(page_content=qa.strip()))
|
| 46 |
|
| 47 |
-
|
| 48 |
-
for k, v in qa_docs.items()
|
| 49 |
-
print(f" {k}:{len(v)} 筆")
|
| 50 |
|
| 51 |
|
| 52 |
# =============================================
|
| 53 |
-
# 3️⃣
|
| 54 |
# =============================================
|
| 55 |
client = chromadb.PersistentClient(path="./chroma_db")
|
| 56 |
-
|
| 57 |
-
|
| 58 |
vectordbs = {}
|
|
|
|
| 59 |
for cat, docs in qa_docs.items():
|
| 60 |
-
|
| 61 |
client=client,
|
| 62 |
-
collection_name=
|
| 63 |
embedding_function=embedding
|
| 64 |
)
|
| 65 |
-
if
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
| 68 |
|
| 69 |
|
| 70 |
# =============================================
|
| 71 |
-
# 4️⃣ 初始化
|
| 72 |
# =============================================
|
| 73 |
-
API_KEY
|
| 74 |
-
|
| 75 |
-
|
|
|
|
| 76 |
|
| 77 |
-
llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", google_api_key=API_KEY)
|
| 78 |
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
| 79 |
|
| 80 |
|
| 81 |
# =============================================
|
| 82 |
# 5️⃣ 對話邏輯
|
| 83 |
# =============================================
|
| 84 |
-
def auto_detect_category(text):
|
|
|
|
| 85 |
if any(k in text for k in ["股票", "證券", "開戶", "下單", "交割"]):
|
| 86 |
return "證券"
|
| 87 |
elif any(k in text for k in ["期貨", "選擇權", "保證金"]):
|
|
@@ -93,13 +122,14 @@ def auto_detect_category(text):
|
|
| 93 |
|
| 94 |
|
| 95 |
def chat_fn(message, history):
|
|
|
|
| 96 |
category = auto_detect_category(message)
|
| 97 |
-
vectordb = vectordbs
|
| 98 |
docs = vectordb.similarity_search(message, k=2)
|
| 99 |
-
context = "\n\n".join(
|
| 100 |
|
| 101 |
prompt = f"""
|
| 102 |
-
|
| 103 |
---
|
| 104 |
{context}
|
| 105 |
---
|
|
@@ -107,140 +137,85 @@ def chat_fn(message, history):
|
|
| 107 |
"""
|
| 108 |
|
| 109 |
try:
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
| 112 |
except Exception as e:
|
| 113 |
reply = f"⚠️ 生成錯誤:{e}"
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
|
| 117 |
# =============================================
|
| 118 |
-
# 6️⃣ Gradio
|
| 119 |
# =============================================
|
| 120 |
-
logo_path = os.path.join(BASE_DIR, "mega.png")
|
| 121 |
logo_base64 = ""
|
| 122 |
-
if os.path.exists(
|
| 123 |
-
with open(
|
| 124 |
logo_base64 = base64.b64encode(f.read()).decode("utf-8")
|
| 125 |
|
| 126 |
with gr.Blocks(
|
| 127 |
theme="soft",
|
| 128 |
css="""
|
| 129 |
-
/* ====== logo ====== */
|
| 130 |
#logo-top {
|
| 131 |
position: fixed; top: 12px; left: 18px;
|
| 132 |
background-color: white; border-radius: 10px;
|
| 133 |
padding: 6px 8px; box-shadow: 0 0 8px rgba(0,0,0,0.15);
|
|
|
|
| 134 |
}
|
| 135 |
#logo-top img { width: 120px; height: auto; display: block; }
|
| 136 |
|
| 137 |
-
|
| 138 |
-
#main-title {
|
| 139 |
-
font-size: 28px; font-weight: bold; text-align: center;
|
| 140 |
-
line-height: 1.4; margin: 0; display: inline-block;
|
| 141 |
-
}
|
| 142 |
-
@media (max-width: 768px) {
|
| 143 |
-
#main-title { font-size: 24px; white-space: pre-line; }
|
| 144 |
-
#main-title::before {
|
| 145 |
-
content: "👨💼 我是小智\\A您的金融好幫手 🫰";
|
| 146 |
-
white-space: pre;
|
| 147 |
-
}
|
| 148 |
-
#main-title span { display: none; }
|
| 149 |
-
}
|
| 150 |
-
|
| 151 |
-
/* ====== footer(純白背景) ====== */
|
| 152 |
-
#footer {
|
| 153 |
-
position: fixed; bottom: 40px; left: 0; width: 100%;
|
| 154 |
-
text-align: center; font-size: 13px; color: #aaa;
|
| 155 |
-
border-top: 1px solid #ddd; padding-top: 8px;
|
| 156 |
-
background-color: transparent;
|
| 157 |
-
}
|
| 158 |
-
@media (max-width: 768px) {
|
| 159 |
-
#footer { position: relative; margin-top: 40px; }
|
| 160 |
-
}
|
| 161 |
-
|
| 162 |
-
/* ====== LINE 風格輸入區 ====== */
|
| 163 |
-
#input-row { display: flex; align-items: center; gap: 8px; margin-top: 10px; }
|
| 164 |
-
#user-input {
|
| 165 |
-
flex-grow: 1; border-radius: 20px; border: 1px solid #ccc;
|
| 166 |
-
padding: 6px 12px; font-size: 15px; background-color: #fff;
|
| 167 |
-
box-shadow: inset 0 0 1px rgba(0,0,0,0.05);
|
| 168 |
-
}
|
| 169 |
-
|
| 170 |
-
/* 🟢 小巧文字版「輸入」按鈕 */
|
| 171 |
-
#send-btn {
|
| 172 |
-
background-color: #00b800;
|
| 173 |
-
color: white;
|
| 174 |
-
border: none;
|
| 175 |
-
border-radius: 14px;
|
| 176 |
-
height: 26px;
|
| 177 |
-
padding: 0 10px;
|
| 178 |
-
font-size: 13px;
|
| 179 |
-
font-weight: 600;
|
| 180 |
-
cursor: pointer;
|
| 181 |
-
transition: background-color 0.2s ease, transform 0.1s ease;
|
| 182 |
-
box-shadow: 0 1px 2px rgba(0,0,0,0.1);
|
| 183 |
-
}
|
| 184 |
-
#send-btn:hover { background-color: #00a000; }
|
| 185 |
-
#send-btn:active { transform: scale(0.95); }
|
| 186 |
"""
|
| 187 |
) as demo:
|
| 188 |
if logo_base64:
|
| 189 |
-
gr.HTML(f""
|
| 190 |
-
<div id="logo-top"><img src="data:image/png;base64,{logo_base64}" alt="logo"></div>
|
| 191 |
-
""")
|
| 192 |
|
| 193 |
-
gr.
|
| 194 |
-
|
| 195 |
-
<h1 id='main-title'><span>👨💼 我是小智 您的金融好幫手 🫰</span></h1>
|
| 196 |
-
<p id='sub-title' style='margin-top:10px; font-size:14px; color:#666;'>Powered by Gemini & LangChain</p>
|
| 197 |
-
</div>
|
| 198 |
-
""")
|
| 199 |
|
| 200 |
with gr.Row():
|
| 201 |
with gr.Column(scale=4):
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
|
|
|
| 206 |
|
| 207 |
def handle_input(message, history):
|
| 208 |
if not message.strip():
|
| 209 |
return history, gr.update(value="")
|
| 210 |
reply = chat_fn(message, history)
|
| 211 |
-
history
|
| 212 |
-
|
| 213 |
-
{"role": "assistant", "content": reply}
|
| 214 |
-
]
|
| 215 |
return history, gr.update(value="")
|
| 216 |
|
| 217 |
-
user_input.submit(handle_input, [user_input,
|
| 218 |
-
send_btn.click(handle_input, [user_input,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
with gr.Column(scale=1):
|
| 221 |
-
gr.Markdown("###
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
]
|
| 230 |
-
for
|
| 231 |
-
gr.Button(
|
| 232 |
-
|
| 233 |
-
def clear_memory():
|
| 234 |
-
memory.clear()
|
| 235 |
-
return [], gr.update(value="", placeholder="輸入訊息...")
|
| 236 |
-
gr.Button("🧹 整理畫面").click(clear_memory, outputs=[chatbox, user_input])
|
| 237 |
|
| 238 |
gr.HTML("<div id='footer'>© Fintech Assistant — 僅業務使用,非官方授權</div>")
|
| 239 |
|
| 240 |
-
demo.load(None, None, None, js="""
|
| 241 |
-
window.addEventListener('focusin', () => {
|
| 242 |
-
document.querySelector('textarea')?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
| 243 |
-
});
|
| 244 |
-
""")
|
| 245 |
-
|
| 246 |
demo.launch()
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
======================================================
|
| 3 |
+
📘 金融客服小智(Fintech Assistant)
|
| 4 |
+
版本:v2 (重構示範 by Supervisor)
|
| 5 |
+
改進重點:
|
| 6 |
+
1. 模組化程式結構(易維護)
|
| 7 |
+
2. 加入記憶體保存(多輪對話)
|
| 8 |
+
3. 改善 Chroma 初始化與 QA 擷取
|
| 9 |
+
4. 加強異常處理與容錯提示
|
| 10 |
+
======================================================
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
import os, re, base64
|
| 14 |
+
import chromadb
|
| 15 |
+
import gradio as gr
|
| 16 |
from langchain_core.documents import Document
|
| 17 |
from langchain_chroma import Chroma
|
| 18 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 19 |
from langchain_google_genai import ChatGoogleGenerativeAI
|
|
|
|
|
|
|
| 20 |
|
| 21 |
# === 記憶模組相容多版本 ===
|
| 22 |
try:
|
|
|
|
| 29 |
|
| 30 |
|
| 31 |
# =============================================
|
| 32 |
+
# 1️⃣ Embedding 與基礎設定
|
| 33 |
# =============================================
|
| 34 |
embedding = HuggingFaceEmbeddings(model_name="BAAI/bge-small-zh-v1.5")
|
| 35 |
|
| 36 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 37 |
+
QA_PATH = os.path.join(BASE_DIR, "QA_v2.txt")
|
| 38 |
+
LOGO_PATH = os.path.join(BASE_DIR, "mega.png")
|
| 39 |
+
|
| 40 |
+
if not os.path.exists(QA_PATH):
|
| 41 |
+
raise FileNotFoundError("❌ 找不到 QA 檔案 QA_v2.txt,請確認路徑。")
|
| 42 |
+
|
| 43 |
+
API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 44 |
+
if not API_KEY:
|
| 45 |
+
print("⚠️ 尚未設定 GOOGLE_API_KEY,系統將以模擬回覆運行。")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
# =============================================
|
| 49 |
+
# 2️⃣ QA 載入與分類(改進版正規化)
|
| 50 |
# =============================================
|
| 51 |
+
def load_qa_documents(path: str):
|
| 52 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 53 |
+
text = f.read()
|
| 54 |
+
|
| 55 |
+
# 改進版正規表達式,確保每筆 QA 含問題與答案
|
| 56 |
+
pattern = r"(Q[::].*?A[::].*?)(?=Q[::]|$)"
|
| 57 |
+
qas = re.findall(pattern, text, flags=re.S)
|
| 58 |
|
| 59 |
+
categories = {"證券": [], "期貨": [], "複委託": []}
|
| 60 |
+
for qa in qas:
|
| 61 |
+
doc = Document(page_content=qa.strip())
|
| 62 |
+
if "證券" in qa:
|
| 63 |
+
categories["證券"].append(doc)
|
| 64 |
+
elif "期貨" in qa:
|
| 65 |
+
categories["期貨"].append(doc)
|
| 66 |
+
elif "複委託" in qa:
|
| 67 |
+
categories["複委託"].append(doc)
|
| 68 |
+
else:
|
| 69 |
+
categories["證券"].append(doc) # 預設分類
|
| 70 |
|
| 71 |
+
return categories
|
|
|
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
+
qa_docs = load_qa_documents(QA_PATH)
|
| 75 |
+
print("✅ 已成功載入 QA 檔案,共分為:", {k: len(v) for k, v in qa_docs.items()})
|
|
|
|
| 76 |
|
| 77 |
|
| 78 |
# =============================================
|
| 79 |
+
# 3️⃣ 向量資料庫初始化(避免重複寫入)
|
| 80 |
# =============================================
|
| 81 |
client = chromadb.PersistentClient(path="./chroma_db")
|
| 82 |
+
collection_map = {"證券": "stocks", "期貨": "futures", "複委託": "overseas"}
|
|
|
|
| 83 |
vectordbs = {}
|
| 84 |
+
|
| 85 |
for cat, docs in qa_docs.items():
|
| 86 |
+
vectordb = Chroma(
|
| 87 |
client=client,
|
| 88 |
+
collection_name=collection_map[cat],
|
| 89 |
embedding_function=embedding
|
| 90 |
)
|
| 91 |
+
if vectordb._collection.count() == 0:
|
| 92 |
+
vectordb.add_documents(docs)
|
| 93 |
+
vectordbs[cat] = vectordb
|
| 94 |
+
|
| 95 |
+
print("✅ 向量資料庫已建立完成。")
|
| 96 |
|
| 97 |
|
| 98 |
# =============================================
|
| 99 |
+
# 4️⃣ 初始化 LLM 與對話記憶
|
| 100 |
# =============================================
|
| 101 |
+
if API_KEY:
|
| 102 |
+
llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", google_api_key=API_KEY)
|
| 103 |
+
else:
|
| 104 |
+
llm = None # 模擬模式
|
| 105 |
|
|
|
|
| 106 |
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
| 107 |
|
| 108 |
|
| 109 |
# =============================================
|
| 110 |
# 5️⃣ 對話邏輯
|
| 111 |
# =============================================
|
| 112 |
+
def auto_detect_category(text: str):
|
| 113 |
+
"""根據關鍵詞自動偵測使用者詢問的業務類別"""
|
| 114 |
if any(k in text for k in ["股票", "證券", "開戶", "下單", "交割"]):
|
| 115 |
return "證券"
|
| 116 |
elif any(k in text for k in ["期貨", "選擇權", "保證金"]):
|
|
|
|
| 122 |
|
| 123 |
|
| 124 |
def chat_fn(message, history):
|
| 125 |
+
"""核心對話函式"""
|
| 126 |
category = auto_detect_category(message)
|
| 127 |
+
vectordb = vectordbs[category]
|
| 128 |
docs = vectordb.similarity_search(message, k=2)
|
| 129 |
+
context = "\n\n".join(d.page_content for d in docs) if docs else "查無相關資料"
|
| 130 |
|
| 131 |
prompt = f"""
|
| 132 |
+
你是一位金融客服人員,請根據以下QA知識回答:
|
| 133 |
---
|
| 134 |
{context}
|
| 135 |
---
|
|
|
|
| 137 |
"""
|
| 138 |
|
| 139 |
try:
|
| 140 |
+
if llm:
|
| 141 |
+
response = llm.invoke(prompt)
|
| 142 |
+
reply = getattr(response, "content", None) or getattr(response, "text", "⚠️ 無回覆")
|
| 143 |
+
else:
|
| 144 |
+
reply = "(模擬模式)這是示範回覆:請確認是否已設定 GOOGLE_API_KEY。"
|
| 145 |
except Exception as e:
|
| 146 |
reply = f"⚠️ 生成錯誤:{e}"
|
| 147 |
+
|
| 148 |
+
# 保存對話記憶
|
| 149 |
+
memory.save_context({"role": "user", "content": message},
|
| 150 |
+
{"role": "assistant", "content": reply})
|
| 151 |
+
return reply
|
| 152 |
|
| 153 |
|
| 154 |
# =============================================
|
| 155 |
+
# 6️⃣ Gradio 介面(重構版)
|
| 156 |
# =============================================
|
|
|
|
| 157 |
logo_base64 = ""
|
| 158 |
+
if os.path.exists(LOGO_PATH):
|
| 159 |
+
with open(LOGO_PATH, "rb") as f:
|
| 160 |
logo_base64 = base64.b64encode(f.read()).decode("utf-8")
|
| 161 |
|
| 162 |
with gr.Blocks(
|
| 163 |
theme="soft",
|
| 164 |
css="""
|
|
|
|
| 165 |
#logo-top {
|
| 166 |
position: fixed; top: 12px; left: 18px;
|
| 167 |
background-color: white; border-radius: 10px;
|
| 168 |
padding: 6px 8px; box-shadow: 0 0 8px rgba(0,0,0,0.15);
|
| 169 |
+
pointer-events: none;
|
| 170 |
}
|
| 171 |
#logo-top img { width: 120px; height: auto; display: block; }
|
| 172 |
|
| 173 |
+
#footer { text-align:center; font-size:13px; color:#aaa; margin-top: 20px; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
"""
|
| 175 |
) as demo:
|
| 176 |
if logo_base64:
|
| 177 |
+
gr.HTML(f"<div id='logo-top'><img src='data:image/png;base64,{logo_base64}'></div>")
|
|
|
|
|
|
|
| 178 |
|
| 179 |
+
gr.Markdown("## 👨💼 我是小智 · 您的金融好幫手 🫰")
|
| 180 |
+
gr.Markdown("Powered by Gemini & LangChain")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
with gr.Row():
|
| 183 |
with gr.Column(scale=4):
|
| 184 |
+
chatbot = gr.Chatbot(label="💬 對話紀錄", type="messages", height=500)
|
| 185 |
+
|
| 186 |
+
with gr.Row():
|
| 187 |
+
user_input = gr.Textbox(placeholder="請輸入問題...", show_label=False)
|
| 188 |
+
send_btn = gr.Button("送出", variant="primary")
|
| 189 |
|
| 190 |
def handle_input(message, history):
|
| 191 |
if not message.strip():
|
| 192 |
return history, gr.update(value="")
|
| 193 |
reply = chat_fn(message, history)
|
| 194 |
+
history += [{"role": "user", "content": message},
|
| 195 |
+
{"role": "assistant", "content": reply}]
|
|
|
|
|
|
|
| 196 |
return history, gr.update(value="")
|
| 197 |
|
| 198 |
+
user_input.submit(handle_input, [user_input, chatbot], [chatbot, user_input])
|
| 199 |
+
send_btn.click(handle_input, [user_input, chatbot], [chatbot, user_input])
|
| 200 |
+
|
| 201 |
+
def clear_all():
|
| 202 |
+
memory.clear()
|
| 203 |
+
return [], gr.update(value="")
|
| 204 |
+
gr.Button("🧹 清除對話").click(clear_all, outputs=[chatbot, user_input])
|
| 205 |
|
| 206 |
with gr.Column(scale=1):
|
| 207 |
+
gr.Markdown("### 🔍 常見問題")
|
| 208 |
+
examples = [
|
| 209 |
+
"未成年可以開戶嗎?",
|
| 210 |
+
"法人開戶要準備什麼?",
|
| 211 |
+
"期貨交易保證金是什麼?",
|
| 212 |
+
"複委託要如何下單?",
|
| 213 |
+
"美股交易時間?",
|
| 214 |
+
"美股可以定期定額嗎?"
|
| 215 |
]
|
| 216 |
+
for q in examples:
|
| 217 |
+
gr.Button(q).click(lambda h, q=q: handle_input(q, h), [chatbot], [chatbot, user_input])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
|
| 219 |
gr.HTML("<div id='footer'>© Fintech Assistant — 僅業務使用,非官方授權</div>")
|
| 220 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
demo.launch()
|