Maryaa4 commited on
Commit
b816b41
·
verified ·
1 Parent(s): 7e3c920

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -28
app.py CHANGED
@@ -4,72 +4,72 @@ import gradio as gr
4
  from fastapi import FastAPI, Request
5
  from transformers import pipeline
6
 
7
- # ============ 1) تحميل الموديل من هجينغ فيس ============
8
- deployed_repo_id = "maryaa4/my-arabic-sentiment-model"
9
 
 
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: str) -> str:
17
- if not text or text.strip() == "":
18
- return "رجاءً أدخل نص عربي عشان أقدر أحلله 📝"
19
-
20
  result = loaded_sentiment_pipeline(text)
21
- label = result[0]["label"]
22
- score = result[0]["score"]
 
23
 
24
- return f"التصنيف: {label}\nنسبة الثقة: {score:.2f}"
25
-
26
- # ============ 2) واجهة Gradio (عشان السبيس يشتغل طبيعي) ============
27
- demo = gr.Interface(
28
  fn=predict_sentiment,
29
  inputs=gr.Textbox(lines=5, placeholder="أدخل النص العربي هنا..."),
30
  outputs="text",
31
  title="Arabic Sentiment Analysis",
32
- description="تحليل مشاعر للنصوص العربية باستخدام الموديل maryaa4/my-arabic-sentiment-model",
 
 
 
33
  )
34
 
35
- # ============ 3) FastAPI + Telegram Webhook ============
36
 
37
  app = FastAPI()
38
 
39
- BOT_TOKEN = os.getenv("TELEGRAM_TOKEN") # حطي التوكن في Secrets باسم 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 مش موجود في Secrets، البوت ما راح يقدر يرسل ردود لتيليجرام.")
45
 
46
  @app.post("/telegram")
47
  async def telegram_webhook(request: Request):
48
- """
49
- هذا المسار اللي تيليجرام بيناديه لما يجي رسالة للبوت.
50
- """
51
  data = await request.json()
52
- print("📩 Webhook data:", data)
53
 
54
  if "message" in data and "text" in data["message"]:
55
  chat_id = data["message"]["chat"]["id"]
56
  user_text = data["message"]["text"]
57
 
58
- reply = predict_sentiment(user_text)
59
 
60
  if TELEGRAM_API:
61
  try:
62
  r = requests.post(
63
  TELEGRAM_API,
64
- json={"chat_id": chat_id, "text": reply},
65
- timeout=10
66
  )
67
- print("✅ Sent to Telegram, status:", r.status_code, r.text)
68
  except Exception as e:
69
  print("❌ Error sending to Telegram:", e)
70
 
71
  return {"ok": True}
72
 
73
- # ============ 4) ربط Gradio مع FastAPI ============
74
- # يخلي واجهة Gradio على "/" والويبهوك على "/telegram"
75
- app = gr.mount_gradio_app(app, demo, path="/")
 
 
 
 
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="/")