Download app.py from seed-image-ai/Performance_Indicators: direct link, hf CLI and curl.
- Browser
- Download file 12.5 kB
-
https://huggingface.co/spaces/seed-image-ai/Performance_Indicators/resolve/main/app.py
- Command line
-
hf download hf://spaces/seed-image-ai/Performance_Indicators/app.py
-
curl -L -o app.py https://huggingface.co/spaces/seed-image-ai/Performance_Indicators/resolve/main/app.py
12.5 kB
| import json | |
| import os | |
| import re | |
| from pathlib import Path | |
| import gradio as gr | |
| import spaces | |
| import torch | |
| from fastapi import HTTPException, Request | |
| from fastapi.responses import FileResponse, JSONResponse | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| BASE_DIR = Path(__file__).resolve().parent | |
| MODEL_ID = os.getenv("HF_MODEL_ID", "Qwen/Qwen2.5-7B-Instruct") | |
| INDEX_FILE = BASE_DIR / "index.html" | |
| CSS_FILE = BASE_DIR / "style.css" | |
| JS_FILE = BASE_DIR / "script.js" | |
| DATA_AR_FILE = BASE_DIR / "data_ar.json" | |
| DATA_EN_FILE = BASE_DIR / "data_en.json" | |
| # Load model weights onto CPU at startup; ZeroGPU allocates the GPU per request. | |
| print(f"[startup] Loading local model: {MODEL_ID}", flush=True) | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL_ID, | |
| torch_dtype=torch.float16, | |
| low_cpu_mem_usage=True, | |
| ) | |
| model.eval() | |
| print("[startup] Qwen model loaded on CPU", flush=True) | |
| def file_response(path: Path, media_type: str): | |
| if not path.is_file(): | |
| raise HTTPException(status_code=404, detail=f"File not found: {path.name}") | |
| return FileResponse(str(path), media_type=media_type) | |
| async def serve_ui(): | |
| return file_response(INDEX_FILE, "text/html; charset=utf-8") | |
| async def serve_css(): | |
| return file_response(CSS_FILE, "text/css; charset=utf-8") | |
| async def serve_js(): | |
| return file_response(JS_FILE, "application/javascript; charset=utf-8") | |
| async def serve_data_ar(): | |
| return file_response(DATA_AR_FILE, "application/json") | |
| async def serve_data_en(): | |
| return file_response(DATA_EN_FILE, "application/json") | |
| def 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): | |
| continue | |
| history = 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 cleaned | |
| def calculate_actual_metrics(kpis): | |
| """حساب الأرقام والنسب والإحصائيات الفعليّة مسبقاً في البايثون بدقة تامة""" | |
| total_kpis = len(kpis) | |
| if total_kpis == 0: | |
| return {} | |
| total_latest_sum = 0 | |
| best_kpi = None | |
| max_progress = -1 | |
| delayed_kpis = [] | |
| improved_kpis = [] | |
| for item in kpis: | |
| name = item.get("kpi_name", "مؤشر غير معروف") | |
| latest = float(item.get("latest_value", 0)) | |
| target = float(item.get("target", 100)) | |
| total_latest_sum += latest | |
| achievement_rate = round((latest / target) * 100, 1) if target > 0 else 0 | |
| if latest > max_progress: | |
| max_progress = latest | |
| best_kpi = {"name": name, "latest": latest, "target": target, "rate": achievement_rate} | |
| status = str(item.get("status", "")) | |
| if latest < target or "متابعة" in status or "متأخر" in status: | |
| diff = round(target - latest, 1) | |
| delayed_kpis.append({"name": name, "latest": latest, "target": target, "diff": diff}) | |
| history = item.get("daily_history", []) | |
| if len(history) >= 2: | |
| first_val = float(history[0].get("value", latest)) | |
| change = round(latest - first_val, 1) | |
| if change > 0: | |
| improved_kpis.append({"name": name, "change": change, "latest": latest}) | |
| avg_achievement = round(total_latest_sum / total_kpis, 1) | |
| return { | |
| "total_kpis": total_kpis, | |
| "avg_achievement": avg_achievement, | |
| "best_kpi": best_kpi, | |
| "delayed_kpis": delayed_kpis, | |
| "improved_kpis": improved_kpis | |
| } | |
| def parse_json_response(content): | |
| """Extract a valid JSON object or array from the model response.""" | |
| text = str(content).strip() | |
| text = re.sub(r"^\s*```(?:json)?\s*", "", text, flags=re.IGNORECASE) | |
| text = re.sub(r"\s*```\s*$", "", text) | |
| decoder = json.JSONDecoder() | |
| for i, char in enumerate(text): | |
| if char not in "{[": | |
| continue | |
| try: | |
| result, _ = decoder.raw_decode(text[i:]) | |
| if isinstance(result, (dict, list)): | |
| return result | |
| except json.JSONDecodeError: | |
| continue | |
| cleaned = re.sub(r",\s*([}\]])", r"\1", text) | |
| for i, char in enumerate(cleaned): | |
| if char not in "{[": | |
| continue | |
| try: | |
| result, _ = decoder.raw_decode(cleaned[i:]) | |
| if isinstance(result, (dict, list)): | |
| return result | |
| except json.JSONDecodeError: | |
| continue | |
| preview = text[:700] | |
| raise ValueError( | |
| "Qwen did not return valid JSON. Response preview: " + preview | |
| ) | |
| def generate_local_qwen(language, kpis, task): | |
| inputs = None | |
| model_on_gpu = False | |
| try: | |
| model.to("cuda") | |
| model_on_gpu = True | |
| is_ar = language != "en" | |
| lang = "Arabic" if is_ar else "English" | |
| metrics = calculate_actual_metrics(kpis) | |
| if task == "insights": | |
| key = "insights" | |
| schema = ( | |
| '{"insights":[' | |
| '{"title":"...","finding":"...",' | |
| '"evidence":"...","recommendation":"..."},' | |
| '{"title":"...","finding":"...",' | |
| '"evidence":"...","recommendation":"..."},' | |
| '{"title":"...","finding":"...",' | |
| '"evidence":"...","recommendation":"..."}' | |
| ']}' | |
| ) | |
| system = ( | |
| f"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. " | |
| f"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." | |
| ) | |
| user = ( | |
| f"Pre-calculated actual metrics:\n{json.dumps(metrics, ensure_ascii=False)}\n\n" | |
| f"Raw KPI data:\n{json.dumps(kpis, ensure_ascii=False)}\n\n" | |
| "Task: Format these pre-calculated metrics and findings into the 3 requested JSON insights in pure Arabic." | |
| ) | |
| else: | |
| key = "indicators" | |
| schema = ('{"indicators":[{"kpi_name":"...","description":"...",' | |
| '"department":"...","target":90,"formula":"...",' | |
| '"rationale":"...","data_needed":"..."}]}') | |
| system = ( | |
| f"You are a KPI design specialist. CRITICAL: Reply strictly and exclusively in {lang}. " | |
| "DO NOT mix any Chinese or foreign characters. " | |
| f"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." | |
| ) | |
| user = "Suggest 3 new KPIs relevant to the organization represented by these existing indicators. Avoid duplicates. Existing KPI data:\n" + json.dumps(kpis, ensure_ascii=False) | |
| messages = [{"role": "system", "content": system}, {"role": "user", "content": user}] | |
| prompt_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) | |
| inputs = tokenizer(prompt_text, return_tensors="pt", truncation=True, max_length=8192).to("cuda") | |
| with torch.inference_mode(): | |
| output = model.generate( | |
| **inputs, | |
| max_new_tokens=1600, | |
| do_sample=False, | |
| pad_token_id=tokenizer.eos_token_id, | |
| eos_token_id=tokenizer.eos_token_id, | |
| ) | |
| new_tokens = output[0][inputs["input_ids"].shape[1]:] | |
| answer = tokenizer.decode(new_tokens, skip_special_tokens=True).strip() | |
| parsed = parse_json_response(answer) | |
| if isinstance(parsed, list): | |
| parsed = {key: parsed} | |
| if not isinstance(parsed, dict) or not isinstance(parsed.get(key), list) or len(parsed[key]) != 3: | |
| raise ValueError("لم يرجع النموذج ثلاثة عناصر بالشكل المطلوب.") | |
| return parsed | |
| finally: | |
| if inputs is not None: | |
| del inputs | |
| if model_on_gpu: | |
| model.to("cpu") | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| async def run_task(request: Request, task: str): | |
| try: | |
| body = await request.json() | |
| if not isinstance(body, dict): | |
| raise HTTPException(status_code=400, detail="يجب إرسال JSON object.") | |
| language = body.get("language", "ar") | |
| if language not in ("ar", "en"): | |
| language = "ar" | |
| kpis = clean_kpis(body.get("kpis")) | |
| result = generate_local_qwen(language, kpis, task) | |
| return JSONResponse(content=result) | |
| except HTTPException: | |
| raise | |
| except Exception as exc: | |
| print(f"[AI error] {type(exc).__name__}: {exc}", flush=True) | |
| raise HTTPException(status_code=500, detail=f"تعذر تشغيل Qwen محليًا ({type(exc).__name__}): {exc}") from exc | |
| async def insights(request: Request): | |
| return await run_task(request, "insights") | |
| async def generate_kpis(request: Request): | |
| return await run_task(request, "generate-kpis") | |
| # Serve the custom frontend directly using Gradio Server mode. | |
| app = gr.Server() | |
| async def homepage(): | |
| return file_response(INDEX_FILE, "text/html; charset=utf-8") | |
| async def serve_custom_ui(): | |
| return file_response(INDEX_FILE, "text/html; charset=utf-8") | |
| async def serve_stylesheet(): | |
| return file_response(CSS_FILE, "text/css; charset=utf-8") | |
| async def serve_javascript(): | |
| return file_response(JS_FILE, "application/javascript; charset=utf-8") | |
| async def serve_arabic_data(): | |
| return file_response(DATA_AR_FILE, "application/json") | |
| async def serve_english_data(): | |
| return file_response(DATA_EN_FILE, "application/json") | |
| async def insights_endpoint(request: Request): | |
| return await run_task(request, "insights") | |
| async def generate_kpis_endpoint(request: Request): | |
| return await run_task(request, "generate-kpis") | |
| if __name__ == "__main__": | |
| app.launch( | |
| server_name="0.0.0.0", | |
| server_port=int(os.getenv("PORT", "7860")), | |
| ) |