VideoConverter / app.py
MegaTronX's picture
Update app.py
efc6117 verified
import gradio as gr
import subprocess
import os
import tempfile
from pathlib import Path
def convert_ts_to_mp4(file_path):
"""
Converts a .ts video file to .mp4 using ffmpeg.
Args:
file_path (str): The path to the .ts file.
Returns:
str: The path to the converted .mp4 file, or None on error.
"""
try:
# 1. Check if the file exists
if not os.path.exists(file_path):
return "Error: File not found."
# 2. Check if the file has the correct extension
if not file_path.lower().endswith(".ts"):
return "Error: Invalid file type. Please upload a .ts file."
# 3. Convert the .ts file to .mp4 using ffmpeg in a temporary location
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as mp4_file:
try:
subprocess.run(
[
"ffmpeg",
"-i",
file_path,
"-c:v",
"libx264", # Use libx264 for H.264 encoding (common)
"-c:a",
"aac", # Use AAC for audio encoding (common)
"-y", # Overwrite output file if it exists
mp4_file.name,
],
check=True, # Raise an exception on non-zero exit code
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except subprocess.CalledProcessError as e:
# ffmpeg failed. Return the error message.
error_message = f"FFmpeg conversion failed: {e.stderr.decode('utf-8')}"
print(error_message) # Print to console for debugging in Spaces
return error_message
# 4. Return the path to the .mp4 file
return mp4_file.name
except Exception as e:
return f"An error occurred: {e}"
def gradio_interface():
"""
Defines the Gradio interface for the application.
"""
inputs = [
gr.File(
label="Upload .TS File",
file_types=[".ts"], # Restrict to .ts files
),
]
outputs = gr.File(label="Converted MP4 File")
title = "TS to MP4 Converter"
description = "Convert .ts video files to .mp4 format. Upload a .ts file, and the converted .mp4 file will be available for download."
article = """
Example Usage:
1. Click the 'Upload .TS File' button to upload a .ts video file from your local machine.
2. Click the 'Submit' button.
3. The converted .mp4 file will be processed, and a download link will be provided.
"""
return gr.Interface(
fn=convert_ts_to_mp4,
inputs=inputs,
outputs=outputs,
title=title,
description=description,
article=article,
)
if __name__ == "__main__":
gradio_interface().launch()