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')