|
import requests |
|
import shutil,os,re |
|
|
|
|
|
def search_pexels(keyword, api_key, orientation='potrait', size='medium', endpoint='videos', num_pages=1): |
|
|
|
if orientation not in ['potrait', 'landscape', 'square']: |
|
raise Exception("Error! orientation must be one of {'square', 'landscape', 'potrait'}") |
|
|
|
if size not in ['medium', 'small', 'large']: |
|
raise Exception("Error! size must be one of ['medium', 'small', 'large']") |
|
|
|
base_url = 'https://api.pexels.com/' |
|
|
|
headers = { |
|
'Authorization': f'{api_key}' |
|
} |
|
|
|
url = f'{base_url}{endpoint}/search?query={keyword}&per_page={num_pages}&orientation={orientation}&size={size}' |
|
|
|
|
|
response = requests.get(url, headers=headers) |
|
|
|
|
|
if response.status_code == 200: |
|
data = response.json() |
|
return data |
|
else: |
|
print(f'Error: {response.status_code}') |
|
|
|
|
|
|
|
def download_video(data, parent_path, height, width, i): |
|
for x in data['videos'][0]['video_files'] : |
|
|
|
if width != None and x['width'] < width: |
|
continue |
|
if height != None and x['height'] < height : |
|
continue |
|
|
|
vid = x |
|
print(vid['link']) |
|
with open(f"{os.path.join(parent_path,str(i) + '_' + str(vid['id']))}.mp4", 'bw') as f: |
|
f.write(requests.get(vid['link']).content) |
|
print("Sucessfully saved video in", os.path.join(parent_path,str(i) + '_' + str(vid['id'])) + '.mp4') |
|
break |
|
|
|
|
|
|
|
def generate_videos(product, api_key, height=None, width=None): |
|
prod = product.replace(" ", "_") |
|
|
|
try : |
|
|
|
|
|
sentences = llm_chain.run(product) |
|
print('Sentence :', sentences) |
|
|
|
|
|
sentences = [x.strip() for x in re.split(r'\d+\.', sentences) if len(x) > 6] |
|
|
|
|
|
|
|
if os.path.exists(prod): |
|
shutil.rmtree(prod) |
|
os.mkdir(prod) |
|
|
|
|
|
print("Keyword :") |
|
for i,s in enumerate(sentences): |
|
keyword = sum_llm_chain.run(s) |
|
print(i+1, ":", keyword) |
|
data = search_pexels(keyword, api_key, ) |
|
download_video(data, prod, height, width, i) |
|
|
|
print("Success! videos has been generated") |
|
except Exception as e : |
|
print("Error! Failed generating videos") |
|
print(e) |
|
|
|
return prod, sentences |
|
|