Skip to content

Commit 801dff8

Browse files
Create lexica.py
1 parent 37b3d22 commit 801dff8

File tree

1 file changed

+235
-0
lines changed

1 file changed

+235
-0
lines changed

ai/lexica.py

Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
1+
# Moon-Userbot - telegram userbot
2+
# Copyright (C) 2020-present Moon Userbot Organization
3+
#
4+
# This program is free software: you can redistribute it and/or modify
5+
# it under the terms of the GNU General Public License as published by
6+
# the Free Software Foundation, either version 3 of the License, or
7+
# (at your option) any later version.
8+
9+
# This program is distributed in the hope that it will be useful,
10+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
# GNU General Public License for more details.
13+
14+
# You should have received a copy of the GNU General Public License
15+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
16+
17+
import asyncio
18+
import logging
19+
import os
20+
import re
21+
import time
22+
23+
import requests
24+
from bs4 import BeautifulSoup
25+
from pyrogram import Client, filters
26+
from pyrogram.types import Message
27+
28+
from utils.misc import modules_help, prefix
29+
from utils.scripts import format_exc, format_module_help, progress, import_library
30+
31+
lexica = import_library("lexica", "lexica-api")
32+
33+
from lexica import AsyncClient, Client
34+
35+
36+
def ImageModels():
37+
models = Client().models["models"]["image"]
38+
dict_models = {}
39+
for model in models:
40+
model_id = model["id"]
41+
model_name = model["name"]
42+
dict_models[model_name] = model_id
43+
return dict_models
44+
45+
46+
async def ImageGeneration(model, prompt):
47+
try:
48+
output = await AsyncClient().generate(model, prompt, "")
49+
if output["code"] != 1:
50+
return 2
51+
if output["code"] == 69:
52+
return output["code"]
53+
task_id, request_id = output["task_id"], output["request_id"]
54+
await asyncio.sleep(20)
55+
tries = 0
56+
image_url = None
57+
resp = await AsyncClient().getImages(task_id, request_id)
58+
while True:
59+
if resp["code"] == 2:
60+
image_url = resp["img_urls"]
61+
break
62+
if tries > 15:
63+
break
64+
await asyncio.sleep(5)
65+
resp = await AsyncClient().getImages(task_id, request_id)
66+
tries += 1
67+
continue
68+
return image_url
69+
except Exception as e:
70+
logging.warning(e)
71+
finally:
72+
await AsyncClient().close()
73+
74+
75+
async def UpscaleImages(image: bytes) -> str:
76+
content = await AsyncClient().upscale(image)
77+
await AsyncClient().close()
78+
upscaled_file_path = "upscaled.png"
79+
with open(upscaled_file_path, "wb") as output_file:
80+
output_file.write(content)
81+
return upscaled_file_path
82+
83+
84+
@Client.on_message(filters.command("upscale", prefix) & filters.me)
85+
async def upscale(client: Client, message: Message):
86+
"""Upscale Image Using Lexica API"""
87+
88+
await message.edit("<code>Processing...</code>")
89+
try:
90+
photo_data = await message.download()
91+
except ValueError:
92+
try:
93+
photo_data = await message.reply_to_message.download()
94+
except ValueError:
95+
await message.edit("<b>File not found</b>")
96+
return
97+
try:
98+
with open(photo_data, "rb") as image_file:
99+
image = image_file.read()
100+
upscaled_image = await UpscaleImages(image)
101+
if message.reply_to_message:
102+
message_id = message.reply_to_message.id
103+
await message.delete()
104+
else:
105+
message_id = message.id
106+
await client.send_document(
107+
message.chat.id,
108+
upscaled_image,
109+
caption="Upscaled!",
110+
reply_to_message_id=message_id,
111+
)
112+
os.remove(upscaled_image)
113+
os.remove(photo_data)
114+
except Exception as e:
115+
await message.edit(format_exc(e))
116+
117+
118+
@Client.on_message(filters.command("lgen", prefix) & filters.me)
119+
async def lgen(client: Client, message: Message):
120+
try:
121+
await message.edit_text("<code>Processing...</code>")
122+
123+
models = ImageModels()
124+
models_ids = models.values()
125+
126+
if len(message.command) > 2:
127+
model_id = int(message.text.split()[1])
128+
if model_id not in models_ids:
129+
return await message.edit_text(format_module_help("lgen"))
130+
message_id = None
131+
prompt = " ".join(message.text.split()[2:])
132+
elif message.reply_to_message and len(message.command) > 1:
133+
model_id = int(message.text.split()[1])
134+
if model_id not in models_ids:
135+
return await message.edit_text(
136+
f"<b>Usage: </b><code>{prefix}lgen [model_id]* [prompt/reply to prompt]*</code>\n <b>Available Models and IDs:</b> <blockquote>{models}</blockquote>"
137+
)
138+
message_id = message.reply_to_message.id
139+
prompt = message.reply_to_message.text
140+
else:
141+
return await message.edit_text(
142+
f"<b>Usage: </b><code>{prefix}lgen [model_id]* [prompt/reply to prompt]*</code>\n <b>Available Models and IDs:</b> <blockquote>{models}</blockquote>"
143+
)
144+
145+
for key, val in models.items():
146+
if val == model_id:
147+
model_name = key
148+
149+
img = await ImageGeneration(model_id, prompt)
150+
if img is None or img == 1 or img == 2:
151+
return await message.edit_text("Something went wrong!")
152+
if img == 69:
153+
return await message.edit_text("NSFW is not allowed")
154+
img_url = img[0]
155+
with open("generated_image.png", "wb") as f:
156+
f.write(requests.get(img_url, timeout=5).content)
157+
158+
await message.delete()
159+
await client.send_document(
160+
message.chat.id,
161+
"generated_image.png",
162+
caption=f"<b>Prompt: </b><code>{prompt}</code>\n<b>Model: </b><code>{model_name}</code>",
163+
reply_to_message_id=message_id,
164+
)
165+
os.remove("generated_image.png")
166+
except Exception as e:
167+
await message.edit(format_exc(e))
168+
169+
170+
@Client.on_message(filters.command("linsta", prefix) & filters.me)
171+
async def linsta(client: Client, message: Message):
172+
if len(message.command) < 2:
173+
return await message.edit_text(
174+
f"<b>Usage: </b><code>{prefix}linsta [link]*</code>"
175+
)
176+
link = message.text.split(maxsplit=1)[1]
177+
url = f"https://social-dl.vercel.app/api/download?url={link}&platform=Instagram"
178+
await message.edit_text("<code>Processing...</code>")
179+
try:
180+
response = requests.post(url)
181+
if response.status_code == 200:
182+
if response.json().get("code") == 2:
183+
if response.json().get("message") == "success":
184+
download_url = response.json().get("content")[0].get("url")
185+
soup = BeautifulSoup(requests.get(link).text, "html.parser")
186+
title = soup.find("meta", property="og:title")
187+
if title:
188+
title_text = title["content"]
189+
title_text = re.sub(r"#\w+", "", title_text)
190+
title_text = title_text.replace("\n", "")
191+
title_text = re.sub(" +", " ", title_text)
192+
if ".mp4" in download_url:
193+
ext = ".mp4"
194+
elif ".jpg" in download_url:
195+
ext = ".jpg"
196+
elif ".png" in download_url:
197+
ext = ".png"
198+
elif ".webp" in download_url:
199+
ext = ".webp"
200+
elif ".gif" in download_url:
201+
ext = ".gif"
202+
with open(f"video_insta{ext}", "wb") as f:
203+
f.write(requests.get(download_url).content)
204+
await message.edit_text(
205+
"Video downloaded successfully... Uploading"
206+
)
207+
await client.send_video(
208+
message.chat.id,
209+
f"video_insta{ext}",
210+
caption=f"<b>Title: </b><code>{title_text}</code>",
211+
progress=progress,
212+
progress_args=(
213+
message,
214+
time.time(),
215+
"Video downloaded successfully... Uploading",
216+
),
217+
)
218+
if os.path.exists(f"video_insta{ext}"):
219+
os.remove(f"video_insta{ext}")
220+
await message.delete()
221+
else:
222+
await message.edit_text("Error: Failed to retrieve download URL")
223+
else:
224+
await message.edit_text("Error: Invalid response format")
225+
else:
226+
await message.edit_text("Error: Failed to send request")
227+
except Exception as e:
228+
await message.edit_text(format_exc(e))
229+
230+
231+
modules_help["lexica"] = {
232+
"lgen [model_id]* [prompt/reply to prompt]*": "Generate Image with Lexica API",
233+
"upscale [cap/reply to image]*": "Upscale Image through Lexica API",
234+
"linsta [link]*": "Download Instagram Media",
235+
}

0 commit comments

Comments
 (0)