File size: 12,191 Bytes
fde6ce9 c3b7bd1 fde6ce9 c3b7bd1 fde6ce9 c3b7bd1 fde6ce9 c3b7bd1 fde6ce9 1c940e6 fde6ce9 1c940e6 fde6ce9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 |
import pixabay.core
import glob
from moviepy.editor import VideoFileClip, ImageClip, concatenate_videoclips, AudioFileClip,CompositeVideoClip, TextClip
import requests
import random
import moviepy.editor as mp
import gradio as gr
import time
import re
import os
from googletrans import Translator
import ffmpeg
import json
import openai
openai.api_key = os.environ["API_KEY"] # 首先要有apikey
#openai.api_key = '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'
messages = [{"role": "system", "content": "eres una mano derecha"}]
def chatgpt(content, temperature=0.8):
global messages
print(f'ask:{content}')
messages.append({"role": "user", "content": content})
time.sleep(1)
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0301", # 或者 gpt-3.5-turbo-0301
messages=messages,
temperature=temperature,
max_tokens=1000,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
)
except Exception as e:
messages = [{"role": "system", "content": "eres una mano derecha"}]
return 'Este mensaje interactivo ha alcanzado el límite superior, el token se ha borrado, vuelva a ingresar'
messages.append(json.loads(str(response.choices[0].message)))
print(f'answer:{response.choices[0].message.content}')
resulado = response.choices[0].message.content
resulado = resulado.replace('.','')
return resulado
pixabayapi = ''
def generaraudio2(texto):
nombre = s=re.sub('[^A-Za-z0-9]+', '',texto)
nombre = nombre.strip()
archivo = 'es_'+nombre+'.wav'
print(archivo)
existe = glob.glob(archivo)
texto = texto.lower()
texto = texto.replace('html5','hache te eme ele cinco')
texto = texto.replace('html','hache te eme ele')
texto = texto.replace('pdf','pe de eefe')
texto = texto.replace('bit.ly','bit punto li!, eslach,')
texto = texto.replace('.',',')
texto = texto.replace('1','uno')
texto = texto.replace('2','dos')
texto = texto.replace('3','tres')
texto = texto.replace('4','cuatro')
texto = texto.replace('5','cinco')
texto = texto.replace('6','seis')
texto = texto.replace('7','siete')
texto = texto.replace('8','ocho')
texto = texto.replace('9','nueve')
if not existe:
response = requests.post("https://iricardoxd-texto-a-voz-aws.hf.space/api/predict", json={
"data": [
texto
]},headers={'Content-Type':'application/json','Authorization': 'Bearer {}'.format('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')}).json()
data = response["data"]
print(response['data'][0]['name'])
time.sleep(5)
response = requests.get("https://iricardoxd-texto-a-voz-aws.hf.space/file="+response['data'][0]['name'],headers={'Content-Type':'application/json','Authorization': 'Bearer {}'.format('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')})
if response.status_code == 200:
open(archivo, 'wb').write(response.content)
print('downloaded')
else:
print(response.status_code)
return archivo
import requests
import shutil
def buscar(palabra,category):
xd = palabra.split()
xdfile = '_'.join(xd)
xdfile = xdfile.replace('/','').replace('"','').replace('.','').replace('!','').replace('@','').replace('\\','').replace('\n','').replace('\rn','').replace(':','').replace(',','')
archivo = category+'_'+xdfile+".mp4"
#existe = glob.glob(archivo)
if True:#not existe:
# Establece tu clave de API de Pexels
PEXELS_API_KEY = '563492ad6f917000010000011b2f873942744900a033f732a56ae4b7'
translator = Translator()
search_term = translator.translate(palabra, dest='en').text#blob.translate(to='en')
print(search_term)
# Crea el URL de la API
api_url = f'https://api.pexels.com/videos/search?query={search_term}&orientation=portrait&per_page=3&locale=en-US'
print(api_url)
# Establece los encabezados de la solicitud
headers = {'Authorization': PEXELS_API_KEY}
# Realiza la solicitud a la API
response = requests.get(api_url, headers=headers)
# Verifica si la solicitud fue exitosa
if response.status_code == 200:
# Obtiene los resultados de la búsqueda
results = response.json()['videos']
#print(results)
# Itera sobre los resultados
if len(results)>0:
ancho = 1
ancho = ancho - 1
numero = random.randint(0,ancho)
print('el numero es ',numero)
# Obtiene el URL del video
for videox in results[numero]['video_files']:
if videox['height']==1920:
video_url = videox['link']
else:
if videox['quality']=='hd':
video_url = videox['link']
else:
video_url = results[numero]['video_files'][0]['link']
print('el video es',video_url)
# Descarga el video
with requests.get(video_url, stream=True) as r:
with open(archivo, 'wb') as f:
shutil.copyfileobj(r.raw, f)
print(f'Descargado video {numero} de {len(results)}')
else:
api_url2 = f'https://api.pexels.com/v1/search?query={search_term}&per_page=1&orientation=portrait&locale=en-US'
print(api_url2)
response2 = requests.get(api_url2, headers=headers)
if response2.status_code == 200:
# Obtiene los resultados de la búsqueda
results2 = response2.json()['photos']
# Itera sobre los resultados
if len(results2)>0:
ancho = 1
ancho = ancho - 1
numero = random.randint(0,ancho)
print('el numero es ',numero)
# Obtiene el URL del video
video_url = results2[numero]['src']['portrait']
imagen = results2[numero]['src']['original']
filex = imagen.split('/')
print(' imagen es',video_url)
x=len(filex)-1
archivo=filex[x]
print(' imagen es x ',archivo)
# Descarga el video
with requests.get(video_url, stream=True) as r:
with open(archivo, 'wb') as f:
shutil.copyfileobj(r.raw, f)
print(f'Descargado imagen {numero} de {len(results)}')
else:
archivo='doctor.mp4'
else:
print('Error al realizar la solicitud a la API')
return archivo
def buscarsustantivo(frase):
if frase !='':
prompt ='Respond only with one word of videos availables in pixels.com that best expresses the English phrase: '+frase
return chatgpt(prompt)
def combinar(frase, api_pixabay):
global pixabayapi
pixabayapi = '38938115-4ffafdfccf94d14e4d35899f5'
category="travel"
clips = []
palabras = frase.split(' ')
palabras_frases = frase.split('.')
frases = []
i = 0
linea = ''
for palabra in palabras:
i = i + 1
linea = linea + ' ' + palabra
escena_palabras = random.randint(1, 5)
if i>escena_palabras or '.' in linea or '?' in linea or '!' in linea:
i=0
frases.append(linea)
linea = ''
if linea !='':
frases.append(linea)
duracionTotal = 0
for lineaf in frases:
tema = buscarsustantivo(lineaf)
palabras_de_tema = tema.split(' ')
if len(palabras_de_tema)>1:
tema = palabras_de_tema[0]
#for tema in temas:
if len(tema)>0:
palabraclave = tema
else:
palabraclave = frases[0]
print(palabraclave)
resultado = buscar(palabraclave,category)
if(resultado=='lv_0_20230901171552.mp4'):
tema = buscarsustantivo(lineaf)
palabras_de_tema = tema.split(' ')
if len(palabras_de_tema)>1:
tema = palabras_de_tema[0]
#for tema in temas:
if len(tema)>0:
palabraclave = tema
else:
palabraclave = frases[0]
print(palabraclave)
resultado = buscar(palabraclave,category)
if resultado!=None:
velocidadhabla = 15#catacteres por segundos 18 teresa, 22 huggie
print(len(lineaf))
duracion = len(lineaf)/velocidadhabla
print(resultado)
try:
audiofile = generaraudio2(lineaf)
clip1 = VideoFileClip(generate_subtitled_video(resultado,lineaf))
audio = AudioFileClip(audiofile)
#duracion = audio.duration
duracionTotal = duracionTotal + duracion
subclip = clip1.subclip(0, duracion)
resized_clip = subclip.resize((1080, 1920))
video = resized_clip.resize(height=1920)
final_clip = video#final_clip = video.crop(x1=1166.6,y1=0,x2=2246.6,y2=1920)
final_clip.audio = audio
clips.append(final_clip)
except Exception as e:
print(f'Ocurrió un error: {e}')
clip = ImageClip(resultado)
# Establece la duración del clip en segundos
clip = clip.set_duration(5)
# Guarda el clip como un archivo de video
clip.write_videofile('videoxd.mp4', fps=24)
audiofile = generaraudio2(lineaf)
clip1 = VideoFileClip(generate_subtitled_video('videoxd.mp4',lineaf))#generate_subtitled_video('videoxd.mp4',audiofile,lineaf))
audio = AudioFileClip(audiofile)
#duracion = audio.duration
duracionTotal = duracionTotal + duracion
subclip = clip1.subclip(0, duracion)
resized_clip = subclip.resize((1080, 1920))
video = resized_clip.resize(height=1920)
final_clip = video#final_clip = video.crop(x1=1166.6,y1=0,x2=2246.6,y2=1920)
#final_clip.audio = audio
clips.append(final_clip)
filename=palabras_frases[0]+'.mp4'
if len(clips)>0:
audiofilefinal = generaraudio2(frase)
final_clip = concatenate_videoclips(clips)
final_clip.audio = AudioFileClip(audiofilefinal)
final_clip.write_videofile(filename)
print('listo video')
final = filename
html= '<a href="file/'+final+'" download>Descargar video</a><a href="file/final.mp4" download>Descargar video</a>'
image=subir(filename,palabras_frases[0])
return (final,html,image)
def generate_subtitled_video(video, transcript):
input = ffmpeg.input(video)
output = ffmpeg.output(input, 'srt'+video, vf="drawtext=text='"+transcript+"':fontcolor=white:fontsize=24:box=1:boxcolor=black@0.5:boxborderw=5:x=(w-text_w)/2:y=((h-text_h-line_h)/9)*10")
output.run(quiet=True, overwrite_output=True)
video_with_subs = 'srt'+video
print(video_with_subs)
return video_with_subs
def subir(video,descripcion):
from upload import upload_videos
from auth import AuthBackend
videos = [
{
'video': video,
'description': descripcion
}
]
auth = AuthBackend(cookies='cookies.txt')
failed_videos = upload_videos(videos=videos, auth=auth)
for video in failed_videos: # each input video object which failed
print(f'{video["video"]} with description "{video["description"]}" failed')
demo = gr.Interface(fn=combinar, inputs=["text","text"], outputs=["video","html",gr.Image(type="pil", height=360, width=540)])
demo.launch() |