CoolFace
Apppublic

hitmanblade/PowerPoint-AI

sourceHugging Facemitupdated 2y agoView on Hugging Face
9likes
image_search.py149 linesDownload Raw Back to helpers
1"""2Search photos using Pexels API.3"""4import logging5import os6import random7from io import BytesIO8from typing import Union, Tuple, Literal9from urllib.parse import urlparse, parse_qs10 11import requests12from dotenv import load_dotenv13 14 15load_dotenv()16 17 18REQUEST_TIMEOUT = 1219MAX_PHOTOS = 320 21 22# Only show errors23logging.getLogger('urllib3').setLevel(logging.ERROR)24# Disable all child loggers of urllib3, e.g. urllib3.connectionpool25# logging.getLogger('urllib3').propagate = True26 27 28 29def search_pexels(30        query: str,31        size: Literal['small', 'medium', 'large'] = 'medium',32        per_page: int = MAX_PHOTOS33) -> dict:34    """35    Searches for images on Pexels using the provided query.36 37    This function sends a GET request to the Pexels API with the specified search query38    and authorization header containing the API key. It returns the JSON response from the API.39 40    [2024-08-31] Note:41    `curl` succeeds but API call via Python `requests` fail. Apparently, this could be due to42    Cloudflare (or others) blocking the requests, perhaps identifying as Web-scraping. So,43    changing the user-agent to Firefox.44    https://stackoverflow.com/a/74674276/14702145    https://stackoverflow.com/a/51268523/14702146    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox#linux47 48    :param query: The search query for finding images.49    :param size: The size of the images: small, medium, or large.50    :param per_page: No. of results to be displayed per page.51    :return: The JSON response from the Pexels API containing search results.52    :raises requests.exceptions.RequestException: If the request to the Pexels API fails.53    """54 55    url = 'https://api.pexels.com/v1/search'56    headers = {57        'Authorization': os.getenv('PEXEL_API_KEY'),58        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0',59    }60    params = {61        'query': query,62        'size': size,63        'page': 1,64        'per_page': per_page65    }66    response = requests.get(url, headers=headers, params=params, timeout=REQUEST_TIMEOUT)67    response.raise_for_status()  # Ensure the request was successful68 69    return response.json()70 71 72def get_photo_url_from_api_response(73        json_response: dict74) -> Tuple[Union[str, None], Union[str, None]]:75    """76    Return a randomly chosen photo from a Pexels search API response. In addition, also return77    the original URL of the page on Pexels.78 79    :param json_response: The JSON response.80    :return: The selected photo URL and page URL or `None`.81    """82 83    page_url = None84    photo_url = None85 86    if 'photos' in json_response:87        photos = json_response['photos']88 89        if photos:90            photo_idx = random.choice(list(range(MAX_PHOTOS)))91            photo = photos[photo_idx]92 93            if 'url' in photo:94                page_url = photo['url']95 96            if 'src' in photo:97                if 'large' in photo['src']:98                    photo_url = photo['src']['large']99                elif 'original' in photo['src']:100                    photo_url = photo['src']['original']101 102    return photo_url, page_url103 104 105def get_image_from_url(url: str) -> BytesIO:106    """107    Fetches an image from the specified URL and returns it as a BytesIO object.108 109    This function sends a GET request to the provided URL, retrieves the image data,110    and wraps it in a BytesIO object, which can be used like a file.111 112    :param url: The URL of the image to be fetched.113    :return: A BytesIO object containing the image data.114    :raises requests.exceptions.RequestException: If the request to the URL fails.115    """116 117    headers = {118        'Authorization': os.getenv('PEXEL_API_KEY'),119        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0',120    }121    response = requests.get(url, headers=headers, stream=True, timeout=REQUEST_TIMEOUT)122    response.raise_for_status()123    image_data = BytesIO(response.content)124 125    return image_data126 127 128def extract_dimensions(url: str) -> Tuple[int, int]:129    """130    Extracts the height and width from the URL parameters.131 132    :param url: The URL containing the image dimensions.133    :return: A tuple containing the width and height as integers.134    """135    parsed_url = urlparse(url)136    query_params = parse_qs(parsed_url.query)137    width = int(query_params.get('w', [0])[0])138    height = int(query_params.get('h', [0])[0])139 140    return width, height141 142 143if __name__ == '__main__':144    print(145        search_pexels(146            query='people'147        )148    )149