Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,104 +1,75 @@
|
|
| 1 |
import os
|
| 2 |
import requests
|
|
|
|
| 3 |
from fastapi import FastAPI, Request
|
|
|
|
| 4 |
|
| 5 |
-
#
|
|
|
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
BOT_TOKEN = os.getenv("TELEGRAM_TOKEN") # برضه من Secrets
|
| 13 |
-
TELEGRAM_API = (
|
| 14 |
-
f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
|
| 15 |
-
if BOT_TOKEN
|
| 16 |
-
else None
|
| 17 |
)
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def analyze_sentiment(text: str) -> str:
|
| 23 |
-
"""
|
| 24 |
-
ينادي Hugging Face Inference API ويحلل المشاعر
|
| 25 |
-
"""
|
| 26 |
-
if not HF_TOKEN:
|
| 27 |
-
return "❌ HF_TOKEN مفقود في Secrets حق السبيس"
|
| 28 |
-
|
| 29 |
-
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 30 |
-
payload = {"inputs": text}
|
| 31 |
|
| 32 |
-
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
|
| 35 |
-
if resp.status_code != 200:
|
| 36 |
-
return f"❌ Error from HF API: {resp.status_code} - {resp.text}"
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
else:
|
| 47 |
-
result = data[0]
|
| 48 |
-
else:
|
| 49 |
-
return f"⚠️ Unexpected HF response structure: {data}"
|
| 50 |
-
|
| 51 |
-
label = result["label"]
|
| 52 |
-
score = result["score"]
|
| 53 |
-
except Exception:
|
| 54 |
-
return f"⚠️ Unexpected HF response content: {data}"
|
| 55 |
-
|
| 56 |
-
label_lower = label.lower()
|
| 57 |
-
if "pos" in label_lower:
|
| 58 |
-
label_ar = "إيجابي 🌿"
|
| 59 |
-
elif "neg" in label_lower:
|
| 60 |
-
label_ar = "سلبي 💔"
|
| 61 |
-
elif "neu" in label_lower:
|
| 62 |
-
label_ar = "محايد 😐"
|
| 63 |
-
else:
|
| 64 |
-
label_ar = label
|
| 65 |
-
|
| 66 |
-
return f"التصنيف: {label_ar}\nنسبة الثقة: {score:.2f}"
|
| 67 |
|
|
|
|
| 68 |
|
| 69 |
-
|
| 70 |
-
def root():
|
| 71 |
-
return {
|
| 72 |
-
"status": "ok",
|
| 73 |
-
"message": "Telegram webhook for Arabic sentiment bot is running ✅",
|
| 74 |
-
}
|
| 75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
-
@app.post("/")
|
| 78 |
async def telegram_webhook(request: Request):
|
| 79 |
"""
|
| 80 |
-
هذا
|
| 81 |
"""
|
| 82 |
data = await request.json()
|
| 83 |
-
print("📩
|
| 84 |
|
| 85 |
-
# نتأكد إن فيه رسالة نصية
|
| 86 |
if "message" in data and "text" in data["message"]:
|
| 87 |
chat_id = data["message"]["chat"]["id"]
|
| 88 |
user_text = data["message"]["text"]
|
| 89 |
|
| 90 |
-
|
| 91 |
|
| 92 |
if TELEGRAM_API:
|
| 93 |
try:
|
| 94 |
r = requests.post(
|
| 95 |
TELEGRAM_API,
|
| 96 |
-
json={"chat_id": chat_id, "text":
|
|
|
|
| 97 |
)
|
| 98 |
-
print("
|
| 99 |
except Exception as e:
|
| 100 |
-
print("Error sending
|
| 101 |
-
|
| 102 |
-
|
| 103 |
|
| 104 |
-
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
+
import gradio as gr
|
| 4 |
from fastapi import FastAPI, Request
|
| 5 |
+
from transformers import pipeline
|
| 6 |
|
| 7 |
+
# ============ 1) تحميل الموديل من هجينغ فيس ============
|
| 8 |
+
deployed_repo_id = "maryaa4/my-arabic-sentiment-model"
|
| 9 |
|
| 10 |
+
loaded_sentiment_pipeline = pipeline(
|
| 11 |
+
"sentiment-analysis",
|
| 12 |
+
model=deployed_repo_id,
|
| 13 |
+
trust_remote_code=True,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
)
|
| 15 |
|
| 16 |
+
def predict_sentiment(text: str) -> str:
|
| 17 |
+
if not text or text.strip() == "":
|
| 18 |
+
return "رجاءً أدخل نص عربي عشان أقدر أحلله 📝"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
+
result = loaded_sentiment_pipeline(text)
|
| 21 |
+
label = result[0]["label"]
|
| 22 |
+
score = result[0]["score"]
|
| 23 |
|
| 24 |
+
return f"التصنيف: {label}\nنسبة الثقة: {score:.2f}"
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
# ============ 2) واجهة Gradio (عشان السبيس يشتغل طبيعي) ============
|
| 27 |
+
demo = gr.Interface(
|
| 28 |
+
fn=predict_sentiment,
|
| 29 |
+
inputs=gr.Textbox(lines=5, placeholder="أدخل النص العربي هنا..."),
|
| 30 |
+
outputs="text",
|
| 31 |
+
title="Arabic Sentiment Analysis",
|
| 32 |
+
description="تحليل مشاعر للنصوص العربية باستخدام الموديل maryaa4/my-arabic-sentiment-model",
|
| 33 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
# ============ 3) FastAPI + Telegram Webhook ============
|
| 36 |
|
| 37 |
+
app = FastAPI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
BOT_TOKEN = os.getenv("TELEGRAM_TOKEN") # حطي التوكن في Secrets باسم TELEGRAM_TOKEN
|
| 40 |
+
if BOT_TOKEN:
|
| 41 |
+
TELEGRAM_API = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
|
| 42 |
+
else:
|
| 43 |
+
TELEGRAM_API = None
|
| 44 |
+
print("⚠️ TELEGRAM_TOKEN مش موجود في Secrets، البوت ما راح يقدر يرسل ردود لتيليجرام.")
|
| 45 |
|
| 46 |
+
@app.post("/telegram")
|
| 47 |
async def telegram_webhook(request: Request):
|
| 48 |
"""
|
| 49 |
+
هذا المسار اللي تيليجرام بيناديه لما يجي رسالة للبوت.
|
| 50 |
"""
|
| 51 |
data = await request.json()
|
| 52 |
+
print("📩 Webhook data:", data)
|
| 53 |
|
|
|
|
| 54 |
if "message" in data and "text" in data["message"]:
|
| 55 |
chat_id = data["message"]["chat"]["id"]
|
| 56 |
user_text = data["message"]["text"]
|
| 57 |
|
| 58 |
+
reply = predict_sentiment(user_text)
|
| 59 |
|
| 60 |
if TELEGRAM_API:
|
| 61 |
try:
|
| 62 |
r = requests.post(
|
| 63 |
TELEGRAM_API,
|
| 64 |
+
json={"chat_id": chat_id, "text": reply},
|
| 65 |
+
timeout=10
|
| 66 |
)
|
| 67 |
+
print("✅ Sent to Telegram, status:", r.status_code, r.text)
|
| 68 |
except Exception as e:
|
| 69 |
+
print("❌ Error sending to Telegram:", e)
|
| 70 |
+
|
| 71 |
+
return {"ok": True}
|
| 72 |
|
| 73 |
+
# ============ 4) ربط Gradio مع FastAPI ============
|
| 74 |
+
# يخلي واجهة Gradio على "/" والويبهوك على "/telegram"
|
| 75 |
+
app = gr.mount_gradio_app(app, demo, path="/")
|