# Video_transcription_tab.py
# Description: This file contains the code for the video transcription tab in the Gradio UI.
#
# Imports
import json
import logging
import os
#
# External Imports
import gradio as gr
import yt_dlp
from App_Function_Libraries.Confabulation_check import simplified_geval
#
# Local Imports
from App_Function_Libraries.DB.DB_Manager import load_preset_prompts, add_media_to_database
from App_Function_Libraries.Gradio_UI.Gradio_Shared import whisper_models, update_user_prompt
from App_Function_Libraries.Gradio_UI.Gradio_Shared import error_handler
from App_Function_Libraries.Summarization_General_Lib import perform_transcription, perform_summarization, \
save_transcription_and_summary
from App_Function_Libraries.Utils.Utils import convert_to_seconds, safe_read_file, format_transcription, \
create_download_directory, generate_unique_identifier, extract_text_from_segments
from App_Function_Libraries.Video_DL_Ingestion_Lib import parse_and_expand_urls, extract_metadata, download_video
#
################################################################################################################################################################
#
# Functions:
def create_video_transcription_tab():
with (gr.TabItem("Video Transcription + Summarization")):
gr.Markdown("# Transcribe & Summarize Videos from URLs")
with gr.Row():
gr.Markdown("""Follow this project at [tldw - GitHub](https://github.com/rmusser01/tldw)""")
with gr.Row():
gr.Markdown(
"""If you're wondering what all this is, please see the 'Introduction/Help' tab up above for more detailed information and how to obtain an API Key.""")
with gr.Row():
with gr.Column():
url_input = gr.Textbox(label="URL(s) (Mandatory)",
placeholder="Enter video URLs here, one per line. Supports YouTube, Vimeo, other video sites and Youtube playlists.",
lines=5)
video_file_input = gr.File(label="Upload Video File (Optional)", file_types=["video/*"])
diarize_input = gr.Checkbox(label="Enable Speaker Diarization", value=False)
whisper_model_input = gr.Dropdown(choices=whisper_models, value="medium", label="Whisper Model")
with gr.Row():
custom_prompt_checkbox = gr.Checkbox(label="Use a Custom Prompt",
value=False,
visible=True)
preset_prompt_checkbox = gr.Checkbox(label="Use a pre-set Prompt",
value=False,
visible=True)
with gr.Row():
preset_prompt = gr.Dropdown(label="Select Preset Prompt",
choices=load_preset_prompts(),
visible=False)
with gr.Row():
custom_prompt_input = gr.Textbox(label="Custom Prompt",
placeholder="Enter custom prompt here",
lines=3,
visible=False)
with gr.Row():
system_prompt_input = gr.Textbox(label="System Prompt",
value="""You are a bulleted notes specialist. [INST]```When creating comprehensive bulleted notes, you should follow these guidelines: Use multiple headings based on the referenced topics, not categories like quotes or terms. Headings should be surrounded by bold formatting and not be listed as bullet points themselves. Leave no space between headings and their corresponding list items underneath. Important terms within the content should be emphasized by setting them in bold font. Any text that ends with a colon should also be bolded. Before submitting your response, review the instructions, and make any corrections necessary to adhered to the specified format. Do not reference these instructions within the notes.``` \nBased on the content between backticks create comprehensive bulleted notes.[/INST]
**Bulleted Note Creation Guidelines**
**Headings**:
- Based on referenced topics, not categories like quotes or terms
- Surrounded by **bold** formatting
- Not listed as bullet points
- No space between headings and list items underneath
**Emphasis**:
- **Important terms** set in bold font
- **Text ending in a colon**: also bolded
**Review**:
- Ensure adherence to specified format
- Do not reference these instructions in your response.[INST] {{ .Prompt }} [/INST]
""",
lines=3,
visible=False,
interactive=True)
custom_prompt_checkbox.change(
fn=lambda x: (gr.update(visible=x), gr.update(visible=x)),
inputs=[custom_prompt_checkbox],
outputs=[custom_prompt_input, system_prompt_input]
)
preset_prompt_checkbox.change(
fn=lambda x: gr.update(visible=x),
inputs=[preset_prompt_checkbox],
outputs=[preset_prompt]
)
def update_prompts(preset_name):
prompts = update_user_prompt(preset_name)
return (
gr.update(value=prompts["user_prompt"], visible=True),
gr.update(value=prompts["system_prompt"], visible=True)
)
preset_prompt.change(
update_prompts,
inputs=preset_prompt,
outputs=[custom_prompt_input, system_prompt_input]
)
api_name_input = gr.Dropdown(
choices=[None, "Local-LLM", "OpenAI", "Anthropic", "Cohere", "Groq", "DeepSeek", "Mistral",
"OpenRouter",
"Llama.cpp", "Kobold", "Ooba", "Tabbyapi", "VLLM", "ollama", "HuggingFace"],
value=None, label="API Name (Mandatory)")
api_key_input = gr.Textbox(label="API Key (Mandatory)", placeholder="Enter your API key here",
type="password")
keywords_input = gr.Textbox(label="Keywords", placeholder="Enter keywords here (comma-separated)",
value="default,no_keyword_set")
batch_size_input = gr.Slider(minimum=1, maximum=10, value=1, step=1,
label="Batch Size (Number of videos to process simultaneously)")
timestamp_option = gr.Radio(choices=["Include Timestamps", "Exclude Timestamps"],
value="Include Timestamps", label="Timestamp Option")
keep_original_video = gr.Checkbox(label="Keep Original Video", value=False)
# First, create a checkbox to toggle the chunking options
chunking_options_checkbox = gr.Checkbox(label="Show Chunking Options", value=False)
summarize_recursively = gr.Checkbox(label="Enable Recursive Summarization", value=False)
use_cookies_input = gr.Checkbox(label="Use cookies for authenticated download", value=False)
use_time_input = gr.Checkbox(label="Use Start and End Time", value=False)
confab_checkbox = gr.Checkbox(label="Perform Confabulation Check of Summary", value=False)
with gr.Row(visible=False) as time_input_box:
gr.Markdown("### Start and End time")
with gr.Column():
start_time_input = gr.Textbox(label="Start Time (Optional)",
placeholder="e.g., 1:30 or 90 (in seconds)")
end_time_input = gr.Textbox(label="End Time (Optional)",
placeholder="e.g., 5:45 or 345 (in seconds)")
use_time_input.change(
fn=lambda x: gr.update(visible=x),
inputs=[use_time_input],
outputs=[time_input_box]
)
cookies_input = gr.Textbox(
label="User Session Cookies",
placeholder="Paste your cookies here (JSON format)",
lines=3,
visible=False
)
use_cookies_input.change(
fn=lambda x: gr.update(visible=x),
inputs=[use_cookies_input],
outputs=[cookies_input]
)
# Then, create a Box to group the chunking options
with gr.Row(visible=False) as chunking_options_box:
gr.Markdown("### Chunking Options")
with gr.Column():
chunk_method = gr.Dropdown(choices=['words', 'sentences', 'paragraphs', 'tokens'],
label="Chunking Method")
max_chunk_size = gr.Slider(minimum=100, maximum=1000, value=300, step=50,
label="Max Chunk Size")
chunk_overlap = gr.Slider(minimum=0, maximum=100, value=0, step=10, label="Chunk Overlap")
use_adaptive_chunking = gr.Checkbox(
label="Use Adaptive Chunking (Adjust chunking based on text complexity)")
use_multi_level_chunking = gr.Checkbox(label="Use Multi-level Chunking")
chunk_language = gr.Dropdown(choices=['english', 'french', 'german', 'spanish'],
label="Chunking Language")
# Add JavaScript to toggle the visibility of the chunking options box
chunking_options_checkbox.change(
fn=lambda x: gr.update(visible=x),
inputs=[chunking_options_checkbox],
outputs=[chunking_options_box]
)
process_button = gr.Button("Process Videos")
with gr.Column():
progress_output = gr.Textbox(label="Progress")
error_output = gr.Textbox(label="Errors", visible=False)
results_output = gr.HTML(label="Results")
confabulation_output = gr.Textbox(label="Confabulation Check Results", visible=False)
download_transcription = gr.File(label="Download All Transcriptions as JSON")
download_summary = gr.File(label="Download All Summaries as Text")
@error_handler
def process_videos_with_error_handling(inputs, start_time, end_time, diarize, whisper_model,
custom_prompt_checkbox, custom_prompt, chunking_options_checkbox,
chunk_method, max_chunk_size, chunk_overlap, use_adaptive_chunking,
use_multi_level_chunking, chunk_language, api_name,
api_key, keywords, use_cookies, cookies, batch_size,
timestamp_option, keep_original_video, summarize_recursively,
progress: gr.Progress = gr.Progress()) -> tuple:
try:
logging.info("Entering process_videos_with_error_handling")
logging.info(f"Received inputs: {inputs}")
if not inputs:
raise ValueError("No inputs provided")
logging.debug("Input(s) is(are) valid")
# Ensure batch_size is an integer
try:
batch_size = int(batch_size)
except (ValueError, TypeError):
batch_size = 1 # Default to processing one video at a time if invalid
# Separate URLs and local files
urls = [input for input in inputs if
isinstance(input, str) and input.startswith(('http://', 'https://'))]
local_files = [input for input in inputs if
isinstance(input, str) and not input.startswith(('http://', 'https://'))]
# Parse and expand URLs if there are any
expanded_urls = parse_and_expand_urls(urls) if urls else []
valid_local_files = []
invalid_local_files = []
for file_path in local_files:
if os.path.exists(file_path):
valid_local_files.append(file_path)
else:
invalid_local_files.append(file_path)
error_message = f"Local file not found: {file_path}"
logging.error(error_message)
if invalid_local_files:
logging.warning(f"Found {len(invalid_local_files)} invalid local file paths")
# FIXME - Add more complete error handling for invalid local files
all_inputs = expanded_urls + valid_local_files
logging.info(f"Total valid inputs to process: {len(all_inputs)} "
f"({len(expanded_urls)} URLs, {len(valid_local_files)} local files)")
all_inputs = expanded_urls + local_files
logging.info(f"Total inputs to process: {len(all_inputs)}")
results = []
errors = []
results_html = ""
all_transcriptions = {}
all_summaries = ""
for i in range(0, len(all_inputs), batch_size):
batch = all_inputs[i:i + batch_size]
batch_results = []
for input_item in batch:
try:
start_seconds = convert_to_seconds(start_time)
end_seconds = convert_to_seconds(end_time) if end_time else None
logging.info(f"Attempting to extract metadata for {input_item}")
if input_item.startswith(('http://', 'https://')):
logging.info(f"Attempting to extract metadata for URL: {input_item}")
video_metadata = extract_metadata(input_item, use_cookies, cookies)
if not video_metadata:
raise ValueError(f"Failed to extract metadata for {input_item}")
else:
logging.info(f"Processing local file: {input_item}")
video_metadata = {"title": os.path.basename(input_item), "url": input_item}
chunk_options = {
'method': chunk_method,
'max_size': max_chunk_size,
'overlap': chunk_overlap,
'adaptive': use_adaptive_chunking,
'multi_level': use_multi_level_chunking,
'language': chunk_language
} if chunking_options_checkbox else None
if custom_prompt_checkbox:
custom_prompt = custom_prompt
else:
custom_prompt = ("""
You are a bulleted notes specialist. [INST]```When creating comprehensive bulleted notes, you should follow these guidelines: Use multiple headings based on the referenced topics, not categories like quotes or terms. Headings should be surrounded by bold formatting and not be listed as bullet points themselves. Leave no space between headings and their corresponding list items underneath. Important terms within the content should be emphasized by setting them in bold font. Any text that ends with a colon should also be bolded. Before submitting your response, review the instructions, and make any corrections necessary to adhered to the specified format. Do not reference these instructions within the notes.``` \nBased on the content between backticks create comprehensive bulleted notes.[/INST]
**Bulleted Note Creation Guidelines**
**Headings**:
- Based on referenced topics, not categories like quotes or terms
- Surrounded by **bold** formatting
- Not listed as bullet points
- No space between headings and list items underneath
**Emphasis**:
- **Important terms** set in bold font
- **Text ending in a colon**: also bolded
**Review**:
- Ensure adherence to specified format
- Do not reference these instructions in your response.[INST] {{ .Prompt }} [/INST]
""")
logging.debug("Gradio_Related.py: process_url_with_metadata being called")
result = process_url_with_metadata(
input_item, 2, whisper_model,
custom_prompt,
start_seconds, api_name, api_key,
False, False, False, False, 0.01, None, keywords, None, diarize,
end_time=end_seconds,
include_timestamps=(timestamp_option == "Include Timestamps"),
metadata=video_metadata,
use_chunking=chunking_options_checkbox,
chunk_options=chunk_options,
keep_original_video=keep_original_video,
current_whisper_model=whisper_model,
)
if result[0] is None:
error_message = "Processing failed without specific error"
batch_results.append(
(input_item, error_message, "Error", video_metadata, None, None))
errors.append(f"Error processing {input_item}: {error_message}")
else:
url, transcription, summary, json_file, summary_file, result_metadata = result
if transcription is None:
error_message = f"Processing failed for {input_item}: Transcription is None"
batch_results.append(
(input_item, error_message, "Error", result_metadata, None, None))
errors.append(error_message)
else:
batch_results.append(
(input_item, transcription, "Success", result_metadata, json_file,
summary_file))
except Exception as e:
error_message = f"Error processing {input_item}: {str(e)}"
logging.error(error_message, exc_info=True)
batch_results.append((input_item, error_message, "Error", {}, None, None))
errors.append(error_message)
results.extend(batch_results)
logging.debug(f"Processed {len(batch_results)} videos in batch")
if isinstance(progress, gr.Progress):
progress((i + len(batch)) / len(all_inputs),
f"Processed {i + len(batch)}/{len(all_inputs)} videos")
# Generate HTML for results
logging.debug(f"Generating HTML for {len(results)} results")
for url, transcription, status, metadata, json_file, summary_file in results:
if status == "Success":
title = metadata.get('title', 'Unknown Title')
# Check if transcription is a string (which it should be now)
if isinstance(transcription, str):
# Split the transcription into metadata and actual transcription
parts = transcription.split('\n\n', 1)
if len(parts) == 2:
metadata_text, transcription_text = parts
else:
metadata_text = "Metadata not found"
transcription_text = transcription
else:
metadata_text = "Metadata format error"
transcription_text = "Transcription format error"
summary = safe_read_file(summary_file) if summary_file else "No summary available"
# FIXME - Add to other functions that generate HTML
# Format the transcription
formatted_transcription = format_transcription(transcription_text)
# Format the summary
formatted_summary = format_transcription(summary)
results_html += f"""
URL: {url}
{metadata_text}
{transcription}
" + str(e) + "