File size: 3,130 Bytes
08e06c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Persistent visit/creation counter for AI KING©️.

Primary store: a small private dataset repo (INTERNETCON/ai-king-stats, file stats.json),
synced every ~90 s by a background thread (needs the AIKING_HUB_TOKEN Space secret).
Fallback: /data/stats.json if Space persistent storage exists, else ./stats.json
(local JSON resets when the Space restarts; the UI says which store is active).
"""
from __future__ import annotations

import json, os, threading, time

REPO = os.environ.get("AIKING_STATS_REPO", "INTERNETCON/ai-king-stats")
TOKEN = os.environ.get("AIKING_HUB_TOKEN") or None
KEYS = ["visits", "images", "edits", "videos", "audio", "loops", "covers", "prompts"]
_lock = threading.Lock()
_data = {k: 0 for k in KEYS}
_dirty = False
MODE = "local JSON"
_local = "/data/stats.json" if os.path.isdir("/data") and os.access("/data", os.W_OK) else os.path.join(os.path.dirname(__file__), "stats.json")
if _local.startswith("/data"):
    MODE = "Space persistent storage (/data)"


def _merge(d: dict):
    for k in KEYS:
        try:
            _data[k] = max(_data[k], int(d.get(k, 0)))
        except Exception:
            pass


def _init():
    global MODE
    if os.path.exists(_local):
        try:
            _merge(json.load(open(_local)))
        except Exception:
            pass
    if TOKEN and os.environ.get("AIKING_STATS_LOCAL") != "1":
        try:
            from huggingface_hub import HfApi, hf_hub_download
            api = HfApi(token=TOKEN)
            api.create_repo(REPO, repo_type="dataset", private=True, exist_ok=True)
            try:
                p = hf_hub_download(REPO, "stats.json", repo_type="dataset", token=TOKEN, force_download=True)
                _merge(json.load(open(p)))
            except Exception:
                pass
            MODE = f"HF dataset repo ({REPO})"
        except Exception as e:
            print("stats: dataset unavailable, using local JSON:", type(e).__name__)


def _flush_loop():
    global _dirty
    while True:
        time.sleep(90)
        with _lock:
            if not _dirty:
                continue
            snap = dict(_data, updated=int(time.time()))
            _dirty = False
        try:
            json.dump(snap, open(_local, "w"))
        except Exception:
            pass
        if MODE.startswith("HF dataset"):
            try:
                from huggingface_hub import HfApi
                HfApi(token=TOKEN).upload_file(path_or_fileobj=json.dumps(snap, indent=1).encode(), path_in_repo="stats.json",
                                               repo_id=REPO, repo_type="dataset", commit_message="stats sync")
            except Exception as e:
                print("stats: sync failed:", type(e).__name__)
                with _lock:
                    _dirty = True


def hit(key: str, n: int = 1):
    global _dirty
    with _lock:
        _data[key] = _data.get(key, 0) + n
        _dirty = True


def snapshot() -> dict:
    with _lock:
        d = dict(_data)
    d["creations"] = sum(d[k] for k in KEYS if k != "visits")
    return d


_init()
threading.Thread(target=_flush_loop, daemon=True).start()