ahmedyoussef1 commited on
Commit
59ea8c7
·
verified ·
1 Parent(s): 0746ad2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -15
app.py CHANGED
@@ -1,23 +1,47 @@
 
 
 
 
1
  import tensorflow as tf
2
- from transformers import BertTokenizer
3
 
4
- # تحميل tokenizer من الملفات اللي في نفس المسار
5
- tokenizer = BertTokenizer.from_pretrained(".")
 
 
 
6
 
7
- # تحميل الموديل
8
  model = tf.keras.models.load_model("rnn_Bi.h5")
9
  print("✅ Model loaded successfully!")
10
 
11
- # تجربة بسيطة لتنبؤ
12
- test_sentence = "I love this movie!"
13
- tokens = tokenizer(
14
- test_sentence,
15
- padding='max_length',
16
- truncation=True,
17
- max_length=128,
18
- return_tensors="np"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  )
20
 
21
- input_ids = tokens["input_ids"]
22
- prediction = model.predict(input_ids)[0][0]
23
- print(f"Prediction: {prediction}")
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import torch
4
+ from transformers import BertTokenizer, AutoModel
5
  import tensorflow as tf
 
6
 
7
+ # Load tokenizer and BERT model for embeddings extraction
8
+ model_name = "aubmindlab/bert-base-arabertv02"
9
+ tokenizer = BertTokenizer.from_pretrained(model_name)
10
+ bert_model = AutoModel.from_pretrained(model_name)
11
+ bert_model.eval()
12
 
13
+ # Load your trained RNN model
14
  model = tf.keras.models.load_model("rnn_Bi.h5")
15
  print("✅ Model loaded successfully!")
16
 
17
+ def get_bert_embedding(text, max_length=100):
18
+ inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=max_length)
19
+ with torch.no_grad():
20
+ outputs = bert_model(**inputs)
21
+ # Use CLS token embedding as sentence embedding
22
+ embedding = outputs.last_hidden_state[:, 0, :].numpy()
23
+ embedding = embedding.reshape(1, 1, 768) # shape (1, 1, 768)
24
+ return embedding
25
+
26
+ def predict_sentiment(text):
27
+ embedding = get_bert_embedding(text)
28
+ pred = model.predict(embedding)[0][0]
29
+ label = "Positive" if pred > 0.5 else "Negative"
30
+ confidence = pred if pred > 0.5 else 1 - pred
31
+ return label, f"Confidence: {confidence:.2f}"
32
+
33
+ # Build Gradio interface
34
+ iface = gr.Interface(
35
+ fn=predict_sentiment,
36
+ inputs=gr.Textbox(lines=2, placeholder="اكتب الجملة هنا..."),
37
+ outputs=[
38
+ gr.Label(num_top_classes=2, label="Sentiment"),
39
+ gr.Textbox(label="Confidence Score")
40
+ ],
41
+ title="Arabic Sentiment Analysis",
42
+ description="اكتب جملة لتحليل المشاعر (إيجابي أو سلبي)",
43
+ theme="default"
44
  )
45
 
46
+ if __name__ == "__main__":
47
+ iface.launch()