Araeynn commited on
Commit
967fdcc
1 Parent(s): 99467b5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +249 -0
app.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import re
4
+ import asyncio
5
+ import random
6
+ import datetime
7
+ from threading import Thread
8
+ import discord
9
+ from discord.ext import tasks
10
+ from PIL import Image
11
+ import streamlit as st
12
+ from huggingface_hub import AsyncInferenceClient, login
13
+ import time
14
+ import os
15
+
16
+ launch_time = datetime.datetime.utcnow()
17
+
18
+ ph = st.empty()
19
+
20
+ def syncMessages():
21
+ with ph.container():
22
+ st.markdown(f"`Status:` :green[**Running**]")
23
+ st.link_button(label="Invite the Bot", url="https://discord.com/api/oauth2/authorize?client_id=1116821362695221349&permissions=1067299753024&scope=bot", type="primary")
24
+ if os.listdir("data") == []:
25
+ return 0
26
+ dirs = st.tabs(os.listdir("data"))
27
+ i = -1
28
+ for dir in os.listdir("data"):
29
+ i += 1
30
+ with dirs[i]:
31
+ if os.listdir(f"data/{dir}") == []:
32
+ return 0
33
+ files = st.tabs(os.listdir("data/" + dir))
34
+ k = -1
35
+ for file in os.listdir("data/" + dir):
36
+ k += 1
37
+ with files[k]:
38
+ with open(f"data/{dir}/{file}", "r") as f:
39
+ o = f.read().split("<|end_of_turn|>")
40
+ for item in o:
41
+ if item == "":
42
+ continue
43
+ item = item.split(": ", 1)
44
+ st.markdown(f":blue[{item[0].split('GPT4 Correct ')[1]}]: {item[1]}")
45
+
46
+ lock_file_path = "test.txt"
47
+
48
+ if not os.path.exists(lock_file_path):
49
+ with open(lock_file_path, "w") as f:
50
+ f.write("running")
51
+ clone = False
52
+ st.markdown("Bot is running, reload the page to see activity.")
53
+ else:
54
+ print("Streamlit app is already running, only streaming activity.")
55
+ clone = True
56
+ while True:
57
+ syncMessages()
58
+ time.sleep(0.5)
59
+ exit()
60
+
61
+ try:
62
+ os.mkdir("data")
63
+ except:
64
+ pass
65
+
66
+
67
+ HF_TOKEN = os.environ["HF_TOKEN"]
68
+
69
+ login(HF_TOKEN)
70
+ sd_turbo = "stabilityai/sd-turbo"
71
+ sdxl_turbo = "stabilityai/sd-turbo"
72
+ sdxl = "stabilityai/stable-diffusion-xl-base-1.0"
73
+ proteus = "dataautogpt3/ProteusV0.2"
74
+ sd_2_1 = "stabilityai/stable-diffusion-2-1"
75
+ open_journey = "prompthero/openjourney-v4"
76
+ SD = AsyncInferenceClient(model=sd_2_1)
77
+ SDT = AsyncInferenceClient(model=sdxl_turbo)
78
+ PT = AsyncInferenceClient(model=proteus)
79
+ LLM = AsyncInferenceClient(model="openchat/openchat-3.5-0106")
80
+ RF = AsyncInferenceClient(model="stabilityai/stable-diffusion-xl-refiner-1.0")
81
+
82
+
83
+ def ec(x, fd="<|image|>", sd="<|image|>"):
84
+ matches = re.findall(re.escape(fd) + "(.*?)" + re.escape(sd), x)
85
+ matches = matches if matches else [""]
86
+ return matches
87
+
88
+
89
+ intents = discord.Intents.default()
90
+ intents.message_content = True
91
+
92
+ client = discord.Client(intents=intents)
93
+
94
+ @client.event
95
+ async def on_ready():
96
+ if clone:
97
+ print(f"Clone started.")
98
+ syncMessages()
99
+ else:
100
+ print(f"Logged in as {client.user}")
101
+ presence.start()
102
+
103
+
104
+ @tasks.loop(seconds=60)
105
+ async def presence():
106
+ if not clone:
107
+ delta_uptime = datetime.datetime.utcnow() - launch_time
108
+ hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
109
+ minutes, seconds = divmod(remainder, 60)
110
+ days, hours = divmod(hours, 24)
111
+ print(f"Online Time: {days:02d}d | {hours:02d}h | {minutes:02d}m | {seconds:02d}s")
112
+ await client.change_presence(
113
+ status=discord.Status.idle,
114
+ activity=discord.Activity(
115
+ type=discord.ActivityType.playing,
116
+ large_image="https://i.imgur.com/Kk2BvJg.jpg",
117
+ large_text="This is Game Icon",
118
+ name="Escaping the IRS.",
119
+ details="",
120
+ state=f"Running for {days:02d}d | {hours:02d}h | {minutes:02d}m",
121
+ ),
122
+ )
123
+
124
+
125
+ @client.event
126
+ async def on_disconnect():
127
+ print("Disconnected, Clone status:", clone)
128
+
129
+ @client.event
130
+ async def on_message(message):
131
+ for user in message.mentions:
132
+ if user.bot:
133
+ message.content = message.content.replace(f"<@{user.id}>",
134
+ f"<@{str(user)}[bot]>")
135
+ try:
136
+ msgchannel = message.channel
137
+ try:
138
+ msgchannel_name = msgchannel.name
139
+ guild = message.guild
140
+ guild_name = guild.name
141
+ except:
142
+ guild_name = "Direct"
143
+ msgchannel_name = str(message.author)
144
+ s = f":green[{message.author}]: :violet[{message.content}] :blue[{msgchannel_name}] :orange[{guild_name}]"
145
+ if message.author == client.user:
146
+ return
147
+ sysp = f"""GPT4 Correct System: You are lr, a discord bot. You were made by Araeyn.
148
+ You must use the markdown format for your responses.
149
+ Do not excessively use bullet points.
150
+ Use emojis at the start of your responses.
151
+ Use <|title|> at the start of your title for the response and <|title|> at the end of the title.
152
+ Your title is a conversation name that ChatGPT would make for the response and question.
153
+ If the user asks you to generate an image, use the start tag <|image|> and the end tag <|image|> around the prompt to generate it. Put this at the end of your response. Do not use a link for the image.
154
+ For example, if the user asks you to generate an image of a cat, you could say <|image|>A cute cat with long fur that is looking out a window with curious eyes, hd, realistic<|image|>
155
+ Always include a title.
156
+ Do not generate images unless the user speciifes that they want an image.
157
+ If a user has [bot] next to their username, they are a bot."""
158
+ try:
159
+ os.mkdir("data/" + guild_name)
160
+ except:
161
+ pass
162
+ if os.path.exists(f"data/{guild_name}/{msgchannel_name}"):
163
+ with open(f"data/{guild_name}/{msgchannel_name}", "a") as f:
164
+ n = "\n"
165
+ if message.author.bot:
166
+ f.write(
167
+ f"""GPT4 Correct {message.author}[bot]: {message.content.strip(n)}<|end_of_turn|>"""
168
+ )
169
+ else:
170
+ f.write(
171
+ f"""GPT4 Correct {message.author}: {message.content.strip(n)}<|end_of_turn|>"""
172
+ )
173
+ else:
174
+ with open(f"data/{guild_name}/{msgchannel_name}", "w") as f:
175
+ if message.author.bot:
176
+ f.write(
177
+ f"GPT4 Correct system: {sysp}<|end_of_turn|>GPT4 Correct {message.author}[bot]: {message.content}<|end_of_turn|>"
178
+ )
179
+ else:
180
+ f.write(
181
+ f"GPT4 Correct system: {sysp}<|end_of_turn|>GPT4 Correct {message.author}: {message.content}<|end_of_turn|>"
182
+ )
183
+ with open(f"data/{guild_name}/{msgchannel_name}", "r") as f:
184
+ context = f.read()
185
+ if "Feeway" in guild_name or guild_name == "Direct":
186
+ async with msgchannel.typing():
187
+ context += f"GPT4 Correct Assistant:"
188
+ load = random.choice(
189
+ [
190
+ "https://i.pinimg.com/originals/49/23/29/492329d446c422b0483677d0318ab4fa.gif"
191
+ ]
192
+ )
193
+ output = await LLM.text_generation(context,
194
+ stop_sequences=["<|end_of_turn|>"],
195
+ max_new_tokens=4096)
196
+ title = ec(output, "<|title|>", "<|title|>")[0]
197
+ imgp = ec(output)[0]
198
+ with open(f"data/{guild_name}/{msgchannel_name}", "a") as f:
199
+ f.write(f"GPT4 Correct Assistant: {output}<|end_of_turn|>")
200
+ embed = discord.Embed(title=title,
201
+ description=output.replace(
202
+ f"<|title|>{title}<|title|>", "").replace(f"<|image|>{imgp}<|image|>", ""),
203
+ color=0x1E81B0)
204
+ if imgp != "":
205
+ embed.set_image(url=load)
206
+ embed.set_footer(
207
+ text=
208
+ """Creating..."""
209
+ )
210
+ else:
211
+ embed.set_footer(
212
+ text=
213
+ """Information or code generated by Lyre may not always be correct. Lyre was made by Araeyn."""
214
+ )
215
+
216
+ e = await message.reply(embed=embed)
217
+ if imgp != "":
218
+ np = """lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"""
219
+ image = await SD.text_to_image(imgp, negative_prompt=np)
220
+ image.save("image.png")
221
+ embed.set_footer(
222
+ text=
223
+ """Refining..."""
224
+ )
225
+ file = discord.File("image.png", filename="image.png")
226
+ embed.set_image(url="attachment://image.png")
227
+ await e.edit(embed=embed, attachments=[file])
228
+ image = await RF.image_to_image("image.png")
229
+ embed.set_footer(
230
+ text=
231
+ """Information or code generated by Lyre may not always be correct."""
232
+ )
233
+ image.save("image.png")
234
+ file = discord.File("image.png", filename="image.png")
235
+ embed.set_image(url="attachment://image.png")
236
+ await e.edit(embed=embed, attachments=[file])
237
+
238
+ except Exception as exc:
239
+ print(exc)
240
+ c = client.get_channel(1202160048126840882)
241
+ embed = discord.Embed(title="ERROR",
242
+ description=exc,
243
+ color=0xFF3348)
244
+ await c.send(embed=embed)
245
+ embed = discord.Embed(title="ERROR", color=0xFF3348)
246
+ await e.edit(embed=embed)
247
+
248
+ token = os.environ["TOKEN"]
249
+ client.run(token)