Chrunos commited on
Commit
ab6b560
·
verified ·
1 Parent(s): 46f4432

Delete api.py

Browse files
Files changed (1) hide show
  1. api.py +0 -124
api.py DELETED
@@ -1,124 +0,0 @@
1
- # api.py
2
- from fastapi import FastAPI, HTTPException
3
- from pydantic import BaseModel
4
- import instaloader
5
- import os
6
- from dotenv import load_dotenv
7
- import re
8
- from typing import Optional, List
9
- import shutil
10
-
11
- # Load environment variables
12
- load_dotenv()
13
-
14
- # Get credentials from environment variables
15
- INSTAGRAM_USERNAME = os.getenv('INSTAGRAM_USERNAME')
16
- INSTAGRAM_PASSWORD = os.getenv('INSTAGRAM_PASSWORD')
17
-
18
- app = FastAPI(title="Instagram Downloader API")
19
-
20
- class DownloadRequest(BaseModel):
21
- url: str
22
-
23
- class DownloadResponse(BaseModel):
24
- success: bool
25
- message: str
26
- download_urls: Optional[List[str]] = None
27
- media_type: Optional[str] = None
28
- shortcode: Optional[str] = None
29
-
30
- def clean_url(url: str) -> Optional[str]:
31
- """Clean Instagram URL and extract shortcode"""
32
- try:
33
- cleaned_url = url.split('?')[0].split('#')[0].strip('/')
34
- patterns = [
35
- r'instagram.com/reel/([A-Za-z0-9_-]+)',
36
- r'instagram.com/p/([A-Za-z0-9_-]+)',
37
- r'instagram.com/stories/([A-Za-z0-9_-]+)',
38
- r'/([A-Za-z0-9_-]{11})[/]?$'
39
- ]
40
-
41
- for pattern in patterns:
42
- match = re.search(pattern, cleaned_url)
43
- if match:
44
- return match.group(1)
45
-
46
- segments = cleaned_url.split('/')
47
- if segments:
48
- return segments[-1]
49
-
50
- return None
51
- except Exception:
52
- return None
53
-
54
- @app.post("/download", response_model=DownloadResponse)
55
- async def download_media(request: DownloadRequest):
56
- try:
57
- # Extract shortcode
58
- shortcode = clean_url(request.url)
59
- if not shortcode:
60
- raise HTTPException(status_code=400, message="Invalid URL format")
61
-
62
- # Initialize loader
63
- loader = instaloader.Instaloader(
64
- download_videos=True,
65
- download_video_thumbnails=False,
66
- download_geotags=False,
67
- download_comments=False,
68
- save_metadata=False,
69
- compress_json=False,
70
- filename_pattern='{shortcode}'
71
- )
72
-
73
- # Login
74
- if not all([INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD]):
75
- raise HTTPException(status_code=500, message="Missing Instagram credentials")
76
-
77
- loader.login(INSTAGRAM_USERNAME, INSTAGRAM_PASSWORD)
78
-
79
- # Create temporary directory
80
- temp_dir = f"temp_{shortcode}"
81
- os.makedirs(temp_dir, exist_ok=True)
82
-
83
- try:
84
- # Get post
85
- post = instaloader.Post.from_shortcode(loader.context, shortcode)
86
-
87
- download_urls = []
88
-
89
- if post.is_video:
90
- # For videos
91
- media_type = "video"
92
- download_urls.append(post.video_url)
93
- else:
94
- # For images
95
- media_type = "image"
96
- if post.typename == "GraphSidecar":
97
- # Multiple images
98
- for node in post.get_sidecar_nodes():
99
- download_urls.append(node.display_url)
100
- else:
101
- # Single image
102
- download_urls.append(post.url)
103
-
104
- return DownloadResponse(
105
- success=True,
106
- message="Media URLs retrieved successfully",
107
- download_urls=download_urls,
108
- media_type=media_type,
109
- shortcode=shortcode
110
- )
111
-
112
- finally:
113
- # Cleanup
114
- if os.path.exists(temp_dir):
115
- shutil.rmtree(temp_dir)
116
-
117
- except instaloader.exceptions.InstaloaderException as e:
118
- raise HTTPException(status_code=400, detail=str(e))
119
- except Exception as e:
120
- raise HTTPException(status_code=500, detail=str(e))
121
-
122
- @app.get("/health")
123
- async def health_check():
124
- return {"status": "healthy"}