This repository has been archived by the owner on May 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Crawler.py
173 lines (147 loc) · 6.09 KB
/
Crawler.py
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
import os
import shutil
from bs4 import BeautifulSoup
import dearpygui.dearpygui as dpg
import random
from PIL import Image
import win32clipboard
from io import BytesIO
import webbrowser
import urllib.request
import requests
class LSCrawler:
def __init__(self):
debugPrint("Starting...")
self.chars = "abcdefghijklmnopqrstuvwxyz0123456789"
self.folderSetup()
debugPrint("Startup complete.")
####################################################
# Functions below are for the gui #
####################################################
#GUI
dpg.create_context()
dpg.create_viewport(title='LS-Crawler', width=562, height=250, resizable=False)
dpg.setup_dearpygui()
dpg.show_viewport()
self.initMainWindow()
self.setWindowAsPrimary()
self.run()
def initMainWindow(self):
with dpg.texture_registry():
width, height, _, data = dpg.load_image("./assets/placeholder.png")
self.texture_id = dpg.add_dynamic_texture(width, height, data, tag="ImagePreview")
with dpg.window(tag="Window"):
#Image Button
dpg.add_image_button(texture_tag=self.texture_id,width=200,height=175,pos=(12,12),callback=self.openImage)
#Next Image Button
dpg.add_button(label="Next Image",callback=self.nextImage, pos=(232,14), width=300, height=50)
#Copy Image Button
dpg.add_button(label="Copy Image",callback=self.copyImage, pos=(232,76), width=300, height=50)
#Copy Image URL Button
dpg.add_button(label="Copy Image URL",callback=self.copyImageURL, pos=(232,138), width=300, height=51)
def setWindowAsPrimary(self):
dpg.set_primary_window("Window", True)
def run(self):
dpg.start_dearpygui()
dpg.destroy_context()
####################################################
# Functions below are for the buttons #
####################################################
def nextImage(self):
self.setImageToPreview("./assets/download.png") #placeholder for a loading thingy
self.ImageData = self.downloadImage(self.genURLCode())
if not self.ImageData:
debugPrint("Failed to download image. Trying again.")
self.nextImage()
else:
image = Image.open(os.path.expandvars(self.ImageData["ImagePath"]))
image.resize((259,194)).save(os.path.expandvars(str(self.ImageData["ImagePath"]).replace("/Screenshots","/Screenshots/preview")))
self.setImageToPreview(os.path.expandvars(self.ImageData["ImagePath"]).replace("/Screenshots","/Screenshots/preview"))
def copyImage(self):
try:
path = os.path.expandvars(self.ImageData["ImagePath"])
except (KeyError, AttributeError):
os.system("echo " + "I tried to copy a Image before i generated a Image. Man i am dumb lol" + " | clip")
self.sendToClipboard(os.path.expandvars(self.ImageData["ImagePath"]))
def copyImageURL(self):
try:
os.system("echo " + self.ImageData["ImageURL"] + " | clip")
except (KeyError, AttributeError):
os.system("echo " + "I tried to copy a Image Url before i generated a Image. Man i am dumb lol" + " | clip")
def openImage(self):
try:
webbrowser.open(self.ImageData["ImageURL"])
except (KeyError, AttributeError):
debugPrint("No Image to open")
####################################################
# Functions below do the actual work #
####################################################
def setImageToPreview(self, path):
with dpg.texture_registry():
_, _, _, data = dpg.load_image(f"{path}")
dpg.set_value(item = self.texture_id, value = data)
debugPrint("Updated Image Preview")
def downloadImage(self, code):
debugPrint("#####Start of Download Thread#####")
debugPrint(f"Trying to download image from https://prnt.sc/{code}")
try:
webpage = BeautifulSoup(urllib.request.urlopen(urllib.request.Request(f"https://prnt.sc/{code}",headers={'User-Agent': 'Mozilla/5.0'}),timeout=20).read().decode('ISO-8859-1'), 'html.parser')
except:
debugPrint("Timeout reached. (20 Sec)")
debugPrint("######End of Download Thread######")
return False
imageURLs = webpage.find_all('img')
debugPrint(f"Found {len(imageURLs)} images.")
for imageURL in imageURLs:
debugPrint(f"{imageURL['src']}")
debugPrint(f"Choosing {imageURLs[0]['src']}")
if not str(imageURLs[0]['src']).startswith("https://"):
debugPrint("Invalid image URL.")
debugPrint("######End of Download Thread######")
return False
if not os.path.isfile(os.path.expandvars(f"%appdata%/LSCrawler/Screenshots/{code}.png")):
with requests.get(str(imageURLs[0]['src']),headers={'User-Agent': 'Mozilla/5.0'}, stream=True) as url:
#test if the request returned a 404 response
if url.status_code == 404:
debugPrint("Image not found.")
return False
with open(str(os.path.expandvars(f"%appdata%/LSCrawler/Screenshots/{code}.png")), "wb") as file:
shutil.copyfileobj(url.raw, file)
else:
debugPrint(f"Image already exists.")
debugPrint("######End of Download Thread######")
return False
debugPrint("######End of Download Thread######")
results = {"ImagePath":f"%appdata%/LSCrawler/Screenshots/{code}.png","ImageURL":f"https://prnt.sc/{code}"}
return results
def folderSetup(self):
if not os.path.exists(os.path.expandvars("%appdata%/LSCrawler/Screenshots")):
os.makedirs(os.path.expandvars("%appdata%/LSCrawler/Screenshots"))
if not os.path.exists(os.path.expandvars("%appdata%/LSCrawler/Screenshots/preview")):
os.makedirs(os.path.expandvars("%appdata%/LSCrawler/Screenshots/preview"))
def sendToClipboard(self,path):
image = Image.open(path)
output = BytesIO()
image.convert('RGB').save(output, 'BMP')
data = output.getvalue()[14:]
output.close()
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data)
win32clipboard.CloseClipboard()
def placeholder(self):
pass
def genURLCode(self):
code = ""
for _ in range(7):
code += self.chars[random.randint(0,len(self.chars)-1)]
return code
####################################################
# Functions below are helper functions #
####################################################
debug = True
def debugPrint(message):
if debug:
print(f"[LS]> {message}")
if __name__ == "__main__":
thing = LSCrawler()