sheikhed commited on
Commit
b38db57
·
verified ·
1 Parent(s): c0e2e5e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -70
app.py CHANGED
@@ -1,94 +1,63 @@
1
  import os
2
- import subprocess
3
- import instaloader
4
  import gradio as gr
 
5
  from pydantic import BaseModel
6
 
7
  class Config(BaseModel):
8
  class Config:
9
  arbitrary_types_allowed = True
10
 
11
- def download_instagram_reel(url, output_folder="downloads"):
12
- loader = instaloader.Instaloader()
13
- loader.download_video_thumbnails = False
 
14
  try:
15
- # Extract shortcode from URL
16
- shortcode = url.split("/")[-2]
17
  # Ensure output folder exists
18
  os.makedirs(output_folder, exist_ok=True)
19
- # Download reel
20
- loader.download_post(instaloader.Post.from_shortcode(loader.context, shortcode), target=output_folder)
21
- # Find downloaded video file
22
- for file in os.listdir(output_folder):
23
- if file.endswith(".mp4"):
24
- return os.path.join(output_folder, file)
25
- return None
26
- except Exception as e:
27
- return f"Error downloading reel: {e}"
28
-
29
- def extract_audio(video_path, output_folder="downloads"):
30
- try:
31
- # Ensure output folder exists
32
- os.makedirs(output_folder, exist_ok=True)
33
-
34
- # Generate output audio path
35
- audio_path = os.path.join(output_folder,
36
- os.path.splitext(os.path.basename(video_path))[0] + ".mp3")
37
 
38
- # FFmpeg command to extract audio
39
- command = [
40
- 'ffmpeg',
41
- '-i', video_path, # Input file
42
- '-vn', # Disable video
43
- '-acodec', 'libmp3lame', # Use MP3 codec
44
- '-ab', '192k', # Audio bitrate
45
- '-ar', '44100', # Audio sample rate
46
- '-y', # Overwrite output file if it exists
47
- audio_path
48
- ]
49
-
50
- # Run FFmpeg command
51
- result = subprocess.run(command,
52
- stdout=subprocess.PIPE,
53
- stderr=subprocess.PIPE)
54
-
55
- if result.returncode != 0:
56
- return f"FFmpeg error: {result.stderr.decode()}"
57
-
58
- return audio_path
59
- except Exception as e:
60
- return f"Error extracting audio: {e}"
61
 
62
- def process_reel(url):
63
- # Download reel
64
- video_path = download_instagram_reel(url)
65
- if isinstance(video_path, str) and video_path.endswith(".mp4"):
66
- # Extract audio
67
- audio_path = extract_audio(video_path)
68
- if isinstance(audio_path, str) and audio_path.endswith(".mp3"):
69
- # Clean up video file after extraction
70
- try:
71
- os.remove(video_path)
72
- except:
73
- pass
74
- return "Audio extracted successfully!", audio_path
75
- else:
76
- return f"Failed to extract audio: {audio_path}", None
77
- else:
78
- return f"Failed to download reel: {video_path}", None
79
 
80
  # Gradio Interface
81
  interface = gr.Interface(
82
- fn=process_reel,
83
- inputs=gr.Textbox(label="Instagram Reel URL",
84
- placeholder="Enter the Instagram reel URL here"),
 
 
85
  outputs=[
86
  gr.Textbox(label="Status"),
87
  gr.Audio(label="Downloaded Audio")
88
  ],
89
  title="Instagram Reel to Audio Downloader",
90
- description="Enter the URL of an Instagram reel to download the audio as an MP3 file.",
91
- theme="compact"
 
 
 
 
 
 
 
92
  )
93
 
94
  if __name__ == "__main__":
 
1
  import os
 
 
2
  import gradio as gr
3
+ from yt_dlp import YoutubeDL
4
  from pydantic import BaseModel
5
 
6
  class Config(BaseModel):
7
  class Config:
8
  arbitrary_types_allowed = True
9
 
10
+ def download_reel_audio(url, output_folder="downloads"):
11
+ """
12
+ Download audio from Instagram reel using yt-dlp
13
+ """
14
  try:
 
 
15
  # Ensure output folder exists
16
  os.makedirs(output_folder, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ # Configure yt-dlp options
19
+ ydl_opts = {
20
+ 'format': 'bestaudio/best',
21
+ 'outtmpl': os.path.join(output_folder, '%(title)s.%(ext)s'),
22
+ 'postprocessors': [{
23
+ 'key': 'FFmpegExtractAudio',
24
+ 'preferredcodec': 'mp3',
25
+ 'preferredquality': '192',
26
+ }],
27
+ 'quiet': True,
28
+ 'no_warnings': True
29
+ }
30
+
31
+ # Download the audio
32
+ with YoutubeDL(ydl_opts) as ydl:
33
+ info = ydl.extract_info(url, download=True)
34
+ audio_path = os.path.join(output_folder, f"{info['title']}.mp3")
35
+ return "Audio downloaded successfully!", audio_path
 
 
 
 
 
36
 
37
+ except Exception as e:
38
+ return f"Error downloading audio: {str(e)}", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  # Gradio Interface
41
  interface = gr.Interface(
42
+ fn=download_reel_audio,
43
+ inputs=gr.Textbox(
44
+ label="Instagram Reel URL",
45
+ placeholder="Enter the Instagram reel URL here (e.g., https://www.instagram.com/reel/...)"
46
+ ),
47
  outputs=[
48
  gr.Textbox(label="Status"),
49
  gr.Audio(label="Downloaded Audio")
50
  ],
51
  title="Instagram Reel to Audio Downloader",
52
+ description="""
53
+ Enter the URL of an Instagram reel to download its audio as an MP3 file.
54
+ This tool uses yt-dlp which is more reliable and doesn't require authentication.
55
+ """,
56
+ theme="default",
57
+ examples=[
58
+ ["https://www.instagram.com/reel/example1"],
59
+ ["https://www.instagram.com/reel/example2"]
60
+ ]
61
  )
62
 
63
  if __name__ == "__main__":