setup.py heavily refactored, all files formatted with python-BLACK and added shebang lines

pull/345/head
CordlessCoder 3 years ago
parent 1462b1d9b6
commit 45a296db80

@ -1 +1,2 @@
docker build -t rvmt . #!/bin/sh
docker build -t rvmt .

@ -1,3 +1,4 @@
#!/usr/bin/env python3
# Main # Main
from utils.console import print_markdown from utils.console import print_markdown
from utils.console import print_step from utils.console import print_step
@ -54,7 +55,7 @@ if not os.path.exists(".env"):
console.log("[red] Your .env file is invalid, or was never created. Standby.") console.log("[red] Your .env file is invalid, or was never created. Standby.")
for val in REQUIRED_VALUES: for val in REQUIRED_VALUES:
#print(os.getenv(val)) # print(os.getenv(val))
if val not in os.environ or not os.getenv(val): if val not in os.environ or not os.getenv(val):
console.log(f'[bold red]Missing Variable: "{val}"') console.log(f'[bold red]Missing Variable: "{val}"')
configured = False configured = False

@ -1,3 +1,4 @@
#!/usr/bin/env python3
from rich.console import Console from rich.console import Console
from utils.console import print_markdown, print_step, print_substep from utils.console import print_markdown, print_step, print_substep
from dotenv import load_dotenv from dotenv import load_dotenv
@ -48,7 +49,11 @@ def get_subreddit_threads():
# ! Prompt the user to enter a subreddit # ! Prompt the user to enter a subreddit
try: try:
subreddit = reddit.subreddit( subreddit = reddit.subreddit(
re.sub(r"r\/", "",input("What subreddit would you like to pull from? ")) re.sub(
r"r\/",
"",
input("What subreddit would you like to pull from? "),
)
) )
except ValueError: except ValueError:
subreddit = reddit.subreddit("askreddit") subreddit = reddit.subreddit("askreddit")

@ -1 +1,2 @@
docker run -v $(pwd)/out/:/app/assets -v $(pwd)/.env:/app/.env -it rvmt #!/bin/sh
docker run -v "$(pwd)/out/:/app/assets" -v "$(pwd)/.env:/app/.env -it rvmt"

@ -1,55 +1,98 @@
""" #!/usr/bin/env python3
# Setup Script for RedditVideoMakerBot
Setup Script for RedditVideoMakerBot
"""
# Imports # Imports
import os import os
import time import subprocess
import re
from utils.console import print_markdown from utils.console import print_markdown
from utils.console import print_step from utils.console import print_step
from utils.console import print_substep
from rich.console import Console from rich.console import Console
from utils.loader import Loader from utils.loader import Loader
from os.path import exists
console = Console() console = Console()
setup_done = exists(".setup-done-before")
if setup_done == True: def handle_input(
console.log("[red]Setup was already completed! Please make sure you have to run this script again. If you have to, please delete the file .setup-done-before") message: str = "",
exit() check_type=False,
match: str = "",
err_message: str = "",
nmin=None,
nmax=None,
oob_error="",
):
match = re.compile(match)
while True:
user_input = input(message + "\n> ").strip()
if re.match(match, user_input) is not None:
if check_type is not False:
try:
user_input = check_type(user_input)
if nmin is not None and user_input < nmin:
console.log("[red]" + oob_error) # Input too low failstate
continue
if nmax is not None and user_input > nmax:
console.log("[red]" + oob_error) # Input too high
continue
break # Successful type conversion and number in bounds
except ValueError:
console.log("[red]" + err_message) # Type conversion failed
continue
if (
nmin is not None and len(user_input) < nmin
): # Check if string is long enough
console.log("[red]" + oob_error)
continue
if (
nmax is not None and len(user_input) > nmax
): # Check if string is not too long
console.log("[red]" + oob_error)
continue
break
console.log("[red]" + err_message)
return user_input
if os.path.isfile(".setup-done-before"):
console.log(
"[red]Setup was already completed! Please make sure you have to run this script again. If that is such, delete the file .setup-done-before"
)
exit()
# These lines ensure the user: # These lines ensure the user:
# - knows they are in setup mode # - knows they are in setup mode
# - knows that they are about to erase any other setup files/data. # - knows that they are about to erase any other setup files/data.
print_step("Setup Assistant") print_step("Setup Assistant")
print_markdown( print_markdown(
"### You're in the setup wizard. Ensure you're supposed to be here, then type yes to continue. If you're not sure, type no to quit." "### You're in the setup wizard. Ensure you're supposed to be here, then type yes to continue. If you're not sure, type no to quit."
) )
# This Input is used to ensure the user is sure they want to continue. # This Input is used to ensure the user is sure they want to continue.
ensureSetupIsRequired = input("Are you sure you want to continue? > ").casefold() if input("Are you sure you want to continue? > ").strip().casefold() != "yes":
if ensureSetupIsRequired != "yes": console.print("[red]Exiting...")
console.print("[red]Exiting...") exit()
time.sleep(0.5) # This code is inaccessible if the prior check fails, and thus an else statement is unnecessary
exit()
else:
# Again, let them know they are about to erase all other setup data.
console.print("[bold red] This will overwrite your current settings. Are you sure you want to continue? [bold green]yes/no")
overwriteSettings = input("Are you sure you want to continue? > ").casefold()
if overwriteSettings != "yes":
console.print("[red]Abort mission! Exiting...")
time.sleep(0.5)
exit()
else:
# Once they confirm, move on with the script.
console.print("[bold green]Alright! Let's get started!")
time.sleep(1)
# Again, let them know they are about to erase all other setup data.
console.print(
"[bold red] This will overwrite your current settings. Are you sure you want to continue? [bold green]yes/no"
)
if input("Are you sure you want to continue? > ").strip().casefold() != "yes":
console.print("[red]Abort mission! Exiting...")
exit()
# This is once again inaccessible if the prior checks fail
# Once they confirm, move on with the script.
console.print("[bold green]Alright! Let's get started!")
print("\n")
console.log("Ensure you have the following ready to enter:") console.log("Ensure you have the following ready to enter:")
console.log("[bold green]Reddit Client ID") console.log("[bold green]Reddit Client ID")
console.log("[bold green]Reddit Client Secret") console.log("[bold green]Reddit Client Secret")
@ -59,64 +102,108 @@ console.log("[bold green]Reddit 2FA (yes or no)")
console.log("[bold green]Opacity (range of 0-1, decimals are OK)") console.log("[bold green]Opacity (range of 0-1, decimals are OK)")
console.log("[bold green]Subreddit (without r/ or /r/)") console.log("[bold green]Subreddit (without r/ or /r/)")
console.log("[bold green]Theme (light or dark)") console.log("[bold green]Theme (light or dark)")
time.sleep(0.5) console.print(
console.print("[green]If you don't have these, please follow the instructions in the README.md file to set them up.") "[green]If you don't have these, please follow the instructions in the README.md file to set them up."
console.print("[green]If you do have these, type yes to continue. If you dont, go ahead and grab those quickly and come back.") )
confirmUserHasCredentials = input("Are you sure you have the credentials? > ").casefold() console.print(
if confirmUserHasCredentials != "yes": "[green]If you do have these, type yes to continue. If you dont, go ahead and grab those quickly and come back."
console.print("[red]I don't understand that.") )
console.print("[red]Exiting...") print()
exit()
else:
console.print("[bold green]Alright! Let's get started!")
time.sleep(1)
"""
Begin the setup process. if input("Are you sure you have the credentials? > ").strip().casefold() != "yes":
console.print("[red]I don't understand that.")
console.print("[red]Exiting...")
exit()
"""
console.print("[bold green]Alright! Let's get started!")
# Begin the setup process.
console.log("Enter your credentials now.") console.log("Enter your credentials now.")
cliID = input("Client ID > ") client_id = handle_input(
cliSec = input("Client Secret > ") "Client ID > ",
user = input("Username > ") False,
passw = input("Password > ") "[-a-zA-Z0-9._~+/]+=*",
twofactor = input("2fa Enabled? (yes/no) > ") "That is somehow not a correct ID, try again.",
opacity = input("Opacity? (range of 0-1) > ") 20,
subreddit = input("Subreddit (without r/) > ") 40,
theme = input("Theme? (light or dark) > ") "The ID should be over 20 and under 40 characters, double check your input.",
console.log("Attempting to save your credentials...") )
loader = Loader("Saving Credentials...", "Done!").start() client_sec = handle_input(
# you can also put a while loop here, e.g. while VideoIsBeingMade == True: ... "Client Secret > ",
time.sleep(0.5) False,
console.log("Removing old .env file...") "[-a-zA-Z0-9._~+/]+=*",
os.remove(".env") "That is somehow not a correct secret, try again.",
time.sleep(0.5) 20,
console.log("Creating new .env file...") 40,
with open('.env', 'a') as f: "The secret should be over 20 and under 40 characters, double check your input.",
f.write(f'REDDIT_CLIENT_ID="{cliID}"\n') )
time.sleep(0.5) user = handle_input(
f.write(f'REDDIT_CLIENT_SECRET="{cliSec}"\n') "Username > ",
time.sleep(0.5) False,
f.write(f'REDDIT_USERNAME="{user}"\n') r"[_0-9a-zA-Z]+",
time.sleep(0.5) "That is not a valid user",
f.write(f'REDDIT_PASSWORD="{passw}"\n') 3,
time.sleep(0.5) 20,
f.write(f'REDDIT_2FA="{twofactor}"\n') "A username HAS to be between 3 and 20 characters",
time.sleep(0.5) )
f.write(f'THEME="{theme}"\n') passw = handle_input("Password > ", False, "", "", 8, None, "Password too short")
time.sleep(0.5) twofactor = handle_input(
f.write(f'SUBREDDIT="{subreddit}"\n') "2fa Enabled? (yes/no) > ",
time.sleep(0.5) False,
f.write(f'OPACITY="{opacity}"\n') r"(yes)|(no)",
"You need to input either yes or no",
with open('.setup-done-before', 'a') as f: )
f.write("This file blocks the setup assistant from running again. Delete this file to run setup again.") opacity = handle_input(
"Opacity? (range of 0-1) > ",
float,
"",
"You need to input a number between 0 and 1",
0,
1,
"Your number is not between 0 and 1",
)
subreddit = handle_input(
"Subreddit (without r/) > ",
False,
r"[_0-9a-zA-Z]+",
"This subreddit cannot exist, make sure you typed it in correctly and removed the r/ (or /r/).",
3,
20,
"A subreddit name HAS to be between 3 and 20 characters",
)
theme = handle_input(
"Theme? (light or dark) > ",
False,
r"(light)|(dark)",
"You need to input 'light' or 'dark'",
)
loader = Loader("Attempting to save your credentials...", "Done!").start()
# you can also put a while loop here, e.g. while VideoIsBeingMade == True: ...
console.log("Writing to the .env file...")
with open(".env", "w") as f:
f.write(
f"""REDDIT_CLIENT_ID="{client_id}"
REDDIT_CLIENT_SECRET="{client_sec}"
REDDIT_USERNAME="{user}"
REDDIT_PASSWORD="{passw}"
REDDIT_2FA="{twofactor}"
THEME="{theme}"
SUBREDDIT="{subreddit}"
OPACITY={opacity}
"""
)
with open(".setup-done-before", "w") as f:
f.write(
"This file blocks the setup assistant from running again. Delete this file to run setup again."
)
loader.stop() loader.stop()
console.log("[bold green]Setup Complete! Returning...") console.log("[bold green]Setup Complete! Returning...")
# Post-Setup: send message and try to run main.py again. # Post-Setup: send message and try to run main.py again.
os.system("python3 main.py") subprocess.call("python3 main.py", shell=True)

@ -1,3 +1,4 @@
#!/usr/bin/env python3
from rich.console import Console from rich.console import Console
from rich.markdown import Markdown from rich.markdown import Markdown
from rich.padding import Padding from rich.padding import Padding

@ -1,9 +1,8 @@
"""
Okay, have to admit. This code is from StackOverflow. It's so efficient, that it's probably the best way to do it. # Okay, have to admit. This code is from StackOverflow. It's so efficient, that it's probably the best way to do it.
Although, it is edited to use less threads. # Although, it is edited to use less threads.
"""
from itertools import cycle from itertools import cycle
from shutil import get_terminal_size from shutil import get_terminal_size
from threading import Thread from threading import Thread
@ -50,4 +49,4 @@ class Loader:
def __exit__(self, exc_type, exc_value, tb): def __exit__(self, exc_type, exc_value, tb):
# handle exceptions with those variables ^ # handle exceptions with those variables ^
self.stop() self.stop()

@ -1,3 +1,4 @@
#!/usr/bin/env python3
from random import randrange from random import randrange
from yt_dlp import YoutubeDL from yt_dlp import YoutubeDL
@ -13,6 +14,7 @@ def get_start_and_end_times(video_length, length_of_clip):
random_time = randrange(180, int(length_of_clip) - int(video_length)) random_time = randrange(180, int(length_of_clip) - int(video_length))
return random_time, random_time + video_length return random_time, random_time + video_length
def download_background(): def download_background():
"""Downloads the background video from youtube. """Downloads the background video from youtube.

@ -1,3 +1,4 @@
#!/usr/bin/env python3
from moviepy.editor import ( from moviepy.editor import (
VideoFileClip, VideoFileClip,
AudioFileClip, AudioFileClip,
@ -7,7 +8,7 @@ from moviepy.editor import (
CompositeAudioClip, CompositeAudioClip,
CompositeVideoClip, CompositeVideoClip,
) )
import reddit.subreddit import reddit.subreddit
import re import re
from utils.console import print_step from utils.console import print_step
from dotenv import load_dotenv from dotenv import load_dotenv
@ -16,13 +17,12 @@ import os
W, H = 1080, 1920 W, H = 1080, 1920
def make_final_video(number_of_clips): def make_final_video(number_of_clips):
# Calls opacity from the .env # Calls opacity from the .env
load_dotenv() load_dotenv()
opacity = os.getenv('OPACITY') opacity = os.getenv("OPACITY")
print_step("Creating the final video...") print_step("Creating the final video...")
VideoFileClip.reW = lambda clip: clip.resize(width=W) VideoFileClip.reW = lambda clip: clip.resize(width=W)
@ -65,7 +65,7 @@ def make_final_video(number_of_clips):
.set_position("center") .set_position("center")
.resize(width=W - 100) .resize(width=W - 100)
.set_opacity(float(opacity)), .set_opacity(float(opacity)),
) )
else: else:
image_clips.insert( image_clips.insert(
0, 0,
@ -74,13 +74,15 @@ def make_final_video(number_of_clips):
.set_position("center") .set_position("center")
.resize(width=W - 100) .resize(width=W - 100)
.set_opacity(float(opacity)), .set_opacity(float(opacity)),
) )
image_concat = concatenate_videoclips(image_clips).set_position( image_concat = concatenate_videoclips(image_clips).set_position(
("center", "center") ("center", "center")
) )
image_concat.audio = audio_composite image_concat.audio = audio_composite
final = CompositeVideoClip([background_clip, image_concat]) final = CompositeVideoClip([background_clip, image_concat])
filename = (re.sub('[?\"%*:|<>]', '', ("assets/" + reddit.subreddit.submission.title + ".mp4"))) filename = re.sub(
'[?"%*:|<>]', "", ("assets/" + reddit.subreddit.submission.title + ".mp4")
)
final.write_videofile(filename, fps=30, audio_codec="aac", audio_bitrate="192k") final.write_videofile(filename, fps=30, audio_codec="aac", audio_bitrate="192k")
for i in range(0, number_of_clips): for i in range(0, number_of_clips):
pass pass

@ -1,3 +1,4 @@
#!/usr/bin/env python3
from playwright.sync_api import sync_playwright, ViewportSize from playwright.sync_api import sync_playwright, ViewportSize
from pathlib import Path from pathlib import Path
from rich.progress import track from rich.progress import track
@ -24,7 +25,7 @@ def download_screenshots_of_reddit_posts(reddit_object, screenshot_num, theme):
context = browser.new_context() context = browser.new_context()
if theme.casefold() == "dark": if theme.casefold() == "dark":
cookie_file = open('video_creation/cookies.json') cookie_file = open("video_creation/cookies.json")
cookies = json.load(cookie_file) cookies = json.load(cookie_file)
context.add_cookies(cookies) context.add_cookies(cookies)
@ -58,5 +59,4 @@ def download_screenshots_of_reddit_posts(reddit_object, screenshot_num, theme):
path=f"assets/png/comment_{idx}.png" path=f"assets/png/comment_{idx}.png"
) )
print_substep("Screenshots downloaded Successfully.", print_substep("Screenshots downloaded Successfully.", style="bold green")
style="bold green")

@ -1,3 +1,4 @@
#!/usr/bin/env python3
from gtts import gTTS from gtts import gTTS
from pathlib import Path from pathlib import Path
from mutagen.mp3 import MP3 from mutagen.mp3 import MP3

Loading…
Cancel
Save