Spaces:
Sleeping
Sleeping
File size: 16,273 Bytes
75bb141 | 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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 | #!/usr/bin/env python3
import gradio as gr
import subprocess
import os
import tempfile
import shutil
import logging
import time
from pathlib import Path
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def process_video_trim(video_file, start_time, end_time):
"""Process video trimming using ffmpeg directly"""
logger.info(f"🎬 Starting trim process: file={video_file}, start={start_time}, end={end_time}")
if not video_file or start_time is None or end_time is None:
error_msg = "Please provide video file and both start/end times"
logger.error(f"❌ {error_msg}")
return None, None, None, error_msg
try:
start_seconds = float(start_time)
end_seconds = float(end_time)
logger.info(f"📊 Parsed times: start={start_seconds}s, end={end_seconds}s")
if start_seconds >= end_seconds:
error_msg = "Start time must be less than end time"
logger.error(f"❌ {error_msg}")
return None, None, None, error_msg
if not os.path.exists(video_file):
error_msg = f"Input video file not found: {video_file}"
logger.error(f"❌ {error_msg}")
return None, None, None, error_msg
# Create temporary directory for output
temp_dir = tempfile.mkdtemp()
logger.info(f"📁 Created temp directory: {temp_dir}")
# Get the base filename without extension
base_name = Path(video_file).stem
output_video = os.path.join(temp_dir, f"{base_name}_trimmed.mp4")
output_audio = os.path.join(temp_dir, f"{base_name}_trimmed.aac")
logger.info(f"📤 Output files will be: video={output_video}, audio={output_audio}")
# Convert seconds to HH:MM:SS format
def seconds_to_time(seconds):
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = seconds % 60
return f"{hours:02d}:{minutes:02d}:{secs:06.3f}"
start_time_str = seconds_to_time(start_seconds)
end_time_str = seconds_to_time(end_seconds)
duration = end_seconds - start_seconds
logger.info(f"🕒 Converted times: start={start_time_str}, duration={duration}s")
# Trim video using ffmpeg
video_cmd = [
"ffmpeg", "-y", "-i", video_file,
"-ss", start_time_str,
"-t", str(duration),
"-c", "copy",
"-avoid_negative_ts", "make_zero",
output_video
]
logger.info(f"🚀 Running video command: {' '.join(video_cmd)}")
video_result = subprocess.run(video_cmd, capture_output=True, text=True)
if video_result.returncode != 0:
logger.warning("Stream copy failed, trying with re-encoding...")
# Fallback to re-encoding
video_cmd = [
"ffmpeg", "-y", "-i", video_file,
"-ss", start_time_str,
"-t", str(duration),
"-c:v", "libx264", "-preset", "fast", "-crf", "23",
"-c:a", "aac", "-b:a", "128k",
output_video
]
video_result = subprocess.run(video_cmd, capture_output=True, text=True)
# Extract audio
audio_cmd = [
"ffmpeg", "-y", "-i", video_file,
"-ss", start_time_str,
"-t", str(duration),
"-vn", "-acodec", "aac", "-b:a", "128k",
output_audio
]
logger.info(f"🎵 Running audio command: {' '.join(audio_cmd)}")
audio_result = subprocess.run(audio_cmd, capture_output=True, text=True)
if video_result.returncode == 0 and audio_result.returncode == 0:
if os.path.exists(output_video) and os.path.exists(output_audio):
# Create MP3 version for better browser compatibility
audio_mp3 = os.path.join(temp_dir, f"{base_name}_trimmed.mp3")
mp3_cmd = [
"ffmpeg", "-y", "-i", output_audio,
"-codec:a", "libmp3lame", "-b:a", "128k",
audio_mp3
]
mp3_result = subprocess.run(mp3_cmd, capture_output=True, text=True)
audio_player_file = audio_mp3 if mp3_result.returncode == 0 else output_audio
success_msg = f"✅ Successfully trimmed video from {start_seconds:.1f}s to {end_seconds:.1f}s"
logger.info(success_msg)
return output_video, audio_player_file, output_audio, success_msg
else:
error_msg = "❌ Output files not created"
return None, None, None, error_msg
else:
error_msg = f"❌ FFmpeg failed. Video: {video_result.stderr}, Audio: {audio_result.stderr}"
logger.error(error_msg)
return None, None, None, error_msg
except Exception as e:
error_msg = f"❌ Unexpected error: {str(e)}"
logger.exception(error_msg)
return None, None, None, error_msg
def get_video_duration(video_file):
"""Get video duration in seconds"""
if not video_file:
return 0
try:
logger.info(f"📺 Getting duration for: {video_file}")
cmd = [
"ffprobe", "-v", "quiet", "-print_format", "json",
"-show_format", "-show_streams", video_file
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
import json
data = json.loads(result.stdout)
duration = float(data['format']['duration'])
logger.info(f"⏱️ Video duration: {duration} seconds")
return duration
else:
logger.warning(f"⚠️ Could not get duration: {result.stderr}")
return 0
except Exception as e:
logger.exception(f"❌ Error getting video duration: {e}")
return 0
def format_time(seconds):
"""Format seconds to mm:ss"""
if seconds is None:
return "0:00"
minutes = int(seconds // 60)
secs = int(seconds % 60)
return f"{minutes}:{secs:02d}"
def get_video_info(video_file):
"""Get video duration and basic info"""
if not video_file:
return "No video uploaded", 0, 0, 0
logger.info(f"📹 Processing video upload: {video_file}")
duration = get_video_duration(video_file)
if duration > 0:
minutes = int(duration // 60)
seconds = int(duration % 60)
info = f"📹 Video loaded! Duration: {minutes}:{seconds:02d} ({duration:.1f}s)"
logger.info(f"✅ {info}")
return info, duration, 0, duration
else:
info = "📹 Video loaded! (Could not determine duration)"
logger.warning(f"⚠️ {info}")
return info, 100, 0, 100
# Client-side Google Drive integration
google_drive_js = """
<script src="https://apis.google.com/js/api.js"></script>
<script src="https://accounts.google.com/gsi/client"></script>
<script>
// Google Drive Picker API
let pickerApiLoaded = false;
let oauthToken;
// Initialize the APIs
function initializeGoogleDrive() {
gapi.load('auth2:picker', onAuthApiLoad);
}
function onAuthApiLoad() {
window.gapi.load('picker', onPickerApiLoad);
// Initialize OAuth2
gapi.auth2.init({
client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com' // You'll need to add your client ID
});
}
function onPickerApiLoad() {
pickerApiLoaded = true;
}
// Authenticate user
function authenticateGoogleDrive() {
const authInstance = gapi.auth2.getAuthInstance();
authInstance.signIn().then(() => {
oauthToken = authInstance.currentUser.get().getAuthResponse().access_token;
console.log('Google Drive authenticated!');
document.getElementById('drive-status').innerText = '✅ Authenticated with Google Drive';
});
}
// Open Google Drive Picker
function openDrivePicker() {
if (pickerApiLoaded && oauthToken) {
const picker = new google.picker.PickerBuilder()
.addView(google.picker.ViewId.DOCS_VIDEOS)
.setOAuthToken(oauthToken)
.setDeveloperKey('YOUR_API_KEY') // You'll need to add your API key
.setCallback(pickerCallback)
.build();
picker.setVisible(true);
} else {
alert('Please authenticate with Google Drive first');
}
}
// Handle file selection
function pickerCallback(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
const file = data[google.picker.Response.DOCUMENTS][0];
const fileId = file[google.picker.Document.ID];
const fileName = file[google.picker.Document.NAME];
console.log('Selected file:', fileName, fileId);
// Download the file
downloadFromDrive(fileId, fileName);
}
}
// Download file from Google Drive
function downloadFromDrive(fileId, fileName) {
const url = `https://www.googleapis.com/drive/v3/files/${fileId}?alt=media`;
fetch(url, {
headers: {
'Authorization': `Bearer ${oauthToken}`
}
})
.then(response => response.blob())
.then(blob => {
// Create a file object and trigger upload to Gradio
const file = new File([blob], fileName, { type: blob.type });
// This would need to integrate with Gradio's file input
console.log('Downloaded file:', file);
document.getElementById('drive-status').innerText = `✅ Downloaded: ${fileName}`;
})
.catch(error => {
console.error('Download failed:', error);
document.getElementById('drive-status').innerText = `❌ Download failed: ${error.message}`;
});
}
// Initialize when page loads
window.addEventListener('load', initializeGoogleDrive);
</script>
<div id="google-drive-section" style="border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 8px;">
<h3>🔗 Google Drive Integration (Client-Side)</h3>
<p><strong>Each user authenticates with their own Google account</strong></p>
<button onclick="authenticateGoogleDrive()" style="background: #4285f4; color: white; padding: 10px 20px; border: none; border-radius: 5px; margin: 5px;">
🔐 Authenticate with Google Drive
</button>
<button onclick="openDrivePicker()" style="background: #34a853; color: white; padding: 10px 20px; border: none; border-radius: 5px; margin: 5px;">
📁 Browse Google Drive
</button>
<div id="drive-status" style="margin-top: 10px; padding: 10px; background: #f5f5f5; border-radius: 5px;">
⚠️ Click "Authenticate" to connect your Google Drive
</div>
</div>
"""
# Create the Gradio interface
custom_css = """
.video-container video {
width: 100%;
max-height: 400px;
}
.slider-container {
margin: 10px 0;
}
"""
with gr.Blocks(title="Video Trimmer Tool", theme=gr.themes.Soft(), css=custom_css) as demo:
gr.Markdown("""
# 🎬 Video Trimmer Tool (Client-Side Google Drive)
Upload a video file, set trim points using the sliders, and get both trimmed video and extracted audio files.
**NEW: Individual Google Drive Authentication** - Each user connects their own Google account!
""")
# Add Google Drive integration
gr.HTML(google_drive_js)
with gr.Row():
with gr.Column(scale=2):
# Video upload and display
video_input = gr.File(
label="📁 Upload Video File (or use Google Drive above)",
file_types=[".mp4", ".mov", ".avi", ".mkv"],
type="filepath"
)
video_player = gr.Video(
label="🎥 Video Player",
show_label=True,
elem_id="main_video_player",
elem_classes=["video-container"]
)
video_info = gr.Textbox(
label="📊 Video Info",
interactive=False,
value="Upload a video to see information"
)
with gr.Column(scale=1):
# Trim controls
gr.Markdown("### ✂️ Trim Settings")
gr.Markdown("**🎯 Drag sliders to set trim points:**")
with gr.Group():
gr.Markdown("**🎯 Start point:**")
start_slider = gr.Slider(
minimum=0,
maximum=100,
value=0,
step=0.1,
label="⏯️ Start Time",
info="Drag to set start position",
elem_classes=["slider-container"]
)
start_time_display = gr.Textbox(
label="⏯️ Start Time",
value="0:00",
interactive=False,
info="Current start time"
)
with gr.Group():
gr.Markdown("**🎯 End point:**")
end_slider = gr.Slider(
minimum=0,
maximum=100,
value=100,
step=0.1,
label="⏹️ End Time",
info="Drag to set end position",
elem_classes=["slider-container"]
)
end_time_display = gr.Textbox(
label="⏹️ End Time",
value="1:40",
interactive=False,
info="Current end time"
)
trim_btn = gr.Button(
"✂️ Trim Video",
variant="primary",
size="lg"
)
status_msg = gr.Textbox(
label="📝 Status",
interactive=False,
value="Ready to trim..."
)
# Output section
gr.Markdown("### 📤 Output Files")
with gr.Row():
with gr.Column():
output_video = gr.Video(
label="🎬 Trimmed Video",
show_label=True
)
with gr.Column():
output_audio_player = gr.Audio(
label="🎵 Play Extracted Audio",
show_label=True,
type="filepath"
)
output_audio_download = gr.File(
label="💾 Download Audio (AAC)",
show_label=True
)
# Event handlers
def update_video_and_sliders(video_file):
info, duration, start_val, end_val = get_video_info(video_file)
return (
video_file, # video_player
info, # video_info
gr.Slider(minimum=0, maximum=duration, value=0, step=0.1), # start_slider
gr.Slider(minimum=0, maximum=duration, value=duration, step=0.1), # end_slider
"0:00", # start_time_display
format_time(duration) # end_time_display
)
def update_start_display(start_val):
return format_time(start_val)
def update_end_display(end_val):
return format_time(end_val)
video_input.change(
fn=update_video_and_sliders,
inputs=[video_input],
outputs=[video_player, video_info, start_slider, end_slider, start_time_display, end_time_display]
)
start_slider.change(
fn=update_start_display,
inputs=[start_slider],
outputs=[start_time_display]
)
end_slider.change(
fn=update_end_display,
inputs=[end_slider],
outputs=[end_time_display]
)
# Trim button handler
trim_btn.click(
fn=process_video_trim,
inputs=[video_input, start_slider, end_slider],
outputs=[output_video, output_audio_player, output_audio_download, status_msg]
)
if __name__ == "__main__":
demo.launch() |