Spaces:
Sleeping
Sleeping
File size: 2,529 Bytes
3ada054 a550529 3ada054 a550529 86f94e0 a550529 eca771b a550529 3ada054 eca771b ee4c373 110260b a550529 110260b a550529 110260b ee4c373 7e3c920 110260b a550529 07ee7c0 a550529 3ada054 a550529 110260b a550529 110260b a550529 07ee7c0 a550529 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
import os
import requests
from fastapi import FastAPI, Request
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TextClassificationPipeline
# توكن تيلقرام (قدري تحطينه هنا مباشرة)
TELEGRAM_BOT_TOKEN = os.getenv(
"TELEGRAM_BOT_TOKEN",
"8513655100:AAH5bgPDpXioJNW-o5IiNy6sqOVQvjvQXS0" # استبدليه لو غيرتي التوكن
)
# موديل المشاعر من هقنق فيس
MODEL_ID = "maryaa4/my-arabic-sentiment-model"
print("Loading model...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID)
pipeline = TextClassificationPipeline(model=model, tokenizer=tokenizer, return_all_scores=False)
print("Model loaded. Device set to CPU.")
app = FastAPI()
@app.get("/")
async def root():
# عشان صفحة السبيس ما تعطي 404
return {"status": "ok", "message": "Telegram webhook is at /telegram"}
def analyze_sentiment(text: str) -> str:
if not text:
return "أرسل لي جملة عربية عشان أحلل مشاعرها 😊"
result = pipeline(text)[0]
label = result["label"]
score = result["score"]
return f"التصنيف: {label} — الثقة: {score:.2f}"
@app.post("/telegram")
async def telegram_webhook(request: Request):
"""
هذا الإندبوينت يستقبل تحديثات تيلقرام كـ JSON
ويرد على نفس الشات باستعمال sendMessage
"""
try:
update = await request.json()
# ناخذ المرسلة الأساسية (لو رسالة جديدة أو معدلة)
message = update.get("message") or update.get("edited_message") or {}
chat = message.get("chat") or {}
chat_id = chat.get("id")
# لو مافي شات آي دي، نطلع بس بدون ما نسوي شيء
if not chat_id:
return {"ok": True}
text = message.get("text") or ""
reply_text = analyze_sentiment(text)
# نرسل الرد لتيلقرام
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
payload = {
"chat_id": chat_id,
"text": reply_text,
}
requests.post(url, json=payload)
except Exception as e:
# تطبعين الخطأ في اللوق لو حبيتي تشوفين وش صار
print("Error in /telegram webhook:", e)
# لازم نرجع 200 لتيلقرام
return {"ok": True} |