Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,18 +9,10 @@ import ffmpeg
|
|
| 9 |
import time
|
| 10 |
import json
|
| 11 |
import psutil
|
| 12 |
-
import sys
|
| 13 |
-
from pathlib import Path
|
| 14 |
-
import glob
|
| 15 |
-
|
| 16 |
-
# Workaround for torch.classes and Streamlit compatibility
|
| 17 |
-
st._is_running_with_streamlit = True
|
| 18 |
-
if 'torch' in sys.modules and hasattr(sys.modules['torch'], '__path__'):
|
| 19 |
-
sys.modules['torch'].__path__ = []
|
| 20 |
|
| 21 |
st.set_page_config(layout="wide")
|
| 22 |
|
| 23 |
-
# CSS
|
| 24 |
st.markdown("""
|
| 25 |
<style>
|
| 26 |
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap');
|
|
@@ -198,7 +190,7 @@ st.markdown("""
|
|
| 198 |
font-family: 'Poppins', sans-serif;
|
| 199 |
}
|
| 200 |
|
| 201 |
-
/* Video player styling */
|
| 202 |
video {
|
| 203 |
display: block;
|
| 204 |
width: 350px !important;
|
|
@@ -300,25 +292,21 @@ class TranscriptionProgress:
|
|
| 300 |
@st.cache_resource
|
| 301 |
def load_model(language='en', summarizer_type='bart'):
|
| 302 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
return processor, model, sum_tokenizer, sum_model, device
|
| 319 |
-
except Exception as e:
|
| 320 |
-
st.error(f"Error loading models: {str(e)}")
|
| 321 |
-
return None, None, None, None, None
|
| 322 |
|
| 323 |
def split_audio_into_chunks(audio, sr, chunk_duration):
|
| 324 |
chunk_samples = int(chunk_duration * sr)
|
|
@@ -326,23 +314,17 @@ def split_audio_into_chunks(audio, sr, chunk_duration):
|
|
| 326 |
return chunks
|
| 327 |
|
| 328 |
def transcribe_audio(audio, sr, processor, model, device, start_time, language, task="transcribe"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
try:
|
| 330 |
-
inputs = processor(audio, sampling_rate=sr, return_tensors="pt")
|
| 331 |
-
input_features = inputs.input_features.to(device)
|
| 332 |
-
attention_mask = inputs.get("attention_mask", None)
|
| 333 |
-
if attention_mask is not None:
|
| 334 |
-
attention_mask = attention_mask.to(device)
|
| 335 |
-
if model.dtype == torch.float16:
|
| 336 |
-
input_features = input_features.half()
|
| 337 |
-
generate_kwargs = {
|
| 338 |
-
"task": task,
|
| 339 |
-
"language": "urdu" if language == "ur" else language,
|
| 340 |
-
"max_new_tokens": 128,
|
| 341 |
-
"return_timestamps": True,
|
| 342 |
-
"do_sample": False
|
| 343 |
-
}
|
| 344 |
-
if attention_mask is not None:
|
| 345 |
-
generate_kwargs["attention_mask"] = attention_mask
|
| 346 |
with torch.no_grad():
|
| 347 |
outputs = model.generate(input_features, **generate_kwargs)
|
| 348 |
text = processor.decode(outputs[0], skip_special_tokens=True)
|
|
@@ -355,28 +337,26 @@ def process_chunks(chunks, sr, processor, model, device, language, chunk_duratio
|
|
| 355 |
transcript = []
|
| 356 |
chunk_start = 0
|
| 357 |
total_chunks = len(chunks)
|
| 358 |
-
|
| 359 |
-
|
| 360 |
if os.path.exists(transcript_file):
|
| 361 |
-
|
| 362 |
-
os.remove(transcript_file)
|
| 363 |
-
except Exception as e:
|
| 364 |
-
st.warning(f"Failed to remove {transcript_file}: {str(e)}")
|
| 365 |
for i, chunk in enumerate(chunks):
|
| 366 |
-
|
| 367 |
try:
|
| 368 |
memory = psutil.virtual_memory()
|
| 369 |
-
|
| 370 |
-
st.warning(f"High memory usage: {memory.percent}% - Consider reducing chunk size.")
|
| 371 |
chunk_transcript = transcribe_audio(chunk, sr, processor, model, device, chunk_start, language, task)
|
| 372 |
transcript.extend(chunk_transcript)
|
| 373 |
with open(transcript_file, "w", encoding="utf-8") as f:
|
| 374 |
json.dump(transcript, f, ensure_ascii=False)
|
| 375 |
chunk_start += chunk_duration
|
|
|
|
| 376 |
except Exception as e:
|
| 377 |
st.error(f"Error processing chunk {i+1}: {str(e)}")
|
| 378 |
break
|
| 379 |
-
|
|
|
|
| 380 |
return transcript
|
| 381 |
|
| 382 |
def summarize_text(text, tokenizer, model, device, summarizer_type='bart'):
|
|
@@ -388,29 +368,18 @@ def summarize_text(text, tokenizer, model, device, summarizer_type='bart'):
|
|
| 388 |
max_input_length = 16384
|
| 389 |
max_summary_length = 512
|
| 390 |
chunk_size = 8192
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 391 |
try:
|
| 392 |
-
inputs = tokenizer(text, return_tensors="pt", truncation=False)
|
| 393 |
-
input_ids = inputs["input_ids"].to(device)
|
| 394 |
-
attention_mask = inputs.get("attention_mask")
|
| 395 |
-
if attention_mask is not None:
|
| 396 |
-
attention_mask = attention_mask.to(device)
|
| 397 |
-
num_tokens = input_ids.shape[1]
|
| 398 |
-
st.write(f"Number of tokens in input: {num_tokens}")
|
| 399 |
-
if num_tokens < 50:
|
| 400 |
-
return "Transcript too short to summarize effectively."
|
| 401 |
summaries = []
|
| 402 |
if num_tokens <= max_input_length:
|
| 403 |
truncated_inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=max_input_length).to(device)
|
| 404 |
with torch.no_grad():
|
| 405 |
-
summary_ids = model.generate(
|
| 406 |
-
truncated_inputs["input_ids"],
|
| 407 |
-
attention_mask=truncated_inputs.get("attention_mask"),
|
| 408 |
-
num_beams=4,
|
| 409 |
-
max_length=max_summary_length,
|
| 410 |
-
min_length=50,
|
| 411 |
-
early_stopping=True,
|
| 412 |
-
temperature=0.7
|
| 413 |
-
)
|
| 414 |
summaries.append(tokenizer.decode(summary_ids[0], skip_special_tokens=True))
|
| 415 |
else:
|
| 416 |
st.write(f"Transcript exceeds {max_input_length} tokens. Processing in chunks...")
|
|
@@ -419,27 +388,12 @@ def summarize_text(text, tokenizer, model, device, summarizer_type='bart'):
|
|
| 419 |
chunk_tokens = tokens[i:i + chunk_size]
|
| 420 |
chunk_input_ids = torch.tensor([chunk_tokens]).to(device)
|
| 421 |
with torch.no_grad():
|
| 422 |
-
summary_ids = model.generate(
|
| 423 |
-
chunk_input_ids,
|
| 424 |
-
num_beams=4,
|
| 425 |
-
max_length=max_summary_length // 2,
|
| 426 |
-
min_length=25,
|
| 427 |
-
early_stopping=True,
|
| 428 |
-
temperature=0.7
|
| 429 |
-
)
|
| 430 |
summaries.append(tokenizer.decode(summary_ids[0], skip_special_tokens=True))
|
| 431 |
combined_summary = " ".join(summaries)
|
| 432 |
combined_inputs = tokenizer(combined_summary, return_tensors="pt", truncation=True, max_length=max_input_length).to(device)
|
| 433 |
with torch.no_grad():
|
| 434 |
-
final_summary_ids = model.generate(
|
| 435 |
-
combined_inputs["input_ids"],
|
| 436 |
-
attention_mask=combined_inputs.get("attention_mask"),
|
| 437 |
-
num_beams=4,
|
| 438 |
-
max_length=max_summary_length,
|
| 439 |
-
min_length=50,
|
| 440 |
-
early_stopping=True,
|
| 441 |
-
temperature=0.7
|
| 442 |
-
)
|
| 443 |
summaries = [tokenizer.decode(final_summary_ids[0], skip_special_tokens=True)]
|
| 444 |
return " ".join(summaries)
|
| 445 |
except Exception as e:
|
|
@@ -448,8 +402,7 @@ def summarize_text(text, tokenizer, model, device, summarizer_type='bart'):
|
|
| 448 |
|
| 449 |
def save_uploaded_file(uploaded_file):
|
| 450 |
try:
|
| 451 |
-
|
| 452 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp_file:
|
| 453 |
tmp_file.write(uploaded_file.read())
|
| 454 |
return tmp_file.name
|
| 455 |
except Exception as e:
|
|
@@ -470,10 +423,10 @@ def merge_intervals(intervals):
|
|
| 470 |
return merged
|
| 471 |
|
| 472 |
def create_edited_video(video_path, transcript, keep_indices):
|
| 473 |
-
temp_files = []
|
| 474 |
try:
|
| 475 |
intervals_to_keep = [(transcript[i][1], transcript[i][2]) for i in keep_indices]
|
| 476 |
merged_intervals = merge_intervals(intervals_to_keep)
|
|
|
|
| 477 |
for j, (start, end) in enumerate(merged_intervals):
|
| 478 |
temp_file = f"temp_{j}.mp4"
|
| 479 |
ffmpeg.input(video_path, ss=start, to=end).output(temp_file, c='copy').run(overwrite_output=True, quiet=True)
|
|
@@ -483,54 +436,28 @@ def create_edited_video(video_path, transcript, keep_indices):
|
|
| 483 |
f.write(f"file '{temp_file}'\n")
|
| 484 |
edited_video_path = "edited_video.mp4"
|
| 485 |
ffmpeg.input('list.txt', format='concat', safe=0).output(edited_video_path, c='copy').run(overwrite_output=True, quiet=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 486 |
return edited_video_path
|
| 487 |
except Exception as e:
|
| 488 |
st.error(f"Error creating edited video: {str(e)}")
|
| 489 |
return None
|
| 490 |
-
finally:
|
| 491 |
-
for temp_file in temp_files:
|
| 492 |
-
if os.path.exists(temp_file):
|
| 493 |
-
try:
|
| 494 |
-
os.remove(temp_file)
|
| 495 |
-
st.info även
|
| 496 |
-
except Exception as e:
|
| 497 |
-
st.warning(f"Failed to remove {temp_file}: {str(e)}")
|
| 498 |
-
if os.path.exists("list.txt"):
|
| 499 |
-
try:
|
| 500 |
-
os.remove("list.txt")
|
| 501 |
-
st.info(f"Removed temporary file: list.txt")
|
| 502 |
-
except Exception as e:
|
| 503 |
-
st.warning(f"Failed to remove list.txt: {str(e)}")
|
| 504 |
|
| 505 |
def generate_srt(transcript, include_timeframe=True):
|
| 506 |
srt_content = ""
|
| 507 |
-
for
|
| 508 |
if include_timeframe:
|
| 509 |
start_time = seconds_to_srt_time(start)
|
| 510 |
end_time = seconds_to_srt_time(end)
|
| 511 |
-
srt_content += f"{
|
| 512 |
else:
|
| 513 |
srt_content += f"{text}\n\n"
|
| 514 |
return srt_content
|
| 515 |
|
| 516 |
-
|
| 517 |
-
temp_files = ["processed_audio.wav", "temp_primary_transcript.json", "temp_english_transcript.json", "edited_video.mp4", "list.txt"]
|
| 518 |
-
for temp_file in temp_files:
|
| 519 |
-
if os.path.exists(temp_file):
|
| 520 |
-
try:
|
| 521 |
-
os.remove(temp_file)
|
| 522 |
-
st.info(f"Removed temporary file: {temp_file}")
|
| 523 |
-
except Exception as e:
|
| 524 |
-
st.warning(f"Failed to remove {temp_file}: {str(e)}")
|
| 525 |
-
for temp_file in glob.glob("temp_*.mp4"):
|
| 526 |
-
if os.path.exists(temp_file):
|
| 527 |
-
try:
|
| 528 |
-
os.remove(temp_file)
|
| 529 |
-
st.info(f"Removed temporary file: {temp_file}")
|
| 530 |
-
except Exception as e:
|
| 531 |
-
st.warning(f"Failed to remove {temp_file}: {str(e)}")
|
| 532 |
-
|
| 533 |
-
# Main Function
|
| 534 |
def main():
|
| 535 |
st.markdown("""
|
| 536 |
<div class="header">
|
|
@@ -553,7 +480,7 @@ def main():
|
|
| 553 |
</div>
|
| 554 |
""", unsafe_allow_html=True)
|
| 555 |
|
| 556 |
-
# Initialize session state
|
| 557 |
if 'app_state' not in st.session_state:
|
| 558 |
st.session_state['app_state'] = 'upload'
|
| 559 |
if 'video_path' not in st.session_state:
|
|
@@ -627,22 +554,16 @@ def main():
|
|
| 627 |
st.session_state['summarizer_type'] = summarizer_type
|
| 628 |
st.write("Loading models...")
|
| 629 |
processor, model, sum_tokenizer, sum_model, device = load_model(language_code, summarizer_type)
|
| 630 |
-
if processor is None:
|
| 631 |
-
st.error("Failed to load models. Please try again.")
|
| 632 |
-
return
|
| 633 |
st.write("Splitting audio into chunks...")
|
| 634 |
chunks = split_audio_into_chunks(audio, sr, chunk_duration)
|
| 635 |
st.write(f"Number of chunks: {len(chunks)}")
|
| 636 |
st.write("Transcribing audio...")
|
| 637 |
-
primary_transcript = process_chunks(chunks, sr, processor, model, device, language_code, chunk_duration, task="transcribe")
|
| 638 |
english_transcript = None
|
| 639 |
if st.session_state['translate_to_english'] and language_code == "ur":
|
| 640 |
st.write("Translating to English...")
|
| 641 |
processor, model, _, _, device = load_model('en', summarizer_type)
|
| 642 |
-
|
| 643 |
-
st.error("Failed to load translation models.")
|
| 644 |
-
return
|
| 645 |
-
english_transcript = process_chunks(chunks, sr, processor, model, device, 'ur', chunk_duration, task="translate")
|
| 646 |
st.session_state.update({
|
| 647 |
'primary_transcript': primary_transcript,
|
| 648 |
'english_transcript': english_transcript,
|
|
@@ -654,9 +575,14 @@ def main():
|
|
| 654 |
except Exception as e:
|
| 655 |
st.error(f"Processing failed: {str(e)}")
|
| 656 |
finally:
|
| 657 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 658 |
|
| 659 |
if st.session_state['app_state'] == 'results':
|
|
|
|
| 660 |
st.markdown('<div style="display: flex; justify-content: center;">', unsafe_allow_html=True)
|
| 661 |
st.video(st.session_state['video_path'], start_time=st.session_state['current_time'])
|
| 662 |
st.markdown('</div>', unsafe_allow_html=True)
|
|
@@ -687,9 +613,6 @@ def main():
|
|
| 687 |
with st.spinner("Generating summary..."):
|
| 688 |
try:
|
| 689 |
_, _, sum_tokenizer, sum_model, device = load_model(st.session_state['language_code'], st.session_state['summarizer_type'])
|
| 690 |
-
if sum_tokenizer is None:
|
| 691 |
-
st.error("Failed to load summarization models.")
|
| 692 |
-
return
|
| 693 |
full_text = " ".join([text for text, _, _ in (st.session_state['english_transcript'] or st.session_state['primary_transcript'])])
|
| 694 |
english_summary = summarize_text(full_text, sum_tokenizer, sum_model, device, st.session_state['summarizer_type'])
|
| 695 |
st.session_state['english_summary'] = english_summary
|
|
@@ -740,6 +663,7 @@ def main():
|
|
| 740 |
|
| 741 |
if st.session_state['app_state'] == 'results' and st.session_state['edited_video_path']:
|
| 742 |
st.markdown("### Edited Video")
|
|
|
|
| 743 |
st.markdown('<div style="display: flex; justify-content: center;">', unsafe_allow_html=True)
|
| 744 |
st.video(st.session_state['edited_video_path'])
|
| 745 |
st.markdown('</div>', unsafe_allow_html=True)
|
|
@@ -747,19 +671,10 @@ def main():
|
|
| 747 |
st.download_button(label="Download Edited Video", data=file, file_name="edited_video.mp4", mime="video/mp4")
|
| 748 |
|
| 749 |
if st.session_state.get('video_path') and st.button("Reset"):
|
| 750 |
-
cleanup_temp_files()
|
| 751 |
if st.session_state['video_path'] and os.path.exists(st.session_state['video_path']):
|
| 752 |
-
|
| 753 |
-
os.remove(st.session_state['video_path'])
|
| 754 |
-
st.info(f"Removed video file: {st.session_state['video_path']}")
|
| 755 |
-
except Exception as e:
|
| 756 |
-
st.warning(f"Failed to remove video file: {str(e)}")
|
| 757 |
if st.session_state['edited_video_path'] and os.path.exists(st.session_state['edited_video_path']):
|
| 758 |
-
|
| 759 |
-
os.remove(st.session_state['edited_video_path'])
|
| 760 |
-
st.info(f"Removed edited video file: {st.session_state['edited_video_path']}")
|
| 761 |
-
except Exception as e:
|
| 762 |
-
st.warning(f"Failed to remove edited video file: {str(e)}")
|
| 763 |
st.session_state.clear()
|
| 764 |
st.rerun()
|
| 765 |
|
|
@@ -900,9 +815,4 @@ def main():
|
|
| 900 |
""", unsafe_allow_html=True)
|
| 901 |
|
| 902 |
if __name__ == "__main__":
|
| 903 |
-
|
| 904 |
-
main()
|
| 905 |
-
except Exception as e:
|
| 906 |
-
st.error(f"An unexpected error occurred: {str(e)}")
|
| 907 |
-
finally:
|
| 908 |
-
cleanup_temp_files()
|
|
|
|
| 9 |
import time
|
| 10 |
import json
|
| 11 |
import psutil
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
st.set_page_config(layout="wide")
|
| 14 |
|
| 15 |
+
# Updated CSS with video styling from the second code
|
| 16 |
st.markdown("""
|
| 17 |
<style>
|
| 18 |
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap');
|
|
|
|
| 190 |
font-family: 'Poppins', sans-serif;
|
| 191 |
}
|
| 192 |
|
| 193 |
+
/* Video player styling - Updated to match second code */
|
| 194 |
video {
|
| 195 |
display: block;
|
| 196 |
width: 350px !important;
|
|
|
|
| 292 |
@st.cache_resource
|
| 293 |
def load_model(language='en', summarizer_type='bart'):
|
| 294 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 295 |
+
if language == 'ur':
|
| 296 |
+
processor = AutoProcessor.from_pretrained("GogetaBlueMUI/whisper-medium-ur-fleurs")
|
| 297 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained("GogetaBlueMUI/whisper-medium-ur-fleurs").to(device)
|
| 298 |
+
else:
|
| 299 |
+
processor = AutoProcessor.from_pretrained("openai/whisper-small")
|
| 300 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained("openai/whisper-small").to(device)
|
| 301 |
+
if device.type == "cuda":
|
| 302 |
+
model = model.half()
|
| 303 |
+
if summarizer_type == 'bart':
|
| 304 |
+
sum_tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")
|
| 305 |
+
sum_model = AutoModelForSeq2SeqLM.from_pretrained("facebook/bart-large-cnn").to(device)
|
| 306 |
+
else:
|
| 307 |
+
sum_tokenizer = AutoTokenizer.from_pretrained("pszemraj/led-large-book-summary")
|
| 308 |
+
sum_model = AutoModelForSeq2SeqLM.from_pretrained("pszemraj/led-large-book-summary").to(device)
|
| 309 |
+
return processor, model, sum_tokenizer, sum_model, device
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
def split_audio_into_chunks(audio, sr, chunk_duration):
|
| 312 |
chunk_samples = int(chunk_duration * sr)
|
|
|
|
| 314 |
return chunks
|
| 315 |
|
| 316 |
def transcribe_audio(audio, sr, processor, model, device, start_time, language, task="transcribe"):
|
| 317 |
+
inputs = processor(audio, sampling_rate=sr, return_tensors="pt")
|
| 318 |
+
input_features = inputs.input_features.to(device)
|
| 319 |
+
if model.dtype == torch.float16:
|
| 320 |
+
input_features = input_features.half()
|
| 321 |
+
generate_kwargs = {
|
| 322 |
+
"task": task,
|
| 323 |
+
"language": "urdu" if language == "ur" else language,
|
| 324 |
+
"max_new_tokens": 128,
|
| 325 |
+
"return_timestamps": True
|
| 326 |
+
}
|
| 327 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
with torch.no_grad():
|
| 329 |
outputs = model.generate(input_features, **generate_kwargs)
|
| 330 |
text = processor.decode(outputs[0], skip_special_tokens=True)
|
|
|
|
| 337 |
transcript = []
|
| 338 |
chunk_start = 0
|
| 339 |
total_chunks = len(chunks)
|
| 340 |
+
progress_bar = st.progress(0)
|
| 341 |
+
status_text = st.empty()
|
| 342 |
if os.path.exists(transcript_file):
|
| 343 |
+
os.remove(transcript_file)
|
|
|
|
|
|
|
|
|
|
| 344 |
for i, chunk in enumerate(chunks):
|
| 345 |
+
status_text.text(f"Processing chunk {i+1}/{total_chunks}...")
|
| 346 |
try:
|
| 347 |
memory = psutil.virtual_memory()
|
| 348 |
+
st.write(f"Memory usage: {memory.percent}% (Chunk {i+1}/{total_chunks})")
|
|
|
|
| 349 |
chunk_transcript = transcribe_audio(chunk, sr, processor, model, device, chunk_start, language, task)
|
| 350 |
transcript.extend(chunk_transcript)
|
| 351 |
with open(transcript_file, "w", encoding="utf-8") as f:
|
| 352 |
json.dump(transcript, f, ensure_ascii=False)
|
| 353 |
chunk_start += chunk_duration
|
| 354 |
+
progress_bar.progress((i + 1) / total_chunks)
|
| 355 |
except Exception as e:
|
| 356 |
st.error(f"Error processing chunk {i+1}: {str(e)}")
|
| 357 |
break
|
| 358 |
+
status_text.text("Processing complete!")
|
| 359 |
+
progress_bar.empty()
|
| 360 |
return transcript
|
| 361 |
|
| 362 |
def summarize_text(text, tokenizer, model, device, summarizer_type='bart'):
|
|
|
|
| 368 |
max_input_length = 16384
|
| 369 |
max_summary_length = 512
|
| 370 |
chunk_size = 8192
|
| 371 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=False)
|
| 372 |
+
input_ids = inputs["input_ids"].to(device)
|
| 373 |
+
num_tokens = input_ids.shape[1]
|
| 374 |
+
st.write(f"Number of tokens in input: {num_tokens}")
|
| 375 |
+
if num_tokens < 50:
|
| 376 |
+
return "Transcript too short to summarize effectively."
|
| 377 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
summaries = []
|
| 379 |
if num_tokens <= max_input_length:
|
| 380 |
truncated_inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=max_input_length).to(device)
|
| 381 |
with torch.no_grad():
|
| 382 |
+
summary_ids = model.generate(truncated_inputs["input_ids"], num_beams=4, max_length=max_summary_length, min_length=50, early_stopping=True, temperature=0.7)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
summaries.append(tokenizer.decode(summary_ids[0], skip_special_tokens=True))
|
| 384 |
else:
|
| 385 |
st.write(f"Transcript exceeds {max_input_length} tokens. Processing in chunks...")
|
|
|
|
| 388 |
chunk_tokens = tokens[i:i + chunk_size]
|
| 389 |
chunk_input_ids = torch.tensor([chunk_tokens]).to(device)
|
| 390 |
with torch.no_grad():
|
| 391 |
+
summary_ids = model.generate(chunk_input_ids, num_beams=4, max_length=max_summary_length // 2, min_length=25, early_stopping=True, temperature=0.7)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
summaries.append(tokenizer.decode(summary_ids[0], skip_special_tokens=True))
|
| 393 |
combined_summary = " ".join(summaries)
|
| 394 |
combined_inputs = tokenizer(combined_summary, return_tensors="pt", truncation=True, max_length=max_input_length).to(device)
|
| 395 |
with torch.no_grad():
|
| 396 |
+
final_summary_ids = model.generate(combined_inputs["input_ids"], num_beams=4, max_length=max_summary_length, min_length=50, early_stopping=True, temperature=0.7)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
summaries = [tokenizer.decode(final_summary_ids[0], skip_special_tokens=True)]
|
| 398 |
return " ".join(summaries)
|
| 399 |
except Exception as e:
|
|
|
|
| 402 |
|
| 403 |
def save_uploaded_file(uploaded_file):
|
| 404 |
try:
|
| 405 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_file:
|
|
|
|
| 406 |
tmp_file.write(uploaded_file.read())
|
| 407 |
return tmp_file.name
|
| 408 |
except Exception as e:
|
|
|
|
| 423 |
return merged
|
| 424 |
|
| 425 |
def create_edited_video(video_path, transcript, keep_indices):
|
|
|
|
| 426 |
try:
|
| 427 |
intervals_to_keep = [(transcript[i][1], transcript[i][2]) for i in keep_indices]
|
| 428 |
merged_intervals = merge_intervals(intervals_to_keep)
|
| 429 |
+
temp_files = []
|
| 430 |
for j, (start, end) in enumerate(merged_intervals):
|
| 431 |
temp_file = f"temp_{j}.mp4"
|
| 432 |
ffmpeg.input(video_path, ss=start, to=end).output(temp_file, c='copy').run(overwrite_output=True, quiet=True)
|
|
|
|
| 436 |
f.write(f"file '{temp_file}'\n")
|
| 437 |
edited_video_path = "edited_video.mp4"
|
| 438 |
ffmpeg.input('list.txt', format='concat', safe=0).output(edited_video_path, c='copy').run(overwrite_output=True, quiet=True)
|
| 439 |
+
for temp_file in temp_files:
|
| 440 |
+
if os.path.exists(temp_file):
|
| 441 |
+
os.remove(temp_file)
|
| 442 |
+
if os.path.exists("list.txt"):
|
| 443 |
+
os.remove("list.txt")
|
| 444 |
return edited_video_path
|
| 445 |
except Exception as e:
|
| 446 |
st.error(f"Error creating edited video: {str(e)}")
|
| 447 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 448 |
|
| 449 |
def generate_srt(transcript, include_timeframe=True):
|
| 450 |
srt_content = ""
|
| 451 |
+
for text, start, end in transcript:
|
| 452 |
if include_timeframe:
|
| 453 |
start_time = seconds_to_srt_time(start)
|
| 454 |
end_time = seconds_to_srt_time(end)
|
| 455 |
+
srt_content += f"{start_time} --> {end_time}\n{text}\n\n"
|
| 456 |
else:
|
| 457 |
srt_content += f"{text}\n\n"
|
| 458 |
return srt_content
|
| 459 |
|
| 460 |
+
# Main Function with Centered Video Display
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
def main():
|
| 462 |
st.markdown("""
|
| 463 |
<div class="header">
|
|
|
|
| 480 |
</div>
|
| 481 |
""", unsafe_allow_html=True)
|
| 482 |
|
| 483 |
+
# Initialize session state variables
|
| 484 |
if 'app_state' not in st.session_state:
|
| 485 |
st.session_state['app_state'] = 'upload'
|
| 486 |
if 'video_path' not in st.session_state:
|
|
|
|
| 554 |
st.session_state['summarizer_type'] = summarizer_type
|
| 555 |
st.write("Loading models...")
|
| 556 |
processor, model, sum_tokenizer, sum_model, device = load_model(language_code, summarizer_type)
|
|
|
|
|
|
|
|
|
|
| 557 |
st.write("Splitting audio into chunks...")
|
| 558 |
chunks = split_audio_into_chunks(audio, sr, chunk_duration)
|
| 559 |
st.write(f"Number of chunks: {len(chunks)}")
|
| 560 |
st.write("Transcribing audio...")
|
| 561 |
+
primary_transcript = process_chunks(chunks, sr, processor, model, device, language_code, chunk_duration, task="transcribe", transcript_file="temp_primary_transcript.json")
|
| 562 |
english_transcript = None
|
| 563 |
if st.session_state['translate_to_english'] and language_code == "ur":
|
| 564 |
st.write("Translating to English...")
|
| 565 |
processor, model, _, _, device = load_model('en', summarizer_type)
|
| 566 |
+
english_transcript = process_chunks(chunks, sr, processor, model, device, 'ur', chunk_duration, task="translate", transcript_file="temp_english_transcript.json")
|
|
|
|
|
|
|
|
|
|
| 567 |
st.session_state.update({
|
| 568 |
'primary_transcript': primary_transcript,
|
| 569 |
'english_transcript': english_transcript,
|
|
|
|
| 575 |
except Exception as e:
|
| 576 |
st.error(f"Processing failed: {str(e)}")
|
| 577 |
finally:
|
| 578 |
+
if os.path.exists(audio_path):
|
| 579 |
+
os.remove(audio_path)
|
| 580 |
+
for temp_file in ["temp_primary_transcript.json", "temp_english_transcript.json"]:
|
| 581 |
+
if os.path.exists(temp_file):
|
| 582 |
+
os.remove(temp_file)
|
| 583 |
|
| 584 |
if st.session_state['app_state'] == 'results':
|
| 585 |
+
# Center the original video
|
| 586 |
st.markdown('<div style="display: flex; justify-content: center;">', unsafe_allow_html=True)
|
| 587 |
st.video(st.session_state['video_path'], start_time=st.session_state['current_time'])
|
| 588 |
st.markdown('</div>', unsafe_allow_html=True)
|
|
|
|
| 613 |
with st.spinner("Generating summary..."):
|
| 614 |
try:
|
| 615 |
_, _, sum_tokenizer, sum_model, device = load_model(st.session_state['language_code'], st.session_state['summarizer_type'])
|
|
|
|
|
|
|
|
|
|
| 616 |
full_text = " ".join([text for text, _, _ in (st.session_state['english_transcript'] or st.session_state['primary_transcript'])])
|
| 617 |
english_summary = summarize_text(full_text, sum_tokenizer, sum_model, device, st.session_state['summarizer_type'])
|
| 618 |
st.session_state['english_summary'] = english_summary
|
|
|
|
| 663 |
|
| 664 |
if st.session_state['app_state'] == 'results' and st.session_state['edited_video_path']:
|
| 665 |
st.markdown("### Edited Video")
|
| 666 |
+
# Center the edited video
|
| 667 |
st.markdown('<div style="display: flex; justify-content: center;">', unsafe_allow_html=True)
|
| 668 |
st.video(st.session_state['edited_video_path'])
|
| 669 |
st.markdown('</div>', unsafe_allow_html=True)
|
|
|
|
| 671 |
st.download_button(label="Download Edited Video", data=file, file_name="edited_video.mp4", mime="video/mp4")
|
| 672 |
|
| 673 |
if st.session_state.get('video_path') and st.button("Reset"):
|
|
|
|
| 674 |
if st.session_state['video_path'] and os.path.exists(st.session_state['video_path']):
|
| 675 |
+
os.remove(st.session_state['video_path'])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 676 |
if st.session_state['edited_video_path'] and os.path.exists(st.session_state['edited_video_path']):
|
| 677 |
+
os.remove(st.session_state['edited_video_path'])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 678 |
st.session_state.clear()
|
| 679 |
st.rerun()
|
| 680 |
|
|
|
|
| 815 |
""", unsafe_allow_html=True)
|
| 816 |
|
| 817 |
if __name__ == "__main__":
|
| 818 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|