if not os.path.exists(model_path):
logging.info(f"Downloading Vosk model {model_name}...")
zip_path, _ = urllib.request.urlretrieve(model_url)
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(os.path.dirname(__file__))
os.remove(zip_path)
logging.info("Model downloaded and extracted.")
return model_path
def transcribe_audio(audio_path, model_path):
SetLogLevel(0)
wf = wave.open(audio_path, "rb")
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
logging.error("Audio file must be WAV format mono PCM.")
return []
code
Assistant
The code you provided does indeed include functionality for handling individual word timings in the transcription process for generating captions. The function is responsible for processing the audio file and obtaining word timings, enabling the generation of captions for each word.
User
what part exactly tracks each word?
Assistant
User
Assistant
model = Model(model_path)
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True)
results = []
while True:
data = wf.readframes(4000)
if len(data) == 0:
break
if rec.AcceptWaveform(data):
part_result = json.loads(rec.Result())
results.append(part_result)
part_result = json.loads(rec.FinalResult())
results.append(part_result)
words = []
for r in results:
if 'result' in r:
words.extend(r['result'])
logging.info(f"Transcribed {len(words)} words")
return words
def create_text_image(text, size, font_size, color, font_path, bg_color=(0, 0, 0, 0), border_size=15):
# Increase the size of the image to accommodate the border
increased_size = (size[0] + border_size * 2, size[1] + border_size * 2 + font_size // 2)
img = Image.new('RGBA', increased_size, bg_color)
draw = ImageDraw.Draw(img)
code
# Load the main font
font = ImageFont.truetype(font_path, font_size)
# Calculate text position
text_bbox = font.getbbox(text)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
position = ((increased_size[0] - text_width) // 2, (increased_size[1] - text_height) // 2)
# Draw border
for x_offset in range(-border_size, border_size + 1):
for y_offset in range(-border_size, border_size + 1):
draw.text((position[0] + x_offset, position[1] + y_offset), text, font=font, fill=(0, 0, 0, 255)) # Black border
# Draw main text
draw.text(position, text, font=font, fill=color)
return np.array(img)
def create_caption_clips(word_timings, video_width, video_height, font_path):
caption_clips = []
font_size = 110 # Increased font size
y_offset = 570 # Moving subtitles higher up on the screen
code
for word in word_timings:
img_array = create_text_image(word['word'], (video_width, 120), font_size, (255, 255, 255, 255), font_path)
clip = ImageClip(img_array, duration=word['end'] - word['start'])
# Adjusting position to move subtitles higher
clip = clip.set_position(('center', video_height - y_offset)).set_start(word['start'])
caption_clips.append(clip)
logging.info(f"Created {len(caption_clips)} caption clips")
return caption_clips
def main(input_video_path, output_video_path, font_path):
# Download Vosk model if not present
model_path = download_vosk_model()
code
# Extract audio from video
audio_path = "temp_audio.wav"
extract_audio(input_video_path, audio_path)
# Transcribe audio
word_timings = transcribe_audio(audio_path, model_path)
if not word_timings:
logging.error("No words were transcribed. Check the audio quality and format.")
return
# Print first 10 transcribed words for debugging
logging.info(f"First 10 transcribed words: {word_timings[:10]}")
# Create caption clips
video = VideoFileClip(input_video_path)
caption_clips = create_caption_clips(word_timings, video.w, video.h, font_path)
# Overlay captions on video
final_video = CompositeVideoClip([video] + caption_clips)
# Write output video
final_video.write_videofile(output_video_path,)
# Clean up temporary files
os.remove(audio_path)
logging.info("Video processing completed")
if name == "main":
parser = argparse.ArgumentParser(description='Add captions to video using Vosk and MoviePy.')
parser.add_argument('input_video', type=str, help='Path to the input video file')
parser.add_argument('--font', type=str, default='/home/user/RedditVideoMakerBot-master/fonts/Rubik-Black.ttf', help='Path to the font file')
args = parser.parse_args()
Here's a part of the code that specifically addresses the processing of each word:
Transcribing and Capturing Word Timings:
Inside the transcribe_audio() function, the Vosk recognizer (rec) is used to recognize words in chunks of audio data. The rec.SetWords(True) method call ensures that word-level timings are available.
The recognizer returns "results" which includes words and their respective timings (start and end times).
python
words = []
for r in results:
if 'result' in r:
words.extend(r['result'])
Creating Caption Clips:
The create_caption_clips() function takes these word timings and creates image clips (subtitles) that display each word for the duration specified by its start and end times.
python
for word in word_timings:
img_array = create_text_image(word['word'], (video_width, 120), font_size, (255, 255, 255, 255), font_path)
clip = ImageClip(img_array, duration=word['end'] - word['start'])
clip = clip.set_position(('center', video_height - y_offset)).set_start(word['start'])
caption_clips.append(clip)
Logging Word Count:
After transcription, a log message indicates the number of words transcribed, which can help in understanding the process:
python
logging.info(f"Transcribed {len(words)} words")
Debugging Information:
The code also prints out the first 10 transcribed words along with their timings to help in debugging and verify if the transcription is working correctly:
Conclusively, the code enables you to track the process and timings of each word being transcribed and subsequently displayed as captions on the video, primarily using the Vosk speech recognition library and MoviePy for video and image processing. If you want more detailed logs of each word processing step, you could add further logging statements within the transcribe_audio() loop, logging each word as it is processed.
The part of the code that specifically tracks each word and its timing is within the transcribe_audio() function. This is where the Vosk speech recognition system processes the audio data and extracts the words along with their start and end times. Here is the relevant segment of that function:
python
def transcribe_audio(audio_path, model_path):
SetLogLevel(0)
wf = wave.open(audio_path, "rb")
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
logging.error("Audio file must be WAV format mono PCM.")
return []
model = Model(model_path)
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True) # Ensure word-level timings are captured
results = []
while True:
data = wf.readframes(4000)
if len(data) == 0:
break
if rec.AcceptWaveform(data):
part_result = json.loads(rec.Result())
results.append(part_result)
part_result = json.loads(rec.FinalResult())
results.append(part_result)
words = []
for r in results:
if 'result' in r:
words.extend(r['result']) # Accumulate all words with their timings
logging.info(f"Transcribed {len(words)} words")
return words
Key Points in Tracking Words:
KaldiRecognizer and SetWords: The KaldiRecognizer is initialized with the model, and SetWords(True) is called, which tells Vosk to include word-level timing information in the results.
Processing Audio Data: Audio data is processed in chunks (wf.readframes(4000)), and rec.AcceptWaveform(data) is called to check if the chunk forms a complete recognition result.
Accumulate Results: When a complete segment is recognized, rec.Result() is called, which returns a JSON string containing the recognized words and their respective timings. This is parsed with json.loads() and added to the results list.
Final Result: After processing all chunks, rec.FinalResult() ensures that any remaining buffered data in the recognizer is processed.
Extracting Words: The loop for r in results: processes each recognition result, and if a result contains a result key, it extracts the list of words, which includes fields for word, start, and end times, appending them to the words list.
This collected list of word dictionaries (words) is what directly tracks each word, including its spoken duration, which can then be used to generate captions with precise timing on the video.
update this code: import os
import sys
import json
import wave
import urllib.request
import zipfile
import logging
import subprocess
from moviepy.editor import VideoFileClip, CompositeVideoClip, ImageClip
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from vosk import Model, KaldiRecognizer, SetLogLevel
import argparse
def download_vosk_model(model_name="vosk-model-small-en-us-0.15"):
"""Download Vosk model if not present"""
model_url = f"https://alphacephei.com/vosk/models/{model_name}.zip"
model_path = os.path.join(os.path.dirname(file), model_name)
code
if not os.path.exists(model_path):
logging.info(f"Downloading Vosk model {model_name}...")
zip_path, _ = urllib.request.urlretrieve(model_url)
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(os.path.dirname(__file__))
os.remove(zip_path)
logging.info("Model downloaded and extracted.")
return model_path
def extract_audio(video_path, audio_path):
"""Extract audio from video using ffmpeg"""
if os.path.exists(audio_path):
logging.info(f"File '{audio_path}' already exists. Overwriting...")
os.remove(audio_path)
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
logging.error("Audio file must be WAV format mono PCM.")
return []
model = Model(model_path)
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True)
results = []
while True:
data = wf.readframes(4000)
if len(data) == 0:
break
if rec.AcceptWaveform(data):
part_result = json.loads(rec.Result())
results.append(part_result)
part_result = json.loads(rec.FinalResult())
results.append(part_result)
words = []
for r in results:
if 'result' in r:
words.extend(r['result'])
logging.info(f"Transcribed {len(words)} words")
return words
def create_text_image(text, size, font_size, font_path, color=(255, 255, 255), bg_color=(0, 0, 0, 0), border_size=15):
"""Create image with text"""
try:
# Verify font path
if not os.path.exists(font_path):
logging.error(f"Font file not found: {font_path}")
raise IOError(f"Font file not found or cannot be opened: {font_path}")
code
# Increase size for border
increased_size = (size[0] + border_size * 2, size[1] + border_size * 2 + font_size // 2)
img = Image.new('RGBA', increased_size, bg_color)
draw = ImageDraw.Draw(img)
# Load font
font = ImageFont.truetype(font_path, font_size)
# Calculate text position
text_bbox = font.getbbox(text)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
position = ((increased_size[0] - text_width) // 2, (increased_size[1] - text_height) // 2)
# Draw border
for x_offset in range(-border_size, border_size + 1):
for y_offset in range(-border_size, border_size + 1):
draw.text(
(position[0] + x_offset, position[1] + y_offset),
text,
font=font,
fill=(0, 0, 0, 255)
)
# Draw main text
draw.text(position, text, font=font, fill=color)
return np.array(img)
except Exception as e:
logging.error(f"Error creating text image: {str(e)}")
raise
def create_caption_clips(word_timings, video_width, video_height, font_path):
"""Create caption clips for each word"""
caption_clips = []
font_size = 110
y_offset = 570
def main(input_video, output_video, font_path):
"""Main function for caption generation"""
try:
# Download Vosk model
model_path = download_vosk_model()
code
# Extract audio
audio_path = "temp_audio.wav"
extract_audio(input_video, audio_path)
# Transcribe audio
word_timings = transcribe_audio(audio_path, model_path)
if not word_timings:
logging.error("No words were transcribed. Check the audio quality and format.")
return
# Create caption clips
video = VideoFileClip(input_video)
caption_clips = create_caption_clips(word_timings, video.w, video.h, font_path)
# Combine video with captions
final_video = CompositeVideoClip([video] + caption_clips)
# Write output
final_video.write_videofile(output_video)
# Cleanup
os.remove(audio_path)
logging.info("Video processing completed")
except Exception as e:
logging.error(f"Error in main processing: {str(e)}")
raise
if name == "main":
parser = argparse.ArgumentParser(description='Add captions to video using Vosk and MoviePy.')
parser.add_argument('input_video', type=str, help='Path to the input video file')
parser.add_argument('--font', type=str, help='Path to the font file',
default=DEFAULT_FONT_PATH)
code
args = parser.parse_args()
# Get paths
input_video = os.path.abspath(args.input_video)
output_video = os.path.splitext(input_video)[0] + "_out.mp4"
font_path = os.path.abspath(args.font)
# Verify paths exist
if not os.path.exists(input_video):
print(f"Input video not found: {input_video}")
sys.exit(1)
if not os.path.exists(font_path):
print(f"Font file not found: {font_path}")
sys.exit(1)
print(f"Debug: Input video: {input_video}")
print(f"Debug: Output video: {output_video}")
print(f"Debug: Font path: {font_path}")
main(input_video, output_video, font_path), heres the code section: words = []
for r in results:
if 'result' in r:
words.extend(r['result'])
# Add this line to print each word as it's processed
print(f"Processing: {r['result'][-1]['word']}", flush=True)
logging.info(f"Transcribed {len(words)} words")
return words
Below is the updated version of your code, incorporating the additional print statement to log each processed word. This will allow you to see each word being processed in real-time, enhancing the debugging and monitoring capability of your transcription process:
python
import os
import sys
import json
import wave
import urllib.request
import zipfile
import logging
import subprocess
from moviepy.editor import VideoFileClip, CompositeVideoClip, ImageClip
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from vosk import Model, KaldiRecognizer, SetLogLevel
import argparse
# Set up logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# Constants for font paths
DEFAULT_FONT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts", "Rubik-Black.ttf")
def download_vosk_model(model_name="vosk-model-small-en-us-0.15"):
"""Download Vosk model if not present"""
model_url = f"https://alphacephei.com/vosk/models/{model_name}.zip"
model_path = os.path.join(os.path.dirname(__file__), model_name)
if not os.path.exists(model_path):
logging.info(f"Downloading Vosk model {model_name}...")
zip_path, _ = urllib.request.urlretrieve(model_url)
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(os.path.dirname(__file__))
os.remove(zip_path)
logging.info("Model downloaded and extracted.")
return model_path
def extract_audio(video_path, audio_path):
"""Extract audio from video using ffmpeg"""
if os.path.exists(audio_path):
logging.info(f"File '{audio_path}' already exists. Overwriting...")
os.remove(audio_path)
command = [
"ffmpeg",
"-i", video_path,
"-acodec", "pcm_s16le",
"-ac", "1",
"-ar", "16000",
audio_path
]
subprocess.run(command, check=True)
logging.info(f"Audio extracted to {audio_path}")
def transcribe_audio(audio_path, model_path):
"""Transcribe audio using Vosk"""
SetLogLevel(0)
wf = wave.open(audio_path, "rb")
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
logging.error("Audio file must be WAV format mono PCM.")
return []
model = Model(model_path)
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True)
results = []
while True:
data = wf.readframes(4000)
if len(data) == 0:
break
if rec.AcceptWaveform(data):
part_result = json.loads(rec.Result())
results.append(part_result)
part_result = json.loads(rec.FinalResult())
results.append(part_result)
words = []
for r in results:
if 'result' in r:
words.extend(r['result'])
# Add this line to print each word as it's processed
for word in r['result']:
print(f"Processing: {word['word']}", flush=True)
logging.info(f"Transcribed {len(words)} words")
return words
def create_text_image(text, size, font_size, font_path, color=(255, 255, 255), bg_color=(0, 0, 0, 0), border_size=15):
"""Create image with text"""
try:
# Verify font path
if not os.path.exists(font_path):
logging.error(f"Font file not found: {font_path}")
raise IOError(f"Font file not found or cannot be opened: {font_path}")
# Increase size for border
increased_size = (size[0] + border_size * 2, size[1] + border_size * 2 + font_size // 2)
img = Image.new('RGBA', increased_size, bg_color)
draw = ImageDraw.Draw(img)
# Load font
font = ImageFont.truetype(font_path, font_size)
# Calculate text position
text_bbox = font.getbbox(text)
text_width = text_bbox[2] - text_bbox[0]
text_height = text_bbox[3] - text_bbox[1]
position = ((increased_size[0] - text_width) // 2, (increased_size[1] - text_height) // 2)
# Draw border
for x_offset in range(-border_size, border_size + 1):
for y_offset in range(-border_size, border_size + 1):
draw.text(
(position[0] + x_offset, position[1] + y_offset),
text,
font=font,
fill=(0, 0, 0, 255)
)
# Draw main text
draw.text(position, text, font=font, fill=color)
return np.array(img)
except Exception as e:
logging.error(f"Error creating text image: {str(e)}")
raise
def create_caption_clips(word_timings, video_width, video_height, font_path):
"""Create caption clips for each word"""
caption_clips = []
font_size = 110
y_offset = 570
for word in word_timings:
img_array = create_text_image(
word['word'],
(video_width, 120),
font_size,
font_path
)
clip = ImageClip(img_array, duration=word['end'] - word['start'])
clip = clip.set_position(('center', video_height - y_offset)).set_start(word['start'])
caption_clips.append(clip)
logging.info(f"Created {len(caption_clips)} caption clips")
return caption_clips
def main(input_video, output_video, font_path):
"""Main function for caption generation"""
try:
# Download Vosk model
model_path = download_vosk_model()
# Extract audio
audio_path = "temp_audio.wav"
extract_audio(input_video, audio_path)
# Transcribe audio
word_timings = transcribe_audio(audio_path, model_path)
if not word_timings:
logging.error("No words were transcribed. Check the audio quality and format.")
return
# Create caption clips
video = VideoFileClip(input_video)
caption_clips = create_caption_clips(word_timings, video.w, video.h, font_path)
# Combine video with captions
final_video = CompositeVideoClip([video] + caption_clips)
# Write output
final_video.write_videofile(output_video)
# Cleanup
os.remove(audio_path)
logging.info("Video processing completed")
except Exception as e:
logging.error(f"Error in main processing: {str(e)}")
raise
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Add captions to video using Vosk and MoviePy.')
parser.add_argument('input_video', type=str, help='Path to the input video file')
parser.add_argument('--font', type=str, help='Path to the font file',
default=DEFAULT_FONT_PATH)
args = parser.parse_args()
# Get paths
input_video = os.path.abspath(args.input_video)
output_video = os.path.splitext(input_video)[0] + "_out.mp4"
font_path = os.path.abspath(args.font)
# Verify paths exist
if not os.path.exists(input_video):
print(f"Input video not found: {input_video}")
sys.exit(1)
if not os.path.exists(font_path):
print(f"Font file not found: {font_path}")
sys.exit(1)
print(f"Debug: Input video: {input_video}")
print(f"Debug: Output video: {output_video}")
print(f"Debug: Font path: {font_path}")
main(input_video, output_video, font_path)
Key Changes:
Added a print statement within the for loop that processes each word result in transcribe_audio():
python
for word in r['result']:
print(f"Processing: {word['word']}", flush=True)
This line ensures that each word is printed to the console in real-time as it's transcribed, which can help in tracking and debugging the transcription process. The flush=True argument ensures that the output is immediately flushed and seen on the console in the correct order.