Spaces:
Sleeping
Sleeping
Upload streamlit_app.py
Browse files- streamlit_app.py +272 -296
streamlit_app.py
CHANGED
|
@@ -1,18 +1,21 @@
|
|
| 1 |
-
# streamlit_app.py — AI LightBox · Jewelry
|
| 2 |
-
# Pre-run sabit 4 kart (Input/Packshot/Padded/Video loop) + Run sonrası native odaklı kartlar
|
| 3 |
import os, io, base64, zipfile, requests, streamlit as st
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
# ================= Env & API =================
|
| 7 |
-
API_BASE = (os.getenv("AI_LIGHTBOX_API", "http://127.0.0.1:
|
| 8 |
HF_TOKEN = (os.getenv("AI_LIGHTBOX_TOKEN", "") or "").strip().strip("'\"")
|
| 9 |
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
|
| 10 |
|
| 11 |
# UI vars
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
VIDEO_RES_OPTIONS = ["512P", "768P"]
|
| 14 |
VIDEO_DUR_OPTIONS = ["6", "10"]
|
| 15 |
-
|
| 16 |
|
| 17 |
# ================= Session =================
|
| 18 |
if "results" not in st.session_state:
|
|
@@ -22,14 +25,14 @@ if "job_counter" not in st.session_state:
|
|
| 22 |
if "video_ui_max_px" not in st.session_state:
|
| 23 |
st.session_state["video_ui_max_px"] = VIDEO_MAX_PX_DEFAULT
|
| 24 |
|
| 25 |
-
# =================
|
| 26 |
def _needs_auth(url: str) -> bool:
|
| 27 |
return url.startswith(API_BASE) or url.startswith("outputs/") or url.startswith("/outputs/")
|
| 28 |
|
| 29 |
def _abs_backend_url(url_or_path: str) -> str:
|
| 30 |
if not url_or_path:
|
| 31 |
return ""
|
| 32 |
-
if url_or_path.startswith(
|
| 33 |
return url_or_path
|
| 34 |
if url_or_path.startswith("/outputs/"):
|
| 35 |
return f"{API_BASE}{url_or_path}"
|
|
@@ -65,8 +68,12 @@ def post_video(image_url: str, duration="6", resolution="768P", prompt_optimizer
|
|
| 65 |
|
| 66 |
@st.cache_data(ttl=300, show_spinner=False)
|
| 67 |
def fetch_bytes(url_or_path: str):
|
| 68 |
-
if not url_or_path:
|
|
|
|
| 69 |
try:
|
|
|
|
|
|
|
|
|
|
| 70 |
url = _abs_backend_url(url_or_path)
|
| 71 |
headers = HEADERS if _needs_auth(url) else None
|
| 72 |
r = requests.get(url, headers=headers, timeout=180)
|
|
@@ -75,23 +82,29 @@ def fetch_bytes(url_or_path: str):
|
|
| 75 |
except Exception:
|
| 76 |
return None
|
| 77 |
|
| 78 |
-
def image_bytes_to_data_url(b: bytes, mime="image/png") -> str:
|
| 79 |
-
enc = base64.b64encode(b).decode("ascii")
|
| 80 |
-
return f"data:{mime};base64,{enc}"
|
| 81 |
-
|
| 82 |
@st.cache_data(ttl=300, show_spinner=False)
|
| 83 |
def image_size_from_bytes(b: bytes):
|
| 84 |
try:
|
| 85 |
-
im = Image.open(io.BytesIO(b))
|
|
|
|
| 86 |
except Exception:
|
| 87 |
return None
|
| 88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
def infer_ext(data: bytes) -> str:
|
| 90 |
try:
|
| 91 |
im = Image.open(io.BytesIO(data))
|
| 92 |
fmt = (im.format or "JPEG").lower()
|
| 93 |
-
return "." + {"jpeg":"jpg","jpg":"jpg","png":"png","webp":"webp"}.get(fmt,"jpg")
|
| 94 |
except Exception:
|
|
|
|
| 95 |
if data[:4] == b"\x00\x00\x00\x18" or data[4:8] == b"ftyp":
|
| 96 |
return ".mp4"
|
| 97 |
return ".bin"
|
|
@@ -100,113 +113,133 @@ def make_zip(named_bytes: list[tuple[str, bytes]]) -> bytes:
|
|
| 100 |
buf = io.BytesIO()
|
| 101 |
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as z:
|
| 102 |
for fname, b in named_bytes:
|
| 103 |
-
if b:
|
| 104 |
-
|
|
|
|
|
|
|
| 105 |
|
| 106 |
-
# =================
|
| 107 |
def _parse_aspect_str(s: str):
|
| 108 |
try:
|
| 109 |
a, b = s.split(":"); return max(1, int(a)), max(1, int(b))
|
| 110 |
except Exception:
|
| 111 |
return (9, 16)
|
| 112 |
|
| 113 |
-
def
|
| 114 |
aw, ah = _parse_aspect_str(aspect)
|
| 115 |
st.markdown(f"""
|
| 116 |
<style>
|
| 117 |
-
.lb-card-title {{
|
| 118 |
-
font-weight:700; font-size:1.15rem; margin:0 0 8px 0;
|
| 119 |
-
}}
|
| 120 |
.lb-frame {{
|
| 121 |
position: relative; width: 100%;
|
| 122 |
-
aspect-ratio: {aw} / {ah};
|
| 123 |
border-radius: 12px; overflow: hidden; background: #fff;
|
| 124 |
display:flex; align-items:center; justify-content:center;
|
| 125 |
-
box-shadow: 0 0 0 1px rgba(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
}}
|
| 127 |
-
.lb-
|
| 128 |
-
width:100%; height:100%;
|
| 129 |
-
display:
|
|
|
|
| 130 |
}}
|
| 131 |
-
.lb-video {{ display:flex; justify-content:center; }}
|
| 132 |
-
.lb-video video {{ border-radius:8px; max-width: 540px; width:100%; height:auto; }}
|
| 133 |
-
/* kartlar sabit kalsın */
|
| 134 |
</style>
|
| 135 |
""", unsafe_allow_html=True)
|
| 136 |
|
| 137 |
-
|
| 138 |
-
|
|
|
|
| 139 |
col.markdown(f'<div class="lb-card-title">{title}</div>', unsafe_allow_html=True)
|
| 140 |
|
|
|
|
| 141 |
if not url and not bytes_data:
|
| 142 |
-
col.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
|
| 143 |
-
col.caption("—")
|
|
|
|
| 144 |
|
| 145 |
-
# Render (HTML <img>) + native download
|
| 146 |
if bytes_data is not None:
|
| 147 |
src = image_bytes_to_data_url(bytes_data, "image/png")
|
| 148 |
col.markdown(f'<div class="lb-frame"><img src="{src}"/></div>', unsafe_allow_html=True)
|
| 149 |
-
|
| 150 |
else:
|
| 151 |
abs_url = _abs_backend_url(url)
|
| 152 |
col.markdown(f'<div class="lb-frame"><img src="{abs_url}"/></div>', unsafe_allow_html=True)
|
| 153 |
-
|
| 154 |
|
| 155 |
-
if not
|
| 156 |
-
col.caption("—")
|
|
|
|
| 157 |
|
| 158 |
-
sz = image_size_from_bytes(
|
| 159 |
-
if sz:
|
|
|
|
| 160 |
|
| 161 |
-
ext = infer_ext(
|
| 162 |
mime = "image/jpeg" if ext.lower() in [".jpg",".jpeg"] else ("image/png" if ext.lower()==".png" else "image/webp")
|
| 163 |
-
col.download_button("İndir (tam kalite)", data=
|
| 164 |
file_name=f"{filename_stub}{ext if ext!='.bin' else '.jpg'}",
|
| 165 |
mime=mime, key=f"{key_prefix}_{filename_stub}_dl")
|
| 166 |
-
return (url or "data"),
|
| 167 |
|
| 168 |
-
def
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
if
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
else:
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
st.set_page_config(page_title="AI LightBox · Jewelry", layout="wide", page_icon="💎")
|
| 203 |
st.title("💎 AI LightBox · Jewelry")
|
| 204 |
-
st.caption("
|
| 205 |
|
| 206 |
ok = backend_ok()
|
| 207 |
|
| 208 |
-
#
|
| 209 |
-
col1, col2, col3, col4, col5, col6, col7 = st.columns([1.6, 1.6, 1.0, 1.
|
| 210 |
with col1:
|
| 211 |
file_list = st.file_uploader("Takı görseli (yükle)", type=["jpg","jpeg","png","webp"], accept_multiple_files=True, key="file_upl")
|
| 212 |
with col2:
|
|
@@ -214,285 +247,228 @@ with col2:
|
|
| 214 |
with col3:
|
| 215 |
jewel_type = st.selectbox("Tür", ["auto","earring","ring","necklace","bracelet","pendant","brooch","set","watch"], index=0, key="jewel_type")
|
| 216 |
with col4:
|
| 217 |
-
|
| 218 |
-
help="Sadece önizleme kadrajında büyüklüğü etkiler.", key="preview_ratio")
|
| 219 |
with col5:
|
| 220 |
-
|
| 221 |
with col6:
|
| 222 |
-
|
| 223 |
with col7:
|
| 224 |
-
|
| 225 |
|
| 226 |
-
colA, colB, colC, colD, colE
|
| 227 |
with colA:
|
| 228 |
st.info(f"Bağlantı: {'Online' if ok else 'Offline'}", icon="🔌")
|
| 229 |
with colB:
|
| 230 |
identity_lock = st.checkbox("Identity lock", True, key="identity_lock")
|
| 231 |
with colC:
|
| 232 |
-
|
| 233 |
with colD:
|
| 234 |
-
|
| 235 |
with colE:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
resolution = st.selectbox("Video çözünürlük", VIDEO_RES_OPTIONS, index=1, key="resolution_sel")
|
| 237 |
-
with colF:
|
| 238 |
-
run = st.button("Çalıştır", type="primary", use_container_width=True, key="run_btn")
|
| 239 |
|
| 240 |
-
#
|
| 241 |
-
|
| 242 |
-
with colT1:
|
| 243 |
-
preview_aspect = st.selectbox("Preview Kadraj Oranı", ASPECT_OPTIONS, index=0, key="preview_aspect")
|
| 244 |
-
with colT2:
|
| 245 |
-
preview_long_edge = st.number_input("Preview uzun kenar (px)", min_value=256, max_value=8192, value=1920, step=64, key="preview_long_edge")
|
| 246 |
-
with colT3:
|
| 247 |
-
fit_mode = st.selectbox("Önizleme yerleşimi", ["fit","fill"], index=0, help="Sadece önizlemeyi etkiler.", key="fit_mode")
|
| 248 |
|
| 249 |
-
#
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
| 251 |
|
| 252 |
-
# ====
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
| 255 |
|
| 256 |
-
# Input
|
| 257 |
input_bytes = None
|
| 258 |
if file_list:
|
| 259 |
-
try:
|
| 260 |
-
|
|
|
|
|
|
|
| 261 |
elif image_url:
|
| 262 |
input_bytes = fetch_bytes(image_url)
|
| 263 |
-
elif
|
| 264 |
-
input_bytes =
|
| 265 |
|
| 266 |
-
|
| 267 |
-
bytes_data=input_bytes if input_bytes else demo_files.get("input.jpg"),
|
| 268 |
-
filename_stub="input", key_prefix="pre")
|
| 269 |
|
| 270 |
-
#
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
bytes_data=pack_bytes_demo, filename_stub="packshot", key_prefix="pre")
|
| 274 |
|
| 275 |
-
#
|
| 276 |
-
|
| 277 |
-
if
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
# Video preview (loop; yerel tryon.mp4 varsa)
|
| 288 |
-
vid_demo = demo_files.get("tryon.mp4")
|
| 289 |
-
col_vid.markdown('<div class="lb-card-title">Video preview (loop)</div>', unsafe_allow_html=True)
|
| 290 |
-
if vid_demo:
|
| 291 |
-
data_url = "data:video/mp4;base64," + base64.b64encode(vid_demo).decode("ascii")
|
| 292 |
-
col_vid.markdown(
|
| 293 |
-
f"""
|
| 294 |
-
<div class="lb-frame" style="display:flex;align-items:center;justify-content:center;">
|
| 295 |
-
<video autoplay loop muted playsinline style="width:100%;height:100%;object-fit:cover;">
|
| 296 |
-
<source src="{data_url}" type="video/mp4">
|
| 297 |
-
</video>
|
| 298 |
-
</div>
|
| 299 |
-
""", unsafe_allow_html=True
|
| 300 |
-
)
|
| 301 |
-
col_vid.download_button("Videoyu indir (MP4)", data=vid_demo, file_name="tryon.mp4", mime="video/mp4", key="pre_video_dl")
|
| 302 |
else:
|
| 303 |
-
|
| 304 |
-
col_vid.caption("—")
|
| 305 |
|
| 306 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
if run:
|
| 308 |
if not ok:
|
| 309 |
st.error("Backend erişilemiyor. API_BASE / TOKEN kontrol edin.")
|
| 310 |
-
elif not (file_list or image_url
|
| 311 |
st.error("En az bir görsel girişi yapın (dosya yükle veya URL).")
|
| 312 |
else:
|
| 313 |
try:
|
| 314 |
-
img_urls = image_url or ""
|
| 315 |
-
files_payload = []
|
| 316 |
-
if file_list:
|
| 317 |
-
for f in file_list:
|
| 318 |
-
files_payload.append(("files", (f.name, f.getvalue(), f.type or "image/jpeg")))
|
| 319 |
-
|
| 320 |
data = {
|
| 321 |
-
"category":
|
| 322 |
"edit_prompt": "",
|
| 323 |
"num_images": "1",
|
| 324 |
-
"image_urls":
|
| 325 |
-
"mannequin_image_url": "",
|
| 326 |
"identity_lock": "true" if identity_lock else "false",
|
| 327 |
-
# Preview
|
| 328 |
"preview_aspect": preview_aspect,
|
| 329 |
"preview_long_edge": str(int(preview_long_edge)),
|
| 330 |
"preview_ratio": str(float(preview_ratio)),
|
| 331 |
-
"padding_ratio": str(float(preview_ratio)), # backward-compat
|
| 332 |
# SR
|
| 333 |
"upscale": "true" if upscale else "false",
|
| 334 |
-
"upscale_factor": st.session_state.get("upscale_factor","2"),
|
| 335 |
-
"upscale_stage": st.session_state.get("upscale_stage","both"),
|
| 336 |
-
# Video
|
| 337 |
"to_video": "true" if to_video else "false",
|
| 338 |
"video_prompt": "",
|
| 339 |
-
"duration": st.session_state.get("duration_sel",
|
| 340 |
-
"resolution": st.session_state.get("resolution_sel",
|
| 341 |
"prompt_optimizer": "false",
|
| 342 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
|
| 344 |
with st.spinner("Zincir çalışıyor…"):
|
| 345 |
-
out = post_chain(data, files_payload
|
| 346 |
-
|
| 347 |
-
st.session_state["job_counter"] += 1
|
| 348 |
|
| 349 |
# ---- ÇIKTILAR (NATIVE ODAKLI) ----
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
# Padded BACKEND (ara adım olarak packshot native'den UI'da üretiyoruz; download mümkün)
|
| 357 |
-
# 0.5 oranlı 9:16 görünüm — native dosyayı etkilemez
|
| 358 |
-
pad_backend_bytes = None
|
| 359 |
-
if pack_native:
|
| 360 |
-
nb = fetch_bytes(pack_native)
|
| 361 |
-
if nb:
|
| 362 |
-
try:
|
| 363 |
-
pad_backend_bytes = make_preview_frame(nb, aspect=preview_aspect,
|
| 364 |
-
long_edge=int(preview_long_edge),
|
| 365 |
-
ratio=0.50)
|
| 366 |
-
except Exception:
|
| 367 |
-
pad_backend_bytes = None
|
| 368 |
-
|
| 369 |
-
# Model NATIVE
|
| 370 |
-
placed_native = None
|
| 371 |
-
try:
|
| 372 |
-
placed_native = (out["image_step"]["result"]["images_native"] or [{}])[0].get("url")
|
| 373 |
-
except Exception: pass
|
| 374 |
-
|
| 375 |
-
# Video (zincirde üretildiyse)
|
| 376 |
-
vurl = None
|
| 377 |
-
try:
|
| 378 |
-
vurl = (out.get("video_step") or {}).get("result", {}).get("video", {}).get("url")
|
| 379 |
-
except Exception:
|
| 380 |
-
vurl = None
|
| 381 |
-
|
| 382 |
-
# UI ipucu
|
| 383 |
ui_hints = (out.get("video_step") or {}).get("ui_hints") or {}
|
| 384 |
-
if isinstance(ui_hints, dict):
|
| 385 |
-
st.session_state["video_ui_max_px"] = int(ui_hints
|
| 386 |
|
|
|
|
| 387 |
st.session_state["results"] = {
|
| 388 |
"job_id": out.get("job_id"),
|
| 389 |
"schema_version": out.get("schema_version"),
|
| 390 |
"packshot_native_url": pack_native,
|
| 391 |
-
"
|
| 392 |
"placed_native_url": placed_native,
|
| 393 |
"video_url": vurl,
|
| 394 |
"api_base": API_BASE,
|
| 395 |
"has_auth_header": bool(HEADERS),
|
| 396 |
}
|
| 397 |
|
|
|
|
|
|
|
|
|
|
| 398 |
except requests.HTTPError as e:
|
| 399 |
st.error(f"HTTP {e.response.status_code}")
|
| 400 |
except Exception as e:
|
| 401 |
st.error(f"Hata: {e}")
|
| 402 |
|
| 403 |
-
# ================
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
src_for_video,
|
| 465 |
-
duration=st.session_state.get("duration_sel", VIDEO_DUR_OPTIONS[0]),
|
| 466 |
-
resolution=st.session_state.get("resolution_sel", VIDEO_RES_OPTIONS[1]),
|
| 467 |
-
prompt_optimizer=False,
|
| 468 |
-
preview_aspect=st.session_state.get("preview_aspect","9:16"),
|
| 469 |
-
)
|
| 470 |
-
vurl2 = (v.get("result") or {}).get("video", {}).get("url")
|
| 471 |
-
ui_hints = v.get("ui_hints") or {}
|
| 472 |
-
if vurl2:
|
| 473 |
-
st.session_state["results"]["video_url"] = vurl2
|
| 474 |
-
if isinstance(ui_hints, dict):
|
| 475 |
-
st.session_state["video_ui_max_px"] = int(ui_hints.get("suggested_video_max_px", VIDEO_MAX_PX_DEFAULT))
|
| 476 |
-
st.success("Video hazır. Yukarıdaki Video kartında döngü halinde oynatılıyor.")
|
| 477 |
-
else:
|
| 478 |
-
st.info("Video URL gelmedi.")
|
| 479 |
-
|
| 480 |
-
# Native ZIP (packshot_native + model_native + video)
|
| 481 |
-
named = []
|
| 482 |
-
if p_bytes: named.append((f"packshot_native{infer_ext(p_bytes)}", p_bytes))
|
| 483 |
-
if m_bytes: named.append((f"model_native{infer_ext(m_bytes)}", m_bytes))
|
| 484 |
-
if vbytes: named.append(("video.mp4", vbytes))
|
| 485 |
-
if named:
|
| 486 |
-
zip_bytes = make_zip(named)
|
| 487 |
-
st.download_button("Hepsini ZIP indir", data=zip_bytes,
|
| 488 |
-
file_name="ai_lightbox_outputs.zip", mime="application/zip",
|
| 489 |
-
key=f"job{st.session_state['job_counter']}_zip_dl")
|
| 490 |
-
|
| 491 |
-
# ================= Sidebar =================
|
| 492 |
-
with st.sidebar:
|
| 493 |
-
st.caption(f"API_BASE: {API_BASE}")
|
| 494 |
-
if HF_TOKEN: st.caption("Auth: Bearer (aktif)")
|
| 495 |
-
st.slider("Video önizleme genişliği (px)", 360, 1080, st.session_state["video_ui_max_px"],
|
| 496 |
-
step=10, key="video_ui_max_px")
|
| 497 |
-
if st.button("Önbelleği temizle"): st.cache_data.clear(); st.success("Önbellek temizlendi.")
|
| 498 |
-
if st.button("Son çıktıları temizle"): st.session_state["results"] = None; st.success("Çıktılar temizlendi.")
|
|
|
|
| 1 |
+
# streamlit_app.py — AI LightBox · Jewelry (uniform cards + native backend outputs + loop video)
|
|
|
|
| 2 |
import os, io, base64, zipfile, requests, streamlit as st
|
| 3 |
from PIL import Image
|
| 4 |
|
| 5 |
# ================= Env & API =================
|
| 6 |
+
API_BASE = (os.getenv("AI_LIGHTBOX_API", "http://127.0.0.1:7860") or "http://127.0.0.1:7860").strip().strip("'\"").rstrip("/")
|
| 7 |
HF_TOKEN = (os.getenv("AI_LIGHTBOX_TOKEN", "") or "").strip().strip("'\"")
|
| 8 |
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
|
| 9 |
|
| 10 |
# UI vars
|
| 11 |
+
ASPECT_OPTIONS = ["9:16", "3:4", "1:1"]
|
| 12 |
+
DEFAULT_ASPECT = os.getenv("PREVIEW_ASPECT", "9:16")
|
| 13 |
+
DEFAULT_LONG = int(os.getenv("PREVIEW_LONG_EDGE", "1920"))
|
| 14 |
+
DEFAULT_RATIO = float(os.getenv("PREVIEW_RATIO", "0.50"))
|
| 15 |
+
|
| 16 |
VIDEO_RES_OPTIONS = ["512P", "768P"]
|
| 17 |
VIDEO_DUR_OPTIONS = ["6", "10"]
|
| 18 |
+
VIDEO_MAX_PX_DEFAULT = int(os.getenv("VIDEO_MAX_PX", "720"))
|
| 19 |
|
| 20 |
# ================= Session =================
|
| 21 |
if "results" not in st.session_state:
|
|
|
|
| 25 |
if "video_ui_max_px" not in st.session_state:
|
| 26 |
st.session_state["video_ui_max_px"] = VIDEO_MAX_PX_DEFAULT
|
| 27 |
|
| 28 |
+
# ================= Backend helpers =================
|
| 29 |
def _needs_auth(url: str) -> bool:
|
| 30 |
return url.startswith(API_BASE) or url.startswith("outputs/") or url.startswith("/outputs/")
|
| 31 |
|
| 32 |
def _abs_backend_url(url_or_path: str) -> str:
|
| 33 |
if not url_or_path:
|
| 34 |
return ""
|
| 35 |
+
if url_or_path.startswith("http://") or url_or_path.startswith("https://"):
|
| 36 |
return url_or_path
|
| 37 |
if url_or_path.startswith("/outputs/"):
|
| 38 |
return f"{API_BASE}{url_or_path}"
|
|
|
|
| 68 |
|
| 69 |
@st.cache_data(ttl=300, show_spinner=False)
|
| 70 |
def fetch_bytes(url_or_path: str):
|
| 71 |
+
if not url_or_path:
|
| 72 |
+
return None
|
| 73 |
try:
|
| 74 |
+
if os.path.exists(url_or_path): # local file support
|
| 75 |
+
with open(url_or_path, "rb") as f:
|
| 76 |
+
return f.read()
|
| 77 |
url = _abs_backend_url(url_or_path)
|
| 78 |
headers = HEADERS if _needs_auth(url) else None
|
| 79 |
r = requests.get(url, headers=headers, timeout=180)
|
|
|
|
| 82 |
except Exception:
|
| 83 |
return None
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
@st.cache_data(ttl=300, show_spinner=False)
|
| 86 |
def image_size_from_bytes(b: bytes):
|
| 87 |
try:
|
| 88 |
+
im = Image.open(io.BytesIO(b))
|
| 89 |
+
return im.size
|
| 90 |
except Exception:
|
| 91 |
return None
|
| 92 |
|
| 93 |
+
def image_bytes_to_data_url(b: bytes, mime="image/png") -> str:
|
| 94 |
+
enc = base64.b64encode(b).decode("ascii")
|
| 95 |
+
return f"data:{mime};base64,{enc}"
|
| 96 |
+
|
| 97 |
+
def video_bytes_to_data_url(b: bytes) -> str:
|
| 98 |
+
enc = base64.b64encode(b).decode("ascii")
|
| 99 |
+
return f"data:video/mp4;base64,{enc}"
|
| 100 |
+
|
| 101 |
def infer_ext(data: bytes) -> str:
|
| 102 |
try:
|
| 103 |
im = Image.open(io.BytesIO(data))
|
| 104 |
fmt = (im.format or "JPEG").lower()
|
| 105 |
+
return "." + {"jpeg":"jpg","jpg":"jpg","png":"png","webp":"webp"}.get(fmt, "jpg")
|
| 106 |
except Exception:
|
| 107 |
+
# mp4 sihirli sayfa kontrolü
|
| 108 |
if data[:4] == b"\x00\x00\x00\x18" or data[4:8] == b"ftyp":
|
| 109 |
return ".mp4"
|
| 110 |
return ".bin"
|
|
|
|
| 113 |
buf = io.BytesIO()
|
| 114 |
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as z:
|
| 115 |
for fname, b in named_bytes:
|
| 116 |
+
if b:
|
| 117 |
+
z.writestr(fname, b)
|
| 118 |
+
buf.seek(0)
|
| 119 |
+
return buf.read()
|
| 120 |
|
| 121 |
+
# ================= Uniform Card CSS =================
|
| 122 |
def _parse_aspect_str(s: str):
|
| 123 |
try:
|
| 124 |
a, b = s.split(":"); return max(1, int(a)), max(1, int(b))
|
| 125 |
except Exception:
|
| 126 |
return (9, 16)
|
| 127 |
|
| 128 |
+
def inject_card_css(aspect: str):
|
| 129 |
aw, ah = _parse_aspect_str(aspect)
|
| 130 |
st.markdown(f"""
|
| 131 |
<style>
|
| 132 |
+
.lb-card-title {{ font-weight:700; font-size:1.10rem; margin:0 0 8px 0; }}
|
|
|
|
|
|
|
| 133 |
.lb-frame {{
|
| 134 |
position: relative; width: 100%;
|
| 135 |
+
aspect-ratio: {aw} / {ah}; /* tüm kartlar aynı oran */
|
| 136 |
border-radius: 12px; overflow: hidden; background: #fff;
|
| 137 |
display:flex; align-items:center; justify-content:center;
|
| 138 |
+
box-shadow: 0 0 0 1px rgba(0,0,0,0.06) inset;
|
| 139 |
+
}}
|
| 140 |
+
.lb-frame img, .lb-frame video {{
|
| 141 |
+
width:100%; height:100%; object-fit: contain; /* FIT */
|
| 142 |
+
display:block; background:#fff;
|
| 143 |
}}
|
| 144 |
+
.lb-placeholder {{
|
| 145 |
+
width:100%; height:100%;
|
| 146 |
+
display:flex; align-items:center; justify-content:center;
|
| 147 |
+
color:#9aa0a6; font-size:0.9rem;
|
| 148 |
}}
|
|
|
|
|
|
|
|
|
|
| 149 |
</style>
|
| 150 |
""", unsafe_allow_html=True)
|
| 151 |
|
| 152 |
+
# ================= Card render helpers =================
|
| 153 |
+
def show_image_card(col, title, url: str | None = None, bytes_data: bytes | None = None,
|
| 154 |
+
filename_stub="image", key_prefix=""):
|
| 155 |
col.markdown(f'<div class="lb-card-title">{title}</div>', unsafe_allow_html=True)
|
| 156 |
|
| 157 |
+
native_bytes = None
|
| 158 |
if not url and not bytes_data:
|
| 159 |
+
col.markdown('<div class="lb-frame"><div class="lb-placeholder">Beklemede</div></div>', unsafe_allow_html=True)
|
| 160 |
+
col.caption("—")
|
| 161 |
+
return None, None
|
| 162 |
|
|
|
|
| 163 |
if bytes_data is not None:
|
| 164 |
src = image_bytes_to_data_url(bytes_data, "image/png")
|
| 165 |
col.markdown(f'<div class="lb-frame"><img src="{src}"/></div>', unsafe_allow_html=True)
|
| 166 |
+
native_bytes = bytes_data
|
| 167 |
else:
|
| 168 |
abs_url = _abs_backend_url(url)
|
| 169 |
col.markdown(f'<div class="lb-frame"><img src="{abs_url}"/></div>', unsafe_allow_html=True)
|
| 170 |
+
native_bytes = fetch_bytes(abs_url)
|
| 171 |
|
| 172 |
+
if not native_bytes:
|
| 173 |
+
col.caption("—")
|
| 174 |
+
return (url or "data"), None
|
| 175 |
|
| 176 |
+
sz = image_size_from_bytes(native_bytes)
|
| 177 |
+
if sz:
|
| 178 |
+
col.caption(f"Gerçek çözünürlük: {sz[0]}×{sz[1]} px")
|
| 179 |
|
| 180 |
+
ext = infer_ext(native_bytes)
|
| 181 |
mime = "image/jpeg" if ext.lower() in [".jpg",".jpeg"] else ("image/png" if ext.lower()==".png" else "image/webp")
|
| 182 |
+
col.download_button("İndir (tam kalite)", data=native_bytes,
|
| 183 |
file_name=f"{filename_stub}{ext if ext!='.bin' else '.jpg'}",
|
| 184 |
mime=mime, key=f"{key_prefix}_{filename_stub}_dl")
|
| 185 |
+
return (url or "data"), native_bytes
|
| 186 |
|
| 187 |
+
def show_video_card(col, title, url: str | None = None, bytes_data: bytes | None = None,
|
| 188 |
+
key_prefix=""):
|
| 189 |
+
col.markdown(f'<div class="lb-card-title">{title}</div>', unsafe_allow_html=True)
|
| 190 |
+
|
| 191 |
+
native_bytes = None
|
| 192 |
+
if not url and not bytes_data:
|
| 193 |
+
col.markdown('<div class="lb-frame"><div class="lb-placeholder">Beklemede</div></div>', unsafe_allow_html=True)
|
| 194 |
+
col.caption("—")
|
| 195 |
+
return None, None
|
| 196 |
+
|
| 197 |
+
if bytes_data is not None:
|
| 198 |
+
src = video_bytes_to_data_url(bytes_data)
|
| 199 |
+
col.markdown(
|
| 200 |
+
f'''
|
| 201 |
+
<div class="lb-frame">
|
| 202 |
+
<video loop autoplay muted playsinline controls>
|
| 203 |
+
<source src="{src}" type="video/mp4">
|
| 204 |
+
</video>
|
| 205 |
+
</div>
|
| 206 |
+
''',
|
| 207 |
+
unsafe_allow_html=True
|
| 208 |
+
)
|
| 209 |
+
native_bytes = bytes_data
|
| 210 |
else:
|
| 211 |
+
abs_url = _abs_backend_url(url)
|
| 212 |
+
col.markdown(
|
| 213 |
+
f'''
|
| 214 |
+
<div class="lb-frame">
|
| 215 |
+
<video loop autoplay muted playsinline controls>
|
| 216 |
+
<source src="{abs_url}" type="video/mp4">
|
| 217 |
+
</video>
|
| 218 |
+
</div>
|
| 219 |
+
''',
|
| 220 |
+
unsafe_allow_html=True
|
| 221 |
+
)
|
| 222 |
+
native_bytes = fetch_bytes(abs_url)
|
| 223 |
+
|
| 224 |
+
if not native_bytes:
|
| 225 |
+
col.caption("—")
|
| 226 |
+
return (url or "data"), None
|
| 227 |
+
|
| 228 |
+
col.caption("MP4 • loop")
|
| 229 |
+
col.download_button("Videoyu indir (MP4)", data=native_bytes,
|
| 230 |
+
file_name="video.mp4", mime="video/mp4",
|
| 231 |
+
key=f"{key_prefix}_video_dl")
|
| 232 |
+
return (url or "data"), native_bytes
|
| 233 |
+
|
| 234 |
+
# ================= Page =================
|
| 235 |
st.set_page_config(page_title="AI LightBox · Jewelry", layout="wide", page_icon="💎")
|
| 236 |
st.title("💎 AI LightBox · Jewelry")
|
| 237 |
+
st.caption("Akış: Input → Packshot (backend, BG temiz) → Padded (backend, oran/ölçek) → Model üzerinde (backend) → (opsiyonel) Video")
|
| 238 |
|
| 239 |
ok = backend_ok()
|
| 240 |
|
| 241 |
+
# Üst kontrol şeridi
|
| 242 |
+
col1, col2, col3, col4, col5, col6, col7 = st.columns([1.6, 1.6, 1.0, 1.1, 1.0, 1.0, 1.1])
|
| 243 |
with col1:
|
| 244 |
file_list = st.file_uploader("Takı görseli (yükle)", type=["jpg","jpeg","png","webp"], accept_multiple_files=True, key="file_upl")
|
| 245 |
with col2:
|
|
|
|
| 247 |
with col3:
|
| 248 |
jewel_type = st.selectbox("Tür", ["auto","earring","ring","necklace","bracelet","pendant","brooch","set","watch"], index=0, key="jewel_type")
|
| 249 |
with col4:
|
| 250 |
+
preview_aspect = st.selectbox("Kadraj Oranı", ASPECT_OPTIONS, index=ASPECT_OPTIONS.index(DEFAULT_ASPECT) if DEFAULT_ASPECT in ASPECT_OPTIONS else 0, key="canvas_aspect")
|
|
|
|
| 251 |
with col5:
|
| 252 |
+
preview_long_edge = st.number_input("Uzun Kenar (px)", min_value=256, max_value=8192, value=DEFAULT_LONG, step=64, key="canvas_size")
|
| 253 |
with col6:
|
| 254 |
+
preview_ratio = st.number_input("Preview ölçeği (0.10–0.99)", min_value=0.10, max_value=0.99, value=DEFAULT_RATIO, step=0.01, key="preview_ratio")
|
| 255 |
with col7:
|
| 256 |
+
run = st.button("Çalıştır", type="primary", use_container_width=True, key="run_btn")
|
| 257 |
|
| 258 |
+
colA, colB, colC, colD, colE = st.columns([1.0, 1.0, 1.1, 0.9, 1.0])
|
| 259 |
with colA:
|
| 260 |
st.info(f"Bağlantı: {'Online' if ok else 'Offline'}", icon="🔌")
|
| 261 |
with colB:
|
| 262 |
identity_lock = st.checkbox("Identity lock", True, key="identity_lock")
|
| 263 |
with colC:
|
| 264 |
+
upscale = st.checkbox("Super Resolution", False, key="upscale")
|
| 265 |
with colD:
|
| 266 |
+
upscale_stage = st.selectbox("SR aşaması", ["both","final","packshot"], index=0, help="Varsayılan: both", key="upscale_stage")
|
| 267 |
with colE:
|
| 268 |
+
upscale_factor = st.selectbox("SR katsayı", ["2","4"], index=0, key="upscale_factor")
|
| 269 |
+
|
| 270 |
+
colV1, colV2, colV3 = st.columns([1.0, 1.0, 1.0])
|
| 271 |
+
with colV1:
|
| 272 |
+
to_video = st.checkbox("Video üret (opsiyonel)", False, key="to_video")
|
| 273 |
+
with colV2:
|
| 274 |
+
duration = st.selectbox("Süre (sn)", VIDEO_DUR_OPTIONS, index=0, key="duration_sel")
|
| 275 |
+
with colV3:
|
| 276 |
resolution = st.selectbox("Video çözünürlük", VIDEO_RES_OPTIONS, index=1, key="resolution_sel")
|
|
|
|
|
|
|
| 277 |
|
| 278 |
+
# Kart CSS (tüm kartlar aynı oran)
|
| 279 |
+
inject_card_css(preview_aspect)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
+
# ============== Kart Alanları (her zaman sabit) ==============
|
| 282 |
+
# Satır 1: Input, Packshot (backend), Padded (backend), Model üzerinde (backend)
|
| 283 |
+
c_in, c_pack, c_pad, c_model = st.columns(4)
|
| 284 |
+
# Satır 2: Video (loop)
|
| 285 |
+
c_video = st.container()
|
| 286 |
|
| 287 |
+
# ==== Pre-run örnek doldurma (mevcut klasörde dosyalar varsa) ====
|
| 288 |
+
input_sample = fetch_bytes("input.jpg") if os.path.exists("input.jpg") else None
|
| 289 |
+
packshot_sample = fetch_bytes("packshot.jpg") if os.path.exists("packshot.jpg") else None
|
| 290 |
+
padded_sample = fetch_bytes("padded.jpg") if os.path.exists("padded.jpg") else None
|
| 291 |
+
model_sample = fetch_bytes("model.jpg") if os.path.exists("model.jpg") else None
|
| 292 |
+
video_sample = fetch_bytes("tryon.mp4") if os.path.exists("tryon.mp4") else None
|
| 293 |
|
| 294 |
+
# ==== Input kartı: upload/URL seçildiğinde anında dolmalı; yoksa sample; yoksa boş ====
|
| 295 |
input_bytes = None
|
| 296 |
if file_list:
|
| 297 |
+
try:
|
| 298 |
+
input_bytes = file_list[0].getvalue()
|
| 299 |
+
except Exception:
|
| 300 |
+
input_bytes = None
|
| 301 |
elif image_url:
|
| 302 |
input_bytes = fetch_bytes(image_url)
|
| 303 |
+
elif input_sample:
|
| 304 |
+
input_bytes = input_sample
|
| 305 |
|
| 306 |
+
show_image_card(c_in, "Input", bytes_data=input_bytes, filename_stub="input", key_prefix="in")
|
|
|
|
|
|
|
| 307 |
|
| 308 |
+
# ==== Diğer kartlar: run sonrası backend'ten; run yapılmadan varsa sample göster ====
|
| 309 |
+
# Placeholderları sabit tutmak için her zaman bir kart çiziyoruz.
|
| 310 |
+
res = st.session_state.get("results") or {}
|
|
|
|
| 311 |
|
| 312 |
+
# Packshot (backend)
|
| 313 |
+
pack_url = res.get("packshot_native_url")
|
| 314 |
+
if not pack_url and packshot_sample is not None:
|
| 315 |
+
_, _ = show_image_card(c_pack, "Packshot (backend)", bytes_data=packshot_sample, filename_stub="packshot_native", key_prefix="pk")
|
| 316 |
+
else:
|
| 317 |
+
_, _ = show_image_card(c_pack, "Packshot (backend)", url=pack_url, filename_stub="packshot_native", key_prefix="pk")
|
| 318 |
+
|
| 319 |
+
# Padded (backend)
|
| 320 |
+
pad_url = res.get("padded_native_url")
|
| 321 |
+
if not pad_url and padded_sample is not None:
|
| 322 |
+
_, _ = show_image_card(c_pad, "Padded (backend)", bytes_data=padded_sample, filename_stub="padded_native", key_prefix="pd")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
else:
|
| 324 |
+
_, _ = show_image_card(c_pad, "Padded (backend)", url=pad_url, filename_stub="padded_native", key_prefix="pd")
|
|
|
|
| 325 |
|
| 326 |
+
# Model üzerinde (backend)
|
| 327 |
+
model_url = res.get("placed_native_url")
|
| 328 |
+
if not model_url and model_sample is not None:
|
| 329 |
+
_, _ = show_image_card(c_model, "Model üzerinde (backend)", bytes_data=model_sample, filename_stub="model_native", key_prefix="md")
|
| 330 |
+
else:
|
| 331 |
+
_, _ = show_image_card(c_model, "Model üzerinde (backend)", url=model_url, filename_stub="model_native", key_prefix="md")
|
| 332 |
+
|
| 333 |
+
# Video (loop) — ayrı sabit kart, her zaman aynı oranda
|
| 334 |
+
with c_video:
|
| 335 |
+
st.markdown(f"### Video (loop)")
|
| 336 |
+
# Kartı aynı CSS ile sar
|
| 337 |
+
if res.get("video_url"):
|
| 338 |
+
show_video_card(st, "", url=res.get("video_url"), key_prefix=f"job{st.session_state['job_counter']}")
|
| 339 |
+
elif video_sample is not None:
|
| 340 |
+
show_video_card(st, "", bytes_data=video_sample, key_prefix="sample_video")
|
| 341 |
+
else:
|
| 342 |
+
st.markdown('<div class="lb-frame"><div class="lb-placeholder">Beklemede</div></div>', unsafe_allow_html=True)
|
| 343 |
+
st.caption("—")
|
| 344 |
+
|
| 345 |
+
# ================ Çalıştır ================
|
| 346 |
if run:
|
| 347 |
if not ok:
|
| 348 |
st.error("Backend erişilemiyor. API_BASE / TOKEN kontrol edin.")
|
| 349 |
+
elif not (file_list or image_url):
|
| 350 |
st.error("En az bir görsel girişi yapın (dosya yükle veya URL).")
|
| 351 |
else:
|
| 352 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
data = {
|
| 354 |
+
"category": jewel_type,
|
| 355 |
"edit_prompt": "",
|
| 356 |
"num_images": "1",
|
| 357 |
+
"image_urls": (image_url or ""),
|
| 358 |
+
"mannequin_image_url": "",
|
| 359 |
"identity_lock": "true" if identity_lock else "false",
|
| 360 |
+
# PAD/Preview kontrolleri (backend native PAD için)
|
| 361 |
"preview_aspect": preview_aspect,
|
| 362 |
"preview_long_edge": str(int(preview_long_edge)),
|
| 363 |
"preview_ratio": str(float(preview_ratio)),
|
|
|
|
| 364 |
# SR
|
| 365 |
"upscale": "true" if upscale else "false",
|
| 366 |
+
"upscale_factor": st.session_state.get("upscale_factor", "2"),
|
| 367 |
+
"upscale_stage": st.session_state.get("upscale_stage", "both"),
|
| 368 |
+
# Video zincirde opsiyonel
|
| 369 |
"to_video": "true" if to_video else "false",
|
| 370 |
"video_prompt": "",
|
| 371 |
+
"duration": st.session_state.get("duration_sel", "6"),
|
| 372 |
+
"resolution": st.session_state.get("resolution_sel", "768P"),
|
| 373 |
"prompt_optimizer": "false",
|
| 374 |
}
|
| 375 |
+
files_payload = []
|
| 376 |
+
if file_list:
|
| 377 |
+
for f in file_list:
|
| 378 |
+
files_payload.append(("files", (f.name, f.getvalue(), f.type or "image/jpeg")))
|
| 379 |
|
| 380 |
with st.spinner("Zincir çalışıyor…"):
|
| 381 |
+
out = post_chain(data, files_payload)
|
|
|
|
|
|
|
| 382 |
|
| 383 |
# ---- ÇIKTILAR (NATIVE ODAKLI) ----
|
| 384 |
+
pack_native = (out["packshot_step"]["result"]["images_native"] or [{}])[0].get("url")
|
| 385 |
+
padded_native = (out["packshot_step"]["result"]["padded_native"] or [{}])[0].get("url")
|
| 386 |
+
placed_native = (out["image_step"]["result"]["images_native"] or [{}])[0].get("url") if out.get("image_step") else None
|
| 387 |
+
vurl = (out.get("video_step") or {}).get("result", {}).get("video", {}).get("url")
|
| 388 |
+
|
| 389 |
+
# UI video ipuçları
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
ui_hints = (out.get("video_step") or {}).get("ui_hints") or {}
|
| 391 |
+
if isinstance(ui_hints, dict) and ui_hints.get("suggested_video_max_px"):
|
| 392 |
+
st.session_state["video_ui_max_px"] = int(ui_hints["suggested_video_max_px"])
|
| 393 |
|
| 394 |
+
st.session_state["job_counter"] += 1
|
| 395 |
st.session_state["results"] = {
|
| 396 |
"job_id": out.get("job_id"),
|
| 397 |
"schema_version": out.get("schema_version"),
|
| 398 |
"packshot_native_url": pack_native,
|
| 399 |
+
"padded_native_url": padded_native,
|
| 400 |
"placed_native_url": placed_native,
|
| 401 |
"video_url": vurl,
|
| 402 |
"api_base": API_BASE,
|
| 403 |
"has_auth_header": bool(HEADERS),
|
| 404 |
}
|
| 405 |
|
| 406 |
+
# Sayfayı yeniden çiz (kartlar otomatik güncellenecek)
|
| 407 |
+
st.experimental_rerun()
|
| 408 |
+
|
| 409 |
except requests.HTTPError as e:
|
| 410 |
st.error(f"HTTP {e.response.status_code}")
|
| 411 |
except Exception as e:
|
| 412 |
st.error(f"Hata: {e}")
|
| 413 |
|
| 414 |
+
# ================ Opsiyonel: Sonradan video üret ================
|
| 415 |
+
st.markdown("---")
|
| 416 |
+
st.subheader("Bu sonuçtan video üret (opsiyonel)")
|
| 417 |
+
res2 = st.session_state.get("results") or {}
|
| 418 |
+
final_src_for_video = res2.get("placed_native_url") or res2.get("padded_native_url") or res2.get("packshot_native_url")
|
| 419 |
+
|
| 420 |
+
colvv1, colvv2, colvv3, colvv4 = st.columns([1.0, 1.0, 1.0, 1.0])
|
| 421 |
+
with colvv1:
|
| 422 |
+
post_video_toggle = st.checkbox("Videoya çevir", value=False, key="video_toggle_manual")
|
| 423 |
+
with colvv2:
|
| 424 |
+
duration2 = st.selectbox("Süre (sn)", VIDEO_DUR_OPTIONS, index=0, key="duration_sel2")
|
| 425 |
+
with colvv3:
|
| 426 |
+
resolution2 = st.selectbox("Çözünürlük", VIDEO_RES_OPTIONS, index=1, key="resolution_sel2")
|
| 427 |
+
with colvv4:
|
| 428 |
+
make_video_btn = st.button("Üret", disabled=not post_video_toggle or not final_src_for_video)
|
| 429 |
+
|
| 430 |
+
if make_video_btn:
|
| 431 |
+
try:
|
| 432 |
+
with st.spinner("Video üretiliyor…"):
|
| 433 |
+
v = post_video(final_src_for_video, duration=duration2, resolution=resolution2, prompt_optimizer=False, preview_aspect=preview_aspect)
|
| 434 |
+
vurl2 = (v.get("result") or {}).get("video", {}).get("url")
|
| 435 |
+
if vurl2:
|
| 436 |
+
st.session_state["results"]["video_url"] = vurl2
|
| 437 |
+
st.success("Video hazır.")
|
| 438 |
+
st.experimental_rerun()
|
| 439 |
+
else:
|
| 440 |
+
st.info("Video URL gelmedi.")
|
| 441 |
+
except requests.HTTPError as e:
|
| 442 |
+
st.error(f"HTTP {e.response.status_code}")
|
| 443 |
+
except Exception as e:
|
| 444 |
+
st.error(f"Hata: {e}")
|
| 445 |
+
|
| 446 |
+
# ================ Hepsini ZIP ================
|
| 447 |
+
res3 = st.session_state.get("results") or {}
|
| 448 |
+
named = []
|
| 449 |
+
pb = fetch_bytes(res3.get("packshot_native_url")) if res3.get("packshot_native_url") else None
|
| 450 |
+
if pb: named.append((f"packshot{infer_ext(pb)}", pb))
|
| 451 |
+
pdb = fetch_bytes(res3.get("padded_native_url")) if res3.get("padded_native_url") else None
|
| 452 |
+
if pdb: named.append((f"padded{infer_ext(pdb)}", pdb))
|
| 453 |
+
mb = fetch_bytes(res3.get("placed_native_url")) if res3.get("placed_native_url") else None
|
| 454 |
+
if mb: named.append((f"model{infer_ext(mb)}", mb))
|
| 455 |
+
vb = fetch_bytes(res3.get("video_url")) if res3.get("video_url") else None
|
| 456 |
+
if vb: named.append(("video.mp4", vb))
|
| 457 |
+
if named:
|
| 458 |
+
zip_bytes = make_zip(named)
|
| 459 |
+
st.download_button("Hepsini ZIP indir", data=zip_bytes,
|
| 460 |
+
file_name="ai_lightbox_outputs.zip", mime="application/zip",
|
| 461 |
+
key=f"zip_{st.session_state['job_counter']}")
|
| 462 |
+
|
| 463 |
+
# ================ Debug ================
|
| 464 |
+
with st.expander("Debug / Kaynak Alanlar"):
|
| 465 |
+
st.json({
|
| 466 |
+
"job_id": res3.get("job_id"),
|
| 467 |
+
"schema_version": res3.get("schema_version"),
|
| 468 |
+
"api_base": res3.get("api_base"),
|
| 469 |
+
"has_auth_header": res3.get("has_auth_header"),
|
| 470 |
+
"packshot_native_url": res3.get("packshot_native_url"),
|
| 471 |
+
"padded_native_url": res3.get("padded_native_url"),
|
| 472 |
+
"placed_native_url": res3.get("placed_native_url"),
|
| 473 |
+
"video_url": res3.get("video_url"),
|
| 474 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|