Spaces:
Sleeping
Sleeping
Download app.py from dkvbabu/fdp-streamlit-app: direct link, hf CLI and curl.
- Browser
- Download file 6.54 kB
-
https://huggingface.co/spaces/dkvbabu/fdp-streamlit-app/resolve/main/app.py
- Command line
-
hf download hf://spaces/dkvbabu/fdp-streamlit-app/app.py
-
curl -L -o app.py https://huggingface.co/spaces/dkvbabu/fdp-streamlit-app/resolve/main/app.py
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') |