jonathanjordan21 commited on
Commit
53b9cd0
1 Parent(s): 7ab17a0

Create components/pexels.py

Browse files
Files changed (1) hide show
  1. components/pexels.py +82 -0
components/pexels.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import shutil,os,re
3
+
4
+ # Searching for the videos
5
+ def search_pexels(keyword, api_key, orientation='potrait', size='medium', endpoint='videos', num_pages=1):
6
+
7
+ if orientation not in ['potrait', 'landscape', 'square']:
8
+ raise Exception("Error! orientation must be one of {'square', 'landscape', 'potrait'}")
9
+
10
+ if size not in ['medium', 'small', 'large']:
11
+ raise Exception("Error! size must be one of ['medium', 'small', 'large']")
12
+
13
+ base_url = 'https://api.pexels.com/'
14
+
15
+ headers = {
16
+ 'Authorization': f'{api_key}'
17
+ }
18
+
19
+ url = f'{base_url}{endpoint}/search?query={keyword}&per_page={num_pages}&orientation={orientation}&size={size}'
20
+
21
+
22
+ response = requests.get(url, headers=headers)
23
+
24
+ # Check if request was successful (status code 200)
25
+ if response.status_code == 200:
26
+ data = response.json()
27
+ return data
28
+ else:
29
+ print(f'Error: {response.status_code}')
30
+
31
+
32
+ # Video download function
33
+ def download_video(data, parent_path, height, width, i):
34
+ for x in data['videos'][0]['video_files'] :
35
+
36
+ if width != None and x['width'] < width:
37
+ continue
38
+ if height != None and x['height'] < height :
39
+ continue
40
+
41
+ vid = x
42
+ print(vid['link'])
43
+ with open(f"{os.path.join(parent_path,str(i) + '_' + str(vid['id']))}.mp4", 'bw') as f:
44
+ f.write(requests.get(vid['link']).content)
45
+ print("Sucessfully saved video in", os.path.join(parent_path,str(i) + '_' + str(vid['id'])) + '.mp4')
46
+ break
47
+
48
+
49
+ # Utilizing the LLMs to find the relevant videos
50
+ def generate_videos(product, api_key, height=None, width=None):
51
+ prod = product.replace(" ", "_")
52
+
53
+ try :
54
+ # Split the paragraph by sentences
55
+
56
+ sentences = llm_chain.run(product)
57
+ print('Sentence :', sentences)
58
+
59
+ # sentences = sentences.split(".")[:-1]
60
+ sentences = [x.strip() for x in re.split(r'\d+\.', sentences) if len(x) > 6]
61
+
62
+
63
+ # Create directory with the product's name
64
+ if os.path.exists(prod):
65
+ shutil.rmtree(prod)
66
+ os.mkdir(prod)
67
+
68
+ # Generate video for every sentence
69
+ print("Keyword :")
70
+ for i,s in enumerate(sentences):
71
+ keyword = sum_llm_chain.run(s)
72
+ print(i+1, ":", keyword)
73
+ data = search_pexels(keyword, api_key, )
74
+ download_video(data, prod, height, width, i)
75
+
76
+ print("Success! videos has been generated")
77
+ except Exception as e :
78
+ print("Error! Failed generating videos")
79
+ print(e)
80
+
81
+ return prod, sentences
82
+