File size: 5,190 Bytes
bc44a49
 
 
 
 
 
82f5e79
bc44a49
 
82f5e79
bc44a49
 
82f5e79
 
bc44a49
82f5e79
 
 
bc44a49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82f5e79
 
bc44a49
 
 
 
 
 
 
 
 
82f5e79
 
 
bc44a49
 
 
 
 
82f5e79
 
bc44a49
 
 
 
 
 
82f5e79
 
bc44a49
82f5e79
bc44a49
82f5e79
bc44a49
 
82f5e79
bc44a49
82f5e79
bc44a49
82f5e79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc44a49
 
82f5e79
 
 
 
 
 
 
 
bc44a49
 
82f5e79
bc44a49
 
82f5e79
 
 
bc44a49
82f5e79
bc44a49
 
82f5e79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc44a49
 
 
 
82f5e79
 
bc44a49
 
82f5e79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc44a49
 
82f5e79
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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)