Upload app.py with huggingface_hub
Browse files
app.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
import joblib
|
| 3 |
+
import numpy as np
|
| 4 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
app = Flask(__name__)
|
| 8 |
+
|
| 9 |
+
# تحميل النموذج والمكونات
|
| 10 |
+
print("Loading model components...")
|
| 11 |
+
model = joblib.load("model.pkl")
|
| 12 |
+
vectorizer = joblib.load("vectorizer.pkl")
|
| 13 |
+
label_encoder = joblib.load("label_encoder.pkl")
|
| 14 |
+
print("Model loaded successfully!")
|
| 15 |
+
|
| 16 |
+
def preprocess_text(text):
|
| 17 |
+
"""تنظيف النص قبل التصنيف"""
|
| 18 |
+
text = text.lower()
|
| 19 |
+
text = re.sub(r'[^a-zA-Z\s]', ' ', text)
|
| 20 |
+
text = re.sub(r'\s+', ' ', text)
|
| 21 |
+
return text.strip()
|
| 22 |
+
|
| 23 |
+
@app.route('/predict', methods=['POST'])
|
| 24 |
+
def predict():
|
| 25 |
+
"""نقطة النهاية للتنبؤ"""
|
| 26 |
+
try:
|
| 27 |
+
# الحصول على البيانات
|
| 28 |
+
data = request.get_json()
|
| 29 |
+
|
| 30 |
+
if 'text' not in data:
|
| 31 |
+
return jsonify({'error': 'No text provided'}), 400
|
| 32 |
+
|
| 33 |
+
text = data['text']
|
| 34 |
+
|
| 35 |
+
# المعالجة المسبقة
|
| 36 |
+
processed_text = preprocess_text(text)
|
| 37 |
+
|
| 38 |
+
# تحويل النص إلى ميزات
|
| 39 |
+
features = vectorizer.transform([processed_text])
|
| 40 |
+
|
| 41 |
+
# التنبؤ
|
| 42 |
+
prediction = model.predict(features)[0]
|
| 43 |
+
sentiment = label_encoder.inverse_transform([prediction])[0]
|
| 44 |
+
|
| 45 |
+
# الحصول على احتمالية التصنيف إذا كانت متاحة
|
| 46 |
+
confidence = 0.85 # قيمة افتراضية
|
| 47 |
+
if hasattr(model, 'predict_proba'):
|
| 48 |
+
proba = model.predict_proba(features)
|
| 49 |
+
confidence = np.max(proba) * 100
|
| 50 |
+
|
| 51 |
+
# إرجاع النتيجة
|
| 52 |
+
result = {
|
| 53 |
+
'text': text,
|
| 54 |
+
'sentiment': sentiment,
|
| 55 |
+
'confidence': float(confidence),
|
| 56 |
+
'status': 'success'
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
return jsonify(result), 200
|
| 60 |
+
|
| 61 |
+
except Exception as e:
|
| 62 |
+
return jsonify({'error': str(e), 'status': 'error'}), 500
|
| 63 |
+
|
| 64 |
+
@app.route('/batch_predict', methods=['POST'])
|
| 65 |
+
def batch_predict():
|
| 66 |
+
"""نقطة النهاية للتنبؤ المجمّع"""
|
| 67 |
+
try:
|
| 68 |
+
data = request.get_json()
|
| 69 |
+
|
| 70 |
+
if 'texts' not in data:
|
| 71 |
+
return jsonify({'error': 'No texts provided'}), 400
|
| 72 |
+
|
| 73 |
+
texts = data['texts']
|
| 74 |
+
|
| 75 |
+
if not isinstance(texts, list):
|
| 76 |
+
return jsonify({'error': 'Texts must be a list'}), 400
|
| 77 |
+
|
| 78 |
+
results = []
|
| 79 |
+
for text in texts:
|
| 80 |
+
processed_text = preprocess_text(text)
|
| 81 |
+
features = vectorizer.transform([processed_text])
|
| 82 |
+
prediction = model.predict(features)[0]
|
| 83 |
+
sentiment = label_encoder.inverse_transform([prediction])[0]
|
| 84 |
+
|
| 85 |
+
if hasattr(model, 'predict_proba'):
|
| 86 |
+
proba = model.predict_proba(features)
|
| 87 |
+
confidence = np.max(proba) * 100
|
| 88 |
+
else:
|
| 89 |
+
confidence = 85.0
|
| 90 |
+
|
| 91 |
+
results.append({
|
| 92 |
+
'text': text[:100] + '...' if len(text) > 100 else text,
|
| 93 |
+
'sentiment': sentiment,
|
| 94 |
+
'confidence': float(confidence)
|
| 95 |
+
})
|
| 96 |
+
|
| 97 |
+
return jsonify({
|
| 98 |
+
'results': results,
|
| 99 |
+
'count': len(results),
|
| 100 |
+
'status': 'success'
|
| 101 |
+
}), 200
|
| 102 |
+
|
| 103 |
+
except Exception as e:
|
| 104 |
+
return jsonify({'error': str(e), 'status': 'error'}), 500
|
| 105 |
+
|
| 106 |
+
@app.route('/health', methods=['GET'])
|
| 107 |
+
def health():
|
| 108 |
+
"""نقطة النهاية للتحقق من صحة الخدمة"""
|
| 109 |
+
return jsonify({'status': 'healthy', 'model': str(type(model).__name__)}), 200
|
| 110 |
+
|
| 111 |
+
@app.route('/')
|
| 112 |
+
def home():
|
| 113 |
+
"""الصفحة الرئيسية"""
|
| 114 |
+
return '''
|
| 115 |
+
<h1>📚 Amazon Books Sentiment Analysis API</h1>
|
| 116 |
+
<p>استخدم نقاط النهاية التالية:</p>
|
| 117 |
+
<ul>
|
| 118 |
+
<li><code>POST /predict</code> - تحليل مشاعر مراجعة واحدة</li>
|
| 119 |
+
<li><code>POST /batch_predict</code> - تحليل مجموعة مراجعات</li>
|
| 120 |
+
<li><code>GET /health</code> - التحقق من صحة الخدمة</li>
|
| 121 |
+
</ul>
|
| 122 |
+
'''
|
| 123 |
+
|
| 124 |
+
if __name__ == '__main__':
|
| 125 |
+
app.run(host='0.0.0.0', port=5000, debug=True)
|