Flux / app.py
sanch1txp's picture
Update app.py
5ed19bc verified
Raw History Blame Contribute Delete
2.9 kB
import os
import base64
import asyncio
from uuid import uuid4
from datetime import datetime, timedelta
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import FileResponse
from g4f.client import Client
import g4f
app = FastAPI()
# Load Hugging Face token from environment (set as secret in HF Spaces)
HF_TOKEN = os.getenv("HF_TOKEN")
if not HF_TOKEN:
raise EnvironmentError("HF_TOKEN environment variable is not set.")
# Directory for saving images, use /tmp for writable space in HF Spaces
IMAGE_DIR = "/tmp/generated_images"
os.makedirs(IMAGE_DIR, exist_ok=True)
# Track image creation times for cleanup
image_metadata = {}
# Cleanup images older than 30 minutes every 60 seconds
async def cleanup_old_images():
while True:
now = datetime.utcnow()
to_delete = [fname for fname, created in image_metadata.items() if now - created > timedelta(minutes=30)]
for fname in to_delete:
try:
os.remove(os.path.join(IMAGE_DIR, fname))
except Exception:
pass
image_metadata.pop(fname, None)
await asyncio.sleep(60)
# Silent g4f upgrade every 24 hours
async def auto_upgrade_g4f():
while True:
os.system("pip install -U g4f > /dev/null 2>&1")
await asyncio.sleep(86400) # 24 hours
@app.on_event("startup")
async def startup_event():
asyncio.create_task(cleanup_old_images())
asyncio.create_task(auto_upgrade_g4f())
@app.get("/")
async def root():
return {"message": "🖼️ Flux Image API is running! Use /api?prompt=..."}
@app.get("/api")
async def generate_image(prompt: str, request: Request):
client = Client(provider=g4f.Provider.BlackForestLabs_Flux1Dev, api_key=HF_TOKEN)
try:
res = await client.images.async_generate(
model="flux-dev",
prompt=prompt,
response_format="b64_json"
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Image generation failed: {str(e)}")
try:
b64_img = res.data[0].b64_json
except Exception as e:
raise HTTPException(status_code=500, detail=f"Unexpected response format: {str(e)}")
image_bytes = base64.b64decode(b64_img)
filename = f"{uuid4().hex}.webp"
filepath = os.path.join(IMAGE_DIR, filename)
with open(filepath, "wb") as f:
f.write(image_bytes)
image_metadata[filename] = datetime.utcnow()
base_url = str(request.base_url).rstrip("/")
full_url = f"{base_url}/proxy/{filename}"
return {"url": full_url, "expires_in_minutes": 30}
@app.get("/proxy/{filename}")
async def proxy_image(filename: str):
filepath = os.path.join(IMAGE_DIR, filename)
if not os.path.exists(filepath):
raise HTTPException(status_code=404, detail="File expired or not found.")
return FileResponse(filepath, media_type="image/webp")