import gradio as gr import datetime # This list will store all the chat messages. # In a real-world scenario, you might want to use a database for persistence. chat_history = [] def add_message(message, username="Anonymous"): """ Adds a new message to the chat history with a timestamp and username. """ timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") formatted_message = f"[{timestamp}] {username}: {message}" chat_history.append(formatted_message) # Return the entire chat history as a single string, joined by newlines return "\n".join(chat_history) # Define the Gradio interface with gr.Blocks(title="SmilyAI Community Chat") as demo: gr.Markdown( """ # Welcome to SmilyAI Community Chat! 👋 Chat with your fellow community members here. """ ) # Textbox to display the chat history # Set it to read-only as users will add messages via the input box chat_display = gr.Textbox( label="Chat History", lines=20, interactive=False, # Make it non-editable by the user autoscroll=True, # Automatically scroll to the bottom for new messages value="\n".join(chat_history) # Initialize with current history ) # Input for the user's name username_input = gr.Textbox( label="Your Name (Optional)", placeholder="Enter your name", value="Anonymous", # Default value interactive=True # Users can change their name ) # Input for the new message message_input = gr.Textbox( label="Your Message", placeholder="Type your message here...", lines=3 ) # Button to send the message send_button = gr.Button("Send Message") # When the send button is clicked, call the add_message function. # The outputs are updated in the chat_display textbox. # The message_input is cleared after sending. send_button.click( fn=add_message, inputs=[message_input, username_input], outputs=chat_display ).then( # Clear the message input after sending fn=lambda: "", inputs=[], outputs=message_input ) # Also allow sending messages by pressing Enter in the message_input message_input.submit( fn=add_message, inputs=[message_input, username_input], outputs=chat_display ).then( # Clear the message input after submitting fn=lambda: "", inputs=[], outputs=message_input ) # Launch the Gradio app # The share=True parameter creates a public shareable link (useful for Hugging Face Spaces) # The server_name and server_port might be necessary for some environments, # but Gradio usually handles this automatically on Hugging Face Spaces. if __name__ == "__main__": demo.launch(share=True)