Vosk is an open-source speech recognition toolkit that can be used for various applications like speech-to-text. If you want to show progress while using Vosk, you might need to track the processing of audio chunks during the recognition process.
Here's a general approach to implement progress tracking when working with Vosk:
Use Streamed Audio: If you are processing an audio file, you can read it in chunks rather than loading the entire file at once. This way, you can get feedback on how much of the audio has been processed.
Calculate Progress: You can calculate the processing progress based on the total audio length and the position of the current chunk being processed.
Implement a Callback: You might want to implement a callback function that will be called after each chunk is processed where you can update your progress display.
Example Workflow
Here's a simplified example in Python that outlines this process:
python
import wave
import sys
import vosk
# Load the Vosk model
model = vosk.Model("model")
rec = vosk.KaldiRecognizer(model, 16000)
# Open the audio file
wf = wave.open("your_audio_file.wav", "rb")
total_frames = wf.getnframes()
processed_frames = 0
# Read the audio file in chunks
chunk_size = 4000 # Process in small chunks
while True:
data = wf.readframes(chunk_size)
if len(data) == 0:
break
if rec.AcceptWaveform(data):
processed_frames += len(data) // 2
# Calculate progress percentage
progress = (processed_frames / total_frames) * 100
print(f'Progress: {progress:.2f}%')
else:
rec.PartialResult()
# After processing
result = rec.FinalResult()
print(result)
wf.close()
Explanation:
Adjust chunk_size as needed; smaller sizes might give more frequent updates but could come with overhead.
total_frames is used to determine how much of the audio has been processed to calculate the progress percentage.
The Vosk recognizer processes the audio, and you can call your progress function after each chunk to update the display, which in this example is simply printed to the console.
Notes:
Make sure your audio processing respects the format required by Vosk (like 16kHz mono PCM).
You may need to manage threading or asynchronous processing if you're working with a GUI to avoid freezing the interface while processing audio.
This example should give you a starting point. Depending on your application, you might need to adapt it further.
User
how would i interate this into this code: import json
import os
import sys
import wave
import urllib.request
import zipfile
import subprocess
import time
import logging
from moviepy.editor import *
from moviepy.video.tools.subtitles import SubtitlesClip
from PIL import Image, ImageDraw, ImageFont
import numpy as np
from tkinter import Tk, filedialog
from datetime import datetime
import argparse
try:
import win32api
WIN32_AVAILABLE = True
except ImportError:
WIN32_AVAILABLE = False
Import Vosk for speech recognition
try:
from vosk import Model, KaldiRecognizer, SetLogLevel
VOSK_AVAILABLE = True
except ImportError:
VOSK_AVAILABLE = False
print("Vosk not installed. Run 'pip install vosk' to enable automatic speech recognition.")
Configure MoviePy to show progress
import moviepy.config as conf
conf.PROGRESS_BAR = True
Cache for text clips to avoid recreating the same text multiple times
text_clip_cache = {}
def get_long_path_name(short_path):
"""Convert Windows short path to long path"""
if not WIN32_AVAILABLE:
return short_path
try:
return win32api.GetLongPathName(short_path)
except:
return short_path
def download_vosk_model(model_name="vosk-model-small-en-us-0.15"):
"""Download and extract the Vosk model if not available, with progress reporting"""
models_dir = os.path.join(os.path.dirname(os.path.abspath(file)), "models")
os.makedirs(models_dir, exist_ok=True)
code
Assistant
To incorporate progress tracking into your existing code using the Vosk speech recognition toolkit during the transcribe_audio function, you can follow these steps:
Metrics Tracking: Use the frame count (frames_processed) to calculate the percentage of audio processed and display that percentage as a progress output.
Modify transcribe_audio: You already have a structure in place for reading audio frames and processing them with Vosk. The key point is to calculate the progress after each chunk is processed.
Modified transcribe_audio Function
Here's how you can modify the transcribe_audio function to include the desired progress tracking:
python
def transcribe_audio(audio_path, model_path):
"""Transcribe audio using Vosk model and return word timings with progress reporting."""
if not os.path.exists(audio_path):
raise FileNotFoundError(f"Audio file not found: {audio_path}")
SetLogLevel(0)
wf = wave.open(audio_path, "rb")
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
print("Audio file must be WAV format mono PCM.")
return []
model = Model(model_path)
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True)
results = []
total_frames = wf.getnframes()
frames_processed = 0
print("Starting transcription...")
while True:
data = wf.readframes(4000)
if len(data) == 0:
break
frames_processed += len(data) // 2 # Since samples are 16-bit (2 bytes)
if rec.AcceptWaveform(data):
part_result = json.loads(rec.Result())
if 'result' in part_result:
results.append(part_result)
# Show progress percentage
progress = (frames_processed / total_frames) * 100
sys.stdout.write(f"\rTranscription progress: {progress:.2f}%")
sys.stdout.flush()
part_result = json.loads(rec.FinalResult())
if 'result' in part_result:
results.append(part_result)
print("\nTranscription complete.")
return results
User
whats rhe font color?
Assistant
In the context of your code, especially in the create_text_clip function where text overlays are created for video subtitles, the font color is defined in the font_color parameter.
Default Value
In the create_text_clip function signature, you can see the default font_color is set to:
python
font_color=(255, 255, 255) # This is white
This color is represented in RGB format, where:
255 (Red)
255 (Green)
255 (Blue)
Thus, (255, 255, 255) refers to the color white.
Customization
If you want to change the font color for your text clips, you can pass a different RGB tuple when calling the create_text_clip function. For example:
Black: (0, 0, 0)
Red: (255, 0, 0)
Green: (0, 255, 0)
Blue: (0, 0, 255)
Yellow: (255, 255, 0)
Purple: (128, 0, 128)
Example of Changing Font Color
You can call the function like this to change the font color to red:
python
clip = create_text_clip("Your text here", video_width, video_height, font_color=(255, 0, 0))
In Your Code
In your specific implementation, you’ve set the font_color in make_textclip to (255, 255, 255) by default, while the outline color is set to black (0, 0, 0) to create a readable contrast against various backgrounds.
If you need to adjust the font color for different parts of your text (such as highlighting certain words), you may also want to modify how you're drawing text in your create_text_clip implementation, where you currently have something like this:
python
for offset in [(1,1), (-1,1), (1,-1), (-1,-1)]:
draw.text((x + offset[0], y + offset[1]), word + " ", font=font, fill=outline_color)
draw.text((x, y), word + " ", font=font, fill=word_color)
Here, you are drawing an outline before the main text. You can customize word_color based on conditions within that loop if you have specific words that you want to emphasize differently.
User
how can i track the encoding progress?
Assistant
Tracking the encoding progress of a video file using MoviePy isn't as straightforward as tracking the transcription progress for audio. MoviePy does not provide built-in progress callbacks directly during video encoding. However, you can use a logging approach to get some feedback on the encoding process.
Using the logger Parameter in write_videofile()
MoviePy has a logger parameter in the write_videofile function that can be used to receive updates about the encoding process. By passing a custom logger, you can interpret the logs for progress updates.
Here’s a basic way to accomplish that:
Create a Custom Logger: Write a custom logging class to catch messages from MoviePy.
Pass the Logger to write_videofile: Use this custom logger when calling write_videofile.
Example Implementation
Here's how you can implement this in your existing code:
python
import logging
from moviepy.editor import VideoFileClip, CompositeVideoClip, ImageClip
class CustomLogger:
def __init__(self):
# Set up basic configuration for logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
def write(self, message):
# Log message from MoviePy
if "frame" in message:
# Extract frame-related messages to track progress
frame_info = message.split(' ')
if len(frame_info) > 1: # Ensure there is a second part
# Logging the frame number (or other relevant info)
print(f"Encoding progress: {frame_info[1]} frames processed")
def flush(self):
pass # No implementation needed for flush
# Usage in your existing code
if __name__ == "__main__":
# ... your existing code ...
# Custom logger instance
custom_logger = CustomLogger()
# Encode video with progress tracking
try:
final_video.write_videofile(
output_path,
fps=video.fps,
codec='libx264',
audio_codec='aac',
audio=True,
threads=4,
preset='medium',
logger=custom_logger # Use the custom logger to track progress
)
except Exception as e:
print(f"Error during encoding: {e}")
User
i thought vosk provided some type of progress for each word or something like that
Assistant
Yes, you are correct! Vosk provides more detailed recognition feedback including progress updates for each recognized word. When using the Vosk recognizer, you can take advantage of the partial results it returns after each segment of audio is processed.
Vosk Word-Level Progress
The Vosk recognizer can give you a stream of partial results, which include information about each word with timestamps (e.g., start and end times). This allows you to show progress based on the recognized words rather than just overall audio processing.
Here’s how you can modify your existing transcribe_audio function to utilize Vosk's word-level results for progress tracking:
Modified transcribe_audio Function with Word-Level Progress
python
def transcribe_audio(audio_path, model_path):
"""Transcribe audio using Vosk model and return word timings with progress reporting."""
if not os.path.exists(audio_path):
raise FileNotFoundError(f"Audio file not found: {audio_path}")
SetLogLevel(0)
wf = wave.open(audio_path, "rb")
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
print("Audio file must be WAV format mono PCM.")
return []
model = Model(model_path)
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True)
results = []
total_frames = wf.getnframes()
frames_processed = 0
total_words = 0
print("Starting transcription...")
while True:
data = wf.readframes(4000)
if len(data) == 0:
break
frames_processed += len(data) // 2 # Since samples are 16-bit (2 bytes)
if rec.AcceptWaveform(data):
part_result = json.loads(rec.Result())
if 'result' in part_result:
results.append(part_result)
total_words += len(part_result['result']) # Count words in current result
# Show progress based on the number of words recognized
progress = (total_words / (total_frames // 16000)) * 100 # Assuming 16kHz sample
sys.stdout.write(f"\rTranscription progress: {progress:.2f}% ({total_words} words)")
sys.stdout.flush()
partial_result = json.loads(rec.PartialResult())
if 'result' in partial_result:
for word in partial_result['result']:
total_words += 1 # Count each recognized word
# Show progress for each recognized word
progress = (total_words / (total_frames // 16000)) * 100 # Assuming 16kHz sample
sys.stdout.write(f"\rTranscription progress: {progress:.2f}% ({total_words} words)")
sys.stdout.flush()
part_result = json.loads(rec.FinalResult())
if 'result' in part_result:
results.append(part_result)
print("\nTranscription complete.")
return results
User
is that the same as the progress for video creation?
Assistant
The progress tracking for video creation and audio transcription with Vosk works fundamentally differently, though both can provide insights into the status of their respective tasks.
Key Differences Between Vosk and Video Encoding Progress Tracking:
Nature of Updates:
Vosk Transcription Progress: Provides updates based on the recognition of individual words or partial results. As it processes audio, it can immediately show progress by counting words that have been recognized in real time.
Video Encoding Progress: Typically involves processing frames of the video. MoviePy does not provide explicit frame-by-frame updates directly within its API but relies on logging output, which may not show progress as granularly or as reactively as Vosk's word updates.
Granularity:
Vosk: You can see progress as each word is recognized, which allows for immediate feedback on the transcription process.
MoviePy: Progress may be conveyed through logs indicating frames processed, but the feedback may not be immediate or granular in terms of time. You get updates based on the completion of various encoding tasks rather than word-level progress.
Implementation:
Vosk Progress: As shown in the previous examples, you can track the number of words recognized during the transcription process, giving a clear and immediate indication of progress.
MoviePy Progress: While you can implement a custom logger to track progress based on frames, the updates you receive will depend on how MoviePy outputs its logging information during the write process.
Summary of Usage:
Transcription with Vosk:
Real-time, word-by-word tracking.
Provides immediate feedback.
Video Creation with MoviePy:
Progress tracking typically relies on logs during the encoding process.
Frame-related messages can signal progress but might not be as user-friendly or immediate as Vosk's word tracking.
Example of Vosk vs Video Encoding
Vosk (Word-Level):
python
User
lets only do it for video creation prcess
Assistant
Certainly! To track the video creation process using MoviePy, you can implement a custom logger that captures progress messages related to frame processing. This way, you'll have a running tally of how many frames have been processed during the video encoding step.
Here’s how you can set this up step by step:
Step 1: Create a Custom Logger
You can create a custom logger class that will print out progress information as the video is being processed.
Step 2: Implement the Logger
Here’s how you can define a custom logger class that will output the encoding progress:
python
import logging
class CustomLogger:
def __init__(self):
# Set up basic configuration for logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
def write(self, message):
# Log message from MoviePy
if "frame" in message:
# Extract frame-related messages to track progress
print(message, end='') # Print the message to the console
def flush(self):
pass # No implementation needed for flush
Step 3: Integrate the Logger with MoviePy
You can now pass this logger to the write_videofile method when creating your final video.
Example Integration
Here’s a complete example of how your existing code could look when you include this custom logger during the video encoding step:
python
User
incorperate updates into this code accordingly: import json
import os
import sys
import wave
import urllib.request
import zipfile
import subprocess
import time
import logging
from moviepy.editor import *
from moviepy.video.tools.subtitles import SubtitlesClip
from PIL import Image, ImageDraw, ImageFont
import numpy as np
from tkinter import Tk, filedialog
from datetime import datetime
import argparse
try:
import win32api
WIN32_AVAILABLE = True
except ImportError:
WIN32_AVAILABLE = False
Import Vosk for speech recognition
try:
from vosk import Model, KaldiRecognizer, SetLogLevel
VOSK_AVAILABLE = True
except ImportError:
VOSK_AVAILABLE = False
print("Vosk not installed. Run 'pip install vosk' to enable automatic speech recognition.")
Configure MoviePy to show progress
import moviepy.config as conf
conf.PROGRESS_BAR = True
Cache for text clips to avoid recreating the same text multiple times
text_clip_cache = {}
def get_long_path_name(short_path):
"""Convert Windows short path to long path"""
if not WIN32_AVAILABLE:
return short_path
try:
return win32api.GetLongPathName(short_path)
except:
return short_path
def download_vosk_model(model_name="vosk-model-small-en-us-0.15"):
"""Download and extract the Vosk model if not available, with progress reporting"""
models_dir = os.path.join(os.path.dirname(os.path.abspath(file)), "models")
os.makedirs(models_dir, exist_ok=True)
code
Assistant
Certainly! Below, I'll modify your provided code to integrate a custom logger for tracking the encoding progress during the creation of the video with MoviePy. This logger will provide feedback on how many frames have been processed during the video encoding phase.
Updated Code with Custom Video Encoding Logger
python
User
where does it allow me to adjust the thickness of the text border
Assistant
To adjust the thickness of the text border (or outline) in the text rendering code that you provided, you need to modify the section where the outline of the text is drawn in the create_text_clip function.
Outline Thickness Adjustment
In the create_text_clip function, the thickness of the outline is controlled by the number of times you draw the outline around the text. You can achieve thicker outlines by adjusting how many times and in which directions you draw the outline.
Example of Making the Outline Thicker
Here’s a snippet from your create_text_clip function showing how to achieve the outline effect:
python
# Draw outline
for offset in [(1, 1), (-1, 1), (1, -1), (-1, -1)]:
draw.text((x + offset[0], y + offset[1]), word + " ", font=font, fill=outline_color)
Currently, you are drawing the outline four times with offsets of 1 and -1 for the x and y positions. This creates a thin outline.
Modifying for Thicker Outlines
To adjust the thickness of the outline, you can modify the offsets to use larger values, or you can increase the number of times you draw the outline. Here's how you can implement this:
Increase Offset Values: Increase the offsets to draw the outline further away from the text.
Draw More Outlines: Draw the outline multiple times with a larger spread.
Here’s how you can modify the outline-drawing logic to allow for a thicker border:
python
outline_thickness = 3 # Adjust this value for thicker or thinner outlines
# Draw outline
for x_offset in range(-outline_thickness, outline_thickness + 1): # Draw horizontally
for y_offset in range(-outline_thickness, outline_thickness + 1): # Draw vertically
if abs(x_offset) + abs(y_offset) < outline_thickness: # Condition for thickness
draw.text((x + x_offset, y + y_offset), word + " ", font=font, fill=outline_color)
Complete Example in Context
Here’s the updated function with a configurable outline thickness:
User
how do i use whats there already?
Assistant
Certainly! To adjust the thickness of the text border (border or outline) using what's already in your existing code, you can leverage the nested loop structure you've already set up for drawing the outline.
Existing Outline Drawing Logic
In your provided create_text_clip function, the outline is drawn using these lines, where the outline is drawn at offsets of 1 pixel in different directions:
python
# Draw the outline
for offset in [(1, 1), (-1, 1), (1, -1), (-1, -1)]:
draw.text((x + offset[0], y + offset[1]), word + " ", font=font, fill=outline_color)
Adjusting the Thickness of the Outline
To make the outline thicker using what's already there, you can modify the existing code by adding more iterations to create additional layers of outlines around the text. Here's how to do it using a thickness parameter that you can define when calling the create_text_clip function.
Example Implementation
Step 1: Modify your create_text_clip function to accept an outline_thickness parameter.
Step 2: Update the outline drawing logic to reflect the specified thickness.
model_path = os.path.join(models_dir, model_name)
# Check for pre-downloaded model in current directory
if os.path.exists(model_name) and os.path.isdir(model_name):
print(f"Using pre-downloaded model found at {model_name}")
return os.path.abspath(model_name)
# Check for model in models directory
if os.path.exists(model_path):
print(f"Using cached model found at {model_path}")
return model_path
# Let user manually specify model location
print("\nModel not found in the default location.")
print("Options:")
print("1. Download the model (several hundred MB, may take a while)")
print("2. Specify path to pre-downloaded model")
choice = input("Enter your choice (1 or 2): ")
if choice == "2":
# Use Tkinter to browse for the model folder
root = Tk()
root.withdraw()
custom_model_path = filedialog.askdirectory(title="Select the Vosk model directory")
if custom_model_path:
print(f"Using custom model path: {custom_model_path}")
return custom_model_path
else:
print("No model directory selected, falling back to download.")
# Download the model with progress reporting
print(f"Downloading Vosk model {model_name}...")
zip_path = os.path.join(models_dir, f"{model_name}.zip")
# Create a custom reporthook to show download progress
def download_progress(count, block_size, total_size):
percent = min(100, count * block_size * 100 // total_size)
sys.stdout.write(f"\rDownload progress: {percent}% ({count * block_size // 1024 // 1024} MB / {total_size // 1024 // 1024} MB)")
sys.stdout.flush()
try:
# Download the model
url = f"https://alphacephei.com/vosk/models/{model_name}.zip"
urllib.request.urlretrieve(url, zip_path, download_progress)
print("\nDownload complete, extracting model...")
# Extract the model
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(models_dir)
# Clean up zip file
os.remove(zip_path)
print(f"Model extracted to {model_path}")
return model_path
except Exception as e:
print(f"\nError downloading or extracting model: {e}")
if os.path.exists(zip_path):
os.remove(zip_path)
# Fallback to manual download instructions
print("\nPlease download the model manually:")
print(f"1. Go to https://alphacephei.com/vosk/models")
print(f"2. Download {model_name}.zip")
print(f"3. Extract it to the 'models' folder in {os.path.dirname(os.path.abspath(__file__))}")
print(f"4. Run this script again")
sys.exit(1)
def extract_audio(video_path, audio_path):
"""Extract audio from video using ffmpeg"""
if os.path.exists(audio_path):
os.remove(audio_path)
print("Removed existing audio file")
code
if not os.path.exists(video_path):
raise FileNotFoundError(f"Video file not found: {video_path}")
command = [
"ffmpeg",
"-i", video_path,
"-acodec", "pcm_s16le",
"-ac", "1",
"-ar", "16000",
audio_path
]
subprocess.run(command, check=True)
print("Audio extracted successfully")
def transcribe_audio(audio_path, model_path):
"""Transcribe audio using Vosk model and return word timings"""
if not os.path.exists(audio_path):
raise FileNotFoundError(f"Audio file not found: {audio_path}")
code
SetLogLevel(0)
wf = wave.open(audio_path, "rb")
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
print("Audio file must be WAV format mono PCM.")
return []
model = Model(model_path)
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True)
results = []
total_frames = wf.getnframes()
frames_processed = 0
print("Starting transcription...")
while True:
data = wf.readframes(4000)
frames_processed += 4000
if len(data) == 0:
break
if rec.AcceptWaveform(data):
part_result = json.loads(rec.Result())
if 'result' in part_result:
results.append(part_result)
# Show progress percentage
progress = min(100, (frames_processed * 100) // total_frames)
sys.stdout.write(f"\rTranscription progress: {progress}%")
sys.stdout.flush()
part_result = json.loads(rec.FinalResult())
if 'result' in part_result:
results.append(part_result)
print("\nTranscription complete.")
return results
for res in results:
if 'result' not in res:
continue
for word in res['result']:
total_words += 1
if current_start is None:
current_start = word['start']
current_text.append(word['word'])
char_count += len(word['word']) + 1 # +1 for space
# Create a new subtitle when reaching max chars or after a natural pause
if char_count >= max_chars or (len(current_text) > 1 and word.get('word', '').endswith(('.', '!', '?'))):
text = ' '.join(current_text)
end_time = word['end']
# Don't create super short clips
if end_time - current_start >= 0.3:
subtitles.append(((current_start, end_time), text))
current_text = []
current_start = None
char_count = 0
# Add any remaining text
if current_text and current_start is not None and len(results) > 0 and 'result' in results[-1]:
last_results = results[-1]['result']
if last_results:
last_word = last_results[-1]
subtitles.append(((current_start, last_word['end']), ' '.join(current_text)))
print(f"Generated {len(subtitles)} caption segments from {total_words} words")
return subtitles
def get_project_details(folder_path):
"""Get details from a CapCut project folder"""
meta_file = os.path.join(folder_path, "draft_meta.json")
if os.path.exists(meta_file):
with open(meta_file, 'r', encoding='utf-8') as f:
meta_data = json.load(f)
project_name = meta_data.get("name", "Unnamed Project")
created_time = meta_data.get("created_time", 0) / 1000 # Convert milliseconds to seconds
created_date = datetime.fromtimestamp(created_time).strftime('%Y-%m-%d %H:%M:%S')
return f"{project_name} (Created: {created_date})"
return "Unknown Project"
def extract_script(content):
"""Extract caption script from CapCut project"""
script = []
# Create a material_id to text mapping for faster lookups
materials_dict = {}
if "materials" in content and "texts" in content["materials"]:
for material in content["materials"]["texts"]:
try:
material_content = json.loads(material["content"])
materials_dict[material["id"]] = material_content["text"].replace("\n", " ")
except Exception:
continue
code
for track in content.get("tracks", []):
if track.get("type") == "text":
for segment in track.get("segments", []):
try:
start = segment["target_timerange"]["start"] / 1000000 # Convert to seconds
duration = segment["target_timerange"]["duration"] / 1000000
end = start + duration
material_id = segment["material_id"]
if material_id in materials_dict:
script.append((start, end, materials_dict[material_id]))
except KeyError:
continue
return sorted(script, key=lambda x: x[0])
def create_text_clip(text, video_width, video_height, font_size=60, font_color=(255, 255, 255),
bg_color=(0, 0, 0, 0), outline_color=(0, 0, 0)):
"""Create a text clip with the specified formatting"""
# Use cached clip if available
cache_key = f"{text}{video_width}{video_height}_{font_size}"
if cache_key in text_clip_cache:
return text_clip_cache[cache_key]
code
# Make the text area narrower to enforce wrapping
max_width = int(video_width * 0.4) # Reduced from 0.75 to make text wrap more
max_height = int(video_height * 0.80)
# Try to use the custom font, fall back to system font if not available
font_path = r"C:\Users\buggy\AppData\Local\Microsoft\Windows\Fonts\BowlbyOneSC-Regular.ttf"
try:
font = ImageFont.truetype(font_path, font_size)
except OSError:
print("BowlbyOneSC-Regular font not found. Falling back to Arial.")
font_path = r"C:\Windows\Fonts\Arial.ttf"
font = ImageFont.truetype(font_path, font_size)
words = text.split()
lines = []
current_line = []
current_width = 0
# Better word wrapping for shorter lines
for word in words:
word_bbox = font.getbbox(word + " ")
word_width = word_bbox[2] - word_bbox[0]
if current_width + word_width <= max_width:
current_line.append(word)
current_width += word_width
else:
lines.append(current_line)
current_line = [word]
current_width = word_width
if current_line:
lines.append(current_line)
line_bbox = font.getbbox("A")
line_height = (line_bbox[3] - line_bbox[1]) * 1.2 # Add 20% line spacing
total_text_height = int(line_height * len(lines))
img = Image.new('RGBA', (max_width, max_height), bg_color)
draw = ImageDraw.Draw(img)
# Start text higher up in the image (closer to top)
y_offset = (max_height - total_text_height) // 3 # Changed from //2 to //3 to move up
y = y_offset
# Flatten the lines to get total word count
all_words = [word for line in lines for word in line]
total_words = len(all_words)
word_index = 0
for line in lines:
# Left-align text instead of centering each line
x = 20 # Fixed left margin
for word in line:
if word_index >= total_words - 3: # Color the last three words regardless of line
word_color = [(255, 0, 0), (255, 255, 0), (0, 0, 255)][word_index - (total_words - 3)]
else:
word_color = font_color
# Draw outline
for offset in [(1,1), (-1,1), (1,-1), (-1,-1)]:
draw.text((x + offset[0], y + offset[1]), word + " ", font=font, fill=outline_color)
# Draw main text
draw.text((x, y), word + " ", font=font, fill=word_color)
word_bbox = font.getbbox(word + " ")
x += word_bbox[2] - word_bbox[0]
word_index += 1
y += line_height
clip = ImageClip(np.array(img))
text_clip_cache[cache_key] = clip
return clip
def make_textclip(txt):
"""Create a text clip with proper positioning"""
clip = create_text_clip(txt, video.w, video.h, outline_color=(0, 0, 0)) # Black outline
# Position fixed at left side, 40% of the height from top
y_position = int(video.h * 0.4) # Calculate actual pixel position
return clip.set_position((80, y_position))
Main execution starts here
if name == "main":
# Add command line argument support
parser = argparse.ArgumentParser(description='Add captions to video using CapCut data or Vosk speech recognition.')
parser.add_argument('--video', type=str, help='Path to input video file (optional)')
parser.add_argument('--source', type=str, choices=['capcut', 'vosk'],
help='Source for captions: "capcut" or "vosk" (optional)')
parser.add_argument('--model', type=str, default="vosk-model-small-en-us-0.15",
help='Vosk model name to use (default: vosk-model-small-en-us-0.15)')
args = parser.parse_args()
code
start_time = time.time()
# Determine caption source - Command line or interactive
use_vosk = False
if args.source:
# Use command-line specified source
use_vosk = args.source.lower() == 'vosk'
else:
# Ask interactively if not specified
print("Choose caption source:")
print("1. Extract from CapCut project")
print("2. Generate from speech using Vosk")
while True:
try:
source_choice = int(input("Enter your choice (1 or 2): "))
if source_choice == 1:
use_vosk = False
break
elif source_choice == 2:
if not VOSK_AVAILABLE:
print("Vosk is not installed. Please run 'pip install vosk' first.")
print("Falling back to CapCut extraction.")
use_vosk = False
else:
use_vosk = True
break
else:
print("Invalid choice. Please enter 1 or 2.")
except ValueError:
print("Please enter a number.")
# Get the video path - Command line or interactive
video_path = args.video
if not video_path:
root = Tk()
root.withdraw()
video_path = filedialog.askopenfilename(title="Select the video file",
filetypes=[("Video files", "*.mp4 *.avi *.mov *.wmv")])
if not video_path:
print("No video file selected. Exiting.")
sys.exit(1)
if not os.path.exists(video_path):
print(f"Error: Video file not found at {video_path}")
sys.exit(1)
# Use absolute path
video_path = os.path.abspath(video_path)
# Path for selecting or creating captions
if use_vosk:
print("Using Vosk speech recognition for captioning")
# Use the specified or default Vosk model
model_name = args.model
print(f"Using Vosk model: {model_name}")
# Download or use cached model
try:
model_path = download_vosk_model(model_name)
except Exception as e:
print(f"Error downloading model: {e}")
sys.exit(1)
# Extract audio to WAV format
current_dir = os.path.dirname(os.path.abspath(__file__))
audio_path = os.path.join(current_dir, "temp_audio.wav")
try:
extract_audio(video_path, audio_path)
# Perform speech recognition
results = transcribe_audio(audio_path, model_path)
# Convert to subtitles format
subtitles = vosk_to_subtitles(results)
# Create output filename
video_basename = os.path.basename(video_path)
name = os.path.splitext(video_basename)[0].lower().replace(" ", "_")
except Exception as e:
print(f"Error processing audio: {e}")
if os.path.exists(audio_path):
os.remove(audio_path)
sys.exit(1)
else:
print("Using CapCut project for captioning")
# List all project folders
project_folders = [f for f in os.listdir(base_path) if os.path.isdir(os.path.join(base_path, f)) and f != ".recycle_bin"]
if not project_folders:
print("No project folders found.")
sys.exit(1)
print("Available projects:")
for i, folder in enumerate(project_folders):
folder_path = os.path.join(base_path, folder)
project_details = get_project_details(folder_path)
print(f"{i + 1}. {folder} - {project_details}")
# Ask user to select a project
while True:
try:
choice = int(input("Enter the number of the project you want to process: ")) - 1
if 0 <= choice < len(project_folders):
selected_folder = project_folders[choice]
break
else:
print("Invalid choice. Please try again.")
except ValueError:
print("Please enter a number.")
folder = os.path.join(base_path, selected_folder)
draft_content_path = os.path.join(folder, "draft_content.json")
if not os.path.exists(draft_content_path):
print(f"Error: draft_content.json not found in {folder}")
sys.exit(1)
name = selected_folder.lower().replace(" ", "_")
# Load project file
try:
with open(draft_content_path, encoding="utf-8") as f:
cont = json.load(f)
except json.JSONDecodeError:
print(f"Error: The file at {draft_content_path} is not a valid JSON file.")
sys.exit(1)
except Exception as e:
print(f"An error occurred while reading the file: {e}")
sys.exit(1)
# Extract script data directly with text content
script = extract_script(cont)
print(f"Found {len(script)} captions...")
if not script:
print("Error: No captions were found in the project.")
sys.exit(1)
# Create subtitles list
subtitles = [((start, end), text) for start, end, text in script]
# Common code from here - load video and create captions
try:
print("Loading video file...")
video = VideoFileClip(video_path)
print(f"Video loaded: {video.w}x{video.h}, {video.duration:.2f} seconds")
except Exception as e:
print(f"Error loading video file: {e}")
if use_vosk and os.path.exists(audio_path):
os.remove(audio_path)
sys.exit(1)
# Create subtitles clip with proper error handling
if not subtitles:
print("Error: No subtitles were processed.")
if use_vosk and os.path.exists(audio_path):
os.remove(audio_path)
sys.exit(1)
print("Creating subtitles...")
subs = SubtitlesClip(subtitles, make_textclip)
# Set output file path
current_dir = os.path.dirname(os.path.abspath(__file__))
output_path = os.path.join(current_dir, f"{name}_with_captions.mp4")
print(f"Compositing video... This may take a while.")
print(f"The video will be saved in: {current_dir}")
# Composite video with subtitles
final_video = CompositeVideoClip([video, subs])
# Set encoding parameters - Fixed for better compatibility
print("Encoding video...")
try:
final_video.write_videofile(
output_path,
fps=video.fps,
codec='libx264',
audio_codec='aac',
audio=True,
threads=4, # Reduced for stability
preset='medium', # Balance of speed and quality
logger=None # Reduces console output
)
except Exception as e:
print(f"Error during encoding: {e}")
print("Trying with alternative encoding settings...")
# Try with even more basic settings if the first attempt fails
final_video.write_videofile(
output_path,
fps=video.fps,
codec='libx264',
audio=False, # Disable audio for troubleshooting
threads=1, # Single thread
preset='ultrafast' # Fastest preset
)
# Clean up temporary files
if use_vosk and os.path.exists(audio_path):
try:
os.remove(audio_path)
print(f"Removed temporary audio file: {audio_path}")
except:
pass
# Calculate and display total processing time
elapsed_time = time.time() - start_time
print(f"Processing completed in {elapsed_time:.2f} seconds ({elapsed_time/60:.2f} minutes)")
print(f"Video with captions has been generated as '{os.path.basename(output_path)}'")
print(f"You can find the video at: {output_path}")
# Open the folder containing the video
try:
os.startfile(current_dir)
except:
pass # Ignore error if can't open folder
Key Changes Anticipating Progress:
frames_processed: Add to frames_processed by calculating the number of frames read based on the data size (len(data) // 2, since each sample is represented by 2 bytes).
Progress Calculation: Calculate the progress as a percentage by dividing frames_processed by total_frames and multiply by 100.
Print Output: Update the output format to include two decimal points for clarity.
Integration
You can simply replace your existing transcribe_audio function in your code with the modified one above. This update will now give you a visual signal of how much of the audio has been processed through % output in the command line interface.
It will dynamically show the transcription progress.
Keep in mind that this method assumes that you process the audio in chunks of 4000 frames. You can adjust the chunk size if needed but ensure consistency across the calculation of frames processed to avoid any misleading progress percentages.
Notes:
Message Filtering: The write method checks if "frame" is in the message, which may indicate the current frame being processed. You can modify the condition based on the log messages you observe to get more specific updates.
Compilation: Ensure that logging or print statements do not clutter your console output. You can adjust what information to log based on your needs.
Real-time Updates: Keep in mind that responses from MoviePy might not be real-time updates, and the frequency may depend on the frame rate of the video and the complexity of the task.
Limitations:
MoviePy does not offer precise encoding progress logs directly. The logs may vary based on the configuration or optimization done during the video write process.
You may choose to further refine how you extract and display progress data from the logger based on the message contents.
By following this approach, you can have a rudimentary system to track the encoding progress and provide feedback during the video processing phase.
Key Changes Explained:
Counting Words:
The variable total_words tracks the cumulative count of recognized words.
Progress Calculation:
Progress is calculated by comparing the total number of recognized words to an estimated total. The estimate here is based on the total number of frames divided by the frame rate (for example, assuming a sample rate of 16 kHz, we divide by 16000 to approximate how many seconds of audio are being processed for a rough word estimate).
Displaying Progress:
Updates the progress after every recognized word (via PartialResult). This gives you more responsive updates during transcription.
Notes:
Make sure your audio is in the appropriate format (16 kHz mono PCM).
The logic assumes that the audio is reasonably long enough so that you can estimate total words based on total frames. You may need to adjust it according to your actual data.
This implementation gives you a real-time update on how many words have been processed, significantly enhancing the user experience.
This approach allows you to provide a more granular view of progress as each word is recognized, making it clearer how transcription is progressing.
if rec.AcceptWaveform(data):
part_result = json.loads(rec.Result())
if 'result' in part_result:
# Track recognized words
total_words += len(part_result['result'])
# Update progress
progress = (total_words / estimated_total_words) * 100
print(f'Transcription progress: {progress:.2f}%')
If you want to provide a smoother user experience while encoding video files, using the logging output effectively or providing an animated loading indicator can help reassure users that processing is ongoing despite the lack of granular feedback. For transcription with Vosk, showing the number of words processed in real time can significantly enhance user experience.
from moviepy.editor import VideoFileClip, CompositeVideoClip, ImageClip
# Other imports as necessary for your project ...
class CustomLogger:
def write(self, message):
if "frame" in message:
print(message, end='') # Print out frame processing messages
def flush(self):
pass # Not needed for this example
# Main execution starts here
if __name__ == "__main__":
# Your previous code ...
video_path = "path/to/your/video.mp4" # Replace with actual video path
output_path = "path/to/output/video_with_captions.mp4" # Replace with output path
# Load video file and create subtitles
video = VideoFileClip(video_path)
# Create a custom logger instance
custom_logger = CustomLogger()
# Compositing video with subtitles, your `subtitles` should be created prior to this
final_video = CompositeVideoClip([video, subs])
print("Encoding video... This may take a while...")
# Encode video with the custom logger to track progress
try:
final_video.write_videofile(
output_path,
fps=video.fps,
codec='libx264',
audio_codec='aac',
audio=True,
threads=4,
preset='medium',
logger=custom_logger # Use the custom logger to track progress
)
print("\nVideo encoding complete.")
except Exception as e:
print(f"Error during encoding: {e}")
How It Works
Custom Logger: The CustomLogger class defines a method write that checks for messages containing the word "frame". When such messages are printed, it indicates that a certain frame of the video is being processed.
Integrating the Logger: When calling write_videofile(), you pass in your custom_logger. It will print messages related to the frame processing, thus giving you an overview of the encoding progress.
Additional Output: You might choose to further enhance the write method to parse specific information if you want more detailed insights, such as showing how many frames have been processed versus the total number of frames.
Limitations
The level of detail provided depends on the messages emitted by MoviePy during the encoding process. You might not receive more granular percentages or interactive progress indicators without more advanced integration, but this approach should give you better feedback compared to not having any logger at all.
By incorporating this solution into your video creation workflow, you can provide end-users with a better understanding of the video encoding process and how long it might take.
model_path = os.path.join(models_dir, model_name)
# Check for pre-downloaded model in current directory
if os.path.exists(model_name) and os.path.isdir(model_name):
print(f"Using pre-downloaded model found at {model_name}")
return os.path.abspath(model_name)
# Check for model in models directory
if os.path.exists(model_path):
print(f"Using cached model found at {model_path}")
return model_path
# Let user manually specify model location
print("\nModel not found in the default location.")
print("Options:")
print("1. Download the model (several hundred MB, may take a while)")
print("2. Specify path to pre-downloaded model")
choice = input("Enter your choice (1 or 2): ")
if choice == "2":
# Use Tkinter to browse for the model folder
root = Tk()
root.withdraw()
custom_model_path = filedialog.askdirectory(title="Select the Vosk model directory")
if custom_model_path:
print(f"Using custom model path: {custom_model_path}")
return custom_model_path
else:
print("No model directory selected, falling back to download.")
# Download the model with progress reporting
print(f"Downloading Vosk model {model_name}...")
zip_path = os.path.join(models_dir, f"{model_name}.zip")
# Create a custom reporthook to show download progress
def download_progress(count, block_size, total_size):
percent = min(100, count * block_size * 100 // total_size)
sys.stdout.write(f"\rDownload progress: {percent}% ({count * block_size // 1024 // 1024} MB / {total_size // 1024 // 1024} MB)")
sys.stdout.flush()
try:
# Download the model
url = f"https://alphacephei.com/vosk/models/{model_name}.zip"
urllib.request.urlretrieve(url, zip_path, download_progress)
print("\nDownload complete, extracting model...")
# Extract the model
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(models_dir)
# Clean up zip file
os.remove(zip_path)
print(f"Model extracted to {model_path}")
return model_path
except Exception as e:
print(f"\nError downloading or extracting model: {e}")
if os.path.exists(zip_path):
os.remove(zip_path)
# Fallback to manual download instructions
print("\nPlease download the model manually:")
print(f"1. Go to https://alphacephei.com/vosk/models")
print(f"2. Download {model_name}.zip")
print(f"3. Extract it to the 'models' folder in {os.path.dirname(os.path.abspath(__file__))}")
print(f"4. Run this script again")
sys.exit(1)
def extract_audio(video_path, audio_path):
"""Extract audio from video using ffmpeg"""
if os.path.exists(audio_path):
os.remove(audio_path)
print("Removed existing audio file")
code
if not os.path.exists(video_path):
raise FileNotFoundError(f"Video file not found: {video_path}")
command = [
"ffmpeg",
"-i", video_path,
"-acodec", "pcm_s16le",
"-ac", "1",
"-ar", "16000",
audio_path
]
subprocess.run(command, check=True)
print("Audio extracted successfully")
def transcribe_audio(audio_path, model_path):
"""Transcribe audio using Vosk model and return word timings"""
if not os.path.exists(audio_path):
raise FileNotFoundError(f"Audio file not found: {audio_path}")
code
SetLogLevel(0)
wf = wave.open(audio_path, "rb")
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
print("Audio file must be WAV format mono PCM.")
return []
model = Model(model_path)
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True)
results = []
total_frames = wf.getnframes()
frames_processed = 0
print("Starting transcription...")
while True:
data = wf.readframes(4000)
frames_processed += 4000
if len(data) == 0:
break
if rec.AcceptWaveform(data):
part_result = json.loads(rec.Result())
if 'result' in part_result:
results.append(part_result)
# Show progress percentage
progress = min(100, (frames_processed * 100) // total_frames)
sys.stdout.write(f"\rTranscription progress: {progress}%")
sys.stdout.flush()
part_result = json.loads(rec.FinalResult())
if 'result' in part_result:
results.append(part_result)
print("\nTranscription complete.")
return results
for res in results:
if 'result' not in res:
continue
for word in res['result']:
total_words += 1
if current_start is None:
current_start = word['start']
current_text.append(word['word'])
char_count += len(word['word']) + 1 # +1 for space
# Create a new subtitle when reaching max chars or after a natural pause
if char_count >= max_chars or (len(current_text) > 1 and word.get('word', '').endswith(('.', '!', '?'))):
text = ' '.join(current_text)
end_time = word['end']
# Don't create super short clips
if end_time - current_start >= 0.3:
subtitles.append(((current_start, end_time), text))
current_text = []
current_start = None
char_count = 0
# Add any remaining text
if current_text and current_start is not None and len(results) > 0 and 'result' in results[-1]:
last_results = results[-1]['result']
if last_results:
last_word = last_results[-1]
subtitles.append(((current_start, last_word['end']), ' '.join(current_text)))
print(f"Generated {len(subtitles)} caption segments from {total_words} words")
return subtitles
def get_project_details(folder_path):
"""Get details from a CapCut project folder"""
meta_file = os.path.join(folder_path, "draft_meta.json")
if os.path.exists(meta_file):
with open(meta_file, 'r', encoding='utf-8') as f:
meta_data = json.load(f)
project_name = meta_data.get("name", "Unnamed Project")
created_time = meta_data.get("created_time", 0) / 1000 # Convert milliseconds to seconds
created_date = datetime.fromtimestamp(created_time).strftime('%Y-%m-%d %H:%M:%S')
return f"{project_name} (Created: {created_date})"
return "Unknown Project"
def extract_script(content):
"""Extract caption script from CapCut project"""
script = []
# Create a material_id to text mapping for faster lookups
materials_dict = {}
if "materials" in content and "texts" in content["materials"]:
for material in content["materials"]["texts"]:
try:
material_content = json.loads(material["content"])
materials_dict[material["id"]] = material_content["text"].replace("\n", " ")
except Exception:
continue
code
for track in content.get("tracks", []):
if track.get("type") == "text":
for segment in track.get("segments", []):
try:
start = segment["target_timerange"]["start"] / 1000000 # Convert to seconds
duration = segment["target_timerange"]["duration"] / 1000000
end = start + duration
material_id = segment["material_id"]
if material_id in materials_dict:
script.append((start, end, materials_dict[material_id]))
except KeyError:
continue
return sorted(script, key=lambda x: x[0])
def create_text_clip(text, video_width, video_height, font_size=60, font_color=(0, 0, 0),
bg_color=(0, 0, 0, 0), outline_color=(0, 0, 0)):
"""Create a text clip with the specified formatting"""
# Use cached clip if available
cache_key = f"{text}{video_width}{video_height}_{font_size}"
if cache_key in text_clip_cache:
return text_clip_cache[cache_key]
code
# Make the text area narrower to enforce wrapping
max_width = int(video_width * 0.4) # Reduced from 0.75 to make text wrap more
max_height = int(video_height * 0.95)
# Try to use the custom font, fall back to system font if not available
font_path = r"C:\Users\buggy\AppData\Local\Microsoft\Windows\Fonts\BowlbyOneSC-Regular.ttf"
try:
font = ImageFont.truetype(font_path, font_size)
except OSError:
print("BowlbyOneSC-Regular font not found. Falling back to Arial.")
font_path = r"C:\Windows\Fonts\Arial.ttf"
font = ImageFont.truetype(font_path, font_size)
words = text.split()
lines = []
current_line = []
current_width = 0
# Better word wrapping for shorter lines
for word in words:
word_bbox = font.getbbox(word + " ")
word_width = word_bbox[2] - word_bbox[0]
if current_width + word_width <= max_width:
current_line.append(word)
current_width += word_width
else:
lines.append(current_line)
current_line = [word]
current_width = word_width
if current_line:
lines.append(current_line)
line_bbox = font.getbbox("A")
line_height = (line_bbox[3] - line_bbox[1]) * 1.2 # Add 20% line spacing
total_text_height = int(line_height * len(lines))
img = Image.new('RGBA', (max_width, max_height), bg_color)
draw = ImageDraw.Draw(img)
# Start text higher up in the image (closer to top)
y_offset = (max_height - total_text_height) // 3 # Changed from //2 to //3 to move up
y = y_offset
# Flatten the lines to get total word count
all_words = [word for line in lines for word in line]
total_words = len(all_words)
word_index = 0
for line in lines:
# Left-align text instead of centering each line
x = 20 # Fixed left margin
for word in line:
if word_index >= total_words - 3: # Color the last three words regardless of line
word_color = [(255, 0, 0), (255, 255, 0), (0, 0, 255)][word_index - (total_words - 3)]
else:
word_color = font_color
# Draw outline
for offset in [(1,1), (-1,1), (1,-1), (-1,-1)]:
draw.text((x + offset[0], y + offset[1]), word + " ", font=font, fill=outline_color)
# Draw main text
draw.text((x, y), word + " ", font=font, fill=word_color)
word_bbox = font.getbbox(word + " ")
x += word_bbox[2] - word_bbox[0]
word_index += 1
y += line_height
clip = ImageClip(np.array(img))
text_clip_cache[cache_key] = clip
return clip
def make_textclip(txt):
"""Create a text clip with proper positioning"""
clip = create_text_clip(txt, video.w, video.h, outline_color=(0, 0, 0)) # Black outline
# Position fixed at left side, 40% of the height from top
y_position = int(video.h * 0.4) # Calculate actual pixel position
return clip.set_position((80, y_position))
Main execution starts here
if name == "main":
# Add command line argument support
parser = argparse.ArgumentParser(description='Add captions to video using CapCut data or Vosk speech recognition.')
parser.add_argument('--video', type=str, help='Path to input video file (optional)')
parser.add_argument('--source', type=str, choices=['capcut', 'vosk'],
help='Source for captions: "capcut" or "vosk" (optional)')
parser.add_argument('--model', type=str, default="vosk-model-small-en-us-0.15",
help='Vosk model name to use (default: vosk-model-small-en-us-0.15)')
args = parser.parse_args()
code
start_time = time.time()
# Determine caption source - Command line or interactive
use_vosk = False
if args.source:
# Use command-line specified source
use_vosk = args.source.lower() == 'vosk'
else:
# Ask interactively if not specified
print("Choose caption source:")
print("1. Extract from CapCut project")
print("2. Generate from speech using Vosk")
while True:
try:
source_choice = int(input("Enter your choice (1 or 2): "))
if source_choice == 1:
use_vosk = False
break
elif source_choice == 2:
if not VOSK_AVAILABLE:
print("Vosk is not installed. Please run 'pip install vosk' first.")
print("Falling back to CapCut extraction.")
use_vosk = False
else:
use_vosk = True
break
else:
print("Invalid choice. Please enter 1 or 2.")
except ValueError:
print("Please enter a number.")
# Get the video path - Command line or interactive
video_path = args.video
if not video_path:
root = Tk()
root.withdraw()
video_path = filedialog.askopenfilename(title="Select the video file",
filetypes=[("Video files", "*.mp4 *.avi *.mov *.wmv")])
if not video_path:
print("No video file selected. Exiting.")
sys.exit(1)
if not os.path.exists(video_path):
print(f"Error: Video file not found at {video_path}")
sys.exit(1)
# Use absolute path
video_path = os.path.abspath(video_path)
# Path for selecting or creating captions
if use_vosk:
print("Using Vosk speech recognition for captioning")
# Use the specified or default Vosk model
model_name = args.model
print(f"Using Vosk model: {model_name}")
# Download or use cached model
try:
model_path = download_vosk_model(model_name)
except Exception as e:
print(f"Error downloading model: {e}")
sys.exit(1)
# Extract audio to WAV format
current_dir = os.path.dirname(os.path.abspath(__file__))
audio_path = os.path.join(current_dir, "temp_audio.wav")
try:
extract_audio(video_path, audio_path)
# Perform speech recognition
results = transcribe_audio(audio_path, model_path)
# Convert to subtitles format
subtitles = vosk_to_subtitles(results)
# Create output filename
video_basename = os.path.basename(video_path)
name = os.path.splitext(video_basename)[0].lower().replace(" ", "_")
except Exception as e:
print(f"Error processing audio: {e}")
if os.path.exists(audio_path):
os.remove(audio_path)
sys.exit(1)
else:
print("Using CapCut project for captioning")
# List all project folders
project_folders = [f for f in os.listdir(base_path) if os.path.isdir(os.path.join(base_path, f)) and f != ".recycle_bin"]
if not project_folders:
print("No project folders found.")
sys.exit(1)
print("Available projects:")
for i, folder in enumerate(project_folders):
folder_path = os.path.join(base_path, folder)
project_details = get_project_details(folder_path)
print(f"{i + 1}. {folder} - {project_details}")
# Ask user to select a project
while True:
try:
choice = int(input("Enter the number of the project you want to process: ")) - 1
if 0 <= choice < len(project_folders):
selected_folder = project_folders[choice]
break
else:
print("Invalid choice. Please try again.")
except ValueError:
print("Please enter a number.")
folder = os.path.join(base_path, selected_folder)
draft_content_path = os.path.join(folder, "draft_content.json")
if not os.path.exists(draft_content_path):
print(f"Error: draft_content.json not found in {folder}")
sys.exit(1)
name = selected_folder.lower().replace(" ", "_")
# Load project file
try:
with open(draft_content_path, encoding="utf-8") as f:
cont = json.load(f)
except json.JSONDecodeError:
print(f"Error: The file at {draft_content_path} is not a valid JSON file.")
sys.exit(1)
except Exception as e:
print(f"An error occurred while reading the file: {e}")
sys.exit(1)
# Extract script data directly with text content
script = extract_script(cont)
print(f"Found {len(script)} captions...")
if not script:
print("Error: No captions were found in the project.")
sys.exit(1)
# Create subtitles list
subtitles = [((start, end), text) for start, end, text in script]
# Common code from here - load video and create captions
try:
print("Loading video file...")
video = VideoFileClip(video_path)
print(f"Video loaded: {video.w}x{video.h}, {video.duration:.2f} seconds")
except Exception as e:
print(f"Error loading video file: {e}")
if use_vosk and os.path.exists(audio_path):
os.remove(audio_path)
sys.exit(1)
# Create subtitles clip with proper error handling
if not subtitles:
print("Error: No subtitles were processed.")
if use_vosk and os.path.exists(audio_path):
os.remove(audio_path)
sys.exit(1)
print("Creating subtitles...")
subs = SubtitlesClip(subtitles, make_textclip)
# Set output file path
current_dir = os.path.dirname(os.path.abspath(__file__))
output_path = os.path.join(current_dir, f"{name}_with_captions.mp4")
print(f"Compositing video... This may take a while.")
print(f"The video will be saved in: {current_dir}")
# Composite video with subtitles
final_video = CompositeVideoClip([video, subs])
# Set encoding parameters - Fixed for better compatibility
print("Encoding video...")
try:
final_video.write_videofile(
output_path,
fps=video.fps,
codec='libx264',
audio_codec='aac',
audio=True,
threads=4, # Reduced for stability
preset='medium', # Balance of speed and quality
logger=None # Reduces console output
)
except Exception as e:
print(f"Error during encoding: {e}")
print("Trying with alternative encoding settings...")
# Try with even more basic settings if the first attempt fails
final_video.write_videofile(
output_path,
fps=video.fps,
codec='libx264',
audio=False, # Disable audio for troubleshooting
threads=1, # Single thread
preset='ultrafast' # Fastest preset
)
# Clean up temporary files
if use_vosk and os.path.exists(audio_path):
try:
os.remove(audio_path)
print(f"Removed temporary audio file: {audio_path}")
except:
pass
# Calculate and display total processing time
elapsed_time = time.time() - start_time
print(f"Processing completed in {elapsed_time:.2f} seconds ({elapsed_time/60:.2f} minutes)")
print(f"Video with captions has been generated as '{os.path.basename(output_path)}'")
print(f"You can find the video at: {output_path}")
# Open the folder containing the video
try:
os.startfile(current_dir)
except:
pass # Ignore error if can't open folder
import json
import os
import sys
import wave
import urllib.request
import zipfile
import subprocess
import time
import logging
from moviepy.editor import *
from moviepy.video.tools.subtitles import SubtitlesClip
from PIL import Image, ImageDraw, ImageFont
import numpy as np
from tkinter import Tk, filedialog
from datetime import datetime
import argparse
try:
import win32api
WIN32_AVAILABLE = True
except ImportError:
WIN32_AVAILABLE = False
# Import Vosk for speech recognition
try:
from vosk import Model, KaldiRecognizer, SetLogLevel
VOSK_AVAILABLE = True
except ImportError:
VOSK_AVAILABLE = False
print("Vosk not installed. Run 'pip install vosk' to enable automatic speech recognition.")
# Configure MoviePy to show progress
import moviepy.config as conf
conf.PROGRESS_BAR = True
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
# Specify the base path to your CapCut projects
base_path = r"C:\Users\buggy\AppData\Local\CapCut\User Data\Projects\com.lveditor.draft"
# Cache for text clips to avoid recreating the same text multiple times
text_clip_cache = {}
class CustomLogger:
"""Custom logger to track video encoding progress."""
def write(self, message):
if "frame" in message:
print(message, end='') # Print out processing frame messages
def flush(self):
pass # No implementation needed for flush
# ... (The rest of your utility functions remain unchanged)
def extract_audio(video_path, audio_path):
"""Extract audio from video using ffmpeg"""
if os.path.exists(audio_path):
os.remove(audio_path)
print("Removed existing audio file")
if not os.path.exists(video_path):
raise FileNotFoundError(f"Video file not found: {video_path}")
command = [
"ffmpeg",
"-i", video_path,
"-acodec", "pcm_s16le",
"-ac", "1",
"-ar", "16000",
audio_path
]
subprocess.run(command, check=True)
print("Audio extracted successfully")
def transcribe_audio(audio_path, model_path):
"""Transcribe audio using Vosk model and return word timings"""
if not os.path.exists(audio_path):
raise FileNotFoundError(f"Audio file not found: {audio_path}")
SetLogLevel(0)
wf = wave.open(audio_path, "rb")
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
print("Audio file must be WAV format mono PCM.")
return []
model = Model(model_path)
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True)
results = []
total_frames = wf.getnframes()
frames_processed = 0
print("Starting transcription...")
while True:
data = wf.readframes(4000)
frames_processed += 4000
if len(data) == 0:
break
if rec.AcceptWaveform(data):
part_result = json.loads(rec.Result())
if 'result' in part_result:
results.append(part_result)
# Show progress percentage
progress = min(100, (frames_processed * 100) // total_frames)
sys.stdout.write(f"\rTranscription progress: {progress}%")
sys.stdout.flush()
part_result = json.loads(rec.FinalResult())
if 'result' in part_result:
results.append(part_result)
print("\nTranscription complete.")
return results
# ... (Other functions remain unchanged)
# Main execution starts here
if __name__ == "__main__":
# Add command line argument support
parser = argparse.ArgumentParser(description='Add captions to video using CapCut data or Vosk speech recognition.')
parser.add_argument('--video', type=str, help='Path to input video file (optional)')
parser.add_argument('--source', type=str, choices=['capcut', 'vosk'],
help='Source for captions: "capcut" or "vosk" (optional)')
parser.add_argument('--model', type=str, default="vosk-model-small-en-us-0.15",
help='Vosk model name to use (default: vosk-model-small-en-us-0.15)')
args = parser.parse_args()
start_time = time.time()
# Determine caption source - Command line or interactive
use_vosk = False
if args.source:
# Use command-line specified source
use_vosk = args.source.lower() == 'vosk'
else:
# Ask interactively if not specified
print("Choose caption source:")
print("1. Extract from CapCut project")
print("2. Generate from speech using Vosk")
while True:
try:
source_choice = int(input("Enter your choice (1 or 2): "))
if source_choice == 1:
use_vosk = False
break
elif source_choice == 2:
if not VOSK_AVAILABLE:
print("Vosk is not installed. Please run 'pip install vosk' first.")
print("Falling back to CapCut extraction.")
use_vosk = False
else:
use_vosk = True
break
else:
print("Invalid choice. Please enter 1 or 2.")
except ValueError:
print("Please enter a number.")
# Get the video path - Command line or interactive
video_path = args.video
if not video_path:
root = Tk()
root.withdraw()
video_path = filedialog.askopenfilename(title="Select the video file",
filetypes=[("Video files", "*.mp4 *.avi *.mov *.wmv")])
if not video_path:
print("No video file selected. Exiting.")
sys.exit(1)
if not os.path.exists(video_path):
print(f"Error: Video file not found at {video_path}")
sys.exit(1)
# Use absolute path
video_path = os.path.abspath(video_path)
# Path for selecting or creating captions
if use_vosk:
print("Using Vosk speech recognition for captioning")
# Use the specified or default Vosk model
model_name = args.model
print(f"Using Vosk model: {model_name}")
# Download or use cached model
try:
model_path = download_vosk_model(model_name)
except Exception as e:
print(f"Error downloading model: {e}")
sys.exit(1)
# Extract audio to WAV format
current_dir = os.path.dirname(os.path.abspath(__file__))
audio_path = os.path.join(current_dir, "temp_audio.wav")
try:
extract_audio(video_path, audio_path)
# Perform speech recognition
results = transcribe_audio(audio_path, model_path)
# Convert to subtitles format
subtitles = vosk_to_subtitles(results)
# Create output filename
video_basename = os.path.basename(video_path)
name = os.path.splitext(video_basename)[0].lower().replace(" ", "_")
except Exception as e:
print(f"Error processing audio: {e}")
if os.path.exists(audio_path):
os.remove(audio_path)
sys.exit(1)
else:
print("Using CapCut project for captioning")
# List all project folders
project_folders = [f for f in os.listdir(base_path) if os.path.isdir(os.path.join(base_path, f)) and f != ".recycle_bin"]
if not project_folders:
print("No project folders found.")
sys.exit(1)
print("Available projects:")
for i, folder in enumerate(project_folders):
folder_path = os.path.join(base_path, folder)
project_details = get_project_details(folder_path)
print(f"{i + 1}. {folder} - {project_details}")
# Ask user to select a project
while True:
try:
choice = int(input("Enter the number of the project you want to process: ")) - 1
if 0 <= choice < len(project_folders):
selected_folder = project_folders[choice]
break
else:
print("Invalid choice. Please try again.")
except ValueError:
print("Please enter a number.")
folder = os.path.join(base_path, selected_folder)
draft_content_path = os.path.join(folder, "draft_content.json")
if not os.path.exists(draft_content_path):
print(f"Error: draft_content.json not found in {folder}")
sys.exit(1)
name = selected_folder.lower().replace(" ", "_")
# Load project file
try:
with open(draft_content_path, encoding="utf-8") as f:
cont = json.load(f)
except json.JSONDecodeError:
print(f"Error: The file at {draft_content_path} is not a valid JSON file.")
sys.exit(1)
except Exception as e:
print(f"An error occurred while reading the file: {e}")
sys.exit(1)
# Extract script data directly with text content
script = extract_script(cont)
print(f"Found {len(script)} captions...")
if not script:
print("Error: No captions were found in the project.")
sys.exit(1)
# Create subtitles list
subtitles = [((start, end), text) for start, end, text in script]
# Common code from here - load video and create captions
try:
print("Loading video file...")
video = VideoFileClip(video_path)
print(f"Video loaded: {video.w}x{video.h}, {video.duration:.2f} seconds")
except Exception as e:
print(f"Error loading video file: {e}")
if use_vosk and os.path.exists(audio_path):
os.remove(audio_path)
sys.exit(1)
# Create subtitles clip with proper error handling
if not subtitles:
print("Error: No subtitles were processed.")
if use_vosk and os.path.exists(audio_path):
os.remove(audio_path)
sys.exit(1)
print("Creating subtitles...")
subs = SubtitlesClip(subtitles, make_textclip)
# Set output file path
current_dir = os.path.dirname(os.path.abspath(__file__))
output_path = os.path.join(current_dir, f"{name}_with_captions.mp4")
print(f"Compositing video... This may take a while.")
print(f"The video will be saved in: {current_dir}")
# Composite video with subtitles
final_video = CompositeVideoClip([video, subs])
# Set encoding parameters - Fixed for better compatibility
print("Encoding video...")
custom_logger = CustomLogger() # Create the custom logger instance
try:
final_video.write_videofile(
output_path,
fps=video.fps,
codec='libx264',
audio_codec='aac',
audio=True,
threads=4, # Reduced for stability
preset='medium', # Balance of speed and quality
logger=custom_logger # Use the custom logger to track progress
)
except Exception as e:
print(f"Error during encoding: {e}")
print("Trying with alternative encoding settings...")
# Try with even more basic settings if the first attempt fails
final_video.write_videofile(
output_path,
fps=video.fps,
codec='libx264',
audio=False, # Disable audio for troubleshooting
threads=1, # Single thread
preset='ultrafast' # Fastest preset
)
# Clean up temporary files
if use_vosk and os.path.exists(audio_path):
try:
os.remove(audio_path)
print(f"Removed temporary audio file: {audio_path}")
except:
pass
# Calculate and display total processing time
elapsed_time = time.time() - start_time
print(f"Processing completed in {elapsed_time:.2f} seconds ({elapsed_time/60:.2f} minutes)")
print(f"Video with captions has been generated as '{os.path.basename(output_path)}'")
print(f"You can find the video at: {output_path}")
# Open the folder containing the video
try:
os.startfile(current_dir)
except:
pass # Ignore error if can't open folder
Summary of Modifications:
Custom Logger Class: A CustomLogger class is defined. This logger will look for messages that contain "frame," indicating the processing of frames during encoding, and print these messages to give feedback on progress.
Using the Logger: The final_video.write_videofile() call now passes in the instance of CustomLogger, which allows you to track how many frames have been processed and provides a running update during video encoding.
Integration: The CustomLogger is integrated into the main execution flow, ensuring that you get encoding updates without changing the core functionality of your existing script.
With this implementation, you should now have a clearer sense of progress during the video creation process, enhancing user experience and providing feedback in real time.
create_text_clip
python
def create_text_clip(text, video_width, video_height, font_size=60, font_color=(0, 0, 0),
bg_color=(0, 0, 0, 0), outline_color=(0, 0, 0), outline_thickness=3):
"""Create a text clip with the specified formatting"""
# Use cached clip if available
cache_key = f"{text}_{video_width}_{video_height}_{font_size}"
if cache_key in text_clip_cache:
return text_clip_cache[cache_key]
max_width = int(video_width * 0.4) # Maximum width for the text area
max_height = int(video_height * 0.95)
# Try to use the custom font, fallback to system font if not available
font_path = r"C:\Users\buggy\AppData\Local\Microsoft\Windows\Fonts\BowlbyOneSC-Regular.ttf"
try:
font = ImageFont.truetype(font_path, font_size)
except OSError:
font_path = r"C:\Windows\Fonts\Arial.ttf"
font = ImageFont.truetype(font_path, font_size)
words = text.split()
lines = []
current_line = []
current_width = 0
for word in words:
word_bbox = font.getbbox(word + " ")
word_width = word_bbox[2] - word_bbox[0]
if current_width + word_width <= max_width:
current_line.append(word)
current_width += word_width
else:
lines.append(current_line)
current_line = [word]
current_width = word_width
if current_line:
lines.append(current_line)
line_bbox = font.getbbox("A")
line_height = (line_bbox[3] - line_bbox[1]) * 1.2
total_text_height = int(line_height * len(lines))
img = Image.new('RGBA', (max_width, max_height), bg_color)
draw = ImageDraw.Draw(img)
y_offset = (max_height - total_text_height) // 3
y = y_offset
for line in lines:
x = 20 # Fixed left margin
for word in line:
# Draw a thicker outline
for x_offset in range(-outline_thickness, outline_thickness + 1):
for y_offset in range(-outline_thickness, outline_thickness + 1):
if abs(x_offset) + abs(y_offset) < outline_thickness:
draw.text((x + x_offset, y + y_offset), word + " ", font=font, fill=outline_color)
# Draw main text
draw.text((x, y), word + " ", font=font, fill=font_color)
word_bbox = font.getbbox(word + " ")
x += word_bbox[2] - word_bbox[0]
y += line_height
clip = ImageClip(np.array(img))
text_clip_cache[cache_key] = clip
return clip
Notes:
outline_thickness Parameter: It is passed as an argument to create_text_clip, allowing you to easily modify the thickness of the text outline.
Outline Condition: The abs(x_offset) + abs(y_offset) < outline_thickness condition controls whether to draw the outline for the specified thickness.
You can play around with the outline_thickness value to achieve the desired border thickness for your text.
def create_text_clip(text, video_width, video_height, font_size=60, font_color=(255, 255, 255),
bg_color=(0, 0, 0, 0), outline_color=(0, 0, 0), outline_thickness=2):
"""Create a text clip with the specified formatting"""
# Use cached clip if available
cache_key = f"{text}_{video_width}_{video_height}_{font_size}"
if cache_key in text_clip_cache:
return text_clip_cache[cache_key]
# Make the text area narrower to enforce wrapping
max_width = int(video_width * 0.4) # Reduced from 0.75 to make text wrap more
max_height = int(video_height * 0.95)
# Font loading logic...
# Your existing font loading code goes here
words = text.split()
lines = []
current_line = []
current_width = 0
# Word wrapping logic...
# Your existing word wrapping code goes here
line_bbox = font.getbbox("A")
line_height = (line_bbox[3] - line_bbox[1]) * 1.2 # Add 20% line spacing
total_text_height = int(line_height * len(lines))
img = Image.new('RGBA', (max_width, max_height), bg_color)
draw = ImageDraw.Draw(img)
y_offset = (max_height - total_text_height) // 3 # Changed from //2 to //3 to move up
y = y_offset
for line in lines:
# Left-align text instead of centering each line
x = 20 # Fixed left margin
for word in line:
# Draw outline with specified thickness
for x_offset in range(-outline_thickness, outline_thickness + 1):
for y_offset in range(-outline_thickness, outline_thickness + 1):
# Only draw in the bounding box defined by outline_thickness
if abs(x_offset) + abs(y_offset) < outline_thickness:
draw.text((x + x_offset, y + y_offset), word + " ", font=font, fill=outline_color)
# Draw main text
draw.text((x, y), word + " ", font=font, fill=font_color)
word_bbox = font.getbbox(word + " ")
x += word_bbox[2] - word_bbox[0]
y += line_height
clip = ImageClip(np.array(img))
text_clip_cache[cache_key] = clip
return clip
Adjustments Explained:
Outline Thickness Parameter: The outline_thickness parameter allows users to set how thick the outline should be. This is passed to the function when you call it.
Modified Drawing Logic: I've updated the logic for drawing the outline so that it checks if the combined offsets of x_offset and y_offset (using abs()) fall within the specified outline_thickness. This creates outlines that can be thicker based on the value provided.
Usage Example
You would call the create_text_clip function and specify the desired outline thickness:
python
clip = create_text_clip("Your text here", video_width, video_height, outline_thickness=3) # Adjust as needed
By incorporating these changes, you can effectively control the thickness of the text border in your video captions or overlays while utilizing the existing structure of your code.