import gradio as gr
from datetime import datetime
import random
import uuid
# Shared state to store messages
messages = []
# Dictionary to store user colors
user_colors = {}
def get_user_color(user_id):
if user_id not in user_colors:
user_colors[user_id] = f"#{random.randint(0, 0xFFFFFF):06x}"
return user_colors[user_id]
def chat(message, history, user_id):
global messages
if not user_id:
# Generate a new user ID if one doesn't exist
user_id = str(uuid.uuid4())
# Add the new message to the shared state
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
user_color = get_user_color(user_id)
messages.append([None, f"User_{user_id[:4]}: {message}
{timestamp}"])
# Return the updated chat history and user_id
return "", messages, user_id
def get_updates(history):
global messages
# Check if there are new messages
if len(messages) > len(history):
return messages
# If no new messages, return the current history
return history
# Custom CSS to hide the loading animation
custom_css = """
#chatbot .loading {
display: none !important;
}
"""
# Create the Gradio interface
with gr.Blocks(css=custom_css) as demo:
chatbot = gr.Chatbot(elem_id="chatbot")
msg = gr.Textbox(label="Type your message here")
clear = gr.Button("Clear")
user_id = gr.State(value='') # Add a state component to store the user ID
msg.submit(chat, [msg, chatbot, user_id], [msg, chatbot, user_id])
clear.click(lambda: [], outputs=[chatbot])
# Add an update function that runs every 0.05 seconds
demo.load(get_updates, inputs=chatbot, outputs=chatbot, every=0.2)
# Launch the app
if __name__ == "__main__":
demo.launch()