File size: 2,123 Bytes
c4603f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from PIL import Image

import gradio as gr
import random
import time
import os
import requests


CHATMAGIC_AI = os.environ["CHATMAGIC_AI"]

markdown_text = """
![ChatMagic AI](https://i.ibb.co/3szrgL8/chatmagic-ai.png)
ChatMagic AI is available as an Android app for FREE. Download now to chat faster and better!
- Google Play Store URL: **[CLICK HERE](https://bit.ly/googleplaystore-chatmagicai)**
- Discord URL: **[CLICK HERE](https://bit.ly/discord-chatmagicai)**
"""

welcome_text = """
Hello! I'm ChatMagic AI. I'm here to assist you. I can do the following:
1. Answer questions and give explanations
2. Assist in writing a text based content
3. Follow simple instructions

However, I still have limitations. I may write incorrect information or produce harmful instructions. Please use me with caution.
""".strip()


empty_history = [[None, welcome_text]]


with gr.Blocks() as demo:
    gr.Markdown(markdown_text)
    
    chatbot = gr.Chatbot(empty_history, label="Chat with ChatMagic AI")
    msg = gr.Textbox(label="Enter your question here")
    
    with gr.Row() as row:
        btn_ask = gr.Button("Ask", variant="primary")
        btn_clear = gr.Button("Clear")
    
    def user(user_message: str, history: list) -> tuple[str, list]:
        return "", history + [[user_message, None]]

    def bot(history: list):
        bot_message = "An error has occured. Please try again."
        
        try:
            bot_message = requests.post(CHATMAGIC_AI, json={"question": history[-1][0]}).json()["answer"]
        except Exception as e:
            pass
        
        history[-1][1] = bot_message
        return history

    msg.submit(
        fn=user, inputs=[msg, chatbot], outputs=[msg, chatbot], queue=True).then(
        fn=bot, inputs=chatbot, outputs=chatbot
    )
   
    btn_ask.click(
        fn=user, inputs=[msg, chatbot], outputs=[msg, chatbot], queue=True).then(
        fn=bot, inputs=chatbot, outputs=chatbot
    )
    
    btn_clear.click(
        fn=lambda: empty_history, inputs=None, outputs=chatbot, queue=False)


demo.queue(concurrency_count=1)
demo.launch(server_name="0.0.0.0")