iMeshal's picture
Create app.py
14a721d verified
import gradio as gr
from transformers import pipeline
import torch
# -----------------------------------------------------------------
# 1. تحديد الحد الأقصى للطول (نفس الذي استخدمته في التدريب)
MAX_LENGTH = 512
# 2. تحميل المودل الخاص بك من الـ Hub
# سيقوم "pipeline" بتحميل المودل والتوكنايزر الخاص بك
# (iMeshal/arabic-sentiment-classifier-marbert)
# device=0 لاستخدام الـ GPU (إذا كان متاحاً في الـ Space)
print("Loading model pipeline...")
try:
pipe = pipeline(
"sentiment-analysis",
model="iMeshal/arabic-sentiment-classifier-marbert",
device=0 if torch.cuda.is_available() else -1
)
print("Model loaded successfully.")
except Exception as e:
print(f"Error loading model: {e}")
pipe = None # تعيينه كـ None ليتم التعامل معه لاحقاً
# -----------------------------------------------------------------
# 3. دالة التنبؤ (التي ستتصل بـ Gradio)
def predict_sentiment(text):
# رسالة خطأ إذا لم يتم تحميل المودل
if pipe is None:
return "حدث خطأ فادح: لم يتم تحميل المودل. يرجى مراجعة سجلات الـ Space."
# 3.1. التحقق من الطول (كما طلبت)
if len(text) > MAX_LENGTH:
return f"⚠️ النص طويل جدًا! الحد الأقصى هو {MAX_LENGTH} حرف."
if len(text.strip()) == 0:
return "⚠️ الرجاء إدخال نص."
# 3.2. إرسال النص إلى المودل
try:
result = pipe(text)[0] # نحصل على النتيجة الأولى
# 3.3. تنسيق المخرجات
label = result['label']
score = result['score']
# المودل يُرجع LABEL_0 (سلبي) و LABEL_1 (إيجابي)
if label == 'LABEL_1':
sentiment = "🟢 إيجابي"
else:
sentiment = "🔴 سلبي"
return f"{sentiment} (بثقة: {score:.2%})"
except Exception as e:
return f"حدث خطأ أثناء التحليل: {str(e)}"
# -----------------------------------------------------------------
# 4. بناء واجهة Gradio
iface = gr.Interface(
fn=predict_sentiment,
inputs=gr.Textbox(
lines=4,
placeholder="اكتب تغريدة أو جملة عربية هنا..."
),
outputs=gr.Text(),
title="📊 MARBERT لتحليل المشاعر العربية",
description=f"أدخل نصًا (بحد أقصى {MAX_LENGTH} حرف) لمعرفة ما إذا كان إيجابيًا أم سلبيًا. (المودل: iMeshal/arabic-sentiment-classifier-marbert)",
examples=[
["هذا المنتج رائع جداً وأنصح به بشدة"],
["أسوأ خدمة عملاء واجهتها على الإطلاق"],
["الجو اليوم جميل لكنه حار قليلاً"]
],
allow_flagging="never" # لإخفاء زر "Flag"
)
# 5. تشغيل الواجهة
iface.launch()