Spaces:
duan98
/
Sleeping

TDN-M commited on
Commit
b9dc6c1
verified
1 Parent(s): 113498f

Update components/pexels.py

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