Maryaa4 commited on
Commit
ee4c373
·
verified ·
1 Parent(s): 37b8966

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -13
app.py CHANGED
@@ -2,12 +2,14 @@ import os
2
  import requests
3
  from fastapi import FastAPI, Request
4
 
5
- # رابط الـ Inference API لموديلك
6
- HF_MODEL_URL = "https://api-inference.huggingface.co/models/maryaa4/my-arabic-sentiment-model"
7
 
8
- HF_TOKEN = os.getenv("HF_TOKEN")
9
- BOT_TOKEN = os.getenv("TELEGRAM_TOKEN")
10
 
 
 
 
11
  TELEGRAM_API = (
12
  f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
13
  if BOT_TOKEN
@@ -16,26 +18,40 @@ TELEGRAM_API = (
16
 
17
  app = FastAPI()
18
 
19
- def call_hf_model(text: str) -> str:
 
 
 
 
20
  if not HF_TOKEN:
21
- return "❌ مفقود HF_TOKEN في Secrets حق السبيس"
22
 
23
  headers = {"Authorization": f"Bearer {HF_TOKEN}"}
24
  payload = {"inputs": text}
25
 
26
- resp = requests.post(HF_MODEL_URL, headers=headers, json=payload)
27
 
 
28
  if resp.status_code != 200:
29
  return f"❌ Error from HF API: {resp.status_code} - {resp.text}"
30
 
31
  data = resp.json()
32
- # متوقع يرجع list فيها dict زي: [{"label": "...", "score": 0.9}]
 
33
  try:
34
- result = data[0]
 
 
 
 
 
 
 
 
35
  label = result["label"]
36
  score = result["score"]
37
  except Exception:
38
- return f"⚠️ Unexpected HF response: {data}"
39
 
40
  label_lower = label.lower()
41
  if "pos" in label_lower:
@@ -49,20 +65,29 @@ def call_hf_model(text: str) -> str:
49
 
50
  return f"التصنيف: {label_ar}\nنسبة الثقة: {score:.2f}"
51
 
 
52
  @app.get("/")
53
  def root():
54
- return {"status": "ok", "message": "Telegram bot webhook for Arabic sentiment is running."}
 
 
 
 
55
 
56
  @app.post("/")
57
  async def telegram_webhook(request: Request):
 
 
 
58
  data = await request.json()
59
  print("📩 Incoming update:", data)
60
 
 
61
  if "message" in data and "text" in data["message"]:
62
  chat_id = data["message"]["chat"]["id"]
63
  user_text = data["message"]["text"]
64
 
65
- reply_text = call_hf_model(user_text)
66
 
67
  if TELEGRAM_API:
68
  try:
@@ -74,6 +99,6 @@ async def telegram_webhook(request: Request):
74
  except Exception as e:
75
  print("Error sending message to Telegram:", e)
76
  else:
77
- print("❌ TELEGRAM_API is None (ما لقيت TELEGRAM_TOKEN في Secrets)")
78
 
79
  return {"ok": True}
 
2
  import requests
3
  from fastapi import FastAPI, Request
4
 
5
+ # ========= 1) إعدادات Hugging Face Model =========
 
6
 
7
+ HF_API_URL = "https://api-inference.huggingface.co/models/maryaa4/my-arabic-sentiment-model"
8
+ HF_TOKEN = os.getenv("HF_TOKEN") # نجيبه من Secrets
9
 
10
+ # ========= 2) إعدادات Telegram Bot =========
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
 
18
 
19
  app = FastAPI()
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
+ resp = requests.post(HF_API_URL, headers=headers, json=payload)
33
 
34
+ # لو رجع خطأ من API
35
  if resp.status_code != 200:
36
  return f"❌ Error from HF API: {resp.status_code} - {resp.text}"
37
 
38
  data = resp.json()
39
+
40
+ # متوقع يرجع زي: [[{"label": "POSITIVE", "score": 0.95}]]
41
  try:
42
+ # بعض الموديلات ترجع list جوّا list، نجرب الحالتين
43
+ if isinstance(data, list) and len(data) > 0:
44
+ if isinstance(data[0], list):
45
+ result = data[0][0]
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:
 
65
 
66
  return f"التصنيف: {label_ar}\nنسبة الثقة: {score:.2f}"
67
 
68
+
69
  @app.get("/")
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("📩 Incoming update:", data)
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
+ reply_text = analyze_sentiment(user_text)
91
 
92
  if TELEGRAM_API:
93
  try:
 
99
  except Exception as e:
100
  print("Error sending message to Telegram:", e)
101
  else:
102
+ print("❌ TELEGRAM_TOKEN مفقود في Secrets (TELEGRAM_API = None)")
103
 
104
  return {"ok": True}