File size: 1,986 Bytes
a3bfafd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
HuggingRun default demo: minimal HTTP app on port 7860 with persistence.
- Serves a simple page showing visit counter and PERSIST_PATH status.
- Counter is stored in PERSIST_PATH/counter.txt so it survives restarts (via HF Dataset sync).
"""
import os
import http.server
import socketserver
from pathlib import Path

PORT = int(os.environ.get("PORT", "7860"))
PERSIST_PATH = Path(os.environ.get("PERSIST_PATH", "/data"))
COUNTER_FILE = PERSIST_PATH / "counter.txt"


def get_counter():
    PERSIST_PATH.mkdir(parents=True, exist_ok=True)
    try:
        return int(COUNTER_FILE.read_text().strip())
    except (FileNotFoundError, ValueError):
        return 0


def inc_counter():
    c = get_counter() + 1
    PERSIST_PATH.mkdir(parents=True, exist_ok=True)
    COUNTER_FILE.write_text(str(c))
    return c


class DemoHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        count = inc_counter()
        body = f"""<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>HuggingRun</title></head>
<body style="font-family:sans-serif;max-width:600px;margin:2em auto;padding:1em;">
<h1>Run anything on Hugging Face.</h1>
<p>This is the default HuggingRun demo. Persistence path: <code>{PERSIST_PATH}</code></p>
<p><strong>Visit count (persisted):</strong> {count}</p>
<p>Set <code>RUN_CMD</code> in your Space secrets to run your own app.</p>
</body></html>"""
        self.send_response(200)
        self.send_header("Content-type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(body.encode("utf-8"))))
        self.end_headers()
        self.wfile.write(body.encode("utf-8"))

    def log_message(self, format, *args):
        print(f"[demo] {args[0]}")


if __name__ == "__main__":
    PERSIST_PATH.mkdir(parents=True, exist_ok=True)
    with socketserver.TCPServer(("0.0.0.0", PORT), DemoHandler) as httpd:
        print(f"[HuggingRun demo] Listening on 0.0.0.0:{PORT}")
        httpd.serve_forever()