Spaces:
Build error
Build error
File size: 7,462 Bytes
6715b3e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | import os
from faster_whisper import WhisperModel
import tempfile
import ffmpeg # For audio extraction if yt-dlp doesn't provide a clean audio file or for format conversion
# Load the Whisper model once when the module is imported
# Model sizes: "tiny", "tiny.en", "base", "base.en", "small", "small.en",
# "medium", "medium.en", "large-v1", "large-v2", "large-v3"
# Using "base.en" for a balance of speed and accuracy for English.
# You can change this to a larger model for better accuracy or a multilingual model.
MODEL_SIZE = "base.en"
# Run on GPU with FP16
# model = WhisperModel(MODEL_SIZE, device="cuda", compute_type="float16")
# or run on GPU with INT8
# model = WhisperModel(MODEL_SIZE, device="cuda", compute_type="int8_float16")
# or run on CPU with INT8
model = WhisperModel(MODEL_SIZE, device="cpu", compute_type="int8") # Good for CPU
def transcribe_audio(video_or_audio_path: str,
language: str = None,
task: str = "transcribe",
beam_size: int = 5,
word_timestamps: bool = False) -> dict:
"""Returns full transcript from video or audio file using faster-whisper.
Args:
video_or_audio_path: Path to the video or audio file.
language: Language code (e.g., 'en', 'es'). If None, auto-detects.
task: 'transcribe' or 'translate' (to English).
beam_size: Beam size for decoding.
word_timestamps: Whether to include word-level timestamps.
Returns:
A dictionary containing the full text and optionally segments with timestamps.
E.g., {"text": "Hello world.", "segments": [...], "language": "en"}
"""
if not os.path.exists(video_or_audio_path):
raise FileNotFoundError(f"Media file not found: {video_or_audio_path}")
print(f"Transcribing audio for {video_or_audio_path} using model {MODEL_SIZE}...")
# Whisper works best with audio files. If it's a video, extract audio first.
# Common audio formats like wav, mp3 are fine. We can use ffmpeg to ensure compatibility.
# Create a temporary file for the audio if extraction or conversion is needed.
# Check if it's a common audio format, otherwise assume it might be video or needs conversion
is_common_audio = video_or_audio_path.lower().endswith(('.wav', '.mp3', '.m4a', '.aac', '.ogg', '.flac'))
temp_audio_file = None
audio_to_transcribe = video_or_audio_path
try:
if not is_common_audio:
print(f"Input {video_or_audio_path} is not a standard audio file, attempting to extract/convert audio.")
# Create a temporary WAV file for the extracted audio
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmpfile:
temp_audio_file_name = tmpfile.name
try:
ffmpeg.input(video_or_audio_path).output(temp_audio_file_name, acodec='pcm_s16le', ar='16000', ac=1).run(quiet=True, overwrite_output=True)
audio_to_transcribe = temp_audio_file_name
print(f"Audio extracted/converted to {audio_to_transcribe}")
except ffmpeg.Error as e:
print(f"FFmpeg error during audio extraction/conversion for {video_or_audio_path}: {e.stderr.decode() if e.stderr else str(e)}")
# Fallback to trying the original file directly if ffmpeg fails
print("Falling back to transcribing the original file directly.")
segments, info = model.transcribe(
audio_to_transcribe,
language=language,
task=task,
beam_size=beam_size,
word_timestamps=word_timestamps
)
full_text = ""
segment_data = []
for segment in segments:
full_text += segment.text + " "
seg_dict = {"start": segment.start, "end": segment.end, "text": segment.text}
if word_timestamps:
seg_dict["words"] = [
{"word": word.word, "start": word.start, "end": word.end, "probability": word.probability}
for word in segment.words
]
segment_data.append(seg_dict)
print(f"Transcription complete for {video_or_audio_path}. Detected language: {info.language} with probability {info.language_probability:.2f}")
return {
"text": full_text.strip(),
"segments": segment_data,
"language": info.language,
"language_probability": info.language_probability
}
except Exception as e:
print(f"Error during transcription of {video_or_audio_path}: {e}")
raise
finally:
if temp_audio_file and os.path.exists(temp_audio_file):
print(f"Deleting temporary audio file {temp_audio_file}")
os.remove(temp_audio_file)
elif temp_audio_file: # If temp_audio_file was assigned but creation failed
print(f"Note: Temporary audio file {temp_audio_file} was planned but may not have been created or already cleaned up.")
# Example usage (for testing):
# if __name__ == '__main__':
# # This requires a test audio/video file.
# # For example, download a short one with yt-dlp first.
# # dummy_video_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" # Short, famous video
# # from tools.downloader import download_video # Assuming downloader.py is in tools/
# # print(f"Downloading test video...")
# # test_file_path = download_video(dummy_video_url)
# # print(f"Test video downloaded to {test_file_path}")
# # Create a dummy wav file for testing if no video download is preferred
# import soundfile as sf
# import numpy as np
# dummy_audio_path = "dummy_audio_test.wav"
# data = np.random.uniform(-0.5, 0.5, 44100 * 2) # 2 seconds of dummy audio
# sf.write(dummy_audio_path, data, 44100)
# print(f"Created dummy audio: {dummy_audio_path}")
# test_file_path = dummy_audio_path
# if os.path.exists(test_file_path):
# print(f"\nTranscribing {test_file_path} (with word timestamps):")
# transcript_data = transcribe_audio(test_file_path, language="en", word_timestamps=True)
# print(f"Full text: {transcript_data['text']}")
# # for i, seg in enumerate(transcript_data['segments']):
# # print(f" Segment {i+1} ({seg['start']:.2f}s - {seg['end']:.2f}s): {seg['text']}")
# # if "words" in seg:
# # for word_info in seg["words"]:
# # print(f" {word_info['word']} ({word_info['start']:.2f}-{word_info['end']:.2f}) - conf: {word_info['probability']:.2f}")
# # print(f"\nTranscribing {test_file_path} (summary, auto language detection):")
# # transcript_data_simple = transcribe_audio(test_file_path)
# # print(f"Full text: {transcript_data_simple['text']}")
# # print(f"Detected language: {transcript_data_simple['language']}")
# if test_file_path == dummy_audio_path: # Clean up dummy audio
# os.remove(test_file_path)
# print(f"Cleaned up {dummy_audio_path}")
# # elif test_file_path.startswith("data/videos/"): # Clean up downloaded video
# # os.remove(test_file_path)
# # print(f"Cleaned up downloaded video: {test_file_path}")
# else:
# print(f"Test file {test_file_path} not found, skipping transcription test.")
|