Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,12 +5,21 @@ import tempfile
|
|
| 5 |
import shutil
|
| 6 |
from pathlib import Path
|
| 7 |
from typing import List, Dict, Optional
|
|
|
|
|
|
|
| 8 |
|
| 9 |
import spacy
|
| 10 |
import gradio as gr
|
| 11 |
from transformers import pipeline
|
| 12 |
import torch
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
# βββ spaCy setup for HF Spaces βββ
|
| 15 |
def setup_spacy():
|
| 16 |
"""Setup spaCy model with proper error handling for HF Spaces"""
|
|
@@ -18,94 +27,116 @@ def setup_spacy():
|
|
| 18 |
nlp = spacy.load("en_core_web_sm")
|
| 19 |
return nlp
|
| 20 |
except OSError:
|
| 21 |
-
print("
|
| 22 |
-
|
| 23 |
-
from spacy.cli import download as spacy_download
|
| 24 |
-
spacy_download("en_core_web_sm")
|
| 25 |
-
nlp = spacy.load("en_core_web_sm")
|
| 26 |
-
return nlp
|
| 27 |
-
except Exception as e:
|
| 28 |
-
print(f"Failed to download spaCy model: {e}")
|
| 29 |
-
return None
|
| 30 |
|
| 31 |
nlp = setup_spacy()
|
| 32 |
|
| 33 |
|
| 34 |
-
def
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
|
| 55 |
def check_ffmpeg():
|
| 56 |
-
"""Check if ffmpeg is available
|
| 57 |
try:
|
| 58 |
-
subprocess.run(["ffmpeg", "-version"], capture_output=True,
|
| 59 |
-
return
|
| 60 |
-
except
|
| 61 |
return False
|
| 62 |
|
| 63 |
|
| 64 |
-
def
|
| 65 |
-
"""
|
| 66 |
-
if output_dir is None:
|
| 67 |
-
output_dir = tempfile.mkdtemp(prefix="chunks_")
|
| 68 |
-
|
| 69 |
-
Path(output_dir).mkdir(exist_ok=True)
|
| 70 |
-
output_pattern = os.path.join(output_dir, "chunk_%03d.mp4")
|
| 71 |
-
|
| 72 |
try:
|
| 73 |
cmd = [
|
| 74 |
-
"
|
| 75 |
-
"-
|
| 76 |
-
"-reset_timestamps", "1", "-c", "copy",
|
| 77 |
-
output_pattern
|
| 78 |
]
|
| 79 |
-
result = subprocess.run(cmd, capture_output=True, text=True, timeout=
|
| 80 |
|
| 81 |
-
if result.returncode
|
| 82 |
-
|
| 83 |
-
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
except Exception as e:
|
| 90 |
-
print(f"Error
|
| 91 |
-
|
|
|
|
| 92 |
|
| 93 |
|
| 94 |
-
def
|
| 95 |
-
"""Extract audio with
|
| 96 |
try:
|
| 97 |
cmd = [
|
| 98 |
-
"ffmpeg", "-y",
|
| 99 |
-
"-
|
| 100 |
-
"-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
audio_path
|
| 102 |
]
|
| 103 |
-
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
return False
|
| 108 |
-
|
| 109 |
except subprocess.TimeoutExpired:
|
| 110 |
print("Audio extraction timed out")
|
| 111 |
return False
|
|
@@ -114,119 +145,83 @@ def extract_audio(video_path: str, audio_path: str) -> bool:
|
|
| 114 |
return False
|
| 115 |
|
| 116 |
|
| 117 |
-
def
|
| 118 |
-
"""
|
| 119 |
-
if nlp is None:
|
| 120 |
-
# Fallback: simple word extraction
|
| 121 |
-
words = text.split()
|
| 122 |
-
key_words = [w for w in words if len(w) > 4 and w.isalpha()]
|
| 123 |
-
return list(dict.fromkeys(key_words))[:top_n]
|
| 124 |
-
|
| 125 |
-
try:
|
| 126 |
-
doc = nlp(text)
|
| 127 |
-
phrases = [chunk.text.strip() for chunk in doc.noun_chunks if len(chunk.text.strip()) > 2]
|
| 128 |
-
seen = set()
|
| 129 |
-
unique_phrases = [p for p in phrases if not (p.lower() in seen or seen.add(p.lower()))]
|
| 130 |
-
return unique_phrases[:top_n]
|
| 131 |
-
except Exception as e:
|
| 132 |
-
print(f"Error extracting key phrases: {str(e)}")
|
| 133 |
-
return []
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
def extract_frame(video_path: str, timestamp: str, output_path: str) -> bool:
|
| 137 |
-
"""Extract frame with timeout for HF Spaces"""
|
| 138 |
try:
|
| 139 |
-
|
| 140 |
-
result = subprocess.run(cmd, capture_output=True, text=True, timeout=15)
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
return True
|
| 145 |
-
except (subprocess.TimeoutExpired, Exception):
|
| 146 |
-
return False
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
@retry_on_rate_limit
|
| 150 |
-
def transcribe_audio(asr_pipeline, audio_path: str) -> List[Dict]:
|
| 151 |
-
"""Transcribe audio with improved error handling"""
|
| 152 |
-
try:
|
| 153 |
-
# Use the pipeline with proper parameters
|
| 154 |
-
result = asr_pipeline(
|
| 155 |
-
audio_path,
|
| 156 |
-
return_timestamps=True,
|
| 157 |
-
chunk_length_s=30,
|
| 158 |
-
stride_length_s=5
|
| 159 |
-
)
|
| 160 |
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
elif isinstance(result, list):
|
| 173 |
-
# Handle list of results
|
| 174 |
segments = []
|
| 175 |
-
for
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
})
|
| 181 |
return segments
|
|
|
|
|
|
|
| 182 |
else:
|
| 183 |
-
return [{"text":
|
| 184 |
|
| 185 |
except Exception as e:
|
| 186 |
print(f"Transcription error: {str(e)}")
|
| 187 |
-
return [{"text": "Transcription failed", "timestamp": (0
|
| 188 |
|
| 189 |
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
return "No content to summarize."
|
| 195 |
|
| 196 |
-
#
|
| 197 |
-
text = text.strip()
|
| 198 |
words = text.split()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
-
#
|
| 205 |
-
|
| 206 |
-
|
| 207 |
|
| 208 |
-
|
| 209 |
-
# Calculate appropriate lengths
|
| 210 |
-
input_length = len(words)
|
| 211 |
-
max_new_tokens = min(100, max(20, input_length // 3))
|
| 212 |
-
min_length = min(15, max(5, input_length // 8))
|
| 213 |
-
|
| 214 |
-
result = summarizer_pipeline(
|
| 215 |
-
text,
|
| 216 |
-
max_new_tokens=max_new_tokens,
|
| 217 |
-
min_length=min_length,
|
| 218 |
-
do_sample=False,
|
| 219 |
-
early_stopping=True
|
| 220 |
-
)
|
| 221 |
-
|
| 222 |
-
if isinstance(result, list) and len(result) > 0:
|
| 223 |
-
summary = result[0]["summary_text"].strip()
|
| 224 |
-
return summary if summary else text
|
| 225 |
return text
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
| 230 |
|
| 231 |
|
| 232 |
def format_timestamp(seconds: float) -> str:
|
|
@@ -236,168 +231,201 @@ def format_timestamp(seconds: float) -> str:
|
|
| 236 |
return f"{minutes:02d}:{remaining_seconds:02d}"
|
| 237 |
|
| 238 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
def run_pipeline(video_file: str, progress=gr.Progress()) -> List[Dict]:
|
| 240 |
-
"""Main pipeline function
|
| 241 |
if not video_file:
|
| 242 |
return [{"error": "No video file provided"}]
|
| 243 |
|
|
|
|
|
|
|
| 244 |
# Check if ffmpeg is available
|
| 245 |
if not check_ffmpeg():
|
| 246 |
return [{"error": "FFmpeg is not available in this environment"}]
|
| 247 |
|
| 248 |
-
progress(0.1, desc="
|
| 249 |
|
| 250 |
-
#
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
)
|
| 269 |
-
progress(0.3, desc="Summarization model loaded...")
|
| 270 |
-
|
| 271 |
-
except Exception as e:
|
| 272 |
-
return [{"error": f"Failed to load models: {str(e)}"}]
|
| 273 |
-
|
| 274 |
-
# Create temporary directories
|
| 275 |
temp_dir = tempfile.mkdtemp(prefix="lecture_capture_")
|
| 276 |
-
chunks_dir = os.path.join(temp_dir, "chunks")
|
| 277 |
-
frames_dir = os.path.join(temp_dir, "frames")
|
| 278 |
|
| 279 |
try:
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
# Process video with shorter chunks
|
| 286 |
-
chunks = chunk_video(video_file, chunk_length=180, output_dir=chunks_dir)
|
| 287 |
-
if not chunks:
|
| 288 |
-
return [{"error": "No video chunks were created. Video may be corrupted or unsupported format."}]
|
| 289 |
-
|
| 290 |
-
# Limit number of chunks for HF Spaces
|
| 291 |
-
chunks = chunks[:5] # Process max 5 chunks (15 minutes)
|
| 292 |
-
|
| 293 |
-
progress(0.5, desc=f"Processing {len(chunks)} chunks...")
|
| 294 |
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
progress(0.5 + (0.3 * i / len(chunks)), desc=f"Processing chunk {i+1}/{len(chunks)}...")
|
| 299 |
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
continue
|
| 306 |
-
|
| 307 |
-
# Transcribe with better error handling
|
| 308 |
-
try:
|
| 309 |
-
chunk_segments = transcribe_audio(asr, wav_path)
|
| 310 |
-
|
| 311 |
-
# Calculate absolute timestamps
|
| 312 |
-
chunk_start_time = i * 180 # 180 seconds per chunk
|
| 313 |
-
|
| 314 |
-
for seg in chunk_segments:
|
| 315 |
-
timestamp = seg.get("timestamp", (0.0, 30.0))
|
| 316 |
-
if isinstance(timestamp, tuple) and len(timestamp) == 2:
|
| 317 |
-
start_time = chunk_start_time + timestamp[0]
|
| 318 |
-
end_time = chunk_start_time + timestamp[1]
|
| 319 |
-
else:
|
| 320 |
-
start_time = chunk_start_time
|
| 321 |
-
end_time = chunk_start_time + 30
|
| 322 |
-
|
| 323 |
-
text = seg.get("text", "").strip()
|
| 324 |
-
if text: # Only add non-empty segments
|
| 325 |
-
all_segments.append({
|
| 326 |
-
"text": text,
|
| 327 |
-
"start": format_timestamp(start_time),
|
| 328 |
-
"end": format_timestamp(end_time),
|
| 329 |
-
"start_seconds": start_time,
|
| 330 |
-
"end_seconds": end_time
|
| 331 |
-
})
|
| 332 |
-
|
| 333 |
-
except Exception as e:
|
| 334 |
-
print(f"Error processing chunk {i}: {str(e)}")
|
| 335 |
-
continue
|
| 336 |
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
os.remove(wav_path)
|
| 340 |
-
except:
|
| 341 |
-
pass
|
| 342 |
-
|
| 343 |
-
if not all_segments:
|
| 344 |
-
return [{"error": "No segments were successfully processed"}]
|
| 345 |
-
|
| 346 |
-
progress(0.8, desc="Generating summaries and extracting key phrases...")
|
| 347 |
|
| 348 |
-
|
| 349 |
-
all_segments.sort(key=lambda x: x["start_seconds"])
|
| 350 |
|
| 351 |
-
#
|
| 352 |
timeline = []
|
| 353 |
-
for i,
|
| 354 |
-
|
|
|
|
|
|
|
|
|
|
| 355 |
|
| 356 |
-
# Generate summary
|
| 357 |
try:
|
| 358 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
except Exception as e:
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
"text": segment_text,
|
| 370 |
-
"summary": summary,
|
| 371 |
-
"key_phrases": key_phrases
|
| 372 |
-
})
|
| 373 |
|
| 374 |
progress(1.0, desc="Processing complete!")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
return timeline
|
| 376 |
-
|
| 377 |
except Exception as e:
|
| 378 |
import traceback
|
| 379 |
-
|
|
|
|
|
|
|
| 380 |
|
| 381 |
finally:
|
| 382 |
# Clean up temporary files
|
| 383 |
try:
|
| 384 |
shutil.rmtree(temp_dir)
|
|
|
|
| 385 |
except Exception as e:
|
| 386 |
print(f"Failed to clean up temp directory: {str(e)}")
|
| 387 |
|
| 388 |
|
| 389 |
-
# βββ Gradio UI
|
| 390 |
def create_interface():
|
| 391 |
with gr.Blocks(title="Lecture Capture AI Pipeline", theme=gr.themes.Soft()) as demo:
|
| 392 |
gr.Markdown("""
|
| 393 |
-
# π Lecture Capture AI Pipeline
|
| 394 |
|
| 395 |
Upload a lecture video to automatically generate:
|
| 396 |
- π Transcription with timestamps
|
| 397 |
- π Summaries for each segment
|
| 398 |
- π Key phrases extraction
|
| 399 |
|
| 400 |
-
**
|
| 401 |
""")
|
| 402 |
|
| 403 |
with gr.Row():
|
|
@@ -415,10 +443,10 @@ def create_interface():
|
|
| 415 |
|
| 416 |
gr.Markdown("""
|
| 417 |
### π‘ Tips:
|
| 418 |
-
- Videos up to
|
| 419 |
-
- Clear audio improves
|
| 420 |
- Processing takes 2-5 minutes
|
| 421 |
-
-
|
| 422 |
""")
|
| 423 |
|
| 424 |
with gr.Column(scale=2):
|
|
@@ -435,11 +463,11 @@ def create_interface():
|
|
| 435 |
)
|
| 436 |
|
| 437 |
gr.Markdown("""
|
| 438 |
-
### π§
|
| 439 |
-
- Uses Whisper
|
| 440 |
-
-
|
| 441 |
-
-
|
| 442 |
-
-
|
| 443 |
""")
|
| 444 |
|
| 445 |
return demo
|
|
@@ -447,4 +475,4 @@ def create_interface():
|
|
| 447 |
|
| 448 |
if __name__ == "__main__":
|
| 449 |
demo = create_interface()
|
| 450 |
-
demo.launch()
|
|
|
|
| 5 |
import shutil
|
| 6 |
from pathlib import Path
|
| 7 |
from typing import List, Dict, Optional
|
| 8 |
+
import threading
|
| 9 |
+
import signal
|
| 10 |
|
| 11 |
import spacy
|
| 12 |
import gradio as gr
|
| 13 |
from transformers import pipeline
|
| 14 |
import torch
|
| 15 |
|
| 16 |
+
# Global timeout handler
|
| 17 |
+
class TimeoutError(Exception):
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
def timeout_handler(signum, frame):
|
| 21 |
+
raise TimeoutError("Operation timed out")
|
| 22 |
+
|
| 23 |
# βββ spaCy setup for HF Spaces βββ
|
| 24 |
def setup_spacy():
|
| 25 |
"""Setup spaCy model with proper error handling for HF Spaces"""
|
|
|
|
| 27 |
nlp = spacy.load("en_core_web_sm")
|
| 28 |
return nlp
|
| 29 |
except OSError:
|
| 30 |
+
print("spaCy model not found, using fallback...")
|
| 31 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
nlp = setup_spacy()
|
| 34 |
|
| 35 |
|
| 36 |
+
def run_with_timeout(func, timeout_seconds, *args, **kwargs):
|
| 37 |
+
"""Run a function with a timeout"""
|
| 38 |
+
result = [None]
|
| 39 |
+
exception = [None]
|
| 40 |
+
|
| 41 |
+
def target():
|
| 42 |
+
try:
|
| 43 |
+
result[0] = func(*args, **kwargs)
|
| 44 |
+
except Exception as e:
|
| 45 |
+
exception[0] = e
|
| 46 |
+
|
| 47 |
+
thread = threading.Thread(target=target)
|
| 48 |
+
thread.daemon = True
|
| 49 |
+
thread.start()
|
| 50 |
+
thread.join(timeout_seconds)
|
| 51 |
+
|
| 52 |
+
if thread.is_alive():
|
| 53 |
+
# Force cleanup if thread is still running
|
| 54 |
+
raise TimeoutError(f"Function timed out after {timeout_seconds} seconds")
|
| 55 |
+
|
| 56 |
+
if exception[0]:
|
| 57 |
+
raise exception[0]
|
| 58 |
+
|
| 59 |
+
return result[0]
|
| 60 |
|
| 61 |
|
| 62 |
def check_ffmpeg():
|
| 63 |
+
"""Check if ffmpeg is available"""
|
| 64 |
try:
|
| 65 |
+
result = subprocess.run(["ffmpeg", "-version"], capture_output=True, timeout=10)
|
| 66 |
+
return result.returncode == 0
|
| 67 |
+
except:
|
| 68 |
return False
|
| 69 |
|
| 70 |
|
| 71 |
+
def get_video_info(video_path: str) -> Dict:
|
| 72 |
+
"""Get video information using ffprobe"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
try:
|
| 74 |
cmd = [
|
| 75 |
+
"ffprobe", "-v", "quiet", "-print_format", "json", "-show_format",
|
| 76 |
+
"-show_streams", video_path
|
|
|
|
|
|
|
| 77 |
]
|
| 78 |
+
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
|
| 79 |
|
| 80 |
+
if result.returncode == 0:
|
| 81 |
+
import json
|
| 82 |
+
info = json.loads(result.stdout)
|
| 83 |
|
| 84 |
+
# Extract video stream info
|
| 85 |
+
video_streams = [s for s in info.get('streams', []) if s.get('codec_type') == 'video']
|
| 86 |
+
audio_streams = [s for s in info.get('streams', []) if s.get('codec_type') == 'audio']
|
| 87 |
+
|
| 88 |
+
duration = float(info.get('format', {}).get('duration', 0))
|
| 89 |
+
|
| 90 |
+
return {
|
| 91 |
+
'duration': duration,
|
| 92 |
+
'has_video': len(video_streams) > 0,
|
| 93 |
+
'has_audio': len(audio_streams) > 0,
|
| 94 |
+
'video_codec': video_streams[0].get('codec_name') if video_streams else None,
|
| 95 |
+
'audio_codec': audio_streams[0].get('codec_name') if audio_streams else None
|
| 96 |
+
}
|
| 97 |
except Exception as e:
|
| 98 |
+
print(f"Error getting video info: {e}")
|
| 99 |
+
|
| 100 |
+
return {'duration': 0, 'has_video': False, 'has_audio': False}
|
| 101 |
|
| 102 |
|
| 103 |
+
def extract_audio_simple(video_path: str, audio_path: str, start_time: float = 0, duration: float = 180) -> bool:
|
| 104 |
+
"""Extract audio with simpler approach and better error handling"""
|
| 105 |
try:
|
| 106 |
cmd = [
|
| 107 |
+
"ffmpeg", "-y",
|
| 108 |
+
"-ss", str(start_time), # Start time
|
| 109 |
+
"-i", video_path,
|
| 110 |
+
"-t", str(duration), # Duration
|
| 111 |
+
"-vn", # No video
|
| 112 |
+
"-acodec", "pcm_s16le", # Audio codec
|
| 113 |
+
"-ar", "16000", # Sample rate
|
| 114 |
+
"-ac", "1", # Mono
|
| 115 |
+
"-f", "wav", # Output format
|
| 116 |
audio_path
|
| 117 |
]
|
|
|
|
| 118 |
|
| 119 |
+
print(f"Extracting audio: {' '.join(cmd)}")
|
| 120 |
+
|
| 121 |
+
result = subprocess.run(
|
| 122 |
+
cmd,
|
| 123 |
+
capture_output=True,
|
| 124 |
+
text=True,
|
| 125 |
+
timeout=60 # 1 minute timeout
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
if result.returncode == 0:
|
| 129 |
+
# Check if file was created and has content
|
| 130 |
+
if os.path.exists(audio_path) and os.path.getsize(audio_path) > 1000:
|
| 131 |
+
print(f"Audio extracted successfully: {os.path.getsize(audio_path)} bytes")
|
| 132 |
+
return True
|
| 133 |
+
else:
|
| 134 |
+
print("Audio file created but seems empty")
|
| 135 |
+
return False
|
| 136 |
+
else:
|
| 137 |
+
print(f"FFmpeg error: {result.stderr}")
|
| 138 |
return False
|
| 139 |
+
|
| 140 |
except subprocess.TimeoutExpired:
|
| 141 |
print("Audio extraction timed out")
|
| 142 |
return False
|
|
|
|
| 145 |
return False
|
| 146 |
|
| 147 |
|
| 148 |
+
def transcribe_audio_simple(audio_path: str) -> List[Dict]:
|
| 149 |
+
"""Simple transcription without complex pipeline parameters"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
try:
|
| 151 |
+
print(f"Starting transcription of {audio_path}")
|
|
|
|
| 152 |
|
| 153 |
+
# Use a simpler approach
|
| 154 |
+
import whisper
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
+
# Load smaller model
|
| 157 |
+
model = whisper.load_model("tiny")
|
| 158 |
+
|
| 159 |
+
# Transcribe with timeout
|
| 160 |
+
def do_transcribe():
|
| 161 |
+
result = model.transcribe(audio_path, language="en")
|
| 162 |
+
return result
|
| 163 |
+
|
| 164 |
+
result = run_with_timeout(do_transcribe, 120) # 2 minute timeout
|
| 165 |
+
|
| 166 |
+
if result and "segments" in result:
|
|
|
|
|
|
|
| 167 |
segments = []
|
| 168 |
+
for seg in result["segments"]:
|
| 169 |
+
segments.append({
|
| 170 |
+
"text": seg.get("text", "").strip(),
|
| 171 |
+
"timestamp": (seg.get("start", 0), seg.get("end", 30))
|
| 172 |
+
})
|
|
|
|
| 173 |
return segments
|
| 174 |
+
elif result and "text" in result:
|
| 175 |
+
return [{"text": result["text"], "timestamp": (0, 30)}]
|
| 176 |
else:
|
| 177 |
+
return [{"text": "Transcription failed", "timestamp": (0, 30)}]
|
| 178 |
|
| 179 |
except Exception as e:
|
| 180 |
print(f"Transcription error: {str(e)}")
|
| 181 |
+
return [{"text": f"Transcription failed: {str(e)}", "timestamp": (0, 30)}]
|
| 182 |
|
| 183 |
|
| 184 |
+
def extract_key_phrases_simple(text: str, top_n: int = 5) -> List[str]:
|
| 185 |
+
"""Simple key phrase extraction"""
|
| 186 |
+
if not text:
|
| 187 |
+
return []
|
|
|
|
| 188 |
|
| 189 |
+
# Simple approach: extract longer words
|
|
|
|
| 190 |
words = text.split()
|
| 191 |
+
# Filter for meaningful words
|
| 192 |
+
key_words = [
|
| 193 |
+
w.strip('.,!?";') for w in words
|
| 194 |
+
if len(w) > 4 and w.isalpha() and w.lower() not in {
|
| 195 |
+
'this', 'that', 'with', 'have', 'will', 'from', 'they', 'been',
|
| 196 |
+
'were', 'said', 'each', 'which', 'their', 'time', 'would', 'there'
|
| 197 |
+
}
|
| 198 |
+
]
|
| 199 |
+
|
| 200 |
+
# Remove duplicates while preserving order
|
| 201 |
+
seen = set()
|
| 202 |
+
unique_words = [w for w in key_words if not (w.lower() in seen or seen.add(w.lower()))]
|
| 203 |
|
| 204 |
+
return unique_words[:top_n]
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def summarize_text_simple(text: str) -> str:
|
| 208 |
+
"""Simple text summarization"""
|
| 209 |
+
if not text or len(text.split()) < 10:
|
| 210 |
+
return text
|
| 211 |
|
| 212 |
+
# Simple approach: take first and last sentences, or middle part
|
| 213 |
+
sentences = text.split('.')
|
| 214 |
+
sentences = [s.strip() for s in sentences if s.strip()]
|
| 215 |
|
| 216 |
+
if len(sentences) <= 2:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
return text
|
| 218 |
+
elif len(sentences) <= 5:
|
| 219 |
+
return '. '.join(sentences[:2]) + '.'
|
| 220 |
+
else:
|
| 221 |
+
# Take first, middle, and last sentences
|
| 222 |
+
middle_idx = len(sentences) // 2
|
| 223 |
+
summary_sentences = [sentences[0], sentences[middle_idx], sentences[-1]]
|
| 224 |
+
return '. '.join(summary_sentences) + '.'
|
| 225 |
|
| 226 |
|
| 227 |
def format_timestamp(seconds: float) -> str:
|
|
|
|
| 231 |
return f"{minutes:02d}:{remaining_seconds:02d}"
|
| 232 |
|
| 233 |
|
| 234 |
+
def process_video_segment(video_path: str, start_time: float, duration: float, segment_id: int, temp_dir: str) -> Dict:
|
| 235 |
+
"""Process a single video segment"""
|
| 236 |
+
try:
|
| 237 |
+
print(f"Processing segment {segment_id}: {start_time}s - {start_time + duration}s")
|
| 238 |
+
|
| 239 |
+
# Create audio file path
|
| 240 |
+
audio_path = os.path.join(temp_dir, f"segment_{segment_id:03d}.wav")
|
| 241 |
+
|
| 242 |
+
# Extract audio for this segment
|
| 243 |
+
if not extract_audio_simple(video_path, audio_path, start_time, duration):
|
| 244 |
+
return {
|
| 245 |
+
"segment": segment_id,
|
| 246 |
+
"start_time": format_timestamp(start_time),
|
| 247 |
+
"end_time": format_timestamp(start_time + duration),
|
| 248 |
+
"text": "Audio extraction failed",
|
| 249 |
+
"summary": "Failed to process this segment",
|
| 250 |
+
"key_phrases": []
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
# Transcribe audio
|
| 254 |
+
segments = transcribe_audio_simple(audio_path)
|
| 255 |
+
|
| 256 |
+
# Combine all text from segments
|
| 257 |
+
full_text = " ".join([seg["text"] for seg in segments if seg["text"]])
|
| 258 |
+
|
| 259 |
+
# Clean up audio file
|
| 260 |
+
try:
|
| 261 |
+
os.remove(audio_path)
|
| 262 |
+
except:
|
| 263 |
+
pass
|
| 264 |
+
|
| 265 |
+
if not full_text.strip():
|
| 266 |
+
return {
|
| 267 |
+
"segment": segment_id,
|
| 268 |
+
"start_time": format_timestamp(start_time),
|
| 269 |
+
"end_time": format_timestamp(start_time + duration),
|
| 270 |
+
"text": "No speech detected",
|
| 271 |
+
"summary": "No content in this segment",
|
| 272 |
+
"key_phrases": []
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
# Generate summary and key phrases
|
| 276 |
+
summary = summarize_text_simple(full_text)
|
| 277 |
+
key_phrases = extract_key_phrases_simple(full_text)
|
| 278 |
+
|
| 279 |
+
return {
|
| 280 |
+
"segment": segment_id,
|
| 281 |
+
"start_time": format_timestamp(start_time),
|
| 282 |
+
"end_time": format_timestamp(start_time + duration),
|
| 283 |
+
"text": full_text,
|
| 284 |
+
"summary": summary,
|
| 285 |
+
"key_phrases": key_phrases
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
except Exception as e:
|
| 289 |
+
print(f"Error processing segment {segment_id}: {str(e)}")
|
| 290 |
+
return {
|
| 291 |
+
"segment": segment_id,
|
| 292 |
+
"start_time": format_timestamp(start_time),
|
| 293 |
+
"end_time": format_timestamp(start_time + duration),
|
| 294 |
+
"text": f"Processing failed: {str(e)}",
|
| 295 |
+
"summary": "Error occurred during processing",
|
| 296 |
+
"key_phrases": []
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
|
| 300 |
def run_pipeline(video_file: str, progress=gr.Progress()) -> List[Dict]:
|
| 301 |
+
"""Main pipeline function with better error handling and debugging"""
|
| 302 |
if not video_file:
|
| 303 |
return [{"error": "No video file provided"}]
|
| 304 |
|
| 305 |
+
print(f"Processing video: {video_file}")
|
| 306 |
+
|
| 307 |
# Check if ffmpeg is available
|
| 308 |
if not check_ffmpeg():
|
| 309 |
return [{"error": "FFmpeg is not available in this environment"}]
|
| 310 |
|
| 311 |
+
progress(0.1, desc="Analyzing video...")
|
| 312 |
|
| 313 |
+
# Get video information
|
| 314 |
+
video_info = get_video_info(video_file)
|
| 315 |
+
print(f"Video info: {video_info}")
|
| 316 |
+
|
| 317 |
+
if not video_info['has_audio']:
|
| 318 |
+
return [{"error": "Video has no audio track"}]
|
| 319 |
+
|
| 320 |
+
duration = video_info['duration']
|
| 321 |
+
if duration == 0:
|
| 322 |
+
return [{"error": "Could not determine video duration"}]
|
| 323 |
+
|
| 324 |
+
# Limit processing time for HF Spaces
|
| 325 |
+
max_duration = min(duration, 600) # Max 10 minutes
|
| 326 |
+
segment_length = 120 # 2 minutes per segment
|
| 327 |
+
|
| 328 |
+
progress(0.2, desc=f"Video duration: {duration:.1f}s, processing {max_duration:.1f}s...")
|
| 329 |
+
|
| 330 |
+
# Create temporary directory
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
temp_dir = tempfile.mkdtemp(prefix="lecture_capture_")
|
|
|
|
|
|
|
| 332 |
|
| 333 |
try:
|
| 334 |
+
# Calculate segments
|
| 335 |
+
segments_to_process = []
|
| 336 |
+
current_time = 0
|
| 337 |
+
segment_id = 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 338 |
|
| 339 |
+
while current_time < max_duration:
|
| 340 |
+
remaining_time = max_duration - current_time
|
| 341 |
+
actual_duration = min(segment_length, remaining_time)
|
|
|
|
| 342 |
|
| 343 |
+
segments_to_process.append({
|
| 344 |
+
'start_time': current_time,
|
| 345 |
+
'duration': actual_duration,
|
| 346 |
+
'segment_id': segment_id
|
| 347 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
+
current_time += actual_duration
|
| 350 |
+
segment_id += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
|
| 352 |
+
print(f"Will process {len(segments_to_process)} segments")
|
|
|
|
| 353 |
|
| 354 |
+
# Process each segment
|
| 355 |
timeline = []
|
| 356 |
+
for i, seg_info in enumerate(segments_to_process):
|
| 357 |
+
progress(
|
| 358 |
+
0.3 + (0.6 * i / len(segments_to_process)),
|
| 359 |
+
desc=f"Processing segment {i+1}/{len(segments_to_process)}..."
|
| 360 |
+
)
|
| 361 |
|
|
|
|
| 362 |
try:
|
| 363 |
+
result = run_with_timeout(
|
| 364 |
+
process_video_segment,
|
| 365 |
+
300, # 5 minute timeout per segment
|
| 366 |
+
video_file,
|
| 367 |
+
seg_info['start_time'],
|
| 368 |
+
seg_info['duration'],
|
| 369 |
+
seg_info['segment_id'],
|
| 370 |
+
temp_dir
|
| 371 |
+
)
|
| 372 |
+
timeline.append(result)
|
| 373 |
+
|
| 374 |
+
except TimeoutError:
|
| 375 |
+
print(f"Segment {i+1} timed out")
|
| 376 |
+
timeline.append({
|
| 377 |
+
"segment": seg_info['segment_id'],
|
| 378 |
+
"start_time": format_timestamp(seg_info['start_time']),
|
| 379 |
+
"end_time": format_timestamp(seg_info['start_time'] + seg_info['duration']),
|
| 380 |
+
"text": "Processing timed out",
|
| 381 |
+
"summary": "Segment processing exceeded time limit",
|
| 382 |
+
"key_phrases": []
|
| 383 |
+
})
|
| 384 |
except Exception as e:
|
| 385 |
+
print(f"Error processing segment {i+1}: {str(e)}")
|
| 386 |
+
timeline.append({
|
| 387 |
+
"segment": seg_info['segment_id'],
|
| 388 |
+
"start_time": format_timestamp(seg_info['start_time']),
|
| 389 |
+
"end_time": format_timestamp(seg_info['start_time'] + seg_info['duration']),
|
| 390 |
+
"text": f"Error: {str(e)}",
|
| 391 |
+
"summary": "Processing failed",
|
| 392 |
+
"key_phrases": []
|
| 393 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 394 |
|
| 395 |
progress(1.0, desc="Processing complete!")
|
| 396 |
+
|
| 397 |
+
if not timeline:
|
| 398 |
+
return [{"error": "No segments were successfully processed"}]
|
| 399 |
+
|
| 400 |
return timeline
|
| 401 |
+
|
| 402 |
except Exception as e:
|
| 403 |
import traceback
|
| 404 |
+
print(f"Pipeline error: {str(e)}")
|
| 405 |
+
print(traceback.format_exc())
|
| 406 |
+
return [{"error": f"Pipeline failed: {str(e)}"}]
|
| 407 |
|
| 408 |
finally:
|
| 409 |
# Clean up temporary files
|
| 410 |
try:
|
| 411 |
shutil.rmtree(temp_dir)
|
| 412 |
+
print("Cleaned up temporary files")
|
| 413 |
except Exception as e:
|
| 414 |
print(f"Failed to clean up temp directory: {str(e)}")
|
| 415 |
|
| 416 |
|
| 417 |
+
# βββ Gradio UI βββ
|
| 418 |
def create_interface():
|
| 419 |
with gr.Blocks(title="Lecture Capture AI Pipeline", theme=gr.themes.Soft()) as demo:
|
| 420 |
gr.Markdown("""
|
| 421 |
+
# π Lecture Capture AI Pipeline (Debug Version)
|
| 422 |
|
| 423 |
Upload a lecture video to automatically generate:
|
| 424 |
- π Transcription with timestamps
|
| 425 |
- π Summaries for each segment
|
| 426 |
- π Key phrases extraction
|
| 427 |
|
| 428 |
+
**Debug Features**: Enhanced error reporting and timeout handling
|
| 429 |
""")
|
| 430 |
|
| 431 |
with gr.Row():
|
|
|
|
| 443 |
|
| 444 |
gr.Markdown("""
|
| 445 |
### π‘ Tips:
|
| 446 |
+
- Videos up to 10 minutes work best
|
| 447 |
+
- Clear audio improves results
|
| 448 |
- Processing takes 2-5 minutes
|
| 449 |
+
- Check browser console for debug info
|
| 450 |
""")
|
| 451 |
|
| 452 |
with gr.Column(scale=2):
|
|
|
|
| 463 |
)
|
| 464 |
|
| 465 |
gr.Markdown("""
|
| 466 |
+
### π§ Debug Info:
|
| 467 |
+
- Uses direct Whisper model loading
|
| 468 |
+
- Enhanced timeout handling
|
| 469 |
+
- Detailed error reporting
|
| 470 |
+
- Segment-by-segment processing
|
| 471 |
""")
|
| 472 |
|
| 473 |
return demo
|
|
|
|
| 475 |
|
| 476 |
if __name__ == "__main__":
|
| 477 |
demo = create_interface()
|
| 478 |
+
demo.launch(debug=True)
|