CoolFace
Apppublic

Vrush1t/Level-2-FS-LLM-UI

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
streamlit_app.py355 linesDownload Raw Back to src
1import streamlit as st2import requests3from typing import List, Optional4from datetime import datetime5from enum import Enum6 7# API base URL8BASE_URL = "https://vrush1t-level-2-fs-llm-api.hf.space"9 10# Define enums to match main.py11class Status(str, Enum):12    QUALIFIED = "Qualified"13    NURTURE = "Nurture"14 15class BudgetType(str, Enum):16    SELF = "Self"17    COMPANY = "Company"18 19# Initialize session state for customers list20if 'customers' not in st.session_state:21    st.session_state.customers = []22 23def fetch_customers():24    """Fetch all customers from the API"""25    try:26        response = requests.get(f"{BASE_URL}/customers")27        if response.status_code == 200:28            st.session_state.customers = response.json()29    except requests.exceptions.RequestException as e:30        st.error(f"Error fetching customers: {str(e)}")31 32def create_customer(name: str, email: str, phone: Optional[str] = None, country: Optional[str] = None,33                   goal: Optional[str] = None, budget: Optional[str] = None,34                   webinar_join: Optional[datetime] = None, webinar_leave: Optional[datetime] = None,35                   asked_q: bool = False, referred: bool = False, past_touchpoints: int = 0):36    """Create a new customer"""37    try:38        # Find the next available ID39        next_id = max([c['id'] for c in st.session_state.customers], default=0) + 140        41        # If webinar_join is provided but not webinar_leave, set webinar_leave to 2 hours after join42        if webinar_join and not webinar_leave:43            webinar_leave = webinar_join + datetime.timedelta(hours=2)44        45        customer_data = {46            "id": next_id,47            "name": name,48            "email": email,49            "phone": phone,50            "country": country,51            "goal": goal,52            "budget": budget,53            "webinar_join": webinar_join.isoformat() if webinar_join else None,54            "webinar_leave": webinar_leave.isoformat() if webinar_leave else None,55            "asked_q": asked_q,56            "referred": referred,57            "past_touchpoints": past_touchpoints58        }59        60        response = requests.post(f"{BASE_URL}/customers", json=customer_data)61        if response.status_code == 200:62            st.success("Customer created successfully!")63            fetch_customers()64        else:65            st.error(f"Error creating customer: {response.text}")66    except requests.exceptions.RequestException as e:67        st.error(f"Error creating customer: {str(e)}")68 69def update_customer(customer_id: int, name: str, email: str, phone: Optional[str] = None, 70                   country: Optional[str] = None, goal: Optional[str] = None, 71                   budget: Optional[str] = None, webinar_join: Optional[datetime] = None, 72                   webinar_leave: Optional[datetime] = None, asked_q: bool = False, 73                   referred: bool = False, past_touchpoints: int = 0):74    """Update an existing customer"""75    try:76        # If webinar_join is provided but not webinar_leave, set webinar_leave to 2 hours after join77        if webinar_join and not webinar_leave:78            webinar_leave = webinar_join + datetime.timedelta(hours=2)79            80        customer_data = {81            "id": customer_id,82            "name": name,83            "email": email,84            "phone": phone,85            "country": country,86            "goal": goal,87            "budget": budget,88            "webinar_join": webinar_join.isoformat() if webinar_join else None,89            "webinar_leave": webinar_leave.isoformat() if webinar_leave else None,90            "asked_q": asked_q,91            "referred": referred,92            "past_touchpoints": past_touchpoints93        }94        95        response = requests.put(f"{BASE_URL}/customers/{customer_id}", json=customer_data)96        if response.status_code == 200:97            st.success("Customer updated successfully!")98            fetch_customers()99        else:100            st.error(f"Error updating customer: {response.text}")101    except requests.exceptions.RequestException as e:102        st.error(f"Error updating customer: {str(e)}")103 104def delete_customer(customer_id: int):105    """Delete a customer"""106    try:107        response = requests.delete(f"{BASE_URL}/customers/{customer_id}")108        if response.status_code == 200:109            st.success("Customer deleted successfully!")110            fetch_customers()111        else:112            st.error(f"Error deleting customer: {response.text}")113    except requests.exceptions.RequestException as e:114        st.error(f"Error deleting customer: {str(e)}")115 116def qualify_customer(customer_id: int):117    """Qualify a customer"""118    try:119        response = requests.post(f"{BASE_URL}/customers/{customer_id}/qualify")120        if response.status_code == 200:121            st.success("Customer qualification successful!")122            fetch_customers()123        else:124            st.error(f"Error qualifying customer: {response.text}")125    except requests.exceptions.RequestException as e:126        st.error(f"Error qualifying customer: {str(e)}")127 128# Streamlit UI129st.title("100xEngineers CRM")130 131# Sidebar for navigation132page = st.sidebar.selectbox("Choose an operation", 133                          ["View Customers", "Add Customer", "Update Customer", "Delete Customer", "Qualify Customer"])134 135# Fetch customers on initial load136fetch_customers()137 138if page == "View Customers":139    st.header("All Customers")140    141    # Add filtering options142    filter_status = st.selectbox("Filter by Status", ["All", "Qualified", "Nurture"])143    144    filtered_customers = st.session_state.customers145    if filter_status != "All":146        filtered_customers = [c for c in st.session_state.customers if c.get('status') == filter_status]147    148    if filtered_customers:149        for customer in filtered_customers:150            # Create columns for better layout151            col1, col2 = st.columns(2)152            153            with col1:154                st.write(f"**ID:** {customer['id']}")155                st.write(f"**Name:** {customer['name']}")156                st.write(f"**Email:** {customer['email']}")157                if customer.get('phone'):158                    st.write(f"**Phone:** {customer['phone']}")159                if customer.get('country'):160                    st.write(f"**Country:** {customer['country']}")161                if customer.get('goal'):162                    st.write(f"**Goal:** {customer['goal']}")163                164            with col2:165                if customer.get('budget'):166                    st.write(f"**Budget:** {customer['budget']}")167                if customer.get('webinar_join'):168                    st.write(f"**Webinar Join:** {customer['webinar_join']}")169                if customer.get('webinar_leave'):170                    st.write(f"**Webinar Leave:** {customer['webinar_leave']}")171                st.write(f"**Asked Questions:** {'Yes' if customer.get('asked_q') else 'No'}")172                st.write(f"**Referred:** {'Yes' if customer.get('referred') else 'No'}")173                st.write(f"**Past Touchpoints:** {customer.get('past_touchpoints', 0)}")174            175            # Qualification info in a separate section with highlight176            if customer.get('status'):177                status_color = "green" if customer.get('status') == "Qualified" else "orange"178                st.markdown(f"**Status:** <span style='color:{status_color}'>{customer.get('status')}</span>", unsafe_allow_html=True)179                if customer.get('score'):180                    st.write(f"**Score:** {customer.get('score')}")181                if customer.get('reasoning'):182                    with st.expander("Qualification Reasoning"):183                        st.write(customer.get('reasoning'))184            185            st.write("---")186    else:187        st.info("No customers found.")188 189elif page == "Add Customer":190    st.header("Add New Customer")191    with st.form("add_customer_form"):192        col1, col2 = st.columns(2)193        194        with col1:195            name = st.text_input("Name")196            email = st.text_input("Email")197            phone = st.text_input("Phone (optional)")198            country = st.text_input("Country (optional)")199            goal = st.text_input("Goal (optional)")200        201        with col2:202            budget = st.selectbox("Budget (optional)", ["", "Self", "Company"])203            webinar_date = st.date_input("Webinar Date (optional)", value=None)204            join_time = st.time_input("Webinar Join Time (optional)", value=None)205            leave_time = st.time_input("Webinar Leave Time (optional)", value=None)206        207        col3, col4 = st.columns(2)208        with col3:209            asked_q = st.checkbox("Asked Questions During Webinar")210            referred = st.checkbox("Customer Was Referred")211        212        with col4:213            past_touchpoints = st.number_input("Past Touchpoints", min_value=0, value=0)214        215        submitted = st.form_submit_button("Add Customer")216        if submitted:217            if name and email:218                # Convert date and time inputs to datetime objects219                webinar_join_dt = None220                webinar_leave_dt = None221                222                if webinar_date and join_time:223                    webinar_join_dt = datetime.combine(webinar_date, join_time)224                    225                    if leave_time:226                        webinar_leave_dt = datetime.combine(webinar_date, leave_time)227                        # If leave time is earlier than join time, assume it's the next day228                        if webinar_leave_dt < webinar_join_dt:229                            webinar_leave_dt = datetime.combine(webinar_date + datetime.timedelta(days=1), leave_time)230                231                create_customer(232                    name, email, phone, country, goal, budget,233                    webinar_join_dt, webinar_leave_dt, asked_q, referred, past_touchpoints234                )235            else:236                st.warning("Please fill in the required fields (Name and Email)")237 238elif page == "Update Customer":239    st.header("Update Customer")240    if st.session_state.customers:241        customer_id = st.selectbox(242            "Select Customer to Update",243            options=[c['id'] for c in st.session_state.customers]244        )245        246        # Get the selected customer's data247        selected_customer = next((c for c in st.session_state.customers if c['id'] == customer_id), None)248        249        if selected_customer:250            with st.form("update_customer_form"):251                col1, col2 = st.columns(2)252                253                with col1:254                    name = st.text_input("Name", value=selected_customer['name'])255                    email = st.text_input("Email", value=selected_customer['email'])256                    phone = st.text_input("Phone", value=selected_customer.get('phone', ''))257                    country = st.text_input("Country", value=selected_customer.get('country', ''))258                    goal = st.text_input("Goal", value=selected_customer.get('goal', ''))259                260                with col2:261                    budget = st.selectbox("Budget", 262                                        ["", "Self", "Company"], 263                                        index=["", "Self", "Company"].index(selected_customer.get('budget', '')) if selected_customer.get('budget') in ["Self", "Company"] else 0)264                    265                    # Handle webinar date and time fields266                    webinar_date = None267                    join_time = None268                    leave_time = None269                    270                    if selected_customer.get('webinar_join'):271                        try:272                            webinar_join_dt = datetime.fromisoformat(selected_customer.get('webinar_join'))273                            webinar_date = webinar_join_dt.date()274                            join_time = webinar_join_dt.time()275                        except (ValueError, TypeError):276                            pass277                            278                    if selected_customer.get('webinar_leave'):279                        try:280                            webinar_leave_dt = datetime.fromisoformat(selected_customer.get('webinar_leave'))281                            leave_time = webinar_leave_dt.time()282                        except (ValueError, TypeError):283                            pass284                    285                    webinar_date = st.date_input("Webinar Date", value=webinar_date)286                    join_time = st.time_input("Webinar Join Time", value=join_time)287                    leave_time = st.time_input("Webinar Leave Time", value=leave_time)288                289                col3, col4 = st.columns(2)290                with col3:291                    asked_q = st.checkbox("Asked Questions During Webinar", value=selected_customer.get('asked_q', False))292                    referred = st.checkbox("Customer Was Referred", value=selected_customer.get('referred', False))293                294                with col4:295                    past_touchpoints = st.number_input("Past Touchpoints", 296                                                    min_value=0, 297                                                    value=selected_customer.get('past_touchpoints', 0))298                299                submitted = st.form_submit_button("Update Customer")300                if submitted:301                    if name and email:302                        # Convert date and time inputs to datetime objects303                        webinar_join_dt = None304                        webinar_leave_dt = None305                        306                        if webinar_date and join_time:307                            webinar_join_dt = datetime.combine(webinar_date, join_time)308                            309                            if leave_time:310                                webinar_leave_dt = datetime.combine(webinar_date, leave_time)311                                # If leave time is earlier than join time, assume it's the next day312                                if webinar_leave_dt < webinar_join_dt:313                                    webinar_leave_dt = datetime.combine(webinar_date + datetime.timedelta(days=1), leave_time)314                        315                        update_customer(316                            customer_id, name, email, phone, country, goal, budget,317                            webinar_join_dt, webinar_leave_dt, asked_q, referred, past_touchpoints318                        )319                    else:320                        st.warning("Please fill in the required fields (Name and Email)")321    else:322        st.info("No customers available to update.")323 324elif page == "Delete Customer":325    st.header("Delete Customer")326    if st.session_state.customers:327        customer_id = st.selectbox(328            "Select Customer to Delete",329            options=[c['id'] for c in st.session_state.customers]330        )331        332        if st.button("Delete Customer"):333            delete_customer(customer_id)334    else:335        st.info("No customers available to delete.")336 337elif page == "Qualify Customer":338    st.header("Qualify Customer")339    if st.session_state.customers:340        # Filter out already qualified customers341        unqualified_customers = [c for c in st.session_state.customers if not c.get('status')]342        343        if unqualified_customers:344            customer_id = st.selectbox(345                "Select Customer to Qualify",346                options=[c['id'] for c in unqualified_customers],347                format_func=lambda id: next((f"{c['id']} - {c['name']}" for c in unqualified_customers if c['id'] == id), str(id))348            )349            350            if st.button("Qualify Customer"):351                qualify_customer(customer_id)352        else:353            st.info("All customers have already been qualified.")354    else:355        st.info("No customers available to qualify.")