amalsp commited on
Commit
82f5e79
Β·
verified Β·
1 Parent(s): d8a8d12

Update app.py with enhanced Gradio interface and progress tracking

Browse files
Files changed (1) hide show
  1. app.py +89 -24
app.py CHANGED
@@ -2,16 +2,20 @@ import gradio as gr
2
  import instaloader
3
  import os
4
  import tempfile
5
- import shutil
6
  from pathlib import Path
7
 
8
- def download_instagram_media(instagram_url):
9
  """
10
  Download Instagram media using instaloader
 
11
  """
12
  try:
 
 
13
  if not instagram_url or not instagram_url.strip():
14
- return None, "Please provide a valid Instagram URL"
 
 
15
 
16
  # Create a temporary directory
17
  temp_dir = tempfile.mkdtemp()
@@ -27,6 +31,8 @@ def download_instagram_media(instagram_url):
27
  save_metadata=False
28
  )
29
 
 
 
30
  # Extract shortcode from URL
31
  shortcode = None
32
  if '/p/' in instagram_url:
@@ -36,58 +42,117 @@ def download_instagram_media(instagram_url):
36
  elif '/tv/' in instagram_url:
37
  shortcode = instagram_url.split('/tv/')[1].split('/')[0].split('?')[0]
38
  else:
39
- return None, "Invalid Instagram URL. Please provide a post, reel, or IGTV URL."
 
 
40
 
41
  # Download the post
42
  post = instaloader.Post.from_shortcode(L.context, shortcode)
43
  L.download_post(post, target=temp_dir)
44
 
 
 
45
  # Find downloaded media file
46
  media_files = []
47
  for file in Path(temp_dir).glob('*'):
48
  if file.suffix.lower() in ['.jpg', '.jpeg', '.png', '.mp4', '.mov']:
49
  media_files.append(str(file))
50
 
 
 
51
  if media_files:
52
- # Return the first media file found
53
- return media_files[0], "Download successful!"
54
  else:
55
- return None, "No media file found. Please check the URL."
56
 
57
  except instaloader.exceptions.ConnectionException:
58
- return None, "Connection error. Instagram might be blocking requests."
59
  except instaloader.exceptions.InstaloaderException as e:
60
- return None, f"Error downloading: {str(e)}"
61
  except Exception as e:
62
- return None, f"Unexpected error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
  # Create Gradio interface
65
- with gr.Blocks(title="Instagram Downloader") as demo:
66
- gr.Markdown("# Instagram Media Downloader")
67
- gr.Markdown("Download images and videos from Instagram posts, reels, and IGTV")
 
 
 
 
 
68
 
69
  with gr.Row():
70
- with gr.Column():
71
  url_input = gr.Textbox(
72
  label="Instagram URL",
73
- placeholder="https://www.instagram.com/p/...",
74
- lines=1
 
75
  )
76
- download_btn = gr.Button("Download", variant="primary")
77
-
78
  with gr.Row():
79
  with gr.Column():
80
- output_file = gr.File(label="Downloaded Media")
81
- status_text = gr.Textbox(label="Status", lines=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  download_btn.click(
84
  fn=download_instagram_media,
85
  inputs=[url_input],
86
- outputs=[output_file, status_text]
 
87
  )
88
 
89
- gr.Markdown("---")
90
- gr.Markdown("**Note:** This tool is for personal use only. Please respect copyright and Instagram's terms of service.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
  if __name__ == "__main__":
93
- demo.launch()
 
2
  import instaloader
3
  import os
4
  import tempfile
 
5
  from pathlib import Path
6
 
7
+ def download_instagram_media(instagram_url, progress=gr.Progress()):
8
  """
9
  Download Instagram media using instaloader
10
+ Returns: (file_path, status_message)
11
  """
12
  try:
13
+ progress(0, desc="Starting download...")
14
+
15
  if not instagram_url or not instagram_url.strip():
16
+ return None, "❌ Please provide a valid Instagram URL"
17
+
18
+ progress(0.2, desc="Initializing downloader...")
19
 
20
  # Create a temporary directory
21
  temp_dir = tempfile.mkdtemp()
 
31
  save_metadata=False
32
  )
33
 
34
+ progress(0.4, desc="Extracting URL information...")
35
+
36
  # Extract shortcode from URL
37
  shortcode = None
38
  if '/p/' in instagram_url:
 
42
  elif '/tv/' in instagram_url:
43
  shortcode = instagram_url.split('/tv/')[1].split('/')[0].split('?')[0]
44
  else:
45
+ return None, "❌ Invalid Instagram URL. Please provide a post, reel, or IGTV URL."
46
+
47
+ progress(0.6, desc="Downloading media...")
48
 
49
  # Download the post
50
  post = instaloader.Post.from_shortcode(L.context, shortcode)
51
  L.download_post(post, target=temp_dir)
52
 
53
+ progress(0.8, desc="Processing downloaded files...")
54
+
55
  # Find downloaded media file
56
  media_files = []
57
  for file in Path(temp_dir).glob('*'):
58
  if file.suffix.lower() in ['.jpg', '.jpeg', '.png', '.mp4', '.mov']:
59
  media_files.append(str(file))
60
 
61
+ progress(1.0, desc="Complete!")
62
+
63
  if media_files:
64
+ return media_files[0], "βœ… Download successful!"
 
65
  else:
66
+ return None, "❌ No media file found. Please check the URL."
67
 
68
  except instaloader.exceptions.ConnectionException:
69
+ return None, "❌ Connection error. Instagram might be blocking requests. Try again later."
70
  except instaloader.exceptions.InstaloaderException as e:
71
+ return None, f"❌ Error downloading: {str(e)}"
72
  except Exception as e:
73
+ return None, f"❌ Unexpected error: {str(e)}"
74
+
75
+ # Custom CSS
76
+ custom_css = """
77
+ .gradio-container {
78
+ font-family: 'Arial', sans-serif;
79
+ }
80
+ .main-header {
81
+ text-align: center;
82
+ margin-bottom: 2rem;
83
+ }
84
+ .download-btn {
85
+ background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
86
+ border: none;
87
+ }
88
+ """
89
 
90
  # Create Gradio interface
91
+ with gr.Blocks(title="Instagram Downloader", css=custom_css, theme=gr.themes.Soft()) as demo:
92
+ gr.Markdown(
93
+ """
94
+ # πŸ“Έ Instagram Media Downloader
95
+ Download images and videos from Instagram posts, reels, and IGTV
96
+ """,
97
+ elem_classes="main-header"
98
+ )
99
 
100
  with gr.Row():
101
+ with gr.Column(scale=2):
102
  url_input = gr.Textbox(
103
  label="Instagram URL",
104
+ placeholder="https://www.instagram.com/p/... or /reel/... or /tv/...",
105
+ lines=1,
106
+ info="Paste the full Instagram URL here"
107
  )
108
+
 
109
  with gr.Row():
110
  with gr.Column():
111
+ download_btn = gr.Button("⬇️ Download", variant="primary", size="lg")
112
+
113
+ with gr.Row():
114
+ with gr.Column():
115
+ output_file = gr.File(label="πŸ“₯ Downloaded Media", interactive=False)
116
+ status_text = gr.Textbox(label="Status", lines=2, interactive=False)
117
+
118
+ # Examples
119
+ gr.Examples(
120
+ examples=[
121
+ ["https://www.instagram.com/p/example123/"],
122
+ ["https://www.instagram.com/reel/example456/"],
123
+ ],
124
+ inputs=[url_input],
125
+ label="Example URLs (replace with real URLs)"
126
+ )
127
 
128
  download_btn.click(
129
  fn=download_instagram_media,
130
  inputs=[url_input],
131
+ outputs=[output_file, status_text],
132
+ show_progress=True
133
  )
134
 
135
+ gr.Markdown(
136
+ """
137
+ ---
138
+ ### ⚠️ Important Notes:
139
+ - This tool is for **personal use only**
140
+ - Please respect **copyright** and Instagram's **terms of service**
141
+ - Works with public Instagram posts, reels, and IGTV videos
142
+ - Some posts might not be downloadable due to Instagram restrictions
143
+
144
+ ### πŸ”Œ API Usage:
145
+ This Space also provides an API endpoint. You can use it programmatically:
146
+ ```python
147
+ import requests
148
+
149
+ response = requests.post(
150
+ "https://your-space-url/api/predict",
151
+ json={"data": ["https://www.instagram.com/p/your-post-id/"]}
152
+ )
153
+ ```
154
+ """
155
+ )
156
 
157
  if __name__ == "__main__":
158
+ demo.launch(server_name="0.0.0.0", server_port=7860)