lightlambert0 commited on
Commit
2396bb6
·
verified ·
1 Parent(s): 2136000

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +209 -0
app.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Lambert AI Image Generator - Hugging Face Space
4
+ Génération d'images HD avec SDXL 1.0 - Version sécurisée + Anti-veille
5
+ """
6
+
7
+ import gradio as gr
8
+ from diffusers import StableDiffusionXLPipeline
9
+ import torch
10
+ import os
11
+ import gc
12
+ import threading
13
+ import time
14
+ import requests
15
+ from functools import wraps
16
+
17
+ # ========== CONFIGURATION ==========
18
+ # 🔑 La clé API est UNIQUEMENT dans les variables d'environnement
19
+ # Ne JAMAIS mettre de clé en dur ici !
20
+ API_KEY = os.environ.get("API_KEY")
21
+
22
+ # Vérification obligatoire
23
+ if not API_KEY:
24
+ print("=" * 60)
25
+ print("❌ ERREUR CRITIQUE: Clé API non configurée!")
26
+ print("📌 Pour corriger:")
27
+ print(" 1. Allez dans Settings → Repository secrets")
28
+ print(" 2. Ajoutez un secret: Name = API_KEY, Value = votre-clé")
29
+ print(" 3. Redémarrez le Space")
30
+ print("=" * 60)
31
+ raise ValueError("API_KEY non configurée dans les variables d'environnement")
32
+
33
+ MODEL_NAME = "stabilityai/stable-diffusion-xl-base-1.0"
34
+ USE_GPU = torch.cuda.is_available()
35
+ DEVICE = "cuda" if USE_GPU else "cpu"
36
+ DTYPE = torch.float16 if USE_GPU else torch.float32
37
+
38
+ print(f"🚀 Démarrage sur {DEVICE}")
39
+ print(f"🔒 Clé API configurée: ✅ Oui (depuis variables d'environnement)")
40
+ print(f"📝 Longueur de la clé: {len(API_KEY)} caractères")
41
+
42
+ # ========== ANTI-VEILLE ==========
43
+ # Récupérer l'URL du Space
44
+ SPACE_HOST = os.environ.get("SPACE_HOST", "")
45
+ SPACE_URL = f"https://{SPACE_HOST}" if SPACE_HOST else "https://localhost"
46
+
47
+ def anti_veille():
48
+ """Ping automatique toutes les 7 minutes pour éviter la mise en veille"""
49
+ if not SPACE_HOST:
50
+ return
51
+ while True:
52
+ try:
53
+ response = requests.get(SPACE_URL, timeout=10)
54
+ print(f"💓 Anti-veille: ping envoyé - Status {response.status_code}")
55
+ except Exception as e:
56
+ print(f"⚠️ Anti-veille: erreur - {e}")
57
+ time.sleep(420) # 7 minutes
58
+
59
+ # Démarrer le thread anti-veille
60
+ if SPACE_HOST:
61
+ anti_veille_thread = threading.Thread(target=anti_veille, daemon=True)
62
+ anti_veille_thread.start()
63
+ print("✅ Service anti-veille démarré (ping toutes les 7 minutes)")
64
+ else:
65
+ print("⚠️ Anti-veille désactivé (mode local)")
66
+
67
+ # ========== AUTHENTIFICATION ==========
68
+ def check_auth(api_key):
69
+ """Vérifie si la clé API est valide"""
70
+ return api_key == API_KEY
71
+
72
+ def require_auth(func):
73
+ """Décorateur pour protéger la fonction"""
74
+ @wraps(func)
75
+ def wrapper(api_key, *args, **kwargs):
76
+ if not check_auth(api_key):
77
+ return None, "🔒 Non autorisé - Clé API invalide"
78
+ return func(*args, **kwargs)
79
+ return wrapper
80
+
81
+ # ========== MODÈLE ==========
82
+ pipe = None
83
+
84
+ def load_model():
85
+ """Charge le modèle SDXL (une seule fois)"""
86
+ global pipe
87
+ if pipe is None:
88
+ print("🚀 Chargement du modèle SDXL...")
89
+ pipe = StableDiffusionXLPipeline.from_pretrained(
90
+ MODEL_NAME,
91
+ torch_dtype=DTYPE,
92
+ use_safetensors=True,
93
+ variant="fp16" if USE_GPU else None
94
+ )
95
+
96
+ if USE_GPU:
97
+ pipe = pipe.to(DEVICE)
98
+ pipe.enable_attention_slicing()
99
+ print("✅ Modèle chargé sur GPU")
100
+ else:
101
+ print("⚠️ Modèle chargé sur CPU (plus lent)")
102
+ return pipe
103
+
104
+ # ========== GÉNÉRATION ==========
105
+ @require_auth
106
+ def generate_image(prompt, negative_prompt, steps, width, height, seed, guidance):
107
+ """Génère une image avec SDXL"""
108
+ try:
109
+ pipe = load_model()
110
+
111
+ if seed != -1:
112
+ torch.manual_seed(seed)
113
+
114
+ print(f"🎨 Génération: {prompt[:50]}...")
115
+
116
+ image = pipe(
117
+ prompt=prompt,
118
+ negative_prompt=negative_prompt,
119
+ num_inference_steps=int(steps),
120
+ width=int(width),
121
+ height=int(height),
122
+ guidance_scale=float(guidance)
123
+ ).images[0]
124
+
125
+ gc.collect()
126
+ if USE_GPU:
127
+ torch.cuda.empty_cache()
128
+
129
+ return image, "✅ Génération réussie !"
130
+
131
+ except Exception as e:
132
+ print(f"❌ Erreur: {e}")
133
+ return None, f"❌ Erreur: {str(e)}"
134
+
135
+ # ========== INTERFACE GRADIO ==========
136
+ with gr.Blocks(
137
+ title="Lambert AI Image Generator",
138
+ theme=gr.themes.Soft(primary_hue="blue", secondary_hue="purple"),
139
+ css="""
140
+ .gradio-container { max-width: 1200px; margin: auto; }
141
+ .footer { text-align: center; margin-top: 20px; font-size: 0.8em; opacity: 0.7; }
142
+ """
143
+ ) as demo:
144
+
145
+ gr.Markdown("""
146
+ # 🎨 Lambert AI Image Generator
147
+
148
+ ### Génération d'images HD avec SDXL 1.0
149
+ *Service réservé à Lambert Assistant - Clé API requise*
150
+
151
+ **⏰ Anti-veille actif: service disponible 24h/24**
152
+ """)
153
+
154
+ with gr.Row():
155
+ with gr.Column(scale=1):
156
+ api_key_input = gr.Textbox(
157
+ label="🔒 Clé API (obligatoire)",
158
+ type="password",
159
+ placeholder="Entrez votre clé API",
160
+ value=""
161
+ )
162
+
163
+ prompt = gr.Textbox(
164
+ label="📝 Prompt",
165
+ lines=3,
166
+ placeholder="Ex: Un dragon en feu volant au-dessus d'un château..."
167
+ )
168
+
169
+ negative = gr.Textbox(
170
+ label="🚫 Negative prompt",
171
+ lines=2,
172
+ placeholder="bad hands, deformed fingers, blurry...",
173
+ value="bad hands, deformed fingers, blurry, distorted, ugly, low quality"
174
+ )
175
+
176
+ with gr.Row():
177
+ steps = gr.Slider(minimum=15, maximum=50, value=25, step=1, label="🎯 Steps")
178
+ guidance = gr.Slider(minimum=1, maximum=15, value=7.5, step=0.5, label="🎨 Guidance")
179
+
180
+ with gr.Row():
181
+ width = gr.Dropdown(choices=[512, 768, 1024, 1280], value=1024, label="📏 Largeur")
182
+ height = gr.Dropdown(choices=[512, 768, 1024, 1280], value=1024, label="📏 Hauteur")
183
+ seed = gr.Number(value=-1, precision=0, label="🎲 Seed (-1 = aléatoire)")
184
+
185
+ btn = gr.Button("🚀 Générer l'image", variant="primary", size="lg")
186
+
187
+ with gr.Column(scale=1):
188
+ output = gr.Image(label="🖼️ Image générée")
189
+ status = gr.Markdown("💡 Entrez votre clé API et un prompt")
190
+
191
+ btn.click(
192
+ fn=generate_image,
193
+ inputs=[api_key_input, prompt, negative, steps, width, height, seed, guidance],
194
+ outputs=[output, status]
195
+ )
196
+
197
+ gr.Markdown("""
198
+ <div class="footer">
199
+ 🚀 Hébergé sur Hugging Face Spaces | Modèle: SDXL 1.0 | Anti-veille: ✅ actif
200
+ </div>
201
+ """)
202
+
203
+ # ========== LANCEMENT ==========
204
+ if __name__ == "__main__":
205
+ print("=" * 50)
206
+ print("🎨 Lambert Image Generator - Prêt")
207
+ print("💓 Anti-veille: démarré (ping toutes les 7 minutes)")
208
+ print("=" * 50)
209
+ demo.launch(server_name="0.0.0.0", server_port=7860)