dkvbabu
Streamlit app with Docker
35c4cda
Raw History Blame Contribute Delete
6.54 kB
import streamlit as st
import requests
from textblob import TextBlob
from collections import Counter
API_URL = "https://dkvbabu-fdp-flask-api.hf.space/predict"
st.set_page_config(page_title='FDP Sentiment Analyzer', page_icon='πŸŽ“', layout='centered')
def textblob_sentiment(text):
"""Reliable fallback for demo day."""
polarity = TextBlob(text).sentiment.polarity
abs_pol = abs(polarity)
if polarity > 0.1:
conf = 0.5 + (abs_pol / 2)
scores = {"Positive": conf, "Negative": max(0, 0.1 - abs_pol), "Neutral": max(0, 0.4 - abs_pol)}
return "positive", conf, scores
elif polarity < -0.1:
conf = 0.5 + (abs_pol / 2)
scores = {"Positive": max(0, 0.1 - abs_pol), "Negative": conf, "Neutral": max(0, 0.4 - abs_pol)}
return "negative", conf, scores
else:
return "neutral", 0.6, {"Positive": 0.2, "Negative": 0.2, "Neutral": 0.6}
def safe_predict(text):
"""Use custom model if healthy, else fallback to TextBlob."""
if model is None:
return textblob_sentiment(text)
try:
pred = model.predict([text])[0]
proba = model.predict_proba([text])[0]
conf = float(max(proba))
classes = [str(c) for c in model.classes_]
scores = {c.capitalize(): float(p) for c, p in zip(classes, proba)}
return str(pred), conf, scores
except Exception as e:
st.toast(f"⚠️ Model error: {e}. Using fallback.", icon="πŸ”₯")
return textblob_sentiment(text)
st.title('πŸŽ“ FDP Feedback Sentiment Analyzer')
st.markdown('Built during 5-Day FDP on Deep Learning and NLP β€” **Day 5: Deployment**')
st.divider()
with st.sidebar:
st.header('About')
st.markdown('Classifies FDP feedback as **Positive**, **Negative**, or **Neutral**')
st.markdown('Model: `TF-IDF + Logistic Regression`')
use_fallback = st.toggle(
'πŸ”’ Demo Safe Mode (TextBlob)',
value=False,
help="Toggle ON if your custom model is untrained or gives wrong predictions"
)
# st.info('πŸ’‘ **Trainer Tip:** If "good" shows as NEGATIVE, enable Safe Mode above.')
st.markdown("---")
st.markdown("**Confidence Guide:**")
st.markdown("🟒 **>60%** β€” High confidence")
st.markdown("🟑 **40–60%** β€” Uncertain")
st.markdown("πŸ”΄ **<40%** β€” Low confidence / Random guess")
st.subheader('πŸ“ Analyze a Single Review')
user_input = st.text_area(
'Enter feedback:',
height=120,
placeholder="e.g., The workshop was incredibly informative and well-paced!"
)
if st.button('πŸ” Analyze', type='primary'):
if not user_input.strip():
st.warning('⚠️ Please enter some text first!')
else:
with st.spinner('Analyzing sentiment...'):
if use_fallback:
pred, conf, scores = textblob_sentiment(user_input)
else:
pred, conf, scores = safe_predict(user_input)
pred_lower = pred.lower()
if conf >= 0.6:
conf_emoji, conf_text = "🟒", "High"
elif conf >= 0.4:
conf_emoji, conf_text = "🟑", "Medium"
else:
conf_emoji, conf_text = "πŸ”΄", "Low"
with st.container(border=True):
if pred_lower == 'positive':
st.success(f'### 🟒 POSITIVE \n**Confidence:** {conf:.1%} ({conf_text})')
elif pred_lower == 'negative':
st.error(f'### πŸ”΄ NEGATIVE \n**Confidence:** {conf:.1%} ({conf_text})')
else:
st.info(f'### βšͺ NEUTRAL \n**Confidence:** {conf:.1%} ({conf_text})')
if conf < 0.5 and not use_fallback:
st.warning(
"⚠️ Confidence is very low. Toggle **Demo Safe Mode** in the sidebar "
"if the model seems unreliable."
)
st.markdown("**Class Probabilities:**")
st.bar_chart({k: [v] for k, v in scores.items()})
with st.expander("πŸ”§ Raw JSON Output"):
st.json({
"text": user_input,
"prediction": pred_lower,
"confidence": conf,
"scores": scores
})
st.divider()
st.subheader('πŸ“Š Batch Analysis')
batch = st.text_area(
'Enter reviews (one per line):',
height=150,
placeholder="Great session!\nCould have been slower...\nThe hands-on part was okay."
)
if st.button('πŸš€ Analyze Batch', type='secondary'):
if not batch.strip():
st.warning('⚠️ Please enter at least one review!')
else:
revs = [r.strip() for r in batch.split('\n') if r.strip()]
progress = st.progress(0, text="Processing reviews...")
results = []
for i, rev in enumerate(revs):
if use_fallback:
p, c, _ = textblob_sentiment(rev)
else:
p, c, _ = safe_predict(rev)
results.append({
"review": rev,
"sentiment": str(p).capitalize(),
"confidence": c
})
progress.progress((i + 1) / len(revs), text=f"Processed {i+1}/{len(revs)}...")
progress.empty()
st.markdown("**Detailed Results:**")
for i, res in enumerate(results, 1):
emoji = "🟒" if res['sentiment'].lower() == 'positive' else \
"πŸ”΄" if res['sentiment'].lower() == 'negative' else "βšͺ"
with st.expander(f"{emoji} Review {i}: {res['review'][:55]}..."):
st.write(f"**Sentiment:** {res['sentiment']}")
st.write(f"**Confidence:** {res['confidence']:.1%}")
c = Counter([r['sentiment'].lower() for r in results])
st.markdown("---")
st.subheader("πŸ“ˆ Summary Dashboard")
m1, m2, m3, m4 = st.columns(4)
m1.metric('🟒 Positive', c.get('positive', 0))
m2.metric('πŸ”΄ Negative', c.get('negative', 0))
m3.metric('βšͺ Neutral', c.get('neutral', 0))
m4.metric('πŸ“ Total', len(revs))
st.bar_chart({
"Positive": [c.get('positive', 0)],
"Negative": [c.get('negative', 0)],
"Neutral": [c.get('neutral', 0)]
})
st.divider()
st.caption('Β© 5-Day FDP on Deep Learning and NLP β€” Day 5: Deployment | Built with Streamlit')