feat: Cleanup dockerfiles

Former-commit-id: 74297ff116
blog-agent
Zack 2 years ago
parent 8d41ad1aa8
commit 707a9b5a32

@ -43,7 +43,7 @@ def check_verion() -> None:
@bot.event
async def on_ready():
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)
for Filename in os.listdir("./cogs"):
if Filename.endswith(".py"):

@ -19,7 +19,6 @@ users_chatbot = {}
users_image_generator = {}
user_conversation_style = {}
async def init_chatbot(user_id):
with open("./cookies.json", encoding="utf-8") as file:
cookie_json = json.load(file)
@ -27,40 +26,51 @@ async def init_chatbot(user_id):
if cookie.get("name") == "_U":
auth_cookie = cookie.get("value")
break
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")
users_chatbot[user_id] = UserChatbot(cookies=cookie_json)
users_image_generator[user_id] = ImageGenAsync(auth_cookie, quiet=True)
user_conversation_style[user_id] = "balanced"
class UserChatbot:
def __init__(self, cookies):
self.chatbot = Chatbot(cookies=cookies)
async def send_message(self, interaction, message, conversation_style):
await send_message(self.chatbot, interaction, message, conversation_style)
async def create_image(self, interaction, prompt: str, image_generator):
await create_image(interaction, prompt, image_generator)
async def reset(self):
await self.chatbot.reset()
async def send_message(self, interaction, message, conversation_style, image_file=None):
if image_file:
# Download the image from Discord
image_data = await image_file.read()
# Send the image data to the Bing model
response = await self.chatbot.send_image(image_data)
# Send the response from the Bing model to the user
await interaction.channel.send(content=response)
else:
await send_message(self.chatbot, interaction, message, conversation_style)
class EdgeGPT(Cog_Extension):
# Chat with Bing
@app_commands.command(name="bing", description="Have a chat with Bing")
async def bing(self, interaction: discord.Interaction, *, message: str):
try:
using = await get_using_send(interaction.user.id)
except:
await set_using_send(interaction.user.id, False)
using = await get_using_send(interaction.user.id)
user_id = interaction.user.id
if user_id not in users_chatbot:
await init_chatbot(user_id)
conversation_style = user_conversation_style[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:
await interaction.response.defer(ephemeral=False, thinking=True)
await interaction.response.defer(ephemeral=False, thinking=True)
username = str(interaction.user)
usermessage = message
channel = str(interaction.channel)
@ -68,18 +78,12 @@ class EdgeGPT(Cog_Extension):
if user_id not in users_chatbot:
await init_chatbot(interaction.user.id)
conversation_style = user_conversation_style[user_id]
logger.info(
f"\x1b[31m{username}\x1b[0m : '{usermessage}' ({channel}) [Style: {conversation_style}]"
)
await users_chatbot[user_id].send_message(
interaction, usermessage, conversation_style
)
logger.info(f"\x1b[31m{username}\x1b[0m : '{usermessage}' ({channel}) [Style: {conversation_style}]")
await users_chatbot[user_id].send_message(interaction, usermessage, conversation_style)
else:
await interaction.response.defer(ephemeral=True, thinking=True)
await interaction.followup.send(
"> **Please wait for your last conversation to finish.**"
)
await interaction.followup.send("> **Please wait for your last conversation to finish.**")
# Reset Bing conversation
@app_commands.command(name="reset", description="Reset Bing conversation")
async def reset(self, interaction: discord.Interaction):
@ -90,49 +94,25 @@ class EdgeGPT(Cog_Extension):
await interaction.followup.send("> **Info: Reset finish.**")
logger.warning("\x1b[31mBing has been successfully reset\x1b[0m")
except:
await interaction.followup.send(
f"> **You don't have any conversation yet.**"
)
await interaction.followup.send(f"> **You don't have any conversation yet.**")
logger.exception("Bing reset failed.")
# Switch conversation style
@app_commands.command(name="switch_style", description="Switch conversation style")
@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"),
]
)
async def switch_style(
self, interaction: discord.Interaction, style: app_commands.Choice[str]
):
@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")])
async def switch_style(self, interaction: discord.Interaction, style: app_commands.Choice[str]):
await interaction.response.defer(ephemeral=True, thinking=True)
user_id = interaction.user.id
if user_id not in users_chatbot:
await init_chatbot(user_id)
user_conversation_style[user_id] = style.value
await interaction.followup.send(
f"> **Info: successfull switch conversation style to {style.value}.**"
)
logger.warning(
f"\x1b[31mConversation style has been successfully switch to {style.value}\x1b[0m"
)
await interaction.followup.send(f"> **Info: successfull switch conversation style to {style.value}.**")
logger.warning(f"\x1b[31mConversation style has been successfully switch to {style.value}\x1b[0m")
# Set and delete personal Bing Cookies
@app_commands.command(name="bing_cookies", description="Set or delete Bing Cookies")
@app_commands.choices(
choice=[
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,
):
@app_commands.choices(choice=[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)
user_id = interaction.user.id
if choice.value == "set":
@ -144,15 +124,11 @@ class EdgeGPT(Cog_Extension):
break
users_image_generator[user_id] = ImageGenAsync(auth_cookie, quiet=True)
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!**")
logger.warning(
f"\x1b[31m{interaction.user} set Bing Cookies successful\x1b[0m"
)
logger.warning(f"\x1b[31m{interaction.user} set Bing Cookies successful\x1b[0m")
except:
await interaction.followup.send(
"> **Please upload your Bing Cookies.**"
)
await interaction.followup.send("> **Please upload your Bing Cookies.**")
else:
try:
del users_chatbot[user_id]
@ -161,14 +137,10 @@ class EdgeGPT(Cog_Extension):
await interaction.followup.send("> **Delete finish.**")
logger.warning(f"\x1b[31m{interaction.user} delete Cookies\x1b[0m")
except:
await interaction.followup.send(
"> **You don't have any Bing Cookies.**"
)
await interaction.followup.send("> **You don't have any Bing Cookies.**")
# Create images
@app_commands.command(
name="create_image", description="generate image by Bing image creator"
)
@app_commands.command(name="create_image", description="generate image by Bing image creator")
async def create_image(self, interaction: discord.Interaction, *, prompt: str):
user_id = interaction.user.id
if interaction.user.id not in users_chatbot:
@ -178,19 +150,12 @@ class EdgeGPT(Cog_Extension):
except:
await set_using_create(user_id, False)
using = await get_using_create(user_id)
if not using:
logger.info(
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]
)
if not using:
logger.info(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] )
else:
await interaction.response.defer(ephemeral=True, thinking=True)
await interaction.followup.send(
"> **Please wait for your last image to create finish.**"
)
await interaction.followup.send("> **Please wait for your last image to create finish.**")
async def setup(bot):
await bot.add_cog(EdgeGPT(bot))

@ -143,7 +143,7 @@ async def set_chatbot(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:
if isinstance(message, discord.message.Message):
await message.channel.typing()
@ -155,24 +155,57 @@ async def send_message(chatbot: Chatbot, message, user_message: str):
try:
# Change conversation style
if conversation_style == "creative":
reply = await chatbot.ask(
prompt=user_message,
conversation_style=ConversationStyle.creative,
simplify_response=True,
)
if image_file:
# Download the image from Discord
image_data = await image_file.read()
# 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":
reply = await chatbot.ask(
prompt=user_message,
conversation_style=ConversationStyle.precise,
simplify_response=True,
)
if image_file:
# Download the image from Discord
image_data = await image_file.read()
# 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:
reply = await chatbot.ask(
prompt=user_message,
conversation_style=ConversationStyle.balanced,
simplify_response=True,
)
if image_file:
# Download the image from Discord
image_data = await image_file.read()
# 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
text = f"{reply['text']}"
text = re.sub(r"\[\^(\d+)\^\]", lambda match: "", text)

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

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

@ -1,4 +1,4 @@
discord.py==2.3.2
python-dotenv==0.21.1
PyYAML==6.0
EdgeGPT==0.13.2
python-dotenv==1.0.0
PyYAML==6.0.1
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 discord
from discord.ext import commands
import interpreter
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")
bot_id = os.getenv("BOT_ID")
bot_token = os.getenv("DISCORD_TOKEN")
interpreter.api_key = os.getenv("OPENAI_API_KEY")
# interpreter.api_base = os.getenv("API_BASE")
# interpreter.auto_run = True
def split_text(text, chunk_size=1500):
#########################################################################
return [text[i : i + chunk_size] for i in range(0, len(text), chunk_size)]
# discord initial
intents = discord.Intents.all()
intents.message_content = True
client = commands.Bot(command_prefix="$", intents=intents)
message_chunks = []
send_image = False
model = whisper.load_model("base")
def transcribe(audio):
# load audio and pad/trim it to fit 30 seconds
audio = whisper.load_audio(audio)
audio = whisper.pad_or_trim(audio)
# make log-Mel spectrogram and move to the same device as the model
mel = whisper.log_mel_spectrogram(audio).to(model.device)
# detect the spoken language
_, probs = model.detect_language(mel)
# decode the audio
options = whisper.DecodingOptions()
result = whisper.decode(model, mel, options)
return result.text
@client.event
async def on_message(message):
await client.process_commands(message)
bot_mention = f"<@{bot_id}>"
# if ("<@1158923910855798804>" in message.content) or (message.author == client.user or message.content[0] == '$'):
# return
response = []
for chunk in interpreter.chat(message.content, display=False, stream=False):
# await message.channel.send(chunk)
if "message" in chunk:
response.append(chunk["message"])
last_response = response[-1]
max_message_length = 2000 # Discord's max message length is 2000 characters
# Splitting the message into chunks of 2000 characters
response_chunks = [
last_response[i : i + max_message_length]
for i in range(0, len(last_response), max_message_length)
]
# Sending each chunk as a separate message
for chunk in response_chunks:
await message.channel.send(chunk)
@client.command()
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)
# Initialize the EdgeGPTModel
model = BingChat()
response = model("Generate")
logging.basicConfig(level=logging.INFO)
accumulated_story = ""
latest_caption = ""
standard_suffix = ""
storyboard = []
caption = "Create comic about opensourcerer a robot wizard"
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()

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