Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# main.py
|
2 |
+
import asyncio
|
3 |
+
import logging
|
4 |
+
import os
|
5 |
+
|
6 |
+
from fastapi import FastAPI, Request, HTTPException
|
7 |
+
from starlette.responses import JSONResponse
|
8 |
+
import uvicorn
|
9 |
+
|
10 |
+
import bot
|
11 |
+
import config
|
12 |
+
|
13 |
+
app = FastAPI()
|
14 |
+
|
15 |
+
# Health endpoint
|
16 |
+
@app.get("/health")
|
17 |
+
async def health():
|
18 |
+
return {"status": "ok", "uptime": bot.get_uptime()}
|
19 |
+
|
20 |
+
# Optional admin endpoint (secured with ADMIN_API_TOKEN)
|
21 |
+
@app.get("/admin")
|
22 |
+
async def admin(request: Request):
|
23 |
+
token = request.query_params.get("token")
|
24 |
+
if config.ADMIN_API_TOKEN and token != config.ADMIN_API_TOKEN:
|
25 |
+
raise HTTPException(status_code=403, detail="Forbidden")
|
26 |
+
|
27 |
+
# Basic batch stats
|
28 |
+
batches = {
|
29 |
+
batch_id: {
|
30 |
+
"processed": batch["processed_links"],
|
31 |
+
"total": batch["total_links"],
|
32 |
+
"successful": len(batch["successful_downloads"]),
|
33 |
+
"failed": len(batch["failed_links"]),
|
34 |
+
}
|
35 |
+
for batch_id, batch in bot.BATCH_JOBS.items()
|
36 |
+
}
|
37 |
+
return {"active_batches": batches}
|
38 |
+
|
39 |
+
async def main():
|
40 |
+
# Run both bot and web API
|
41 |
+
bot_task = asyncio.create_task(bot.run_bot())
|
42 |
+
await bot_task
|
43 |
+
|
44 |
+
if __name__ == "__main__":
|
45 |
+
# Run FastAPI + start asyncio bot inside it
|
46 |
+
import threading
|
47 |
+
|
48 |
+
def run_uvicorn():
|
49 |
+
uvicorn.run("main:app", host="0.0.0.0", port=7860, log_level="info")
|
50 |
+
|
51 |
+
threading.Thread(target=run_uvicorn, daemon=True).start()
|
52 |
+
|
53 |
+
asyncio.run(main())
|