Skip to content

Commit

Permalink
Working but needs cleaned
Browse files Browse the repository at this point in the history
  • Loading branch information
jake-lower17 committed Nov 20, 2021
0 parents commit 525cb76
Show file tree
Hide file tree
Showing 14 changed files with 509 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/env
.env
/data
__pycache__
client_secrets.json
*.json
95 changes: 95 additions & 0 deletions CreateMovie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
from moviepy.editor import *
import random
import os

dir_path = os.path.dirname(os.path.realpath(__file__))
music_path = os.path.join(dir_path, "Music/")

def add_return_comment(comment):
need_return = 30
new_comment = ""
return_added = 0
return_added += comment.count('\n')
for i, letter in enumerate(comment):
if i > need_return and letter == " ":
letter = "\n"
need_return += 30
return_added += 1
new_comment += letter
return new_comment, return_added


class CreateMovie():

@classmethod
def CreateMP4(cls, post_data):

clips = []
for post in post_data:
print(post['image_path'])
if "gif" not in post['image_path']:
clip = ImageSequenceClip([post['image_path']], durations=[12])
clips.append(clip)
else:
clip = VideoFileClip(post['image_path'])
clip_lengthener = [clip] * 60
clip = concatenate_videoclips(clip_lengthener)
clip = clip.subclip(0,12)
clips.append(clip)

# After we have out clip.
clip = concatenate_videoclips(clips)

# Hack to fix getting extra frame errors??
clip = clip.subclip(0,60)

colors = ['yellow', 'LightGreen', 'LightSkyBlue', 'LightPink4', 'SkyBlue2', 'MintCream','LimeGreen', 'WhiteSmoke', 'HotPink4']
colors = colors + ['PeachPuff3', 'OrangeRed3', 'silver']
random.shuffle(colors)
text_clips = []
notification_sounds = []
for i, post in enumerate(post_data):
print(post['Best_comment'])
return_comment, return_count = add_return_comment(post['Best_comment'])
txt = TextClip(return_comment, font='Courier',
fontsize=38, color=colors.pop(), bg_color='black')
txt = txt.set_position((5,500))
txt = txt.set_start((0, 3 + (i * 12))) # (min, s)
txt = txt.set_duration(7)
txt = txt.crossfadein(0.5)
txt = txt.crossfadeout(0.5)
text_clips.append(txt)
return_comment, _ = add_return_comment(post['best_reply'])
txt = TextClip(return_comment, font='Courier',
fontsize=38, color=colors.pop(), bg_color='black')
#print(TextClip.list('color'))
txt = txt.set_position((15,585 + (return_count * 50)))
txt = txt.set_start((0, 5 + (i * 12))) # (min, s)
txt = txt.set_duration(7)
txt = txt.crossfadein(0.5)
txt = txt.crossfadeout(0.5)
text_clips.append(txt)
notification = AudioFileClip("notification.mp3")
notification = notification.set_start((0, 3 + (i * 12)))
#notification = notification.set_duration(2)
notification_sounds.append(notification)
notification = AudioFileClip("notification.mp3")
notification = notification.set_start((0, 5 + (i * 12)))
#notification = notification.set_duration(2)
notification_sounds.append(notification)

music_file = os.path.join(music_path, f"music{random.randint(0,4)}.mp3")
music = AudioFileClip(music_file)
music = music.set_start((0,0))
music = music.volumex(.4)
music = music.set_duration(59)

notification = AudioFileClip("notification.mp3")
new_audioclip = CompositeAudioClip([music]+notification_sounds)

clip = CompositeVideoClip([clip] + text_clips)
clip.audio = new_audioclip
clip.write_videofile("video.mp4", fps = 24)

if __name__ == '__main__':
print(TextClip.list('color'))
Binary file added Music/music0.mp3
Binary file not shown.
Binary file added Music/music1.mp3
Binary file not shown.
Binary file added Music/music2.mp3
Binary file not shown.
Binary file added Music/music3.mp3
Binary file not shown.
Binary file added Music/music4.mp3
Binary file not shown.
125 changes: 125 additions & 0 deletions RedditBot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import os
import praw
from dotenv import load_dotenv
from datetime import date
import requests
import json
from Scalegif import scale_gif

load_dotenv()

class RedditBot():

def __init__(self):
self.reddit = praw.Reddit(
client_id=os.getenv('client_id'),
client_secret=os.getenv('client_secret'),
user_agent=os.getenv('user_agent'),
)
dir_path = os.path.dirname(os.path.realpath(__file__))
self.data_path = os.path.join(dir_path, "data/")
self.post_data = []
self.already_posted = []
if os.path.isfile("posted_already.json"):
with open("posted_already.json", "r") as file:
self.already_posted = json.load(file)
#print(self.already_posted)

def get_posts(self):
self.post_data = []
subreddit = self.reddit.subreddit("memes")
posts = []
for submission in subreddit.top("day", limit=20):
if submission.stickied:
print("Mod Post")
else:
posts.append(submission)

return posts

def create_data_folder(self):
today = date.today()
dt_string = today.strftime("%m%d%Y")
data_folder_path = os.path.join(self.data_path, f"{dt_string}/")
CHECK_FOLDER = os.path.isdir(data_folder_path)
# If folder doesn't exist, then create it.
if not CHECK_FOLDER:
os.makedirs(data_folder_path)

def save_image(self, submission):
if "jpg" in submission.url.lower() or "png" in submission.url.lower() or "gif" in submission.url.lower():
#try:

# Get all images to ignore
dt_string = date.today().strftime("%m%d%Y")
data_folder_path = os.path.join(self.data_path, f"{dt_string}/")
CHECK_FOLDER = os.path.isdir(data_folder_path)
if CHECK_FOLDER and len(self.post_data) < 5 and not submission.over_18 and submission.id not in self.already_posted:
image_path = f"{data_folder_path}Post-{submission.id}{submission.url.lower()[-4:]}"

# Get the image and write the path
r = requests.get(submission.url.lower())
with open(image_path, 'wb') as f:
f.write(r.content)

# Could do transforms on images like resize!
#image = cv2.resize(image,(720,1280))
scale_gif(image_path, (720,1280))

#cv2.imwrite(f"{image_path}", image)
submission.comment_sort = 'best'

# Get best comment.
for top_level_comment in submission.comments:
# Here you can fetch data off the comment.
# For the sake of example, we're just printing the comment body.
best_comment = top_level_comment
if len(best_comment.body) <= 140 and "http" not in best_comment.body:
break

best_comment.reply_sort = "top"
best_comment.refresh()
replies = best_comment.replies

for top_level_comment in replies:
# Here you can fetch data off the comment.
# For the sake of example, we're just printing the comment body.
best_reply = top_level_comment
if len(best_reply.body) <= 140 and "http" not in best_reply.body:
break

data_file = {
"image_path": image_path,
'id':submission.id,
"title": submission.title,
"score": submission.score,
"18": submission.over_18,
"Best_comment": best_comment.body,
"best_reply": best_reply.body
}

self.post_data.append(data_file)
self.already_posted.append(submission.id)
with open(f"{data_folder_path}{submission.id}.json", "w") as outfile:
json.dump(data_file, outfile)
with open("posted_already.json", "w") as outfile:
json.dump(self.already_posted, outfile)
else:
return None

#except Exception as e:
# print(f"Image failed. {submission.url.lower()}")
# print(e)

if __name__ == "__main__":
redditbot = RedditBot()
posts = redditbot.get_posts()

# Create folder if it doesn't exist
redditbot.create_data_folder()

for post in posts:
#print(post.title, post.url, post.permalink)
redditbot.save_image(post)

#redditbot.create_movie()
47 changes: 47 additions & 0 deletions Scalegif.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from PIL import Image

def scale_gif(path, scale, new_path=None):
gif = Image.open(path)
if not new_path:
new_path = path
if path[-3:] == "gif":
old_gif_information = {
'loop': bool(gif.info.get('loop', 1)),
'duration': gif.info.get('duration', 40),
'background': gif.info.get('background', 223),
'extension': gif.info.get('extension', (b'NETSCAPE2.0')),
'transparency': gif.info.get('transparency', 223)
}
print(path)
print(old_gif_information)
new_frames = get_new_frames(gif, scale)
save_new_gif(new_frames, old_gif_information, new_path)
else:
gif = gif.resize(scale)
gif.save(path)


def get_new_frames(gif, scale):
new_frames = []
actual_frames = gif.n_frames
for frame in range(actual_frames):
gif.seek(frame)
new_frame = Image.new('RGBA', gif.size)
new_frame.paste(gif)
new_frame = new_frame.resize(scale, Image.ANTIALIAS)
new_frames.append(new_frame)
return new_frames

def save_new_gif(new_frames, old_gif_information, new_path):
new_frames[0].save(new_path,
save_all = True,
append_images = new_frames[1:],
duration = old_gif_information['duration'],
loop = old_gif_information['loop'],
background = old_gif_information['background'],
extension = old_gif_information['extension'] ,
transparency = old_gif_information['transparency'])


if __name__ == "__main__":
scale_gif(f"Post-qtehpj.gif", (720,1280),"test.gif")
47 changes: 47 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from CreateMovie import CreateMovie
from RedditBot import RedditBot
from upload_video import update_video
from datetime import date
import time

def GetDaySuffix(day):
if day == 1 or day == 21 or day == 31:
return "st"
elif day == 2 or day == 22:
return "nd"
elif day == 3 or day == 23:
return "rd"
else:
return "th"

#Create data
redditbot = RedditBot()

while True:
# Make sure to do just this inside loop.
posts = redditbot.get_posts()

# Create folder if it doesn't exist
redditbot.create_data_folder()

for post in posts:
redditbot.save_image(post)

day = date.today().strftime("%d")
day = str(int(day)) + GetDaySuffix(int(day))

CreateMovie.CreateMP4(redditbot.post_data)
dt_string = date.today().strftime("%A %B") + f" {day}"

video_data = {
"file": "video.mp4",
"title": f"{redditbot.post_data[0]['title']} - Dankest memes and comments {dt_string}!",
"description": "#shorts\nGiving you the hottest memes of the day with funny comments!",
"keywords":"meme,reddit,Dankestmemes",
"privacyStatus":"public"
}
print(video_data["title"])
print("Printing in 60 seconds...")
time.sleep(60)
update_video(video_data)
time.sleep(60 * 60 * 24 - 1)
Binary file added notification.mp3
Binary file not shown.
38 changes: 38 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
cachetools==4.2.4
certifi==2021.10.8
charset-normalizer==2.0.7
colorama==0.4.4
decorator==4.4.2
google-api-core==2.2.1
google-api-python-client==2.28.0
google-auth==2.3.2
google-auth-httplib2==0.1.0
google-auth-oauthlib==0.4.6
googleapis-common-protos==1.53.0
httplib2==0.20.1
idna==3.3
imageio==2.10.1
imageio-ffmpeg==0.4.5
moviepy==1.0.3
numpy==1.21.3
oauthlib==3.1.1
opencv-python==4.5.4.58
Pillow==8.4.0
praw==7.4.0
prawcore==2.3.0
proglog==0.1.9
protobuf==3.19.1
pyasn1==0.4.8
pyasn1-modules==0.2.8
pyparsing==2.4.7
python-dotenv==0.19.1
requests==2.26.0
requests-oauthlib==1.3.0
rsa==4.7.2
scipy==1.7.1
six==1.16.0
tqdm==4.62.3
update-checker==0.18.0
uritemplate==4.1.1
urllib3==1.26.7
websocket-client==1.2.1
Loading

0 comments on commit 525cb76

Please sign in to comment.