audio-trim / app.py
sheikhed's picture
Update app.py
cb503aa verified
raw
history blame
2.6 kB
import os
import instaloader
from moviepy.editor import VideoFileClip
import gradio as gr
from pydantic import BaseModel
# Custom Pydantic Config to avoid schema generation issues
class Config(BaseModel):
class Config:
arbitrary_types_allowed = True
# Function to download Instagram reel
def download_instagram_reel(url, output_folder="downloads"):
loader = instaloader.Instaloader()
loader.download_video_thumbnails = False # Disable thumbnail downloads
try:
# Extract shortcode from URL
shortcode = url.split("/")[-2]
# Ensure output folder exists
os.makedirs(output_folder, exist_ok=True)
# Download reel
loader.download_post(instaloader.Post.from_shortcode(loader.context, shortcode), target=output_folder)
# Find downloaded video file
for file in os.listdir(output_folder):
if file.endswith(".mp4"):
return os.path.join(output_folder, file)
return None
except Exception as e:
return f"Error downloading reel: {e}"
# Function to extract audio from video
def extract_audio(video_path, output_folder="downloads"):
try:
# Ensure output folder exists
os.makedirs(output_folder, exist_ok=True)
# Extract audio
video = VideoFileClip(video_path)
audio_path = os.path.join(output_folder, os.path.splitext(os.path.basename(video_path))[0] + ".mp3")
video.audio.write_audiofile(audio_path)
return audio_path
except Exception as e:
return f"Error extracting audio: {e}"
# Gradio interface function
def process_reel(url):
# Download reel
video_path = download_instagram_reel(url)
if isinstance(video_path, str) and video_path.endswith(".mp4"):
# Extract audio
audio_path = extract_audio(video_path)
if isinstance(audio_path, str) and audio_path.endswith(".mp3"):
return "Audio extracted successfully!", audio_path
else:
return "Failed to extract audio.", None
else:
return "Failed to download reel.", None
# Gradio Interface
interface = gr.Interface(
fn=process_reel,
inputs=gr.Textbox(label="Instagram Reel URL", placeholder="Enter the Instagram reel URL here"),
outputs=[
gr.Textbox(label="Status"),
gr.Audio(label="Downloaded Audio")
],
title="Instagram Reel to Audio Downloader",
description="Enter the URL of an Instagram reel to download the audio as an MP3 file.",
theme="compact"
)
# Launch the interface
if __name__ == "__main__":
interface.launch()