File size: 7,992 Bytes
e71d833 |
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 |
import re
import json
import g4f
import openai
from typing import Tuple, List
from termcolor import colored
from dotenv import load_dotenv
import os
import google.generativeai as genai
# Load environment variables
load_dotenv("../.env")
# Set environment variables
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
openai.api_key = OPENAI_API_KEY
GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
genai.configure(api_key=GOOGLE_API_KEY)
def generate_response(prompt: str, ai_model: str) -> str:
"""
Generate a script for a video, depending on the subject of the video.
Args:
video_subject (str): The subject of the video.
ai_model (str): The AI model to use for generation.
Returns:
str: The response from the AI model.
"""
if ai_model == 'g4f':
response = g4f.ChatCompletion.create(
model=g4f.models.gpt_35_turbo_16k_0613,
messages=[{"role": "user", "content": prompt}],
)
elif ai_model in ["gpt3.5-turbo", "gpt4"]:
model_name = "gpt-3.5-turbo" if ai_model == "gpt3.5-turbo" else "gpt-4-1106-preview"
response = openai.chat.completions.create(
model=model_name,
messages=[{"role": "user", "content": prompt}],
).choices[0].message.content
elif ai_model == 'gemmini':
model = genai.GenerativeModel('gemini-pro')
response_model = model.generate_content(prompt)
response = response_model.text
else:
raise ValueError("Invalid AI model selected.")
return response
def generate_script(video_subject: str, paragraph_number: int, ai_model: str, voice: str, customPrompt: str) -> str:
"""
Generate a script for a video, depending on the subject of the video, the number of paragraphs, and the AI model.
Args:
video_subject (str): The subject of the video.
paragraph_number (int): The number of paragraphs to generate.
ai_model (str): The AI model to use for generation.
Returns:
str: The script for the video.
"""
# Build prompt
if customPrompt:
prompt = customPrompt
else:
prompt = """
Generate a script for a video, depending on the subject of the video.
The script is to be returned as a string with the specified number of paragraphs.
Here is an example of a string:
"This is an example string."
Do not under any circumstance reference this prompt in your response.
Get straight to the point, don't start with unnecessary things like, "welcome to this video".
Obviously, the script should be related to the subject of the video.
YOU MUST NOT INCLUDE ANY TYPE OF MARKDOWN OR FORMATTING IN THE SCRIPT, NEVER USE A TITLE.
YOU MUST WRITE THE SCRIPT IN THE LANGUAGE SPECIFIED IN [LANGUAGE].
ONLY RETURN THE RAW CONTENT OF THE SCRIPT. DO NOT INCLUDE "VOICEOVER", "NARRATOR" OR SIMILAR INDICATORS OF WHAT SHOULD BE SPOKEN AT THE BEGINNING OF EACH PARAGRAPH OR LINE. YOU MUST NOT MENTION THE PROMPT, OR ANYTHING ABOUT THE SCRIPT ITSELF. ALSO, NEVER TALK ABOUT THE AMOUNT OF PARAGRAPHS OR LINES. JUST WRITE THE SCRIPT.
"""
prompt += f"""
Subject: {video_subject}
Number of paragraphs: {paragraph_number}
Language: {voice}
"""
# Generate script
response = generate_response(prompt, ai_model)
print(colored(response, "cyan"))
# Return the generated script
if response:
# Clean the script
# Remove asterisks, hashes
response = response.replace("*", "")
response = response.replace("#", "")
# Remove markdown syntax
response = re.sub(r"\[.*\]", "", response)
response = re.sub(r"\(.*\)", "", response)
# Split the script into paragraphs
paragraphs = response.split("\n\n")
# Select the specified number of paragraphs
selected_paragraphs = paragraphs[:paragraph_number]
# Join the selected paragraphs into a single string
final_script = "\n\n".join(selected_paragraphs)
# Print to console the number of paragraphs used
print(colored(f"Number of paragraphs used: {len(selected_paragraphs)}", "green"))
return final_script
else:
print(colored("[-] GPT returned an empty response.", "red"))
return None
def get_search_terms(video_subject: str, amount: int, script: str, ai_model: str) -> List[str]:
"""
Generate a JSON-Array of search terms for stock videos,
depending on the subject of a video.
Args:
video_subject (str): The subject of the video.
amount (int): The amount of search terms to generate.
script (str): The script of the video.
ai_model (str): The AI model to use for generation.
Returns:
List[str]: The search terms for the video subject.
"""
# Build prompt
prompt = f"""
Generate {amount} search terms for stock videos,
depending on the subject of a video.
Subject: {video_subject}
The search terms are to be returned as
a JSON-Array of strings.
Each search term should consist of 1-3 words,
always add the main subject of the video.
YOU MUST ONLY RETURN THE JSON-ARRAY OF STRINGS.
YOU MUST NOT RETURN ANYTHING ELSE.
YOU MUST NOT RETURN THE SCRIPT.
The search terms must be related to the subject of the video.
Here is an example of a JSON-Array of strings:
["search term 1", "search term 2", "search term 3"]
For context, here is the full text:
{script}
"""
# Generate search terms
response = generate_response(prompt, ai_model)
# Parse response into a list of search terms
search_terms = []
try:
search_terms = json.loads(response)
if not isinstance(search_terms, list) or not all(isinstance(term, str) for term in search_terms):
raise ValueError("Response is not a list of strings.")
except (json.JSONDecodeError, ValueError):
print(colored("[*] GPT returned an unformatted response. Attempting to clean...", "yellow"))
# Attempt to extract list-like string and convert to list
match = re.search(r'\["(?:[^"\\]|\\.)*"(?:,\s*"[^"\\]*")*\]', response)
if match:
try:
search_terms = json.loads(match.group())
except json.JSONDecodeError:
print(colored("[-] Could not parse response.", "red"))
return []
# Let user know
print(colored(f"\nGenerated {len(search_terms)} search terms: {', '.join(search_terms)}", "cyan"))
# Return search terms
return search_terms
def generate_metadata(video_subject: str, script: str, ai_model: str) -> Tuple[str, str, List[str]]:
"""
Generate metadata for a YouTube video, including the title, description, and keywords.
Args:
video_subject (str): The subject of the video.
script (str): The script of the video.
ai_model (str): The AI model to use for generation.
Returns:
Tuple[str, str, List[str]]: The title, description, and keywords for the video.
"""
# Build prompt for title
title_prompt = f"""
Generate a catchy and SEO-friendly title for a YouTube shorts video about {video_subject}.
"""
# Generate title
title = generate_response(title_prompt, ai_model).strip()
# Build prompt for description
description_prompt = f"""
Write a brief and engaging description for a YouTube shorts video about {video_subject}.
The video is based on the following script:
{script}
"""
# Generate description
description = generate_response(description_prompt, ai_model).strip()
# Generate keywords
keywords = get_search_terms(video_subject, 6, script, ai_model)
return title, description, keywords
|