Skip to content

Commit 9132d9c

Browse files
add images to video and improved prompt
1 parent 01f2581 commit 9132d9c

9 files changed

+278
-67
lines changed

.gitignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
.env
2-
venv/
2+
venv/
3+
config.yaml

ImageHandler.py

+139
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
import requests
2+
import pysrt
3+
import logging
4+
import os
5+
from openai import OpenAI
6+
7+
from dotenv import load_dotenv # To load environment variables
8+
9+
# Load environment variables from .env file
10+
load_dotenv()
11+
12+
class ImageHandler:
13+
def __init__(self, pexels_api_key, openai_api_key):
14+
15+
self.pexels_api_key = pexels_api_key
16+
self.openai_api_key = openai_api_key
17+
self.openai = OpenAI(api_key=self.openai_api_key)
18+
19+
def search_pexels_images(self, query):
20+
"""Search for images using Pexels API and return the URLs."""
21+
search_url = "https://api.pexels.com/v1/search"
22+
23+
headers = {
24+
'Authorization': self.pexels_api_key
25+
}
26+
27+
params = {
28+
'query': query,
29+
'per_page': 2
30+
}
31+
32+
try:
33+
response = requests.get(search_url, headers=headers, params=params)
34+
response.raise_for_status() # Raise an error for bad responses
35+
except requests.exceptions.HTTPError as e:
36+
logging.error(f"HTTP error occurred: {e}") # Log the error
37+
return [] # Return an empty list on error
38+
except Exception as e:
39+
logging.error(f"An error occurred during the request: {e}")
40+
return []
41+
42+
search_results = response.json()
43+
image_urls = [photo['src']['original'] for photo in search_results.get('photos', [])] # Extract image URLs
44+
return image_urls
45+
46+
def search_google_images(self, query):
47+
"""Search for images using Google Custom Search API and return the URLs."""
48+
search_url = "https://customsearch.googleapis.com/customsearch/v1?"
49+
50+
params = {
51+
'q': query,
52+
'cx': self.google_cx, # Ensure no leading/trailing spaces
53+
'searchType': 'image',
54+
'num': 1, # Number of results to return
55+
'key': self.google_api_key.strip() # Ensure no leading/trailing spaces
56+
}
57+
58+
try:
59+
response = requests.get(search_url, params=params)
60+
response.raise_for_status() # Raise an error for bad responses
61+
except requests.exceptions.HTTPError as e:
62+
logging.error(f"HTTP error occurred: {e}") # Log the error
63+
return [] # Return an empty list on error
64+
except Exception as e:
65+
logging.error(f"An error occurred during the request: {e}")
66+
return []
67+
68+
search_results = response.json()
69+
print(search_results)
70+
image_urls = [item['link'] for item in search_results.get('items', [])] # Extract image URLs
71+
return image_urls
72+
73+
def download_image(self, url, filename):
74+
"""Download an image from a URL."""
75+
try:
76+
response = requests.get(url, timeout=10) # Timeout for network issues
77+
response.raise_for_status() # Raise for HTTP errors
78+
os.makedirs(os.path.dirname(filename), exist_ok=True) # Ensure directory exists
79+
with open(filename, 'wb') as f:
80+
f.write(response.content)
81+
return filename
82+
except requests.exceptions.RequestException as e:
83+
logging.error(f"Failed to download image: {e}")
84+
except Exception as e:
85+
logging.error(f"Error while saving image: {e}")
86+
return None
87+
88+
def extract_keywords_from_subtitles(self, subtitles_file):
89+
"""Extract key phrases from subtitles."""
90+
seconds_per_keyword = 5
91+
try:
92+
subs = pysrt.open(subtitles_file)
93+
keywords = []
94+
current_text = []
95+
current_duration = 0
96+
97+
for sub in subs:
98+
current_text.append(sub.text)
99+
current_duration += (sub.end - sub.start).milliseconds # Use seconds attribute
100+
if current_duration >= seconds_per_keyword*1000: # Check if we reached 10 seconds
101+
keywords.append(' '.join(current_text)) # Join the accumulated text
102+
current_text = [] # Reset for the next batch
103+
current_duration = 0 # Reset duration
104+
105+
return keywords
106+
except Exception as e:
107+
logging.error(f"Error extracting keywords from subtitles: {e}")
108+
return []
109+
110+
def refine_keyword_with_openai(self, keyword, video_context):
111+
"""Refine the keyword using OpenAI's ChatGPT 3.5 for better image search results."""
112+
113+
try:
114+
completion = self.openai.chat.completions.create( # Async call to create chat completion
115+
model="gpt-3.5-turbo", # Updated model name
116+
messages=[{'role':'system','content':'You are a query generation system designed to enhance video automation. Your task is to receive phrases and generate concise queries that will help in finding suitable images for the given scene. Please create a query based on the provided phrase and the context of the video.'},{'role': 'user', 'content': f' \n Original phrase: "{keyword}" \n Video topic: {video_context}'}],
117+
max_tokens=200
118+
)
119+
refined_keyword = completion.choices[0].message.content.strip()
120+
return refined_keyword
121+
except requests.exceptions.RequestException as e:
122+
logging.error(f"Error calling OpenAI API: {e}")
123+
return keyword # Return the original keyword on error
124+
125+
def get_images_from_subtitles(self, subtitles_file_path, video_context):
126+
"""Fetch relevant images based on the subtitles."""
127+
keywords = self.extract_keywords_from_subtitles(subtitles_file_path) # Extract keywords from subtitles
128+
image_paths = []
129+
130+
for keyword in keywords:
131+
refined_keyword = self.refine_keyword_with_openai(keyword, video_context) # Refine the keyword
132+
logging.info(f"Searching image for keywords: {refined_keyword}")
133+
image_urls = self.search_pexels_images(refined_keyword) # Search for images using the refined keyword
134+
if image_urls:
135+
img_path = f"assets/images/subtitle_image_{refined_keyword}.jpg"
136+
logging.info(f"Downloading image: {image_urls[0]}") # Unique filename for each image
137+
if self.download_image(image_urls[0], img_path):
138+
image_paths.append(img_path) # Add the downloaded image path to the list
139+
return image_paths

README.md

+31-22
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
# TurboReelGPT
22

3-
**TurboReelGPT** is your go-to tool for creating short, engaging videos for TikTok, Instagram Reels, and YouTube Shorts. Unlike other AI video generators, TurboReelGPT aims to be the first prompt-to-video model that focuses on making content feel real and engaging.
3+
**Welcome to TurboReelGPT!** Your new buddy for creating short videos for TikTok, Instagram Reels, and YouTube Shorts. Unlike other AI video generators out there, we’re all about making your content feel real.
44

5-
### What Were About
5+
## What We're About
66

77
Just like Midjourney changed the game for images, TurboReelGPT is here to transform how we make videos. Our mission is to help creators easily produce videos that connect with their audience on a human level.
88

9-
- **Example YouTube Video**: Check out this [example video](https://www.youtube.com/watch?v=Dljw1VYg-g0&list=TLGG7jhQJ1_OX9gwMzEwMjAyNA) to see what you can create with TurboReelGPT.
10-
![Video Preview](https://img.youtube.com/vi/Dljw1VYg-g0/0.jpg)
9+
- **Check This Out**: Want to see what you can create? Check out this [example video](https://youtu.be/4tFtKmXc-xE?si=KTb0MLfAYTe7eVtP).
10+
![Video Preview](https://i.ytimg.com/vi/4tFtKmXc-xE/hqdefault.jpg)
1111

12-
### Our Roadmap
12+
## 🚀 Our Roadmap
1313

14-
1. **Make Storytelling Even Better**: Work on improving how we tell stories in videos.
14+
1. **Storytelling**: Work on improving how we tell stories in videos.
1515
2. **Stock Images Galore**: Add more stock images for users to choose from.
1616
3. **More Voice Options**: Introduce even more human-like voice choices.
1717
4. **AI-Generated Images**: Let users create and use AI-generated images in their videos.
@@ -20,47 +20,56 @@ Just like Midjourney changed the game for images, TurboReelGPT is here to transf
2020
7. **AI for Image Recognition**: Use AI to recognize images and sync them better with videos.
2121
8. **Fun Video Remixing**: Let users remix and play around with existing videos.
2222

23-
### Getting Started
23+
## 💡 Getting Started
2424

2525
Ready to dive in? Here’s how to get started with TurboReelGPT:
2626

27-
1. **Clone the repo**:
27+
1. **Clone the Repo**:
2828
```bash
2929
git clone https://github.com/yourusername/turboreelgpt.git
3030
```
31-
2. **Go to the project folder**:
31+
32+
2. **Head to the Project Folder**:
3233
```bash
3334
cd turboreelgpt
3435
```
35-
3. **Make sure you have Python 3.10.12 installed**. You can download it from [python.org](https://www.python.org/downloads/release/python-31012/).
36+
37+
3. **Make Sure You’ve Got Python**: Grab Python 3.10.x from [python.org](https://www.python.org/downloads/release/python-31012/).
3638

3739
4. **Install FFmpeg and ImageMagick**:
38-
- **For Windows**: You can download the binaries from the [FFmpeg](https://ffmpeg.org/download.html) and [ImageMagick](https://imagemagick.org/script/download.php) websites and add them to your system's PATH.
39-
- **For macOS**: You can use Homebrew to install them:
40+
- **For Windows**: Download the binaries from [FFmpeg](https://ffmpeg.org/download.html) and [ImageMagick](https://imagemagick.org/script/download.php). Just add them to your system's PATH.
41+
- **For macOS**: Use Homebrew (if you haven’t tried it yet, now’s the time!):
4042
```bash
4143
brew install ffmpeg imagemagick
4244
```
43-
- **For Linux**: Use your package manager to install them:
45+
- **For Linux**: Just use your package manager:
4446
```bash
4547
sudo apt-get install ffmpeg imagemagick
4648
```
4749

48-
5. **Install the required Python packages**:
50+
5. **Get the Required Python Packages**:
4951
```bash
5052
pip install -r requirements.txt
5153
```
52-
6. **Launch the app**:
54+
55+
6. **Grab Your API Keys**: You’ll need keys for OPENAI (for generating scripts) and PEXELS (for fetching images). Get your PEXELS API key [here](https://www.pexels.com/api/key/).
56+
57+
7. **Set Up Your Config**: Create a `config.yaml` file in the root folder. Clone `config-example.yaml`, fill it in with your API keys and desired settings.
58+
59+
8. **Launch the App**:
5360
```bash
5461
python app.py
5562
```
5663

57-
### Want to Help?
64+
**Heads Up**: This project uses YT-DLP for downloading YouTube videos, and it needs cookies to work properly. So, automating this in a VM might not be the best idea. Instead, download some videos manually, toss them in the assets folder, and change the "video path" in `app.py` (around line 219) to point to your downloaded videos.
65+
66+
## 🤗 Want to Help?
5867

59-
We’d love your help! If you want to contribute to TurboReelGPT, here’s what to do:
68+
We’d love your help! If you’re excited to contribute to TurboReelGPT, here’s how you can jump in:
6069

61-
1. **Fork the repo**.
62-
2. **Create a new branch** for your feature or fix.
63-
3. **Make your changes and commit them**.
64-
4. **Push your branch** and submit a pull request.
70+
1. **Fork the Repo**.
71+
2. **Create a New Branch** for your feature or fix.
72+
3. **Make Your Changes and Commit Them**.
73+
4. **Push Your Branch** and submit a pull request.
6574

66-
- **Join our Discord**: Connect with us and other creators on our [Discord server](https://discord.gg/4dnynCSN).
75+
- **Join Our Crew**: Let’s connect! Join us and other creators on our [Discord server](https://discord.gg/4dnynCSN). We can’t wait to see what you create!
5.16 KB
Binary file not shown.

0 commit comments

Comments
 (0)