Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
elebumm
GitHub Repository: elebumm/redditvideomakerbot
Path: blob/master/utils/subreddit.py
846 views
1
import json
2
from os.path import exists
3
4
from utils import settings
5
from utils.ai_methods import sort_by_similarity
6
from utils.console import print_substep
7
8
9
def _contains_blocked_words(text: str) -> bool:
10
"""Returns True if the text contains any blocked words from config."""
11
blocked_raw = settings.config["reddit"]["thread"].get("blocked_words", "")
12
if not blocked_raw:
13
return False
14
blocked = [w.strip().lower() for w in blocked_raw.split(",") if w.strip()]
15
text_lower = text.lower()
16
return any(word in text_lower for word in blocked)
17
18
19
def get_subreddit_undone(submissions: list, subreddit, times_checked=0, similarity_scores=None):
20
"""_summary_
21
22
Args:
23
submissions (list): List of posts that are going to potentially be generated into a video
24
subreddit (praw.Reddit.SubredditHelper): Chosen subreddit
25
26
Returns:
27
Any: The submission that has not been done
28
"""
29
# Second try of getting a valid Submission
30
if times_checked and settings.config["ai"]["ai_similarity_enabled"]:
31
print("Sorting based on similarity for a different date filter and thread limit..")
32
submissions = sort_by_similarity(
33
submissions, keywords=settings.config["ai"]["ai_similarity_enabled"]
34
)
35
36
# recursively checks if the top submission in the list was already done.
37
if not exists("./video_creation/data/videos.json"):
38
with open("./video_creation/data/videos.json", "w+") as f:
39
json.dump([], f)
40
with open("./video_creation/data/videos.json", "r", encoding="utf-8") as done_vids_raw:
41
done_videos = json.load(done_vids_raw)
42
for i, submission in enumerate(submissions):
43
if already_done(done_videos, submission):
44
continue
45
if submission.over_18:
46
try:
47
if not settings.config["settings"]["allow_nsfw"]:
48
print_substep("NSFW Post Detected. Skipping...")
49
continue
50
except AttributeError:
51
print_substep("NSFW settings not defined. Skipping NSFW post...")
52
if submission.stickied:
53
print_substep("This post was pinned by moderators. Skipping...")
54
continue
55
if _contains_blocked_words(submission.title + " " + (submission.selftext or "")):
56
print_substep("Post contains a blocked word. Skipping...")
57
continue
58
if (
59
submission.num_comments <= int(settings.config["reddit"]["thread"]["min_comments"])
60
and not settings.config["settings"]["storymode"]
61
):
62
print_substep(
63
f'This post has under the specified minimum of comments ({settings.config["reddit"]["thread"]["min_comments"]}). Skipping...'
64
)
65
continue
66
if settings.config["settings"]["storymode"]:
67
if not submission.selftext:
68
print_substep("You are trying to use story mode on post with no post text")
69
continue
70
else:
71
# Check for the length of the post text
72
if len(submission.selftext) > (
73
settings.config["settings"]["storymode_max_length"] or 2000
74
):
75
print_substep(
76
f"Post is too long ({len(submission.selftext)}), try with a different post. ({settings.config['settings']['storymode_max_length']} character limit)"
77
)
78
continue
79
elif len(submission.selftext) < 30:
80
continue
81
if settings.config["settings"]["storymode"] and not submission.is_self:
82
continue
83
if similarity_scores is not None:
84
return submission, similarity_scores[i].item()
85
return submission
86
print("all submissions have been done going by top submission order")
87
VALID_TIME_FILTERS = [
88
"day",
89
"hour",
90
"month",
91
"week",
92
"year",
93
"all",
94
] # set doesn't have __getitem__
95
index = times_checked + 1
96
if index == len(VALID_TIME_FILTERS):
97
print("All submissions have been done.")
98
99
return get_subreddit_undone(
100
subreddit.top(
101
time_filter=VALID_TIME_FILTERS[index],
102
limit=(50 if int(index) == 0 else index + 1 * 50),
103
),
104
subreddit,
105
times_checked=index,
106
) # all the videos in hot have already been done
107
108
109
def already_done(done_videos: list, submission) -> bool:
110
"""Checks to see if the given submission is in the list of videos
111
112
Args:
113
done_videos (list): Finished videos
114
submission (Any): The submission
115
116
Returns:
117
Boolean: Whether the video was found in the list
118
"""
119
120
for video in done_videos:
121
if video["id"] == str(submission):
122
return True
123
return False
124
125