disham993 commited on
Commit
2e9c780
·
verified ·
1 Parent(s): 7716738

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +200 -0
app.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import plotly.express as px
3
+ import pandas as pd
4
+ from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
5
+ import os
6
+
7
+ # Set the page configuration (must be the first Streamlit command)
8
+ st.set_page_config(page_title="⚡ Device Feedback Classification", layout="wide")
9
+
10
+ # Model configurations
11
+ MODELS = {
12
+ "ModernBERT Base": {
13
+ "path": "disham993/electrical-classification-ModernBERT-base",
14
+ "description": "⚙️ This model is fine-tuned specifically for the electrical engineering domain for electrical device feedback classification."
15
+ },
16
+ "ModernBERT Large": {
17
+ "path": "disham993/electrical-classification-ModernBERT-large",
18
+ "description": "🚀 A larger version of ModernBERT with improved capacity for electrical device feedback classification."
19
+ },
20
+ "DistilBERT Base": {
21
+ "path": "disham993/electrical-classification-distilbert-base",
22
+ "description": "⚡ A lightweight model optimized for faster inference in electrical device feedback classification."
23
+ },
24
+ "BERT Base": {
25
+ "path": "disham993/electrical-classification-bert-base",
26
+ "description": "🔧 Standard BERT model fine-tuned for electrical device feedback analysis."
27
+ },
28
+ "BERT Large": {
29
+ "path": "disham993/electrical-classification-bert-large",
30
+ "description": "📈 A larger variant of BERT designed for higher accuracy in electrical device feedback sentiment classification."
31
+ }
32
+ }
33
+
34
+ # Example texts
35
+ EXAMPLES = [
36
+ "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.",
37
+ "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.",
38
+ "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.",
39
+ "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."
40
+ ]
41
+
42
+ @st.cache_resource
43
+ def load_classifier(model_name):
44
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
45
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
46
+ return pipeline("text-classification", model=model, tokenizer=tokenizer)
47
+
48
+ def main():
49
+ st.title("⚡ Electrical Device Feedback Classification")
50
+
51
+ # Add app description
52
+ st.markdown(
53
+ """
54
+ ### 🔍 What does this app do?
55
+ This application allows users to classify customer feedback about **electrical devices** such as:
56
+
57
+ - ⚙️ **Circuit breakers**
58
+ - 🔋 **Transformers**
59
+ - 📱 **Smart meters**
60
+ - ⚡ **Inverters**
61
+ - 🔧 **Electric panels**, **switchgear**, **relays**, and more.
62
+
63
+ The feedback is categorized into **sentiment categories**:
64
+ - ✅ **Positive**
65
+ - ❌ **Negative**
66
+ - ⚖️ **Neutral**
67
+ - 🔄 **Mixed**
68
+
69
+ Simply select a model, input your feedback text, and get detailed results with a confidence score.
70
+ This tool is ideal for manufacturers and service providers to identify areas of improvement and enhance product reliability and customer satisfaction. 🚀
71
+ """
72
+ )
73
+
74
+ # Sidebar
75
+ st.sidebar.header("🛠️ Model Configuration")
76
+ selected_model = st.sidebar.selectbox("⚙️ Select Model", list(MODELS.keys()))
77
+
78
+ # Show model details in a collapsible section
79
+ with st.sidebar.expander("ℹ️ Model Details"):
80
+ st.markdown(f"**🔗 Model Path**: {MODELS[selected_model]['path']}")
81
+ st.markdown(f"{MODELS[selected_model]['description']}")
82
+
83
+ # Add Clear button in the sidebar
84
+ if st.sidebar.button("🧹 Clear Input", key="clear_button"):
85
+ # Reset session state
86
+ st.session_state.feedback_text = EXAMPLES[0]
87
+ st.session_state.example_idx = 0
88
+ st.session_state.classification_result = None
89
+
90
+ # Load model
91
+ classifier = load_classifier(MODELS[selected_model]["path"])
92
+
93
+ # Ensure session state for example index and feedback text
94
+ if "example_idx" not in st.session_state:
95
+ st.session_state.example_idx = 0
96
+ if "feedback_text" not in st.session_state:
97
+ st.session_state.feedback_text = EXAMPLES[st.session_state.example_idx]
98
+
99
+ # Dropdown for examples
100
+ selected_example_idx = st.selectbox(
101
+ "Select an example or write your own:",
102
+ range(len(EXAMPLES)),
103
+ format_func=lambda x: EXAMPLES[x][:100] + "...",
104
+ index=st.session_state.example_idx
105
+ )
106
+
107
+ # Sync dropdown with text area before widget instantiation
108
+ if selected_example_idx != st.session_state.example_idx:
109
+ st.session_state.example_idx = selected_example_idx
110
+ st.session_state.feedback_text = EXAMPLES[selected_example_idx]
111
+
112
+ # Text area for input
113
+ feedback_text = st.text_area(
114
+ "Device Feedback",
115
+ value=st.session_state.feedback_text,
116
+ height=150,
117
+ key="feedback_text"
118
+ )
119
+
120
+ # Only update session state if the text area is edited
121
+ if feedback_text != st.session_state.feedback_text:
122
+ st.session_state.feedback_text = feedback_text
123
+
124
+ # Classification button
125
+ if st.button("🚀 Classify", type="primary"):
126
+ if feedback_text.strip():
127
+ # Get prediction
128
+ result = classifier(feedback_text)
129
+ label = result[0]['label']
130
+ score = result[0]['score']
131
+
132
+ # Create data for visualization
133
+ sentiments = ['Positive', 'Negative', 'Neutral', 'Mixed']
134
+ scores = [score * 100 if s.lower() == label.lower() else 0 for s in sentiments]
135
+
136
+ df = pd.DataFrame({
137
+ 'Sentiment': sentiments,
138
+ 'Score': scores
139
+ })
140
+
141
+ # Save results to session state
142
+ st.session_state.classification_result = {
143
+ "label": label,
144
+ "score": score,
145
+ "df": df
146
+ }
147
+
148
+ # Display results if available
149
+ if st.session_state.get("classification_result"):
150
+ result = st.session_state.classification_result
151
+ label = result["label"]
152
+ score = result["score"]
153
+ df = result["df"]
154
+
155
+ st.subheader("🎯 Results")
156
+ st.metric("🏷️ Detected Class", label)
157
+ st.metric("📊 Confidence", f"{score * 100:.2f}%")
158
+
159
+ # Enhanced visualization
160
+ st.subheader("📈 Classification Confidence Scores")
161
+ fig = px.bar(
162
+ df,
163
+ x='Sentiment',
164
+ y='Score',
165
+ color='Sentiment',
166
+ text='Score',
167
+ range_y=[0, 100],
168
+ title="Sentiment Confidence Breakdown",
169
+ labels={'Score': 'Confidence (%)'},
170
+ color_discrete_map={
171
+ 'Positive': '#2ca02c',
172
+ 'Negative': '#d62728',
173
+ 'Neutral': '#1f77b4',
174
+ 'Mixed': '#9467bd'
175
+ }
176
+ )
177
+
178
+ fig.update_traces(
179
+ texttemplate='%{text:.2f}%',
180
+ textposition='outside'
181
+ )
182
+
183
+ fig.update_layout(
184
+ height=450,
185
+ margin=dict(t=40, b=40, l=40, r=40),
186
+ xaxis=dict(title='Sentiment'),
187
+ yaxis=dict(title='Confidence (%)'),
188
+ legend=dict(
189
+ orientation="v",
190
+ yanchor="top",
191
+ y=1,
192
+ xanchor="left",
193
+ x=-0.15 # Adjust legend position to the left side
194
+ )
195
+ )
196
+
197
+ st.plotly_chart(fig, use_container_width=True)
198
+
199
+ if __name__ == "__main__":
200
+ main()