abdullah099's picture
Upload myassign.py
08e6703 verified
# ---------- Sentiment Analyzer Pro (With CSV Export and Language Support) ----------
import streamlit as st
import pandas as pd
import time
from transformers import pipeline
from io import StringIO
import requests
# -------------------- Configurations --------------------
st.set_page_config(
page_title="Sentiment Analyzer Pro",
page_icon="🧠",
layout="wide",
)
# -------------------- Helper Functions --------------------
@st.cache_resource
def load_pipeline(language='en'):
if language == 'ur':
return pipeline("sentiment-analysis", model="urduhack/bert-base-urdu-cased-sentiment")
return pipeline("sentiment-analysis")
classifier = load_pipeline()
def analyze_sentiment(text, language):
result = classifier(text)[0]
return result["label"], result["score"]
def create_csv(data):
df = pd.DataFrame(data)
csv = df.to_csv(index=False)
return csv
def save_csv(data, filename="sentiment_analysis.csv"):
csv = create_csv(data)
st.download_button(
label="Download CSV",
data=csv,
file_name=filename,
mime="text/csv",
)
def submit_contact_form(name, email, message):
# [Optional] You can connect this with Google Forms or Email APIs
st.success(f"βœ… Thank you {name}, your message has been received!")
def show_footer():
st.markdown("---")
st.markdown(
"<p style='text-align: center; font-size: 14px;'>© 2025 Sentiment Analyzer Pro | Built with ❀️ using Hugging Face and Streamlit</p>",
unsafe_allow_html=True,
)
# -------------------- Sidebar --------------------
st.sidebar.title("πŸ“š Navigation")
page = st.sidebar.radio("Go to", ["Home", "About", "Contact"])
st.sidebar.title("πŸ“š Use Cases (on Home)")
use_case = st.sidebar.radio(
"Choose a Use Case",
(
"General Text",
"Social Media Post",
"Customer Review",
"Email/Message",
"Product Description",
)
)
st.sidebar.title("🌐 Language")
language = st.sidebar.selectbox(
"Select Language",
("English", "Urdu"),
)
st.sidebar.markdown("---")
st.sidebar.info(
"This app uses a **Transformers-based model** to predict the **sentiment** "
"(Positive, Negative, Neutral) with a **confidence score**."
)
st.sidebar.write("Made with ❀️ by M-Abdullah")
# -------------------- Page Logic --------------------
if page == "Home":
# ------------- HOME PAGE -------------
st.markdown("<h1 style='text-align: center; color: #4CAF50;'>🧠 Sentiment Analyzer Pro</h1>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center;'>Analyze emotions in text, reviews, posts, and more!</p>", unsafe_allow_html=True)
st.write("---")
st.write(f"### ✍️ Enter your {use_case} below:")
user_input = st.text_area("", placeholder=f"Write your {use_case.lower()} here...", height=200)
if st.button("πŸ” Analyze Sentiment"):
if user_input.strip() == "":
st.warning("⚠️ Please enter some text to analyze!")
else:
with st.spinner('Analyzing...'):
label, score = analyze_sentiment(user_input, language)
time.sleep(1) # Smooth spinner effect
# Emoji Reaction
emoji = {
"POSITIVE": "😊",
"NEGATIVE": "😞",
"NEUTRAL": "😐"
}.get(label.upper(), "πŸ€”")
# Result Display
st.success(f"**Sentiment:** {label} {emoji}")
st.info(f"**Confidence Score:** {score:.2f}")
# Chart Section
st.write("### πŸ“Š Sentiment Score")
st.bar_chart({"Confidence Score": [score]})
# Detailed Explanation
st.write("### πŸ“– Interpretation")
if label == "POSITIVE":
st.write("βœ… This text expresses positive emotions, happiness, satisfaction, or support.")
elif label == "NEGATIVE":
st.write("⚠️ This text expresses negative emotions, dissatisfaction, criticism, or sadness.")
else:
st.write("ℹ️ This text is neutral without strong emotions.")
# Download CSV Button
save_csv([{"Text": user_input, "Sentiment": label, "Confidence Score": score}], "sentiment_analysis.csv")
elif page == "About":
# ------------- ABOUT PAGE -------------
st.markdown("<h1 style='text-align: center; color: #4CAF50;'>πŸ“˜ About Sentiment Analyzer Pro</h1>", unsafe_allow_html=True)
st.write("---")
st.markdown("""
### ✨ Overview
**Sentiment Analyzer Pro** is an advanced natural language processing (NLP) app built using:
- πŸ›  **Streamlit** for the web app interface
- 🧠 **Hugging Face Transformers** for deep learning models
This application can detect and classify **sentiments** (Positive, Negative, Neutral) in:
- General texts
- Social media posts (e.g., Twitter, Facebook)
- Customer feedback
- Emails and messaging
- Product descriptions
### 🎯 Objectives
- Simplify sentiment analysis for all users
- Provide fast, reliable, real-time emotional analysis
- Useful for businesses, researchers, students, and individuals
### πŸš€ Future Enhancements
- Multilingual Sentiment Analysis (Urdu, Arabic, French)
- Custom Model Uploads
- Sentiment Trends over Time
""")
elif page == "Contact":
FORM_URL = "https://docs.google.com/forms/u/0/d/1A95xalIMN6jDN8DCAq3agQGGDaDXP7x1hed-DjHqxow/prefill"
FIELD_IDS = {
"name": "entry.796411702", # replace with actual ID
"email": "entry.796411702", # replace with actual ID
"message": "entry.939908203", # Correct ID
}
# Page Title
st.markdown("<h1 style='text-align: center; color: #4CAF50;'>πŸ“¬ Contact Us</h1>", unsafe_allow_html=True)
st.markdown("---")
st.markdown("""
### πŸ’¬ We'd Love to Hear From You!
Fill out the form below and your message will be saved to our system.
""")
with st.form(key='contact_form'):
name = st.text_input("Your Name")
email = st.text_input("Your Email")
message = st.text_area("Your Message")
submit_button = st.form_submit_button(label='Send Message')
if submit_button:
if name.strip() == "" or email.strip() == "" or message.strip() == "":
st.warning("⚠️ Please fill out all fields before submitting.")
else:
# Debugging: Check form values
st.write(f"Name: {name}, Email: {email}, Message: {message}")
# Submit data to Google Form
data = {
FIELD_IDS["name"]: name,
FIELD_IDS["email"]: email,
FIELD_IDS["message"]: message,
}
response = requests.post(FORM_URL, data=data)
if response.status_code == 200:
st.success(f"βœ… Thank you {name}! Your message has been sent successfully.")
else:
st.error(f"❌ There was a problem sending your message. Error: {response.status_code}")
# Footer
st.markdown("---")
st.markdown("<p style='text-align: center; font-size: 16px;'>Made with ❀️ by <strong>M-Abdullah</strong> | 2025</p>", unsafe_allow_html=True)
# -------------------- Footer --------------------
show_footer()