Skip to content

Commit

Permalink
Merge pull request #25 from qbc2016/ms_us
Browse files Browse the repository at this point in the history
MS ui
  • Loading branch information
ZiTao-Li authored Jan 22, 2024
2 parents 74df05f + 602b449 commit 1e06add
Show file tree
Hide file tree
Showing 5 changed files with 290 additions and 228 deletions.
175 changes: 84 additions & 91 deletions examples/game/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
send_player_msg,
send_player_input,
get_chat_msg,
get_suggests,
ResetException,
)

Expand All @@ -36,25 +35,28 @@ def init_uid_list():
MAX_NUM_DISPLAY_MSG = 20

import base64


# 图片本地路径转换为 base64 格式
def covert_image_to_base64(image_path):
# 获得文件后缀名
ext = image_path.split('.')[-1]
if ext not in ['gif', 'jpeg', 'png']:
ext = 'jpeg'
ext = image_path.split(".")[-1]
if ext not in ["gif", "jpeg", "png"]:
ext = "jpeg"

with open(image_path, 'rb') as image_file:
with open(image_path, "rb") as image_file:
# Read the file
encoded_string = base64.b64encode(image_file.read())

# Convert bytes to string
base64_data = encoded_string.decode('utf-8')
base64_data = encoded_string.decode("utf-8")

# 生成base64编码的地址
base64_url = f'data:image/{ext};base64,{base64_data}'
# 生成base64编码的地址
base64_url = f"data:image/{ext};base64,{base64_data}"
return base64_url

def format_cover_html(config: dict, bot_avatar_path='assets/bg.png'):

def format_cover_html(config: dict, bot_avatar_path="assets/bg.png"):
image_src = covert_image_to_base64(bot_avatar_path)
return f"""
<div class="bot_cover">
Expand All @@ -66,6 +68,7 @@ def format_cover_html(config: dict, bot_avatar_path='assets/bg.png'):
</div>
"""


def export_chat_history(uid):
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
export_filename = f"chat_history_{timestamp}.txt"
Expand All @@ -91,6 +94,10 @@ def get_chat(uid) -> List[List]:
return glb_history_dict[uid][-MAX_NUM_DISPLAY_MSG:]


def fn_choice(data: gr.EventData, uid):
send_player_input(data._data["value"], uid=uid)


if __name__ == "__main__":

def init_game():
Expand All @@ -106,7 +113,6 @@ def init_game():
is_init = True

def check_for_new_session(uid):
# print(uid)
if uid not in glb_signed_user:
glb_signed_user.append(uid)
game_thread = threading.Thread(target=start_game, args=(uid,))
Expand All @@ -127,27 +133,32 @@ def start_game(uid):
except ResetException:
print("重置成功")

with gr.Blocks(css='assets/app.css') as demo:
with gr.Blocks(css="assets/app.css") as demo:
# Users can select the interested exp
uuid = gr.State(uuid.uuid4)

welcome = {
"name": "饮食男女",
"description": "这是一款模拟餐馆经营的文字冒险游戏, 快来开始吧😊"
"description": "这是一款模拟餐馆经营的文字冒险游戏, 快来开始吧😊",
}

user_chat_bot_cover = gr.HTML(format_cover_html(welcome))
chatbot = mgr.Chatbot(label="Dialog", show_label=False, height=600, visible=False)
chatbot = mgr.Chatbot(
label="Dialog",
show_label=False,
height=600,
visible=False,
)

with gr.Row():
with gr.Column():
new_button = gr.Button(
value="🚀新的探险",
)
new_button = gr.Button(
value="🚀新的探险",
)
with gr.Column():
resume_button = gr.Button(
value="🔥续写情缘",
)
resume_button = gr.Button(
value="🔥续写情缘",
)

with gr.Row():
with gr.Column():
Expand All @@ -159,30 +170,20 @@ def start_game(uid):
visible=False,
)

user_chat_bot_suggest = gr.Dataset(
label="选择一个",
components=[user_chat_input],
samples=[],
visible=False,
)

user_chat_bot_suggest.select(
lambda evt: evt[0],
inputs=[user_chat_bot_suggest],
outputs=[user_chat_input],
)

with gr.Column():
send_button = gr.Button(
value="📣发送",
visible=False
visible=False,
)

export = gr.Accordion("导出选项", open=False, visible=False)
with export:
with gr.Column():
export_button = gr.Button("导出完整游戏记录")
export_output = gr.File(label="下载完整游戏记录", visible=False)
export_output = gr.File(
label="下载完整游戏记录",
visible=False,
)

def send_message(msg, uid):
send_player_input(msg, uid=uid)
Expand All @@ -200,83 +201,75 @@ def send_reset_message(uid):
send_player_input("**Reset**", uid=uid)
return ""

def update_suggest(uid):
msg, samples = get_suggests(uid)
if msg is not None:
return gr.Dataset(
label=msg,
samples=samples,
visible=True,
components=[user_chat_input],
)
else:
return gr.Dataset(
label="选择一个",
components=[user_chat_input],
samples=[],
visible=True,
)

def game_ui():
visible = True
invisible = False
return {chatbot: mgr.Chatbot(visible=visible),
user_chat_input: gr.Text(visible=visible),
send_button: gr.Button(visible=visible),
new_button: gr.Button(visible=invisible),
resume_button: gr.Button(visible=invisible),
return_welcome_button: gr.Button(visible=visible),
user_chat_bot_suggest: gr.Dataset(
components=[user_chat_input],
visible=visible,
),
export: gr.Accordion(visible=visible),
user_chat_bot_cover:gr.HTML(visible=invisible)}
return {
chatbot: mgr.Chatbot(visible=visible),
user_chat_input: gr.Text(visible=visible),
send_button: gr.Button(visible=visible),
new_button: gr.Button(visible=invisible),
resume_button: gr.Button(visible=invisible),
return_welcome_button: gr.Button(visible=visible),
export: gr.Accordion(visible=visible),
user_chat_bot_cover: gr.HTML(visible=invisible),
}

def welcome_ui():
visible = True
invisible = False
return {chatbot: mgr.Chatbot(visible=invisible),
user_chat_input: gr.Text(visible=invisible),
send_button: gr.Button(visible=invisible),
new_button: gr.Button(visible=visible),
resume_button: gr.Button(visible=visible),
return_welcome_button: gr.Button(visible=invisible),
user_chat_bot_suggest: gr.Dataset(
components=[user_chat_input],
visible=invisible,
),
export: gr.Accordion(visible=invisible),
user_chat_bot_cover:gr.HTML(visible=visible)}

outputs = [chatbot, user_chat_input, send_button, new_button, resume_button,return_welcome_button, user_chat_bot_suggest, export, user_chat_bot_cover]

return {
chatbot: mgr.Chatbot(visible=invisible),
user_chat_input: gr.Text(visible=invisible),
send_button: gr.Button(visible=invisible),
new_button: gr.Button(visible=visible),
resume_button: gr.Button(visible=visible),
return_welcome_button: gr.Button(visible=invisible),
export: gr.Accordion(visible=invisible),
user_chat_bot_cover: gr.HTML(visible=visible),
}

outputs = [
chatbot,
user_chat_input,
send_button,
new_button,
resume_button,
return_welcome_button,
export,
user_chat_bot_cover,
]

# submit message
send_button.click(send_message, [user_chat_input, uuid], user_chat_input)
user_chat_input.submit(send_message, [user_chat_input, uuid], user_chat_input)
send_button.click(
send_message,
[user_chat_input, uuid],
user_chat_input,
)
user_chat_input.submit(
send_message,
[user_chat_input, uuid],
user_chat_input,
)

# change ui
chatbot.custom(fn=fn_choice, inputs=[uuid])

# change ui
new_button.click(game_ui, outputs=outputs)
resume_button.click(game_ui, outputs=outputs)
return_welcome_button.click(welcome_ui, outputs=outputs)

# start game
# start game
new_button.click(send_reset_message, inputs=[uuid])
resume_button.click(check_for_new_session, inputs=[uuid])
# export

# export
export_button.click(export_chat_history, [uuid], export_output)

# update chat history
demo.load(init_game)
demo.load(check_for_new_session, inputs=[uuid], every=0.1)
demo.load(get_chat, inputs=[uuid], outputs=chatbot, every=0.5)
demo.load(
update_suggest,
inputs=[uuid],
outputs=user_chat_bot_suggest,
every=0.5,
)

demo.queue()
demo.launch()
15 changes: 10 additions & 5 deletions examples/game/customer.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def __init__(self, game_config: dict, **kwargs: Any):
self.game_config = game_config
self.max_itr_preorder = 5
self.preorder_itr_count = 0
self.avatar = self.config.get('avatar', get_a_random_avatar())
self.avatar = self.config.get("avatar", get_a_random_avatar())
self.background = self.config["character_setting"]["background"]
self.friendship = int(self.config.get("friendship", 60))

Expand Down Expand Up @@ -61,13 +61,15 @@ def activate_plot(self, active_plots: list[int]) -> None:
# when the customer is the main role in a plot, it will be activated
self.plot_stage = CustomerPlot.ACTIVE
for p in active_plots:
if str(p) in self.config["character_setting"]["hidden_plot"] \
and len(self.active_plots) == 0:
if (
str(p) in self.config["character_setting"]["hidden_plot"]
and len(self.active_plots) == 0
):
self.active_plots = [str(p)]
elif str(p) in self.config["character_setting"]["hidden_plot"]:
raise ValueError(
"A customer can be in at most one plot in the current "
"version"
"version",
)

def deactivate_plot(self) -> None:
Expand All @@ -82,7 +84,10 @@ def reply(self, x: dict = None) -> Union[dict, tuple]:
# the first/last message must have role 'user'.
if x is not None:
x["role"] = "user"
logger.debug(f"{self.name} state: {self.cur_state} {self.plot_stage} {self.active_plots}")
logger.debug(
f"{self.name} state: {self.cur_state} {self.plot_stage}"
f" {self.active_plots}",
)
return StateAgent.reply(self, x=x)

def _recommendation_to_score(self, x: dict) -> dict:
Expand Down
Loading

0 comments on commit 1e06add

Please sign in to comment.