Chrunos commited on
Commit
020e553
·
verified ·
1 Parent(s): 4197321

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -8
app.py CHANGED
@@ -1,7 +1,9 @@
1
  import streamlit as st
2
  import instaloader
3
  import os
 
4
  from dotenv import load_dotenv
 
5
 
6
  # Load environment variables
7
  load_dotenv()
@@ -13,9 +15,20 @@ INSTAGRAM_PASSWORD = os.getenv('INSTAGRAM_PASSWORD')
13
  def initialize_instaloader():
14
  """Initialize and login to Instaloader"""
15
  try:
16
- loader = instaloader.Instaloader()
 
 
 
 
 
 
 
 
 
17
  if INSTAGRAM_USERNAME and INSTAGRAM_PASSWORD:
 
18
  loader.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
 
19
  return loader
20
  else:
21
  st.error("Instagram credentials not found in environment variables")
@@ -23,6 +36,9 @@ def initialize_instaloader():
23
  except instaloader.exceptions.BadCredentialsException:
24
  st.error("Invalid Instagram credentials")
25
  return None
 
 
 
26
  except Exception as e:
27
  st.error(f"Error initializing Instaloader: {str(e)}")
28
  return None
@@ -30,9 +46,18 @@ def initialize_instaloader():
30
  def extract_shortcode(url):
31
  """Extract shortcode from Instagram URL"""
32
  try:
33
- # Handle both full URLs and shortened ones
34
- parts = url.strip('/').split('/')
35
- return parts[-1] if parts[-1] else parts[-2]
 
 
 
 
 
 
 
 
 
36
  except Exception:
37
  return None
38
 
@@ -41,26 +66,44 @@ def download_reel(url):
41
  if not url:
42
  return "Please enter a URL"
43
 
 
 
44
  loader = initialize_instaloader()
45
  if not loader:
46
  return "Failed to initialize downloader"
47
 
 
48
  shortcode = extract_shortcode(url)
49
  if not shortcode:
50
- return "Invalid URL format"
 
 
51
 
52
  try:
53
  # Create download directory
54
  os.makedirs("reels", exist_ok=True)
55
 
56
- # Download the post
 
 
 
 
57
  post = instaloader.Post.from_shortcode(loader.context, shortcode)
 
 
58
  loader.download_post(post, target=f"reels/{shortcode}")
59
 
60
  return f"Reel downloaded successfully to reels/{shortcode}"
61
 
62
  except instaloader.exceptions.InstaloaderException as e:
63
- return f"Instagram error: {str(e)}"
 
 
 
 
 
 
 
64
  except Exception as e:
65
  return f"An unexpected error occurred: {str(e)}"
66
 
@@ -72,7 +115,7 @@ def main():
72
 
73
  st.title('📱 Instagram Reel Downloader')
74
 
75
- # Add instructions
76
  st.markdown("""
77
  ### Instructions:
78
  1. Paste an Instagram reel URL
@@ -82,10 +125,21 @@ def main():
82
  Note: This tool requires valid Instagram credentials to work.
83
  """)
84
 
 
 
 
85
  # Input for Reel URL
86
  url = st.text_input('Enter the Instagram Reel URL',
87
  placeholder='https://www.instagram.com/reel/...')
88
 
 
 
 
 
 
 
 
 
89
  # Download button
90
  if st.button('Download Reel', type='primary'):
91
  if url:
 
1
  import streamlit as st
2
  import instaloader
3
  import os
4
+ import re
5
  from dotenv import load_dotenv
6
+ import time
7
 
8
  # Load environment variables
9
  load_dotenv()
 
15
  def initialize_instaloader():
16
  """Initialize and login to Instaloader"""
17
  try:
18
+ loader = instaloader.Instaloader(
19
+ download_videos=True,
20
+ download_video_thumbnails=False,
21
+ download_geotags=False,
22
+ download_comments=False,
23
+ save_metadata=False,
24
+ compress_json=False,
25
+ max_connection_attempts=3
26
+ )
27
+
28
  if INSTAGRAM_USERNAME and INSTAGRAM_PASSWORD:
29
+ st.info(f"Attempting to login as {INSTAGRAM_USERNAME}...")
30
  loader.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
31
+ st.success("Login successful!")
32
  return loader
33
  else:
34
  st.error("Instagram credentials not found in environment variables")
 
36
  except instaloader.exceptions.BadCredentialsException:
37
  st.error("Invalid Instagram credentials")
38
  return None
39
+ except instaloader.exceptions.TwoFactorAuthRequiredException:
40
+ st.error("2FA is enabled on this account. Please use an account without 2FA.")
41
+ return None
42
  except Exception as e:
43
  st.error(f"Error initializing Instaloader: {str(e)}")
44
  return None
 
46
  def extract_shortcode(url):
47
  """Extract shortcode from Instagram URL"""
48
  try:
49
+ # Handle different URL formats
50
+ patterns = [
51
+ r'instagram.com/reel/([A-Za-z0-9_-]+)',
52
+ r'instagram.com/p/([A-Za-z0-9_-]+)',
53
+ r'/([A-Za-z0-9_-]{11})[/]?$'
54
+ ]
55
+
56
+ for pattern in patterns:
57
+ match = re.search(pattern, url)
58
+ if match:
59
+ return match.group(1)
60
+ return None
61
  except Exception:
62
  return None
63
 
 
66
  if not url:
67
  return "Please enter a URL"
68
 
69
+ # Initialize loader with debug message
70
+ st.info("Initializing downloader...")
71
  loader = initialize_instaloader()
72
  if not loader:
73
  return "Failed to initialize downloader"
74
 
75
+ # Extract and validate shortcode
76
  shortcode = extract_shortcode(url)
77
  if not shortcode:
78
+ return "Invalid URL format. Please provide a valid Instagram reel URL."
79
+
80
+ st.info(f"Attempting to download reel with shortcode: {shortcode}")
81
 
82
  try:
83
  # Create download directory
84
  os.makedirs("reels", exist_ok=True)
85
 
86
+ # Add delay to prevent rate limiting
87
+ time.sleep(2)
88
+
89
+ # Download the post with progress updates
90
+ st.info("Fetching post metadata...")
91
  post = instaloader.Post.from_shortcode(loader.context, shortcode)
92
+
93
+ st.info("Starting download...")
94
  loader.download_post(post, target=f"reels/{shortcode}")
95
 
96
  return f"Reel downloaded successfully to reels/{shortcode}"
97
 
98
  except instaloader.exceptions.InstaloaderException as e:
99
+ error_msg = str(e)
100
+ if "404" in error_msg:
101
+ return "Post not found. The reel might be private or deleted."
102
+ elif "429" in error_msg:
103
+ return "Too many requests. Please try again later."
104
+ elif "login" in error_msg.lower():
105
+ return "Session expired. Please try logging in again."
106
+ return f"Instagram error: {error_msg}"
107
  except Exception as e:
108
  return f"An unexpected error occurred: {str(e)}"
109
 
 
115
 
116
  st.title('📱 Instagram Reel Downloader')
117
 
118
+ # Add instructions and debug mode toggle
119
  st.markdown("""
120
  ### Instructions:
121
  1. Paste an Instagram reel URL
 
125
  Note: This tool requires valid Instagram credentials to work.
126
  """)
127
 
128
+ # Debug mode toggle
129
+ debug_mode = st.checkbox('Enable debug mode')
130
+
131
  # Input for Reel URL
132
  url = st.text_input('Enter the Instagram Reel URL',
133
  placeholder='https://www.instagram.com/reel/...')
134
 
135
+ if debug_mode and url:
136
+ st.info(f"URL provided: {url}")
137
+ shortcode = extract_shortcode(url)
138
+ if shortcode:
139
+ st.info(f"Extracted shortcode: {shortcode}")
140
+ else:
141
+ st.warning("Could not extract shortcode from URL")
142
+
143
  # Download button
144
  if st.button('Download Reel', type='primary'):
145
  if url: