import gradio as gr from transformers import pipeline import time # Load the sentiment analysis model print("Loading model...") # Force reload without cache classifier = pipeline( "sentiment-analysis", model="./istrenirani_model", device=-1 # Force CPU (same as Streamlit) ) print("Model loaded successfully!") # Translation function def prevedi_labelu(label, score): """Translate model labels to Serbian""" # Note: Your model's label mapping from training: # LABEL_0 = Negativan (0) # LABEL_1 = Neutralan (1) # LABEL_2 = Pozitivan (2) if label == 'LABEL_0': return "🔴 Negativan", score, "#ff4444" elif label == 'LABEL_1': return "⚪ Neutralan", score, "#888888" elif label == 'LABEL_2': return "🟢 Pozitivan", score, "#44ff44" return "❓ Nepoznat", score, "#888888" # Main prediction function def analyze_sentiment(text): """Analyze sentiment of Serbian text""" if not text or not text.strip(): return "⚠️ Molim vas unesite tekst!" try: # Get prediction result = classifier(text)[0] # Translate result sentiment, confidence, color = prevedi_labelu(result['label'], result['score']) # Create colored HTML output sentiment_html = f"""

{sentiment}

""" return sentiment_html except Exception as e: return f"❌ Greška: {str(e)}" # Custom CSS for better styling custom_css = """ #sentiment-output { font-size: 24px; font-weight: bold; } .gradio-container { max-width: 800px; margin: auto; } """ # Create Gradio interface with gr.Blocks(css=custom_css, title="Serbian Sentiment Analyzer", theme=gr.themes.Soft()) as demo: # Header gr.Markdown( """ # 🎭 Analiza Sentimenta - Srpski Jezik Unesite tekst na srpskom jeziku da biste analizirali sentiment. Model prepoznaje: **Pozitivan** 🟢, **Neutralan** ⚪, **Negativan** 🔴 --- """ ) # Input and output with gr.Row(): with gr.Column(): text_input = gr.Textbox( label="Unesite tekst za analizu", placeholder="Npr: Ovaj film je bio fenomenalan!", lines=5 ) analyze_btn = gr.Button("🔍 Analiziraj Sentiment", variant="primary", size="lg") with gr.Row(): sentiment_output = gr.HTML(label="Rezultat", elem_id="sentiment-output") # Connect button to function analyze_btn.click( fn=analyze_sentiment, inputs=text_input, outputs=sentiment_output ) # Footer gr.Markdown( """ --- ### ℹ️ O Modelu - **Baziran na**: [dejanseo/BERTic-sentiment](https://huggingface.co/dejanseo/BERTic-sentiment) - **Istreniran na**: 4500 srpskih rečenica (1500 po kategoriji) - **Klase**: Pozitivan, Neutralan, Negativan 🤖 Napravljeno sa ❤️ koristeći Transformers i Gradio (Iako mi je Streamlit bolji) --- ### 🔌 Korišćenje API-ja Ovaj Space podržava API koji možete pozivati programski... Primer (JavaScript): ```javascript const response = await fetch("https://huggingface.co/spaces/codepanov/serbian-sentiment-analyzer/api/predict", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ data: ["Vaš tekst ovde"] }) }); const result = await response.json(); ``` """ ) # Launch the app if __name__ == "__main__": demo.launch()