Files changed (2) hide show
  1. app.py +228 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from pathlib import Path
4
+
5
+ import gradio as gr
6
+ from huggingface_hub import InferenceClient
7
+
8
+ BASE_DIR = Path(__file__).resolve().parent
9
+ MODEL_ID = os.getenv("HF_MODEL_ID", "Qwen/Qwen2.5-7B-Instruct")
10
+
11
+ LANG_FILES = {
12
+ "العربية": BASE_DIR / "data_ar.json",
13
+ "English": BASE_DIR / "data_en.json",
14
+ }
15
+
16
+ SAMPLE_PROMPTS = {
17
+ "العربية": [
18
+ "حلّل مؤشرات الأداء وحدد أهم المخاطر والتوصيات.",
19
+ "ما المؤشر الأكثر حاجة إلى تدخل؟ استند إلى الأرقام.",
20
+ "اقترح 3 مؤشرات أداء جديدة مرتبطة بالبيانات الحالية بصيغة JSON.",
21
+ ],
22
+ "English": [
23
+ "Analyze the KPIs and identify the main risks and recommendations.",
24
+ "Which KPI needs the most intervention? Use the data.",
25
+ "Suggest 3 new KPIs related to the current data in JSON format.",
26
+ ],
27
+ }
28
+
29
+
30
+ def load_json_file(path):
31
+ if not path:
32
+ raise ValueError("لم يتم اختيار ملف JSON.")
33
+ with open(path, "r", encoding="utf-8") as f:
34
+ data = json.load(f)
35
+ if isinstance(data, dict):
36
+ # Accept either a list or a wrapper object containing a KPI list.
37
+ for key in ("kpis", "data", "items", "indicators"):
38
+ if isinstance(data.get(key), list):
39
+ data = data[key]
40
+ break
41
+ if not isinstance(data, list):
42
+ raise ValueError("يجب أن يحتوي JSON على قائمة مؤشرات أو على كائن يحوي قائمة kpis/data/items/indicators.")
43
+ if not data:
44
+ raise ValueError("ملف JSON لا يحتوي على أي مؤشرات.")
45
+ return data
46
+
47
+
48
+ def pick_data(language, uploaded_file, sample_choice):
49
+ if uploaded_file:
50
+ return load_json_file(uploaded_file), "الملف المرفوع"
51
+ path = LANG_FILES.get(language, LANG_FILES["العربية"])
52
+ return load_json_file(str(path)), path.name
53
+
54
+
55
+ def summarize_data(data, language):
56
+ total = len(data)
57
+ values = []
58
+ good = medium = delayed = 0
59
+ missing = []
60
+ for i, item in enumerate(data, 1):
61
+ if not isinstance(item, dict):
62
+ missing.append(f"item {i} is not an object")
63
+ continue
64
+ for key in ("kpi_name", "latest_value", "target"):
65
+ if key not in item:
66
+ missing.append(f"item {i}: missing {key}")
67
+ try:
68
+ values.append(float(item.get("latest_value", 0)))
69
+ except (TypeError, ValueError):
70
+ pass
71
+ status = str(item.get("status", "")).lower()
72
+ if any(x in status for x in ("good", "جيد")):
73
+ good += 1
74
+ elif any(x in status for x in ("medium", "needs", "follow", "متوسط", "متابعة")):
75
+ medium += 1
76
+ else:
77
+ delayed += 1
78
+
79
+ avg = sum(values) / len(values) if values else 0
80
+ if language == "English":
81
+ lines = [
82
+ "## Data summary (calculated from the uploaded JSON)",
83
+ f"- KPI count: **{total}**",
84
+ f"- Good: **{good}** | Needs follow-up: **{medium}** | Other/delayed: **{delayed}**",
85
+ f"- Average latest value: **{avg:.1f}**",
86
+ ]
87
+ if missing:
88
+ lines.append("- Data quality notes: " + "; ".join(missing[:8]))
89
+ else:
90
+ lines = [
91
+ "## ملخص البيانات (محسوب برمجياً من ملف JSON)",
92
+ f"- عدد المؤشرات: **{total}**",
93
+ f"- جيد: **{good}** | يحتاج متابعة: **{medium}** | حالات أخرى/متأخرة: **{delayed}**",
94
+ f"- متوسط آخر القيم المسجلة: **{avg:.1f}**",
95
+ ]
96
+ if missing:
97
+ lines.append("- ملاحظات على البيانات: " + "؛ ".join(missing[:8]))
98
+ return "\n".join(lines)
99
+
100
+
101
+ def call_qwen(language, data, question):
102
+ token = os.getenv("HF_TOKEN")
103
+ if not token:
104
+ message = (
105
+ "لم يتم ضبط سر HF_TOKEN في إعدادات Space. أضيفي Hugging Face User Access Token "
106
+ "في Settings → Secrets ثم أعيدي تشغيل Space."
107
+ if language == "العربية"
108
+ else "HF_TOKEN is not configured in Space Settings → Secrets. Add a Hugging Face User Access Token and restart the Space."
109
+ )
110
+ return message
111
+
112
+ try:
113
+ client = InferenceClient(model=MODEL_ID, token=token)
114
+ lang_instruction = (
115
+ "Respond in Arabic. Use only the supplied KPI data as factual evidence."
116
+ if language == "العربية"
117
+ else "Respond in English. Use only the supplied KPI data as factual evidence."
118
+ )
119
+ system_prompt = (
120
+ "You are an analytical assistant for a KPI performance platform. "
121
+ "Analyze the JSON provided by the user. Do not invent numbers, trends, departments, "
122
+ "causes, or facts that are not present in the data. Clearly distinguish observed facts "
123
+ "from recommendations or hypotheses. If information is missing, say so. "
124
+ "When asked to generate new KPIs, output valid JSON with an array of objects containing "
125
+ "kpi_name, description, department, target, measurement_method, and rationale. "
126
+ + lang_instruction
127
+ )
128
+ payload = json.dumps(data, ensure_ascii=False)
129
+ # Keep the prompt bounded for hosted inference services.
130
+ if len(payload) > 24000:
131
+ payload = json.dumps(
132
+ [
133
+ {k: v for k, v in item.items() if k != "daily_history"}
134
+ | {"daily_history": item.get("daily_history", [])[-10:]}
135
+ for item in data
136
+ ],
137
+ ensure_ascii=False,
138
+ )
139
+ user_prompt = (
140
+ f"KPI JSON data:\n{payload}\n\n"
141
+ f"User request:\n{question.strip() or ('Analyze the KPIs and recommend next steps.' if language == 'English' else 'حلّل المؤشرات وقدّم توصيات عملية.')}"
142
+ )
143
+ response = client.chat_completion(
144
+ messages=[
145
+ {"role": "system", "content": system_prompt},
146
+ {"role": "user", "content": user_prompt},
147
+ ],
148
+ max_tokens=900,
149
+ temperature=0.3,
150
+ )
151
+ return response.choices[0].message.content or "The model returned an empty response."
152
+ except Exception as exc:
153
+ return (
154
+ f"تعذّر الاتصال بالمودل ({type(exc).__name__}): {exc}\n\n"
155
+ "تحققي من أن المودل متاح عبر Inference Providers وأن الرمز يملك صلاحية Make calls to Inference Providers."
156
+ if language == "العربية"
157
+ else f"Could not call the model ({type(exc).__name__}): {exc}\n\nCheck that the model is available through Inference Providers and the token has 'Make calls to Inference Providers' permission."
158
+ )
159
+
160
+
161
+ def run_analysis(language, uploaded_file, sample_choice, question):
162
+ try:
163
+ data, source = pick_data(language, uploaded_file, sample_choice)
164
+ summary = summarize_data(data, language)
165
+ answer = call_qwen(language, data, question)
166
+ source_label = f"\n\n**مصدر البيانات:** {source}" if language == "العربية" else f"\n\n**Data source:** {source}"
167
+ return summary + source_label, answer, json.dumps(data, ensure_ascii=False, indent=2)
168
+ except Exception as exc:
169
+ error = f"خطأ في قراءة البيانات: {exc}" if language == "العربية" else f"Data loading error: {exc}"
170
+ return error, "", ""
171
+
172
+
173
+ def update_examples(language):
174
+ prompts = SAMPLE_PROMPTS.get(language, SAMPLE_PROMPTS["العربية"])
175
+ return gr.update(choices=prompts, value=prompts[0])
176
+
177
+
178
+ with gr.Blocks(title="منصة الأداء | KPI AI", theme=gr.themes.Soft()) as demo:
179
+ gr.Markdown(
180
+ "# ✨ منصة الأداء — تحليل مؤشرات الأداء بالذكاء الاصطناعي\n"
181
+ "اختاري ملف بيانات، راجعي ملخصاً محسوباً من الأرقام الفعلية، ثم اطلبي من Qwen تحليلها."
182
+ )
183
+ with gr.Row():
184
+ language = gr.Dropdown(
185
+ choices=["العربية", "English"],
186
+ value="العربية",
187
+ label="لغة الواجهة / Interface language",
188
+ )
189
+ sample_choice = gr.Dropdown(
190
+ choices=SAMPLE_PROMPTS["العربية"],
191
+ value=SAMPLE_PROMPTS["العربية"][0],
192
+ label="مثال جاهز / Example prompt",
193
+ )
194
+ upload = gr.File(
195
+ label="رفع ملف JSON (اختياري — إذا لم ترفعي ملفاً سيُستخدم ملف اللغة المختارة)",
196
+ file_types=[".json", ".txt"],
197
+ type="filepath",
198
+ )
199
+ question = gr.Textbox(
200
+ label="طلبك من المودل / Ask the model",
201
+ placeholder="مثلاً: ما المؤشر الأكثر حاجة إلى تدخل؟ ولماذا؟",
202
+ lines=3,
203
+ )
204
+ with gr.Row():
205
+ run_button = gr.Button("تحليل البيانات باستخدام Qwen", variant="primary")
206
+ clear_button = gr.ClearButton([upload, question])
207
+ summary_output = gr.Markdown(label="ملخص البيانات")
208
+ answer_output = gr.Markdown(label="رد Qwen")
209
+ with gr.Accordion("عرض بيانات JSON التي قرأها التطبيق", open=False):
210
+ json_output = gr.Code(label="JSON", language="json")
211
+
212
+ run_button.click(
213
+ fn=run_analysis,
214
+ inputs=[language, upload, sample_choice, question],
215
+ outputs=[summary_output, answer_output, json_output],
216
+ )
217
+ sample_choice.change(
218
+ fn=lambda x: x,
219
+ inputs=[sample_choice],
220
+ outputs=[question],
221
+ )
222
+ language.change(
223
+ fn=update_examples,
224
+ inputs=[language],
225
+ outputs=[sample_choice],
226
+ )
227
+
228
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gradio>=5.0,<7.0
2
+ huggingface_hub>=0.30.0