Spaces:
Running
Running
| import asyncio | |
| import os | |
| from fastapi import FastAPI | |
| from fastapi.responses import FileResponse | |
| from contextlib import asynccontextmanager | |
| import subprocess | |
| # We will run the bot as a background subprocess so it doesn't block the web server event loop | |
| bot_process = None | |
| async def lifespan(app: FastAPI): | |
| global bot_process | |
| # Setup data files | |
| if not os.path.exists("game_history.csv"): | |
| open("game_history.csv", "w").close() | |
| # Start the bot.py in background with xvfb wrapper to simulate a real monitor display | |
| bot_process = subprocess.Popen(["xvfb-run", "-a", "python", "run_bot.py"]) | |
| print("[SERVER] Bot started in background with Xvfb (Virtual Display)...") | |
| yield | |
| # Teardown: Stop the bot | |
| if bot_process: | |
| bot_process.terminate() | |
| print("[SERVER] Bot stopped.") | |
| app = FastAPI(lifespan=lifespan) | |
| def read_root(): | |
| return {"status": "Active", "message": "Aviator Data Collector is running ๐"} | |
| def get_results(): | |
| try: | |
| if os.path.exists("game_history.csv"): | |
| with open("game_history.csv", "r") as f: | |
| lines = f.readlines() | |
| # return last 50 results | |
| return {"results": [l.strip() for l in lines[-50:]]} | |
| except: | |
| pass | |
| return {"results": []} | |
| def download_file(): | |
| """Allows user to directly download the CSV file""" | |
| if os.path.exists("game_history.csv"): | |
| return FileResponse(path="game_history.csv", filename="game_history.csv", media_type="text/csv") | |
| return {"error": "File not found or no data collected yet."} | |