Nancy77 commited on
Commit
c949f72
·
verified ·
1 Parent(s): 11d57d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +531 -2
app.py CHANGED
@@ -1,4 +1,533 @@
 
1
  import streamlit as st
 
 
 
 
 
2
 
3
- x = st.slider('Select a value')
4
- st.write(x, 'squared is', x * x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
  import streamlit as st
3
+ import subprocess
4
+ import replicate
5
+ import openai
6
+ import requests
7
+ from PIL import Image
8
 
9
+ import tempfile
10
+ import base64
11
+ from dotenv import load_dotenv
12
+ from io import BytesIO
13
+ from openai import OpenAI
14
+ import re
15
+
16
+ load_dotenv()
17
+ OpenAI.api_key = os.getenv("OPENAI_API_KEY")
18
+ if not OpenAI.api_key:
19
+ raise ValueError("The OpenAI API key must be set in the OPENAI_API_KEY environment variable.")
20
+ client = OpenAI()
21
+
22
+
23
+ def execute_ffmpeg_command(command):
24
+ try:
25
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
26
+ if result.returncode == 0:
27
+ print("FFmpeg command executed successfully.")
28
+ return result.stdout, result.stderr
29
+ else:
30
+ print("Error executing FFmpeg command:")
31
+ return None, result.stderr
32
+ except Exception as e:
33
+ print("An error occurred during FFmpeg execution:")
34
+ return None, str(e)
35
+
36
+
37
+ def execute_fmpeg_command(command):
38
+ try:
39
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
40
+ return result.stdout # Return just the stdout part, not a tuple
41
+ except subprocess.CalledProcessError as e:
42
+ print(f"FFmpeg command failed with error: {e.stderr.decode()}")
43
+ return None
44
+
45
+ def search_keyword(keyword, frame_texts):
46
+ return [index for index, text in st.session_state.frame_texts.items() if keyword.lower() in text.lower()]
47
+ frame_numbers = []
48
+ # Function to generate description for video frames
49
+
50
+ def generate_description(base64_frames):
51
+ try:
52
+ prompt_messages = [
53
+ {
54
+ "role": "user",
55
+ "content": [ " Find the most interesting / impactful portions of a video. The output will be targeted towards social media (like TikTok or Reels) or to news broadcasts. For the provided frames return the most interesting / impactful frames that will hold the interest of an audience and also describe why you chose it. I am trying to fill these frames for a TikTok video. Hence while selecting the frames keep that in mind. You do not have to give me the script of the Tiktok vfideo. Just return the most interesting frames in a sequence that will come for a 10 second tiktok video. List all frame numbers separated by commas at the end like this for eg, Frames : 1,2,4,7,9",
56
+ *map(lambda x: {"image": x, "resize": 428}, base64_frames),
57
+ ],
58
+ },
59
+ ]
60
+ response = client.chat.completions.create(
61
+ model="gpt-4-vision-preview",
62
+ messages=prompt_messages,
63
+ max_tokens=3000,
64
+ )
65
+ description = response.choices[0].message.content
66
+
67
+ # Use regular expression to find frame numbers
68
+ frame_numbers = re.findall(r'Frames\s*:\s*(\d+(?:,\s*\d+)*)', response.choices[0].message.content)
69
+
70
+ # Convert the string of numbers into a list of integers
71
+ if frame_numbers:
72
+ frame_numbers = [int(num) for num in frame_numbers[0].split(',')]
73
+ else:
74
+ frame_numbers = []
75
+
76
+ print("Frame numbers to extract:", frame_numbers)
77
+
78
+ return description, frame_numbers
79
+
80
+ except Exception as e:
81
+ print(f"Error in generate_description: {e}")
82
+ return None, []
83
+
84
+ def generate_video(prompt, num_frames):
85
+ # Run the text-to-video generation job
86
+ output = replicate.run(
87
+ "cjwbw/damo-text-to-video:1e205ea73084bd17a0a3b43396e49ba0d6bc2e754e9283b2df49fad2dcf95755",
88
+ input={"prompt": prompt, "num_frames": num_frames}
89
+ )
90
+ # Print the output URL
91
+ st.success(f"Video generation successful! Output URL: {output}")
92
+ return output
93
+
94
+
95
+ def overlay_text(video_path, dynamic_text, text_effect):
96
+ # Define the text filter based on the selected effect
97
+ if text_effect == "Vertical scroll":
98
+ text_filter = f"drawtext=text='{dynamic_text}':fontsize=24:fontfile=Opensans.ttf:fontcolor=white:box=1:boxcolor=black@0.5:boxborderw=5:x=(w-text_w)/2:y='if(lt(mod(t,10),5*(n-1)/10),(h-text_h)/2+((h+text_h)/10)*mod(t,5), (h-text_h)/2+((h+text_h)/10)*(1-(mod(t,10)/10)))':enable='between(t,0,10*(n-1)/10)"
99
+ elif text_effect == "typing":
100
+ text_filter = f"drawtext=text='{dynamic_text}':subtitles=typewriter.ass:force_style='FontName=Ubuntu Mono,FontSize=100,PrimaryColour=&H00FFFFFF&'"
101
+ elif text_effect == "Horizontal scroll":
102
+ text_filter = f"drawtext=text='{dynamic_text}':fontsize=24:fontfile=OpenSans-Regular.ttf:fontcolor=white:box=1:boxcolor=black@0.5:boxborderw=5:x=(w-text_w)/2:y=(h-text_h)/2:enable='between(t,0,10*(n-1)/10)':x='if(lt(t,10*(n-1)/10),(w-text_w)/2-((w+text_w)/10)*mod(t,10),NAN)'"
103
+ else:
104
+ # Handle the case where none of the conditions are met
105
+ print("Invalid text effect selected.")
106
+ return None
107
+
108
+ # Print the FFmpeg command
109
+ ffmpeg_command = [
110
+ "ffmpeg", "-i", "uploaded_video.mp4",
111
+ "-vf", text_filter,
112
+ "-c:a", "copy", "-y", "text_overlay_video.mp4"
113
+ ]
114
+ print("FFmpeg Command:", " ".join(ffmpeg_command))
115
+
116
+ # Run FFmpeg command to overlay text onto the video with the selected effect
117
+ result = subprocess.run(ffmpeg_command, capture_output=True, text=True)
118
+
119
+ # Check if the process was successful
120
+ if result.returncode == 0:
121
+ # Print the standard output of the command
122
+ print("FFmpeg output:", result.stdout)
123
+ else:
124
+ # Print error message if the process failed
125
+ print("Error running FFmpeg command:", result.stderr)
126
+ return None
127
+
128
+ # Example usage
129
+ overlay_text("input_video.mp4", "Dynamic Text", "Vertical scroll")
130
+
131
+ def text_to_video_section():
132
+ # Set your Replicate API token
133
+ os.environ["REPLICATE_API_TOKEN"] = "r8_Djd5NwqalQ0wwD9jsdBHOtyUhwCiEBU1R5oO6"
134
+ st.title("Text-to-Video Generation")
135
+
136
+ # Input prompt from user
137
+ prompt = st.text_input("Enter your prompt:", "batman riding a horse")
138
+
139
+ # Number of frames input from user
140
+ num_frames = st.slider("Select number of frames:", min_value=1, max_value=100, value=50)
141
+
142
+ # Button to trigger text-to-video generation
143
+ if st.button("Generate Video"):
144
+ video_path = generate_video(prompt, num_frames)
145
+ st.video(video_path)
146
+
147
+ # Input field for dynamic text
148
+ dynamic_text = st.text_input("Enter dynamic text:", "Your dynamic text here")
149
+
150
+ # Dropdown for selecting text effects
151
+ text_effects = ["None", "Vertical scroll", "Typing", "Horizontal scroll"]
152
+ selected_effect = st.selectbox("Select text effect:", text_effects)
153
+
154
+ # Button to overlay text onto the video
155
+ if st.button("Add Text"):
156
+ if not os.path.exists("uploaded_video.mp4"):
157
+ st.error("Please upload a video first.")
158
+ else:
159
+ if selected_effect != "None":
160
+ # Convert selected effect to lowercase
161
+ selected_effect_lower = selected_effect.lower()
162
+ result_video = overlay_text("uploaded_video.mp4", dynamic_text, selected_effect_lower)
163
+ if result_video:
164
+ st.video(result_video)
165
+ else:
166
+ st.error("Please select a text effect.")
167
+
168
+
169
+ def extract_keywords(article):
170
+
171
+ prompt = f"Grab 5 keywords from {article} and add .jpg at the end of the keywords"
172
+
173
+ completions = client.chat.completions.create(
174
+ model="gpt-4",
175
+ messages=[
176
+
177
+ {"role": "user", "content": prompt}
178
+ ],
179
+ max_tokens=200,
180
+ n=1,
181
+ stop=None,
182
+ temperature=0.0,
183
+ )
184
+
185
+ # Extract keywords from the OpenAI response
186
+ keywords =completions.choices[0].message.content
187
+ return keywords
188
+
189
+ def fetch_images(query):
190
+ api_key = "c9000cf8cfc73ea3b0b116e60ff234eea944e0529424e663da47fe095c2cae69" # Replace "YOUR_API_KEY" with your actual API key
191
+ endpoint = f"https://serpapi.com/search?engine=google_images&q={query}&api_key={api_key}"
192
+
193
+ try:
194
+ response = requests.get(endpoint)
195
+ data = response.json()
196
+ print("API Response:", data)
197
+ image_urls = [result['original'] for result in data['images_results']]
198
+ return image_urls[:10] # Return only the first 5 images
199
+ except Exception as e:
200
+ st.error(f"Error fetching images: {e}")
201
+ return []
202
+
203
+
204
+ def resize_images(image_files):
205
+ resized_image_files = []
206
+ for image_file in image_files:
207
+ try:
208
+ with Image.open(image_file) as img:
209
+ # Convert image to RGB mode if it has an alpha channel
210
+ if img.mode == 'RGBA':
211
+ img = img.convert('RGB')
212
+ # Ensure width and height are divisible by 2
213
+ width = img.width - (img.width % 2)
214
+ height = img.height - (img.height % 2)
215
+ resized_img = img.resize((width, height))
216
+ resized_image_file = f"{image_file.split('.')[0]}_resized.jpg"
217
+ resized_img.save(resized_image_file)
218
+ resized_image_files.append(resized_image_file)
219
+ except (OSError) as e:
220
+ st.warning(f"Skipping image {image_file} as it cannot be identified.")
221
+ continue
222
+ return resized_image_files
223
+
224
+
225
+
226
+ def create_video_slideshow(image_urls):
227
+ # Create temporary directory to store image files
228
+ temp_dir = "temp_images"
229
+ os.makedirs(temp_dir, exist_ok=True)
230
+
231
+ # Download and save images
232
+ image_files = []
233
+ for i, image_url in enumerate(image_urls):
234
+ image_path = os.path.join(temp_dir, f"image_{i}.jpg")
235
+ with open(image_path, 'wb') as f:
236
+ response = requests.get(image_url)
237
+ f.write(response.content)
238
+ image_files.append(image_path)
239
+
240
+ # Resize images
241
+ resized_image_files = resize_images(image_files)
242
+
243
+ # Run FFmpeg command to create video slideshow
244
+ output_video_path = "slideshow_video.mp4"
245
+ subprocess.run([
246
+ "ffmpeg", "-y", "-framerate", "1", "-i", os.path.join(temp_dir, "image_%d.jpg"), '-c:v', 'libx264','-r', '30',
247
+ output_video_path
248
+ ])
249
+
250
+ # Cleanup temporary directory
251
+ for image_file in image_files:
252
+ os.remove(image_file)
253
+ for resized_image_file in resized_image_files:
254
+ os.remove(resized_image_file)
255
+ os.rmdir(temp_dir)
256
+
257
+ return output_video_path
258
+
259
+ def add_text_to_video(input_video_path, output_video_path, text_input, text_animation):
260
+ # Define text animation filter based on dropdown selection
261
+ if text_animation == "fade_in_out":
262
+ text_animation_filter = f"drawtext=text='{text_input}':fontsize=24:fontcolor=darkslategray:fontfile=Opensans.ttf:box=1:boxcolor=white@0.8:boxborderw=5:x=w+tw-55*t:y=h-line_h-20:enable='between(t,0,10*(n-1)/10)':x='if(lt(t,10*(n-1)/10),(w-text_w)/2+(w/10)*mod(t,10),NAN)', drawtext=textfile=latest.txt:fontsize=24:fontcolor=white:fontfile=Opensans.ttf:y=h-line_h-20:x=13:box=1:boxcolor=darkorange:boxborderw=8'"
263
+ elif text_animation == "slide_from_left":
264
+ text_animation_filter = "split[text][tmp];[tmp]crop=w='min(iw\\,iw*max(1,(iw/2-2*t)/iw)):h='min(ih\\,ih*max(1,(ih/2-2*t)/ih)):x=-100+t*300:y=0[tleft];[text]crop=w='min(iw\\,iw*max(1,(iw/2-2*t)/iw)):h='min(ih\\,ih*max(1,(ih/2-2*t)/ih)):x=100-t*300:y=0[tright];[tmp][tleft]overlay=x='min(0,-100+t*300)':y=0[tmp];[tmp][tright]overlay=x='min(0,100-t*300)':y=0"
265
+ else:
266
+ text_animation_filter = "" # No animation
267
+
268
+ # Check if text_input is empty or text_animation is "None"
269
+ if not text_input or text_animation == "None":
270
+ # Return the input video path without any modifications
271
+ return input_video_path
272
+
273
+ print("text filter:",text_animation_filter)
274
+ # Run ffmpeg command to overlay text onto the video with animation
275
+ cmd = [
276
+ "ffmpeg","-y",
277
+ "-i", input_video_path,
278
+ "-vf", text_animation_filter,
279
+ "-c:a", "copy",
280
+ output_video_path
281
+ ]
282
+ print(" ".join(cmd))
283
+ subprocess.run(cmd)
284
+ return output_video_path
285
+
286
+ def image_to_video_section():
287
+ st.title("Image-to-Video Generation")
288
+
289
+ # Multi-input box for entering the article
290
+ article = st.text_area("Enter the article:", "Your article here")
291
+
292
+ # Define video filter options
293
+ video_filter_options=["None","Vintage warm","Grayscale","Invert","Sepia"]
294
+ # Add text overlay options outside of the button block
295
+ text_input = st.text_input("Enter text to overlay")
296
+ text_animation_options = ["None", "fade_in_out", "Horizontal scroll"]
297
+ text_animation = st.selectbox("Select text animation", text_animation_options)
298
+ print("text applied:",text_input)
299
+
300
+ # Select video filter
301
+ video_filter = st.selectbox("Select video filter", video_filter_options)
302
+
303
+ # Button to trigger keyword extraction and video generation
304
+ if st.button("Generate Video"):
305
+ if article.strip() != "":
306
+ # Extract keywords using OpenAI API
307
+ keywords = extract_keywords(article)
308
+ st.write(keywords)
309
+
310
+ # Fetch images from Google Images based on keywords
311
+ image_urls = fetch_images(" ".join(keywords.split()[:10])) # Fetch images based on the first 5 keywords
312
+ if image_urls:
313
+ st.success("Images fetched successfully!")
314
+
315
+ # Display the first 5 images
316
+ for image_url in image_urls:
317
+ st.image(image_url, caption='Image from Google', use_column_width=True)
318
+
319
+ # Create video slideshow from fetched images
320
+ video_path = create_video_slideshow(image_urls)
321
+
322
+ # Display generated video
323
+ st.video(video_path)
324
+
325
+ #video filter
326
+ if video_filter=="Vintage warm":
327
+ video_filt="eq=brightness=0.05:saturation=1.5"
328
+ elif video_filter=="Grayscale":
329
+ video_filt="hue=s=0"
330
+ elif video_filter=="Invert":
331
+ video_filt="lutrgb='r=negval:g=negval:b=negval'"
332
+ elif video_filter=="Sepia":
333
+ video_filt="colorchannelmixer=.393:.769:.189:0:.349:.686:.168:0:.272:.534:.131"
334
+ else:
335
+ video_filt="" #no filter
336
+
337
+ if not video_filter=="None":
338
+ cmdvid=["ffmpeg","-y","-i", video_path,"-vf",video_filt,"-c:a", "copy","videofilter.mp4"]
339
+ print(" ".join(cmdvid))
340
+ subprocess.run(cmdvid)
341
+ st.video("videofilter.mp4")
342
+
343
+
344
+
345
+
346
+ #text filter
347
+ if text_animation == "fade_in_out":
348
+
349
+ text_animation_filter = f"drawtext=text='{text_input}':fontsize=24:fontcolor=darkslategray:fontfile=Opensans.ttf:box=1:boxcolor=white@0.8:boxborderw=5:x=w+tw-55*t:y=h-line_h-20:enable='between(t,0,10*(n-1)/10)':x='if(lt(t,10*(n-1)/10),(w-text_w)/2+(w/10)*mod(t,10),NAN)', drawtext=textfile=latest.txt:fontsize=24:fontcolor=white:fontfile=Opensans.ttf:y=h-line_h-20:x=13:box=1:boxcolor=darkorange:boxborderw=8'"
350
+
351
+ elif text_animation == "Horizontal scroll":
352
+ text_animation_filter =f"drawtext=text='{text_input}':fontsize=24:fontcolor=darkslategray:fontfile=Opensans.ttf:box=1:boxcolor=white@0.8:boxborderw=5:x=w+tw-55*t:y=h-line_h-20:enable='between(t,0,10*(n-1)/10)':x='if(lt(t,10*(n-1)/10),(w-text_w)/2+(w/10)*mod(t,10),NAN)', drawtext=textfile=latest.txt:fontsize=24:fontcolor=white:fontfile=Opensans.ttf:y=h-line_h-20:x=13:box=1:boxcolor=darkorange:boxborderw=8'"
353
+ else:
354
+ text_animation_filter = "" # No animation
355
+
356
+ # Check if text_input is empty or text_animation is "None"
357
+ if not text_input or text_animation == "None":
358
+ # Return the input video path without any modifications
359
+ return video_path
360
+
361
+ print("text filter:",text_animation_filter)
362
+ # Run ffmpeg command to overlay text onto the video with animation
363
+ cmd = [
364
+ "ffmpeg","-y",
365
+ "-i", video_path,
366
+ "-vf", text_animation_filter,
367
+ "-c:a", "copy",
368
+ "output_video.mp4"
369
+ ]
370
+ print(" ".join(cmd))
371
+ subprocess.run(cmd)
372
+ #return output_video_path
373
+ # Add text overlay to the generated video
374
+
375
+ st.video("output_video.mp4")
376
+ else:
377
+ st.error("No images found for the given keywords.")
378
+ else:
379
+ st.warning("Please enter an article before generating the video.")
380
+
381
+
382
+ def frame_extraction():
383
+ st.title("Insightly Video")
384
+ # stream_url = st.text_input("Enter the live stream URL (YouTube, Twitch, etc.):")
385
+ # keyword = st.text_input("Enter a keyword to filter the frames (optional):")
386
+ uploaded_video = st.file_uploader("Or upload a video file (MP4):", type=["mp4"])
387
+
388
+
389
+
390
+ # Slider to select the number of seconds for extraction
391
+ seconds = st.slider("Select the number of seconds for extraction:", min_value=1, max_value=60, value=10)
392
+
393
+ extract_frames_button = st.button("Extract Frames")
394
+
395
+ if uploaded_video is not None and extract_frames_button:
396
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmpfile:
397
+ tmpfile.write(uploaded_video.getvalue())
398
+ video_file_path = tmpfile.name
399
+
400
+ ffmpeg_command = [
401
+ 'ffmpeg', # Input stream URL
402
+ '-i', video_file_path,
403
+ '-t', str(seconds), # Duration to process the input (selected seconds)
404
+ '-vf', 'fps=1', # Extract one frame per second
405
+ '-f', 'image2pipe', # Output format as image2pipe
406
+ '-c:v', 'mjpeg', # Codec for output video
407
+ '-an', # No audio
408
+ '-'
409
+ ]
410
+
411
+ ffmpeg_output = execute_fmpeg_command(ffmpeg_command)
412
+
413
+ if ffmpeg_output:
414
+ st.write("Frames Extracted:")
415
+ frame_bytes_list = ffmpeg_output.split(b'\xff\xd8')[1:] # Correct splitting for JPEG frames
416
+ n_frames = len(frame_bytes_list)
417
+ base64_frames = [base64.b64encode(b'\xff\xd8' + frame_bytes).decode('utf-8') for frame_bytes in frame_bytes_list]
418
+
419
+ frame_dict = {}
420
+
421
+ for idx, frame_base64 in enumerate(base64_frames):
422
+ col1, col2 = st.columns([3, 2])
423
+ with col1:
424
+ frame_bytes = base64.b64decode(frame_base64)
425
+ frame_dict[idx + 1] = frame_bytes
426
+ st.image(Image.open(BytesIO(frame_bytes)), caption=f'Frame {idx + 1}', use_column_width=True)
427
+ with col2:
428
+ pass
429
+
430
+ # Here, you might want to process combined_analysis_results to summarize or just display them
431
+
432
+ # Extract audio
433
+ audio_command = [
434
+ 'ffmpeg',
435
+ '-i', video_file_path,
436
+ '-t', str(seconds),
437
+ '-vf', 'fps=1', # Input stream URL
438
+ '-vn', # Ignore the video for the audio output
439
+ '-acodec', 'libmp3lame', # Set the audio codec to MP3 # Duration for the audio extraction (selected seconds)
440
+ '-f', 'mp3', # Output format as MP3
441
+ '-'
442
+ ]
443
+ audio_output, _ = execute_ffmpeg_command(audio_command)
444
+
445
+ st.write("Extracted Audio:")
446
+ audio_tempfile = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
447
+ audio_tempfile.write(audio_output)
448
+ audio_tempfile.close()
449
+
450
+ st.audio(audio_output, format='audio/mpeg', start_time=0)
451
+
452
+ # Get consolidated description for all frames
453
+ if ffmpeg_output:
454
+ description, frame_numbers = generate_description(base64_frames)
455
+ if description:
456
+ st.header("Frame Description:")
457
+ st.write(description)
458
+ else:
459
+ st.write("Failed to generate description.")
460
+
461
+ if frame_numbers:
462
+ print("Frame numbers to extract:", frame_numbers) # Check frame numbers
463
+
464
+ # Create a mapping from original frame numbers to sequential numbers
465
+ frame_mapping = {}
466
+ new_frame_numbers = []
467
+ for idx, frame_number in enumerate(sorted(frame_numbers)):
468
+ frame_mapping[frame_number] = idx + 1
469
+ new_frame_numbers.append(idx + 1)
470
+
471
+ print("New frame numbers:", new_frame_numbers)
472
+ print("Frame mapping:", frame_mapping)
473
+
474
+ # Create a temporary directory to store images
475
+ with tempfile.TemporaryDirectory() as temp_dir:
476
+ image_paths = []
477
+ for frame_number in frame_numbers:
478
+ if frame_number in frame_dict:
479
+ frame_path = os.path.join(temp_dir, f'frame_{frame_mapping[frame_number]:03}.jpg') # Updated file naming
480
+ image_paths.append(frame_path)
481
+ with open(frame_path, 'wb') as f:
482
+ f.write(frame_dict[frame_number])
483
+
484
+ # Once all selected frames are saved as images, create a video from them using FFmpeg
485
+ video_output_path = os.path.join(temp_dir, 'output.mp4')
486
+ framerate = 1 # Adjust framerate based on the number of frames
487
+ ffmpeg_command = [
488
+ 'ffmpeg',
489
+ '-framerate', str(framerate), # Set framerate based on the number of frames
490
+ '-i', os.path.join(temp_dir, 'frame_%03d.jpg'), # Input pattern for all frame files
491
+ '-c:v', 'libx264',
492
+ '-pix_fmt', 'yuv420p',
493
+ video_output_path
494
+ ]
495
+
496
+ print("FFmpeg command:", ' '.join(ffmpeg_command)) # Debug FFmpeg command
497
+
498
+ subprocess.run(ffmpeg_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
499
+
500
+ # Display or provide a download link for the created video
501
+ st.header("Final Video")
502
+ st.video(video_output_path)
503
+
504
+ else:
505
+ st.write(" ")
506
+
507
+ def main():
508
+ # st.title("Video Uploader and Player")
509
+
510
+ # uploaded_file = st.file_uploader("Upload a video", type=["mp4", "mov"])
511
+
512
+ # if uploaded_file is not None:
513
+ # Save the uploaded video to disk
514
+ # with open("uploaded_video.mp4", "wb") as f:
515
+ # f.write(uploaded_file.getbuffer())
516
+
517
+ # st.success("Video uploaded successfully!")
518
+
519
+ # Display the uploaded video
520
+ # st.video("uploaded_video.mp4")
521
+
522
+ # Add accordion menu for text to video and image to video sections
523
+ menu_selection = st.sidebar.selectbox("Select:", ["Text to video", "Image to video","Frame Extraction"])
524
+
525
+ if menu_selection == "Text to video":
526
+ text_to_video_section()
527
+ elif menu_selection == "Image to video":
528
+ image_to_video_section()
529
+ elif menu_selection == "Frame Extraction":
530
+ frame_extraction()
531
+
532
+ if __name__ == "__main__":
533
+ main()