Spaces:
Sleeping
Sleeping
| import os | |
| import base64 | |
| import requests | |
| import uvicorn | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.responses import HTMLResponse | |
| from pydantic import BaseModel | |
| app = FastAPI() | |
| # Configuration via Secret (HF_TOKEN doit être dans tes "Secrets" sur HF) | |
| HF_TOKEN = os.environ.get("HF_TOKEN") | |
| # Utilisation de l'API Stable Diffusion XL pour la haute qualité | |
| API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0" | |
| class ImageRequest(BaseModel): | |
| prompt: str | |
| async def generate_image(request: ImageRequest): | |
| if not HF_TOKEN: | |
| raise HTTPException(status_code=500, detail="Token HF_TOKEN manquant dans les Secrets.") | |
| headers = {"Authorization": f"Bearer {HF_TOKEN}"} | |
| try: | |
| # Envoi de la requête à l'API Hugging Face | |
| response = requests.post(API_URL, headers=headers, json={"inputs": request.prompt}) | |
| if response.status_code != 200: | |
| # Si le modèle est en train de charger, on renvoie une erreur propre | |
| print(f"Erreur API: {response.text}") | |
| raise Exception("L'IA est occupée ou en chargement. Réessayez dans 30 secondes.") | |
| # Conversion binaire -> Base64 pour éviter l'écriture de fichiers (Error 137) | |
| base64_image = base64.b64encode(response.content).decode('utf-8') | |
| # Format compatible avec ton script JavaScript | |
| return {"image_url": f"data:image/png;base64,{base64_image}"} | |
| except Exception as e: | |
| print(f"❌ Erreur : {str(e)}") | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def read_index(): | |
| # Lit ton fichier HTML et le renvoie au navigateur | |
| try: | |
| with open("index.html", "r", encoding="utf-8") as f: | |
| return f.read() | |
| except FileNotFoundError: | |
| return "Fichier index.html introuvable. Assurez-vous qu'il est à la racine." | |
| if __name__ == "__main__": | |
| # Port 7860 obligatoire pour Hugging Face Spaces | |
| uvicorn.run(app, host="0.0.0.0", port=7860) |