Spaces:
Running
Running
import gradio as gr | |
from datetime import datetime | |
import random | |
import uuid | |
from dataclasses import dataclass | |
# Shared state to store messages | |
messages = [] | |
# Dictionary to store user colors | |
user_colors = {} | |
class Data: | |
user_id: str | |
message: str | |
timestamp: str | |
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(input_text, history): | |
global messages | |
# Parse the input to get user_id and message | |
user_id, message = input_text.split("; ") | |
# 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(Data(user_id=user_id, message=message, timestamp=timestamp)) | |
# Update the chat history | |
history.append(f"User_{user_id[:4]}: {message} ({timestamp})") | |
return "", history | |
def get_updates(history): | |
global messages | |
# Check if there are new messages | |
if len(messages) > len(history): | |
return [f"User_{msg.user_id[:4]}: {msg.message} ({msg.timestamp})" for msg in messages] | |
# If no new messages, return the current history | |
return history | |
# Create the Gradio interface | |
with gr.Blocks() as demo: | |
chatbot = gr.Chatbot() | |
msg = gr.Textbox(label="Type your message here (format: 'id here; text here')") | |
clear = gr.Button("Clear") | |
msg.submit(chat, [msg, chatbot], [msg, chatbot]) | |
clear.click(lambda: [], outputs=[chatbot]) | |
# Add an update function that runs every 0.2 seconds | |
demo.load(get_updates, inputs=chatbot, outputs=chatbot, every=0.2) | |
# Launch the app | |
if __name__ == "__main__": | |
demo.launch() | |