File size: 8,359 Bytes
6c22325
 
 
85efe48
 
 
6c22325
 
85efe48
6c22325
80f9977
85efe48
86b14fc
da57ba6
 
169d34c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da57ba6
 
 
 
 
03b0f62
da57ba6
03b0f62
 
169d34c
 
 
8ca9e2b
da57ba6
85efe48
 
0a397b1
85efe48
80f9977
0a397b1
6c22325
 
 
 
 
 
69770d5
6c22325
 
8ca9e2b
85efe48
 
 
6c22325
 
 
 
 
 
 
85efe48
 
e6f469c
6c22325
 
03b0f62
 
0bea5e0
03b0f62
 
 
85efe48
 
0cc05a6
85efe48
03b0f62
d5b2074
03b0f62
 
 
 
 
 
5fb599f
03b0f62
 
 
 
 
 
 
 
 
6c22325
 
e6f469c
 
 
 
6c22325
 
03b0f62
1cf7548
 
03b0f62
1cf7548
 
85efe48
 
d2bc99c
6c22325
85efe48
 
 
 
 
 
 
 
 
 
 
8ca9e2b
d1fef5f
 
 
8ca9e2b
d1fef5f
8ca9e2b
 
d1fef5f
 
85efe48
 
 
6b2fa83
eef37bc
6b2fa83
 
 
 
 
eef37bc
6b2fa83
 
 
 
eef37bc
 
0cc05a6
a8bbf8d
d1fef5f
 
 
 
 
 
 
 
 
 
 
 
 
f8ceb30
 
d1fef5f
 
 
 
23e687f
d1fef5f
 
 
 
 
a8dd034
 
7aa5741
c96561c
a8dd034
 
 
 
 
 
 
 
 
 
 
ce51aac
d1fef5f
85efe48
 
6c22325
 
85efe48
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
import json
import os
import re
import asyncio
import random
import datetime
from threading import Thread
import discord
from discord.ext import tasks
from PIL import Image
import streamlit as st
from huggingface_hub import InferenceClient, login
import time
import os


ph = st.empty()

async def syncMessages():
    if os.listdir("data") == []:
        return 0
    with ph.container():
        dirs = st.tabs(os.listdir("data"))
        i = -1
        for dir in os.listdir("data"):
            i += 1
            with dirs[i]:
                if os.listdir(f"data/{dir}") == []:
                  return 0
                files = st.tabs(os.listdir("data/" + dir))
                k = -1
                for file in os.listdir("data/" + dir):
                    k += 1
                    with files[k]:
                        with open(f"data/{dir}/{file}", "r") as f:
                            o = f.read().split("<|end_of_turn|>")
                            for item in o:
                                if item == "":
                                    continue
                                item = item.split(": ", 1)
                                st.markdown(f":blue[{item[0].split('GPT4 Correct ')[1]}]: {item[1]}")

lock_file_path = "test.txt"

if not os.path.exists(lock_file_path):
    with open(lock_file_path, "w") as f:
        f.write("Running!")
    clone = False
else:
    print("Streamlit app is already running, only streaming activity.")
    clone = True
    while True:
        asyncio.run(syncMessages())
        time.sleep(0.5)
    exit()

try:
    os.mkdir("data")
except:
    pass


HF_TOKEN = os.environ["HF_TOKEN"]

login(HF_TOKEN)

SD = InferenceClient(model="stabilityai/stable-diffusion-2-1")
LLM = InferenceClient(model="openchat/openchat-3.5-0106")
RF = InferenceClient(model="stabilityai/stable-diffusion-xl-refiner-1.0")


def ec(x, fd="<|image|>", sd="<|image|>"):
    matches = re.findall(re.escape(fd) + "(.*?)" + re.escape(sd), x)
    matches = matches if matches else [""]
    return matches


intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

launch_time = datetime.datetime.utcnow()


@client.event
async def on_ready():
    if clone:
        print(f"Clone started.")
        await syncMessages()
    else:
        print(f"Logged in as {client.user}")
        presence.start()


@tasks.loop(seconds=60)
async def presence():
    if not clone:
        await syncMessages()
        delta_uptime = datetime.datetime.utcnow() - launch_time
        hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
        minutes, seconds = divmod(remainder, 60)
        days, hours = divmod(hours, 24)
        print(f"Online Time: {days:02d}d | {hours:02d}h | {minutes:02d}m | {seconds:02d}s")
        await client.change_presence(
            status=discord.Status.idle,
            activity=discord.Activity(
                type=discord.ActivityType.playing,
                large_image="https://i.imgur.com/Kk2BvJg.jpg",
                large_text="This is Game Icon",
                name="Escaping the IRS.",
                details="",
                state=f"Running for {days:02d}d | {hours:02d}h | {minutes:02d}m",
            ),
        )


@client.event
async def on_disconnect():
    print("Disconnected, Clone status:", clone)

@client.event
async def on_message(message):
    if clone:
        asyncio.sleep(1)
        await syncMessages()
        return 0
    else:
        await syncMessages()
    for user in message.mentions:
        message.content = message.content.replace(f"<@{user.id}>",
                                                  f"<@{str(user)}>")
    try:
        msgchannel = message.channel
        try:
            msgchannel_name = msgchannel.name
            guild = message.guild
            guild_name = guild.name
        except:
            guild_name = "Direct"
            msgchannel_name = message.author.display_name
        s = f":green[{message.author}]: :violet[{message.content}] :blue[{msgchannel_name}] :orange[{guild_name}]"
        if message.author == client.user:
            return
        sysp = """GPT4 Correct System: You are lr, a discord bot. You were made by Araeyn.
            You must use the markdown format for your responses.
            Do not excessively use bullet points.
            Use emojis at the start of your responses.
            Use <|title|> at the start of your title for the response and <|title|> at the end of the title.
            Your title must summarize the user's message.
            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.
            For example, if the user asks you to generate an image of a cat, you would say <|image|>A cute cat with long fur that is looking out a window with curious eyes.<|image|>
            Always include a title.
            Do not generate images unless the user speciifes that they want an image."""
        try:
            os.mkdir("data/" + guild_name)
        except:
            pass
        if os.path.exists(f"data/{guild_name}/{msgchannel_name}"):
            with open(f"data/{guild_name}/{msgchannel_name}", "a") as f:
                n = "\n"
                f.write(
                    f"""GPT4 Correct {message.author.name}: {message.content.strip(n)}<|end_of_turn|>"""
                )
        else:
            with open(f"data/{guild_name}/{msgchannel_name}", "w") as f:
                f.write(
                    f"GPT4 Correct system: {sysp}<|end_of_turn|>GPT4 Correct {message.author}: {message.content}<|end_of_turn|>"
                )
        with open(f"data/{guild_name}/{msgchannel_name}", "r") as f:
            context = f.read()
        await syncMessages()
        if "Feeway" in guild_name:
            async with msgchannel.typing():
                context += f"GPT4 Correct Assistant:"
                load = random.choice(
                    [
                        "https://cdn.dribbble.com/users/744913/screenshots/4094897/media/771a495231b798c0ccf7a59a19f31946.gif",
                        "https://cdn.dribbble.com/users/563824/screenshots/3633228/media/b620ccb3ae8c14ea5447d159ebb1da58.gif",
                        "https://cdn.dribbble.com/users/563824/screenshots/4155980/media/d3828cd14ed415eb6f90310991e06f27.gif",
                        "https://cdn.dribbble.com/users/107759/screenshots/3498589/media/5bc45101de34a80ea71238a02f3a75b5.gif",
                    ]
                )
                output = LLM.text_generation(context,
                                             stop_sequences=["<|end_of_turn|>"],
                                             max_new_tokens=4096)
                title = ec(output, "<|title|>", "<|title|>")[0]
                imgp = ec(output)[0]
                with open(f"data/{guild_name}/{msgchannel_name}", "a") as f:
                    f.write(f"GPT4 Correct Assistant: {output}<|end_of_turn|>")
                embed = discord.Embed(title=title,
                                      description=output.replace(
                                          f"<|title|>{title}<|title|>", "").replace(f"<|image|>{imgp}<|image|>", ""), 
                                      color=0x1E81B0)
                embed.set_footer(
                    text=
                    """Information or code generated by Lyre may not always be correct. Lyre was made by Araeyn."""
                )
                if imgp != "":
                    embed.set_image(url=load)
                e = await message.reply(embed=embed)
            print(imgp)
            if imgp != "":
                image = SD.text_to_image(imgp)
                image.save("image.png")
                image = RF.image_to_image("image.png")
                if image["warnings"]:
                    print(image)
                    return 0
                image.save("image.png")
                file = discord.File("image.png", filename="image.png")
                embed.set_image(url="attachment://image.png")
                await e.edit(embed=embed, attachments=[file])
                
            
    except Exception as e:
        print(e)

token = os.environ["TOKEN"]
client.run(token)