import os
from multiprocess import Process
import discord
import traceback
import json
import torch
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="", second_delimiter=""
):
# 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-0106"
API_URL = "https://api-inference.huggingface.co/models/" + model
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
# from diffusers import StableDiffusionXLImg2ImgPipeline
# from diffusers.utils import load_image
# pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
# "stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float32, use_safetensors=True
# )
# pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
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()
def caption(filename):
with open(filename, "rb") as f:
data = f.read()
response = requests.post(API_URL, headers=headers, data=data)
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
ats = []
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
at the start of your title for the response and 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 and the end tag 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 A cute cat with long fur that is looking out a window with curious eyes.
Always include a title.
Do not generate images unless the user speciifes that they want an image.
<|end_of_turn|>"""
)
f.write(s)
if guild_name == "Direct" or msgchannel_name == "lyre":
async with msgchannel.typing():
with open(os.path.join(guild_name, f"{msgchannel_name}.txt"), "r") as f:
o = f.read()
title = ""
embed = discord.Embed(title=title, description="...", color=0x1E81B0)
embed.set_footer(
text="""Information or code generated by Lyre may not always be correct. Lyre was made by Araeyn."""
)
e = await message.reply(embed=embed)
o += "GPT4 Correct Assistant: "
print("right before query step.")
y = query({"inputs": o})
print("Got past query step.")
print(y)
r = y[0]["generated_text"][len(o) :]
title = extract_content(
r, first_delimiter="", second_delimiter=""
)[0]
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, "", "")[0]
print(title)
r = r.replace("" + 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 "" in r and "" in r:
i = extract_content(r)[0]
r = r.replace("" + i + "", "")
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")
# prompt = ""
# url = "latest.png"
# init_image = load_image(url).convert("RGB")
# image = pipe(prompt, image=init_image).images[0]
# print(image)
image.save("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)
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()