amalsp's picture
Update app.py with enhanced Gradio interface and progress tracking
82f5e79 verified
import gradio as gr
import instaloader
import os
import tempfile
from pathlib import Path
def download_instagram_media(instagram_url, progress=gr.Progress()):
"""
Download Instagram media using instaloader
Returns: (file_path, status_message)
"""
try:
progress(0, desc="Starting download...")
if not instagram_url or not instagram_url.strip():
return None, "❌ Please provide a valid Instagram URL"
progress(0.2, desc="Initializing downloader...")
# Create a temporary directory
temp_dir = tempfile.mkdtemp()
# Initialize Instaloader
L = instaloader.Instaloader(
dirname_pattern=temp_dir,
filename_pattern='{shortcode}',
download_comments=False,
download_geotags=False,
download_video_thumbnails=False,
compress_json=False,
save_metadata=False
)
progress(0.4, desc="Extracting URL information...")
# Extract shortcode from URL
shortcode = None
if '/p/' in instagram_url:
shortcode = instagram_url.split('/p/')[1].split('/')[0].split('?')[0]
elif '/reel/' in instagram_url:
shortcode = instagram_url.split('/reel/')[1].split('/')[0].split('?')[0]
elif '/tv/' in instagram_url:
shortcode = instagram_url.split('/tv/')[1].split('/')[0].split('?')[0]
else:
return None, "❌ Invalid Instagram URL. Please provide a post, reel, or IGTV URL."
progress(0.6, desc="Downloading media...")
# Download the post
post = instaloader.Post.from_shortcode(L.context, shortcode)
L.download_post(post, target=temp_dir)
progress(0.8, desc="Processing downloaded files...")
# Find downloaded media file
media_files = []
for file in Path(temp_dir).glob('*'):
if file.suffix.lower() in ['.jpg', '.jpeg', '.png', '.mp4', '.mov']:
media_files.append(str(file))
progress(1.0, desc="Complete!")
if media_files:
return media_files[0], "βœ… Download successful!"
else:
return None, "❌ No media file found. Please check the URL."
except instaloader.exceptions.ConnectionException:
return None, "❌ Connection error. Instagram might be blocking requests. Try again later."
except instaloader.exceptions.InstaloaderException as e:
return None, f"❌ Error downloading: {str(e)}"
except Exception as e:
return None, f"❌ Unexpected error: {str(e)}"
# Custom CSS
custom_css = """
.gradio-container {
font-family: 'Arial', sans-serif;
}
.main-header {
text-align: center;
margin-bottom: 2rem;
}
.download-btn {
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
border: none;
}
"""
# Create Gradio interface
with gr.Blocks(title="Instagram Downloader", css=custom_css, theme=gr.themes.Soft()) as demo:
gr.Markdown(
"""
# πŸ“Έ Instagram Media Downloader
Download images and videos from Instagram posts, reels, and IGTV
""",
elem_classes="main-header"
)
with gr.Row():
with gr.Column(scale=2):
url_input = gr.Textbox(
label="Instagram URL",
placeholder="https://www.instagram.com/p/... or /reel/... or /tv/...",
lines=1,
info="Paste the full Instagram URL here"
)
with gr.Row():
with gr.Column():
download_btn = gr.Button("⬇️ Download", variant="primary", size="lg")
with gr.Row():
with gr.Column():
output_file = gr.File(label="πŸ“₯ Downloaded Media", interactive=False)
status_text = gr.Textbox(label="Status", lines=2, interactive=False)
# Examples
gr.Examples(
examples=[
["https://www.instagram.com/p/example123/"],
["https://www.instagram.com/reel/example456/"],
],
inputs=[url_input],
label="Example URLs (replace with real URLs)"
)
download_btn.click(
fn=download_instagram_media,
inputs=[url_input],
outputs=[output_file, status_text],
show_progress=True
)
gr.Markdown(
"""
---
### ⚠️ Important Notes:
- This tool is for **personal use only**
- Please respect **copyright** and Instagram's **terms of service**
- Works with public Instagram posts, reels, and IGTV videos
- Some posts might not be downloadable due to Instagram restrictions
### πŸ”Œ API Usage:
This Space also provides an API endpoint. You can use it programmatically:
```python
import requests
response = requests.post(
"https://your-space-url/api/predict",
json={"data": ["https://www.instagram.com/p/your-post-id/"]}
)
```
"""
)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)