Spaces:
Sleeping

QLHT / routes /pyc_incremental_api.py
doluong6's picture
Create pyc_incremental_api.py
8c94c5b verified
Raw History Blame Contribute Delete
10.3 kB
# routes/pyc_incremental_api.py
import os, re, json
from typing import Dict, List, Optional, Tuple
from fastapi import APIRouter, Query
from pydantic import BaseModel
from huggingface_hub import list_repo_files, hf_hub_download
from openpyxl import load_workbook
# ================= CẤU HÌNH =================
REPO_ID = os.environ.get("REPO_ID", "doluong6/Quatest1")
HF_TOKEN = os.environ.get("HF_TOKEN") # để trống nếu dataset public
HF_CACHE = os.environ.get("HF_HUB_CACHE", "/tmp/hf_cache")
os.makedirs(HF_CACHE, exist_ok=True)
# Thư mục chứa PYC trong dataset:
PYC_SCOPE = os.environ.get("PYC_FOLDER", "Phieu_yeu_cau/")
if not PYC_SCOPE.endswith("/"): PYC_SCOPE += "/"
# Cột theo template PYC của bạn:
COL_QTY = "BM"
COL_PRICE = "BP"
COL_KD = "AV" # "P" => KĐ
COL_HC = "AY" # "P" => HC
COL_DTN = "BB" # "P" => ĐTN
COL_DAY = "BM3" # ngày (số)
COL_MONTH = "BS3" # tháng (1..12 dạng chuỗi số)
COL_CUST = "I8" # tên khách hàng
START_ROW = 24
# File cache (lưu results per-file + chỉ mục đã xử lý)
CACHE_PATH = os.path.join(HF_CACHE, "pyc_cache.json")
router = APIRouter(prefix="/pyc2", tags=["PYC-incremental"])
# ================= TIỆN ÍCH =================
def _safe_float(x) -> float:
try: return float(x)
except Exception: return 0.0
def _to_month_int(x) -> Optional[int]:
if x is None: return None
s = str(x).strip()
if not s.isdigit(): return None
m = int(s)
return m if 1 <= m <= 12 else None
def _period_of(day: Optional[int]) -> Optional[str]:
if day is None: return None
return "1_15" if day <= 15 else "16_31"
def _iter_services(ws):
r = START_ROW
while True:
qty = ws[f"{COL_QTY}{r}"].value
if qty is None: break
price = ws[f"{COL_PRICE}{r}"].value
kd = str(ws[f"{COL_KD}{r}"].value or "").strip().upper() == "P"
hc = str(ws[f"{COL_HC}{r}"].value or "").strip().upper() == "P"
dtn= str(ws[f"{COL_DTN}{r}"].value or "").strip().upper() == "P"
yield _safe_float(qty), _safe_float(price), kd, hc, dtn
r += 1
def _extract_number(basename: str) -> Optional[int]:
"""Lấy số thứ tự từ tên file: PYC_0158.xlsx, 0158.xlsx, pyc-158.xlsx, ..."""
m = re.search(r"(\d{3,5})", basename)
return int(m.group(1)) if m else None
def _download(repo_path: str) -> str:
return hf_hub_download(
REPO_ID, repo_path, repo_type="dataset",
token=HF_TOKEN, cache_dir=HF_CACHE
)
# ================= CACHE =================
def _load_cache() -> Dict:
if os.path.exists(CACHE_PATH):
try:
with open(CACHE_PATH, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
return {
"version": 1,
"repo_id": REPO_ID,
"scope": PYC_SCOPE,
# files: { repo_path: { "num": 158, "month":7, "day":12, "customer":"...",
# "totals":{"KĐ":..,"HC":..,"ĐTN":..},
# "revenue":{"KĐ":..,"HC":..,"ĐTN":..} } }
"files": {}
}
def _save_cache(cache: Dict):
tmp = CACHE_PATH + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(cache, f, ensure_ascii=False)
os.replace(tmp, CACHE_PATH)
def _list_repo_files() -> List[str]:
files = list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN)
return [f for f in files
if f.startswith(PYC_SCOPE)
and f.lower().endswith(".xlsx")
and not os.path.basename(f).startswith("~$")]
def _process_file(local_path: str):
"""
Trả (totals, revenue, month, day, customer)
"""
wb = load_workbook(local_path, data_only=True)
ws = wb.active
day_val = ws[COL_DAY].value
month_val = ws[COL_MONTH].value
cust_val = str(ws[COL_CUST].value or "").strip()
day = int(day_val) if isinstance(day_val, (int, float)) else None
month = _to_month_int(month_val)
totals = {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0}
revenue= {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0}
for sl, gia, kd, hc, dtn in _iter_services(ws):
if kd:
totals["KĐ"] += sl
revenue["KĐ"] += sl * gia
if hc:
totals["HC"] += sl
revenue["HC"] += sl * gia
if dtn:
totals["ĐTN"] += sl
revenue["ĐTN"] += sl * gia
for k in totals: totals[k] = round(totals[k], 2)
for k in revenue: revenue[k] = round(revenue[k], 0)
return totals, revenue, month, day, cust_val
def _refresh_cache(cache: Dict) -> Dict:
"""
Quét repo, chỉ xử lý file MỚI (chưa có trong cache).
Sắp theo số tăng dần để gộp đúng trình tự.
"""
existing = set(cache["files"].keys())
all_files = _list_repo_files()
new_files = [rp for rp in all_files if rp not in existing]
def _sort_key(rp: str):
n = _extract_number(os.path.basename(rp)) or 10**9
return (n, rp)
new_files.sort(key=_sort_key)
added = 0
for rp in new_files:
try:
lp = _download(rp)
totals, revenue, month, day, cust = _process_file(lp)
num = _extract_number(os.path.basename(rp))
cache["files"][rp] = {
"num": num, "month": month, "day": day,
"customer": cust, "totals": totals, "revenue": revenue
}
added += 1
except Exception as e:
cache["files"][rp] = {"error": str(e)}
if added:
_save_cache(cache)
return {"added": added, "known": len(cache["files"])}
# ================= SCHEMAS =================
class StateResp(BaseModel):
repo_id: str
scope: str
known: int
newest_num: Optional[int] = None
added: int
class StatsResp(BaseModel):
month: Optional[int] = None
period: Optional[str] = None # '1_15' | '16_31' | None
totals: Dict[str, float]
revenue: Dict[str, float]
customers: List[str]
files: List[str]
# ================= ENDPOINTS CHO FRONTEND =================
@router.post("/refresh", response_model=StateResp)
def refresh():
"""
Incremental refresh: chỉ xử lý file mới kể từ lần trước.
Frontend nên gọi endpoint này trước khi hiển thị thống kê.
"""
cache = _load_cache()
out = _refresh_cache(cache)
nums = [v.get("num") for v in cache["files"].values() if isinstance(v, dict) and v.get("num") is not None]
newest = max(nums) if nums else None
return {"repo_id": cache["repo_id"], "scope": cache["scope"],
"known": out["known"], "added": out["added"], "newest_num": newest}
@router.get("/stats", response_model=StatsResp)
def stats(
month: Optional[int] = Query(default=None, ge=1, le=12),
period: Optional[str] = Query(default=None, regex=r"^(1_15|16_31)$"),
refresh_first: bool = Query(default=True)
):
"""
Lấy thống kê nhanh từ cache. Nếu refresh_first=true → xử lý file mới trước khi trả kết quả.
"""
cache = _load_cache()
if refresh_first:
_refresh_cache(cache)
totals = {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0}
revenue= {"KĐ": 0.0, "HC": 0.0, "ĐTN": 0.0}
customers = set()
used_files = []
def _ok(meta) -> bool:
return isinstance(meta, dict) and "error" not in meta
for rp, meta in cache["files"].items():
if not _ok(meta): continue
if month is not None and meta.get("month") != month: continue
if period is not None and _period_of(meta.get("day")) != period: continue
t = meta.get("totals", {}); r = meta.get("revenue", {})
for k in totals: totals[k] += float(t.get(k, 0))
for k in revenue: revenue[k] += float(r.get(k, 0))
if meta.get("customer"): customers.add(meta["customer"])
used_files.append(rp)
for k in totals: totals[k] = round(totals[k], 2)
for k in revenue: revenue[k] = round(revenue[k], 0)
return {
"month": month, "period": period,
"totals": totals, "revenue": revenue,
"customers": sorted(customers), "files": used_files
}
@router.get("/list")
def list_files(
month: Optional[int] = Query(default=None, ge=1, le=12),
period: Optional[str] = Query(default=None, regex=r"^(1_15|16_31)$"),
limit: int = Query(default=200, ge=1, le=1000),
refresh_first: bool = Query(default=False)
):
"""
Danh sách file đã biết (từ cache), có thể lọc theo month/period.
"""
cache = _load_cache()
if refresh_first:
_refresh_cache(cache)
out = []
for rp, meta in cache["files"].items():
if not isinstance(meta, dict) or "error" in meta:
continue
if month is not None and meta.get("month") != month: continue
if period is not None and _period_of(meta.get("day")) != period: continue
out.append({
"repo_path": rp, "num": meta.get("num"),
"month": meta.get("month"), "day": meta.get("day"),
"customer": meta.get("customer"),
"totals": meta.get("totals"), "revenue": meta.get("revenue")
})
out.sort(key=lambda x: (x.get("num") if x.get("num") is not None else 10**9, x["repo_path"]))
return {"count": len(out), "items": out[:limit]}
@router.post("/reset")
def reset_cache():
"""
XÓA cache → lần sau /refresh sẽ build lại từ đầu.
"""
if os.path.exists(CACHE_PATH):
os.remove(CACHE_PATH)
return {"status": "ok", "msg": "Cache cleared"}
# ====== Aliases để tương thích /pyc/* nếu frontend đang gọi tên cũ ======
alias = APIRouter(prefix="/pyc", tags=["PYC"])
@alias.post("/refresh_incremental")
def _a_refresh(): return refresh()
@alias.get("/stats_incremental")
def _a_stats(month: Optional[int] = None, period: Optional[str] = None, refresh_first: bool = True):
return stats(month=month, period=period, refresh_first=refresh_first)
@alias.get("/list_incremental")
def _a_list(month: Optional[int] = None, period: Optional[str] = None, limit: int = 200, refresh_first: bool = False):
return list_files(month=month, period=period, limit=limit, refresh_first=refresh_first)
# export alias router
alias_router = alias