Spaces:
Sleeping
Sleeping
import gradio as gr | |
import numpy as np | |
import torch | |
from transformers import BertTokenizer, AutoModel | |
import tensorflow as tf | |
model_name = "aubmindlab/bert-base-arabertv02" | |
tokenizer = BertTokenizer.from_pretrained(model_name) | |
bert_model = AutoModel.from_pretrained(model_name) | |
bert_model.eval() | |
model = tf.keras.models.load_model("rnn_Bi.h5") | |
print("✅ Model loaded successfully!") | |
def get_bert_embedding(text, max_length=100): | |
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=max_length) | |
with torch.no_grad(): | |
outputs = bert_model(**inputs) | |
embedding = outputs.last_hidden_state[:, 0, :].numpy() | |
embedding = embedding.reshape(1, 1, 768) | |
return embedding | |
def predict_sentiment(text): | |
embedding = get_bert_embedding(text) | |
pred = model.predict(embedding)[0][0] | |
label = "إيجابي" if pred > 0.5 else "سلبي" | |
confidence = pred if pred > 0.5 else 1 - pred | |
return label, confidence | |
css = """ | |
body { | |
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; | |
direction: rtl; | |
text-align: right; | |
} | |
.gradio-container { | |
max-width: 600px; | |
margin: auto; | |
background: #f9f9f9; | |
padding: 20px; | |
border-radius: 12px; | |
box-shadow: 0 6px 15px rgb(0 0 0 / 0.1); | |
} | |
.gr-button { | |
background-color: #007bff !important; | |
color: white !important; | |
font-weight: bold; | |
border-radius: 8px !important; | |
padding: 10px 25px !important; | |
font-size: 16px !important; | |
} | |
.gr-textbox textarea { | |
font-size: 18px !important; | |
padding: 10px !important; | |
} | |
""" | |
with gr.Blocks(css=css) as iface: | |
gr.Markdown("## تحليل المشاعر بالعربية 📝", elem_id="title") | |
gr.Markdown("أدخل جملة لتحليل المشاعر: هل هي **إيجابية** أم **سلبية**؟", elem_id="description") | |
text_input = gr.Textbox(lines=3, placeholder="اكتب جملتك هنا...", label="النص") | |
predict_btn = gr.Button("تنبؤ") | |
sentiment_output = gr.Label(label="النتيجة") | |
confidence_score = gr.Textbox(label="نسبة الثقة") | |
def on_predict(text): | |
label, confidence = predict_sentiment(text) | |
confidence_percent = f"{confidence*100:.1f}%" | |
return label, confidence_percent | |
predict_btn.click(fn=on_predict, inputs=text_input, outputs=[sentiment_output, confidence_score]) | |
if __name__ == "__main__": | |
iface.launch() | |