import streamlit as st import json def load_contacts(): """Load contacts from a JSON file.""" try: with open("contacts.json", "r") as f: return json.load(f) except FileNotFoundError: return {} def save_contacts(contacts): """Save contacts to a JSON file.""" with open("contacts.json", "w") as f: json.dump(contacts, f) # Load existing contacts contacts = load_contacts() # Streamlit app configuration st.set_page_config(page_title="Chat App", layout="wide") st.title("Chat App") # Sidebar: Add Contact Section st.sidebar.header("Add a New Contact") with st.sidebar.form("add_contact_form"): contact_name = st.text_input("Contact Name") contact_number = st.text_input("Phone Number") submit_contact = st.form_submit_button("Add Contact") if submit_contact: if contact_name and contact_number: contacts[contact_name] = {"number": contact_number, "messages": []} save_contacts(contacts) st.sidebar.success(f"Contact '{contact_name}' added successfully!") else: st.sidebar.error("Please provide both name and number.") # Main Section: Chat Functionality st.header("Chat with Your Contacts") selected_contact = st.selectbox( "Select a contact to chat with", options=["Select"] + list(contacts.keys()) ) if selected_contact != "Select": contact_data = contacts[selected_contact] st.subheader(f"Chat with {selected_contact}") # Display chat history chat_history = st.empty() if contact_data["messages"]: chat_history.write("\n".join(contact_data["messages"])) # Input message section with st.form("send_message_form"): message = st.text_input("Type your message") send_message = st.form_submit_button("Send") if send_message: if message.strip(): contact_data["messages"].append(f"You: {message}") save_contacts(contacts) chat_history.write("\n".join(contact_data["messages"])) else: st.error("Message cannot be empty.") # Footer st.sidebar.markdown("---") st.sidebar.markdown("### Instructions") st.sidebar.markdown( "1. Use the sidebar to add new contacts.\n" "2. Select a contact from the dropdown to start chatting.\n" "3. Your chat history is saved locally." )