Download actions.py from doluong6/QLHT: direct link, hf CLI and curl.
- Browser
- Download file 6.51 kB
-
https://huggingface.co/spaces/doluong6/QLHT/resolve/main/actions.py
- Command line
-
hf download hf://spaces/doluong6/QLHT/actions.py
-
curl -L -o actions.py https://huggingface.co/spaces/doluong6/QLHT/resolve/main/actions.py
6.51 kB
| # actions.py | |
| import os | |
| import re | |
| import time | |
| import glob | |
| import pandas as pd | |
| from difflib import SequenceMatcher | |
| from typing import Dict, List, Tuple, Optional | |
| DATA_ROOT = os.environ.get("DATA_ROOT", "./data") # có thể trỏ sang ổ dữ liệu | |
| _PRICE_CACHE: Dict[str, Dict] = {} # {path: {"mtime":..., "df":...}} | |
| def _vn_norm(s: str) -> str: | |
| if s is None: return "" | |
| s = str(s) | |
| s = s.lower() | |
| # loại dấu đơn giản (không cần external lib) | |
| rep = { | |
| "à":"a","á":"a","ạ":"a","ả":"a","ã":"a","ă":"a","ằ":"a","ắ":"a","ặ":"a","ẳ":"a","ẵ":"a", | |
| "â":"a","ầ":"a","ấ":"a","ậ":"a","ẩ":"a","ẫ":"a","đ":"d", | |
| "è":"e","é":"e","ẹ":"e","ẻ":"e","ẽ":"e","ê":"e","ề":"e","ế":"e","ệ":"e","ể":"e","ễ":"e", | |
| "ì":"i","í":"i","ị":"i","ỉ":"i","ĩ":"i", | |
| "ò":"o","ó":"o","ọ":"o","ỏ":"o","õ":"o","ô":"o","ồ":"o","ố":"o","ộ":"o","ổ":"o","ỗ":"o", | |
| "ơ":"o","ờ":"o","ớ":"o","ợ":"o","ở":"o","ỡ":"o", | |
| "ù":"u","ú":"u","ụ":"u","ủ":"u","ũ":"u","ư":"u","ừ":"u","ứ":"u","ự":"u","ử":"u","ữ":"u", | |
| "ỳ":"y","ý":"y","ỵ":"y","ỷ":"y","ỹ":"y", | |
| } | |
| return "".join(rep.get(ch, ch) for ch in s) | |
| def _ratio(a: str, b: str) -> float: | |
| return SequenceMatcher(None, _vn_norm(a), _vn_norm(b)).ratio() | |
| def _load_price_frames() -> List[Tuple[str, pd.DataFrame]]: | |
| """ | |
| Dò toàn bộ file bảng giá .xlsx/.csv trong DATA_ROOT và các file ở root dataset | |
| (ví dụ: bang_gia_*.xlsx, Baogia.xlsx, bang_gia_*csv). Cache theo mtime. | |
| """ | |
| patterns = [ | |
| os.path.join(DATA_ROOT, "**", "bang_gia*.xlsx"), | |
| os.path.join(DATA_ROOT, "**", "bang_gia*.csv"), | |
| os.path.join(DATA_ROOT, "**", "baogia*.xlsx"), | |
| os.path.join(DATA_ROOT, "**", "baogia*.csv"), | |
| # để chắc ăn: các file ở thư mục gốc project | |
| "bang_gia*.xlsx", | |
| "bang_gia*.csv", | |
| "Baogia.xlsx", | |
| "baogia*.xlsx", | |
| "baogia*.csv", | |
| ] | |
| paths = set() | |
| for p in patterns: | |
| for f in glob.glob(p, recursive=True): | |
| paths.add(os.path.abspath(f)) | |
| out = [] | |
| for path in sorted(paths): | |
| try: | |
| mtime = os.path.getmtime(path) | |
| cache = _PRICE_CACHE.get(path) | |
| if not cache or cache["mtime"] != mtime: | |
| if path.lower().endswith(".xlsx"): | |
| df = pd.read_excel(path) | |
| else: | |
| df = pd.read_csv(path) | |
| # Chuẩn hóa tên cột | |
| df.columns = [str(c).strip() for c in df.columns] | |
| _PRICE_CACHE[path] = {"mtime": mtime, "df": df} | |
| out.append((path, _PRICE_CACHE[path]["df"])) | |
| except Exception as e: | |
| # bỏ qua file lỗi | |
| continue | |
| return out | |
| def action_price_table() -> str: | |
| """Liệt kê các file bảng giá tìm thấy.""" | |
| frames = _load_price_frames() | |
| if not frames: | |
| return "Không tìm thấy file bảng giá (.xlsx/.csv). Hãy kiểm tra DATA_ROOT." | |
| lines = ["Các bảng giá sẵn có:"] | |
| for path, df in frames: | |
| fname = os.path.basename(path) | |
| lines.append(f"- {fname} ({len(df)} dòng)") | |
| return "\n".join(lines) | |
| def action_price_lookup(query: str, top_k: int = 5) -> str: | |
| """ | |
| Tìm đơn giá theo tên thiết bị/dịch vụ từ nhiều bảng giá. | |
| Heuristic cột: ưu tiên ['Tên', 'Tên thiết bị', 'Thiết bị', 'Dịch vụ'] & ['Đơn giá', 'Giá', 'Unit price']. | |
| """ | |
| frames = _load_price_frames() | |
| if not frames: | |
| return "Không có bảng giá nào để tra cứu." | |
| q = query or "" | |
| # cột ứng viên | |
| name_candidates = ["Tên", "Tên thiết bị", "Thiết bị", "Dịch vụ", "Tên dịch vụ", "Tên sản phẩm", "Tên máy"] | |
| price_candidates = ["Đơn giá", "Giá", "Đơn giá", "Đơn_giá", "Unit price", "Price"] | |
| matches = [] | |
| for path, df in frames: | |
| cols = list(df.columns) | |
| name_col = next((c for c in name_candidates if c in cols), None) | |
| price_col = next((c for c in price_candidates if c in cols), None) | |
| if not name_col: | |
| # thử đoán cột tên: cột đầu tiên dạng object/string | |
| obj_cols = [c for c in cols if df[c].dtype == "object"] | |
| if obj_cols: name_col = obj_cols[0] | |
| if not name_col: | |
| continue | |
| # duyệt từng dòng | |
| for idx, row in df.iterrows(): | |
| name_val = str(row.get(name_col, "")).strip() | |
| if not name_val: | |
| continue | |
| score = _ratio(name_val, q) | |
| if score < 0.50: | |
| continue | |
| price_val = row.get(price_col, None) if price_col else None | |
| matches.append({ | |
| "score": score, | |
| "file": os.path.basename(path), | |
| "name": name_val, | |
| "price": price_val, | |
| }) | |
| if not matches: | |
| return "Không tìm thấy mục khớp trong các bảng giá." | |
| matches.sort(key=lambda x: (-x["score"], x["name"])) | |
| top = matches[:top_k] | |
| lines = ["Kết quả khớp tốt nhất:"] | |
| for m in top: | |
| p = m["price"] | |
| if pd.isna(p): | |
| p_str = "(không có cột đơn giá)" | |
| else: | |
| try: | |
| p_str = f"{float(p):,.0f} ₫".replace(",", ".") | |
| except: | |
| p_str = str(p) | |
| lines.append(f"- {m['name']} — {p_str} (nguồn: {m['file']}, match={m['score']:.2f})") | |
| return "\n".join(lines) | |
| # actions.py (thêm cuối file hoặc ngay dưới các hàm action_) | |
| from fastapi import APIRouter, Query | |
| router = APIRouter() | |
| def price_table(): | |
| """REST endpoint: liệt kê các bảng giá đã phát hiện.""" | |
| return {"text": action_price_table()} | |
| def price_lookup(q: str = Query(..., description="Tên thiết bị/dịch vụ cần tra giá"), top_k: int = 5): | |
| """REST endpoint: tra cứu giá theo tên.""" | |
| return {"text": action_price_lookup(q, top_k=top_k)} | |
| # (tuỳ chọn) nếu bạn có hàm action_procedure_answer: | |
| def procedure_search(q: str = Query(..., description="Câu hỏi về Quy trình/Tài liệu")): | |
| try: | |
| return {"text": action_procedure_answer(q)} | |
| except Exception as e: | |
| return {"text": f"Lỗi: {e}"} | |