I mean its the biggest commit I ever did (did git add * cause I didn't want to explain all of this It's already so complicated)

This commit is contained in:
Paillat
2023-06-25 16:12:23 +02:00
parent 09c98a460b
commit e676d5851e
14 changed files with 568 additions and 123 deletions

View File

@@ -1,10 +1,6 @@
import openai
import os
import json
from dotenv import load_dotenv
load_dotenv()
from utils.openaicaller import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
with open('prompts/ideas.txt') as f:
prompt = f.read()
f.close()
@@ -25,13 +21,13 @@ async def generate_ideas(path, subject):
exuisting_ideas += f"{idea['title']}\n"
prmpt = prmpt.replace('[existing ideas]', exuisting_ideas)
print(prmpt)
response = await openai.ChatCompletion.acreate(
response = await openai.generate_response(
model="gpt-3.5-turbo",
messages=[
{"role":"user","content":prmpt},
],
)
json_in_str= response['choices'][0]['message']['content']
json_in_str= response['choices'][0]['message']['content'] # type: ignore
json_obj = json.loads(json_in_str)
for idea in json_obj:
ides_json.append(idea)

View File

@@ -2,22 +2,22 @@ import json
import os
import requests
import pysrt
import deepl
import random
from generators.speak import generate_voice, voices
from moviepy.video.VideoClip import ImageClip
from moviepy.editor import VideoFileClip, concatenate_videoclips, CompositeAudioClip, concatenate_audioclips
from moviepy.editor import concatenate_videoclips, CompositeAudioClip, concatenate_audioclips
from moviepy.audio.io.AudioFileClip import AudioFileClip
from moviepy.audio.fx.all import volumex, audio_fadein, audio_fadeout # type: ignore
from dotenv import load_dotenv
load_dotenv()
unsplash_access = os.getenv("UNSPLASH_ACCESS_KEY") or "UNSPLASH_ACCESS_KEY"
unsplash_url = "https://api.unsplash.com/photos/random/?client_id=" + unsplash_access + "&query="
deepl_access = os.getenv("DEEPL_ACCESS_KEY") or "DEEPL_ACCESS_KEY"
translator = deepl.Translator(deepl_access)
from utils.misc import getenv
def prepare(path):
unsplash_access = getenv("unsplash_access_key")
if not unsplash_access:
raise Exception("UNSPLASH_ACCESS_KEY is not set in .env file")
unsplash_url = "https://api.unsplash.com/photos/random/?client_id=" + unsplash_access + "&query="
async def prepare(path):
with open(path + "/script.json", 'r', encoding='utf-8') as f:
script = json.load(f)
f.close()
@@ -94,7 +94,7 @@ def subs(length, total, text, srt, index):
srt.append(sub)
return srt
def mount(path, script):
async def mount(path, script):
if not os.path.exists(path + "/montage.mp4"):
num_slides = len(os.listdir(path + "/audio"))
clips = []

View File

@@ -1,20 +1,20 @@
import os
import openai
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
from utils.openaicaller import openai
with open('prompts/script.txt') as f:
global_prompt = f.read()
f.close()
async def generate_script(title, description):
with open('prompts/script.txt') as f:
prompt = f.read()
f.close()
prompt = global_prompt
prompt = prompt.replace("[title]", title)
prompt = prompt.replace("[description]", description)
response = await openai.ChatCompletion.acreate(
'''response = await openai.ChatCompletion.acreate(
model="gpt-4",
messages=[
{"role":"user","content":prompt}
],
)
return response['choices'][0]['message']['content']
)''' # Deprecated. Use openaicaller.py instead
response = await openai.generate_response(model="gpt-4", messages=[{'role':'user', 'content': prompt}])
return response['choices'][0]['message']['content'] # type: ignore

View File

@@ -1,13 +1,10 @@
import openai
import random
import os
from PIL import Image, ImageDraw, ImageFont
import random
from dotenv import load_dotenv
from PIL import Image
load_dotenv()
from PIL import Image, ImageDraw, ImageFont
openai.api_key = os.getenv("OPENAI_API_KEY")
from utils.openaicaller import openai
'''
Putpose of this file is to generate a miniature of the video.
It has a function that takes a path, title, and description and generates a miniature.
@@ -30,11 +27,12 @@ Answer without anything else, just with the 2 textes. Answer with text1 on the f
Here is the title of the video: [TITLE]
Here is the description of the video: [DESCRIPTION]'''
def rand_gradient(image):
async def rand_gradient(image):
randr = random.SystemRandom().randint(1, 20)
randg = random.SystemRandom().randint(1, 20)
randb = random.SystemRandom().randint(1, 20)
textcolor1 = [0, 0, 0]
textcolor2 = [0, 0, 0]
for i in range(image.size[0]):
for j in range(image.size[1]):
colors = [i//randr, j//randg, i//randb]
@@ -47,20 +45,19 @@ def rand_gradient(image):
image.putpixel((i,j), (colors[0], colors[1], colors[2]))
return image, textcolor1, textcolor2
def generate_miniature(path, title, description):
async def generate_thumbnail(path, title, description):
prmpt = prompt.replace("[TITLE]", title).replace("[DESCRIPTION]", description)
response = openai.ChatCompletion.create(
response = openai.generate_response(
model="gpt-4",
messages=[
{"role":"user","content":prmpt},
],
)
response['choices'][0]['message']['content']
text1 = response['choices'][0]['message']['content'].split("\n")[0]
text2 = response['choices'][0]['message']['content'].split("\n")[1]
generate_image(path, text1, text2)
text1 = response['choices'][0]['message']['content'].split("\n")[0] # type: ignore
text2 = response['choices'][0]['message']['content'].split("\n")[1] # type: ignore
await generate_image(path, text1, text2)
def generate_image(path, text1, text2):
async def generate_image(path, text1, text2):
path_to_bcg = path.split("/")[:-1]
path_to_bcg = "/".join(path_to_bcg)
print(path_to_bcg)
@@ -71,7 +68,7 @@ def generate_image(path, text1, text2):
exit()
bcg = Image.open(f"{path_to_bcg}/bcg.png")
img = Image.new('RGBA', (1920, 1080))
img, textcolor1, textcolor2 = rand_gradient(img)
img, textcolor1, textcolor2 = await rand_gradient(img)
draw = ImageDraw.Draw(img)
font1 = ImageFont.truetype("./Sigmar-Regular.ttf", 200)
font2 = ImageFont.truetype("./Sigmar-Regular.ttf", 200)

View File

@@ -1,148 +0,0 @@
#!/usr/bin/python
'''Uploads a video to YouTube.'''
from http import client
import httplib2
import os
import random
import time
import json
import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload
from google_auth_oauthlib.flow import InstalledAppFlow
httplib2.RETRIES = 1
MAX_RETRIES = 10
RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, client.NotConnected,
client.IncompleteRead, client.ImproperConnectionState,
client.CannotSendRequest, client.CannotSendHeader,
client.ResponseNotReady, client.BadStatusLine)
RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
CLIENT_SECRETS_FILE = ''
#SCOPES = ['https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/upload/youtube/v3/thumbnails/set', 'https://www.googleapis.com/auth/youtube.force-ssl']
SCOPES = ['https://www.googleapis.com/auth/youtube']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'
VALID_PRIVACY_STATUSES = ('public', 'private', 'unlisted')
# Authorize the request and store authorization credentials.
def get_authenticated_service(credentialsPath=""):
CLIENT_SECRETS_FILE=f'{credentialsPath}/client_secret.json'
if os.path.exists(f'{credentialsPath}/credentials.json'):
with open(f'{credentialsPath}/credentials.json') as json_file:
data = json.load(json_file)
credentials = google.oauth2.credentials.Credentials(
token=data['token'],
refresh_token=data['refresh_token'],
token_uri=data['token_uri'],
client_id=data['client_id'],
client_secret=data['client_secret'],
scopes=data['scopes']
)
else:
flow = InstalledAppFlow.from_client_secrets_file(
CLIENT_SECRETS_FILE, SCOPES)
credentials = flow.run_local_server(success_message="Heyy, yippie, you're authenticated ! You can close this window now !", authorization_prompt_message="Please authorize this app to upload videos on your YouTube account !")
with open(f'{credentialsPath}/credentials.json', 'w') as outfile:
outfile.write(credentials.to_json())
return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
def initialize_upload(youtube, options):
tags = None
if options['keywords']:
tags = options['keywords'].split(',')
body = dict(
snippet=dict(
title=options['title'],
description=options['description'],
tags=tags,
categoryId=options['category'],
defaultLanguage='en'
),
status=dict(
privacyStatus=options['privacyStatus'],
selfDeclaredMadeForKids=False
)
)
# Call the API's videos.insert method to create and upload the video.
insert_request = youtube.videos().insert(
part=','.join(body.keys()),
body=body,
media_body=MediaFileUpload(options['file'], chunksize=-1, resumable=True)
)
videoid = resumable_upload(insert_request)
return videoid
def resumable_upload(request):
response = None
error = None
retry = 0
while response is None:
try:
print('Uploading file...')
status, response = request.next_chunk()
if response is not None:
if 'id' in response:
print('Video id "%s" was successfully uploaded.' %
response['id'])
return response['id']
else:
exit('The upload failed with an unexpected response: %s' % response)
except HttpError as e:
if e.resp.status in RETRIABLE_STATUS_CODES:
error = 'A retriable HTTP error %d occurred:\n%s' % (e.resp.status,
e.content)
else:
raise
except RETRIABLE_EXCEPTIONS as e:
error = 'A retriable error occurred: %s' % e
if error is not None:
print(error)
retry += 1
if retry > MAX_RETRIES:
exit('No longer attempting to retry.')
max_sleep = 2 ** retry
sleep_seconds = random.random() * max_sleep
print('Sleeping %f seconds and then retrying...' % sleep_seconds)
time.sleep(sleep_seconds)
def upload_video(path, title, description, category, keywords, privacyStatus='private', credentials_path=""):
options = {
'file': path +"/montage.mp4",
'title': title,
'description': description,
'category': category,
'keywords': keywords,
'privacyStatus': privacyStatus
}
youtube = get_authenticated_service(credentials_path)
try:
videoid = initialize_upload(youtube, options)
except HttpError as e:
print('An HTTP error %d occurred:\n%s' % (e.resp.status, e.content))
upload_thumbnail(videoid, path + "/miniature.png", credentials_path)
def upload_thumbnail(video_id, file, credentials_path=""):
youtube = get_authenticated_service(credentials_path)
youtube.thumbnails().set(
videoId=video_id,
media_body=file
).execute()