disham993's picture
Update app.py
38794ba verified
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()