Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI | |
| from fastapi.responses import JSONResponse | |
| import time | |
| import psutil | |
| import os | |
| app = FastAPI() | |
| process = psutil.Process(os.getpid()) | |
| last_cpu_times = process.cpu_times() | |
| last_time = time.time() | |
| def get_cpu_percent(): | |
| global last_cpu_times, last_time | |
| now = time.time() | |
| times = process.cpu_times() | |
| elapsed = now - last_time | |
| cpu_used = (times.user - last_cpu_times.user) + (times.system - last_cpu_times.system) | |
| last_cpu_times = times | |
| last_time = now | |
| return round((cpu_used / elapsed) * 100, 1) | |
| def simulate_work(): | |
| start = time.time() | |
| while (time.time() - start) < 0.005: | |
| pass | |
| async def root(): | |
| simulate_work() | |
| return {"ok": True, "time": int(time.time() * 1000)} | |
| async def metrics(): | |
| try: | |
| cpu_percent = get_cpu_percent() | |
| mem_info = process.memory_info() | |
| return { | |
| "cpu": cpu_percent, | |
| "memory": round(mem_info.rss / 1024 / 1024, 1) | |
| } | |
| except Exception as e: | |
| return JSONResponse(status_code=500, content={"error": str(e)}) | |
| if __name__ == "__main__": | |
| port = int(os.environ.get("PORT", 3000)) | |
| print(f"✅ FastAPI server running on port {port}") | |
| import uvicorn | |
| uvicorn.run("main:app", host="0.0.0.0", port=port, log_level="info") | |