File size: 8,789 Bytes
2e9c780
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38794ba
 
 
 
 
 
 
 
 
2e9c780
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import streamlit as st
import plotly.express as px
import pandas as pd
from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
import os

# Set the page configuration (must be the first Streamlit command)
st.set_page_config(page_title="⚡ Device Feedback Classification", layout="wide")

# Model configurations
MODELS = {
    "ModernBERT Base": {
        "path": "disham993/electrical-classification-ModernBERT-base",
        "description": "⚙️ This model is fine-tuned specifically for the electrical engineering domain for electrical device feedback classification."
    },
    "ModernBERT Large": {
        "path": "disham993/electrical-classification-ModernBERT-large",
        "description": "🚀 A larger version of ModernBERT with improved capacity for electrical device feedback classification."
    },
    "DistilBERT Base": {
        "path": "disham993/electrical-classification-distilbert-base",
        "description": "⚡ A lightweight model optimized for faster inference in electrical device feedback classification."
    },
    "BERT Base": {
        "path": "disham993/electrical-classification-bert-base",
        "description": "🔧 Standard BERT model fine-tuned for electrical device feedback analysis."
    },
    "BERT Large": {
        "path": "disham993/electrical-classification-bert-large",
        "description": "📈 A larger variant of BERT designed for higher accuracy in electrical device feedback sentiment classification."
    }
}

# Example texts
EXAMPLES = [
    "The circuit breaker's thermal-magnetic trip mechanism is satisfactory in terms of fault current interruption capability, but its response time could be improved for more sensitive applications.",
    "The device's transient recovery voltage rating exceeds the maximum permissible value by a factor of two, yet it still satisfies the required switching performance.",
    "I've had the Enermax SM100 smart meter installed in my home for six months now. I'm really impressed with how easy it is to set up and use, especially with the mobile app that lets me monitor my energy usage remotely. The real-time consumption data has also been accurate and helpful for optimizing our energy efficiency. However, the device itself is quite bulky and takes up a lot of space on our wall outlet, which I wish they would address in future designs. Additionally, there have been occasional lag times when trying to access historical usage data through the app.",
    "The X5000 inverter was installed on the rooftop solar array on February 20th. The unit operates at a DC-AC conversion efficiency of 95% and maintains a frequency stability within ±1% under normal operating conditions. Monthly monitoring shows the inverter has achieved a total energy production of 8,200 kWh since installation, with an average daily output of 275 Wh. The installation required standard rooftop mounting hardware and took approximately 2 hours to complete, including conduit connections. System logs indicate the inverter has automatically adjusted for temperature compensation during extreme weather conditions."
]

@st.cache_resource
def load_classifier(model_name):
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    model = AutoModelForSequenceClassification.from_pretrained(model_name)
    return pipeline("text-classification", model=model, tokenizer=tokenizer)

def main():
    st.title("⚡ Electrical Device Feedback Classification")
    
    # Add app description
    st.markdown(
         """
        ### 🔍 What does this app do?
        This application allows users to classify customer feedback about **electrical devices** such as:
        
        - ⚙️ **Circuit breakers**
        - 🔋 **Transformers**
        - 📱 **Smart meters**
        - ⚡ **Inverters**
        - 🔧 **Electric panels**, **switchgear**, **relays**, and more.
        
        Simply select a model, input your feedback text, and get detailed results with a confidence score. 
        This tool is ideal for manufacturers and service providers to identify areas of improvement and enhance product reliability and customer satisfaction. 🚀
        """
    )

    # Sidebar
    st.sidebar.header("🛠️ Model Configuration")
    selected_model = st.sidebar.selectbox("⚙️ Select Model", list(MODELS.keys()))
    
    # Show model details in a collapsible section
    with st.sidebar.expander("ℹ️ Model Details"):
        st.markdown(f"**🔗 Model Path**: {MODELS[selected_model]['path']}")
        st.markdown(f"{MODELS[selected_model]['description']}")
    
    # Add Clear button in the sidebar
    if st.sidebar.button("🧹 Clear Input", key="clear_button"):
        # Reset session state
        st.session_state.feedback_text = EXAMPLES[0]
        st.session_state.example_idx = 0
        st.session_state.classification_result = None
    
    # Load model
    classifier = load_classifier(MODELS[selected_model]["path"])
    
    # Ensure session state for example index and feedback text
    if "example_idx" not in st.session_state:
        st.session_state.example_idx = 0
    if "feedback_text" not in st.session_state:
        st.session_state.feedback_text = EXAMPLES[st.session_state.example_idx]

    # Dropdown for examples
    selected_example_idx = st.selectbox(
        "Select an example or write your own:",
        range(len(EXAMPLES)),
        format_func=lambda x: EXAMPLES[x][:100] + "...",
        index=st.session_state.example_idx
    )

    # Sync dropdown with text area before widget instantiation
    if selected_example_idx != st.session_state.example_idx:
        st.session_state.example_idx = selected_example_idx
        st.session_state.feedback_text = EXAMPLES[selected_example_idx]

    # Text area for input
    feedback_text = st.text_area(
        "Device Feedback",
        value=st.session_state.feedback_text,
        height=150,
        key="feedback_text"
    )

    # Only update session state if the text area is edited
    if feedback_text != st.session_state.feedback_text:
        st.session_state.feedback_text = feedback_text

    # Classification button
    if st.button("🚀 Classify", type="primary"):
        if feedback_text.strip():
            # Get prediction
            result = classifier(feedback_text)
            label = result[0]['label']
            score = result[0]['score']
            
            # Create data for visualization
            sentiments = ['Positive', 'Negative', 'Neutral', 'Mixed']
            scores = [score * 100 if s.lower() == label.lower() else 0 for s in sentiments]
            
            df = pd.DataFrame({
                'Sentiment': sentiments,
                'Score': scores
            })
            
            # Save results to session state
            st.session_state.classification_result = {
                "label": label,
                "score": score,
                "df": df
            }
    
    # Display results if available
    if st.session_state.get("classification_result"):
        result = st.session_state.classification_result
        label = result["label"]
        score = result["score"]
        df = result["df"]
        
        st.subheader("🎯 Results")
        st.metric("🏷️ Detected Class", label)
        st.metric("📊 Confidence", f"{score * 100:.2f}%")
        
        # Enhanced visualization
        st.subheader("📈 Classification Confidence Scores")
        fig = px.bar(
            df,
            x='Sentiment',
            y='Score',
            color='Sentiment',
            text='Score',
            range_y=[0, 100],
            title="Sentiment Confidence Breakdown",
            labels={'Score': 'Confidence (%)'},
            color_discrete_map={
                'Positive': '#2ca02c',
                'Negative': '#d62728',
                'Neutral': '#1f77b4',
                'Mixed': '#9467bd'
            }
        )
        
        fig.update_traces(
            texttemplate='%{text:.2f}%',
            textposition='outside'
        )
        
        fig.update_layout(
            height=450,
            margin=dict(t=40, b=40, l=40, r=40),
            xaxis=dict(title='Sentiment'),
            yaxis=dict(title='Confidence (%)'),
            legend=dict(
                orientation="v",
                yanchor="top",
                y=1,
                xanchor="left",
                x=-0.15  # Adjust legend position to the left side
            )
        )
        
        st.plotly_chart(fig, use_container_width=True)

    # Entity type legend
    st.sidebar.title("Sentiment Categories")
    st.sidebar.markdown("""
    - ✅ **Positive**
    - ❌ **Negative**
    - ⚖️ **Neutral**
    - 🔄 **Mixed**
    """)

if __name__ == "__main__":
    main()