fix cache
Browse files- rag_core/business.py +34 -32
- rag_core/retriever.py +6 -4
rag_core/business.py
CHANGED
|
@@ -1,61 +1,63 @@
|
|
| 1 |
-
import os
|
| 2 |
import logging
|
| 3 |
from rag_core.chunker import chunk_legal_text
|
| 4 |
from rag_core.embedder import get_embedding
|
| 5 |
from rag_core.retriever import Retriever
|
| 6 |
from rag_core.llm import generate_answer
|
|
|
|
| 7 |
|
| 8 |
retriever = Retriever()
|
|
|
|
| 9 |
|
| 10 |
def is_ready():
|
| 11 |
-
ready = retriever.index is not None
|
| 12 |
-
logging.info(f"✅ Kiểm tra index sẵn sàng: {ready}")
|
| 13 |
return ready
|
| 14 |
|
|
|
|
| 15 |
def build_index():
|
| 16 |
-
|
|
|
|
| 17 |
try:
|
| 18 |
with open("data/raw_law.txt", "r", encoding="utf-8") as f:
|
| 19 |
text = f.read()
|
| 20 |
-
logging.info(f"📄 Đọc văn bản thành công, độ dài: {len(text)} ký tự")
|
| 21 |
chunks = chunk_legal_text(text)
|
| 22 |
-
logging.info(f"✂️ Đã chunk thành {len(chunks)} đoạn")
|
| 23 |
retriever.build(chunks, get_embedding)
|
|
|
|
| 24 |
logging.info("✅ Xây FAISS index thành công.")
|
| 25 |
except Exception as e:
|
| 26 |
-
logging.
|
|
|
|
| 27 |
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
logging.info(f"❓ Nhận câu hỏi: {query}")
|
| 30 |
-
if not
|
| 31 |
-
logging.warning("⚠️ Index chưa sẵn sàng
|
| 32 |
-
return {"error": "Index chưa sẵn sàng. Vui lòng bấm '
|
| 33 |
try:
|
| 34 |
docs = retriever.query(query, get_embedding)
|
| 35 |
logging.info(f"📚 Truy xuất được {len(docs)} đoạn liên quan")
|
| 36 |
prompt = "\n\n".join(docs) + f"\n\nCâu hỏi: {query}\nTrả lời:"
|
| 37 |
answer = generate_answer(prompt)
|
| 38 |
-
logging.info("✅ Đã tạo câu trả lời thành công.")
|
| 39 |
return {"answer": answer}
|
| 40 |
except Exception as e:
|
| 41 |
-
logging.
|
| 42 |
return {"error": str(e)}
|
| 43 |
-
|
| 44 |
-
def rescan_index():
|
| 45 |
-
if not is_ready():
|
| 46 |
-
logging.info("⚠️ Chưa có index, gọi build_index() thay vì rescan.")
|
| 47 |
-
build_index()
|
| 48 |
-
return {"status": "✅ Đã tạo mới FAISS index."}
|
| 49 |
-
logging.info("♻️ Tiến hành rescan và cập nhật các chunk mới...")
|
| 50 |
-
try:
|
| 51 |
-
with open("data/raw_law.txt", "r", encoding="utf-8") as f:
|
| 52 |
-
text = f.read()
|
| 53 |
-
logging.info(f"📄 Đọc văn bản thành công, độ dài: {len(text)} ký tự")
|
| 54 |
-
chunks = chunk_legal_text(text)
|
| 55 |
-
logging.info(f"✂️ Đã chunk thành {len(chunks)} đoạn")
|
| 56 |
-
retriever.rescan_and_append(chunks, get_embedding)
|
| 57 |
-
logging.info("✅ Rescan hoàn tất.")
|
| 58 |
-
return {"status": "✅ Rescan & update thành công."}
|
| 59 |
-
except Exception as e:
|
| 60 |
-
logging.exception(f"❌ Lỗi trong quá trình rescan: {e}")
|
| 61 |
-
return {"status": f"Lỗi: {str(e)}"}
|
|
|
|
|
|
|
| 1 |
import logging
|
| 2 |
from rag_core.chunker import chunk_legal_text
|
| 3 |
from rag_core.embedder import get_embedding
|
| 4 |
from rag_core.retriever import Retriever
|
| 5 |
from rag_core.llm import generate_answer
|
| 6 |
+
from rag_core.utils import log_timed
|
| 7 |
|
| 8 |
retriever = Retriever()
|
| 9 |
+
ready = retriever.index is not None
|
| 10 |
|
| 11 |
def is_ready():
|
|
|
|
|
|
|
| 12 |
return ready
|
| 13 |
|
| 14 |
+
@log_timed("xây FAISS index")
|
| 15 |
def build_index():
|
| 16 |
+
global ready
|
| 17 |
+
logging.info("🔄 Bắt đầu xây FAISS index từ file dữ liệu...")
|
| 18 |
try:
|
| 19 |
with open("data/raw_law.txt", "r", encoding="utf-8") as f:
|
| 20 |
text = f.read()
|
|
|
|
| 21 |
chunks = chunk_legal_text(text)
|
|
|
|
| 22 |
retriever.build(chunks, get_embedding)
|
| 23 |
+
ready = True
|
| 24 |
logging.info("✅ Xây FAISS index thành công.")
|
| 25 |
except Exception as e:
|
| 26 |
+
logging.error(f"❌ Lỗi khi xây index: {e}")
|
| 27 |
+
raise
|
| 28 |
|
| 29 |
+
@log_timed("rescan FAISS index")
|
| 30 |
+
def rescan_index():
|
| 31 |
+
global ready
|
| 32 |
+
logging.info("🔍 Bắt đầu kiểm tra và cập nhật index...")
|
| 33 |
+
if retriever.index is None:
|
| 34 |
+
logging.info("⚠️ Chưa có index. Gọi build_index().")
|
| 35 |
+
build_index()
|
| 36 |
+
return {"status": "✅ Tạo mới FAISS index."}
|
| 37 |
+
else:
|
| 38 |
+
try:
|
| 39 |
+
with open("data/raw_law.txt", "r", encoding="utf-8") as f:
|
| 40 |
+
text = f.read()
|
| 41 |
+
chunks = chunk_legal_text(text)
|
| 42 |
+
retriever.rescan_and_append(chunks, get_embedding)
|
| 43 |
+
logging.info("✅ Đã cập nhật index với các chunk mới.")
|
| 44 |
+
return {"status": "✅ Rescan & update thành công."}
|
| 45 |
+
except Exception as e:
|
| 46 |
+
logging.error(f"❌ Lỗi khi rescan index: {e}")
|
| 47 |
+
return {"status": f"❌ Lỗi khi rescan: {e}"}
|
| 48 |
+
|
| 49 |
+
@log_timed("trả lời câu hỏi")
|
| 50 |
+
def answer_query(query: str) -> str:
|
| 51 |
logging.info(f"❓ Nhận câu hỏi: {query}")
|
| 52 |
+
if not ready:
|
| 53 |
+
logging.warning("⚠️ Index chưa sẵn sàng.")
|
| 54 |
+
return {"error": "Index chưa sẵn sàng. Vui lòng bấm 'Xây Index' hoặc gọi API /rescan."}
|
| 55 |
try:
|
| 56 |
docs = retriever.query(query, get_embedding)
|
| 57 |
logging.info(f"📚 Truy xuất được {len(docs)} đoạn liên quan")
|
| 58 |
prompt = "\n\n".join(docs) + f"\n\nCâu hỏi: {query}\nTrả lời:"
|
| 59 |
answer = generate_answer(prompt)
|
|
|
|
| 60 |
return {"answer": answer}
|
| 61 |
except Exception as e:
|
| 62 |
+
logging.error(f"❌ Lỗi khi trả lời câu hỏi: {e}")
|
| 63 |
return {"error": str(e)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rag_core/retriever.py
CHANGED
|
@@ -5,17 +5,19 @@ import pickle
|
|
| 5 |
import logging
|
| 6 |
from rag_core.utils import log_timed
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
INDEX_PATH = "/data/index.faiss"
|
| 10 |
-
META_PATH = "/data/meta.pkl"
|
| 11 |
|
| 12 |
class Retriever:
|
| 13 |
def __init__(self):
|
| 14 |
if os.path.exists(INDEX_PATH):
|
|
|
|
| 15 |
self.index = faiss.read_index(INDEX_PATH)
|
| 16 |
with open(META_PATH, "rb") as f:
|
| 17 |
self.texts = pickle.load(f)
|
| 18 |
else:
|
|
|
|
| 19 |
self.index = None
|
| 20 |
self.texts = []
|
| 21 |
|
|
@@ -54,7 +56,7 @@ class Retriever:
|
|
| 54 |
existing_set = set(self.texts)
|
| 55 |
new_texts = [t for t in full_texts if t not in existing_set]
|
| 56 |
if not new_texts:
|
| 57 |
-
logging.info("Không có chunk mới để thêm.")
|
| 58 |
return
|
| 59 |
new_embeddings = []
|
| 60 |
for i, t in enumerate(new_texts):
|
|
|
|
| 5 |
import logging
|
| 6 |
from rag_core.utils import log_timed
|
| 7 |
|
| 8 |
+
# ✅ Sử dụng thư mục tương đối, tránh bị hiểu nhầm sang /data (root)
|
| 9 |
+
INDEX_PATH = "./data/index.faiss"
|
| 10 |
+
META_PATH = "./data/meta.pkl"
|
| 11 |
|
| 12 |
class Retriever:
|
| 13 |
def __init__(self):
|
| 14 |
if os.path.exists(INDEX_PATH):
|
| 15 |
+
logging.info(f"✅ Đã tìm thấy index: {INDEX_PATH}")
|
| 16 |
self.index = faiss.read_index(INDEX_PATH)
|
| 17 |
with open(META_PATH, "rb") as f:
|
| 18 |
self.texts = pickle.load(f)
|
| 19 |
else:
|
| 20 |
+
logging.info("⚠️ Chưa có index. Cần xây dựng mới.")
|
| 21 |
self.index = None
|
| 22 |
self.texts = []
|
| 23 |
|
|
|
|
| 56 |
existing_set = set(self.texts)
|
| 57 |
new_texts = [t for t in full_texts if t not in existing_set]
|
| 58 |
if not new_texts:
|
| 59 |
+
logging.info("📭 Không có chunk mới để thêm.")
|
| 60 |
return
|
| 61 |
new_embeddings = []
|
| 62 |
for i, t in enumerate(new_texts):
|