seed-image-ai commited on
Commit
8d4920b
·
verified ·
1 Parent(s): 99cf783

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +7 -75
app.py CHANGED
@@ -2,7 +2,6 @@ import json
2
  import os
3
  import re
4
  from pathlib import Path
5
- import math
6
 
7
  import gradio as gr
8
  import spaces
@@ -60,92 +59,25 @@ async def serve_data_en():
60
 
61
 
62
  def clean_kpis(kpis):
63
- """Validate KPI records and attach numeric metrics calculated in Python."""
64
  if not isinstance(kpis, list) or not kpis:
65
  raise HTTPException(status_code=400, detail="لا توجد مؤشرات صالحة للتحليل.")
66
-
67
  cleaned = []
68
  for item in kpis[:80]:
69
  if not isinstance(item, dict):
70
  continue
71
-
72
  history = item.get("daily_history", [])
73
  if not isinstance(history, list):
74
  history = []
75
-
76
- # Keep valid numeric history entries and order them by day/date.
77
- valid_history = []
78
- for point in history:
79
- if not isinstance(point, dict):
80
- continue
81
- value = point.get("value")
82
- if isinstance(value, (int, float)) and math.isfinite(value):
83
- valid_history.append({
84
- "day": point.get("day"),
85
- "date": str(point.get("date", ""))[:30],
86
- "value": float(value),
87
- })
88
-
89
- def history_sort_key(point):
90
- day = point.get("day")
91
- return (0, day) if isinstance(day, (int, float)) else (1, point.get("date", ""))
92
-
93
- valid_history.sort(key=history_sort_key)
94
- recent_history = valid_history[-15:]
95
-
96
- latest = item.get("latest_value")
97
- if not isinstance(latest, (int, float)) or not math.isfinite(latest):
98
- latest = recent_history[-1]["value"] if recent_history else None
99
- else:
100
- latest = float(latest)
101
-
102
- previous = (
103
- recent_history[-2]["value"]
104
- if len(recent_history) >= 2
105
- else None
106
- )
107
- target = item.get("target")
108
- if not isinstance(target, (int, float)) or not math.isfinite(target):
109
- target = None
110
- else:
111
- target = float(target)
112
-
113
- metrics = {
114
- "latest_value": latest,
115
- "previous_value": previous,
116
- "change_from_previous": (
117
- round(latest - previous, 4)
118
- if latest is not None and previous is not None
119
- else None
120
- ),
121
- "target": target,
122
- # Neutral arithmetic only; interpretation depends on KPI direction.
123
- "difference_from_target": (
124
- round(latest - target, 4)
125
- if latest is not None and target is not None
126
- else None
127
- ),
128
- "value_to_target_ratio_percent": (
129
- round((latest / target) * 100, 2)
130
- if latest is not None and target not in (None, 0)
131
- else None
132
- ),
133
- "recent_history_start": recent_history[0] if recent_history else None,
134
- "recent_history_end": recent_history[-1] if recent_history else None,
135
- }
136
-
137
  cleaned.append({
138
  "kpi_id": str(item.get("kpi_id", ""))[:80],
139
  "kpi_name": str(item.get("kpi_name", ""))[:180],
140
  "description": str(item.get("description", ""))[:500],
141
  "department": str(item.get("department", ""))[:120],
142
- "target": target,
143
- "latest_value": latest,
144
  "status": str(item.get("status", ""))[:80],
145
- "daily_history": recent_history,
146
- "calculated_metrics": metrics,
147
  })
148
-
149
  if not cleaned:
150
  raise HTTPException(status_code=400, detail="لا توجد بيانات مؤشرات قابلة للتحليل.")
151
  return cleaned
@@ -214,7 +146,7 @@ def generate_local_qwen(language, kpis, task):
214
 
215
  system = (
216
  f"You are a careful KPI performance analyst. Reply in {lang}. "
217
- "Use only supplied data; never invent figures, trends, causes or facts. ""All numeric metrics are calculated by Python and provided in calculated_metrics. Do not calculate, estimate, or alter numeric results; explain only the supplied values. Interpret difference_from_target and value_to_target_ratio_percent cautiously because the data does not specify whether higher or lower values are better for every KPI. "
218
  f"Return valid JSON only with schema {schema}. "
219
  "Exactly 3 insights in this order: notable improvement, alert, recommendation. "
220
  "For Arabic, titles must be exactly: تحسين ملحوظ, تنبيه, توصية. "
@@ -222,10 +154,10 @@ def generate_local_qwen(language, kpis, task):
222
  "For every insight, provide all four fields: title, finding, evidence, recommendation. "
223
  "Do not omit the recommendation field. "
224
  "Write a detailed but concise analysis similar to a professional KPI dashboard. "
225
- "In finding, explain the supplied change_from_previous and current value when available. "
226
  "Always use the human-readable kpi_name instead of technical IDs such as KPI_01. "
227
  "Never write KPI IDs when the indicator name is available. "
228
- "In evidence, cite the supplied calculated_metrics and recent history values/dates. Do not derive new numbers from raw history. "
229
  "In recommendation, always provide a practical, actionable next step based on the findings. "
230
  "Do not repeat the title inside finding. "
231
  "Do not add the labels 'الدليل من البيانات:' or 'الإجراء المقترح:' "
@@ -243,7 +175,7 @@ def generate_local_qwen(language, kpis, task):
243
  '"department":"...","target":90,"formula":"...",'
244
  '"rationale":"...","data_needed":"..."}]}')
245
  system = (
246
- f"You are a KPI design specialist. Reply in {lang}. Return valid JSON only with schema {schema}. ""Use the existing KPI records and Python-calculated calculated_metrics only as context. Do not calculate or invent performance statistics; focus on proposing genuinely new KPIs. "
247
  "Exactly 3 genuinely new, measurable, non-duplicate KPI proposals. Use numeric target where appropriate. "
248
  "Do not claim proposals have been saved. Explain formula, rationale and required data briefly."
249
  )
 
2
  import os
3
  import re
4
  from pathlib import Path
 
5
 
6
  import gradio as gr
7
  import spaces
 
59
 
60
 
61
  def clean_kpis(kpis):
 
62
  if not isinstance(kpis, list) or not kpis:
63
  raise HTTPException(status_code=400, detail="لا توجد مؤشرات صالحة للتحليل.")
 
64
  cleaned = []
65
  for item in kpis[:80]:
66
  if not isinstance(item, dict):
67
  continue
 
68
  history = item.get("daily_history", [])
69
  if not isinstance(history, list):
70
  history = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  cleaned.append({
72
  "kpi_id": str(item.get("kpi_id", ""))[:80],
73
  "kpi_name": str(item.get("kpi_name", ""))[:180],
74
  "description": str(item.get("description", ""))[:500],
75
  "department": str(item.get("department", ""))[:120],
76
+ "target": item.get("target"),
77
+ "latest_value": item.get("latest_value"),
78
  "status": str(item.get("status", ""))[:80],
79
+ "daily_history": history[-15:],
 
80
  })
 
81
  if not cleaned:
82
  raise HTTPException(status_code=400, detail="لا توجد بيانات مؤشرات قابلة للتحليل.")
83
  return cleaned
 
146
 
147
  system = (
148
  f"You are a careful KPI performance analyst. Reply in {lang}. "
149
+ "Use only supplied data; never invent figures, trends, causes or facts. "
150
  f"Return valid JSON only with schema {schema}. "
151
  "Exactly 3 insights in this order: notable improvement, alert, recommendation. "
152
  "For Arabic, titles must be exactly: تحسين ملحوظ, تنبيه, توصية. "
 
154
  "For every insight, provide all four fields: title, finding, evidence, recommendation. "
155
  "Do not omit the recommendation field. "
156
  "Write a detailed but concise analysis similar to a professional KPI dashboard. "
157
+ "In finding, describe what changed and include the relevant values when available. "
158
  "Always use the human-readable kpi_name instead of technical IDs such as KPI_01. "
159
  "Never write KPI IDs when the indicator name is available. "
160
+ "In evidence, explain the specific supporting values, dates, or trends from the data. "
161
  "In recommendation, always provide a practical, actionable next step based on the findings. "
162
  "Do not repeat the title inside finding. "
163
  "Do not add the labels 'الدليل من البيانات:' or 'الإجراء المقترح:' "
 
175
  '"department":"...","target":90,"formula":"...",'
176
  '"rationale":"...","data_needed":"..."}]}')
177
  system = (
178
+ f"You are a KPI design specialist. Reply in {lang}. Return valid JSON only with schema {schema}. "
179
  "Exactly 3 genuinely new, measurable, non-duplicate KPI proposals. Use numeric target where appropriate. "
180
  "Do not claim proposals have been saved. Explain formula, rationale and required data briefly."
181
  )