Update app.py
Browse files1 unmodified line234567851 unmodified lines6061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015162 unmodified lines2142152162172182192201 unmodified line22222322422522622722822923023111 unmodified lines2432442452462472482491 unmodified lineimport osimport refrom pathlib import Pathimport mathimport gradio as grimport spaces51 unmodified linesdef 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):continuehistory = 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):continuevalue = 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 Noneelse:latest = float(latest)previous = (recent_history[-2]["value"]if len(recent_history) >= 2else None)target = item.get("target")if not isinstance(target, (int, float)) or not math.isfinite(target):target = Noneelse: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 Noneelse 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 Noneelse 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,"status": str(item.get("status", ""))[:80],"daily_history": recent_history,"calculated_metrics": metrics,})if not cleaned:raise HTTPException(status_code=400, detail="لا توجد بيانات مؤشرات قابلة للتحليل.")return cleaned62 unmodified linessystem = (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. "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. ""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 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. ""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.")1 unmodified line23456751 unmodified lines5960616263646566676869707172737475767778798081828362 unmodified lines1461471481491501511521 unmodified line15415515615715815916016116216311 unmodified lines1751761771781791801811 unmodified lineimport osimport refrom pathlib import Pathimport gradio as grimport spaces51 unmodified linesdef clean_kpis(kpis):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):continuehistory = item.get("daily_history", [])if not isinstance(history, list):history = []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": item.get("target"),"latest_value": item.get("latest_value"),"status": str(item.get("status", ""))[:80],"daily_history": history[-15:],})if not cleaned:raise HTTPException(status_code=400, detail="لا توجد بيانات مؤشرات قابلة للتحليل.")return cleaned62 unmodified linessystem = (f"You are a careful KPI performance analyst. Reply in {lang}. ""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, 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, 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}. ""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