lightlambert0's picture
Update app.py
4d75a35 verified
Raw History Blame Contribute Delete
4.57 kB
#!/usr/bin/env python3
"""
Lambert AI Image Generator - Hugging Face Inference API
Fiable et rapide sur HF Spaces
"""
import gradio as gr
import requests
import io
import os
from PIL import Image
from functools import wraps
import time
# ========== CONFIGURATION ==========
API_KEY = os.environ.get("API_KEY")
HF_TOKEN = os.environ.get("HF_TOKEN") # Token Hugging Face
if not HF_TOKEN:
print("⚠️ HF_TOKEN non configuré dans les secrets")
def check_auth(api_key):
return api_key == API_KEY
def require_auth(func):
@wraps(func)
def wrapper(api_key, *args, **kwargs):
if not check_auth(api_key):
return None, "🔒 Clé API invalide"
return func(*args, **kwargs)
return wrapper
# ========== GÉNÉRATION VIA API HUGGING FACE ==========
@require_auth
def generate_image(prompt, style, width, height, seed):
try:
# Styles
styles = {
"✨ Général": "",
"📸 Photo réaliste": "photorealistic, realistic, 8k, sharp focus, detailed",
"🎨 Artistique": "digital art, artistic, vibrant colors, masterpiece, trending on artstation",
"🎬 Cinématique": "cinematic, dramatic lighting, epic composition, movie poster"
}
style_suffix = styles.get(style, "")
if style_suffix:
final_prompt = f"{prompt}, {style_suffix}"
else:
final_prompt = prompt
print(f"🎨 Génération: {final_prompt[:50]}...")
# API Hugging Face - Modèle SDXL Turbo (rapide)
API_URL = "https://api-inference.huggingface.co/models/stabilityai/sdxl-turbo"
headers = {
"Authorization": f"Bearer {HF_TOKEN}"
}
payload = {
"inputs": final_prompt,
"parameters": {
"negative_prompt": "blurry, ugly, low quality, deformed",
"num_inference_steps": 4,
"guidance_scale": 0.0
}
}
response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
if response.status_code == 200:
# Convertir la réponse en image
image = Image.open(io.BytesIO(response.content))
temp_path = "/tmp/generated_image.png"
image.save(temp_path)
return temp_path, f"✅ Image générée ! Prompt: {final_prompt[:80]}"
else:
return None, f"❌ Erreur API: {response.status_code} - {response.text}"
except requests.exceptions.Timeout:
return None, "⏰ Timeout. Réessayez."
except Exception as e:
print(f"❌ Erreur: {e}")
return None, f"❌ {str(e)}"
# ========== INTERFACE GRADIO ==========
with gr.Blocks(title="Lambert AI - Image Generator") as demo:
gr.Markdown("""
# 🎨 Lambert AI - Image Generator
### Propulsé par Hugging Face Inference API
""")
with gr.Row():
with gr.Column(scale=1):
api_key_input = gr.Textbox(
label="🔒 Clé API Lambert",
type="password",
placeholder="Votre clé API"
)
prompt = gr.Textbox(
label="📝 Description",
lines=3,
placeholder="Ex: un chat mignon avec un chapeau de magicien"
)
style = gr.Dropdown(
choices=["✨ Général", "📸 Photo réaliste", "🎨 Artistique", "🎬 Cinématique"],
value="✨ Général",
label="🎭 Style"
)
with gr.Row():
width = gr.Dropdown(choices=[512, 768, 1024], value=768, label="Largeur")
height = gr.Dropdown(choices=[512, 768, 1024], value=768, label="Hauteur")
seed = gr.Number(value=-1, precision=0, label="🎲 Seed (-1 = aléatoire)")
btn = gr.Button("🚀 Générer l'image", variant="primary")
with gr.Column(scale=1):
output = gr.Image(label="🖼️ Image générée", height=450)
status = gr.Markdown("💡 Entrez votre clé API")
btn.click(
fn=generate_image,
inputs=[api_key_input, prompt, style, width, height, seed],
outputs=[output, status]
)
if __name__ == "__main__":
print("=" * 50)
print("✨ Lambert AI - Hugging Face API")
print("🎨 Modèle: SDXL Turbo")
print("⚡ Génération rapide et fiable")
print("=" * 50)
demo.launch(server_name="0.0.0.0", server_port=7860)