whispertube_backend / helperfunctions.py
uzi007's picture
Added UUID & Media Metadata
6459994
raw
history blame
4.76 kB
import os
import time
import uuid
import hashlib
import subprocess
def generate_uuid(user_ip, url):
"""
Generates a uuid based on User IP, URL & timestamp
"""
# Converting User IP to bytes and Hashing it using SHA-1
user_ip_bytes = user_ip.encode('utf-8')
hashed_user_ip = hashlib.sha1(user_ip_bytes).hexdigest()
# Converting URL to bytes and Hashing it using SHA-1
url_bytes = url.encode('utf-8')
hashed_url = hashlib.sha1(url_bytes).hexdigest()
# Combining Hashed User IP, URL and Current Timestamp to Create a Unique Identifier
unique_id = f"{hashed_user_ip}-{hashed_url}-{int(time.time())}"
# Generate a UUID from the Unique Identifier
uuid_value = uuid.uuid5(uuid.NAMESPACE_URL, unique_id)
return str(uuid_value)
def extract_audio(video_path):
"""
Extract audio from a video file (MP4 or WebM) and save it as an MP3 file using ffmpeg.
Args:
video_path (str): Path to the input video file.
Returns:
str: Path of extracted audio.
"""
try:
# Path for Extracted Audio File
filename, extension = os.path.splitext(video_path)
audio_path = filename + '.mp3'
# Choosing the Appropriate Codec for the Output Audio Format (MP3)
audio_codec = "libmp3lame" if extension.lower() in (".mp4", ".webm") else "mp3"
# Extracting Audio using FFMPEG Command
command = ["ffmpeg", "-i", video_path, "-vn", "-acodec",
audio_codec, audio_path, '-loglevel', 'quiet']
subprocess.run(command, check=True)
return audio_path
except Exception as e:
print(f"Error in extract_audio: {e}")
def burn_subtitles(video_file_path, subtitle_file_path):
'''
Burns the subtitles onto the video
Args:
video_file_path (str): Path to the input video file.
subtitle_file_path (str): Path to the subtitle file.
Returns:
str: Path of output video with subtitles.
'''
try:
# Getting Output File Path
video_filename, video_extension = os.path.splitext(video_file_path)
subtitle_filename, subtitle_extension = os.path.splitext(subtitle_file_path)
output_file_path = video_filename + subtitle_extension.replace('.', '_') + video_extension
# Burning the Subtitles onto Video using FFMPEG Command
command = ['ffmpeg', '-i', video_file_path,
'-vf', f'subtitles={subtitle_file_path}',
output_file_path, '-loglevel', 'quiet']
subprocess.run(command, check=True)
return output_file_path
except Exception as e:
print(f"Error in burn_subtitles: {e}")
def convert_to_srt_time_format(seconds):
'''
Converts seconds into .srt format
'''
try:
hours = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
milliseconds = int((seconds - int(seconds)) * 1000)
return f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d},{milliseconds:03d}"
except Exception as e:
print(f"Error in save_translated_subtitles: {e}")
def save_translated_subtitles(subtitles, media_path):
'''
Saves the translated subtitles into .srt file
'''
try:
# Converting to SRT Format
srt_content = ""
counter = 1
for subtitle in subtitles:
start_time = subtitle['start']
end_time = subtitle['end']
text = subtitle['text']
srt_content += f"{counter}\n"
srt_content += f"{convert_to_srt_time_format(start_time)} --> {convert_to_srt_time_format(end_time)}\n"
srt_content += f"{text}\n\n"
counter += 1
# Saving SRT content to a .srt file
subtitles_filename = os.path.splitext(media_path)[0]
subtitles_filename = f'{subtitles_filename}.srt'
with open(subtitles_filename, 'w', encoding='utf-8') as srt_file:
srt_file.write(srt_content)
return subtitles_filename
except Exception as e:
print(f"Error in save_translated_subtitles: {e}")
def convert_audio(input_file, audio_format, audio_quality):
'''
Converts the audio according to the given audio parameters
'''
try:
# Getting Output File Path
output_file = f"{input_file.rsplit('.', 1)[0]}_converted.{audio_format}"
# Running the command using Subprocess
command = [
'ffmpeg', '-i', input_file,
'-b:a', audio_quality[:-3], output_file,
'-loglevel', 'quiet'
]
subprocess.run(command)
except Exception as e:
print(f"Error in convert_audio: {e}")