renderfy commited on
Commit
74dc30d
·
verified ·
1 Parent(s): 3618edf

Upload streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +128 -222
streamlit_app.py CHANGED
@@ -1,9 +1,9 @@
1
- # streamlit_app.py — AI LightBox · Jewelry (Dark+Orange + Orange UI Labels)
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
- # ===== Theme (programmatic dark) =====
7
  def apply_theme():
8
  THEME = {
9
  "base": "dark",
@@ -23,7 +23,6 @@ def apply_theme():
23
  except Exception:
24
  pass
25
 
26
- # CSS: genel koyu tema + TÜM label/caption/info yazıları turuncu
27
  st.markdown(f"""
28
  <style>
29
  :root {{
@@ -34,111 +33,63 @@ def apply_theme():
34
  --primary: {THEME["primaryColor"]};
35
  --outline: {THEME["cardOutline"]};
36
  }}
37
-
38
  html, body, .block-container {{ background: var(--bg) !important; color: var(--text) !important; }}
39
  .stApp header {{ background: var(--bg) !important; }}
40
-
41
- /* Kart ve panel arkaplanları */
42
- [data-testid="stVerticalBlock"] > div, .st-emotion-cache-1r6slb0, .st-emotion-cache-1dp5vir {{
43
- background: var(--sb) !important;
44
- border-radius: 12px;
45
- box-shadow: 0 0 0 1px var(--outline) inset;
46
- }}
47
-
48
- /* --- LABEL'LERİ TURUNCU YAP --- */
49
- /* Tüm widget etiketleri (input/select/checkbox/slider vs.) */
50
- label, .stSelectbox label, .stTextInput label, .stNumberInput label,
51
- .stFileUploader label, .stCheckbox > label, .stRadio > label,
52
- .stSlider > label, [data-testid="stWidgetLabel"] p {{
53
- color: var(--primary) !important;
54
- font-weight: 600;
55
- }}
56
-
57
- /* Üst şerit başlık/alt yazılar ve kart başlıkları */
58
- .lb-card-title, h1, h2, h3 {{
59
  color: var(--primary) !important;
60
  }}
61
-
62
- /* Captions (örn. Real Res…, Upload. Try-on. Download.) */
63
- .stCaption, .stMarkdown div small, .stMarkdown p:has(small), .stMarkdown > p {{
64
- color: var(--primary) !important;
65
- }}
66
-
67
- /* Info/Warning kutularının iç metni */
68
- .stAlert, .stAlert p, .stAlert span, .stAlert div {{
69
- color: var(--primary) !important;
70
- background: var(--sb) !important;
71
- border-radius: 12px;
72
- box-shadow: 0 0 0 1px var(--outline) inset;
73
- }}
74
-
75
- /* Butonlar: mevcut koyu turuncu stiller */
76
- .stButton > button {{
77
- background: var(--primary) !important; color: #101215 !important; font-weight: 700;
78
- border: none; border-radius: 10px; box-shadow: 0 0 0 1px #00000033 inset;
79
- }}
80
  .stButton > button:hover {{ filter: brightness(1.05); }}
81
-
82
- /* Download butonları */
83
- .stDownloadButton > button {{
84
- background: transparent !important; color: var(--primary) !important;
85
- border: 1px solid var(--primary); border-radius: 10px;
86
- }}
87
- .stDownloadButton > button:hover {{
88
- filter: brightness(1.1);
89
- }}
90
-
91
- /* Önizleme kartları */
92
- .lb-frame {{
93
- border-radius: 12px; overflow: hidden; background: var(--sb);
94
- display:flex; align-items:center; justify-content:center;
95
- box-shadow: 0 0 0 1px var(--outline) inset;
96
- }}
97
  </style>
98
  """, unsafe_allow_html=True)
99
 
100
  apply_theme()
101
 
102
- # ================= Env & API =================
103
  API_BASE = (os.getenv("AI_LIGHTBOX_API", "http://127.0.0.1:8000") or "http://127.0.0.1:8000").strip().strip("'\"").rstrip("/")
104
  HF_TOKEN = (os.getenv("AI_LIGHTBOX_TOKEN", "") or "").strip().strip("'\"")
105
  HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
106
 
107
- # UI vars
108
  VIDEO_MAX_PX_DEFAULT = int(os.getenv("VIDEO_MAX_PX", "720"))
109
  VIDEO_RES_OPTIONS = ["512P", "768P"]
110
  VIDEO_DUR_OPTIONS = ["6", "10"]
111
- ASPECT_OPTIONS = ["9:16", "3:4", "1:1"] # preview kadraj oranları
112
 
113
- # ================= Session =================
114
- if "results" not in st.session_state:
115
- st.session_state["results"] = None
116
- if "job_counter" not in st.session_state:
117
- st.session_state["job_counter"] = 0
118
- if "video_ui_max_px" not in st.session_state:
119
- st.session_state["video_ui_max_px"] = VIDEO_MAX_PX_DEFAULT
120
 
121
- # ================= HTTP/Backend helpers =================
122
  def _needs_auth(url: str) -> bool:
123
  return url.startswith(API_BASE) or url.startswith("outputs/") or url.startswith("/outputs/")
124
 
125
  def _abs_backend_url(url_or_path: str) -> str:
126
- if not url_or_path:
127
- return ""
128
- if url_or_path.startswith(("http://","https://")):
129
- return url_or_path
130
- if url_or_path.startswith("/outputs/"):
131
- return f"{API_BASE}{url_or_path}"
132
- if url_or_path.startswith("outputs/"):
133
- return f"{API_BASE}/{url_or_path}"
134
  return f"{API_BASE}/{url_or_path.lstrip('/')}"
135
 
136
  def backend_ok() -> bool:
137
  try:
138
  r = requests.get(f"{API_BASE}/health", headers=HEADERS, timeout=10)
139
  r.raise_for_status()
 
140
  return True
141
  except Exception:
 
142
  return False
143
 
144
  def post_chain(data: dict, files_payload):
@@ -171,6 +122,7 @@ def fetch_bytes(url_or_path: str):
171
  except Exception:
172
  return None
173
 
 
174
  def _sniff_mime_from_bytes(b: bytes) -> str:
175
  try:
176
  fmt = (Image.open(io.BytesIO(b)).format or "JPEG").lower()
@@ -179,8 +131,7 @@ def _sniff_mime_from_bytes(b: bytes) -> str:
179
  return "image/jpeg"
180
 
181
  def image_bytes_to_data_url(b: bytes, mime: str | None = None) -> str:
182
- if not mime:
183
- mime = _sniff_mime_from_bytes(b)
184
  enc = base64.b64encode(b).decode("ascii")
185
  return f"data:{mime};base64,{enc}"
186
 
@@ -197,18 +148,30 @@ def infer_ext(data: bytes) -> str:
197
  fmt = (im.format or "JPEG").lower()
198
  return "." + {"jpeg":"jpg","jpg":"jpg","png":"png","webp":"webp"}.get(fmt,"jpg")
199
  except Exception:
200
- if data[:4] == b"\x00\x00\x00\x18" or data[4:8] == b"ftyp":
201
- return ".mp4"
202
  return ".bin"
203
 
204
- def make_zip(named_bytes: list[tuple[str, bytes]]) -> bytes:
205
- buf = io.BytesIO()
206
- with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as z:
207
- for fname, b in named_bytes:
208
- if b: z.writestr(fname, b)
209
- buf.seek(0); return buf.read()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
 
211
- # ================= Preview helpers (uniform cards) =================
212
  def _parse_aspect_str(s: str):
213
  try:
214
  a, b = s.split(":"); return max(1, int(a)), max(1, int(b))
@@ -230,7 +193,7 @@ def inject_preview_css(aspect: str, fit_mode="contain"):
230
  box-shadow: 0 0 0 1px var(--outline) inset;
231
  }}
232
  .lb-frame img {{
233
- width:100%; height:100%; object-fit:{fit_mode}; /* contain=fit, cover=fill */
234
  display:block;
235
  }}
236
  .lb-video {{ display:flex; justify-content:center; }}
@@ -247,25 +210,21 @@ def show_tile_card_display_download(
247
  filename_stub: str = "image",
248
  key_prefix: str = "",
249
  ):
250
- """Gösterimde HAFİF JPEG/PNG (display_bytes) tercih edilir; indirmede NATIVE."""
251
  col.markdown(f'<div class="lb-card-title">{title}</div>', unsafe_allow_html=True)
252
 
253
- # ---- Display ----
254
  if not display_url and not display_bytes:
255
  col.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
256
  col.caption("—"); return None, None
257
 
258
  if display_bytes is not None:
259
- src = image_bytes_to_data_url(display_bytes) # mime otomatik
260
  col.markdown(f'<div class="lb-frame"><img src="{src}"/></div>', unsafe_allow_html=True)
261
  else:
262
  abs_url = _abs_backend_url(display_url)
263
  col.markdown(f'<div class="lb-frame"><img src="{abs_url}"/></div>', unsafe_allow_html=True)
264
 
265
- # ---- Native (caption + download) ----
266
  native = download_bytes or (fetch_bytes(download_url) if download_url else None)
267
- if not native:
268
- native = display_bytes # en azından çözünürlük gösterebilmek için
269
 
270
  if native:
271
  sz = image_size_from_bytes(native)
@@ -280,54 +239,7 @@ def show_tile_card_display_download(
280
 
281
  return display_url or "data", native
282
 
283
- def rgba_to_rgb_on_bg(img_rgba: Image.Image, bg_rgb=(255,255,255)) -> Image.Image:
284
- """RGBA görseli seçilen arka plana kompoze ederek RGB'ye çevir (siyah sorununu çözer)."""
285
- if img_rgba.mode != "RGBA":
286
- return img_rgba.convert("RGB")
287
- bg = Image.new("RGBA", img_rgba.size, (*bg_rgb, 255))
288
- bg.paste(img_rgba, (0,0), img_rgba)
289
- return bg.convert("RGB")
290
-
291
- @st.cache_data(ttl=300, show_spinner=False)
292
- def make_small_jpeg_from_native(native: bytes, target_long_edge: int = 1280, bg_rgb=(23,26,31)) -> bytes:
293
- """Şeffaf PNG → koyu zemine kompoze → hafif JPEG (dark tema için)."""
294
- im = Image.open(io.BytesIO(native))
295
- if im.mode != "RGBA" and "transparency" not in im.info:
296
- im = im.convert("RGB")
297
- else:
298
- im = im.convert("RGBA")
299
- w, h = im.size
300
- if w >= h:
301
- new_w = min(target_long_edge, w)
302
- new_h = max(1, int(h * (new_w / max(1, w))))
303
- else:
304
- new_h = min(target_long_edge, h)
305
- new_w = max(1, int(w * (new_h / max(1, h))))
306
- im2 = im.resize((new_w, new_h), Image.LANCZOS)
307
- im2_rgb = rgba_to_rgb_on_bg(im2, bg_rgb=bg_rgb)
308
- out = io.BytesIO(); im2_rgb.save(out, format="JPEG", quality=88, subsampling=1)
309
- return out.getvalue()
310
-
311
- def make_preview_frame(img_bytes: bytes, aspect: str, long_edge: int, ratio: float, bg_rgb=(23,26,31)) -> bytes:
312
- """UI-only: seçilen aspect’te tuval + içerik oranı (JPEG)."""
313
- im = Image.open(io.BytesIO(img_bytes)).convert("RGBA")
314
- aw, ah = _parse_aspect_str(aspect)
315
- if aw >= ah:
316
- W = max(256, min(8192, int(long_edge))); H = max(1, int(W * ah / aw))
317
- else:
318
- H = max(256, min(8192, int(long_edge))); W = max(1, int(H * aw / ah))
319
- ratio = max(0.10, min(0.99, float(ratio)))
320
- target = int(min(W, H) * ratio if aw == ah else (H * ratio if aw < ah else W * ratio))
321
- w, h = im.size
322
- if w >= h: new_w, new_h = target, max(1, int(h * (target / max(1, w))))
323
- else: new_h, new_w = target, max(1, int(w * (target / max(1, h))))
324
- im_resized = im.resize((new_w, new_h), Image.LANCZOS)
325
- canvas = Image.new("RGBA", (W, H), (*bg_rgb, 255))
326
- off = ((W - new_w)//2, (H - new_h)//2); canvas.paste(im_resized, off, im_resized)
327
- out = io.BytesIO(); canvas.convert("RGB").save(out, format="JPEG", quality=90, subsampling=1)
328
- return out.getvalue()
329
-
330
- # ================= Yerel DEMO dosyaları =================
331
  def load_local_demo():
332
  demo = {}
333
  for fname in ["input.jpg", "packshot.jpg", "model.jpg", "tryon.mp4"]:
@@ -337,15 +249,16 @@ def load_local_demo():
337
 
338
  demo_files = load_local_demo()
339
 
340
- # ================= Sayfa =================
341
  st.set_page_config(page_title="AI LightBox · Jewelry", layout="wide", page_icon="💎")
342
  st.title("💎 AI LightBox · Jewelry")
343
- # Turuncu caption (CSS tüm captionları turuncu yapıyor)
344
  st.caption("Upload. Try-on. Download.")
345
 
346
  ok = backend_ok()
 
 
347
 
348
- # -------- Üst Kontrol Şeridi --------
349
  col1, col2, col3, col4, col5, col6, col7 = st.columns([1.6, 1.6, 1.0, 1.2, 0.9, 1.1, 0.9])
350
  with col1:
351
  file_list = st.file_uploader("Product Image (Upload)", type=["jpg","jpeg","png","webp"], accept_multiple_files=True, key="file_upl")
@@ -365,7 +278,7 @@ with col7:
365
 
366
  colA, colB, colC, colD, colE, colF = st.columns([1.0, 1.0, 1.1, 0.9, 0.9, 1.2])
367
  with colA:
368
- st.info(f"Connection: {'Online' if ok else 'Offline'}", icon="🔌")
369
  with colB:
370
  identity_lock = st.checkbox("Identity lock", True, key="identity_lock")
371
  with colC:
@@ -377,7 +290,7 @@ with colE:
377
  with colF:
378
  run = st.button("Run 💎", type="primary", use_container_width=True, key="run_btn")
379
 
380
- # Tuval/kadraj + fit/fill
381
  colT1, colT2, colT3 = st.columns([1.0, 1.0, 1.0])
382
  with colT1:
383
  preview_aspect = st.selectbox("Preview Frame Ratio", ASPECT_OPTIONS, index=0, key="preview_aspect")
@@ -386,14 +299,12 @@ with colT2:
386
  with colT3:
387
  fit_mode = st.selectbox("Preview Layout", ["fit","fill"], index=0, help="Sadece önizlemeyi etkiler.", key="fit_mode")
388
 
389
- # Inject CSS (uniform kartlar)
390
  inject_preview_css(preview_aspect, fit_mode="contain" if fit_mode=="fit" else "cover")
391
 
392
- # ================= PRE-RUN PREVIEWS =================
393
  st.subheader("Previews")
394
  col_in, col_pack, col_pad, col_vid = st.columns(4)
395
 
396
- # Input bytes (upload/URL öncelikli; yoksa demo)
397
  input_bytes = None
398
  if file_list:
399
  try: input_bytes = file_list[0].getvalue()
@@ -410,7 +321,6 @@ show_tile_card_display_download(
410
  filename_stub="input", key_prefix="pre"
411
  )
412
 
413
- # Packshot preview (demo dosyası varsa; yoksa input görüntü)
414
  pack_bytes_demo = demo_files.get("packshot.jpg") or input_bytes
415
  show_tile_card_display_download(
416
  col_pack, "Sample Packshot (BG Removed)",
@@ -419,25 +329,42 @@ show_tile_card_display_download(
419
  filename_stub="packshot", key_prefix="pre"
420
  )
421
 
422
- # Padded preview (packshot.jpg veya input.jpg → seçilen kadraja, UI-only)
423
  padded_bytes = None
424
  if pack_bytes_demo:
425
  try:
426
- padded_bytes = make_preview_frame(pack_bytes_demo, aspect=preview_aspect,
427
- long_edge=int(preview_long_edge),
428
- ratio=float(preview_ratio))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  except Exception:
430
  padded_bytes = None
 
431
  show_tile_card_display_download(
432
- col_pad, "Sample Padded Preview ",
433
  display_bytes=padded_bytes or pack_bytes_demo,
434
  download_bytes=padded_bytes or pack_bytes_demo,
435
  filename_stub="padded_ui", key_prefix="pre"
436
  )
437
 
438
- # Video preview (loop; yerel tryon.mp4 varsa)
439
  vid_demo = demo_files.get("tryon.mp4")
440
- col_vid.markdown('<div class="lb-card-title">AI Generated Video Preview </div>', unsafe_allow_html=True)
441
  if vid_demo:
442
  data_url = "data:video/mp4;base64," + base64.b64encode(vid_demo).decode("ascii")
443
  col_vid.markdown(
@@ -454,7 +381,7 @@ else:
454
  col_vid.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
455
  col_vid.caption("—")
456
 
457
- # ================= ÇALIŞTIR =================
458
  if run:
459
  if not ok:
460
  st.error("Backend erişilemiyor. API_BASE / TOKEN kontrol edin.")
@@ -470,21 +397,21 @@ if run:
470
 
471
  data = {
472
  "category": st.session_state.get("jewel_type","auto"),
473
- "edit_prompt": "",
474
  "num_images": "1",
475
  "image_urls": img_urls,
476
  "mannequin_image_url": "",
477
  "identity_lock": "true" if identity_lock else "false",
478
- # Preview controls (backend pad/preview için)
479
- "preview_aspect": preview_aspect,
480
- "preview_long_edge": str(int(preview_long_edge)),
481
- "preview_ratio": str(float(preview_ratio)),
482
- "padding_ratio": str(float(preview_ratio)), # backward-compat
483
  # SR
484
  "upscale": "true" if upscale else "false",
485
  "upscale_factor": st.session_state.get("upscale_factor","2"),
486
  "upscale_stage": st.session_state.get("upscale_stage","both"),
487
- # Video (opsiyonel zincir)
488
  "to_video": "true" if to_video else "false",
489
  "video_prompt": "",
490
  "duration": st.session_state.get("duration_sel", VIDEO_DUR_OPTIONS[0]),
@@ -497,45 +424,28 @@ if run:
497
 
498
  st.session_state["job_counter"] += 1
499
 
500
- # ---- ÇIKTILAR ----
501
- # Packshot NATIVE → DISPLAY küçük JPEG (şeffaflık koyuya kompoze)
502
- pack_native_url = None; pack_display_jpeg = None
503
- try:
504
- pack_native_url = (out["packshot_step"]["result"]["images_native"] or [{}])[0].get("url")
505
- if pack_native_url:
506
- pn = fetch_bytes(pack_native_url)
507
- if pn: pack_display_jpeg = make_small_jpeg_from_native(pn, 1280, bg_rgb=(23,26,31))
508
- except Exception: pass
509
-
510
- # Padded NATIVE → DISPLAY küçük JPEG (pad etkisi görünür)
511
- padded_native_url = None; padded_display_jpeg = None
512
- try:
513
- padded_native_url = (out["packshot_step"]["result"]["padded_native"] or [{}])[0].get("url")
514
- if padded_native_url:
515
- nb = fetch_bytes(padded_native_url)
516
- if nb: padded_display_jpeg = make_small_jpeg_from_native(nb, 1280, bg_rgb=(23,26,31))
517
- except Exception: pass
518
-
519
- # Model NATIVE → DISPLAY küçük JPEG
520
- placed_native_url = None; placed_display_jpeg = None
521
- try:
522
- placed_native_url = (out["image_step"]["result"]["images_native"] or [{}])[0].get("url")
523
- if placed_native_url:
524
- mn = fetch_bytes(placed_native_url)
525
- if mn: placed_display_jpeg = make_small_jpeg_from_native(mn, 1280, bg_rgb=(23,26,31))
526
- except Exception: pass
527
-
528
- # Video (zincirde üretildiyse)
529
- vurl = None
530
- try:
531
- vurl = (out.get("video_step") or {}).get("result", {}).get("video", {}).get("url")
532
- except Exception:
533
- vurl = None
534
-
535
- # UI ipucu
536
- ui_hints = (out.get("video_step") or {}).get("ui_hints") or {}
537
- if isinstance(ui_hints, dict):
538
- st.session_state["video_ui_max_px"] = int(ui_hints.get("suggested_video_max_px", VIDEO_MAX_PX_DEFAULT))
539
 
540
  st.session_state["results"] = {
541
  "job_id": out.get("job_id"),
@@ -549,7 +459,7 @@ if run:
549
  "video_url": vurl,
550
  "api_base": API_BASE,
551
  "has_auth_header": bool(HEADERS),
552
- "preview_aspect": preview_aspect,
553
  }
554
 
555
  except requests.HTTPError as e:
@@ -557,14 +467,13 @@ if run:
557
  except Exception as e:
558
  st.error(f"Hata: {e}")
559
 
560
- # ================= SONUÇLAR =================
561
  res = st.session_state.get("results")
562
  vbytes = None
563
  if res:
564
  st.subheader("Product Results")
565
  c_pack, c_pad, c_model, c_vid = st.columns(4)
566
 
567
- # Packshot (backend) — DISPLAY = küçük JPEG, DOWNLOAD = NATIVE
568
  show_tile_card_display_download(
569
  c_pack, "Packshot (Removed BG)",
570
  display_bytes=res.get("packshot_display_jpeg"),
@@ -572,8 +481,6 @@ if res:
572
  filename_stub="packshot_native",
573
  key_prefix=f"job{st.session_state['job_counter']}"
574
  )
575
-
576
- # Padded (backend) — DISPLAY = padded küçük JPEG, DOWNLOAD = padded NATIVE
577
  show_tile_card_display_download(
578
  c_pad, "Padded",
579
  display_bytes=res.get("padded_display_jpeg"),
@@ -581,8 +488,6 @@ if res:
581
  filename_stub="padded_backend",
582
  key_prefix=f"job{st.session_state['job_counter']}"
583
  )
584
-
585
- # Model üzerinde (backend) — DISPLAY = küçük JPEG (native’den), DOWNLOAD = NATIVE
586
  show_tile_card_display_download(
587
  c_model, "TryON Model",
588
  display_bytes=res.get("placed_display_jpeg"),
@@ -591,7 +496,6 @@ if res:
591
  key_prefix=f"job{st.session_state['job_counter']}"
592
  )
593
 
594
- # Video
595
  vurl = res.get("video_url")
596
  c_vid.markdown('<div class="lb-card-title">AI Generated Video</div>', unsafe_allow_html=True)
597
  if vurl:
@@ -626,16 +530,13 @@ if res:
626
  prompt_optimizer=False,
627
  )
628
  vurl2 = (v.get("result") or {}).get("video", {}).get("url")
629
- ui_hints = v.get("ui_hints") or {}
630
  if vurl2:
631
  st.session_state["results"]["video_url"] = vurl2
632
- if isinstance(ui_hints, dict):
633
- st.session_state["video_ui_max_px"] = int(ui_hints.get("suggested_video_max_px", VIDEO_MAX_PX_DEFAULT))
634
  st.success("Video is Ready!.")
635
  else:
636
  st.info("Video URL gelmedi.")
637
 
638
- # Native ZIP
639
  named = []
640
  pn = fetch_bytes(res.get("packshot_native_url")) if res.get("packshot_native_url") else None
641
  mn = fetch_bytes(res.get("placed_native_url")) if res.get("placed_native_url") else None
@@ -643,15 +544,20 @@ if res:
643
  if mn: named.append((f"model_native{infer_ext(mn)}", mn))
644
  if vbytes: named.append(("video.mp4", vbytes))
645
  if named:
646
- zip_bytes = make_zip(named)
647
- st.download_button("Download All (ZIP)", data=zip_bytes,
 
 
 
 
648
  file_name="ai_lightbox_outputs.zip", mime="application/zip",
649
  key=f"job{st.session_state['job_counter']}_zip_dl")
650
 
651
- # ================= Sidebar =================
652
  with st.sidebar:
653
  st.caption(f"API_BASE: {API_BASE}")
654
  if HF_TOKEN: st.caption("Auth: Bearer (aktif)")
 
655
  st.slider("Video önizleme genişliği (px)", 360, 1080, st.session_state["video_ui_max_px"],
656
  step=10, key="video_ui_max_px")
657
  if st.button("Önbelleği temizle"): st.cache_data.clear(); st.success("Önbellek temizlendi.")
 
1
+ # streamlit_app.py — AI LightBox · Jewelry (Frontend, v0.6.0 compatible)
2
+ # Dark + orange theme, all UI labels in orange. Works with app.py v0.6.0 (conditional RMBG).
3
  import os, io, base64, zipfile, requests, streamlit as st
4
  from PIL import Image
5
 
6
+ # ======================= THEME (dark+orange + orange labels) =======================
7
  def apply_theme():
8
  THEME = {
9
  "base": "dark",
 
23
  except Exception:
24
  pass
25
 
 
26
  st.markdown(f"""
27
  <style>
28
  :root {{
 
33
  --primary: {THEME["primaryColor"]};
34
  --outline: {THEME["cardOutline"]};
35
  }}
 
36
  html, body, .block-container {{ background: var(--bg) !important; color: var(--text) !important; }}
37
  .stApp header {{ background: var(--bg) !important; }}
38
+ [data-testid="stVerticalBlock"] > div {{ background: var(--sb) !important; border-radius: 12px;
39
+ box-shadow: 0 0 0 1px var(--outline) inset; }}
40
+ /* Orange labels/captions */
41
+ label, [data-testid="stWidgetLabel"] p, .lb-card-title, h1, h2, h3, .stCaption, .stMarkdown > p {{
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  color: var(--primary) !important;
43
  }}
44
+ .stAlert, .stAlert p, .stAlert span {{ color: var(--primary) !important; background: var(--sb) !important;
45
+ border-radius: 12px; box-shadow: 0 0 0 1px var(--outline) inset; }}
46
+ .stButton > button {{ background: var(--primary) !important; color: #101215 !important; font-weight: 700;
47
+ border: none; border-radius: 10px; box-shadow: 0 0 0 1px #00000033 inset; }}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  .stButton > button:hover {{ filter: brightness(1.05); }}
49
+ .stDownloadButton > button {{ background: transparent !important; color: var(--primary) !important;
50
+ border: 1px solid var(--primary); border-radius: 10px; }}
51
+ .stDownloadButton > button:hover {{ filter: brightness(1.1); }}
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  </style>
53
  """, unsafe_allow_html=True)
54
 
55
  apply_theme()
56
 
57
+ # ======================= Env & API =======================
58
  API_BASE = (os.getenv("AI_LIGHTBOX_API", "http://127.0.0.1:8000") or "http://127.0.0.1:8000").strip().strip("'\"").rstrip("/")
59
  HF_TOKEN = (os.getenv("AI_LIGHTBOX_TOKEN", "") or "").strip().strip("'\"")
60
  HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
61
 
 
62
  VIDEO_MAX_PX_DEFAULT = int(os.getenv("VIDEO_MAX_PX", "720"))
63
  VIDEO_RES_OPTIONS = ["512P", "768P"]
64
  VIDEO_DUR_OPTIONS = ["6", "10"]
65
+ ASPECT_OPTIONS = ["9:16", "3:4", "1:1"]
66
 
67
+ # ======================= Session =======================
68
+ for k, v in {
69
+ "results": None, "job_counter": 0, "video_ui_max_px": VIDEO_MAX_PX_DEFAULT,
70
+ "health": {}
71
+ }.items():
72
+ if k not in st.session_state: st.session_state[k] = v
 
73
 
74
+ # ======================= HTTP helpers =======================
75
  def _needs_auth(url: str) -> bool:
76
  return url.startswith(API_BASE) or url.startswith("outputs/") or url.startswith("/outputs/")
77
 
78
  def _abs_backend_url(url_or_path: str) -> str:
79
+ if not url_or_path: return ""
80
+ if url_or_path.startswith(("http://","https://")): return url_or_path
81
+ if url_or_path.startswith("/outputs/"): return f"{API_BASE}{url_or_path}"
82
+ if url_or_path.startswith("outputs/"): return f"{API_BASE}/{url_or_path}"
 
 
 
 
83
  return f"{API_BASE}/{url_or_path.lstrip('/')}"
84
 
85
  def backend_ok() -> bool:
86
  try:
87
  r = requests.get(f"{API_BASE}/health", headers=HEADERS, timeout=10)
88
  r.raise_for_status()
89
+ st.session_state["health"] = r.json()
90
  return True
91
  except Exception:
92
+ st.session_state["health"] = {}
93
  return False
94
 
95
  def post_chain(data: dict, files_payload):
 
122
  except Exception:
123
  return None
124
 
125
+ # ======================= Image utils =======================
126
  def _sniff_mime_from_bytes(b: bytes) -> str:
127
  try:
128
  fmt = (Image.open(io.BytesIO(b)).format or "JPEG").lower()
 
131
  return "image/jpeg"
132
 
133
  def image_bytes_to_data_url(b: bytes, mime: str | None = None) -> str:
134
+ if not mime: mime = _sniff_mime_from_bytes(b)
 
135
  enc = base64.b64encode(b).decode("ascii")
136
  return f"data:{mime};base64,{enc}"
137
 
 
148
  fmt = (im.format or "JPEG").lower()
149
  return "." + {"jpeg":"jpg","jpg":"jpg","png":"png","webp":"webp"}.get(fmt,"jpg")
150
  except Exception:
151
+ if data[:4] == b"\x00\x00\x00\x18" or data[4:8] == b"ftyp": return ".mp4"
 
152
  return ".bin"
153
 
154
+ def rgba_to_rgb_on_bg(img_rgba: Image.Image, bg_rgb=(23,26,31)) -> Image.Image:
155
+ if img_rgba.mode != "RGBA": return img_rgba.convert("RGB")
156
+ bg = Image.new("RGBA", img_rgba.size, (*bg_rgb, 255))
157
+ bg.paste(img_rgba, (0,0), img_rgba)
158
+ return bg.convert("RGB")
159
+
160
+ @st.cache_data(ttl=300, show_spinner=False)
161
+ def make_small_jpeg_from_native(native: bytes, target_long_edge: int = 1280, bg_rgb=(23,26,31)) -> bytes:
162
+ im = Image.open(io.BytesIO(native))
163
+ if im.mode != "RGBA" and "transparency" not in im.info: im = im.convert("RGB")
164
+ else: im = im.convert("RGBA")
165
+ w, h = im.size
166
+ if w >= h:
167
+ new_w = min(target_long_edge, w); new_h = max(1, int(h * (new_w / max(1, w))))
168
+ else:
169
+ new_h = min(target_long_edge, h); new_w = max(1, int(w * (new_h / max(1, h))))
170
+ im2 = im.resize((new_w, new_h), Image.LANCZOS)
171
+ im2_rgb = rgba_to_rgb_on_bg(im2, bg_rgb=bg_rgb)
172
+ out = io.BytesIO(); im2_rgb.save(out, format="JPEG", quality=88, subsampling=1)
173
+ return out.getvalue()
174
 
 
175
  def _parse_aspect_str(s: str):
176
  try:
177
  a, b = s.split(":"); return max(1, int(a)), max(1, int(b))
 
193
  box-shadow: 0 0 0 1px var(--outline) inset;
194
  }}
195
  .lb-frame img {{
196
+ width:100%; height:100%; object-fit:{fit_mode};
197
  display:block;
198
  }}
199
  .lb-video {{ display:flex; justify-content:center; }}
 
210
  filename_stub: str = "image",
211
  key_prefix: str = "",
212
  ):
 
213
  col.markdown(f'<div class="lb-card-title">{title}</div>', unsafe_allow_html=True)
214
 
 
215
  if not display_url and not display_bytes:
216
  col.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
217
  col.caption("—"); return None, None
218
 
219
  if display_bytes is not None:
220
+ src = image_bytes_to_data_url(display_bytes)
221
  col.markdown(f'<div class="lb-frame"><img src="{src}"/></div>', unsafe_allow_html=True)
222
  else:
223
  abs_url = _abs_backend_url(display_url)
224
  col.markdown(f'<div class="lb-frame"><img src="{abs_url}"/></div>', unsafe_allow_html=True)
225
 
 
226
  native = download_bytes or (fetch_bytes(download_url) if download_url else None)
227
+ if not native: native = display_bytes
 
228
 
229
  if native:
230
  sz = image_size_from_bytes(native)
 
239
 
240
  return display_url or "data", native
241
 
242
+ # ======================= Local demo =======================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def load_local_demo():
244
  demo = {}
245
  for fname in ["input.jpg", "packshot.jpg", "model.jpg", "tryon.mp4"]:
 
249
 
250
  demo_files = load_local_demo()
251
 
252
+ # ======================= Page =======================
253
  st.set_page_config(page_title="AI LightBox · Jewelry", layout="wide", page_icon="💎")
254
  st.title("💎 AI LightBox · Jewelry")
 
255
  st.caption("Upload. Try-on. Download.")
256
 
257
  ok = backend_ok()
258
+ use_rmbg = (st.session_state["health"].get("use_rmbg") if isinstance(st.session_state["health"], dict) else None) or "unknown"
259
+ version = st.session_state["health"].get("version", "—")
260
 
261
+ # -------- Top control bar --------
262
  col1, col2, col3, col4, col5, col6, col7 = st.columns([1.6, 1.6, 1.0, 1.2, 0.9, 1.1, 0.9])
263
  with col1:
264
  file_list = st.file_uploader("Product Image (Upload)", type=["jpg","jpeg","png","webp"], accept_multiple_files=True, key="file_upl")
 
278
 
279
  colA, colB, colC, colD, colE, colF = st.columns([1.0, 1.0, 1.1, 0.9, 0.9, 1.2])
280
  with colA:
281
+ st.info(f"Connection: {'Online' if ok else 'Offline'} · Backend v{version} · RMBG: {use_rmbg}", icon="🔌")
282
  with colB:
283
  identity_lock = st.checkbox("Identity lock", True, key="identity_lock")
284
  with colC:
 
290
  with colF:
291
  run = st.button("Run 💎", type="primary", use_container_width=True, key="run_btn")
292
 
293
+ # Canvas/frame
294
  colT1, colT2, colT3 = st.columns([1.0, 1.0, 1.0])
295
  with colT1:
296
  preview_aspect = st.selectbox("Preview Frame Ratio", ASPECT_OPTIONS, index=0, key="preview_aspect")
 
299
  with colT3:
300
  fit_mode = st.selectbox("Preview Layout", ["fit","fill"], index=0, help="Sadece önizlemeyi etkiler.", key="fit_mode")
301
 
 
302
  inject_preview_css(preview_aspect, fit_mode="contain" if fit_mode=="fit" else "cover")
303
 
304
+ # ======================= PRE-RUN PREVIEWS =======================
305
  st.subheader("Previews")
306
  col_in, col_pack, col_pad, col_vid = st.columns(4)
307
 
 
308
  input_bytes = None
309
  if file_list:
310
  try: input_bytes = file_list[0].getvalue()
 
321
  filename_stub="input", key_prefix="pre"
322
  )
323
 
 
324
  pack_bytes_demo = demo_files.get("packshot.jpg") or input_bytes
325
  show_tile_card_display_download(
326
  col_pack, "Sample Packshot (BG Removed)",
 
329
  filename_stub="packshot", key_prefix="pre"
330
  )
331
 
 
332
  padded_bytes = None
333
  if pack_bytes_demo:
334
  try:
335
+ # UI-only padded frame (local), not backend PAD
336
+ from math import isfinite
337
+ ratio_val = float(st.session_state.get("preview_ratio", 0.5))
338
+ ratio_val = max(0.10, min(0.99, ratio_val if isfinite(ratio_val) else 0.5))
339
+ # Use same helper as make_small_jpeg_from_native background for visual harmony
340
+ im = Image.open(io.BytesIO(pack_bytes_demo)).convert("RGBA")
341
+ aw, ah = (lambda s: (int(s.split(":")[0]), int(s.split(":")[1])))(st.session_state.get("preview_aspect","9:16"))
342
+ if aw >= ah:
343
+ W = int(st.session_state.get("preview_long_edge", 1920)); H = max(1, int(W * ah / aw))
344
+ else:
345
+ H = int(st.session_state.get("preview_long_edge", 1920)); W = max(1, int(H * aw / ah))
346
+ from PIL import ImageOps
347
+ w, h = im.size
348
+ target = int(min(W, H) * ratio_val if aw == ah else (H * ratio_val if aw < ah else W * ratio_val))
349
+ if w >= h: new_w, new_h = target, max(1, int(h * (target / max(1, w))))
350
+ else: new_h, new_w = target, max(1, int(w * (target / max(1, h))))
351
+ im_resized = im.resize((new_w, new_h), Image.LANCZOS)
352
+ canvas = Image.new("RGBA", (W, H), (255,255,255,255))
353
+ off = ((W - new_w)//2, (H - new_h)//2); canvas.paste(im_resized, off, im_resized)
354
+ out = io.BytesIO(); canvas.convert("RGB").save(out, format="JPEG", quality=90, subsampling=1)
355
+ padded_bytes = out.getvalue()
356
  except Exception:
357
  padded_bytes = None
358
+
359
  show_tile_card_display_download(
360
+ col_pad, "Sample Padded Preview",
361
  display_bytes=padded_bytes or pack_bytes_demo,
362
  download_bytes=padded_bytes or pack_bytes_demo,
363
  filename_stub="padded_ui", key_prefix="pre"
364
  )
365
 
 
366
  vid_demo = demo_files.get("tryon.mp4")
367
+ col_vid.markdown('<div class="lb-card-title">AI Generated Video Preview</div>', unsafe_allow_html=True)
368
  if vid_demo:
369
  data_url = "data:video/mp4;base64," + base64.b64encode(vid_demo).decode("ascii")
370
  col_vid.markdown(
 
381
  col_vid.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
382
  col_vid.caption("—")
383
 
384
+ # ======================= RUN =======================
385
  if run:
386
  if not ok:
387
  st.error("Backend erişilemiyor. API_BASE / TOKEN kontrol edin.")
 
397
 
398
  data = {
399
  "category": st.session_state.get("jewel_type","auto"),
400
+ "edit_prompt": "", # backend kendi packshot prompt’unu normalize ediyor
401
  "num_images": "1",
402
  "image_urls": img_urls,
403
  "mannequin_image_url": "",
404
  "identity_lock": "true" if identity_lock else "false",
405
+ # Preview/Pad controls
406
+ "preview_aspect": st.session_state.get("preview_aspect","9:16"),
407
+ "preview_long_edge": str(int(st.session_state.get("preview_long_edge", 1920))),
408
+ "preview_ratio": str(float(st.session_state.get("preview_ratio", 0.5))),
409
+ "padding_ratio": str(float(st.session_state.get("preview_ratio", 0.5))), # backward-compat
410
  # SR
411
  "upscale": "true" if upscale else "false",
412
  "upscale_factor": st.session_state.get("upscale_factor","2"),
413
  "upscale_stage": st.session_state.get("upscale_stage","both"),
414
+ # Video (optional inside chain)
415
  "to_video": "true" if to_video else "false",
416
  "video_prompt": "",
417
  "duration": st.session_state.get("duration_sel", VIDEO_DUR_OPTIONS[0]),
 
424
 
425
  st.session_state["job_counter"] += 1
426
 
427
+ # Parse outputs (v0.6.0)
428
+ pack_native_url = (out.get("packshot_step", {}).get("result", {}).get("images_native") or [{}])[0].get("url")
429
+ padded_native_url = (out.get("packshot_step", {}).get("result", {}).get("padded_native") or [{}])[0].get("url")
430
+ placed_native_url = (out.get("image_step", {}).get("result", {}).get("images_native") or [{}])[0].get("url")
431
+ vurl = (out.get("video_step") or {}).get("result", {}).get("video", {}).get("url")
432
+
433
+ # DISPLAY small JPGs (dark-friendly)
434
+ pack_display_jpeg = None
435
+ if pack_native_url:
436
+ pn = fetch_bytes(pack_native_url)
437
+ if pn: pack_display_jpeg = make_small_jpeg_from_native(pn, 1280, bg_rgb=(23,26,31))
438
+ padded_display_jpeg = None
439
+ if padded_native_url:
440
+ nb = fetch_bytes(padded_native_url)
441
+ if nb: padded_display_jpeg = make_small_jpeg_from_native(nb, 1280, bg_rgb=(23,26,31))
442
+ placed_display_jpeg = None
443
+ if placed_native_url:
444
+ mn = fetch_bytes(placed_native_url)
445
+ if mn: placed_display_jpeg = make_small_jpeg_from_native(mn, 1280, bg_rgb=(23,26,31))
446
+
447
+ # UI hints from /health for video width, else default
448
+ st.session_state["video_ui_max_px"] = st.session_state.get("video_ui_max_px", VIDEO_MAX_PX_DEFAULT)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
449
 
450
  st.session_state["results"] = {
451
  "job_id": out.get("job_id"),
 
459
  "video_url": vurl,
460
  "api_base": API_BASE,
461
  "has_auth_header": bool(HEADERS),
462
+ "preview_aspect": st.session_state.get("preview_aspect","9:16"),
463
  }
464
 
465
  except requests.HTTPError as e:
 
467
  except Exception as e:
468
  st.error(f"Hata: {e}")
469
 
470
+ # ======================= RESULTS =======================
471
  res = st.session_state.get("results")
472
  vbytes = None
473
  if res:
474
  st.subheader("Product Results")
475
  c_pack, c_pad, c_model, c_vid = st.columns(4)
476
 
 
477
  show_tile_card_display_download(
478
  c_pack, "Packshot (Removed BG)",
479
  display_bytes=res.get("packshot_display_jpeg"),
 
481
  filename_stub="packshot_native",
482
  key_prefix=f"job{st.session_state['job_counter']}"
483
  )
 
 
484
  show_tile_card_display_download(
485
  c_pad, "Padded",
486
  display_bytes=res.get("padded_display_jpeg"),
 
488
  filename_stub="padded_backend",
489
  key_prefix=f"job{st.session_state['job_counter']}"
490
  )
 
 
491
  show_tile_card_display_download(
492
  c_model, "TryON Model",
493
  display_bytes=res.get("placed_display_jpeg"),
 
496
  key_prefix=f"job{st.session_state['job_counter']}"
497
  )
498
 
 
499
  vurl = res.get("video_url")
500
  c_vid.markdown('<div class="lb-card-title">AI Generated Video</div>', unsafe_allow_html=True)
501
  if vurl:
 
530
  prompt_optimizer=False,
531
  )
532
  vurl2 = (v.get("result") or {}).get("video", {}).get("url")
 
533
  if vurl2:
534
  st.session_state["results"]["video_url"] = vurl2
 
 
535
  st.success("Video is Ready!.")
536
  else:
537
  st.info("Video URL gelmedi.")
538
 
539
+ # ZIP bundle
540
  named = []
541
  pn = fetch_bytes(res.get("packshot_native_url")) if res.get("packshot_native_url") else None
542
  mn = fetch_bytes(res.get("placed_native_url")) if res.get("placed_native_url") else None
 
544
  if mn: named.append((f"model_native{infer_ext(mn)}", mn))
545
  if vbytes: named.append(("video.mp4", vbytes))
546
  if named:
547
+ buf = io.BytesIO()
548
+ with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as z:
549
+ for fname, b in named:
550
+ if b: z.writestr(fname, b)
551
+ buf.seek(0)
552
+ st.download_button("Download All (ZIP)", data=buf.read(),
553
  file_name="ai_lightbox_outputs.zip", mime="application/zip",
554
  key=f"job{st.session_state['job_counter']}_zip_dl")
555
 
556
+ # ======================= Sidebar =======================
557
  with st.sidebar:
558
  st.caption(f"API_BASE: {API_BASE}")
559
  if HF_TOKEN: st.caption("Auth: Bearer (aktif)")
560
+ st.caption(f"Backend RMBG policy: {use_rmbg}")
561
  st.slider("Video önizleme genişliği (px)", 360, 1080, st.session_state["video_ui_max_px"],
562
  step=10, key="video_ui_max_px")
563
  if st.button("Önbelleği temizle"): st.cache_data.clear(); st.success("Önbellek temizlendi.")