import streamlit as st from transformers import pipeline import re st.set_page_config(page_title="Hindi Sentiment Analysis", page_icon="😊") pipe = pipeline("text-classification", model="trohith89/Hindi_Sentiment_3_class") names = ["neutral", "positive", "negative"] emojis = {"positive": "🤗", "negative": "😔", "neutral": "😐"} def is_mostly_hindi(text): if not text.strip(): return False devanagari_pattern = r'[\u0900-\u097F]' allowed_pattern = r'[a-zA-Z0-9\s.,!?]' devanagari_chars = len(re.findall(devanagari_pattern, text)) allowed_chars = len(re.findall(allowed_pattern, text)) total_chars = len(text) hindi_proportion = devanagari_chars / total_chars if total_chars > 0 else 0 valid_chars = devanagari_chars + allowed_chars == total_chars return hindi_proportion >= 0.7 and valid_chars def clean_input(text): cleaned_text = re.sub(r'[^a-zA-Z0-9\u0900-\u097F\s?.!]', ' ', text) cleaned_text = re.sub(r'([?.!])(?![?.!]\s|$)', '', cleaned_text) cleaned_text = ' '.join(cleaned_text.split()) return cleaned_text # --- Custom CSS Styling --- st.markdown(""" """, unsafe_allow_html=True) # --- App Content --- st.markdown("

Hindi Sentiment Analysis

", unsafe_allow_html=True) st.markdown("""
Please enter a sentence or paragraph in Hindi in the text area below.
Text must be primarily in Hindi.
Example: "यह फिल्म बहुत अच्छी थी और अभिनय शानदार था।
Click the 'Predict' button to analyze the sentiment (positive, negative, or neutral)!
""", unsafe_allow_html=True) user_input = st.text_area("", placeholder="Enter your text in Hindi here...") if st.button("Predict"): if not user_input.strip(): st.warning("⚠️ Please enter text. Empty input is not allowed.") else: cleaned_input = clean_input(user_input) if not is_mostly_hindi(cleaned_input): st.error("❌ Please enter text primarily in Hindi (Devanagari script).") else: result = pipe(cleaned_input)[0] sentiment_index = int(result['label'].split("_")[1]) sentiment = names[sentiment_index] emoji = emojis[sentiment] output_class = f"output-{sentiment}" st.markdown(f"
{sentiment.capitalize()} {emoji}
", unsafe_allow_html=True) st.markdown(f"
Your Text: {user_input}
Confidence Score: {result['score']:.2f}
", unsafe_allow_html=True)