feat: Cleanup dockerfiles

pull/69/head
Zack 2 years ago
parent 38cdd95c0a
commit 74297ff116

@ -43,7 +43,7 @@ def check_verion() -> None:
@bot.event @bot.event
async def on_ready(): async def on_ready():
bot_status = discord.Status.online bot_status = discord.Status.online
bot_activity = discord.Activity(type=discord.ActivityType.playing, name="bing.com") # bot_activity = discord.Activity(type=discord.ActivityType.playing, name="bing.com")
await bot.change_presence(status=bot_status, activity=bot_activity) await bot.change_presence(status=bot_status, activity=bot_activity)
for Filename in os.listdir("./cogs"): for Filename in os.listdir("./cogs"):
if Filename.endswith(".py"): if Filename.endswith(".py"):

@ -19,7 +19,6 @@ users_chatbot = {}
users_image_generator = {} users_image_generator = {}
user_conversation_style = {} user_conversation_style = {}
async def init_chatbot(user_id): async def init_chatbot(user_id):
with open("./cookies.json", encoding="utf-8") as file: with open("./cookies.json", encoding="utf-8") as file:
cookie_json = json.load(file) cookie_json = json.load(file)
@ -30,35 +29,46 @@ async def init_chatbot(user_id):
auth_cookie = os.environ.get("AUTH_COOKIE") auth_cookie = os.environ.get("AUTH_COOKIE")
auth_cookie_SRCHHPGUSR = os.environ.get("AUTH_COOKIE_SRCHHPGUSR") auth_cookie_SRCHHPGUSR = os.environ.get("AUTH_COOKIE_SRCHHPGUSR")
# auth_cookie_SRCHHPGUSR = os.environ.get("AUTH_COOKIE_SRCHHPGUSR")
users_chatbot[user_id] = UserChatbot(cookies=cookie_json) users_chatbot[user_id] = UserChatbot(cookies=cookie_json)
users_image_generator[user_id] = ImageGenAsync(auth_cookie, quiet=True) users_image_generator[user_id] = ImageGenAsync(auth_cookie, quiet=True)
user_conversation_style[user_id] = "balanced" user_conversation_style[user_id] = "balanced"
class UserChatbot: class UserChatbot:
def __init__(self, cookies): def __init__(self, cookies):
self.chatbot = Chatbot(cookies=cookies) self.chatbot = Chatbot(cookies=cookies)
async def send_message(self, interaction, message, conversation_style): async def send_message(self, interaction, message, conversation_style, image_file=None):
await send_message(self.chatbot, interaction, message, conversation_style) if image_file:
# Download the image from Discord
async def create_image(self, interaction, prompt: str, image_generator): image_data = await image_file.read()
await create_image(interaction, prompt, image_generator) # Send the image data to the Bing model
response = await self.chatbot.send_image(image_data)
async def reset(self): # Send the response from the Bing model to the user
await self.chatbot.reset() await interaction.channel.send(content=response)
else:
await send_message(self.chatbot, interaction, message, conversation_style)
class EdgeGPT(Cog_Extension): class EdgeGPT(Cog_Extension):
# Chat with Bing
@app_commands.command(name="bing", description="Have a chat with Bing") @app_commands.command(name="bing", description="Have a chat with Bing")
async def bing(self, interaction: discord.Interaction, *, message: str): async def bing(self, interaction: discord.Interaction, *, message: str):
try: user_id = interaction.user.id
using = await get_using_send(interaction.user.id) if user_id not in users_chatbot:
except: await init_chatbot(user_id)
await set_using_send(interaction.user.id, False) conversation_style = user_conversation_style[user_id]
using = await get_using_send(interaction.user.id) usermessage = message
# Check the last 10 messages for attachments
image_file = None
async for msg in interaction.channel.history(limit=10):
if msg.attachments:
image_file = msg.attachments[0]
break
# If an attachment was found, send it to the model
if image_file:
await users_chatbot[user_id].send_message(interaction, usermessage, conversation_style, image_file)
else:
await users_chatbot[user_id].send_message(interaction, usermessage, conversation_style)
if not using: if not using:
await interaction.response.defer(ephemeral=False, thinking=True) await interaction.response.defer(ephemeral=False, thinking=True)
username = str(interaction.user) username = str(interaction.user)
@ -68,17 +78,11 @@ class EdgeGPT(Cog_Extension):
if user_id not in users_chatbot: if user_id not in users_chatbot:
await init_chatbot(interaction.user.id) await init_chatbot(interaction.user.id)
conversation_style = user_conversation_style[user_id] conversation_style = user_conversation_style[user_id]
logger.info( logger.info(f"\x1b[31m{username}\x1b[0m : '{usermessage}' ({channel}) [Style: {conversation_style}]")
f"\x1b[31m{username}\x1b[0m : '{usermessage}' ({channel}) [Style: {conversation_style}]" await users_chatbot[user_id].send_message(interaction, usermessage, conversation_style)
)
await users_chatbot[user_id].send_message(
interaction, usermessage, conversation_style
)
else: else:
await interaction.response.defer(ephemeral=True, thinking=True) await interaction.response.defer(ephemeral=True, thinking=True)
await interaction.followup.send( await interaction.followup.send("> **Please wait for your last conversation to finish.**")
"> **Please wait for your last conversation to finish.**"
)
# Reset Bing conversation # Reset Bing conversation
@app_commands.command(name="reset", description="Reset Bing conversation") @app_commands.command(name="reset", description="Reset Bing conversation")
@ -90,49 +94,25 @@ class EdgeGPT(Cog_Extension):
await interaction.followup.send("> **Info: Reset finish.**") await interaction.followup.send("> **Info: Reset finish.**")
logger.warning("\x1b[31mBing has been successfully reset\x1b[0m") logger.warning("\x1b[31mBing has been successfully reset\x1b[0m")
except: except:
await interaction.followup.send( await interaction.followup.send(f"> **You don't have any conversation yet.**")
f"> **You don't have any conversation yet.**"
)
logger.exception("Bing reset failed.") logger.exception("Bing reset failed.")
# Switch conversation style # Switch conversation style
@app_commands.command(name="switch_style", description="Switch conversation style") @app_commands.command(name="switch_style", description="Switch conversation style")
@app_commands.choices( @app_commands.choices(style=[app_commands.Choice(name="Creative", value="creative"), app_commands.Choice(name="Balanced", value="balanced"), app_commands.Choice(name="Precise", value="precise")])
style=[ async def switch_style(self, interaction: discord.Interaction, style: app_commands.Choice[str]):
app_commands.Choice(name="Creative", value="creative"),
app_commands.Choice(name="Balanced", value="balanced"),
app_commands.Choice(name="Precise", value="precise"),
]
)
async def switch_style(
self, interaction: discord.Interaction, style: app_commands.Choice[str]
):
await interaction.response.defer(ephemeral=True, thinking=True) await interaction.response.defer(ephemeral=True, thinking=True)
user_id = interaction.user.id user_id = interaction.user.id
if user_id not in users_chatbot: if user_id not in users_chatbot:
await init_chatbot(user_id) await init_chatbot(user_id)
user_conversation_style[user_id] = style.value user_conversation_style[user_id] = style.value
await interaction.followup.send( await interaction.followup.send(f"> **Info: successfull switch conversation style to {style.value}.**")
f"> **Info: successfull switch conversation style to {style.value}.**" logger.warning(f"\x1b[31mConversation style has been successfully switch to {style.value}\x1b[0m")
)
logger.warning(
f"\x1b[31mConversation style has been successfully switch to {style.value}\x1b[0m"
)
# Set and delete personal Bing Cookies # Set and delete personal Bing Cookies
@app_commands.command(name="bing_cookies", description="Set or delete Bing Cookies") @app_commands.command(name="bing_cookies", description="Set or delete Bing Cookies")
@app_commands.choices( @app_commands.choices(choice=[app_commands.Choice(name="set", value="set"), app_commands.Choice(name="delete", value="delete")])
choice=[ async def cookies_setting(self, interaction: discord.Interaction, choice: app_commands.Choice[str], cookies_file: Optional[discord.Attachment]=None):
app_commands.Choice(name="set", value="set"),
app_commands.Choice(name="delete", value="delete"),
]
)
async def cookies_setting(
self,
interaction: discord.Interaction,
choice: app_commands.Choice[str],
cookies_file: Optional[discord.Attachment] = None,
):
await interaction.response.defer(ephemeral=True, thinking=True) await interaction.response.defer(ephemeral=True, thinking=True)
user_id = interaction.user.id user_id = interaction.user.id
if choice.value == "set": if choice.value == "set":
@ -146,13 +126,9 @@ class EdgeGPT(Cog_Extension):
users_chatbot[user_id] = UserChatbot(cookies=content) users_chatbot[user_id] = UserChatbot(cookies=content)
user_conversation_style[user_id] = "balanced" user_conversation_style[user_id] = "balanced"
await interaction.followup.send("> **Upload successful!**") await interaction.followup.send("> **Upload successful!**")
logger.warning( logger.warning(f"\x1b[31m{interaction.user} set Bing Cookies successful\x1b[0m")
f"\x1b[31m{interaction.user} set Bing Cookies successful\x1b[0m"
)
except: except:
await interaction.followup.send( await interaction.followup.send("> **Please upload your Bing Cookies.**")
"> **Please upload your Bing Cookies.**"
)
else: else:
try: try:
del users_chatbot[user_id] del users_chatbot[user_id]
@ -161,14 +137,10 @@ class EdgeGPT(Cog_Extension):
await interaction.followup.send("> **Delete finish.**") await interaction.followup.send("> **Delete finish.**")
logger.warning(f"\x1b[31m{interaction.user} delete Cookies\x1b[0m") logger.warning(f"\x1b[31m{interaction.user} delete Cookies\x1b[0m")
except: except:
await interaction.followup.send( await interaction.followup.send("> **You don't have any Bing Cookies.**")
"> **You don't have any Bing Cookies.**"
)
# Create images # Create images
@app_commands.command( @app_commands.command(name="create_image", description="generate image by Bing image creator")
name="create_image", description="generate image by Bing image creator"
)
async def create_image(self, interaction: discord.Interaction, *, prompt: str): async def create_image(self, interaction: discord.Interaction, *, prompt: str):
user_id = interaction.user.id user_id = interaction.user.id
if interaction.user.id not in users_chatbot: if interaction.user.id not in users_chatbot:
@ -179,18 +151,11 @@ class EdgeGPT(Cog_Extension):
await set_using_create(user_id, False) await set_using_create(user_id, False)
using = await get_using_create(user_id) using = await get_using_create(user_id)
if not using: if not using:
logger.info( logger.info(f"\x1b[31m{interaction.user}\x1b[0m : '{prompt}' ({interaction.channel}) [BingImageCreator]")
f"\x1b[31m{interaction.user}\x1b[0m : '{prompt}' ({interaction.channel}) [BingImageCreator]" await users_chatbot[user_id].create_image(interaction, prompt, users_image_generator[user_id] )
)
await users_chatbot[user_id].create_image(
interaction, prompt, users_image_generator[user_id]
)
else: else:
await interaction.response.defer(ephemeral=True, thinking=True) await interaction.response.defer(ephemeral=True, thinking=True)
await interaction.followup.send( await interaction.followup.send("> **Please wait for your last image to create finish.**")
"> **Please wait for your last image to create finish.**"
)
async def setup(bot): async def setup(bot):
await bot.add_cog(EdgeGPT(bot)) await bot.add_cog(EdgeGPT(bot))

@ -143,7 +143,7 @@ async def set_chatbot(cookies):
chatbot = Chatbot(cookies=cookies) chatbot = Chatbot(cookies=cookies)
async def send_message(chatbot: Chatbot, message, user_message: str): async def send_message(chatbot: Chatbot, message, user_message: str, image_file=None):
async with sem: async with sem:
if isinstance(message, discord.message.Message): if isinstance(message, discord.message.Message):
await message.channel.typing() await message.channel.typing()
@ -155,23 +155,56 @@ async def send_message(chatbot: Chatbot, message, user_message: str):
try: try:
# Change conversation style # Change conversation style
if conversation_style == "creative": if conversation_style == "creative":
reply = await chatbot.ask( if image_file:
prompt=user_message, # Download the image from Discord
conversation_style=ConversationStyle.creative, image_data = await image_file.read()
simplify_response=True, # Send the image data to the model
) reply = await chatbot.ask(
prompt=user_message,
conversation_style=ConversationStyle.creative,
simplify_response=True,
image=image_data,
)
else:
reply = await chatbot.ask(
prompt=user_message,
conversation_style=ConversationStyle.creative,
simplify_response=True,
)
elif conversation_style == "precise": elif conversation_style == "precise":
reply = await chatbot.ask( if image_file:
prompt=user_message, # Download the image from Discord
conversation_style=ConversationStyle.precise, image_data = await image_file.read()
simplify_response=True, # Send the image data to the model
) reply = await chatbot.ask(
prompt=user_message,
conversation_style=ConversationStyle.precise,
simplify_response=True,
image=image_data,
)
else:
reply = await chatbot.ask(
prompt=user_message,
conversation_style=ConversationStyle.precise,
simplify_response=True,
)
else: else:
reply = await chatbot.ask( if image_file:
prompt=user_message, # Download the image from Discord
conversation_style=ConversationStyle.balanced, image_data = await image_file.read()
simplify_response=True, # Send the image data to the model
) reply = await chatbot.ask(
prompt=user_message,
conversation_style=ConversationStyle.balanced,
simplify_response=True,
image=image_data,
)
else:
reply = await chatbot.ask(
prompt=user_message,
conversation_style=ConversationStyle.balanced,
simplify_response=True,
)
# Get reply text # Get reply text
text = f"{reply['text']}" text = f"{reply['text']}"

@ -8,7 +8,6 @@ class Help(Cog_Extension):
async def help(self, interaction: discord.Interaction): async def help(self, interaction: discord.Interaction):
embed = discord.Embed( embed = discord.Embed(
title="Help", title="Help",
description="[see more](https://github.com/FuseFairy/DiscordBot-EdgeGPT/blob/main/README.md)\n\n**COMMANDS -**",
) )
embed.add_field( embed.add_field(
name="/bing_cookies", name="/bing_cookies",

@ -1,7 +1,8 @@
version: '3' version: '3'
services: services:
BingBot: spartan:
container_name: Spartan
build: . build: .
environment: environment:
- DISCORD_BOT_TOKEN=${DISCORD_BOT_TOKEN} - DISCORD_BOT_TOKEN=${DISCORD_BOT_TOKEN}

@ -1,4 +1,4 @@
discord.py==2.3.2 discord.py==2.3.2
python-dotenv==0.21.1 python-dotenv==1.0.0
PyYAML==6.0 PyYAML==6.0.1
EdgeGPT==0.13.2 bing-chat==1.9.3

@ -1,75 +0,0 @@
import openai
import os
import dotenv
import logging
import gradio as gr
from BingImageCreator import ImageGen
from swarms.models.bing_chat import BingChat
# from swarms.models.bingchat import BingChat
dotenv.load_dotenv(".env")
# Initialize the EdgeGPTModel
model = BingChat()
response = model("Generate")
logging.basicConfig(level=logging.INFO)
accumulated_story = ""
latest_caption = ""
standard_suffix = ""
storyboard = []
def generate_images_with_bingchat(caption):
img_path = model.create_img(caption)
img_urls = model.images(caption)
return img_urls
def generate_single_caption(text):
prompt = f"A comic about {text}."
response = model(text)
return response
def interpret_text_with_gpt(text, suffix):
return generate_single_caption(f"{text} {suffix}")
def create_standard_suffix(original_prompt):
return f"In the style of {original_prompt}"
def gradio_interface(text=None, next_button_clicked=False):
global accumulated_story, latest_caption, standard_suffix, storyboard
if not standard_suffix:
standard_suffix = create_standard_suffix(text)
if next_button_clicked:
new_caption = generate_single_caption(latest_caption + " " + standard_suffix)
new_urls = generate_images_with_bingchat(new_caption)
latest_caption = new_caption
storyboard.append((new_urls, new_caption))
elif text:
caption = generate_single_caption(text + " " + standard_suffix)
comic_panel_urls = generate_images_with_bingchat(caption)
latest_caption = caption
storyboard.append((comic_panel_urls, caption))
storyboard_html = ""
for urls, cap in storyboard:
for url in urls:
storyboard_html += f'<img src="{url}" alt="{cap}" width="300"/><br>{cap}<br>'
return storyboard_html
if __name__ == "__main__":
iface = gr.Interface(
fn=gradio_interface,
inputs=[
gr.inputs.Textbox(default="Type your story concept here", optional=True, label="Story Concept"),
gr.inputs.Checkbox(label="Generate Next Part")
],
outputs=[gr.outputs.HTML()],
live=False # Submit button will appear
)
iface.launch()

@ -1,135 +1,77 @@
import openai
import os import os
import discord
from discord.ext import commands
import interpreter
import dotenv import dotenv
import whisper import logging
import gradio as gr
from BingImageCreator import ImageGen
from swarms.models.bing_chat import BingChat
# from swarms.models.bingchat import BingChat
dotenv.load_dotenv(".env") dotenv.load_dotenv(".env")
bot_id = os.getenv("BOT_ID") # Initialize the EdgeGPTModel
bot_token = os.getenv("DISCORD_TOKEN") model = BingChat()
interpreter.api_key = os.getenv("OPENAI_API_KEY") response = model("Generate")
# interpreter.api_base = os.getenv("API_BASE")
# interpreter.auto_run = True logging.basicConfig(level=logging.INFO)
accumulated_story = ""
def split_text(text, chunk_size=1500): latest_caption = ""
######################################################################### standard_suffix = ""
return [text[i : i + chunk_size] for i in range(0, len(text), chunk_size)] storyboard = []
caption = "Create comic about opensourcerer a robot wizard"
# discord initial
intents = discord.Intents.all() def generate_images_with_bingchat(caption):
intents.message_content = True img_path = model.create_img(caption)
client = commands.Bot(command_prefix="$", intents=intents) img_urls = model.images(caption)
return img_urls
message_chunks = []
send_image = False def generate_single_caption(text):
prompt = f"A comic about {text}."
model = whisper.load_model("base") response = model(text)
return response
def transcribe(audio): def interpret_text_with_gpt(text, suffix):
# load audio and pad/trim it to fit 30 seconds return generate_single_caption(f"{text} {suffix}")
audio = whisper.load_audio(audio)
audio = whisper.pad_or_trim(audio) def create_standard_suffix(original_prompt):
return f"In the style of {original_prompt}"
# make log-Mel spectrogram and move to the same device as the model
mel = whisper.log_mel_spectrogram(audio).to(model.device) def gradio_interface(text=None, next_button_clicked=False):
global accumulated_story, latest_caption, standard_suffix, storyboard
# detect the spoken language
_, probs = model.detect_language(mel) if not standard_suffix:
standard_suffix = create_standard_suffix(text)
# decode the audio
options = whisper.DecodingOptions() if next_button_clicked:
result = whisper.decode(model, mel, options) new_caption = generate_single_caption(latest_caption + " " + standard_suffix)
return result.text new_urls = generate_images_with_bingchat(new_caption)
latest_caption = new_caption
storyboard.append((new_urls, new_caption))
@client.event
async def on_message(message): elif text:
await client.process_commands(message) caption = generate_single_caption(text + " " + standard_suffix)
bot_mention = f"<@{bot_id}>" comic_panel_urls = generate_images_with_bingchat(caption)
# if ("<@1158923910855798804>" in message.content) or (message.author == client.user or message.content[0] == '$'): latest_caption = caption
# return storyboard.append((comic_panel_urls, caption))
response = []
for chunk in interpreter.chat(message.content, display=False, stream=False): storyboard_html = ""
# await message.channel.send(chunk) for urls, cap in storyboard:
if "message" in chunk: for url in urls:
response.append(chunk["message"]) storyboard_html += f'<img src="{url}" alt="{cap}" width="300"/><br>{cap}<br>'
last_response = response[-1]
return storyboard_html
max_message_length = 2000 # Discord's max message length is 2000 characters
# Splitting the message into chunks of 2000 characters if __name__ == "__main__":
response_chunks = [ iface = gr.Interface(
last_response[i : i + max_message_length] fn=gradio_interface,
for i in range(0, len(last_response), max_message_length) inputs=[
] gr.inputs.Textbox(default="Type your story concept here", optional=True, label="Story Concept"),
# Sending each chunk as a separate message gr.inputs.Checkbox(label="Generate Next Part")
for chunk in response_chunks: ],
await message.channel.send(chunk) outputs=[gr.outputs.HTML()],
live=False # Submit button will appear
)
@client.command() iface.launch()
async def join(ctx):
if ctx.author.voice:
channel = ctx.message.author.voice.channel
print("joining..")
await channel.connect()
print("joined.")
else:
print("not in a voice channel!")
@client.command()
async def leave(ctx):
if ctx.voice_client:
await ctx.voice_client.disconnect()
else:
print("not in a voice channel!")
@client.command()
async def listen(ctx):
if ctx.voice_client:
print("trying to listen..")
ctx.voice_client.start_recording(discord.sinks.WaveSink(), callback, ctx)
print("listening..")
else:
print("not in a voice channel!")
async def callback(sink: discord.sinks, ctx):
print("in callback..")
for user_id, audio in sink.audio_data.items():
if user_id == ctx.author.id:
print("saving audio..")
audio: discord.sinks.core.AudioData = audio
print(user_id)
filename = "audio.wav"
with open(filename, "wb") as f:
f.write(audio.file.getvalue())
print("audio saved.")
transcription = transcribe(filename)
print(transcription)
response = []
for chunk in interpreter.chat(transcription, display=False, stream=True):
# await message.channel.send(chunk)
if "message" in chunk:
response.append(chunk["message"])
await ctx.message.channel.send(" ".join(response))
@client.command()
async def stop(ctx):
ctx.voice_client.stop_recording()
@client.event
async def on_ready():
print(f"We have logged in as {client.user}")
client.run(bot_token)

File diff suppressed because one or more lines are too long
Loading…
Cancel
Save