Spaces:
Paused
Paused
File size: 10,535 Bytes
3a8ffa5 f4e1d2a 3a8ffa5 b4074b4 3a8ffa5 b61978a 3a8ffa5 b61978a 3a8ffa5 b61978a 3a8ffa5 b61978a 3a8ffa5 b61978a 3a8ffa5 b61978a 3a8ffa5 b61978a 3a8ffa5 fb3c3dd 3a8ffa5 e061df9 6f3a584 e061df9 3a8ffa5 b61978a 3a8ffa5 b61978a 3a8ffa5 b61978a 3a8ffa5 b61978a 3a8ffa5 b61978a 3a8ffa5 e061df9 3a8ffa5 b61978a 3a8ffa5 b61978a 3a8ffa5 b61978a 3a8ffa5 b61978a d99e3cf b61978a 3a8ffa5 b61978a 4d7eb22 b61978a 3a8ffa5 b61978a 3a8ffa5 b61978a d125931 1a84248 b61978a 1a84248 af28236 b61978a 1a84248 b61978a 1a84248 b61978a 3a8ffa5 b61978a 9fbae99 f4e1d2a b61978a f4e1d2a b61978a |
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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
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="<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-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 <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.
<|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="<title>", second_delimiter="</title>"
)[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, "<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")
# 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()
|