File size: 7,676 Bytes
08e6703
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# ---------- 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()