Spaces:
Paused
Paused
import gradio as gr | |
from datetime import datetime | |
import random | |
# Shared state to store messages | |
messages = [] | |
# Generate a random color for each user | |
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): | |
global messages | |
# Generate a unique user ID (in a real app, this would be managed by authentication) | |
user_id = f"User_{len(user_colors) + 1}" | |
# 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"<span style='color: {user_color};'>{user_id}</span>: {message}<br><small>{timestamp}</small>"]) | |
# Return the updated chat history | |
return "", messages | |
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 | |
# Create the Gradio interface | |
with gr.Blocks(css="#chatbot {height: 400px; overflow-y: auto;}") as demo: | |
chatbot = gr.Chatbot(elem_id="chatbot") | |
msg = gr.Textbox(label="Type your message here") | |
clear = gr.Button("Clear") | |
msg.submit(chat, [msg, chatbot], [msg, chatbot]) | |
clear.click(lambda: [], outputs=[chatbot]) | |
# Add an update function that runs every second | |
demo.load(get_updates, inputs=chatbot, outputs=chatbot, every=1) | |
# Launch the app | |
if __name__ == "__main__": | |
demo.launch() |