Spaces:
Sleeping
Sleeping
Update src/gametracker/grab_gt_stats.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109from pathlib import Pathfrom PIL import Image, ImageOpsimport easyocrimport base64import requestsimport reimport warningsfrom urllib.parse import quote_plus# ---- Suppress Torch + EasyOCR warnings ----warnings.filterwarnings("ignore", message=".*pin_memory.*")try:import torchGPU_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 = "149.202.87.35:27015"START = "-1w"OUT_DIR = Path("data") / "images"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) -> str:"""Build the GameTracker image URL for a specific player."""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)r.raise_for_status()out_path.write_bytes(r.content)return out_pathdef 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)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:passreturn sum(nums) if nums else 0def 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: Path = Path.cwd().parent / "data" / "admins.txt") -> dict[str, int]:"""Fetch playtimes for all admins via GameTracker (OCR).Returns a dict {admin: minutes}."""admins = load_admins(admin_file)reader = easyocr.Reader(["en"], gpu=GPU_AVAILABLE)results: dict[str, int] = {}for name in admins:url = build_url(name)img_path = OUT_DIR / f"{name}.png"try:download_image(url, img_path)minutes = ocr_total_minutes(reader, img_path)results[name] = minutesexcept Exception as e:print(f"Error processing {name}: {e}")return resultsdef main():results = fetch_playtimes()for name, minutes in results.items():print(f"{name}: {minutes} minutes")if __name__ == "__main__":main()
src/gametracker/grab_gt_stats.py+109