CoolFace
Apppublic

devronn/CustomerService

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py143 linesDownload Raw Back to root
1import streamlit as st2from transformers import pipeline3 4# Configure Streamlit page5st.set_page_config(6    page_title="Customer Service Ticket Analyzer",7    page_icon="🎫",8    layout="centered"9)10 11# Initialize pipelines12@st.cache_resource13def load_models():14    sentiment_analyzer = pipeline(15        "sentiment-analysis",16        model="distilbert/distilbert-base-uncased-finetuned-sst-2-english"17    )18    department_classifier = pipeline(19        "zero-shot-classification",20        model="devronn/Finetuned_bge"21    )22    return sentiment_analyzer, department_classifier23 24# Load models25try:26    sentiment_analyzer, department_classifier = load_models()27except Exception as e:28    st.error(f"Error loading models: {str(e)}")29    st.stop()30 31# Define departments and their descriptions32departments = {33    "Customer Support": "Handles customer inquiries and product issues.",34    "Technical Support": "Provides technical assistance and troubleshooting.",35    "Billing and Sales": "Handles payment inquiries, sales questions, and general inquiries.",36    "Product Feedback": "Collects feedback about products and services.",37    "Account Management": "Manages customer accounts and retention."38}39 40# Define potential responses based on keywords41response_templates = {42    "billing": "For billing inquiries, please check your account or contact our billing department directly.",43    "technical": "For technical support, please provide detailed information about the issue.",44    "product": "For product inquiries, please specify the product name and your question.",45    "general": "Thank you for your inquiry! We will get back to you shortly.",46    "order": "For order-related questions, please provide your order number.",47    "refund": "For refund inquiries, please allow us to assist you with the process.",48}49 50# Title and description51st.title("Customer Service Ticket Analyzer")52st.markdown("Analyze customer tickets for sentiment and department routing")53 54# Main input form55customer_name = st.text_input("Customer Name")56ticket_subject = st.text_input("Ticket Subject")57ticket_content = st.text_area("Ticket Content", height=150)58 59if st.button("Analyze Ticket") and ticket_content.strip():60    try:61        with st.spinner('Analyzing...'):62            # Limit input length for faster processing63            limited_content = ticket_content[:500]  # Limit to 500 characters64 65            # Sentiment Analysis66            sentiment = sentiment_analyzer(limited_content)[0]67 68            # Department Classification69            department_result = department_classifier(70                limited_content,71                candidate_labels=list(departments.keys()),72                multi_label=False73            )74 75            # Keyword Extraction76            keyword_matches = []77            for keyword in response_templates.keys():78                if keyword in limited_content.lower():79                    keyword_matches.append(response_templates[keyword])80 81            # Display results82            st.markdown("### Analysis Results")83 84            # Create three columns for results85            col1, col2, col3 = st.columns(3)86 87            with col1:88                st.markdown("#### Sentiment")89                sentiment_color = "green" if sentiment['label'] == "POSITIVE" else "red"90                st.markdown(91                    f"<p style='color: {sentiment_color};'>{sentiment['label']}</p>",92                    unsafe_allow_html=True93                )94                st.write(f"Confidence: {sentiment['score']:.2%}")95 96            with col2:97                st.markdown("#### Department")98                suggested_dept = department_result['labels'][0]99                st.write(f"**Suggested:** {suggested_dept}")100                st.write(f"Confidence: {department_result['scores'][0]:.2%}")101 102            with col3:103                st.markdown("#### Priority")104                priority = "HIGH" if sentiment['label'] == "NEGATIVE" and sentiment['score'] > 0.8 else "MEDIUM"105                priority_color = "red" if priority == "HIGH" else "orange"106                st.markdown(107                    f"<p style='color: {priority_color};'>{priority}</p>",108                    unsafe_allow_html=True109                )110 111            # Ticket Summary112            st.markdown("### Ticket Details")113            st.write(f"**Customer:** {customer_name}")114            st.write(f"**Subject:** {ticket_subject}")115            st.write(f"**Content:** {ticket_content}")116 117            # Recommended Responses118            st.markdown("### Recommended Responses")119            if keyword_matches:120                for response in keyword_matches:121                    st.write(f"- {response}")122            else:123                st.write("No specific recommendations available.")124 125    except Exception as e:126        st.error(f"An error occurred during analysis: {str(e)}")127 128# Sidebar information129with st.sidebar:130    st.markdown("### About")131    st.write("""132    This tool analyzes customer service tickets by:133    - Determining sentiment134    - Suggesting appropriate department135    - Setting priority level136    - Providing confidence scores137    """)138 139    st.markdown("### Departments")140    for dept, desc in departments.items():141        st.write(f"**{dept}**")142        st.write(desc)143        st.write("---")