Spaces:
Running
Running
Upload streamlit_app.py
Browse files- streamlit_app.py +296 -272
streamlit_app.py
CHANGED
|
@@ -1,21 +1,18 @@
|
|
| 1 |
-
# streamlit_app.py — AI LightBox · Jewelry
|
|
|
|
| 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:
|
| 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 |
-
|
| 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 |
-
|
| 19 |
|
| 20 |
# ================= Session =================
|
| 21 |
if "results" not in st.session_state:
|
|
@@ -25,14 +22,14 @@ if "job_counter" 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://"
|
| 36 |
return url_or_path
|
| 37 |
if url_or_path.startswith("/outputs/"):
|
| 38 |
return f"{API_BASE}{url_or_path}"
|
|
@@ -68,12 +65,8 @@ def post_video(image_url: str, duration="6", resolution="768P", prompt_optimizer
|
|
| 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,29 +75,23 @@ def fetch_bytes(url_or_path: str):
|
|
| 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,
|
| 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,133 +100,112 @@ def make_zip(named_bytes: list[tuple[str, bytes]]) -> bytes:
|
|
| 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 |
-
|
| 118 |
-
buf.seek(0)
|
| 119 |
-
return buf.read()
|
| 120 |
|
| 121 |
-
# =================
|
| 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
|
| 129 |
aw, ah = _parse_aspect_str(aspect)
|
| 130 |
st.markdown(f"""
|
| 131 |
<style>
|
| 132 |
-
.lb-card-title {{
|
|
|
|
|
|
|
| 133 |
.lb-frame {{
|
| 134 |
position: relative; width: 100%;
|
| 135 |
-
aspect-ratio: {aw} / {ah};
|
| 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(
|
| 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-
|
| 145 |
-
width:100%; height:100%;
|
| 146 |
-
display:
|
| 147 |
-
color:#9aa0a6; font-size:0.9rem;
|
| 148 |
}}
|
|
|
|
|
|
|
| 149 |
</style>
|
| 150 |
""", unsafe_allow_html=True)
|
| 151 |
|
| 152 |
-
|
| 153 |
-
|
| 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"><
|
| 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 |
-
|
| 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 |
-
|
| 171 |
|
| 172 |
-
if not
|
| 173 |
-
col.caption("—")
|
| 174 |
-
return (url or "data"), None
|
| 175 |
|
| 176 |
-
sz = image_size_from_bytes(
|
| 177 |
-
if sz:
|
| 178 |
-
col.caption(f"Gerçek çözünürlük: {sz[0]}×{sz[1]} px")
|
| 179 |
|
| 180 |
-
ext = infer_ext(
|
| 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=
|
| 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"),
|
| 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 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
</video>
|
| 205 |
-
</div>
|
| 206 |
-
''',
|
| 207 |
-
unsafe_allow_html=True
|
| 208 |
-
)
|
| 209 |
-
native_bytes = bytes_data
|
| 210 |
else:
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
return
|
| 233 |
-
|
| 234 |
-
|
|
|
|
|
|
|
| 235 |
st.set_page_config(page_title="AI LightBox · Jewelry", layout="wide", page_icon="💎")
|
| 236 |
st.title("💎 AI LightBox · Jewelry")
|
| 237 |
-
st.caption("
|
| 238 |
|
| 239 |
ok = backend_ok()
|
| 240 |
|
| 241 |
-
# Üst
|
| 242 |
-
col1, col2, col3, col4, col5, col6, col7 = st.columns([1.6, 1.6, 1.0, 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,228 +213,286 @@ 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 |
-
|
|
|
|
| 251 |
with col5:
|
| 252 |
-
|
| 253 |
with col6:
|
| 254 |
-
|
| 255 |
with col7:
|
| 256 |
-
|
| 257 |
|
| 258 |
-
colA, colB, colC, colD, colE = st.columns([1.0, 1.0, 1.1, 0.9, 1.
|
| 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 |
-
|
| 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
|
| 276 |
resolution = st.selectbox("Video çözünürlük", VIDEO_RES_OPTIONS, index=1, key="resolution_sel")
|
|
|
|
|
|
|
| 277 |
|
| 278 |
-
#
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
-
#
|
| 282 |
-
|
| 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 |
-
# ====
|
| 288 |
-
|
| 289 |
-
|
| 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 |
-
#
|
| 295 |
input_bytes = None
|
| 296 |
if file_list:
|
| 297 |
-
try:
|
| 298 |
-
|
| 299 |
-
except Exception:
|
| 300 |
-
input_bytes = None
|
| 301 |
elif image_url:
|
| 302 |
input_bytes = fetch_bytes(image_url)
|
| 303 |
-
elif
|
| 304 |
-
input_bytes =
|
| 305 |
|
| 306 |
-
|
|
|
|
|
|
|
| 307 |
|
| 308 |
-
#
|
| 309 |
-
|
| 310 |
-
|
|
|
|
| 311 |
|
| 312 |
-
#
|
| 313 |
-
|
| 314 |
-
if
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
else:
|
| 331 |
-
|
| 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 |
-
# ================
|
| 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":
|
| 358 |
-
"mannequin_image_url": "",
|
| 359 |
"identity_lock": "true" if identity_lock else "false",
|
| 360 |
-
#
|
| 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",
|
| 367 |
-
"upscale_stage": st.session_state.get("upscale_stage",
|
| 368 |
-
# Video
|
| 369 |
"to_video": "true" if to_video else "false",
|
| 370 |
"video_prompt": "",
|
| 371 |
-
"duration": st.session_state.get("duration_sel",
|
| 372 |
-
"resolution": st.session_state.get("resolution_sel",
|
| 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 |
-
|
| 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 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
ui_hints = (out.get("video_step") or {}).get("ui_hints") or {}
|
| 391 |
-
if isinstance(ui_hints, dict)
|
| 392 |
-
st.session_state["video_ui_max_px"] = int(ui_hints
|
| 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 |
-
"
|
| 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 |
-
# ================
|
| 415 |
-
st.
|
| 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 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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:8000") or "http://127.0.0.1:8000").strip().strip("'\"").rstrip("/")
|
| 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 |
+
VIDEO_MAX_PX_DEFAULT = int(os.getenv("VIDEO_MAX_PX", "720"))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
VIDEO_RES_OPTIONS = ["512P", "768P"]
|
| 14 |
VIDEO_DUR_OPTIONS = ["6", "10"]
|
| 15 |
+
ASPECT_OPTIONS = ["9:16", "3:4", "1:1"] # preview kadraj oranları
|
| 16 |
|
| 17 |
# ================= Session =================
|
| 18 |
if "results" 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 |
+
# ================= HTTP/Backend helpers =================
|
| 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(("http://","https://")):
|
| 33 |
return url_or_path
|
| 34 |
if url_or_path.startswith("/outputs/"):
|
| 35 |
return f"{API_BASE}{url_or_path}"
|
|
|
|
| 65 |
|
| 66 |
@st.cache_data(ttl=300, show_spinner=False)
|
| 67 |
def fetch_bytes(url_or_path: str):
|
| 68 |
+
if not url_or_path: return None
|
|
|
|
| 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 |
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)); return im.size
|
|
|
|
| 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 |
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: z.writestr(fname, b)
|
| 104 |
+
buf.seek(0); return buf.read()
|
|
|
|
|
|
|
| 105 |
|
| 106 |
+
# ================= Preview helpers (uniform cards) =================
|
| 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 inject_preview_css(aspect: str, fit_mode="contain"):
|
| 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(255,255,255,0.06) inset;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
}}
|
| 127 |
+
.lb-frame img {{
|
| 128 |
+
width:100%; height:100%; object-fit:{fit_mode}; /* contain=fit, cover=fill */
|
| 129 |
+
display:block;
|
|
|
|
| 130 |
}}
|
| 131 |
+
.lb-video {{ display:flex; justify-content:center; }}
|
| 132 |
+
.lb-video video {{ border-radius:8px; max-width: 540px; width:100%; height:auto; }}
|
| 133 |
</style>
|
| 134 |
""", unsafe_allow_html=True)
|
| 135 |
|
| 136 |
+
def show_tile_card(col, title, url: str | None = None, bytes_data: bytes | None = None,
|
| 137 |
+
filename_stub="image", key_prefix=""):
|
|
|
|
| 138 |
col.markdown(f'<div class="lb-card-title">{title}</div>', unsafe_allow_html=True)
|
| 139 |
|
|
|
|
| 140 |
if not url and not bytes_data:
|
| 141 |
+
col.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
|
| 142 |
+
col.caption("—"); return None, None
|
|
|
|
| 143 |
|
| 144 |
+
# Render (HTML <img>) + native download
|
| 145 |
if bytes_data is not None:
|
| 146 |
src = image_bytes_to_data_url(bytes_data, "image/png")
|
| 147 |
col.markdown(f'<div class="lb-frame"><img src="{src}"/></div>', unsafe_allow_html=True)
|
| 148 |
+
native = bytes_data
|
| 149 |
else:
|
| 150 |
abs_url = _abs_backend_url(url)
|
| 151 |
col.markdown(f'<div class="lb-frame"><img src="{abs_url}"/></div>', unsafe_allow_html=True)
|
| 152 |
+
native = fetch_bytes(abs_url)
|
| 153 |
|
| 154 |
+
if not native:
|
| 155 |
+
col.caption("—"); return url or "data", None
|
|
|
|
| 156 |
|
| 157 |
+
sz = image_size_from_bytes(native)
|
| 158 |
+
if sz: col.caption(f"Gerçek çözünürlük: {sz[0]}×{sz[1]} px")
|
|
|
|
| 159 |
|
| 160 |
+
ext = infer_ext(native)
|
| 161 |
mime = "image/jpeg" if ext.lower() in [".jpg",".jpeg"] else ("image/png" if ext.lower()==".png" else "image/webp")
|
| 162 |
+
col.download_button("İndir (tam kalite)", data=native,
|
| 163 |
file_name=f"{filename_stub}{ext if ext!='.bin' else '.jpg'}",
|
| 164 |
mime=mime, key=f"{key_prefix}_{filename_stub}_dl")
|
| 165 |
+
return (url or "data"), native
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
+
def make_preview_frame(img_bytes: bytes, aspect: str, long_edge: int, ratio: float, bg_rgb=(255,255,255)) -> bytes:
|
| 168 |
+
"""Sadece UI için: seçilen aspect’te tuval + içerik oranı."""
|
| 169 |
+
im = Image.open(io.BytesIO(img_bytes)).convert("RGBA")
|
| 170 |
+
aw, ah = _parse_aspect_str(aspect)
|
| 171 |
+
# hedef tuval boyutu (uzun kenar sabit)
|
| 172 |
+
if aw >= ah:
|
| 173 |
+
W = max(256, min(8192, int(long_edge))); H = max(1, int(W * ah / aw))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
else:
|
| 175 |
+
H = max(256, min(8192, int(long_edge))); W = max(1, int(H * aw / ah))
|
| 176 |
+
ratio = max(0.30, min(0.99, float(ratio)))
|
| 177 |
+
target = int(min(W, H) * ratio if aw == ah else (H * ratio if aw < ah else W * ratio))
|
| 178 |
+
w, h = im.size
|
| 179 |
+
if w >= h:
|
| 180 |
+
new_w, new_h = target, max(1, int(h * (target / max(1, w))))
|
| 181 |
+
else:
|
| 182 |
+
new_h, new_w = target, max(1, int(w * (target / max(1, h))))
|
| 183 |
+
im_resized = im.resize((new_w, new_h), Image.LANCZOS)
|
| 184 |
+
canvas = Image.new("RGBA", (W, H), (*bg_rgb, 255))
|
| 185 |
+
off = ((W - new_w)//2, (H - new_h)//2)
|
| 186 |
+
canvas.paste(im_resized, off, im_resized)
|
| 187 |
+
out = io.BytesIO(); canvas.convert("RGB").save(out, format="JPEG", quality=95, subsampling=1)
|
| 188 |
+
return out.getvalue()
|
| 189 |
+
|
| 190 |
+
# ================= Yerel DEMO dosyaları =================
|
| 191 |
+
def load_local_demo():
|
| 192 |
+
demo = {}
|
| 193 |
+
for fname in ["input.jpg", "packshot.jpg", "model.jpg", "tryon.mp4"]:
|
| 194 |
+
if os.path.exists(fname):
|
| 195 |
+
with open(fname, "rb") as f: demo[fname] = f.read()
|
| 196 |
+
return demo
|
| 197 |
+
|
| 198 |
+
demo_files = load_local_demo()
|
| 199 |
+
|
| 200 |
+
# ================= Sayfa =================
|
| 201 |
st.set_page_config(page_title="AI LightBox · Jewelry", layout="wide", page_icon="💎")
|
| 202 |
st.title("💎 AI LightBox · Jewelry")
|
| 203 |
+
st.caption("Pre-run: sabit preview kartları. Run sonrası: Packshot/Model çıktıları native indirilir. Padded sadece ara adımdır.")
|
| 204 |
|
| 205 |
ok = backend_ok()
|
| 206 |
|
| 207 |
+
# -------- Üst Kontrol Şeridi (Üretim Parametreleri) --------
|
| 208 |
+
col1, col2, col3, col4, col5, col6, col7 = st.columns([1.6, 1.6, 1.0, 1.2, 0.9, 1.1, 0.9])
|
| 209 |
with col1:
|
| 210 |
file_list = st.file_uploader("Takı görseli (yükle)", type=["jpg","jpeg","png","webp"], accept_multiple_files=True, key="file_upl")
|
| 211 |
with col2:
|
|
|
|
| 213 |
with col3:
|
| 214 |
jewel_type = st.selectbox("Tür", ["auto","earring","ring","necklace","bracelet","pendant","brooch","set","watch"], index=0, key="jewel_type")
|
| 215 |
with col4:
|
| 216 |
+
preview_ratio = st.number_input("Preview ölçeği (0.10–0.99)", min_value=0.10, max_value=0.99, value=0.50, step=0.01,
|
| 217 |
+
help="Sadece önizleme kadrajında büyüklüğü etkiler.", key="preview_ratio")
|
| 218 |
with col5:
|
| 219 |
+
upscale = st.checkbox("Super Resolution", False, key="upscale")
|
| 220 |
with col6:
|
| 221 |
+
upscale_stage = st.selectbox("SR aşaması", ["both","final","packshot"], index=0, help="Varsayılan: both", key="upscale_stage")
|
| 222 |
with col7:
|
| 223 |
+
upscale_factor = st.selectbox("SR katsayı", ["2","4"], index=0, key="upscale_factor")
|
| 224 |
|
| 225 |
+
colA, colB, colC, colD, colE, colF = st.columns([1.0, 1.0, 1.1, 0.9, 0.9, 1.2])
|
| 226 |
with colA:
|
| 227 |
st.info(f"Bağlantı: {'Online' if ok else 'Offline'}", icon="🔌")
|
| 228 |
with colB:
|
| 229 |
identity_lock = st.checkbox("Identity lock", True, key="identity_lock")
|
| 230 |
with colC:
|
| 231 |
+
to_video = st.checkbox("Zincirde video üret", False, key="to_video")
|
| 232 |
with colD:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
duration = st.selectbox("Süre (sn)", VIDEO_DUR_OPTIONS, index=0, key="duration_sel")
|
| 234 |
+
with colE:
|
| 235 |
resolution = st.selectbox("Video çözünürlük", VIDEO_RES_OPTIONS, index=1, key="resolution_sel")
|
| 236 |
+
with colF:
|
| 237 |
+
run = st.button("Çalıştır", type="primary", use_container_width=True, key="run_btn")
|
| 238 |
|
| 239 |
+
# Tuval/kadraj + fit/fill
|
| 240 |
+
colT1, colT2, colT3 = st.columns([1.0, 1.0, 1.0])
|
| 241 |
+
with colT1:
|
| 242 |
+
preview_aspect = st.selectbox("Preview Kadraj Oranı", ASPECT_OPTIONS, index=0, key="preview_aspect")
|
| 243 |
+
with colT2:
|
| 244 |
+
preview_long_edge = st.number_input("Preview uzun kenar (px)", min_value=256, max_value=8192, value=1920, step=64, key="preview_long_edge")
|
| 245 |
+
with colT3:
|
| 246 |
+
fit_mode = st.selectbox("Önizleme yerleşimi", ["fit","fill"], index=0, help="Sadece önizlemeyi etkiler.", key="fit_mode")
|
| 247 |
|
| 248 |
+
# Inject CSS (uniform kartlar)
|
| 249 |
+
inject_preview_css(preview_aspect, fit_mode="contain" if fit_mode=="fit" else "cover")
|
|
|
|
|
|
|
|
|
|
| 250 |
|
| 251 |
+
# ================= PRE-RUN PREVIEWS (her zaman sabit) =================
|
| 252 |
+
st.subheader("Önizlemeler")
|
| 253 |
+
col_in, col_pack, col_pad, col_vid = st.columns(4)
|
|
|
|
|
|
|
|
|
|
| 254 |
|
| 255 |
+
# Input bytes (upload/URL öncelikli; yoksa demo)
|
| 256 |
input_bytes = None
|
| 257 |
if file_list:
|
| 258 |
+
try: input_bytes = file_list[0].getvalue()
|
| 259 |
+
except Exception: input_bytes = None
|
|
|
|
|
|
|
| 260 |
elif image_url:
|
| 261 |
input_bytes = fetch_bytes(image_url)
|
| 262 |
+
elif demo_files.get("input.jpg"):
|
| 263 |
+
input_bytes = demo_files["input.jpg"]
|
| 264 |
|
| 265 |
+
show_tile_card(col_in, "Input preview",
|
| 266 |
+
bytes_data=input_bytes if input_bytes else demo_files.get("input.jpg"),
|
| 267 |
+
filename_stub="input", key_prefix="pre")
|
| 268 |
|
| 269 |
+
# Packshot preview (demo dosyası varsa; yoksa input görüntü)
|
| 270 |
+
pack_bytes_demo = demo_files.get("packshot.jpg") or input_bytes
|
| 271 |
+
show_tile_card(col_pack, "Packshot preview",
|
| 272 |
+
bytes_data=pack_bytes_demo, filename_stub="packshot", key_prefix="pre")
|
| 273 |
|
| 274 |
+
# Padded preview (packshot.jpg veya input.jpg → seçilen kadraja, UI-only)
|
| 275 |
+
padded_bytes = None
|
| 276 |
+
if pack_bytes_demo:
|
| 277 |
+
try:
|
| 278 |
+
padded_bytes = make_preview_frame(pack_bytes_demo, aspect=preview_aspect,
|
| 279 |
+
long_edge=int(preview_long_edge),
|
| 280 |
+
ratio=float(preview_ratio))
|
| 281 |
+
except Exception:
|
| 282 |
+
padded_bytes = None
|
| 283 |
+
show_tile_card(col_pad, "Padded preview (UI only)",
|
| 284 |
+
bytes_data=padded_bytes or pack_bytes_demo, filename_stub="padded", key_prefix="pre")
|
| 285 |
+
|
| 286 |
+
# Video preview (loop; yerel tryon.mp4 varsa)
|
| 287 |
+
vid_demo = demo_files.get("tryon.mp4")
|
| 288 |
+
col_vid.markdown('<div class="lb-card-title">Video preview (loop)</div>', unsafe_allow_html=True)
|
| 289 |
+
if vid_demo:
|
| 290 |
+
data_url = "data:video/mp4;base64," + base64.b64encode(vid_demo).decode("ascii")
|
| 291 |
+
col_vid.markdown(
|
| 292 |
+
f"""
|
| 293 |
+
<div class="lb-frame" style="display:flex;align-items:center;justify-content:center;">
|
| 294 |
+
<video autoplay loop muted playsinline style="width:100%;height:100%;object-fit:cover;">
|
| 295 |
+
<source src="{data_url}" type="video/mp4">
|
| 296 |
+
</video>
|
| 297 |
+
</div>
|
| 298 |
+
""", unsafe_allow_html=True
|
| 299 |
+
)
|
| 300 |
+
col_vid.download_button("Videoyu indir (MP4)", data=vid_demo, file_name="tryon.mp4", mime="video/mp4", key="pre_video_dl")
|
| 301 |
else:
|
| 302 |
+
col_vid.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
|
| 303 |
+
col_vid.caption("—")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
+
# ================= ÇALIŞTIR =================
|
| 306 |
if run:
|
| 307 |
if not ok:
|
| 308 |
st.error("Backend erişilemiyor. API_BASE / TOKEN kontrol edin.")
|
| 309 |
+
elif not (file_list or image_url or demo_files.get("input.jpg")):
|
| 310 |
st.error("En az bir görsel girişi yapın (dosya yükle veya URL).")
|
| 311 |
else:
|
| 312 |
try:
|
| 313 |
+
img_urls = image_url or ""
|
| 314 |
+
files_payload = []
|
| 315 |
+
if file_list:
|
| 316 |
+
for f in file_list:
|
| 317 |
+
files_payload.append(("files", (f.name, f.getvalue(), f.type or "image/jpeg")))
|
| 318 |
+
|
| 319 |
data = {
|
| 320 |
+
"category": st.session_state.get("jewel_type","auto"),
|
| 321 |
"edit_prompt": "",
|
| 322 |
"num_images": "1",
|
| 323 |
+
"image_urls": img_urls,
|
| 324 |
+
"mannequin_image_url": "", # opsiyonel
|
| 325 |
"identity_lock": "true" if identity_lock else "false",
|
| 326 |
+
# Preview controls (backend pad/preview için)
|
| 327 |
"preview_aspect": preview_aspect,
|
| 328 |
"preview_long_edge": str(int(preview_long_edge)),
|
| 329 |
"preview_ratio": str(float(preview_ratio)),
|
| 330 |
+
"padding_ratio": str(float(preview_ratio)), # backward-compat
|
| 331 |
# SR
|
| 332 |
"upscale": "true" if upscale else "false",
|
| 333 |
+
"upscale_factor": st.session_state.get("upscale_factor","2"),
|
| 334 |
+
"upscale_stage": st.session_state.get("upscale_stage","both"),
|
| 335 |
+
# Video (opsiyonel zincir)
|
| 336 |
"to_video": "true" if to_video else "false",
|
| 337 |
"video_prompt": "",
|
| 338 |
+
"duration": st.session_state.get("duration_sel", VIDEO_DUR_OPTIONS[0]),
|
| 339 |
+
"resolution": st.session_state.get("resolution_sel", VIDEO_RES_OPTIONS[1]),
|
| 340 |
"prompt_optimizer": "false",
|
| 341 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
|
| 343 |
with st.spinner("Zincir çalışıyor…"):
|
| 344 |
+
out = post_chain(data, files_payload if files_payload else None)
|
| 345 |
|
| 346 |
+
st.session_state["job_counter"] += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
|
| 348 |
+
# ---- ÇIKTILAR (NATIVE ODAKLI) ----
|
| 349 |
+
# Packshot NATIVE (arka planı temiz PNG)
|
| 350 |
+
pack_native = None
|
| 351 |
+
try:
|
| 352 |
+
pack_native = (out["packshot_step"]["result"]["images_native"] or [{}])[0].get("url")
|
| 353 |
+
except Exception: pass
|
| 354 |
+
|
| 355 |
+
# Padded BACKEND (ara adım olarak packshot native'den UI'da üretiyoruz; download mümkün)
|
| 356 |
+
# 0.5 oranlı 9:16 görünüm — native dosyayı etkilemez
|
| 357 |
+
pad_backend_bytes = None
|
| 358 |
+
if pack_native:
|
| 359 |
+
nb = fetch_bytes(pack_native)
|
| 360 |
+
if nb:
|
| 361 |
+
try:
|
| 362 |
+
pad_backend_bytes = make_preview_frame(nb, aspect=preview_aspect,
|
| 363 |
+
long_edge=int(preview_long_edge),
|
| 364 |
+
ratio=float(preview_ratio))
|
| 365 |
+
except Exception:
|
| 366 |
+
pad_backend_bytes = None
|
| 367 |
+
|
| 368 |
+
# Model NATIVE
|
| 369 |
+
placed_native = None
|
| 370 |
+
try:
|
| 371 |
+
placed_native = (out["image_step"]["result"]["images_native"] or [{}])[0].get("url")
|
| 372 |
+
except Exception: pass
|
| 373 |
+
|
| 374 |
+
# Video (zincirde üretildiyse)
|
| 375 |
+
vurl = None
|
| 376 |
+
try:
|
| 377 |
+
vurl = (out.get("video_step") or {}).get("result", {}).get("video", {}).get("url")
|
| 378 |
+
except Exception:
|
| 379 |
+
vurl = None
|
| 380 |
+
|
| 381 |
+
# UI ipucu
|
| 382 |
ui_hints = (out.get("video_step") or {}).get("ui_hints") or {}
|
| 383 |
+
if isinstance(ui_hints, dict):
|
| 384 |
+
st.session_state["video_ui_max_px"] = int(ui_hints.get("suggested_video_max_px", VIDEO_MAX_PX_DEFAULT))
|
| 385 |
|
|
|
|
| 386 |
st.session_state["results"] = {
|
| 387 |
"job_id": out.get("job_id"),
|
| 388 |
"schema_version": out.get("schema_version"),
|
| 389 |
"packshot_native_url": pack_native,
|
| 390 |
+
"padded_backend_bytes": pad_backend_bytes, # ara adım UI-only
|
| 391 |
"placed_native_url": placed_native,
|
| 392 |
"video_url": vurl,
|
| 393 |
"api_base": API_BASE,
|
| 394 |
"has_auth_header": bool(HEADERS),
|
| 395 |
+
"preview_aspect": preview_aspect,
|
| 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 |
+
# ================= SONUÇLAR =================
|
| 404 |
+
res = st.session_state.get("results")
|
| 405 |
+
vbytes = None
|
| 406 |
+
if res:
|
| 407 |
+
st.subheader("Üretilen Sonuçlar")
|
| 408 |
+
c_pack, c_pad, c_model, c_vid = st.columns(4)
|
| 409 |
+
|
| 410 |
+
# Packshot (backend) — NATIVE
|
| 411 |
+
p_url, p_bytes = show_tile_card(
|
| 412 |
+
c_pack, "Packshot (backend)",
|
| 413 |
+
url=res.get("packshot_native_url"),
|
| 414 |
+
filename_stub="packshot_native",
|
| 415 |
+
key_prefix=f"job{st.session_state['job_counter']}"
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
# Padded (backend) — ara adım (UI’da packshot native’den seçilen oranla kadraj)
|
| 419 |
+
pad_bytes = res.get("padded_backend_bytes")
|
| 420 |
+
_, _ = show_tile_card(
|
| 421 |
+
c_pad, "Padded (backend) • ara adım",
|
| 422 |
+
bytes_data=pad_bytes if pad_bytes else (p_bytes or b""),
|
| 423 |
+
filename_stub="padded_backend",
|
| 424 |
+
key_prefix=f"job{st.session_state['job_counter']}"
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
# Model üzerinde (backend) — NATIVE
|
| 428 |
+
m_url, m_bytes = show_tile_card(
|
| 429 |
+
c_model, "Model üzerinde (backend)",
|
| 430 |
+
url=res.get("placed_native_url"),
|
| 431 |
+
filename_stub="model_native",
|
| 432 |
+
key_prefix=f"job{st.session_state['job_counter']}"
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# Video: varsa göster; yoksa kullanıcı isterse üretecek (loop)
|
| 436 |
+
vurl = res.get("video_url")
|
| 437 |
+
c_vid.markdown('<div class="lb-card-title">Video</div>', unsafe_allow_html=True)
|
| 438 |
+
if vurl:
|
| 439 |
+
abs_v = _abs_backend_url(vurl)
|
| 440 |
+
c_vid.markdown(
|
| 441 |
+
f"""
|
| 442 |
+
<div class="lb-frame" style="display:flex;align-items:center;justify-content:center;">
|
| 443 |
+
<video autoplay loop muted controls playsinline style="width:100%;height:100%;object-fit:cover;">
|
| 444 |
+
<source src="{abs_v}" type="video/mp4">
|
| 445 |
+
</video>
|
| 446 |
+
</div>
|
| 447 |
+
""", unsafe_allow_html=True
|
| 448 |
+
)
|
| 449 |
+
vb = fetch_bytes(abs_v)
|
| 450 |
+
if vb:
|
| 451 |
+
vbytes = vb
|
| 452 |
+
c_vid.download_button("Videoyu indir (MP4)", data=vb, file_name="ai_lightbox_video.mp4",
|
| 453 |
+
mime="video/mp4", key=f"job{st.session_state['job_counter']}_video_dl")
|
| 454 |
+
else:
|
| 455 |
+
c_vid.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
|
| 456 |
+
if st.checkbox("Bu sonuçtan video üret", value=False, key="video_toggle"):
|
| 457 |
+
# Öncelik: model native → değilse packshot native
|
| 458 |
+
src_for_video = res.get("placed_native_url") or res.get("packshot_native_url")
|
| 459 |
+
if not src_for_video:
|
| 460 |
+
st.warning("Video için kullanılacak native görsel bulunamadı.")
|
| 461 |
+
else:
|
| 462 |
+
with st.spinner("Video üretiliyor…"):
|
| 463 |
+
v = post_video(
|
| 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 |
+
preview_aspect=st.session_state.get("preview_aspect","9:16"),
|
| 468 |
+
prompt_optimizer=False,
|
| 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.")
|