File size: 3,412 Bytes
3009683
 
 
48b241a
3009683
 
48b241a
 
 
 
 
 
 
 
 
3009683
 
48b241a
3009683
48b241a
3009683
 
 
 
48b241a
 
3009683
 
48b241a
 
 
3009683
 
 
 
48b241a
 
 
 
 
 
 
 
 
3009683
 
48b241a
 
3009683
 
 
 
 
48b241a
 
3009683
48b241a
 
 
3009683
 
48b241a
3009683
48b241a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3009683
 
 
 
 
 
48b241a
3009683
 
 
 
48b241a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from argparse import ArgumentParser
import time
from pathlib import Path


def add_message(history, mic, text):
    if not mic and not text:
        return history, "Input is empty"
    if mic and Path(mic).exists():
        history.append({"role": "user", "content": {"path": mic}})
    if text:
        history.append({"role": "user", "content": text})
    print(f"{history=}")
    return history, None


def reset_state():
    """Reset the chat history."""
    return []


def regenerate(task_history):
    """Regenerate the last bot response."""
    while task_history and task_history[-1]["role"] == "assistant":
        print(f"discard {task_history[-1]}")
        task_history.pop()
    if task_history:
        print(f"{task_history=}")
        return predict(task_history)


def predict(chatbot):
    """Generate a response from the model."""
    if len(chatbot) > 0:
        for item in reversed(chatbot):
            if item["role"] != "user":
                break
            if isinstance(item["content"], dict):
                chatbot.append({"role": "assistant", "content": item["content"]})
            elif isinstance(item["content"], tuple):
                chatbot.append({"role": "assistant", "content": {"path":item["content"][0]}})
            else:
                chatbot.append({"role": "assistant", "content": f"echo {item['content']}"})
    else:
        response = "**That's cool!**"
        chatbot.append({"role": "assistant", "content": response})
    return chatbot


def _launch_demo(args):
    with gr.Blocks() as demo:
        gr.Markdown("""<center><font size=8>ChatBot Dummy</center>""")
        chatbot = gr.Chatbot(
            elem_id="chatbot", bubble_full_width=False, type="messages"
        )
        # task_history = gr.State([])
        mic = gr.Audio(type="filepath")
        text = gr.Textbox(placeholder="Enter message ...")

        with gr.Row():
            clean_btn = gr.Button("🧹 Clean History (清除历史)")
            regen_btn = gr.Button("🤔️ Regenerate (重试)")
            submit_btn = gr.Button("🚀 Submit")

        def on_submit(chatbot, mic, text):
            history, error = add_message(chatbot, mic, text)
            if error:
                gr.Warning(error)  # 显示警告消息
                return history, None, None
            else:
                return predict(history), None, None

        submit_btn.click(
            fn=on_submit,
            inputs=[chatbot, mic, text],
            outputs=[chatbot, mic, text],
        )
        clean_btn.click(reset_state, outputs=[chatbot], show_progress=True)
        regen_btn.click(regenerate, [chatbot], [chatbot], show_progress=True)

    demo.queue().launch(
        share=False,
        inbrowser=args.inbrowser,
        server_port=args.server_port,
        server_name=args.server_name,
        max_threads=4,
    )


if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument(
        "--inbrowser",
        action="store_true",
        default=False,
        help="Automatically launch the interface in a new tab on the default browser.",
    )
    parser.add_argument(
        "--server-port", type=int, default=7860, help="Demo server port."
    )
    parser.add_argument(
        "--server-name", type=str, default="0.0.0.0", help="Demo server name."
    )

    args = parser.parse_args()

    _launch_demo(args)