From cbe86bf3e57e14c90e3f9b73f3b33915f5004c62 Mon Sep 17 00:00:00 2001 From: radry Date: Thu, 8 Feb 2024 14:37:30 +0100 Subject: [PATCH] Improve Search --- Backend/search.py | 46 +++++++++++++++++++++++++++------------------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/Backend/search.py b/Backend/search.py index 92c3bdd3..acd60dbb 100644 --- a/Backend/search.py +++ b/Backend/search.py @@ -3,7 +3,7 @@ from typing import List from termcolor import colored -def search_for_stock_videos(query: str, api_key: str) -> List[str]: +def search_for_stock_videos(query: str, api_key: str, it: int) -> List[str]: """ Searches for stock videos based on a query. @@ -21,35 +21,43 @@ def search_for_stock_videos(query: str, api_key: str) -> List[str]: } # Build URL - url = f"https://api.pexels.com/videos/search?query={query}&per_page=1" + qurl = f"https://api.pexels.com/videos/search?query={query}&per_page={it}" # Send the request - r = requests.get(url, headers=headers) + r = requests.get(qurl, headers=headers) # Parse the response response = r.json() - # Get first video url - video_urls = [] - video_url = "" + # Parse each video + raw_urls = [] + video_url = [] video_res = 0 try: - video_urls = response["videos"][0]["video_files"] - except Exception: + # loop through each video in the result + for i in range(it): + raw_urls = response["videos"][i]["video_files"] + temp_video_url = "" + + # loop through each url to determine the best quality + for video in raw_urls: + # Check if video has a valid download link + if ".com/external" in video["link"]: + # Only save the URL with the largest resolution + if (video["width"]*video["height"]) > video_res: + temp_video_url = video["link"] + video_res = video["width"]*video["height"] + + # add the url to the return list if it's not empty + if temp_video_url != "": + video_url.append(temp_video_url) + + except Exception as e: print(colored("[-] No Videos found.", "red")) - print(colored(response, "red")) - - # Loop through video urls - for video in video_urls: - # Check if video has a download link - if ".com/external" in video["link"]: - # Only save the URL with the largest resolution - if (video["width"]*video["height"]) > video_res: - video_url = video["link"] - video_res = video["width"]*video["height"] + print(colored(e, "red")) # Let user know - print(colored(f"\t=>{video_url}", "cyan")) + print(colored(f"\t=> \"{query}\" found {len(video_url)} Videos", "cyan")) # Return the video url return video_url