Spaces:
Sleeping
Sleeping
CB commited on
Update streamlit_app.py
Browse files- streamlit_app.py +126 -34
streamlit_app.py
CHANGED
|
@@ -28,8 +28,9 @@ except Exception:
|
|
| 28 |
# google.generativeai SDK (guarded)
|
| 29 |
try:
|
| 30 |
import google.generativeai as genai
|
| 31 |
-
|
| 32 |
-
|
|
|
|
| 33 |
HAS_GENAI = True
|
| 34 |
except Exception:
|
| 35 |
genai = None
|
|
@@ -94,9 +95,7 @@ def convert_video_to_mp4(video_path: str) -> str:
|
|
| 94 |
try:
|
| 95 |
ffmpeg.input(video_path).output(target_path).run(overwrite_output=True, quiet=True)
|
| 96 |
except Exception:
|
| 97 |
-
# re-raise so caller can handle
|
| 98 |
raise
|
| 99 |
-
# remove source only if different and successful
|
| 100 |
if os.path.exists(target_path) and os.path.getsize(target_path) > 0:
|
| 101 |
try:
|
| 102 |
if str(Path(video_path).resolve()) != str(Path(target_path).resolve()):
|
|
@@ -152,8 +151,21 @@ def file_name_or_id(file_obj):
|
|
| 152 |
if file_obj is None:
|
| 153 |
return None
|
| 154 |
if isinstance(file_obj, dict):
|
| 155 |
-
return file_obj.get("name") or file_obj.get("id")
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
def get_effective_api_key():
|
| 159 |
return st.session_state.get("api_key") or os.getenv("GOOGLE_API_KEY")
|
|
@@ -203,7 +215,6 @@ def clear_all_video_state():
|
|
| 203 |
# Reset when URL changes (compare against last_url only)
|
| 204 |
current_url = st.session_state.get("url", "")
|
| 205 |
if current_url != st.session_state.get("last_url"):
|
| 206 |
-
# avoid clearing on first load when last_url is empty
|
| 207 |
if st.session_state.get("last_url"):
|
| 208 |
clear_all_video_state()
|
| 209 |
st.session_state["last_url"] = current_url
|
|
@@ -254,41 +265,120 @@ safety_settings = [
|
|
| 254 |
]
|
| 255 |
|
| 256 |
# ---- Upload & processing helpers ----
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
def upload_video_sdk(filepath: str):
|
| 258 |
key = get_effective_api_key()
|
| 259 |
if not key:
|
| 260 |
raise RuntimeError("No API key provided")
|
| 261 |
-
if not HAS_GENAI or
|
| 262 |
raise RuntimeError("google.generativeai SDK not available; cannot upload")
|
|
|
|
| 263 |
genai.configure(api_key=key)
|
| 264 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
|
| 266 |
def wait_for_processed(file_obj, timeout: int = None):
|
| 267 |
if timeout is None:
|
| 268 |
timeout = st.session_state.get("processing_timeout", 900)
|
| 269 |
-
if not HAS_GENAI or
|
| 270 |
return file_obj
|
| 271 |
start = time.time()
|
| 272 |
name = file_name_or_id(file_obj)
|
|
|
|
| 273 |
if not name:
|
| 274 |
return file_obj
|
|
|
|
| 275 |
backoff = 1.0
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
if not state or getattr(state, "name", None) != "PROCESSING":
|
| 288 |
-
return obj
|
| 289 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
if time.time() - start > timeout:
|
| 291 |
-
raise TimeoutError("File processing timed out")
|
| 292 |
time.sleep(backoff)
|
| 293 |
backoff = min(backoff * 2, 8.0)
|
| 294 |
|
|
@@ -341,9 +431,8 @@ def compress_video_if_large(local_path: str, threshold_mb: int = 200):
|
|
| 341 |
# ---- Simple layout ----
|
| 342 |
col1, col2 = st.columns([1, 3])
|
| 343 |
with col1:
|
| 344 |
-
generate_now = st.button("Generate the story", type="primary", disabled=not bool(get_effective_api_key()))
|
| 345 |
with col2:
|
| 346 |
-
# small UX note column
|
| 347 |
if not st.session_state.get("videos"):
|
| 348 |
st.info("Load a video first (sidebar) to enable generation.", icon="ℹ️")
|
| 349 |
else:
|
|
@@ -355,7 +444,6 @@ if st.sidebar.button("Load Video", use_container_width=True):
|
|
| 355 |
path = download_video_ytdlp(st.session_state.get("url", ""), str(DATA_DIR), vpw)
|
| 356 |
st.session_state["videos"] = path
|
| 357 |
st.session_state["last_local_path"] = path
|
| 358 |
-
# keep last_url intact — it tracks the input URL
|
| 359 |
st.session_state.pop("uploaded_file", None)
|
| 360 |
st.session_state.pop("processed_file", None)
|
| 361 |
try:
|
|
@@ -367,7 +455,6 @@ if st.sidebar.button("Load Video", use_container_width=True):
|
|
| 367 |
|
| 368 |
if st.session_state["videos"]:
|
| 369 |
path = st.session_state["videos"]
|
| 370 |
-
# ensure mp4 for preview and read bytes for reliable preview
|
| 371 |
try:
|
| 372 |
mp4_path = convert_video_to_mp4(path)
|
| 373 |
with open(mp4_path, "rb") as vf:
|
|
@@ -398,7 +485,7 @@ if st.session_state["videos"]:
|
|
| 398 |
except Exception:
|
| 399 |
pass
|
| 400 |
|
| 401 |
-
# ---- Generation flow (
|
| 402 |
if generate_now and not st.session_state.get("busy"):
|
| 403 |
if not st.session_state.get("videos"):
|
| 404 |
st.error("No video loaded. Use 'Load Video' in the sidebar.")
|
|
@@ -430,7 +517,6 @@ if generate_now and not st.session_state.get("busy"):
|
|
| 430 |
reupload_needed = True
|
| 431 |
uploaded_file = st.session_state.get("uploaded_file")
|
| 432 |
uploaded_name = file_name_or_id(uploaded_file)
|
| 433 |
-
# Use last_local_path to determine if file changed
|
| 434 |
if processed and st.session_state.get("last_local_path") == current_path and st.session_state.get("file_hash") == current_hash and uploaded_name:
|
| 435 |
reupload_needed = False
|
| 436 |
|
|
@@ -446,7 +532,8 @@ if generate_now and not st.session_state.get("busy"):
|
|
| 446 |
except Exception as e:
|
| 447 |
st.session_state["last_error"] = f"Upload failed for {upload_path}: {e}\n{traceback.format_exc()}"
|
| 448 |
st.error(f"Upload failed: {e}. Check the error log for more details.")
|
| 449 |
-
|
|
|
|
| 450 |
|
| 451 |
try:
|
| 452 |
processing_placeholder = st.empty()
|
|
@@ -461,6 +548,7 @@ if generate_now and not st.session_state.get("busy"):
|
|
| 461 |
except Exception as e:
|
| 462 |
st.session_state["last_error"] = f"Processing failed/wait timeout: {e}"
|
| 463 |
st.error("Video processing failed or timed out. See Last Error.")
|
|
|
|
| 464 |
raise
|
| 465 |
|
| 466 |
st.session_state["uploaded_file"] = uploaded
|
|
@@ -501,7 +589,6 @@ if generate_now and not st.session_state.get("busy"):
|
|
| 501 |
debug_info["agent_error"] = f"{ae}"
|
| 502 |
|
| 503 |
if not out:
|
| 504 |
-
# Use Responses API directly
|
| 505 |
def generate_via_responses_api(prompt_text: str, processed, model_used: str, max_tokens: int = 1024, timeout: int = 300):
|
| 506 |
key = get_effective_api_key()
|
| 507 |
if not key:
|
|
@@ -544,7 +631,6 @@ if generate_now and not st.session_state.get("busy"):
|
|
| 544 |
outputs = []
|
| 545 |
if response is None:
|
| 546 |
return ""
|
| 547 |
-
# response may be SDK object or dict-like; coerce to string chunks
|
| 548 |
text_pieces = []
|
| 549 |
try:
|
| 550 |
if isinstance(response, dict):
|
|
@@ -567,6 +653,12 @@ if generate_now and not st.session_state.get("busy"):
|
|
| 567 |
text_pieces.append(str(v).strip())
|
| 568 |
break
|
| 569 |
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
text_pieces.append(str(response))
|
| 571 |
except Exception:
|
| 572 |
text_pieces.append(str(response))
|
|
@@ -611,4 +703,4 @@ if generate_now and not st.session_state.get("busy"):
|
|
| 611 |
st.session_state["last_error"] = f"{e}\n{traceback.format_exc()}"
|
| 612 |
st.error("An error occurred while generating the story. You can try Generate again; the uploaded video will be reused.")
|
| 613 |
finally:
|
| 614 |
-
st.session_state["busy"] = False
|
|
|
|
| 28 |
# google.generativeai SDK (guarded)
|
| 29 |
try:
|
| 30 |
import google.generativeai as genai
|
| 31 |
+
# older SDK exposed upload_file/get_file at top-level; try to bind them if present
|
| 32 |
+
upload_file = getattr(genai, "upload_file", None)
|
| 33 |
+
get_file = getattr(genai, "get_file", None)
|
| 34 |
HAS_GENAI = True
|
| 35 |
except Exception:
|
| 36 |
genai = None
|
|
|
|
| 95 |
try:
|
| 96 |
ffmpeg.input(video_path).output(target_path).run(overwrite_output=True, quiet=True)
|
| 97 |
except Exception:
|
|
|
|
| 98 |
raise
|
|
|
|
| 99 |
if os.path.exists(target_path) and os.path.getsize(target_path) > 0:
|
| 100 |
try:
|
| 101 |
if str(Path(video_path).resolve()) != str(Path(target_path).resolve()):
|
|
|
|
| 151 |
if file_obj is None:
|
| 152 |
return None
|
| 153 |
if isinstance(file_obj, dict):
|
| 154 |
+
return file_obj.get("name") or file_obj.get("id") or file_obj.get("fileId")
|
| 155 |
+
# SDK objects might expose .name, .id, .fileId, or nested fields
|
| 156 |
+
for attr in ("name", "id", "fileId", "file_id"):
|
| 157 |
+
v = getattr(file_obj, attr, None)
|
| 158 |
+
if v:
|
| 159 |
+
return v
|
| 160 |
+
# sometimes SDK returns {'file': {...}}
|
| 161 |
+
try:
|
| 162 |
+
if hasattr(file_obj, "to_dict"):
|
| 163 |
+
d = file_obj.to_dict()
|
| 164 |
+
if isinstance(d, dict):
|
| 165 |
+
return d.get("name") or d.get("id") or d.get("fileId")
|
| 166 |
+
except Exception:
|
| 167 |
+
pass
|
| 168 |
+
return None
|
| 169 |
|
| 170 |
def get_effective_api_key():
|
| 171 |
return st.session_state.get("api_key") or os.getenv("GOOGLE_API_KEY")
|
|
|
|
| 215 |
# Reset when URL changes (compare against last_url only)
|
| 216 |
current_url = st.session_state.get("url", "")
|
| 217 |
if current_url != st.session_state.get("last_url"):
|
|
|
|
| 218 |
if st.session_state.get("last_url"):
|
| 219 |
clear_all_video_state()
|
| 220 |
st.session_state["last_url"] = current_url
|
|
|
|
| 265 |
]
|
| 266 |
|
| 267 |
# ---- Upload & processing helpers ----
|
| 268 |
+
def _normalize_uploaded_obj(obj):
|
| 269 |
+
"""
|
| 270 |
+
Normalize possible upload_file return shapes:
|
| 271 |
+
- SDK object with .name or .id
|
| 272 |
+
- dict with 'name' or 'id'
|
| 273 |
+
- legacy or ragstore shapes: {'file': {...}} etc.
|
| 274 |
+
Return a dict-like wrapper with at least 'name' key or original obj.
|
| 275 |
+
"""
|
| 276 |
+
if obj is None:
|
| 277 |
+
return None
|
| 278 |
+
if isinstance(obj, dict):
|
| 279 |
+
# common keys
|
| 280 |
+
name = obj.get("name") or obj.get("id") or obj.get("fileId") or (obj.get("file") and obj["file"].get("name"))
|
| 281 |
+
if name:
|
| 282 |
+
return {"name": name, "_raw": obj}
|
| 283 |
+
return obj
|
| 284 |
+
# SDK object: try attributes and to_dict
|
| 285 |
+
for attr in ("name", "id", "fileId", "file_id"):
|
| 286 |
+
v = getattr(obj, attr, None)
|
| 287 |
+
if v:
|
| 288 |
+
return {"name": v, "_raw": obj}
|
| 289 |
+
try:
|
| 290 |
+
if hasattr(obj, "to_dict"):
|
| 291 |
+
d = obj.to_dict()
|
| 292 |
+
if isinstance(d, dict):
|
| 293 |
+
name = d.get("name") or d.get("id") or d.get("fileId") or (d.get("file") and d["file"].get("name"))
|
| 294 |
+
if name:
|
| 295 |
+
return {"name": name, "_raw": obj}
|
| 296 |
+
except Exception:
|
| 297 |
+
pass
|
| 298 |
+
return {"name": None, "_raw": obj}
|
| 299 |
+
|
| 300 |
def upload_video_sdk(filepath: str):
|
| 301 |
key = get_effective_api_key()
|
| 302 |
if not key:
|
| 303 |
raise RuntimeError("No API key provided")
|
| 304 |
+
if not HAS_GENAI or genai is None:
|
| 305 |
raise RuntimeError("google.generativeai SDK not available; cannot upload")
|
| 306 |
+
# prefer upload_file if present, otherwise try genai.ragstore or genai.files.upload style
|
| 307 |
genai.configure(api_key=key)
|
| 308 |
+
last_exc = None
|
| 309 |
+
# try a few known entrypoints
|
| 310 |
+
candidate_calls = []
|
| 311 |
+
if upload_file:
|
| 312 |
+
candidate_calls.append(("upload_file", upload_file))
|
| 313 |
+
# sometimes SDK exposed as genai.ragstore.upload_file or genai.files.upload
|
| 314 |
+
candidate_calls.append(("genai.ragstore.upload_file", getattr(genai, "ragstore", None) and getattr(genai.ragstore, "upload_file", None)))
|
| 315 |
+
candidate_calls.append(("genai.files.upload", getattr(genai, "files", None) and getattr(genai.files, "upload", None)))
|
| 316 |
+
candidate_calls.append(("genai.upload", getattr(genai, "upload", None)))
|
| 317 |
+
# filter none
|
| 318 |
+
candidate_calls = [(n, fn) for n, fn in candidate_calls if fn]
|
| 319 |
+
if not candidate_calls:
|
| 320 |
+
raise RuntimeError("No upload function available in google.generativeai SDK")
|
| 321 |
+
for name, fn in candidate_calls:
|
| 322 |
+
try:
|
| 323 |
+
res = fn(filepath)
|
| 324 |
+
norm = _normalize_uploaded_obj(res)
|
| 325 |
+
# ensure we return something that file_name_or_id understands
|
| 326 |
+
return norm if isinstance(norm, dict) else res
|
| 327 |
+
except Exception as e:
|
| 328 |
+
last_exc = e
|
| 329 |
+
continue
|
| 330 |
+
raise RuntimeError(f"All upload methods failed. Last error: {last_exc}")
|
| 331 |
|
| 332 |
def wait_for_processed(file_obj, timeout: int = None):
|
| 333 |
if timeout is None:
|
| 334 |
timeout = st.session_state.get("processing_timeout", 900)
|
| 335 |
+
if not HAS_GENAI or genai is None:
|
| 336 |
return file_obj
|
| 337 |
start = time.time()
|
| 338 |
name = file_name_or_id(file_obj)
|
| 339 |
+
# If no determinable name/id, just return file_obj
|
| 340 |
if not name:
|
| 341 |
return file_obj
|
| 342 |
+
genai.configure(api_key=get_effective_api_key())
|
| 343 |
backoff = 1.0
|
| 344 |
+
last_exc = None
|
| 345 |
+
# prefer get_file if present, otherwise try genai.ragstore.get or genai.files.get
|
| 346 |
+
candidate_getters = []
|
| 347 |
+
if get_file:
|
| 348 |
+
candidate_getters.append(("get_file", get_file))
|
| 349 |
+
candidate_getters.append(("genai.ragstore.get", getattr(genai, "ragstore", None) and getattr(genai.ragstore, "get", None)))
|
| 350 |
+
candidate_getters.append(("genai.files.get", getattr(genai, "files", None) and getattr(genai.files, "get", None)))
|
| 351 |
+
candidate_getters = [(n, fn) for n, fn in candidate_getters if fn]
|
| 352 |
+
# If none, return file_obj immediately
|
| 353 |
+
if not candidate_getters:
|
| 354 |
+
return file_obj
|
|
|
|
|
|
|
| 355 |
|
| 356 |
+
while True:
|
| 357 |
+
for name_label, getter in candidate_getters:
|
| 358 |
+
try:
|
| 359 |
+
obj = getter(name)
|
| 360 |
+
# normalize possible SDK object/dict
|
| 361 |
+
# check for state attribute or dict field
|
| 362 |
+
state = None
|
| 363 |
+
if isinstance(obj, dict):
|
| 364 |
+
state = obj.get("state") or (obj.get("status") and {"name": obj.get("status")})
|
| 365 |
+
else:
|
| 366 |
+
state = getattr(obj, "state", None) or getattr(obj, "status", None)
|
| 367 |
+
if not state:
|
| 368 |
+
return obj
|
| 369 |
+
# state might be dict or object with .name
|
| 370 |
+
state_name = state.get("name") if isinstance(state, dict) else getattr(state, "name", None)
|
| 371 |
+
if state_name and state_name.upper() == "PROCESSING":
|
| 372 |
+
# still processing; continue polling
|
| 373 |
+
last_obj = obj
|
| 374 |
+
break
|
| 375 |
+
return obj
|
| 376 |
+
except Exception as e:
|
| 377 |
+
last_exc = e
|
| 378 |
+
# transient errors: backoff and retry until timeout
|
| 379 |
+
continue
|
| 380 |
if time.time() - start > timeout:
|
| 381 |
+
raise TimeoutError(f"File processing timed out. Last error: {last_exc}")
|
| 382 |
time.sleep(backoff)
|
| 383 |
backoff = min(backoff * 2, 8.0)
|
| 384 |
|
|
|
|
| 431 |
# ---- Simple layout ----
|
| 432 |
col1, col2 = st.columns([1, 3])
|
| 433 |
with col1:
|
| 434 |
+
generate_now = st.button("Generate the story", type="primary", disabled=not bool(get_effective_api_key()))
|
| 435 |
with col2:
|
|
|
|
| 436 |
if not st.session_state.get("videos"):
|
| 437 |
st.info("Load a video first (sidebar) to enable generation.", icon="ℹ️")
|
| 438 |
else:
|
|
|
|
| 444 |
path = download_video_ytdlp(st.session_state.get("url", ""), str(DATA_DIR), vpw)
|
| 445 |
st.session_state["videos"] = path
|
| 446 |
st.session_state["last_local_path"] = path
|
|
|
|
| 447 |
st.session_state.pop("uploaded_file", None)
|
| 448 |
st.session_state.pop("processed_file", None)
|
| 449 |
try:
|
|
|
|
| 455 |
|
| 456 |
if st.session_state["videos"]:
|
| 457 |
path = st.session_state["videos"]
|
|
|
|
| 458 |
try:
|
| 459 |
mp4_path = convert_video_to_mp4(path)
|
| 460 |
with open(mp4_path, "rb") as vf:
|
|
|
|
| 485 |
except Exception:
|
| 486 |
pass
|
| 487 |
|
| 488 |
+
# ---- Generation flow (fixed and robust) ----
|
| 489 |
if generate_now and not st.session_state.get("busy"):
|
| 490 |
if not st.session_state.get("videos"):
|
| 491 |
st.error("No video loaded. Use 'Load Video' in the sidebar.")
|
|
|
|
| 517 |
reupload_needed = True
|
| 518 |
uploaded_file = st.session_state.get("uploaded_file")
|
| 519 |
uploaded_name = file_name_or_id(uploaded_file)
|
|
|
|
| 520 |
if processed and st.session_state.get("last_local_path") == current_path and st.session_state.get("file_hash") == current_hash and uploaded_name:
|
| 521 |
reupload_needed = False
|
| 522 |
|
|
|
|
| 532 |
except Exception as e:
|
| 533 |
st.session_state["last_error"] = f"Upload failed for {upload_path}: {e}\n{traceback.format_exc()}"
|
| 534 |
st.error(f"Upload failed: {e}. Check the error log for more details.")
|
| 535 |
+
st.session_state["busy"] = False
|
| 536 |
+
raise
|
| 537 |
|
| 538 |
try:
|
| 539 |
processing_placeholder = st.empty()
|
|
|
|
| 548 |
except Exception as e:
|
| 549 |
st.session_state["last_error"] = f"Processing failed/wait timeout: {e}"
|
| 550 |
st.error("Video processing failed or timed out. See Last Error.")
|
| 551 |
+
st.session_state["busy"] = False
|
| 552 |
raise
|
| 553 |
|
| 554 |
st.session_state["uploaded_file"] = uploaded
|
|
|
|
| 589 |
debug_info["agent_error"] = f"{ae}"
|
| 590 |
|
| 591 |
if not out:
|
|
|
|
| 592 |
def generate_via_responses_api(prompt_text: str, processed, model_used: str, max_tokens: int = 1024, timeout: int = 300):
|
| 593 |
key = get_effective_api_key()
|
| 594 |
if not key:
|
|
|
|
| 631 |
outputs = []
|
| 632 |
if response is None:
|
| 633 |
return ""
|
|
|
|
| 634 |
text_pieces = []
|
| 635 |
try:
|
| 636 |
if isinstance(response, dict):
|
|
|
|
| 653 |
text_pieces.append(str(v).strip())
|
| 654 |
break
|
| 655 |
else:
|
| 656 |
+
# SDK object: try attributes
|
| 657 |
+
for attr in ("output", "candidates", "text", "message", "content"):
|
| 658 |
+
v = getattr(response, attr, None)
|
| 659 |
+
if v:
|
| 660 |
+
text_pieces.append(str(v).strip())
|
| 661 |
+
if not text_pieces:
|
| 662 |
text_pieces.append(str(response))
|
| 663 |
except Exception:
|
| 664 |
text_pieces.append(str(response))
|
|
|
|
| 703 |
st.session_state["last_error"] = f"{e}\n{traceback.format_exc()}"
|
| 704 |
st.error("An error occurred while generating the story. You can try Generate again; the uploaded video will be reused.")
|
| 705 |
finally:
|
| 706 |
+
st.session_state["busy"] = False
|