zyliu commited on
Commit
af98bc5
1 Parent(s): 9f9fa2d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -725
app.py CHANGED
@@ -1,727 +1,29 @@
1
- import copy
2
- import logging
3
  import os
4
- import os.path as osp
5
- from functools import partial
6
- from pydoc import locate
7
- import shutil
8
- import json
9
- from traceback import print_exc
10
- import uuid
11
- from pathlib import Path
12
- from collections import OrderedDict
13
- import numpy as np
14
- from PIL import Image
15
-
16
- import whisper
17
- import fire
18
- import gradio as gr
19
- import gradio.themes.base as ThemeBase
20
- from gradio.themes.utils import colors, sizes
21
- from gradio.components.image_editor import Brush
22
- import sys
23
-
24
- sys.path.append(os.getcwd())
25
-
26
- from cllm.agents.builtin import plans
27
- from cllm.services.general.api import remote_logging
28
- from cllm.agents import container, FILE_EXT
29
- from cllm.utils import get_real_path, plain2md, md2plain
30
- import openai
31
-
32
- openai.api_base = os.environ.get("OPENAI_API_BASE", None)
33
- openai.api_key = os.environ.get("OPENAI_API_KEY", None)
34
-
35
-
36
- logging.basicConfig(
37
- filename="cllm.log",
38
- level=logging.INFO,
39
- format="%(asctime)s %(levelname)-8s %(message)s",
40
- )
41
-
42
- logger = logging.getLogger(__name__)
43
-
44
- RESOURCE_ROOT = os.environ.get("CLIENT_ROOT", "./client_resources")
45
-
46
-
47
- def is_image(file_path):
48
- ext = FILE_EXT["image"]
49
- _, extension = os.path.splitext(file_path)
50
- return extension[1:] in ext
51
-
52
-
53
- def is_video(file_path):
54
- ext = FILE_EXT["video"]
55
- _, extension = os.path.splitext(file_path)
56
- return extension[1:] in ext
57
-
58
-
59
- def is_audio(file_path):
60
- ext = FILE_EXT["audio"]
61
- _, extension = os.path.splitext(file_path)
62
- return extension[1:] in ext
63
-
64
-
65
- def get_file_type(file_path):
66
- if is_image(file_path):
67
- if "mask" in file_path:
68
- return "mask"
69
- return "image"
70
- elif is_video(file_path):
71
- return "video"
72
- elif is_audio(file_path):
73
- return "audio"
74
- raise ValueError("Invalid file type")
75
-
76
-
77
- def convert_dict_to_frame(data):
78
- import pandas
79
-
80
- outputs = []
81
- for k, v in data.items():
82
- output = {"Resource": k}
83
- if not isinstance(v, str):
84
- output["Type"] = str(v.__class__)
85
- else:
86
- output["Type"] = v
87
- outputs.append(output)
88
- if len(outputs) == 0:
89
- return None
90
- return pandas.DataFrame(outputs)
91
-
92
-
93
- class Seafoam(ThemeBase.Base):
94
- def __init__(
95
- self,
96
- *,
97
- primary_hue=colors.emerald,
98
- secondary_hue=colors.blue,
99
- neutral_hue=colors.gray,
100
- spacing_size=sizes.spacing_md,
101
- radius_size=sizes.radius_md,
102
- text_size=sizes.text_sm,
103
- ):
104
- super().__init__(
105
- primary_hue=primary_hue,
106
- secondary_hue=secondary_hue,
107
- neutral_hue=neutral_hue,
108
- spacing_size=spacing_size,
109
- radius_size=radius_size,
110
- text_size=text_size,
111
- )
112
- super().set(
113
- body_background_fill_dark="#111111",
114
- button_primary_background_fill="*primary_300",
115
- button_primary_background_fill_hover="*primary_200",
116
- button_primary_text_color="black",
117
- button_secondary_background_fill="*secondary_300",
118
- button_secondary_background_fill_hover="*secondary_200",
119
- border_color_primary="#0BB9BF",
120
- slider_color="*secondary_300",
121
- slider_color_dark="*secondary_600",
122
- block_title_text_weight="600",
123
- block_border_width="3px",
124
- block_shadow="*shadow_drop_lg",
125
- button_shadow="*shadow_drop_lg",
126
- button_large_padding="10px",
127
- )
128
-
129
-
130
- class InteractionLoop:
131
- def __init__(
132
- self,
133
- controller="cllm.agents.code.Controller",
134
- ):
135
- self.stream = True
136
- Controller = locate(controller)
137
- self.controller = Controller(stream=self.stream, interpretor_kwargs=dict())
138
- self.whisper = whisper.load_model("base")
139
-
140
- def _gen_new_name(self, r_type, ext="png"):
141
- this_new_uuid = str(uuid.uuid4())[:6]
142
- new_file_name = f"{this_new_uuid}_{r_type}.{ext}"
143
- return new_file_name
144
-
145
- def init_state(self):
146
- user_state = OrderedDict()
147
- user_state["resources"] = OrderedDict()
148
- user_state["history_msgs"] = []
149
- resources = OrderedDict()
150
- for item in sorted(os.listdir("./assets/resources")):
151
- if item.startswith("."):
152
- continue
153
- shutil.copy(
154
- osp.join("./assets/resources", item),
155
- osp.join(RESOURCE_ROOT, item),
156
- )
157
- resources[item] = get_file_type(item)
158
- # return user_state, user_state["resources"]
159
- return user_state, resources
160
-
161
- def add_file(self, user_state, history, file):
162
- if user_state.get("resources", None) is None:
163
- user_state["resources"] = OrderedDict()
164
-
165
- if file is None:
166
- return user_state, None, history, None
167
- # filename = os.path.basename(file.name)
168
- file = Path(file)
169
- ext = file.suffix[1:]
170
- if ext in FILE_EXT["image"]:
171
- ext = "png"
172
- r_type = get_file_type(file.name)
173
- new_filename = self._gen_new_name(r_type, ext)
174
- saved_path = get_real_path(new_filename)
175
- if ext in FILE_EXT["image"]:
176
- Image.open(file).convert("RGB").save(saved_path, "png")
177
- user_state["input_image"] = new_filename
178
- else:
179
- shutil.copy(file, saved_path)
180
- logger.info(f"add file: {saved_path}")
181
- user_state["resources"][new_filename] = r_type
182
- for key, val in user_state["resources"].items():
183
- if key == "prompt_points":
184
- user_state["resources"].pop(key)
185
- break
186
- history, _ = self.add_text(history, (saved_path,), role="human", append=False)
187
- history, _ = self.add_text(
188
- history, f"Recieved file {new_filename}", role="assistant", append=False
189
- )
190
- memory = convert_dict_to_frame(user_state["resources"])
191
- image_name = None
192
- if Path(saved_path).suffix[1:] in FILE_EXT["image"]:
193
- image_name = saved_path
194
- return user_state, image_name, history, memory
195
-
196
- def add_msg(self, history, text, audio, role="assistant", append=False):
197
- if text is not None and text.strip() != "":
198
- return self.add_text(history, text, role=role, append=append)
199
- elif audio is not None:
200
- return self.add_audio(history, audio, role=role, append=append)
201
- return history, ""
202
-
203
- def add_sketch(self, user_state, history, sketch):
204
- if user_state.get("resources", None) is None:
205
- user_state["resources"] = OrderedDict()
206
-
207
- if sketch is None or "layers" not in sketch:
208
- return user_state, None, history, None
209
-
210
- mask = None
211
- for layer in sketch["layers"]:
212
- alpha = layer[:, :, 3:] // 255
213
- if mask is None:
214
- mask = np.ones_like(layer[:, :, :3]) * 255
215
- mask = mask * (1 - alpha) + layer[:, :, :3] * alpha
216
-
217
- ext = "png"
218
- r_type = "scribble"
219
- new_filename = self._gen_new_name(r_type, ext)
220
- saved_path = get_real_path(new_filename)
221
- if ext in FILE_EXT["image"]:
222
- Image.fromarray(mask).save(saved_path, "png")
223
- user_state["sketch_image"] = new_filename
224
-
225
- logger.info(f"add file: {saved_path}")
226
- user_state["resources"][new_filename] = r_type
227
- history, _ = self.add_text(history, (saved_path,), role="human", append=False)
228
- history, _ = self.add_text(
229
- history, f"Recieved file {new_filename}", role="assistant", append=False
230
- )
231
- memory = convert_dict_to_frame(user_state["resources"])
232
-
233
- return user_state, history, memory
234
-
235
- def add_text(self, history, text, role="assistant", append=False):
236
- if history is None:
237
- history = []
238
- # return history, ""
239
- assert role in ["human", "assistant"]
240
- idx = 0
241
- if len(history) == 0 or role == "human":
242
- history.append([None, None])
243
- if role == "assistant":
244
- idx = 1
245
- if not append and history[-1][1] is not None:
246
- history.append([None, None])
247
-
248
- if append:
249
- history[-1][idx] = (
250
- text if history[-1][idx] is None else history[-1][idx] + text
251
- )
252
- else:
253
- history[-1][idx] = text
254
- if isinstance(text, str):
255
- logger.info(f"add text: {md2plain(text)}")
256
-
257
- return history, ""
258
-
259
- def add_audio(self, history, audio, role="assistant", append=False):
260
- assert role in ["human", "assistant"]
261
- result = self.whisper.transcribe(audio)
262
- text = result["text"]
263
- logger.info(f"add audio: {text}")
264
- return self.add_text(history, text, role=role, append=append)
265
-
266
- def plan(self, user_state, input_image, history, history_plan):
267
- logger.info(f"Task plan...")
268
- if user_state.get("resources", None) is None:
269
- user_state["resources"] = OrderedDict()
270
-
271
- request = history[-1][0]
272
- user_state["request"] = request
273
- if isinstance(request, str) and request.startswith("$"):
274
- solution = f'show$("{request[1:]}")'
275
- else:
276
- solution = self.controller.plan(request, state=user_state)
277
- print(f"request: {request}")
278
- if solution == self.controller.SHORTCUT:
279
- # md_text = "**Using builtin shortcut solution.**"
280
- history, _ = self.add_text(
281
- history, solution, role="assistant", append=False
282
- )
283
- user_state["solution"] = solution
284
- user_state["history_msgs"] = history
285
- yield user_state, input_image, history, [solution]
286
- elif isinstance(solution, str) and solution.startswith("show$"):
287
- user_state["solution"] = solution
288
- yield user_state, input_image, history, solution
289
- else:
290
- output_text = (
291
- "The whole process will take some time, please be patient.<br><br>"
292
- )
293
- history, _ = self.add_text(
294
- history, output_text, role="assistant", append=True
295
- )
296
- yield user_state, input_image, history, history_plan
297
- task_decomposition = next(solution)
298
- if task_decomposition in [None, [], ""]:
299
- output = "Error: unrecognized resource(s) in task decomposition."
300
- task_decomposition = "[]"
301
- else:
302
- output = task_decomposition
303
-
304
- output = f"**Task Decomposition:**\n{output}"
305
- output = plain2md(output)
306
- history, _ = self.add_text(history, output, role="assistant", append=True)
307
- user_state["task_decomposition"] = json.loads(task_decomposition)
308
- yield user_state, input_image, history, history_plan
309
-
310
- history, _ = self.add_text(
311
- history,
312
- plain2md("\n\n**Thoughs-on-Graph:**\n"),
313
- role="assistant",
314
- append=True,
315
- )
316
- yield user_state, input_image, history, history_plan
317
- solution_str = next(solution)
318
- logger.info(f"Thoughs-on-Graph: \n{solution_str}")
319
- if solution_str in [None, [], ""]:
320
- output = "Empty solution possibly due to some internal errors."
321
- solution_str = "[]"
322
- else:
323
- output = solution_str
324
-
325
- output_md = plain2md(output)
326
- history, _ = self.add_text(
327
- history, output_md, role="assistant", append=True
328
- )
329
- solution = json.loads(solution_str)
330
- user_state["solution"] = solution
331
- user_state["history_msgs"] = history
332
- yield user_state, input_image, history, solution
333
-
334
- def execute(self, user_state, input_image, history, history_plan):
335
- resources_state = user_state.get("resources", OrderedDict())
336
- solution = user_state.get("solution", None)
337
- if not solution:
338
- yield user_state, input_image, history, history_plan
339
- return
340
- logger.info(f"Tool execution...")
341
- if isinstance(solution, str) and solution.startswith("show$"):
342
- key = solution[7:-2]
343
- r_type = resources_state.get(key)
344
- if r_type is None:
345
- resource = f"{key} not found"
346
- resource = container.auto_type("None", r_type, key)
347
- history, _ = self.add_text(
348
- history, (resource.to_chatbot(),), role="assistant"
349
- )
350
- user_state["history_msgs"] = history
351
- yield user_state, input_image, history, history_plan
352
- return
353
- elif solution:
354
- results = self.controller.execute(solution, state=user_state)
355
- if not results:
356
- yield user_state, input_image, history, history_plan
357
- return
358
-
359
- user_state["outputs"] = []
360
- for result_per_step, executed_solutions, wrapped_outputs in results:
361
- tool_name = json.dumps(result_per_step[0], ensure_ascii=False)
362
- args = json.dumps(result_per_step[1], ensure_ascii=False)
363
- ret = json.dumps(result_per_step[2], ensure_ascii=False)
364
- history, _ = self.add_text(
365
- history,
366
- f"Call **{tool_name}:**<br>&nbsp;&nbsp;&nbsp;&nbsp;**Args**: {plain2md(args)}<br>&nbsp;&nbsp;&nbsp;&nbsp;**Ret**: {plain2md(ret)}",
367
- role="assistant",
368
- )
369
- user_state["history_msgs"] = history
370
- user_state["executed_solutions"] = executed_solutions
371
- yield user_state, input_image, history, history_plan
372
- for _, output in enumerate(wrapped_outputs):
373
- if output is None or output.value is None:
374
- continue
375
- if isinstance(output, container.File):
376
- history, _ = self.add_text(
377
- history,
378
- f"Here is {output.filename}:",
379
- role="assistant",
380
- )
381
- history, _ = self.add_text(
382
- history, (output.to_chatbot(),), role="assistant"
383
- )
384
- user_state["outputs"].extend(wrapped_outputs)
385
- user_state["history_msgs"] = history
386
- yield user_state, input_image, history, history_plan
387
-
388
- else:
389
- yield user_state, input_image, history, history_plan
390
-
391
- def reply(self, user_state, history):
392
- logger.info(f"Make response...")
393
- executed_solution = user_state.get("executed_solutions", None)
394
- resources_state = user_state.get("resources", OrderedDict())
395
- solution = user_state.get("solution", None)
396
- memory = convert_dict_to_frame(resources_state)
397
- if isinstance(solution, str) and solution.startswith("show$"):
398
- return user_state, history, memory
399
-
400
- outputs = user_state.get("outputs", None)
401
- response, user_state = self.controller.reply(
402
- executed_solution, outputs, user_state
403
- )
404
- # prompt_mask_out = None
405
- for i, output in enumerate(response):
406
- if isinstance(output, container.File):
407
- history, _ = self.add_text(history, f"Here is [{output.filename}]: ")
408
- history, _ = self.add_text(history, (output.to_chatbot(),))
409
- elif i == 0:
410
- history, _ = self.add_text(history, output.to_chatbot())
411
-
412
- user_state["history_msgs"] = history
413
- return user_state, history, memory
414
-
415
- def vote(self, user_state, history, data: gr.LikeData):
416
- data_value = data.value
417
- if isinstance(data_value, dict):
418
- data_value = json.dumps(data_value)
419
-
420
- if data.liked:
421
- print("You upvoted this response: ", data_value)
422
- logger.info("You upvoted this response: " + data_value)
423
- else:
424
- print("You downvoted this response: ", data_value)
425
- logger.info("You downvoted this response: " + data_value)
426
-
427
- remote_logging(
428
- user_state.get("history_msgs", []),
429
- user_state.get("task_decomposition", ""),
430
- user_state.get("solution", []),
431
- data_value,
432
- data.liked,
433
- )
434
-
435
- msg = f"Thanks for your feedback! You feedback will contribute a lot to improving our ControlLLM."
436
- history, _ = self.add_text(history, msg)
437
- user_state["history_msgs"] = history
438
- return user_state, history
439
-
440
- def save_point(self, user_state, history, data: gr.SelectData):
441
- if isinstance(data, gr.LikeData):
442
- return self.vote(user_state, history, data)
443
-
444
- if not isinstance(data, gr.SelectData):
445
- return user_state, history
446
-
447
- resource_state = user_state.get("resources")
448
- input_image = user_state.get("input_image", None)
449
- if input_image is None:
450
- history, _ = self.add_text(history, "Please upload an image at first.")
451
- history, _ = self.add_text(history, plans.BUILTIN_SEG_BY_POINTS, "human")
452
- user_state["history_msg"] = history
453
- return user_state, history
454
-
455
- resource_state.pop(input_image, None)
456
- resource_state[input_image] = "image"
457
-
458
- history = history + [[plans.BUILTIN_SEG_BY_POINTS, None]]
459
- points = []
460
- if isinstance(points, str):
461
- points = json.loads(points)
462
-
463
- points.append(data.index)
464
- resource_state[json.dumps(points)] = "prompt_points"
465
- user_state["resources"] = resource_state
466
- return user_state, history
467
-
468
-
469
- def on_switch_input(state_input, text, audio, disable=False):
470
- if state_input == "audio" or disable:
471
- return "text", gr.update(visible=True), gr.update(visible=False)
472
- return "audio", gr.update(visible=False), gr.update(visible=True)
473
-
474
-
475
- def on_mask_submit(history):
476
- history = history + [(plans.BUILTIN_SEG_BY_MASK, None)]
477
- return history
478
-
479
-
480
- def app(controller="cllm.agents.tog.Controller", https=False, **kwargs):
481
- loop = InteractionLoop(controller=controller)
482
- init_state, builtin_resources = loop.init_state()
483
- css = """
484
- code {
485
- font-size: var(--text-sm);
486
- white-space: pre-wrap; /* Since CSS 2.1 */
487
- white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
488
- white-space: -pre-wrap; /* Opera 4-6 */
489
- white-space: -o-pre-wrap; /* Opera 7 */
490
- word-wrap: break-word; /* Internet Explorer 5.5+ */
491
  }
492
- """
493
- with gr.Blocks(theme=Seafoam(), css=css) as demo:
494
- gr.HTML(
495
- """
496
- <div align='center'> <h1>ControlLLM </h1> </div>
497
- <p align="center"> A framework for multi-modal interaction which is able to control LLMs over invoking tools more accurately. </p>
498
- <p align="center"><a href="https://github.com/OpenGVLab/ControlLLM"><b>GitHub</b></a>
499
- &nbsp;&nbsp;&nbsp; <a href="https://arxiv.org/abs/2311.11797"><b>ArXiv</b></a></p>
500
- """,
501
- )
502
-
503
- state_input = gr.State("text")
504
- user_state = gr.State(copy.deepcopy(init_state))
505
- with gr.Row():
506
- with gr.Column(scale=6):
507
- with gr.Tabs():
508
- with gr.Tab("Chat"):
509
- chatbot = gr.Chatbot(
510
- [],
511
- elem_id="chatbot",
512
- avatar_images=[
513
- "assets/human.png",
514
- "assets/assistant.png",
515
- ],
516
- show_copy_button=True,
517
- height=550,
518
- )
519
-
520
- with gr.Row():
521
- with gr.Column(scale=12):
522
- text = gr.Textbox(
523
- show_label=False,
524
- placeholder="Enter text and press enter, or upload an image.",
525
- container=False,
526
- )
527
- audio = gr.Audio(
528
- sources="microphone", type="filepath", visible=False
529
- )
530
- with gr.Column(scale=2, min_width=80):
531
- submit = gr.Button("Submit", variant="primary")
532
- with gr.Column(scale=1, min_width=40):
533
- record = gr.Button("🎙️")
534
- with gr.Column(scale=1, min_width=40):
535
- upload_btn = gr.UploadButton(
536
- "📁",
537
- file_types=[
538
- "image",
539
- "video",
540
- "audio",
541
- ".pdf",
542
- ],
543
- )
544
-
545
- gr.Examples(
546
- [
547
- "Who are you?",
548
- "How is about weather in Beijing",
549
- "Describe the given image.",
550
- "find the woman wearing the red skirt in the image",
551
- "Generate a video that shows Pikachu surfing in waves.",
552
- "How many horses are there in the image?",
553
- "Can you erase the dog in the given image?",
554
- "Remove the object based on the given mask.",
555
- "Can you make a video of a serene lake with vibrant green grass and trees all around? And then create a webpage using HTML to showcase this video?",
556
- "Generate an image that shows a beautiful landscape with a calm lake reflecting the blue sky and white clouds. Then generate a video to introduce this image.",
557
- "replace the masked object with a cute yellow dog",
558
- "replace the sheep with a cute dog in the image",
559
- "Recognize the action in the video",
560
- "Generate an image where a astronaut is riding a horse",
561
- "Please generate a piece of music from the given image",
562
- "Please give me an image that shows an astronaut riding a horse on mars.",
563
- "What’s the weather situation in Berlin? Can you generate a new image that represents the weather in there?",
564
- "Can you recognize the text from the image and tell me how much is Eggs Florentine?",
565
- "Generate a piece of music for this video and dub this video with generated music",
566
- "Generate a new image based on depth map from input image",
567
- "Remove the cats from the image_1.png, image_2.png, image_3.png",
568
- "I need the banana removed from the c4c40e_image.png, 9e867c_image.png, 9e13sc_image.png",
569
- "I would be so happy if you could create a new image using the scribble from input image. The new image should be a tropical island with a dog. Write a detailed description of the given image. and highlight the dog in image",
570
- "Please generate a piece of music and a new video from the input image",
571
- "generate a new image conditioned on the segmentation from input image and the new image shows that a gorgeous lady is dancing",
572
- "generate a new image with a different background but maintaining the same composition as input image",
573
- "Generate a new image that shows an insect robot preparing a delicious meal. Then give me a video based on new image. Finally, dub the video with suitable background music.",
574
- "Translate the text into speech: I have a dream that one day this nation will rise up and live out the true meaning of its creed: We hold these truths to be self-evident that all men are created equal.I have a dream that one day on the red hills of Georgia the sons of former slaves and the sons of former slave owners will be able to sit down together at the table of brotherhood. I have a dream that one day even the state of Mississippi, a state sweltering with the heat of injustice, sweltering with the heat of oppression, will be transformed into an oasis of freedom and justice.",
575
- ],
576
- inputs=[text],
577
- )
578
- gr.Examples(
579
- list(plans.BUILTIN_PLANS.keys()),
580
- inputs=[text],
581
- label="Builtin Examples",
582
- )
583
-
584
- with gr.Column(scale=5):
585
- with gr.Tabs():
586
- with gr.Tab("Click"):
587
- click_image = gr.Image(
588
- sources=["upload", "clipboard"],
589
- interactive=True,
590
- type="filepath",
591
- )
592
- with gr.Row():
593
- click_image_submit_btn = gr.Button(
594
- "Upload", variant="primary"
595
- )
596
- gr.Examples(
597
- [
598
- osp.join("./assets/resources", item)
599
- for item in builtin_resources.keys()
600
- if item.endswith(".png")
601
- ],
602
- inputs=[click_image],
603
- label="File Examples",
604
- )
605
-
606
- with gr.Tab("Draw"):
607
- sketch = gr.Sketchpad(
608
- sources=(), brush=Brush(colors=["#000000"])
609
- )
610
- with gr.Row():
611
- sketch_submit_btn = gr.Button("Upload", variant="primary")
612
-
613
- with gr.Tab("Plan"):
614
- planbot = gr.JSON(elem_classes="json")
615
-
616
- with gr.Tab("Memory"):
617
- memory_table = gr.DataFrame(
618
- label="Memory",
619
- headers=["Resource", "Type"],
620
- row_count=5,
621
- wrap=True,
622
- )
623
-
624
- chatbot.like(
625
- loop.vote,
626
- [
627
- user_state,
628
- chatbot,
629
- ],
630
- [
631
- user_state,
632
- chatbot,
633
- ],
634
- )
635
- reply_inputs = [user_state, click_image, chatbot, planbot]
636
- reply_outputs = [user_state, chatbot, memory_table]
637
-
638
- add_text = [
639
- partial(loop.add_text, role="human"),
640
- [chatbot, text],
641
- [chatbot, text],
642
- ]
643
-
644
- text.submit(*add_text).then(loop.plan, reply_inputs, reply_inputs).then(
645
- loop.execute, reply_inputs, reply_inputs
646
- ).then(loop.reply, [user_state, chatbot], reply_outputs)
647
-
648
- add_msg = [
649
- partial(loop.add_msg, role="human"),
650
- [chatbot, text, audio],
651
- [chatbot, text],
652
- ]
653
-
654
- submit.click(*add_msg).then(
655
- partial(on_switch_input, disable=True),
656
- [state_input, text, audio],
657
- [state_input, text, audio],
658
- ).then(loop.plan, reply_inputs, reply_inputs).then(
659
- loop.execute, reply_inputs, reply_inputs
660
- ).then(
661
- loop.reply, [user_state, chatbot], reply_outputs
662
- )
663
-
664
- upload_btn.upload(
665
- loop.add_file,
666
- inputs=[user_state, chatbot, upload_btn],
667
- outputs=[user_state, click_image, chatbot, memory_table],
668
- )
669
- record.click(
670
- on_switch_input,
671
- [state_input, text, audio],
672
- [state_input, text, audio],
673
- )
674
-
675
- click_image.select(
676
- loop.save_point, [user_state, chatbot], [user_state, chatbot]
677
- ).then(loop.plan, reply_inputs, reply_inputs).then(
678
- loop.execute, reply_inputs, reply_inputs
679
- ).then(
680
- loop.reply, [user_state, chatbot], reply_outputs
681
- )
682
-
683
- click_image.upload(
684
- loop.add_file,
685
- inputs=[user_state, chatbot, click_image],
686
- outputs=[user_state, click_image, chatbot, memory_table],
687
- )
688
- click_image_submit_btn.click(
689
- loop.add_file,
690
- inputs=[user_state, chatbot, click_image],
691
- outputs=[user_state, click_image, chatbot, memory_table],
692
- )
693
-
694
- sketch_submit_btn.click(
695
- loop.add_sketch,
696
- inputs=[user_state, chatbot, sketch],
697
- outputs=[user_state, chatbot, memory_table],
698
- )
699
-
700
- if https:
701
- demo.queue().launch(
702
- server_name="0.0.0.0",
703
- ssl_certfile="./certificate/cert.pem",
704
- ssl_keyfile="./certificate/key.pem",
705
- ssl_verify=False,
706
- show_api=False,
707
- allowed_paths=[
708
- "assets/human.png",
709
- "assets/assistant.png",
710
- ],
711
- **kwargs,
712
- )
713
- else:
714
- demo.queue().launch(
715
- server_name="0.0.0.0",
716
- show_api=False,
717
- allowed_paths=[
718
- "assets/human.png",
719
- "assets/assistant.png",
720
- ],
721
- **kwargs,
722
- )
723
-
724
-
725
- if __name__ == "__main__":
726
- os.makedirs(RESOURCE_ROOT, exist_ok=True)
727
- app(controller="cllm.agents.tog.Controller")
 
 
 
1
  import os
2
+ import streamlit as st
3
+ import streamlit.components.v1 as components
4
+
5
+ st.set_page_config(layout="wide")
6
+
7
+ iframe_html = """
8
+ <!DOCTYPE html>
9
+ <html>
10
+ <head>
11
+ <title>ControlLLM</title>
12
+ <style>
13
+ iframe {
14
+ position: absolute;
15
+ top: 0;
16
+ left: 0;
17
+ width: 100%;
18
+ height: 100%;
19
+ border: none;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  }
21
+ </style>
22
+ </head>
23
+ <body>
24
+ <div style="text-align:center"> <h1><strong><font style=color:rgba(2200,10,10,1)>This space is currently under maintenance due to network issues 😊😊</font></strong></h1></div>
25
+ <div style="text-align:center"><h2>We warmly welcome you to visit our <a href="https://github.com/OpenGVLab/ControlLLM" target="_blank">GitHub</a> if you’re interested 🎉🎉</br></h2></div>
26
+ </body>
27
+ </html>
28
+ """
29
+ components.html(iframe_html, height=1200)