PawinC commited on
Commit
68be93f
1 Parent(s): 80b53e6

Delete UpscalerBotV1.py

Browse files
Files changed (1) hide show
  1. UpscalerBotV1.py +0 -213
UpscalerBotV1.py DELETED
@@ -1,213 +0,0 @@
1
- import os, datetime, pytz, discord, shutil, requests, subprocess
2
- from discord.ext import commands
3
- from time import perf_counter
4
-
5
- CLIENT_SECRET = "Ca3tbHTsbImaDmlzXqnpUQLONYtBY1eA"
6
- TOKEN = "OTE5ODk0NDEwODkwNzI3NDg1.G96t2g.XV5efYvSNKqsNvPFxwmviLi-oY6oAYVPTzV78A"
7
- ADMINS = [766145655038410763, 937495666471628831]
8
- basepath = r"C:\Users\Pawin\Software\real-esrgan\discordbot"
9
-
10
- def getloggingtime():
11
- return datetime.datetime.now(pytz.timezone('Asia/Bangkok')).strftime('%d/%m/%Y %H:%M:%S')
12
-
13
- def generate_id(path):
14
- return str(len(os.listdir(path))+1).zfill(3)
15
-
16
- def file_cleanup():
17
- dirlist = [fr"{basepath}\input", fr"{basepath}\output"]
18
- for directory in dirlist:
19
- shutil.rmtree(directory)
20
- os.mkdir(directory)
21
- print("BOT: Sucessfully cleaned directories")
22
-
23
- file_cleanup()
24
-
25
- client = commands.Bot(
26
- command_prefix = "!",
27
- case_insensitive = True,
28
- help_command = None,
29
- activity = discord.Streaming(name = f"/help | Local Instance", url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ")
30
- )
31
-
32
- """BOT EVENTS"""
33
- #Show Status When Bot Is Ready
34
- @client.event
35
- async def on_ready():
36
- print('BOT: We have successfully logged in as {0.user}\n'.format(client))
37
-
38
-
39
- @client.event
40
- async def on_message(message):
41
- msg = str(message.content)
42
- validMediaChannels = [1083235916354703430, 896342418859892736, 915795164721709077]
43
- channel = message.channel
44
- author = message.author
45
-
46
- channelId = int(channel.id)
47
- authorId = int(author.id)
48
- #print(f"Channel id is {channelId}, author id is {authorId}")
49
-
50
- imageList = []
51
- for item in message.attachments:
52
- if item.content_type.startswith("image"):
53
- imageList.append(item.url)
54
-
55
- if message.author.bot or msg.startswith("p!"):
56
- pass
57
-
58
- elif (authorId in ADMINS) and (channelId in validMediaChannels) and (message.attachments) and (imageList):
59
- print(f'IMAGE: New attachment recieved from {author} in channel {channel}. Processing...')
60
- jobReceiptMessage = await message.channel.send(f"\nUpscale job received for message {message.id}")
61
- jobStatusMessage = await message.channel.send(f"Status: Starting upscale.")
62
-
63
-
64
- attachmentCount = len(imageList)
65
- multipleImages = attachmentCount > 1
66
- if multipleImages:
67
- batchstart = perf_counter()
68
- taskType = "Batch Upscale"
69
- else:
70
- taskType = "Image Upscaling"
71
-
72
- for i in range(attachmentCount):
73
-
74
- """PREPROCESSING"""
75
- fileid = f"{message.id}_{i}"
76
- statusTemplate = f"__Status__: %CURRENTSTEP% image from message *{message.id}* **({i+1}/{attachmentCount})**."
77
- await jobStatusMessage.edit(content=statusTemplate.replace("%CURRENTSTEP%", "🔄 Preprocessing"))
78
-
79
- starttime = perf_counter()
80
- url = imageList[i]
81
-
82
- extension = url.split(".")[-1]
83
- #fileid = generate_id(f"{basepath}\input")
84
-
85
- inputfile = fr"{basepath}\input\{fileid}.{extension}"
86
- outputfile = fr"{basepath}\output\{fileid}.png"
87
-
88
- with open (inputfile, "wb") as f:
89
- f.write(requests.get(url).content)
90
-
91
-
92
-
93
- """UPSCALE CONFIG"""
94
- ai_model = "realesrgan-x4plus-anime"
95
- #Can be realesr-animevideov3 (default) | realesrgan-x4plus | realesrgan-x4plus-anime | realesrnet-x4plus
96
- if ai_model == "realesr-animevideov3":
97
- scale = "2"
98
- tilesize = "768"
99
- resizeRequired = False
100
- else:
101
- scale = "4"
102
- tilesize = "256"
103
- resizeRequired = True
104
-
105
- #Scale 2 only works with the default model
106
- execute_upscale = fr"C:\Users\Pawin\Software\real-esrgan\realesrgan-ncnn-vulkan.exe -i {inputfile} -o {outputfile} -s {scale} -n {ai_model} -f png -t {tilesize} -j 1:1:1"
107
-
108
-
109
-
110
- """UPSCALING"""
111
- pendtime = perf_counter()
112
- preprocessingtime = round((pendtime-starttime), 2)
113
- print(f"PREPROCESS: Completed in {preprocessingtime}s.\nUPSCALE:")
114
- await jobStatusMessage.edit(content=(statusTemplate.replace("%CURRENTSTEP%", "🧠 Upscaling")+"\nThis may take a while..."))
115
- #os.system(execute_upscale)
116
- subprocess.run(execute_upscale, shell=True)
117
-
118
- uendtime = perf_counter()
119
-
120
- upscaletime = round((uendtime-pendtime),2)
121
- print(f"UPSCALE: Completed in {upscaletime}s.")
122
-
123
-
124
-
125
- """RESIZING"""
126
- if resizeRequired:
127
- await jobStatusMessage.edit(content=statusTemplate.replace("%CURRENTSTEP%", "⚙️ Resizing"))
128
- subprocess.run(f"mogrify -resize 50% {outputfile}", shell=True)
129
- rendtime = perf_counter()
130
- resizingtime = round((rendtime-uendtime), 2)
131
- print(f"RESIZE: Completed in {resizingtime}s.")
132
- else:
133
- resizingtime = 0
134
-
135
-
136
-
137
- """DELIVERING"""
138
- await jobStatusMessage.edit(content=statusTemplate.replace("%CURRENTSTEP%", "✉️ Sending"))
139
-
140
- try:
141
- file=discord.File(outputfile)
142
- imgurl = f"attachment://{fileid}.png"
143
- prepembed=discord.Embed(title="Sucessfully Upscaled Image")
144
- prepembed.set_image(url=imgurl)
145
-
146
- jobResultMessage = await message.channel.send(embed=prepembed, file=file)
147
-
148
- outputImageUrl = jobResultMessage.embeds[0].image.url
149
- #outputImageUrl = jobResultMessage.attachments[0].url
150
-
151
- #print(outputImageUrl)
152
- embed = discord.Embed(title="Upscaled Image", url=outputImageUrl)
153
- embed.set_author(name=author, icon_url=message.author.avatar_url)
154
- embed.set_image(url=imgurl)
155
- processingstats = f"Preprocessing took {preprocessingtime}s | Resizing took {resizingtime}s."
156
- embed.set_footer(text=f"Took {upscaletime}s to upscale {fileid}.\nUpscaling done with {ai_model}.\n{processingstats}")
157
-
158
- await jobResultMessage.edit(embed=embed)
159
-
160
- except discord.errors.HTTPException as e:
161
- baseErrorMessage = f"There was an error sending the output for image id {fileid}."
162
- if '413 Payload Too Large' in str(e):
163
- await message.channel.send(f"{baseErrorMessage} It was probably too large for discord to handle.\n```python\n{e}```")
164
- else:
165
- await message.channel.send(f"{baseErrorMessage}\n```python\n{e}```")
166
-
167
- except Exception as e:
168
- await message.channel.send(f"Encountered an error while processing attachment {fileid}\n```python\n{e}```")
169
-
170
-
171
-
172
- """CLEANING UP"""
173
- #Already finished the whole job.
174
- await jobStatusMessage.edit(content=f"\n__Status__: ✅ Job Completed for all {attachmentCount} attachments from message {message.id} at {getloggingtime()}".replace("all 1 attachments", "an attachment"))
175
- await message.delete()
176
- await jobReceiptMessage.delete()
177
-
178
-
179
- print(f"IMAGE: Task completed for messageID {message.id}\n")
180
-
181
-
182
- else:
183
- print(f"MESSAGE: {channel}- {author}: {msg}")
184
- await client.process_commands(message)
185
-
186
-
187
- """BOT COMMANDS"""
188
-
189
- @client.command()
190
- async def test(ctx):
191
- await ctx.send("Hello!")
192
-
193
- @client.command()
194
- async def ping(ctx):
195
- await ctx.send(f'The ping is {round(client.latency * 1000)}ms.')
196
-
197
- @client.command()
198
- async def clear(ctx, amount=None):
199
- if ctx.author.id in ADMINS:
200
- if amount == "all":
201
- amount = 100
202
- elif amount == None:
203
- amount = 2
204
- else:
205
- amount = int(amount)
206
- await ctx.channel.purge(limit=amount)
207
- await ctx.send(f"Finished clearing {amount} messages {ctx.message.author.mention}", delete_after=4)
208
- else:
209
- await ctx.send('You do not have the permissions to to clear messages using this bot.')
210
-
211
- logmsg = f"BOT: Attempting to starting the bot at {getloggingtime()} GMT+7"
212
- print(logmsg)
213
- client.run(TOKEN)