Download app.py from Fred808/Insta-req: direct link, hf CLI and curl.
- Browser
- Download file 2.45 kB
-
https://huggingface.co/spaces/Fred808/Insta-req/resolve/main/app.py
- Command line
-
hf download hf://spaces/Fred808/Insta-req/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Fred808/Insta-req/resolve/main/app.py
2.45 kB
| from fastapi import FastAPI, HTTPException | |
| import instaloader | |
| from pydantic import BaseModel | |
| from typing import List | |
| import os | |
| app = FastAPI() | |
| # Pydantic model for the response | |
| class PostResponse(BaseModel): | |
| caption: str | |
| likes: int | |
| comments: int | |
| posted_on: str | |
| image_url: str | |
| # Define proxy settings (replace with your proxy details) | |
| PROXY_URL = "http://p.webshare.io:5157:kknqfmqe:0wyvognccou8" | |
| async def fetch_instagram_posts(username: str, max_posts: int = 10): | |
| """ | |
| Fetch Instagram posts from a public profile using a proxy. | |
| Args: | |
| username (str): The username of the Instagram profile. | |
| max_posts (int): The maximum number of posts to fetch (default is 10). | |
| Returns: | |
| List[PostResponse]: A list of posts with caption, likes, comments, posted_on, and image_url. | |
| """ | |
| # Initialize Instaloader with proxy configuration | |
| L = instaloader.Instaloader() | |
| L.context.proxy = PROXY_URL | |
| try: | |
| # Load the profile | |
| print(f"Fetching posts for user: {username}") | |
| profile = instaloader.Profile.from_username(L.context, username) | |
| # List to store posts | |
| posts = [] | |
| # Counter to limit the number of posts | |
| count = 0 | |
| # Loop through the posts | |
| for post in profile.get_posts(): | |
| post_data = { | |
| "caption": post.caption or "No Caption", | |
| "likes": post.likes, | |
| "comments": post.comments, | |
| "posted_on": post.date_utc.strftime("%Y-%m-%d %H:%M:%S"), | |
| "image_url": post.url, | |
| } | |
| posts.append(post_data) | |
| # Increment the counter | |
| count += 1 | |
| if count >= max_posts: | |
| break | |
| print(f"\nFetched {count} posts for user: {username}.") | |
| return posts | |
| except instaloader.exceptions.ProfileNotExistsException: | |
| raise HTTPException(status_code=404, detail=f"Profile '{username}' does not exist.") | |
| except instaloader.exceptions.ConnectionException: | |
| raise HTTPException(status_code=503, detail="Unable to connect to Instagram. Check your internet connection.") | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Unexpected error: {e}") | |
| # Run the FastAPI app | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=8000) | |