VietCat commited on
Commit
7dcd77a
·
1 Parent(s): af30c7d
Files changed (5) hide show
  1. .gitignore +24 -0
  2. Dockerfile +7 -0
  3. README.md +5 -0
  4. rag_core/llm.py +16 -6
  5. rag_core/retriever.py +4 -7
.gitignore CHANGED
@@ -1,2 +1,26 @@
1
  # files
2
  *.DS_Store
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # files
2
  *.DS_Store
3
+ # Ignore Python cache & virtual env
4
+ __pycache__/
5
+ *.py[cod]
6
+ *.egg-info/
7
+ .venv/
8
+ env/
9
+ venv/
10
+
11
+ # Ignore Jupyter checkpoints
12
+ .ipynb_checkpoints/
13
+
14
+ # Ignore model checkpoints if any
15
+ *.ckpt
16
+ *.pt
17
+ *.bin
18
+
19
+ # Hugging Face Spaces: keep data/index.faiss
20
+ # But ignore any other temp or large files optionally
21
+ # DO NOT IGNORE data/index.faiss or data/raw_law.txt
22
+ # So we do NOT put 'data/' in here
23
+
24
+ # Optional: ignore large test dumps
25
+ *.log
26
+ *.tmp
Dockerfile CHANGED
@@ -6,8 +6,15 @@ WORKDIR /app
6
  # Sao chép toàn bộ nội dung project
7
  COPY . .
8
 
 
 
 
 
 
9
  # ✅ Tạo thư mục FAISS index và gán quyền đầy đủ
10
  RUN mkdir -p faiss_index && chmod -R 777 faiss_index
 
 
11
 
12
  # Cài đặt dependencies
13
  RUN pip install --upgrade pip
 
6
  # Sao chép toàn bộ nội dung project
7
  COPY . .
8
 
9
+ # Cài đặt g++ để build FAISS
10
+ RUN apt-get update && apt-get install -y \
11
+ build-essential \
12
+ && rm -rf /var/lib/apt/lists/*
13
+
14
  # ✅ Tạo thư mục FAISS index và gán quyền đầy đủ
15
  RUN mkdir -p faiss_index && chmod -R 777 faiss_index
16
+ # Tạo thư mục FAISS index cache
17
+ RUN mkdir -p /data
18
 
19
  # Cài đặt dependencies
20
  RUN pip install --upgrade pip
README.md CHANGED
@@ -9,3 +9,8 @@ short_description: 'A sample for RAG implementation '
9
  ---
10
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
9
  ---
10
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
12
+
13
+ # 📚 Trợ lý Hỏi Đáp Luật Giao Thông (RAG)
14
+ - Build index từ luật giao thông Việt Nam.
15
+ - Có thể cache FAISS index tại `/data` để tránh build lại mỗi lần khởi động.
16
+ - Bao gồm API (`/ask`, `/rescan`) và UI Gradio tại `/`.
rag_core/llm.py CHANGED
@@ -1,11 +1,21 @@
1
  import requests
 
2
  from rag_core.utils import log_timed
3
 
4
  @log_timed("gửi prompt tới LLM")
5
  def generate_answer(prompt: str) -> str:
6
- response = requests.post(
7
- "https://vietcat-gemma34b.hf.space/purechat",
8
- json={"prompt": prompt},
9
- timeout=30
10
- )
11
- return response.json()["response"]
 
 
 
 
 
 
 
 
 
 
1
  import requests
2
+ import logging
3
  from rag_core.utils import log_timed
4
 
5
  @log_timed("gửi prompt tới LLM")
6
  def generate_answer(prompt: str) -> str:
7
+ try:
8
+ response = requests.post(
9
+ "https://vietcat-gemma34b.hf.space/purechat",
10
+ json={"prompt": prompt},
11
+ timeout=60
12
+ )
13
+ response.raise_for_status()
14
+ json_data = response.json()
15
+ return json_data.get("response", "⚠️ LLM không trả về kết quả.")
16
+ except requests.exceptions.RequestException as e:
17
+ logging.error(f"❌ Lỗi khi gửi request tới LLM: {e}")
18
+ return f"❌ Không thể kết nối đến LLM: {e}"
19
+ except ValueError as e:
20
+ logging.error(f"❌ Phản hồi từ LLM không hợp lệ JSON: {response.text}")
21
+ return f"❌ Lỗi phân tích JSON từ LLM."
rag_core/retriever.py CHANGED
@@ -5,8 +5,9 @@ import pickle
5
  import logging
6
  from rag_core.utils import log_timed
7
 
8
- INDEX_PATH = "faiss_index/index.faiss"
9
- META_PATH = "faiss_index/meta.pkl"
 
10
 
11
  class Retriever:
12
  def __init__(self):
@@ -20,8 +21,6 @@ class Retriever:
20
 
21
  @log_timed("xây FAISS index")
22
  def build(self, texts: list, embed_fn):
23
- os.makedirs(os.path.dirname(INDEX_PATH), exist_ok=True)
24
-
25
  embeddings = []
26
  valid_texts = []
27
  for i, t in enumerate(texts):
@@ -33,13 +32,12 @@ class Retriever:
33
  logging.warning(f"❌ Lỗi embedding chunk {i}: {e}")
34
  if not embeddings:
35
  raise RuntimeError("Không có embedding nào thành công!")
 
36
  dim = len(embeddings[0])
37
  self.index = faiss.IndexFlatL2(dim)
38
  self.index.add(np.array(embeddings).astype("float32"))
39
 
40
- # ✅ Tạo thư mục nếu chưa tồn tại
41
  os.makedirs(os.path.dirname(INDEX_PATH), exist_ok=True)
42
-
43
  faiss.write_index(self.index, INDEX_PATH)
44
  with open(META_PATH, "wb") as f:
45
  pickle.dump(valid_texts, f)
@@ -68,7 +66,6 @@ class Retriever:
68
  logging.warning(f"❌ Lỗi embedding chunk mới {i}: {e}")
69
  if new_embeddings:
70
  self.index.add(np.array(new_embeddings).astype("float32"))
71
- os.makedirs(os.path.dirname(INDEX_PATH), exist_ok=True)
72
  faiss.write_index(self.index, INDEX_PATH)
73
  with open(META_PATH, "wb") as f:
74
  pickle.dump(self.texts, f)
 
5
  import logging
6
  from rag_core.utils import log_timed
7
 
8
+ # Dùng thư mục /data để tránh mất khi restart trên Hugging Face
9
+ INDEX_PATH = "/data/index.faiss"
10
+ META_PATH = "/data/meta.pkl"
11
 
12
  class Retriever:
13
  def __init__(self):
 
21
 
22
  @log_timed("xây FAISS index")
23
  def build(self, texts: list, embed_fn):
 
 
24
  embeddings = []
25
  valid_texts = []
26
  for i, t in enumerate(texts):
 
32
  logging.warning(f"❌ Lỗi embedding chunk {i}: {e}")
33
  if not embeddings:
34
  raise RuntimeError("Không có embedding nào thành công!")
35
+
36
  dim = len(embeddings[0])
37
  self.index = faiss.IndexFlatL2(dim)
38
  self.index.add(np.array(embeddings).astype("float32"))
39
 
 
40
  os.makedirs(os.path.dirname(INDEX_PATH), exist_ok=True)
 
41
  faiss.write_index(self.index, INDEX_PATH)
42
  with open(META_PATH, "wb") as f:
43
  pickle.dump(valid_texts, f)
 
66
  logging.warning(f"❌ Lỗi embedding chunk mới {i}: {e}")
67
  if new_embeddings:
68
  self.index.add(np.array(new_embeddings).astype("float32"))
 
69
  faiss.write_index(self.index, INDEX_PATH)
70
  with open(META_PATH, "wb") as f:
71
  pickle.dump(self.texts, f)