Maryaa4 commited on
Commit
eca771b
·
verified ·
1 Parent(s): 110260b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -79
app.py CHANGED
@@ -4,111 +4,54 @@ from fastapi import FastAPI, Request
4
  from transformers import pipeline
5
  import torch
6
 
7
- # ----------------------
8
- # 1) إعداد توكن البوت
9
- # ----------------------
10
- BOT_TOKEN = "8513655100:AAH5bgPDpXioJNW-o5IiNy6sqOVQvjvQXS0" # يفضل بعدين تحطيه من Secrets
11
  TELEGRAM_API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}"
12
 
13
- # ----------------------
14
- # 2) تحميل المودل مرة وحدة
15
- # ----------------------
16
- print("Loading model...")
17
 
18
  device = 0 if torch.cuda.is_available() else -1
 
19
  sentiment_pipeline = pipeline(
20
  "sentiment-analysis",
21
- model="maryaa4/my-arabic-sentiment-model",
22
- device=device,
23
- trust_remote_code=True
24
  )
25
 
26
- print(f"Model loaded. Device = {'cuda' if device == 0 else 'cpu'}")
27
 
28
- # ----------------------
29
- # 3) دوال التحليل والإرسال
30
- # ----------------------
31
- def analyze_text(text: str) -> str:
32
- text = text.strip()
33
- if not text:
34
- return "رجاءً أرسل لي نص عربي عشان أحلل مشاعره 🌟"
35
 
36
  result = sentiment_pipeline(text)[0]
37
  label = result["label"]
38
  score = result["score"]
39
 
40
- # نحاول نترجم الليبل للعربي + ايموجي لطيف
41
- lower_label = label.lower()
42
- if "pos" in lower_label:
43
- mood = "إيجابي"
44
- emoji = "😊✨"
45
- elif "neg" in lower_label:
46
- mood = "سلبي"
47
- emoji = "😔"
48
- else:
49
- mood = "محايد"
50
- emoji = "😐"
51
 
52
- reply = (
53
- f"🧠 *تحليل المشاعر:*\n"
54
- f"- التصنيف: {mood} ({label})\n"
55
- f"- نسبة الثقة: {score:.3f}\n\n"
56
- f"{emoji}"
57
  )
58
 
59
- # تيليجرام ما يحب الماركداون الغلط، فخليك حاليًا بدون parse_mode
60
- return reply
61
-
62
-
63
- def send_message(chat_id: int, text: str):
64
- try:
65
- requests.post(
66
- TELEGRAM_API_URL + "/sendMessage",
67
- json={
68
- "chat_id": chat_id,
69
- "text": text
70
- },
71
- timeout=10
72
- )
73
- except Exception as e:
74
- print("Error sending message:", e)
75
-
76
-
77
- # ----------------------
78
- # 4) تطبيق FastAPI + /telegram
79
- # ----------------------
80
- app = FastAPI()
81
-
82
  @app.post("/telegram")
83
  async def telegram_webhook(request: Request):
84
  update = await request.json()
85
- print("Incoming update:", update)
86
 
87
  if "message" not in update:
88
  return {"ok": True}
89
 
90
- message = update["message"]
91
- chat_id = message["chat"]["id"]
92
- text = message.get("text", "")
93
-
94
- if text == "/start":
95
- send_message(
96
- chat_id,
97
- "هلا 🤍\n"
98
- "أرسل لي أي جملة بالعربي، وأنا أقولك إذا إحساسها إيجابي، سلبي، أو محايد ✨"
99
- )
100
- return {"ok": True}
101
 
102
  reply = analyze_text(text)
103
- send_message(chat_id, reply)
104
 
105
  return {"ok": True}
106
 
107
-
108
- # ----------------------
109
- # 5) تشغيل السيرفر داخل الـ Space
110
- # ----------------------
111
- if __name__ == "__main__":
112
- import uvicorn
113
- # مهم جداً: هذا اللي يخلي السيرفر يشتغل وما يطلع Runtime error
114
- uvicorn.run("app:app", host="0.0.0.0", port=7860)
 
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"}