BuildPlay / home_view /ui_home.py
Kim Adams
adding handlers to openai responses
a2627f1
import gradio as gr
import pandas as pd
import openai
from home_view.app_theme import SoftBlue
from home_view import simple_chat
from utilities import constants
from sketch import sketch as sk
from slack_processing.slack_data_prep import FetchSlack, ProcessSlack, CreateEmbeddings
from create_games.create_games_slack import LoadThemes,GetPlayersAndIndex,CreateGameForGroup,GetPeopleByThemesDF
startDF=pd.DataFrame()
slackDF=pd.DataFrame()
embeddingsDF=pd.DataFrame()
playersDF=pd.DataFrame()
gamesDF=pd.DataFrame()
gameType=None
gameName=None
gameDescription=None
gameTips=None
gameRules=None
gameContext=None
playersValues=[]
selected= []
players=[]
initQuestion=None
def FetchData():
global gamesDF, startDF, slackDF, embeddingsDF, playersDF,playersValues
startDF=FetchSlack()
slackDF=ProcessSlack()
embeddingsDF=CreateEmbeddings()
gamesDF=gamesDF
playersDF=GetPeopleByThemesDF()
playersValues=[]
playersCB.choices = playersValues
return startDF, slackDF, embeddingsDF, playersDF, gamesDF
def Init():
global startDF, slackDF, embeddingsDF, gamesDF,playersDF, playersValues
startDF=FetchSlack()
slackDF=ProcessSlack()
embeddingsDF=CreateEmbeddings()
gamesDF=LoadThemes()
playersValues=GetPlayersAndIndex()
playersDF = GetPeopleByThemesDF()
playersCB.choices = playersValues
def SetSelected(playersCB):
global playersValues,selected,players
selected=[]
players=[]
for check in playersCB:
selected.append(check)
for player_name, player_id in playersValues:
if player_id == check:
if player_name not in players:
players.append(player_name)
print("player_name", player_name)
break
def CreateGame(gamePlay,chat_history,draw):
if gamePlay==constants.DRAW:
return PlayDrawGame()
else:
return PlayChatGame(chat_history)
def ClearVars():
global gameDescription, gameName, gameTips,initQuestion,gamesDF
gameDescription=None
gameName=None
gameTips=None
initQuestion=None
gamesDF=pd.DataFrame()
def GetDetails(game_ideas, type):
global gameDescription, gameName, gameTips,initQuestion, gamesDF,gameRules
game_ideas_dict = game_ideas.to_dict('records')
gamesDF=game_ideas
if 'Description' in game_ideas_dict[0]:
gameDescription=game_ideas_dict[0]['Description']
else:
gameDescription=constants.GAME_DESC_NOTFOUND
if 'Name' in game_ideas_dict[0]:
gameName=game_ideas_dict[0]['Name']
else:
gameName=constants.NAME_NOTFOUND
if 'Tips' in game_ideas_dict[0]:
if isinstance(game_ideas_dict[0]['Tips'], list):
gameTips = ', '.join(game_ideas_dict[0]['Tips'])
else:
gameTips = game_ideas_dict[0]['Tips']
else:
gameTips = constants.TIPS_NOTFOUND
if 'Rules' in game_ideas_dict[0]:
if isinstance(game_ideas_dict[0]['Rules'], list):
gameRules = ', '.join(game_ideas_dict[0]['Rules'])
else:
gameRules = game_ideas_dict[0]['Rules']
else:
gameRules = constants.RULES_NOTFOUND
if type==constants.CHAT:
initQuestion= "### "+game_ideas_dict[0]['InitialQuestion']
else:
initQuestion= game_ideas_dict[0]['InitialQuestion']
def PlayDrawGame():
global players,gamesDF, gameDescription, gameName, gameTips,initQuestion
game_ideas,common_topic = CreateGameForGroup(players, constants.DRAW)
playerNames = ', '.join(players)
ClearVars()
if game_ideas is not None and not game_ideas.empty:
GetDetails(game_ideas, constants.DRAW)
return gr.update(visible=True), gr.update(visible=True),gr.update(visible=True), gr.update(visible=False), ("## You'll be playing "+ gameName), gameDescription, gamesDF, gameRules, gameTips, None, gr.update(visible=False), initQuestion, ("### "+constants.TOPIC+": "+common_topic.title()), (constants.PLAYER_NAMES+": "+playerNames.title())
return gr.update(visible=False), gr.update(visible=False),gr.update(visible=False),gr.update(visible=False), constants.NO_GAME_TITLE, constants.NO_GAME, None, "", "",None,gr.update(visible=True), initQuestion, ("### "+constants.TOPIC+": No topic found."), (constants.PLAYER_NAMES+": No Players found.")
def PlayChatGame(chat_history):
global players, gamesDF, gameDescription, gameName, gameTips,initQuestion
gi,common_topic = CreateGameForGroup(players, constants.CHAT)
playerNames = ', '.join(players)
ClearVars()
if gi is not None and not gi.empty:
GetDetails(gi, constants.CHAT)
chat_history.append(("Let the game begin!",initQuestion))
return gr.update(visible=True), gr.update(visible=True),gr.update(visible=False), gr.update(visible=True), "## You'll be playing "+gameName, gameDescription, gamesDF, gameRules, gameTips,chat_history, gr.update(visible=False),"", ("### "+constants.TOPIC+": "+common_topic.title()), (constants.PLAYER_NAMES+": "+ playerNames.title())
return gr.update(visible=False), gr.update(visible=False),gr.update(visible=False),gr.update(visible=False), constants.NO_GAME_TITLE, constants.NO_GAME, None, "", "",chat_history,gr.update(visible=True),"", ("### "+constants.TOPIC+": No topic found."), (constants.PLAYER_NAMES+": No Players found.")
def Reset(msg, chatbot):
msg=None
chatbot=None
return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False),msg, chatbot
def Predict(sketch):
confidences = sk.Predict(sketch)
return confidences
def BuildContext():
global initQuestion, gameDescription, gameRules, gameTips, gameName, gameContext
gameContext = f"You are playing: {gameName if gameName else ''}" + \
(f". Desc: {gameDescription}" if gameDescription else '') + \
(f". Rules: {gameRules}" if gameRules else '') + \
(f". Gameplay Tips: {gameTips}" if gameTips else '') + \
(f". Initial Question: {initQuestion}" if initQuestion else '')
def Respond(message, chat_history):
global gameContext
BuildContext()
bot_message,df=simple_chat.ManageChatGame(message, gameContext)
chat_history.append((message, bot_message))
return "", chat_history
df1 =gr.Dataframe(type="pandas", value=startDF)
df2 =gr.Dataframe(type="pandas", value=slackDF)
df3 =gr.Dataframe(type="pandas", value=embeddingsDF)
df4 =gr.Dataframe(type="pandas", value=playersDF)
df5 =gr.Dataframe(type="pandas", value=gamesDF)
with gr.Blocks() as ui:
with gr.Column() as gameMaker:
with gr.Row():
with gr.Column():
html_styling = gr.HTML("""<div id='output_image' style='width: 180px;display:block; margin-left: auto; margin-right: auto;'>""")
result = gr.Image(value=constants.BUILDPLAY_LOGO, show_label=False, container=False, show_share_button=False, show_download_button=False, elem_id="output_image")
buildPlayLabel= gr.Markdown(constants.BUILDPLAY_LABEL, container=False)
with gr.Column():
directionsLabel= gr.Markdown(constants.DIRECTIONS_LABEL, container=False)
directions= gr.Markdown(constants.DIRECTIONS, container=False)
playersCB = gr.CheckboxGroup ([], label=constants.PLAYERS, info=constants.PLAYERS_INFO )
gamePlay=gr.Radio([constants.CHAT,constants.DRAW], label=constants.GAME_TYPE, value=constants.CHAT)
createBtn = gr.Button(value=constants.CREATE_GAME, variant="primary")
with gr.Column(visible=False) as pGame:
with gr.Row():
with gr.Column():
chatTitle= gr.Markdown ()
chatDesc= gr.Markdown ()
gameTopic=gr.Markdown()
players=gr.Markdown()
with gr.Column():
rules=gr.Markdown(constants.RULES_LABEL)
chatRules=gr.Markdown(constants.GAME_DESC)
tipTitle=gr.Markdown(constants.QUESTIONS_LABEL)
tips=gr.Markdown(constants.GAME_TIPS)
with gr.Row() as holder:
with gr.Column():
drawMD=gr.Markdown()
with gr.Column(visible=False) as drawGame:
with gr.Row():
sketch=gr.Image(image_mode="L", source="canvas", brush_radius=3, type="pil", shape=(120, 120),
invert_colors=True, interactive=True, label=constants.SKETCH,
show_label=True, show_download_button=False)
label=gr.Label(label=constants.GUESSES, show_label=True)
resetDrwBtn=gr.Button(value=constants.RESET)
with gr.Column(visible=False) as chatGame:
chatbot = gr.Chatbot(label=constants.CHAT_BOT, height=constants.CHAT_BOT_HEIGHT)
msg = gr.Textbox(label=constants.CHAT_BOT_INPUT)
with gr.Row():
resetBtn=gr.Button(value=constants.RESET)
clearBtn = gr.ClearButton([msg, chatbot])
submitBtn=gr.Button(value=constants.SUBMIT, variant="primary")
sketch.change(Predict, inputs=[sketch], outputs=[label])
playersCB.change(SetSelected, inputs=[playersCB], outputs=[])
createBtn.click(CreateGame, inputs=[gamePlay,chatbot,drawMD], outputs=[pGame, holder, drawGame, chatGame, chatTitle, chatDesc, df4, chatRules, tips, chatbot, gameMaker, drawMD, gameTopic, players])
msg.submit(Respond, [msg, chatbot], [msg, chatbot])
submitBtn.click(Respond, [msg, chatbot], [msg, chatbot])
resetBtn.click(Reset, [msg, chatbot], [pGame, holder,gameMaker,drawGame,chatGame, msg, chatbot])
resetDrwBtn.click(Reset, [msg, chatbot], [pGame, holder,gameMaker,drawGame,chatGame,msg, chatbot])
with gr.Blocks() as dfs:
fetchBtn=gr.Button(value=constants.FETCH_DATA, variant="primary")
gr.TabbedInterface([df1,df2,df3,df4,df5], (constants.UI1, constants.UI2, constants.UI3, constants.UI4, constants.UI5), theme=SoftBlue())
fetchBtn.click(FetchData, inputs=[], outputs=[df1,df2,df3,df4,df5])
combo=gr.TabbedInterface([ui,dfs], (constants.BUILDPLAY, constants.DATAFRAMES), theme=SoftBlue())
Init()