Maryaa4 commited on
Commit
a550529
·
verified ·
1 Parent(s): 7c9adbd

Update app.py

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