| | import uvicorn |
| | from fastapi import FastAPI, HTTPException |
| | from fastapi.staticfiles import StaticFiles |
| | from fastapi.responses import FileResponse |
| | from pydantic import BaseModel |
| | import requests |
| | import os |
| | import uuid |
| |
|
| | app = FastAPI() |
| |
|
| | |
| | HF_TOKEN = os.environ.get("HF_TOKEN") |
| | API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0" |
| |
|
| | class ImageRequest(BaseModel): |
| | prompt: str |
| |
|
| | @app.post("/generate") |
| | async def generate_image(request: ImageRequest): |
| | print(f"🎨 Génération (HF API) : {request.prompt}") |
| | |
| | if not HF_TOKEN: |
| | raise HTTPException(status_code=500, detail="Token HF manquant. Configurez le secret HF_TOKEN.") |
| |
|
| | headers = {"Authorization": f"Bearer {HF_TOKEN}"} |
| | payload = {"inputs": request.prompt} |
| | |
| | try: |
| | response = requests.post(API_URL, headers=headers, json=payload) |
| | |
| | if response.status_code != 200: |
| | raise Exception(f"Erreur API HF: {response.text}") |
| | |
| | |
| | image_bytes = response.content |
| | |
| | |
| | filename = f"gen_{uuid.uuid4()}.png" |
| | with open(filename, "wb") as f: |
| | f.write(image_bytes) |
| | |
| | |
| | return {"image_url": f"/{filename}"} |
| |
|
| | except Exception as e: |
| | print(f"❌ Erreur : {str(e)}") |
| | raise HTTPException(status_code=500, detail=str(e)) |
| |
|
| | @app.get("/") |
| | async def read_index(): |
| | return FileResponse('index.html') |
| |
|
| | app.mount("/", StaticFiles(directory=".", html=True), name="static") |
| |
|
| | if __name__ == "__main__": |
| | uvicorn.run(app, host="0.0.0.0", port=7860) |
| |
|