RawadAlghamdi's picture
Create app.py
8533898 verified
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()