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

Upload streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +278 -267
streamlit_app.py CHANGED
@@ -1,11 +1,10 @@
1
- # streamlit_app.py — LamboVision · AI Car Studio (uniform cards) v0.6.4
2
- # All cards have identical size; images/videos are fit inside the frame (no overflow).
3
- # Default aspect is 3:4 (less tall), but user can switch to 9:16 or 1:1.
4
 
5
  import os, io, base64, zipfile, requests, streamlit as st
6
  from PIL import Image
7
 
8
- # ==== Theming (dark + orange) ====
9
  try:
10
  st._config.set_option("theme.base", "dark")
11
  st._config.set_option("theme.primaryColor", "#ff7a1a")
@@ -15,18 +14,18 @@ try:
15
  except Exception:
16
  pass
17
 
18
- # ==== Env & API ====
19
- API_BASE = (os.getenv("AI_LamboVision_API", "http://127.0.0.1:8000") or "http://127.0.0.1:8000").strip().strip("'\"").rstrip("/")
20
  HF_TOKEN = (os.getenv("AI_LamboVision_TOKEN", "") or "").strip().strip("'\"")
21
  HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
22
 
23
  VIDEO_MAX_PX_DEFAULT = int(os.getenv("VIDEO_MAX_PX", "720"))
24
  VIDEO_RES_OPTIONS = ["512P", "768P"]
25
  VIDEO_DUR_OPTIONS = ["6", "10"]
26
- # Default 3:4 to avoid very tall cards; user can switch
27
- ASPECT_OPTIONS = ["3:4", "9:16", "1:1"]
28
 
29
- # ==== Session ====
30
  if "results" not in st.session_state:
31
  st.session_state["results"] = None
32
  if "job_counter" not in st.session_state:
@@ -34,15 +33,19 @@ if "job_counter" not in st.session_state:
34
  if "video_ui_max_px" not in st.session_state:
35
  st.session_state["video_ui_max_px"] = VIDEO_MAX_PX_DEFAULT
36
 
37
- # ==== Backend helpers ====
38
  def _needs_auth(url: str) -> bool:
39
  return url.startswith(API_BASE) or url.startswith("outputs/") or url.startswith("/outputs/")
40
 
41
  def _abs_backend_url(url_or_path: str) -> str:
42
- if not url_or_path: return ""
43
- if url_or_path.startswith(("http://","https://")): return url_or_path
44
- if url_or_path.startswith("/outputs/"): return f"{API_BASE}{url_or_path}"
45
- if url_or_path.startswith("outputs/"): return f"{API_BASE}/{url_or_path}"
 
 
 
 
46
  return f"{API_BASE}/{url_or_path.lstrip('/')}"
47
 
48
  def backend_ok() -> bool:
@@ -59,9 +62,15 @@ def post_chain(data: dict, files_payload):
59
  r.raise_for_status()
60
  return r.json()
61
 
62
- def post_video(image_url: str, duration="6", resolution="768P", preview_aspect="3:4", prompt=None):
63
- payload = {"image_url": image_url, "duration": duration, "resolution": resolution, "preview_aspect": preview_aspect}
64
- if prompt is not None: payload["prompt"] = prompt
 
 
 
 
 
 
65
  r = requests.post(f"{API_BASE}/v1/video/from-image", data=payload, headers=HEADERS, timeout=600)
66
  r.raise_for_status()
67
  return r.json()
@@ -86,7 +95,8 @@ def _sniff_mime_from_bytes(b: bytes) -> str:
86
  return "image/jpeg"
87
 
88
  def image_bytes_to_data_url(b: bytes, mime: str | None = None) -> str:
89
- if not mime: mime = _sniff_mime_from_bytes(b)
 
90
  enc = base64.b64encode(b).decode("ascii")
91
  return f"data:{mime};base64,{enc}"
92
 
@@ -103,7 +113,8 @@ def infer_ext(data: bytes) -> str:
103
  fmt = (im.format or "JPEG").lower()
104
  return "." + {"jpeg":"jpg","jpg":"jpg","png":"png","webp":"webp"}.get(fmt,"jpg")
105
  except Exception:
106
- if data[:4] == b"\x00\x00\x00\x18" or data[4:8] == b"ftyp": return ".mp4"
 
107
  return ".bin"
108
 
109
  def make_zip(named_bytes: list[tuple[str, bytes]]) -> bytes:
@@ -113,79 +124,92 @@ def make_zip(named_bytes: list[tuple[str, bytes]]) -> bytes:
113
  if b: z.writestr(fname, b)
114
  buf.seek(0); return buf.read()
115
 
116
- # ==== Preview helpers ====
117
  def _parse_aspect_str(s: str):
118
  try:
119
  a, b = s.split(":"); return max(1, int(a)), max(1, int(b))
120
  except Exception:
121
  return (3, 4)
122
 
123
- def inject_base_css():
124
- st.markdown("""
 
125
  <style>
126
- .stApp { background: #0e0f12; }
127
- header[data-testid="stHeader"] { background: transparent; }
128
- .block-container { padding-top: 1.1rem; }
129
 
130
- h1, .stMarkdown h1 { font-size: 1.85rem; line-height: 1.25; margin-bottom: 0.1rem; }
131
- .stMarkdown p { margin-top: 0.15rem; }
132
 
133
  label, .stTextInput label, .stSelectbox label, .stNumberInput label, .stFileUploader label,
134
- .stCheckbox label, .stSlider label, .stRadio label {
135
  color: #ff8a33 !important; font-weight: 600 !important;
136
- }
137
-
138
- .stButton > button[kind="primary"]{
139
- background: #ff7a1a !important; border: 0 !important; color: #111 !important;
140
- }
141
- .stButton > button:hover { filter: brightness(1.05); }
142
 
143
- .stAlert { border-radius: 10px; }
144
 
145
- .lv-card-title { font-weight: 700; font-size: 1.05rem; margin: 2px 0 8px 0; color: #eaecef; }
146
-
147
- /* UNIFORM FRAME: one box size for all media; content never overflows */
148
- .lv-frame {
149
- position: relative;
150
- width: 100%;
151
- aspect-ratio: 3 / 4; /* default; overridden by inject_preview_css */
152
- border-radius: 12px;
153
- overflow: hidden;
154
  background: #111419;
155
- display: flex; align-items: center; justify-content: center;
156
  box-shadow: 0 0 0 1px rgba(255,122,26,0.15) inset;
157
- }
158
-
159
- /* CONTAIN for both IMG and VIDEO (no cropping, no spill) */
160
- .lv-frame > img,
161
- .lv-frame > video,
162
- .lv-frame > .lv-media {
163
- width: 100%;
164
- height: 100%;
165
- object-fit: contain !important;
166
- display: block;
167
- background: transparent;
168
- }
169
-
170
- /* reset inner element spacing to avoid shifting card height */
171
- .lv-frame * { margin: 0 !important; padding: 0 !important; border: 0 !important; }
172
  </style>
173
  """, unsafe_allow_html=True)
174
 
175
- def inject_preview_css(aspect: str, fit_mode="contain"):
176
- try:
177
- a, b = [int(x) for x in aspect.split(":")]
178
- except Exception:
179
- a, b = 3, 4
180
  st.markdown(f"""
181
  <style>
182
- .lv-frame {{ aspect-ratio: {a} / {b}; }}
183
- .lv-frame > img, .lv-frame > video, .lv-frame > .lv-media {{ object-fit: {fit_mode}; }}
184
  </style>
185
  """, unsafe_allow_html=True)
186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  def rgba_to_rgb_on_bg(img_rgba: Image.Image, bg_rgb=(255,255,255)) -> Image.Image:
188
- if img_rgba.mode != "RGBA": return img_rgba.convert("RGB")
 
189
  bg = Image.new("RGBA", img_rgba.size, (*bg_rgb, 255))
190
  bg.paste(img_rgba, (0,0), img_rgba)
191
  return bg.convert("RGB")
@@ -199,9 +223,11 @@ def make_small_jpeg_from_native(native: bytes, target_long_edge: int = 1280, bg_
199
  im = im.convert("RGBA")
200
  w, h = im.size
201
  if w >= h:
202
- new_w = min(target_long_edge, w); new_h = max(1, int(h * (new_w / max(1, w))))
 
203
  else:
204
- new_h = min(target_long_edge, h); new_w = max(1, int(w * (new_h / max(1, h))))
 
205
  im2 = im.resize((new_w, new_h), Image.LANCZOS)
206
  im2_rgb = rgba_to_rgb_on_bg(im2, bg_rgb=bg_rgb)
207
  out = io.BytesIO(); im2_rgb.save(out, format="JPEG", quality=88, subsampling=1)
@@ -217,154 +243,160 @@ def make_preview_frame(img_bytes: bytes, aspect: str, long_edge: int, ratio: flo
217
  ratio = max(0.10, min(0.99, float(ratio)))
218
  target = int(min(W, H) * ratio if a == b else (H * ratio if a < b else W * ratio))
219
  w, h = im.size
220
- if w >= h: new_w, new_h = target, max(1, int(h * (new_w / max(1, w))))
221
- else: new_h, new_w = target, max(1, int(w * (new_h / max(1, h))))
222
  im_resized = im.resize((new_w, new_h), Image.LANCZOS)
223
  canvas = Image.new("RGBA", (W, H), (*bg_rgb, 255))
224
  off = ((W - new_w)//2, (H - new_h)//2); canvas.paste(im_resized, off, im_resized)
225
  out = io.BytesIO(); canvas.convert("RGB").save(out, format="JPEG", quality=90, subsampling=1)
226
- return out.read()
227
 
228
- # ==== Local demo files (optional) ====
229
  def load_local_demo():
230
  demo = {}
231
- for fname in ["input.jpg", "packshot.jpg", "scene.jpg", "tryon.mp4"]:
232
  if os.path.exists(fname):
233
  with open(fname, "rb") as f: demo[fname] = f.read()
234
  return demo
 
235
  demo_files = load_local_demo()
236
 
237
- # ==== Configurator data ====
238
- LAMBOMODELS = [
239
- "Revuelto", "Huracán Tecnica", "Huracán Sterrato", "Huracán EVO",
240
- "Urus S", "Urus Performante", "Sián", "Aventador SVJ (legacy)"
241
- ]
242
- FINISHES = ["Gloss", "Matte", "Satin", "Pearl"]
243
- WHEELS = ["Hexagon Forged", "Narvi", "Minotauro", "Taigete", "Shiny Black", "Graphite Gray"]
244
- CALIPERS = ["Yellow", "Black", "Red", "Green", "Orange", "Silver"]
245
- BODY_COLORS = [
246
- "Giallo Auge", "Arancio Borealis", "Verde Mantis", "Blu Nila",
247
- "Grigio Telesto", "Nero Noctis", "Bianco Monocerus", "Rosso Mars"
248
- ]
 
 
 
 
 
 
 
 
 
249
  SCENE_PRESETS = {
250
- "Studio Clean": "premium studio, neutral gradient backdrop, soft rim light, glossy floor reflections",
251
- "Monaco Sunset": "Monaco harbor at golden hour, warm reflections on paint, soft shadows",
252
- "Dubai Night": "Dubai skyline at night, neon reflections, high-contrast lighting, luxurious vibe",
253
- "Track Day": "race track pit lane, subtle motion cues, realistic asphalt reflections",
254
- "Mountain Pass": "alpine pass road, crisp air, cool daylight, cinematic depth"
255
  }
256
 
257
- # ==== App ====
258
- st.set_page_config(page_title="LamboVision · AI Car Studio", layout="wide", page_icon="🏎️")
259
- inject_base_css()
 
 
 
 
 
 
 
260
 
261
  st.title("🏎️ LamboVision · AI Car Studio")
262
- st.caption("Upload → Configure → Scene → Cinematic")
263
 
264
  ok = backend_ok()
265
 
266
- # ---- Top controls ----
267
- col1, col2, col3, col4, col5, col6, col7 = st.columns([1.6, 1.6, 1.2, 1.4, 1.0, 1.0, 1.2])
268
  with col1:
269
  file_list = st.file_uploader("Car Image (Upload)", type=["jpg","jpeg","png","webp"], accept_multiple_files=True, key="file_upl")
270
  with col2:
271
  image_url = st.text_input("Or URL", key="image_url", placeholder="https://... (optional)")
272
  with col3:
273
- model_sel = st.selectbox("Model", LAMBOMODELS, index=0, key="lv_model")
274
  with col4:
275
- body_color = st.selectbox("Body Color", BODY_COLORS, index=0, key="lv_color")
 
276
  with col5:
277
- finish = st.selectbox("Finish", FINISHES, index=0, key="lv_finish")
278
  with col6:
279
- wheel = st.selectbox("Wheel Style", WHEELS, index=0, key="lv_wheel")
280
  with col7:
281
- caliper = st.selectbox("Caliper Color", CALIPERS, index=0, key="lv_caliper")
282
 
283
- colA, colB, colC, colD, colE, colF = st.columns([1.4, 1.4, 1.2, 1.0, 1.2, 1.2])
284
  with colA:
285
- extra_prompt = st.text_input("Extra (optional)", placeholder="carbon mirrors, dual stripe delete, etc.", key="extra_prompt")
286
  with colB:
287
- scene_name = st.selectbox("Scene Preset", list(SCENE_PRESETS.keys()), index=0, key="scene_preset")
288
  with colC:
289
- preview_ratio = st.number_input("Preview Scale (0.10–0.99)", min_value=0.10, max_value=0.99, value=0.90, step=0.01, key="preview_ratio")
290
  with colD:
291
- upscale = st.checkbox("Super Res", False, key="upscale")
292
  with colE:
293
- upscale_stage = st.selectbox("SR Step", ["both","final","packshot"], index=0, help="Default: both", key="upscale_stage")
294
  with colF:
295
- identity_lock = st.checkbox("Identity lock", True, key="identity_lock")
296
 
297
- colT1, colT2, colT3, colT4 = st.columns([1.0, 1.0, 1.0, 1.2])
298
- with colT1:
299
- preview_aspect = st.selectbox("Preview Frame Ratio", ASPECT_OPTIONS, index=0, key="preview_aspect") # default 3:4
300
- with colT2:
301
- preview_long_edge = st.number_input("Preview Long Edge (px)", min_value=256, max_value=8192, value=1536, step=64, key="preview_long_edge")
302
- with colT3:
303
- fit_mode = st.selectbox("Preview Layout", ["fit","fill"], index=0, help="Affects previews only.", key="fit_mode")
304
- with colT4:
305
- st.info(f"Connection: {'Online' if ok else 'Offline'}", icon="🔌")
306
 
307
- # Apply uniform frame CSS
308
- inject_preview_css(preview_aspect, fit_mode="contain" if fit_mode=="fit" else "cover")
309
-
310
- # ==== Build edit prompt (cars) ====
311
- def build_edit_prompt(model, color, finish, wheel, caliper, extra):
312
- parts = [
313
- f"Lamborghini {model}",
314
- f"body color: {color}",
315
- f"finish: {finish}",
316
- f"wheel style: {wheel}",
317
- f"brake calipers: {caliper}",
318
- "catalog-clean alignment, keep true geometry, badges and proportions, realistic reflections"
319
- ]
320
- if extra and extra.strip():
321
- parts.append(extra.strip())
322
- return ", ".join(parts)
323
-
324
- # ==== Pre-run PREVIEWS (5 uniform cards) ====
325
- st.subheader("Previews (Uniform Cards)")
326
- c_in, c_pack, c_pad, c_scene, c_video = st.columns(5)
327
 
328
- def show_tile_card_display_download(
329
- col, title,
330
- display_url: str | None = None,
331
- display_bytes: bytes | None = None,
332
- download_url: str | None = None,
333
- download_bytes: bytes | None = None,
334
- filename_stub: str = "image",
335
- key_prefix: str = "",
336
- ):
337
- col.markdown(f'<div class="lv-card-title">{title}</div>', unsafe_allow_html=True)
338
 
339
- # FRAME (always same size)
340
- if display_bytes is not None:
341
- src = image_bytes_to_data_url(display_bytes)
342
- col.markdown(f'<div class="lv-frame"><img class="lv-media" src="{src}"/></div>', unsafe_allow_html=True)
343
- elif display_url:
344
- abs_url = _abs_backend_url(display_url)
345
- col.markdown(f'<div class="lv-frame"><img class="lv-media" src="{abs_url}"/></div>', unsafe_allow_html=True)
346
- else:
347
- col.markdown('<div class="lv-frame"></div>', unsafe_allow_html=True)
348
- col.caption("—"); return None, None
349
 
350
- # Native (caption + download)
351
- native = download_bytes or (fetch_bytes(download_url) if download_url else None)
352
- if not native:
353
- native = display_bytes
354
- if native:
355
- sz = image_size_from_bytes(native)
356
- if sz: col.caption(f"Real Res: {sz[0]}×{sz[1]} px")
357
- ext = infer_ext(native)
358
- mime = "image/jpeg" if ext.lower() in [".jpg",".jpeg"] else ("image/png" if ext.lower()==".png" else "image/webp")
359
- col.download_button("Download (Full Quality)", data=native,
360
- file_name=f"{filename_stub}{ext if ext!='.bin' else '.jpg'}",
361
- mime=mime, key=f"{key_prefix}_{filename_stub}_dl")
362
- else:
363
- col.caption("—")
364
 
365
- return display_url or "data", native
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
 
367
- # Input bytes
368
  input_bytes = None
369
  if file_list:
370
  try: input_bytes = file_list[0].getvalue()
@@ -375,7 +407,7 @@ elif demo_files.get("input.jpg"):
375
  input_bytes = demo_files["input.jpg"]
376
 
377
  show_tile_card_display_download(
378
- c_in, "Sample Input",
379
  display_bytes=input_bytes if input_bytes else demo_files.get("input.jpg"),
380
  download_bytes=input_bytes if input_bytes else demo_files.get("input.jpg"),
381
  filename_stub="input", key_prefix="pre"
@@ -383,7 +415,7 @@ show_tile_card_display_download(
383
 
384
  pack_bytes_demo = demo_files.get("packshot.jpg") or input_bytes
385
  show_tile_card_display_download(
386
- c_pack, "Sample Packshot (Configured)",
387
  display_bytes=pack_bytes_demo,
388
  download_bytes=pack_bytes_demo,
389
  filename_stub="packshot", key_prefix="pre"
@@ -398,103 +430,84 @@ if pack_bytes_demo:
398
  except Exception:
399
  padded_bytes = None
400
  show_tile_card_display_download(
401
- c_pad, "Sample Padded (UI)",
402
  display_bytes=padded_bytes or pack_bytes_demo,
403
  download_bytes=padded_bytes or pack_bytes_demo,
404
  filename_stub="padded_ui", key_prefix="pre"
405
  )
406
 
407
- scene_bytes_demo = demo_files.get("scene.jpg") or pack_bytes_demo
408
- show_tile_card_display_download(
409
- c_scene, "Sample AI Scene",
410
- display_bytes=scene_bytes_demo,
411
- download_bytes=scene_bytes_demo,
412
- filename_stub="scene_composite", key_prefix="pre"
413
- )
414
-
415
- c_video.markdown('<div class="lv-card-title">Sample AI Generated Video</div>', unsafe_allow_html=True)
416
  vid_demo = demo_files.get("tryon.mp4")
 
417
  if vid_demo:
418
  data_url = "data:video/mp4;base64," + base64.b64encode(vid_demo).decode("ascii")
419
- c_video.markdown(
420
  f"""
421
- <div class="lv-frame">
422
- <video class="lv-media" autoplay loop muted playsinline>
423
  <source src="{data_url}" type="video/mp4">
424
  </video>
425
  </div>
426
  """, unsafe_allow_html=True
427
  )
428
- c_video.download_button("Download Video (MP4)", data=vid_demo, file_name="sample_tryon.mp4", mime="video/mp4", key="pre_video_dl")
429
  else:
430
- c_video.markdown('<div class="lv-frame"></div>', unsafe_allow_html=True)
431
- c_video.caption("—")
432
-
433
- # ==== Actions ====
434
- colAct1, colAct2, colAct3, colAct4, colAct5 = st.columns([1.0, 1.0, 1.2, 1.0, 1.2])
435
- with colAct1:
436
- to_video = st.checkbox("One Click Generate Video", False, key="to_video")
437
- with colAct2:
438
- duration = st.selectbox("Duration", VIDEO_DUR_OPTIONS, index=0, key="duration_sel")
439
- with colAct3:
440
- resolution = st.selectbox("Video Res", VIDEO_RES_OPTIONS, index=1, key="resolution_sel")
441
- with colAct4:
442
- do_scene_pass = st.checkbox("Scene Composite", True, key="do_scene_pass")
443
- with colAct5:
444
- run = st.button("Run ▶", type="primary", use_container_width=True, key="run_btn")
445
-
446
- # ==== Pipeline ====
447
- def build_edit_prompt(model, color, finish, wheel, caliper, extra):
448
- parts = [
449
- f"Lamborghini {model}",
450
- f"body color: {color}",
451
- f"finish: {finish}",
452
- f"wheel style: {wheel}",
453
- f"brake calipers: {caliper}",
454
- "catalog-clean alignment, keep true geometry, badges and proportions, realistic reflections"
455
- ]
456
- if extra and extra.strip(): parts.append(extra.strip())
457
- return ", ".join(parts)
458
 
 
459
  if run:
460
  if not ok:
461
- st.error("Backend unreachable. Check API_BASE / TOKEN.")
462
  elif not (file_list or image_url or demo_files.get("input.jpg")):
463
- st.error("Provide at least one image (upload or URL).")
464
  else:
465
  try:
466
- edit_prompt = build_edit_prompt(model_sel, body_color, finish, wheel, caliper, extra_prompt)
467
- scene_text = SCENE_PRESETS.get(scene_name, "premium studio scene")
 
 
 
 
 
 
 
 
468
  img_urls = image_url or ""
469
  files_payload = []
470
  if file_list:
471
  for f in file_list:
472
  files_payload.append(("files", (f.name, f.getvalue(), f.type or "image/jpeg")))
 
473
  data = {
474
- "category": "auto",
475
  "edit_prompt": edit_prompt,
476
  "num_images": "1",
477
  "image_urls": img_urls,
478
- "do_scene_pass": "true" if do_scene_pass else "false",
479
- "scene_prompt_text": scene_text,
480
  "identity_lock": "true" if identity_lock else "false",
 
481
  "preview_aspect": preview_aspect,
482
  "preview_long_edge": str(int(preview_long_edge)),
483
  "preview_ratio": str(float(preview_ratio)),
 
 
484
  "upscale": "true" if upscale else "false",
485
- "upscale_factor": "2",
486
  "upscale_stage": st.session_state.get("upscale_stage","both"),
 
487
  "to_video": "true" if to_video else "false",
488
- "video_prompt": scene_text,
489
  "duration": st.session_state.get("duration_sel", VIDEO_DUR_OPTIONS[0]),
490
  "resolution": st.session_state.get("resolution_sel", VIDEO_RES_OPTIONS[1]),
491
  "prompt_optimizer": "false",
492
  }
493
- with st.spinner("LamboVision pipeline running…"):
 
494
  out = post_chain(data, files_payload if files_payload else None)
495
 
496
  st.session_state["job_counter"] += 1
497
 
 
498
  pack_native_url = None; pack_display_jpeg = None
499
  try:
500
  pack_native_url = (out["packshot_step"]["result"]["images_native"] or [{}])[0].get("url")
@@ -511,13 +524,12 @@ if run:
511
  if nb: padded_display_jpeg = make_small_jpeg_from_native(nb, 1280, bg_rgb=(255,255,255))
512
  except Exception: pass
513
 
514
- scene_native_url = None; scene_display_jpeg = None
515
  try:
516
- if out.get("scene_step"):
517
- scene_native_url = (out["scene_step"]["result"]["images_native"] or [{}])[0].get("url")
518
- if scene_native_url:
519
- sb = fetch_bytes(scene_native_url)
520
- if sb: scene_display_jpeg = make_small_jpeg_from_native(sb, 1280, bg_rgb=(255,255,255))
521
  except Exception: pass
522
 
523
  vurl = None
@@ -537,15 +549,12 @@ if run:
537
  "packshot_display_jpeg": pack_display_jpeg,
538
  "padded_native_url": padded_native_url,
539
  "padded_display_jpeg": padded_display_jpeg,
540
- "scene_native_url": scene_native_url,
541
- "scene_display_jpeg": scene_display_jpeg,
542
  "video_url": vurl,
543
  "api_base": API_BASE,
544
  "has_auth_header": bool(HEADERS),
545
  "preview_aspect": preview_aspect,
546
- "scene_vendor_url": out.get("scene_vendor_url"),
547
- "scene_prompt_text": scene_text,
548
- "edit_prompt": edit_prompt,
549
  }
550
 
551
  except requests.HTTPError as e:
@@ -553,15 +562,15 @@ if run:
553
  except Exception as e:
554
  st.error(f"Error: {e}")
555
 
556
- # ==== Results (Uniform Cards) ====
557
  res = st.session_state.get("results")
558
  vbytes = None
559
  if res:
560
  st.subheader("Results")
561
- c_pack2, c_pad2, c_scene2, c_video2 = st.columns(4)
562
 
563
  show_tile_card_display_download(
564
- c_pack2, "Configured Packshot",
565
  display_bytes=res.get("packshot_display_jpeg"),
566
  download_url=res.get("packshot_native_url"),
567
  filename_stub="packshot_native",
@@ -569,7 +578,7 @@ if res:
569
  )
570
 
571
  show_tile_card_display_download(
572
- c_pad2, "Padded (Canvas)",
573
  display_bytes=res.get("padded_display_jpeg"),
574
  download_url=res.get("padded_native_url"),
575
  filename_stub="padded_backend",
@@ -577,21 +586,21 @@ if res:
577
  )
578
 
579
  show_tile_card_display_download(
580
- c_scene2, "Scene Composite",
581
- display_bytes=res.get("scene_display_jpeg"),
582
- download_url=res.get("scene_native_url"),
583
- filename_stub="scene_native",
584
  key_prefix=f"job{st.session_state['job_counter']}"
585
  )
586
 
587
- c_video2.markdown('<div class="lv-card-title">AI Cinematic</div>', unsafe_allow_html=True)
588
  vurl = res.get("video_url")
589
  if vurl:
590
  abs_v = _abs_backend_url(vurl)
591
- c_video2.markdown(
592
  f"""
593
- <div class="lv-frame">
594
- <video class="lv-media" autoplay loop muted controls playsinline>
595
  <source src="{abs_v}" type="video/mp4">
596
  </video>
597
  </div>
@@ -600,24 +609,26 @@ if res:
600
  vb = fetch_bytes(abs_v)
601
  if vb:
602
  vbytes = vb
603
- c_video2.download_button("Download Video (MP4)", data=vb, file_name="lambo_vision_video.mp4",
604
- mime="video/mp4", key=f"job{st.session_state['job_counter']}_video_dl")
605
  else:
606
- c_video2.markdown('<div class="lv-frame"></div>', unsafe_allow_html=True)
607
  vid_checkbox_key = f"video_toggle_job{st.session_state['job_counter']}"
608
- if st.checkbox("Generate Video From Scene", value=False, key=vid_checkbox_key):
609
- src_for_video = res.get("scene_native_url") or res.get("packshot_native_url")
610
  if not src_for_video:
611
  st.warning("No image found for video.")
612
  else:
613
- with st.spinner("Generating video …"):
614
  try:
615
  v = post_video(
616
  src_for_video,
617
  duration=st.session_state.get("duration_sel", VIDEO_DUR_OPTIONS[0]),
618
  resolution=st.session_state.get("resolution_sel", VIDEO_RES_OPTIONS[1]),
619
  preview_aspect=st.session_state.get("preview_aspect","3:4"),
620
- prompt=res.get("scene_prompt_text")
 
 
621
  )
622
  except requests.HTTPError as e:
623
  st.error(f"HTTP {e.response.status_code}")
@@ -633,26 +644,26 @@ if res:
633
  st.success("Video is ready.")
634
  st.rerun()
635
  else:
636
- st.info("No video URL returned.")
637
 
638
- # ZIP bundle
639
  named = []
640
  pn = fetch_bytes(res.get("packshot_native_url")) if res.get("packshot_native_url") else None
641
- sn = fetch_bytes(res.get("scene_native_url")) if res.get("scene_native_url") else None
642
  if pn: named.append((f"packshot_native{infer_ext(pn)}", pn))
643
- if sn: named.append((f"scene_native{infer_ext(sn)}", sn))
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="lambo_vision_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 ✓")
655
  st.slider("Video preview width (px)", 360, 1080, st.session_state["video_ui_max_px"],
656
  step=10, key="video_ui_max_px")
657
  if st.button("Clear cache"): st.cache_data.clear(); st.success("Cache cleared.")
658
- if st.button("Clear last results"): st.session_state["results"] = None; st.success("Results cleared.")
 
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
6
 
7
+ # ===== Theme (dark + Lamborghini orange) =====
8
  try:
9
  st._config.set_option("theme.base", "dark")
10
  st._config.set_option("theme.primaryColor", "#ff7a1a")
 
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:
30
  st.session_state["results"] = None
31
  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
 
40
  def _abs_backend_url(url_or_path: str) -> str:
41
+ if not url_or_path:
42
+ return ""
43
+ if url_or_path.startswith(("http://","https://")):
44
+ return url_or_path
45
+ if url_or_path.startswith("/outputs/"):
46
+ return f"{API_BASE}{url_or_path}"
47
+ if url_or_path.startswith("outputs/"):
48
+ return f"{API_BASE}/{url_or_path}"
49
  return f"{API_BASE}/{url_or_path.lstrip('/')}"
50
 
51
  def backend_ok() -> bool:
 
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()
76
  return r.json()
 
95
  return "image/jpeg"
96
 
97
  def image_bytes_to_data_url(b: bytes, mime: str | None = None) -> str:
98
+ if not mime:
99
+ mime = _sniff_mime_from_bytes(b)
100
  enc = base64.b64encode(b).decode("ascii")
101
  return f"data:{mime};base64,{enc}"
102
 
 
113
  fmt = (im.format or "JPEG").lower()
114
  return "." + {"jpeg":"jpg","jpg":"jpg","png":"png","webp":"webp"}.get(fmt,"jpg")
115
  except Exception:
116
+ if data[:4] == b"\x00\x00\x00\x18" or data[4:8] == b"ftyp":
117
+ return ".mp4"
118
  return ".bin"
119
 
120
  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))
130
  except Exception:
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;
 
 
 
 
 
 
156
  background: #111419;
157
+ display:flex; align-items:center; justify-content:center;
158
  box-shadow: 0 0 0 1px rgba(255,122,26,0.15) inset;
159
+ }}
160
+ .lb-frame img, .lb-frame video {{
161
+ width:100%; height:100%; display:block; object-fit:{card_fit_mode};
162
+ }}
163
+ .stCaption {{ color:#ffb07a !important; }}
 
 
 
 
 
 
 
 
 
 
164
  </style>
165
  """, unsafe_allow_html=True)
166
 
167
+ def inject_preview_css(aspect: str):
168
+ aw, ah = _parse_aspect_str(aspect)
 
 
 
169
  st.markdown(f"""
170
  <style>
171
+ .lb-frame {{ aspect-ratio: {aw} / {ah}; }}
 
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")
 
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)
 
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. "
268
+ "Neutral studio background, soft rim light, realistic reflections, no text/logos in background. "
269
+ "Keep true proportions, lens look (35–50mm), and paint micro-highlights. "
270
+ "IDENTITY & GEOMETRY LOCK: Treat the car as a fixed real object. "
271
+ "Do NOT redraw or stylize body panels; preserve body lines, panel gaps, reflections and lenses; "
272
+ "no rotation/mirroring (Δyaw/pitch/roll ≤ 1°); keep wheel circles true, tire sidewalls, brake discs & calipers, ride height; "
273
+ "preserve badges/logo integrity; no warp or fake text."
274
+ )
275
+ cfg = (
276
+ f" Subject: {model_name}. "
277
+ f"Change body color to {body_color} with {finish} finish. "
278
+ f"Wheels: {wheel_style}; brake calipers {caliper_color}. "
279
+ "Maintain original stance; no suspension changes; no aero additions."
280
+ )
281
+ if extra.strip():
282
+ cfg += " " + extra.strip()
283
+ return base + " " + cfg
284
+
285
  SCENE_PRESETS = {
286
+ "Studio Cinematic": "High-end studio cyclorama, soft rim light, tripod-like stability, subtle parallax.",
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 = [
343
+ "Revuelto", "Huracán Tecnica", "Huracán Sterrato",
344
+ "Urus S", "Urus Performante", "Countach LPI 800-4", "Custom…"
345
+ ]
346
+ COLOR_CHOICES = [
347
+ "Verde Ithaca", "Giallo Orion", "Rosso Mars",
348
+ "Blu Nethuns", "Nero Noctis", "Bianco Monocerus", "Arancio Borealis", "Custom…"
349
+ ]
350
+ FINISH_CHOICES = ["gloss", "matte", "satin"]
351
+ WHEEL_CHOICES = [
352
+ "lightweight forged", "diamond-cut multi-spoke",
353
+ "center-lock race", "Aesir (20\")", "Taigete (23\")", "Custom…"
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")
361
+ model_name = st.text_input("Model (custom)", value="", key="cfg_model_txt") if model_sel == "Custom…" else model_sel
 
 
 
 
 
 
 
362
 
363
+ with c2:
364
+ color_sel = st.selectbox("Body color", COLOR_CHOICES, index=0, key="cfg_color_sel")
365
+ body_color = st.text_input("Body color (custom)", value="", key="cfg_color_txt") if color_sel == "Custom…" else color_sel
 
 
 
 
 
 
 
 
 
 
 
366
 
367
+ with c3:
368
+ finish = st.selectbox("Finish", FINISH_CHOICES, index=0, key="cfg_finish")
369
+
370
+ with c4:
371
+ wheel_sel = st.selectbox("Wheel style", WHEEL_CHOICES, index=0, key="cfg_wheels_sel")
372
+ wheel_style = st.text_input("Wheel style (custom)", value="", key="cfg_wheels_txt") if wheel_sel == "Custom…" else wheel_sel
373
+
374
+ with c5:
375
+ caliper_sel = st.selectbox("Caliper", CALIPER_CHOICES, index=0, key="cfg_caliper_sel")
376
+ caliper_color = st.text_input("Caliper (custom)", value="", key="cfg_caliper_txt") if caliper_sel == "Custom…" else caliper_sel
377
+
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:
402
  try: input_bytes = file_list[0].getvalue()
 
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"
 
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"
 
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">
446
+ <video autoplay loop muted playsinline>
447
  <source src="{data_url}" type="video/mp4">
448
  </video>
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.")
461
  elif not (file_list or image_url or demo_files.get("input.jpg")):
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")
 
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
 
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:
 
562
  except Exception as e:
563
  st.error(f"Error: {e}")
564
 
565
+ # ================= RESULTS =================
566
  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",
 
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",
 
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:
599
  abs_v = _abs_backend_url(vurl)
600
+ c_vid.markdown(
601
  f"""
602
+ <div class="lb-frame">
603
+ <video autoplay loop muted controls playsinline>
604
  <source src="{abs_v}" type="video/mp4">
605
  </video>
606
  </div>
 
609
  vb = fetch_bytes(abs_v)
610
  if vb:
611
  vbytes = vb
612
+ c_vid.download_button("Download Video (MP4)", data=vb, file_name="lambovision_video.mp4",
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}")
 
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)
658
  st.download_button("Download All (ZIP)", data=zip_bytes,
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.")