sanch1txp commited on
Commit
2812cf0
·
verified ·
1 Parent(s): 9da3c0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -25
app.py CHANGED
@@ -1,39 +1,72 @@
1
- import os, base64
 
 
2
  from uuid import uuid4
3
  from datetime import datetime, timedelta
4
- from fastapi import FastAPI, Request
5
- from fastapi.responses import JSONResponse
6
- from fastapi.staticfiles import StaticFiles
7
  import g4f
8
 
9
  app = FastAPI()
10
- client = g4f.Client()
11
- TEMP_DIR = "/tmp"
12
 
 
 
 
 
 
13
  os.makedirs(TEMP_DIR, exist_ok=True)
14
- app.mount("/static", StaticFiles(directory=TEMP_DIR), name="static")
15
 
16
- def cleanup_old_files():
17
- now = datetime.now()
18
- for fname in os.listdir(TEMP_DIR):
19
- path = os.path.join(TEMP_DIR, fname)
20
- if os.path.isfile(path):
21
- if now - datetime.fromtimestamp(os.path.getctime(path)) > timedelta(minutes=30):
22
- os.remove(path)
 
 
 
23
 
24
  @app.get("/api")
25
- async def generate(request: Request, prompt: str):
26
- cleanup_old_files()
27
  try:
28
- res = await client.images.async_generate(
29
- model="flux-dev", prompt=prompt, response_format="b64_json"
30
- )
31
- img_data = base64.b64decode(res["data"][0]["b64_json"])
32
- file_id = f"{uuid4()}.png"
33
- img_path = os.path.join(TEMP_DIR, file_id)
34
- with open(img_path, "wb") as f:
 
35
  f.write(img_data)
36
 
37
- return {"url": f"{request.base_url}static/{file_id}"}
 
 
38
  except Exception as e:
39
- return JSONResponse(status_code=500, content={"error": str(e)})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import base64
3
+ import asyncio
4
  from uuid import uuid4
5
  from datetime import datetime, timedelta
6
+ from fastapi import FastAPI
7
+ from fastapi.responses import FileResponse, JSONResponse
8
+ from g4f.client import AsyncClient
9
  import g4f
10
 
11
  app = FastAPI()
 
 
12
 
13
+ HF_TOKEN = os.getenv("HF_TOKEN")
14
+ if not HF_TOKEN:
15
+ raise RuntimeError("HF_TOKEN not set in environment.")
16
+
17
+ TEMP_DIR = "/tmp/generated_images"
18
  os.makedirs(TEMP_DIR, exist_ok=True)
 
19
 
20
+ image_cache = {}
21
+
22
+ @app.on_event("startup")
23
+ async def startup_event():
24
+ asyncio.create_task(clean_old_images())
25
+ asyncio.create_task(update_g4f_periodically())
26
+
27
+ @app.get("/")
28
+ def home():
29
+ return {"message": "🖼️ Flux Image API is running! Use /api?prompt=..."}
30
 
31
  @app.get("/api")
32
+ async def generate(prompt: str):
 
33
  try:
34
+ client = AsyncClient(provider=g4f.Provider.BlackForestLabs_Flux1Dev, api_key=HF_TOKEN)
35
+ res = await client.images.async_generate(model="flux-dev", prompt=prompt, response_format="b64_json")
36
+
37
+ img_data = base64.b64decode(res.data[0]["b64_json"])
38
+ filename = f"{uuid4().hex}.webp"
39
+ filepath = os.path.join(TEMP_DIR, filename)
40
+
41
+ with open(filepath, "wb") as f:
42
  f.write(img_data)
43
 
44
+ image_cache[filename] = {"path": filepath, "created": datetime.utcnow()}
45
+ return {"url": f"/proxy/{filename}", "expires_in": "30 minutes"}
46
+
47
  except Exception as e:
48
+ return JSONResponse(content={"error": str(e)}, status_code=500)
49
+
50
+ @app.get("/proxy/{filename}")
51
+ async def proxy_image(filename: str):
52
+ file_path = image_cache.get(filename, {}).get("path")
53
+ if file_path and os.path.exists(file_path):
54
+ return FileResponse(file_path, media_type="image/webp")
55
+ return JSONResponse(content={"error": "Image not found or expired."}, status_code=404)
56
+
57
+ async def clean_old_images():
58
+ while True:
59
+ now = datetime.utcnow()
60
+ for name, meta in list(image_cache.items()):
61
+ if now - meta["created"] > timedelta(minutes=30):
62
+ try:
63
+ os.remove(meta["path"])
64
+ del image_cache[name]
65
+ except Exception:
66
+ pass
67
+ await asyncio.sleep(60)
68
+
69
+ async def update_g4f_periodically():
70
+ while True:
71
+ os.system("pip install -U g4f > /dev/null 2>&1")
72
+ await asyncio.sleep(86400) # 24 hours