-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
136 lines (108 loc) · 4.24 KB
/
app.py
File metadata and controls
136 lines (108 loc) · 4.24 KB
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
prompt = "A peaceful mountain landscape at sunset, digital painting, high detail."
import streamlit as st
from io import BytesIO
import math
import os
from PIL import Image
import requests
import time
import dotenv
dotenv.load_dotenv()
STABILITY_KEY = os.getenv("STABILITY_KEY")
def send_generation_request(host, params):
"""Send a REST request to the Stability API and return the Response object.
Opens any files referenced in params and ensures they are closed after the request.
"""
headers = {
"Accept": "image/*",
"Authorization": f"Bearer {STABILITY_KEY}"
}
# Encode parameters
files = {}
opened_files = []
image = params.pop("image", None)
mask = params.pop("mask", None)
if image is not None and image != '':
f = open(image, 'rb')
files["image"] = f
opened_files.append(f)
if mask is not None and mask != '':
f = open(mask, 'rb')
files["mask"] = f
opened_files.append(f)
if len(files) == 0:
# keep the same form as original script
files["none"] = ''
# Send request
response = requests.post(
host,
headers=headers,
files=files,
data=params
)
# close opened files
for f in opened_files:
try:
f.close()
except Exception:
pass
if not response.ok:
raise Exception(f"HTTP {response.status_code}: {response.text}")
return response
DEFAULT_PROMPT = (
"A peaceful mountain landscape at sunset, digital painting, high detail."
)
def main():
st.set_page_config(page_title="Generador de imágenes - SD3", layout="centered")
st.title("Generador de imágenes (SD3)")
st.write("Introduce un prompt y genera una imagen usando la API de Stability.")
# Requirements / key check
env_exists = os.path.exists(".env")
if not env_exists or not STABILITY_KEY:
st.error(
"No se ha encontrado la variable de entorno `STABILITY_KEY`.\n\n"
"Por favor, añade un archivo `.env` en la raíz del proyecto o exporta la variable de entorno."
)
st.markdown("[Abrir README (instrucciones)](README.md)")
return
# UI inputs (Spanish)
prompt = st.text_area("Prompt", value=DEFAULT_PROMPT, height=120)
col1, col2 = st.columns(2)
with col1:
aspect_ratio = st.selectbox("Relación de aspecto", options=["1:1", "16:9", "9:16"], index=0)
with col2:
output_format = st.selectbox("Formato de salida", options=["jpeg", "png"], index=0)
seed_input = st.text_input("Semilla (opcional)", value="")
generate_btn = st.button("Generar imagen")
if generate_btn:
seed = int(seed_input) if seed_input.isdigit() else math.floor(time.time())
host = "https://api.stability.ai/v2beta/stable-image/generate/sd3"
params = {
"prompt": prompt,
"aspect_ratio": aspect_ratio,
"seed": seed,
"output_format": output_format,
"model": "sd3-turbo"
}
with st.spinner("Generando imagen, espera por favor..."):
try:
response = send_generation_request(host, params)
output_image = response.content
finish_reason = response.headers.get("finish-reason")
seed_returned = response.headers.get("seed") or seed
if finish_reason == 'CONTENT_FILTERED':
st.warning("La generación fue filtrada por el clasificador NSFW.")
# Display image
try:
img = Image.open(BytesIO(output_image))
st.image(img, caption=f"Imagen generada — seed: {seed_returned}")
except Exception:
# If PIL cannot open, still provide raw bytes preview
st.write("No se pudo abrir la imagen con PIL, mostrando como bytes.")
st.code(output_image[:100])
filename = f"generated_{seed_returned}.{output_format}"
st.download_button("Descargar imagen", data=output_image, file_name=filename, mime=f"image/{output_format}")
except Exception as e:
st.error(f"Error al generar la imagen: {e}")
if __name__ == "__main__":
main()