"""Independent logs page for VNEWS Space. Serves /logs (HTML) and /logs.txt (raw) so build/runtime errors are visible even when the Hugging Face build-logs tab is stuck/unavailable. Mounted from _run.py. """ import os import time import json import subprocess from fastapi import Request from fastapi.responses import HTMLResponse, PlainTextResponse try: from app_v2_entry import app except Exception: from main import app BUILD_DONE = "/app/.build_done" DATA_DIR = '/data' if os.path.isdir('/data') else os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data') def _collect(): lines = [] lines.append("=== VNEWS LOGS ===") lines.append("generated: " + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) lines.append("") # Build marker if os.path.exists(BUILD_DONE): lines.append("[BUILD] .build_done exists -> container started OK") try: lines.append("[BUILD] built at: " + open(BUILD_DONE).read().strip()) except Exception: pass else: lines.append("[BUILD] WARNING: .build_done MISSING -> uvicorn started before build finished?") lines.append("") # Space status from HF runtime file try: import json as _j mj = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.huggingface', 'main.json') if os.path.exists(mj): lines.append("[RUNTIME] .huggingface/main.json present") else: lines.append("[RUNTIME] .huggingface/main.json NOT found") except Exception as e: lines.append("[RUNTIME] error: " + str(e)) lines.append("") # Data dir contents lines.append("[DATA] dir=" + DATA_DIR) try: if os.path.isdir(DATA_DIR): for f in sorted(os.listdir(DATA_DIR)): p = os.path.join(DATA_DIR, f) lines.append(" - %s (%d bytes)" % (f, os.path.getsize(p))) else: lines.append(" (data dir missing)") except Exception as e: lines.append(" error: " + str(e)) lines.append("") # Recent container logs (stdout) if captured log_paths = ["/tmp/vnews_stdout.log", os.path.join(DATA_DIR, "app.log")] for lp in log_paths: if os.path.exists(lp): lines.append("[STDOUT] tail of " + lp + ":") try: with open(lp, "r", errors="replace") as fh: tail = fh.read().splitlines()[-50:] for l in tail: lines.append(" " + l) except Exception as e: lines.append(" read error: " + str(e)) lines.append("") # Environment hints lines.append("[ENV] HF_SPACE: " + os.environ.get("HF_SPACE", "?")) lines.append("[ENV] SPACE_ID: " + os.environ.get("SPACE_ID", "?")) lines.append("[ENV] CUDA/CPU: " + ("gpu" if os.environ.get("CUDA_VISIBLE_DEVICES") else "cpu")) lines.append("") lines.append("=== END ===") return "\n".join(lines) @app.get("/logs") def logs_page(request: Request): txt = _collect() html = ( "
" "" "📄 raw text · refresh để cập nhật
" "" + txt.replace("&", "&").replace("<", "<").replace(">", ">") + ""
""
)
return HTMLResponse(html)
@app.get("/logs.txt")
def logs_raw(request: Request):
return PlainTextResponse(_collect())