File size: 8,406 Bytes
930b748
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env python3
"""
API Flask pour générer des images
Endpoint unique: /generate
"""

import torch
from pathlib import Path
from flask import Flask, request, jsonify, send_file
from diffusers import StableDiffusionPipeline
from datetime import datetime
import io

app = Flask(__name__)

# Configuration
MODEL_PATH = Path("/app/model")
OUTPUT_DIR = Path("/app/generated_images")
OUTPUT_DIR.mkdir(exist_ok=True, parents=True)

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

# Variable globale
pipeline = None
model_loaded = False

def load_model():
    """Charge le modèle au démarrage"""
    global pipeline, model_loaded
    
    print("\n" + "="*70)
    print("🤖 Chargement du modèle fusionné...")
    print("="*70 + "\n")
    
    if not MODEL_PATH.exists():
        print(f"❌ Erreur: Le modèle n'existe pas à {MODEL_PATH}")
        return False
    
    try:
        print(f"📱 Appareil: {DEVICE}")
        print(f"📁 Modèle: {MODEL_PATH}\n")
        
        print("Chargement...", end=" ", flush=True)
        
        # Sur CPU: toujours float32, sur GPU: float16
        dtype = torch.float32 if DEVICE == "cpu" else torch.float16
        
        pipeline = StableDiffusionPipeline.from_pretrained(
            str(MODEL_PATH),
            torch_dtype=dtype,
            safety_checker=None
        ).to(DEVICE)
        print("✅\n")
        
        print("Optimisations...", end=" ", flush=True)
        pipeline.enable_attention_slicing()
        print("✅\n")
        
        model_loaded = True
        print("="*70)
        print("✅ Modèle prêt!")
        print("="*70 + "\n")
        return True
    except Exception as e:
        print(f"❌ Erreur: {e}")
        return False

@app.route('/health', methods=['GET'])
def health():
    """Health check"""
    return jsonify({
        "status": "ok" if model_loaded else "loading",
        "device": DEVICE,
        "model_loaded": model_loaded
    })

@app.route('/generate', methods=['POST'])
def generate():
    """
    Endpoint unique pour générer une image
    POST /generate
    {
        "prompt": "electrical wiring schematic",
        "steps": 30,
        "guidance_scale": 7.5
    }
    """
    
    if not model_loaded:
        return jsonify({"error": "Model not loaded"}), 503
    
    try:
        data = request.get_json()
        
        if not data or "prompt" not in data:
            return jsonify({"error": "Missing 'prompt' in request"}), 400
        
        prompt = data.get("prompt", "")
        steps = int(data.get("steps", 30))
        guidance_scale = float(data.get("guidance_scale", 7.5))
        
        if not prompt:
            return jsonify({"error": "Prompt cannot be empty"}), 400
        
        if steps < 1 or steps > 50:
            return jsonify({"error": "Steps must be 1-50"}), 400
        
        print(f"\n🎨 Génération...")
        print(f"   Prompt: {prompt}")
        print(f"   Steps: {steps}, Guidance: {guidance_scale}")
        
        with torch.no_grad():
            image = pipeline(
                prompt,
                num_inference_steps=steps,
                guidance_scale=guidance_scale,
                height=512,
                width=512
            ).images[0]
        
        # Sauvegarder
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"generated_{timestamp}.png"
        filepath = OUTPUT_DIR / filename
        image.save(filepath)
        
        print(f"   ✅ Image générée: {filename}\n")
        
        # Retourner l'image
        img_io = io.BytesIO()
        image.save(img_io, 'PNG')
        img_io.seek(0)
        
        return send_file(img_io, mimetype='image/png')
    
    except Exception as e:
        print(f"❌ Erreur: {str(e)}\n")
        return jsonify({"error": str(e)}), 500

@app.route('/', methods=['GET'])
def home():
    """Info sur l'API"""
    return jsonify({
        "service": "LoRA Solar Panel Generator API",
        "version": "1.0",
        "device": DEVICE,
        "model_loaded": model_loaded,
        "endpoints": {
            "health": "GET /health",
            "generate": "POST /generate"
        }
    })

if __name__ == '__main__':
    if not load_model():
        exit(1)
    
    # HF Spaces écoute sur le port 7860
    port = 7860
    print(f"\n🚀 Serveur démarrage sur 0.0.0.0:{port}\n")
    app.run(host='0.0.0.0', port=port, debug=False, threaded=True)
#!/usr/bin/env python3
"""
API Flask simple pour générer des images
Utilise UNIQUEMENT le modèle fusionné
"""

import torch
from pathlib import Path
from flask import Flask, request, jsonify, send_file
from diffusers import StableDiffusionPipeline
from datetime import datetime
import io
import os

app = Flask(__name__)

# Configuration
MODEL_PATH = Path("/app/model")
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
OUTPUT_DIR = Path("/app/generated_images")
OUTPUT_DIR.mkdir(exist_ok=True, parents=True)

# Variable globale
pipeline = None
model_loaded = False

def load_model():
    """Charge le modèle au démarrage"""
    global pipeline, model_loaded
    
    print("\n" + "="*70)
    print("🤖 Chargement du modèle fusionné...")
    print("="*70 + "\n")
    
    if not MODEL_PATH.exists():
        print(f"❌ Erreur: Le modèle n'existe pas à {MODEL_PATH}")
        return False
    
    try:
        print(f"📱 Appareil: {DEVICE}")
        print(f"📁 Modèle: {MODEL_PATH}\n")
        
        print("Chargement...", end=" ", flush=True)
        pipeline = StableDiffusionPipeline.from_pretrained(
            str(MODEL_PATH),
            torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
            safety_checker=None
        ).to(DEVICE)
        print("✅\n")
        
        print("Optimisations...", end=" ", flush=True)
        pipeline.enable_attention_slicing()
        print("✅\n")
        
        model_loaded = True
        print("="*70)
        print("✅ Modèle prêt!")
        print("="*70 + "\n")
        return True
    except Exception as e:
        print(f"❌ Erreur: {e}")
        return False

@app.route('/health', methods=['GET'])
def health():
    """Health check"""
    return jsonify({
        "status": "ok" if model_loaded else "loading",
        "device": DEVICE,
        "model_loaded": model_loaded
    })

@app.route('/generate', methods=['POST'])
def generate():
    """
    Endpoint unique pour générer une image
    POST /generate
    {
        "prompt": "electrical wiring schematic",
        "steps": 30,
        "guidance_scale": 7.5
    }
    """
    
    if not model_loaded:
        return jsonify({"error": "Model not loaded"}), 503
    
    try:
        data = request.get_json()
        
        if not data or "prompt" not in data:
            return jsonify({"error": "Missing 'prompt' in request"}), 400
        
        prompt = data.get("prompt", "")
        steps = int(data.get("steps", 30))
        guidance_scale = float(data.get("guidance_scale", 7.5))
        
        if not prompt:
            return jsonify({"error": "Prompt cannot be empty"}), 400
        
        if steps < 1 or steps > 50:
            return jsonify({"error": "Steps must be 1-50"}), 400
        
        print(f"\n🎨 Génération...")
        print(f"   Prompt: {prompt}")
        print(f"   Steps: {steps}, Guidance: {guidance_scale}")
        
        with torch.no_grad():
            image = pipeline(
                prompt,
                num_inference_steps=steps,
                guidance_scale=guidance_scale,
                height=512,
                width=512
            ).images[0]
        
        # Sauvegarder
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"generated_{timestamp}.png"
        filepath = OUTPUT_DIR / filename
        image.save(filepath)
        
        print(f"   ✅ Image générée: {filename}\n")
        
        # Retourner l'image
        img_io = io.BytesIO()
        image.save(img_io, 'PNG')
        img_io.seek(0)
        
        return send_file(img_io, mimetype='image/png')
    
    except Exception as e:
        print(f"❌ Erreur: {str(e)}\n")
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    if not load_model():
        exit(1)
    
    print("\n🚀 Serveur démarrage sur 0.0.0.0:5000\n")
    app.run(host='0.0.0.0', port=5000, debug=False)