Spaces:
Paused
Paused
Download app.py from igardner/StockAnalysis: direct link, hf CLI and curl.
- Browser
- Download file 4.71 kB
-
https://huggingface.co/spaces/igardner/StockAnalysis/resolve/main/app.py
- Command line
-
hf download hf://spaces/igardner/StockAnalysis/app.py
-
curl -L -o app.py https://huggingface.co/spaces/igardner/StockAnalysis/resolve/main/app.py
4.71 kB
| import os | |
| import time | |
| import logging | |
| import platform | |
| import re | |
| import sqlite3 | |
| import uuid | |
| from flask import Flask, request, g | |
| from config import Config | |
| from extensions import db, sock | |
| from models import * | |
| from routes import lobby, telemetry, websocket | |
| from games import registry, assigner | |
| from games.loader import GameLoader | |
| from services.lobby import RUNTIME as LOBBY_RUNTIME | |
| from services.eventlog import log_event | |
| from services.brand import random_mark | |
| from services.avatar import AvatarService | |
| # Configure heavy logging - output to stdout so HF captures it | |
| logging.basicConfig( | |
| level=logging.DEBUG if Config.TEST_MODE else logging.INFO, | |
| format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", | |
| datefmt="%Y-%m-%d %H:%M:%S", | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # Silence Werkzeug's per-request HTTP access lines. We emit our own richer, | |
| # filtered request log below (non-GET, errors, and API traffic only). | |
| logging.getLogger("werkzeug").setLevel(logging.ERROR) | |
| app = Flask(__name__, instance_path=Config.INSTANCE_PATH) | |
| app.config.from_object(Config) | |
| os.makedirs(app.instance_path, exist_ok=True) | |
| Config.ensure_data_dir() | |
| os.makedirs(Config.DATA_DIR, exist_ok=True) | |
| db.init_app(app) | |
| sock.init_app(app) | |
| app.register_blueprint(lobby.bp) | |
| app.register_blueprint(telemetry.bp) | |
| def inject_brand(): | |
| from flask import session as _session | |
| uid = _session.get("user_id") | |
| user = User.query.get(uid) if uid else None | |
| avatar = ( | |
| AvatarService.build_url(user.avatar_style, user.avatar_seed, user.avatar_bg) | |
| if user else None | |
| ) | |
| return { | |
| "mark_svg": random_mark(), | |
| "current_user": user, | |
| "current_avatar": avatar, | |
| } | |
| def _start_timer(): | |
| g._t0 = time.perf_counter() | |
| supplied = request.headers.get("X-Request-ID", "") | |
| g.request_id = supplied[:64] if re.fullmatch(r"[A-Za-z0-9._-]{1,64}", supplied) else uuid.uuid4().hex[:16] | |
| request.environ["opencode.request_id"] = g.request_id | |
| def _log_request(response): | |
| """Compact request log: skip successful GETs, keep writes/errors/API.""" | |
| path = request.path | |
| interesting = ( | |
| response.status_code >= 400 | |
| or ( | |
| request.method not in ("GET", "HEAD", "OPTIONS") | |
| and path != "/api/telemetry" | |
| ) | |
| ) | |
| if interesting and not path.startswith("/static/"): | |
| ms = (time.perf_counter() - getattr(g, "_t0", time.perf_counter())) * 1000 | |
| log_event( | |
| "http", | |
| page=path, | |
| payload={ | |
| "method": request.method, | |
| "status": response.status_code, | |
| "ms": round(ms, 1), | |
| }, | |
| request_id=getattr(g, "request_id", None), | |
| req=request, | |
| ) | |
| return response | |
| def _check_sqlite_integrity(): | |
| if db.engine.dialect.name != "sqlite": | |
| return | |
| database = db.engine.url.database or "(memory)" | |
| try: | |
| with db.engine.connect() as connection: | |
| results = [row[0] for row in connection.exec_driver_sql( | |
| "PRAGMA integrity_check" | |
| ).fetchmany(5)] | |
| except Exception as exc: | |
| raise RuntimeError( | |
| f"SQLite integrity preflight failed for {database}: {type(exc).__name__}: {exc}" | |
| ) from exc | |
| if results != ["ok"]: | |
| details = "; ".join(str(item) for item in results)[:1000] | |
| raise RuntimeError( | |
| f"SQLite integrity preflight found corruption in {database}: {details}" | |
| ) | |
| # Load games | |
| loader = GameLoader(registry) | |
| loader.discover() | |
| logger.info("GAMES_LOADED count=%s", len(registry.list_games())) | |
| with app.app_context(): | |
| logger.info( | |
| "RUNTIME_VERSIONS python=%s sqlite=%s", | |
| platform.python_version(), sqlite3.sqlite_version, | |
| ) | |
| _check_sqlite_integrity() | |
| db.create_all() | |
| from models import migrate_db | |
| migrate_db(app) | |
| logger.info( | |
| "DATABASE_INITIALIZED driver=%s database=%s", | |
| db.engine.dialect.name, | |
| db.engine.url.database, | |
| ) | |
| LOBBY_RUNTIME.start(app) | |
| def health(): | |
| runtime_alive = bool(LOBBY_RUNTIME._thread and LOBBY_RUNTIME._thread.is_alive()) | |
| return { | |
| "status": "ok", | |
| "games": len(registry.list_games()), | |
| "test_mode": Config.TEST_MODE, | |
| "lobby_runtime": "running" if runtime_alive else "stopped", | |
| } | |
| if __name__ == "__main__": | |
| logger.info("STARTING cuddly happy game platform on 0.0.0.0:7860") | |
| # The lobby scheduler is process-local; avoid a second scheduler in the | |
| # Werkzeug debug reloader parent/child pair. | |
| app.run(host="0.0.0.0", port=7860, debug=True, use_reloader=False) | |