renderfy commited on
Commit
8549301
·
verified ·
1 Parent(s): 5b30094

Upload streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +151 -334
streamlit_app.py CHANGED
@@ -1,5 +1,8 @@
1
- # streamlit_app.py — LamboVision (Car) UI · uniform 3:4 cards, dropdown configurator, sample previews
2
- # Works with your FastAPI backend (app.py). All preview/output tiles share the same 3:4 frame and use object-fit: contain.
 
 
 
3
 
4
  import os, io, base64, zipfile, requests, streamlit as st
5
  from PIL import Image
@@ -15,15 +18,14 @@ except Exception:
15
  pass
16
 
17
  # ================= Env & API =================
18
- API_BASE = (os.getenv("AI_LamboVision_API", "http://127.0.0.1:7860") or "http://127.0.0.1:7860").strip().strip("'\"").rstrip("/")
19
- HF_TOKEN = (os.getenv("AI_LamboVision_TOKEN", "") or "").strip().strip("'\"")
20
  HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
21
 
22
  VIDEO_MAX_PX_DEFAULT = int(os.getenv("VIDEO_MAX_PX", "720"))
23
  VIDEO_RES_OPTIONS = ["512P", "768P"]
24
  VIDEO_DUR_OPTIONS = ["6", "10"]
25
- # Default 3:4 for uniform desktop tiles; 9:16 also available
26
- ASPECT_OPTIONS = ["3:4", "9:16", "1:1", "16:9"]
27
 
28
  # ================= Session =================
29
  if "results" not in st.session_state:
@@ -33,7 +35,7 @@ if "job_counter" not in st.session_state:
33
  if "video_ui_max_px" not in st.session_state:
34
  st.session_state["video_ui_max_px"] = VIDEO_MAX_PX_DEFAULT
35
 
36
- # ================= Helpers =================
37
  def _needs_auth(url: str) -> bool:
38
  return url.startswith(API_BASE) or url.startswith("outputs/") or url.startswith("/outputs/")
39
 
@@ -56,20 +58,20 @@ def backend_ok() -> bool:
56
  except Exception:
57
  return False
58
 
59
- def post_chain(data: dict, files_payload):
60
- r = requests.post(f"{API_BASE}/v1/tryon/chain", data=data, files=files_payload or None,
61
  headers=HEADERS, timeout=600)
62
  r.raise_for_status()
63
  return r.json()
64
 
65
- def post_video(image_url: str, duration="6", resolution="768P", prompt_optimizer=False, preview_aspect="3:4", prompt_text=""):
66
  payload = {
67
  "image_url": image_url,
68
  "duration": duration,
69
  "resolution": resolution,
70
- "preview_aspect": preview_aspect,
71
- "prompt_optimizer": "true" if prompt_optimizer else "false",
72
  "prompt": prompt_text or "",
 
73
  }
74
  r = requests.post(f"{API_BASE}/v1/video/from-image", data=payload, headers=HEADERS, timeout=600)
75
  r.raise_for_status()
@@ -124,6 +126,7 @@ def make_zip(named_bytes: list[tuple[str, bytes]]) -> bytes:
124
  if b: z.writestr(fname, b)
125
  buf.seek(0); return buf.read()
126
 
 
127
  def _parse_aspect_str(s: str):
128
  try:
129
  a, b = s.split(":"); return max(1, int(a)), max(1, int(b))
@@ -131,25 +134,20 @@ def _parse_aspect_str(s: str):
131
  return (3, 4)
132
 
133
  def inject_base_css(card_fit_mode="contain"):
134
- # All frames share the same aspect via per-run CSS; images/videos use object-fit: contain to avoid overflow
135
  st.markdown(f"""
136
  <style>
137
  .stApp {{ background: #0e0f12; }}
138
  header[data-testid="stHeader"] {{ background: transparent; }}
139
  .block-container {{ padding-top: 1.0rem; }}
140
-
141
  h1, .stMarkdown h1 {{ font-size: 1.85rem; margin-bottom: 0.15rem; }}
142
  .stMarkdown p {{ margin-top: 0.1rem; }}
143
-
144
  label, .stTextInput label, .stSelectbox label, .stNumberInput label, .stFileUploader label,
145
  .stCheckbox label, .stSlider label, .stRadio label {{
146
  color: #ff8a33 !important; font-weight: 600 !important;
147
  }}
148
  .stButton > button[kind="primary"]{{ background:#ff7a1a !important; border:0 !important; color:#111 !important; }}
149
  .stButton > button:hover {{ filter: brightness(1.05); }}
150
-
151
  .lb-card-title {{ font-weight:700; font-size:1.05rem; margin:2px 0 8px 0; color:#eaecef; }}
152
-
153
  .lb-frame {{
154
  position: relative; width: 100%;
155
  border-radius: 12px; overflow: hidden;
@@ -172,96 +170,7 @@ def inject_preview_css(aspect: str):
172
  </style>
173
  """, unsafe_allow_html=True)
174
 
175
- def show_tile_card_display_download(
176
- col, title,
177
- display_url: str | None = None,
178
- display_bytes: bytes | None = None,
179
- download_url: str | None = None,
180
- download_bytes: bytes | None = None,
181
- filename_stub: str = "image",
182
- key_prefix: str = "",
183
- ):
184
- col.markdown(f'<div class="lb-card-title">{title}</div>', unsafe_allow_html=True)
185
- if not display_url and not display_bytes:
186
- col.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
187
- col.caption("—"); return None, None
188
- if display_bytes is not None:
189
- src = image_bytes_to_data_url(display_bytes)
190
- col.markdown(f'<div class="lb-frame"><img src="{src}"/></div>', unsafe_allow_html=True)
191
- else:
192
- abs_url = _abs_backend_url(display_url)
193
- col.markdown(f'<div class="lb-frame"><img src="{abs_url}"/></div>', unsafe_allow_html=True)
194
-
195
- native = download_bytes or (fetch_bytes(download_url) if download_url else None)
196
- if not native:
197
- native = display_bytes
198
- if native:
199
- sz = image_size_from_bytes(native)
200
- if sz: col.caption(f"Real Res: {sz[0]}×{sz[1]} px")
201
- ext = infer_ext(native)
202
- mime = "image/jpeg" if ext.lower() in [".jpg",".jpeg"] else ("image/png" if ext.lower()==".png" else "image/webp")
203
- col.download_button("Download (Full Quality)", data=native,
204
- file_name=f"{filename_stub}{ext if ext!='.bin' else '.jpg'}",
205
- mime=mime, key=f"{key_prefix}_{filename_stub}_dl")
206
- else:
207
- col.caption("—")
208
- return display_url or "data", native
209
-
210
- def rgba_to_rgb_on_bg(img_rgba: Image.Image, bg_rgb=(255,255,255)) -> Image.Image:
211
- if img_rgba.mode != "RGBA":
212
- return img_rgba.convert("RGB")
213
- bg = Image.new("RGBA", img_rgba.size, (*bg_rgb, 255))
214
- bg.paste(img_rgba, (0,0), img_rgba)
215
- return bg.convert("RGB")
216
-
217
- @st.cache_data(ttl=300, show_spinner=False)
218
- def make_small_jpeg_from_native(native: bytes, target_long_edge: int = 1280, bg_rgb=(255,255,255)) -> bytes:
219
- im = Image.open(io.BytesIO(native))
220
- if im.mode != "RGBA" and "transparency" not in im.info:
221
- im = im.convert("RGB")
222
- else:
223
- im = im.convert("RGBA")
224
- w, h = im.size
225
- if w >= h:
226
- new_w = min(target_long_edge, w)
227
- new_h = max(1, int(h * (new_w / max(1, w))))
228
- else:
229
- new_h = min(target_long_edge, h)
230
- new_w = max(1, int(w * (new_h / max(1, h))))
231
- im2 = im.resize((new_w, new_h), Image.LANCZOS)
232
- im2_rgb = rgba_to_rgb_on_bg(im2, bg_rgb=bg_rgb)
233
- out = io.BytesIO(); im2_rgb.save(out, format="JPEG", quality=88, subsampling=1)
234
- return out.getvalue()
235
-
236
- def make_preview_frame(img_bytes: bytes, aspect: str, long_edge: int, ratio: float, bg_rgb=(255,255,255)) -> bytes:
237
- im = Image.open(io.BytesIO(img_bytes)).convert("RGBA")
238
- a, b = _parse_aspect_str(aspect)
239
- if a >= b:
240
- W = max(256, min(8192, int(long_edge))); H = max(1, int(W * b / a))
241
- else:
242
- H = max(256, min(8192, int(long_edge))); W = max(1, int(H * a / b))
243
- ratio = max(0.10, min(0.99, float(ratio)))
244
- target = int(min(W, H) * ratio if a == b else (H * ratio if a < b else W * ratio))
245
- w, h = im.size
246
- if w >= h: new_w, new_h = target, max(1, int(h * (target / max(1, w))))
247
- else: new_h, new_w = target, max(1, int(w * (target / max(1, h))))
248
- im_resized = im.resize((new_w, new_h), Image.LANCZOS)
249
- canvas = Image.new("RGBA", (W, H), (*bg_rgb, 255))
250
- off = ((W - new_w)//2, (H - new_h)//2); canvas.paste(im_resized, off, im_resized)
251
- out = io.BytesIO(); canvas.convert("RGB").save(out, format="JPEG", quality=90, subsampling=1)
252
- return out.getvalue()
253
-
254
- # ================= Local demo assets (optional) =================
255
- def load_local_demo():
256
- demo = {}
257
- for fname in ["input.jpg", "packshot.jpg", "model.jpg", "tryon.mp4"]:
258
- if os.path.exists(fname):
259
- with open(fname, "rb") as f: demo[fname] = f.read()
260
- return demo
261
-
262
- demo_files = load_local_demo()
263
-
264
- # ================= Prompt builders =================
265
  def build_car_prompt(model_name: str, body_color: str, finish: str, wheel_style: str, caliper_color: str, extra: str = "") -> str:
266
  base = (
267
  "Catalog-ready studio photo of a Lamborghini from a three-quarter front view. "
@@ -287,56 +196,42 @@ SCENE_PRESETS = {
287
  "Monaco Sunset": "Monaco coastal boulevard at golden hour; gentle dolly-in; realistic paint reflections.",
288
  "Dubai Night": "Dubai Marina night city lights; lateral parallax; crisp highlights; clean reflections."
289
  }
290
-
291
  def build_video_prompt(scene_name: str, extra: str = "") -> str:
292
  base = SCENE_PRESETS.get(scene_name, "High-end studio, subtle parallax, natural camera micro-motion.")
293
  lock = " Keep logos and wheel circles intact; no wheel warping; no added text; realistic reflections."
294
- if extra.strip():
295
- return base + " " + lock + " " + extra.strip()
296
  return base + " " + lock
297
 
298
  # ================= Page =================
299
- st.set_page_config(page_title="LamboVision · Car Configurator", layout="wide", page_icon="🏎️")
300
  inject_base_css(card_fit_mode="contain")
301
 
302
  st.title("🏎️ LamboVision · AI Car Studio")
303
- st.caption("Configure a Lamborghini, then export studio images and 5–10s cinematic videos. All tiles share the same frame.")
304
 
305
  ok = backend_ok()
306
 
307
  # -------- Top control bar --------
308
- col1, col2, col3, col4, col5, col6, col7 = st.columns([1.6, 1.6, 1.0, 1.2, 0.9, 1.1, 0.9])
309
  with col1:
310
  file_list = st.file_uploader("Car Image (Upload)", type=["jpg","jpeg","png","webp"], accept_multiple_files=True, key="file_upl")
311
  with col2:
312
  image_url = st.text_input("Or URL", key="image_url", placeholder="https://... (optional)")
313
  with col3:
314
- category = st.selectbox("Category", ["auto","car","vehicle"], index=0, key="category")
315
  with col4:
316
- preview_ratio = st.number_input("Preview Scale (0.10–0.99)", min_value=0.10, max_value=0.99, value=0.60, step=0.01,
317
- help="Only affects the UI canvas fill.", key="preview_ratio")
318
  with col5:
319
- upscale = st.checkbox("Super Res", False, key="upscale")
320
  with col6:
321
- upscale_stage = st.selectbox("SR Step", ["both","final","packshot"], index=0, help="Default: both", key="upscale_stage")
322
- with col7:
323
- upscale_factor = st.selectbox("SR Factor", ["2","4"], index=0, key="upscale_factor")
324
-
325
- colA, colB, colC, colD, colE, colF = st.columns([1.0, 1.0, 1.1, 0.9, 0.9, 1.2])
326
- with colA:
327
- st.info(f"Connection: {'Online' if ok else 'Offline'}", icon="🔌")
328
- with colB:
329
- identity_lock = st.checkbox("Identity lock", True, key="identity_lock")
330
- with colC:
331
- to_video = st.checkbox("One Click Generate Video", False, key="to_video")
332
- with colD:
333
- duration = st.selectbox("Duration ", VIDEO_DUR_OPTIONS, index=0, key="duration_sel")
334
- with colE:
335
  resolution = st.selectbox("Video Res", VIDEO_RES_OPTIONS, index=1, key="resolution_sel")
336
- with colF:
337
  run = st.button("Run 🏁", type="primary", use_container_width=True, key="run_btn")
338
 
339
- # -------- Configurator row (dropdowns + custom) --------
 
 
 
340
  st.markdown("### Configurator")
341
 
342
  MODEL_CHOICES = [
@@ -354,7 +249,7 @@ WHEEL_CHOICES = [
354
  ]
355
  CALIPER_CHOICES = ["yellow", "red", "black", "green", "silver", "Custom…"]
356
 
357
- c1, c2, c3, c4, c5, c6 = st.columns([1.3, 1.1, 0.9, 1.2, 1.0, 1.2])
358
 
359
  with c1:
360
  model_sel = st.selectbox("Model", MODEL_CHOICES, index=0, key="cfg_model_sel")
@@ -378,24 +273,17 @@ with c5:
378
  with c6:
379
  extra_prompt = st.text_input("Extra (optional)", value="", placeholder="stripe delete, studio floor reflection, …", key="cfg_extra")
380
 
381
- # -------- Scene presets for video + frame controls --------
382
- st.markdown("### Scene & Frame")
383
- s1, s2, s3, s4 = st.columns([1.2, 1.2, 1.1, 1.1])
384
- with s1:
385
- scene_name = st.selectbox("Scene", list(SCENE_PRESETS.keys()), index=0, key="scene_name")
386
- with s2:
387
- scene_extra = st.text_input("Scene extra (optional)", value="", key="scene_extra")
388
- with s3:
389
- preview_aspect = st.selectbox("Tile Aspect", ASPECT_OPTIONS, index=0, key="preview_aspect") # default 3:4
390
- with s4:
391
- preview_long_edge = st.number_input("Tile Long Edge (px)", min_value=256, max_value=8192, value=1536, step=64, key="preview_long_edge")
392
-
393
- inject_preview_css(preview_aspect) # Ensures all tiles have the exact same aspect
394
- st.caption("All preview and result cards share the same frame. Images and videos are fit inside; no overflow.")
395
 
396
- # ================= PRE-RUN SAMPLE PREVIEWS =================
397
  st.subheader("Sample Previews")
398
- col_in, col_pack, col_pad, col_vid = st.columns(4)
399
 
400
  input_bytes = None
401
  if file_list:
@@ -406,40 +294,32 @@ elif image_url:
406
  elif demo_files.get("input.jpg"):
407
  input_bytes = demo_files["input.jpg"]
408
 
409
- show_tile_card_display_download(
410
- col_in, "Sample Input",
411
- display_bytes=input_bytes if input_bytes else demo_files.get("input.jpg"),
412
- download_bytes=input_bytes if input_bytes else demo_files.get("input.jpg"),
413
- filename_stub="input", key_prefix="pre"
414
- )
415
-
416
- pack_bytes_demo = demo_files.get("packshot.jpg") or input_bytes
417
- show_tile_card_display_download(
418
- col_pack, "Sample Packshot (Studio)",
419
- display_bytes=pack_bytes_demo,
420
- download_bytes=pack_bytes_demo,
421
- filename_stub="packshot", key_prefix="pre"
422
- )
423
-
424
- padded_bytes = None
425
- if pack_bytes_demo:
426
- try:
427
- padded_bytes = make_preview_frame(pack_bytes_demo, aspect=preview_aspect,
428
- long_edge=int(preview_long_edge),
429
- ratio=float(preview_ratio))
430
- except Exception:
431
- padded_bytes = None
432
- show_tile_card_display_download(
433
- col_pad, "Sample Padded UI",
434
- display_bytes=padded_bytes or pack_bytes_demo,
435
- download_bytes=padded_bytes or pack_bytes_demo,
436
- filename_stub="padded_ui", key_prefix="pre"
437
- )
438
-
439
- vid_demo = demo_files.get("tryon.mp4")
440
- col_vid.markdown('<div class="lb-card-title">Sample Video Loop</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(
444
  f"""
445
  <div class="lb-frame">
@@ -449,12 +329,19 @@ if vid_demo:
449
  </div>
450
  """, unsafe_allow_html=True
451
  )
452
- col_vid.download_button("Download Video (MP4)", data=vid_demo, file_name="tryon.mp4", mime="video/mp4", key="pre_video_dl")
453
  else:
454
  col_vid.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
455
  col_vid.caption("—")
456
 
457
- # ================= RUN =================
 
 
 
 
 
 
 
458
  if run:
459
  if not ok:
460
  st.error("Backend not reachable. Check API_BASE / TOKEN.")
@@ -462,99 +349,56 @@ if run:
462
  st.error("Provide at least one input image (upload or URL).")
463
  else:
464
  try:
465
- # Build edit prompt from configurator
466
- edit_prompt = build_car_prompt(
467
- model_name=model_name if model_name else "Lamborghini",
468
- body_color=body_color if body_color else "Verde Ithaca",
469
- finish=finish,
470
- wheel_style=wheel_style if wheel_style else "lightweight forged",
471
- caliper_color=caliper_color if caliper_color else "yellow",
472
- extra=extra_prompt
473
- )
474
-
475
- img_urls = image_url or ""
476
  files_payload = []
477
  if file_list:
478
  for f in file_list:
479
  files_payload.append(("files", (f.name, f.getvalue(), f.type or "image/jpeg")))
480
 
481
- data = {
482
- "category": category,
483
- "edit_prompt": edit_prompt,
484
- "num_images": "1",
485
- "image_urls": img_urls,
486
- "mannequin_image_url": "",
487
- "identity_lock": "true" if identity_lock else "false",
488
- # Preview controls — the backend also uses these for padding/preview
489
- "preview_aspect": preview_aspect,
490
- "preview_long_edge": str(int(preview_long_edge)),
491
- "preview_ratio": str(float(preview_ratio)),
492
- "padding_ratio": str(float(preview_ratio)),
493
- # SR
494
- "upscale": "true" if upscale else "false",
495
- "upscale_factor": st.session_state.get("upscale_factor","2"),
496
- "upscale_stage": st.session_state.get("upscale_stage","both"),
497
- # Video (optional)
498
- "to_video": "true" if to_video else "false",
499
- "video_prompt": build_video_prompt(scene_name, scene_extra) if to_video else "",
500
- "duration": st.session_state.get("duration_sel", VIDEO_DUR_OPTIONS[0]),
501
- "resolution": st.session_state.get("resolution_sel", VIDEO_RES_OPTIONS[1]),
502
- "prompt_optimizer": "false",
503
- }
504
 
505
- with st.spinner("Running LamboVision chain…"):
506
- out = post_chain(data, files_payload if files_payload else None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
507
 
508
  st.session_state["job_counter"] += 1
509
-
510
- # ---- Outputs ----
511
- pack_native_url = None; pack_display_jpeg = None
512
- try:
513
- pack_native_url = (out["packshot_step"]["result"]["images_native"] or [{}])[0].get("url")
514
- if pack_native_url:
515
- pn = fetch_bytes(pack_native_url)
516
- if pn: pack_display_jpeg = make_small_jpeg_from_native(pn, 1280, bg_rgb=(255,255,255))
517
- except Exception: pass
518
-
519
- padded_native_url = None; padded_display_jpeg = None
520
- try:
521
- padded_native_url = (out["packshot_step"]["result"]["padded_native"] or [{}])[0].get("url")
522
- if padded_native_url:
523
- nb = fetch_bytes(padded_native_url)
524
- if nb: padded_display_jpeg = make_small_jpeg_from_native(nb, 1280, bg_rgb=(255,255,255))
525
- except Exception: pass
526
-
527
- placed_native_url = None; placed_display_jpeg = None
528
- try:
529
- placed_native_url = (out.get("image_step") or {}).get("result", {}).get("images_native", [{}])[0].get("url")
530
- if placed_native_url:
531
- mn = fetch_bytes(placed_native_url)
532
- if mn: placed_display_jpeg = make_small_jpeg_from_native(mn, 1280, bg_rgb=(255,255,255))
533
- except Exception: pass
534
-
535
- vurl = None
536
- try:
537
- vurl = (out.get("video_step") or {}).get("result", {}).get("video", {}).get("url")
538
- except Exception:
539
- vurl = None
540
-
541
- ui_hints = (out.get("video_step") or {}).get("ui_hints") or {}
542
- if isinstance(ui_hints, dict):
543
- st.session_state["video_ui_max_px"] = int(ui_hints.get("suggested_video_max_px", VIDEO_MAX_PX_DEFAULT))
544
-
545
  st.session_state["results"] = {
546
- "job_id": out.get("job_id"),
547
- "schema_version": out.get("schema_version"),
548
- "packshot_native_url": pack_native_url,
549
- "packshot_display_jpeg": pack_display_jpeg,
550
- "padded_native_url": padded_native_url,
551
- "padded_display_jpeg": padded_display_jpeg,
552
- "placed_native_url": placed_native_url,
553
- "placed_display_jpeg": placed_display_jpeg,
554
  "video_url": vurl,
555
  "api_base": API_BASE,
556
- "has_auth_header": bool(HEADERS),
557
- "preview_aspect": preview_aspect,
558
  }
559
 
560
  except requests.HTTPError as e:
@@ -567,32 +411,29 @@ res = st.session_state.get("results")
567
  vbytes = None
568
  if res:
569
  st.subheader("Results")
570
- c_pack, c_pad, c_model, c_vid = st.columns(4)
571
-
572
- show_tile_card_display_download(
573
- c_pack, "Packshot (Studio)",
574
- display_bytes=res.get("packshot_display_jpeg"),
575
- download_url=res.get("packshot_native_url"),
576
- filename_stub="packshot_native",
577
- key_prefix=f"job{st.session_state['job_counter']}"
578
- )
579
-
580
- show_tile_card_display_download(
581
- c_pad, "Padded",
582
- display_bytes=res.get("padded_display_jpeg"),
583
- download_url=res.get("padded_native_url"),
584
- filename_stub="padded_backend",
585
- key_prefix=f"job{st.session_state['job_counter']}"
586
- )
587
-
588
- show_tile_card_display_download(
589
- c_model, "Composite",
590
- display_bytes=res.get("placed_display_jpeg"),
591
- download_url=res.get("placed_native_url"),
592
- filename_stub="composite_native",
593
- key_prefix=f"job{st.session_state['job_counter']}"
594
- )
595
-
596
  c_vid.markdown('<div class="lb-card-title">AI Generated Video</div>', unsafe_allow_html=True)
597
  vurl = res.get("video_url")
598
  if vurl:
@@ -613,45 +454,14 @@ if res:
613
  mime="video/mp4", key=f"job{st.session_state['job_counter']}_video_dl")
614
  else:
615
  c_vid.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
616
- vid_checkbox_key = f"video_toggle_job{st.session_state['job_counter']}"
617
- if st.checkbox("Generate Video From This Result", value=False, key=vid_checkbox_key):
618
- src_for_video = res.get("packshot_native_url") or res.get("placed_native_url")
619
- if not src_for_video:
620
- st.warning("No image found for video.")
621
- else:
622
- with st.spinner("Generating Video …"):
623
- try:
624
- v = post_video(
625
- src_for_video,
626
- duration=st.session_state.get("duration_sel", VIDEO_DUR_OPTIONS[0]),
627
- resolution=st.session_state.get("resolution_sel", VIDEO_RES_OPTIONS[1]),
628
- preview_aspect=st.session_state.get("preview_aspect","3:4"),
629
- prompt_text=build_video_prompt(st.session_state.get("scene_name","Studio Cinematic"),
630
- st.session_state.get("scene_extra","")),
631
- prompt_optimizer=False,
632
- )
633
- except requests.HTTPError as e:
634
- st.error(f"HTTP {e.response.status_code}")
635
- v = None
636
- if v:
637
- vurl2 = (v.get("result") or {}).get("video", {}).get("url")
638
- ui_hints = v.get("ui_hints") or {}
639
- if vurl2:
640
- st.session_state["results"]["video_url"] = vurl2
641
- if isinstance(ui_hints, dict):
642
- st.session_state["video_ui_max_px"] = int(ui_hints.get("suggested_video_max_px", VIDEO_MAX_PX_DEFAULT))
643
- st.session_state.pop(vid_checkbox_key, None)
644
- st.success("Video is ready.")
645
- st.rerun()
646
- else:
647
- st.info("Video URL not returned.")
648
-
649
- # ZIP
650
  named = []
651
- pn = fetch_bytes(res.get("packshot_native_url")) if res.get("packshot_native_url") else None
652
- mn = fetch_bytes(res.get("placed_native_url")) if res.get("placed_native_url") else None
653
- if pn: named.append((f"packshot_native{infer_ext(pn)}", pn))
654
- if mn: named.append((f"composite_native{infer_ext(mn)}", mn))
655
  if vbytes: named.append(("video.mp4", vbytes))
656
  if named:
657
  zip_bytes = make_zip(named)
@@ -659,11 +469,18 @@ if res:
659
  file_name="lambovision_outputs.zip", mime="application/zip",
660
  key=f"job{st.session_state['job_counter']}_zip_dl")
661
 
 
 
 
 
 
 
 
 
662
  # ================= Sidebar =================
663
  with st.sidebar:
664
  st.caption(f"API_BASE: {API_BASE}")
665
  if HF_TOKEN: st.caption("Auth: Bearer (active)")
666
- st.slider("Video preview width (px)", 360, 1080, st.session_state["video_ui_max_px"],
667
- step=10, key="video_ui_max_px")
668
  if st.button("Clear cache"): st.cache_data.clear(); st.success("Cache cleared.")
669
  if st.button("Clear results"): st.session_state["results"] = None; st.success("Cleared.")
 
1
+ # streamlit_app.py — LamboVision · AI Car Studio (Automotive, 3-step flow, no padded)
2
+ # Step 1: Gallery (clean packshot, native)
3
+ # Step 2: AI Composition (config prompt, native)
4
+ # Step 3: AI Generated Video (from composition native)
5
+ # Uniform tiles by CSS aspect; images/videos fit via object-fit: contain. No padding images are generated.
6
 
7
  import os, io, base64, zipfile, requests, streamlit as st
8
  from PIL import Image
 
18
  pass
19
 
20
  # ================= Env & API =================
21
+ API_BASE = (os.getenv("AI_LIGHTBOX_API", "http://127.0.0.1:7860") or "http://127.0.0.1:7860").strip().strip("'\"").rstrip("/")
22
+ HF_TOKEN = (os.getenv("AI_LIGHTBOX_TOKEN", "") or "").strip().strip("'\"")
23
  HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
24
 
25
  VIDEO_MAX_PX_DEFAULT = int(os.getenv("VIDEO_MAX_PX", "720"))
26
  VIDEO_RES_OPTIONS = ["512P", "768P"]
27
  VIDEO_DUR_OPTIONS = ["6", "10"]
28
+ ASPECT_OPTIONS = ["3:4", "9:16", "1:1", "16:9"] # visual frame only
 
29
 
30
  # ================= Session =================
31
  if "results" not in st.session_state:
 
35
  if "video_ui_max_px" not in st.session_state:
36
  st.session_state["video_ui_max_px"] = VIDEO_MAX_PX_DEFAULT
37
 
38
+ # ================= HTTP helpers =================
39
  def _needs_auth(url: str) -> bool:
40
  return url.startswith(API_BASE) or url.startswith("outputs/") or url.startswith("/outputs/")
41
 
 
58
  except Exception:
59
  return False
60
 
61
+ def post_image_edit(data: dict, files_payload):
62
+ r = requests.post(f"{API_BASE}/v1/image/edit", data=data, files=files_payload or None,
63
  headers=HEADERS, timeout=600)
64
  r.raise_for_status()
65
  return r.json()
66
 
67
+ def post_video(image_url: str, duration="6", resolution="768P", aspect="3:4", prompt_text="", prompt_optimizer=False):
68
  payload = {
69
  "image_url": image_url,
70
  "duration": duration,
71
  "resolution": resolution,
72
+ "aspect": aspect,
 
73
  "prompt": prompt_text or "",
74
+ "prompt_optimizer": "true" if prompt_optimizer else "false",
75
  }
76
  r = requests.post(f"{API_BASE}/v1/video/from-image", data=payload, headers=HEADERS, timeout=600)
77
  r.raise_for_status()
 
126
  if b: z.writestr(fname, b)
127
  buf.seek(0); return buf.read()
128
 
129
+ # ================= UI CSS =================
130
  def _parse_aspect_str(s: str):
131
  try:
132
  a, b = s.split(":"); return max(1, int(a)), max(1, int(b))
 
134
  return (3, 4)
135
 
136
  def inject_base_css(card_fit_mode="contain"):
 
137
  st.markdown(f"""
138
  <style>
139
  .stApp {{ background: #0e0f12; }}
140
  header[data-testid="stHeader"] {{ background: transparent; }}
141
  .block-container {{ padding-top: 1.0rem; }}
 
142
  h1, .stMarkdown h1 {{ font-size: 1.85rem; margin-bottom: 0.15rem; }}
143
  .stMarkdown p {{ margin-top: 0.1rem; }}
 
144
  label, .stTextInput label, .stSelectbox label, .stNumberInput label, .stFileUploader label,
145
  .stCheckbox label, .stSlider label, .stRadio label {{
146
  color: #ff8a33 !important; font-weight: 600 !important;
147
  }}
148
  .stButton > button[kind="primary"]{{ background:#ff7a1a !important; border:0 !important; color:#111 !important; }}
149
  .stButton > button:hover {{ filter: brightness(1.05); }}
 
150
  .lb-card-title {{ font-weight:700; font-size:1.05rem; margin:2px 0 8px 0; color:#eaecef; }}
 
151
  .lb-frame {{
152
  position: relative; width: 100%;
153
  border-radius: 12px; overflow: hidden;
 
170
  </style>
171
  """, unsafe_allow_html=True)
172
 
173
+ # ================= Prompts (builder) =================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  def build_car_prompt(model_name: str, body_color: str, finish: str, wheel_style: str, caliper_color: str, extra: str = "") -> str:
175
  base = (
176
  "Catalog-ready studio photo of a Lamborghini from a three-quarter front view. "
 
196
  "Monaco Sunset": "Monaco coastal boulevard at golden hour; gentle dolly-in; realistic paint reflections.",
197
  "Dubai Night": "Dubai Marina night city lights; lateral parallax; crisp highlights; clean reflections."
198
  }
 
199
  def build_video_prompt(scene_name: str, extra: str = "") -> str:
200
  base = SCENE_PRESETS.get(scene_name, "High-end studio, subtle parallax, natural camera micro-motion.")
201
  lock = " Keep logos and wheel circles intact; no wheel warping; no added text; realistic reflections."
202
+ if extra.strip(): return base + " " + lock + " " + extra.strip()
 
203
  return base + " " + lock
204
 
205
  # ================= Page =================
206
+ st.set_page_config(page_title="LamboVision · AI Car Studio", layout="wide", page_icon="🏎️")
207
  inject_base_css(card_fit_mode="contain")
208
 
209
  st.title("🏎️ LamboVision · AI Car Studio")
210
+ st.caption("Step 1: Gallery (clean packshot) · Step 2: AI Composition (config) · Step 3: AI Generated Video")
211
 
212
  ok = backend_ok()
213
 
214
  # -------- Top control bar --------
215
+ col1, col2, col3, col4, col5, col6, col7 = st.columns([1.6, 1.6, 1.1, 1.1, 1.0, 1.1, 1.1])
216
  with col1:
217
  file_list = st.file_uploader("Car Image (Upload)", type=["jpg","jpeg","png","webp"], accept_multiple_files=True, key="file_upl")
218
  with col2:
219
  image_url = st.text_input("Or URL", key="image_url", placeholder="https://... (optional)")
220
  with col3:
221
+ preview_aspect = st.selectbox("Tile Aspect", ASPECT_OPTIONS, index=0, key="preview_aspect") # only frame
222
  with col4:
223
+ to_video = st.checkbox("Generate Video", False, key="to_video")
 
224
  with col5:
225
+ duration = st.selectbox("Video Duration", VIDEO_DUR_OPTIONS, index=0, key="duration_sel")
226
  with col6:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  resolution = st.selectbox("Video Res", VIDEO_RES_OPTIONS, index=1, key="resolution_sel")
228
+ with col7:
229
  run = st.button("Run 🏁", type="primary", use_container_width=True, key="run_btn")
230
 
231
+ inject_preview_css(preview_aspect)
232
+ st.caption("Tiles share the same aspect ratio (CSS). Images and videos fit; no overflow. No padded images are generated.")
233
+
234
+ # -------- Configurator (dropdowns + custom) --------
235
  st.markdown("### Configurator")
236
 
237
  MODEL_CHOICES = [
 
249
  ]
250
  CALIPER_CHOICES = ["yellow", "red", "black", "green", "silver", "Custom…"]
251
 
252
+ c1, c2, c3, c4, c5, c6 = st.columns([1.3, 1.1, 0.9, 1.2, 1.0, 1.4])
253
 
254
  with c1:
255
  model_sel = st.selectbox("Model", MODEL_CHOICES, index=0, key="cfg_model_sel")
 
273
  with c6:
274
  extra_prompt = st.text_input("Extra (optional)", value="", placeholder="stripe delete, studio floor reflection, …", key="cfg_extra")
275
 
276
+ # -------- Sample Previews (no padded) --------
277
+ def load_local_demo():
278
+ demo = {}
279
+ for fname in ["input.jpg", "packshot.jpg", "tryon.mp4"]:
280
+ if os.path.exists(fname):
281
+ with open(fname, "rb") as f: demo[fname] = f.read()
282
+ return demo
283
+ demo_files = load_local_demo()
 
 
 
 
 
 
284
 
 
285
  st.subheader("Sample Previews")
286
+ col_in, col_gallery, col_comp, col_vid = st.columns(4)
287
 
288
  input_bytes = None
289
  if file_list:
 
294
  elif demo_files.get("input.jpg"):
295
  input_bytes = demo_files["input.jpg"]
296
 
297
+ def show_card(col, title, display_bytes=None, download_bytes=None, url=None, fname="image"):
298
+ col.markdown(f'<div class="lb-card-title">{title}</div>', unsafe_allow_html=True)
299
+ if display_bytes is not None:
300
+ src = "data:" + (_sniff_mime_from_bytes(display_bytes)) + ";base64," + base64.b64encode(display_bytes).decode("ascii")
301
+ col.markdown(f'<div class="lb-frame"><img src="{src}"/></div>', unsafe_allow_html=True)
302
+ elif url:
303
+ abs_url = _abs_backend_url(url)
304
+ col.markdown(f'<div class="lb-frame"><img src="{abs_url}"/></div>', unsafe_allow_html=True)
305
+ else:
306
+ col.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
307
+ col.caption("—"); return
308
+ native = download_bytes or (fetch_bytes(url) if url else display_bytes)
309
+ if native:
310
+ sz = image_size_from_bytes(native)
311
+ if sz: col.caption(f"Real Res: {sz[0]}×{sz[1]} px")
312
+ ext = infer_ext(native)
313
+ mime = "image/jpeg" if ext in [".jpg",".jpeg"] else ("image/png" if ext==".png" else "image/webp")
314
+ col.download_button("Download (Full Quality)", data=native, file_name=f"{fname}{ext if ext!='.bin' else '.jpg'}", mime=mime)
315
+
316
+ show_card(col_in, "Input", display_bytes=input_bytes or demo_files.get("input.jpg"), download_bytes=input_bytes or demo_files.get("input.jpg"), fname="input")
317
+ show_card(col_gallery, "Gallery", display_bytes=demo_files.get("packshot.jpg") or input_bytes, download_bytes=demo_files.get("packshot.jpg") or input_bytes, fname="gallery")
318
+ show_card(col_comp, "AI Composition", display_bytes=demo_files.get("packshot.jpg") or input_bytes, download_bytes=demo_files.get("packshot.jpg") or input_bytes, fname="ai_composition")
319
+
320
+ col_vid.markdown('<div class="lb-card-title">AI Generated Video</div>', unsafe_allow_html=True)
321
+ if demo_files.get("tryon.mp4"):
322
+ data_url = "data:video/mp4;base64," + base64.b64encode(demo_files["tryon.mp4"]).decode("ascii")
 
 
 
 
 
 
 
 
323
  col_vid.markdown(
324
  f"""
325
  <div class="lb-frame">
 
329
  </div>
330
  """, unsafe_allow_html=True
331
  )
332
+ col_vid.download_button("Download Video (MP4)", data=demo_files["tryon.mp4"], file_name="tryon.mp4", mime="video/mp4")
333
  else:
334
  col_vid.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
335
  col_vid.caption("—")
336
 
337
+ # ================= RUN (3-step chain, native only) =================
338
+ def make_gallery_payload():
339
+ return {"category": "auto", "prompt": "", "num_images": "1", "upscale": "false", "upscale_factor": "2"}
340
+
341
+ def make_composition_payload(edit_prompt, upscale=False, upscale_factor="2"):
342
+ return {"category": "auto", "prompt": edit_prompt, "num_images": "1",
343
+ "upscale": "true" if upscale else "false", "upscale_factor": upscale_factor}
344
+
345
  if run:
346
  if not ok:
347
  st.error("Backend not reachable. Check API_BASE / TOKEN.")
 
349
  st.error("Provide at least one input image (upload or URL).")
350
  else:
351
  try:
 
 
 
 
 
 
 
 
 
 
 
352
  files_payload = []
353
  if file_list:
354
  for f in file_list:
355
  files_payload.append(("files", (f.name, f.getvalue(), f.type or "image/jpeg")))
356
 
357
+ # Step 1: Gallery (clean)
358
+ g_payload = make_gallery_payload()
359
+ if image_url: g_payload["image_urls"] = image_url
360
+ out_gallery = post_image_edit(g_payload, files_payload if files_payload else None)
361
+ gallery_native_url = (out_gallery["result"]["images_native"] or [{}])[0].get("url") if out_gallery else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
 
363
+ # Step 2: AI Composition (config)
364
+ edit_prompt = build_car_prompt(
365
+ model_name=model_name or "Lamborghini",
366
+ body_color=body_color or "Verde Ithaca",
367
+ finish=finish,
368
+ wheel_style=wheel_style or "lightweight forged",
369
+ caliper_color=caliper_color or "yellow",
370
+ extra=extra_prompt or ""
371
+ )
372
+ c_payload = make_composition_payload(edit_prompt, upscale=False, upscale_factor="2")
373
+ c_payload["image_urls"] = gallery_native_url or "" # pass /outputs/* back; backend re-uploads to fal
374
+ out_comp = post_image_edit(c_payload, files_payload=None)
375
+ composition_native_url = (out_comp["result"]["images_native"] or [{}])[0].get("url") if out_comp else None
376
+
377
+ # Step 3: Video (optional)
378
+ vurl = None; ui_hints = {}
379
+ if st.session_state.get("to_video", False) and (composition_native_url or gallery_native_url):
380
+ video_prompt = build_video_prompt(st.session_state.get("scene_name","Studio Cinematic"),
381
+ st.session_state.get("scene_extra",""))
382
+ v = post_video(
383
+ composition_native_url or gallery_native_url,
384
+ duration=st.session_state.get("duration_sel","6"),
385
+ resolution=st.session_state.get("resolution_sel","768P"),
386
+ aspect=st.session_state.get("preview_aspect","3:4"),
387
+ prompt_text=video_prompt,
388
+ prompt_optimizer=False,
389
+ )
390
+ vurl = (v.get("result") or {}).get("video", {}).get("url")
391
+ ui_hints = v.get("ui_hints") or {}
392
+ if isinstance(ui_hints, dict):
393
+ st.session_state["video_ui_max_px"] = int(ui_hints.get("suggested_video_max_px", VIDEO_MAX_PX_DEFAULT))
394
 
395
  st.session_state["job_counter"] += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
396
  st.session_state["results"] = {
397
+ "gallery_native_url": gallery_native_url,
398
+ "composition_native_url": composition_native_url,
 
 
 
 
 
 
399
  "video_url": vurl,
400
  "api_base": API_BASE,
401
+ "preview_aspect": st.session_state.get("preview_aspect","3:4"),
 
402
  }
403
 
404
  except requests.HTTPError as e:
 
411
  vbytes = None
412
  if res:
413
  st.subheader("Results")
414
+ c_gallery, c_comp, c_vid = st.columns(3)
415
+
416
+ # Gallery (native only)
417
+ def show_card_url(col, title, url, fname):
418
+ col.markdown(f'<div class="lb-card-title">{title}</div>', unsafe_allow_html=True)
419
+ if url:
420
+ abs_url = _abs_backend_url(url)
421
+ col.markdown(f'<div class="lb-frame"><img src="{abs_url}"/></div>', unsafe_allow_html=True)
422
+ nb = fetch_bytes(abs_url)
423
+ if nb:
424
+ sz = image_size_from_bytes(nb)
425
+ if sz: col.caption(f"Real Res: {sz[0]}×{sz[1]} px")
426
+ ext = infer_ext(nb)
427
+ mime = "image/jpeg" if ext in [".jpg",".jpeg"] else ("image/png" if ext==".png" else "image/webp")
428
+ col.download_button("Download (Full Quality)", data=nb, file_name=f"{fname}{ext if ext!='.bin' else '.jpg'}", mime=mime)
429
+ else:
430
+ col.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
431
+ col.caption("—")
432
+
433
+ show_card_url(c_gallery, "Gallery", res.get("gallery_native_url"), "gallery_native")
434
+ show_card_url(c_comp, "AI Composition", res.get("composition_native_url"), "ai_composition_native")
435
+
436
+ # Video
 
 
 
437
  c_vid.markdown('<div class="lb-card-title">AI Generated Video</div>', unsafe_allow_html=True)
438
  vurl = res.get("video_url")
439
  if vurl:
 
454
  mime="video/mp4", key=f"job{st.session_state['job_counter']}_video_dl")
455
  else:
456
  c_vid.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
457
+ c_vid.caption("—")
458
+
459
+ # ZIP bundle
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
460
  named = []
461
+ gnat = fetch_bytes(res.get("gallery_native_url")) if res.get("gallery_native_url") else None
462
+ cnat = fetch_bytes(res.get("composition_native_url")) if res.get("composition_native_url") else None
463
+ if gnat: named.append((f"gallery_native{infer_ext(gnat)}", gnat))
464
+ if cnat: named.append((f"ai_composition_native{infer_ext(cnat)}", cnat))
465
  if vbytes: named.append(("video.mp4", vbytes))
466
  if named:
467
  zip_bytes = make_zip(named)
 
469
  file_name="lambovision_outputs.zip", mime="application/zip",
470
  key=f"job{st.session_state['job_counter']}_zip_dl")
471
 
472
+ # ================= Scene controls (moved under results to avoid clutter) =================
473
+ st.markdown("### Scene")
474
+ s1, s2 = st.columns([1.2, 1.8])
475
+ with s1:
476
+ scene_name = st.selectbox("Scene preset", list(SCENE_PRESETS.keys()), index=0, key="scene_name")
477
+ with s2:
478
+ scene_extra = st.text_input("Scene extra (optional)", value="", key="scene_extra")
479
+
480
  # ================= Sidebar =================
481
  with st.sidebar:
482
  st.caption(f"API_BASE: {API_BASE}")
483
  if HF_TOKEN: st.caption("Auth: Bearer (active)")
484
+ st.slider("Video preview width (px)", 360, 1080, st.session_state["video_ui_max_px"], step=10, key="video_ui_max_px")
 
485
  if st.button("Clear cache"): st.cache_data.clear(); st.success("Cache cleared.")
486
  if st.button("Clear results"): st.session_state["results"] = None; st.success("Cleared.")