renderfy commited on
Commit
d833530
·
verified ·
1 Parent(s): 4f9bdd7

Upload 7 files

Browse files
Files changed (8) hide show
  1. .gitattributes +4 -0
  2. Dockerfile +13 -0
  3. input.jpg +3 -0
  4. model.jpg +3 -0
  5. packshot.jpg +3 -0
  6. requirements.txt +12 -0
  7. streamlit_app.py +618 -0
  8. tryon.mp4 +3 -0
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ input.jpg filter=lfs diff=lfs merge=lfs -text
37
+ model.jpg filter=lfs diff=lfs merge=lfs -text
38
+ packshot.jpg filter=lfs diff=lfs merge=lfs -text
39
+ tryon.mp4 filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ RUN useradd -m -u 1000 user
4
+ USER user
5
+ ENV PATH="/home/user/.local/bin:$PATH"
6
+ WORKDIR /app
7
+
8
+ COPY --chown=user requirements.txt .
9
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
10
+
11
+ COPY --chown=user . .
12
+ EXPOSE 7860
13
+ CMD ["streamlit", "run", "streamlit_app.py", "--server.address=0.0.0.0", "--server.port=7860"]
input.jpg ADDED

Git LFS Details

  • SHA256: bbf3b194679ec541b484cdd1aa9a8535335136be00e1905cb274b419bb0aa211
  • Pointer size: 131 Bytes
  • Size of remote file: 471 kB
model.jpg ADDED

Git LFS Details

  • SHA256: a42954db2fb9b804446edc4580391006bfb048e1920a25dcfb9ba9ca779a652e
  • Pointer size: 131 Bytes
  • Size of remote file: 219 kB
packshot.jpg ADDED

Git LFS Details

  • SHA256: f841e191b40d50a9626e3385e935256b4703f6881c606c10a8eb0fee1e34e884
  • Pointer size: 131 Bytes
  • Size of remote file: 204 kB
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ httpx>=0.27
3
+ pyjwt>=2.9
4
+ fastapi
5
+ uvicorn[standard]
6
+ pillow
7
+ requests
8
+ fal-client
9
+ python-multipart
10
+ aiofiles
11
+ websockets
12
+ websocket-client
streamlit_app.py ADDED
@@ -0,0 +1,618 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # streamlit_app.py — LamboVision (Car) UI
2
+ # Pre-run sabit 4 kart (Input/Packshot/Padded/Video loop) + Run sonrası native odaklı kartlar
3
+
4
+ import os, io, base64, zipfile, requests, streamlit as st
5
+ from PIL import Image
6
+
7
+ # ===== Theme (programmatic dark orange) =====
8
+ try:
9
+ st._config.set_option("theme.base", "dark")
10
+ st._config.set_option("theme.primaryColor", "#ff7a1a") # dark orange
11
+ st._config.set_option("theme.backgroundColor", "#0e0f12") # app bg
12
+ st._config.set_option("theme.secondaryBackgroundColor", "#161a1f")
13
+ st._config.set_option("theme.textColor", "#e7e9ed")
14
+ except Exception:
15
+ pass
16
+
17
+ # ================= Env & API =================
18
+ API_BASE = (os.getenv("AI_LIGHTBOX_API", "http://127.0.0.1:8000") or "http://127.0.0.1:8000").strip().strip("'\"").rstrip("/")
19
+ HF_TOKEN = (os.getenv("AI_LIGHTBOX_TOKEN", "") or "").strip().strip("'\"")
20
+ HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
21
+
22
+ # UI vars
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
+ # Otomotiv odaklı kadraj önerisi: 16:9 (diğerleri de korundu)
27
+ ASPECT_OPTIONS = ["16:9", "9:16", "1:1", "4:3"]
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:
33
+ st.session_state["job_counter"] = 0
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
+ # ================= HTTP/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:
43
+ return ""
44
+ if url_or_path.startswith(("http://","https://")):
45
+ return url_or_path
46
+ if url_or_path.startswith("/outputs/"):
47
+ return f"{API_BASE}{url_or_path}"
48
+ if url_or_path.startswith("outputs/"):
49
+ return f"{API_BASE}/{url_or_path}"
50
+ return f"{API_BASE}/{url_or_path.lstrip('/')}"
51
+
52
+ def backend_ok() -> bool:
53
+ try:
54
+ r = requests.get(f"{API_BASE}/health", headers=HEADERS, timeout=10)
55
+ r.raise_for_status()
56
+ return True
57
+ except Exception:
58
+ return False
59
+
60
+ def post_chain(data: dict, files_payload):
61
+ r = requests.post(f"{API_BASE}/v1/tryon/chain", data=data, files=files_payload or None,
62
+ headers=HEADERS, timeout=600)
63
+ r.raise_for_status()
64
+ return r.json()
65
+
66
+ def post_video(image_url: str, duration="6", resolution="768P", prompt_optimizer=False, preview_aspect="16:9"):
67
+ payload = {
68
+ "image_url": image_url,
69
+ "duration": duration,
70
+ "resolution": resolution,
71
+ "prompt_optimizer": "true" if prompt_optimizer else "false",
72
+ "preview_aspect": preview_aspect,
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()
77
+
78
+ @st.cache_data(ttl=300, show_spinner=False)
79
+ def fetch_bytes(url_or_path: str):
80
+ if not url_or_path: return None
81
+ try:
82
+ url = _abs_backend_url(url_or_path)
83
+ headers = HEADERS if _needs_auth(url) else None
84
+ r = requests.get(url, headers=headers, timeout=180)
85
+ r.raise_for_status()
86
+ return r.content
87
+ except Exception:
88
+ return None
89
+
90
+ def _sniff_mime_from_bytes(b: bytes) -> str:
91
+ try:
92
+ fmt = (Image.open(io.BytesIO(b)).format or "JPEG").lower()
93
+ return {"jpeg":"image/jpeg","jpg":"image/jpeg","png":"image/png","webp":"image/webp"}.get(fmt,"image/jpeg")
94
+ except Exception:
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
+
103
+ @st.cache_data(ttl=300, show_spinner=False)
104
+ def image_size_from_bytes(b: bytes):
105
+ try:
106
+ im = Image.open(io.BytesIO(b)); return im.size
107
+ except Exception:
108
+ return None
109
+
110
+ def infer_ext(data: bytes) -> str:
111
+ try:
112
+ im = Image.open(io.BytesIO(data))
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:
121
+ buf = io.BytesIO()
122
+ with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as z:
123
+ for fname, b in named_bytes:
124
+ if b: z.writestr(fname, b)
125
+ buf.seek(0); return buf.read()
126
+
127
+ # ================= Preview helpers (uniform cards) =================
128
+ def _parse_aspect_str(s: str):
129
+ try:
130
+ a, b = s.split(":"); return max(1, int(a)), max(1, int(b))
131
+ except Exception:
132
+ return (16, 9)
133
+
134
+ def inject_base_css():
135
+ st.markdown("""
136
+ <style>
137
+ /* App-wide */
138
+ .stApp { background: #0e0f12; }
139
+ header[data-testid="stHeader"] { background: transparent; }
140
+ .block-container { padding-top: 1.25rem; }
141
+
142
+ /* Title + caption */
143
+ h1, .stMarkdown h1 { font-size: 1.85rem; line-height: 1.3; margin-bottom: 0.15rem; }
144
+ .stMarkdown p { margin-top: 0.15rem; }
145
+
146
+ /* Labels to dark-orange */
147
+ label, .stTextInput label, .stSelectbox label, .stNumberInput label, .stFileUploader label,
148
+ .stCheckbox label, .stSlider label, .stRadio label {
149
+ color: #ff8a33 !important;
150
+ font-weight: 600 !important;
151
+ }
152
+
153
+ /* Primary buttons (also Run 🚗) */
154
+ .stButton > button[kind="primary"]{
155
+ background: #ff7a1a !important; border: 0 !important; color: #111 !important;
156
+ }
157
+ .stButton > button:hover { filter: brightness(1.05); }
158
+
159
+ /* Card titles */
160
+ .lb-card-title {
161
+ font-weight: 700; font-size: 1.05rem; margin: 2px 0 8px 0; color: #eaecef;
162
+ }
163
+
164
+ /* Frames */
165
+ .lb-frame {
166
+ position: relative; width: 100%;
167
+ border-radius: 12px; overflow: hidden;
168
+ background: #111419;
169
+ display:flex; align-items:center; justify-content:center;
170
+ box-shadow: 0 0 0 1px rgba(255,122,26,0.15) inset;
171
+ }
172
+ .lb-frame img { width:100%; height:100%; display:block; }
173
+
174
+ .lb-video { display:flex; justify-content:center; }
175
+ .lb-video video { border-radius:8px; max-width: 540px; width:100%; height:auto; }
176
+
177
+ .stCaption { color: #ffb07a !important; }
178
+ </style>
179
+ """, unsafe_allow_html=True)
180
+
181
+ def inject_preview_css(aspect: str, fit_mode="contain"):
182
+ aw, ah = _parse_aspect_str(aspect)
183
+ st.markdown(f"""
184
+ <style>
185
+ .lb-frame {{ aspect-ratio: {aw} / {ah}; }}
186
+ .lb-frame img {{ object-fit:{fit_mode}; }}
187
+ </style>
188
+ """, unsafe_allow_html=True)
189
+
190
+ def show_tile_card_display_download(
191
+ col, title,
192
+ display_url: str | None = None,
193
+ display_bytes: bytes | None = None,
194
+ download_url: str | None = None,
195
+ download_bytes: bytes | None = None,
196
+ filename_stub: str = "image",
197
+ key_prefix: str = "",
198
+ ):
199
+ """Gösterimde HAFİF JPEG/PNG (display_bytes) tercih edilir; indirmede NATIVE."""
200
+ col.markdown(f'<div class="lb-card-title">{title}</div>', unsafe_allow_html=True)
201
+
202
+ # ---- Display ----
203
+ if not display_url and not display_bytes:
204
+ col.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
205
+ col.caption("—"); return None, None
206
+
207
+ if display_bytes is not None:
208
+ src = image_bytes_to_data_url(display_bytes) # mime otomatik
209
+ col.markdown(f'<div class="lb-frame"><img src="{src}"/></div>', unsafe_allow_html=True)
210
+ else:
211
+ abs_url = _abs_backend_url(display_url)
212
+ col.markdown(f'<div class="lb-frame"><img src="{abs_url}"/></div>', unsafe_allow_html=True)
213
+
214
+ # ---- Native (caption + download) ----
215
+ native = download_bytes or (fetch_bytes(download_url) if download_url else None)
216
+ if not native:
217
+ native = display_bytes # en azından çözünürlük gösterebilmek için
218
+
219
+ if native:
220
+ sz = image_size_from_bytes(native)
221
+ if sz: col.caption(f"Real Res: {sz[0]}×{sz[1]} px")
222
+ ext = infer_ext(native)
223
+ mime = "image/jpeg" if ext.lower() in [".jpg",".jpeg"] else ("image/png" if ext.lower()==".png" else "image/webp")
224
+ col.download_button("Download (Full Quality)", data=native,
225
+ file_name=f"{filename_stub}{ext if ext!='.bin' else '.jpg'}",
226
+ mime=mime, key=f"{key_prefix}_{filename_stub}_dl")
227
+ else:
228
+ col.caption("—")
229
+
230
+ return display_url or "data", native
231
+
232
+ def rgba_to_rgb_on_bg(img_rgba: Image.Image, bg_rgb=(255,255,255)) -> Image.Image:
233
+ """RGBA görseli seçilen arka plana kompoze ederek RGB'ye çevir (siyah sorununu çözer)."""
234
+ if img_rgba.mode != "RGBA":
235
+ return img_rgba.convert("RGB")
236
+ bg = Image.new("RGBA", img_rgba.size, (*bg_rgb, 255))
237
+ bg.paste(img_rgba, (0,0), img_rgba)
238
+ return bg.convert("RGB")
239
+
240
+ @st.cache_data(ttl=300, show_spinner=False)
241
+ def make_small_jpeg_from_native(native: bytes, target_long_edge: int = 1280, bg_rgb=(255,255,255)) -> bytes:
242
+ """Şeffaf PNG → beyaz zemine kompoze → hafif JPEG (piksel piksel yüklenmeyi azaltır)."""
243
+ im = Image.open(io.BytesIO(native))
244
+ if im.mode != "RGBA" and "transparency" not in im.info:
245
+ im = im.convert("RGB")
246
+ else:
247
+ im = im.convert("RGBA")
248
+ w, h = im.size
249
+ if w >= h:
250
+ new_w = min(target_long_edge, w)
251
+ new_h = max(1, int(h * (new_w / max(1, w))))
252
+ else:
253
+ new_h = min(target_long_edge, h)
254
+ new_w = max(1, int(w * (new_h / max(1, h))))
255
+ im2 = im.resize((new_w, new_h), Image.LANCZOS)
256
+ im2_rgb = rgba_to_rgb_on_bg(im2, bg_rgb=bg_rgb)
257
+ out = io.BytesIO(); im2_rgb.save(out, format="JPEG", quality=88, subsampling=1)
258
+ return out.getvalue()
259
+
260
+ def make_preview_frame(img_bytes: bytes, aspect: str, long_edge: int, ratio: float, bg_rgb=(255,255,255)) -> bytes:
261
+ """UI-only: seçilen aspect’te tuval + içerik oranı (JPEG)."""
262
+ im = Image.open(io.BytesIO(img_bytes)).convert("RGBA")
263
+ aw, ah = _parse_aspect_str(aspect)
264
+ if aw >= ah:
265
+ W = max(256, min(8192, int(long_edge))); H = max(1, int(W * ah / aw))
266
+ else:
267
+ H = max(256, min(8192, int(long_edge))); W = max(1, int(H * aw / ah))
268
+ ratio = max(0.10, min(0.99, float(ratio)))
269
+ target = int(min(W, H) * ratio if aw == ah else (H * ratio if aw < ah else W * ratio))
270
+ w, h = im.size
271
+ if w >= h: new_w, new_h = target, max(1, int(h * (target / max(1, w))))
272
+ else: new_h, new_w = target, max(1, int(w * (new_h / max(1, h))))
273
+ im_resized = im.resize((new_w, new_h), Image.LANCZOS)
274
+ canvas = Image.new("RGBA", (W, H), (*bg_rgb, 255))
275
+ off = ((W - new_w)//2, (H - new_h)//2); canvas.paste(im_resized, off, im_resized)
276
+ out = io.BytesIO(); canvas.convert("RGB").save(out, format="JPEG", quality=90, subsampling=1)
277
+ return out.getvalue()
278
+
279
+ # ================= Yerel DEMO dosyaları =================
280
+ def load_local_demo():
281
+ demo = {}
282
+ for fname in ["input.jpg", "packshot.jpg", "model.jpg", "tryon.mp4"]:
283
+ if os.path.exists(fname):
284
+ with open(fname, "rb") as f: demo[fname] = f.read()
285
+ return demo
286
+
287
+ demo_files = load_local_demo()
288
+
289
+ # ================= Sayfa =================
290
+ st.set_page_config(page_title="LamboVision · Car Configurator", layout="wide", page_icon="🏎️")
291
+ inject_base_css()
292
+
293
+ st.title("🏎️ LamboVision · AI Car Studio")
294
+ st.caption("Upload · Configure · Generate Cinematic")
295
+
296
+ ok = backend_ok()
297
+
298
+ # -------- Üst Kontrol Şeridi --------
299
+ col1, col2, col3, col4, col5, col6, col7 = st.columns([1.6, 1.6, 1.0, 1.2, 0.9, 1.1, 0.9])
300
+ with col1:
301
+ file_list = st.file_uploader("Car Image (Upload)", type=["jpg","jpeg","png","webp"], accept_multiple_files=True, key="file_upl")
302
+ with col2:
303
+ image_url = st.text_input("Or URL", key="image_url", placeholder="https://... (optional)")
304
+ with col3:
305
+ # Backend Category: otomotive indirgenmiş set
306
+ jewel_type = st.selectbox("Category", ["auto","car","vehicle"], index=0, key="jewel_type")
307
+ with col4:
308
+ 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,
309
+ help="Sadece önizleme kadrajında büyüklüğü etkiler.", key="preview_ratio")
310
+ with col5:
311
+ upscale = st.checkbox("Super Res", False, key="upscale")
312
+ with col6:
313
+ upscale_stage = st.selectbox("SR Step", ["both","final","packshot"], index=0, help="Varsayılan: both", key="upscale_stage")
314
+ with col7:
315
+ upscale_factor = st.selectbox("SR Factor", ["2","4"], index=0, key="upscale_factor")
316
+
317
+ colA, colB, colC, colD, colE, colF = st.columns([1.0, 1.0, 1.1, 0.9, 0.9, 1.2])
318
+ with colA:
319
+ st.info(f"Connection: {'Online' if ok else 'Offline'}", icon="🔌")
320
+ with colB:
321
+ identity_lock = st.checkbox("Identity lock", True, key="identity_lock")
322
+ with colC:
323
+ to_video = st.checkbox("One Click Generate Video", False, key="to_video")
324
+ with colD:
325
+ duration = st.selectbox("Duration ", VIDEO_DUR_OPTIONS, index=0, key="duration_sel")
326
+ with colE:
327
+ resolution = st.selectbox("Video Res", VIDEO_RES_OPTIONS, index=1, key="resolution_sel")
328
+ with colF:
329
+ run = st.button("Run 🏁", type="primary", use_container_width=True, key="run_btn")
330
+
331
+ # Tuval/kadraj + fit/fill
332
+ colT1, colT2, colT3 = st.columns([1.0, 1.0, 1.0])
333
+ with colT1:
334
+ preview_aspect = st.selectbox("Preview Frame Ratio", ASPECT_OPTIONS, index=0, key="preview_aspect")
335
+ with colT2:
336
+ preview_long_edge = st.number_input("Preview Long Edge (px)", min_value=256, max_value=8192, value=1920, step=64, key="preview_long_edge")
337
+ with colT3:
338
+ fit_mode = st.selectbox("Preview Layout", ["fit","fill"], index=0, help="Sadece önizlemeyi etkiler.", key="fit_mode")
339
+
340
+ # Inject CSS (uniform kartlar)
341
+ inject_preview_css(preview_aspect, fit_mode="contain" if fit_mode=="fit" else "cover")
342
+
343
+ # ================= PRE-RUN PREVIEWS =================
344
+ st.subheader("Previews")
345
+ col_in, col_pack, col_pad, col_vid = st.columns(4)
346
+
347
+ # Input bytes (upload/URL öncelikli; yoksa demo)
348
+ input_bytes = None
349
+ if file_list:
350
+ try: input_bytes = file_list[0].getvalue()
351
+ except Exception: input_bytes = None
352
+ elif image_url:
353
+ input_bytes = fetch_bytes(image_url)
354
+ elif demo_files.get("input.jpg"):
355
+ input_bytes = demo_files["input.jpg"]
356
+
357
+ show_tile_card_display_download(
358
+ col_in, "Sample Input preview",
359
+ display_bytes=input_bytes if input_bytes else demo_files.get("input.jpg"),
360
+ download_bytes=input_bytes if input_bytes else demo_files.get("input.jpg"),
361
+ filename_stub="input", key_prefix="pre"
362
+ )
363
+
364
+ # Packshot preview (demo dosyası varsa; yoksa input görüntü)
365
+ pack_bytes_demo = demo_files.get("packshot.jpg") or input_bytes
366
+ show_tile_card_display_download(
367
+ col_pack, "Sample Packshot (Studio)",
368
+ display_bytes=pack_bytes_demo,
369
+ download_bytes=pack_bytes_demo,
370
+ filename_stub="packshot", key_prefix="pre"
371
+ )
372
+
373
+ # Padded preview (packshot.jpg veya input.jpg → seçilen kadraja, UI-only)
374
+ padded_bytes = None
375
+ if pack_bytes_demo:
376
+ try:
377
+ padded_bytes = make_preview_frame(pack_bytes_demo, aspect=preview_aspect,
378
+ long_edge=int(preview_long_edge),
379
+ ratio=float(preview_ratio))
380
+ except Exception:
381
+ padded_bytes = None
382
+ show_tile_card_display_download(
383
+ col_pad, "Sample Padded Preview ",
384
+ display_bytes=padded_bytes or pack_bytes_demo,
385
+ download_bytes=padded_bytes or pack_bytes_demo,
386
+ filename_stub="padded_ui", key_prefix="pre"
387
+ )
388
+
389
+ # Video preview (loop; yerel tryon.mp4 varsa)
390
+ vid_demo = demo_files.get("tryon.mp4")
391
+ col_vid.markdown('<div class="lb-card-title">AI Generated Video Preview </div>', unsafe_allow_html=True)
392
+ if vid_demo:
393
+ data_url = "data:video/mp4;base64," + base64.b64encode(vid_demo).decode("ascii")
394
+ col_vid.markdown(
395
+ f"""
396
+ <div class="lb-frame" style="display:flex;align-items:center;justify-content:center;">
397
+ <video autoplay loop muted playsinline style="width:100%;height:100%;object-fit:cover;">
398
+ <source src="{data_url}" type="video/mp4">
399
+ </video>
400
+ </div>
401
+ """, unsafe_allow_html=True
402
+ )
403
+ col_vid.download_button("Download Video (MP4)", data=vid_demo, file_name="tryon.mp4", mime="video/mp4", key="pre_video_dl")
404
+ else:
405
+ col_vid.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
406
+ col_vid.caption("—")
407
+
408
+ # ================= ÇALIŞTIR =================
409
+ if run:
410
+ if not ok:
411
+ st.error("Backend erişilemiyor. API_BASE / TOKEN kontrol edin.")
412
+ elif not (file_list or image_url or demo_files.get("input.jpg")):
413
+ st.error("En az bir görsel girişi yapın (dosya yükle veya URL).")
414
+ else:
415
+ try:
416
+ img_urls = image_url or ""
417
+ files_payload = []
418
+ if file_list:
419
+ for f in file_list:
420
+ files_payload.append(("files", (f.name, f.getvalue(), f.type or "image/jpeg")))
421
+
422
+ data = {
423
+ "category": st.session_state.get("jewel_type","auto"),
424
+ "edit_prompt": "", # backend, boşsa otomotiv packshot prompt’u kullanır
425
+ "num_images": "1",
426
+ "image_urls": img_urls,
427
+ "mannequin_image_url": "", # otomotivde kullanılmıyor
428
+ "identity_lock": "true" if identity_lock else "false",
429
+ # Preview controls (backend pad/preview için)
430
+ "preview_aspect": preview_aspect,
431
+ "preview_long_edge": str(int(preview_long_edge)),
432
+ "preview_ratio": str(float(preview_ratio)),
433
+ "padding_ratio": str(float(preview_ratio)), # backward-compat
434
+ # SR
435
+ "upscale": "true" if upscale else "false",
436
+ "upscale_factor": st.session_state.get("upscale_factor","2"),
437
+ "upscale_stage": st.session_state.get("upscale_stage","both"),
438
+ # Video (opsiyonel zincir)
439
+ "to_video": "true" if to_video else "false",
440
+ "video_prompt": "", # backend default: CAR_LIFESTYLE_PROMPT
441
+ "duration": st.session_state.get("duration_sel", VIDEO_DUR_OPTIONS[0]),
442
+ "resolution": st.session_state.get("resolution_sel", VIDEO_RES_OPTIONS[1]),
443
+ "prompt_optimizer": "false",
444
+ }
445
+
446
+ with st.spinner("AI Chain Running…"):
447
+ out = post_chain(data, files_payload if files_payload else None)
448
+
449
+ st.session_state["job_counter"] += 1
450
+
451
+ # ---- ÇIKTILAR ----
452
+ # Packshot NATIVE → DISPLAY küçük JPEG (şeffaflık beyaza kompoze)
453
+ pack_native_url = None; pack_display_jpeg = None
454
+ try:
455
+ pack_native_url = (out["packshot_step"]["result"]["images_native"] or [{}])[0].get("url")
456
+ if pack_native_url:
457
+ pn = fetch_bytes(pack_native_url)
458
+ if pn: pack_display_jpeg = make_small_jpeg_from_native(pn, 1280, bg_rgb=(255,255,255))
459
+ except Exception: pass
460
+
461
+ # Padded NATIVE → DISPLAY küçük JPEG (pad etkisi görünür)
462
+ padded_native_url = None; padded_display_jpeg = None
463
+ try:
464
+ padded_native_url = (out["packshot_step"]["result"]["padded_native"] or [{}])[0].get("url")
465
+ if padded_native_url:
466
+ nb = fetch_bytes(padded_native_url)
467
+ if nb: padded_display_jpeg = make_small_jpeg_from_native(nb, 1280, bg_rgb=(255,255,255))
468
+ except Exception: pass
469
+
470
+ # Model/placement (legacy; otomotivde yoksa boş kalabilir)
471
+ placed_native_url = None; placed_display_jpeg = None
472
+ try:
473
+ placed_native_url = (out.get("image_step") or {}).get("result", {}).get("images_native", [{}])[0].get("url")
474
+ if placed_native_url:
475
+ mn = fetch_bytes(placed_native_url)
476
+ if mn: placed_display_jpeg = make_small_jpeg_from_native(mn, 1280, bg_rgb=(255,255,255))
477
+ except Exception: pass
478
+
479
+ # Video (zincirde üretildiyse)
480
+ vurl = None
481
+ try:
482
+ vurl = (out.get("video_step") or {}).get("result", {}).get("video", {}).get("url")
483
+ except Exception:
484
+ vurl = None
485
+
486
+ # UI ipucu
487
+ ui_hints = (out.get("video_step") or {}).get("ui_hints") or {}
488
+ if isinstance(ui_hints, dict):
489
+ st.session_state["video_ui_max_px"] = int(ui_hints.get("suggested_video_max_px", VIDEO_MAX_PX_DEFAULT))
490
+
491
+ st.session_state["results"] = {
492
+ "job_id": out.get("job_id"),
493
+ "schema_version": out.get("schema_version"),
494
+ "packshot_native_url": pack_native_url,
495
+ "packshot_display_jpeg": pack_display_jpeg,
496
+ "padded_native_url": padded_native_url,
497
+ "padded_display_jpeg": padded_display_jpeg,
498
+ "placed_native_url": placed_native_url,
499
+ "placed_display_jpeg": placed_display_jpeg,
500
+ "video_url": vurl,
501
+ "api_base": API_BASE,
502
+ "has_auth_header": bool(HEADERS),
503
+ "preview_aspect": preview_aspect,
504
+ }
505
+
506
+ except requests.HTTPError as e:
507
+ st.error(f"HTTP {e.response.status_code}")
508
+ except Exception as e:
509
+ st.error(f"Hata: {e}")
510
+
511
+ # ================= SONUÇLAR =================
512
+ res = st.session_state.get("results")
513
+ vbytes = None
514
+ if res:
515
+ st.subheader("Results")
516
+ c_pack, c_pad, c_model, c_vid = st.columns(4)
517
+
518
+ # Packshot (backend) — DISPLAY = küçük JPEG, DOWNLOAD = NATIVE
519
+ show_tile_card_display_download(
520
+ c_pack, "Packshot (Studio)",
521
+ display_bytes=res.get("packshot_display_jpeg"),
522
+ download_url=res.get("packshot_native_url"),
523
+ filename_stub="packshot_native",
524
+ key_prefix=f"job{st.session_state['job_counter']}"
525
+ )
526
+
527
+ # Padded (backend) — DISPLAY = padded küçük JPEG, DOWNLOAD = padded NATIVE
528
+ show_tile_card_display_download(
529
+ c_pad, "Padded",
530
+ display_bytes=res.get("padded_display_jpeg"),
531
+ download_url=res.get("padded_native_url"),
532
+ filename_stub="padded_backend",
533
+ key_prefix=f"job{st.session_state['job_counter']}"
534
+ )
535
+
536
+ # Placement (legacy) — DISPLAY = küçük JPEG, DOWNLOAD = NATIVE
537
+ show_tile_card_display_download(
538
+ c_model, "Composite",
539
+ display_bytes=res.get("placed_display_jpeg"),
540
+ download_url=res.get("placed_native_url"),
541
+ filename_stub="composite_native",
542
+ key_prefix=f"job{st.session_state['job_counter']}"
543
+ )
544
+
545
+ # Video
546
+ vurl = res.get("video_url")
547
+ c_vid.markdown('<div class="lb-card-title">AI Generated Video</div>', unsafe_allow_html=True)
548
+ if vurl:
549
+ abs_v = _abs_backend_url(vurl)
550
+ c_vid.markdown(
551
+ f"""
552
+ <div class="lb-frame" style="display:flex;align-items:center;justify-content:center;">
553
+ <video autoplay loop muted controls playsinline style="width:100%;height:100%;object-fit:cover;">
554
+ <source src="{abs_v}" type="video/mp4">
555
+ </video>
556
+ </div>
557
+ """, unsafe_allow_html=True
558
+ )
559
+ vb = fetch_bytes(abs_v)
560
+ if vb:
561
+ vbytes = vb
562
+ c_vid.download_button("Download Video (MP4)", data=vb, file_name="lambovision_video.mp4",
563
+ mime="video/mp4", key=f"job{st.session_state['job_counter']}_video_dl")
564
+ else:
565
+ c_vid.markdown('<div class="lb-frame"></div>', unsafe_allow_html=True)
566
+ # ---- Generate video on demand ----
567
+ vid_checkbox_key = f"video_toggle_job{st.session_state['job_counter']}"
568
+ if st.checkbox("Generate Video From This Result", value=False, key=vid_checkbox_key):
569
+ src_for_video = res.get("placed_native_url") or res.get("packshot_native_url")
570
+ if not src_for_video:
571
+ st.warning("Video için kullanılacak native görsel bulunamadı.")
572
+ else:
573
+ with st.spinner("Generating Video …"):
574
+ try:
575
+ v = post_video(
576
+ src_for_video,
577
+ duration=st.session_state.get("duration_sel", VIDEO_DUR_OPTIONS[0]),
578
+ resolution=st.session_state.get("resolution_sel", VIDEO_RES_OPTIONS[1]),
579
+ preview_aspect=st.session_state.get("preview_aspect","16:9"),
580
+ prompt_optimizer=False,
581
+ )
582
+ except requests.HTTPError as e:
583
+ st.error(f"HTTP {e.response.status_code}")
584
+ v = None
585
+ if v:
586
+ vurl2 = (v.get("result") or {}).get("video", {}).get("url")
587
+ ui_hints = v.get("ui_hints") or {}
588
+ if vurl2:
589
+ st.session_state["results"]["video_url"] = vurl2
590
+ if isinstance(ui_hints, dict):
591
+ st.session_state["video_ui_max_px"] = int(ui_hints.get("suggested_video_max_px", VIDEO_MAX_PX_DEFAULT))
592
+ st.session_state.pop(vid_checkbox_key, None)
593
+ st.success("Video is Ready! Showing preview…")
594
+ st.rerun()
595
+ else:
596
+ st.info("Video URL gelmedi.")
597
+
598
+ # Native ZIP
599
+ named = []
600
+ pn = fetch_bytes(res.get("packshot_native_url")) if res.get("packshot_native_url") else None
601
+ mn = fetch_bytes(res.get("placed_native_url")) if res.get("placed_native_url") else None
602
+ if pn: named.append((f"packshot_native{infer_ext(pn)}", pn))
603
+ if mn: named.append((f"composite_native{infer_ext(mn)}", mn))
604
+ if vbytes: named.append(("video.mp4", vbytes))
605
+ if named:
606
+ zip_bytes = make_zip(named)
607
+ st.download_button("Download All (ZIP)", data=zip_bytes,
608
+ file_name="lambovision_outputs.zip", mime="application/zip",
609
+ key=f"job{st.session_state['job_counter']}_zip_dl")
610
+
611
+ # ================= Sidebar =================
612
+ with st.sidebar:
613
+ st.caption(f"API_BASE: {API_BASE}")
614
+ if HF_TOKEN: st.caption("Auth: Bearer (aktif)")
615
+ st.slider("Video önizleme genişliği (px)", 360, 1080, st.session_state["video_ui_max_px"],
616
+ step=10, key="video_ui_max_px")
617
+ if st.button("Önbelleği temizle"): st.cache_data.clear(); st.success("Önbellek temizlendi.")
618
+ if st.button("Son çıktıları temizle"): st.session_state["results"] = None; st.success("Çıktılar temizlendi.")
tryon.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f765897c9f290758536c84e4ca71562bd5d68cc0baa79c7c6922a8ed28f1dd67
3
+ size 2514851