saanity / app.py
Araeynn's picture
Update app.py
09e9ff8
raw
history blame
9.03 kB
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()