Chrunos commited on
Commit
23f77f0
·
verified ·
1 Parent(s): 811682a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -52
app.py CHANGED
@@ -2,8 +2,8 @@ import streamlit as st
2
  import instaloader
3
  import os
4
  from dotenv import load_dotenv
5
- import time
6
- import glob
7
 
8
  # Load environment variables
9
  load_dotenv()
@@ -12,116 +12,147 @@ load_dotenv()
12
  INSTAGRAM_USERNAME = os.getenv('INSTAGRAM_USERNAME')
13
  INSTAGRAM_PASSWORD = os.getenv('INSTAGRAM_PASSWORD')
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  def verify_download(shortcode):
16
  """Verify that files were actually downloaded"""
17
- download_path = f"reels/{shortcode}"
18
 
19
  # Check if directory exists
20
  if not os.path.exists(download_path):
21
  return False, "Download directory not found"
22
 
23
- # Look for video files (mp4)
24
- video_files = glob.glob(f"{download_path}/*.mp4")
 
 
 
 
25
 
26
  if video_files:
27
- # Get the full path of the first video file
28
- video_path = video_files[0]
29
  file_size = os.path.getsize(video_path)
30
  return True, {
31
  'path': video_path,
32
  'size': f"{file_size / (1024*1024):.2f} MB",
33
  'exists': os.path.exists(video_path)
34
  }
35
- return False, "No video files found in download directory"
36
 
37
  def download_reel(url):
38
  """Download Instagram reel"""
39
  if not url:
40
  return "Please enter a URL"
41
 
42
- # Initialize loader with debug message
43
- st.info("Initializing downloader...")
 
 
 
 
 
 
44
  loader = instaloader.Instaloader(
45
  download_videos=True,
46
  download_video_thumbnails=False,
47
  download_geotags=False,
48
  download_comments=False,
49
  save_metadata=False,
50
- compress_json=False,
51
- max_connection_attempts=3,
52
- dirname_pattern="reels/{target}" # Explicitly set download directory
53
  )
54
 
55
  try:
 
56
  if INSTAGRAM_USERNAME and INSTAGRAM_PASSWORD:
57
- st.info(f"Attempting to login as {INSTAGRAM_USERNAME}...")
58
  loader.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
59
  st.success("Login successful!")
60
  else:
61
- st.error("Instagram credentials not found")
62
- return "Missing credentials"
63
-
64
- # Extract shortcode
65
- shortcode = url.strip('/').split('/')[-1]
66
- if not shortcode:
67
- shortcode = url.strip('/').split('/')[-2]
68
-
69
- st.info(f"Attempting to download reel with shortcode: {shortcode}")
70
-
71
- # Create download directory
72
- os.makedirs(f"reels/{shortcode}", exist_ok=True)
73
 
74
- # Get absolute path
75
- abs_download_path = os.path.abspath(f"reels/{shortcode}")
76
- st.info(f"Download directory: {abs_download_path}")
 
77
 
78
- # Download the post
79
  st.info("Fetching post metadata...")
80
  post = instaloader.Post.from_shortcode(loader.context, shortcode)
81
 
82
- st.info(f"Starting download of post type: {post.typename}")
83
- loader.download_post(post, target=shortcode)
84
 
85
- # Verify the download
86
  success, result = verify_download(shortcode)
87
-
88
  if success:
89
- return f"""Download completed:
90
- - File: {result['path']}
91
- - Size: {result['size']}
92
- - File exists: {result['exists']}"""
93
  else:
94
- return f"Download failed: {result}"
95
-
96
  except instaloader.exceptions.InstaloaderException as e:
97
- return f"Instagram error: {str(e)}\nCurrent working directory: {os.getcwd()}"
98
  except Exception as e:
99
- return f"An unexpected error occurred: {str(e)}"
100
 
101
  def main():
102
- st.set_page_config(page_title="Instagram Reel Downloader", page_icon="📱")
 
 
 
103
 
104
  st.title('📱 Instagram Reel Downloader')
105
 
106
- # Show current working directory
107
- st.text(f"Working directory: {os.getcwd()}")
108
-
109
  # Input for Reel URL
110
  url = st.text_input('Enter the Instagram Reel URL',
111
- placeholder='https://www.instagram.com/reel/...')
 
 
 
 
 
 
 
112
 
113
  # Download button
114
  if st.button('Download Reel', type='primary'):
115
  if url:
116
  with st.spinner('Downloading reel...'):
117
  result = download_reel(url)
118
- st.text(result) # Show detailed result
119
 
120
- # List contents of download directory
121
- if "reels" in os.listdir():
122
- st.text("Contents of reels directory:")
123
  for item in os.listdir("reels"):
124
- st.text(f"- {item}")
125
  else:
126
  st.warning('Please enter a URL.')
127
 
 
2
  import instaloader
3
  import os
4
  from dotenv import load_dotenv
5
+ import re
6
+ from urllib.parse import urlparse, unquote
7
 
8
  # Load environment variables
9
  load_dotenv()
 
12
  INSTAGRAM_USERNAME = os.getenv('INSTAGRAM_USERNAME')
13
  INSTAGRAM_PASSWORD = os.getenv('INSTAGRAM_PASSWORD')
14
 
15
+ def clean_url(url):
16
+ """Clean Instagram URL and extract shortcode"""
17
+ try:
18
+ # Remove query parameters and fragments
19
+ cleaned_url = url.split('?')[0].split('#')[0].strip('/')
20
+
21
+ # Extract shortcode using regex
22
+ patterns = [
23
+ r'instagram.com/reel/([A-Za-z0-9_-]+)',
24
+ r'instagram.com/p/([A-Za-z0-9_-]+)',
25
+ r'/([A-Za-z0-9_-]{11})[/]?$'
26
+ ]
27
+
28
+ for pattern in patterns:
29
+ match = re.search(pattern, cleaned_url)
30
+ if match:
31
+ return match.group(1)
32
+
33
+ # If patterns don't match, try getting the last segment
34
+ segments = cleaned_url.split('/')
35
+ if segments:
36
+ last_segment = segments[-1]
37
+ if len(last_segment) >= 11: # Instagram shortcodes are usually 11 chars or longer
38
+ return last_segment
39
+
40
+ return None
41
+ except Exception as e:
42
+ st.error(f"Error cleaning URL: {str(e)}")
43
+ return None
44
+
45
  def verify_download(shortcode):
46
  """Verify that files were actually downloaded"""
47
+ download_path = os.path.join('reels', shortcode)
48
 
49
  # Check if directory exists
50
  if not os.path.exists(download_path):
51
  return False, "Download directory not found"
52
 
53
+ # List all files in directory
54
+ files = os.listdir(download_path)
55
+ st.info(f"Files in download directory: {files}")
56
+
57
+ # Look for video files
58
+ video_files = [f for f in files if f.endswith('.mp4')]
59
 
60
  if video_files:
61
+ video_path = os.path.join(download_path, video_files[0])
 
62
  file_size = os.path.getsize(video_path)
63
  return True, {
64
  'path': video_path,
65
  'size': f"{file_size / (1024*1024):.2f} MB",
66
  'exists': os.path.exists(video_path)
67
  }
68
+ return False, "No video files found"
69
 
70
  def download_reel(url):
71
  """Download Instagram reel"""
72
  if not url:
73
  return "Please enter a URL"
74
 
75
+ # Clean URL and extract shortcode
76
+ shortcode = clean_url(url)
77
+ if not shortcode:
78
+ return "Could not extract valid shortcode from URL"
79
+
80
+ st.info(f"Extracted shortcode: {shortcode}")
81
+
82
+ # Initialize loader
83
  loader = instaloader.Instaloader(
84
  download_videos=True,
85
  download_video_thumbnails=False,
86
  download_geotags=False,
87
  download_comments=False,
88
  save_metadata=False,
89
+ compress_json=False
 
 
90
  )
91
 
92
  try:
93
+ # Login
94
  if INSTAGRAM_USERNAME and INSTAGRAM_PASSWORD:
95
+ st.info(f"Logging in as {INSTAGRAM_USERNAME}...")
96
  loader.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
97
  st.success("Login successful!")
98
  else:
99
+ return "Missing Instagram credentials"
 
 
 
 
 
 
 
 
 
 
 
100
 
101
+ # Create clean download directory
102
+ download_path = os.path.join('reels', shortcode)
103
+ os.makedirs(download_path, exist_ok=True)
104
+ st.info(f"Download directory: {os.path.abspath(download_path)}")
105
 
106
+ # Download post
107
  st.info("Fetching post metadata...")
108
  post = instaloader.Post.from_shortcode(loader.context, shortcode)
109
 
110
+ st.info("Starting download...")
111
+ loader.download_post(post, target=download_path)
112
 
113
+ # Verify download
114
  success, result = verify_download(shortcode)
 
115
  if success:
116
+ return f"Download successful!\nFile: {result['path']}\nSize: {result['size']}"
 
 
 
117
  else:
118
+ return f"Download verification failed: {result}"
119
+
120
  except instaloader.exceptions.InstaloaderException as e:
121
+ return f"Instagram error: {str(e)}"
122
  except Exception as e:
123
+ return f"Unexpected error: {str(e)}"
124
 
125
  def main():
126
+ st.set_page_config(
127
+ page_title="Instagram Reel Downloader",
128
+ page_icon="📱"
129
+ )
130
 
131
  st.title('📱 Instagram Reel Downloader')
132
 
 
 
 
133
  # Input for Reel URL
134
  url = st.text_input('Enter the Instagram Reel URL',
135
+ placeholder='https://www.instagram.com/reel/XXXXXXXXXXXX')
136
+
137
+ if url:
138
+ shortcode = clean_url(url)
139
+ if shortcode:
140
+ st.info(f"Detected shortcode: {shortcode}")
141
+ else:
142
+ st.warning("Could not detect valid shortcode from URL")
143
 
144
  # Download button
145
  if st.button('Download Reel', type='primary'):
146
  if url:
147
  with st.spinner('Downloading reel...'):
148
  result = download_reel(url)
149
+ st.write(result)
150
 
151
+ # Show directory contents
152
+ if os.path.exists("reels"):
153
+ st.write("Contents of reels directory:")
154
  for item in os.listdir("reels"):
155
+ st.write(f"- {item}")
156
  else:
157
  st.warning('Please enter a URL.')
158