|
|
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"] |
|
|
|
|
|
|
|
|
|
|
|
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", |
|
|
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" |
|
|
|
|
|
if True: |
|
|
|
|
|
PEXELS_API_KEY = '563492ad6f917000010000011b2f873942744900a033f732a56ae4b7' |
|
|
translator = Translator() |
|
|
search_term = translator.translate(palabra, dest='en').text |
|
|
print(search_term) |
|
|
|
|
|
api_url = f'https://api.pexels.com/videos/search?query={search_term}&orientation=portrait&per_page=3&locale=en-US' |
|
|
print(api_url) |
|
|
|
|
|
headers = {'Authorization': PEXELS_API_KEY} |
|
|
|
|
|
|
|
|
response = requests.get(api_url, headers=headers) |
|
|
|
|
|
|
|
|
if response.status_code == 200: |
|
|
|
|
|
results = response.json()['videos'] |
|
|
|
|
|
|
|
|
if len(results)>0: |
|
|
ancho = 1 |
|
|
ancho = ancho - 1 |
|
|
numero = random.randint(0,ancho) |
|
|
print('el numero es ',numero) |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
results2 = response2.json()['photos'] |
|
|
|
|
|
if len(results2)>0: |
|
|
ancho = 1 |
|
|
ancho = ancho - 1 |
|
|
numero = random.randint(0,ancho) |
|
|
print('el numero es ',numero) |
|
|
|
|
|
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) |
|
|
|
|
|
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] |
|
|
|
|
|
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] |
|
|
|
|
|
if len(tema)>0: |
|
|
palabraclave = tema |
|
|
else: |
|
|
palabraclave = frases[0] |
|
|
print(palabraclave) |
|
|
resultado = buscar(palabraclave,category) |
|
|
if resultado!=None: |
|
|
velocidadhabla = 15 |
|
|
print(len(lineaf)) |
|
|
duracion = len(lineaf)/velocidadhabla |
|
|
print(resultado) |
|
|
try: |
|
|
audiofile = generaraudio2(lineaf) |
|
|
clip1 = VideoFileClip(generate_subtitled_video(resultado,lineaf)) |
|
|
audio = AudioFileClip(audiofile) |
|
|
|
|
|
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.audio = audio |
|
|
clips.append(final_clip) |
|
|
except Exception as e: |
|
|
print(f'Ocurrió un error: {e}') |
|
|
clip = ImageClip(resultado) |
|
|
|
|
|
clip = clip.set_duration(5) |
|
|
|
|
|
clip.write_videofile('videoxd.mp4', fps=24) |
|
|
audiofile = generaraudio2(lineaf) |
|
|
clip1 = VideoFileClip(generate_subtitled_video('videoxd.mp4',lineaf)) |
|
|
audio = AudioFileClip(audiofile) |
|
|
|
|
|
duracionTotal = duracionTotal + duracion |
|
|
subclip = clip1.subclip(0, duracion) |
|
|
resized_clip = subclip.resize((1080, 1920)) |
|
|
video = resized_clip.resize(height=1920) |
|
|
final_clip = video |
|
|
|
|
|
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: |
|
|
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() |