Spaces:
Sleeping

doluong6 commited on
Commit
5bca3dd
·
verified ·
1 Parent(s): 9aa2e34

Update actions.py

Browse files
Files changed (1) hide show
  1. actions.py +125 -55
actions.py CHANGED
@@ -1,72 +1,142 @@
1
  # actions.py
2
  import os
 
 
3
  import glob
4
- from pathlib import Path
5
- from typing import List, Dict, Any, Optional
6
-
7
  import pandas as pd
8
- from fastapi import APIRouter, Query
 
9
 
10
- router = APIRouter()
 
11
 
12
- DATA_DIR = os.environ.get("DATA_DIR", "./")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- TABULAR_EXTS = {".csv", ".xlsx", ".xls"}
 
15
 
16
- def _iter_tabular_files(root: str) -> List[str]:
17
- files = []
18
- for ext in TABULAR_EXTS:
19
- files.extend(glob.glob(os.path.join(root, "**", f"*{ext}"), recursive=True))
20
- return sorted(files)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- def _read_any(path: str) -> pd.DataFrame:
23
- ext = Path(path).suffix.lower()
24
- if ext == ".csv":
25
- return pd.read_csv(path)
26
- return pd.read_excel(path)
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- def _row_contains_all_kw(row: pd.Series, kws: List[str]) -> bool:
29
- text = row.to_string(index=False)
30
- text_low = text.lower()
31
- return all(k.lower() in text_low for k in kws)
 
 
 
 
 
 
32
 
33
- @router.get("/tabular_search")
34
- def tabular_search(
35
- q: str = Query(..., description="Chuỗi từ khóa, ngăn cách bởi dấu cách"),
36
- folder: Optional[str] = Query(None, description="Tên thư mục con để giới hạn tìm kiếm"),
37
- limit: int = Query(10, ge=1, le=100, description="Số dòng tối đa trả về")
38
- ) -> Dict[str, Any]:
39
  """
40
- Tìm các dòng trong các file CSV/XLSX sao cho chứa tất cả từ khóa.
41
- Kết quả trả về: danh sách dòng (dict) + nguồn file.
42
  """
43
- kws = [w for w in q.strip().split() if w.strip()]
44
- if not kws:
45
- return {"data": [], "message": "Không có từ khóa."}
 
 
 
 
46
 
47
- root = DATA_DIR if not folder else os.path.join(DATA_DIR, folder)
48
- files = _iter_tabular_files(root)
 
 
 
 
 
 
 
 
 
49
 
50
- results: List[Dict[str, Any]] = []
51
- for fp in files:
52
- try:
53
- df = _read_any(fp)
54
- if df.empty:
55
  continue
56
- mask = df.apply(lambda r: _row_contains_all_kw(r, kws), axis=1)
57
- sub = df[mask]
58
- if not sub.empty:
59
- for _, row in sub.head(limit - len(results)).iterrows():
60
- results.append({
61
- "source": os.path.relpath(fp, DATA_DIR),
62
- "row": {str(c): (None if pd.isna(row[c]) else row[c]) for c in df.columns}
63
- })
64
- if len(results) >= limit:
65
- break
66
- except Exception as e:
67
- # bỏ qua lỗi từng file
68
- continue
69
- if len(results) >= limit:
70
- break
71
 
72
- return {"data": results, "keywords": kws, "count": len(results)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # actions.py
2
  import os
3
+ import re
4
+ import time
5
  import glob
 
 
 
6
  import pandas as pd
7
+ from difflib import SequenceMatcher
8
+ from typing import Dict, List, Tuple, Optional
9
 
10
+ DATA_ROOT = os.environ.get("DATA_ROOT", "./data") # có thể trỏ sang ổ dữ liệu
11
+ _PRICE_CACHE: Dict[str, Dict] = {} # {path: {"mtime":..., "df":...}}
12
 
13
+ def _vn_norm(s: str) -> str:
14
+ if s is None: return ""
15
+ s = str(s)
16
+ s = s.lower()
17
+ # loại dấu đơn giản (không cần external lib)
18
+ rep = {
19
+ "à":"a","á":"a","ạ":"a","ả":"a","ã":"a","ă":"a","ằ":"a","ắ":"a","ặ":"a","ẳ":"a","ẵ":"a",
20
+ "â":"a","ầ":"a","ấ":"a","ậ":"a","ẩ":"a","ẫ":"a","đ":"d",
21
+ "è":"e","é":"e","ẹ":"e","ẻ":"e","ẽ":"e","ê":"e","ề":"e","ế":"e","ệ":"e","ể":"e","ễ":"e",
22
+ "ì":"i","í":"i","ị":"i","ỉ":"i","ĩ":"i",
23
+ "ò":"o","ó":"o","ọ":"o","ỏ":"o","õ":"o","ô":"o","ồ":"o","ố":"o","ộ":"o","ổ":"o","ỗ":"o",
24
+ "ơ":"o","ờ":"o","ớ":"o","ợ":"o","ở":"o","ỡ":"o",
25
+ "ù":"u","ú":"u","ụ":"u","ủ":"u","ũ":"u","ư":"u","ừ":"u","ứ":"u","ự":"u","ử":"u","ữ":"u",
26
+ "ỳ":"y","ý":"y","ỵ":"y","ỷ":"y","ỹ":"y",
27
+ }
28
+ return "".join(rep.get(ch, ch) for ch in s)
29
 
30
+ def _ratio(a: str, b: str) -> float:
31
+ return SequenceMatcher(None, _vn_norm(a), _vn_norm(b)).ratio()
32
 
33
+ def _load_price_frames() -> List[Tuple[str, pd.DataFrame]]:
34
+ """
35
+ Dò toàn bộ file bảng giá .xlsx/.csv trong DATA_ROOT và các file ở root dataset
36
+ (ví dụ: bang_gia_*.xlsx, Baogia.xlsx, bang_gia_*csv). Cache theo mtime.
37
+ """
38
+ patterns = [
39
+ os.path.join(DATA_ROOT, "**", "bang_gia*.xlsx"),
40
+ os.path.join(DATA_ROOT, "**", "bang_gia*.csv"),
41
+ os.path.join(DATA_ROOT, "**", "baogia*.xlsx"),
42
+ os.path.join(DATA_ROOT, "**", "baogia*.csv"),
43
+ # để chắc ăn: các file ở thư mục gốc project
44
+ "bang_gia*.xlsx",
45
+ "bang_gia*.csv",
46
+ "Baogia.xlsx",
47
+ "baogia*.xlsx",
48
+ "baogia*.csv",
49
+ ]
50
+ paths = set()
51
+ for p in patterns:
52
+ for f in glob.glob(p, recursive=True):
53
+ paths.add(os.path.abspath(f))
54
 
55
+ out = []
56
+ for path in sorted(paths):
57
+ try:
58
+ mtime = os.path.getmtime(path)
59
+ cache = _PRICE_CACHE.get(path)
60
+ if not cache or cache["mtime"] != mtime:
61
+ if path.lower().endswith(".xlsx"):
62
+ df = pd.read_excel(path)
63
+ else:
64
+ df = pd.read_csv(path)
65
+ # Chuẩn hóa tên cột
66
+ df.columns = [str(c).strip() for c in df.columns]
67
+ _PRICE_CACHE[path] = {"mtime": mtime, "df": df}
68
+ out.append((path, _PRICE_CACHE[path]["df"]))
69
+ except Exception as e:
70
+ # bỏ qua file lỗi
71
+ continue
72
+ return out
73
 
74
+ def action_price_table() -> str:
75
+ """Liệt kê các file bảng giá tìm thấy."""
76
+ frames = _load_price_frames()
77
+ if not frames:
78
+ return "Không tìm thấy file bảng giá (.xlsx/.csv). Hãy kiểm tra DATA_ROOT."
79
+ lines = ["Các bảng giá sẵn có:"]
80
+ for path, df in frames:
81
+ fname = os.path.basename(path)
82
+ lines.append(f"- {fname} ({len(df)} dòng)")
83
+ return "\n".join(lines)
84
 
85
+ def action_price_lookup(query: str, top_k: int = 5) -> str:
 
 
 
 
 
86
  """
87
+ Tìm đơn giá theo tên thiết bị/dịch vụ từ nhiều bảng giá.
88
+ Heuristic cột: ưu tiên ['Tên', 'Tên thiết bị', 'Thiết bị', 'Dịch vụ'] & ['Đơn giá', 'Giá', 'Unit price'].
89
  """
90
+ frames = _load_price_frames()
91
+ if not frames:
92
+ return "Không có bảng giá nào để tra cứu."
93
+ q = query or ""
94
+ # cột ứng viên
95
+ 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"]
96
+ price_candidates = ["Đơn giá", "Giá", "Đơn giá", "Đơn_giá", "Unit price", "Price"]
97
 
98
+ matches = []
99
+ for path, df in frames:
100
+ cols = list(df.columns)
101
+ name_col = next((c for c in name_candidates if c in cols), None)
102
+ price_col = next((c for c in price_candidates if c in cols), None)
103
+ if not name_col:
104
+ # thử đoán cột tên: cột đầu tiên dạng object/string
105
+ obj_cols = [c for c in cols if df[c].dtype == "object"]
106
+ if obj_cols: name_col = obj_cols[0]
107
+ if not name_col:
108
+ continue
109
 
110
+ # duyệt từng dòng
111
+ for idx, row in df.iterrows():
112
+ name_val = str(row.get(name_col, "")).strip()
113
+ if not name_val:
 
114
  continue
115
+ score = _ratio(name_val, q)
116
+ if score < 0.50:
117
+ continue
118
+ price_val = row.get(price_col, None) if price_col else None
119
+ matches.append({
120
+ "score": score,
121
+ "file": os.path.basename(path),
122
+ "name": name_val,
123
+ "price": price_val,
124
+ })
125
+
126
+ if not matches:
127
+ return "Không tìm thấy mục khớp trong các bảng giá."
 
 
128
 
129
+ matches.sort(key=lambda x: (-x["score"], x["name"]))
130
+ top = matches[:top_k]
131
+ lines = ["Kết quả khớp tốt nhất:"]
132
+ for m in top:
133
+ p = m["price"]
134
+ if pd.isna(p):
135
+ p_str = "(không có cột đơn giá)"
136
+ else:
137
+ try:
138
+ p_str = f"{float(p):,.0f} ₫".replace(",", ".")
139
+ except:
140
+ p_str = str(p)
141
+ lines.append(f"- {m['name']} — {p_str} (nguồn: {m['file']}, match={m['score']:.2f})")
142
+ return "\n".join(lines)