Spaces:
Sleeping

File size: 4,160 Bytes
30de2ca
 
 
 
 
 
 
 
fda591b
30de2ca
 
 
 
 
 
 
 
 
 
 
 
9777545
 
30de2ca
5063fec
4b09c14
30de2ca
 
 
 
 
 
 
 
 
 
 
9777545
30de2ca
9777545
 
 
 
 
 
30de2ca
 
9777545
30de2ca
 
 
 
 
 
5a97fac
aaaf0a3
 
 
30de2ca
 
 
 
 
 
 
 
 
 
 
 
 
433b797
 
 
30de2ca
 
 
 
 
 
 
 
 
 
d1cbc96
30de2ca
 
 
 
 
 
 
 
 
 
 
 
 
9777545
30de2ca
 
433b797
 
 
30de2ca
 
433b797
 
 
 
 
 
 
 
30de2ca
 
 
 
9777545
30de2ca
 
 
 
 
 
aaaf0a3
30de2ca
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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