Araeynn commited on
Commit
828319c
1 Parent(s): 967fdcc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -237
app.py CHANGED
@@ -1,249 +1,141 @@
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)
 
 
 
 
 
 
 
 
1
  import discord
2
+ from discord import app_commands
3
+ import requests
4
+ import grequests
5
+ import asyncio
6
+ from discord.ext.commands import is_owner, Context, has_permissions
7
  import os
8
+ from typing import Optional
9
 
10
+ intents = discord.Intents.all()
11
+ client = discord.Client(intents=intents)
12
+ tree = app_commands.CommandTree(client)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ url = "https://huggingface.co/chat/conversation"
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ # load system prompt
17
  try:
18
+ with open("sysp.txt", "r") as f:
19
+ sysp = f.read()
20
  except:
21
+ sysp = ""
22
+
23
+ # models
24
+ mixtral = "mistralai/Mixtral-8x7B-Instruct-v0.1"
25
+ llama = "meta-llama/Llama-2-70b-chat-hf"
26
+ openchat = "openchat/openchat-3.5-0106"
27
+ mistral = "mistralai/Mistral-7B-Instruct-v0.2"
28
+ hermes = "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO"
29
+ codellama = "codellama/CodeLlama-70b-Instruct-hf"
30
+
31
+ async def chat(conversationId, ip, cookie):
32
+ url = f"https://huggingface.co/chat/conversation/{conversationId}"
33
+
34
+ payload = {
35
+ "inputs": ip,
36
+ "id": cookie,
37
+ "is_retry": False,
38
+ "is_continue": False,
39
+ "web_search": False,
40
+ "files": []
41
+ }
42
+
43
+ headers = {
44
+ "authority": "huggingface.co",
45
+ "accept": "*/*",
46
+ "accept-language": "en-US,en;q=0.9",
47
+ "content-type": "application/json",
48
+ }
49
+
50
+ response = session.post(url, json=payload, headers=headers)
51
+ return response
52
+
53
+ @client.tree.command(
54
+ description="Starts the conversation with Lyre.",
55
+ guild=discord.Object(id=1079318749116641320)
56
+ )
57
+ @app_commands.describe(
58
+ channel='The channel to start the conversation in. Defaults to the channel it was called in.',
59
+ )
60
+ @has_permissions(manage_channels=True, manage_messages=True)
61
+ async def start(ctx: discord.Interaction, channel: Optional[discord.AppCommandOptionType.channel]=None):
62
+ s = requests.Session()
63
+ payload = {
64
+ "model": mixtral,
65
+ "preprompt": sysp
66
+ }
67
+ headers = {
68
+ "authority": "huggingface.co",
69
+ "accept": "*/*",
70
+ "accept-language": "en-US,en;q=0.9",
71
+ "content-type": "application/json"
72
+ }
73
+ if channel == None:
74
+ chping = f"<#{ctx.channel_id}>"
75
+ with open(str(ctx.channel_id), "w") as f:
76
+ f.write(s.cookies.get("hf-chat") + "\n" + response.json.loads(response.text)['conversationId'])
77
  else:
78
+ chping = f"<#{channel.id}>"
79
+ with open(str(ctx.channel_id), "w") as f:
80
+ f.write(s.cookies.get("hf-chat") + "\n" + response.json.loads(response.text)['conversationId'])
81
+ ctx.response.send_message(f"Started a conversation in {chping}")
82
+
83
+ @start.error
84
+ async def start_error(error, ctx):
85
+ if isinstance(error, commands.MissingPermissions):
86
+ ctx.response.send_message(f"Missing permissions in {chping}")
87
+
88
+ @client.tree.command(
89
+ description="Ends the conversation with Lyre.",
90
+ guild=discord.Object(id=1079318749116641320)
91
+ )
92
+ @app_commands.describe(
93
+ channel='The channel to end the conversation in. Defaults to the channel it was called in.',
94
+ )
95
+ @has_permissions(manage_channels=True, manage_messages=True)
96
+ async def start(ctx: discord.Interaction, channel: Optional[discord.AppCommandOptionType.channel]=None):
97
+ s = requests.Session()
98
+ payload = {
99
+ "model": mixtral,
100
+ "preprompt": sysp
101
+ }
102
+ headers = {
103
+ "authority": "huggingface.co",
104
+ "accept": "*/*",
105
+ "accept-language": "en-US,en;q=0.9",
106
+ "content-type": "application/json"
107
+ }
108
+ if channel == None:
109
+ chping = f"<#{ctx.channel_id}>"
110
+ os.remove(str(ctx.channel_id))
111
+ else:
112
+ chping = f"<#{channel.id}>"
113
+ os.remove(str(ctx.channel_id))
114
+ ctx.response.send_message(f"Ended the conversation in {chping}")
115
+ s.close()
116
+
117
+ @end.error
118
+ async def end_error(error, ctx):
119
+ if isinstance(error, commands.MissingPermissions):
120
+ ctx.response.send_message(f"Missing permissions in {chping}")
121
+
122
+ @client.command()
123
+ @is_owner()
124
+ async def sync(ctx: Context) -> None:
125
+ synced = await client.tree.sync()
126
+ await ctx.reply("{} commands synced".format(len(synced)))
127
 
128
  @client.event
129
+ async def on_ready():
130
+ print("Ready!")
131
 
132
  @client.event
133
+ async def on_message_create(msg):
134
+ if os.path.exists(str(msg.channel.id)) or isinstance(msg.channel, discord.DMChannel):
135
+ with open(str(msg.channel.id), "r") as f:
136
+ cookie, id = f.read().split("\n")
137
+ r = await chat(id, "{" + str(msg.author) + "}\n" + msg.content, id)
138
+ await msg.reply(json.loads("{" + r.text.split("finalAnswer")[-1][2:].strip())["text"].strip())
139
+
140
+
141
+ client.run(os.environ["TOKEN"])