import io import requests import os import re import uuid from PIL import Image, ImageEnhance from fastapi import APIRouter, Depends from fastapi.responses import StreamingResponse from fastapi import UploadFile from fastapi.responses import JSONResponse from fastapi import HTTPException from dotenv import load_dotenv from pydantic import BaseModel from pymongo import MongoClient from models import * from driver import Driver from huggingface_hub import InferenceClient from selenium.webdriver.common.by import By from selenium.webdriver.support.expected_conditions import ( presence_of_element_located, visibility_of_element_located) from selenium.webdriver.support.wait import WebDriverWait class InstagramX(BaseModel): link: str router = APIRouter() def obtain_ids(user: str): response = requests.get("https://www.instagram.com/" + user) appid = re.search(r'appId":"(\d*)', response.text)[1] serverid = re.search(r'server_revision":(\d*)', response.text)[1] return appid, serverid @router.post("/akeno/instagram/reels", response_model=SuccessResponse, responses={422: {"model": SuccessResponse}}) async def instagram_reels(payload: InstagramX): isInstagramLink = lambda link: bool( re.match(r"^https?://(?:www\.)?instagram\.com/reel/", link) ) if not isInstagramLink(payload.link): return SuccessResponse( status="False", randydev={"error": "Give a valid Instagram reels link."} ) try: driver, error_message = Driver.get() if not driver: return SuccessResponse( status="False", randydev={"error": error_message} ) driver.get(payload.link) wait = WebDriverWait(driver, 10) element = wait.until(presence_of_element_located((By.TAG_NAME, "video"))) reels_url = element.get_attribute("src") driver.quit() if reels_url: binary_content = requests.get(reels_url).content file_name = f"reels_{int(time.time())}.mp4" with open(file_name, "wb") as file: file.write(binary_content) with open(file_name, "rb") as video: encoded_string = base64.b64encode(video.read()).decode('utf-8') os.remove(file_name) return SuccessResponse( status="True", randydev={"video_data": encoded_string} ) except Exception as e: return SuccessResponse( status="False", randydev={"error": f"An error occurred: {str(e)}"} )