Spaces:
Running
Running
Create generation.py
Browse filesfeat: add generation.py
- generation.py +51 -0
generation.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import random
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
from huggingface_hub import InferenceClient
|
| 7 |
+
|
| 8 |
+
# Directorio donde se guardan las imágenes generadas
|
| 9 |
+
OUTPUT_DIR = "generated_images"
|
| 10 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 11 |
+
|
| 12 |
+
# Cliente de inferencia (igual que en Sofia Rivera)
|
| 13 |
+
client = InferenceClient()
|
| 14 |
+
|
| 15 |
+
def generate_image_from_prompt(
|
| 16 |
+
prompt: str,
|
| 17 |
+
negative_prompt: str = "",
|
| 18 |
+
model_name: str = "black-forest-labs/FLUX.1-dev",
|
| 19 |
+
seed: Optional[int] = None,
|
| 20 |
+
) -> tuple[Optional[str], str]:
|
| 21 |
+
"""
|
| 22 |
+
Genera una imagen usando Hugging Face InferenceClient.text_to_image
|
| 23 |
+
y la guarda en OUTPUT_DIR.
|
| 24 |
+
|
| 25 |
+
Devuelve (image_path, status_message).
|
| 26 |
+
Si hay error, image_path = None y status_message contiene el error.
|
| 27 |
+
"""
|
| 28 |
+
try:
|
| 29 |
+
if seed is None:
|
| 30 |
+
seed = random.randint(0, 2_147_483_647)
|
| 31 |
+
|
| 32 |
+
image = client.text_to_image(
|
| 33 |
+
prompt=prompt,
|
| 34 |
+
negative_prompt=negative_prompt,
|
| 35 |
+
model=model_name,
|
| 36 |
+
guidance_scale=7.5,
|
| 37 |
+
num_inference_steps=50,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 41 |
+
filename = f"sofia_{timestamp}_{seed}.png"
|
| 42 |
+
file_path = os.path.join(OUTPUT_DIR, filename)
|
| 43 |
+
|
| 44 |
+
image.save(file_path)
|
| 45 |
+
|
| 46 |
+
status = f"✅ Imagen generada y guardada: {filename}\nModelo: {model_name}\nSeed: {seed}"
|
| 47 |
+
return file_path, status
|
| 48 |
+
|
| 49 |
+
except Exception as e:
|
| 50 |
+
error_msg = f"❌ Error al generar imagen: {str(e)}"
|
| 51 |
+
return None, error_msg
|