Spaces:
Sleeping
Sleeping
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
import subprocess | |
from pathlib import Path | |
from .config import ( | |
AUDIO_DIR, | |
TRANSCRIPTS_DIR, | |
AUDIO_EXT, | |
TEXT_EXT, | |
) | |
# -->> Tunables <<--------------------- | |
# -->> Definitions <<------------------ | |
# -->> API <<-------------------------- | |
def extract_audio_from_video(video_file, audio_folder_path): | |
"""Converts video to audio directly using `ffmpeg` command | |
with the help of subprocess module""" | |
# Create the audio folder if it doesn't exist | |
Path(audio_folder_path).mkdir(parents=True, exist_ok=True) | |
# Extract the filename from the video_file path | |
video_filename = Path(video_file).name | |
video_name = Path(video_filename).stem | |
output_audio_path = Path(audio_folder_path) / (video_name + AUDIO_EXT) | |
output_audio_pathstr = str(output_audio_path) | |
# Check if the audio file already exists and remove it | |
if output_audio_path.exists(): | |
output_audio_path.unlink() | |
# Command to extract audio using ffmpeg | |
command = [ | |
"ffmpeg", | |
"-i", | |
video_file, | |
"-ab", | |
"160k", | |
"-ac", | |
"2", | |
"-ar", | |
"44100", | |
"-vn", | |
output_audio_pathstr | |
] | |
# Run the command | |
print("Extracting audio...") | |
subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
print("Audio extracted!") | |
# If save_audio is True, provide a link to save the file | |
return output_audio_pathstr, output_audio_path | |
def save_file(audio_path, transcript_folder_path, text): | |
"""Saves the text to a file""" | |
# Create the transcript folder if it doesn't exist | |
transcript_folder_path = Path(transcript_folder_path) | |
transcript_folder_path.mkdir(parents=True, exist_ok=True) | |
# Extract the filename from the audio_file path | |
audio_filename = Path(audio_path).stem | |
output_transcript_path = transcript_folder_path / (audio_filename + TEXT_EXT) | |
output_transcript_pathstr = str(output_transcript_path) | |
# Check if the transcript file already exists and remove it | |
if output_transcript_path.exists(): | |
output_transcript_path.unlink(missing_ok=True) | |
# Save the transcript to a file | |
with open(output_transcript_pathstr, "w") as f: | |
f.write(text) | |
return output_transcript_pathstr, text | |
# -->> Execute <<---------------------- | |
# -->> Export <<----------------------- | |