Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,288 +1,468 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
| 2 |
import sys
|
| 3 |
-
sys.modules[
|
| 4 |
|
|
|
|
|
|
|
|
|
|
| 5 |
import os
|
| 6 |
-
import
|
|
|
|
| 7 |
|
|
|
|
| 8 |
import pandas as pd
|
| 9 |
import docx2txt
|
| 10 |
-
from langchain_community.document_loaders import PyPDFLoader, TextLoader
|
| 11 |
-
from langchain_core.documents import Document
|
| 12 |
|
| 13 |
-
# --- IMPORT CÁC THƯ VIỆN ---
|
| 14 |
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 15 |
from langchain_chroma import Chroma
|
| 16 |
-
|
| 17 |
-
from langchain_community.document_loaders import
|
| 18 |
-
PyPDFLoader,
|
| 19 |
-
DirectoryLoader,
|
| 20 |
-
TextLoader,
|
| 21 |
-
Docx2txtLoader,
|
| 22 |
-
UnstructuredExcelLoader
|
| 23 |
-
)
|
| 24 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 25 |
from langchain_community.retrievers import BM25Retriever
|
| 26 |
from langchain.retrievers.ensemble import EnsembleRetriever
|
|
|
|
| 27 |
from langchain.chains import create_retrieval_chain, create_history_aware_retriever
|
| 28 |
from langchain.chains.combine_documents import create_stuff_documents_chain
|
|
|
|
| 29 |
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 30 |
from langchain_core.messages import HumanMessage, AIMessage
|
| 31 |
from langchain_core.documents import Document
|
|
|
|
| 32 |
from langchain_huggingface import HuggingFaceEmbeddings
|
| 33 |
|
| 34 |
-
|
| 35 |
-
#
|
| 36 |
-
#
|
|
|
|
|
|
|
|
|
|
| 37 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
#
|
| 46 |
-
#
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
if not os.path.exists(folder_path):
|
| 52 |
-
os.makedirs(folder_path)
|
|
|
|
| 53 |
return []
|
| 54 |
|
| 55 |
-
for
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
# Chuyển từng dòng thành dạng: "Tên cột: Giá trị. Tên cột: Giá tr���..."
|
| 83 |
-
# Giúp AI hiểu ngữ cảnh của từng ô dữ liệu
|
| 84 |
-
text_data = ""
|
| 85 |
-
for index, row in df.iterrows():
|
| 86 |
-
row_str = " | ".join([f"{col}: {val}" for col, val in row.items() if pd.notna(val)])
|
| 87 |
-
text_data += row_str + "\n"
|
| 88 |
-
|
| 89 |
-
if text_data.strip():
|
| 90 |
-
doc = Document(page_content=text_data, metadata={"source": filename})
|
| 91 |
-
documents.append(doc)
|
| 92 |
else:
|
| 93 |
-
|
| 94 |
-
except Exception as e:
|
| 95 |
-
print(f" Lỗi đọc Excel {filename}: {e}")
|
| 96 |
-
|
| 97 |
-
# 4. XỬ LÝ TEXT (.txt) VÀ MARKDOWN (.md) <--- ĐÃ CẬP NHẬT Ở ĐÂY
|
| 98 |
-
elif filename_lower.endswith(".txt") or filename_lower.endswith(".md"):
|
| 99 |
-
print(f"-> Đang xử lý Text/Markdown: {filename}")
|
| 100 |
-
text = ""
|
| 101 |
-
try:
|
| 102 |
-
# Ưu tiên đọc UTF-8
|
| 103 |
-
with open(file_path, "r", encoding="utf-8") as f:
|
| 104 |
-
text = f.read()
|
| 105 |
-
except UnicodeDecodeError:
|
| 106 |
-
# Nếu lỗi font, thử đọc Latin-1
|
| 107 |
-
print(f" Encoding UTF-8 thất bại, thử Latin-1...")
|
| 108 |
-
with open(file_path, "r", encoding="latin-1") as f:
|
| 109 |
-
text = f.read()
|
| 110 |
-
|
| 111 |
-
if text.strip():
|
| 112 |
-
doc = Document(page_content=text, metadata={"source": filename})
|
| 113 |
-
documents.append(doc)
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
return documents
|
| 123 |
|
| 124 |
-
def get_retriever():
|
| 125 |
-
print("--- Đang tải model Embedding... ---")
|
| 126 |
-
embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
|
| 127 |
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
vectorstore = None
|
| 130 |
-
|
| 131 |
-
#
|
| 132 |
if os.path.exists(DB_PATH) and os.listdir(DB_PATH):
|
| 133 |
try:
|
| 134 |
-
|
| 135 |
-
vectorstore = Chroma(
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
| 141 |
splits.append(Document(page_content=text, metadata=meta))
|
|
|
|
| 142 |
else:
|
| 143 |
-
|
|
|
|
| 144 |
except Exception as e:
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
-
#
|
| 148 |
if not splits:
|
| 149 |
-
|
| 150 |
documents = load_documents_from_folder(DATA_PATH)
|
| 151 |
-
|
| 152 |
if not documents:
|
| 153 |
-
|
| 154 |
-
return None
|
| 155 |
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
splits = text_splitter.split_documents(documents)
|
|
|
|
| 158 |
|
| 159 |
-
|
|
|
|
| 160 |
vectorstore = Chroma.from_documents(
|
| 161 |
-
documents=splits,
|
| 162 |
-
embedding=embedding_model,
|
| 163 |
persist_directory=DB_PATH
|
| 164 |
)
|
| 165 |
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
bm25_retriever = BM25Retriever.from_documents(splits)
|
| 170 |
-
bm25_retriever.k =
|
| 171 |
-
chroma_retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
|
| 172 |
|
|
|
|
| 173 |
ensemble_retriever = EnsembleRetriever(
|
| 174 |
retrievers=[bm25_retriever, chroma_retriever],
|
| 175 |
weights=[0.4, 0.6]
|
| 176 |
)
|
|
|
|
| 177 |
return ensemble_retriever
|
| 178 |
|
| 179 |
-
# ==========================================
|
| 180 |
-
# LOGIC CHATBOT THÔNG MINH (CÓ NHỚ)
|
| 181 |
-
# ==========================================
|
| 182 |
-
rag_chain = None
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
if not retriever: return False
|
| 188 |
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
-
# --- BƯỚC 1: Contextualize Question ---
|
| 196 |
-
# (Viết lại câu hỏi mới dựa trên lịch sử để AI hiểu context)
|
| 197 |
-
contextualize_q_system_prompt = (
|
| 198 |
-
"Dựa trên lịch sử trò chuyện và câu hỏi mới nhất của người dùng, "
|
| 199 |
-
"nếu câu hỏi liên quan đến ngữ cảnh trước đó, hãy viết lại nó thành một câu hỏi độc lập đầy đủ ý nghĩa. "
|
| 200 |
-
"Nếu không liên quan, giữ nguyên câu hỏi gốc. KHÔNG trả lời câu hỏi, chỉ viết lại thôi."
|
| 201 |
-
)
|
| 202 |
-
contextualize_q_prompt = ChatPromptTemplate.from_messages([
|
| 203 |
-
("system", contextualize_q_system_prompt),
|
| 204 |
-
MessagesPlaceholder("chat_history"),
|
| 205 |
-
("human", "{input}"),
|
| 206 |
-
])
|
| 207 |
-
# Retriever biết nhớ lịch sử
|
| 208 |
-
history_aware_retriever = create_history_aware_retriever(
|
| 209 |
-
llm, retriever, contextualize_q_prompt
|
| 210 |
-
)
|
| 211 |
|
| 212 |
-
# --- BƯỚC 2: Answer Question ---
|
| 213 |
-
# (Trả lời dựa trên Documents tìm được)
|
| 214 |
-
qa_system_prompt = (
|
| 215 |
-
"Bạn là trợ lý y tế DeepMed. Sử dụng các đoạn văn bản được cung cấp (Context) để trả lời câu hỏi. "
|
| 216 |
-
"Nếu không biết, hãy nói không biết. Nếu tìm thấy nội dung trả lời hãy trích dẫn tài liệu. Giữ câu trả lời ngắn gọn, súc tích.\n\n"
|
| 217 |
-
"Context:\n{context}"
|
| 218 |
-
)
|
| 219 |
-
qa_prompt = ChatPromptTemplate.from_messages([
|
| 220 |
-
("system", qa_system_prompt),
|
| 221 |
-
MessagesPlaceholder("chat_history"),
|
| 222 |
-
("human", "{input}"),
|
| 223 |
-
])
|
| 224 |
-
|
| 225 |
-
question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
|
| 226 |
-
|
| 227 |
-
# Kết hợp lại thành chuỗi RAG hoàn chỉnh
|
| 228 |
-
rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)
|
| 229 |
-
|
| 230 |
-
print("--- Chatbot đã sẵn sàng! ---")
|
| 231 |
-
return True
|
| 232 |
-
|
| 233 |
-
init_success = init_chatbot()
|
| 234 |
-
|
| 235 |
-
# ==========================================
|
| 236 |
-
# HÀM CHAT (Xử lý Lịch sử & Trích dẫn)
|
| 237 |
-
# ==========================================
|
| 238 |
-
def chat(message, history):
|
| 239 |
-
if not init_success:
|
| 240 |
-
return "Hệ thống chưa sẵn sàng. Kiểm tra lại data và API Key."
|
| 241 |
-
|
| 242 |
-
# 1. Chuyển đổi lịch sử Gradio sang format LangChain
|
| 243 |
-
chat_history = []
|
| 244 |
-
for user_msg, bot_msg in history:
|
| 245 |
-
chat_history.append(HumanMessage(content=user_msg))
|
| 246 |
-
chat_history.append(AIMessage(content=bot_msg))
|
| 247 |
-
|
| 248 |
-
try:
|
| 249 |
-
# 2. Gọi Chain xử lý
|
| 250 |
-
response = rag_chain.invoke({
|
| 251 |
-
"input": message,
|
| 252 |
-
"chat_history": chat_history
|
| 253 |
-
})
|
| 254 |
-
|
| 255 |
-
answer = response["answer"]
|
| 256 |
-
|
| 257 |
-
# 3. Xử lý Trích dẫn nguồn (References)
|
| 258 |
-
sources = set()
|
| 259 |
-
if "context" in response:
|
| 260 |
-
for doc in response["context"]:
|
| 261 |
-
source_name = doc.metadata.get("source", "Tài liệu không tên")
|
| 262 |
-
page_num = doc.metadata.get("page", None)
|
| 263 |
-
|
| 264 |
-
# Format tên file cho gọn (bỏ đường dẫn)
|
| 265 |
-
source_name = os.path.basename(source_name)
|
| 266 |
-
|
| 267 |
-
if page_num is not None:
|
| 268 |
-
sources.add(f"{source_name} (Trang {page_num + 1})")
|
| 269 |
-
else:
|
| 270 |
-
sources.add(source_name)
|
| 271 |
-
|
| 272 |
-
if sources:
|
| 273 |
-
answer += "\n\n---\n📚 **Tài liệu tham khảo:**\n" + "\n".join([f"- {s}" for s in sources])
|
| 274 |
-
|
| 275 |
-
return answer
|
| 276 |
-
|
| 277 |
-
except Exception as e:
|
| 278 |
-
return f"Lỗi hệ thống: {str(e)}"
|
| 279 |
-
|
| 280 |
-
# ==========================================
|
| 281 |
-
# GIAO DIỆN
|
| 282 |
-
# ==========================================
|
| 283 |
demo = gr.ChatInterface(
|
| 284 |
-
fn=
|
| 285 |
-
title="🏥 DeepMed AI Pro - Trợ lý Y
|
|
|
|
|
|
|
|
|
|
| 286 |
)
|
| 287 |
|
| 288 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
# =====================================================
|
| 2 |
+
# 1. FIX sqlite3 CHO CHROMA (pysqlite3 hack)
|
| 3 |
+
# =====================================================
|
| 4 |
+
__import__("pysqlite3")
|
| 5 |
import sys
|
| 6 |
+
sys.modules["sqlite3"] = sys.modules.pop("pysqlite3")
|
| 7 |
|
| 8 |
+
# =====================================================
|
| 9 |
+
# 2. IMPORTS
|
| 10 |
+
# =====================================================
|
| 11 |
import os
|
| 12 |
+
import logging
|
| 13 |
+
import traceback
|
| 14 |
|
| 15 |
+
import gradio as gr
|
| 16 |
import pandas as pd
|
| 17 |
import docx2txt
|
|
|
|
|
|
|
| 18 |
|
|
|
|
| 19 |
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 20 |
from langchain_chroma import Chroma
|
| 21 |
+
|
| 22 |
+
from langchain_community.document_loaders import PyPDFLoader
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 24 |
from langchain_community.retrievers import BM25Retriever
|
| 25 |
from langchain.retrievers.ensemble import EnsembleRetriever
|
| 26 |
+
|
| 27 |
from langchain.chains import create_retrieval_chain, create_history_aware_retriever
|
| 28 |
from langchain.chains.combine_documents import create_stuff_documents_chain
|
| 29 |
+
|
| 30 |
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 31 |
from langchain_core.messages import HumanMessage, AIMessage
|
| 32 |
from langchain_core.documents import Document
|
| 33 |
+
|
| 34 |
from langchain_huggingface import HuggingFaceEmbeddings
|
| 35 |
|
| 36 |
+
|
| 37 |
+
# =====================================================
|
| 38 |
+
# 3. CẤU HÌNH CHUNG
|
| 39 |
+
# =====================================================
|
| 40 |
+
|
| 41 |
+
# Lấy API key từ biến môi trường
|
| 42 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 43 |
+
|
| 44 |
+
DATA_PATH = "medical_data" # thư mục chứa tài liệu
|
| 45 |
+
DB_PATH = "chroma_db" # thư mục chứa database Chroma
|
| 46 |
+
|
| 47 |
+
# Số lượt đối thoại gần nhất gửi vào LLM (mỗi lượt gồm 1 user + 1 bot)
|
| 48 |
+
MAX_HISTORY_TURNS = 6
|
| 49 |
+
|
| 50 |
+
# Chọn chiến lược truy vấn:
|
| 51 |
+
USE_BM25 = True # True = dùng hybrid (BM25 + Vector), False = chỉ dùng Vector
|
| 52 |
+
USE_MMR = True # True = dùng MMR cho retriever vector
|
| 53 |
+
|
| 54 |
+
# Logging cơ bản
|
| 55 |
+
logging.basicConfig(
|
| 56 |
+
level=logging.INFO,
|
| 57 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# =====================================================
|
| 62 |
+
# 4. HÀM LOAD TÀI LIỆU ĐA ĐỊNH DẠNG (PDF, DOCX, EXCEL, CSV, TXT, MD)
|
| 63 |
+
# =====================================================
|
| 64 |
+
|
| 65 |
+
def load_documents_from_folder(folder_path: str) -> list[Document]:
|
| 66 |
+
"""
|
| 67 |
+
Quét thư mục (kể cả subfolder), đọc các file hỗ trợ và trả về list Document.
|
| 68 |
+
"""
|
| 69 |
+
logging.info(f"--- Bắt đầu quét thư mục: {folder_path} ---")
|
| 70 |
+
documents: list[Document] = []
|
| 71 |
+
|
| 72 |
if not os.path.exists(folder_path):
|
| 73 |
+
os.makedirs(folder_path, exist_ok=True)
|
| 74 |
+
logging.warning(f"Thư mục {folder_path} chưa tồn tại. Đã tạo mới, tạm thời chưa có tài liệu.")
|
| 75 |
return []
|
| 76 |
|
| 77 |
+
for root, _, files in os.walk(folder_path):
|
| 78 |
+
for filename in files:
|
| 79 |
+
file_path = os.path.join(root, filename)
|
| 80 |
+
filename_lower = filename.lower()
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
# 1. PDF
|
| 84 |
+
if filename_lower.endswith(".pdf"):
|
| 85 |
+
logging.info(f"-> Đang xử lý PDF: {file_path}")
|
| 86 |
+
loader = PyPDFLoader(file_path)
|
| 87 |
+
docs = loader.load() # mỗi trang = 1 Document
|
| 88 |
+
# Thêm metadata source gọn (chỉ tên file)
|
| 89 |
+
for d in docs:
|
| 90 |
+
d.metadata["source"] = filename
|
| 91 |
+
documents.extend(docs)
|
| 92 |
+
|
| 93 |
+
# 2. DOCX
|
| 94 |
+
elif filename_lower.endswith(".docx"):
|
| 95 |
+
logging.info(f"-> Đang xử lý Word: {file_path}")
|
| 96 |
+
text = docx2txt.process(file_path)
|
| 97 |
+
if text and text.strip():
|
| 98 |
+
documents.append(
|
| 99 |
+
Document(
|
| 100 |
+
page_content=text,
|
| 101 |
+
metadata={"source": filename}
|
| 102 |
+
)
|
| 103 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
else:
|
| 105 |
+
logging.warning(f"File Word rỗng: {filename}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
# 3. EXCEL (XLS, XLSX)
|
| 108 |
+
elif filename_lower.endswith((".xlsx", ".xls")):
|
| 109 |
+
logging.info(f"-> Đang xử lý Excel: {file_path}")
|
| 110 |
+
try:
|
| 111 |
+
df = pd.read_excel(file_path)
|
| 112 |
+
text_data = ""
|
| 113 |
+
for _, row in df.iterrows():
|
| 114 |
+
row_str = " | ".join(
|
| 115 |
+
f"{col}: {val}"
|
| 116 |
+
for col, val in row.items()
|
| 117 |
+
if pd.notna(val)
|
| 118 |
+
)
|
| 119 |
+
if row_str:
|
| 120 |
+
text_data += row_str + "\n"
|
| 121 |
+
if text_data.strip():
|
| 122 |
+
documents.append(
|
| 123 |
+
Document(
|
| 124 |
+
page_content=text_data,
|
| 125 |
+
metadata={"source": filename}
|
| 126 |
+
)
|
| 127 |
+
)
|
| 128 |
+
else:
|
| 129 |
+
logging.warning(f"File Excel rỗng: {filename}")
|
| 130 |
+
except Exception as e:
|
| 131 |
+
logging.error(f"Lỗi đọc Excel {filename}: {e}")
|
| 132 |
|
| 133 |
+
# 4. CSV
|
| 134 |
+
elif filename_lower.endswith(".csv"):
|
| 135 |
+
logging.info(f"-> Đang xử lý CSV: {file_path}")
|
| 136 |
+
try:
|
| 137 |
+
df = pd.read_csv(file_path)
|
| 138 |
+
text_data = ""
|
| 139 |
+
for _, row in df.iterrows():
|
| 140 |
+
row_str = " | ".join(
|
| 141 |
+
f"{col}: {val}"
|
| 142 |
+
for col, val in row.items()
|
| 143 |
+
if pd.notna(val)
|
| 144 |
+
)
|
| 145 |
+
if row_str:
|
| 146 |
+
text_data += row_str + "\n"
|
| 147 |
+
if text_data.strip():
|
| 148 |
+
documents.append(
|
| 149 |
+
Document(
|
| 150 |
+
page_content=text_data,
|
| 151 |
+
metadata={"source": filename}
|
| 152 |
+
)
|
| 153 |
+
)
|
| 154 |
+
else:
|
| 155 |
+
logging.warning(f"File CSV rỗng: {filename}")
|
| 156 |
+
except Exception as e:
|
| 157 |
+
logging.error(f"Lỗi đọc CSV {filename}: {e}")
|
| 158 |
|
| 159 |
+
# 5. TEXT / MARKDOWN
|
| 160 |
+
elif filename_lower.endswith((".txt", ".md")):
|
| 161 |
+
logging.info(f"-> Đang xử lý Text/Markdown: {file_path}")
|
| 162 |
+
text = ""
|
| 163 |
+
try:
|
| 164 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 165 |
+
text = f.read()
|
| 166 |
+
except UnicodeDecodeError:
|
| 167 |
+
logging.warning(f"Encoding UTF-8 thất bại, thử Latin-1 cho {filename}")
|
| 168 |
+
with open(file_path, "r", encoding="latin-1") as f:
|
| 169 |
+
text = f.read()
|
| 170 |
+
|
| 171 |
+
if text and text.strip():
|
| 172 |
+
documents.append(
|
| 173 |
+
Document(
|
| 174 |
+
page_content=text,
|
| 175 |
+
metadata={"source": filename}
|
| 176 |
+
)
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
else:
|
| 180 |
+
logging.info(f"-> Bỏ qua file không hỗ trợ: {file_path}")
|
| 181 |
+
|
| 182 |
+
except Exception as e:
|
| 183 |
+
logging.error(f"❌ LỖI khi đọc file {filename}: {e}")
|
| 184 |
+
logging.debug(traceback.format_exc())
|
| 185 |
+
|
| 186 |
+
logging.info(f"--- Hoàn tất load tài liệu. Tổng số Document: {len(documents)} ---")
|
| 187 |
return documents
|
| 188 |
|
|
|
|
|
|
|
|
|
|
| 189 |
|
| 190 |
+
# =====================================================
|
| 191 |
+
# 5. XÂY DỰNG VECTORSTORE + RETRIEVER
|
| 192 |
+
# =====================================================
|
| 193 |
+
|
| 194 |
+
def build_vectorstore_and_corpus(embedding_model):
|
| 195 |
+
"""
|
| 196 |
+
- Nếu đã có DB Chroma: load lên.
|
| 197 |
+
- Nếu chưa: đọc folder, split, tạo DB mới.
|
| 198 |
+
Trả về (vectorstore, splits).
|
| 199 |
+
"""
|
| 200 |
+
from shutil import rmtree
|
| 201 |
+
|
| 202 |
+
splits: list[Document] = []
|
| 203 |
vectorstore = None
|
| 204 |
+
|
| 205 |
+
# TH1: có DB cũ
|
| 206 |
if os.path.exists(DB_PATH) and os.listdir(DB_PATH):
|
| 207 |
try:
|
| 208 |
+
logging.info("--- Tìm thấy ChromaDB cũ, đang load... ---")
|
| 209 |
+
vectorstore = Chroma(
|
| 210 |
+
persist_directory=DB_PATH,
|
| 211 |
+
embedding_function=embedding_model
|
| 212 |
+
)
|
| 213 |
+
existing = vectorstore.get()
|
| 214 |
+
if existing.get("documents"):
|
| 215 |
+
for text, meta in zip(existing["documents"], existing["metadatas"]):
|
| 216 |
splits.append(Document(page_content=text, metadata=meta))
|
| 217 |
+
logging.info(f"Tải lại corpus từ DB, tổng số chunk: {len(splits)}")
|
| 218 |
else:
|
| 219 |
+
logging.warning("ChromaDB không chứa documents. Sẽ rebuild.")
|
| 220 |
+
splits = []
|
| 221 |
except Exception as e:
|
| 222 |
+
logging.error(f"Lỗi đọc DB cũ: {e}. Xóa và rebuild lại.")
|
| 223 |
+
logging.debug(traceback.format_exc())
|
| 224 |
+
rmtree(DB_PATH, ignore_errors=True)
|
| 225 |
+
splits = []
|
| 226 |
+
vectorstore = None
|
| 227 |
|
| 228 |
+
# TH2: chưa có dữ liệu trong splits → đọc file gốc, split và tạo DB mới
|
| 229 |
if not splits:
|
| 230 |
+
logging.info("--- Đang đọc tài liệu gốc để tạo index mới... ---")
|
| 231 |
documents = load_documents_from_folder(DATA_PATH)
|
|
|
|
| 232 |
if not documents:
|
| 233 |
+
logging.error("Không tìm thấy tài liệu nào trong thư mục medical_data.")
|
| 234 |
+
return None, []
|
| 235 |
|
| 236 |
+
# Chunking
|
| 237 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 238 |
+
chunk_size=800, # nhỏ hơn cho câu trả lời cụ thể hơn
|
| 239 |
+
chunk_overlap=150
|
| 240 |
+
)
|
| 241 |
splits = text_splitter.split_documents(documents)
|
| 242 |
+
logging.info(f"Đã split thành {len(splits)} chunks.")
|
| 243 |
|
| 244 |
+
# Tạo Chroma mới
|
| 245 |
+
logging.info("--- Đang mã hoá embedding vào ChromaDB... ---")
|
| 246 |
vectorstore = Chroma.from_documents(
|
| 247 |
+
documents=splits,
|
| 248 |
+
embedding=embedding_model,
|
| 249 |
persist_directory=DB_PATH
|
| 250 |
)
|
| 251 |
|
| 252 |
+
return vectorstore, splits
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def get_retriever():
|
| 256 |
+
"""
|
| 257 |
+
Khởi tạo retriever:
|
| 258 |
+
- Load hoặc tạo ChromaDB.
|
| 259 |
+
- Tuỳ cấu hình: dùng hybrid (BM25 + Vector) hoặc chỉ Vector.
|
| 260 |
+
- Có thể dùng MMR để tăng đa dạng context.
|
| 261 |
+
"""
|
| 262 |
+
logging.info("--- Đang tải model Embedding (HuggingFace) ---")
|
| 263 |
+
embedding_model = HuggingFaceEmbeddings(
|
| 264 |
+
model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
vectorstore, splits = build_vectorstore_and_corpus(embedding_model)
|
| 268 |
+
if vectorstore is None or not splits:
|
| 269 |
+
logging.error("Không thể khởi tạo retriever vì không có dữ liệu.")
|
| 270 |
+
return None
|
| 271 |
+
|
| 272 |
+
# Vector retriever (có thể dùng MMR)
|
| 273 |
+
if USE_MMR:
|
| 274 |
+
logging.info("Sử dụng Vector Retriever với MMR.")
|
| 275 |
+
chroma_retriever = vectorstore.as_retriever(
|
| 276 |
+
search_type="mmr",
|
| 277 |
+
search_kwargs={"k": 8, "lambda_mult": 0.7}
|
| 278 |
+
)
|
| 279 |
+
else:
|
| 280 |
+
logging.info("Sử dụng Vector Retriever với similarity search.")
|
| 281 |
+
chroma_retriever = vectorstore.as_retriever(
|
| 282 |
+
search_kwargs={"k": 8}
|
| 283 |
+
)
|
| 284 |
|
| 285 |
+
# Nếu không muốn dùng BM25 -> trả về luôn retriever vector
|
| 286 |
+
if not USE_BM25:
|
| 287 |
+
logging.info("Chỉ dùng retriever Vector (không dùng BM25).")
|
| 288 |
+
return chroma_retriever
|
| 289 |
+
|
| 290 |
+
# Tạo BM25 retriever từ corpus
|
| 291 |
+
logging.info("Khởi tạo BM25 Retriever từ corpus (hybrid search).")
|
| 292 |
bm25_retriever = BM25Retriever.from_documents(splits)
|
| 293 |
+
bm25_retriever.k = 8
|
|
|
|
| 294 |
|
| 295 |
+
# Ensemble retriever: BM25 + Vector
|
| 296 |
ensemble_retriever = EnsembleRetriever(
|
| 297 |
retrievers=[bm25_retriever, chroma_retriever],
|
| 298 |
weights=[0.4, 0.6]
|
| 299 |
)
|
| 300 |
+
logging.info("Đã khởi tạo Ensemble Retriever (BM25 + Vector).")
|
| 301 |
return ensemble_retriever
|
| 302 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
|
| 304 |
+
# =====================================================
|
| 305 |
+
# 6. LỚP CHATBOT DEEPMED
|
| 306 |
+
# =====================================================
|
|
|
|
| 307 |
|
| 308 |
+
class DeepMedBot:
|
| 309 |
+
def __init__(self):
|
| 310 |
+
self.retriever = None
|
| 311 |
+
self.rag_chain = None
|
| 312 |
+
self.ready = False
|
| 313 |
+
|
| 314 |
+
if not GOOGLE_API_KEY:
|
| 315 |
+
logging.error("GOOGLE_API_KEY chưa được thiết lập trong biến môi trường.")
|
| 316 |
+
return
|
| 317 |
+
|
| 318 |
+
try:
|
| 319 |
+
self.retriever = get_retriever()
|
| 320 |
+
if self.retriever is None:
|
| 321 |
+
logging.error("Không khởi tạo được retriever.")
|
| 322 |
+
return
|
| 323 |
+
|
| 324 |
+
self.llm = ChatGoogleGenerativeAI(
|
| 325 |
+
model="gemini-2.5-flash", # có thể đổi sang model mạnh hơn nếu muốn
|
| 326 |
+
temperature=0.3,
|
| 327 |
+
google_api_key=GOOGLE_API_KEY
|
| 328 |
+
)
|
| 329 |
+
self._build_chains()
|
| 330 |
+
self.ready = True
|
| 331 |
+
logging.info("--- DeepMedBot đã sẵn sàng ---")
|
| 332 |
+
except Exception as e:
|
| 333 |
+
logging.error(f"Lỗi khởi tạo DeepMedBot: {e}")
|
| 334 |
+
logging.debug(traceback.format_exc())
|
| 335 |
+
self.ready = False
|
| 336 |
+
|
| 337 |
+
def _build_chains(self):
|
| 338 |
+
# 1. Prompt contextualize question
|
| 339 |
+
contextualize_q_system_prompt = (
|
| 340 |
+
"Dựa trên lịch sử trò chuyện và câu hỏi mới nhất của người dùng, "
|
| 341 |
+
"nếu câu hỏi liên quan đến ngữ cảnh trước đó, hãy viết lại nó thành một câu hỏi độc lập đầy đủ ý nghĩa. "
|
| 342 |
+
"Nếu không liên quan, giữ nguyên câu hỏi gốc. KHÔNG trả lời câu hỏi, chỉ viết lại."
|
| 343 |
+
)
|
| 344 |
+
contextualize_q_prompt = ChatPromptTemplate.from_messages([
|
| 345 |
+
("system", contextualize_q_system_prompt),
|
| 346 |
+
MessagesPlaceholder("chat_history"),
|
| 347 |
+
("human", "{input}"),
|
| 348 |
+
])
|
| 349 |
+
|
| 350 |
+
history_aware_retriever = create_history_aware_retriever(
|
| 351 |
+
self.llm, self.retriever, contextualize_q_prompt
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
# 2. Prompt trả lời y khoa an toàn
|
| 355 |
+
qa_system_prompt = (
|
| 356 |
+
"Bạn là trợ lý y tế DeepMed. Bạn hỗ trợ giải thích thông tin y khoa dựa trên tài liệu được cung cấp (Context) "
|
| 357 |
+
"và kiến thức y khoa chung của bạn.\n\n"
|
| 358 |
+
"QUY TẮC AN TOÀN:\n"
|
| 359 |
+
"- Nếu Context không đủ để trả lời chính xác, hãy nói bạn không chắc chắn và khuyên người dùng hỏi bác sĩ.\n"
|
| 360 |
+
"- Ưu tiên sử dụng thông tin trong Context. Nếu có mâu thuẫn giữa Context và hiểu biết của bạn, "
|
| 361 |
+
"hãy nói rõ và khuyên tham khảo nguồn chính thống mới nhất.\n\n"
|
| 362 |
+
"CÁCH TRẢ LỜI:\n"
|
| 363 |
+
"- Trả lời ngắn gọn, dễ hiểu.\n"
|
| 364 |
+
"- Nếu phù hợp, chia câu trả lời thành các mục: Tóm tắt, Chi tiết, Lưu ý.\n\n"
|
| 365 |
+
"Context:\n{context}"
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
qa_prompt = ChatPromptTemplate.from_messages([
|
| 369 |
+
("system", qa_system_prompt),
|
| 370 |
+
MessagesPlaceholder("chat_history"),
|
| 371 |
+
("human", "{input}"),
|
| 372 |
+
])
|
| 373 |
+
|
| 374 |
+
question_answer_chain = create_stuff_documents_chain(self.llm, qa_prompt)
|
| 375 |
+
|
| 376 |
+
# 3. Gộp thành RAG chain
|
| 377 |
+
self.rag_chain = create_retrieval_chain(
|
| 378 |
+
history_aware_retriever,
|
| 379 |
+
question_answer_chain
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
def chat(self, message: str, history: list[list[str]]):
|
| 383 |
+
"""
|
| 384 |
+
Hàm dùng cho Gradio:
|
| 385 |
+
- history: list[[user_msg, bot_msg], ...]
|
| 386 |
+
"""
|
| 387 |
+
if not self.ready:
|
| 388 |
+
return "❗ Hệ thống chưa sẵn sàng. Vui lòng kiểm tra lại API key và dữ liệu (medical_data)."
|
| 389 |
+
|
| 390 |
+
# Giới hạn lịch sử gửi vào LLM cho đỡ nặng
|
| 391 |
+
if len(history) > MAX_HISTORY_TURNS:
|
| 392 |
+
history = history[-MAX_HISTORY_TURNS:]
|
| 393 |
+
|
| 394 |
+
# Chuyển lịch sử Gradio sang LangChain messages
|
| 395 |
+
chat_history = []
|
| 396 |
+
for user_msg, bot_msg in history:
|
| 397 |
+
chat_history.append(HumanMessage(content=user_msg))
|
| 398 |
+
chat_history.append(AIMessage(content=bot_msg))
|
| 399 |
+
|
| 400 |
+
try:
|
| 401 |
+
response = self.rag_chain.invoke({
|
| 402 |
+
"input": message,
|
| 403 |
+
"chat_history": chat_history
|
| 404 |
+
})
|
| 405 |
+
|
| 406 |
+
answer = response.get("answer", "")
|
| 407 |
+
|
| 408 |
+
# Xử lý trích dẫn nguồn
|
| 409 |
+
references_text = self._build_references_text(response)
|
| 410 |
+
if references_text:
|
| 411 |
+
answer += "\n\n---\n📚 **Tài liệu tham khảo:**\n" + references_text
|
| 412 |
+
|
| 413 |
+
return answer
|
| 414 |
+
|
| 415 |
+
except Exception as e:
|
| 416 |
+
logging.error(f"Lỗi khi xử lý chat: {e}")
|
| 417 |
+
logging.debug(traceback.format_exc())
|
| 418 |
+
return "🤖 Xin lỗi, hệ thống gặp lỗi nội bộ. Bạn hãy thử lại sau ít phút."
|
| 419 |
+
|
| 420 |
+
@staticmethod
|
| 421 |
+
def _build_references_text(response) -> str:
|
| 422 |
+
"""
|
| 423 |
+
Gom nguồn trích dẫn:
|
| 424 |
+
- Gộp theo tên file.
|
| 425 |
+
- Nếu có số trang, liệt kê danh sách trang.
|
| 426 |
+
"""
|
| 427 |
+
from collections import defaultdict
|
| 428 |
+
if "context" not in response:
|
| 429 |
+
return ""
|
| 430 |
+
|
| 431 |
+
source_pages = defaultdict(set) # {source_name: {page1, page2, ...}}
|
| 432 |
+
|
| 433 |
+
for doc in response["context"]:
|
| 434 |
+
src = os.path.basename(doc.metadata.get("source", "Tài liệu không tên"))
|
| 435 |
+
page = doc.metadata.get("page", None)
|
| 436 |
+
if page is not None:
|
| 437 |
+
source_pages[src].add(page + 1)
|
| 438 |
+
else:
|
| 439 |
+
# Đảm bảo vẫn tạo key nếu chưa có trang
|
| 440 |
+
_ = source_pages[src]
|
| 441 |
+
|
| 442 |
+
lines = []
|
| 443 |
+
for src, pages in source_pages.items():
|
| 444 |
+
if pages:
|
| 445 |
+
pages_str = ", ".join(str(p) for p in sorted(pages))
|
| 446 |
+
lines.append(f"- {src} (Trang {pages_str})")
|
| 447 |
+
else:
|
| 448 |
+
lines.append(f"- {src}")
|
| 449 |
+
|
| 450 |
+
return "\n".join(lines)
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
bot = DeepMedBot()
|
| 455 |
+
|
| 456 |
+
def gradio_chat(message, history):
|
| 457 |
+
return bot.chat(message, history)
|
| 458 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 459 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
demo = gr.ChatInterface(
|
| 461 |
+
fn=gradio_chat,
|
| 462 |
+
title="🏥 DeepMed AI Pro - Trợ lý Y tế tại Trung Tâm Y Tế khu vực Thanh Ba",
|
| 463 |
+
description=(
|
| 464 |
+
"Chatbot hỗ trợ tra cứu thông tin y khoa từ kho tài liệu nội bộ.\n"
|
| 465 |
+
),
|
| 466 |
)
|
| 467 |
|
| 468 |
if __name__ == "__main__":
|