HuggingRun / app /demo_app.py
tao-shen's picture
HuggingRun: Run anything on Hugging Face — generic Docker + persistence
a3bfafd
#!/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()