PriyankaSatish commited on
Commit
95e4bf2
·
verified ·
1 Parent(s): 6096f06

Upload 3 files

Browse files
Files changed (3) hide show
  1. IntelliStreamLogo.png +0 -0
  2. requirements.txt +0 -0
  3. tegna_final.py +205 -0
IntelliStreamLogo.png ADDED
requirements.txt ADDED
Binary file (6.09 kB). View file
 
tegna_final.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #THIS IS THE FINAL WORKING VIDEO - TEGNA FINAL TIKTOK.
2
+ import subprocess
3
+ import streamlit as st
4
+ import tempfile
5
+ import base64
6
+ import os
7
+ from dotenv import load_dotenv
8
+ from PIL import Image
9
+ from io import BytesIO
10
+ from openai import OpenAI
11
+ import re
12
+
13
+ load_dotenv()
14
+ OpenAI.api_key = os.getenv("OPENAI_API_KEY")
15
+ if not OpenAI.api_key:
16
+ raise ValueError("The OpenAI API key must be set in the OPENAI_API_KEY environment variable.")
17
+ client = OpenAI()
18
+
19
+
20
+ # Create a layout with columns
21
+ col1, col2 = st.columns([8, 2]) # Adjust the ratio as needed
22
+
23
+
24
+ def execute_ffmpeg_command(command):
25
+ try:
26
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
27
+ if result.returncode == 0:
28
+ print("FFmpeg command executed successfully.")
29
+ return result.stdout, result.stderr
30
+ else:
31
+ print("Error executing FFmpeg command:")
32
+ return None, result.stderr
33
+ except Exception as e:
34
+ print("An error occurred during FFmpeg execution:")
35
+ return None, str(e)
36
+
37
+
38
+ def execute_fmpeg_command(command):
39
+ try:
40
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
41
+ return result.stdout # Return just the stdout part, not a tuple
42
+ except subprocess.CalledProcessError as e:
43
+ print(f"FFmpeg command failed with error: {e.stderr.decode()}")
44
+ return None
45
+
46
+ def search_keyword(keyword, frame_texts):
47
+ return [index for index, text in st.session_state.frame_texts.items() if keyword.lower() in text.lower()]
48
+ frame_numbers = []
49
+ # Function to generate description for video frames
50
+
51
+ def generate_description(base64_frames):
52
+ try:
53
+ prompt_messages = [
54
+ {
55
+ "role": "user",
56
+ "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 tiktok video. List all frame numbers separated by commas at the end like this for eg, Frames : 1,2,4,7,9",
57
+ *map(lambda x: {"image": x, "resize": 428}, base64_frames),
58
+ ],
59
+ },
60
+ ]
61
+ response = client.chat.completions.create(
62
+ model="gpt-4-vision-preview",
63
+ messages=prompt_messages,
64
+ max_tokens=3000,
65
+ )
66
+ description = response.choices[0].message.content
67
+
68
+ # Use regular expression to find frame numbers
69
+ frame_numbers = re.findall(r'Frames\s*:\s*(\d+(?:,\s*\d+)*)', response.choices[0].message.content)
70
+
71
+ # Convert the string of numbers into a list of integers
72
+ if frame_numbers:
73
+ frame_numbers = [int(num) for num in frame_numbers[0].split(',')]
74
+ else:
75
+ frame_numbers = []
76
+
77
+ print("Frame numbers to extract:", frame_numbers)
78
+
79
+ return description, frame_numbers
80
+
81
+ except Exception as e:
82
+ print(f"Error in generate_description: {e}")
83
+ return None, []
84
+
85
+ with col2:
86
+ pass
87
+
88
+ with col1:
89
+ is_logo_path = "IntelliStreamLogo.png" # Update this path to where your logo is stored
90
+ is_logo = Image.open(is_logo_path)
91
+ st.image(is_logo, width=200)
92
+
93
+ st.markdown("<h1 style='text-align: left; color: white;'></h1>", unsafe_allow_html=True)
94
+
95
+ # Streamlit UI
96
+ st.title("Insightly Video")
97
+ uploaded_video = st.file_uploader("Or upload a video file (MP4):", type=["mp4"])
98
+
99
+ extract_frames_button = st.button("Extract Frames")
100
+
101
+ if uploaded_video is not None and extract_frames_button:
102
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmpfile:
103
+ tmpfile.write(uploaded_video.getvalue())
104
+ video_file_path = tmpfile.name
105
+
106
+ # Command to extract one frame per second for the entire video duration
107
+ ffmpeg_command = [
108
+ 'ffmpeg',
109
+ '-i', video_file_path,
110
+ '-vf', 'fps=0.25',
111
+ '-f', 'image2pipe',
112
+ '-c:v', 'mjpeg',
113
+ '-an',
114
+ '-'
115
+ ]
116
+
117
+ ffmpeg_output = execute_fmpeg_command(ffmpeg_command)
118
+
119
+ if ffmpeg_output:
120
+ st.write("Frames Extracted:")
121
+ frame_bytes_list = ffmpeg_output.split(b'\xff\xd8')[1:] # Correct splitting for JPEG frames
122
+ n_frames = len(frame_bytes_list)
123
+ base64_frames = [base64.b64encode(b'\xff\xd8' + frame_bytes).decode('utf-8') for frame_bytes in frame_bytes_list]
124
+
125
+ frame_dict = {}
126
+
127
+ for idx, frame_base64 in enumerate(base64_frames):
128
+ col1, col2 = st.columns([3, 2])
129
+ with col1:
130
+ frame_bytes = base64.b64decode(frame_base64)
131
+ frame_dict[idx + 1] = frame_bytes
132
+ st.image(Image.open(BytesIO(frame_bytes)), caption=f'Frame {idx + 1}', use_column_width=True)
133
+ with col2:
134
+ pass
135
+
136
+ # Extract audio for the entire video
137
+ audio_command = [
138
+ 'ffmpeg',
139
+ '-i', video_file_path,
140
+ '-vn',
141
+ '-acodec', 'libmp3lame',
142
+ '-f', 'mp3',
143
+ '-'
144
+ ]
145
+ audio_output, _ = execute_ffmpeg_command(audio_command)
146
+
147
+ st.write("Extracted Audio:")
148
+ audio_tempfile = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
149
+ audio_tempfile.write(audio_output)
150
+ audio_tempfile.close()
151
+
152
+ st.audio(audio_output, format='audio/mpeg', start_time=0)
153
+
154
+ # Get consolidated description for all frames
155
+ if ffmpeg_output:
156
+ description, frame_numbers = generate_description(base64_frames)
157
+ if description:
158
+ st.header("Frame Description:")
159
+ st.write(description)
160
+ else:
161
+ st.write("Failed to generate description.")
162
+
163
+ if frame_numbers:
164
+ print("Frame numbers to extract:", frame_numbers) # Check frame numbers
165
+
166
+ # Create a mapping from original frame numbers to sequential numbers
167
+ frame_mapping = {}
168
+ new_frame_numbers = []
169
+ for idx, frame_number in enumerate(sorted(frame_numbers)):
170
+ frame_mapping[frame_number] = idx + 1
171
+ new_frame_numbers.append(idx + 1)
172
+
173
+ print("New frame numbers:", new_frame_numbers)
174
+ print("Frame mapping:", frame_mapping)
175
+
176
+ # Create a temporary directory to store images
177
+ with tempfile.TemporaryDirectory() as temp_dir:
178
+ image_paths = []
179
+ for frame_number in frame_numbers:
180
+ if frame_number in frame_dict:
181
+ frame_path = os.path.join(temp_dir, f'frame_{frame_mapping[frame_number]:03}.jpg') # Updated file naming
182
+ image_paths.append(frame_path)
183
+ with open(frame_path, 'wb') as f:
184
+ f.write(frame_dict[frame_number])
185
+
186
+ # Once all selected frames are saved as images, create a video from them using FFmpeg
187
+ video_output_path = os.path.join(temp_dir, 'output.mp4')
188
+ framerate = 1 # Adjust framerate based on the number of frames
189
+ ffmpeg_command = [
190
+ 'ffmpeg',
191
+ '-framerate', str(framerate), # Set framerate based on the number of frames
192
+ '-i', os.path.join(temp_dir, 'frame_%03d.jpg'), # Input pattern for all frame files
193
+ '-c:v', 'libx264',
194
+ '-pix_fmt', 'yuv420p',
195
+ video_output_path
196
+ ]
197
+
198
+ print("FFmpeg command:", ' '.join(ffmpeg_command)) # Debug FFmpeg command
199
+
200
+ subprocess.run(ffmpeg_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
201
+
202
+ # Display or provide a download link for the created video
203
+ st.header("Final Video")
204
+ st.video(video_output_path)
205
+