shalabyelectronics commited on
Commit
5b3e8d0
·
verified ·
1 Parent(s): c55ce22

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -20
app.py CHANGED
@@ -3,41 +3,98 @@ import requests
3
  import os
4
  import json
5
 
 
6
  api_key = os.getenv("GEMINI_API_KEY")
7
 
8
- def check_api_key():
 
 
 
9
  if not api_key:
10
- return "خطأ: لم يتم العثور على المفتاح في الـ Secrets."
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- # نطلب من جوجل قائمة النماذج المتاحة لهذا المفتاح
13
- url = f"https://generativelanguage.googleapis.com/v1beta/models?key={api_key}"
 
 
14
 
 
 
 
 
 
 
 
 
 
 
 
15
  try:
16
- response = requests.get(url)
 
 
 
 
 
17
  data = response.json()
18
 
19
- if "error" in data:
20
- return f"❌ المفتاح لا يعمل. رسالة جوجل:\n{json.dumps(data['error'], indent=2, ensure_ascii=False)}"
 
21
 
22
- if "models" in data:
23
- # نستخرج أسماء النماذج فقط
24
- model_names = [m['name'] for m in data['models']]
25
 
26
- # تنسيق القائمة للعرض
27
- formatted_list = "\n".join(model_names)
28
- return f" المفتاح يعمل بنجاح!\n\nالنماذج المتاحة لك هي:\n----------------\n{formatted_list}"
29
-
30
- return f"⚠️ رد غير متوقع من جوجل:\n{data}"
 
 
 
 
 
 
 
 
31
 
32
  except Exception as e:
33
- return f"خطأ في الاتصال: {str(e)}"
34
 
 
35
  with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {direction: rtl; text-align: right;}") as demo:
36
- gr.Markdown("# 🛠️ فحص مفتاح API")
37
 
38
- btn = gr.Button("اضغط لفحص المفتاح والنماذج المتاحة", variant="primary")
39
- output = gr.Textbox(label="نتيجة الفحص", lines=15, text_align="left")
40
 
41
- btn.click(check_api_key, outputs=output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  demo.launch()
 
3
  import os
4
  import json
5
 
6
+ # 1. جلب المفتاح
7
  api_key = os.getenv("GEMINI_API_KEY")
8
 
9
+ def analyze_sentiment(text):
10
+ if not text:
11
+ return "يرجى إدخال نص.", "⚪"
12
+
13
  if not api_key:
14
+ return "خطأ: لم يتم العثور على مفتاح API Key.", "❌"
15
+
16
+ # 2. استخدام أقوى نموذج متاح في قائمتك (Gemini 2.5 Flash)
17
+ # لاحظ: قمنا بتغيير اسم النموذج هنا بناءً على القائمة التي ظهرت لك
18
+ model_name = "gemini-2.5-flash"
19
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_name}:generateContent?key={api_key}"
20
+
21
+ # 3. تجهيز الرسالة (Prompt) بتعليمات دقيقة
22
+ prompt_text = f"""
23
+ أنت نظام ذكي لتحليل المشاعر (Sentiment Analysis) للنصوص العربية (فصحى ولهجات).
24
+
25
+ النص المراد تحليله: "{text}"
26
 
27
+ المطلوب منك الرد بنسق JSON فقط يحتوي على:
28
+ - sentiment: (إيجابي، سلبي، أو محايد)
29
+ - reason: (سبب التصنيف في جملة قصيرة جداً)
30
+ - confidence: (نسبة مئوية تقديرية)
31
 
32
+ إذا لم تستطع الرد بـ JSON، اكتب النتيجة نصياً بشكل مختصر.
33
+ """
34
+
35
+ payload = {
36
+ "contents": [{
37
+ "parts": [{"text": prompt_text}]
38
+ }]
39
+ }
40
+
41
+ headers = {'Content-Type': 'application/json'}
42
+
43
  try:
44
+ # 4. الاتصال المباشر
45
+ response = requests.post(url, headers=headers, data=json.dumps(payload))
46
+
47
+ if response.status_code != 200:
48
+ return f"خطأ من جوجل ({response.status_code}): {response.text}", "❌"
49
+
50
  data = response.json()
51
 
52
+ # استخراج الرد
53
+ try:
54
+ result_text = data['candidates'][0]['content']['parts'][0]['text']
55
 
56
+ # تنظيف الرد
57
+ clean_result = result_text.replace("```json", "").replace("```", "").strip()
 
58
 
59
+ # تحديد الإيموجي واللون
60
+ emoji = "🤔"
61
+ if "إيجابي" in clean_result:
62
+ emoji = "🤩 إيجابي"
63
+ elif "سلبي" in clean_result:
64
+ emoji = "😡 سلبي"
65
+ else:
66
+ emoji = "😐 محايد"
67
+
68
+ return clean_result, emoji
69
+
70
+ except Exception as e:
71
+ return f"فشل استخراج الرد: {str(e)} \nالرد الخام: {str(data)}", "⚠️"
72
 
73
  except Exception as e:
74
+ return f"خطأ في الاتصال: {str(e)}", "❌ فشل"
75
 
76
+ # 5. تصميم واجهة انطباع (Entibaa) الاحترافية
77
  with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {direction: rtl; text-align: right;}") as demo:
 
78
 
79
+ with gr.Row():
80
+ gr.Markdown("# 📊 تطبيق انطباع (Entibaa)")
81
 
82
+ gr.Markdown(f"### يتم العمل الآن بواسطة محرك: **Gemini 2.5 Flash** ⚡")
83
+
84
+ with gr.Row():
85
+ input_text = gr.Textbox(
86
+ label="أدخل التعليق هنا لتحليله",
87
+ placeholder="مثال: التجربة كانت ممتازة والخدمة سريعة...",
88
+ lines=3,
89
+ text_align="right"
90
+ )
91
+
92
+ analyze_btn = gr.Button("تحليل الانطباع 🚀", variant="primary")
93
+
94
+ with gr.Row():
95
+ output_text = gr.Textbox(label="تقرير التحليل المفصل", lines=4, text_align="right")
96
+ sentiment_badge = gr.Label(label="النتيجة النهائية")
97
+
98
+ analyze_btn.click(analyze_sentiment, inputs=input_text, outputs=[output_text, sentiment_badge])
99
 
100
  demo.launch()