Skip to content

Commit

Permalink
Improve Search
Browse files Browse the repository at this point in the history
  • Loading branch information
radry authored Feb 8, 2024
1 parent d84ce40 commit cbe86bf
Showing 1 changed file with 27 additions and 19 deletions.
46 changes: 27 additions & 19 deletions Backend/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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

0 comments on commit cbe86bf

Please sign in to comment.