RawadAlghamdi commited on
Commit
8533898
·
verified ·
1 Parent(s): 0c50555

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -0
app.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ import torch
4
+
5
+ # Initialize sentiment analysis pipeline
6
+ try:
7
+ sentiment_pipeline = pipeline(
8
+ "sentiment-analysis",
9
+ model="nlptown/bert-base-multilingual-uncased-sentiment",
10
+ device=0 if torch.cuda.is_available() else -1
11
+ )
12
+ except Exception as e:
13
+ raise Exception(f"Failed to load model: {str(e)}")
14
+
15
+ def analyze_sentiment(text, language):
16
+ """Analyze sentiment of input text and return sentiment label and confidence score."""
17
+ if not text or not text.strip():
18
+ return "Error: Please enter some text", 0
19
+
20
+ try:
21
+ result = sentiment_pipeline(text)
22
+ sentiment = result[0]['label'] # e.g., "1 star", "2 stars", etc.
23
+ score = result[0]['score'] # Confidence score between 0 and 1
24
+ return sentiment, round(score, 2)
25
+ except Exception as e:
26
+ return "Error occurred", 0
27
+
28
+ # Custom CSS for bilingual readability
29
+ custom_css = """
30
+ body, .gr-button, .gr-input, .gr-output, .gr-textbox {
31
+ font-family: 'Tajawal', 'Arial', sans-serif !important;
32
+ }
33
+ .gr-button {margin: 5px;}
34
+ .output-text {font-size: 16px;}
35
+ """
36
+
37
+ # Gradio interface for Part 1
38
+ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
39
+ gr.Markdown("# Sentiment Analysis Platform")
40
+ gr.Markdown("Enter text in Arabic or English to analyze its sentiment.")
41
+
42
+ with gr.Row():
43
+ with gr.Column(scale=2):
44
+ text_input = gr.Textbox(
45
+ label="Your Comment",
46
+ placeholder="Type your comment here...",
47
+ lines=3
48
+ )
49
+ language_input = gr.Radio(
50
+ ["Arabic", "English"],
51
+ label="Language",
52
+ value="English"
53
+ )
54
+ submit_btn = gr.Button("Analyze", variant="primary")
55
+
56
+ with gr.Column(scale=3):
57
+ sentiment_output = gr.Textbox(label="Sentiment")
58
+ score_output = gr.Slider(0, 1, label="Confidence Score", interactive=False)
59
+
60
+ examples = gr.Examples(
61
+ examples=[
62
+ ["The product is amazing!", "English"],
63
+ ["الخدمة سيئة جداً", "Arabic"],
64
+ ["منتج جيد نوعاً ما", "Arabic"],
65
+ ["It's okay, nothing special", "English"]
66
+ ],
67
+ inputs=[text_input, language_input]
68
+ )
69
+
70
+ submit_btn.click(
71
+ fn=analyze_sentiment,
72
+ inputs=[text_input, language_input],
73
+ outputs=[sentiment_output, score_output]
74
+ )
75
+
76
+ demo.launch()