Spaces:
Sleeping
Sleeping
File size: 11,620 Bytes
6edd739 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 |
import streamlit as st
import os
import time
from yt_dlp import YoutubeDL
import ffmpeg
import tempfile
from utils import (save_uploaded_file, extract_audio,
download_youtube, get_session_dir,
cleanup_session_files, get_session_id,
get_temp_dir, get_features, proc_raw_audio)
st.title('📥📄 Step 1: Upload Video & Preprocess')
# Initialize session state defaults
defaults = {
'uploaded_file': None,
'video_path': None,
'audio_path': None,
'ocr_text': None,
'transcript': None,
'summary': None,
'main_topic': None,
'input_method': 'Upload',
'input_title': None,
'video_input_path': None,
'video_url': None,
# 'audio_wav': None,
# 'audio_file': None,
}
for key, value in defaults.items():
st.session_state.setdefault(key, value)
# --- Option to clear previous session ---
st.sidebar.write('Current Session ID:')
st.sidebar.write(f'`{get_session_id()}`') # session ID for debugging
if st.sidebar.button('Start New Session'):
session_id = get_session_id() # get current ID before clearing
cleanup_session_files(session_id)
for key in list(st.session_state.keys()):
del st.session_state[key] # clear all session state
st.rerun() # rerun the script to reflect cleared state
# --- Main Topic ---
st.session_state.main_topic = st.text_input('(optional) Provide video topic:', st.session_state.main_topic)
# st.session_state.main_topic = m
# col_url, col_start_from = st.columns([5, 2])
# video_url = col_url.text_input('Enter YouTube video URL:', example_youtube['url'])
# start_from = col_start_from.number_input(
# 'Start From:',
# min_value=0.0, step=0.5, format='%f', value=example_youtube['start'],
# help='Time shift from the beginning (in seconds)'
# )
# if video_url:
# st.session_state.video_url = video_url
# st.session_state.video_input_path = '' # clear path if URL is used
# --- Video source selection ---
input_method = st.radio(
'Select Input Method:',
('Upload', 'YouTube'),
key='input_method',
horizontal=True
)
video_path = None
uploaded_file = None
video_url = None
if input_method == 'Upload':
uploaded_file = st.file_uploader(
'Choose a video file',
type=['mp4', 'avi', 'mkv', 'mov']
)
if uploaded_file:
col_info, col_ready = st.columns(2)
# Display basic file info
col_info.info('**[ File Details ]** ' +
f'name: `{uploaded_file.name}` | ' +
f'type: `{uploaded_file.type}` | ' +
f'size: `{uploaded_file.size / (1024 * 1024):.2f} MB`')
# Save uploaded file temporarily for the Prefect flow
temp_dir = get_temp_dir() # use a shared temp location
# Use a unique name to avoid conflicts if multiple users run simultaneously
target_path = os.path.join(temp_dir, f'upload_{get_session_id()}_{uploaded_file.name}')
try:
with open(target_path, 'wb') as f:
f.write(uploaded_file.getbuffer())
st.session_state.video_input_path = target_path
st.session_state.video_input_title = uploaded_file.name
st.session_state.video_url = '' # clear URL if file is uploaded
st.session_state.transcript = None
st.session_state.summary = None
col_ready.info('Ready for processing.')
except Exception as e:
col_ready.error(f'Error saving uploaded file: {e}')
st.session_state.video_input_path = ''
elif input_method == 'YouTube':
#-- Obtain audio from YouTube video
example_youtube = {
'title': 'Общественное движение',
'url': 'https://www.youtube.com/watch?v=c3bhkrKF6F4',
'start': 0.0
}
col_url, col_start_from = st.columns([5, 2])
video_url = col_url.text_input('Enter YouTube video URL:', example_youtube['url'])
start_from = col_start_from.number_input(
'Start From:',
min_value=0.0, step=0.5, format='%f', value=example_youtube['start'],
help='Time shift from the beginning (in seconds)'
)
if video_url:
st.session_state.video_url = video_url
st.session_state.video_input_path = '' # clear path if URL is used
@st.cache_resource
def ui_processed_sound(audio_wav, audio_np):
'''UI to show sound processing results'''
st.audio(audio_wav)
features = get_features(audio_np)
@st.cache_resource
def extract_videofile(video_file):
# video_buffer = BytesIO(video_file.read())
# audio_data = VideoFileClip(video_buffer.name).audio
# raw_source = StringIO(video_file.getvalue().decode('utf-8'))
# raw_source = video_file.getvalue().decode('utf-8')
# raw_source = video_file.read()
# raw_source = BytesIO(video_file.getvalue())
#-- Get video
# out, err = (
# ffmpeg
# .input(video_file, ss=start_from)
# .output('temp.mp4', vcodec='copy')
# .overwrite_output()
# .run()
# )
# st.video('temp.mp4')
# video = VideoFileClip(video_file)
# audio = video.audio
# audio.write_audiofile('output_audio.mp3')
tfile = tempfile.NamedTemporaryFile(delete=False)
tfile.write(video_file.read())
#-- Get audio
# SAMPLE_RATE = 16000
audio_data, err = (
ffmpeg
.input(tfile.name, ss=start_from)
.output('pipe:', format='wav')#, acodec='pcm_s16le')
# .output('pipe:', format='s16le', ac=1, acodec='pcm_s16le', ar=SAMPLE_RATE)
# .global_args('-nostdin', '-threads', '0')
.run(capture_stdout=True)
)
if err:
raise RuntimeError(f'Failed to load audio: {err.decode()}')
return audio_data
@st.cache_resource
def extract_youtube(raw_url):
#-- Get video
# out, err = (
# ffmpeg
# .input(raw_url, ss=start_from)
# .output('temp.mp4', vcodec='copy')
# .overwrite_output()
# .run()
# )
# st.video('temp.mp4')
#-- Get audio
# SAMPLE_RATE = 16000
audio_data, err = (
ffmpeg
.input(raw_url, ss=start_from)
.output('pipe:', format='wav')#, acodec='pcm_s16le')
# .output('pipe:', format='s16le', ac=1, acodec='pcm_s16le', ar=SAMPLE_RATE)
.global_args('-nostdin', '-threads', '0')
.run(capture_stdout=True)
)
if err:
raise RuntimeError(f'Failed to load audio: {err.decode()}')
return audio_data
# --- Processing Button ---
_, col_button_process, _ = st.columns([2, 1, 2])
if col_button_process.button('Process video',
type='primary',
use_container_width=True,
disabled=not (st.session_state.video_input_path or st.session_state.video_url)
):
# Clear previous paths if reprocessing
st.session_state['video_path'] = None
st.session_state['audio_path'] = None
col_info, col_complete, col_next = st.columns(3)
with st.spinner('Processing video input..'):
if st.session_state['input_method'] == 'Upload' and uploaded_file:
st.session_state.uploaded_file = uploaded_file
video = uploaded_file
# audio_data = extract_videofile(uploaded_file)
saved_path = save_uploaded_file(uploaded_file)
if saved_path:
st.session_state['video_path'] = saved_path
col_info.success(f'Video saved temporarily to: {os.path.basename(saved_path)}')
else:
col_info.error('Failed to save uploaded file')
elif st.session_state['input_method'] == 'YouTube' and video_url:
try:
with YoutubeDL({'format': 'best+bestaudio'}) as ydl:
info = ydl.extract_info(video_url, download=False)
except Exception as e:
st.error(e)
else:
d = info['duration']
h, m, s = d // 3600, (d % 3600) // 60, d % 60
time_str = []
if h: time_str.append(f'{h}h')
if m: time_str.append(f'{m}m')
if s or not time_str: time_str.append(f'{s}s')
time_str = ' '.join(time_str)
st.write(f"<small><div style='float: center; text-align: center'>\
**Title:** [{info['title']}]({video_url})\
**Duration:** {info['duration']} sec.</div></small>",
unsafe_allow_html=True)
video = video_url
# audio_data = extract_youtube(info['url'])
st.session_state.video_input_title = info['title']
session_dir = get_session_dir()
os.makedirs(session_dir, exist_ok=True)
downloaded_path = download_youtube(video_url, session_dir)
if downloaded_path and os.path.exists(downloaded_path):
st.session_state['video_path'] = downloaded_path
col_info.success(f'YouTube video downloaded: {os.path.basename(downloaded_path)}')
else:
col_info.error('Failed to download YouTube video')
else:
st.warning('Please upload a file or provide a YouTube URL')
st.stop()
# --- Basic Preprocessing: Audio Extraction ---
if st.session_state['video_path']:
# st.write('Extracting audio..')
start = time.time()
# Ensure utils.extract_audio uses the correct path
audio_path = extract_audio(st.session_state['video_path'], audio_format='mp3')
# audio_path = extract_audio(st.session_state['video_path'])
end = time.time()
if audio_path and os.path.exists(audio_path):
col_info.success(f'Audio extracted to: {os.path.basename(audio_path)} (took {end - start:.2f}s)')
st.session_state['audio_path'] = audio_path
else:
col_info.error('Failed to extract audio from the video')
st.warning('Proceeding without audio. STT step will be skipped')
st.session_state['audio_path'] = None # explicitly set to None
if st.session_state['video_path']:
col_complete.info('Preprocessing complete')
col_next.page_link('ui_transcribe.py', label='Next Step: 🎙️ **Transcribe**', icon='➡️')
# Display video
with st.container(height=300, border=False):
_, col_preview_description, _ = st.columns([1, 3, 1])
col_preview_description.subheader('Preview Video')
_, col_video, _ = st.columns([1, 3, 1])
col_video.video(video)
# audio_data = audio_path
# audio_wav, audio_np = proc_raw_audio(audio_data)
# st.session_state.audio_wav = audio_wav
# st.session_state.audio_np = audio_np
# # st.session_state.video = video.read()
# ui_processed_sound(audio_wav, audio_np)
# # Display current status
# st.subheader("Current Status:")
# if st.session_state.get('video_path'):
# st.success(f"✅ Video Loaded: {os.path.basename(st.session_state['video_path'])}")
# else:
# st.warning("⏳ Video not yet loaded or processed.")
# if st.session_state.get('audio_path'):
# st.success(f"✅ Audio Extracted: {os.path.basename(st.session_state['audio_path'])}")
# elif st.session_state.get('video_path'): # only show warning if video was loaded but audio failed
# st.warning("⚠️ Audio extraction failed or video has no audio track.")
|