seed-image-ai's picture
Update README.md
b18bf4b verified
|
Raw History Blame Contribute Delete
34.5 kB

A newer version of the Gradio SDK is available: 6.32.0

Upgrade
metadata
title: KPI Performance Platform
emoji: 📊
colorFrom: red
colorTo: pink
sdk: gradio
sdk_version: 6.30.0
python_version: '3.12'
app_file: app.py
pinned: false
hardware: zero-gpu

منصة مؤشرات الأداء والتحليلات الذكية | KPI Performance Platform

القسم الأول: العربية

1. نظرة عامة

منصة تفاعلية لمتابعة مؤشرات الأداء الرئيسية وقيمها وأهدافها وحالاتها وتاريخها اليومي. تدعم العربية والإنجليزية، وتوفر ميزتين مدعومتين بالذكاء الاصطناعي:

  • التحليلات الذكية: ثلاثة عناصر بالترتيب: تحسن ملحوظ، تنبيه، وتوصية عملية.
  • اقتراح مؤشرات جديدة: ثلاثة مؤشرات قابلة للقياس وغير مكررة، مع الوصف والجهة المسؤولة والهدف والصيغة والمبررات والبيانات المطلوبة.

2. النموذج ورابط Space

3. هيكل الملفات

الملف الوظيفة
app.py نقطة التشغيل؛ تحميل النموذج والمُرمِّز، معالجة مهام الذكاء الاصطناعي، التحقق من النتائج، وحساب المقارنات الرقمية المشتقة من البيانات قبل إرسالها إلى النموذج.
index.html هيكل الواجهة ولوحة التحكم والأقسام والأزرار.
style.css تنسيق الواجهة والألوان والتخطيط والاستجابة للشاشات.
script.js تبديل اللغة، تحميل البيانات، تحديث البطاقات والرسوم، وعرض التحليلات والاقتراحات عند الطلب.
data_ar.json بيانات مؤشرات الأداء بالعربية.
data_en.json بيانات مؤشرات الأداء بالإنجليزية.
README.md توثيق المشروع والتشغيل والبيانات والاختبار والـ API.
requirements.txt قائمة الحزم المطلوبة إن كانت مضافة إلى المستودع.

تحتوي ملفات البيانات على سجلات مؤشرات الأداء. تشمل الحقول الأساسية kpi_id, kpi_name, description, department, target, status, latest_value, وdaily_history. يمرّر الكود آخر 15 سجلًا من daily_history المتاح لكل مؤشر إلى التحليل. وتنفّذ الدالة calculate_actual_metrics حسابات تمهيدية في Python، ثم تُرسل هذه الملخصات مع بيانات المؤشرات إلى Qwen. لا يغيّر هذا التوثيق ملفات البيانات الأصلية.

4. طريقة التشغيل

على Hugging Face Spaces

  1. ارفع ملفات المشروع إلى Space مهيأ لـ Gradio.
  2. تأكد من وجود app.py وبقية الملفات المشار إليها في جدول هيكل الملفات.
  3. أضف الحزم المطلوبة إلى requirements.txt إن لم تكن موجودة.
  4. النموذج الافتراضي هو Qwen/Qwen2.5-7B-Instruct، ويمكن تغييره بمتغير البيئة HF_MODEL_ID.
  5. انتظر اكتمال البناء وتحميل النموذج ثم افتح رابط Space.
  6. اختر اللغة واستعرض المؤشرات، ثم استخدم زر التحليلات أو زر توليد المؤشرات الجديدة.

قد يستغرق بدء التشغيل الأول وقتًا بسبب تنزيل النموذج وتحميله. في Space المستضاف، تُدار موارد GPU وفق إعداد ZeroGPU.

محليًا

المتطلبات: Python وإصدارات الحزم المتوافقة مع المشروع، وبيئة PyTorch/CUDA مع بطاقة NVIDIA وذاكرة GPU كافية لنموذج 7B، واتصال بالإنترنت أول مرة لتنزيل النموذج، وجميع ملفات المشروع.

python -m venv .venv

Windows:

.venv\Scripts\activate

Linux/macOS:

source .venv/bin/activate

تثبيت الحزم الأساسية المستخدمة:

pip install gradio spaces torch transformers

تشغيل التطبيق:

python app.py

ملاحظة: يعتمد الكود الحالي على spaces.GPU وCUDA. لذلك يتطلب التشغيل المحلي إعدادًا متوافقًا مع هذه الآلية وبطاقة GPU مناسبة؛ التشغيل على CPU فقط غير مضمون دون تعديل الكود.

5. المدخلات والمخرجات

بنية مدخل KPI

يوضح المثال التالي شكل سجل مختصر لإرسال مؤشر إلى API.

[
  {
    "kpi_id": "KPI_01",
    "kpi_name": "رضا المتعاملين",
    "description": "قياس رضا المتعاملين عن الخدمات",
    "department": "خدمة المتعاملين",
    "target": 90,
    "status": "يحتاج متابعة",
    "latest_value": 85,
    "daily_history": [
      {"date": "2026-10-26", "value": 84.5},
      {"date": "2026-10-27", "value": 85}
    ]
  }
]

يستقبل الـ API كائن JSON يحتوي على language وkpis. قيمة language هي ar للعربية أو en للإنجليزية، وتحتوي kpis على قائمة السجلات. في النسخة الحالية، تحسب Python ملخصات مثل عدد المؤشرات، ومتوسط القيم الحالية الخام، والمؤشر ذي القيمة الحالية الأعلى،

نتيجة فعلية للتحليلات باللغة العربيةوقائمة المؤشرات الأقل من الهدف أو ذات حالات متابعة، والمؤشرات التي زادت قيمتها مقارنة بأول سجل تاريخي مُرسل. تُمرّر هذه الملخصات مع بيانات المؤشرات إلى Qwen لصياغة الرد.

تحسن ملحوظ

أظهرت البيانات زيادة في أداء مؤشر رضا المتعاملين بنسبة 0.5، مما يشير إلى تحسن ملحوظ في هذا المؤشر.

  • الدليل من البيانات: سجل مؤشر رضا المتعاملين قيمة 85، وهو أعلى من القيمة السابقة 84.5.
  • الإجراء المقترح: استمرار العمل على تحسين جودة الخدمة المقدمة للمتعاملين لضمان استمرار هذا التحسن.

تنبيه

مؤشر زمن إنجاز المعاملات لم يحقق هدفه، حيث بلغ 65 وهو أقل بـ 15 نقطة من الهدف المحدد 80.

  • الدليل من البيانات: القيمة الحالية للمؤشر هي 65، بينما الهدف هو 80.
  • الإجراء المقترح: مراجعة الإجراءات العملية لتحسين فعالية العمليات وزيادة سرعة إنجاز المعاملات.

توصية

يجب التركيز على تحقيق الهدف المحدد لمؤشر كفاءة استهلاك الطاقة، حيث بلغت القيمة الحالية 86.5 وهو أقل بـ 1.5 نقطة من الهدف 88.

  • الدليل من البيانات: القيمة الحالية للمؤشر هي 86.5، بينما الهدف هو 88.
  • الإجراء المقترح: تنفيذ برامج ترشيد استهلاك الطاقة وإجراءات تحسين كفاءة استخدام الطاقة لضمان تحقيق الهدف المحدد.

ملاحظة حول تفسير الأرقام: وفق تمثيل البيانات في هذا المشروع، القيم هي قيم تحقيق المؤشر مقارنة بالهدف وليست بالضرورة أوقاتًا فعلية أو وحدات قياس خام. لذلك فإن قيمة 65 مقابل هدف 80 تعني فجوة مقدارها 15 نقطة في قيمة المؤشر. ينبغي تفسيرها وفق تعريف المؤشر ووحدة البيانات المعتمدة.

مخرجات لاقتراح مؤشرات جديدة باللغة العربية

زيادة نسبة استخدام التطبيقات الذكية

قياس نسبة استخدام التطبيقات الذكية من قبل الموظفين والمتعاملين.

  • الجهة المقترحة: إدارة التحول الرقمي
  • طريقة القياس: نسبة استخدام التطبيقات الذكية = (عدد المستخدمين للتطبيقات الذكية / عدد الموظفين + عدد المتعاملين) × 100
  • الهدف المقترح: 80%
  • سبب الاقتراح: تعزيز استخدام التقنيات الحديثة لتحسين الكفاءة وتجربة المستخدم.
  • البيانات المطلوبة: عدد المستخدمين للتطبيقات الذكية، عدد الموظفين، عدد المتعاملين.

تقليل نسبة الأخطاء الإدارية

قياس نسبة الأخطاء الإدارية في المعاملات الحكومية.

  • الجهة المقترحة: إدارة العمليات
  • طريقة القياس: نسبة الأخطاء الإدارية = (عدد الأخطاء الإدارية / عدد المعاملات الحكومية) × 100
  • الهدف المقترح: 5%
  • سبب الاقتراح: تحسين جودة الخدمة من خلال تقليل الأخطاء الإدارية.
  • البيانات المطلوبة: عدد الأخطاء الإدارية، عدد المعاملات الحكومية.

زيادة نسبة المشاركة المجتمعية

قياس نسبة المشاركة المجتمعية في البرامج الحكومية.

  • الجهة المقترحة: إدارة العلاقات العامة
  • طريقة القياس: نسبة المشاركة المجتمعية = (عدد المشاركين في البرامج المجتمعية / عدد المستهدفين) × 100
  • الهدف المقترح: 75%
  • سبب الاقتراح: تعزيز الوعي بالبرامج الحكومية وزيادة تأثيرها على المجتمع.
  • البيانات المطلوبة: عدد المشاركين في البرامج المجتمعية، عدد المستهدفين.

تُعرض هذه الاقتراحات بوصفها مخرجات فعلية شاركها المستخدم. لا تُحفظ الاقتراحات تلقائيًا في ملفات البيانات. ويجب مراجعة صيغة كل معادلة للتأكد من استخدام الأقواس المناسبة عند التنفيذ الحسابي، خصوصًا مقام معادلة استخدام التطبيقات الذكية.

6. استدعاء API

يوفر التطبيق مسارين من نوع POST لاستدعاء مهام الذكاء الاصطناعي. استخدم رابط Space المنشور بدل SPACE_URL في الأمثلة أدناه.

المسار الوظيفة
/api/insights تحليل بيانات المؤشرات وإرجاع ثلاثة تحليلات.
/api/generate-kpis اقتراح ثلاثة مؤشرات جديدة.

مثال: استدعاء التحليلات باستخدام cURL

احفظ بيانات الطلب في ملف request.json، أو استخدم المثال التالي بعد استبدال رابط Space بالرابط الفعلي:

curl -X POST "SPACE_URL/api/insights" \
  -H "Content-Type: application/json" \
  -d '{
    "language": "ar",
    "kpis": [
      {
        "kpi_id": "KPI_01",
        "kpi_name": "رضا المتعاملين",
        "description": "قياس رضا المتعاملين عن الخدمات",
        "department": "خدمة المتعاملين",
        "target": 90,
        "status": "يحتاج متابعة",
        "latest_value": 85,
        "daily_history": [
          {"date": "2026-10-26", "value": 84.5},
          {"date": "2026-10-27", "value": 85}
        ]
      }
    ]
  }'

مثال: استدعاء توليد المؤشرات باستخدام cURL

استخدم جسم الطلب نفسه مع تغيير المسار إلى /api/generate-kpis:

curl -X POST "SPACE_URL/api/generate-kpis" \
  -H "Content-Type: application/json" \
  -d '{
    "language": "ar",
    "kpis": [
      {
        "kpi_id": "KPI_01",
        "kpi_name": "رضا المتعاملين",
        "description": "قياس رضا المتعاملين عن الخدمات",
        "department": "خدمة المتعاملين",
        "target": 90,
        "status": "يحتاج متابعة",
        "latest_value": 85,
        "daily_history": [
          {"date": "2026-10-26", "value": 84.5},
          {"date": "2026-10-27", "value": 85}
        ]
      }
    ]
  }'

مثال باستخدام Python

import requests

SPACE_URL = "https://seed-image-ai-Performance_Indicators.hf.space"
endpoint = f"{SPACE_URL}/api/insights"

payload = {
    "language": "ar",
    "kpis": [
        {
            "kpi_id": "KPI_01",
            "kpi_name": "رضا المتعاملين",
            "description": "قياس رضا المتعاملين عن الخدمات",
            "department": "خدمة المتعاملين",
            "target": 90,
            "status": "يحتاج متابعة",
            "latest_value": 85,
            "daily_history": [
                {"date": "2026-10-26", "value": 84.5},
                {"date": "2026-10-27", "value": 85}
            ]
        }
    ]
}

response = requests.post(endpoint, json=payload, timeout=180)
response.raise_for_status()
print(response.json())

تنبيه: قد يختلف عنوان النطاق الذي توفره Hugging Face عن صيغة المثال أعلاه؛ انسخ عنوان التطبيق الفعلي من صفحة Space. يتطلب التوليد وقتًا، وقد يُرجع التطبيق خطأ HTTP إذا فشل تحميل النموذج أو التوليد أو كانت البيانات المرسلة غير صالحة. لا يتطلب هذا التنفيذ رمز وصول شخصيًا ما دام Space متاحًا للعامة ولا توجد قيود وصول إضافية.

7. نصوص الـ Prompts المستخدمة

النصوص التالية مأخوذة من آخر نسخة من app.py التي أرسلها المستخدم. القيم {lang} و{schema} تُملأ وقت التشغيل، ثم تُرفق بيانات المؤشرات في رسالة المستخدم. النص النهائي يمر عبر tokenizer.apply_chat_template.

أ. Prompt التحليلات — تعليمات النظام

You are a careful KPI performance analyst. CRITICAL: Reply strictly and exclusively in {lang}. DO NOT use or mix any Chinese, English, or foreign characters under any circumstances. Every single word must be in proper, professional Arabic if the language is Arabic. Use the pre-calculated actual metrics provided below. Do NOT recalculate or invent numbers. Return valid JSON only with schema {schema}. Exactly 3 insights in this order: notable improvement, alert, recommendation. For Arabic, titles must be exactly: تحسين ملحوظ, تنبيه, توصية. For English: Notable Improvement, Alert, Recommendation. For every insight, provide all four fields: title, finding, evidence, recommendation. Write a detailed but concise analysis similar to a professional KPI dashboard. Always use the human-readable kpi_name instead of technical IDs such as KPI_01. In finding, describe the result using the exact numbers supplied. In evidence, cite the specific supporting values and pre-calculated metrics. In recommendation, provide a practical, actionable next step based on the findings. Do not add labels like 'الدليل من البيانات:' or 'الإجراء المقترح:' inside the JSON fields. Keep all fields factual, clear, and useful.

ب. Prompt التحليلات — رسالة المستخدم

Pre-calculated actual metrics:
{json.dumps(metrics, ensure_ascii=False)}

Raw KPI data:
{json.dumps(kpis, ensure_ascii=False)}

Task: Format these pre-calculated metrics and findings into the 3 requested JSON insights in pure Arabic.

ج. Prompt اقتراح المؤشرات — تعليمات النظام

You are a KPI design specialist. CRITICAL: Reply strictly and exclusively in {lang}. DO NOT mix any Chinese or foreign characters. Return valid JSON only with schema {schema}. Exactly 3 genuinely new, measurable, non-duplicate KPI proposals. Use numeric target where appropriate. Do not claim proposals have been saved. Explain formula, rationale and required data briefly.

د. Prompt اقتراح المؤشرات — رسالة المستخدم

Suggest 3 new KPIs relevant to the organization represented by these existing indicators. Avoid duplicates. Existing KPI data:
{json.dumps(kpis, ensure_ascii=False)}

ملاحظة: هذه هي نصوص الرسائل كما تُبنى في الكود، مع عرض تعبيرات Python التي تُدرج القيم الفعلية وقت التشغيل بدل نسخ بيانات متغيرة حرفيًا. كما أن تعليمات اللغة في الكود تطلب تجنب الأحرف الأجنبية، بينما مخطط JSON نفسه يستخدم مفاتيح إنجليزية مثل title وfinding؛ لذلك قد تظهر هذه المفاتيح الإنجليزية في استجابة JSON حتى عندما تكون قيمها بالعربية.

8. الحسابات ودور النموذج

تحسب الدالة calculate_actual_metrics في Python ملخصات رقمية قبل استدعاء Qwen:

  • total_kpis: عدد المؤشرات التي وصلت إلى الدالة.
  • avg_achievement: متوسط القيم الحالية الخام (latest_value)؛ هذا ليس متوسط نسبة تحقيق الهدف إذا كانت المؤشرات بوحدات مختلفة.
  • best_kpi: المؤشر صاحب أعلى قيمة حالية خام، وليس بالضرورة الأعلى في نسبة تحقيق الهدف.
  • delayed_kpis: المؤشرات التي قيمتها الحالية أقل من الهدف، أو التي تتضمن حالتها كلمات مثل «متابعة» أو «متأخر».
  • improved_kpis: المؤشرات التي تزيد قيمتها الحالية على قيمة أول سجل في daily_history المرسل.

بعد ذلك يرسل الكود هذه الملخصات وبيانات المؤشرات إلى Qwen لصياغة ثلاثة تحليلات. النموذج مسؤول عن الصياغة والتفسير والتوصية، لكن الكود الحالي لا يمنع النموذج تمامًا من صياغة استنتاج غير دقيق؛ لذا تُراجع النتائج مع البيانات الأصلية قبل اعتمادها.

9. نتائج الاختبار والقيود

الاختبار الوظيفي الذي تم الإبلاغ عنه: تم تشغيل ميزة التحليلات الذكية وشارك المستخدم المخرجات العربية الثلاث المدرجة في القسم 5. كما شارك المستخدم ثلاثة اقتراحات فعلية من ميزة توليد المؤشرات وأكد أن التوليد يعمل.

القيود المعروفة:

  • قد يُرجع النموذج JSON غير صالح أو لا يلتزم بالمخطط تمامًا؛ التحقق من البنية لا يضمن صحة المحتوى.
  • تعتمد جودة النتائج على دقة البيانات والأهداف والحالات والتاريخ المتوفر.
  • ينبغي مراجعة التوصيات والتحقق من القيم مقابل ملف JSON الأصلي.
  • يتطلب النموذج ذاكرة وموارد حوسبة مناسبة، وقد يتأخر التحميل أو التوليد.
  • يتطلب التشغيل المحلي الحالي CUDA وإعدادًا متوافقًا مع spaces.GPU.

Section Two: English

1. Overview

The KPI Performance Platform is an interactive dashboard for monitoring key performance indicators, targets, statuses, and available daily history. It supports Arabic and English and provides two AI-assisted features:

  • Smart insights: Three items in order: notable improvement, alert, and actionable recommendation.
  • KPI proposals: Three new, measurable, non-duplicate KPI proposals with descriptions, departments, targets, formulas, rationales, and required data.

The Qwen model is loaded and runs inside the Python environment in the Space, using available GPU resources for generation. The current implementation does not rely on an external inference service or a personal access token.

2. Model and Space URL

3. File Structure

File Purpose
app.py Main entry point; loads the model and tokenizer, processes AI tasks, validates outputs, and calculates numeric comparisons from the KPI data before passing them to the model.
index.html Defines the dashboard structure, sections, and controls.
style.css Provides layout, colors, styling, and responsive presentation.
script.js Handles language switching, data loading, dashboard cards and charts, and on-demand AI results.
data_ar.json Arabic KPI dataset.
data_en.json English KPI dataset.
README.md Project documentation, setup, API, prompts, and test notes.
requirements.txt Python dependency list, if included in the repository.

The datasets contain KPI records with fields such as kpi_id, kpi_name, description, department, target, status, latest_value, and daily_history. The current code passes the last 15 available history entries per KPI and computes preliminary summary metrics in calculate_actual_metrics; these summaries and the KPI records are then sent to Qwen. The original dataset files are not modified.

4. Running the Project

On Hugging Face Spaces

  1. Upload the project files to a Gradio-configured Space.
  2. Ensure app.py and the referenced project files are present.
  3. Add the required packages to requirements.txt if needed.
  4. The default model is Qwen/Qwen2.5-7B-Instruct; set HF_MODEL_ID to use a different model identifier.
  5. Wait for the build and model loading to finish, then open the Space.
  6. Choose a language and use the insights or KPI-generation feature.

The first startup may take longer while the model is downloaded and loaded. GPU resources are managed by the hosted ZeroGPU environment.

Locally

Requirements include a compatible Python environment, PyTorch/CUDA with a compatible NVIDIA GPU and sufficient memory for a 7B model, internet access for the initial model download, and all project files.

python -m venv .venv

Windows:

.venv\Scripts\activate

Linux/macOS:

source .venv/bin/activate

Install the core packages:

pip install gradio spaces torch transformers

Run:

python app.py

Note: The current code relies on spaces.GPU and CUDA. Local execution requires a compatible GPU setup and configuration for this mechanism. CPU-only execution is not guaranteed without code changes.

5. Inputs and Outputs

KPI input structure

The following is a shortened request example; its values illustrate the schema and are not presented as a separate test result:

[
  {
    "kpi_id": "KPI_01",
    "kpi_name": "Customer Satisfaction",
    "description": "Measure customer satisfaction with services",
    "department": "Customer Service",
    "target": 90,
    "status": "Needs Follow-up",
    "latest_value": 85,
    "daily_history": [
      {"date": "2026-10-26", "value": 84.5},
      {"date": "2026-10-27", "value": 85}
    ]
  }
]

The API receives a JSON object containing language (ar or en) and a kpis list. In the current implementation, Python computes summary fields such as KPI count, the average of raw latest values, the KPI with the highest raw latest value, indicators below target or marked for follow-up, and indicators whose latest value exceeds the first supplied history value. These summaries and the raw KPI records are passed to Qwen for wording and explanation.

Actual Arabic smart-insights output

The following Arabic output was returned by the running Space and shared by the user; it is not a fabricated example:

Notable improvement: Customer satisfaction increased by 0.5, from 84.5 to 85. The suggested action was to continue improving service quality.

Alert: Transaction completion-time KPI was reported as 65 against a target of 80, a gap of 15 points. The suggested action was to review operational procedures and improve process effectiveness.

Recommendation: Energy-efficiency KPI was reported as 86.5 against a target of 88, a gap of 1.5 points. The suggested action was to implement energy-saving programs and improve energy-use efficiency.

In this project, the values represent KPI achievement values relative to their targets, rather than necessarily representing raw elapsed time. Interpret them according to the dataset's KPI definition and units.

Actual new-KPI proposals

The user supplied the following three proposals returned by the running Space:

  1. Increase smart application usage rate — proposed department: Digital Transformation; target: 80%; measures usage of smart applications by employees and customers; required data: smart-application users, employee count, and customer count.
  2. Reduce administrative error rate — proposed department: Operations; target: 5%; formula: administrative errors divided by government transactions, multiplied by 100; required data: administrative error count and government transaction count.
  3. Increase community participation rate — proposed department: Public Relations; target: 75%; formula: participants in community programs divided by the target audience, multiplied by 100; required data: participant count and target audience count.

These are user-provided outputs from a real generation run, not benchmark results. The proposals are not automatically saved to the dataset files. The first formula should be checked for denominator grouping before operational use.

6. API Invocation

The application exposes two POST endpoints:

Endpoint Purpose
/api/insights Analyze KPI records and return three insights.
/api/generate-kpis Generate three new KPI proposals.

Replace SPACE_URL with the actual URL shown on the Hugging Face Space page.

cURL example: insights

curl -X POST "SPACE_URL/api/insights" \
  -H "Content-Type: application/json" \
  -d '{
    "language": "en",
    "kpis": [
      {
        "kpi_id": "KPI_01",
        "kpi_name": "Customer Satisfaction",
        "description": "Measure customer satisfaction with services",
        "department": "Customer Service",
        "target": 90,
        "status": "Needs Follow-up",
        "latest_value": 85,
        "daily_history": [
          {"date": "2026-10-26", "value": 84.5},
          {"date": "2026-10-27", "value": 85}
        ]
      }
    ]
  }'

cURL example: generate new KPIs

Use the same request body and change the endpoint to /api/generate-kpis:

curl -X POST "SPACE_URL/api/generate-kpis" \
  -H "Content-Type: application/json" \
  -d '{
    "language": "en",
    "kpis": [
      {
        "kpi_id": "KPI_01",
        "kpi_name": "Customer Satisfaction",
        "description": "Measure customer satisfaction with services",
        "department": "Customer Service",
        "target": 90,
        "status": "Needs Follow-up",
        "latest_value": 85,
        "daily_history": [
          {"date": "2026-10-26", "value": 84.5},
          {"date": "2026-10-27", "value": 85}
        ]
      }
    ]
  }'

Python example

import requests

SPACE_URL = "https://YOUR-SPACE-SUBDOMAIN.hf.space"
payload = {
    "language": "ar",
    "kpis": [
        {
            "kpi_id": "KPI_01",
            "kpi_name": "رضا المتعاملين",
            "description": "قياس رضا المتعاملين عن الخدمات",
            "department": "خدمة المتعاملين",
            "target": 90,
            "status": "يحتاج متابعة",
            "latest_value": 85,
            "daily_history": [
                {"date": "2026-10-26", "value": 84.5},
                {"date": "2026-10-27", "value": 85}
            ]
        }
    ]
}

response = requests.post(f"{SPACE_URL}/api/insights", json=payload, timeout=180)
response.raise_for_status()
print(response.json())

The exact Space subdomain should be copied from the live Space page. Generation can take time; invalid input or a model/runtime failure may result in an HTTP error. No personal access token is required for this implementation when the Space is public and has no additional access restrictions.

7. Prompt Text

The following prompt strings are based on the latest app.py version supplied by the user. {lang} and {schema} are runtime placeholders. The user message also contains the JSON-serialized KPI records and, for insights, the Python-calculated summary object. The tokenizer then applies its chat template.

A. Smart-insights prompt — system message

You are a careful KPI performance analyst. CRITICAL: Reply strictly and exclusively in {lang}. DO NOT use or mix any Chinese, English, or foreign characters under any circumstances. Every single word must be in proper, professional Arabic if the language is Arabic. Use the pre-calculated actual metrics provided below. Do NOT recalculate or invent numbers. Return valid JSON only with schema {schema}. Exactly 3 insights in this order: notable improvement, alert, recommendation. For Arabic, titles must be exactly: تحسين ملحوظ, تنبيه, توصية. For English: Notable Improvement, Alert, Recommendation. For every insight, provide all four fields: title, finding, evidence, recommendation. Write a detailed but concise analysis similar to a professional KPI dashboard. Always use the human-readable kpi_name instead of technical IDs such as KPI_01. In finding, describe the result using the exact numbers supplied. In evidence, cite the specific supporting values and pre-calculated metrics. In recommendation, provide a practical, actionable next step based on the findings. Do not add labels like 'الدليل من البيانات:' or 'الإجراء المقترح:' inside the JSON fields. Keep all fields factual, clear, and useful.

B. Smart-insights prompt — user message construction

Pre-calculated actual metrics:
{json.dumps(metrics, ensure_ascii=False)}

Raw KPI data:
{json.dumps(kpis, ensure_ascii=False)}

Task: Format these pre-calculated metrics and findings into the 3 requested JSON insights in pure Arabic.

C. KPI-generation prompt — system message

You are a KPI design specialist. CRITICAL: Reply strictly and exclusively in {lang}. DO NOT mix any Chinese or foreign characters. Return valid JSON only with schema {schema}. Exactly 3 genuinely new, measurable, non-duplicate KPI proposals. Use numeric target where appropriate. Do not claim proposals have been saved. Explain formula, rationale and required data briefly.

D. KPI-generation prompt — user message construction

Suggest 3 new KPIs relevant to the organization represented by these existing indicators. Avoid duplicates. Existing KPI data:
{json.dumps(kpis, ensure_ascii=False)}

Prompt note: The system prompt asks for Arabic-only wording when Arabic is selected, but the required JSON schema uses English keys such as title, finding, evidence, and recommendation. Those keys may therefore remain English while the values are Arabic. The displayed prompt strings preserve the runtime Python expressions for inserted data rather than expanding them into a fixed dataset.

8. Numeric Processing and Model Responsibilities

The calculate_actual_metrics function computes these Python-side summaries before Qwen is called:

  • total_kpis: number of KPI records passed to the function.
  • avg_achievement: arithmetic mean of raw latest_value values; it is not an average target-achievement rate when KPIs use different units.
  • best_kpi: KPI with the highest raw latest value, not necessarily the highest target-achievement rate.
  • delayed_kpis: KPIs whose latest value is below target or whose status contains follow-up/delayed wording.
  • improved_kpis: KPIs whose latest value is greater than the first supplied daily_history value.

The code sends these summaries and the KPI records to Qwen, which generates the wording and recommendations. The current implementation does not guarantee that every generated interpretation is correct, so outputs should be checked against the original data before being relied upon.

9. Test Results and Limitations

Functional test reported: The user shared three Arabic smart-insight outputs and three actual new-KPI proposals from the running Space, and confirmed that KPI generation works.

Known limitations:

  • The model may return invalid JSON or deviate from the schema; structural validation does not guarantee factual correctness.
  • Output quality depends on the accuracy of KPI data, targets, statuses, and history.
  • Recommendations and numeric statements should be reviewed against the original dataset.
  • The model requires suitable compute and memory; loading or generation may be slow.
  • The current local setup requires CUDA and a compatible spaces.GPU configuration.