CB commited on
Commit
37a29fe
·
verified ·
1 Parent(s): 299e637

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +14 -4
streamlit_app.py CHANGED
@@ -14,7 +14,7 @@ import requests
14
 
15
  load_dotenv()
16
 
17
- # Try to import google.generativeai upload/get helpers
18
  try:
19
  import google.generativeai as genai
20
  from google.generativeai import upload_file, get_file
@@ -32,7 +32,7 @@ DATA_DIR.mkdir(exist_ok=True)
32
  st.session_state.setdefault("videos", "")
33
  st.session_state.setdefault("loop_video", True)
34
 
35
- # Sidebar controls
36
  st.sidebar.header("Video Input")
37
  st.sidebar.text_input("Video URL (or local .mp4 path)", key="url", placeholder="Enter Video URL or path")
38
 
@@ -52,6 +52,7 @@ settings_exp.text_input("Video Password", key="video-password", placeholder="Ent
52
  if not API_KEY:
53
  settings_exp.warning("No Google API key provided. Uploading/processing will not work.", icon="⚠️")
54
 
 
55
  safety_settings = [
56
  {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "OFF"},
57
  {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "OFF"},
@@ -59,6 +60,7 @@ safety_settings = [
59
  {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "OFF"},
60
  ]
61
 
 
62
  def sanitize_filename(path_str: str):
63
  name = Path(path_str).name
64
  name = name.lower().translate(str.maketrans("", "", string.punctuation)).replace(" ", "_")
@@ -78,6 +80,7 @@ def convert_video_to_mp4(video_path: str) -> str:
78
  def download_video_ytdlp(url: str, save_dir: str, video_password: str = None) -> str:
79
  if not url:
80
  raise ValueError("No URL provided")
 
81
  if os.path.exists(url) and os.path.isfile(url):
82
  return convert_video_to_mp4(url)
83
  outtmpl = os.path.join(save_dir, "%(id)s.%(ext)s")
@@ -94,6 +97,7 @@ def download_video_ytdlp(url: str, save_dir: str, video_password: str = None) ->
94
  raise FileNotFoundError("Downloaded video not found")
95
  return convert_video_to_mp4(matches[0])
96
 
 
97
  if st.sidebar.button("Load Video", use_container_width=True):
98
  try:
99
  video_password = st.session_state.get("video-password", "")
@@ -102,6 +106,7 @@ if st.sidebar.button("Load Video", use_container_width=True):
102
  except Exception as e:
103
  st.sidebar.error(f"Failed to load video: {e}")
104
 
 
105
  if st.session_state["videos"]:
106
  try:
107
  st.sidebar.video(st.session_state["videos"], loop=st.session_state.get("loop_video", True))
@@ -134,11 +139,13 @@ if st.session_state["videos"]:
134
 
135
  st.sidebar.write("Title:", Path(st.session_state["videos"]).name)
136
 
 
137
  def upload_video(filepath: str):
138
  if not API_KEY:
139
  raise RuntimeError("No API key provided")
140
  if HAS_GENAI and callable(upload_file):
141
  return upload_file(filepath)
 
142
  url = "https://generative.googleapis.com/v1beta2/files?uploadType=multipart"
143
  headers = {"Authorization": f"Bearer {API_KEY}"}
144
  metadata = {"mimeType": "video/mp4", "displayName": Path(filepath).name}
@@ -176,6 +183,7 @@ def poll_file_processed(file_obj, timeout=180):
176
  raise TimeoutError("File processing timed out")
177
  time.sleep(2)
178
 
 
179
  def call_model_with_file(prompt_text: str, uploaded_file_obj):
180
  if not API_KEY:
181
  raise RuntimeError("No API key provided")
@@ -200,8 +208,8 @@ def call_model_with_file(prompt_text: str, uploaded_file_obj):
200
  except Exception:
201
  pass
202
 
203
- # Use the v1 Responses API host and normalized model_id (models/...)
204
- endpoint = f"https://api.generativeai.googleapis.com/v1/{model_id}:generate"
205
  body = {
206
  "input": [
207
  {
@@ -218,6 +226,7 @@ def call_model_with_file(prompt_text: str, uploaded_file_obj):
218
  r.raise_for_status()
219
  return r.json()
220
 
 
221
  if st.button("Generate the story", type="primary"):
222
  if not st.session_state.get("videos"):
223
  st.error("No video loaded. Use 'Load Video' in the sidebar.")
@@ -234,6 +243,7 @@ if st.button("Generate the story", type="primary"):
234
  with st.spinner("Generating description..."):
235
  result = call_model_with_file(prompt_text, processed)
236
 
 
237
  text_out = ""
238
  if isinstance(result, dict):
239
  if "output" in result:
 
14
 
15
  load_dotenv()
16
 
17
+ # Optional Google SDK helpers
18
  try:
19
  import google.generativeai as genai
20
  from google.generativeai import upload_file, get_file
 
32
  st.session_state.setdefault("videos", "")
33
  st.session_state.setdefault("loop_video", True)
34
 
35
+ # UI - Sidebar
36
  st.sidebar.header("Video Input")
37
  st.sidebar.text_input("Video URL (or local .mp4 path)", key="url", placeholder="Enter Video URL or path")
38
 
 
52
  if not API_KEY:
53
  settings_exp.warning("No Google API key provided. Uploading/processing will not work.", icon="⚠️")
54
 
55
+ # Basic safety settings (kept OFF by default)
56
  safety_settings = [
57
  {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "OFF"},
58
  {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "OFF"},
 
60
  {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "OFF"},
61
  ]
62
 
63
+ # Utilities
64
  def sanitize_filename(path_str: str):
65
  name = Path(path_str).name
66
  name = name.lower().translate(str.maketrans("", "", string.punctuation)).replace(" ", "_")
 
80
  def download_video_ytdlp(url: str, save_dir: str, video_password: str = None) -> str:
81
  if not url:
82
  raise ValueError("No URL provided")
83
+ # local file
84
  if os.path.exists(url) and os.path.isfile(url):
85
  return convert_video_to_mp4(url)
86
  outtmpl = os.path.join(save_dir, "%(id)s.%(ext)s")
 
97
  raise FileNotFoundError("Downloaded video not found")
98
  return convert_video_to_mp4(matches[0])
99
 
100
+ # Load video action
101
  if st.sidebar.button("Load Video", use_container_width=True):
102
  try:
103
  video_password = st.session_state.get("video-password", "")
 
106
  except Exception as e:
107
  st.sidebar.error(f"Failed to load video: {e}")
108
 
109
+ # Sidebar preview & options
110
  if st.session_state["videos"]:
111
  try:
112
  st.sidebar.video(st.session_state["videos"], loop=st.session_state.get("loop_video", True))
 
139
 
140
  st.sidebar.write("Title:", Path(st.session_state["videos"]).name)
141
 
142
+ # Upload helpers
143
  def upload_video(filepath: str):
144
  if not API_KEY:
145
  raise RuntimeError("No API key provided")
146
  if HAS_GENAI and callable(upload_file):
147
  return upload_file(filepath)
148
+ # REST upload (legacy v1beta2 upload used by file-based multimodal flows)
149
  url = "https://generative.googleapis.com/v1beta2/files?uploadType=multipart"
150
  headers = {"Authorization": f"Bearer {API_KEY}"}
151
  metadata = {"mimeType": "video/mp4", "displayName": Path(filepath).name}
 
183
  raise TimeoutError("File processing timed out")
184
  time.sleep(2)
185
 
186
+ # Call model (streamlined, using generativeapis host to avoid HF Spaces cert issue)
187
  def call_model_with_file(prompt_text: str, uploaded_file_obj):
188
  if not API_KEY:
189
  raise RuntimeError("No API key provided")
 
208
  except Exception:
209
  pass
210
 
211
+ # Use generativeapis.googleapis.com to avoid hostname mismatch in some environments (Hugging Face Spaces)
212
+ endpoint = f"https://generativeapis.googleapis.com/v1/{model_id}:generate"
213
  body = {
214
  "input": [
215
  {
 
226
  r.raise_for_status()
227
  return r.json()
228
 
229
+ # Main generate action
230
  if st.button("Generate the story", type="primary"):
231
  if not st.session_state.get("videos"):
232
  st.error("No video loaded. Use 'Load Video' in the sidebar.")
 
243
  with st.spinner("Generating description..."):
244
  result = call_model_with_file(prompt_text, processed)
245
 
246
+ # Extract text from common response shapes
247
  text_out = ""
248
  if isinstance(result, dict):
249
  if "output" in result: