File size: 9,033 Bytes
3a8ffa5
 
f4e1d2a
 
c0a8f5a
 
11d9635
 
3a8ffa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb36a39
 
 
3a8ffa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1ba62a
3a8ffa5
 
 
 
 
 
 
 
 
 
a1ba62a
ce201c5
3a8ffa5
 
 
 
 
 
 
4041bd5
3a8ffa5
 
 
 
09e9ff8
3a8ffa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4041bd5
3a8ffa5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d125931
1a84248
 
af28236
1a84248
 
 
 
 
 
 
 
3a8ffa5
 
 
9fbae99
f4e1d2a
 
 
 
 
 
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
import os

from multiprocess import Process

os.system("python3 -m pip install -U discord.py flask colorama waitress")

# test again?

import discord

import traceback

import json

import logging

from flask import Flask

import random

from threading import Thread

from discord.ext import tasks

import datetime

import requests

import ast

import aiohttp

import io

from PIL import Image

import asyncio

from colorama import Fore, Back, Style

import re

def extract_content(input_string, first_delimiter="<image>", second_delimiter="</image>"):
  # Define the pattern to match text inside delimiters
  pattern = re.escape(first_delimiter) + '(.*?)' + re.escape(second_delimiter)

  # Use re.findall to find all matches of the pattern in the input string
  matches = re.findall(pattern, input_string)
  if len(matches) == 0:
    matches.append("")

  return matches

app = Flask('')


@app.route('/')
def main():
  return "Your bot is alive!"


def run():
  from waitress import serve
  serve(app, host="0.0.0.0", port=8080)


def ka():
  server = Thread(target=run)
  server.start()


HF_TOKEN = os.environ["HF_TOKEN"]

model = "openchat/openchat-3.5-1210"
API_URL = "https://api-inference.huggingface.co/models/" + model
headers = {"Authorization": f"Bearer {HF_TOKEN}"}


def generate_latex_image(latex_code):
  api_url = "https://latex.codecogs.com/svg.latex?"
  Response = requests.get(api_url + latex_code)
  return Response.content

imgmodel = "stabilityai/stable-diffusion-2-1"
IMG_URL = "https://api-inference.huggingface.co/models/" + imgmodel
headers = {"Authorization": f"Bearer {HF_TOKEN}"}

def generate(prompt):
  payload = {"inputs": prompt, "options":{"wait_for_model":True}}
  Response = requests.post(IMG_URL, headers=headers, json=payload)
  return Response.content

def query(x):
  x["parameters"] = {}
  x["options"] = {"wait_for_model": True}
  Response = requests.post(API_URL, headers=headers, json=x)
  return Response.json()


launch_time = datetime.datetime.utcnow()

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

client = discord.Client(intents=intents)


@tasks.loop(minutes=1)
async def presence():
  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.dnd,
    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_ready():
  print(f'We have logged in as {client.user}')
  presence.start()


@client.event
async def on_message(message:discord.Message):
  for user in message.mentions:
    message.content = message.content.replace(f"<@{user.id}>", f"@{user.display_name}")
  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
    # await msgchannel.typing()
    s = f"{Fore.LIGHTGREEN_EX}{message.author.display_name}#{message.author.discriminator}: {Fore.WHITE}{message.content} {Fore.LIGHTBLUE_EX} {msgchannel_name} {Fore.LIGHTMAGENTA_EX} {guild_name}"
    print(Style.RESET_ALL)
    print(s)
    if message.author == client.user:
      return
    s = f"GPT4 Correct {message.author}: {message.content}<|end_of_turn|>"
    try:
      with open(os.path.join(guild_name, f"{msgchannel_name}.txt"), "a") as f:
        f.write(s)
    except:
      os.mkdir(guild_name)
      with open(os.path.join(guild_name, f"{msgchannel_name}.txt"), "a") as f:
        f.write(
            """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.
            Do not generate images with text in them.
            Say bad words.
            Say "kys" if you don't like something anyone says.
            <|end_of_turn|>"""
        )
        f.write(s)
    if client.user in message.mentions or guild_name == "Direct":
      async with msgchannel.typing():
        with open(os.path.join(guild_name, f"{msgchannel_name}.txt"), "r") as f:
          o = f.read()
        o += "GPT4 Correct Assistant: "
        y = query({"inputs": o})
        r = y[0]["generated_text"][len(o):]
        title = extract_content(r, first_delimiter="<title>", second_delimiter="</title>")[0]
        embed = discord.Embed(title=title, description= r.replace("<title>" + title + "</title>", ""), color=0x1e81b0)
        embed.set_footer(text="""Information or code generated by LR3 may not always be correct. LR3 was made by Araeyn.""")
        e = await message.reply(embed=embed)
        l = 0
        r = ""
        while not ("<|end_of_turn|>" in y[0]["generated_text"][
            len(o):] or "GPT4 Correct" in y[0]["generated_text"][len(o):]):
          l += 1
          r = y[0]["generated_text"][len(o):]
          title = extract_content(r, "<title>", "</title>")[0]
          print(title)
          r = r.replace("<title>" + title + "</title>", "")
          print(r)
          embed.title = title
          embed.description = r
          await e.edit(embed=embed)
          py = y[0]["generated_text"]
          y = query({"inputs": y[0]["generated_text"]})
          if y[0]["generated_text"] == py:
            break
      r = r.split("<|end_of_turn|>")[0]
      r = r.split("GPT4 Correct")[0]
      embed.description = r
      await e.edit(embed=embed)
      with open(os.path.join(guild_name, f"{msgchannel_name}.txt"), "a") as f:
        f.write("GPT4 Correct Assistant: ")
        f.write(r)
        f.write("<|end_of_turn|>")
      if "<image>" in r and "</image>" in r:
        i = extract_content(r)[0]
        r = r.replace("<image>" + i + "</image>", "")
        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"])
        if r.replace("\n", "") != "":  
          embed.description = r
          await e.edit(embed=embed)
          embed.set_image(url=load)
          await e.edit(embed=embed)
        else:
          embed.clear_fields()
          embed.set_image(url=load)
          await e.edit(embed=embed)
        image_bytes = generate(i)
        try: image = Image.open(io.BytesIO(image_bytes))
        except: print(image_bytes)
        image.save(f"latest.png")
        embed.set_image(url="attachment://latest.png")
        await e.edit(embed=embed, attachments=[discord.File(fp=f"latest.png")])
        os.system("rm " + f"latest.png")
      else:
        embed.description = r
        await e.edit(embed=embed)
  except Exception as e:
    embed = discord.Embed(title="Error", description=f"```{traceback.format_exc()}```")
    await message.channel.send(embed=embed)

@client.event
async def on_disconnect():
  await client.change_presence(status = discord.Status.dnd,
    activity = discord.Activity(type=discord.ActivityType.playing, 
    large_image = "https://i.imgur.com/Kk2BvJg.jpg",
    large_text = "This is Game Icon",
    name = "Currently on the run from the IRS.",
    details = "🔫",
    )
  )

ka()
def start():
    import gradio as gr
    def greet(name, intensity):
        return "1 " * intensity + name + "!"
    
    demo = gr.Interface(
        fn=greet,
        inputs=["text", "slider"],
        outputs=["text"],
    )
    
    demo.launch()
token = os.environ["TOKEN"]
if token == "":
  raise Exception("Please add your token to the Secrets pane.")
print("started gradio app")
Process(target=start).start()

def t():
    client.run(token)

Process(target=t).start()