Skip to content

Commit 5719398

Browse files
authored
Create imagetools.py
1 parent f303e8d commit 5719398

File tree

1 file changed

+292
-0
lines changed

1 file changed

+292
-0
lines changed

plugins/imagetools.py

Lines changed: 292 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,292 @@
1+
# Ultroid - UserBot
2+
# Copyright (C) 2021-2022 TeamUltroid
3+
#
4+
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
5+
# PLease read the GNU Affero General Public License in
6+
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
7+
"""
8+
✘ Commands Available -
9+
10+
• `{i}border <reply to photo/sticker>`
11+
To create border around that media..
12+
Ex - `{i}border 12,22,23`
13+
- `{i}border 12,22,23 ; width (in number)`
14+
15+
• `{i}grey <reply to any media>`
16+
To make it black nd white.
17+
18+
• `{i}color <reply to any Black nd White media>`
19+
To make it Colorfull.
20+
21+
• `{i}toon <reply to any media>`
22+
To make it toon.
23+
24+
• `{i}danger <reply to any media>`
25+
To make it look Danger.
26+
27+
• `{i}negative <reply to any media>`
28+
To make negative image.
29+
30+
• `{i}blur <reply to any media>`
31+
To make it blurry.
32+
33+
• `{i}quad <reply to any media>`
34+
create a Vortex.
35+
36+
• `{i}mirror <reply to any media>`
37+
To create mirror pic.
38+
39+
• `{i}flip <reply to any media>`
40+
To make it flip.
41+
42+
• `{i}sketch <reply to any media>`
43+
To draw its sketch.
44+
45+
• `{i}blue <reply to any media>`
46+
just cool.
47+
48+
• `{i}csample <color name /color code>`
49+
example : `{i}csample red`
50+
`{i}csample #ffffff`
51+
52+
• `{i}pixelator <reply image>`
53+
Create a Pixelated Image..
54+
"""
55+
import os
56+
57+
from . import LOGS, con
58+
59+
try:
60+
import cv2
61+
except ImportError:
62+
LOGS.error(f"{__file__}: OpenCv not Installed.")
63+
64+
import numpy as np
65+
66+
try:
67+
from PIL import Image
68+
except ImportError:
69+
Image = None
70+
LOGS.info(f"{__file__}: PIL not Installed.")
71+
from telegraph import upload_file as upf
72+
from telethon.errors.rpcerrorlist import (
73+
ChatSendMediaForbiddenError,
74+
MessageDeleteForbiddenError,
75+
)
76+
77+
from . import (
78+
Redis,
79+
async_searcher,
80+
download_file,
81+
get_string,
82+
requests,
83+
udB,
84+
ultroid_cmd,
85+
)
86+
87+
88+
@ultroid_cmd(pattern="color$")
89+
async def _(event):
90+
reply = await event.get_reply_message()
91+
if not (reply and reply.media):
92+
return await event.eor("`Reply To a Black and White Image`")
93+
xx = await event.eor("`Coloring image 🎨🖌️...`")
94+
image = await reply.download_media()
95+
img = cv2.VideoCapture(image)
96+
ret, frame = img.read()
97+
cv2.imwrite("ult.jpg", frame)
98+
if udB.get_key("DEEP_API"):
99+
key = Redis("DEEP_API")
100+
else:
101+
key = "quickstart-QUdJIGlzIGNvbWluZy4uLi4K"
102+
r = requests.post(
103+
"https://api.deepai.org/api/colorizer",
104+
files={"image": open("ult.jpg", "rb")},
105+
headers={"api-key": key},
106+
)
107+
os.remove("ult.jpg")
108+
os.remove(image)
109+
if "status" in r.json():
110+
return await event.edit(
111+
r.json()["status"] + "\nGet api nd set `{i}setdb DEEP_API key`"
112+
)
113+
r_json = r.json()["output_url"]
114+
await event.client.send_file(event.chat_id, r_json, reply_to=reply)
115+
await xx.delete()
116+
117+
118+
@ultroid_cmd(pattern="(grey|blur|negative|danger|mirror|quad|sketch|flip|toon)$")
119+
async def ult_tools(event):
120+
match = event.pattern_match.group(1)
121+
ureply = await event.get_reply_message()
122+
if not (ureply and (ureply.media)):
123+
await event.eor(get_string("cvt_3"))
124+
return
125+
ultt = await ureply.download_media()
126+
xx = await event.eor(get_string("com_1"))
127+
if ultt.endswith(".tgs"):
128+
xx = await xx.edit(get_string("sts_9"))
129+
file = await con.convert(ultt, convert_to="png", outname="ult")
130+
ult = cv2.imread(file)
131+
if match == "grey":
132+
ultroid = cv2.cvtColor(ult, cv2.COLOR_BGR2GRAY)
133+
elif match == "blur":
134+
ultroid = cv2.GaussianBlur(ult, (35, 35), 0)
135+
elif match == "negative":
136+
ultroid = cv2.bitwise_not(ult)
137+
elif match == "danger":
138+
dan = cv2.cvtColor(ult, cv2.COLOR_BGR2RGB)
139+
ultroid = cv2.cvtColor(dan, cv2.COLOR_HSV2BGR)
140+
elif match == "mirror":
141+
ish = cv2.flip(ult, 1)
142+
ultroid = cv2.hconcat([ult, ish])
143+
elif match == "flip":
144+
trn = cv2.flip(ult, 1)
145+
ish = cv2.rotate(trn, cv2.ROTATE_180)
146+
ultroid = cv2.vconcat([ult, ish])
147+
elif match == "quad":
148+
ult = cv2.imread(file)
149+
roid = cv2.flip(ult, 1)
150+
mici = cv2.hconcat([ult, roid])
151+
fr = cv2.flip(mici, 1)
152+
trn = cv2.rotate(fr, cv2.ROTATE_180)
153+
ultroid = cv2.vconcat([mici, trn])
154+
elif match == "sketch":
155+
gray_image = cv2.cvtColor(ult, cv2.COLOR_BGR2GRAY)
156+
inverted_gray_image = 255 - gray_image
157+
blurred_img = cv2.GaussianBlur(inverted_gray_image, (21, 21), 0)
158+
inverted_blurred_img = 255 - blurred_img
159+
ultroid = cv2.divide(gray_image, inverted_blurred_img, scale=256.0)
160+
elif match == "toon":
161+
height, width, _ = ult.shape
162+
samples = np.zeros([height * width, 3], dtype=np.float32)
163+
count = 0
164+
for x in range(height):
165+
for y in range(width):
166+
samples[count] = ult[x][y]
167+
count += 1
168+
_, labels, centers = cv2.kmeans(
169+
samples,
170+
12,
171+
None,
172+
(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10000, 0.0001),
173+
5,
174+
cv2.KMEANS_PP_CENTERS,
175+
)
176+
centers = np.uint8(centers)
177+
ish = centers[labels.flatten()]
178+
ultroid = ish.reshape(ult.shape)
179+
cv2.imwrite("ult.jpg", ultroid)
180+
await ureply.reply(
181+
file="ult.jpg",
182+
force_document=False,
183+
)
184+
await xx.delete()
185+
os.remove("ult.jpg")
186+
os.remove(file)
187+
188+
189+
@ultroid_cmd(pattern="csample (.*)")
190+
async def sampl(ult):
191+
if color := ult.pattern_match.group(1).strip():
192+
img = Image.new("RGB", (200, 100), f"{color}")
193+
img.save("csample.png")
194+
try:
195+
try:
196+
await ult.delete()
197+
await ult.respond(f"Colour Sample for `{color}` !", file="csample.png")
198+
except MessageDeleteForbiddenError:
199+
await ult.reply(f"Colour Sample for `{color}` !", file="csample.png")
200+
except ChatSendMediaForbiddenError:
201+
await ult.eor("Umm! Sending Media is disabled here!")
202+
203+
else:
204+
await ult.eor("Wrong Color Name/Hex Code specified!")
205+
206+
207+
@ultroid_cmd(
208+
pattern="blue$",
209+
)
210+
async def ultd(event):
211+
ureply = await event.get_reply_message()
212+
xx = await event.eor("`...`")
213+
if not (ureply and (ureply.media)):
214+
await xx.edit(get_string("cvt_3"))
215+
return
216+
ultt = await ureply.download_media()
217+
if ultt.endswith(".tgs"):
218+
await xx.edit(get_string("sts_9"))
219+
file = await con.convert(ultt, convert_to="png", outname="ult")
220+
got = upf(file)
221+
lnk = f"https://graph.org{got[0]}"
222+
r = await async_searcher(
223+
f"https://nekobot.xyz/api/imagegen?type=blurpify&image={lnk}", re_json=True
224+
)
225+
ms = r.get("message")
226+
if not r["success"]:
227+
return await xx.edit(ms)
228+
await download_file(ms, "ult.png")
229+
img = Image.open("ult.png").convert("RGB")
230+
img.save("ult.webp", "webp")
231+
await event.client.send_file(
232+
event.chat_id,
233+
"ult.webp",
234+
force_document=False,
235+
reply_to=event.reply_to_msg_id,
236+
)
237+
await xx.delete()
238+
os.remove("ult.png")
239+
os.remove("ult.webp")
240+
os.remove(ultt)
241+
242+
243+
@ultroid_cmd(pattern="border( (.*)|$)")
244+
async def ok(event):
245+
hm = await event.get_reply_message()
246+
if not (hm and (hm.photo or hm.sticker)):
247+
return await event.eor("`Reply to Sticker or Photo..`")
248+
col = event.pattern_match.group(1).strip()
249+
wh = 20
250+
if not col:
251+
col = [255, 255, 255]
252+
else:
253+
try:
254+
if ";" in col:
255+
col_ = col.split(";", maxsplit=1)
256+
wh = int(col_[1])
257+
col = col_[0]
258+
col = [int(col) for col in col.split(",")[:2]]
259+
except ValueError:
260+
return await event.eor("`Not a Valid Input...`")
261+
okla = await hm.download_media()
262+
img1 = cv2.imread(okla)
263+
constant = cv2.copyMakeBorder(img1, wh, wh, wh, wh, cv2.BORDER_CONSTANT, value=col)
264+
cv2.imwrite("output.png", constant)
265+
await event.client.send_file(event.chat.id, "output.png")
266+
os.remove("output.png")
267+
os.remove(okla)
268+
await event.delete()
269+
270+
271+
@ultroid_cmd(pattern="pixelator( (.*)|$)")
272+
async def pixelator(event):
273+
reply_message = await event.get_reply_message()
274+
if not (reply_message and (reply_message.photo or reply_message.sticker)):
275+
return await event.eor("`Reply to a photo`")
276+
hw = 50
277+
try:
278+
hw = int(event.pattern_match.group(1).strip())
279+
except (ValueError, TypeError):
280+
pass
281+
msg = await event.eor(get_string("com_1"))
282+
image = await reply_message.download_media()
283+
input_ = cv2.imread(image)
284+
height, width = input_.shape[:2]
285+
w, h = (hw, hw)
286+
temp = cv2.resize(input_, (w, h), interpolation=cv2.INTER_LINEAR)
287+
output = cv2.resize(temp, (width, height), interpolation=cv2.INTER_NEAREST)
288+
cv2.imwrite("output.jpg", output)
289+
await msg.respond("• Pixelated by Ultroid", file="output.jpg")
290+
await msg.delete()
291+
os.remove("output.jpg")
292+
os.remove(image)

0 commit comments

Comments
 (0)