Update app.py
Browse files1 unmodified line234556751 unmodified lines596061636263666465666771686970757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351367172737475142143767778145146798014881828362 unmodified lines1461471482171491501511521 unmodified line15415515622515715815922816016116216311 unmodified lines1751761772461781791801811 unmodified lineimport osimport refrom pathlib import Pathimport math
import gradio as grimport spaces51 unmodified lines
def clean_kpis(kpis): """Validate KPI records and attach numeric metrics calculated in Python.""" if not isinstance(kpis, list) or not kpis: raise HTTPException(status_code=400, detail="لا توجد مؤشرات صالحة للتحليل.")
cleaned = [] for item in kpis[:80]: if not isinstance(item, dict): continue
history = item.get("daily_history", []) if not isinstance(history, list): history = []
# Keep valid numeric history entries and order them by day/date. valid_history = [] for point in history: if not isinstance(point, dict): continue value = point.get("value") if isinstance(value, (int, float)) and math.isfinite(value): valid_history.append({ "day": point.get("day"), "date": str(point.get("date", ""))[:30], "value": float(value), })
def history_sort_key(point): day = point.get("day") return (0, day) if isinstance(day, (int, float)) else (1, point.get("date", ""))
valid_history.sort(key=history_sort_key) recent_history = valid_history[-15:]
latest = item.get("latest_value") if not isinstance(latest, (int, float)) or not math.isfinite(latest): latest = recent_history[-1]["value"] if recent_history else None else: latest = float(latest)
previous = ( recent_history[-2]["value"] if len(recent_history) >= 2 else None ) target = item.get("target") if not isinstance(target, (int, float)) or not math.isfinite(target): target = None else: target = float(target)
metrics = { "latest_value": latest, "previous_value": previous, "change_from_previous": ( round(latest - previous, 4) if latest is not None and previous is not None else None ), "target": target, # Neutral arithmetic only; interpretation depends on KPI direction. "difference_from_target": ( round(latest - target, 4) if latest is not None and target is not None else None ), "value_to_target_ratio_percent": ( round((latest / target) * 100, 2) if latest is not None and target not in (None, 0) else None ), "recent_history_start": recent_history[0] if recent_history else None, "recent_history_end": recent_history[-1] if recent_history else None, }
cleaned.append({ "kpi_id": str(item.get("kpi_id", ""))[:80], "kpi_name": str(item.get("kpi_name", ""))[:180], "description": str(item.get("description", ""))[:500], "department": str(item.get("department", ""))[:120], "target": target, "latest_value": latest, "target": item.get("target"), "latest_value": item.get("latest_value"), "status": str(item.get("status", ""))[:80], "daily_history": recent_history, "calculated_metrics": metrics, "daily_history": history[-15:], })
if not cleaned: raise HTTPException(status_code=400, detail="لا توجد بيانات مؤشرات قابلة للتحليل.") return cleaned62 unmodified lines
system = ( f"You are a careful KPI performance analyst. Reply in {lang}. " "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. " "Use only supplied data; never invent figures, trends, causes or facts. " f"Return valid JSON only with schema {schema}. " "Exactly 3 insights in this order: notable improvement, alert, recommendation. " "For Arabic, titles must be exactly: تحسين ملحوظ, تنبيه, توصية. "1 unmodified line "For every insight, provide all four fields: title, finding, evidence, recommendation. " "Do not omit the recommendation field. " "Write a detailed but concise analysis similar to a professional KPI dashboard. " "In finding, explain the supplied change_from_previous and current value when available. " "In finding, describe what changed and include the relevant values when available. " "Always use the human-readable kpi_name instead of technical IDs such as KPI_01. " "Never write KPI IDs when the indicator name is available. " "In evidence, cite the supplied calculated_metrics and recent history values/dates. Do not derive new numbers from raw history. " "In evidence, explain the specific supporting values, dates, or trends from the data. " "In recommendation, always provide a practical, actionable next step based on the findings. " "Do not repeat the title inside finding. " "Do not add the labels 'الدليل من البيانات:' or 'الإجراء المقترح:' "11 unmodified lines '"department":"...","target":90,"formula":"...",' '"rationale":"...","data_needed":"..."}]}') system = ( 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. " f"You are a KPI design specialist. Reply in {lang}. 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." )app.py+7-75