Skip to content

Commit 8990cba

Browse files
Merge pull request #1477 from elebumm/develop
Version 3.0.1
2 parents 4c01a1d + c582b04 commit 8990cba

10 files changed

+69
-31
lines changed

TTS/TikTok.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@
7979
class TikTok:
8080
"""TikTok Text-to-Speech Wrapper"""
8181
def __init__(self):
82+
if not settings.config['settings']['tts']['tiktok_sessionid']:
83+
raise TikTokTTSException(5)
8284
headers = {
8385
"User-Agent": "com.zhiliaoapp.musically/2022600030 (Linux; U; Android 7.1.2; es_ES; SM-G988N; "
8486
"Build/NRD90M;tt-ok/3.12.13.1)",
@@ -140,7 +142,7 @@ def get_voices(self, text: str, voice: Optional[str] = None) -> dict:
140142
return response.json()
141143

142144
@staticmethod
143-
def random_voice():
145+
def random_voice() -> str:
144146
return random.choice(eng_voices)
145147

146148

@@ -158,5 +160,8 @@ def __str__(self) -> str:
158160

159161
if self._code == 4:
160162
return f"Code: {self._code}, reason: the speaker doesn't exist, message: {self._message}"
163+
164+
if self._code == 5:
165+
return f"You have to add session id in config to use titok TTS"
161166

162167
return f"Code: {self._message}, reason: unknown, message: {self._message}"

TTS/engine_wrapper.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,18 @@ def __init__(
5151
self.length = 0
5252
self.last_clip_length = last_clip_length
5353

54+
def add_periods(self): # adds periods to the end of paragraphs (where people often forget to put them) so tts doesn't blend sentences
55+
for comment in self.reddit_object["comments"]:
56+
comment["comment_body"] = comment["comment_body"].replace('\n', '. ')
57+
if comment["comment_body"][-1] != '.':
58+
comment["comment_body"] += '.'
59+
5460
def run(self) -> Tuple[int, int]:
5561

5662
Path(self.path).mkdir(parents=True, exist_ok=True)
5763
print_step("Saving Text to MP3 files...")
58-
64+
65+
self.add_periods()
5966
self.call_tts("title", process_text(self.reddit_object["thread_title"]))
6067
# processed_text = ##self.reddit_object["thread_post"] != ""
6168
idx = None

main.py

+7-10
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from video_creation.screenshot_downloader import get_screenshots_of_reddit_posts
2424
from video_creation.voices import save_text_to_mp3
2525

26-
__VERSION__ = "3.0"
26+
__VERSION__ = "3.0.1"
2727

2828
print(
2929
"""
@@ -42,7 +42,7 @@
4242
checkversion(__VERSION__)
4343

4444

45-
def main(POST_ID=None):
45+
def main(POST_ID=None) -> None:
4646
global redditid ,reddit_object
4747
reddit_object = get_subreddit_threads(POST_ID)
4848
redditid = id(reddit_object)
@@ -55,7 +55,7 @@ def main(POST_ID=None):
5555
make_final_video(number_of_comments, length, reddit_object, bg_config)
5656

5757

58-
def run_many(times):
58+
def run_many(times) -> None:
5959
for x in range(1, times + 1):
6060
print_step(
6161
f'on the {x}{("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th")[x % 10]} iteration of {times}'
@@ -108,11 +108,8 @@ def shutdown():
108108

109109
shutdown()
110110
except Exception as err:
111-
print_step(f'''
112-
Sorry, something went wrong with this version! Try again, and feel free to report this issue at GitHub or the Discord community.\n
113-
Version: {__VERSION__} \n
114-
Story mode: {str(config["settings"]["storymode"])} \n
115-
Story mode method: {str(config["settings"]["storymodemethod"])}
116-
''')
111+
print_step(f'Sorry, something went wrong with this version! Try again, and feel free to report this issue at GitHub or the Discord community.\n'
112+
f'Version: {__VERSION__},Story mode: {str(config["settings"]["storymode"])}, Story mode method: {str(config["settings"]["storymodemethod"])},\n'
113+
f'Postid : {str(config["settings"])},allownsfw :{config["settings"]["allow_nsfw"]},is_nsfw : {str(reddit_object["is_nsfw"])}'
114+
)
117115
raise err
118-
# todo error

reddit/subreddit.py

+1
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ def get_subreddit_threads(POST_ID: str):
134134
content["thread_url"] = threadurl
135135
content["thread_title"] = submission.title
136136
content["thread_id"] = submission.id
137+
content["is_nsfw"] = submission.over_18
137138
content["comments"] = []
138139
if settings.config["settings"]["storymode"]:
139140
if settings.config["settings"]["storymodemethod"] == 1:

requirements.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ praw==7.6.1
77
prawcore~=2.3.0
88
pytube==12.1.0
99
requests==2.28.1
10-
rich==12.5.1
10+
rich==13.3.1
1111
toml==0.10.2
1212
translators==5.3.1
1313
pyttsx3==2.90

utils/backgrounds.json

+4-4
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@
44
"https://www.youtube.com/watch?v=vw5L4xCPy9Q",
55
"bike-parkour-gta.mp4",
66
"Achy Gaming",
7-
480
7+
"center"
88
],
99
"rocket-league": [
1010
"https://www.youtube.com/watch?v=2X9QGY__0II",
1111
"rocket_league.mp4",
1212
"Orbital Gameplay",
13-
200
13+
"center"
1414
],
1515
"minecraft": [
1616
"https://www.youtube.com/watch?v=n_Dv4JMiwK8",
@@ -22,7 +22,7 @@
2222
"https://www.youtube.com/watch?v=qGa9kWREOnE",
2323
"gta-stunt-race.mp4",
2424
"Achy Gaming",
25-
480
25+
"center"
2626
],
2727
"csgo-surf": [
2828
"https://www.youtube.com/watch?v=E-8JlyO59Io",
@@ -34,7 +34,7 @@
3434
"https://www.youtube.com/watch?v=uVKxtdMgJVU",
3535
"cluster_truck.mp4",
3636
"No Copyright Gameplay",
37-
480
37+
"center"
3838
],
3939
"minecraft-2": [
4040
"https://www.youtube.com/watch?v=Pt5_GSKIWQM",

utils/console.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -10,28 +10,28 @@
1010
console = Console()
1111

1212

13-
def print_markdown(text):
13+
def print_markdown(text) -> None:
1414
"""Prints a rich info message. Support Markdown syntax."""
1515

1616
md = Padding(Markdown(text), 2)
1717
console.print(md)
1818

1919

20-
def print_step(text):
20+
def print_step(text) -> None:
2121
"""Prints a rich info message."""
2222

2323
panel = Panel(Text(text, justify="left"))
2424
console.print(panel)
2525

2626

27-
def print_table(items):
27+
def print_table(items) -> None:
2828
"""Prints items in a table."""
2929

3030
console.print(Columns([Panel(f"[yellow]{item}", expand=True) for item in items]))
3131

3232

33-
def print_substep(text, style=""):
34-
"""Prints a rich info message without the panelling."""
33+
def print_substep(text, style="") -> None:
34+
"""Prints a rich colored info message without the panelling."""
3535
console.print(text, style=style)
3636

3737

utils/imagenarator.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from rich.progress import track
77
from TTS.engine_wrapper import process_text
88

9-
def draw_multiple_line_text(image, text, font, text_color, padding, wrap=50):
9+
def draw_multiple_line_text(image, text, font, text_color, padding, wrap=50) -> None:
1010
"""
1111
Draw multiline text over given image
1212
"""
@@ -24,7 +24,7 @@ def draw_multiple_line_text(image, text, font, text_color, padding, wrap=50):
2424

2525

2626
# theme=bgcolor,reddit_obj=reddit_object,txtclr=txtcolor
27-
def imagemaker(theme, reddit_obj: dict, txtclr, padding=5):
27+
def imagemaker(theme, reddit_obj: dict, txtclr, padding=5) -> None:
2828
"""
2929
Render Images for video
3030
"""

utils/voice.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from datetime import timezone
1414

1515

16-
def check_ratelimit(response: Response):
16+
def check_ratelimit(response: Response) -> bool:
1717
"""
1818
Checks if the response is a ratelimit response.
1919
If it is, it sleeps for the time specified in the response.
@@ -30,7 +30,7 @@ def check_ratelimit(response: Response):
3030
return True
3131

3232

33-
def sleep_until(time):
33+
def sleep_until(time) -> None:
3434
"""
3535
Pause your program until a specific end time.
3636
'time' is either a valid datetime object or unix timestamp in seconds (i.e. seconds since Unix epoch)

video_creation/screenshot_downloader.py

+33-5
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@
1212
from utils.console import print_step, print_substep
1313
from utils.imagenarator import imagemaker
1414

15+
from utils.videos import save_data
1516

1617
__all__ = ["download_screenshots_of_reddit_posts"]
1718

19+
1820
def get_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: int):
1921
"""Downloads screenshots of reddit posts as seen on the web. Downloads to assets/temp/png
2022
@@ -37,7 +39,7 @@ def get_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: int):
3739
with sync_playwright() as p:
3840
print_substep("Launching Headless Browser...")
3941

40-
browser = p.chromium.launch() # headless=False #to check for chrome view
42+
browser = p.chromium.launch(headless=True) # headless=False will show the browser for debugging purposes
4143
context = browser.new_context()
4244
# Device scale factor (or dsf for short) allows us to increase the resolution of the screenshots
4345
# When the dsf is 1, the width of the screenshot is 600 pixels
@@ -71,6 +73,20 @@ def get_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: int):
7173

7274
context.add_cookies(cookies) # load preference cookies
7375

76+
# Login to Reddit
77+
print_substep("Logging in to Reddit...")
78+
page = context.new_page()
79+
page.goto("https://www.reddit.com/login", timeout=0)
80+
page.set_viewport_size(ViewportSize(width=1920, height=1080))
81+
page.wait_for_load_state()
82+
83+
page.locator('[name="username"]').fill(settings.config["reddit"]["creds"]["username"])
84+
page.locator('[name="password"]').fill(settings.config["reddit"]["creds"]["password"])
85+
page.locator("button:has-text('Log In')").click()
86+
87+
page.wait_for_load_state() # Wait for page to fully load and add 5 seconds
88+
page.wait_for_timeout(5000)
89+
7490
# Get the thread screenshot
7591
page = context.new_page()
7692
page.goto(reddit_object["thread_url"], timeout=0)
@@ -105,7 +121,21 @@ def get_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: int):
105121
print_substep("Skipping translation...")
106122

107123
postcontentpath = f"assets/temp/{reddit_id}/png/title.png"
108-
page.locator('[data-test-id="post-content"]').screenshot(path=postcontentpath)
124+
try:
125+
page.locator('[data-test-id="post-content"]').screenshot(path=postcontentpath)
126+
except Exception as e:
127+
print_substep("Something went wrong!",style="red")
128+
resp = input("Something went wrong with making the screenshots! Do you want to skip the post? (y/n) ")
129+
130+
if resp.casefold().startswith("y"):
131+
save_data("", "", "skipped", reddit_id, "")
132+
print_substep("The post is successfully skipped! You can now restart the program and this post will skipped.","green")
133+
134+
resp = input("Do you want the error traceback for debugging purposes? (y/n)")
135+
if not resp.casefold().startswith("y"):
136+
exit()
137+
138+
raise e
109139

110140
if storymode:
111141
page.locator('[data-click-id="text"]').first.screenshot(
@@ -151,6 +181,4 @@ def get_screenshots_of_reddit_posts(reddit_object: dict, screenshot_num: int):
151181
# close browser instance when we are done using it
152182
browser.close()
153183

154-
155-
156-
print_substep("Screenshots downloaded Successfully.", style="bold green")
184+
print_substep("Screenshots downloaded Successfully.", style="bold green")

0 commit comments

Comments
 (0)