Spaces:
Sleeping
Sleeping
Download src/gametracker/grab_gt_stats.py from DSGC/admin_dashboard: direct link, hf CLI and curl.
- Browser
- Download file 4.16 kB
-
https://huggingface.co/spaces/DSGC/admin_dashboard/resolve/main/src/gametracker/grab_gt_stats.py
- Command line
-
hf download hf://spaces/DSGC/admin_dashboard/src/gametracker/grab_gt_stats.py
-
curl -L -o grab_gt_stats.py https://huggingface.co/spaces/DSGC/admin_dashboard/resolve/main/src/gametracker/grab_gt_stats.py
4.16 kB
| from pathlib import Path | |
| from PIL import Image, ImageOps | |
| import easyocr | |
| import base64 | |
| import requests | |
| import re | |
| import warnings | |
| from urllib.parse import quote_plus | |
| import streamlit as st | |
| # ---- Suppress Torch + EasyOCR warnings ---- | |
| warnings.filterwarnings("ignore", message=".*pin_memory.*") | |
| try: | |
| import torch | |
| GPU_AVAILABLE = bool(getattr(torch, "cuda", None) and torch.cuda.is_available()) \ | |
| or bool(getattr(torch.backends, "mps", None) and torch.backends.mps.is_available()) | |
| except Exception: | |
| GPU_AVAILABLE = False | |
| # ---- Config ---- | |
| HOST_PUBLIC = "149.202.87.35:27015" | |
| HOST_AFK = "149.202.87.35:27016" | |
| START = "-1w" | |
| OUT_DIR = Path("/tmp/") | |
| OUT_DIR.mkdir(parents=True, exist_ok=True) | |
| CROP_BOX = (39, 0, 260, 152) | |
| SCALE_FACTOR = 2 | |
| # ------------------------------ | |
| # Helpers | |
| # ------------------------------ | |
| def b64_name(name: str) -> str: | |
| """Base64-encode a player name for GameTracker URL.""" | |
| return quote_plus(base64.b64encode(name.encode("utf-8")).decode("ascii")) | |
| def build_url(name: str, server_type: str = "public") -> str: | |
| """Build the GameTracker image URL for a specific player.""" | |
| if server_type.lower() == "public": | |
| host = HOST_PUBLIC | |
| elif server_type.lower() == "afk": | |
| host = HOST_AFK | |
| else: | |
| host = HOST_PUBLIC # Default | |
| return ( | |
| "https://cache.gametracker.com/images/graphs/player_time.php" | |
| f"?nameb64={b64_name(name)}&host={host}&start={START}" | |
| ) | |
| def download_image(url: str, out_path: Path) -> Path: | |
| """Download an image from GameTracker and save it locally.""" | |
| out_path.parent.mkdir(parents=True, exist_ok=True) | |
| r = requests.get(url, timeout=20) | |
| # --- DEBUGGING --- | |
| # st.text(f"Request URL: {url}") | |
| # st.text(f"Status code: {r.status_code}") | |
| # st.text(f"Response text (first 200 chars): {r.text[:200]}") | |
| r.raise_for_status() | |
| out_path.write_bytes(r.content) | |
| return out_path | |
| def ocr_total_minutes(reader: easyocr.Reader, image_path: Path) -> int: | |
| """Extract total minutes from a GameTracker image using OCR.""" | |
| gray = ImageOps.grayscale(Image.open(image_path)).crop(CROP_BOX) | |
| resized = gray.resize( | |
| (gray.width * SCALE_FACTOR, gray.height * SCALE_FACTOR), | |
| resample=Image.Resampling.LANCZOS | |
| ) | |
| tmp_path = OUT_DIR / "inprogress.png" | |
| resized.save(tmp_path) | |
| # show image for debuggin purpose | |
| # st.image(resized, caption=f"Current image") | |
| tokens = reader.readtext(str(tmp_path), detail=0) | |
| nums = [] | |
| for t in tokens: | |
| for x in re.findall(r"\d+", str(t)): | |
| try: | |
| nums.append(int(x)) | |
| except ValueError: | |
| pass | |
| return sum(nums) if nums else 0 | |
| def load_admins(path: Path = Path("data") / "admins.txt") -> list[str]: | |
| """Load admin names from a text file.""" | |
| return [ | |
| ln.strip() | |
| for ln in path.read_text(encoding="utf-8").splitlines() | |
| if ln.strip() and not ln.strip().startswith("#") | |
| ] | |
| # ------------------------------ | |
| # Main logic | |
| # ------------------------------ | |
| def fetch_playtimes(admin_file_or_list=Path.cwd().parent / "data" / "admins.txt", server_type: str = "public") -> dict[str, int]: | |
| """ | |
| Fetch playtimes for all admins via GameTracker (OCR). | |
| Accepts either: | |
| - Path to a file containing admin names (one per line), or | |
| - A list of admin names directly. | |
| Returns a dict {admin: minutes}. | |
| """ | |
| if isinstance(admin_file_or_list, (str, Path)): | |
| admins = load_admins(Path(admin_file_or_list)) | |
| elif isinstance(admin_file_or_list, list): | |
| admins = admin_file_or_list | |
| else: | |
| raise TypeError("Expected Path or list[str]") | |
| reader = easyocr.Reader(["en"], gpu=GPU_AVAILABLE) | |
| results: dict[str, int] = {} | |
| for name in admins: | |
| url = build_url(name, server_type) | |
| img_path = OUT_DIR / f"{name}.png" | |
| try: | |
| download_image(url, img_path) | |
| minutes = ocr_total_minutes(reader, img_path) | |
| results[name] = minutes | |
| except Exception as e: | |
| print(f"Error processing {name}: {e}") | |
| return results | |