File size: 2,535 Bytes
8533898
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from transformers import pipeline
import torch

# Initialize sentiment analysis pipeline
try:
    sentiment_pipeline = pipeline(
        "sentiment-analysis",
        model="nlptown/bert-base-multilingual-uncased-sentiment",
        device=0 if torch.cuda.is_available() else -1
    )
except Exception as e:
    raise Exception(f"Failed to load model: {str(e)}")

def analyze_sentiment(text, language):
    """Analyze sentiment of input text and return sentiment label and confidence score."""
    if not text or not text.strip():
        return "Error: Please enter some text", 0
    
    try:
        result = sentiment_pipeline(text)
        sentiment = result[0]['label']  # e.g., "1 star", "2 stars", etc.
        score = result[0]['score']      # Confidence score between 0 and 1
        return sentiment, round(score, 2)
    except Exception as e:
        return "Error occurred", 0

# Custom CSS for bilingual readability
custom_css = """
    body, .gr-button, .gr-input, .gr-output, .gr-textbox {
        font-family: 'Tajawal', 'Arial', sans-serif !important;
    }
    .gr-button {margin: 5px;}
    .output-text {font-size: 16px;}
"""

# Gradio interface for Part 1
with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
    gr.Markdown("# Sentiment Analysis Platform")
    gr.Markdown("Enter text in Arabic or English to analyze its sentiment.")
    
    with gr.Row():
        with gr.Column(scale=2):
            text_input = gr.Textbox(
                label="Your Comment",
                placeholder="Type your comment here...",
                lines=3
            )
            language_input = gr.Radio(
                ["Arabic", "English"],
                label="Language",
                value="English"
            )
            submit_btn = gr.Button("Analyze", variant="primary")
        
        with gr.Column(scale=3):
            sentiment_output = gr.Textbox(label="Sentiment")
            score_output = gr.Slider(0, 1, label="Confidence Score", interactive=False)
    
    examples = gr.Examples(
        examples=[
            ["The product is amazing!", "English"],
            ["الخدمة سيئة جداً", "Arabic"],
            ["منتج جيد نوعاً ما", "Arabic"],
            ["It's okay, nothing special", "English"]
        ],
        inputs=[text_input, language_input]
    )
    
    submit_btn.click(
        fn=analyze_sentiment,
        inputs=[text_input, language_input],
        outputs=[sentiment_output, score_output]
    )

demo.launch()