Upload 2 files
#1
by Batoul2005 - opened
Files changed (2)
- app.pyAdded+228
- requirements.txtAdded+2
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228import jsonimport osfrom pathlib import Path
import gradio as grfrom huggingface_hub import InferenceClient
BASE_DIR = Path(__file__).resolve().parentMODEL_ID = os.getenv("HF_MODEL_ID", "Qwen/Qwen2.5-7B-Instruct")
LANG_FILES = { "العربية": BASE_DIR / "data_ar.json", "English": BASE_DIR / "data_en.json",}
SAMPLE_PROMPTS = { "العربية": [ "حلّل مؤشرات الأداء وحدد أهم المخاطر والتوصيات.", "ما المؤشر الأكثر حاجة إلى تدخل؟ استند إلى الأرقام.", "اقترح 3 مؤشرات أداء جديدة مرتبطة بالبيانات الحالية بصيغة JSON.", ], "English": [ "Analyze the KPIs and identify the main risks and recommendations.", "Which KPI needs the most intervention? Use the data.", "Suggest 3 new KPIs related to the current data in JSON format.", ],}
def load_json_file(path): if not path: raise ValueError("لم يتم اختيار ملف JSON.") with open(path, "r", encoding="utf-8") as f: data = json.load(f) if isinstance(data, dict): # Accept either a list or a wrapper object containing a KPI list. for key in ("kpis", "data", "items", "indicators"): if isinstance(data.get(key), list): data = data[key] break if not isinstance(data, list): raise ValueError("يجب أن يحتوي JSON على قائمة مؤشرات أو على كائن يحوي قائمة kpis/data/items/indicators.") if not data: raise ValueError("ملف JSON لا يحتوي على أي مؤشرات.") return data
def pick_data(language, uploaded_file, sample_choice): if uploaded_file: return load_json_file(uploaded_file), "الملف المرفوع" path = LANG_FILES.get(language, LANG_FILES["العربية"]) return load_json_file(str(path)), path.name
def summarize_data(data, language): total = len(data) values = [] good = medium = delayed = 0 missing = [] for i, item in enumerate(data, 1): if not isinstance(item, dict): missing.append(f"item {i} is not an object") continue for key in ("kpi_name", "latest_value", "target"): if key not in item: missing.append(f"item {i}: missing {key}") try: values.append(float(item.get("latest_value", 0))) except (TypeError, ValueError): pass status = str(item.get("status", "")).lower() if any(x in status for x in ("good", "جيد")): good += 1 elif any(x in status for x in ("medium", "needs", "follow", "متوسط", "متابعة")): medium += 1 else: delayed += 1
avg = sum(values) / len(values) if values else 0 if language == "English": lines = [ "## Data summary (calculated from the uploaded JSON)", f"- KPI count: **{total}**", f"- Good: **{good}** | Needs follow-up: **{medium}** | Other/delayed: **{delayed}**", f"- Average latest value: **{avg:.1f}**", ] if missing: lines.append("- Data quality notes: " + "; ".join(missing[:8])) else: lines = [ "## ملخص البيانات (محسوب برمجياً من ملف JSON)", f"- عدد المؤشرات: **{total}**", f"- جيد: **{good}** | يحتاج متابعة: **{medium}** | حالات أخرى/متأخرة: **{delayed}**", f"- متوسط آخر القيم المسجلة: **{avg:.1f}**", ] if missing: lines.append("- ملاحظات على البيانات: " + "؛ ".join(missing[:8])) return "\n".join(lines)
def call_qwen(language, data, question): token = os.getenv("HF_TOKEN") if not token: message = ( "لم يتم ضبط سر HF_TOKEN في إعدادات Space. أضيفي Hugging Face User Access Token " "في Settings → Secrets ثم أعيدي تشغيل Space." if language == "العربية" else "HF_TOKEN is not configured in Space Settings → Secrets. Add a Hugging Face User Access Token and restart the Space." ) return message
try: client = InferenceClient(model=MODEL_ID, token=token) lang_instruction = ( "Respond in Arabic. Use only the supplied KPI data as factual evidence." if language == "العربية" else "Respond in English. Use only the supplied KPI data as factual evidence." ) system_prompt = ( "You are an analytical assistant for a KPI performance platform. " "Analyze the JSON provided by the user. Do not invent numbers, trends, departments, " "causes, or facts that are not present in the data. Clearly distinguish observed facts " "from recommendations or hypotheses. If information is missing, say so. " "When asked to generate new KPIs, output valid JSON with an array of objects containing " "kpi_name, description, department, target, measurement_method, and rationale. " + lang_instruction ) payload = json.dumps(data, ensure_ascii=False) # Keep the prompt bounded for hosted inference services. if len(payload) > 24000: payload = json.dumps( [ {k: v for k, v in item.items() if k != "daily_history"} | {"daily_history": item.get("daily_history", [])[-10:]} for item in data ], ensure_ascii=False, ) user_prompt = ( f"KPI JSON data:\n{payload}\n\n" f"User request:\n{question.strip() or ('Analyze the KPIs and recommend next steps.' if language == 'English' else 'حلّل المؤشرات وقدّم توصيات عملية.')}" ) response = client.chat_completion( messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}, ], max_tokens=900, temperature=0.3, ) return response.choices[0].message.content or "The model returned an empty response." except Exception as exc: return ( f"تعذّر الاتصال بالمودل ({type(exc).__name__}): {exc}\n\n" "تحققي من أن المودل متاح عبر Inference Providers وأن الرمز يملك صلاحية Make calls to Inference Providers." if language == "العربية" 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." )
def run_analysis(language, uploaded_file, sample_choice, question): try: data, source = pick_data(language, uploaded_file, sample_choice) summary = summarize_data(data, language) answer = call_qwen(language, data, question) source_label = f"\n\n**مصدر البيانات:** {source}" if language == "العربية" else f"\n\n**Data source:** {source}" return summary + source_label, answer, json.dumps(data, ensure_ascii=False, indent=2) except Exception as exc: error = f"خطأ في قراءة البيانات: {exc}" if language == "العربية" else f"Data loading error: {exc}" return error, "", ""
def update_examples(language): prompts = SAMPLE_PROMPTS.get(language, SAMPLE_PROMPTS["العربية"]) return gr.update(choices=prompts, value=prompts[0])
with gr.Blocks(title="منصة الأداء | KPI AI", theme=gr.themes.Soft()) as demo: gr.Markdown( "# ✨ منصة الأداء — تحليل مؤشرات الأداء بالذكاء الاصطناعي\n" "اختاري ملف بيانات، راجعي ملخصاً محسوباً من الأرقام الفعلية، ثم اطلبي من Qwen تحليلها." ) with gr.Row(): language = gr.Dropdown( choices=["العربية", "English"], value="العربية", label="لغة الواجهة / Interface language", ) sample_choice = gr.Dropdown( choices=SAMPLE_PROMPTS["العربية"], value=SAMPLE_PROMPTS["العربية"][0], label="مثال جاهز / Example prompt", ) upload = gr.File( label="رفع ملف JSON (اختياري — إذا لم ترفعي ملفاً سيُستخدم ملف اللغة المختارة)", file_types=[".json", ".txt"], type="filepath", ) question = gr.Textbox( label="طلبك من المودل / Ask the model", placeholder="مثلاً: ما المؤشر الأكثر حاجة إلى تدخل؟ ولماذا؟", lines=3, ) with gr.Row(): run_button = gr.Button("تحليل البيانات باستخدام Qwen", variant="primary") clear_button = gr.ClearButton([upload, question]) summary_output = gr.Markdown(label="ملخص البيانات") answer_output = gr.Markdown(label="رد Qwen") with gr.Accordion("عرض بيانات JSON التي قرأها التطبيق", open=False): json_output = gr.Code(label="JSON", language="json")
run_button.click( fn=run_analysis, inputs=[language, upload, sample_choice, question], outputs=[summary_output, answer_output, json_output], ) sample_choice.change( fn=lambda x: x, inputs=[sample_choice], outputs=[question], ) language.change( fn=update_examples, inputs=[language], outputs=[sample_choice], )
demo.launch()12gradio>=5.0,<7.0huggingface_hub>=0.30.0app.pyAdded+228
requirements.txtAdded+2