Spaces:
Sleeping

doluong6 commited on
Commit
0a906ff
·
verified ·
1 Parent(s): 0b20487

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -32
app.py CHANGED
@@ -48,23 +48,8 @@ app.include_router(banggia5.router)
48
  def root():
49
  return {"message": "✅ Backend is running"}
50
  # ================== CHATBOT – GPT-5 + RAG + ACTION ==================
51
- import os, re, datetime, httpx
52
- from typing import List, Optional, Tuple, Dict
53
- from pydantic import BaseModel
54
- from fastapi import APIRouter, Body
55
- from fastapi.middleware.cors import CORSMiddleware
56
- from openai import OpenAI
57
- from rag_indexer import build_index, search as rag_search
58
-
59
- # Cho phép frontend gọi từ domain khác (nếu cần)
60
- app.add_middleware(
61
- CORSMiddleware,
62
- allow_origins=["*"], allow_credentials=True,
63
- allow_methods=["*"], allow_headers=["*"],
64
- )
65
-
66
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
67
- MODEL_NAME = os.environ.get("OPENAI_MODEL","gpt-5") # ← dùng GPT-5
68
  client = OpenAI(api_key=OPENAI_API_KEY)
69
 
70
  # -------- ReIndex (quét dataset & lập chỉ mục) --------
@@ -115,7 +100,7 @@ CÂU HỎI: {req.question}
115
 
116
  app.include_router(router_rag)
117
 
118
- # -------- Chat thường (giống đang dùng ChatGPT-5) --------
119
  router_chat = APIRouter()
120
 
121
  class ChatReq(BaseModel):
@@ -142,9 +127,8 @@ class SmartResp(BaseModel):
142
  reply: str
143
  sources: Optional[List[str]] = None
144
 
145
- KEY_RAG = [r"\bPYC\b", r"phiếu\s*yêu\s*cầu", r"báo\s*giá", r"hợp\s*đồng", r"quy\s*trình", r"biên\s*bản", r"tài\s*liệu"]
146
  KEY_PYC_PENDING = [r"PYC\s*chưa\s*hoàn\s*thành", r"chưa\s*hoàn\s*thành"]
147
- KEY_REVENUE = [r"doanh\s*thu", r"tháng\s*\d{1,2}", r"\b\d{1,2}/\d{4}\b"]
148
 
149
  def _has(t, pats): return any(re.search(p, t, flags=re.I) for p in pats)
150
 
@@ -176,28 +160,42 @@ async def _POST(path, payload):
176
  except: pass
177
  return {"error": f"POST fail {path}"}
178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  @router_smart.post("/chat_smart", response_model=SmartResp)
180
  async def chat_smart(req: SmartReq = Body(...)):
181
  text = (req.message or "").strip()
182
  if not text:
183
  return SmartResp(intent="general", reply="Bạn hãy nhập câu hỏi hoặc yêu cầu nhé.")
184
 
185
- # ACTION: PYC chưa hoàn thành (gọi route sẵn có của bạn)
186
  if _has(text, KEY_PYC_PENDING):
187
  data = await _GET("/pyc_chua_hoan_thanh", {})
188
  if "error" in data: return SmartResp(intent="action.list_pyc_pending", reply="Không lấy được danh sách.")
189
  rows = data if isinstance(data,list) else data.get("rows") or data.get("data") or []
190
  if not rows: return SmartResp(intent="action.list_pyc_pending", reply="Hiện không có PYC chưa hoàn thành.")
191
- lines=["PYC chưa hoàn thành (tối đa 10 mục):"]
192
- for r in rows[:10]:
193
- if isinstance(r,dict):
 
194
  so = r.get("SỐ PYC") or r.get("so_pyc") or r.get("pyc") or ""
195
  kh = r.get("Tên khách hàng") or r.get("ten_khach_hang") or r.get("khach_hang") or ""
196
  lines.append(f"- {so} | {kh}")
197
- else: lines.append(f"- {r}")
198
- return SmartResp(intent="action.list_pyc_pending", reply="\n".join(lines))
199
 
200
- # ACTION: Doanh thu tháng (đổi path nếu bạn dùng /doanh_thu_theo_thang)
201
  if _has(text, KEY_REVENUE):
202
  mon, yr = _mon_year(text)
203
  if not mon: return SmartResp(intent="action.revenue_month", reply="Bạn muốn xem doanh thu tháng nào? (vd: tháng 7/2025)")
@@ -205,16 +203,30 @@ async def chat_smart(req: SmartReq = Body(...)):
205
  if "error" in data: return SmartResp(intent="action.revenue_month", reply="Không lấy được doanh thu.")
206
  total = data.get("tong_doanh_thu") or data.get("total") or data.get("sum")
207
  if total is not None:
208
- return SmartResp(intent="action.revenue_month", reply=f"Doanh thu tháng {str(mon).zfill(2)}/{yr or datetime.date.today().year}: {total:,} VND")
209
  return SmartResp(intent="action.revenue_month", reply=f"Kết quả: {data}")
210
 
211
- # RAG: hỏi tài liệu nội bộ
212
- if _has(text, KEY_RAG):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  data = await _POST("/chat_rag", {"question": text, "history": req.history or []})
214
- if data.get("reply"): return SmartResp(intent="rag.query", reply=data["reply"], sources=data.get("sources"))
215
- # fallback về chat thường
216
 
217
- # GENERAL: hỏi đáp chung (GPT-5)
218
  msgs = (req.history or []) + [{"role":"user","content":text}]
219
  out = await _POST("/chat", {"messages": msgs})
220
  reply = out.get("reply") or "Xin lỗi, mình chưa trả lời được."
 
48
  def root():
49
  return {"message": "✅ Backend is running"}
50
  # ================== CHATBOT – GPT-5 + RAG + ACTION ==================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
52
+ MODEL_NAME = os.environ.get("OPENAI_MODEL","gpt-5")
53
  client = OpenAI(api_key=OPENAI_API_KEY)
54
 
55
  # -------- ReIndex (quét dataset & lập chỉ mục) --------
 
100
 
101
  app.include_router(router_rag)
102
 
103
+ # -------- Chat thường --------
104
  router_chat = APIRouter()
105
 
106
  class ChatReq(BaseModel):
 
127
  reply: str
128
  sources: Optional[List[str]] = None
129
 
 
130
  KEY_PYC_PENDING = [r"PYC\s*chưa\s*hoàn\s*thành", r"chưa\s*hoàn\s*thành"]
131
+ KEY_REVENUE = [r"doanh\s*thu", r"tháng\s*\d{1,2}", r"\b\d{1,2}\/\d{4}\b"]
132
 
133
  def _has(t, pats): return any(re.search(p, t, flags=re.I) for p in pats)
134
 
 
160
  except: pass
161
  return {"error": f"POST fail {path}"}
162
 
163
+ def _format_rows(rows: List[dict], max_cols: int = 6) -> str:
164
+ if not rows: return "Không tìm thấy dòng phù hợp."
165
+ # mỗi row {"source": "...", "row": {...}}
166
+ lines = []
167
+ for i, item in enumerate(rows, 1):
168
+ src = item.get("source","")
169
+ row = item.get("row", {})
170
+ # lấy vài cột đầu
171
+ cols = list(row.keys())[:max_cols]
172
+ parts = [f"{k}: {row[k]}" for k in cols]
173
+ lines.append(f"{i}. ({src}) " + " | ".join(parts))
174
+ return "\n".join(lines)
175
+
176
  @router_smart.post("/chat_smart", response_model=SmartResp)
177
  async def chat_smart(req: SmartReq = Body(...)):
178
  text = (req.message or "").strip()
179
  if not text:
180
  return SmartResp(intent="general", reply="Bạn hãy nhập câu hỏi hoặc yêu cầu nhé.")
181
 
182
+ # ACTION: PYC chưa hoàn thành
183
  if _has(text, KEY_PYC_PENDING):
184
  data = await _GET("/pyc_chua_hoan_thanh", {})
185
  if "error" in data: return SmartResp(intent="action.list_pyc_pending", reply="Không lấy được danh sách.")
186
  rows = data if isinstance(data,list) else data.get("rows") or data.get("data") or []
187
  if not rows: return SmartResp(intent="action.list_pyc_pending", reply="Hiện không có PYC chưa hoàn thành.")
188
+ top = rows[:10]
189
+ if isinstance(top[0], dict):
190
+ lines = []
191
+ for r in top:
192
  so = r.get("SỐ PYC") or r.get("so_pyc") or r.get("pyc") or ""
193
  kh = r.get("Tên khách hàng") or r.get("ten_khach_hang") or r.get("khach_hang") or ""
194
  lines.append(f"- {so} | {kh}")
195
+ return SmartResp(intent="action.list_pyc_pending", reply="\n".join(lines))
196
+ return SmartResp(intent="action.list_pyc_pending", reply="\n".join([f"- {r}" for r in top]))
197
 
198
+ # ACTION: Doanh thu tháng
199
  if _has(text, KEY_REVENUE):
200
  mon, yr = _mon_year(text)
201
  if not mon: return SmartResp(intent="action.revenue_month", reply="Bạn muốn xem doanh thu tháng nào? (vd: tháng 7/2025)")
 
203
  if "error" in data: return SmartResp(intent="action.revenue_month", reply="Không lấy được doanh thu.")
204
  total = data.get("tong_doanh_thu") or data.get("total") or data.get("sum")
205
  if total is not None:
206
+ return SmartResp(intent="action.revenue_month", reply=f"Doanh thu tháng {str(mon).zfill(2)}/{yr or datetime.date.today().year}: {int(total):,} VND")
207
  return SmartResp(intent="action.revenue_month", reply=f"Kết quả: {data}")
208
 
209
+ # ACTION: Câu hỏi dạng bảng (bảng giá/thiết bị/khách hàng/hóa chất…)
210
+ if is_table_query(text):
211
+ # rút từ khóa gọn để search
212
+ kws = extract_keywords(text)
213
+ q = " ".join(kws) if kws else text
214
+ data = await _GET("/tabular_search", {"q": q, "limit": 10})
215
+ rows = data.get("data", [])
216
+ if rows:
217
+ return SmartResp(intent="action.tabular_search", reply=_format_rows(rows))
218
+ # fallback: RAG
219
+ data_rag = await _POST("/chat_rag", {"question": text, "history": req.history or []})
220
+ if data_rag.get("reply"):
221
+ return SmartResp(intent="rag.query", reply=data_rag["reply"], sources=data_rag.get("sources"))
222
+
223
+ # RAG: nếu nhắc tới tài liệu/quy trình/báo giá…
224
+ if re.search(r"(quy\s*trình|tài\s*liệu|báo\s*giá|PYC|hợp\s*đồng)", text, flags=re.I):
225
  data = await _POST("/chat_rag", {"question": text, "history": req.history or []})
226
+ if data.get("reply"):
227
+ return SmartResp(intent="rag.query", reply=data["reply"], sources=data.get("sources"))
228
 
229
+ # GENERAL
230
  msgs = (req.history or []) + [{"role":"user","content":text}]
231
  out = await _POST("/chat", {"messages": msgs})
232
  reply = out.get("reply") or "Xin lỗi, mình chưa trả lời được."