-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGUI.py
More file actions
248 lines (196 loc) · 10.4 KB
/
Copy pathGUI.py
File metadata and controls
248 lines (196 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# gui.py
from tkinter import *
from tkinter import filedialog
from tkinter.ttk import *
import json
import os
from resources.reddit import Reddit
import threading
class GUI():
def __init__(self):
self.window = Tk()
self.window.title("Enhanced RIS Reddit Image Scraper")
self.window.geometry("800x600")
self.progress = lambda n: Progressbar(self.window, orient=HORIZONTAL, length=n, mode='determinate')
self.scraping = False
self.csvPath = False
self.credentials_file = "credentials.json"
def main(self):
insert_default_text = lambda varname, key: varname.insert(0, str(key))
# Main title
GreetingLabel = Label(self.window, text="Enhanced RIS Reddit Image Scraper", font=("Arial", 16, "bold"))
GreetingLabel.grid(row=0, columnspan=4, sticky="W", padx=10, pady=10)
# Credentials section
cred_frame = Frame(self.window)
cred_frame.grid(row=1, columnspan=4, sticky="ew", padx=10, pady=5)
Label(cred_frame, text="Reddit API Credentials:", font=("Arial", 12, "bold")).pack(anchor="w")
# Load/Save credentials buttons
Button(cred_frame, text="Load Credentials", command=self.__load_credentials).pack(side=LEFT, padx=5)
Button(cred_frame, text="Save Credentials", command=self.__save_credentials).pack(side=LEFT, padx=5)
Button(cred_frame, text="Add New Credential", command=self.__add_credential).pack(side=LEFT, padx=5)
# Credentials display
self.creds_text = Text(self.window, height=6, width=80)
self.creds_text.grid(row=2, columnspan=4, sticky="ew", padx=10, pady=5)
scrollbar = Scrollbar(self.window, orient="vertical", command=self.creds_text.yview)
scrollbar.grid(row=2, column=4, sticky="ns")
self.creds_text.configure(yscrollcommand=scrollbar.set)
# Settings section
settings_frame = Frame(self.window)
settings_frame.grid(row=3, columnspan=4, sticky="ew", padx=10, pady=10)
Label(settings_frame, text="Images per subreddit:", font=("Arial", 11)).grid(row=0, column=0, sticky="w")
self.numberEntry = Entry(settings_frame, width=10)
self.numberEntry.grid(row=0, column=1, sticky="w", padx=5)
insert_default_text(self.numberEntry, 1000)
Label(settings_frame, text="Scraping methods:", font=("Arial", 11)).grid(row=1, column=0, sticky="w")
self.scrape_new = BooleanVar(value=True)
self.scrape_hot = BooleanVar(value=True)
self.scrape_top = BooleanVar(value=True)
Checkbutton(settings_frame, text="New", variable=self.scrape_new).grid(row=1, column=1, sticky="w")
Checkbutton(settings_frame, text="Hot", variable=self.scrape_hot).grid(row=1, column=2, sticky="w")
Checkbutton(settings_frame, text="Top", variable=self.scrape_top).grid(row=1, column=3, sticky="w")
Label(settings_frame, text="Top time period:", font=("Arial", 11)).grid(row=2, column=0, sticky="w")
self.time_period = StringVar(value="all")
time_combo = Combobox(settings_frame, textvariable=self.time_period,
values=["all", "year", "month", "week", "day"], width=10)
time_combo.grid(row=2, column=1, sticky="w", padx=5)
# File selection buttons
buttons_frame = Frame(self.window)
buttons_frame.grid(row=4, columnspan=4, sticky="ew", padx=10, pady=10)
csvButton = Button(buttons_frame, text="Choose CSV File", command=self.__csvFile)
csvButton.pack(side=LEFT, padx=5)
outputButton = Button(buttons_frame, text="Select Output Folder", command=self.__SelectOutputFolder)
outputButton.pack(side=LEFT, padx=5)
runButton = Button(buttons_frame, text="START SCRAPING", command=self.__startScrape)
runButton.pack(side=LEFT, padx=5)
# Progress section
self.progress_frame = Frame(self.window)
self.progress_frame.grid(row=5, columnspan=4, sticky="ew", padx=10, pady=10)
self.status_label = Label(self.progress_frame, text="Ready to scrape", font=("Arial", 10))
self.status_label.pack(anchor="w")
self.progress_bar = Progressbar(self.progress_frame, length=400, mode='determinate')
self.progress_bar.pack(fill=X, pady=5)
# Load credentials on startup
self.__load_credentials()
self.window.mainloop()
def __load_credentials(self):
try:
if os.path.exists(self.credentials_file):
with open(self.credentials_file, 'r') as f:
credentials = json.load(f)
self.creds_text.delete(1.0, END)
for i, cred in enumerate(credentials):
self.creds_text.insert(END, f"Credential {i+1}:\n")
self.creds_text.insert(END, f" Client ID: {cred['client_id']}\n")
self.creds_text.insert(END, f" Client Secret: {cred['client_secret'][:10]}...\n\n")
except Exception as e:
self.creds_text.delete(1.0, END)
self.creds_text.insert(END, f"Error loading credentials: {str(e)}\n")
def __save_credentials(self):
# This would open a dialog to manually edit the JSON file
try:
if os.path.exists(self.credentials_file):
import subprocess
import sys
if sys.platform.startswith('win'):
os.startfile(self.credentials_file)
elif sys.platform.startswith('darwin'):
subprocess.call(['open', self.credentials_file])
else:
subprocess.call(['xdg-open', self.credentials_file])
except Exception as e:
print(f"Could not open credentials file: {e}")
def __add_credential(self):
# Simple dialog to add new credentials
add_window = Toplevel(self.window)
add_window.title("Add Reddit API Credentials")
add_window.geometry("400x200")
Label(add_window, text="Client ID:", font=("Arial", 11)).grid(row=0, column=0, sticky="w", padx=10, pady=5)
client_id_entry = Entry(add_window, width=40)
client_id_entry.grid(row=0, column=1, padx=10, pady=5)
Label(add_window, text="Client Secret:", font=("Arial", 11)).grid(row=1, column=0, sticky="w", padx=10, pady=5)
client_secret_entry = Entry(add_window, width=40, show="*")
client_secret_entry.grid(row=1, column=1, padx=10, pady=5)
def save_new_credential():
client_id = client_id_entry.get().strip()
client_secret = client_secret_entry.get().strip()
if client_id and client_secret:
try:
credentials = []
if os.path.exists(self.credentials_file):
with open(self.credentials_file, 'r') as f:
credentials = json.load(f)
credentials.append({
"client_id": client_id,
"client_secret": client_secret
})
with open(self.credentials_file, 'w') as f:
json.dump(credentials, f, indent=2)
self.__load_credentials()
add_window.destroy()
except Exception as e:
Label(add_window, text=f"Error: {str(e)}", fg="red").grid(row=3, columnspan=2, pady=5)
Button(add_window, text="Save", command=save_new_credential).grid(row=2, column=0, pady=10)
Button(add_window, text="Cancel", command=add_window.destroy).grid(row=2, column=1, pady=10)
def __SelectOutputFolder(self):
self.output = filedialog.askdirectory(title="Choose Export Folder", initialdir='/')
if self.output:
self.status_label.config(text=f"Output folder: {self.output}")
def __csvFile(self):
self.csvPath = filedialog.askopenfilename(
title="Choose Subreddit CSV File",
initialdir='/',
filetypes=(('CSV files', '*.csv'), ('All files', '*.*'))
)
if self.csvPath:
self.status_label.config(text=f"CSV file: {os.path.basename(self.csvPath)}")
def __startScrape(self):
if not self.csvPath:
self.status_label.config(text="Please select a CSV file first!")
return
if not hasattr(self, 'output') or not self.output:
self.status_label.config(text="Please select an output folder first!")
return
if not os.path.exists(self.credentials_file):
self.status_label.config(text="No credentials found! Please add credentials first!")
return
try:
with open(self.credentials_file, 'r') as f:
credentials = json.load(f)
if not credentials:
self.status_label.config(text="No valid credentials found!")
return
self.scraping = True
# Get scraping options
scrape_methods = []
if self.scrape_new.get():
scrape_methods.append('new')
if self.scrape_hot.get():
scrape_methods.append('hot')
if self.scrape_top.get():
scrape_methods.append(('top', self.time_period.get()))
n = int(self.numberEntry.get())
# Start scraping in separate thread
self.scrape_thread = threading.Thread(
target=self.__run_scraper,
args=(credentials, n, scrape_methods)
)
self.scrape_thread.daemon = True
self.scrape_thread.start()
except Exception as e:
self.status_label.config(text=f"Error starting scraper: {str(e)}")
def __run_scraper(self, credentials, n, scrape_methods):
try:
self.Reddit = Reddit(credentials, self.update_progress, self.update_status)
self.Reddit.getSubreddit(csvFile=self.csvPath)
self.Reddit.run(n, self.output, scrape_methods)
self.update_status("Scraping completed!")
except Exception as e:
self.update_status(f"Scraping error: {str(e)}")
def update_progress(self, value):
self.progress_bar['value'] = value
self.window.update_idletasks()
def update_status(self, message):
self.status_label.config(text=message)
self.window.update_idletasks()
def run(self):
self.main()