-
Notifications
You must be signed in to change notification settings - Fork 8
/
utils.py
298 lines (236 loc) · 7.85 KB
/
utils.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
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import random
from constants import *
import aiohttp
import io
from urllib.parse import quote
from pymongo import MongoClient
import sys
import json
from PIL import Image
import piexif
from bson.son import SON
import discord
import datetime
client = MongoClient(MONGODB_URI)
try:
client.admin.command("ping")
print("\n Pinged your deployment. You successfully connected to MongoDB! \n")
except Exception as e:
print(e)
db = client["pollinations"]
prompts = db["prompts"]
users = db["users"]
multi_prompts = db["multi_prompts"]
NUMBER_EMOJIES = {
1: "🥇",
2: "🥈",
3: "🥉",
4: "4️⃣",
5: "5️⃣",
6: "6️⃣",
7: "7️⃣",
8: "8️⃣",
9: "9️⃣",
10: "🔟",
}
waiting_gifs = [
"https://media3.giphy.com/media/l0HlBO7eyXzSZkJri/giphy.gif?cid=ecf05e475p246q1gdcu96b5mkqlqvuapb7xay2hywmki7f5q&ep=v1_gifs_search&rid=giphy.gif&ct=g",
"https://media2.giphy.com/media/QBd2kLB5qDmysEXre9/giphy.gif?cid=ecf05e47ha6xwa7rq38dcst49nefabwwrods631hvz67ptfg&ep=v1_gifs_search&rid=giphy.gif&ct=g",
"https://media2.giphy.com/media/ZgqJGwh2tLj5C/giphy.gif?cid=ecf05e47gflyso481izbdcrw7y8okfkgdxgc7zoh34q9rxim&ep=v1_gifs_search&rid=giphy.gif&ct=g",
"https://media0.giphy.com/media/EWhLjxjiqdZjW/giphy.gif?cid=ecf05e473fifxe2bg4act0zq73nkyjw0h69fxi52t8jt37lf&ep=v1_gifs_search&rid=giphy.gif&ct=g",
"https://i.giphy.com/26BRuo6sLetdllPAQ.webp",
"https://i.giphy.com/tXL4FHPSnVJ0A.gif",
]
class PromptTooLongError(discord.app_commands.AppCommandError):
pass
class DimensionTooSmallError(discord.app_commands.AppCommandError):
pass
def get_prompt_data(message_id: int):
try:
return prompts.find_one({"_id": message_id})
except Exception as e:
print(e)
return None
def save_prompt_data(message_id: int, data: dict):
try:
prompts.insert_one(data)
except Exception as e:
print(e)
def update_prompt_data(message_id: int, data: dict):
try:
prompts.update_one({"_id": message_id}, {"$set": data})
except Exception as e:
print(e)
def delete_prompt_data(message_id: int):
try:
prompts.delete_one({"_id": message_id})
except Exception as e:
print(e)
def get_multi_imagined_prompt_data(message_id: int):
try:
return multi_prompts.find_one({"_id": message_id})
except Exception as e:
print(e)
return None
def save_multi_imagined_prompt_data(message_id: int, data: dict):
try:
multi_prompts.insert_one(data)
except Exception as e:
print(e)
def update_multi_imagined_prompt_data(message_id: int, data: dict):
try:
multi_prompts.update_one({"_id": message_id}, {"$set": data})
except Exception as e:
print(e)
def delete_multi_imagined_prompt_data(message_id: int):
try:
multi_prompts.delete_one({"_id": message_id})
except Exception as e:
print(e)
def get_prompts_counts():
try:
return prompts.count_documents({}) + multi_prompts.count_documents({})
except Exception as e:
print(e)
return None
def get_user_data(user_id: int):
try:
return users.find_one({"_id": user_id})
except Exception as e:
print(e)
return None
def save_user_data(user_id: int, data: dict):
try:
users.insert_one(data)
except Exception as e:
print(e)
def update_user_data(user_id: int, data: dict):
try:
users.update_one({"_id": user_id}, {"$set": data})
except Exception as e:
print(e)
pipeline = [
{"$unwind": "$prompts"},
{"$group": {"_id": "$_id", "count": {"$sum": 1}}},
{"$sort": SON([("count", -1)])},
{"$limit": 10},
]
def generate_global_leaderboard():
try:
top_10_users = list(users.aggregate(pipeline))
top_10_users = {doc["_id"]: doc["count"] for doc in top_10_users}
return top_10_users
except Exception as e:
print(e)
return None
def ordinal(n):
suffix = ["th", "st", "nd", "rd"] + ["th"] * 6
if 10 <= n % 100 <= 20:
suffix_choice = "th"
else:
suffix_choice = suffix[n % 10]
return f"{n}{suffix_choice}"
async def generate_error_message(
interaction: discord.Interaction,
error,
cooldown_configuration=[
"- ```1 time every 10 seconds```",
"- ```5 times every 60 seconds```",
"- ```200 times every 24 hours```",
],
):
end_time = datetime.datetime.now() + datetime.timedelta(seconds=error.retry_after)
end_time_ts = int(end_time.timestamp())
embed = discord.Embed(
title="⏳ Cooldown",
description=f"### You can use this command again <t:{end_time_ts}:R>",
color=discord.Color.red(),
timestamp=interaction.created_at,
)
embed.set_image(url=random.choice(waiting_gifs))
embed.add_field(
name="How many times can I use this command?",
value="\n".join(cooldown_configuration),
inline=False,
)
try:
embed.set_footer(
text=f"{interaction.user} used /{interaction.command.name}",
icon_url=interaction.user.avatar,
)
except:
embed.set_footer(
text=f"{interaction.user} used /{interaction.command.name}",
icon_url=interaction.user.default_avatar,
)
return embed
def extract_user_comment(image_bytes):
image = Image.open(io.BytesIO(image_bytes))
try:
exif = image.info["exif"].decode("latin-1", errors="ignore")
user_comment = json.loads(exif[exif.find("{") : exif.rfind("}") + 1])
except Exception as e:
print(e)
return "No user comment found."
if user_comment:
return user_comment
else:
return "No user comment found."
async def generate_image(
prompt: str,
width: int = 800,
height: int = 800,
model: str = f"{MODELS[0]}",
negative: str | None = None,
cached: bool = False,
nologo: bool = False,
enhance: bool = False,
private: bool = False,
**kwargs,
):
print(
f"Generating image with prompt: {prompt}, width: {width}, height: {height}, negative: {negative}, cached: {cached}, nologo: {nologo}, enhance: {enhance}, model: {model}",
file=sys.stderr,
)
seed = str(random.randint(0, 1000000000))
url = f"https://image.pollinations.ai/prompt/{prompt}"
url += f"?seed={seed}" if not cached else ""
url += f"&width={width}"
url += f"&height={height}"
url += f"&model={model}"
url += f"&negative={negative}" if negative else ""
url += f"&nologo={nologo}" if nologo else ""
url += f"&enhance={enhance}" if enhance else ""
url += f"&nofeed={private}" if private else ""
url += "&referer=discordbot"
dic = {
"prompt": prompt,
"width": width,
"height": height,
"negative": negative,
"cached": cached,
"nologo": nologo,
"enhance": enhance,
"bookmark_url": quote(url, safe=":/&=?"),
}
dic["seed"] = seed if not cached else None
async with aiohttp.ClientSession() as session:
async with session.get(url, allow_redirects=True) as response:
response.raise_for_status() # Raise an exception for non-2xx status codes
image_data = await response.read()
if image_data:
user_comment = extract_user_comment(image_data)
image_file = io.BytesIO(image_data)
image_file.seek(0)
try:
dic["nsfw"] = user_comment["has_nsfw_concept"]
if enhance or len(prompt) < 80:
enhance_prompt = user_comment["prompt"]
enhance_prompt = enhance_prompt[
: enhance_prompt.rfind("\n")
].strip()
dic["enhanced_prompt"] = enhance_prompt
except Exception as e:
print(e)
dic["nsfw"] = False
return (dic, image_file)