Maryaa4 commited on
Commit
86f94e0
·
verified ·
1 Parent(s): b816b41

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -46
app.py CHANGED
@@ -1,75 +1,65 @@
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) نفس كودك القديم حق الموديل + Gradio =====
8
-
9
  deployed_repo_id = "maryaa4/my-arabic-sentiment-model"
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):
17
- if not text:
18
- return "Please enter some text for sentiment analysis."
19
- result = loaded_sentiment_pipeline(text)
20
- label = result[0]['label']
21
- score = result[0]['score']
22
- return f"Sentiment: {label.capitalize()}, Confidence: {score:.4f}"
23
-
24
- iface = gr.Interface(
25
- fn=predict_sentiment,
26
- inputs=gr.Textbox(lines=5, placeholder="أدخل النص العربي هنا..."),
27
- outputs="text",
28
- title="Arabic Sentiment Analysis",
29
- description=(
30
- "A sentiment analysis model for Arabic text, deployed from "
31
- "maryaa4/my-arabic-sentiment-model. Enter Arabic text and get the predicted sentiment."
32
- ),
33
- )
34
-
35
- # ===== 2) إعداد FastAPI للبوت =====
36
 
 
37
  app = FastAPI()
38
 
 
39
  BOT_TOKEN = os.getenv("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 is not set. Telegram bot will not be able to reply.")
 
 
 
 
45
 
46
  @app.post("/telegram")
47
  async def telegram_webhook(request: Request):
 
 
 
48
  data = await request.json()
49
  print("📩 Incoming update:", data)
50
 
51
- if "message" in data and "text" in data["message"]:
52
- chat_id = data["message"]["chat"]["id"]
53
- user_text = data["message"]["text"]
54
-
55
- reply_text = predict_sentiment(user_text)
56
 
57
- if TELEGRAM_API:
58
- try:
59
- r = requests.post(
60
- TELEGRAM_API,
61
- json={"chat_id": chat_id, "text": reply_text},
62
- timeout=10,
63
- )
64
- print("✅ Sent to Telegram:", r.status_code, r.text)
65
- except Exception as e:
66
- print("❌ Error sending to Telegram:", e)
67
 
68
- return {"ok": True}
69
 
70
- # ===== 3) نركّب Gradio فوق FastAPI =====
 
 
 
 
 
 
 
 
 
71
 
72
- # كذا:
73
- # - "/" → يفتح واجهة Gradio (ما يلزم تفتحينه أبدًا)
74
- # - "/telegram" → يستخدمه تيليجرام Webhook
75
- app = gr.mount_gradio_app(app, iface, path="/")
 
1
  import os
2
  import requests
 
3
  from fastapi import FastAPI, Request
4
  from transformers import pipeline
5
 
6
+ # ========== 1) تحميل الموديل ==========
 
7
  deployed_repo_id = "maryaa4/my-arabic-sentiment-model"
8
+
9
+ sentiment_pipeline = pipeline(
10
  "sentiment-analysis",
11
  model=deployed_repo_id,
12
  trust_remote_code=True
13
  )
14
 
15
+ def predict_sentiment(text: str) -> str:
16
+ if not text or text.strip() == "":
17
+ return "رجاءً أرسل نص عربي عشان أقدر أحلله 🙂"
18
+ result = sentiment_pipeline(text)
19
+ label = result[0]["label"]
20
+ score = result[0]["score"]
21
+ return f"التصنيف: {label}\nدرجة الثقة: {score:.2f}"
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # ========== 2) FastAPI app ==========
24
  app = FastAPI()
25
 
26
+ # توكن تيليجرام من Secrets
27
  BOT_TOKEN = os.getenv("TELEGRAM_TOKEN")
28
  if BOT_TOKEN:
29
  TELEGRAM_API = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
30
  else:
31
  TELEGRAM_API = None
32
+ print("⚠️ TELEGRAM_TOKEN is not set. Telegram replies will fail.")
33
+
34
+ @app.get("/")
35
+ async def root():
36
+ return {"status": "ok", "message": "ArabicSentimentBoot is running."}
37
 
38
  @app.post("/telegram")
39
  async def telegram_webhook(request: Request):
40
+ """
41
+ هذا المسار اللي تيليجرام يستدعيه كـ Webhook
42
+ """
43
  data = await request.json()
44
  print("📩 Incoming update:", data)
45
 
46
+ if "message" not in data or "text" not in data["message"]:
47
+ return {"ok": True}
 
 
 
48
 
49
+ chat_id = data["message"]["chat"]["id"]
50
+ user_text = data["message"]["text"]
 
 
 
 
 
 
 
 
51
 
52
+ reply_text = predict_sentiment(user_text)
53
 
54
+ if TELEGRAM_API:
55
+ try:
56
+ r = requests.post(
57
+ TELEGRAM_API,
58
+ json={"chat_id": chat_id, "text": reply_text},
59
+ timeout=10,
60
+ )
61
+ print("✅ Sent to Telegram:", r.status_code, r.text)
62
+ except Exception as e:
63
+ print("❌ Error sending message to Telegram:", e)
64
 
65
+ return {"ok": True}