Amazing-Python-Scripts
126 строк · 3.8 Кб
1import praw2import PySimpleGUI as sg3import wget4import pandas as pd5import datetime as dt6import json7import os8
9destination_folder = sg.popup_get_folder(10'Choose where to download files:\n\n'11'NOTE: A folder to store the files will be created within the directory!',12default_path='',13title='Choose destination')14folder_lst = [destination_folder]15if folder_lst[0] is None:16sg.Popup('Destination not specified!\nProgram terminated!',17title='ERROR: No destination!',18custom_text='Close',19button_type=0)20raise SystemExit()21
22
23class RedditCred:24def __init__(self):25self.text_file = 'reddit_tokens.json'26
27
28# Functions made to read the reddit app id and secret from file
29
30
31def read_id(self):32file = self.text_file33with open(file, 'r') as f:34data = json.load(f)35keys = data.keys()36return str(*keys)37
38def read_secret(self):39file = self.text_file40with open(file, 'r') as f:41data = json.load(f)42value = data.values()43return str(*value)44
45
46red_cred = RedditCred()47u_agent = 'Script that downloads memes from various subreddits'48
49reddit = praw.Reddit(client_id=red_cred.read_id(),50client_secret=red_cred.read_secret(),51user_agent=u_agent)52
53subreddit = reddit.subreddit(54'deepfriedmemes+surrealmemes+nukedmemes+bigbangedmemes+wackytictacs+bonehurtingjuice'55)
56posts = subreddit.hot(limit=25)57
58# Empty lists to hold data
59
60image_urls = []61image_titles = []62image_scores = []63image_timestamps = []64image_ids = []65image_extensions = ['.jpg', '.jpeg', '.png']66
67# This iterates through posts and collects their data into lists
68
69for post in posts:70image_urls.append(post.url.encode('utf-8'))71image_titles.append(post.title.encode('utf-8'))72image_scores.append(post.score)73image_timestamps.append(dt.datetime.fromtimestamp(post.created))74image_ids.append(post.id)75
76# This creates a GUI window with a progress bar to keep track of the download
77
78layout = [[sg.Text(f"Downloading files...", key='textkey')],79[sg.ProgressBar(25, orientation='h', size=(20, 20), key='progbar')],80[sg.Cancel()]]81
82window = sg.Window('Download in Progress', layout)83
84# This iterates through URLs, checks if it has the specified image extension and downloads the image
85
86for index, url in enumerate(image_urls):87path = str(folder_lst[0])88file_ending = str(url)[2:-1]89event, values = window.read(timeout=0)90_, extension = os.path.splitext(file_ending)91if extension in image_extensions:92try:93if os.path.exists(path + '/' + 'Downloaded Images'):94pass95else:96os.mkdir(path + '/' + 'Downloaded Images')97if event == 'Cancel' or event == sg.WIN_CLOSED:98break99
100destination = str(folder_lst[0]) + '/' + 'Downloaded Images' + '/'101window['progbar'].update_bar(index + 1)102print(103f"Downloading '{str(image_titles[index])[2:-1]}' to '{path}' from '{str(image_urls[index])[2:-1]}'"104)105download = wget.download(str(image_urls[index])[2:-1],106out=destination)107except:108print(109f"Something went wrong while downloading '{str(image_urls[index])[2:-1]}'\n"110)111else:112print("\nDownload complete!")113window.close()114sg.Popup(f"Files downloaded into:\n\n'{path}/Downloaded Images'",115title='Download complete!')116
117# Optional saving of collected data to .csv file
118
119dataframe = pd.DataFrame({120'Title': image_titles,121'Score': image_scores,122'URL': image_urls,123'Timestamp': image_timestamps,124'ID': image_ids125})126csv = dataframe.to_csv('./images.csv', index=True, header=True)127