Skip to content

Commit 7540dbe

Browse files
authored
Merge pull request #1137 from elebumm/develop
2.4.1
2 parents 3eff3e4 + 5a8db46 commit 7540dbe

15 files changed

+106
-58
lines changed

GUI.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Import the server module
22
import http.server
33
import webbrowser
4+
45
# Set the hostname
56
HOST = "localhost"
67
# Set the port number
@@ -9,15 +10,16 @@
910
# Define class to display the index page of the web server
1011
class PythonServer(http.server.SimpleHTTPRequestHandler):
1112
def do_GET(self):
12-
if self.path == '/GUI':
13-
self.path = 'index.html'
13+
if self.path == "/GUI":
14+
self.path = "index.html"
1415
return http.server.SimpleHTTPRequestHandler.do_GET(self)
1516

17+
1618
# Declare object of the class
1719
webServer = http.server.HTTPServer((HOST, PORT), PythonServer)
1820
# Print the URL of the webserver, new =2 opens in a new tab
1921
print(f"Server started at http://{HOST}:{PORT}/GUI/")
20-
webbrowser.open(f'http://{HOST}:{PORT}/GUI/', new = 2)
22+
webbrowser.open(f"http://{HOST}:{PORT}/GUI/", new=2)
2123
print("Website opened in new tab")
2224
print("Press Ctrl+C to quit")
2325
try:
@@ -27,4 +29,4 @@ def do_GET(self):
2729
# Stop the web server
2830
webServer.server_close()
2931
print("The server is stopped.")
30-
exit()
32+
exit()

TTS/engine_wrapper.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,14 @@ def __init__(
3434
self,
3535
tts_module,
3636
reddit_object: dict,
37-
path: str = "assets/temp/mp3",
37+
path: str = "assets/temp/",
3838
max_length: int = DEFAULT_MAX_LENGTH,
3939
last_clip_length: int = 0,
4040
):
4141
self.tts_module = tts_module()
4242
self.reddit_object = reddit_object
43-
self.path = path
43+
self.redditid = re.sub(r"[^\w\s-]", "", reddit_object["thread_id"])
44+
self.path = path + self.redditid + "/mp3"
4445
self.max_length = max_length
4546
self.length = 0
4647
self.last_clip_length = last_clip_length

TTS/pyttsx.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,7 @@ def run(
1919
if voice_id == "" or voice_num == "":
2020
voice_id = 2
2121
voice_num = 3
22-
raise ValueError(
23-
"set pyttsx values to a valid value, switching to defaults"
24-
)
22+
raise ValueError("set pyttsx values to a valid value, switching to defaults")
2523
else:
2624
voice_id = int(voice_id)
2725
voice_num = int(voice_num)

main.py

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
#!/usr/bin/env python
22
import math
3+
import re
34
from subprocess import Popen
45
from os import name
56

67
from prawcore import ResponseException
78

89
from reddit.subreddit import get_subreddit_threads
910
from utils.cleanup import cleanup
10-
from utils.console import print_markdown, print_step
11+
from utils.console import print_markdown, print_step, print_substep
1112
from utils import settings
13+
from utils.id import id
14+
from utils.version import checkversion
1215

1316
from video_creation.background import (
1417
download_background,
@@ -19,8 +22,7 @@
1922
from video_creation.screenshot_downloader import download_screenshots_of_reddit_posts
2023
from video_creation.voices import save_text_to_mp3
2124

22-
__VERSION__ = "2.4"
23-
__BRANCH__ = "master"
25+
__VERSION__ = "2.4.1"
2426

2527
print(
2628
"""
@@ -36,18 +38,19 @@
3638
print_markdown(
3739
"### Thanks for using this tool! [Feel free to contribute to this project on GitHub!](https://lewismenelaws.com) If you have any questions, feel free to reach out to me on Twitter or submit a GitHub issue. You can find solutions to many common problems in the [Documentation](https://luka-hietala.gitbook.io/documentation-for-the-reddit-bot/)"
3840
)
39-
print_step(f"You are using v{__VERSION__} of the bot")
41+
checkversion(__VERSION__)
4042

4143

4244
def main(POST_ID=None):
43-
cleanup()
4445
reddit_object = get_subreddit_threads(POST_ID)
46+
global redditid
47+
redditid = id(reddit_object)
4548
length, number_of_comments = save_text_to_mp3(reddit_object)
4649
length = math.ceil(length)
4750
download_screenshots_of_reddit_posts(reddit_object, number_of_comments)
4851
bg_config = get_background_config()
4952
download_background(bg_config)
50-
chop_background_video(bg_config, length)
53+
chop_background_video(bg_config, length, reddit_object)
5154
make_final_video(number_of_comments, length, reddit_object, bg_config)
5255

5356

@@ -62,10 +65,15 @@ def run_many(times):
6265

6366
def shutdown():
6467
print_markdown("## Clearing temp files")
65-
cleanup()
66-
print("Exiting...")
67-
exit()
68-
68+
try:
69+
redditid
70+
except NameError:
71+
print("Exiting...")
72+
exit()
73+
else:
74+
cleanup(redditid)
75+
print("Exiting...")
76+
exit()
6977

7078
if __name__ == "__main__":
7179
config = settings.check_toml("utils/.config.template.toml", "config.toml")

reddit/subreddit.py

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import re
22

3+
from prawcore.exceptions import ResponseException
4+
35
from utils import settings
46
import praw
57
from praw.models import MoreComments
@@ -29,14 +31,21 @@ def get_subreddit_threads(POST_ID: str):
2931
username = settings.config["reddit"]["creds"]["username"]
3032
if str(username).casefold().startswith("u/"):
3133
username = username[2:]
32-
reddit = praw.Reddit(
33-
client_id=settings.config["reddit"]["creds"]["client_id"],
34-
client_secret=settings.config["reddit"]["creds"]["client_secret"],
35-
user_agent="Accessing Reddit threads",
36-
username=username,
37-
passkey=passkey,
38-
check_for_async=False,
39-
)
34+
try:
35+
reddit = praw.Reddit(
36+
client_id=settings.config["reddit"]["creds"]["client_id"],
37+
client_secret=settings.config["reddit"]["creds"]["client_secret"],
38+
user_agent="Accessing Reddit threads",
39+
username=username,
40+
passkey=passkey,
41+
check_for_async=False,
42+
)
43+
except ResponseException as e:
44+
match e.response.status_code:
45+
case 401:
46+
print("Invalid credentials - please check them in config.toml")
47+
except:
48+
print("Something went wrong...")
4049

4150
# Ask user for subreddit input
4251
print_step("Getting subreddit threads...")
@@ -57,9 +66,7 @@ def get_subreddit_threads(POST_ID: str):
5766
subreddit_choice = sub
5867
if str(subreddit_choice).casefold().startswith("r/"): # removes the r/ from the input
5968
subreddit_choice = subreddit_choice[2:]
60-
subreddit = reddit.subreddit(
61-
subreddit_choice
62-
) # Allows you to specify in .env. Done for automation purposes.
69+
subreddit = reddit.subreddit(subreddit_choice)
6370

6471
if POST_ID: # would only be called if there are multiple queued posts
6572
submission = reddit.submission(id=POST_ID)

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@ requests==2.28.1
99
rich==12.5.1
1010
toml==0.10.2
1111
translators==5.3.1
12-
12+
pyttsx3==2.90
1313
Pillow~=9.1.1

utils/.config.template.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ password = { optional = false, nmin = 8, explanation = "The password of your red
88

99
[reddit.thread]
1010
random = { optional = true, options = [true, false,], default = false, type = "bool", explanation = "If set to no, it will ask you a thread link to extract the thread, if yes it will randomize it. Default: 'False'", example = "True" }
11-
subreddit = { optional = false, regex = "[_0-9a-zA-Z]+$", nmin = 3, explanation = "What subreddit to pull posts from, the name of the sub, not the URL", example = "AskReddit", oob_error = "A subreddit name HAS to be between 3 and 20 characters" }
11+
subreddit = { optional = false, regex = "[_0-9a-zA-Z]+$", nmin = 3, explanation = "What subreddit to pull posts from, the name of the sub, not the URL. You can have multiple subreddits, add an + with no spaces.", example = "AskReddit+Redditdev", oob_error = "A subreddit name HAS to be between 3 and 20 characters" }
1212
post_id = { optional = true, default = "", regex = "^((?!://|://)[+a-zA-Z0-9])*$", explanation = "Used if you want to use a specific post.", example = "urdtfx" }
1313
max_comment_length = { default = 500, optional = false, nmin = 10, nmax = 10000, type = "int", explanation = "max number of characters a comment can have. default is 500", example = 500, oob_error = "the max comment length should be between 10 and 10000" }
1414
post_lang = { default = "", optional = true, explanation = "The language you would like to translate to.", example = "es-cr" }

utils/cleanup.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ def _listdir(d): # listdir with full path
66
return [os.path.join(d, f) for f in os.listdir(d)]
77

88

9-
def cleanup() -> int:
9+
def cleanup(id) -> int:
1010
"""Deletes all temporary assets in assets/temp
1111
1212
Returns:
@@ -18,7 +18,7 @@ def cleanup() -> int:
1818
count += len(files)
1919
for f in files:
2020
os.remove(f)
21-
REMOVE_DIRS = ["./assets/temp/mp3/", "./assets/temp/png/"]
21+
REMOVE_DIRS = [f"./assets/temp/{id}/mp3/", f"./assets/temp/{id}/png/"]
2222
files_to_remove = list(map(_listdir, REMOVE_DIRS))
2323
for directory in files_to_remove:
2424
for file in directory:

utils/console.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,4 +118,3 @@ def handle_input(
118118
console.print(
119119
"[red bold]" + err_message + "\nValid options are: " + ", ".join(map(str, options)) + "."
120120
)
121-

utils/id.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import re
2+
from utils import print_substep
3+
4+
def id(reddit_obj: dict):
5+
"""
6+
This function takes a reddit object and returns the post id
7+
"""
8+
id = re.sub(r"[^\w\s-]", "", reddit_obj["thread_id"])
9+
print_substep(f"Thread ID is {id}", style="bold blue")
10+
return id

utils/version.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import requests
2+
from utils.console import print_step
3+
4+
5+
def checkversion(__VERSION__):
6+
response = requests.get(
7+
"https://api.github.com/repos/elebumm/RedditVideoMakerBot/releases/latest"
8+
)
9+
latestversion = response.json()["tag_name"]
10+
if __VERSION__ == latestversion:
11+
print_step(f"You are using the newest version ({__VERSION__}) of the bot")
12+
return True
13+
else:
14+
print_step(
15+
f"You are using an older version ({__VERSION__}) of the bot. Download the newest version ({latestversion}) from https://github.com/elebumm/RedditVideoMakerBot/releases/latest"
16+
)

utils/video.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
from __future__ import annotations
2+
from ast import Str
3+
import re
24

35
from typing import Tuple
46

@@ -14,8 +16,9 @@ def __init__(self, video: VideoClip, *args, **kwargs):
1416
self.duration = self.video.duration
1517

1618
@staticmethod
17-
def _create_watermark(text, fontsize, opacity=0.5):
18-
path = "./assets/temp/png/watermark.png"
19+
def _create_watermark(text, redditid, fontsize, opacity=0.5):
20+
id = re.sub(r"[^\w\s-]", "", redditid["thread_id"])
21+
path = f"./assets/temp/{id}/png/watermark.png"
1922
width = int(fontsize * len(text))
2023
height = int(fontsize * len(text) / 2)
2124
white = (255, 255, 255)
@@ -35,7 +38,7 @@ def _create_watermark(text, fontsize, opacity=0.5):
3538
return ImageClip(path)
3639

3740
def add_watermark(
38-
self, text, opacity=0.5, duration: int | float = 5, position: Tuple = (0.7, 0.9), fontsize=15
41+
self, text, redditid, opacity=0.5, duration: int | float = 5, position: Tuple = (0.7, 0.9), fontsize=15
3942
):
4043
compensation = round(
4144
(position[0] / ((len(text) * (fontsize / 5) / 1.5) / 100 + position[0] * position[0])),
@@ -44,7 +47,7 @@ def add_watermark(
4447
position = (compensation, position[1])
4548
# print(f'{compensation=}')
4649
# print(f'{position=}')
47-
img_clip = self._create_watermark(text, opacity=opacity, fontsize=fontsize)
50+
img_clip = self._create_watermark(text, redditid, fontsize=fontsize, opacity=opacity)
4851
img_clip = img_clip.set_opacity(opacity).set_duration(duration)
4952
img_clip = img_clip.set_position(
5053
position, relative=True

video_creation/background.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from pathlib import Path
22
import random
33
from random import randrange
4+
import re
45
from typing import Any, Tuple
56

67

@@ -62,7 +63,7 @@ def download_background(background_config: Tuple[str, str, str, Any]):
6263
print_substep("Background video downloaded successfully! 🎉", style="bold green")
6364

6465

65-
def chop_background_video(background_config: Tuple[str, str, str, Any], video_length: int):
66+
def chop_background_video(background_config: Tuple[str, str, str, Any], video_length: int, reddit_object: dict):
6667
"""Generates the background footage to be used in the video and writes it to assets/temp/background.mp4
6768
6869
Args:
@@ -72,7 +73,7 @@ def chop_background_video(background_config: Tuple[str, str, str, Any], video_le
7273

7374
print_step("Finding a spot in the backgrounds video to chop...✂️")
7475
choice = f"{background_config[2]}-{background_config[1]}"
75-
76+
id = re.sub(r"[^\w\s-]", "", reddit_object["thread_id"])
7677
background = VideoFileClip(f"assets/backgrounds/{choice}")
7778

7879
start_time, end_time = get_start_and_end_times(video_length, background.duration)
@@ -81,12 +82,12 @@ def chop_background_video(background_config: Tuple[str, str, str, Any], video_le
8182
f"assets/backgrounds/{choice}",
8283
start_time,
8384
end_time,
84-
targetname="assets/temp/background.mp4",
85+
targetname=f"assets/temp/{id}/background.mp4",
8586
)
8687
except (OSError, IOError): # ffmpeg issue see #348
8788
print_substep("FFMPEG issue. Trying again...")
8889
with VideoFileClip(f"assets/backgrounds/{choice}") as video:
8990
new = video.subclip(start_time, end_time)
90-
new.write_videofile("assets/temp/background.mp4")
91+
new.write_videofile(f"assets/temp/{id}/background.mp4")
9192
print_substep("Background video chopped successfully!", style="bold green")
9293
return background_config[2]

0 commit comments

Comments
 (0)