Download app.py from Batoul2005/Performance_Indicators: direct link, hf CLI and curl.
- Browser
- Download file 4.49 kB
-
https://huggingface.co/spaces/Batoul2005/Performance_Indicators/resolve/main/app.py
- Command line
-
hf download hf://spaces/Batoul2005/Performance_Indicators/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Batoul2005/Performance_Indicators/resolve/main/app.py
4.49 kB
| import os, json, re | |
| from pathlib import Path | |
| from typing import Any | |
| import gradio as gr | |
| import requests | |
| BASE_DIR = Path(__file__).parent | |
| MODEL = os.getenv("HF_MODEL", "Qwen/Qwen2.5-7B-Instruct") | |
| TOKEN = os.getenv("HF_TOKEN", "") | |
| API_URL = "https://router.huggingface.co/v1/chat/completions" | |
| def call_qwen(task: str, data: Any, language: str = "ar"): | |
| if not TOKEN: | |
| raise gr.Error("أضيفي HF_TOKEN في Settings → Secrets داخل Space أولًا.") | |
| lang = "Arabic" if language == "ar" else "English" | |
| if task == "insights": | |
| system = f"You are a careful KPI performance analyst. Reply in {lang}. Use only the supplied data, do not invent facts. Return valid JSON only: {{\"insights\":[{{\"title\":\"...\",\"observation\":\"...\",\"recommendation\":\"...\",\"priority\":\"high|medium|low\"}}]}}. Exactly 3 distinct insights." | |
| user = "Analyze these KPI records and recent trends. Include target gaps and trend evidence when available. Data:\n" + json.dumps(data, ensure_ascii=False) | |
| else: | |
| system = f"You are a KPI design specialist. Reply in {lang}. Use the supplied KPI data to propose genuinely new, non-duplicate measurable indicators relevant to the same organization. Return valid JSON only: {{\"kpis\":[{{\"name\":\"...\",\"description\":\"...\",\"department\":\"...\",\"target\":\"...\",\"measurement\":\"...\",\"rationale\":\"...\"}}]}}. Exactly 3 proposals." | |
| user = "Suggest 3 new measurable KPIs based on this existing data. Avoid duplicates of current indicators. Data:\n" + json.dumps(data, ensure_ascii=False) | |
| try: | |
| response = requests.post(API_URL, headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}, json={"model": MODEL, "messages": [{"role":"system","content":system},{"role":"user","content":user}], "temperature":0.4, "max_tokens":1200}, timeout=90) | |
| if not response.ok: | |
| detail = "" | |
| try: detail = response.json().get("error", {}).get("message", "") | |
| except Exception: pass | |
| raise gr.Error(f"Hugging Face API أعاد HTTP {response.status_code}. {detail or 'تحققي من صلاحية التوكن وتوفر النموذج/الرصيد.'}") | |
| text = response.json()["choices"][0]["message"]["content"] | |
| text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text.strip(), flags=re.I) | |
| match = re.search(r"\{.*\}", text, flags=re.S) | |
| if not match: raise ValueError("Model did not return JSON") | |
| result = json.loads(match.group(0)) | |
| key = "insights" if task == "insights" else "kpis" | |
| if not isinstance(result.get(key), list) or len(result[key]) < 3: | |
| raise ValueError("Expected three results") | |
| return result | |
| except requests.Timeout: | |
| raise gr.Error("تأخر رد النموذج. جرّبي مرة ثانية بعد قليل.") | |
| except gr.Error: | |
| raise | |
| except Exception as exc: | |
| raise gr.Error(f"تعذر تحليل رد النموذج: {exc}") | |
| def load_data(lang): | |
| filename = "data_ar.json" if lang == "ar" else "data_en.json" | |
| path = BASE_DIR / filename | |
| if not path.exists(): | |
| raise gr.Error(f"الملف {filename} غير موجود. ارفعي ملفي البيانات بجانب app.py.") | |
| return json.loads(path.read_text(encoding="utf-8")) | |
| def insights(lang): | |
| return call_qwen("insights", load_data(lang), lang) | |
| def suggestions(lang): | |
| return call_qwen("kpis", load_data(lang), lang) | |
| with gr.Blocks(title="منصة الأداء — AI KPI") as demo: | |
| gr.Markdown("# منصة الأداء — تحليل مؤشرات الأداء بالذكاء الاصطناعي\nهذه واجهة اختبار للخادم. ملف التصميم الأصلي محفوظ في `index.html`، ونربط واجهته في الخطوة التالية بعد التأكد من عمل اتصال Qwen.") | |
| lang = gr.Radio(choices=[("العربية", "ar"), ("English", "en")], value="ar", label="لغة النتائج") | |
| with gr.Row(): | |
| insight_btn = gr.Button("تحليل المؤشرات — 3 رؤى", variant="primary") | |
| kpi_btn = gr.Button("اقتراح 3 مؤشرات جديدة") | |
| output = gr.JSON(label="نتيجة النموذج") | |
| insight_btn.click(fn=insights, inputs=[lang], outputs=[output], api_name="ai_insights") | |
| kpi_btn.click(fn=suggestions, inputs=[lang], outputs=[output], api_name="generate_kpis") | |
| demo.queue(default_concurrency_limit=2) | |
| demo.launch() | |