Spaces:
Running
Running
File size: 25,003 Bytes
1d266a5 6ba08e7 1d266a5 9eaee4d 1d266a5 9eaee4d 1d266a5 9eaee4d 1d266a5 9eaee4d 1d266a5 6ba08e7 1d266a5 6ba08e7 1d266a5 6ba08e7 1d266a5 6ba08e7 1d266a5 6ba08e7 1d266a5 9eaee4d 1d266a5 9eaee4d 1d266a5 df98a45 |
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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 |
import base64
import openai
import itertools
import json
from typing import Dict, List, Tuple
import cv2
import gradio as gr
from agentverse import TaskSolving
from agentverse.simulation import Simulation
from agentverse.message import Message
def cover_img(background, img, place: Tuple[int, int]):
"""
Overlays the specified image to the specified position of the background image.
:param background: background image
:param img: the specified image
:param place: the top-left coordinate of the target location
"""
back_h, back_w, _ = background.shape
height, width, _ = img.shape
for i, j in itertools.product(range(height), range(width)):
if img[i, j, 3]:
background[place[0] + i, place[1] + j] = img[i, j, :3]
class GUI:
"""
the UI of frontend
"""
def __init__(
self,
task: str = "simulation/nlp_classroom_9players",
tasks_dir: str = "agentverse/tasks",
):
"""
init a UI.
default number of students is 0
"""
self.messages = []
self.task = task
self.tasks_dir = tasks_dir
if task == "pipeline_brainstorming":
self.backend = TaskSolving.from_task(task, tasks_dir)
else:
self.backend = Simulation.from_task(task, tasks_dir)
self.turns_remain = 0
self.agent_id = {
self.backend.agents[idx].name: idx
for idx in range(len(self.backend.agents))
}
self.stu_num = len(self.agent_id) - 1
self.autoplay = False
self.image_now = None
self.text_now = None
self.tot_solutions = 5
self.solution_status = [False] * self.tot_solutions
def get_avatar(self, idx):
if idx == -1:
img = cv2.imread("./imgs/db_diag/-1.png")
elif self.task == "simulation/prisoner_dilemma":
img = cv2.imread(f"./imgs/prison/{idx}.png")
else:
img = cv2.imread(f"./imgs/{idx}.png")
base64_str = cv2.imencode(".png", img)[1].tostring()
return "data:image/png;base64," + base64.b64encode(base64_str).decode("utf-8")
def stop_autoplay(self):
self.autoplay = False
return (
gr.Button.update(interactive=False),
gr.Button.update(interactive=False),
gr.Button.update(interactive=False),
)
def start_autoplay(self):
self.autoplay = True
yield (
self.image_now,
self.text_now,
gr.Button.update(interactive=False),
gr.Button.update(interactive=True),
gr.Button.update(interactive=False),
*[gr.Button.update(visible=statu) for statu in self.solution_status],
gr.Box.update(visible=any(self.solution_status)),
)
while self.autoplay and self.turns_remain > 0:
outputs = self.gen_output()
self.image_now, self.text_now = outputs
yield (
*outputs,
gr.Button.update(
interactive=not self.autoplay and self.turns_remain > 0
),
gr.Button.update(interactive=self.autoplay and self.turns_remain > 0),
gr.Button.update(
interactive=not self.autoplay and self.turns_remain > 0
),
*[gr.Button.update(visible=statu) for statu in self.solution_status],
gr.Box.update(visible=any(self.solution_status)),
)
def delay_gen_output(
self,
):
yield (
self.image_now,
self.text_now,
gr.Button.update(interactive=False),
gr.Button.update(interactive=False),
*[gr.Button.update(visible=statu) for statu in self.solution_status],
gr.Box.update(visible=any(self.solution_status)),
)
outputs = self.gen_output()
self.image_now, self.text_now = outputs
yield (
self.image_now,
self.text_now,
gr.Button.update(interactive=self.turns_remain > 0),
gr.Button.update(interactive=self.turns_remain > 0),
*[gr.Button.update(visible=statu) for statu in self.solution_status],
gr.Box.update(visible=any(self.solution_status)),
)
def delay_reset(self, task_dropdown, api_key_text, organization_text, api_base_text):
self.autoplay = False
self.image_now, self.text_now = self.reset(
task_dropdown, api_key_text, organization_text, api_base_text
)
return (
self.image_now,
self.text_now,
gr.Button.update(interactive=True),
gr.Button.update(interactive=False),
gr.Button.update(interactive=True),
*[gr.Button.update(visible=statu) for statu in self.solution_status],
gr.Box.update(visible=any(self.solution_status)),
)
def reset(
self,
task_dropdown="simulation/nlp_classroom_9players",
api_key_text="",
organization_text="",
api_base_text=""
):
openai.api_key = api_key_text
openai.organization = organization_text
openai.api_base = api_base_text if api_base_text else None
"""
tell backend the new number of students and generate new empty image
:param stu_num:
:return: [empty image, empty message]
"""
# if not 0 <= stu_num <= 30:
# raise gr.Error("the number of students must be between 0 and 30.")
"""
# [To-Do] Need to add a function to assign agent numbers into the backend.
"""
# self.backend.reset(stu_num)
# self.stu_num = stu_num
"""
# [To-Do] Pass the parameters to reset
"""
if task_dropdown == "pipeline_brainstorming":
self.backend = TaskSolving.from_task(task_dropdown, self.tasks_dir)
else:
self.backend = Simulation.from_task(task_dropdown, self.tasks_dir)
self.agent_id = {
self.backend.agents[idx].name: idx
for idx in range(len(self.backend.agents))
}
self.task = task_dropdown
self.stu_num = len(self.agent_id) - 1
self.backend.reset()
self.turns_remain = self.backend.environment.max_turns
if task_dropdown == "simulation/prisoner_dilemma":
background = cv2.imread("./imgs/prison/case_1.png")
elif task_dropdown == "simulation/db_diag":
background = cv2.imread("./imgs/db_diag/background.png")
elif "sde" in task_dropdown:
background = cv2.imread("./imgs/sde/background.png")
else:
background = cv2.imread("./imgs/background.png")
back_h, back_w, _ = background.shape
stu_cnt = 0
for h_begin, w_begin in itertools.product(
range(800, back_h, 300), range(135, back_w - 200, 200)
):
stu_cnt += 1
img = cv2.imread(
f"./imgs/{(stu_cnt - 1) % 11 + 1 if stu_cnt <= self.stu_num else 'empty'}.png",
cv2.IMREAD_UNCHANGED,
)
cover_img(
background,
img,
(h_begin - 30 if img.shape[0] > 190 else h_begin, w_begin),
)
self.messages = []
self.solution_status = [False] * self.tot_solutions
return [cv2.cvtColor(background, cv2.COLOR_BGR2RGB), ""]
def gen_img(self, data: List[Dict]):
"""
generate new image with sender rank
:param data:
:return: the new image
"""
# The following code need to be more general. This one is too task-specific.
# if len(data) != self.stu_num:
if len(data) != self.stu_num + 1:
raise gr.Error("data length is not equal to the total number of students.")
if self.task == "simulation/prisoner_dilemma":
img = cv2.imread("./imgs/speaking.png", cv2.IMREAD_UNCHANGED)
if (
len(self.messages) < 2
or self.messages[-1][0] == 1
or self.messages[-2][0] == 2
):
background = cv2.imread("./imgs/prison/case_1.png")
if data[0]["message"] != "":
cover_img(background, img, (400, 480))
else:
background = cv2.imread("./imgs/prison/case_2.png")
if data[0]["message"] != "":
cover_img(background, img, (400, 880))
if data[1]["message"] != "":
cover_img(background, img, (550, 480))
if data[2]["message"] != "":
cover_img(background, img, (550, 880))
elif self.task == "db_diag":
background = cv2.imread("./imgs/db_diag/background.png")
img = cv2.imread("./imgs/db_diag/speaking.png", cv2.IMREAD_UNCHANGED)
if data[0]["message"] != "":
cover_img(background, img, (750, 80))
if data[1]["message"] != "":
cover_img(background, img, (310, 220))
if data[2]["message"] != "":
cover_img(background, img, (522, 11))
elif "sde" in self.task:
background = cv2.imread("./imgs/sde/background.png")
img = cv2.imread("./imgs/sde/speaking.png", cv2.IMREAD_UNCHANGED)
if data[0]["message"] != "":
cover_img(background, img, (692, 330))
if data[1]["message"] != "":
cover_img(background, img, (692, 660))
if data[2]["message"] != "":
cover_img(background, img, (692, 990))
else:
background = cv2.imread("./imgs/background.png")
back_h, back_w, _ = background.shape
stu_cnt = 0
if data[stu_cnt]["message"] not in ["", "[RaiseHand]"]:
img = cv2.imread("./imgs/speaking.png", cv2.IMREAD_UNCHANGED)
cover_img(background, img, (370, 1250))
for h_begin, w_begin in itertools.product(
range(800, back_h, 300), range(135, back_w - 200, 200)
):
stu_cnt += 1
if stu_cnt <= self.stu_num:
img = cv2.imread(
f"./imgs/{(stu_cnt - 1) % 11 + 1}.png", cv2.IMREAD_UNCHANGED
)
cover_img(
background,
img,
(h_begin - 30 if img.shape[0] > 190 else h_begin, w_begin),
)
if "[RaiseHand]" in data[stu_cnt]["message"]:
# elif data[stu_cnt]["message"] == "[RaiseHand]":
img = cv2.imread("./imgs/hand.png", cv2.IMREAD_UNCHANGED)
cover_img(background, img, (h_begin - 90, w_begin + 10))
elif data[stu_cnt]["message"] not in ["", "[RaiseHand]"]:
img = cv2.imread("./imgs/speaking.png", cv2.IMREAD_UNCHANGED)
cover_img(background, img, (h_begin - 90, w_begin + 10))
else:
img = cv2.imread("./imgs/empty.png", cv2.IMREAD_UNCHANGED)
cover_img(background, img, (h_begin, w_begin))
return cv2.cvtColor(background, cv2.COLOR_BGR2RGB)
def return_format(self, messages: List[Message]):
_format = [{"message": "", "sender": idx} for idx in range(len(self.agent_id))]
for message in messages:
if self.task == "db_diag":
content_json: dict = message.content
content_json[
"diagnose"
] = f"[{message.sender}]: {content_json['diagnose']}"
_format[self.agent_id[message.sender]]["message"] = json.dumps(
content_json
)
elif "sde" in self.task:
if message.sender == "code_tester":
pre_message, message_ = message.content.split("\n")
message_ = "{}\n{}".format(
pre_message, json.loads(message_)["feedback"]
)
_format[self.agent_id[message.sender]][
"message"
] = "[{}]: {}".format(message.sender, message_)
else:
_format[self.agent_id[message.sender]][
"message"
] = "[{}]: {}".format(message.sender, message.content)
else:
_format[self.agent_id[message.sender]]["message"] = "[{}]: {}".format(
message.sender, message.content
)
return _format
def gen_output(self):
"""
generate new image and message of next step
:return: [new image, new message]
"""
# data = self.backend.next_data()
return_message = self.backend.next()
data = self.return_format(return_message)
# data.sort(key=lambda item: item["sender"])
"""
# [To-Do]; Check the message from the backend: only 1 person can speak
"""
for item in data:
if item["message"] not in ["", "[RaiseHand]"]:
self.messages.append((item["sender"], item["message"]))
message = self.gen_message()
self.turns_remain -= 1
return [self.gen_img(data), message]
def gen_message(self):
# If the backend cannot handle this error, use the following code.
message = ""
"""
for item in data:
if item["message"] not in ["", "[RaiseHand]"]:
message = item["message"]
break
"""
for sender, msg in self.messages:
if sender == 0:
avatar = self.get_avatar(0)
elif sender == -1:
avatar = self.get_avatar(-1)
else:
avatar = self.get_avatar((sender - 1) % 11 + 1)
if self.task == "db_diag":
msg_json = json.loads(msg)
self.solution_status = [False] * self.tot_solutions
msg = msg_json["diagnose"]
if msg_json["solution"] != "":
solution: List[str] = msg_json["solution"]
for solu in solution:
if "query" in solu or "queries" in solu:
self.solution_status[0] = True
solu = solu.replace(
"query", '<span style="color:yellow;">query</span>'
)
solu = solu.replace(
"queries", '<span style="color:yellow;">queries</span>'
)
if "join" in solu:
self.solution_status[1] = True
solu = solu.replace(
"join", '<span style="color:yellow;">join</span>'
)
if "index" in solu:
self.solution_status[2] = True
solu = solu.replace(
"index", '<span style="color:yellow;">index</span>'
)
if "system configuration" in solu:
self.solution_status[3] = True
solu = solu.replace(
"system configuration",
'<span style="color:yellow;">system configuration</span>',
)
if (
"monitor" in solu
or "Monitor" in solu
or "Investigate" in solu
):
self.solution_status[4] = True
solu = solu.replace(
"monitor", '<span style="color:yellow;">monitor</span>'
)
solu = solu.replace(
"Monitor", '<span style="color:yellow;">Monitor</span>'
)
solu = solu.replace(
"Investigate",
'<span style="color:yellow;">Investigate</span>',
)
msg = f"{msg}<br>{solu}"
if msg_json["knowledge"] != "":
msg = f'{msg}<hr style="margin: 5px 0"><span style="font-style: italic">{msg_json["knowledge"]}<span>'
else:
msg = msg.replace("<", "<")
msg = msg.replace(">", ">")
message = (
f'<div style="display: flex; align-items: center; margin-bottom: 10px;overflow:auto;">'
f'<img src="{avatar}" style="width: 5%; height: 5%; border-radius: 25px; margin-right: 10px;">'
f'<div style="background-color: gray; color: white; padding: 10px; border-radius: 10px;'
f'max-width: 70%; white-space: pre-wrap">'
f"{msg}"
f"</div></div>" + message
)
message = (
'<div id="divDetail" style="height:600px;overflow:auto;">'
+ message
+ "</div>"
)
return message
def submit(self, message: str):
"""
submit message to backend
:param message: message
:return: [new image, new message]
"""
self.backend.submit(message)
self.messages.append((-1, f"[User]: {message}"))
return self.gen_img([{"message": ""}] * len(self.agent_id)), self.gen_message()
def launch(self, single_agent=False, discussion_mode=False):
if self.task == "pipeline_brainstorming":
with gr.Blocks() as demo:
chatbot = gr.Chatbot(height=800, show_label=False)
msg = gr.Textbox(label="Input")
def respond(message, chat_history):
chat_history.append((message, None))
yield "", chat_history
for response in self.backend.iter_run(
single_agent=single_agent, discussion_mode=discussion_mode
):
print(response)
chat_history.append((None, response))
yield "", chat_history
msg.submit(respond, [msg, chatbot], [msg, chatbot])
else:
with gr.Blocks() as demo:
with gr.Row():
task_dropdown = gr.Dropdown(
choices=[
"simulation/nlp_classroom_9players",
"simulation/prisoner_dilemma",
],
value="simulation/nlp_classroom_9players",
label="Task",
)
api_key_text = gr.Textbox(label="OPENAI API KEY")
organization_text = gr.Textbox(label="Organization")
api_base_text = gr.Textbox(label="OpenAI Base URL", default="", placeholder="if not set, will use openai's default url")
with gr.Row():
with gr.Column():
image_output = gr.Image()
with gr.Row():
reset_btn = gr.Button("Build/Reset")
# next_btn = gr.Button("Next", variant="primary")
next_btn = gr.Button("Next", interactive=False)
stop_autoplay_btn = gr.Button(
"Stop Autoplay", interactive=False
)
start_autoplay_btn = gr.Button(
"Start Autoplay", interactive=False
)
with gr.Box(visible=False) as solutions:
with gr.Column():
gr.HTML("Optimization Solutions:")
with gr.Row():
rewrite_slow_query_btn = gr.Button(
"Rewrite Slow Query", visible=False
)
add_query_hints_btn = gr.Button(
"Add Query Hints", visible=False
)
update_indexes_btn = gr.Button(
"Update Indexes", visible=False
)
tune_parameters_btn = gr.Button(
"Tune Parameters", visible=False
)
gather_more_info_btn = gr.Button(
"Gather More Info", visible=False
)
# text_output = gr.Textbox()
text_output = gr.HTML(self.reset()[1])
# Given a botton to provide student numbers and their inf.
# stu_num = gr.Number(label="Student Number", precision=0)
# stu_num = self.stu_num
if self.task == "db_diag":
user_msg = gr.Textbox()
submit_btn = gr.Button("Submit", variant="primary")
submit_btn.click(
fn=self.submit,
inputs=user_msg,
outputs=[image_output, text_output],
show_progress=False,
)
else:
pass
# next_btn.click(fn=self.gen_output, inputs=None, outputs=[image_output, text_output],
# show_progress=False)
next_btn.click(
fn=self.delay_gen_output,
inputs=None,
outputs=[
image_output,
text_output,
next_btn,
start_autoplay_btn,
rewrite_slow_query_btn,
add_query_hints_btn,
update_indexes_btn,
tune_parameters_btn,
gather_more_info_btn,
solutions,
],
show_progress=False,
)
# [To-Do] Add botton: re-start (load different people and env)
# reset_btn.click(fn=self.reset, inputs=stu_num, outputs=[image_output, text_output],
# show_progress=False)
# reset_btn.click(fn=self.reset, inputs=None, outputs=[image_output, text_output], show_progress=False)
reset_btn.click(
fn=self.delay_reset,
inputs=[task_dropdown, api_key_text, organization_text, api_base_text],
outputs=[
image_output,
text_output,
next_btn,
stop_autoplay_btn,
start_autoplay_btn,
rewrite_slow_query_btn,
add_query_hints_btn,
update_indexes_btn,
tune_parameters_btn,
gather_more_info_btn,
solutions,
],
show_progress=False,
)
stop_autoplay_btn.click(
fn=self.stop_autoplay,
inputs=None,
outputs=[next_btn, stop_autoplay_btn, start_autoplay_btn],
show_progress=False,
)
start_autoplay_btn.click(
fn=self.start_autoplay,
inputs=None,
outputs=[
image_output,
text_output,
next_btn,
stop_autoplay_btn,
start_autoplay_btn,
rewrite_slow_query_btn,
add_query_hints_btn,
update_indexes_btn,
tune_parameters_btn,
gather_more_info_btn,
solutions,
],
show_progress=False,
)
demo.queue(concurrency_count=5, max_size=20).launch()
# demo.launch()
GUI().launch()
|