Asem75 commited on
Commit
db4506d
·
verified ·
1 Parent(s): ec34ed3

Upload 13 files

Browse files
admin_office_app_patch.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # admin_office_app_patch.py
2
+ #!/usr/bin/env python3
3
+ # -*- coding: utf-8 -*-
4
+
5
+ """
6
+ Patch صغير لربط admin_office_ui.py بالـ app.py الحالي.
7
+
8
+ السبب:
9
+ app.py الحالي هو Bridge يقوم بتعديل app_original.py وقت التشغيل.
10
+ بدل إعادة كتابة التطبيق كله، نضيف مكتب الإدارة الجديد ونُبقي
11
+ واجهة إدارة التسجيل القديمة مخفية للتوافق مع التوصيلات الموجودة.
12
+
13
+ الاستخدام داخل _patch_source في app.py:
14
+ from admin_office_app_patch import apply_admin_office_patch
15
+ source = apply_admin_office_patch(source)
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+
21
+ VERSION = "admin_office_app_patch_v2_reports_repositories"
22
+
23
+
24
+ def apply_admin_office_patch(source: str) -> str:
25
+ if not isinstance(source, str) or not source.strip():
26
+ raise RuntimeError("مصدر app.py فارغ.")
27
+
28
+ marker = ' with gr.Accordion("إدارة تسجيل الطلاب", open=True):'
29
+
30
+ if marker not in source:
31
+ # دعم نسخة قديمة بتنسيق السطر نفسه لكن بدون المسافات المتوقعة.
32
+ loose_marker = 'with gr.Accordion("إدارة تسجيل الطلاب", open=True):'
33
+ if loose_marker not in source:
34
+ raise RuntimeError(
35
+ "لم أجد واجهة إدارة تسجيل الطلاب القديمة داخل المصدر. "
36
+ "لم يتم تطبيق Patch حتى لا نكسر التطبيق."
37
+ )
38
+ marker = loose_marker
39
+ indent = source[source.rfind("\n", 0, source.find(marker)) + 1:source.find(marker)]
40
+ else:
41
+ indent = " "
42
+
43
+ replacement = (
44
+ indent + "# مكتب الإدارة الجديد - يبنى فوق AdminManager الحالي\n"
45
+ + indent + "try:\n"
46
+ + indent + " from admin_office_ui import build_admin_office\n"
47
+ + indent + " _ADMIN_OFFICE_COMPONENTS = build_admin_office(\n"
48
+ + indent + " get_admin_manager=get_admin_manager,\n"
49
+ + indent + " get_student_manager=get_student_manager,\n"
50
+ + indent + " admin_key=ADMIN_PANEL_KEY,\n"
51
+ + indent + " )\n"
52
+ + indent + "except Exception as _admin_office_error:\n"
53
+ + indent + " gr.Markdown(\n"
54
+ + indent + ' "### تعذر تحميل مكتب الإدارة الجديد\\n\\n"\n'
55
+ + indent + " + str(_admin_office_error)\n"
56
+ + indent + " )\n\n"
57
+ + indent + "# نبقي الواجهة القديمة مخفية حتى لا تنكسر التوصيلات الحالية\n"
58
+ + indent + 'with gr.Accordion("إدارة تسجيل الطلاب القديمة - توافق", open=False, visible=False):'
59
+ )
60
+
61
+ patched = source.replace(marker, replacement, 1)
62
+
63
+ required = [
64
+ "from admin_office_ui import build_admin_office",
65
+ "_ADMIN_OFFICE_COMPONENTS = build_admin_office(",
66
+ 'visible=False):',
67
+ ]
68
+ missing = [item for item in required if item not in patched]
69
+ if missing:
70
+ raise RuntimeError("فشل التحقق من Patch مكتب الإدارة: " + repr(missing))
71
+
72
+ return patched
73
+
74
+
75
+ def summary():
76
+ return {
77
+ "success": True,
78
+ "ready": True,
79
+ "version": VERSION,
80
+ "role": "admin_office_bridge_patch",
81
+ "message": "Patch مكتب الإدارة جاهز: الطلاب + بلاغات الأسئلة + المستودعات.",
82
+ }
admin_office_ui.py ADDED
@@ -0,0 +1,1589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # admin_office_ui.py
2
+ #!/usr/bin/env python3
3
+ # -*- coding: utf-8 -*-
4
+
5
+ """
6
+ مكتب الإدارة المرئي لمنصة Divid Teacher.
7
+
8
+ الإصدار:
9
+ admin_office_ui_v1_dashboard_students_academic_system
10
+
11
+ هذا الملف لا يستبدل AdminManager.
12
+ هو طبقة واجهة فقط فوق admin_manager.py الحالي.
13
+
14
+ المزايا:
15
+ - لوحة رئيسية بإحصاءات الحسابات وحالة الخدمات.
16
+ - البحث في الطلاب وعرضهم حسب الحالة.
17
+ - فتح ملف الطالب وتعديل البيانات المسموح بها.
18
+ - تفعيل / انتظار / إيقاف / رفض الحساب.
19
+ - إعادة إنشاء أو تغيير مفتاح الدخول.
20
+ - إعادة ضبط كلمة مرور ولي الأمر.
21
+ - عرض الأجهزة الموثوقة وحذف جهاز أو جميع الأجهزة.
22
+ - حذف حساب محلي بتأكيد صريح.
23
+ - عرض الملف الأكاديمي من StudentAcademicManager إذا كان متاحًا.
24
+ - عرض لقطة النظام وسجل عمليات الإدارة.
25
+
26
+ مهم:
27
+ - لا يخزن كلمة مرور المدير.
28
+ - يستقبل ADMIN_PANEL_KEY من app.py بعد نجاح بوابة المدير.
29
+ - لا يقرأ أو يعرض Hash كلمة مرور ولي الأمر.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import html
35
+ import json
36
+ import traceback
37
+ from typing import Any, Dict, List, Optional, Tuple
38
+
39
+ import gradio as gr
40
+
41
+
42
+ VERSION = "admin_office_ui_v2_question_reports_repositories"
43
+
44
+ STATUS_LABELS = {
45
+ "all": "الكل",
46
+ "pending": "بانتظار التفعيل",
47
+ "active": "نشط",
48
+ "suspended": "موقوف",
49
+ "rejected": "مرفوض",
50
+ }
51
+
52
+ STATUS_FROM_UI = {
53
+ "الكل": "all",
54
+ "بانتظار التفعيل": "pending",
55
+ "نشط": "active",
56
+ "موقوف": "suspended",
57
+ "مرفوض": "rejected",
58
+ "pending": "pending",
59
+ "active": "active",
60
+ "suspended": "suspended",
61
+ "rejected": "rejected",
62
+ "all": "all",
63
+ }
64
+
65
+ STATUS_ICON = {
66
+ "pending": "⏳",
67
+ "active": "✅",
68
+ "suspended": "⛔",
69
+ "rejected": "❌",
70
+ }
71
+
72
+ STUDENT_EDITABLE_FIELDS = (
73
+ "full_name",
74
+ "birth_date",
75
+ "age",
76
+ "country",
77
+ "grade",
78
+ "phone",
79
+ "email",
80
+ "gender",
81
+ "preferred_dialect",
82
+ "voice_locale",
83
+ "voice_gender",
84
+ "voice_language_mode",
85
+ "scientific_terms_mode",
86
+ )
87
+
88
+
89
+ def _text(value: Any) -> str:
90
+ return str(value if value is not None else "").strip()
91
+
92
+
93
+ def _json(value: Any) -> str:
94
+ try:
95
+ return json.dumps(value, ensure_ascii=False, indent=2, default=str)
96
+ except Exception:
97
+ return str(value)
98
+
99
+
100
+ def _safe_html(value: Any) -> str:
101
+ return html.escape(_text(value))
102
+
103
+
104
+ def _result_markdown(title: str, result: Any) -> str:
105
+ if isinstance(result, dict):
106
+ success = bool(result.get("success"))
107
+ icon = "✅" if success else "❌"
108
+ message = _text(result.get("message"))
109
+ lines = [f"### {icon} {title}"]
110
+ if message:
111
+ lines.append(message)
112
+
113
+ if result.get("warning"):
114
+ lines.append(f"\n⚠️ {_text(result.get('warning'))}")
115
+
116
+ if result.get("access_key"):
117
+ lines.append(f"\n**مفتاح الدخول الجديد:** `{_text(result.get('access_key'))}`")
118
+
119
+ if not message and not success:
120
+ lines.append("\n```json\n" + _json(result) + "\n```")
121
+ return "\n\n".join(lines)
122
+
123
+ return f"### {title}\n\n{_text(result)}"
124
+
125
+
126
+ def _student_name(student: Dict[str, Any]) -> str:
127
+ return _text(
128
+ student.get("full_name")
129
+ or student.get("name")
130
+ or student.get("student_name")
131
+ or student.get("identity")
132
+ or "طالب"
133
+ )
134
+
135
+
136
+ def _student_identity(student: Dict[str, Any]) -> str:
137
+ return _text(student.get("identity") or student.get("student_id"))
138
+
139
+
140
+ def _compact_student_line(student: Dict[str, Any]) -> str:
141
+ identity = _student_identity(student)
142
+ name = _student_name(student)
143
+ grade = _text(student.get("grade"))
144
+ status = _text(student.get("account_status") or "pending")
145
+ icon = STATUS_ICON.get(status, "•")
146
+ return f"{icon} **{name}** — `{identity}` — الصف: {grade or '-'} — {STATUS_LABELS.get(status, status)}"
147
+
148
+
149
+ def _normalize_status(value: Any) -> str:
150
+ raw = _text(value)
151
+ return STATUS_FROM_UI.get(raw, raw.lower() or "all")
152
+
153
+
154
+ def _manager_from(get_admin_manager):
155
+ manager = get_admin_manager() if callable(get_admin_manager) else get_admin_manager
156
+ if manager is None:
157
+ raise RuntimeError("AdminManager غير متاح.")
158
+ return manager
159
+
160
+
161
+ def _resolve_student(manager, query: Any, admin_key: str) -> Tuple[Optional[Dict[str, Any]], str]:
162
+ wanted = _text(query)
163
+ if not wanted:
164
+ return None, "أدخل مفتاح الدخول أو الاسم أو البريد أو رقم الهاتف أو معرّف الطالب."
165
+
166
+ # البحث المركزي الموجود في AdminManager.
167
+ result = manager.list_students(
168
+ status="all",
169
+ full_profiles=True,
170
+ search_text=wanted,
171
+ admin_key=admin_key,
172
+ )
173
+ if not isinstance(result, dict) or not result.get("success"):
174
+ return None, _text(result.get("message") if isinstance(result, dict) else result) or "تعذر البحث."
175
+
176
+ students = result.get("students") or []
177
+ if not isinstance(students, list) or not students:
178
+ return None, "لم يتم العثور على طالب مطابق."
179
+
180
+ wanted_lower = wanted.lower()
181
+ exact_fields = (
182
+ "identity",
183
+ "student_id",
184
+ "access_key",
185
+ "email",
186
+ "phone",
187
+ "full_name",
188
+ "name",
189
+ )
190
+
191
+ exact = []
192
+ for student in students:
193
+ if not isinstance(student, dict):
194
+ continue
195
+ for field in exact_fields:
196
+ if _text(student.get(field)).lower() == wanted_lower:
197
+ exact.append(student)
198
+ break
199
+
200
+ if len(exact) == 1:
201
+ return exact[0], ""
202
+
203
+ if len(students) == 1:
204
+ return students[0], ""
205
+
206
+ preview = "\n".join(
207
+ f"- {_compact_student_line(student)}"
208
+ for student in students[:10]
209
+ if isinstance(student, dict)
210
+ )
211
+ return None, (
212
+ "يوجد أكثر من طالب مطابق. استخدم مفتاح الدخول أو المعرّف الدقيق.\n\n"
213
+ + preview
214
+ )
215
+
216
+
217
+ def _service_state(service: Any) -> Tuple[str, str]:
218
+ if not isinstance(service, dict):
219
+ return "⚪", "غير معروف"
220
+ if service.get("success") is True or service.get("ready") is True:
221
+ return "🟢", "جاهز"
222
+ if service.get("available") is False:
223
+ return "🔴", "غير متاح"
224
+ return "🟠", "يحتاج فحص"
225
+
226
+
227
+ def _dashboard_html(manager, admin_key: str) -> str:
228
+ counts_result = manager.student_status_counts(admin_key=admin_key)
229
+ counts = counts_result.get("counts", {}) if isinstance(counts_result, dict) else {}
230
+ total = counts_result.get("total", 0) if isinstance(counts_result, dict) else 0
231
+
232
+ try:
233
+ snapshot = manager.system_snapshot(admin_key=admin_key)
234
+ except Exception:
235
+ snapshot = {}
236
+ services = snapshot.get("services", {}) if isinstance(snapshot, dict) else {}
237
+
238
+ cards = [
239
+ ("جميع الطلاب", total, "👥"),
240
+ ("بانتظار التفعيل", counts.get("pending", 0), "⏳"),
241
+ ("الحسابات النشطة", counts.get("active", 0), "✅"),
242
+ ("الحسابات الموقوفة", counts.get("suspended", 0), "⛔"),
243
+ ("الحسابات المرفوضة", counts.get("rejected", 0), "❌"),
244
+ ]
245
+
246
+ cards_html = "".join(
247
+ f"""
248
+ <div class="divid-admin-card">
249
+ <div class="divid-admin-card-icon">{icon}</div>
250
+ <div class="divid-admin-card-number">{_safe_html(number)}</div>
251
+ <div class="divid-admin-card-label">{_safe_html(label)}</div>
252
+ </div>
253
+ """
254
+ for label, number, icon in cards
255
+ )
256
+
257
+ service_rows = []
258
+ for key, label in [
259
+ ("student_manager", "StudentManager"),
260
+ ("device_identity_manager", "DeviceIdentityManager"),
261
+ ("badge_progress_manager", "BadgeProgressManager"),
262
+ ("report_manager", "ReportManager"),
263
+ ("ai_task_queue_manager", "AITaskQueueManager"),
264
+ ("language_manager", "LanguageManager"),
265
+ ]:
266
+ icon, state = _service_state(services.get(key))
267
+ service_rows.append(
268
+ f"<tr><td>{_safe_html(label)}</td><td>{icon} {_safe_html(state)}</td></tr>"
269
+ )
270
+
271
+ return f"""
272
+ <style>
273
+ .divid-admin-office {{
274
+ direction: rtl;
275
+ font-family: inherit;
276
+ }}
277
+ .divid-admin-header {{
278
+ padding: 18px 20px;
279
+ border: 1px solid rgba(148,163,184,.25);
280
+ border-radius: 18px;
281
+ margin-bottom: 14px;
282
+ }}
283
+ .divid-admin-header h2 {{
284
+ margin: 0 0 6px 0;
285
+ }}
286
+ .divid-admin-grid {{
287
+ display: grid;
288
+ grid-template-columns: repeat(auto-fit,minmax(145px,1fr));
289
+ gap: 10px;
290
+ margin: 12px 0 18px;
291
+ }}
292
+ .divid-admin-card {{
293
+ border: 1px solid rgba(148,163,184,.25);
294
+ border-radius: 16px;
295
+ padding: 14px 10px;
296
+ text-align: center;
297
+ min-height: 105px;
298
+ }}
299
+ .divid-admin-card-icon {{font-size: 25px;}}
300
+ .divid-admin-card-number {{font-size: 26px;font-weight: 800;margin-top: 4px;}}
301
+ .divid-admin-card-label {{font-size: 13px;opacity:.85;margin-top: 4px;}}
302
+ .divid-admin-table {{
303
+ width: 100%;
304
+ border-collapse: collapse;
305
+ margin-top: 8px;
306
+ }}
307
+ .divid-admin-table th,.divid-admin-table td {{
308
+ border-bottom: 1px solid rgba(148,163,184,.22);
309
+ text-align: right;
310
+ padding: 8px;
311
+ }}
312
+ </style>
313
+
314
+ <div class="divid-admin-office">
315
+ <div class="divid-admin-header">
316
+ <h2>🏢 مكتب الإدارة</h2>
317
+ <div>لوحة التحكم اليومية لمنصة Divid Teacher — {VERSION}</div>
318
+ </div>
319
+
320
+ <div class="divid-admin-grid">
321
+ {cards_html}
322
+ </div>
323
+
324
+ <h3>حالة الخدمات الأساسية</h3>
325
+ <table class="divid-admin-table">
326
+ <thead><tr><th>الخدمة</th><th>الحالة</th></tr></thead>
327
+ <tbody>{''.join(service_rows)}</tbody>
328
+ </table>
329
+ </div>
330
+ """
331
+
332
+
333
+ def _students_markdown(manager, status_filter: Any, search_text: Any, admin_key: str) -> str:
334
+ status = _normalize_status(status_filter)
335
+ result = manager.list_students(
336
+ status=status,
337
+ full_profiles=False,
338
+ search_text=_text(search_text),
339
+ admin_key=admin_key,
340
+ )
341
+ if not isinstance(result, dict) or not result.get("success"):
342
+ return _result_markdown("تعذر عرض الطلاب", result)
343
+
344
+ students = result.get("students") or []
345
+ if not students:
346
+ return "### الطلاب\n\nلا توجد نتائج مطابقة."
347
+
348
+ lines = [
349
+ f"### الطلاب — {len(students)}",
350
+ "",
351
+ "| الطالب | المعرّف | الصف | الحالة | مفتاح الدخول | الأجهزة |",
352
+ "|---|---|---:|---|---|---:|",
353
+ ]
354
+ for student in students[:200]:
355
+ if not isinstance(student, dict):
356
+ continue
357
+ status = _text(student.get("account_status") or "pending")
358
+ lines.append(
359
+ "| {name} | `{identity}` | {grade} | {status} | `{key}` | {devices} |".format(
360
+ name=_student_name(student).replace("|", " "),
361
+ identity=_student_identity(student).replace("|", " "),
362
+ grade=_text(student.get("grade") or "-").replace("|", " "),
363
+ status=(STATUS_ICON.get(status, "•") + " " + STATUS_LABELS.get(status, status)).replace("|", " "),
364
+ key=_text(student.get("access_key") or "-").replace("|", " "),
365
+ devices=_text(student.get("authorized_devices_count") or 0),
366
+ )
367
+ )
368
+
369
+ if len(students) > 200:
370
+ lines.append(f"\n> تم عرض أول 200 طالب من أصل {len(students)}.")
371
+ return "\n".join(lines)
372
+
373
+
374
+ def _academic_summary(identity: str) -> str:
375
+ identity = _text(identity)
376
+ if not identity:
377
+ return "### الملف الأكاديمي\n\nافتح طالبًا أولًا من تبويب **الطلاب**."
378
+
379
+ try:
380
+ from student_academic_manager import get_manager as get_academic_manager
381
+ manager = get_academic_manager()
382
+ profile = manager.load_profile(identity)
383
+ except Exception as exc:
384
+ return (
385
+ "### الملف الأكاديمي\n\n"
386
+ "StudentAcademicManager غير متاح أو لم يكتمل ربطه بعد.\n\n"
387
+ f"`{exc}`"
388
+ )
389
+
390
+ if not isinstance(profile, dict):
391
+ return "### الملف الأكاديمي\n\nلا توجد بيانات أكاديمية قابلة للعرض."
392
+
393
+ counts = {}
394
+ for key in (
395
+ "skill_states",
396
+ "badge_progress",
397
+ "assessment_attempts",
398
+ "answer_events",
399
+ "learning_gaps",
400
+ "remedial_assignments",
401
+ "remedial_sessions",
402
+ "closure_checks",
403
+ "scheduled_rechecks",
404
+ "flashcards",
405
+ "challenge_tests",
406
+ "certificates",
407
+ "lesson_history",
408
+ "mastery_history",
409
+ "game_assignments",
410
+ "interactive_game_results",
411
+ "whiteboard_responses",
412
+ ):
413
+ value = profile.get(key)
414
+ if isinstance(value, dict):
415
+ counts[key] = len(value)
416
+ elif isinstance(value, list):
417
+ counts[key] = len(value)
418
+ elif value:
419
+ counts[key] = 1
420
+ else:
421
+ counts[key] = 0
422
+
423
+ labels = {
424
+ "skill_states": "حالات المهارات",
425
+ "badge_progress": "تقدم الأوسمة",
426
+ "assessment_attempts": "محاولات التقييم",
427
+ "answer_events": "إجابات مسجلة",
428
+ "learning_gaps": "الفجوات التعليمية",
429
+ "remedial_assignments": "تكليفات علاجية",
430
+ "remedial_sessions": "جلسات علاجية",
431
+ "closure_checks": "اختبارات الإغلاق",
432
+ "scheduled_rechecks": "إعادات الفحص",
433
+ "flashcards": "بطاقات المراجعة",
434
+ "challenge_tests": "اختبارات التحدي",
435
+ "certificates": "الشهادات",
436
+ "lesson_history": "سجل الدروس",
437
+ "mastery_history": "سجل الإتقان",
438
+ "game_assignments": "تكليفات الألعاب",
439
+ "interactive_game_results": "نتائج الألعاب",
440
+ "whiteboard_responses": "استجابات السبورة",
441
+ }
442
+
443
+ lines = [
444
+ f"### 📚 الملف الأكاديمي — `{identity}`",
445
+ "",
446
+ "| القسم | العدد |",
447
+ "|---|---:|",
448
+ ]
449
+ for key, value in counts.items():
450
+ lines.append(f"| {labels.get(key, key)} | {value} |")
451
+
452
+ active_gaps = profile.get("learning_gaps") or []
453
+ if isinstance(active_gaps, dict):
454
+ active_gaps = list(active_gaps.values())
455
+ if isinstance(active_gaps, list):
456
+ opened = [
457
+ item for item in active_gaps
458
+ if isinstance(item, dict)
459
+ and _text(item.get("status")).lower() not in {"closed", "mastered", "resolved"}
460
+ ]
461
+ if opened:
462
+ lines.extend(["", "#### الفجوات المفتوحة"])
463
+ for gap in opened[-10:]:
464
+ lines.append(
465
+ "- **{skill}** — الحالة: `{status}` — الشدة: `{intensity}`".format(
466
+ skill=_text(gap.get("skill_id") or gap.get("root_skill_id") or "غير محددة"),
467
+ status=_text(gap.get("status") or "open"),
468
+ intensity=_text(gap.get("intensity") or gap.get("intervention_level") or "-"),
469
+ )
470
+ )
471
+ return "\n".join(lines)
472
+
473
+
474
+ def build_admin_office(
475
+ get_admin_manager,
476
+ admin_key: str,
477
+ get_student_manager=None,
478
+ ) -> Dict[str, Any]:
479
+ """
480
+ يبني مكتب الإدارة داخل بلوك Gradio الحالي.
481
+
482
+ يجب استدعاء هذه الدالة من داخل:
483
+ with gr.Group(visible=False) as admin_panel:
484
+ build_admin_office(...)
485
+
486
+ تسجيل الدخول للمدير يبقى في app.py الحالي.
487
+ """
488
+
489
+ admin_key = _text(admin_key)
490
+
491
+ def manager():
492
+ return _manager_from(get_admin_manager)
493
+
494
+ def storage_manager():
495
+ try:
496
+ from storage_manager import get_manager as get_storage_manager
497
+ return get_storage_manager()
498
+ except Exception as exc:
499
+ raise RuntimeError(f"StorageManager غير متاح: {exc}")
500
+
501
+ def question_report_manager():
502
+ try:
503
+ from question_report_manager import get_manager as get_question_report_manager
504
+ return get_question_report_manager()
505
+ except Exception as exc:
506
+ raise RuntimeError(f"QuestionReportManager غير متاح: {exc}")
507
+
508
+ def refresh_dashboard():
509
+ try:
510
+ return _dashboard_html(manager(), admin_key)
511
+ except Exception as exc:
512
+ return (
513
+ "<div style='direction:rtl'>"
514
+ "<h3>❌ تعذر تحميل لوحة الإدارة</h3>"
515
+ f"<pre>{_safe_html(exc)}</pre></div>"
516
+ )
517
+
518
+ def list_students(status_filter, search_text):
519
+ try:
520
+ return _students_markdown(manager(), status_filter, search_text, admin_key)
521
+ except Exception as exc:
522
+ return f"### ❌ تعذر عرض الطلاب\n\n`{exc}`"
523
+
524
+ def open_student(query):
525
+ try:
526
+ student, error = _resolve_student(manager(), query, admin_key)
527
+ if not isinstance(student, dict):
528
+ return (
529
+ "",
530
+ "",
531
+ "",
532
+ "",
533
+ "",
534
+ "",
535
+ "",
536
+ "",
537
+ "",
538
+ "",
539
+ "",
540
+ "",
541
+ "",
542
+ "",
543
+ "",
544
+ "",
545
+ "",
546
+ "",
547
+ error,
548
+ gr.update(choices=[], value=None),
549
+ "### الأجهزة\n\nافتح طالبًا صحيحًا أولًا.",
550
+ "### الملف الأكاديمي\n\nافتح طالبًا صحيحًا أولًا.",
551
+ )
552
+
553
+ identity = _student_identity(student)
554
+ status = _text(student.get("account_status") or "pending")
555
+
556
+ devices_result = manager().list_student_devices(identity, admin_key=admin_key)
557
+ devices = devices_result.get("devices") or [] if isinstance(devices_result, dict) else []
558
+ choices = []
559
+ device_lines = ["### 📱 الأجهزة الموثوقة"]
560
+ if devices:
561
+ for device in devices:
562
+ if not isinstance(device, dict):
563
+ continue
564
+ fingerprint = _text(device.get("fingerprint_hash"))
565
+ preview = _text(device.get("fingerprint_preview")) or (fingerprint[:8] + "…" if fingerprint else "")
566
+ name = _text(device.get("device_name") or device.get("name") or "جهاز")
567
+ label = f"{name} — {preview or 'بدون بصمة'}"
568
+ if fingerprint:
569
+ choices.append((label, fingerprint))
570
+ device_lines.append(
571
+ f"- **{name}** — `{preview or '-'}` — الحالة: `{_text(device.get('status') or 'active')}`"
572
+ )
573
+ else:
574
+ device_lines.append("\nلا توجد أجهزة موثوقة مسجلة.")
575
+
576
+ message = (
577
+ f"### ✅ تم فتح ملف الطالب\n\n"
578
+ f"**{_student_name(student)}** — `{identity}` — "
579
+ f"{STATUS_ICON.get(status, '•')} {STATUS_LABELS.get(status, status)}"
580
+ )
581
+
582
+ return (
583
+ identity,
584
+ _text(student.get("full_name") or student.get("name")),
585
+ _text(student.get("birth_date")),
586
+ _text(student.get("age")),
587
+ _text(student.get("country")),
588
+ _text(student.get("grade")),
589
+ _text(student.get("phone")),
590
+ _text(student.get("email")),
591
+ _text(student.get("gender")),
592
+ _text(student.get("preferred_dialect")),
593
+ _text(student.get("voice_locale")),
594
+ _text(student.get("voice_gender")),
595
+ _text(student.get("voice_language_mode")),
596
+ _text(student.get("scientific_terms_mode")),
597
+ status,
598
+ _text(student.get("access_key")),
599
+ "",
600
+ "",
601
+ message,
602
+ gr.update(
603
+ choices=choices,
604
+ value=choices[0][1] if choices else None,
605
+ ),
606
+ "\n".join(device_lines),
607
+ _academic_summary(identity),
608
+ )
609
+ except Exception as exc:
610
+ return (
611
+ "", "", "", "", "", "", "", "", "", "", "", "", "", "",
612
+ "", "", "", "",
613
+ f"### ❌ فشل فتح الطالب\n\n`{exc}`",
614
+ gr.update(choices=[], value=None),
615
+ "### الأجهزة\n\nتعذر التحميل.",
616
+ "### الملف الأكاديمي\n\nتعذر التحميل.",
617
+ )
618
+
619
+ def save_student_profile(
620
+ identity,
621
+ full_name,
622
+ birth_date,
623
+ age,
624
+ country,
625
+ grade,
626
+ phone,
627
+ email,
628
+ gender,
629
+ preferred_dialect,
630
+ voice_locale,
631
+ voice_gender,
632
+ voice_language_mode,
633
+ scientific_terms_mode,
634
+ ):
635
+ if not _text(identity):
636
+ return "### ❌ لم يتم اختيار طالب."
637
+ updates = {
638
+ "full_name": _text(full_name),
639
+ "birth_date": _text(birth_date),
640
+ "age": _text(age),
641
+ "country": _text(country),
642
+ "grade": _text(grade),
643
+ "phone": _text(phone),
644
+ "email": _text(email),
645
+ "gender": _text(gender),
646
+ "preferred_dialect": _text(preferred_dialect),
647
+ "voice_locale": _text(voice_locale),
648
+ "voice_gender": _text(voice_gender),
649
+ "voice_language_mode": _text(voice_language_mode),
650
+ "scientific_terms_mode": _text(scientific_terms_mode),
651
+ }
652
+ try:
653
+ result = manager().update_student_profile(
654
+ identity=_text(identity),
655
+ updates=updates,
656
+ changed_by="admin_office",
657
+ admin_key=admin_key,
658
+ )
659
+ return _result_markdown("حفظ بيانات الطالب", result)
660
+ except Exception as exc:
661
+ return f"### ❌ فشل الحفظ\n\n`{exc}`"
662
+
663
+ def change_status(identity, new_status, reason):
664
+ if not _text(identity):
665
+ return "### ❌ افتح ملف طالب أولًا.", gr.skip()
666
+ status = _normalize_status(new_status)
667
+ if status == "all":
668
+ return "### ❌ اختر حالة حساب صحيحة.", gr.skip()
669
+ try:
670
+ result = manager().change_student_registration_status(
671
+ identity=_text(identity),
672
+ new_status=status,
673
+ reason=_text(reason),
674
+ changed_by="admin_office",
675
+ admin_key=admin_key,
676
+ )
677
+ return _result_markdown("تغيير حالة الحساب", result), status
678
+ except Exception as exc:
679
+ return f"### ❌ فشل تغيير الحالة\n\n`{exc}`", gr.skip()
680
+
681
+ def reset_access_key(identity, requested_key):
682
+ if not _text(identity):
683
+ return "### ❌ افتح ملف طالب أولًا.", gr.skip()
684
+ try:
685
+ result = manager().reset_student_access_key(
686
+ identity=_text(identity),
687
+ new_access_key=_text(requested_key),
688
+ changed_by="admin_office",
689
+ admin_key=admin_key,
690
+ )
691
+ new_key = _text(result.get("access_key")) if isinstance(result, dict) else ""
692
+ return _result_markdown("تحديث مفتاح الدخول", result), (new_key or gr.skip())
693
+ except Exception as exc:
694
+ return f"### ❌ تعذر تحديث مفتاح الدخول\n\n`{exc}`", gr.skip()
695
+
696
+ def reset_parent_password(identity, new_password):
697
+ if not _text(identity):
698
+ return "### ❌ افتح ملف طالب أولًا.", ""
699
+ try:
700
+ result = manager().reset_parent_password(
701
+ identity=_text(identity),
702
+ new_parent_password=_text(new_password),
703
+ changed_by="admin_office",
704
+ admin_key=admin_key,
705
+ )
706
+ return _result_markdown("إعادة ضبط كلمة مرور ولي الأمر", result), ""
707
+ except Exception as exc:
708
+ return f"### ❌ تعذر إعادة الضبط\n\n`{exc}`", ""
709
+
710
+ def refresh_devices(identity):
711
+ if not _text(identity):
712
+ return gr.update(choices=[], value=None), "### الأجهزة\n\nافتح طالبًا أولًا."
713
+ try:
714
+ result = manager().list_student_devices(_text(identity), admin_key=admin_key)
715
+ devices = result.get("devices") or [] if isinstance(result, dict) else []
716
+ choices = []
717
+ lines = [f"### 📱 الأجهزة الموثوقة — {len(devices)}"]
718
+ for device in devices:
719
+ if not isinstance(device, dict):
720
+ continue
721
+ fingerprint = _text(device.get("fingerprint_hash"))
722
+ preview = _text(device.get("fingerprint_preview")) or (fingerprint[:8] + "…" if fingerprint else "")
723
+ name = _text(device.get("device_name") or device.get("name") or "جهاز")
724
+ if fingerprint:
725
+ choices.append((f"{name} — {preview}", fingerprint))
726
+ lines.append(
727
+ f"- **{name}** — `{preview or '-'}` — الحالة: `{_text(device.get('status') or 'active')}`"
728
+ )
729
+ if not devices:
730
+ lines.append("\nلا توجد أجهزة موثوقة.")
731
+ return (
732
+ gr.update(choices=choices, value=choices[0][1] if choices else None),
733
+ "\n".join(lines),
734
+ )
735
+ except Exception as exc:
736
+ return gr.update(choices=[], value=None), f"### ❌ تعذر عرض الأجهزة\n\n`{exc}`"
737
+
738
+ def remove_device(identity, fingerprint):
739
+ if not _text(identity) or not _text(fingerprint):
740
+ return "### ❌ اختر طالبًا وجهازًا.", gr.skip(), gr.skip()
741
+ try:
742
+ result = manager().remove_student_device(
743
+ identity=_text(identity),
744
+ fingerprint_hash=_text(fingerprint),
745
+ changed_by="admin_office",
746
+ admin_key=admin_key,
747
+ )
748
+ choices_update, devices_md = refresh_devices(identity)
749
+ return _result_markdown("حذف الجهاز", result), choices_update, devices_md
750
+ except Exception as exc:
751
+ return f"### ❌ تعذر حذف الجهاز\n\n`{exc}`", gr.skip(), gr.skip()
752
+
753
+ def clear_devices(identity):
754
+ if not _text(identity):
755
+ return "### ❌ افتح ملف طالب أولًا.", gr.skip(), gr.skip()
756
+ try:
757
+ result = manager().clear_student_devices(
758
+ identity=_text(identity),
759
+ changed_by="admin_office",
760
+ admin_key=admin_key,
761
+ )
762
+ choices_update, devices_md = refresh_devices(identity)
763
+ return _result_markdown("مسح أجهزة الطالب", result), choices_update, devices_md
764
+ except Exception as exc:
765
+ return f"### ❌ تعذر مسح الأجهزة\n\n`{exc}`", gr.skip(), gr.skip()
766
+
767
+ def delete_student(identity, confirmation):
768
+ if not _text(identity):
769
+ return "### ❌ افتح ملف طالب أولًا.", gr.skip()
770
+ try:
771
+ result = manager().delete_student_account(
772
+ identity=_text(identity),
773
+ confirmation=_text(confirmation),
774
+ changed_by="admin_office",
775
+ admin_key=admin_key,
776
+ )
777
+ if isinstance(result, dict) and result.get("success"):
778
+ return _result_markdown("حذف الطالب", result), ""
779
+ return _result_markdown("حذف الطالب", result), gr.skip()
780
+ except Exception as exc:
781
+ return f"### ❌ تعذر حذف الطالب\n\n`{exc}`", gr.skip()
782
+
783
+ def refresh_academic(identity):
784
+ return _academic_summary(identity)
785
+
786
+ def system_snapshot():
787
+ try:
788
+ result = manager().system_snapshot(admin_key=admin_key)
789
+ if not isinstance(result, dict):
790
+ return f"```text\n{result}\n```"
791
+ return "### ⚙️ لقطة النظام\n\n```json\n" + _json(result) + "\n```"
792
+ except Exception as exc:
793
+ return f"### ❌ تعذر فحص النظام\n\n`{exc}`"
794
+
795
+ def audit_log():
796
+ try:
797
+ result = manager().load_audit_log(limit=150, admin_key=admin_key)
798
+ if not isinstance(result, dict) or not result.get("success"):
799
+ return _result_markdown("سجل الإدارة", result)
800
+ events = result.get("events") or []
801
+ if not events:
802
+ return "### 🧾 سجل الإدارة\n\nلا توجد عمليات مسجلة."
803
+ lines = [
804
+ f"### 🧾 سجل الإدارة — آخر {len(events)} عملية",
805
+ "",
806
+ "| الوقت | العملية | الهدف | المنفذ | النتيجة |",
807
+ "|---|---|---|---|---|",
808
+ ]
809
+ for event in reversed(events[-150:]):
810
+ if not isinstance(event, dict):
811
+ continue
812
+ lines.append(
813
+ "| {time} | `{action}` | `{target}` | {actor} | {ok} |".format(
814
+ time=_text(event.get("created_at")).replace("|", " "),
815
+ action=_text(event.get("action")).replace("|", " "),
816
+ target=_text(event.get("target")).replace("|", " "),
817
+ actor=_text(event.get("actor")).replace("|", " "),
818
+ ok="✅" if event.get("success") else "❌",
819
+ )
820
+ )
821
+ return "\n".join(lines)
822
+ except Exception as exc:
823
+ return f"### ❌ تعذر قراءة سجل الإدارة\n\n`{exc}`"
824
+
825
+ # =========================================================
826
+ # بلاغات جودة الأسئلة
827
+ # =========================================================
828
+
829
+ QUESTION_REASON_LABELS = {
830
+ "unclear": "السؤال غير واضح",
831
+ "no_correct_answer": "لا توجد إجابة صحيحة",
832
+ "multiple_correct_answers": "أكثر من إجابة صحيحة",
833
+ "wrong_skill": "السؤال لا يطابق المهارة",
834
+ "language_error": "خطأ لغوي أو في الصياغة",
835
+ "visual_error": "خطأ في صورة أو رسم",
836
+ "technical_error": "مشكلة تقنية في السؤال",
837
+ "other": "أخرى",
838
+ }
839
+
840
+ def question_reports_summary():
841
+ try:
842
+ qrm = question_report_manager()
843
+ stats = qrm.stats(refresh_cloud=True)
844
+ storage = qrm.storage_status()
845
+
846
+ by_status = stats.get("by_status") or {}
847
+ lines = [
848
+ "### 🚩 ملخص بلاغات الأسئلة",
849
+ "",
850
+ f"- جميع البلاغات: **{stats.get('total', 0)}**",
851
+ f"- مفتوحة: **{by_status.get('open', 0)}**",
852
+ f"- في طابور إعادة التدقيق: **{by_status.get('queued_for_reaudit', 0)}**",
853
+ f"- تحت المراجعة: **{by_status.get('under_review', 0)}**",
854
+ f"- تم حلها: **{by_status.get('resolved', 0)}**",
855
+ f"- مستبعدة: **{by_status.get('dismissed', 0)}**",
856
+ ]
857
+
858
+ if isinstance(storage, dict):
859
+ storage_info = storage.get("storage") or {}
860
+ lines.extend([
861
+ "",
862
+ "#### التخزين المركزي",
863
+ f"- المستودع: `{storage_info.get('repo_key', '-')}`",
864
+ f"- المسار: `{storage_info.get('path_in_repo', '-')}`",
865
+ f"- الحالة: {'✅ جاهز' if storage.get('success') else '⚠️ غير مؤكد'}",
866
+ ])
867
+
868
+ return "\n".join(lines)
869
+ except Exception as exc:
870
+ return f"### ❌ تعذر تحميل ملخص البلاغات\n\n`{exc}`"
871
+
872
+ def question_reports_list(status_filter, reason_filter, grade_filter, skill_filter):
873
+ try:
874
+ qrm = question_report_manager()
875
+
876
+ status_value = _text(status_filter)
877
+ if status_value == "الكل":
878
+ status_value = ""
879
+
880
+ reason_value = _text(reason_filter)
881
+ reason_reverse = {
882
+ label: key for key, label in QUESTION_REASON_LABELS.items()
883
+ }
884
+ if reason_value == "الكل":
885
+ reason_value = ""
886
+ else:
887
+ reason_value = reason_reverse.get(reason_value, reason_value)
888
+
889
+ grade_value = None
890
+ grade_text = _text(grade_filter)
891
+ if grade_text:
892
+ try:
893
+ grade_value = int(float(grade_text))
894
+ except Exception:
895
+ grade_value = None
896
+
897
+ result = qrm.list_reports(
898
+ status=status_value,
899
+ grade=grade_value,
900
+ skill_id=_text(skill_filter),
901
+ reason_id=reason_value,
902
+ limit=500,
903
+ refresh_cloud=True,
904
+ )
905
+ reports = result.get("reports") or []
906
+ if not reports:
907
+ return "### البلاغات\n\nلا توجد بلاغات مطابقة."
908
+
909
+ lines = [
910
+ f"### 🚩 البلاغات — {len(reports)}",
911
+ "",
912
+ "| الحالة | السبب | الصف | المهارة | السؤال | report_id |",
913
+ "|---|---|---:|---|---|---|",
914
+ ]
915
+ for report in reversed(reports):
916
+ if not isinstance(report, dict):
917
+ continue
918
+ question_text = _text(
919
+ report.get("question_text")
920
+ or report.get("prompt")
921
+ or report.get("question")
922
+ )
923
+ if len(question_text) > 80:
924
+ question_text = question_text[:77] + "…"
925
+ reason = QUESTION_REASON_LABELS.get(
926
+ _text(report.get("reason_id")),
927
+ _text(report.get("reason_id") or "أخرى"),
928
+ )
929
+ lines.append(
930
+ "| `{status}` | {reason} | {grade} | `{skill}` | {question} | `{rid}` |".format(
931
+ status=_text(report.get("report_status") or "open").replace("|", " "),
932
+ reason=reason.replace("|", " "),
933
+ grade=_text(report.get("grade") or "-").replace("|", " "),
934
+ skill=_text(report.get("skill_id") or "-").replace("|", " "),
935
+ question=question_text.replace("|", " "),
936
+ rid=_text(report.get("report_id")).replace("|", " "),
937
+ )
938
+ )
939
+ return "\n".join(lines)
940
+ except Exception as exc:
941
+ return f"### ❌ تعذر تحميل البلاغات\n\n`{exc}`"
942
+
943
+ def open_question_report(report_id):
944
+ report_id = _text(report_id)
945
+ if not report_id:
946
+ return "### ❌ أدخل report_id."
947
+ try:
948
+ result = question_report_manager().get_report(
949
+ report_id=report_id,
950
+ refresh_cloud=True,
951
+ )
952
+ if not result.get("success"):
953
+ return _result_markdown("فتح البلاغ", result)
954
+
955
+ report = result.get("report") or {}
956
+ reason = QUESTION_REASON_LABELS.get(
957
+ _text(report.get("reason_id")),
958
+ _text(report.get("reason_id") or "أخرى"),
959
+ )
960
+ lines = [
961
+ "### 🚩 تفاصيل البلاغ",
962
+ "",
963
+ f"**report_id:** `{_text(report.get('report_id'))}`",
964
+ "",
965
+ f"**الحالة:** `{_text(report.get('report_status') or 'open')}`",
966
+ "",
967
+ f"**السبب:** {reason}",
968
+ "",
969
+ f"**الطالب:** `{_text(report.get('student_id') or report.get('identity') or '-')}`",
970
+ "",
971
+ f"**الصف:** `{_text(report.get('grade') or '-')}`",
972
+ "",
973
+ f"**المهارة:** `{_text(report.get('skill_id') or '-')}`",
974
+ "",
975
+ f"**question_id:** `{_text(report.get('question_id') or '-')}`",
976
+ "",
977
+ f"**السؤال:** {_text(report.get('question_text') or report.get('prompt') or '-')}",
978
+ ]
979
+ note = _text(report.get("student_note") or report.get("note"))
980
+ if note:
981
+ lines.extend(["", f"**ملاحظة الطالب:** {note}"])
982
+ review_note = _text(report.get("review_note"))
983
+ if review_note:
984
+ lines.extend(["", f"**ملاحظة الإدارة:** {review_note}"])
985
+
986
+ reaudit = report.get("reaudit") or {}
987
+ if isinstance(reaudit, dict):
988
+ lines.extend([
989
+ "",
990
+ f"**إعادة التدقيق:** {'✅ طُلبت' if reaudit.get('requested') else '— لم تُطلب تلقائيًا'}",
991
+ ])
992
+ if reaudit.get("message"):
993
+ lines.append(f"\n{_text(reaudit.get('message'))}")
994
+
995
+ lines.extend([
996
+ "",
997
+ "<details><summary>البيانات التقنية الكاملة</summary>",
998
+ "",
999
+ "```json",
1000
+ _json(report),
1001
+ "```",
1002
+ "</details>",
1003
+ ])
1004
+ return "\n".join(lines)
1005
+ except Exception as exc:
1006
+ return f"### ❌ تعذر فتح البلاغ\n\n`{exc}`"
1007
+
1008
+ def change_question_report_status(report_id, status, review_note):
1009
+ report_id = _text(report_id)
1010
+ status = _text(status)
1011
+ if not report_id:
1012
+ return "### ❌ أدخل report_id.", gr.skip(), gr.skip()
1013
+
1014
+ try:
1015
+ result = question_report_manager().set_report_status(
1016
+ report_id=report_id,
1017
+ status=status,
1018
+ review_note=_text(review_note),
1019
+ changed_by="admin_office",
1020
+ )
1021
+ details = open_question_report(report_id)
1022
+ return _result_markdown("تحديث حالة البلاغ", result), details, question_reports_summary()
1023
+ except Exception as exc:
1024
+ return f"### ❌ تعذر تحديث البلاغ\n\n`{exc}`", gr.skip(), gr.skip()
1025
+
1026
+ # =========================================================
1027
+ # إدارة المستودعات
1028
+ # =========================================================
1029
+
1030
+ def repositories_overview():
1031
+ try:
1032
+ sm = storage_manager()
1033
+ connection = sm.test_connection()
1034
+ overview = sm.repository_overview(include_file_counts=True)
1035
+ rows = overview.get("repositories") or []
1036
+
1037
+ lines = [
1038
+ "### 🗄️ حالة المستودعات",
1039
+ "",
1040
+ f"**الاتصال:** {'✅ متصل' if connection.get('success') else '❌ غير متصل'}",
1041
+ "",
1042
+ ]
1043
+ if connection.get("message"):
1044
+ lines.append(_text(connection.get("message")))
1045
+ lines.append("")
1046
+
1047
+ lines.extend([
1048
+ "| المفتاح | المستودع | النوع | الملفات | الحالة |",
1049
+ "|---|---|---|---:|---|",
1050
+ ])
1051
+ for row in rows:
1052
+ reachable = row.get("reachable")
1053
+ state = "✅" if reachable else ("❌" if reachable is False else "—")
1054
+ lines.append(
1055
+ "| `{key}` | `{repo}` | {rtype} | {count} | {state} |".format(
1056
+ key=_text(row.get("repo_key")),
1057
+ repo=_text(row.get("repo_id")),
1058
+ rtype=_text(row.get("repo_type")),
1059
+ count=_text(row.get("files_count") if row.get("files_count") is not None else "-"),
1060
+ state=state,
1061
+ )
1062
+ )
1063
+
1064
+ lines.extend([
1065
+ "",
1066
+ "#### بلاغات الأسئلة",
1067
+ f"- المستودع: `{_text(overview.get('question_reports_repo_key'))}`",
1068
+ f"- المسار: `{_text(overview.get('question_reports_path'))}`",
1069
+ "",
1070
+ "> أدوات هذا التبويب للعرض والتنزيل فقط؛ لا يوجد حذف للمستودعات أو الملفات من مكتب الإدارة.",
1071
+ ])
1072
+ return "\n".join(lines)
1073
+ except Exception as exc:
1074
+ return f"### ❌ تعذر فحص المستودعات\n\n`{exc}`"
1075
+
1076
+ def list_repository_files_ui(repo_key, prefix):
1077
+ try:
1078
+ result = storage_manager().list_repository_files(
1079
+ repo_key=_text(repo_key),
1080
+ prefix=_text(prefix),
1081
+ limit=1000,
1082
+ )
1083
+ if not result.get("success"):
1084
+ return _result_markdown("عرض ملفات المستودع", result)
1085
+
1086
+ files = result.get("files") or []
1087
+ lines = [
1088
+ f"### 📂 `{result.get('repo_key')}` — {result.get('count', 0)} ملف",
1089
+ "",
1090
+ ]
1091
+ if not files:
1092
+ lines.append("لا توجد ملفات مطابقة.")
1093
+ else:
1094
+ lines.append("```text")
1095
+ lines.extend(str(name) for name in files)
1096
+ lines.append("```")
1097
+ if result.get("truncated"):
1098
+ lines.append("\n> القائمة مختصرة. استخدم Prefix لتضييق النتائج.")
1099
+ return "\n".join(lines)
1100
+ except Exception as exc:
1101
+ return f"### ❌ تعذر عرض الملفات\n\n`{exc}`"
1102
+
1103
+ def download_repository_file_ui(repo_key, filename):
1104
+ try:
1105
+ result = storage_manager().download_repository_file_for_admin(
1106
+ repo_key=_text(repo_key),
1107
+ filename=_text(filename),
1108
+ )
1109
+ if not result.get("success"):
1110
+ return _result_markdown("تنزيل ملف المستودع", result), None
1111
+ return (
1112
+ "### ✅ تم تنزيل الملف إلى الكاش\n\n"
1113
+ f"`{_text(result.get('local_path'))}`",
1114
+ result.get("local_path"),
1115
+ )
1116
+ except Exception as exc:
1117
+ return f"### ❌ تعذر تنزيل الملف\n\n`{exc}`", None
1118
+
1119
+ # =========================================================
1120
+ # الواجهة
1121
+ # =========================================================
1122
+
1123
+ selected_identity = gr.State("")
1124
+
1125
+ gr.HTML(
1126
+ """
1127
+ <div style="direction:rtl;margin:6px 0 12px">
1128
+ <h2 style="margin-bottom:4px">🏢 مكتب الإدارة</h2>
1129
+ <div style="opacity:.8">الإدارة اليومية للطلاب والحسابات والمتابعة والنظام</div>
1130
+ </div>
1131
+ """
1132
+ )
1133
+
1134
+ with gr.Tabs():
1135
+ # -----------------------------------------------------
1136
+ # الرئيسية
1137
+ # -----------------------------------------------------
1138
+ with gr.Tab("🏠 الرئيسية"):
1139
+ dashboard = gr.HTML(refresh_dashboard())
1140
+ refresh_dashboard_btn = gr.Button("🔄 تحديث لوحة الإدارة")
1141
+ refresh_dashboard_btn.click(refresh_dashboard, [], [dashboard])
1142
+
1143
+ # -----------------------------------------------------
1144
+ # الطلاب
1145
+ # -----------------------------------------------------
1146
+ with gr.Tab("👨‍🎓 الطلاب"):
1147
+ with gr.Row():
1148
+ student_status_filter = gr.Dropdown(
1149
+ choices=[
1150
+ "الكل",
1151
+ "بانتظار التفعيل",
1152
+ "نشط",
1153
+ "موقوف",
1154
+ "مرفوض",
1155
+ ],
1156
+ value="بانتظار التفعيل",
1157
+ label="حالة الحساب",
1158
+ )
1159
+ student_search = gr.Textbox(
1160
+ label="بحث",
1161
+ placeholder="الاسم أو مفتاح الدخول أو البريد أو الهاتف أو المعرّف",
1162
+ )
1163
+ refresh_students_btn = gr.Button("🔄 عرض الطلاب")
1164
+
1165
+ students_out = gr.Markdown(
1166
+ list_students("بانتظار التفعيل", "")
1167
+ )
1168
+
1169
+ refresh_students_btn.click(
1170
+ list_students,
1171
+ [student_status_filter, student_search],
1172
+ [students_out],
1173
+ )
1174
+ student_status_filter.change(
1175
+ list_students,
1176
+ [student_status_filter, student_search],
1177
+ [students_out],
1178
+ )
1179
+
1180
+ gr.Markdown("### فتح ملف طالب")
1181
+ student_lookup = gr.Textbox(
1182
+ label="الطالب",
1183
+ placeholder="أدخل مفتاح الدخول أو المعرّف أو الاسم الدقيق",
1184
+ )
1185
+ open_student_btn = gr.Button("📂 فتح الملف", variant="primary")
1186
+ student_action_out = gr.Markdown("")
1187
+
1188
+ with gr.Tabs():
1189
+ with gr.Tab("البيانات الأساسية"):
1190
+ full_name = gr.Textbox(label="الاسم الكامل")
1191
+ with gr.Row():
1192
+ birth_date = gr.Textbox(label="تاريخ الميلاد")
1193
+ age = gr.Textbox(label="العمر")
1194
+ country = gr.Textbox(label="البلد")
1195
+ grade = gr.Textbox(label="الصف")
1196
+ with gr.Row():
1197
+ phone = gr.Textbox(label="الهاتف")
1198
+ email = gr.Textbox(label="البريد الإلكتروني")
1199
+ gender = gr.Textbox(label="الجنس")
1200
+ with gr.Row():
1201
+ preferred_dialect = gr.Textbox(label="اللهجة المفضلة")
1202
+ voice_locale = gr.Textbox(label="Voice locale")
1203
+ voice_gender = gr.Textbox(label="نوع الصوت")
1204
+ with gr.Row():
1205
+ voice_language_mode = gr.Textbox(label="وضع اللغة الصوتية")
1206
+ scientific_terms_mode = gr.Textbox(label="نطق المصطلحات العلمية")
1207
+
1208
+ save_profile_btn = gr.Button("💾 حفظ بيانات الطالب", variant="primary")
1209
+
1210
+ with gr.Tab("الحساب والدخول"):
1211
+ account_status = gr.Dropdown(
1212
+ choices=["pending", "active", "suspended", "rejected"],
1213
+ value="pending",
1214
+ label="حالة الحساب",
1215
+ )
1216
+ status_reason = gr.Textbox(
1217
+ label="سبب تغيير الحالة",
1218
+ lines=2,
1219
+ )
1220
+ change_status_btn = gr.Button("حفظ حالة الحساب", variant="primary")
1221
+
1222
+ gr.Markdown("---")
1223
+ current_access_key = gr.Textbox(
1224
+ label="مفتاح الدخول الحالي",
1225
+ interactive=False,
1226
+ )
1227
+ new_access_key = gr.Textbox(
1228
+ label="مفتاح دخول جديد",
1229
+ placeholder="اتركه فارغًا لإنشاء مفتاح تلقائي",
1230
+ )
1231
+ reset_access_key_btn = gr.Button("🔑 تغيير مفتاح الدخول")
1232
+
1233
+ gr.Markdown("---")
1234
+ new_parent_password = gr.Textbox(
1235
+ label="كلمة مرور ولي الأمر الجديدة",
1236
+ type="password",
1237
+ )
1238
+ reset_parent_password_btn = gr.Button("🔐 إعادة ضبط كلمة مرور ولي الأمر")
1239
+
1240
+ with gr.Tab("الأجهزة"):
1241
+ refresh_devices_btn = gr.Button("🔄 تحديث الأجهزة")
1242
+ devices_out = gr.Markdown("افتح ملف طالب أولًا.")
1243
+ device_selector = gr.Dropdown(
1244
+ choices=[],
1245
+ value=None,
1246
+ label="اختر الجهاز",
1247
+ )
1248
+ with gr.Row():
1249
+ remove_device_btn = gr.Button("حذف الجهاز المحدد")
1250
+ clear_devices_btn = gr.Button("مسح جميع أجهزة الطالب")
1251
+ device_action_out = gr.Markdown("")
1252
+
1253
+ with gr.Tab("حذف الحساب"):
1254
+ gr.Markdown(
1255
+ "⚠️ **الحذف عملية حساسة.** لا يتم التنف��ذ إلا بكتابة "
1256
+ "`DELETE_STUDENT` حرفيًا."
1257
+ )
1258
+ delete_confirmation = gr.Textbox(
1259
+ label="تأكيد الحذف",
1260
+ placeholder="DELETE_STUDENT",
1261
+ )
1262
+ delete_student_btn = gr.Button("🗑️ حذف الطالب")
1263
+ delete_student_out = gr.Markdown("")
1264
+
1265
+ open_outputs = [
1266
+ selected_identity,
1267
+ full_name,
1268
+ birth_date,
1269
+ age,
1270
+ country,
1271
+ grade,
1272
+ phone,
1273
+ email,
1274
+ gender,
1275
+ preferred_dialect,
1276
+ voice_locale,
1277
+ voice_gender,
1278
+ voice_language_mode,
1279
+ scientific_terms_mode,
1280
+ account_status,
1281
+ current_access_key,
1282
+ new_access_key,
1283
+ new_parent_password,
1284
+ student_action_out,
1285
+ device_selector,
1286
+ devices_out,
1287
+ # هذا الناتج يذهب أيضًا إلى التبويب الأكاديمي أدناه.
1288
+ ]
1289
+
1290
+ # -----------------------------------------------------
1291
+ # الملف الأكاديمي
1292
+ # -----------------------------------------------------
1293
+ with gr.Tab("📚 الملف الأكاديمي"):
1294
+ gr.Markdown(
1295
+ "هذا التبويب **للقراءة والمتابعة** في هذه المرحلة، "
1296
+ "ولا يعدّل بيانات الإتقان أو الفاقد يدويًا."
1297
+ )
1298
+ refresh_academic_btn = gr.Button("🔄 تحديث الملف الأكاديمي")
1299
+ academic_out = gr.Markdown(
1300
+ "افتح طالبًا من تبويب **الطلاب** أولًا."
1301
+ )
1302
+
1303
+ # -----------------------------------------------------
1304
+ # بلاغات الأسئلة
1305
+ # -----------------------------------------------------
1306
+ with gr.Tab("🚩 بلاغات الأسئلة"):
1307
+ question_reports_stats_out = gr.Markdown(question_reports_summary())
1308
+
1309
+ with gr.Row():
1310
+ question_report_status_filter = gr.Dropdown(
1311
+ choices=[
1312
+ "الكل",
1313
+ "open",
1314
+ "queued_for_reaudit",
1315
+ "under_review",
1316
+ "resolved",
1317
+ "dismissed",
1318
+ ],
1319
+ value="الكل",
1320
+ label="الحالة",
1321
+ )
1322
+ question_report_reason_filter = gr.Dropdown(
1323
+ choices=["الكل"] + list(QUESTION_REASON_LABELS.values()),
1324
+ value="الكل",
1325
+ label="سبب البلاغ",
1326
+ )
1327
+ question_report_grade_filter = gr.Textbox(
1328
+ label="الصف - اختياري",
1329
+ placeholder="مثال: 5",
1330
+ )
1331
+ question_report_skill_filter = gr.Textbox(
1332
+ label="skill_id - اختياري",
1333
+ )
1334
+
1335
+ refresh_question_reports_btn = gr.Button("🔄 تحديث البلاغات", variant="primary")
1336
+ question_reports_out = gr.Markdown(
1337
+ question_reports_list("الكل", "الكل", "", "")
1338
+ )
1339
+
1340
+ gr.Markdown("### فتح بلاغ ومراجعته")
1341
+ question_report_id = gr.Textbox(
1342
+ label="report_id",
1343
+ placeholder="انسخ report_id من الجدول",
1344
+ )
1345
+ open_question_report_btn = gr.Button("📂 فتح البلاغ")
1346
+ question_report_details = gr.Markdown("")
1347
+
1348
+ with gr.Row():
1349
+ question_report_new_status = gr.Dropdown(
1350
+ choices=[
1351
+ "open",
1352
+ "queued_for_reaudit",
1353
+ "under_review",
1354
+ "resolved",
1355
+ "dismissed",
1356
+ ],
1357
+ value="under_review",
1358
+ label="الحالة الجديدة",
1359
+ )
1360
+ question_report_review_note = gr.Textbox(
1361
+ label="ملاحظة الإدارة",
1362
+ lines=2,
1363
+ )
1364
+
1365
+ update_question_report_btn = gr.Button(
1366
+ "💾 حفظ مراجعة البلاغ",
1367
+ variant="primary",
1368
+ )
1369
+ question_report_action_out = gr.Markdown("")
1370
+
1371
+ # -----------------------------------------------------
1372
+ # المستودعات
1373
+ # -----------------------------------------------------
1374
+ with gr.Tab("🗄️ المستودعات"):
1375
+ repositories_out = gr.Markdown(
1376
+ "اضغط **فحص المستودعات** لعرض الحالة."
1377
+ )
1378
+ refresh_repositories_btn = gr.Button(
1379
+ "🔄 فحص المستودعات",
1380
+ variant="primary",
1381
+ )
1382
+
1383
+ with gr.Row():
1384
+ repo_selector = gr.Dropdown(
1385
+ choices=["students", "teachers", "system", "models"],
1386
+ value="system",
1387
+ label="المستودع",
1388
+ )
1389
+ repo_prefix = gr.Textbox(
1390
+ label="Prefix - اختياري",
1391
+ placeholder="مثال: quality/ أو remedial_library/",
1392
+ )
1393
+
1394
+ list_repo_files_btn = gr.Button("📂 عرض ملفات المستودع")
1395
+ repo_files_out = gr.Markdown("")
1396
+
1397
+ gr.Markdown("### تنزيل ملف محدد إلى الكاش")
1398
+ repo_file_path = gr.Textbox(
1399
+ label="مسار الملف داخل المستودع",
1400
+ placeholder="مثال: quality/question_reports.jsonl",
1401
+ )
1402
+ download_repo_file_btn = gr.Button("⬇️ تنزيل الملف")
1403
+ repo_download_status = gr.Markdown("")
1404
+ repo_download_file = gr.File(label="الملف المنزّل", interactive=False)
1405
+
1406
+ # -----------------------------------------------------
1407
+ # النظام
1408
+ # -----------------------------------------------------
1409
+ with gr.Tab("⚙️ النظام"):
1410
+ with gr.Row():
1411
+ snapshot_btn = gr.Button("فحص خدمات النظام")
1412
+ audit_btn = gr.Button("عرض سجل الإدارة")
1413
+ system_out = gr.Markdown("")
1414
+ audit_out = gr.Markdown("")
1415
+
1416
+ # =========================================================
1417
+ # التوصيلات
1418
+ # =========================================================
1419
+
1420
+ open_student_btn.click(
1421
+ open_student,
1422
+ [student_lookup],
1423
+ open_outputs + [academic_out],
1424
+ )
1425
+
1426
+ save_profile_btn.click(
1427
+ save_student_profile,
1428
+ [
1429
+ selected_identity,
1430
+ full_name,
1431
+ birth_date,
1432
+ age,
1433
+ country,
1434
+ grade,
1435
+ phone,
1436
+ email,
1437
+ gender,
1438
+ preferred_dialect,
1439
+ voice_locale,
1440
+ voice_gender,
1441
+ voice_language_mode,
1442
+ scientific_terms_mode,
1443
+ ],
1444
+ [student_action_out],
1445
+ )
1446
+
1447
+ change_status_btn.click(
1448
+ change_status,
1449
+ [selected_identity, account_status, status_reason],
1450
+ [student_action_out, account_status],
1451
+ ).then(
1452
+ list_students,
1453
+ [student_status_filter, student_search],
1454
+ [students_out],
1455
+ ).then(
1456
+ refresh_dashboard,
1457
+ [],
1458
+ [dashboard],
1459
+ )
1460
+
1461
+ reset_access_key_btn.click(
1462
+ reset_access_key,
1463
+ [selected_identity, new_access_key],
1464
+ [student_action_out, current_access_key],
1465
+ )
1466
+
1467
+ reset_parent_password_btn.click(
1468
+ reset_parent_password,
1469
+ [selected_identity, new_parent_password],
1470
+ [student_action_out, new_parent_password],
1471
+ )
1472
+
1473
+ refresh_devices_btn.click(
1474
+ refresh_devices,
1475
+ [selected_identity],
1476
+ [device_selector, devices_out],
1477
+ )
1478
+
1479
+ remove_device_btn.click(
1480
+ remove_device,
1481
+ [selected_identity, device_selector],
1482
+ [device_action_out, device_selector, devices_out],
1483
+ )
1484
+
1485
+ clear_devices_btn.click(
1486
+ clear_devices,
1487
+ [selected_identity],
1488
+ [device_action_out, device_selector, devices_out],
1489
+ )
1490
+
1491
+ delete_student_btn.click(
1492
+ delete_student,
1493
+ [selected_identity, delete_confirmation],
1494
+ [delete_student_out, selected_identity],
1495
+ ).then(
1496
+ list_students,
1497
+ [student_status_filter, student_search],
1498
+ [students_out],
1499
+ ).then(
1500
+ refresh_dashboard,
1501
+ [],
1502
+ [dashboard],
1503
+ )
1504
+
1505
+ refresh_academic_btn.click(
1506
+ refresh_academic,
1507
+ [selected_identity],
1508
+ [academic_out],
1509
+ )
1510
+
1511
+ refresh_question_reports_btn.click(
1512
+ question_reports_list,
1513
+ [
1514
+ question_report_status_filter,
1515
+ question_report_reason_filter,
1516
+ question_report_grade_filter,
1517
+ question_report_skill_filter,
1518
+ ],
1519
+ [question_reports_out],
1520
+ ).then(
1521
+ question_reports_summary,
1522
+ [],
1523
+ [question_reports_stats_out],
1524
+ )
1525
+
1526
+ open_question_report_btn.click(
1527
+ open_question_report,
1528
+ [question_report_id],
1529
+ [question_report_details],
1530
+ )
1531
+
1532
+ update_question_report_btn.click(
1533
+ change_question_report_status,
1534
+ [
1535
+ question_report_id,
1536
+ question_report_new_status,
1537
+ question_report_review_note,
1538
+ ],
1539
+ [
1540
+ question_report_action_out,
1541
+ question_report_details,
1542
+ question_reports_stats_out,
1543
+ ],
1544
+ ).then(
1545
+ question_reports_list,
1546
+ [
1547
+ question_report_status_filter,
1548
+ question_report_reason_filter,
1549
+ question_report_grade_filter,
1550
+ question_report_skill_filter,
1551
+ ],
1552
+ [question_reports_out],
1553
+ )
1554
+
1555
+ refresh_repositories_btn.click(
1556
+ repositories_overview,
1557
+ [],
1558
+ [repositories_out],
1559
+ )
1560
+
1561
+ list_repo_files_btn.click(
1562
+ list_repository_files_ui,
1563
+ [repo_selector, repo_prefix],
1564
+ [repo_files_out],
1565
+ )
1566
+
1567
+ download_repo_file_btn.click(
1568
+ download_repository_file_ui,
1569
+ [repo_selector, repo_file_path],
1570
+ [repo_download_status, repo_download_file],
1571
+ )
1572
+
1573
+ snapshot_btn.click(system_snapshot, [], [system_out])
1574
+ audit_btn.click(audit_log, [], [audit_out])
1575
+
1576
+ return {
1577
+ "version": VERSION,
1578
+ "selected_identity": selected_identity,
1579
+ "dashboard": dashboard,
1580
+ "students_out": students_out,
1581
+ "student_action_out": student_action_out,
1582
+ "academic_out": academic_out,
1583
+ "system_out": system_out,
1584
+ "audit_out": audit_out,
1585
+ "question_reports_out": question_reports_out,
1586
+ "question_reports_stats_out": question_reports_stats_out,
1587
+ "repositories_out": repositories_out,
1588
+ "repo_files_out": repo_files_out,
1589
+ }
ai_manager.py CHANGED
@@ -6,6 +6,7 @@ import os
6
  import gc
7
  import json
8
  import inspect
 
9
  import subprocess
10
  import tempfile
11
  import traceback
@@ -312,164 +313,351 @@ def normalize_error_message(error):
312
  return text
313
 
314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  # =========================================================
316
  # تشغيل نموذج نصي مرة واحدة
317
  # =========================================================
318
 
319
- def run_model_once(role, user_text, system_text="", max_new_tokens=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  if not str(user_text or "").strip():
321
  return {
322
  "success": False,
323
- "role": role,
324
  "message": "النص المرسل للنموذج فارغ.",
325
  "text": "",
326
  "debug": "",
327
  "gpu_duration": GPU_DURATION,
328
  }
329
 
330
- config = get_model_config(role)
331
- model_name = get_model_name(role)
332
 
333
  if not config or not model_name:
334
  return {
335
  "success": False,
336
- "role": role,
337
  "model": "",
338
- "message": f"لا يوجد نموذج مضبوط لهذا الدور في ai_models.py: {role}",
 
 
 
339
  "text": "",
340
  "debug": "",
341
  "gpu_duration": GPU_DURATION,
342
  }
343
 
 
 
 
344
  try:
345
  import torch
346
- from transformers import AutoTokenizer, AutoModelForCausalLM
 
 
 
347
 
348
  device = choose_device(config)
349
 
350
  if device == "cuda" and not torch.cuda.is_available():
351
  device = "cpu"
352
 
353
- torch_dtype = torch.float16 if device == "cuda" else torch.float32
354
- trust_remote_code = bool(config.get("trust_remote_code", False))
355
-
356
- tokenizer = AutoTokenizer.from_pretrained(
357
- model_name,
358
- trust_remote_code=trust_remote_code,
 
359
  )
360
 
361
- if tokenizer.pad_token is None:
362
- tokenizer.pad_token = tokenizer.eos_token
363
 
364
- model_kwargs = {
365
- "trust_remote_code": trust_remote_code,
366
- "torch_dtype": torch_dtype,
367
- "low_cpu_mem_usage": True,
368
- "attn_implementation": config.get("attn_implementation", "eager"),
369
- }
 
 
 
370
 
371
- try:
372
- model = AutoModelForCausalLM.from_pretrained(
373
- model_name,
374
- **model_kwargs,
375
- )
376
- except TypeError:
377
- model_kwargs.pop("attn_implementation", None)
378
- model = AutoModelForCausalLM.from_pretrained(
379
- model_name,
380
- **model_kwargs,
381
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
382
 
383
- model.to(device)
384
- model.eval()
 
 
 
 
 
 
 
 
 
 
385
 
386
- prompt = build_prompt(
387
- tokenizer=tokenizer,
388
- user_text=user_text,
389
- system_text=system_text,
390
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
 
392
- max_input_length = int(config.get("max_input_length", 1536) or 1536)
 
 
 
393
 
394
- inputs = tokenizer(
395
- prompt,
396
- return_tensors="pt",
397
- truncation=True,
398
- max_length=max_input_length,
399
- padding=True,
400
- )
 
 
401
 
402
- inputs = {key: value.to(device) for key, value in inputs.items()}
 
 
 
 
 
 
 
 
 
 
 
 
 
403
 
404
- input_length = inputs["input_ids"].shape[-1]
 
405
 
406
- max_tokens = int(
407
- max_new_tokens
408
- or get_max_new_tokens(role, 160)
409
- or 160
410
- )
411
 
412
- # حماية قوية حتى لا يطول التوليد على ZeroGPU
413
- if role in ["lesson_planner", "phi"]:
414
- if max_tokens > 120:
415
- max_tokens = 120
416
- elif role in ["teacher_chat", "qwen"]:
417
- if max_tokens > 160:
418
- max_tokens = 160
419
- else:
420
- if max_tokens > 160:
421
- max_tokens = 160
422
 
423
- do_sample = bool(config.get("do_sample", False))
 
 
 
424
 
425
- generation_kwargs = {
426
- "max_new_tokens": max_tokens,
427
- "do_sample": do_sample,
428
- "repetition_penalty": float(config.get("repetition_penalty", 1.05) or 1.05),
429
- "pad_token_id": tokenizer.pad_token_id,
430
- "eos_token_id": tokenizer.eos_token_id,
431
- }
432
 
433
- # لا نرسل temperature إذا كان do_sample=False حتى لا يظهر التحذير
434
- if do_sample:
435
- generation_kwargs["temperature"] = float(config.get("temperature", 0.2) or 0.2)
 
436
 
437
- with torch.no_grad():
438
- output_ids = model.generate(
439
- **inputs,
440
- **generation_kwargs,
 
 
 
 
 
441
  )
442
 
443
- new_tokens = output_ids[0][input_length:]
444
- text = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
445
 
446
- raw_path = write_text_file(
447
- AI_OUTPUT_DIR,
448
- f"{role}_raw_{now_stamp()}.txt",
449
- text,
450
- )
451
 
452
- try:
453
- del model
454
- del tokenizer
455
- del inputs
456
- del output_ids
457
- except Exception:
458
- pass
 
 
 
 
 
 
 
 
 
 
 
 
459
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
460
  cleanup_memory()
461
 
462
  return {
463
  "success": True,
464
- "role": role,
 
465
  "model": model_name,
466
  "device": device,
467
- "message": f"تم توليد رد من الدور: {role}",
468
- "text": text,
 
 
469
  "raw_path": raw_path,
470
  "debug": "",
471
  "gpu_duration": GPU_DURATION,
472
  "max_new_tokens_used": max_tokens,
 
 
 
473
  }
474
 
475
  except Exception as e:
@@ -478,21 +666,25 @@ def run_model_once(role, user_text, system_text="", max_new_tokens=None):
478
 
479
  error_path = write_text_file(
480
  AI_OUTPUT_DIR,
481
- f"{role}_error_{now_stamp()}.txt",
482
  error_text,
483
  )
484
 
 
485
  cleanup_memory()
486
 
487
  return {
488
  "success": False,
489
- "role": role,
 
490
  "model": model_name,
491
  "message": clean_message,
492
  "text": "",
493
  "error_path": error_path,
494
  "debug": error_text,
495
  "gpu_duration": GPU_DURATION,
 
 
496
  }
497
 
498
 
@@ -1547,6 +1739,36 @@ def run_teacher_chat_gpu(user_text, system_text="", max_new_tokens=None):
1547
  )
1548
 
1549
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1550
  @spaces.GPU(duration=ASR_GPU_DURATION)
1551
  def run_speech_to_text_gpu(
1552
  role,
@@ -1613,13 +1835,14 @@ def unload_global_model():
1613
  يحرر أي مراجع تشغيلية محفوظة فقط.
1614
  مسح gc وكاش CUDA مسؤولية ModelMemoryManager وحده.
1615
  """
1616
- global _MODEL, _TOKENIZER, _CURRENT_ROLE, _CURRENT_MODEL_NAME
1617
 
1618
  for name in (
1619
  "_MODEL",
1620
  "_TOKENIZER",
1621
  "_CURRENT_ROLE",
1622
  "_CURRENT_MODEL_NAME",
 
1623
  ):
1624
  if name not in globals():
1625
  globals()[name] = None
@@ -1647,7 +1870,7 @@ class AIManager:
1647
  """
1648
 
1649
  def __init__(self, root_dir=None, registry_file=None):
1650
- self.version = "ai_manager_v16_cohere_arabic_asr_official_loader"
1651
 
1652
  self.root_dir = Path(
1653
  root_dir or Path(__file__).resolve().parent
@@ -2766,34 +2989,78 @@ class AIManager:
2766
  "text": "",
2767
  }
2768
 
2769
- if role in ["lesson_planner", "phi"]:
2770
  return run_lesson_planner_gpu(
2771
  user_text=user_text,
2772
  system_text=system_text,
2773
  max_new_tokens=max_new_tokens,
2774
  )
2775
 
2776
- if role in ["teacher_chat", "qwen"]:
2777
  return run_teacher_chat_gpu(
2778
  user_text=user_text,
2779
  system_text=system_text,
2780
  max_new_tokens=max_new_tokens,
2781
  )
2782
 
2783
- if role == "image_generator":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2784
  return run_image_generator_gpu(
2785
  prompt=user_text,
2786
  negative_prompt=system_text,
2787
  )
2788
 
2789
- if role == "animation_generator":
2790
  return run_animation_generator_gpu(
2791
  prompt=user_text,
2792
  negative_prompt=system_text,
2793
  )
2794
 
2795
  return run_model_once(
2796
- role=role,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2797
  user_text=user_text,
2798
  system_text=system_text,
2799
  max_new_tokens=max_new_tokens,
@@ -3013,6 +3280,21 @@ class AIManager:
3013
  "animation_gpu_duration": ANIMATION_GPU_DURATION,
3014
  "lesson_planner_model": get_model_name("lesson_planner"),
3015
  "teacher_chat_model": get_model_name("teacher_chat"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3016
  "image_generator_model": get_model_name("image_generator"),
3017
  "animation_generator_model": get_model_name("animation_generator"),
3018
  "animation_motion_adapter": (
 
6
  import gc
7
  import json
8
  import inspect
9
+ import threading
10
  import subprocess
11
  import tempfile
12
  import traceback
 
313
  return text
314
 
315
 
316
+ # =========================================================
317
+ # مراجع تشغيل النموذج النصي لمسار جودة البنك فقط
318
+ # =========================================================
319
+ # هذه المراجع تسمح بإعادة استخدام نفس النموذج بين أسئلة المرحلة الواحدة.
320
+ # ModelMemoryManager هو الوحيد الذي يقرر متى يتم تحريرها بالكامل.
321
+ _MODEL = None
322
+ _TOKENIZER = None
323
+ _CURRENT_ROLE = None
324
+ _CURRENT_MODEL_NAME = None
325
+ _CURRENT_DEVICE = None
326
+ _TEXT_MODEL_LOCK = threading.RLock()
327
+
328
+
329
  # =========================================================
330
  # تشغيل نموذج نصي مرة واحدة
331
  # =========================================================
332
 
333
+ def run_model_once(
334
+ role,
335
+ user_text,
336
+ system_text="",
337
+ max_new_tokens=None,
338
+ keep_loaded=False,
339
+ ):
340
+ """
341
+ تشغيل نموذج نصي.
342
+
343
+ keep_loaded=False:
344
+ السلوك القديم للحصة العلاجية وبقية المسارات؛
345
+ يحمل النموذج لهذا الاستدعاء فقط.
346
+
347
+ keep_loaded=True:
348
+ مخصص لمسار جودة بنك الأسئلة.
349
+ يحتفظ بنفس الدور والنموذج في الذاكرة بين الأسئلة،
350
+ إلى أن يستدعي ModelMemoryManager أمر التحرير.
351
+ """
352
+ global _MODEL, _TOKENIZER
353
+ global _CURRENT_ROLE, _CURRENT_MODEL_NAME, _CURRENT_DEVICE
354
+
355
+ normalized_role = normalize_role(role)
356
+
357
  if not str(user_text or "").strip():
358
  return {
359
  "success": False,
360
+ "role": normalized_role,
361
  "message": "النص المرسل للنموذج فارغ.",
362
  "text": "",
363
  "debug": "",
364
  "gpu_duration": GPU_DURATION,
365
  }
366
 
367
+ config = get_model_config(normalized_role)
368
+ model_name = get_model_name(normalized_role)
369
 
370
  if not config or not model_name:
371
  return {
372
  "success": False,
373
+ "role": normalized_role,
374
  "model": "",
375
+ "message": (
376
+ "لا يوجد نموذج مضبوط لهذا الدور في ai_models.py: "
377
+ f"{normalized_role}"
378
+ ),
379
  "text": "",
380
  "debug": "",
381
  "gpu_duration": GPU_DURATION,
382
  }
383
 
384
+ local_model = None
385
+ local_tokenizer = None
386
+
387
  try:
388
  import torch
389
+ from transformers import (
390
+ AutoTokenizer,
391
+ AutoModelForCausalLM,
392
+ )
393
 
394
  device = choose_device(config)
395
 
396
  if device == "cuda" and not torch.cuda.is_available():
397
  device = "cpu"
398
 
399
+ torch_dtype = (
400
+ torch.float16
401
+ if device == "cuda"
402
+ else torch.float32
403
+ )
404
+ trust_remote_code = bool(
405
+ config.get("trust_remote_code", False)
406
  )
407
 
408
+ cache_reused = False
 
409
 
410
+ with _TEXT_MODEL_LOCK:
411
+ if keep_loaded:
412
+ same_cached_model = bool(
413
+ _MODEL is not None
414
+ and _TOKENIZER is not None
415
+ and _CURRENT_ROLE == normalized_role
416
+ and _CURRENT_MODEL_NAME == model_name
417
+ and _CURRENT_DEVICE == device
418
+ )
419
 
420
+ if same_cached_model:
421
+ model = _MODEL
422
+ tokenizer = _TOKENIZER
423
+ cache_reused = True
424
+ else:
425
+ # لا نمسح CUDA هنا.
426
+ # إذا كان هناك دور سابق، ModelMemoryManager
427
+ # هو المسؤول عن تحريره قبل بدء الدور الجديد.
428
+ if _MODEL is not None or _TOKENIZER is not None:
429
+ return {
430
+ "success": False,
431
+ "ready": False,
432
+ "role": normalized_role,
433
+ "model": model_name,
434
+ "message": (
435
+ "يوجد نموذج نصي آخر ما زال محمّلًا. "
436
+ "يجب على ModelMemoryManager تحرير الدور السابق "
437
+ "قبل تحميل دور جديد."
438
+ ),
439
+ "loaded_role": _CURRENT_ROLE,
440
+ "loaded_model": _CURRENT_MODEL_NAME,
441
+ "cache_owner": "model_memory_manager",
442
+ "text": "",
443
+ "gpu_duration": GPU_DURATION,
444
+ }
445
+
446
+ tokenizer = AutoTokenizer.from_pretrained(
447
+ model_name,
448
+ trust_remote_code=trust_remote_code,
449
+ )
450
 
451
+ if tokenizer.pad_token is None:
452
+ tokenizer.pad_token = tokenizer.eos_token
453
+
454
+ model_kwargs = {
455
+ "trust_remote_code": trust_remote_code,
456
+ "torch_dtype": torch_dtype,
457
+ "low_cpu_mem_usage": True,
458
+ "attn_implementation": config.get(
459
+ "attn_implementation",
460
+ "eager",
461
+ ),
462
+ }
463
 
464
+ try:
465
+ model = AutoModelForCausalLM.from_pretrained(
466
+ model_name,
467
+ **model_kwargs,
468
+ )
469
+ except TypeError:
470
+ model_kwargs.pop(
471
+ "attn_implementation",
472
+ None,
473
+ )
474
+ model = AutoModelForCausalLM.from_pretrained(
475
+ model_name,
476
+ **model_kwargs,
477
+ )
478
+
479
+ model.to(device)
480
+ model.eval()
481
+
482
+ _MODEL = model
483
+ _TOKENIZER = tokenizer
484
+ _CURRENT_ROLE = normalized_role
485
+ _CURRENT_MODEL_NAME = model_name
486
+ _CURRENT_DEVICE = device
487
+ else:
488
+ # السلوك القديم للمسارات الأخرى.
489
+ local_tokenizer = AutoTokenizer.from_pretrained(
490
+ model_name,
491
+ trust_remote_code=trust_remote_code,
492
+ )
493
 
494
+ if local_tokenizer.pad_token is None:
495
+ local_tokenizer.pad_token = (
496
+ local_tokenizer.eos_token
497
+ )
498
 
499
+ model_kwargs = {
500
+ "trust_remote_code": trust_remote_code,
501
+ "torch_dtype": torch_dtype,
502
+ "low_cpu_mem_usage": True,
503
+ "attn_implementation": config.get(
504
+ "attn_implementation",
505
+ "eager",
506
+ ),
507
+ }
508
 
509
+ try:
510
+ local_model = AutoModelForCausalLM.from_pretrained(
511
+ model_name,
512
+ **model_kwargs,
513
+ )
514
+ except TypeError:
515
+ model_kwargs.pop(
516
+ "attn_implementation",
517
+ None,
518
+ )
519
+ local_model = AutoModelForCausalLM.from_pretrained(
520
+ model_name,
521
+ **model_kwargs,
522
+ )
523
 
524
+ local_model.to(device)
525
+ local_model.eval()
526
 
527
+ model = local_model
528
+ tokenizer = local_tokenizer
 
 
 
529
 
530
+ prompt = build_prompt(
531
+ tokenizer=tokenizer,
532
+ user_text=user_text,
533
+ system_text=system_text,
534
+ )
 
 
 
 
 
535
 
536
+ max_input_length = int(
537
+ config.get("max_input_length", 1536)
538
+ or 1536
539
+ )
540
 
541
+ inputs = tokenizer(
542
+ prompt,
543
+ return_tensors="pt",
544
+ truncation=True,
545
+ max_length=max_input_length,
546
+ padding=True,
547
+ )
548
 
549
+ inputs = {
550
+ key: value.to(device)
551
+ for key, value in inputs.items()
552
+ }
553
 
554
+ input_length = inputs["input_ids"].shape[-1]
555
+
556
+ max_tokens = int(
557
+ max_new_tokens
558
+ or get_max_new_tokens(
559
+ normalized_role,
560
+ 160,
561
+ )
562
+ or 160
563
  )
564
 
565
+ # حماية زمن التوليد حسب الدور.
566
+ if normalized_role in {
567
+ "lesson_planner",
568
+ "phi",
569
+ }:
570
+ max_tokens = min(max_tokens, 120)
571
+ elif normalized_role in {
572
+ "teacher_chat",
573
+ "qwen",
574
+ }:
575
+ max_tokens = min(max_tokens, 160)
576
+ elif normalized_role in {
577
+ "question_support_generator",
578
+ "question_support_reviewer",
579
+ }:
580
+ max_tokens = min(max_tokens, 520)
581
+ else:
582
+ max_tokens = min(max_tokens, 160)
583
 
584
+ do_sample = bool(
585
+ config.get("do_sample", False)
586
+ )
 
 
587
 
588
+ generation_kwargs = {
589
+ "max_new_tokens": max_tokens,
590
+ "do_sample": do_sample,
591
+ "repetition_penalty": float(
592
+ config.get(
593
+ "repetition_penalty",
594
+ 1.05,
595
+ )
596
+ or 1.05
597
+ ),
598
+ "pad_token_id": tokenizer.pad_token_id,
599
+ "eos_token_id": tokenizer.eos_token_id,
600
+ }
601
+
602
+ if do_sample:
603
+ generation_kwargs["temperature"] = float(
604
+ config.get("temperature", 0.2)
605
+ or 0.2
606
+ )
607
 
608
+ with torch.no_grad():
609
+ output_ids = model.generate(
610
+ **inputs,
611
+ **generation_kwargs,
612
+ )
613
+
614
+ new_tokens = output_ids[0][input_length:]
615
+ generated_text = tokenizer.decode(
616
+ new_tokens,
617
+ skip_special_tokens=True,
618
+ ).strip()
619
+
620
+ raw_path = write_text_file(
621
+ AI_OUTPUT_DIR,
622
+ f"{normalized_role}_raw_{now_stamp()}.txt",
623
+ generated_text,
624
+ )
625
+
626
+ try:
627
+ del inputs
628
+ del output_ids
629
+ del new_tokens
630
+ except Exception:
631
+ pass
632
+
633
+ # للمسارات القديمة فقط نسقط المراجع المحلية بعد الطلب.
634
+ if not keep_loaded:
635
+ try:
636
+ del local_model
637
+ del local_tokenizer
638
+ except Exception:
639
+ pass
640
+
641
+ # لا يوجد gc/empty_cache هنا.
642
  cleanup_memory()
643
 
644
  return {
645
  "success": True,
646
+ "ready": True,
647
+ "role": normalized_role,
648
  "model": model_name,
649
  "device": device,
650
+ "message": (
651
+ f"تم توليد رد من الدور: {normalized_role}"
652
+ ),
653
+ "text": generated_text,
654
  "raw_path": raw_path,
655
  "debug": "",
656
  "gpu_duration": GPU_DURATION,
657
  "max_new_tokens_used": max_tokens,
658
+ "keep_loaded": bool(keep_loaded),
659
+ "model_cache_reused": bool(cache_reused),
660
+ "cache_owner": "model_memory_manager",
661
  }
662
 
663
  except Exception as e:
 
666
 
667
  error_path = write_text_file(
668
  AI_OUTPUT_DIR,
669
+ f"{normalized_role}_error_{now_stamp()}.txt",
670
  error_text,
671
  )
672
 
673
+ # لا نمسح CUDA هنا حتى عند الفشل.
674
  cleanup_memory()
675
 
676
  return {
677
  "success": False,
678
+ "ready": False,
679
+ "role": normalized_role,
680
  "model": model_name,
681
  "message": clean_message,
682
  "text": "",
683
  "error_path": error_path,
684
  "debug": error_text,
685
  "gpu_duration": GPU_DURATION,
686
+ "keep_loaded": bool(keep_loaded),
687
+ "cache_owner": "model_memory_manager",
688
  }
689
 
690
 
 
1739
  )
1740
 
1741
 
1742
+ @spaces.GPU(duration=GPU_DURATION)
1743
+ def run_question_support_generator_gpu(
1744
+ user_text,
1745
+ system_text="",
1746
+ max_new_tokens=None,
1747
+ ):
1748
+ return run_model_once(
1749
+ role="question_support_generator",
1750
+ user_text=user_text,
1751
+ system_text=system_text,
1752
+ max_new_tokens=max_new_tokens,
1753
+ keep_loaded=True,
1754
+ )
1755
+
1756
+
1757
+ @spaces.GPU(duration=GPU_DURATION)
1758
+ def run_question_support_reviewer_gpu(
1759
+ user_text,
1760
+ system_text="",
1761
+ max_new_tokens=None,
1762
+ ):
1763
+ return run_model_once(
1764
+ role="question_support_reviewer",
1765
+ user_text=user_text,
1766
+ system_text=system_text,
1767
+ max_new_tokens=max_new_tokens,
1768
+ keep_loaded=True,
1769
+ )
1770
+
1771
+
1772
  @spaces.GPU(duration=ASR_GPU_DURATION)
1773
  def run_speech_to_text_gpu(
1774
  role,
 
1835
  يحرر أي مراجع تشغيلية محفوظة فقط.
1836
  مسح gc وكاش CUDA مسؤولية ModelMemoryManager وحده.
1837
  """
1838
+ global _MODEL, _TOKENIZER, _CURRENT_ROLE, _CURRENT_MODEL_NAME, _CURRENT_DEVICE
1839
 
1840
  for name in (
1841
  "_MODEL",
1842
  "_TOKENIZER",
1843
  "_CURRENT_ROLE",
1844
  "_CURRENT_MODEL_NAME",
1845
+ "_CURRENT_DEVICE",
1846
  ):
1847
  if name not in globals():
1848
  globals()[name] = None
 
1870
  """
1871
 
1872
  def __init__(self, root_dir=None, registry_file=None):
1873
+ self.version = "ai_manager_v17_question_quality_role_cache"
1874
 
1875
  self.root_dir = Path(
1876
  root_dir or Path(__file__).resolve().parent
 
2989
  "text": "",
2990
  }
2991
 
2992
+ if normalized_role in ["lesson_planner", "phi"]:
2993
  return run_lesson_planner_gpu(
2994
  user_text=user_text,
2995
  system_text=system_text,
2996
  max_new_tokens=max_new_tokens,
2997
  )
2998
 
2999
+ if normalized_role in ["teacher_chat", "qwen"]:
3000
  return run_teacher_chat_gpu(
3001
  user_text=user_text,
3002
  system_text=system_text,
3003
  max_new_tokens=max_new_tokens,
3004
  )
3005
 
3006
+ if normalized_role == "question_support_generator":
3007
+ return run_question_support_generator_gpu(
3008
+ user_text=user_text,
3009
+ system_text=system_text,
3010
+ max_new_tokens=max_new_tokens,
3011
+ )
3012
+
3013
+ if normalized_role == "question_support_reviewer":
3014
+ return run_question_support_reviewer_gpu(
3015
+ user_text=user_text,
3016
+ system_text=system_text,
3017
+ max_new_tokens=max_new_tokens,
3018
+ )
3019
+
3020
+ if normalized_role == "image_generator":
3021
  return run_image_generator_gpu(
3022
  prompt=user_text,
3023
  negative_prompt=system_text,
3024
  )
3025
 
3026
+ if normalized_role == "animation_generator":
3027
  return run_animation_generator_gpu(
3028
  prompt=user_text,
3029
  negative_prompt=system_text,
3030
  )
3031
 
3032
  return run_model_once(
3033
+ role=normalized_role,
3034
+ user_text=user_text,
3035
+ system_text=system_text,
3036
+ max_new_tokens=max_new_tokens,
3037
+ )
3038
+
3039
+ # =====================================================
3040
+ # جودة بنك الأسئلة
3041
+ # =====================================================
3042
+
3043
+ def run_question_support_generator(
3044
+ self,
3045
+ user_text,
3046
+ system_text="",
3047
+ max_new_tokens=None,
3048
+ ):
3049
+ return self.ask_role_raw(
3050
+ role="question_support_generator",
3051
+ user_text=user_text,
3052
+ system_text=system_text,
3053
+ max_new_tokens=max_new_tokens,
3054
+ )
3055
+
3056
+ def run_question_support_reviewer(
3057
+ self,
3058
+ user_text,
3059
+ system_text="",
3060
+ max_new_tokens=None,
3061
+ ):
3062
+ return self.ask_role_raw(
3063
+ role="question_support_reviewer",
3064
  user_text=user_text,
3065
  system_text=system_text,
3066
  max_new_tokens=max_new_tokens,
 
3280
  "animation_gpu_duration": ANIMATION_GPU_DURATION,
3281
  "lesson_planner_model": get_model_name("lesson_planner"),
3282
  "teacher_chat_model": get_model_name("teacher_chat"),
3283
+ "question_support_generator_model": get_model_name(
3284
+ "question_support_generator"
3285
+ ),
3286
+ "question_support_reviewer_model": get_model_name(
3287
+ "question_support_reviewer"
3288
+ ),
3289
+ "question_quality_runtime": {
3290
+ "generator_keep_loaded_during_phase": True,
3291
+ "reviewer_keep_loaded_during_phase": True,
3292
+ "loaded_role": _CURRENT_ROLE,
3293
+ "loaded_model": _CURRENT_MODEL_NAME,
3294
+ "loaded_device": _CURRENT_DEVICE,
3295
+ "release_owner": "model_memory_manager",
3296
+ "remedial_text_roles_keep_old_behavior": True,
3297
+ },
3298
  "image_generator_model": get_model_name("image_generator"),
3299
  "animation_generator_model": get_model_name("animation_generator"),
3300
  "animation_motion_adapter": (
ai_models.py CHANGED
@@ -20,7 +20,7 @@ import os
20
  from typing import Any, Dict
21
 
22
 
23
- AI_MODELS_VERSION = "ai_models_v4_cohere_arabic_conversation_asr_enabled"
24
 
25
 
26
  def env_text(name: str, default: str = "") -> str:
@@ -65,6 +65,17 @@ TEACHER_CHAT_MODEL = env_text(
65
  "Qwen/Qwen2.5-1.5B-Instruct",
66
  )
67
 
 
 
 
 
 
 
 
 
 
 
 
68
  IMAGE_GENERATOR_MODEL = env_text(
69
  "IMAGE_GENERATOR_MODEL",
70
  "stabilityai/sd-turbo",
@@ -144,6 +155,90 @@ AI_MODELS: Dict[str, Dict[str, Any]] = {
144
  "الشارح التعليمي: يحول الخطة إلى شرح للطالب."
145
  ),
146
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  "image_generator": {
148
  "enabled": env_bool("IMAGE_GENERATOR_ENABLED", True)
149
  and bool(IMAGE_GENERATOR_MODEL),
@@ -327,6 +422,13 @@ def normalize_role(role: Any) -> str:
327
  "oral_arabic": "arabic_conversation_asr",
328
  "english_speech": "english_asr",
329
  "english_reading": "english_asr",
 
 
 
 
 
 
 
330
  }
331
  return aliases.get(role_key, role_key)
332
 
@@ -381,7 +483,12 @@ def list_models() -> Dict[str, Dict[str, Any]]:
381
  def validate() -> Dict[str, Any]:
382
  problems = []
383
 
384
- for role in ("lesson_planner", "teacher_chat"):
 
 
 
 
 
385
  config = get_model_config(role)
386
  if not config.get("model"):
387
  problems.append(
@@ -423,6 +530,12 @@ def validate() -> Dict[str, Any]:
423
  "teacher_chat_model": get_model_name(
424
  "teacher_chat"
425
  ),
 
 
 
 
 
 
426
  "image_generator_model": get_model_name(
427
  "image_generator"
428
  ),
@@ -459,6 +572,24 @@ def summary() -> Dict[str, Any]:
459
  "teacher_chat_model": get_model_name(
460
  "teacher_chat"
461
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
462
  "image_generator_enabled": is_model_enabled(
463
  "image_generator"
464
  ),
 
20
  from typing import Any, Dict
21
 
22
 
23
+ AI_MODELS_VERSION = "ai_models_v5_question_quality_roles_enabled"
24
 
25
 
26
  def env_text(name: str, default: str = "") -> str:
 
65
  "Qwen/Qwen2.5-1.5B-Instruct",
66
  )
67
 
68
+
69
+ QUESTION_SUPPORT_GENERATOR_MODEL = env_text(
70
+ "QUESTION_SUPPORT_GENERATOR_MODEL",
71
+ LESSON_PLANNER_MODEL,
72
+ )
73
+
74
+ QUESTION_SUPPORT_REVIEWER_MODEL = env_text(
75
+ "QUESTION_SUPPORT_REVIEWER_MODEL",
76
+ TEACHER_CHAT_MODEL,
77
+ )
78
+
79
  IMAGE_GENERATOR_MODEL = env_text(
80
  "IMAGE_GENERATOR_MODEL",
81
  "stabilityai/sd-turbo",
 
155
  "الشارح التعليمي: يحول الخطة إلى شرح للطالب."
156
  ),
157
  },
158
+ "question_support_generator": {
159
+ "enabled": env_bool(
160
+ "QUESTION_SUPPORT_GENERATOR_ENABLED",
161
+ True,
162
+ ) and bool(QUESTION_SUPPORT_GENERATOR_MODEL),
163
+ "model": QUESTION_SUPPORT_GENERATOR_MODEL,
164
+ "device": env_text(
165
+ "QUESTION_SUPPORT_GENERATOR_DEVICE",
166
+ env_text("LESSON_PLANNER_DEVICE", "cuda"),
167
+ ),
168
+ "max_input_length": env_int(
169
+ "QUESTION_SUPPORT_GENERATOR_MAX_INPUT",
170
+ 3072,
171
+ ),
172
+ "max_new_tokens": env_int(
173
+ "QUESTION_SUPPORT_GENERATOR_MAX_NEW_TOKENS",
174
+ 520,
175
+ ),
176
+ "temperature": env_float(
177
+ "QUESTION_SUPPORT_GENERATOR_TEMPERATURE",
178
+ 0.1,
179
+ ),
180
+ "do_sample": env_bool(
181
+ "QUESTION_SUPPORT_GENERATOR_DO_SAMPLE",
182
+ False,
183
+ ),
184
+ "repetition_penalty": env_float(
185
+ "QUESTION_SUPPORT_GENERATOR_REPETITION_PENALTY",
186
+ 1.05,
187
+ ),
188
+ "trust_remote_code": False,
189
+ "attn_implementation": env_text(
190
+ "QUESTION_SUPPORT_GENERATOR_ATTN",
191
+ env_text("LESSON_PLANNER_ATTN", "eager"),
192
+ ),
193
+ "role_description": (
194
+ "يدقق السؤال أو القالب أولًا، ثم يولد التوضيح "
195
+ "والتلميحات فقط إذا اجتاز السؤال التدقيق الأولي."
196
+ ),
197
+ "task_family": "question_bank_quality",
198
+ "phase": "generator_audit_and_support",
199
+ },
200
+ "question_support_reviewer": {
201
+ "enabled": env_bool(
202
+ "QUESTION_SUPPORT_REVIEWER_ENABLED",
203
+ True,
204
+ ) and bool(QUESTION_SUPPORT_REVIEWER_MODEL),
205
+ "model": QUESTION_SUPPORT_REVIEWER_MODEL,
206
+ "device": env_text(
207
+ "QUESTION_SUPPORT_REVIEWER_DEVICE",
208
+ env_text("TEACHER_CHAT_DEVICE", "cuda"),
209
+ ),
210
+ "max_input_length": env_int(
211
+ "QUESTION_SUPPORT_REVIEWER_MAX_INPUT",
212
+ 3072,
213
+ ),
214
+ "max_new_tokens": env_int(
215
+ "QUESTION_SUPPORT_REVIEWER_MAX_NEW_TOKENS",
216
+ 520,
217
+ ),
218
+ "temperature": env_float(
219
+ "QUESTION_SUPPORT_REVIEWER_TEMPERATURE",
220
+ 0.1,
221
+ ),
222
+ "do_sample": env_bool(
223
+ "QUESTION_SUPPORT_REVIEWER_DO_SAMPLE",
224
+ False,
225
+ ),
226
+ "repetition_penalty": env_float(
227
+ "QUESTION_SUPPORT_REVIEWER_REPETITION_PENALTY",
228
+ 1.05,
229
+ ),
230
+ "trust_remote_code": False,
231
+ "attn_implementation": env_text(
232
+ "QUESTION_SUPPORT_REVIEWER_ATTN",
233
+ env_text("TEACHER_CHAT_ATTN", "eager"),
234
+ ),
235
+ "role_description": (
236
+ "مراجع مستقل يعيد فحص صحة السؤال والإجابة والخيارات "
237
+ "ثم يراجع التوضيح والتلميحات قبل الاعتماد النهائي."
238
+ ),
239
+ "task_family": "question_bank_quality",
240
+ "phase": "independent_review",
241
+ },
242
  "image_generator": {
243
  "enabled": env_bool("IMAGE_GENERATOR_ENABLED", True)
244
  and bool(IMAGE_GENERATOR_MODEL),
 
422
  "oral_arabic": "arabic_conversation_asr",
423
  "english_speech": "english_asr",
424
  "english_reading": "english_asr",
425
+
426
+ # أدوار جودة بنك الأسئلة.
427
+ "question_support": "question_support_generator",
428
+ "question_quality_generator": "question_support_generator",
429
+ "question_audit_generator": "question_support_generator",
430
+ "question_quality_reviewer": "question_support_reviewer",
431
+ "question_audit_reviewer": "question_support_reviewer",
432
  }
433
  return aliases.get(role_key, role_key)
434
 
 
483
  def validate() -> Dict[str, Any]:
484
  problems = []
485
 
486
+ for role in (
487
+ "lesson_planner",
488
+ "teacher_chat",
489
+ "question_support_generator",
490
+ "question_support_reviewer",
491
+ ):
492
  config = get_model_config(role)
493
  if not config.get("model"):
494
  problems.append(
 
530
  "teacher_chat_model": get_model_name(
531
  "teacher_chat"
532
  ),
533
+ "question_support_generator_model": get_model_name(
534
+ "question_support_generator"
535
+ ),
536
+ "question_support_reviewer_model": get_model_name(
537
+ "question_support_reviewer"
538
+ ),
539
  "image_generator_model": get_model_name(
540
  "image_generator"
541
  ),
 
572
  "teacher_chat_model": get_model_name(
573
  "teacher_chat"
574
  ),
575
+ "question_support_generator_enabled": is_model_enabled(
576
+ "question_support_generator"
577
+ ),
578
+ "question_support_generator_model": get_model_name(
579
+ "question_support_generator"
580
+ ),
581
+ "question_support_reviewer_enabled": is_model_enabled(
582
+ "question_support_reviewer"
583
+ ),
584
+ "question_support_reviewer_model": get_model_name(
585
+ "question_support_reviewer"
586
+ ),
587
+ "question_quality_policy": {
588
+ "generator_then_reviewer": True,
589
+ "roles_are_function_names": True,
590
+ "models_are_replaceable_by_environment": True,
591
+ "generator_and_reviewer_not_concurrent": True,
592
+ },
593
  "image_generator_enabled": is_model_enabled(
594
  "image_generator"
595
  ),
ai_task_queue_manager.py CHANGED
@@ -152,6 +152,8 @@ class AITaskQueueManager:
152
  )
153
 
154
  self._question_quality_lock = threading.RLock()
 
 
155
 
156
  self.old_video_api_manager_used = False
157
  self.direct_video_upload_used = False
@@ -845,11 +847,13 @@ class AITaskQueueManager:
845
  # 2) المدير يختار صفًا واحدًا من النتائج.
846
  # 3) create_or_resume_question_quality_task(grade)
847
  # -> ينشئ Snapshot ثابتًا للأسئلة التي تحتاج تدقيقًا لذلك الصف.
848
- # 4) SessionManager يستلم task_id لاحقًا ويقود التنفيذ.
849
- # 5) AITaskQueueManager يبقى ذاكرة المهمة:
850
- # أين وصل Phi؟ أين وصل Qwen؟ كم اعتمد؟ كم رفض؟
 
 
851
  #
852
- # ModelMemoryManager/AIManager لا يتم استدعاؤهما هنا في هذه النسخة.
853
  # =========================================================
854
 
855
  QUESTION_QUALITY_STATUSES = (
@@ -2352,8 +2356,8 @@ class AITaskQueueManager:
2352
  session_id: str = "session_manager",
2353
  ) -> Dict[str, Any]:
2354
  """
2355
- SessionManager يستدعيها عند استلام المهمة.
2356
- لا يتم هنا تحميل أي نموذج.
2357
  """
2358
  with self._question_quality_lock:
2359
  task = self.get_question_quality_task(
@@ -2403,7 +2407,7 @@ class AITaskQueueManager:
2403
  "claimed": True,
2404
  "task": task,
2405
  "message": (
2406
- "استلم SessionManager مهمة التدقيق."
2407
  ),
2408
  "version": (
2409
  self.question_quality_version
@@ -3023,6 +3027,642 @@ class AITaskQueueManager:
3023
  ),
3024
  }
3025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3026
  def request_question_quality_reaudit(
3027
  self,
3028
  source_type: str,
@@ -4990,6 +5630,7 @@ class AITaskQueueManager:
4990
  # Question-quality lane.
4991
  "scan_question_bank_for_audit",
4992
  "create_or_resume_question_quality_task",
 
4993
  "get_question_quality_task",
4994
  "get_next_question_quality_item",
4995
  "checkpoint_question_quality_item",
@@ -5082,6 +5723,18 @@ def format_student_remedial_center(identity: str = "student") -> str:
5082
  # واجهات مسار تدقيق بنك الأسئلة
5083
  # =============================================================
5084
 
 
 
 
 
 
 
 
 
 
 
 
 
5085
  def scan_question_bank_for_audit(
5086
  bank_files: Optional[Iterable[str]] = None,
5087
  skills_file: str = "",
 
152
  )
153
 
154
  self._question_quality_lock = threading.RLock()
155
+ self._question_quality_worker_lock = threading.Lock()
156
+ self._question_quality_active_task_id = ""
157
 
158
  self.old_video_api_manager_used = False
159
  self.direct_video_upload_used = False
 
847
  # 2) المدير يختار صفًا واحدًا من النتائج.
848
  # 3) create_or_resume_question_quality_task(grade)
849
  # -> ينشئ Snapshot ثابتًا للأسئلة التي تحتاج تدقيقًا لذلك الصف.
850
+ # 4) SessionManager يعطي أمر التشغيل فقط.
851
+ # 5) AITaskQueueManager يملك المهمة كاملة:
852
+ # أين وصل المولد؟ أين وصل المراجع؟ كم اعتمد؟ كم رفض؟
853
+ # 6) AITaskQueueManager يطلب تجهيز/تحرير الأدوار من ModelMemoryManager
854
+ # ويطلب تنفيذ الاستدلال من AIManager.
855
  #
856
+ # SessionManager لا يحمل النماذج ولا يلف على عناصر البنك.
857
  # =========================================================
858
 
859
  QUESTION_QUALITY_STATUSES = (
 
2356
  session_id: str = "session_manager",
2357
  ) -> Dict[str, Any]:
2358
  """
2359
+ دالة توافقية: تسجل أن الطلب جاء من SessionManager فقط.
2360
+ التنفيذ الطويل نفسه يبقى مسؤولية AITaskQueueManager.
2361
  """
2362
  with self._question_quality_lock:
2363
  task = self.get_question_quality_task(
 
2407
  "claimed": True,
2408
  "task": task,
2409
  "message": (
2410
+ "تم تسجيل طلب SessionManager، والتنفيذ تحت مسؤولية AITaskQueueManager."
2411
  ),
2412
  "version": (
2413
  self.question_quality_version
 
3027
  ),
3028
  }
3029
 
3030
+
3031
+ # =========================================================
3032
+ # منفذ مهمة تدقيق البنك
3033
+ # =========================================================
3034
+
3035
+ def get_question_quality_ai_manager(self):
3036
+ try:
3037
+ from ai_manager import AIManager
3038
+ return AIManager()
3039
+ except Exception:
3040
+ try:
3041
+ from ai_manager import get_manager
3042
+ return get_manager()
3043
+ except Exception:
3044
+ return None
3045
+
3046
+ def get_question_quality_memory_manager(self):
3047
+ try:
3048
+ from model_memory_manager import ModelMemoryManager
3049
+ return ModelMemoryManager()
3050
+ except Exception:
3051
+ try:
3052
+ from model_memory_manager import get_manager
3053
+ return get_manager()
3054
+ except Exception:
3055
+ return None
3056
+
3057
+ def get_question_support_manager(self):
3058
+ try:
3059
+ from question_support_manager import get_manager
3060
+ return get_manager()
3061
+ except Exception:
3062
+ try:
3063
+ from question_support_manager import QuestionSupportManager
3064
+ return QuestionSupportManager()
3065
+ except Exception:
3066
+ return None
3067
+
3068
+ def question_quality_intermediate_for_source(self, task_id, source_key):
3069
+ latest = {}
3070
+ for row in self.iter_jsonl_file(
3071
+ self.question_quality_intermediate_bank
3072
+ ) or []:
3073
+ if str(row.get("task_id") or "") != str(task_id or ""):
3074
+ continue
3075
+ if str(row.get("source_key") or "") != str(source_key or ""):
3076
+ continue
3077
+ latest = row
3078
+ return latest
3079
+
3080
+ def write_question_quality_intermediate(
3081
+ self,
3082
+ task,
3083
+ item,
3084
+ generated,
3085
+ validation,
3086
+ ai_result=None,
3087
+ ):
3088
+ row = {
3089
+ "record_type": "question_quality_intermediate",
3090
+ "task_id": str(task.get("task_id") or ""),
3091
+ "grade": self.question_quality_int(task.get("grade"), -1),
3092
+ "source_key": str(item.get("source_key") or ""),
3093
+ "source_type": str(item.get("source_type") or ""),
3094
+ "source_id": str(item.get("source_id") or ""),
3095
+ "source_fingerprint": str(item.get("source_fingerprint") or ""),
3096
+ "raw_item": self.json_safe(item),
3097
+ "generator_result": self.json_safe(generated or {}),
3098
+ "generator_validation": self.json_safe(validation or {}),
3099
+ "ai_meta": {
3100
+ "role": str((ai_result or {}).get("role") or ""),
3101
+ "model": str((ai_result or {}).get("model") or ""),
3102
+ "device": str((ai_result or {}).get("device") or ""),
3103
+ "model_cache_reused": bool(
3104
+ (ai_result or {}).get("model_cache_reused", False)
3105
+ ),
3106
+ },
3107
+ "created_at": self.now(),
3108
+ "audit_version": self.question_quality_audit_version,
3109
+ }
3110
+ self.append_jsonl_file(
3111
+ self.question_quality_intermediate_bank,
3112
+ row,
3113
+ )
3114
+ return row
3115
+
3116
+ def write_question_quality_final(
3117
+ self,
3118
+ task,
3119
+ intermediate,
3120
+ reviewer_result,
3121
+ decision,
3122
+ ai_result=None,
3123
+ ):
3124
+ approved = bool(decision.get("approved"))
3125
+ quality_status = str(
3126
+ decision.get("status")
3127
+ or ("approved" if approved else "rejected")
3128
+ ).strip()
3129
+
3130
+ row = {
3131
+ "record_type": (
3132
+ "quality_question"
3133
+ if approved
3134
+ else "question_quality_review_item"
3135
+ ),
3136
+ "task_id": str(task.get("task_id") or ""),
3137
+ "grade": self.question_quality_int(task.get("grade"), -1),
3138
+ "source_key": str(intermediate.get("source_key") or ""),
3139
+ "source_type": str(intermediate.get("source_type") or ""),
3140
+ "source_id": str(intermediate.get("source_id") or ""),
3141
+ "source_fingerprint": str(
3142
+ intermediate.get("source_fingerprint") or ""
3143
+ ),
3144
+ "raw_item": self.json_safe(intermediate.get("raw_item") or {}),
3145
+ "generator_result": self.json_safe(
3146
+ intermediate.get("generator_result") or {}
3147
+ ),
3148
+ "generator_validation": self.json_safe(
3149
+ intermediate.get("generator_validation") or {}
3150
+ ),
3151
+ "reviewer_result": self.json_safe(reviewer_result or {}),
3152
+ "decision": self.json_safe(decision or {}),
3153
+ "quality_status": quality_status,
3154
+ "quality_verified": approved,
3155
+ "quality_badge": "✓ مدقّق ومعتمد" if approved else "",
3156
+ "ai_meta": {
3157
+ "role": str((ai_result or {}).get("role") or ""),
3158
+ "model": str((ai_result or {}).get("model") or ""),
3159
+ "device": str((ai_result or {}).get("device") or ""),
3160
+ "model_cache_reused": bool(
3161
+ (ai_result or {}).get("model_cache_reused", False)
3162
+ ),
3163
+ },
3164
+ "reviewed_at": self.now(),
3165
+ "audit_version": self.question_quality_audit_version,
3166
+ }
3167
+
3168
+ target = (
3169
+ self.question_quality_final_bank
3170
+ if approved
3171
+ else self.question_quality_review_queue
3172
+ )
3173
+ self.append_jsonl_file(target, row)
3174
+ return row
3175
+
3176
+ def _question_quality_prepare_role(self, memory, role, task_id, phase):
3177
+ if memory is None or not hasattr(memory, "prepare_for_role"):
3178
+ return {
3179
+ "success": False,
3180
+ "message": "ModelMemoryManager غير جاهز.",
3181
+ }
3182
+ try:
3183
+ return memory.prepare_for_role(
3184
+ role_key=role,
3185
+ task_name=f"{task_id}:{phase}",
3186
+ )
3187
+ except Exception as exc:
3188
+ return {
3189
+ "success": False,
3190
+ "message": str(exc),
3191
+ "traceback": traceback.format_exc(),
3192
+ }
3193
+
3194
+ def _question_quality_release_role(self, memory, role, task_id, phase):
3195
+ if memory is None or not hasattr(memory, "release_after_task"):
3196
+ return {
3197
+ "success": False,
3198
+ "message": "ModelMemoryManager غير جاهز للتحرير.",
3199
+ }
3200
+ try:
3201
+ return memory.release_after_task(
3202
+ task_name=f"{task_id}:{phase}",
3203
+ role_key=role,
3204
+ )
3205
+ except Exception as exc:
3206
+ return {
3207
+ "success": False,
3208
+ "message": str(exc),
3209
+ "traceback": traceback.format_exc(),
3210
+ }
3211
+
3212
+ def _question_quality_ai_call(self, ai, role, request):
3213
+ if ai is None:
3214
+ return {"success": False, "message": "AIManager غير جاهز."}
3215
+
3216
+ method_name = (
3217
+ "run_question_support_generator"
3218
+ if role == "question_support_generator"
3219
+ else "run_question_support_reviewer"
3220
+ )
3221
+ method = getattr(ai, method_name, None)
3222
+ if callable(method):
3223
+ try:
3224
+ return method(
3225
+ user_text=str(request.get("user_prompt") or ""),
3226
+ system_text=str(request.get("system_prompt") or ""),
3227
+ max_new_tokens=520,
3228
+ )
3229
+ except Exception as exc:
3230
+ return {
3231
+ "success": False,
3232
+ "message": str(exc),
3233
+ "traceback": traceback.format_exc(),
3234
+ }
3235
+
3236
+ generic = getattr(ai, "ask_role_raw", None)
3237
+ if callable(generic):
3238
+ try:
3239
+ return generic(
3240
+ role=role,
3241
+ user_text=str(request.get("user_prompt") or ""),
3242
+ system_text=str(request.get("system_prompt") or ""),
3243
+ max_new_tokens=520,
3244
+ )
3245
+ except Exception as exc:
3246
+ return {
3247
+ "success": False,
3248
+ "message": str(exc),
3249
+ "traceback": traceback.format_exc(),
3250
+ }
3251
+
3252
+ return {
3253
+ "success": False,
3254
+ "message": "AIManager لا يحتوي منفذ جودة البنك.",
3255
+ }
3256
+
3257
+ def run_question_quality_task(
3258
+ self,
3259
+ task_id,
3260
+ max_items=0,
3261
+ max_retries=2,
3262
+ ):
3263
+ """
3264
+ ينفذ Snapshot الصف كاملة أو يستأنفها من آخر checkpoint.
3265
+
3266
+ لا يلمس مسار remedial_lesson.
3267
+ SessionManager يعطي الأمر ويتابع النتيجة فقط.
3268
+ """
3269
+ task_id = str(task_id or "").strip()
3270
+ if not task_id:
3271
+ return {
3272
+ "success": False,
3273
+ "message": "task_id مفقود.",
3274
+ "version": self.question_quality_version,
3275
+ }
3276
+
3277
+ if not self._question_quality_worker_lock.acquire(blocking=False):
3278
+ return {
3279
+ "success": False,
3280
+ "busy": True,
3281
+ "active_task_id": self._question_quality_active_task_id,
3282
+ "message": "هناك مهمة تدقيق بنك أخرى تعمل الآن.",
3283
+ "version": self.question_quality_version,
3284
+ }
3285
+
3286
+ self._question_quality_active_task_id = task_id
3287
+
3288
+ try:
3289
+ task = self.get_question_quality_task(task_id)
3290
+ if not task:
3291
+ return {
3292
+ "success": False,
3293
+ "message": "مهمة التدقيق غير موجودة.",
3294
+ "version": self.question_quality_version,
3295
+ }
3296
+
3297
+ if task.get("status") == "done":
3298
+ return {
3299
+ "success": True,
3300
+ "completed": True,
3301
+ "task": task,
3302
+ "progress": self.question_quality_progress(task),
3303
+ "version": self.question_quality_version,
3304
+ }
3305
+
3306
+ support = self.get_question_support_manager()
3307
+ ai = self.get_question_quality_ai_manager()
3308
+ memory = self.get_question_quality_memory_manager()
3309
+
3310
+ if support is None:
3311
+ return {
3312
+ "success": False,
3313
+ "paused": True,
3314
+ "task": task,
3315
+ "message": (
3316
+ "question_support_manager.py غير موجود بعد. "
3317
+ "المهمة محفوظة ولن تضيع."
3318
+ ),
3319
+ "version": self.question_quality_version,
3320
+ }
3321
+
3322
+ if ai is None or memory is None:
3323
+ return {
3324
+ "success": False,
3325
+ "paused": True,
3326
+ "task": task,
3327
+ "message": "AIManager أو ModelMemoryManager غير جاهز.",
3328
+ "version": self.question_quality_version,
3329
+ }
3330
+
3331
+ max_items = max(
3332
+ 0,
3333
+ self.question_quality_int(max_items, 0),
3334
+ )
3335
+ max_retries = max(
3336
+ 1,
3337
+ self.question_quality_int(max_retries, 2),
3338
+ )
3339
+
3340
+ task["status"] = "running"
3341
+ total = self.question_quality_int(task.get("total"), 0)
3342
+
3343
+ if self.question_quality_int(task.get("phi_completed"), 0) < total:
3344
+ task["phase"] = "phi_audit"
3345
+ self.save_question_quality_task(task, "running")
3346
+
3347
+ role = "question_support_generator"
3348
+ prepared = self._question_quality_prepare_role(
3349
+ memory, role, task_id, "phi_audit"
3350
+ )
3351
+ if not prepared.get("success"):
3352
+ self.pause_question_quality_task(
3353
+ task_id,
3354
+ reason="generator_memory_prepare_failed",
3355
+ )
3356
+ return {
3357
+ "success": False,
3358
+ "paused": True,
3359
+ "phase": "phi_audit",
3360
+ "memory": prepared,
3361
+ "progress": self.question_quality_progress(task_id),
3362
+ "version": self.question_quality_version,
3363
+ }
3364
+
3365
+ processed = 0
3366
+ try:
3367
+ while True:
3368
+ task = self.get_question_quality_task(task_id)
3369
+ if self.question_quality_int(
3370
+ task.get("phi_completed"), 0
3371
+ ) >= self.question_quality_int(task.get("total"), 0):
3372
+ break
3373
+
3374
+ if max_items and processed >= max_items:
3375
+ self.pause_question_quality_task(
3376
+ task_id,
3377
+ reason="max_items_checkpoint",
3378
+ )
3379
+ return {
3380
+ "success": True,
3381
+ "paused": True,
3382
+ "phase": "phi_audit",
3383
+ "progress": self.question_quality_progress(task_id),
3384
+ "version": self.question_quality_version,
3385
+ }
3386
+
3387
+ current = self.get_next_question_quality_item(task_id)
3388
+ if not current.get("success") or not current.get("found"):
3389
+ break
3390
+
3391
+ item = current.get("item") or {}
3392
+ request = support.build_generator_request(item)
3393
+
3394
+ parsed = {}
3395
+ validation = {}
3396
+ ai_result = {}
3397
+ error_message = ""
3398
+
3399
+ for _ in range(max_retries):
3400
+ ai_result = self._question_quality_ai_call(
3401
+ ai, role, request
3402
+ )
3403
+ if not ai_result.get("success"):
3404
+ error_message = str(
3405
+ ai_result.get("message")
3406
+ or "فشل التدقيق الأول."
3407
+ )
3408
+ continue
3409
+
3410
+ parsed = support.parse_json_output(ai_result)
3411
+ validation = support.validate_generator_output(
3412
+ item,
3413
+ parsed,
3414
+ )
3415
+ if parsed and validation.get("success"):
3416
+ break
3417
+
3418
+ error_message = str(
3419
+ validation.get("problems")
3420
+ or "خرج غير صالح."
3421
+ )
3422
+
3423
+ if not parsed or not validation.get("success"):
3424
+ self.checkpoint_question_quality_item(
3425
+ task_id=task_id,
3426
+ phase="phi_audit",
3427
+ success=False,
3428
+ result_status="generator_item_failed",
3429
+ details={"message": error_message},
3430
+ )
3431
+ return {
3432
+ "success": False,
3433
+ "paused": True,
3434
+ "phase": "phi_audit",
3435
+ "message": error_message,
3436
+ "progress": self.question_quality_progress(task_id),
3437
+ "version": self.question_quality_version,
3438
+ }
3439
+
3440
+ row = self.write_question_quality_intermediate(
3441
+ task,
3442
+ item,
3443
+ parsed,
3444
+ validation,
3445
+ ai_result,
3446
+ )
3447
+
3448
+ self.checkpoint_question_quality_item(
3449
+ task_id=task_id,
3450
+ phase="phi_audit",
3451
+ success=True,
3452
+ result_status=str(
3453
+ validation.get("verdict") or "generator_done"
3454
+ ),
3455
+ result_reference=str(row.get("source_key") or ""),
3456
+ )
3457
+ processed += 1
3458
+
3459
+ self.complete_question_quality_phase(
3460
+ task_id,
3461
+ "phi_audit",
3462
+ )
3463
+ finally:
3464
+ self._question_quality_release_role(
3465
+ memory,
3466
+ role,
3467
+ task_id,
3468
+ "phi_audit",
3469
+ )
3470
+
3471
+ task = self.get_question_quality_task(task_id)
3472
+ total = self.question_quality_int(task.get("total"), 0)
3473
+
3474
+ if self.question_quality_int(task.get("qwen_completed"), 0) < total:
3475
+ if str(task.get("phase") or "") == "waiting_for_qwen":
3476
+ self.start_question_quality_qwen_phase(task_id)
3477
+
3478
+ task = self.get_question_quality_task(task_id)
3479
+ role = "question_support_reviewer"
3480
+ prepared = self._question_quality_prepare_role(
3481
+ memory, role, task_id, "qwen_review"
3482
+ )
3483
+ if not prepared.get("success"):
3484
+ self.pause_question_quality_task(
3485
+ task_id,
3486
+ reason="reviewer_memory_prepare_failed",
3487
+ )
3488
+ return {
3489
+ "success": False,
3490
+ "paused": True,
3491
+ "phase": "qwen_review",
3492
+ "memory": prepared,
3493
+ "progress": self.question_quality_progress(task_id),
3494
+ "version": self.question_quality_version,
3495
+ }
3496
+
3497
+ processed = 0
3498
+ try:
3499
+ while True:
3500
+ task = self.get_question_quality_task(task_id)
3501
+ if self.question_quality_int(
3502
+ task.get("qwen_completed"), 0
3503
+ ) >= self.question_quality_int(task.get("total"), 0):
3504
+ break
3505
+
3506
+ if max_items and processed >= max_items:
3507
+ self.pause_question_quality_task(
3508
+ task_id,
3509
+ reason="max_items_checkpoint",
3510
+ )
3511
+ return {
3512
+ "success": True,
3513
+ "paused": True,
3514
+ "phase": "qwen_review",
3515
+ "progress": self.question_quality_progress(task_id),
3516
+ "version": self.question_quality_version,
3517
+ }
3518
+
3519
+ current = self.get_next_question_quality_item(task_id)
3520
+ if not current.get("success") or not current.get("found"):
3521
+ break
3522
+
3523
+ item = current.get("item") or {}
3524
+ source_key = str(item.get("source_key") or "")
3525
+ intermediate = self.question_quality_intermediate_for_source(
3526
+ task_id,
3527
+ source_key,
3528
+ )
3529
+
3530
+ if not intermediate:
3531
+ self.checkpoint_question_quality_item(
3532
+ task_id=task_id,
3533
+ phase="qwen_review",
3534
+ success=False,
3535
+ result_status="missing_intermediate_record",
3536
+ )
3537
+ return {
3538
+ "success": False,
3539
+ "paused": True,
3540
+ "phase": "qwen_review",
3541
+ "message": "نتيجة التدقيق الأول مفقودة.",
3542
+ "progress": self.question_quality_progress(task_id),
3543
+ "version": self.question_quality_version,
3544
+ }
3545
+
3546
+ request = support.build_reviewer_request(intermediate)
3547
+
3548
+ parsed = {}
3549
+ ai_result = {}
3550
+ error_message = ""
3551
+
3552
+ for _ in range(max_retries):
3553
+ ai_result = self._question_quality_ai_call(
3554
+ ai, role, request
3555
+ )
3556
+ if not ai_result.get("success"):
3557
+ error_message = str(
3558
+ ai_result.get("message")
3559
+ or "فشل المراجع."
3560
+ )
3561
+ continue
3562
+
3563
+ parsed = support.parse_json_output(ai_result)
3564
+ if parsed and parsed.get("verdict"):
3565
+ break
3566
+ error_message = "خرج المراجع غير صالح."
3567
+
3568
+ if not parsed or not parsed.get("verdict"):
3569
+ self.checkpoint_question_quality_item(
3570
+ task_id=task_id,
3571
+ phase="qwen_review",
3572
+ success=False,
3573
+ result_status="reviewer_item_failed",
3574
+ details={"message": error_message},
3575
+ )
3576
+ return {
3577
+ "success": False,
3578
+ "paused": True,
3579
+ "phase": "qwen_review",
3580
+ "message": error_message,
3581
+ "progress": self.question_quality_progress(task_id),
3582
+ "version": self.question_quality_version,
3583
+ }
3584
+
3585
+ decision = support.decide_review(parsed, threshold=92)
3586
+ final_row = self.write_question_quality_final(
3587
+ task,
3588
+ intermediate,
3589
+ parsed,
3590
+ decision,
3591
+ ai_result,
3592
+ )
3593
+
3594
+ quality_status = str(
3595
+ decision.get("status")
3596
+ or (
3597
+ "approved"
3598
+ if decision.get("approved")
3599
+ else "rejected"
3600
+ )
3601
+ )
3602
+
3603
+ self.register_question_quality_final_decision(
3604
+ task_id=task_id,
3605
+ source_key=source_key,
3606
+ source_fingerprint=str(
3607
+ item.get("source_fingerprint") or ""
3608
+ ),
3609
+ quality_status=quality_status,
3610
+ grade=self.question_quality_int(
3611
+ item.get("grade"),
3612
+ self.question_quality_int(
3613
+ task.get("grade"),
3614
+ -1,
3615
+ ),
3616
+ ),
3617
+ source_type=str(item.get("source_type") or ""),
3618
+ source_id=str(item.get("source_id") or ""),
3619
+ decision_reference=str(
3620
+ final_row.get("source_key") or ""
3621
+ ),
3622
+ details={"decision": decision},
3623
+ )
3624
+
3625
+ self.checkpoint_question_quality_item(
3626
+ task_id=task_id,
3627
+ phase="qwen_review",
3628
+ success=True,
3629
+ result_status=quality_status,
3630
+ result_reference=str(
3631
+ final_row.get("source_key") or ""
3632
+ ),
3633
+ )
3634
+ processed += 1
3635
+
3636
+ self.complete_question_quality_phase(
3637
+ task_id,
3638
+ "qwen_review",
3639
+ )
3640
+ finally:
3641
+ self._question_quality_release_role(
3642
+ memory,
3643
+ role,
3644
+ task_id,
3645
+ "qwen_review",
3646
+ )
3647
+
3648
+ task = self.get_question_quality_task(task_id)
3649
+ return {
3650
+ "success": bool(task.get("status") == "done"),
3651
+ "completed": bool(task.get("status") == "done"),
3652
+ "task": task,
3653
+ "progress": self.question_quality_progress(task),
3654
+ "message": (
3655
+ "اكتملت مهمة تدقيق البنك."
3656
+ if task.get("status") == "done"
3657
+ else "تم حفظ تقدم المهمة ويمكن استئنافها."
3658
+ ),
3659
+ "version": self.question_quality_version,
3660
+ }
3661
+
3662
+ finally:
3663
+ self._question_quality_active_task_id = ""
3664
+ self._question_quality_worker_lock.release()
3665
+
3666
  def request_question_quality_reaudit(
3667
  self,
3668
  source_type: str,
 
5630
  # Question-quality lane.
5631
  "scan_question_bank_for_audit",
5632
  "create_or_resume_question_quality_task",
5633
+ "run_question_quality_task",
5634
  "get_question_quality_task",
5635
  "get_next_question_quality_item",
5636
  "checkpoint_question_quality_item",
 
5723
  # واجهات مسار تدقيق بنك الأسئلة
5724
  # =============================================================
5725
 
5726
+ def run_question_quality_task(
5727
+ task_id: str,
5728
+ max_items: int = 0,
5729
+ max_retries: int = 2,
5730
+ ) -> Dict[str, Any]:
5731
+ return get_manager().run_question_quality_task(
5732
+ task_id=task_id,
5733
+ max_items=max_items,
5734
+ max_retries=max_retries,
5735
+ )
5736
+
5737
+
5738
  def scan_question_bank_for_audit(
5739
  bank_files: Optional[Iterable[str]] = None,
5740
  skills_file: str = "",
app.py CHANGED
@@ -35,12 +35,12 @@ import re
35
  import sys
36
  from pathlib import Path
37
 
38
- BRIDGE_VERSION = "app_stage_question_clarity_auto_board_v5_4"
39
- BUILD_ID = "QUESTION_CLARITY_AUTO_BOARD_KINDergarten_002"
40
  ROOT = Path(__file__).resolve().parent
41
  ORIGINAL_APP = ROOT / "app_original.py"
42
  PATCHED_CACHE = Path(
43
- os.getenv("DIVID_PATCHED_APP_PATH", "/tmp/divid_teacher_app_stage_question_clarity_auto_board_v5_4.py")
44
  )
45
 
46
 
@@ -677,49 +677,143 @@ def ui_show_badge_concepts(app_state):
677
  return "\n".join(lines).strip()
678
 
679
 
680
- def ui_report_unclear_badge_question(app_state):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
681
  question = _current_badge_question_from_state(app_state)
682
  if not question:
683
- return "لا يوجد سؤال حالي للإبلاغ عنه."
 
 
 
 
684
 
685
- manager = _clarification_manager()
686
- event = {
687
- "event_type": "question_reported_unclear",
688
- "student_id": str((app_state or {}).get("identity") or ""),
689
- "question_id": str(question.get("question_id") or ""),
690
- "skill_id": str(question.get("skill_id") or ""),
691
- "question_text": _clarification_question_text(question),
692
- "evaluation_effect": "none",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
693
  "quality_signal_only": True,
 
694
  "reported_at": now(),
695
  }
696
- if manager is not None:
697
- try:
698
- event.update(
699
- manager.build_clarification_usage_event(
700
- student_id=event["student_id"],
701
- question_id=event["question_id"],
702
- skill_id=event["skill_id"],
703
- clarification_type="student_reported_unclear",
704
- )
705
- )
706
- event["event_type"] = "question_reported_unclear"
707
- except Exception:
708
- pass
709
 
710
  try:
711
- report_path = Path(__file__).resolve().parent / "question_quality_reports.jsonl"
712
- with report_path.open("a", encoding="utf-8") as file:
713
- file.write(json.dumps(event, ensure_ascii=False) + "\n")
714
  except Exception as exc:
715
- print("[WARN] could not save unclear-question report:", exc)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716
 
717
  return (
718
- "تم تسجيل أن السؤال غير واضح للمراجعة اللغوية والتربوية. "
719
- "لن يؤثر البلاغ في علامتك أو عدد محاولاتك."
 
 
 
 
 
 
720
  )
721
 
722
 
 
 
 
 
 
 
 
 
 
 
723
  def _board_response_submission_key(response):
724
  if not isinstance(response, dict):
725
  return ""
@@ -2818,8 +2912,30 @@ def ui_check():'''
2818
  with gr.Row():
2819
  clarify_badge_question_btn = gr.Button("❓ وضّح السؤال")
2820
  show_badge_concepts_btn = gr.Button("📘 معاني المفاهيم والرموز")
2821
- report_unclear_question_btn = gr.Button("⚠️ السؤال غير واضح")
2822
  badge_clarification_out = gr.Markdown("")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2823
  badge_debug = gr.Markdown("", visible=False)
2824
 
2825
  with gr.Accordion("🧮 نشاط السبورة المرتبط بالمهارة", open=True):
@@ -3091,9 +3207,29 @@ def ui_check():'''
3091
  )
3092
 
3093
  report_unclear_question_btn.click(
3094
- ui_report_unclear_badge_question,
3095
- [app_state],
3096
- [badge_clarification_out],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3097
  )
3098
 
3099
  submit_badge_board_answer_btn.click(
@@ -3494,6 +3630,15 @@ pre {
3494
  if board_apply_count != 1:
3495
  raise RuntimeError("تعذر عزل زر تحديث السبورة عن ألوان المنصة.")
3496
 
 
 
 
 
 
 
 
 
 
3497
  forbidden = [
3498
  'or "1234"',
3499
  'password == str(ADMIN_PASSWORD)',
@@ -3544,9 +3689,13 @@ pre {
3544
  'with gr.Tab("السبورة", visible=False) as whiteboard_tab:',
3545
  'clarify_badge_question_btn = gr.Button("❓ وضّح السؤال")',
3546
  'show_badge_concepts_btn = gr.Button("📘 معاني المفاهيم والرموز")',
3547
- 'report_unclear_question_btn = gr.Button("⚠️ السؤال غير واضح")',
 
 
3548
  'def ui_auto_submit_badge_from_board(app_state, board_value):',
3549
  'badge_whiteboard.change(',
 
 
3550
  ]
3551
  missing = [item for item in required if item not in source]
3552
  if missing:
@@ -3573,7 +3722,7 @@ def _run_original() -> None:
3573
  except Exception as e:
3574
  print("[WARN] Could not write patched cache:", e)
3575
 
3576
- print(f"[INFO] {BRIDGE_VERSION} | BUILD_ID={BUILD_ID}: skills-first path, kindergarten migration, question clarification, concept dictionary, and automatic board progression loaded.")
3577
 
3578
  runtime_globals = globals()
3579
  runtime_globals["__file__"] = str(ORIGINAL_APP)
 
35
  import sys
36
  from pathlib import Path
37
 
38
+ BRIDGE_VERSION = "app_stage_admin_question_reports_storage_v5_5"
39
+ BUILD_ID = "ADMIN_OFFICE_REPORTS_REPOSITORIES_003"
40
  ROOT = Path(__file__).resolve().parent
41
  ORIGINAL_APP = ROOT / "app_original.py"
42
  PATCHED_CACHE = Path(
43
+ os.getenv("DIVID_PATCHED_APP_PATH", "/tmp/divid_teacher_app_stage_admin_question_reports_storage_v5_5.py")
44
  )
45
 
46
 
 
677
  return "\n".join(lines).strip()
678
 
679
 
680
+ QUESTION_REPORT_REASON_CHOICES = [
681
+ ("السؤال غير واضح", "unclear"),
682
+ ("لا توجد إجابة صحيحة", "no_correct_answer"),
683
+ ("أكثر من إجابة صحيحة", "multiple_correct_answers"),
684
+ ("السؤال لا يطابق المهارة", "wrong_skill"),
685
+ ("خطأ لغوي أو في الصياغة", "language_error"),
686
+ ("خطأ في صورة أو رسم", "visual_error"),
687
+ ("مشكلة تقنية في السؤال", "technical_error"),
688
+ ("أخرى", "other"),
689
+ ]
690
+
691
+
692
+ def ui_open_question_report_form():
693
+ return gr.update(visible=True), ""
694
+
695
+
696
+ def ui_close_question_report_form():
697
+ return gr.update(visible=False), ""
698
+
699
+
700
+ def ui_submit_question_report(app_state, reason_id, student_note):
701
  question = _current_badge_question_from_state(app_state)
702
  if not question:
703
+ return (
704
+ "لا يوجد سؤال حالي للإبلاغ عنه.",
705
+ str(student_note or ""),
706
+ gr.update(visible=True),
707
+ )
708
 
709
+ state = app_state if isinstance(app_state, dict) else {}
710
+ reason_id = str(reason_id or "unclear").strip().lower()
711
+ student_note = str(student_note or "").strip()[:1000]
712
+
713
+ question_text = _clarification_question_text(question)
714
+ skill_id = str(question.get("skill_id") or "").strip()
715
+ question_id = str(question.get("question_id") or "").strip()
716
+
717
+ if not question_id:
718
+ try:
719
+ question_id = "runtime_" + uuid.uuid5(
720
+ uuid.NAMESPACE_URL,
721
+ f"{skill_id}|{question_text}",
722
+ ).hex
723
+ except Exception:
724
+ question_id = f"runtime_{skill_id or 'question'}"
725
+
726
+ source_type = str(
727
+ question.get("source_type")
728
+ or question.get("content_origin")
729
+ or question.get("source")
730
+ or ""
731
+ ).strip()
732
+ source_id = str(
733
+ question.get("source_id")
734
+ or question.get("source_item_id")
735
+ or question.get("template_id")
736
+ or ""
737
+ ).strip()
738
+
739
+ report = {
740
+ "report_id": uuid.uuid4().hex,
741
+ "student_id": str(state.get("identity") or ""),
742
+ "identity": str(state.get("identity") or ""),
743
+ "student_name": str(state.get("student_name") or ""),
744
+ "grade": state.get("grade", ""),
745
+ "subject": str(state.get("subject") or question.get("subject") or ""),
746
+ "badge_id": str(question.get("badge_id") or (state.get("badge_state") or {}).get("badge_id") or ""),
747
+ "skill_id": skill_id,
748
+ "question_id": question_id,
749
+ "question_text": question_text,
750
+ "item_type": str(
751
+ question.get("item_type")
752
+ or question.get("question_type")
753
+ or ""
754
+ ),
755
+ "reason_id": reason_id,
756
+ "student_note": student_note,
757
+ "source_type": source_type,
758
+ "source_id": source_id,
759
  "quality_signal_only": True,
760
+ "evaluation_effect": "none",
761
  "reported_at": now(),
762
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
763
 
764
  try:
765
+ from question_report_manager import get_manager as get_question_report_manager
766
+ report_manager = get_question_report_manager()
767
+ result = report_manager.report_question(report=report)
768
  except Exception as exc:
769
+ print("[WARN] question_report_manager failed:", exc)
770
+ return (
771
+ "تعذر حفظ البلاغ الآن. حاول مرة أخرى.",
772
+ student_note,
773
+ gr.update(visible=True),
774
+ )
775
+
776
+ if not isinstance(result, dict) or not result.get("success"):
777
+ return (
778
+ "تعذر حفظ البلاغ: "
779
+ + str((result or {}).get("message") if isinstance(result, dict) else result),
780
+ student_note,
781
+ gr.update(visible=True),
782
+ )
783
+
784
+ cloud_note = (
785
+ " وتمت مزامنته مع خزنة النظام."
786
+ if result.get("cloud_synced")
787
+ else " وتم حفظه محليًا، وستتم مزامنته مع الخزنة عند توفر الاتصال."
788
+ )
789
+ reaudit_note = (
790
+ " وأُرسل السؤال تلقائيًا لإعادة التدقيق."
791
+ if result.get("reaudit_requested")
792
+ else ""
793
+ )
794
 
795
  return (
796
+ "✅ تم إرسال بلاغ السؤال إلى الإدارة."
797
+ + cloud_note
798
+ + reaudit_note
799
+ + "
800
+
801
+ لن يؤثر البلاغ في علامتك أو عدد محاولاتك.",
802
+ "",
803
+ gr.update(visible=False),
804
  )
805
 
806
 
807
+ # توافق مع الاسم القديم إن استدعاه أي جزء قديم.
808
+ def ui_report_unclear_badge_question(app_state):
809
+ message, _note, _visibility = ui_submit_question_report(
810
+ app_state,
811
+ "unclear",
812
+ "",
813
+ )
814
+ return message
815
+
816
+
817
  def _board_response_submission_key(response):
818
  if not isinstance(response, dict):
819
  return ""
 
2912
  with gr.Row():
2913
  clarify_badge_question_btn = gr.Button("❓ وضّح السؤال")
2914
  show_badge_concepts_btn = gr.Button("📘 معاني المفاهيم والرموز")
2915
+ report_unclear_question_btn = gr.Button("🚩 الإبلاغ عن السؤال")
2916
  badge_clarification_out = gr.Markdown("")
2917
+
2918
+ with gr.Group(visible=False) as question_report_form:
2919
+ gr.Markdown("### 🚩 بلاغ عن جودة السؤال")
2920
+ question_report_reason = gr.Dropdown(
2921
+ choices=QUESTION_REPORT_REASON_CHOICES,
2922
+ value="unclear",
2923
+ label="سبب البلاغ",
2924
+ )
2925
+ question_report_note = gr.Textbox(
2926
+ label="ملاحظة إضافية - اختيارية",
2927
+ lines=3,
2928
+ max_lines=5,
2929
+ placeholder="اكتب ما المشكلة في السؤال باختصار.",
2930
+ )
2931
+ with gr.Row():
2932
+ submit_question_report_btn = gr.Button(
2933
+ "إرسال البلاغ",
2934
+ variant="primary",
2935
+ )
2936
+ cancel_question_report_btn = gr.Button("إلغاء")
2937
+ badge_question_report_out = gr.Markdown("")
2938
+
2939
  badge_debug = gr.Markdown("", visible=False)
2940
 
2941
  with gr.Accordion("🧮 نشاط السبورة المرتبط بالمهارة", open=True):
 
3207
  )
3208
 
3209
  report_unclear_question_btn.click(
3210
+ ui_open_question_report_form,
3211
+ [],
3212
+ [question_report_form, badge_question_report_out],
3213
+ )
3214
+
3215
+ cancel_question_report_btn.click(
3216
+ ui_close_question_report_form,
3217
+ [],
3218
+ [question_report_form, badge_question_report_out],
3219
+ )
3220
+
3221
+ submit_question_report_btn.click(
3222
+ ui_submit_question_report,
3223
+ [
3224
+ app_state,
3225
+ question_report_reason,
3226
+ question_report_note,
3227
+ ],
3228
+ [
3229
+ badge_question_report_out,
3230
+ question_report_note,
3231
+ question_report_form,
3232
+ ],
3233
  )
3234
 
3235
  submit_badge_board_answer_btn.click(
 
3630
  if board_apply_count != 1:
3631
  raise RuntimeError("تعذر عزل زر تحديث السبورة عن ألوان المنصة.")
3632
 
3633
+ # ---------------------------------------------------------
3634
+ # مكتب الإدارة الجديد: الطلاب + بلاغات الأسئلة + المستودعات
3635
+ # ---------------------------------------------------------
3636
+ try:
3637
+ from admin_office_app_patch import apply_admin_office_patch
3638
+ source = apply_admin_office_patch(source)
3639
+ except Exception as e:
3640
+ raise RuntimeError(f"تعذر تركيب مكتب الإدارة الجد��د: {e}")
3641
+
3642
  forbidden = [
3643
  'or "1234"',
3644
  'password == str(ADMIN_PASSWORD)',
 
3689
  'with gr.Tab("السبورة", visible=False) as whiteboard_tab:',
3690
  'clarify_badge_question_btn = gr.Button("❓ وضّح السؤال")',
3691
  'show_badge_concepts_btn = gr.Button("📘 معاني المفاهيم والرموز")',
3692
+ 'report_unclear_question_btn = gr.Button("🚩 الإبلاغ عن السؤال")',
3693
+ 'submit_question_report_btn = gr.Button(',
3694
+ 'from question_report_manager import get_manager as get_question_report_manager',
3695
  'def ui_auto_submit_badge_from_board(app_state, board_value):',
3696
  'badge_whiteboard.change(',
3697
+ 'from admin_office_ui import build_admin_office',
3698
+ '_ADMIN_OFFICE_COMPONENTS = build_admin_office(',
3699
  ]
3700
  missing = [item for item in required if item not in source]
3701
  if missing:
 
3722
  except Exception as e:
3723
  print("[WARN] Could not write patched cache:", e)
3724
 
3725
+ print(f"[INFO] {BRIDGE_VERSION} | BUILD_ID={BUILD_ID}: skills-first path, question reports, admin office, repository management, clarification, and automatic board progression loaded.")
3726
 
3727
  runtime_globals = globals()
3728
  runtime_globals["__file__"] = str(ORIGINAL_APP)
badge_game_manager.py CHANGED
@@ -22,9 +22,9 @@
22
  from __future__ import annotations
23
 
24
  from datetime import datetime
 
25
  import json
26
  import random
27
- import secrets
28
  import re
29
  import uuid
30
  from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
@@ -39,7 +39,7 @@ except Exception:
39
  class BadgeGameManager:
40
  """مدير لعبة الوسام والتشخيص التفاعلي."""
41
 
42
- VERSION = "badge_game_manager_v14_random_seed_synced_question_oral_retry"
43
  UNKNOWN_LABEL = "لا أعلم"
44
 
45
  PRIZE_LADDER = [
@@ -83,6 +83,19 @@ class BadgeGameManager:
83
  ("D", "د"),
84
  ]
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  def __init__(self, *args: Any, **kwargs: Any) -> None:
87
  self.version = self.VERSION
88
  self.last_state: Dict[str, Any] = {}
@@ -462,20 +475,11 @@ class BadgeGameManager:
462
  badge_id: str,
463
  count: int,
464
  skill_id: str = "",
465
- seed: Any = None,
466
- exclude_question_ids: Optional[Sequence[str]] = None,
467
- exclude_question_texts: Optional[Sequence[str]] = None,
468
  ) -> List[Dict[str, Any]]:
469
  method = getattr(bank, method_name, None)
470
  if not callable(method):
471
  return []
472
 
473
- common = {
474
- "seed": seed,
475
- "exclude_question_ids": list(exclude_question_ids or []),
476
- "exclude_question_texts": list(exclude_question_texts or []),
477
- "usage_context": "badge_game",
478
- }
479
  attempts = [
480
  {
481
  "subject": subject,
@@ -483,12 +487,11 @@ class BadgeGameManager:
483
  "badge_id": badge_id,
484
  "skill_id": skill_id,
485
  "count": count,
486
- **common,
487
  },
488
- {"skill_id": skill_id, "grade": grade, "count": count, **common} if skill_id else {},
489
- {"grade": grade, "badge_id": badge_id, "count": count, **common},
490
- {"badge_id": badge_id, "count": count, **common},
491
- {"badge_id": badge_id, "count": count, "seed": seed},
492
  ]
493
 
494
  for call_kwargs in attempts:
@@ -513,9 +516,6 @@ class BadgeGameManager:
513
  badge_id: str = "math_addition",
514
  count: int = 8,
515
  skill_id: str = "",
516
- seed: Any = None,
517
- exclude_question_ids: Optional[Sequence[str]] = None,
518
- exclude_question_texts: Optional[Sequence[str]] = None,
519
  ) -> List[Dict[str, Any]]:
520
  subject = self.normalize_subject(subject)
521
  grade = self.safe_int(grade, 1)
@@ -545,9 +545,6 @@ class BadgeGameManager:
545
  badge_id=badge_id,
546
  count=count,
547
  skill_id=target_skill,
548
- seed=seed,
549
- exclude_question_ids=exclude_question_ids,
550
- exclude_question_texts=exclude_question_texts,
551
  )
552
  if questions:
553
  return questions[:count]
@@ -761,36 +758,12 @@ class BadgeGameManager:
761
  answer = str(raw_options[0])
762
 
763
  answer_text = self._strip_choice_prefix(answer)
 
764
 
765
- item_type = str(
766
- q.get("item_type")
767
- or q.get("question_type")
768
- or ""
769
- ).strip().lower()
770
-
771
- is_oral = (
772
- item_type == "oral_response"
773
- or q.get("input_mode") == "speech_or_text"
774
- or q.get("microphone_required") is True
775
- )
776
-
777
- if is_oral:
778
- option_texts = []
779
- labeled_options = []
780
- option_buttons = []
781
- else:
782
- option_texts = self._ensure_four_options(
783
- prompt,
784
- raw_options,
785
- answer_text,
786
- )
787
-
788
- if shuffle_options:
789
- random.shuffle(option_texts)
790
 
791
- labeled_options, option_buttons = self._label_options(
792
- option_texts
793
- )
794
 
795
  cleaned = dict(q)
796
  cleaned.update(
@@ -841,30 +814,11 @@ class BadgeGameManager:
841
  or ""
842
  ).strip()
843
 
844
- item_type = str(
845
- question.get("item_type")
846
- or question.get("question_type")
847
- or ""
848
- ).strip().lower()
849
-
850
- if (
851
- item_type == "oral_response"
852
- or question.get("input_mode") == "speech_or_text"
853
- or question.get("microphone_required") is True
854
- ):
855
- instruction = (
856
- "استخدم الميكروفون، أو اكتب الإجابة في مربع النص، "
857
- "ثم اضغط اعتماد الإجابة الشفهية."
858
- )
859
- else:
860
- instruction = (
861
- "اختر إجابتك من الأزرار، أو اضغط لا أعلم."
862
- )
863
-
864
  return (
865
  f"السؤال {index + 1} من {total}\n\n"
866
  f"{prompt}\n\n"
867
- f"{instruction}"
868
  ).strip()
869
 
870
  def build_question_ui(
@@ -935,25 +889,14 @@ class BadgeGameManager:
935
  if not exact_skill_id and str(badge_id).startswith("DIVID-MATH-"):
936
  exact_skill_id = str(badge_id)
937
 
938
- session_seed = str(
939
- kwargs.get("seed")
940
- or kwargs.get("session_seed")
941
- or f"{identity}|{badge_id}|{uuid.uuid4().hex}|{secrets.token_hex(8)}"
942
- )
943
- exclude_ids = list(kwargs.get("exclude_question_ids") or [])
944
- exclude_texts = list(kwargs.get("exclude_question_texts") or [])
945
-
946
  questions = self.load_questions_from_bank(
947
  subject=subject_key,
948
  grade=grade,
949
  badge_id=badge_id,
950
  count=count,
951
  skill_id=exact_skill_id,
952
- seed=session_seed,
953
- exclude_question_ids=exclude_ids,
954
- exclude_question_texts=exclude_texts,
955
  )
956
- source = "question_bank_manager_exact_skill_randomized"
957
 
958
  if not questions:
959
  questions = self.emergency_questions(badge_id=badge_id, count=count)
@@ -964,7 +907,6 @@ class BadgeGameManager:
964
  for item in questions
965
  if isinstance(item, dict)
966
  ]
967
- random.Random(session_seed).shuffle(cleaned_questions)
968
 
969
  if not cleaned_questions:
970
  return {
@@ -1010,16 +952,6 @@ class BadgeGameManager:
1010
  "last_help_request": {},
1011
  "answer_locked": False,
1012
  "last_feedback": {},
1013
- "session_seed": session_seed,
1014
- "question_history_ids": [
1015
- str(item.get("question_id") or "")
1016
- for item in cleaned_questions
1017
- ],
1018
- "oral_max_attempts": 2,
1019
- "oral_attempts_by_question": {},
1020
- "oral_retry_events": [],
1021
- "current_question": cleaned_questions[0],
1022
- "question": cleaned_questions[0],
1023
  "stop_on_first_confirmed_error": bool(
1024
  STOP_ON_FIRST_CONFIRMED_ERROR
1025
  ),
@@ -1028,6 +960,14 @@ class BadgeGameManager:
1028
  "termination_error_type": "",
1029
  "terminated_at_index": None,
1030
  "attempted_questions": 0,
 
 
 
 
 
 
 
 
1031
  "source": source,
1032
  "created_at": self.now(),
1033
  "question_started_at": self.now(),
@@ -1075,56 +1015,17 @@ class BadgeGameManager:
1075
  # الإجابات وتكرار الخطأ
1076
  # =========================================================
1077
 
1078
-
1079
- def _whiteboard_submission_result(self, answer: Any) -> Dict[str, Any]:
1080
- if not isinstance(answer, dict):
1081
- return {"is_whiteboard": False, "authoritative": False, "is_correct": None, "unknown": False, "selected": "", "evaluation": {}}
1082
- evaluation = answer.get("evaluation") if isinstance(answer.get("evaluation"), dict) else {}
1083
- status = str(evaluation.get("status") or answer.get("status") or "").strip().lower()
1084
- is_whiteboard = bool("evaluation" in answer or "response_mode" in answer or "task_id" in answer or "confirmed_at" in answer)
1085
- authoritative = status in {"correct", "incorrect", "dont_know"}
1086
- if status == "correct": forced_correct = True
1087
- elif status in {"incorrect", "dont_know"}: forced_correct = False
1088
- elif evaluation.get("is_correct") is True:
1089
- forced_correct = True; authoritative = True
1090
- elif evaluation.get("is_correct") is False:
1091
- forced_correct = False; authoritative = True
1092
- else: forced_correct = None
1093
- nested = answer.get("answer")
1094
- selected = ""
1095
- if isinstance(nested, dict):
1096
- for key in ("value","text","label","selected","selected_value","target_value"):
1097
- value=nested.get(key)
1098
- if value not in (None,"",[],{}): selected=str(value).strip(); break
1099
- if not selected:
1100
- visited=nested.get("visited_values")
1101
- if isinstance(visited,list) and visited: selected=str(visited[-1]).strip()
1102
- if not selected:
1103
- vals=nested.get("selected_values")
1104
- if isinstance(vals,list) and vals: selected="، ".join(str(x) for x in vals)
1105
- if not selected:
1106
- try: selected=json.dumps(nested,ensure_ascii=False,sort_keys=True)
1107
- except Exception: selected=str(nested)
1108
- elif nested not in (None,""): selected=str(nested).strip()
1109
- if not selected:
1110
- selected = "إجابة سبورة صحيحة" if forced_correct is True else "إجابة سبورة غير صحيحة" if forced_correct is False else "إجابة سبورة"
1111
- return {"is_whiteboard":is_whiteboard,"authoritative":authoritative,"is_correct":forced_correct,"unknown":status=="dont_know","status":status,"selected":selected,"evaluation":evaluation}
1112
-
1113
  def _resolve_selected_value(
1114
  self,
1115
  answer: Any,
1116
  question: Dict[str, Any],
1117
  ) -> str:
1118
  if isinstance(answer, dict):
1119
- whiteboard = self._whiteboard_submission_result(answer)
1120
- if whiteboard.get("is_whiteboard"):
1121
- return str(whiteboard.get("selected") or "").strip()
1122
  answer = (
1123
  answer.get("value")
1124
  or answer.get("text")
1125
  or answer.get("label")
1126
  or answer.get("key")
1127
- or answer.get("answer")
1128
  or ""
1129
  )
1130
 
@@ -1278,7 +1179,6 @@ class BadgeGameManager:
1278
  shuffle_options=False,
1279
  )
1280
 
1281
- whiteboard_submission = self._whiteboard_submission_result(answer)
1282
  selected = self._resolve_selected_value(answer, current_question)
1283
  if not selected:
1284
  return {
@@ -1306,103 +1206,8 @@ class BadgeGameManager:
1306
  or ""
1307
  ).strip()
1308
 
1309
- unknown = (bool(whiteboard_submission.get("unknown")) if whiteboard_submission.get("is_whiteboard") else self.is_unknown(selected))
1310
- if whiteboard_submission.get("is_whiteboard") and whiteboard_submission.get("authoritative"):
1311
- is_correct = bool(whiteboard_submission.get("is_correct"))
1312
- else:
1313
- is_correct = False if unknown else self.answer_matches(selected, correct)
1314
-
1315
- item_type = str(
1316
- current_question.get("item_type")
1317
- or current_question.get("question_type")
1318
- or "multiple_choice"
1319
- ).strip().lower()
1320
-
1321
- # الخطأ الأول في سؤال شفهي قد يكون من محرك التعرف الصوتي.
1322
- # لذلك يسمح بمحاولة ثانية واحدة فقط دون تسجيل خطأ نهائي.
1323
- if item_type == "oral_response" and not is_correct and not unknown:
1324
- question_id = str(
1325
- current_question.get("question_id")
1326
- or f"oral_{current_index}"
1327
- )
1328
- attempts_by_question = state.setdefault(
1329
- "oral_attempts_by_question", {}
1330
- )
1331
- oral_attempt = self.safe_int(
1332
- attempts_by_question.get(question_id, 0), 0
1333
- ) + 1
1334
- attempts_by_question[question_id] = oral_attempt
1335
- oral_limit = max(
1336
- 1,
1337
- self.safe_int(state.get("oral_max_attempts", 2), 2),
1338
- )
1339
-
1340
- state.setdefault("oral_retry_events", []).append(
1341
- {
1342
- "question_id": question_id,
1343
- "attempt_number": oral_attempt,
1344
- "selected": selected,
1345
- "created_at": self.now(),
1346
- "counts_in_evaluation": False,
1347
- }
1348
- )
1349
- state["current_question"] = current_question
1350
- state["question"] = current_question
1351
- state["answer_locked"] = False
1352
- state["updated_at"] = self.now()
1353
-
1354
- if oral_attempt < oral_limit:
1355
- feedback = {
1356
- "event": "oral_retry",
1357
- "sound_key": "try_again",
1358
- "message": (
1359
- "لم تتطابق الإجابة الشفهية. "
1360
- "راجع النص الناتج ثم حاول مرة أخيرة."
1361
- ),
1362
- "screen_reader_status": "محاولة شفهية أخيرة",
1363
- "help_available": False,
1364
- }
1365
- state["last_feedback"] = feedback
1366
- self.last_state = state
1367
- question_ui = self.build_question_ui(
1368
- current_question,
1369
- current_index,
1370
- len(questions),
1371
- help_available=False,
1372
- )
1373
- return {
1374
- "success": True,
1375
- "ready": True,
1376
- "completed": False,
1377
- "retry_same_question": True,
1378
- "oral_retry": True,
1379
- "oral_attempt_number": oral_attempt,
1380
- "oral_attempts_remaining": oral_limit - oral_attempt,
1381
- "state": state,
1382
- "game_state": state,
1383
- "current_question": current_question,
1384
- "question": current_question,
1385
- "options": current_question.get("options", []),
1386
- "choices": current_question.get("options", []),
1387
- "option_buttons": current_question.get("option_buttons", []),
1388
- "unknown_option": current_question.get("unknown_option", {}),
1389
- "question_ui": question_ui,
1390
- "millionaire_ui": question_ui,
1391
- "text": (
1392
- self.question_text(
1393
- current_question,
1394
- current_index,
1395
- len(questions),
1396
- )
1397
- + "\n\nلديك محاولة صوتية أخيرة."
1398
- ),
1399
- "feedback": feedback,
1400
- "feedback_event": feedback.get("event"),
1401
- "feedback_sound_key": feedback.get("sound_key"),
1402
- "screen_reader_status": feedback.get("screen_reader_status"),
1403
- "answer_locked": False,
1404
- "version": self.version,
1405
- }
1406
 
1407
  if is_correct:
1408
  answer_type = "correct"
@@ -1427,8 +1232,6 @@ class BadgeGameManager:
1427
  "prompt": current_question.get("prompt", ""),
1428
  "selected": selected,
1429
  "selected_raw": str(answer or ""),
1430
- "submission_source": "whiteboard" if whiteboard_submission.get("is_whiteboard") else "direct",
1431
- "whiteboard_evaluation": whiteboard_submission.get("evaluation") or {},
1432
  "correct": correct,
1433
  "is_correct": is_correct,
1434
  "answer_type": answer_type,
@@ -1513,9 +1316,6 @@ class BadgeGameManager:
1513
 
1514
  if state["current_index"] >= len(questions):
1515
  state["status"] = "completed"
1516
- state["last_answered_question"] = current_question
1517
- state["current_question"] = {}
1518
- state["question"] = {}
1519
  self.last_state = state
1520
  return self.completed_result(
1521
  state,
@@ -1528,8 +1328,6 @@ class BadgeGameManager:
1528
  badge_id=state.get("badge_id", "math_addition"),
1529
  shuffle_options=False,
1530
  )
1531
- state["current_question"] = next_question
1532
- state["question"] = next_question
1533
  state["answer_locked"] = False
1534
  state["question_started_at"] = self.now()
1535
  state["current_prize"] = self.prize_for_index(state["current_index"], len(questions))
@@ -1714,6 +1512,735 @@ class BadgeGameManager:
1714
  def submit_badge_answer(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
1715
  return self.submit_answer(*args, **kwargs)
1716
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1717
  # =========================================================
1718
  # طلب المساعدة
1719
  # =========================================================
@@ -1847,6 +2374,121 @@ class BadgeGameManager:
1847
  "version": self.version,
1848
  }
1849
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1850
  # =========================================================
1851
  # قراءة الحالة وفحص المدير
1852
  # =========================================================
@@ -1908,6 +2550,17 @@ class BadgeGameManager:
1908
  "answer_options": 4,
1909
  "unknown_is_separate_button": True,
1910
  "unknown_label": self.UNKNOWN_LABEL,
 
 
 
 
 
 
 
 
 
 
 
1911
  "help_trigger": {
1912
  "same_error_count": 2,
1913
  "consecutive_wrong": 2,
@@ -1929,6 +2582,8 @@ class BadgeGameManager:
1929
  "start_game",
1930
  "submit_answer",
1931
  "submit_badge_answer",
 
 
1932
  "get_current_question",
1933
  "get_help_options",
1934
  "request_help",
@@ -1972,6 +2627,20 @@ def submit_badge_answer(*args: Any, **kwargs: Any) -> Dict[str, Any]:
1972
  return get_manager().submit_badge_answer(*args, **kwargs)
1973
 
1974
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1975
  def get_current_question(*args: Any, **kwargs: Any) -> Dict[str, Any]:
1976
  return get_manager().get_current_question(*args, **kwargs)
1977
 
 
22
  from __future__ import annotations
23
 
24
  from datetime import datetime
25
+ import hashlib
26
  import json
27
  import random
 
28
  import re
29
  import uuid
30
  from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
 
39
  class BadgeGameManager:
40
  """مدير لعبة الوسام والتشخيص التفاعلي."""
41
 
42
+ VERSION = "badge_game_manager_v16_question_report_source_identity"
43
  UNKNOWN_LABEL = "لا أعلم"
44
 
45
  PRIZE_LADDER = [
 
83
  ("D", "د"),
84
  ]
85
 
86
+ QUESTION_REPORT_REASONS = {
87
+ "wording_unclear": "صياغة السؤال غير واضحة",
88
+ "answer_key_wrong": "الإجابة المعتمدة تبدو خاطئة",
89
+ "no_correct_option": "لا يوجد خيار صحيح",
90
+ "multiple_correct_options": "يوجد أكثر من خيار صحيح",
91
+ "skill_mismatch": "السؤال لا يطابق المهارة",
92
+ "symbol_or_visual_unclear": "رمز أو صورة أو سبورة غير واضحة",
93
+ "clarification_inappropriate": "التوضيح غير مناسب",
94
+ "hint_inappropriate": "التلميح غير مناسب أو يكشف الحل",
95
+ "glossary_incorrect": "تعريف مفهوم أو رمز غير صحيح",
96
+ "other": "سبب آخر",
97
+ }
98
+
99
  def __init__(self, *args: Any, **kwargs: Any) -> None:
100
  self.version = self.VERSION
101
  self.last_state: Dict[str, Any] = {}
 
475
  badge_id: str,
476
  count: int,
477
  skill_id: str = "",
 
 
 
478
  ) -> List[Dict[str, Any]]:
479
  method = getattr(bank, method_name, None)
480
  if not callable(method):
481
  return []
482
 
 
 
 
 
 
 
483
  attempts = [
484
  {
485
  "subject": subject,
 
487
  "badge_id": badge_id,
488
  "skill_id": skill_id,
489
  "count": count,
 
490
  },
491
+ {"skill_id": skill_id, "grade": grade, "count": count} if skill_id else {},
492
+ {"grade": grade, "badge_id": badge_id, "count": count},
493
+ {"badge_id": badge_id, "count": count},
494
+ {"badge_id": badge_id},
495
  ]
496
 
497
  for call_kwargs in attempts:
 
516
  badge_id: str = "math_addition",
517
  count: int = 8,
518
  skill_id: str = "",
 
 
 
519
  ) -> List[Dict[str, Any]]:
520
  subject = self.normalize_subject(subject)
521
  grade = self.safe_int(grade, 1)
 
545
  badge_id=badge_id,
546
  count=count,
547
  skill_id=target_skill,
 
 
 
548
  )
549
  if questions:
550
  return questions[:count]
 
758
  answer = str(raw_options[0])
759
 
760
  answer_text = self._strip_choice_prefix(answer)
761
+ option_texts = self._ensure_four_options(prompt, raw_options, answer_text)
762
 
763
+ if shuffle_options:
764
+ random.shuffle(option_texts)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
765
 
766
+ labeled_options, option_buttons = self._label_options(option_texts)
 
 
767
 
768
  cleaned = dict(q)
769
  cleaned.update(
 
814
  or ""
815
  ).strip()
816
 
817
+ # لا نكرر الخيارات داخل النص؛ app.py يعرضها كأزرار مستقلة.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
818
  return (
819
  f"السؤال {index + 1} من {total}\n\n"
820
  f"{prompt}\n\n"
821
+ "اختر إجابتك من الأزرار، أو اضغط لا أعلم."
822
  ).strip()
823
 
824
  def build_question_ui(
 
889
  if not exact_skill_id and str(badge_id).startswith("DIVID-MATH-"):
890
  exact_skill_id = str(badge_id)
891
 
 
 
 
 
 
 
 
 
892
  questions = self.load_questions_from_bank(
893
  subject=subject_key,
894
  grade=grade,
895
  badge_id=badge_id,
896
  count=count,
897
  skill_id=exact_skill_id,
 
 
 
898
  )
899
+ source = "question_bank_manager_exact_skill"
900
 
901
  if not questions:
902
  questions = self.emergency_questions(badge_id=badge_id, count=count)
 
907
  for item in questions
908
  if isinstance(item, dict)
909
  ]
 
910
 
911
  if not cleaned_questions:
912
  return {
 
952
  "last_help_request": {},
953
  "answer_locked": False,
954
  "last_feedback": {},
 
 
 
 
 
 
 
 
 
 
955
  "stop_on_first_confirmed_error": bool(
956
  STOP_ON_FIRST_CONFIRMED_ERROR
957
  ),
 
960
  "termination_error_type": "",
961
  "terminated_at_index": None,
962
  "attempted_questions": 0,
963
+
964
+ # بلاغات جودة السؤال لا تدخل في التقييم.
965
+ "reported_question_ids": [],
966
+ "question_reports": [],
967
+ "reported_questions_count": 0,
968
+ "last_question_report": {},
969
+ "last_report_replacement": {},
970
+
971
  "source": source,
972
  "created_at": self.now(),
973
  "question_started_at": self.now(),
 
1015
  # الإجابات وتكرار الخطأ
1016
  # =========================================================
1017
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1018
  def _resolve_selected_value(
1019
  self,
1020
  answer: Any,
1021
  question: Dict[str, Any],
1022
  ) -> str:
1023
  if isinstance(answer, dict):
 
 
 
1024
  answer = (
1025
  answer.get("value")
1026
  or answer.get("text")
1027
  or answer.get("label")
1028
  or answer.get("key")
 
1029
  or ""
1030
  )
1031
 
 
1179
  shuffle_options=False,
1180
  )
1181
 
 
1182
  selected = self._resolve_selected_value(answer, current_question)
1183
  if not selected:
1184
  return {
 
1206
  or ""
1207
  ).strip()
1208
 
1209
+ unknown = self.is_unknown(selected)
1210
+ is_correct = False if unknown else self.answer_matches(selected, correct)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1211
 
1212
  if is_correct:
1213
  answer_type = "correct"
 
1232
  "prompt": current_question.get("prompt", ""),
1233
  "selected": selected,
1234
  "selected_raw": str(answer or ""),
 
 
1235
  "correct": correct,
1236
  "is_correct": is_correct,
1237
  "answer_type": answer_type,
 
1316
 
1317
  if state["current_index"] >= len(questions):
1318
  state["status"] = "completed"
 
 
 
1319
  self.last_state = state
1320
  return self.completed_result(
1321
  state,
 
1328
  badge_id=state.get("badge_id", "math_addition"),
1329
  shuffle_options=False,
1330
  )
 
 
1331
  state["answer_locked"] = False
1332
  state["question_started_at"] = self.now()
1333
  state["current_prize"] = self.prize_for_index(state["current_index"], len(questions))
 
1512
  def submit_badge_answer(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
1513
  return self.submit_answer(*args, **kwargs)
1514
 
1515
+ # =========================================================
1516
+ # الإبلاغ عن سؤال جودة واستبداله
1517
+ # =========================================================
1518
+
1519
+ def _question_report_manager(self):
1520
+ """
1521
+ BadgeGameManager لا يملك ملف البلاغات.
1522
+ الحفظ الدائم مسؤولية QuestionReportManager.
1523
+ """
1524
+ try:
1525
+ from question_report_manager import get_manager
1526
+ return get_manager()
1527
+ except Exception:
1528
+ try:
1529
+ from question_report_manager import QuestionReportManager
1530
+ return QuestionReportManager()
1531
+ except Exception:
1532
+ return None
1533
+
1534
+ def normalize_report_reason(self, reason: Any) -> str:
1535
+ raw = str(reason or "").strip()
1536
+ if raw in self.QUESTION_REPORT_REASONS:
1537
+ return raw
1538
+
1539
+ normalized = self.normalize_text(raw)
1540
+ for key, label in self.QUESTION_REPORT_REASONS.items():
1541
+ if normalized == self.normalize_text(label):
1542
+ return key
1543
+
1544
+ return "other"
1545
+
1546
+ def question_report_reasons(self) -> List[Dict[str, str]]:
1547
+ return [
1548
+ {
1549
+ "id": key,
1550
+ "label": label,
1551
+ }
1552
+ for key, label in self.QUESTION_REPORT_REASONS.items()
1553
+ ]
1554
+
1555
+ def _question_quality_fingerprint(
1556
+ self,
1557
+ question: Dict[str, Any],
1558
+ ) -> str:
1559
+ if not isinstance(question, dict):
1560
+ return ""
1561
+
1562
+ explicit = str(
1563
+ question.get("source_fingerprint")
1564
+ or question.get("question_fingerprint")
1565
+ or question.get("fingerprint")
1566
+ or ""
1567
+ ).strip()
1568
+ if explicit:
1569
+ return explicit
1570
+
1571
+ payload = {
1572
+ "question_id": question.get("question_id", ""),
1573
+ "skill_id": question.get("skill_id", ""),
1574
+ "prompt": question.get("prompt", ""),
1575
+ "options": question.get("option_texts")
1576
+ or question.get("options")
1577
+ or [],
1578
+ "answer": question.get("correct_answer")
1579
+ or question.get("answer")
1580
+ or "",
1581
+ }
1582
+ try:
1583
+ raw = json.dumps(
1584
+ payload,
1585
+ ensure_ascii=False,
1586
+ sort_keys=True,
1587
+ default=str,
1588
+ )
1589
+ except Exception:
1590
+ raw = str(payload)
1591
+
1592
+ return hashlib.sha256(
1593
+ raw.encode("utf-8")
1594
+ ).hexdigest()
1595
+
1596
+ def build_question_report_payload(
1597
+ self,
1598
+ state: Any,
1599
+ reason: Any,
1600
+ note: Any = "",
1601
+ ) -> Dict[str, Any]:
1602
+ state_dict = self.ensure_state(state) or self.last_state
1603
+ if not isinstance(state_dict, dict) or not state_dict:
1604
+ return {
1605
+ "success": False,
1606
+ "message": "لا توجد جلسة وسام نشطة.",
1607
+ "version": self.version,
1608
+ }
1609
+
1610
+ questions = state_dict.get("questions") or []
1611
+ current_index = self.safe_int(
1612
+ state_dict.get("current_index", 0),
1613
+ 0,
1614
+ )
1615
+ if (
1616
+ not isinstance(questions, list)
1617
+ or current_index < 0
1618
+ or current_index >= len(questions)
1619
+ ):
1620
+ return {
1621
+ "success": False,
1622
+ "message": "لا يوجد سؤال حالي للإبلاغ عنه.",
1623
+ "version": self.version,
1624
+ }
1625
+
1626
+ question = self.clean_question(
1627
+ questions[current_index],
1628
+ badge_id=state_dict.get(
1629
+ "badge_id",
1630
+ "math_addition",
1631
+ ),
1632
+ shuffle_options=False,
1633
+ )
1634
+
1635
+ reason_id = self.normalize_report_reason(reason)
1636
+ reason_label = self.QUESTION_REPORT_REASONS.get(
1637
+ reason_id,
1638
+ self.QUESTION_REPORT_REASONS["other"],
1639
+ )
1640
+
1641
+ note_text = str(note or "").strip()[:1000]
1642
+
1643
+ report = {
1644
+ "event_type": "question_quality_report",
1645
+ "report_id": f"qreport_{uuid.uuid4().hex}",
1646
+ "session_id": str(
1647
+ state_dict.get("session_id") or ""
1648
+ ),
1649
+ "game_id": str(
1650
+ state_dict.get("game_id") or ""
1651
+ ),
1652
+ "student_id": str(
1653
+ state_dict.get("identity") or ""
1654
+ ),
1655
+ "subject": str(
1656
+ state_dict.get("subject")
1657
+ or question.get("subject")
1658
+ or ""
1659
+ ),
1660
+ "grade": self.safe_int(
1661
+ state_dict.get("grade"),
1662
+ 1,
1663
+ ),
1664
+ "badge_id": str(
1665
+ state_dict.get("badge_id")
1666
+ or question.get("badge_id")
1667
+ or ""
1668
+ ),
1669
+ "skill_id": str(
1670
+ state_dict.get("skill_id")
1671
+ or question.get("skill_id")
1672
+ or ""
1673
+ ),
1674
+ "question_id": str(
1675
+ question.get("question_id") or ""
1676
+ ),
1677
+ "source_key": str(
1678
+ question.get("source_key")
1679
+ or question.get("quality_source_key")
1680
+ or ""
1681
+ ),
1682
+ "source_type": str(
1683
+ question.get("source_type")
1684
+ or question.get("quality_source_type")
1685
+ or question.get("source")
1686
+ or ""
1687
+ ),
1688
+ "source_id": str(
1689
+ question.get("source_id")
1690
+ or question.get("template_id")
1691
+ or question.get("question_id")
1692
+ or ""
1693
+ ),
1694
+ "question_fingerprint": self._question_quality_fingerprint(
1695
+ question
1696
+ ),
1697
+ "question_version": str(
1698
+ question.get("audit_version")
1699
+ or question.get("quality_version")
1700
+ or question.get("version")
1701
+ or ""
1702
+ ),
1703
+ "quality_status": str(
1704
+ question.get("quality_status") or ""
1705
+ ),
1706
+ "quality_badge": str(
1707
+ question.get("quality_badge") or ""
1708
+ ),
1709
+ "reason_id": reason_id,
1710
+ "reason_label": reason_label,
1711
+ "note": note_text,
1712
+ "question_snapshot": {
1713
+ "question_id": str(
1714
+ question.get("question_id") or ""
1715
+ ),
1716
+ "prompt": str(
1717
+ question.get("prompt")
1718
+ or question.get("question")
1719
+ or ""
1720
+ ),
1721
+ "item_type": str(
1722
+ question.get("item_type")
1723
+ or question.get("question_type")
1724
+ or ""
1725
+ ),
1726
+ "options": list(
1727
+ question.get("option_texts")
1728
+ or question.get("options")
1729
+ or []
1730
+ ),
1731
+ "approved_answer": str(
1732
+ question.get("correct_answer")
1733
+ or question.get("answer")
1734
+ or ""
1735
+ ),
1736
+ "approved_support": question.get(
1737
+ "approved_support"
1738
+ )
1739
+ or question.get("support")
1740
+ or {},
1741
+ "source": str(
1742
+ question.get("source") or ""
1743
+ ),
1744
+ "source_key": str(
1745
+ question.get("source_key")
1746
+ or question.get("quality_source_key")
1747
+ or ""
1748
+ ),
1749
+ "source_type": str(
1750
+ question.get("source_type")
1751
+ or question.get("quality_source_type")
1752
+ or question.get("source")
1753
+ or ""
1754
+ ),
1755
+ "source_id": str(
1756
+ question.get("source_id")
1757
+ or question.get("template_id")
1758
+ or question.get("question_id")
1759
+ or ""
1760
+ ),
1761
+ },
1762
+ "evaluation_effect": "none",
1763
+ "counts_as_attempt": False,
1764
+ "counts_as_wrong": False,
1765
+ "opens_learning_gap": False,
1766
+ "student_flow_action": "replace_question_and_continue",
1767
+ "reported_at": self.now(),
1768
+ "badge_game_manager_version": self.version,
1769
+ }
1770
+
1771
+ return {
1772
+ "success": True,
1773
+ "report": report,
1774
+ "question": question,
1775
+ "current_index": current_index,
1776
+ "version": self.version,
1777
+ }
1778
+
1779
+ def _save_question_report(
1780
+ self,
1781
+ report: Dict[str, Any],
1782
+ report_manager: Any = None,
1783
+ ) -> Dict[str, Any]:
1784
+ manager = report_manager or self._question_report_manager()
1785
+
1786
+ if manager is None:
1787
+ return {
1788
+ "success": False,
1789
+ "saved": False,
1790
+ "message": (
1791
+ "QuestionReportManager غير متاح؛ "
1792
+ "لن يتم تخطي السؤال قبل حفظ البلاغ."
1793
+ ),
1794
+ }
1795
+
1796
+ for method_name in (
1797
+ "report_question",
1798
+ "create_report",
1799
+ "save_report",
1800
+ "submit_report",
1801
+ ):
1802
+ method = getattr(manager, method_name, None)
1803
+ if not callable(method):
1804
+ continue
1805
+
1806
+ try:
1807
+ try:
1808
+ result = method(report=report)
1809
+ except TypeError:
1810
+ result = method(report)
1811
+
1812
+ if isinstance(result, dict):
1813
+ if result.get("success"):
1814
+ result.setdefault("saved", True)
1815
+ return result
1816
+ return result
1817
+
1818
+ if result:
1819
+ return {
1820
+ "success": True,
1821
+ "saved": True,
1822
+ "result": result,
1823
+ }
1824
+ except Exception as exc:
1825
+ return {
1826
+ "success": False,
1827
+ "saved": False,
1828
+ "message": str(exc),
1829
+ }
1830
+
1831
+ return {
1832
+ "success": False,
1833
+ "saved": False,
1834
+ "message": (
1835
+ "QuestionReportManager لا يحتوي دالة حفظ بلاغ مدعومة."
1836
+ ),
1837
+ }
1838
+
1839
+ def _reported_question_blocklist(
1840
+ self,
1841
+ state: Dict[str, Any],
1842
+ ) -> Tuple[set, set]:
1843
+ blocked_ids = {
1844
+ str(value)
1845
+ for value in (
1846
+ state.get("reported_question_ids") or []
1847
+ )
1848
+ if str(value).strip()
1849
+ }
1850
+
1851
+ blocked_fingerprints = set()
1852
+
1853
+ for item in state.get("question_reports") or []:
1854
+ if not isinstance(item, dict):
1855
+ continue
1856
+ report = item.get("report") or item
1857
+ if not isinstance(report, dict):
1858
+ continue
1859
+ question_id = str(
1860
+ report.get("question_id") or ""
1861
+ ).strip()
1862
+ fingerprint = str(
1863
+ report.get("question_fingerprint") or ""
1864
+ ).strip()
1865
+ if question_id:
1866
+ blocked_ids.add(question_id)
1867
+ if fingerprint:
1868
+ blocked_fingerprints.add(fingerprint)
1869
+
1870
+ return blocked_ids, blocked_fingerprints
1871
+
1872
+ def _find_replacement_question(
1873
+ self,
1874
+ state: Dict[str, Any],
1875
+ reported_question: Dict[str, Any],
1876
+ ) -> Dict[str, Any]:
1877
+ questions = state.get("questions") or []
1878
+ current_index = self.safe_int(
1879
+ state.get("current_index", 0),
1880
+ 0,
1881
+ )
1882
+
1883
+ blocked_ids, blocked_fingerprints = (
1884
+ self._reported_question_blocklist(state)
1885
+ )
1886
+
1887
+ current_id = str(
1888
+ reported_question.get("question_id") or ""
1889
+ ).strip()
1890
+ current_fingerprint = self._question_quality_fingerprint(
1891
+ reported_question
1892
+ )
1893
+ if current_id:
1894
+ blocked_ids.add(current_id)
1895
+ if current_fingerprint:
1896
+ blocked_fingerprints.add(current_fingerprint)
1897
+
1898
+ # لا نكرر سؤالًا موجودًا أصلًا داخل نفس جلسة الوسام.
1899
+ existing_ids = set()
1900
+ existing_fingerprints = set()
1901
+ for index, question in enumerate(questions):
1902
+ if index == current_index or not isinstance(question, dict):
1903
+ continue
1904
+ qid = str(question.get("question_id") or "").strip()
1905
+ if qid:
1906
+ existing_ids.add(qid)
1907
+ fp = self._question_quality_fingerprint(question)
1908
+ if fp:
1909
+ existing_fingerprints.add(fp)
1910
+
1911
+ requested_count = max(
1912
+ 20,
1913
+ len(questions) + len(blocked_ids) + 10,
1914
+ )
1915
+
1916
+ candidates = self.load_questions_from_bank(
1917
+ subject=str(state.get("subject") or "math"),
1918
+ grade=self.safe_int(state.get("grade"), 1),
1919
+ badge_id=str(
1920
+ state.get("badge_id")
1921
+ or reported_question.get("badge_id")
1922
+ or "math_addition"
1923
+ ),
1924
+ count=requested_count,
1925
+ skill_id=str(
1926
+ state.get("skill_id")
1927
+ or reported_question.get("skill_id")
1928
+ or ""
1929
+ ),
1930
+ )
1931
+
1932
+ for candidate in candidates:
1933
+ if not isinstance(candidate, dict):
1934
+ continue
1935
+
1936
+ cleaned = self.clean_question(
1937
+ candidate,
1938
+ badge_id=str(
1939
+ state.get("badge_id")
1940
+ or reported_question.get("badge_id")
1941
+ or "math_addition"
1942
+ ),
1943
+ shuffle_options=True,
1944
+ )
1945
+
1946
+ candidate_id = str(
1947
+ cleaned.get("question_id") or ""
1948
+ ).strip()
1949
+ candidate_fp = self._question_quality_fingerprint(cleaned)
1950
+
1951
+ if candidate_id and (
1952
+ candidate_id in blocked_ids
1953
+ or candidate_id in existing_ids
1954
+ ):
1955
+ continue
1956
+
1957
+ if candidate_fp and (
1958
+ candidate_fp in blocked_fingerprints
1959
+ or candidate_fp in existing_fingerprints
1960
+ ):
1961
+ continue
1962
+
1963
+ return {
1964
+ "success": True,
1965
+ "question": cleaned,
1966
+ "source": "question_bank_same_skill",
1967
+ }
1968
+
1969
+ return {
1970
+ "success": False,
1971
+ "message": (
1972
+ "تم حفظ البلاغ، لكن لم يُعثر الآن على سؤال بديل "
1973
+ "جديد من نفس المهارة."
1974
+ ),
1975
+ }
1976
+
1977
+ def report_current_question(
1978
+ self,
1979
+ state: Any = None,
1980
+ reason: Any = "other",
1981
+ note: Any = "",
1982
+ report_manager: Any = None,
1983
+ ) -> Dict[str, Any]:
1984
+ """
1985
+ يسجل البلاغ ويستبدل السؤال دون أي أثر تقييمي.
1986
+
1987
+ ثوابت لا تتغير بسبب البلاغ:
1988
+ - current_index
1989
+ - answers
1990
+ - correct_count
1991
+ - wrong_count
1992
+ - unknown_count
1993
+ - attempted_questions
1994
+ - error_counts
1995
+ - needs_remedial
1996
+ """
1997
+ state_dict = self.ensure_state(state)
1998
+ if not state_dict:
1999
+ state_dict = self.last_state
2000
+
2001
+ if not isinstance(state_dict, dict) or not state_dict:
2002
+ return {
2003
+ "success": False,
2004
+ "message": "لا توجد جلسة وسام نشطة.",
2005
+ "version": self.version,
2006
+ }
2007
+
2008
+ if str(state_dict.get("status") or "active") != "active":
2009
+ return {
2010
+ "success": False,
2011
+ "message": "جلسة الوسام ليست نشطة.",
2012
+ "state": state_dict,
2013
+ "game_state": state_dict,
2014
+ "version": self.version,
2015
+ }
2016
+
2017
+ payload_result = self.build_question_report_payload(
2018
+ state_dict,
2019
+ reason,
2020
+ note,
2021
+ )
2022
+ if not payload_result.get("success"):
2023
+ return payload_result
2024
+
2025
+ report = payload_result["report"]
2026
+ reported_question = payload_result["question"]
2027
+ current_index = payload_result["current_index"]
2028
+
2029
+ # Snapshot للعدادات قبل البلاغ لضمان أن البلاغ لا يدخل التقييم.
2030
+ invariants = {
2031
+ "current_index": self.safe_int(
2032
+ state_dict.get("current_index"), 0
2033
+ ),
2034
+ "answers_len": len(
2035
+ state_dict.get("answers") or []
2036
+ ),
2037
+ "correct_count": self.safe_int(
2038
+ state_dict.get("correct_count"), 0
2039
+ ),
2040
+ "wrong_count": self.safe_int(
2041
+ state_dict.get("wrong_count"), 0
2042
+ ),
2043
+ "unknown_count": self.safe_int(
2044
+ state_dict.get("unknown_count"), 0
2045
+ ),
2046
+ "attempted_questions": self.safe_int(
2047
+ state_dict.get("attempted_questions"), 0
2048
+ ),
2049
+ "error_counts": dict(
2050
+ state_dict.get("error_counts") or {}
2051
+ ),
2052
+ "needs_remedial": bool(
2053
+ state_dict.get("needs_remedial", False)
2054
+ ),
2055
+ "terminated_early": bool(
2056
+ state_dict.get("terminated_early", False)
2057
+ ),
2058
+ }
2059
+
2060
+ saved = self._save_question_report(
2061
+ report,
2062
+ report_manager=report_manager,
2063
+ )
2064
+ if not isinstance(saved, dict) or not saved.get("success"):
2065
+ return {
2066
+ "success": False,
2067
+ "report_saved": False,
2068
+ "message": (
2069
+ (saved or {}).get("message")
2070
+ if isinstance(saved, dict)
2071
+ else "تعذر حفظ البلاغ."
2072
+ ),
2073
+ "report": report,
2074
+ "state": state_dict,
2075
+ "game_state": state_dict,
2076
+ "version": self.version,
2077
+ }
2078
+
2079
+ state_dict.setdefault(
2080
+ "reported_question_ids",
2081
+ [],
2082
+ )
2083
+ question_id = str(
2084
+ report.get("question_id") or ""
2085
+ ).strip()
2086
+ if (
2087
+ question_id
2088
+ and question_id not in state_dict["reported_question_ids"]
2089
+ ):
2090
+ state_dict["reported_question_ids"].append(
2091
+ question_id
2092
+ )
2093
+
2094
+ state_dict.setdefault(
2095
+ "question_reports",
2096
+ [],
2097
+ ).append(
2098
+ {
2099
+ "report": report,
2100
+ "save_result": saved,
2101
+ }
2102
+ )
2103
+ state_dict["reported_questions_count"] = len(
2104
+ state_dict.get("question_reports") or []
2105
+ )
2106
+ state_dict["last_question_report"] = report
2107
+
2108
+ replacement = self._find_replacement_question(
2109
+ state_dict,
2110
+ reported_question,
2111
+ )
2112
+
2113
+ if not replacement.get("success"):
2114
+ # البلاغ محفوظ، لكن لا نسمح بإجابة السؤال المبلغ عنه.
2115
+ state_dict["answer_locked"] = True
2116
+ state_dict["updated_at"] = self.now()
2117
+ self.last_state = state_dict
2118
+
2119
+ return {
2120
+ "success": False,
2121
+ "report_saved": True,
2122
+ "replacement_found": False,
2123
+ "message": replacement.get(
2124
+ "message",
2125
+ "تم حفظ البلاغ وتعذر إيجاد بديل.",
2126
+ ),
2127
+ "report": report,
2128
+ "save_result": saved,
2129
+ "state": state_dict,
2130
+ "game_state": state_dict,
2131
+ "current_question": reported_question,
2132
+ "question": reported_question,
2133
+ "evaluation_effect": "none",
2134
+ "counts_as_attempt": False,
2135
+ "counts_as_wrong": False,
2136
+ "opens_learning_gap": False,
2137
+ "version": self.version,
2138
+ }
2139
+
2140
+ new_question = replacement["question"]
2141
+ questions = state_dict.get("questions") or []
2142
+ questions[current_index] = new_question
2143
+ state_dict["questions"] = questions
2144
+
2145
+ state_dict["last_report_replacement"] = {
2146
+ "reported_question_id": question_id,
2147
+ "replacement_question_id": str(
2148
+ new_question.get("question_id") or ""
2149
+ ),
2150
+ "replaced_at": self.now(),
2151
+ "source": replacement.get("source", ""),
2152
+ }
2153
+
2154
+ # إعادة نفس السؤال الرقمي بسؤال جديد، لا انتقال للسؤال التالي.
2155
+ state_dict["current_index"] = invariants["current_index"]
2156
+ state_dict["correct_count"] = invariants["correct_count"]
2157
+ state_dict["wrong_count"] = invariants["wrong_count"]
2158
+ state_dict["unknown_count"] = invariants["unknown_count"]
2159
+ state_dict["attempted_questions"] = invariants[
2160
+ "attempted_questions"
2161
+ ]
2162
+ state_dict["error_counts"] = invariants["error_counts"]
2163
+ state_dict["needs_remedial"] = invariants["needs_remedial"]
2164
+ state_dict["terminated_early"] = invariants[
2165
+ "terminated_early"
2166
+ ]
2167
+
2168
+ # answers نفسها لم تُلمس؛ نتحقق ونحميها.
2169
+ answers = state_dict.get("answers") or []
2170
+ if len(answers) != invariants["answers_len"]:
2171
+ state_dict["answers"] = answers[
2172
+ :invariants["answers_len"]
2173
+ ]
2174
+
2175
+ state_dict["answer_locked"] = False
2176
+ state_dict["question_started_at"] = self.now()
2177
+ state_dict["updated_at"] = self.now()
2178
+ state_dict["last_feedback"] = {
2179
+ "event": "question_reported_replaced",
2180
+ "sound_key": "",
2181
+ "message": (
2182
+ "تم إرسال البلاغ للمراجعة واستبدال السؤال "
2183
+ "بسؤال آخر من نفس المهارة. البلاغ لا يؤثر في نتيجتك."
2184
+ ),
2185
+ "screen_reader_status": (
2186
+ "تم استبدال السؤال المبلغ عنه بسؤال جديد"
2187
+ ),
2188
+ "help_available": bool(
2189
+ state_dict.get("help_available", False)
2190
+ ),
2191
+ }
2192
+
2193
+ self.last_state = state_dict
2194
+
2195
+ question_ui = self.build_question_ui(
2196
+ new_question,
2197
+ current_index,
2198
+ len(questions),
2199
+ help_available=bool(
2200
+ state_dict.get("help_available", False)
2201
+ ),
2202
+ )
2203
+
2204
+ return {
2205
+ "success": True,
2206
+ "ready": True,
2207
+ "completed": False,
2208
+ "report_saved": True,
2209
+ "replacement_found": True,
2210
+ "report": report,
2211
+ "save_result": saved,
2212
+ "state": state_dict,
2213
+ "game_state": state_dict,
2214
+ "current_question": new_question,
2215
+ "question": new_question,
2216
+ "options": new_question.get("options", []),
2217
+ "choices": new_question.get("options", []),
2218
+ "option_buttons": new_question.get(
2219
+ "option_buttons",
2220
+ [],
2221
+ ),
2222
+ "unknown_option": new_question.get(
2223
+ "unknown_option",
2224
+ {},
2225
+ ),
2226
+ "question_ui": question_ui,
2227
+ "millionaire_ui": question_ui,
2228
+ "text": self.question_text(
2229
+ new_question,
2230
+ current_index,
2231
+ len(questions),
2232
+ ),
2233
+ "feedback": state_dict["last_feedback"],
2234
+ "feedback_event": "question_reported_replaced",
2235
+ "evaluation_effect": "none",
2236
+ "counts_as_attempt": False,
2237
+ "counts_as_wrong": False,
2238
+ "counts_as_unknown": False,
2239
+ "opens_learning_gap": False,
2240
+ "current_index_unchanged": True,
2241
+ "version": self.version,
2242
+ }
2243
+
2244
  # =========================================================
2245
  # طلب المساعدة
2246
  # =========================================================
 
2374
  "version": self.version,
2375
  }
2376
 
2377
+ # =========================================================
2378
+ # جسر السبورة التفاعلية
2379
+ # =========================================================
2380
+
2381
+ def whiteboard_task_from_current_question(
2382
+ self,
2383
+ state: Any = None,
2384
+ include_answer: bool = False,
2385
+ source: str = "badge",
2386
+ ) -> Dict[str, Any]:
2387
+ current = self.get_current_question(state)
2388
+ if not isinstance(current, dict) or not current.get("success"):
2389
+ return {
2390
+ "success": False,
2391
+ "message": current.get("message", "لا يوجد سؤال حالي للسبورة.") if isinstance(current, dict) else "لا يوجد سؤال حالي للسبورة.",
2392
+ "version": self.version,
2393
+ }
2394
+
2395
+ question = current.get("current_question") or {}
2396
+ option_buttons = question.get("option_buttons") or []
2397
+ options: List[Dict[str, Any]] = []
2398
+ for index, item in enumerate(option_buttons):
2399
+ if not isinstance(item, dict):
2400
+ continue
2401
+ value = item.get("value", item.get("text", ""))
2402
+ label = item.get("text") or item.get("label") or value
2403
+ options.append({
2404
+ "id": str(item.get("key") or f"opt_{index + 1}"),
2405
+ "value": str(value),
2406
+ "label_ar": str(label),
2407
+ })
2408
+
2409
+ task = {
2410
+ "task_id": str(question.get("question_id") or f"badge_task_{uuid.uuid4().hex}"),
2411
+ "question_id": str(question.get("question_id") or ""),
2412
+ "skill_id": str(question.get("skill_id") or (current.get("state") or {}).get("skill_id") or ""),
2413
+ "badge_id": str(question.get("badge_id") or (current.get("state") or {}).get("badge_id") or ""),
2414
+ "source": str(source or "badge"),
2415
+ "instruction_ar": str(question.get("prompt") or question.get("question") or ""),
2416
+ "response_mode": "single_choice",
2417
+ "options": options,
2418
+ "correct_answer": str(question.get("correct_answer") or question.get("answer") or "") if include_answer else None,
2419
+ "scoring": {
2420
+ "mode": "exact" if include_answer else "external",
2421
+ "incorrect_feedback_ar": str(question.get("explanation") or "الإجابة غير صحيحة."),
2422
+ },
2423
+ "feedback_policy": {
2424
+ "show_immediate": bool(include_answer),
2425
+ "show_correct_answer": False,
2426
+ },
2427
+ "allowed_tools": [],
2428
+ "clear_page": True,
2429
+ "max_attempts": 1,
2430
+ "stop_on_first_confirmed_error": bool(
2431
+ (current.get("state") or {}).get(
2432
+ "stop_on_first_confirmed_error",
2433
+ STOP_ON_FIRST_CONFIRMED_ERROR,
2434
+ )
2435
+ ),
2436
+ "metadata": {
2437
+ "current_index": (current.get("state") or {}).get("current_index", 0),
2438
+ "difficulty": question.get("difficulty", 1),
2439
+ "error_type_if_wrong": question.get("error_type_if_wrong", ""),
2440
+ },
2441
+ }
2442
+ return {
2443
+ "success": True,
2444
+ "ready": True,
2445
+ "task": task,
2446
+ "question": question,
2447
+ "state": current.get("state") or {},
2448
+ "version": self.version,
2449
+ }
2450
+
2451
+ def submit_whiteboard_response(
2452
+ self,
2453
+ state: Any = None,
2454
+ whiteboard_value: Any = None,
2455
+ whiteboard_response: Optional[Dict[str, Any]] = None,
2456
+ **kwargs: Any,
2457
+ ) -> Dict[str, Any]:
2458
+ response = whiteboard_response if isinstance(whiteboard_response, dict) else {}
2459
+ if not response and whiteboard_value is not None:
2460
+ try:
2461
+ from whiteboard_manager import get_whiteboard_response
2462
+ response = get_whiteboard_response(whiteboard_value)
2463
+ except Exception:
2464
+ response = {}
2465
+
2466
+ if not response:
2467
+ return {
2468
+ "success": False,
2469
+ "message": "لم تصل إجابة مؤكدة من السبورة.",
2470
+ "version": self.version,
2471
+ }
2472
+
2473
+ if str(response.get("status") or "") == "dont_know":
2474
+ selected = self.UNKNOWN_LABEL
2475
+ else:
2476
+ selected = response.get("answer")
2477
+ if isinstance(selected, dict) and "value" in selected:
2478
+ selected = selected.get("value")
2479
+ if isinstance(selected, list):
2480
+ selected = selected[0] if len(selected) == 1 else ",".join(str(x) for x in selected)
2481
+
2482
+ result = self.submit_answer(
2483
+ state=state,
2484
+ answer=selected,
2485
+ **kwargs,
2486
+ )
2487
+ if isinstance(result, dict):
2488
+ result["whiteboard_response"] = response
2489
+ result["input_channel"] = "interactive_whiteboard"
2490
+ return result
2491
+
2492
  # =========================================================
2493
  # قراءة الحالة وفحص المدير
2494
  # =========================================================
 
2550
  "answer_options": 4,
2551
  "unknown_is_separate_button": True,
2552
  "unknown_label": self.UNKNOWN_LABEL,
2553
+ "question_reporting": {
2554
+ "enabled": True,
2555
+ "reasons": self.question_report_reasons(),
2556
+ "evaluation_effect": "none",
2557
+ "counts_as_attempt": False,
2558
+ "counts_as_wrong": False,
2559
+ "counts_as_unknown": False,
2560
+ "opens_learning_gap": False,
2561
+ "replacement_policy": "same_skill_same_index",
2562
+ "persistence_owner": "question_report_manager",
2563
+ },
2564
  "help_trigger": {
2565
  "same_error_count": 2,
2566
  "consecutive_wrong": 2,
 
2582
  "start_game",
2583
  "submit_answer",
2584
  "submit_badge_answer",
2585
+ "report_current_question",
2586
+ "question_report_reasons",
2587
  "get_current_question",
2588
  "get_help_options",
2589
  "request_help",
 
2627
  return get_manager().submit_badge_answer(*args, **kwargs)
2628
 
2629
 
2630
+ def whiteboard_task_from_current_question(*args: Any, **kwargs: Any) -> Dict[str, Any]:
2631
+ return get_manager().whiteboard_task_from_current_question(*args, **kwargs)
2632
+
2633
+ def submit_whiteboard_response(*args: Any, **kwargs: Any) -> Dict[str, Any]:
2634
+ return get_manager().submit_whiteboard_response(*args, **kwargs)
2635
+
2636
+ def report_current_question(*args: Any, **kwargs: Any) -> Dict[str, Any]:
2637
+ return get_manager().report_current_question(*args, **kwargs)
2638
+
2639
+
2640
+ def question_report_reasons() -> List[Dict[str, str]]:
2641
+ return get_manager().question_report_reasons()
2642
+
2643
+
2644
  def get_current_question(*args: Any, **kwargs: Any) -> Dict[str, Any]:
2645
  return get_manager().get_current_question(*args, **kwargs)
2646
 
question_report_manager.py ADDED
@@ -0,0 +1,800 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ مدير بلاغات جودة الأسئلة.
6
+
7
+ v2:
8
+ - يوحد جميع بلاغات الأسئلة في ملف JSONL واحد.
9
+ - يزامن الملف مع StorageManager وخزنة النظام.
10
+ - البلاغ لا يحتسب إجابة أو خطأ أو محاولة.
11
+ - يطلب إعادة تدقيق السؤال من AITaskQueueManager عندما تتوفر هوية المصدر.
12
+ - يدعم حالات المراجعة من مكتب الإدارة.
13
+ - يحتفظ بالسجل كأحداث append-only حتى لا تضيع المراجعات السابقة.
14
+ - لا يستخدم GPU ولا يحمل أي نموذج.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import threading
22
+ import time
23
+ from copy import deepcopy
24
+ from datetime import datetime, timezone
25
+ from pathlib import Path
26
+ from typing import Any, Dict, List, Optional
27
+
28
+
29
+ VERSION = "question_report_manager_v2_storage_admin_review"
30
+
31
+ DEFAULT_REPORTS_FILE = (
32
+ os.getenv("QUESTION_REPORTS_FILE", "question_reports.jsonl").strip()
33
+ or "question_reports.jsonl"
34
+ )
35
+
36
+ VALID_STATUSES = {
37
+ "open",
38
+ "queued_for_reaudit",
39
+ "under_review",
40
+ "resolved",
41
+ "dismissed",
42
+ }
43
+
44
+ VALID_REASON_IDS = {
45
+ "unclear",
46
+ "no_correct_answer",
47
+ "multiple_correct_answers",
48
+ "wrong_skill",
49
+ "language_error",
50
+ "visual_error",
51
+ "technical_error",
52
+ "other",
53
+ }
54
+
55
+
56
+ class QuestionReportManager:
57
+ def __init__(
58
+ self,
59
+ reports_file: str = DEFAULT_REPORTS_FILE,
60
+ *args: Any,
61
+ **kwargs: Any,
62
+ ) -> None:
63
+ del args, kwargs
64
+ self.version = VERSION
65
+ self.reports_file = Path(reports_file)
66
+ self._lock = threading.RLock()
67
+ self._last_cloud_sync = 0.0
68
+ self._cloud_sync_interval_seconds = 15.0
69
+
70
+ parent = self.reports_file.parent
71
+ if str(parent) not in {"", "."}:
72
+ parent.mkdir(parents=True, exist_ok=True)
73
+
74
+ # ======================================================
75
+ # أدوات عامة
76
+ # ======================================================
77
+
78
+ def now(self) -> str:
79
+ return datetime.now(timezone.utc).isoformat()
80
+
81
+ def json_safe(self, value: Any) -> Any:
82
+ if value is None or isinstance(value, (str, int, float, bool)):
83
+ return value
84
+ if isinstance(value, dict):
85
+ return {
86
+ str(key): self.json_safe(item)
87
+ for key, item in value.items()
88
+ }
89
+ if isinstance(value, (list, tuple, set)):
90
+ return [self.json_safe(item) for item in value]
91
+ return str(value)
92
+
93
+ def _storage_manager(self):
94
+ try:
95
+ from storage_manager import get_manager
96
+ return get_manager()
97
+ except Exception:
98
+ try:
99
+ from storage_manager import StorageManager
100
+ return StorageManager()
101
+ except Exception:
102
+ return None
103
+
104
+ # ======================================================
105
+ # مزامنة الخزنة
106
+ # ======================================================
107
+
108
+ def sync_from_storage(
109
+ self,
110
+ force: bool = False,
111
+ ) -> Dict[str, Any]:
112
+ now_ts = time.time()
113
+ if (
114
+ not force
115
+ and self._last_cloud_sync
116
+ and now_ts - self._last_cloud_sync < self._cloud_sync_interval_seconds
117
+ ):
118
+ return {
119
+ "success": True,
120
+ "synced": False,
121
+ "skipped": True,
122
+ "message": "تم تجاوز المزامنة المتكررة القصيرة.",
123
+ "version": self.version,
124
+ }
125
+
126
+ storage = self._storage_manager()
127
+ if storage is None:
128
+ return {
129
+ "success": False,
130
+ "synced": False,
131
+ "message": "StorageManager غير متاح.",
132
+ "version": self.version,
133
+ }
134
+
135
+ method = getattr(storage, "sync_question_reports_from_cloud", None)
136
+ if not callable(method):
137
+ return {
138
+ "success": False,
139
+ "synced": False,
140
+ "message": "StorageManager لا يدعم مزامنة بلاغات الأسئلة.",
141
+ "version": self.version,
142
+ }
143
+
144
+ try:
145
+ result = method(str(self.reports_file))
146
+ self._last_cloud_sync = now_ts
147
+ if not isinstance(result, dict):
148
+ result = {
149
+ "success": bool(result),
150
+ "synced": bool(result),
151
+ }
152
+ result["report_manager_version"] = self.version
153
+ return result
154
+ except Exception as exc:
155
+ return {
156
+ "success": False,
157
+ "synced": False,
158
+ "message": str(exc),
159
+ "version": self.version,
160
+ }
161
+
162
+ def sync_to_storage(self) -> Dict[str, Any]:
163
+ storage = self._storage_manager()
164
+ if storage is None:
165
+ return {
166
+ "success": False,
167
+ "synced": False,
168
+ "message": "StorageManager غير متاح.",
169
+ "version": self.version,
170
+ }
171
+
172
+ method = getattr(storage, "sync_question_reports_to_cloud", None)
173
+ if not callable(method):
174
+ return {
175
+ "success": False,
176
+ "synced": False,
177
+ "message": "StorageManager لا يدعم رفع بلاغات الأسئلة.",
178
+ "version": self.version,
179
+ }
180
+
181
+ try:
182
+ result = method(str(self.reports_file))
183
+ if not isinstance(result, dict):
184
+ result = {
185
+ "success": bool(result),
186
+ "synced": bool(result),
187
+ }
188
+ result["report_manager_version"] = self.version
189
+ return result
190
+ except Exception as exc:
191
+ return {
192
+ "success": False,
193
+ "synced": False,
194
+ "message": str(exc),
195
+ "version": self.version,
196
+ }
197
+
198
+ # ======================================================
199
+ # سجل الأحداث
200
+ # ======================================================
201
+
202
+ def _append_local(self, row: Dict[str, Any]) -> None:
203
+ with self._lock:
204
+ with open(
205
+ self.reports_file,
206
+ "a",
207
+ encoding="utf-8",
208
+ ) as file:
209
+ file.write(
210
+ json.dumps(
211
+ self.json_safe(row),
212
+ ensure_ascii=False,
213
+ )
214
+ + "\n"
215
+ )
216
+
217
+ def _append(self, row: Dict[str, Any]) -> Dict[str, Any]:
218
+ # نسحب آخر نسخة معقولة قبل الكتابة حتى لا نستبدل سجلًا سحابيًا أقدم/أحدث.
219
+ self.sync_from_storage(force=True)
220
+ self._append_local(row)
221
+ cloud = self.sync_to_storage()
222
+ return cloud
223
+
224
+ def _read_events(
225
+ self,
226
+ refresh_cloud: bool = True,
227
+ ) -> List[Dict[str, Any]]:
228
+ if refresh_cloud:
229
+ self.sync_from_storage(force=False)
230
+
231
+ rows: List[Dict[str, Any]] = []
232
+ if not self.reports_file.exists():
233
+ return rows
234
+
235
+ try:
236
+ with self._lock:
237
+ with open(
238
+ self.reports_file,
239
+ "r",
240
+ encoding="utf-8",
241
+ ) as file:
242
+ for line in file:
243
+ line = line.strip()
244
+ if not line:
245
+ continue
246
+ try:
247
+ row = json.loads(line)
248
+ except Exception:
249
+ continue
250
+ if isinstance(row, dict):
251
+ rows.append(row)
252
+ except Exception:
253
+ return []
254
+
255
+ return rows
256
+
257
+ def _materialize_reports(
258
+ self,
259
+ events: List[Dict[str, Any]],
260
+ ) -> List[Dict[str, Any]]:
261
+ reports: Dict[str, Dict[str, Any]] = {}
262
+ order: List[str] = []
263
+
264
+ for event in events:
265
+ if not isinstance(event, dict):
266
+ continue
267
+
268
+ event_type = str(event.get("event_type") or "").strip()
269
+ report_id = str(event.get("report_id") or "").strip()
270
+ if not report_id:
271
+ continue
272
+
273
+ if event_type == "question_quality_report":
274
+ if report_id not in reports:
275
+ reports[report_id] = deepcopy(event)
276
+ order.append(report_id)
277
+ continue
278
+
279
+ if event_type == "question_report_status_changed":
280
+ report = reports.get(report_id)
281
+ if not isinstance(report, dict):
282
+ continue
283
+
284
+ report["report_status"] = str(
285
+ event.get("new_status")
286
+ or report.get("report_status")
287
+ or "open"
288
+ )
289
+ report["review_note"] = str(
290
+ event.get("review_note")
291
+ or report.get("review_note")
292
+ or ""
293
+ )
294
+ report["reviewed_by"] = str(
295
+ event.get("changed_by")
296
+ or report.get("reviewed_by")
297
+ or ""
298
+ )
299
+ report["reviewed_at"] = str(
300
+ event.get("changed_at")
301
+ or report.get("reviewed_at")
302
+ or ""
303
+ )
304
+ report["last_status_event"] = deepcopy(event)
305
+
306
+ return [
307
+ reports[report_id]
308
+ for report_id in order
309
+ if report_id in reports
310
+ ]
311
+
312
+ # ======================================================
313
+ # إعادة التدقيق
314
+ # ======================================================
315
+
316
+ def _request_reaudit(
317
+ self,
318
+ report: Dict[str, Any],
319
+ ) -> Dict[str, Any]:
320
+ source_type = str(
321
+ report.get("source_type") or ""
322
+ ).strip()
323
+ source_id = str(
324
+ report.get("source_id") or ""
325
+ ).strip()
326
+
327
+ if not source_type or not source_id:
328
+ return {
329
+ "success": False,
330
+ "requested": False,
331
+ "message": (
332
+ "تم حفظ البلاغ، لكن السؤال لا يحمل source_type/source_id "
333
+ "كافيين لإعادة إدخاله تلقائيًا في التدقيق."
334
+ ),
335
+ }
336
+
337
+ try:
338
+ from ai_task_queue_manager import get_manager
339
+ queue = get_manager()
340
+ except Exception:
341
+ try:
342
+ from ai_task_queue_manager import AITaskQueueManager
343
+ queue = AITaskQueueManager()
344
+ except Exception as exc:
345
+ return {
346
+ "success": False,
347
+ "requested": False,
348
+ "message": f"تعذر تحميل AITaskQueueManager: {exc}",
349
+ }
350
+
351
+ method = getattr(
352
+ queue,
353
+ "request_question_quality_reaudit",
354
+ None,
355
+ )
356
+ if not callable(method):
357
+ return {
358
+ "success": False,
359
+ "requested": False,
360
+ "message": (
361
+ "AITaskQueueManager لا يدعم طلب إعادة تدقيق السؤال."
362
+ ),
363
+ }
364
+
365
+ try:
366
+ result = method(
367
+ source_type=source_type,
368
+ source_id=source_id,
369
+ reason=(
370
+ "student_question_report:"
371
+ + str(report.get("reason_id") or "other")
372
+ ),
373
+ )
374
+ except Exception as exc:
375
+ return {
376
+ "success": False,
377
+ "requested": False,
378
+ "message": str(exc),
379
+ }
380
+
381
+ if not isinstance(result, dict):
382
+ result = {
383
+ "success": bool(result),
384
+ "result": result,
385
+ }
386
+
387
+ result["requested"] = bool(
388
+ result.get("success", False)
389
+ )
390
+ return result
391
+
392
+ # ======================================================
393
+ # إنشاء البلاغ
394
+ # ======================================================
395
+
396
+ def report_question(
397
+ self,
398
+ report: Optional[Dict[str, Any]] = None,
399
+ **kwargs: Any,
400
+ ) -> Dict[str, Any]:
401
+ data = dict(report) if isinstance(report, dict) else {}
402
+ data.update(kwargs)
403
+
404
+ report_id = str(data.get("report_id") or "").strip()
405
+ question_id = str(data.get("question_id") or "").strip()
406
+ reason_id = str(data.get("reason_id") or "other").strip().lower()
407
+
408
+ if not report_id:
409
+ return {
410
+ "success": False,
411
+ "saved": False,
412
+ "message": "report_id مفقود.",
413
+ "version": self.version,
414
+ }
415
+
416
+ if not question_id:
417
+ return {
418
+ "success": False,
419
+ "saved": False,
420
+ "message": "question_id مفقود.",
421
+ "version": self.version,
422
+ }
423
+
424
+ if reason_id not in VALID_REASON_IDS:
425
+ reason_id = "other"
426
+
427
+ # حماية من تكرار نفس report_id.
428
+ for existing in self._materialize_reports(
429
+ self._read_events(refresh_cloud=True)
430
+ ):
431
+ if str(existing.get("report_id") or "") == report_id:
432
+ return {
433
+ "success": True,
434
+ "saved": True,
435
+ "duplicate": True,
436
+ "report_id": report_id,
437
+ "report": existing,
438
+ "message": "البلاغ محفوظ مسبقًا.",
439
+ "version": self.version,
440
+ }
441
+
442
+ row = deepcopy(data)
443
+ row["reason_id"] = reason_id
444
+ row["event_type"] = "question_quality_report"
445
+ row["report_status"] = "open"
446
+ row["saved_at"] = self.now()
447
+ row["report_manager_version"] = self.version
448
+
449
+ # نثبت أن البلاغ لا يؤثر في التقييم.
450
+ row["evaluation_effect"] = "none"
451
+ row["counts_as_attempt"] = False
452
+ row["counts_as_wrong"] = False
453
+ row["counts_as_unknown"] = False
454
+ row["opens_learning_gap"] = False
455
+
456
+ reaudit = self._request_reaudit(row)
457
+
458
+ if reaudit.get("requested"):
459
+ row["report_status"] = "queued_for_reaudit"
460
+
461
+ row["reaudit"] = self.json_safe(reaudit)
462
+
463
+ try:
464
+ cloud = self._append(row)
465
+ except Exception as exc:
466
+ return {
467
+ "success": False,
468
+ "saved": False,
469
+ "message": f"تعذر حفظ البلاغ: {exc}",
470
+ "version": self.version,
471
+ }
472
+
473
+ return {
474
+ "success": True,
475
+ "saved": True,
476
+ "duplicate": False,
477
+ "report_id": report_id,
478
+ "report_status": row["report_status"],
479
+ "reaudit_requested": bool(
480
+ reaudit.get("requested", False)
481
+ ),
482
+ "cloud_synced": bool(
483
+ isinstance(cloud, dict) and cloud.get("success")
484
+ ),
485
+ "cloud_sync": cloud,
486
+ "report": row,
487
+ "message": (
488
+ "تم حفظ البلاغ وإرسال السؤال لإعادة التدقيق."
489
+ if reaudit.get("requested")
490
+ else "تم حفظ البلاغ."
491
+ ),
492
+ "version": self.version,
493
+ }
494
+
495
+ def create_report(self, report: Dict[str, Any]) -> Dict[str, Any]:
496
+ return self.report_question(report=report)
497
+
498
+ def save_report(self, report: Dict[str, Any]) -> Dict[str, Any]:
499
+ return self.report_question(report=report)
500
+
501
+ def submit_report(self, report: Dict[str, Any]) -> Dict[str, Any]:
502
+ return self.report_question(report=report)
503
+
504
+ # ======================================================
505
+ # الإدارة والمراجعة
506
+ # ======================================================
507
+
508
+ def list_reports(
509
+ self,
510
+ status: str = "",
511
+ grade: Optional[int] = None,
512
+ skill_id: str = "",
513
+ reason_id: str = "",
514
+ limit: int = 500,
515
+ refresh_cloud: bool = True,
516
+ ) -> Dict[str, Any]:
517
+ rows = self._materialize_reports(
518
+ self._read_events(refresh_cloud=refresh_cloud)
519
+ )
520
+
521
+ wanted_status = str(status or "").strip()
522
+ wanted_skill = str(skill_id or "").strip()
523
+ wanted_reason = str(reason_id or "").strip()
524
+
525
+ filtered: List[Dict[str, Any]] = []
526
+ for row in rows:
527
+ if wanted_status and str(
528
+ row.get("report_status") or ""
529
+ ) != wanted_status:
530
+ continue
531
+
532
+ if grade is not None:
533
+ try:
534
+ if int(row.get("grade")) != int(grade):
535
+ continue
536
+ except Exception:
537
+ continue
538
+
539
+ if wanted_skill and str(
540
+ row.get("skill_id") or ""
541
+ ) != wanted_skill:
542
+ continue
543
+
544
+ if wanted_reason and str(
545
+ row.get("reason_id") or ""
546
+ ) != wanted_reason:
547
+ continue
548
+
549
+ filtered.append(row)
550
+
551
+ try:
552
+ limit = max(1, min(int(limit), 5000))
553
+ except Exception:
554
+ limit = 500
555
+
556
+ filtered = filtered[-limit:]
557
+
558
+ return {
559
+ "success": True,
560
+ "count": len(filtered),
561
+ "reports": filtered,
562
+ "file": str(self.reports_file),
563
+ "version": self.version,
564
+ }
565
+
566
+ def get_report(
567
+ self,
568
+ report_id: str,
569
+ refresh_cloud: bool = True,
570
+ ) -> Dict[str, Any]:
571
+ report_id = str(report_id or "").strip()
572
+ if not report_id:
573
+ return {
574
+ "success": False,
575
+ "message": "report_id مفقود.",
576
+ "version": self.version,
577
+ }
578
+
579
+ result = self.list_reports(
580
+ limit=5000,
581
+ refresh_cloud=refresh_cloud,
582
+ )
583
+ for row in result.get("reports", []):
584
+ if str(row.get("report_id") or "") == report_id:
585
+ return {
586
+ "success": True,
587
+ "report": row,
588
+ "version": self.version,
589
+ }
590
+
591
+ return {
592
+ "success": False,
593
+ "message": "البلاغ غير موجود.",
594
+ "report_id": report_id,
595
+ "version": self.version,
596
+ }
597
+
598
+ def set_report_status(
599
+ self,
600
+ report_id: str,
601
+ status: str,
602
+ review_note: str = "",
603
+ changed_by: str = "admin",
604
+ ) -> Dict[str, Any]:
605
+ report_id = str(report_id or "").strip()
606
+ status = str(status or "").strip().lower()
607
+
608
+ if status not in VALID_STATUSES:
609
+ return {
610
+ "success": False,
611
+ "message": f"حالة البلاغ غير صحيحة: {status}",
612
+ "valid_statuses": sorted(VALID_STATUSES),
613
+ "version": self.version,
614
+ }
615
+
616
+ current = self.get_report(
617
+ report_id=report_id,
618
+ refresh_cloud=True,
619
+ )
620
+ if not current.get("success"):
621
+ return current
622
+
623
+ old_status = str(
624
+ (current.get("report") or {}).get("report_status")
625
+ or "open"
626
+ )
627
+
628
+ event = {
629
+ "event_type": "question_report_status_changed",
630
+ "report_id": report_id,
631
+ "old_status": old_status,
632
+ "new_status": status,
633
+ "review_note": str(review_note or "").strip(),
634
+ "changed_by": str(changed_by or "admin").strip(),
635
+ "changed_at": self.now(),
636
+ "report_manager_version": self.version,
637
+ }
638
+
639
+ try:
640
+ cloud = self._append(event)
641
+ except Exception as exc:
642
+ return {
643
+ "success": False,
644
+ "message": f"تعذر تحديث حالة البلاغ: {exc}",
645
+ "version": self.version,
646
+ }
647
+
648
+ return {
649
+ "success": True,
650
+ "report_id": report_id,
651
+ "old_status": old_status,
652
+ "new_status": status,
653
+ "cloud_synced": bool(
654
+ isinstance(cloud, dict) and cloud.get("success")
655
+ ),
656
+ "message": "تم تحديث حالة البلاغ.",
657
+ "version": self.version,
658
+ }
659
+
660
+ # ======================================================
661
+ # إحصاءات وحالة
662
+ # ======================================================
663
+
664
+ def stats(
665
+ self,
666
+ refresh_cloud: bool = True,
667
+ ) -> Dict[str, Any]:
668
+ rows = self._materialize_reports(
669
+ self._read_events(refresh_cloud=refresh_cloud)
670
+ )
671
+ by_status: Dict[str, int] = {}
672
+ by_reason: Dict[str, int] = {}
673
+ by_grade: Dict[str, int] = {}
674
+
675
+ for row in rows:
676
+ status = str(
677
+ row.get("report_status") or "open"
678
+ )
679
+ reason = str(
680
+ row.get("reason_id") or "other"
681
+ )
682
+ grade = str(
683
+ row.get("grade")
684
+ if row.get("grade") is not None
685
+ else "unknown"
686
+ )
687
+
688
+ by_status[status] = by_status.get(status, 0) + 1
689
+ by_reason[reason] = by_reason.get(reason, 0) + 1
690
+ by_grade[grade] = by_grade.get(grade, 0) + 1
691
+
692
+ return {
693
+ "success": True,
694
+ "total": len(rows),
695
+ "by_status": by_status,
696
+ "by_reason": by_reason,
697
+ "by_grade": by_grade,
698
+ "file": str(self.reports_file),
699
+ "version": self.version,
700
+ }
701
+
702
+ def storage_status(self) -> Dict[str, Any]:
703
+ storage = self._storage_manager()
704
+ if storage is None:
705
+ return {
706
+ "success": False,
707
+ "ready": False,
708
+ "message": "StorageManager غير متاح.",
709
+ "version": self.version,
710
+ }
711
+
712
+ method = getattr(storage, "question_reports_storage_info", None)
713
+ if not callable(method):
714
+ return {
715
+ "success": False,
716
+ "ready": False,
717
+ "message": "StorageManager لا يعرض معلومات تخزين البلاغات.",
718
+ "version": self.version,
719
+ }
720
+
721
+ try:
722
+ result = method()
723
+ return {
724
+ "success": bool(result.get("success")),
725
+ "ready": bool(result.get("success")),
726
+ "storage": result,
727
+ "version": self.version,
728
+ }
729
+ except Exception as exc:
730
+ return {
731
+ "success": False,
732
+ "ready": False,
733
+ "message": str(exc),
734
+ "version": self.version,
735
+ }
736
+
737
+ def status(self) -> Dict[str, Any]:
738
+ return {
739
+ "success": True,
740
+ "ready": True,
741
+ "version": self.version,
742
+ "reports_file": str(self.reports_file),
743
+ "valid_statuses": sorted(VALID_STATUSES),
744
+ "valid_reason_ids": sorted(VALID_REASON_IDS),
745
+ "uses_gpu": False,
746
+ "loads_models": False,
747
+ "reaudit_bridge": "ai_task_queue_manager",
748
+ "storage_bridge": "storage_manager",
749
+ }
750
+
751
+ def summary(self) -> Dict[str, Any]:
752
+ data = self.status()
753
+ data["storage"] = self.storage_status()
754
+ return data
755
+
756
+
757
+ _MANAGER: Optional[QuestionReportManager] = None
758
+
759
+
760
+ def get_manager() -> QuestionReportManager:
761
+ global _MANAGER
762
+ if _MANAGER is None:
763
+ _MANAGER = QuestionReportManager()
764
+ return _MANAGER
765
+
766
+
767
+ def report_question(*args: Any, **kwargs: Any) -> Dict[str, Any]:
768
+ return get_manager().report_question(*args, **kwargs)
769
+
770
+
771
+ def list_reports(*args: Any, **kwargs: Any) -> Dict[str, Any]:
772
+ return get_manager().list_reports(*args, **kwargs)
773
+
774
+
775
+ def get_report(*args: Any, **kwargs: Any) -> Dict[str, Any]:
776
+ return get_manager().get_report(*args, **kwargs)
777
+
778
+
779
+ def set_report_status(*args: Any, **kwargs: Any) -> Dict[str, Any]:
780
+ return get_manager().set_report_status(*args, **kwargs)
781
+
782
+
783
+ def stats(*args: Any, **kwargs: Any) -> Dict[str, Any]:
784
+ return get_manager().stats(*args, **kwargs)
785
+
786
+
787
+ def sync_from_storage(*args: Any, **kwargs: Any) -> Dict[str, Any]:
788
+ return get_manager().sync_from_storage(*args, **kwargs)
789
+
790
+
791
+ def sync_to_storage(*args: Any, **kwargs: Any) -> Dict[str, Any]:
792
+ return get_manager().sync_to_storage(*args, **kwargs)
793
+
794
+
795
+ def status() -> Dict[str, Any]:
796
+ return get_manager().status()
797
+
798
+
799
+ def summary() -> Dict[str, Any]:
800
+ return get_manager().summary()
question_support_manager.py ADDED
@@ -0,0 +1,732 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ مدير قواعد تدقيق ودعم أسئلة Divid Teacher.
6
+
7
+ لا يحمل نموذجًا ولا يستخدم GPU.
8
+ AITaskQueueManager يستعمله لبناء طلبات:
9
+ - question_support_generator
10
+ - question_support_reviewer
11
+ ثم لفحص العقود واتخاذ قرار الاعتماد النهائي.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import re
18
+ from copy import deepcopy
19
+ from typing import Any, Dict, List, Optional
20
+
21
+
22
+ VERSION = "question_support_manager_v4_grade_aware_two_phase_quality"
23
+ GENERATOR_ROLE = "question_support_generator"
24
+ REVIEWER_ROLE = "question_support_reviewer"
25
+ DEFAULT_REVIEW_THRESHOLD = 92
26
+
27
+ GENERATOR_VERDICTS = {"valid", "needs_fix", "rejected"}
28
+ REVIEWER_VERDICTS = {"approved", "revise", "rejected"}
29
+
30
+ HARD_FLAGS = {
31
+ "wrong_answer",
32
+ "multiple_correct_answers",
33
+ "no_correct_option",
34
+ "skill_mismatch",
35
+ "grade_mismatch",
36
+ "ambiguous_question",
37
+ "answer_leakage",
38
+ "unsafe_or_invalid_content",
39
+ "broken_symbol_or_required_visual",
40
+ }
41
+
42
+ GRADE_LABELS = {
43
+ 0: "الروضة",
44
+ 1: "الصف الأول",
45
+ 2: "الصف الثاني",
46
+ 3: "الصف الثالث",
47
+ 4: "الصف الرابع",
48
+ 5: "الصف الخامس",
49
+ 6: "الصف السادس",
50
+ 7: "الصف السابع",
51
+ 8: "الصف الثامن",
52
+ 9: "الصف التاسع",
53
+ 10: "الصف العاشر",
54
+ 11: "الصف الحادي عشر",
55
+ 12: "الصف الثاني عشر",
56
+ }
57
+
58
+
59
+ class QuestionSupportManager:
60
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
61
+ del args, kwargs
62
+ self.version = VERSION
63
+
64
+ def safe_int(self, value: Any, default: int = -1) -> int:
65
+ try:
66
+ text = str(value or "").translate(
67
+ str.maketrans("٠١٢٣٤٥٦٧٨٩", "0123456789")
68
+ )
69
+ return int(float(text))
70
+ except Exception:
71
+ return int(default)
72
+
73
+ def json_safe(self, value: Any) -> Any:
74
+ if value is None or isinstance(value, (str, int, float, bool)):
75
+ return value
76
+ if isinstance(value, dict):
77
+ return {
78
+ str(key): self.json_safe(item)
79
+ for key, item in value.items()
80
+ }
81
+ if isinstance(value, (list, tuple, set)):
82
+ return [self.json_safe(item) for item in value]
83
+ return str(value)
84
+
85
+ def grade_label(self, grade: Any) -> str:
86
+ number = self.safe_int(grade, -1)
87
+ return GRADE_LABELS.get(number, f"الصف {grade}")
88
+
89
+ def grade_profile(self, grade: Any) -> Dict[str, Any]:
90
+ number = self.safe_int(grade, -1)
91
+
92
+ if number == 0:
93
+ return {
94
+ "grade": 0,
95
+ "label": "الروضة",
96
+ "language_level": "شديد البساطة",
97
+ "instruction_style": "تعليمة واحدة قصيرة ومباشرة",
98
+ "reading_load": "منخفض جدًا",
99
+ }
100
+ if 1 <= number <= 3:
101
+ return {
102
+ "grade": number,
103
+ "label": self.grade_label(number),
104
+ "language_level": "بسيط جدًا",
105
+ "instruction_style": "جمل قصيرة ومطلوب واحد واضح",
106
+ "reading_load": "منخفض",
107
+ }
108
+ if 4 <= number <= 6:
109
+ return {
110
+ "grade": number,
111
+ "label": self.grade_label(number),
112
+ "language_level": "مدرسي واضح",
113
+ "instruction_style": "صياغة مباشرة دون حشو",
114
+ "reading_load": "منخفض إلى متوسط",
115
+ }
116
+ if 7 <= number <= 9:
117
+ return {
118
+ "grade": number,
119
+ "label": self.grade_label(number),
120
+ "language_level": "متوسط مناسب للمراهقين",
121
+ "instruction_style": "واضح وغير طفولي",
122
+ "reading_load": "متوسط",
123
+ }
124
+
125
+ return {
126
+ "grade": number,
127
+ "label": self.grade_label(number),
128
+ "language_level": "أكاديمي مبسط",
129
+ "instruction_style": "دقيق مع المحافظة على المعنى الرياضي",
130
+ "reading_load": "متوسط",
131
+ }
132
+
133
+ def _source_record(self, item: Any) -> Dict[str, Any]:
134
+ if not isinstance(item, dict):
135
+ return {}
136
+
137
+ source_record = item.get("source_record")
138
+ if isinstance(source_record, dict):
139
+ return deepcopy(source_record)
140
+
141
+ raw_item = item.get("raw_item")
142
+ if isinstance(raw_item, dict):
143
+ nested = raw_item.get("source_record")
144
+ if isinstance(nested, dict):
145
+ return deepcopy(nested)
146
+ return deepcopy(raw_item)
147
+
148
+ return deepcopy(item)
149
+
150
+ def question_snapshot(self, item: Any) -> Dict[str, Any]:
151
+ item = item if isinstance(item, dict) else {}
152
+ record = self._source_record(item)
153
+
154
+ options = record.get("options") or record.get("choices") or []
155
+ if isinstance(options, dict):
156
+ options = list(options.values())
157
+ if not isinstance(options, list):
158
+ options = [options] if options not in (None, "") else []
159
+
160
+ grade = self.safe_int(
161
+ item.get("grade"),
162
+ self.safe_int(record.get("grade"), -1),
163
+ )
164
+
165
+ return {
166
+ "source_key": str(item.get("source_key") or ""),
167
+ "source_type": str(item.get("source_type") or ""),
168
+ "source_id": str(item.get("source_id") or ""),
169
+ "source_fingerprint": str(
170
+ item.get("source_fingerprint") or ""
171
+ ),
172
+ "grade": grade,
173
+ "grade_label": self.grade_label(grade),
174
+ "skill_id": str(
175
+ item.get("skill_id")
176
+ or record.get("skill_id")
177
+ or ""
178
+ ),
179
+ "item_type": str(
180
+ record.get("item_type")
181
+ or record.get("question_type")
182
+ or record.get("type")
183
+ or ""
184
+ ),
185
+ "prompt": str(
186
+ record.get("prompt")
187
+ or record.get("question")
188
+ or record.get("question_ar")
189
+ or record.get("text")
190
+ or ""
191
+ ).strip(),
192
+ "options": self.json_safe(options),
193
+ "answer": self.json_safe(
194
+ record.get("answer")
195
+ or record.get("correct_answer")
196
+ or record.get("expected_answer")
197
+ or ""
198
+ ),
199
+ "source_record": self.json_safe(record),
200
+ }
201
+
202
+ def safety_rules(self) -> Dict[str, Any]:
203
+ return {
204
+ "clarification": (
205
+ "إعادة صياغة المطلوب لغويًا فقط دون كشف الإجابة "
206
+ "أو العملية المقاسة أو استبعاد الخيارات."
207
+ ),
208
+ "hint_level_1": (
209
+ "توجيه الانتباه لما يجب ملاحظته فقط، بلا خطوة حل."
210
+ ),
211
+ "hint_level_2": (
212
+ "تذكير بالمفهوم أو الخاصية العامة دون تطبيقها "
213
+ "على أرقام السؤال."
214
+ ),
215
+ "hint_level_3": (
216
+ "اقتراح بداية استراتيجية عامة دون إكمال الحل "
217
+ "أو كشف الناتج."
218
+ ),
219
+ "glossary": (
220
+ "إذا كان تعريف المفهوم نفسه هو المطلوب قياسه "
221
+ "يجب إخفاء التعريف."
222
+ ),
223
+ }
224
+
225
+ # =========================================================
226
+ # المولد: تدقيق أول ثم دعم
227
+ # =========================================================
228
+
229
+ def build_generator_request(
230
+ self,
231
+ item: Dict[str, Any],
232
+ ) -> Dict[str, Any]:
233
+ snapshot = self.question_snapshot(item)
234
+ grade_profile = self.grade_profile(snapshot["grade"])
235
+
236
+ contract = {
237
+ "verdict": "valid | needs_fix | rejected",
238
+ "question_audit": {
239
+ "question_correct": True,
240
+ "answer_correct": True,
241
+ "skill_alignment": True,
242
+ "grade_alignment": True,
243
+ "item_type_valid": True,
244
+ "options_valid": True,
245
+ "single_correct_answer": True,
246
+ "bounds_valid": True,
247
+ "wording_clear": True,
248
+ "age_appropriate": True,
249
+ "translation_ok": True,
250
+ "symbols_or_visuals_ok": True,
251
+ },
252
+ "problems": [],
253
+ "recommended_fix": "",
254
+ "support": {
255
+ "clarification_ar": "",
256
+ "instruction_clarification_ar": "",
257
+ "hint_level_1_ar": "",
258
+ "hint_level_2_ar": "",
259
+ "hint_level_3_ar": "",
260
+ "concept_ids": [],
261
+ "symbol_ids": [],
262
+ },
263
+ "support_safety": {
264
+ "clarification_leaks_answer": False,
265
+ "hint_1_leaks_answer": False,
266
+ "hint_2_leaks_answer": False,
267
+ "hint_3_leaks_answer": False,
268
+ },
269
+ }
270
+
271
+ system_prompt = (
272
+ "أنت مدقق جودة أول لأسئلة تعليمية. "
273
+ "افحص السؤال والإجابة والخيارات والمهارة والصف واللغة أولًا. "
274
+ "إذا كان السؤال غير صالح فلا تولد أي توضيح أو تلميحات. "
275
+ "إذا كان صالحًا فقط ولّد توضيحًا محايدًا وثلاثة مستويات "
276
+ "تلميح لا تكشف الإجابة. أعد JSON فقط."
277
+ )
278
+
279
+ user_prompt = (
280
+ "مستوى الطالب:\n"
281
+ + json.dumps(grade_profile, ensure_ascii=False, indent=2)
282
+ + "\n\nقواعد الدعم:\n"
283
+ + json.dumps(self.safety_rules(), ensure_ascii=False, indent=2)
284
+ + "\n\nالعنصر:\n"
285
+ + json.dumps(snapshot, ensure_ascii=False, indent=2)
286
+ + "\n\nعقد JSON:\n"
287
+ + json.dumps(contract, ensure_ascii=False, indent=2)
288
+ + "\n\nإذا verdict ليست valid يجب أن تكون حقول الدعم النصية فارغة."
289
+ )
290
+
291
+ return {
292
+ "success": True,
293
+ "role": GENERATOR_ROLE,
294
+ "system_prompt": system_prompt,
295
+ "user_prompt": user_prompt,
296
+ "snapshot": snapshot,
297
+ "grade_profile": grade_profile,
298
+ "contract": contract,
299
+ "version": self.version,
300
+ }
301
+
302
+ # =========================================================
303
+ # المراجع المستقل
304
+ # =========================================================
305
+
306
+ def build_reviewer_request(
307
+ self,
308
+ intermediate: Dict[str, Any],
309
+ ) -> Dict[str, Any]:
310
+ intermediate = (
311
+ deepcopy(intermediate)
312
+ if isinstance(intermediate, dict)
313
+ else {}
314
+ )
315
+
316
+ snapshot = self.question_snapshot(
317
+ intermediate.get("raw_item") or {}
318
+ )
319
+ grade_profile = self.grade_profile(snapshot["grade"])
320
+
321
+ contract = {
322
+ "verdict": "approved | revise | rejected",
323
+ "scores": {
324
+ "question_correctness": 0,
325
+ "answer_correctness": 0,
326
+ "skill_alignment": 0,
327
+ "grade_alignment": 0,
328
+ "clarity": 0,
329
+ "options_quality": 0,
330
+ "support_safety": 0,
331
+ "age_appropriateness": 0,
332
+ },
333
+ "hard_flags": [],
334
+ "problems": [],
335
+ "review_notes": "",
336
+ "approved_support": {
337
+ "clarification_ar": "",
338
+ "instruction_clarification_ar": "",
339
+ "hint_level_1_ar": "",
340
+ "hint_level_2_ar": "",
341
+ "hint_level_3_ar": "",
342
+ "concept_ids": [],
343
+ "symbol_ids": [],
344
+ },
345
+ }
346
+
347
+ payload = {
348
+ "question_snapshot": snapshot,
349
+ "grade_profile": grade_profile,
350
+ "generator_result": (
351
+ intermediate.get("generator_result") or {}
352
+ ),
353
+ "generator_validation": (
354
+ intermediate.get("generator_validation") or {}
355
+ ),
356
+ }
357
+
358
+ system_prompt = (
359
+ "أنت المراجع النهائي المستقل لبنك الأسئلة. "
360
+ "لا تثق بقرار المدقق الأول. أعد فحص السؤال والإجابة "
361
+ "والخيارات والمهارة والصف والوضوح، ثم افحص التوضيح "
362
+ "والتلميحات للتأكد من عدم كشف الإجابة. أعد JSON فقط."
363
+ )
364
+
365
+ user_prompt = (
366
+ "الحزمة:\n"
367
+ + json.dumps(payload, ensure_ascii=False, indent=2)
368
+ + "\n\nعقد JSON:\n"
369
+ + json.dumps(contract, ensure_ascii=False, indent=2)
370
+ + "\n\nكل درجة من 0 إلى 100. "
371
+ "وجود hard flag جوهري يمنع الاعتماد."
372
+ )
373
+
374
+ return {
375
+ "success": True,
376
+ "role": REVIEWER_ROLE,
377
+ "system_prompt": system_prompt,
378
+ "user_prompt": user_prompt,
379
+ "snapshot": snapshot,
380
+ "contract": contract,
381
+ "version": self.version,
382
+ }
383
+
384
+ # =========================================================
385
+ # قراءة JSON
386
+ # =========================================================
387
+
388
+ def parse_json_output(self, value: Any) -> Dict[str, Any]:
389
+ if isinstance(value, dict):
390
+ if isinstance(value.get("text"), str):
391
+ parsed = self._parse_json_text(value["text"])
392
+ if parsed:
393
+ return parsed
394
+
395
+ if (
396
+ "verdict" in value
397
+ or "question_audit" in value
398
+ or "scores" in value
399
+ ):
400
+ return deepcopy(value)
401
+
402
+ for key in ("result", "output", "data"):
403
+ nested = value.get(key)
404
+ if isinstance(nested, dict) and "verdict" in nested:
405
+ return deepcopy(nested)
406
+ if isinstance(nested, str):
407
+ parsed = self._parse_json_text(nested)
408
+ if parsed:
409
+ return parsed
410
+ return {}
411
+
412
+ if isinstance(value, str):
413
+ return self._parse_json_text(value)
414
+
415
+ return {}
416
+
417
+ def _parse_json_text(self, value: Any) -> Dict[str, Any]:
418
+ text = str(value or "").strip()
419
+ if not text:
420
+ return {}
421
+
422
+ text = re.sub(
423
+ r"^```(?:json)?\s*",
424
+ "",
425
+ text,
426
+ count=1,
427
+ flags=re.IGNORECASE,
428
+ )
429
+ text = re.sub(r"\s*```$", "", text, count=1)
430
+
431
+ try:
432
+ data = json.loads(text)
433
+ if isinstance(data, dict):
434
+ return data
435
+ except Exception:
436
+ pass
437
+
438
+ start = text.find("{")
439
+ end = text.rfind("}")
440
+ if start >= 0 and end > start:
441
+ try:
442
+ data = json.loads(text[start:end + 1])
443
+ if isinstance(data, dict):
444
+ return data
445
+ except Exception:
446
+ pass
447
+
448
+ return {}
449
+
450
+ # =========================================================
451
+ # تحقق التدقيق الأول
452
+ # =========================================================
453
+
454
+ def validate_generator_output(
455
+ self,
456
+ item: Dict[str, Any],
457
+ output: Dict[str, Any],
458
+ ) -> Dict[str, Any]:
459
+ problems: List[str] = []
460
+
461
+ if not isinstance(output, dict) or not output:
462
+ return {
463
+ "success": False,
464
+ "verdict": "invalid_output",
465
+ "problems": ["خرج المولد ليس JSON صالحًا."],
466
+ "version": self.version,
467
+ }
468
+
469
+ verdict = str(output.get("verdict") or "").strip().lower()
470
+ if verdict not in GENERATOR_VERDICTS:
471
+ problems.append("verdict غير صالح.")
472
+
473
+ audit = output.get("question_audit")
474
+ if not isinstance(audit, dict):
475
+ audit = {}
476
+ problems.append("question_audit مفقود.")
477
+
478
+ audit_keys = (
479
+ "question_correct",
480
+ "answer_correct",
481
+ "skill_alignment",
482
+ "grade_alignment",
483
+ "item_type_valid",
484
+ "options_valid",
485
+ "single_correct_answer",
486
+ "bounds_valid",
487
+ "wording_clear",
488
+ "age_appropriate",
489
+ "translation_ok",
490
+ "symbols_or_visuals_ok",
491
+ )
492
+
493
+ for key in audit_keys:
494
+ if key not in audit:
495
+ problems.append(f"question_audit.{key} مفقود.")
496
+
497
+ support = output.get("support")
498
+ if not isinstance(support, dict):
499
+ support = {}
500
+
501
+ safety = output.get("support_safety")
502
+ if not isinstance(safety, dict):
503
+ safety = {}
504
+
505
+ support_text_keys = (
506
+ "clarification_ar",
507
+ "instruction_clarification_ar",
508
+ "hint_level_1_ar",
509
+ "hint_level_2_ar",
510
+ "hint_level_3_ar",
511
+ )
512
+
513
+ if verdict == "valid":
514
+ failed = [
515
+ key
516
+ for key in audit_keys
517
+ if audit.get(key) is not True
518
+ ]
519
+ if failed:
520
+ problems.append(
521
+ "السؤال معلن valid مع فحوص فاشلة: "
522
+ + ", ".join(failed)
523
+ )
524
+
525
+ for key in support_text_keys:
526
+ if not str(support.get(key) or "").strip():
527
+ problems.append(f"support.{key} فارغ.")
528
+
529
+ leakage_keys = (
530
+ "clarification_leaks_answer",
531
+ "hint_1_leaks_answer",
532
+ "hint_2_leaks_answer",
533
+ "hint_3_leaks_answer",
534
+ )
535
+ for key in leakage_keys:
536
+ if safety.get(key) is not False:
537
+ problems.append(
538
+ f"support_safety.{key} يجب أن يكون false."
539
+ )
540
+ else:
541
+ leaked = [
542
+ key
543
+ for key in support_text_keys
544
+ if str(support.get(key) or "").strip()
545
+ ]
546
+ if leaked:
547
+ problems.append(
548
+ "تم توليد دعم لسؤال غير صالح: "
549
+ + ", ".join(leaked)
550
+ )
551
+
552
+ snapshot = self.question_snapshot(item)
553
+ if not snapshot.get("prompt"):
554
+ problems.append("السؤال الخام لا يحتوي نصًا.")
555
+
556
+ return {
557
+ "success": not problems,
558
+ "verdict": verdict,
559
+ "problems": problems,
560
+ "normalized": self.json_safe(output),
561
+ "source_key": snapshot.get("source_key", ""),
562
+ "grade": snapshot.get("grade", -1),
563
+ "skill_id": snapshot.get("skill_id", ""),
564
+ "version": self.version,
565
+ }
566
+
567
+ # =========================================================
568
+ # قرار المراجع
569
+ # =========================================================
570
+
571
+ def decide_review(
572
+ self,
573
+ reviewer_output: Dict[str, Any],
574
+ threshold: int = DEFAULT_REVIEW_THRESHOLD,
575
+ ) -> Dict[str, Any]:
576
+ if not isinstance(reviewer_output, dict):
577
+ return {
578
+ "approved": False,
579
+ "status": "rejected",
580
+ "score": 0.0,
581
+ "hard_flags": ["invalid_reviewer_output"],
582
+ "version": self.version,
583
+ }
584
+
585
+ verdict = str(
586
+ reviewer_output.get("verdict") or ""
587
+ ).strip().lower()
588
+
589
+ scores = reviewer_output.get("scores")
590
+ if not isinstance(scores, dict):
591
+ scores = {}
592
+
593
+ score_names = (
594
+ "question_correctness",
595
+ "answer_correctness",
596
+ "skill_alignment",
597
+ "grade_alignment",
598
+ "clarity",
599
+ "options_quality",
600
+ "support_safety",
601
+ "age_appropriateness",
602
+ )
603
+
604
+ normalized_scores = {}
605
+ for key in score_names:
606
+ try:
607
+ value = float(scores.get(key, 0))
608
+ except Exception:
609
+ value = 0.0
610
+ normalized_scores[key] = max(0.0, min(100.0, value))
611
+
612
+ average = sum(normalized_scores.values()) / len(score_names)
613
+
614
+ raw_flags = reviewer_output.get("hard_flags") or []
615
+ if not isinstance(raw_flags, list):
616
+ raw_flags = [raw_flags]
617
+
618
+ hard_flags = [
619
+ str(flag).strip()
620
+ for flag in raw_flags
621
+ if str(flag).strip()
622
+ ]
623
+ blocking_flags = [
624
+ flag for flag in hard_flags if flag in HARD_FLAGS
625
+ ]
626
+
627
+ threshold = max(
628
+ 1,
629
+ min(100, self.safe_int(threshold, DEFAULT_REVIEW_THRESHOLD)),
630
+ )
631
+
632
+ approved = bool(
633
+ verdict == "approved"
634
+ and average >= threshold
635
+ and not blocking_flags
636
+ )
637
+
638
+ if approved:
639
+ status = "approved"
640
+ elif verdict == "revise" or (
641
+ verdict == "approved" and blocking_flags
642
+ ):
643
+ status = "needs_revision"
644
+ else:
645
+ status = "rejected"
646
+
647
+ return {
648
+ "approved": approved,
649
+ "status": status,
650
+ "score": round(average, 2),
651
+ "threshold": threshold,
652
+ "reviewer_verdict": verdict,
653
+ "scores": normalized_scores,
654
+ "hard_flags": hard_flags,
655
+ "blocking_flags": blocking_flags,
656
+ "problems": self.json_safe(
657
+ reviewer_output.get("problems") or []
658
+ ),
659
+ "review_notes": str(
660
+ reviewer_output.get("review_notes") or ""
661
+ ).strip(),
662
+ "approved_support": self.json_safe(
663
+ reviewer_output.get("approved_support") or {}
664
+ ),
665
+ "version": self.version,
666
+ }
667
+
668
+ def status(self) -> Dict[str, Any]:
669
+ return {
670
+ "success": True,
671
+ "ready": True,
672
+ "version": self.version,
673
+ "generator_role": GENERATOR_ROLE,
674
+ "reviewer_role": REVIEWER_ROLE,
675
+ "review_threshold": DEFAULT_REVIEW_THRESHOLD,
676
+ "uses_gpu": False,
677
+ "loads_models": False,
678
+ "manages_memory": False,
679
+ "manages_queue": False,
680
+ }
681
+
682
+ def summary(self) -> Dict[str, Any]:
683
+ return self.status()
684
+
685
+
686
+ _MANAGER: Optional[QuestionSupportManager] = None
687
+
688
+
689
+ def get_manager() -> QuestionSupportManager:
690
+ global _MANAGER
691
+ if _MANAGER is None:
692
+ _MANAGER = QuestionSupportManager()
693
+ return _MANAGER
694
+
695
+
696
+ def build_generator_request(item: Dict[str, Any]) -> Dict[str, Any]:
697
+ return get_manager().build_generator_request(item)
698
+
699
+
700
+ def build_reviewer_request(
701
+ intermediate: Dict[str, Any],
702
+ ) -> Dict[str, Any]:
703
+ return get_manager().build_reviewer_request(intermediate)
704
+
705
+
706
+ def parse_json_output(value: Any) -> Dict[str, Any]:
707
+ return get_manager().parse_json_output(value)
708
+
709
+
710
+ def validate_generator_output(
711
+ item: Dict[str, Any],
712
+ output: Dict[str, Any],
713
+ ) -> Dict[str, Any]:
714
+ return get_manager().validate_generator_output(item, output)
715
+
716
+
717
+ def decide_review(
718
+ reviewer_output: Dict[str, Any],
719
+ threshold: int = DEFAULT_REVIEW_THRESHOLD,
720
+ ) -> Dict[str, Any]:
721
+ return get_manager().decide_review(
722
+ reviewer_output,
723
+ threshold=threshold,
724
+ )
725
+
726
+
727
+ def status() -> Dict[str, Any]:
728
+ return get_manager().status()
729
+
730
+
731
+ def summary() -> Dict[str, Any]:
732
+ return get_manager().summary()
session_manager.py CHANGED
@@ -28,7 +28,7 @@ class SessionManager:
28
  """
29
 
30
  def __init__(self, *args, **kwargs):
31
- self.version = "session_manager_v18_explicit_current_question_contract"
32
 
33
  self.ai_mode = os.getenv("AI_MODE", "auto").strip().lower()
34
 
@@ -47,6 +47,13 @@ class SessionManager:
47
  self.last_ai_lesson_state = {}
48
  self.last_queue_result = {}
49
 
 
 
 
 
 
 
 
50
  self.last_phi_output_preview = ""
51
  self.last_qwen_output_preview = ""
52
  self.last_local_fallback_reason = ""
@@ -716,6 +723,802 @@ class SessionManager:
716
  "version": self.version,
717
  }
718
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
719
  # =========================================================
720
  # بدء فحص الوسام
721
  # =========================================================
@@ -2601,10 +3404,30 @@ class SessionManager:
2601
  "arabic_conversation": "arabic_conversation_asr",
2602
  "english": "english_asr",
2603
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2604
  "cache_owner": "model_memory_manager",
2605
  "message": (
2606
- "SessionManager يقود الجلسة وتحويل كلام الطالب، "
2607
- "وModelMemoryManager وحده يمسح الذاكرة والكاش."
 
2608
  ),
2609
  }
2610
 
@@ -2645,6 +3468,50 @@ def start_student_session(*args, **kwargs):
2645
  return get_manager().start_student_session(*args, **kwargs)
2646
 
2647
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2648
  def get_badge_roadmap(*args, **kwargs):
2649
  return get_manager().get_badge_roadmap(*args, **kwargs)
2650
 
 
28
  """
29
 
30
  def __init__(self, *args, **kwargs):
31
+ self.version = "session_manager_v20_question_report_bridge"
32
 
33
  self.ai_mode = os.getenv("AI_MODE", "auto").strip().lower()
34
 
 
47
  self.last_ai_lesson_state = {}
48
  self.last_queue_result = {}
49
 
50
+ # مسار تدقيق بنك الأسئلة:
51
+ # SessionManager يحتفظ فقط بآخر طلب/نتيجة للواجهة.
52
+ # AITaskQueueManager هو صاحب المهمة والتقدم والتنفيذ الطويل.
53
+ self.last_question_quality_scan = {}
54
+ self.last_question_quality_task = {}
55
+ self.last_question_quality_progress = {}
56
+
57
  self.last_phi_output_preview = ""
58
  self.last_qwen_output_preview = ""
59
  self.last_local_fallback_reason = ""
 
723
  "version": self.version,
724
  }
725
 
726
+ # =========================================================
727
+ # بلاغات أسئلة الوسام
728
+ # =========================================================
729
+
730
+ def get_question_report_reasons(self):
731
+ if self.badge_game_manager is None:
732
+ return {
733
+ "success": False,
734
+ "reasons": [],
735
+ "message": "BadgeGameManager غير جاهز.",
736
+ "session_manager_version": self.version,
737
+ }
738
+
739
+ method = getattr(
740
+ self.badge_game_manager,
741
+ "question_report_reasons",
742
+ None,
743
+ )
744
+ if not callable(method):
745
+ return {
746
+ "success": False,
747
+ "reasons": [],
748
+ "message": "BadgeGameManager لا يدعم أسباب البلاغ.",
749
+ "session_manager_version": self.version,
750
+ }
751
+
752
+ try:
753
+ reasons = method()
754
+ except Exception as exc:
755
+ return {
756
+ "success": False,
757
+ "reasons": [],
758
+ "message": str(exc),
759
+ "traceback": traceback.format_exc(),
760
+ "session_manager_version": self.version,
761
+ }
762
+
763
+ return {
764
+ "success": True,
765
+ "reasons": reasons if isinstance(reasons, list) else [],
766
+ "session_manager_version": self.version,
767
+ }
768
+
769
+ def report_badge_question(
770
+ self,
771
+ game_state=None,
772
+ reason="other",
773
+ note="",
774
+ identity="student",
775
+ ):
776
+ """
777
+ جسر الواجهة لزر «الإبلاغ عن السؤال».
778
+
779
+ لا يسجل إجابة ولا يحكم على الطالب.
780
+ BadgeGameManager يحفظ البلاغ ويستبدل السؤال.
781
+ """
782
+ trace = self.trace_new()
783
+ self.trace_add(
784
+ trace,
785
+ "question_report",
786
+ "start",
787
+ "إرسال بلاغ عن السؤال الحالي.",
788
+ )
789
+
790
+ if self.badge_game_manager is None:
791
+ return self.fail(
792
+ trace,
793
+ "question_report",
794
+ "BadgeGameManager غير جاهز.",
795
+ {"init_errors": self.init_errors},
796
+ )
797
+
798
+ if game_state is None:
799
+ game_state = self.last_badge_state
800
+
801
+ if not isinstance(game_state, dict):
802
+ return self.fail(
803
+ trace,
804
+ "question_report",
805
+ "حالة الوسام غير صالحة.",
806
+ )
807
+
808
+ # نحافظ على هوية الطالب الموجودة في الحالة،
809
+ # وإن كانت فارغة نمرر الهوية الحالية.
810
+ if not str(game_state.get("identity") or "").strip():
811
+ game_state["identity"] = self.normalize_identity(identity)
812
+
813
+ method = getattr(
814
+ self.badge_game_manager,
815
+ "report_current_question",
816
+ None,
817
+ )
818
+ if not callable(method):
819
+ return self.fail(
820
+ trace,
821
+ "question_report",
822
+ "BadgeGameManager لا يدعم الإبلاغ عن السؤال.",
823
+ )
824
+
825
+ try:
826
+ result = method(
827
+ state=game_state,
828
+ reason=reason,
829
+ note=note,
830
+ )
831
+ except Exception as exc:
832
+ return self.fail(
833
+ trace,
834
+ "question_report",
835
+ f"فشل إرسال البلاغ: {exc}",
836
+ {"traceback": traceback.format_exc()},
837
+ )
838
+
839
+ if not isinstance(result, dict):
840
+ return self.fail(
841
+ trace,
842
+ "question_report",
843
+ "رجعت نتيجة غير صالحة من BadgeGameManager.",
844
+ {"result": str(result)},
845
+ )
846
+
847
+ state = (
848
+ result.get("state")
849
+ or result.get("game_state")
850
+ or game_state
851
+ )
852
+ if isinstance(state, dict):
853
+ self.last_badge_state = state
854
+ result["state"] = state
855
+ result["game_state"] = state
856
+
857
+ self.trace_add(
858
+ trace,
859
+ "question_report",
860
+ "ok" if result.get("report_saved") else "failed",
861
+ result.get(
862
+ "message",
863
+ "تمت معالجة بلاغ السؤال.",
864
+ ),
865
+ {
866
+ "report_saved": result.get("report_saved", False),
867
+ "replacement_found": result.get(
868
+ "replacement_found",
869
+ False,
870
+ ),
871
+ "counts_as_attempt": result.get(
872
+ "counts_as_attempt",
873
+ False,
874
+ ),
875
+ "counts_as_wrong": result.get(
876
+ "counts_as_wrong",
877
+ False,
878
+ ),
879
+ "opens_learning_gap": result.get(
880
+ "opens_learning_gap",
881
+ False,
882
+ ),
883
+ },
884
+ )
885
+
886
+ result["debug_trace"] = trace
887
+ result["session_manager_version"] = self.version
888
+ result["report_route"] = (
889
+ "SessionManager -> BadgeGameManager "
890
+ "-> QuestionReportManager"
891
+ )
892
+ return result
893
+
894
+ # =========================================================
895
+ # تدقيق بنك الأسئلة - أوامر فقط
896
+ # =========================================================
897
+
898
+ def _question_quality_queue(self):
899
+ """
900
+ يعيد AITaskQueueManager لمسار الجودة.
901
+
902
+ لا يحمل AIManager ولا ModelMemoryManager هنا.
903
+ """
904
+ queue = self.get_queue_manager()
905
+
906
+ if isinstance(queue, dict) and queue.get("error"):
907
+ return None, {
908
+ "success": False,
909
+ "message": (
910
+ "تعذر تحميل AITaskQueueManager: "
911
+ + str(queue.get("error") or "")
912
+ ),
913
+ "manager_error": queue,
914
+ "session_manager_version": self.version,
915
+ }
916
+
917
+ if queue is None:
918
+ return None, {
919
+ "success": False,
920
+ "message": "AITaskQueueManager غير متاح.",
921
+ "session_manager_version": self.version,
922
+ }
923
+
924
+ return queue, None
925
+
926
+ def scan_question_bank_quality(
927
+ self,
928
+ source_files=None,
929
+ ):
930
+ """
931
+ Scan فقط.
932
+
933
+ لا ينشئ مهمة، ولا يحمل نموذجًا، ولا يبدأ تدقيقًا.
934
+ يعيد الصفوف التي تحتوي عناصر جديدة/متغيرة/معاد طلب تدقيقها.
935
+ """
936
+ trace = self.trace_new()
937
+ self.trace_add(
938
+ trace,
939
+ "question_quality_scan",
940
+ "start",
941
+ "طلب فحص بنك الأسئلة دون تشغيل أي نموذج.",
942
+ )
943
+
944
+ queue, error = self._question_quality_queue()
945
+ if error:
946
+ return self.fail(
947
+ trace,
948
+ "question_quality_scan",
949
+ error.get("message", "AITaskQueueManager غير متاح."),
950
+ error,
951
+ )
952
+
953
+ method = getattr(
954
+ queue,
955
+ "scan_question_bank_for_audit",
956
+ None,
957
+ )
958
+ if not callable(method):
959
+ return self.fail(
960
+ trace,
961
+ "question_quality_scan",
962
+ "AITaskQueueManager لا يدعم فحص بنك الأسئلة.",
963
+ )
964
+
965
+ try:
966
+ if source_files:
967
+ result = method(source_files=source_files)
968
+ else:
969
+ result = method()
970
+ except TypeError:
971
+ # توافق مع نسخة لا تستقبل source_files.
972
+ result = method()
973
+ except Exception as exc:
974
+ return self.fail(
975
+ trace,
976
+ "question_quality_scan",
977
+ f"فشل فحص بنك الأسئلة: {exc}",
978
+ {"traceback": traceback.format_exc()},
979
+ )
980
+
981
+ if not isinstance(result, dict):
982
+ return self.fail(
983
+ trace,
984
+ "question_quality_scan",
985
+ "رجع AITaskQueueManager نتيجة Scan غير صالحة.",
986
+ {"result": str(result)},
987
+ )
988
+
989
+ self.last_question_quality_scan = result
990
+
991
+ if not result.get("success"):
992
+ return self.fail(
993
+ trace,
994
+ "question_quality_scan",
995
+ result.get("message", "فشل فحص البنك."),
996
+ result,
997
+ )
998
+
999
+ self.trace_add(
1000
+ trace,
1001
+ "question_quality_scan",
1002
+ "ok",
1003
+ "اكتمل فحص البنك. لم يتم تشغيل أي نموذج.",
1004
+ {
1005
+ "scan_id": result.get("scan_id", ""),
1006
+ "grade_options": result.get("grade_options", []),
1007
+ "totals": result.get("totals", {}),
1008
+ },
1009
+ )
1010
+
1011
+ result["debug_trace"] = trace
1012
+ result["session_manager_version"] = self.version
1013
+ result["execution_owner"] = "ai_task_queue_manager"
1014
+ result["models_started"] = False
1015
+ return result
1016
+
1017
+ def get_latest_question_bank_quality_scan(self):
1018
+ queue, error = self._question_quality_queue()
1019
+ if error:
1020
+ return error
1021
+
1022
+ method = getattr(
1023
+ queue,
1024
+ "latest_question_bank_scan",
1025
+ None,
1026
+ )
1027
+ if not callable(method):
1028
+ return {
1029
+ "success": False,
1030
+ "message": "AITaskQueueManager لا يدعم قراءة آخر Scan.",
1031
+ "session_manager_version": self.version,
1032
+ }
1033
+
1034
+ try:
1035
+ result = method()
1036
+ except Exception as exc:
1037
+ return {
1038
+ "success": False,
1039
+ "message": str(exc),
1040
+ "traceback": traceback.format_exc(),
1041
+ "session_manager_version": self.version,
1042
+ }
1043
+
1044
+ if isinstance(result, dict) and result:
1045
+ self.last_question_quality_scan = result
1046
+ result["session_manager_version"] = self.version
1047
+ return result
1048
+
1049
+ return {
1050
+ "success": False,
1051
+ "message": "لا يوجد Scan محفوظ بعد.",
1052
+ "session_manager_version": self.version,
1053
+ }
1054
+
1055
+ def create_or_resume_question_bank_quality_task(
1056
+ self,
1057
+ grade,
1058
+ scan_id="",
1059
+ requested_by="admin",
1060
+ ):
1061
+ """
1062
+ ينشئ Snapshot ثابتًا لصف واحد أو يعيد المهمة غير المنتهية.
1063
+
1064
+ هذه الدالة لا تشغل النموذج.
1065
+ """
1066
+ trace = self.trace_new()
1067
+ self.trace_add(
1068
+ trace,
1069
+ "question_quality_task",
1070
+ "start",
1071
+ f"طلب إنشاء/استئناف مهمة تدقيق للصف: {grade}.",
1072
+ )
1073
+
1074
+ queue, error = self._question_quality_queue()
1075
+ if error:
1076
+ return self.fail(
1077
+ trace,
1078
+ "question_quality_task",
1079
+ error.get("message", "AITaskQueueManager غير متاح."),
1080
+ error,
1081
+ )
1082
+
1083
+ method = getattr(
1084
+ queue,
1085
+ "create_or_resume_question_quality_task",
1086
+ None,
1087
+ )
1088
+ if not callable(method):
1089
+ return self.fail(
1090
+ trace,
1091
+ "question_quality_task",
1092
+ "AITaskQueueManager لا يدعم إنشاء مهمة جودة البنك.",
1093
+ )
1094
+
1095
+ try:
1096
+ result = method(
1097
+ grade=grade,
1098
+ scan_id=str(scan_id or ""),
1099
+ requested_by=str(requested_by or "admin"),
1100
+ )
1101
+ except TypeError:
1102
+ result = method(
1103
+ grade=grade,
1104
+ scan_id=str(scan_id or ""),
1105
+ )
1106
+ except Exception as exc:
1107
+ return self.fail(
1108
+ trace,
1109
+ "question_quality_task",
1110
+ f"فشل إنشاء/استئناف مهمة التدقيق: {exc}",
1111
+ {"traceback": traceback.format_exc()},
1112
+ )
1113
+
1114
+ if not isinstance(result, dict):
1115
+ return self.fail(
1116
+ trace,
1117
+ "question_quality_task",
1118
+ "رجع AITaskQueueManager نتيجة غير صالحة.",
1119
+ {"result": str(result)},
1120
+ )
1121
+
1122
+ if not result.get("success"):
1123
+ return self.fail(
1124
+ trace,
1125
+ "question_quality_task",
1126
+ result.get("message", "فشل إنشاء مهمة التدقيق."),
1127
+ result,
1128
+ )
1129
+
1130
+ task = result.get("task") or {}
1131
+ if isinstance(task, dict) and task:
1132
+ self.last_question_quality_task = task
1133
+ try:
1134
+ progress_method = getattr(
1135
+ queue,
1136
+ "question_quality_progress",
1137
+ None,
1138
+ )
1139
+ if callable(progress_method):
1140
+ progress = progress_method(task)
1141
+ if isinstance(progress, dict):
1142
+ self.last_question_quality_progress = progress
1143
+ except Exception:
1144
+ pass
1145
+
1146
+ self.trace_add(
1147
+ trace,
1148
+ "question_quality_task",
1149
+ "ok",
1150
+ result.get(
1151
+ "message",
1152
+ "تم إنشاء أو استئناف مهمة تدقيق البنك.",
1153
+ ),
1154
+ {
1155
+ "task_id": result.get("task_id", ""),
1156
+ "snapshot_count": result.get("snapshot_count", 0),
1157
+ "existing": result.get("existing", False),
1158
+ "nothing_to_audit": result.get("nothing_to_audit", False),
1159
+ },
1160
+ )
1161
+
1162
+ result["debug_trace"] = trace
1163
+ result["session_manager_version"] = self.version
1164
+ result["execution_owner"] = "ai_task_queue_manager"
1165
+ result["session_executes_items"] = False
1166
+ return result
1167
+
1168
+ def run_question_bank_quality_task(
1169
+ self,
1170
+ task_id,
1171
+ max_items=0,
1172
+ max_retries=2,
1173
+ ):
1174
+ """
1175
+ يعطي أمر التنفيذ لـ AITaskQueueManager.
1176
+
1177
+ SessionManager لا يستدعي المولد أو المراجع ولا يحمّل/يفرغ نموذجًا.
1178
+ """
1179
+ trace = self.trace_new()
1180
+ self.trace_add(
1181
+ trace,
1182
+ "question_quality_run",
1183
+ "start",
1184
+ f"إرسال أمر تنفيذ المهمة: {task_id}.",
1185
+ )
1186
+
1187
+ queue, error = self._question_quality_queue()
1188
+ if error:
1189
+ return self.fail(
1190
+ trace,
1191
+ "question_quality_run",
1192
+ error.get("message", "AITaskQueueManager غير متاح."),
1193
+ error,
1194
+ )
1195
+
1196
+ method = getattr(
1197
+ queue,
1198
+ "run_question_quality_task",
1199
+ None,
1200
+ )
1201
+ if not callable(method):
1202
+ return self.fail(
1203
+ trace,
1204
+ "question_quality_run",
1205
+ "AITaskQueueManager لا يحتوي منفذ مهمة تدقيق البنك.",
1206
+ )
1207
+
1208
+ try:
1209
+ result = method(
1210
+ task_id=str(task_id or ""),
1211
+ max_items=max_items,
1212
+ max_retries=max_retries,
1213
+ )
1214
+ except Exception as exc:
1215
+ return self.fail(
1216
+ trace,
1217
+ "question_quality_run",
1218
+ f"فشل تنفيذ مهمة تدقيق البنك: {exc}",
1219
+ {"traceback": traceback.format_exc()},
1220
+ )
1221
+
1222
+ if not isinstance(result, dict):
1223
+ result = {
1224
+ "success": False,
1225
+ "message": str(result),
1226
+ }
1227
+
1228
+ task = result.get("task") or {}
1229
+ progress = result.get("progress") or {}
1230
+
1231
+ if isinstance(task, dict) and task:
1232
+ self.last_question_quality_task = task
1233
+
1234
+ if isinstance(progress, dict) and progress:
1235
+ self.last_question_quality_progress = progress
1236
+
1237
+ self.trace_add(
1238
+ trace,
1239
+ "question_quality_run",
1240
+ "ok" if result.get("success") else (
1241
+ "paused" if result.get("paused") else "failed"
1242
+ ),
1243
+ result.get(
1244
+ "message",
1245
+ "عاد AITaskQueueManager بنتيجة التنفيذ.",
1246
+ ),
1247
+ {
1248
+ "task_id": str(task_id or ""),
1249
+ "completed": result.get("completed", False),
1250
+ "paused": result.get("paused", False),
1251
+ "phase": result.get("phase")
1252
+ or (task.get("phase") if isinstance(task, dict) else ""),
1253
+ },
1254
+ )
1255
+
1256
+ result["debug_trace"] = trace
1257
+ result["session_manager_version"] = self.version
1258
+ result["execution_owner"] = "ai_task_queue_manager"
1259
+ result["memory_owner"] = "model_memory_manager"
1260
+ return result
1261
+
1262
+ def start_question_bank_quality_audit(
1263
+ self,
1264
+ grade,
1265
+ scan_id="",
1266
+ requested_by="admin",
1267
+ run_now=True,
1268
+ max_items=0,
1269
+ max_retries=2,
1270
+ ):
1271
+ """
1272
+ أمر واجهة واحد لزر «ابدأ / استأنف التدقيق».
1273
+
1274
+ 1) ينشئ/يستأنف Snapshot الصف.
1275
+ 2) إذا run_now=True يسلّم task_id إلى AITaskQueueManager للتنفيذ.
1276
+ """
1277
+ task_result = self.create_or_resume_question_bank_quality_task(
1278
+ grade=grade,
1279
+ scan_id=scan_id,
1280
+ requested_by=requested_by,
1281
+ )
1282
+
1283
+ if not isinstance(task_result, dict) or not task_result.get("success"):
1284
+ return task_result
1285
+
1286
+ if task_result.get("nothing_to_audit"):
1287
+ return task_result
1288
+
1289
+ task_id = str(
1290
+ task_result.get("task_id")
1291
+ or (task_result.get("task") or {}).get("task_id")
1292
+ or ""
1293
+ ).strip()
1294
+
1295
+ if not task_id:
1296
+ task_result["success"] = False
1297
+ task_result["message"] = (
1298
+ "تم تجهيز الصف لكن لم يرجع task_id صالحًا."
1299
+ )
1300
+ return task_result
1301
+
1302
+ if not run_now:
1303
+ task_result["started"] = False
1304
+ task_result["message"] = (
1305
+ str(task_result.get("message") or "")
1306
+ + " المهمة جاهزة ولم يبدأ التنفيذ بعد."
1307
+ ).strip()
1308
+ return task_result
1309
+
1310
+ run_result = self.run_question_bank_quality_task(
1311
+ task_id=task_id,
1312
+ max_items=max_items,
1313
+ max_retries=max_retries,
1314
+ )
1315
+
1316
+ if not isinstance(run_result, dict):
1317
+ return {
1318
+ "success": False,
1319
+ "task_id": task_id,
1320
+ "message": "نتيجة التنفيذ غير صالحة.",
1321
+ "session_manager_version": self.version,
1322
+ }
1323
+
1324
+ run_result.setdefault("task_id", task_id)
1325
+ run_result["task_creation"] = task_result
1326
+ return run_result
1327
+
1328
+ def get_question_bank_quality_status(self, task_id):
1329
+ queue, error = self._question_quality_queue()
1330
+ if error:
1331
+ return error
1332
+
1333
+ task_method = getattr(
1334
+ queue,
1335
+ "get_question_quality_task",
1336
+ None,
1337
+ )
1338
+ progress_method = getattr(
1339
+ queue,
1340
+ "question_quality_progress",
1341
+ None,
1342
+ )
1343
+
1344
+ if not callable(task_method) or not callable(progress_method):
1345
+ return {
1346
+ "success": False,
1347
+ "message": (
1348
+ "AITaskQueueManager لا يدعم قراءة حالة مهمة الجودة."
1349
+ ),
1350
+ "session_manager_version": self.version,
1351
+ }
1352
+
1353
+ try:
1354
+ task = task_method(str(task_id or ""))
1355
+ progress = progress_method(
1356
+ task if isinstance(task, dict) and task else str(task_id or "")
1357
+ )
1358
+ except Exception as exc:
1359
+ return {
1360
+ "success": False,
1361
+ "message": str(exc),
1362
+ "traceback": traceback.format_exc(),
1363
+ "session_manager_version": self.version,
1364
+ }
1365
+
1366
+ if not isinstance(task, dict) or not task:
1367
+ return {
1368
+ "success": False,
1369
+ "message": "مهمة التدقيق غير موجودة.",
1370
+ "task_id": str(task_id or ""),
1371
+ "session_manager_version": self.version,
1372
+ }
1373
+
1374
+ self.last_question_quality_task = task
1375
+ if isinstance(progress, dict):
1376
+ self.last_question_quality_progress = progress
1377
+
1378
+ return {
1379
+ "success": True,
1380
+ "task_id": task.get("task_id", ""),
1381
+ "task": task,
1382
+ "progress": progress,
1383
+ "execution_owner": "ai_task_queue_manager",
1384
+ "memory_owner": "model_memory_manager",
1385
+ "session_manager_version": self.version,
1386
+ }
1387
+
1388
+ def list_question_bank_quality_tasks(
1389
+ self,
1390
+ statuses=None,
1391
+ grade=None,
1392
+ ):
1393
+ queue, error = self._question_quality_queue()
1394
+ if error:
1395
+ return error
1396
+
1397
+ method = getattr(
1398
+ queue,
1399
+ "list_question_quality_tasks",
1400
+ None,
1401
+ )
1402
+ if not callable(method):
1403
+ return {
1404
+ "success": False,
1405
+ "message": "AITaskQueueManager لا يدعم عرض مهام الجودة.",
1406
+ "session_manager_version": self.version,
1407
+ }
1408
+
1409
+ try:
1410
+ tasks = method(
1411
+ statuses=statuses,
1412
+ grade=grade,
1413
+ )
1414
+ except TypeError:
1415
+ tasks = method()
1416
+ except Exception as exc:
1417
+ return {
1418
+ "success": False,
1419
+ "message": str(exc),
1420
+ "traceback": traceback.format_exc(),
1421
+ "session_manager_version": self.version,
1422
+ }
1423
+
1424
+ if not isinstance(tasks, list):
1425
+ tasks = []
1426
+
1427
+ return {
1428
+ "success": True,
1429
+ "count": len(tasks),
1430
+ "tasks": tasks,
1431
+ "session_manager_version": self.version,
1432
+ }
1433
+
1434
+ def pause_question_bank_quality_task(
1435
+ self,
1436
+ task_id,
1437
+ reason="admin_pause",
1438
+ ):
1439
+ queue, error = self._question_quality_queue()
1440
+ if error:
1441
+ return error
1442
+
1443
+ method = getattr(
1444
+ queue,
1445
+ "pause_question_quality_task",
1446
+ None,
1447
+ )
1448
+ if not callable(method):
1449
+ return {
1450
+ "success": False,
1451
+ "message": "AITaskQueueManager لا يدعم إيقاف المهمة.",
1452
+ "session_manager_version": self.version,
1453
+ }
1454
+
1455
+ try:
1456
+ result = method(
1457
+ task_id=str(task_id or ""),
1458
+ reason=str(reason or "admin_pause"),
1459
+ )
1460
+ except Exception as exc:
1461
+ return {
1462
+ "success": False,
1463
+ "message": str(exc),
1464
+ "traceback": traceback.format_exc(),
1465
+ "session_manager_version": self.version,
1466
+ }
1467
+
1468
+ if isinstance(result, dict):
1469
+ result["session_manager_version"] = self.version
1470
+ result["execution_owner"] = "ai_task_queue_manager"
1471
+ return result
1472
+
1473
+ def resume_question_bank_quality_task(
1474
+ self,
1475
+ task_id,
1476
+ run_now=True,
1477
+ max_items=0,
1478
+ max_retries=2,
1479
+ ):
1480
+ queue, error = self._question_quality_queue()
1481
+ if error:
1482
+ return error
1483
+
1484
+ method = getattr(
1485
+ queue,
1486
+ "resume_question_quality_task",
1487
+ None,
1488
+ )
1489
+ if not callable(method):
1490
+ return {
1491
+ "success": False,
1492
+ "message": "AITaskQueueManager لا يدعم استئناف المهمة.",
1493
+ "session_manager_version": self.version,
1494
+ }
1495
+
1496
+ try:
1497
+ result = method(task_id=str(task_id or ""))
1498
+ except Exception as exc:
1499
+ return {
1500
+ "success": False,
1501
+ "message": str(exc),
1502
+ "traceback": traceback.format_exc(),
1503
+ "session_manager_version": self.version,
1504
+ }
1505
+
1506
+ if not isinstance(result, dict) or not result.get("success"):
1507
+ if isinstance(result, dict):
1508
+ result["session_manager_version"] = self.version
1509
+ return result
1510
+
1511
+ if result.get("completed") or not run_now:
1512
+ result["session_manager_version"] = self.version
1513
+ result["execution_owner"] = "ai_task_queue_manager"
1514
+ return result
1515
+
1516
+ return self.run_question_bank_quality_task(
1517
+ task_id=task_id,
1518
+ max_items=max_items,
1519
+ max_retries=max_retries,
1520
+ )
1521
+
1522
  # =========================================================
1523
  # بدء فحص الوسام
1524
  # =========================================================
 
3404
  "arabic_conversation": "arabic_conversation_asr",
3405
  "english": "english_asr",
3406
  },
3407
+ "question_quality_orchestration": {
3408
+ "scan_owner": "ai_task_queue_manager",
3409
+ "task_owner": "ai_task_queue_manager",
3410
+ "execution_owner": "ai_task_queue_manager",
3411
+ "memory_owner": "model_memory_manager",
3412
+ "model_execution_owner": "ai_manager",
3413
+ "session_role": "command_and_status_only",
3414
+ "last_scan_id": (
3415
+ self.last_question_quality_scan.get("scan_id", "")
3416
+ if isinstance(self.last_question_quality_scan, dict)
3417
+ else ""
3418
+ ),
3419
+ "last_task_id": (
3420
+ self.last_question_quality_task.get("task_id", "")
3421
+ if isinstance(self.last_question_quality_task, dict)
3422
+ else ""
3423
+ ),
3424
+ "last_progress": self.last_question_quality_progress,
3425
+ },
3426
  "cache_owner": "model_memory_manager",
3427
  "message": (
3428
+ "SessionManager يوزع الأوامر ويتابع الحالة. "
3429
+ "مسار تدقيق البنك ينفذه AITaskQueueManager، "
3430
+ "وModelMemoryManager وحده يدير تنظيف الذاكرة والكاش."
3431
  ),
3432
  }
3433
 
 
3468
  return get_manager().start_student_session(*args, **kwargs)
3469
 
3470
 
3471
+ def get_question_report_reasons(*args, **kwargs):
3472
+ return get_manager().get_question_report_reasons(*args, **kwargs)
3473
+
3474
+
3475
+ def report_badge_question(*args, **kwargs):
3476
+ return get_manager().report_badge_question(*args, **kwargs)
3477
+
3478
+
3479
+ def scan_question_bank_quality(*args, **kwargs):
3480
+ return get_manager().scan_question_bank_quality(*args, **kwargs)
3481
+
3482
+
3483
+ def get_latest_question_bank_quality_scan(*args, **kwargs):
3484
+ return get_manager().get_latest_question_bank_quality_scan(*args, **kwargs)
3485
+
3486
+
3487
+ def create_or_resume_question_bank_quality_task(*args, **kwargs):
3488
+ return get_manager().create_or_resume_question_bank_quality_task(*args, **kwargs)
3489
+
3490
+
3491
+ def start_question_bank_quality_audit(*args, **kwargs):
3492
+ return get_manager().start_question_bank_quality_audit(*args, **kwargs)
3493
+
3494
+
3495
+ def run_question_bank_quality_task(*args, **kwargs):
3496
+ return get_manager().run_question_bank_quality_task(*args, **kwargs)
3497
+
3498
+
3499
+ def get_question_bank_quality_status(*args, **kwargs):
3500
+ return get_manager().get_question_bank_quality_status(*args, **kwargs)
3501
+
3502
+
3503
+ def list_question_bank_quality_tasks(*args, **kwargs):
3504
+ return get_manager().list_question_bank_quality_tasks(*args, **kwargs)
3505
+
3506
+
3507
+ def pause_question_bank_quality_task(*args, **kwargs):
3508
+ return get_manager().pause_question_bank_quality_task(*args, **kwargs)
3509
+
3510
+
3511
+ def resume_question_bank_quality_task(*args, **kwargs):
3512
+ return get_manager().resume_question_bank_quality_task(*args, **kwargs)
3513
+
3514
+
3515
  def get_badge_roadmap(*args, **kwargs):
3516
  return get_manager().get_badge_roadmap(*args, **kwargs)
3517
 
storage_manager-2.py ADDED
@@ -0,0 +1,2188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # storage_manager.py
2
+ #!/usr/bin/env python3
3
+ # -*- coding: utf-8 -*-
4
+
5
+ """
6
+ storage_manager.py
7
+ مدير التخزين الرسمي في منصة Divid Teacher.
8
+
9
+ v3:
10
+ - يحافظ على وظائف التخزين القديمة.
11
+ - يدعم مكتبة الحصص العلاجية المشتركة.
12
+ - يدعم تكليف الطالب بحصة علاجية.
13
+ - لا يعتبر الحصة المشتركة جاهزة إلا إذا كان الفيديو محفوظًا فعلًا.
14
+ - يتجاهل الحزم القديمة الفاشلة التي فيها cloud_files فارغة أو video failed.
15
+ """
16
+
17
+ import os
18
+ import json
19
+ import hashlib
20
+ import traceback
21
+ from pathlib import Path
22
+ from datetime import datetime
23
+
24
+ from huggingface_hub import (
25
+ HfApi,
26
+ hf_hub_download,
27
+ snapshot_download,
28
+ upload_file as hf_upload_file,
29
+ upload_folder as hf_upload_folder,
30
+ )
31
+
32
+ from config import (
33
+ HF_TOKEN,
34
+ AIOCR_KEY,
35
+ STUDENT_REPO,
36
+ TEACHER_REPO,
37
+ SYSTEM_REPO,
38
+ MODELS_REPO,
39
+ DATA_FOLDER,
40
+ MODELS_FOLDER,
41
+ STUDENTS_FOLDER,
42
+ TEACHERS_FOLDER,
43
+ SYSTEM_FOLDER,
44
+ CACHE_FOLDER,
45
+ REMEDIAL_LIBRARY_ROOT,
46
+ STUDENT_ASSIGNMENTS_ROOT,
47
+ GAMES_INDEX_PATH,
48
+ GAMES_REPO_KEY,
49
+ STRATEGIES_REPO_KEY,
50
+ GENERAL_STRATEGIES_PATH,
51
+ DEFAULT_LEARNING_MODE,
52
+ REMEDIAL_DEFAULT_INTERVENTION,
53
+ REMEDIAL_CONTENT_VERSION,
54
+ )
55
+
56
+
57
+ class StorageManager:
58
+
59
+ def __init__(self):
60
+ self.version = "storage_manager_v5_admin_repositories_question_reports"
61
+
62
+ self.token = (HF_TOKEN or AIOCR_KEY or "").strip()
63
+ self.aiocr_key = AIOCR_KEY
64
+
65
+ self.api = HfApi(token=self.token if self.token else None)
66
+
67
+ self.repositories = {
68
+ "students": {
69
+ "repo_id": STUDENT_REPO,
70
+ "repo_type": "dataset",
71
+ "local_folder": STUDENTS_FOLDER,
72
+ },
73
+ "teachers": {
74
+ "repo_id": TEACHER_REPO,
75
+ "repo_type": "dataset",
76
+ "local_folder": TEACHERS_FOLDER,
77
+ },
78
+ "system": {
79
+ "repo_id": SYSTEM_REPO,
80
+ "repo_type": "dataset",
81
+ "local_folder": SYSTEM_FOLDER,
82
+ },
83
+ "models": {
84
+ "repo_id": MODELS_REPO,
85
+ "repo_type": "model",
86
+ "local_folder": MODELS_FOLDER,
87
+ },
88
+ }
89
+
90
+ self.remedial_library_root = REMEDIAL_LIBRARY_ROOT
91
+ self.student_assignments_root = STUDENT_ASSIGNMENTS_ROOT
92
+
93
+ self.games_repo_key = GAMES_REPO_KEY
94
+ self.games_index_path = GAMES_INDEX_PATH
95
+
96
+ self.strategies_repo_key = STRATEGIES_REPO_KEY
97
+ self.general_strategies_path = GENERAL_STRATEGIES_PATH
98
+
99
+ # بلاغات جودة الأسئلة تحفظ مركزيًا في خزنة النظام افتراضيًا.
100
+ # يمكن تغيير المستودع والمسار من Secrets/Variables دون تعديل الكود.
101
+ self.question_reports_repo_key = (
102
+ os.getenv("QUESTION_REPORTS_REPO_KEY", "system").strip()
103
+ or "system"
104
+ )
105
+ self.question_reports_path = (
106
+ os.getenv(
107
+ "QUESTION_REPORTS_REPO_PATH",
108
+ "quality/question_reports.jsonl",
109
+ ).strip()
110
+ or "quality/question_reports.jsonl"
111
+ )
112
+
113
+ self.ensure_local_folders()
114
+
115
+ # ======================================================
116
+ # أدوات عامة
117
+ # ======================================================
118
+
119
+ def now(self):
120
+ return datetime.utcnow().isoformat()
121
+
122
+ def ensure_local_folders(self):
123
+ folders = [
124
+ DATA_FOLDER,
125
+ MODELS_FOLDER,
126
+ STUDENTS_FOLDER,
127
+ TEACHERS_FOLDER,
128
+ SYSTEM_FOLDER,
129
+ CACHE_FOLDER,
130
+ ]
131
+
132
+ for folder in folders:
133
+ Path(folder).mkdir(parents=True, exist_ok=True)
134
+
135
+ Path(os.path.join(CACHE_FOLDER, "remedial_packages")).mkdir(
136
+ parents=True,
137
+ exist_ok=True,
138
+ )
139
+ Path(os.path.join(CACHE_FOLDER, "question_reports")).mkdir(
140
+ parents=True,
141
+ exist_ok=True,
142
+ )
143
+
144
+ return True
145
+
146
+ def safe_int(self, value, default=0):
147
+ try:
148
+ text = str(value or "").strip()
149
+ text = text.translate(str.maketrans("٠١٢٣٤٥٦٧٨٩", "0123456789"))
150
+ return int(float(text))
151
+ except Exception:
152
+ return default
153
+
154
+ def normalize_identity(self, identity):
155
+ text = str(identity or "").strip().replace(" ", "_")
156
+ return self.clean_name(text or "student", "student")
157
+
158
+ def normalize_subject(self, subject):
159
+ text = str(subject or "").strip().lower()
160
+
161
+ if text in ["رياضيات", "math", "mathematics", "رياضيات أساسية"]:
162
+ return "math"
163
+
164
+ if text in ["عربي", "لغة عربية", "arabic"]:
165
+ return "arabic"
166
+
167
+ if text in ["انجليزي", "english", "لغة انجليزية", "لغة إنجليزية"]:
168
+ return "english"
169
+
170
+ if text in ["علوم", "science"]:
171
+ return "science"
172
+
173
+ return self.clean_name(text or "math", "math")
174
+
175
+ def clean_name(self, value, default="item"):
176
+ text = str(value or default).strip().replace(" ", "_")
177
+
178
+ allowed = []
179
+ for ch in text:
180
+ if ch.isalnum() or ch in [
181
+ "_",
182
+ "-",
183
+ ".",
184
+ "ء",
185
+ "آ",
186
+ "أ",
187
+ "إ",
188
+ "ؤ",
189
+ "ئ",
190
+ "ى",
191
+ "ة",
192
+ ]:
193
+ allowed.append(ch)
194
+ elif "\u0600" <= ch <= "\u06FF":
195
+ allowed.append(ch)
196
+ else:
197
+ allowed.append("_")
198
+
199
+ text = "".join(allowed).strip("_")
200
+ while "__" in text:
201
+ text = text.replace("__", "_")
202
+
203
+ return text or default
204
+
205
+ def json_safe(self, value):
206
+ try:
207
+ json.dumps(value, ensure_ascii=False)
208
+ return value
209
+ except Exception:
210
+ if isinstance(value, dict):
211
+ return {str(k): self.json_safe(v) for k, v in value.items()}
212
+ if isinstance(value, list):
213
+ return [self.json_safe(x) for x in value]
214
+ if isinstance(value, tuple):
215
+ return [self.json_safe(x) for x in value]
216
+ return str(value)
217
+
218
+ def short_hash(self, value, length=10):
219
+ text = json.dumps(
220
+ self.json_safe(value),
221
+ ensure_ascii=False,
222
+ sort_keys=True,
223
+ )
224
+ return hashlib.sha1(text.encode("utf-8")).hexdigest()[:length]
225
+
226
+ def grade_folder(self, grade):
227
+ grade = self.safe_int(grade, 1)
228
+ return f"grade_{grade:02d}"
229
+
230
+ def grade_band_name(self, grade):
231
+ grade = self.safe_int(grade, 1)
232
+
233
+ if grade <= 3:
234
+ return "early_primary"
235
+ if grade <= 6:
236
+ return "upper_primary"
237
+ if grade <= 9:
238
+ return "middle_school"
239
+ return "high_school"
240
+
241
+ def detect_voice_locale(self, task=None, gap_report=None, student=None):
242
+ task = task if isinstance(task, dict) else {}
243
+ gap_report = gap_report if isinstance(gap_report, dict) else {}
244
+ student = student if isinstance(student, dict) else {}
245
+
246
+ value = (
247
+ student.get("voice_locale")
248
+ or student.get("locale")
249
+ or student.get("country_locale")
250
+ or task.get("voice_locale")
251
+ or gap_report.get("voice_locale")
252
+ or "ar-JO"
253
+ )
254
+
255
+ return self.clean_name(value, "ar-JO")
256
+
257
+ def detect_media_mode(self, media=None, task=None, lesson=None):
258
+ media = media if isinstance(media, dict) else {}
259
+ task = task if isinstance(task, dict) else {}
260
+ lesson = lesson if isinstance(lesson, dict) else {}
261
+
262
+ value = (
263
+ media.get("mode")
264
+ or task.get("media_mode")
265
+ or lesson.get("media_mode")
266
+ or "hybrid_auto"
267
+ )
268
+
269
+ return self.clean_name(value, "hybrid_auto")
270
+
271
+
272
+ # ======================================================
273
+ # إعدادات الألعاب والاستراتيجيات
274
+ # ======================================================
275
+
276
+ def load_games_index(self, default=None):
277
+ if default is None:
278
+ default = {
279
+ "version": "games_index_v1",
280
+ "games": [],
281
+ }
282
+
283
+ data = self.download_json_optional(
284
+ repo_key=self.games_repo_key,
285
+ filename=self.games_index_path,
286
+ default=default,
287
+ )
288
+
289
+ if isinstance(data, list):
290
+ data = {
291
+ "version": "games_index_legacy_list",
292
+ "games": data,
293
+ }
294
+
295
+ if not isinstance(data, dict):
296
+ return default
297
+
298
+ games = data.get("games")
299
+ if not isinstance(games, list):
300
+ for key in ("items", "data", "results"):
301
+ if isinstance(data.get(key), list):
302
+ data["games"] = data[key]
303
+ break
304
+
305
+ if not isinstance(data.get("games"), list):
306
+ data["games"] = []
307
+
308
+ return data
309
+
310
+ def save_games_index(self, data):
311
+ data = data if isinstance(data, dict) else {
312
+ "version": "games_index_v1",
313
+ "games": [],
314
+ }
315
+
316
+ data["updated_at"] = self.now()
317
+
318
+ return self.upload_json_optional(
319
+ repo_key=self.games_repo_key,
320
+ data=data,
321
+ path_in_repo=self.games_index_path,
322
+ local_name="games_index.json",
323
+ commit_message="Update interactive games index",
324
+ )
325
+
326
+ def load_general_strategies(self, default=None):
327
+ if default is None:
328
+ default = {}
329
+
330
+ return self.download_json_optional(
331
+ repo_key=self.strategies_repo_key,
332
+ filename=self.general_strategies_path,
333
+ default=default,
334
+ )
335
+
336
+ def save_general_strategies(self, data):
337
+ data = data if isinstance(data, dict) else {}
338
+ data["updated_at"] = self.now()
339
+
340
+ return self.upload_json_optional(
341
+ repo_key=self.strategies_repo_key,
342
+ data=data,
343
+ path_in_repo=self.general_strategies_path,
344
+ local_name="general_strategies.json",
345
+ commit_message="Update general teaching strategies",
346
+ )
347
+
348
+ # ======================================================
349
+ # فحص الاتصال
350
+ # ======================================================
351
+
352
+ def test_connection(self):
353
+ if not self.token:
354
+ return {
355
+ "connected": False,
356
+ "success": False,
357
+ "message": "HF_TOKEN غير موجود في Secrets",
358
+ "version": self.version,
359
+ }
360
+
361
+ try:
362
+ user = self.api.whoami()
363
+ return {
364
+ "connected": True,
365
+ "success": True,
366
+ "message": "تم الاتصال بنجاح",
367
+ "user": user.get("name", ""),
368
+ "version": self.version,
369
+ }
370
+
371
+ except Exception as e:
372
+ return {
373
+ "connected": False,
374
+ "success": False,
375
+ "message": str(e),
376
+ "version": self.version,
377
+ }
378
+
379
+ # ======================================================
380
+ # بيانات المستودعات
381
+ # ======================================================
382
+
383
+ def get_repo(self, repo_key):
384
+ if repo_key not in self.repositories:
385
+ raise ValueError(f"Unknown repository key: {repo_key}")
386
+
387
+ return self.repositories[repo_key]
388
+
389
+ def list_repositories(self):
390
+ return self.repositories
391
+
392
+ def list_repository_files(
393
+ self,
394
+ repo_key,
395
+ prefix="",
396
+ limit=500,
397
+ ):
398
+ """
399
+ يعرض ملفات مستودع واحد لاستخدام مكتب الإدارة.
400
+ لا يغيّر ولا يحذف أي ملف.
401
+ """
402
+ try:
403
+ repo = self.get_repo(repo_key)
404
+ files = self.api.list_repo_files(
405
+ repo_id=repo["repo_id"],
406
+ repo_type=repo["repo_type"],
407
+ token=self.token if self.token else None,
408
+ )
409
+ prefix = str(prefix or "").strip().lstrip("/")
410
+ if prefix:
411
+ files = [
412
+ name for name in files
413
+ if str(name).startswith(prefix)
414
+ ]
415
+
416
+ try:
417
+ limit = max(1, min(int(limit), 5000))
418
+ except Exception:
419
+ limit = 500
420
+
421
+ total = len(files)
422
+ visible = files[:limit]
423
+
424
+ return {
425
+ "success": True,
426
+ "repo_key": repo_key,
427
+ "repo_id": repo["repo_id"],
428
+ "repo_type": repo["repo_type"],
429
+ "prefix": prefix,
430
+ "count": total,
431
+ "returned": len(visible),
432
+ "files": visible,
433
+ "truncated": total > len(visible),
434
+ "version": self.version,
435
+ }
436
+ except Exception as e:
437
+ return {
438
+ "success": False,
439
+ "repo_key": repo_key,
440
+ "prefix": str(prefix or ""),
441
+ "count": 0,
442
+ "files": [],
443
+ "message": str(e),
444
+ "traceback": traceback.format_exc(),
445
+ "version": self.version,
446
+ }
447
+
448
+ def repository_overview(self, include_file_counts=True):
449
+ """
450
+ لقطة آمنة للمستودعات الأربعة لمكتب الإدارة.
451
+ """
452
+ rows = []
453
+
454
+ for repo_key, repo in self.repositories.items():
455
+ row = {
456
+ "repo_key": repo_key,
457
+ "repo_id": repo.get("repo_id", ""),
458
+ "repo_type": repo.get("repo_type", ""),
459
+ "local_folder": repo.get("local_folder", ""),
460
+ "reachable": None,
461
+ "files_count": None,
462
+ "message": "",
463
+ }
464
+
465
+ if include_file_counts:
466
+ check = self.list_repository_files(
467
+ repo_key=repo_key,
468
+ prefix="",
469
+ limit=1,
470
+ )
471
+ row["reachable"] = bool(check.get("success"))
472
+ row["files_count"] = check.get("count")
473
+ row["message"] = check.get("message", "")
474
+ rows.append(row)
475
+
476
+ return {
477
+ "success": True,
478
+ "repositories": rows,
479
+ "has_token": bool(self.token),
480
+ "question_reports_repo_key": self.question_reports_repo_key,
481
+ "question_reports_path": self.question_reports_path,
482
+ "version": self.version,
483
+ }
484
+
485
+ def download_repository_file_for_admin(
486
+ self,
487
+ repo_key,
488
+ filename,
489
+ ):
490
+ """
491
+ تنزيل ملف محدد إلى كاش الإدارة دون تعديل المستودع.
492
+ """
493
+ filename = str(filename or "").strip().lstrip("/")
494
+ if not filename:
495
+ return {
496
+ "success": False,
497
+ "message": "أدخل مسار الملف داخل المستودع.",
498
+ "version": self.version,
499
+ }
500
+
501
+ local_dir = os.path.join(
502
+ CACHE_FOLDER,
503
+ "admin_repository_files",
504
+ self.clean_name(repo_key, "repo"),
505
+ )
506
+ try:
507
+ path = self.download_file(
508
+ repo_key=repo_key,
509
+ filename=filename,
510
+ local_dir=local_dir,
511
+ )
512
+ return {
513
+ "success": True,
514
+ "repo_key": repo_key,
515
+ "filename": filename,
516
+ "local_path": path,
517
+ "version": self.version,
518
+ }
519
+ except Exception as e:
520
+ return {
521
+ "success": False,
522
+ "repo_key": repo_key,
523
+ "filename": filename,
524
+ "message": str(e),
525
+ "version": self.version,
526
+ }
527
+
528
+ # ======================================================
529
+ # تنزيل ملف واحد
530
+ # ======================================================
531
+
532
+ def download_file(
533
+ self,
534
+ repo_key,
535
+ filename,
536
+ local_dir=None,
537
+ ):
538
+ repo = self.get_repo(repo_key)
539
+
540
+ if local_dir is None:
541
+ local_dir = repo["local_folder"]
542
+
543
+ Path(local_dir).mkdir(parents=True, exist_ok=True)
544
+
545
+ file_path = hf_hub_download(
546
+ repo_id=repo["repo_id"],
547
+ repo_type=repo["repo_type"],
548
+ filename=filename,
549
+ local_dir=local_dir,
550
+ token=self.token if self.token else None,
551
+ )
552
+
553
+ return file_path
554
+
555
+ def download_file_optional(
556
+ self,
557
+ repo_key,
558
+ filename,
559
+ local_dir=None,
560
+ ):
561
+ try:
562
+ return self.download_file(
563
+ repo_key=repo_key,
564
+ filename=filename,
565
+ local_dir=local_dir,
566
+ )
567
+ except Exception:
568
+ return ""
569
+
570
+ # ======================================================
571
+ # تنزيل مستودع كامل
572
+ # ======================================================
573
+
574
+ def download_repository(
575
+ self,
576
+ repo_key,
577
+ local_dir=None,
578
+ ):
579
+ repo = self.get_repo(repo_key)
580
+
581
+ if local_dir is None:
582
+ local_dir = repo["local_folder"]
583
+
584
+ Path(local_dir).mkdir(parents=True, exist_ok=True)
585
+
586
+ folder_path = snapshot_download(
587
+ repo_id=repo["repo_id"],
588
+ repo_type=repo["repo_type"],
589
+ local_dir=local_dir,
590
+ token=self.token if self.token else None,
591
+ )
592
+
593
+ return folder_path
594
+
595
+ # ======================================================
596
+ # رفع ملف واحد
597
+ # ======================================================
598
+
599
+ def upload_file(
600
+ self,
601
+ repo_key,
602
+ local_path,
603
+ path_in_repo,
604
+ commit_message="Upload file",
605
+ ):
606
+ if not local_path or not os.path.exists(local_path):
607
+ return {
608
+ "success": False,
609
+ "uploaded": False,
610
+ "message": f"الملف المحلي غير موجود: {local_path}",
611
+ "path_in_repo": path_in_repo,
612
+ "version": self.version,
613
+ }
614
+
615
+ repo = self.get_repo(repo_key)
616
+
617
+ result = hf_upload_file(
618
+ path_or_fileobj=local_path,
619
+ path_in_repo=path_in_repo,
620
+ repo_id=repo["repo_id"],
621
+ repo_type=repo["repo_type"],
622
+ token=self.token if self.token else None,
623
+ commit_message=commit_message,
624
+ )
625
+
626
+ return {
627
+ "success": True,
628
+ "uploaded": True,
629
+ "repo_key": repo_key,
630
+ "repo_id": repo["repo_id"],
631
+ "repo_type": repo["repo_type"],
632
+ "local_path": local_path,
633
+ "path_in_repo": path_in_repo,
634
+ "raw_result": str(result),
635
+ "version": self.version,
636
+ }
637
+
638
+ def upload_file_optional(
639
+ self,
640
+ repo_key,
641
+ local_path,
642
+ path_in_repo,
643
+ commit_message="Upload file",
644
+ ):
645
+ try:
646
+ result = self.upload_file(
647
+ repo_key=repo_key,
648
+ local_path=local_path,
649
+ path_in_repo=path_in_repo,
650
+ commit_message=commit_message,
651
+ )
652
+ return result
653
+ except Exception as e:
654
+ return {
655
+ "success": False,
656
+ "uploaded": False,
657
+ "repo_key": repo_key,
658
+ "local_path": local_path,
659
+ "path_in_repo": path_in_repo,
660
+ "message": str(e),
661
+ "traceback": traceback.format_exc(),
662
+ "version": self.version,
663
+ }
664
+
665
+ # ======================================================
666
+ # رفع مجلد كامل
667
+ # ======================================================
668
+
669
+ def upload_folder(
670
+ self,
671
+ repo_key,
672
+ folder_path,
673
+ path_in_repo=None,
674
+ commit_message="Upload folder",
675
+ ):
676
+ if not folder_path or not os.path.isdir(folder_path):
677
+ return {
678
+ "success": False,
679
+ "uploaded": False,
680
+ "message": f"المجلد المحلي غير موجود: {folder_path}",
681
+ "path_in_repo": path_in_repo,
682
+ "version": self.version,
683
+ }
684
+
685
+ repo = self.get_repo(repo_key)
686
+
687
+ result = hf_upload_folder(
688
+ folder_path=folder_path,
689
+ repo_id=repo["repo_id"],
690
+ repo_type=repo["repo_type"],
691
+ path_in_repo=path_in_repo,
692
+ token=self.token if self.token else None,
693
+ commit_message=commit_message,
694
+ )
695
+
696
+ return {
697
+ "success": True,
698
+ "uploaded": True,
699
+ "repo_key": repo_key,
700
+ "repo_id": repo["repo_id"],
701
+ "repo_type": repo["repo_type"],
702
+ "folder_path": folder_path,
703
+ "path_in_repo": path_in_repo,
704
+ "raw_result": str(result),
705
+ "version": self.version,
706
+ }
707
+
708
+ def upload_folder_optional(
709
+ self,
710
+ repo_key,
711
+ folder_path,
712
+ path_in_repo=None,
713
+ commit_message="Upload folder",
714
+ ):
715
+ try:
716
+ return self.upload_folder(
717
+ repo_key=repo_key,
718
+ folder_path=folder_path,
719
+ path_in_repo=path_in_repo,
720
+ commit_message=commit_message,
721
+ )
722
+ except Exception as e:
723
+ return {
724
+ "success": False,
725
+ "uploaded": False,
726
+ "repo_key": repo_key,
727
+ "folder_path": folder_path,
728
+ "path_in_repo": path_in_repo,
729
+ "message": str(e),
730
+ "traceback": traceback.format_exc(),
731
+ "version": self.version,
732
+ }
733
+
734
+ # ======================================================
735
+ # قراءة JSON من مستودع
736
+ # ======================================================
737
+
738
+ def download_json(
739
+ self,
740
+ repo_key,
741
+ filename,
742
+ local_dir=None,
743
+ ):
744
+ file_path = self.download_file(
745
+ repo_key=repo_key,
746
+ filename=filename,
747
+ local_dir=local_dir,
748
+ )
749
+
750
+ with open(file_path, "r", encoding="utf-8") as f:
751
+ data = json.load(f)
752
+
753
+ return data
754
+
755
+ def download_json_optional(
756
+ self,
757
+ repo_key,
758
+ filename,
759
+ local_dir=None,
760
+ default=None,
761
+ ):
762
+ if default is None:
763
+ default = {}
764
+
765
+ try:
766
+ data = self.download_json(
767
+ repo_key=repo_key,
768
+ filename=filename,
769
+ local_dir=local_dir,
770
+ )
771
+ return data if isinstance(data, dict) else default
772
+ except Exception:
773
+ return default
774
+
775
+ # ======================================================
776
+ # حفظ JSON محليًا ثم رفعه
777
+ # ======================================================
778
+
779
+ def upload_json(
780
+ self,
781
+ repo_key,
782
+ data,
783
+ path_in_repo,
784
+ local_name=None,
785
+ commit_message="Upload JSON file",
786
+ ):
787
+ if local_name is None:
788
+ local_name = os.path.basename(path_in_repo)
789
+
790
+ local_name = self.clean_name(local_name, "data.json")
791
+ if not local_name.endswith(".json"):
792
+ local_name += ".json"
793
+
794
+ local_path = os.path.join(CACHE_FOLDER, local_name)
795
+
796
+ Path(CACHE_FOLDER).mkdir(parents=True, exist_ok=True)
797
+
798
+ with open(local_path, "w", encoding="utf-8") as f:
799
+ json.dump(
800
+ self.json_safe(data),
801
+ f,
802
+ ensure_ascii=False,
803
+ indent=4,
804
+ )
805
+
806
+ return self.upload_file(
807
+ repo_key=repo_key,
808
+ local_path=local_path,
809
+ path_in_repo=path_in_repo,
810
+ commit_message=commit_message,
811
+ )
812
+
813
+ def upload_json_optional(
814
+ self,
815
+ repo_key,
816
+ data,
817
+ path_in_repo,
818
+ local_name=None,
819
+ commit_message="Upload JSON file",
820
+ ):
821
+ try:
822
+ return self.upload_json(
823
+ repo_key=repo_key,
824
+ data=data,
825
+ path_in_repo=path_in_repo,
826
+ local_name=local_name,
827
+ commit_message=commit_message,
828
+ )
829
+ except Exception as e:
830
+ return {
831
+ "success": False,
832
+ "uploaded": False,
833
+ "repo_key": repo_key,
834
+ "path_in_repo": path_in_repo,
835
+ "message": str(e),
836
+ "traceback": traceback.format_exc(),
837
+ "version": self.version,
838
+ }
839
+
840
+ # ======================================================
841
+ # قراءة وحفظ النصوص
842
+ # ======================================================
843
+
844
+ def download_text(
845
+ self,
846
+ repo_key,
847
+ filename,
848
+ local_dir=None,
849
+ ):
850
+ file_path = self.download_file(
851
+ repo_key=repo_key,
852
+ filename=filename,
853
+ local_dir=local_dir,
854
+ )
855
+
856
+ with open(file_path, "r", encoding="utf-8") as f:
857
+ text = f.read()
858
+
859
+ return text
860
+
861
+ def download_text_optional(
862
+ self,
863
+ repo_key,
864
+ filename,
865
+ local_dir=None,
866
+ default="",
867
+ ):
868
+ try:
869
+ return self.download_text(
870
+ repo_key=repo_key,
871
+ filename=filename,
872
+ local_dir=local_dir,
873
+ )
874
+ except Exception:
875
+ return default
876
+
877
+ def upload_text(
878
+ self,
879
+ repo_key,
880
+ text,
881
+ path_in_repo,
882
+ local_name=None,
883
+ commit_message="Upload text file",
884
+ ):
885
+ if local_name is None:
886
+ local_name = os.path.basename(path_in_repo)
887
+
888
+ local_name = self.clean_name(local_name, "text.txt")
889
+
890
+ local_path = os.path.join(CACHE_FOLDER, local_name)
891
+
892
+ Path(CACHE_FOLDER).mkdir(parents=True, exist_ok=True)
893
+
894
+ with open(local_path, "w", encoding="utf-8") as f:
895
+ f.write(str(text or ""))
896
+
897
+ return self.upload_file(
898
+ repo_key=repo_key,
899
+ local_path=local_path,
900
+ path_in_repo=path_in_repo,
901
+ commit_message=commit_message,
902
+ )
903
+
904
+ # ======================================================
905
+ # اختصارات تنزيل المستودعات
906
+ # ======================================================
907
+
908
+ def download_students(self):
909
+ return self.download_repository("students")
910
+
911
+ def download_teachers(self):
912
+ return self.download_repository("teachers")
913
+
914
+ def download_system(self):
915
+ return self.download_repository("system")
916
+
917
+ def download_models(self):
918
+ return self.download_repository("models")
919
+
920
+ # ======================================================
921
+ # ملفات الطلاب القديمة
922
+ # ======================================================
923
+
924
+ def save_student_profile(self, student_id, data):
925
+ student_id = self.normalize_identity(student_id)
926
+
927
+ path_in_repo = f"students/{student_id}/profile.json"
928
+
929
+ return self.upload_json(
930
+ repo_key="students",
931
+ data=data,
932
+ path_in_repo=path_in_repo,
933
+ local_name=f"profile_{student_id}.json",
934
+ commit_message=f"Update student profile: {student_id}",
935
+ )
936
+
937
+ def load_student_profile(self, student_id):
938
+ student_id = self.normalize_identity(student_id)
939
+
940
+ filename = f"students/{student_id}/profile.json"
941
+
942
+ return self.download_json(
943
+ repo_key="students",
944
+ filename=filename,
945
+ )
946
+
947
+ # ======================================================
948
+ # ملفات النظام القديمة
949
+ # ======================================================
950
+
951
+ def load_general_instruction(self):
952
+ return self.download_text(
953
+ repo_key="system",
954
+ filename="general_instruction.txt",
955
+ )
956
+
957
+ def save_general_instruction(self, text):
958
+ return self.upload_text(
959
+ repo_key="system",
960
+ text=text,
961
+ path_in_repo="general_instruction.txt",
962
+ commit_message="Update general instruction",
963
+ )
964
+
965
+ # ======================================================
966
+ # بلاغات جودة الأسئلة
967
+ # ======================================================
968
+
969
+ def question_reports_storage_info(self):
970
+ repo = self.get_repo(self.question_reports_repo_key)
971
+ return {
972
+ "success": True,
973
+ "repo_key": self.question_reports_repo_key,
974
+ "repo_id": repo.get("repo_id", ""),
975
+ "repo_type": repo.get("repo_type", ""),
976
+ "path_in_repo": self.question_reports_path,
977
+ "version": self.version,
978
+ }
979
+
980
+ def sync_question_reports_from_cloud(self, local_path):
981
+ """
982
+ يجلب سجل البلاغات المركزي إلى الملف المحلي.
983
+ إذا لم يوجد الملف سحابيًا فلا يعتبر ذلك خطأ.
984
+ """
985
+ local_path = str(local_path or "").strip()
986
+ if not local_path:
987
+ return {
988
+ "success": False,
989
+ "synced": False,
990
+ "message": "local_path مفقود.",
991
+ "version": self.version,
992
+ }
993
+
994
+ cache_dir = os.path.join(CACHE_FOLDER, "question_reports", "cloud")
995
+ Path(cache_dir).mkdir(parents=True, exist_ok=True)
996
+
997
+ cloud_path = self.download_file_optional(
998
+ repo_key=self.question_reports_repo_key,
999
+ filename=self.question_reports_path,
1000
+ local_dir=cache_dir,
1001
+ )
1002
+
1003
+ if not cloud_path or not os.path.exists(cloud_path):
1004
+ return {
1005
+ "success": True,
1006
+ "synced": False,
1007
+ "cloud_exists": False,
1008
+ "local_path": local_path,
1009
+ "message": "لا يوجد سجل بلاغات مركزي بعد.",
1010
+ "version": self.version,
1011
+ }
1012
+
1013
+ try:
1014
+ target = Path(local_path)
1015
+ target.parent.mkdir(parents=True, exist_ok=True)
1016
+ source = Path(cloud_path)
1017
+
1018
+ # ندمج السجل السحابي مع أي أحداث محلية غير مرفوعة بدل
1019
+ # استبدال الملف المحلي بالكامل، حتى لا يضيع بلاغ عند انقطاع الشبكة.
1020
+ cloud_lines = []
1021
+ local_lines = []
1022
+
1023
+ if source.exists():
1024
+ cloud_lines = [
1025
+ line.strip()
1026
+ for line in source.read_text(encoding="utf-8").splitlines()
1027
+ if line.strip()
1028
+ ]
1029
+
1030
+ if target.exists():
1031
+ local_lines = [
1032
+ line.strip()
1033
+ for line in target.read_text(encoding="utf-8").splitlines()
1034
+ if line.strip()
1035
+ ]
1036
+
1037
+ merged = []
1038
+ seen = set()
1039
+ for line in cloud_lines + local_lines:
1040
+ if line in seen:
1041
+ continue
1042
+ seen.add(line)
1043
+ merged.append(line)
1044
+
1045
+ target.write_text(
1046
+ ("\n".join(merged) + "\n") if merged else "",
1047
+ encoding="utf-8",
1048
+ )
1049
+
1050
+ return {
1051
+ "success": True,
1052
+ "synced": True,
1053
+ "cloud_exists": True,
1054
+ "local_path": str(target),
1055
+ "cloud_cache_path": str(source),
1056
+ "repo_key": self.question_reports_repo_key,
1057
+ "path_in_repo": self.question_reports_path,
1058
+ "version": self.version,
1059
+ }
1060
+ except Exception as e:
1061
+ return {
1062
+ "success": False,
1063
+ "synced": False,
1064
+ "cloud_exists": True,
1065
+ "local_path": local_path,
1066
+ "message": str(e),
1067
+ "version": self.version,
1068
+ }
1069
+
1070
+ def sync_question_reports_to_cloud(self, local_path):
1071
+ """
1072
+ يرفع سجل البلاغات المحلي كاملًا إلى خزنة النظام.
1073
+ """
1074
+ local_path = str(local_path or "").strip()
1075
+ if not local_path or not os.path.exists(local_path):
1076
+ return {
1077
+ "success": False,
1078
+ "synced": False,
1079
+ "message": "ملف البلاغات المحلي غير موجود.",
1080
+ "local_path": local_path,
1081
+ "version": self.version,
1082
+ }
1083
+
1084
+ result = self.upload_file_optional(
1085
+ repo_key=self.question_reports_repo_key,
1086
+ local_path=local_path,
1087
+ path_in_repo=self.question_reports_path,
1088
+ commit_message="Update question quality reports",
1089
+ )
1090
+ return {
1091
+ "success": bool(result.get("success")),
1092
+ "synced": bool(result.get("success")),
1093
+ "repo_key": self.question_reports_repo_key,
1094
+ "path_in_repo": self.question_reports_path,
1095
+ "local_path": local_path,
1096
+ "upload_result": result,
1097
+ "version": self.version,
1098
+ }
1099
+
1100
+ # ======================================================
1101
+ # الحصص العلاجية المشتركة
1102
+ # ======================================================
1103
+
1104
+ def extract_remedial_fields(
1105
+ self,
1106
+ task=None,
1107
+ gap_report=None,
1108
+ lesson=None,
1109
+ student=None,
1110
+ media=None,
1111
+ ):
1112
+ task = task if isinstance(task, dict) else {}
1113
+ gap_report = gap_report if isinstance(gap_report, dict) else {}
1114
+ lesson = lesson if isinstance(lesson, dict) else {}
1115
+ student = student if isinstance(student, dict) else {}
1116
+ media = media if isinstance(media, dict) else {}
1117
+
1118
+ if not gap_report:
1119
+ gap_report = task.get("gap_report") or {}
1120
+
1121
+ if not student:
1122
+ student = task.get("student") or {}
1123
+
1124
+ subject = self.normalize_subject(
1125
+ gap_report.get("subject")
1126
+ or task.get("subject")
1127
+ or lesson.get("subject")
1128
+ or "math"
1129
+ )
1130
+
1131
+ grade = self.safe_int(
1132
+ gap_report.get("grade")
1133
+ or task.get("grade")
1134
+ or lesson.get("grade")
1135
+ or student.get("grade")
1136
+ or 1,
1137
+ 1,
1138
+ )
1139
+
1140
+ badge_id = self.clean_name(
1141
+ gap_report.get("badge_id")
1142
+ or task.get("badge_id")
1143
+ or lesson.get("badge_id")
1144
+ or gap_report.get("skill_id")
1145
+ or "unknown_badge",
1146
+ "unknown_badge",
1147
+ )
1148
+
1149
+ skill_id = self.clean_name(
1150
+ gap_report.get("skill_id")
1151
+ or task.get("skill_id")
1152
+ or lesson.get("skill_id")
1153
+ or badge_id,
1154
+ badge_id,
1155
+ )
1156
+
1157
+ main_error_type = self.clean_name(
1158
+ gap_report.get("main_error_type")
1159
+ or task.get("main_error_type")
1160
+ or lesson.get("main_error_type")
1161
+ or "not_full_mastery",
1162
+ "not_full_mastery",
1163
+ )
1164
+
1165
+ skill_title = str(
1166
+ gap_report.get("skill_title")
1167
+ or lesson.get("skill_title")
1168
+ or skill_id
1169
+ ).strip()
1170
+
1171
+ voice_locale = self.detect_voice_locale(
1172
+ task=task,
1173
+ gap_report=gap_report,
1174
+ student=student,
1175
+ )
1176
+
1177
+ media_mode = self.detect_media_mode(
1178
+ media=media,
1179
+ task=task,
1180
+ lesson=lesson,
1181
+ )
1182
+
1183
+ learning_mode = self.clean_name(
1184
+ gap_report.get("learning_mode")
1185
+ or task.get("learning_mode")
1186
+ or lesson.get("learning_mode")
1187
+ or DEFAULT_LEARNING_MODE,
1188
+ DEFAULT_LEARNING_MODE,
1189
+ )
1190
+
1191
+ intervention_level = self.clean_name(
1192
+ gap_report.get("intervention_level")
1193
+ or task.get("intervention_level")
1194
+ or lesson.get("intervention_level")
1195
+ or REMEDIAL_DEFAULT_INTERVENTION,
1196
+ REMEDIAL_DEFAULT_INTERVENTION,
1197
+ ).upper()
1198
+
1199
+ strategy_variant = self.clean_name(
1200
+ gap_report.get("strategy_variant")
1201
+ or task.get("strategy_variant")
1202
+ or lesson.get("strategy_variant")
1203
+ or "A",
1204
+ "A",
1205
+ ).upper()
1206
+
1207
+ content_version = self.clean_name(
1208
+ gap_report.get("content_version")
1209
+ or task.get("content_version")
1210
+ or lesson.get("content_version")
1211
+ or REMEDIAL_CONTENT_VERSION,
1212
+ REMEDIAL_CONTENT_VERSION,
1213
+ )
1214
+
1215
+ grade_band = self.clean_name(
1216
+ gap_report.get("grade_band")
1217
+ or task.get("grade_band")
1218
+ or lesson.get("grade_band")
1219
+ or self.grade_band_name(grade),
1220
+ self.grade_band_name(grade),
1221
+ )
1222
+
1223
+ return {
1224
+ "subject": subject,
1225
+ "grade": grade,
1226
+ "grade_folder": self.grade_folder(grade),
1227
+ "grade_band": grade_band,
1228
+ "badge_id": badge_id,
1229
+ "skill_id": skill_id,
1230
+ "skill_title": skill_title,
1231
+ "main_error_type": main_error_type,
1232
+ "learning_mode": learning_mode,
1233
+ "intervention_level": intervention_level,
1234
+ "strategy_variant": strategy_variant,
1235
+ "voice_locale": voice_locale,
1236
+ "media_mode": media_mode,
1237
+ "content_version": content_version,
1238
+ }
1239
+
1240
+ def make_shared_remedial_package_id(
1241
+ self,
1242
+ task=None,
1243
+ gap_report=None,
1244
+ lesson=None,
1245
+ student=None,
1246
+ media=None,
1247
+ ):
1248
+ fields = self.extract_remedial_fields(
1249
+ task=task,
1250
+ gap_report=gap_report,
1251
+ lesson=lesson,
1252
+ student=student,
1253
+ media=media,
1254
+ )
1255
+
1256
+ package_id = (
1257
+ f"{fields['subject']}_"
1258
+ f"{fields['grade_band']}_"
1259
+ f"{fields['skill_id']}_"
1260
+ f"{fields['main_error_type']}_"
1261
+ f"{fields['learning_mode']}_"
1262
+ f"{fields['intervention_level']}_"
1263
+ f"{fields['strategy_variant']}_"
1264
+ f"{fields['voice_locale']}_"
1265
+ f"{fields['media_mode']}_"
1266
+ f"{fields['content_version']}"
1267
+ )
1268
+
1269
+ return self.clean_name(package_id, "remedial_package")
1270
+
1271
+ def shared_package_base_path(self, fields, package_id):
1272
+ return (
1273
+ f"{self.remedial_library_root}/"
1274
+ f"{fields['subject']}/"
1275
+ f"{fields['grade_band']}/"
1276
+ f"{fields['skill_id']}/"
1277
+ f"{fields['main_error_type']}/"
1278
+ f"{fields['learning_mode']}/"
1279
+ f"{fields['intervention_level']}/"
1280
+ f"{fields['strategy_variant']}/"
1281
+ f"{fields['voice_locale']}/"
1282
+ f"{fields['media_mode']}/"
1283
+ f"{fields['content_version']}/"
1284
+ f"{package_id}"
1285
+ )
1286
+
1287
+ def get_shared_package_paths(
1288
+ self,
1289
+ task=None,
1290
+ gap_report=None,
1291
+ lesson=None,
1292
+ student=None,
1293
+ media=None,
1294
+ ):
1295
+ fields = self.extract_remedial_fields(
1296
+ task=task,
1297
+ gap_report=gap_report,
1298
+ lesson=lesson,
1299
+ student=student,
1300
+ media=media,
1301
+ )
1302
+
1303
+ package_id = self.make_shared_remedial_package_id(
1304
+ task=task,
1305
+ gap_report=gap_report,
1306
+ lesson=lesson,
1307
+ student=student,
1308
+ media=media,
1309
+ )
1310
+
1311
+ base_path = self.shared_package_base_path(fields, package_id)
1312
+
1313
+ return {
1314
+ "package_id": package_id,
1315
+ "fields": fields,
1316
+ "base_path": base_path,
1317
+ "package_json": f"{base_path}/package.json",
1318
+ "lesson_json": f"{base_path}/lesson.json",
1319
+ "video": f"{base_path}/remedial_lesson.mp4",
1320
+ "audio": f"{base_path}/lesson_audio.mp3",
1321
+ "media_manifest": f"{base_path}/media_manifest.json",
1322
+ "scene_plan": f"{base_path}/scene_plan.json",
1323
+ "narration": f"{base_path}/narration.txt",
1324
+ "slides": f"{base_path}/slides",
1325
+ }
1326
+
1327
+ def is_shared_package_ready(self, manifest):
1328
+ """
1329
+ لا نعتبر الحصة المشتركة جاهزة إلا إذا كان الفيديو محفوظًا فعليًا.
1330
+
1331
+ هذا يمنع استخدام package قديم فاشل كان محفوظًا بدون فيديو.
1332
+ """
1333
+ if not isinstance(manifest, dict):
1334
+ return False, "manifest ليس JSON صالحًا."
1335
+
1336
+ if not manifest.get("package_id"):
1337
+ return False, "package_id مفقود."
1338
+
1339
+ if manifest.get("ready") is False:
1340
+ return False, "package.ready=false."
1341
+
1342
+ if manifest.get("success") is False:
1343
+ return False, "package.success=false."
1344
+
1345
+ cloud_files = manifest.get("cloud_files") or {}
1346
+ if not isinstance(cloud_files, dict):
1347
+ cloud_files = {}
1348
+
1349
+ video_cloud = (
1350
+ cloud_files.get("video")
1351
+ or ((manifest.get("media_summary") or {}).get("video_path"))
1352
+ or ""
1353
+ )
1354
+
1355
+ lesson = manifest.get("lesson") or {}
1356
+ if not isinstance(lesson, dict):
1357
+ lesson = {}
1358
+
1359
+ video_info = lesson.get("video") or {}
1360
+ if not isinstance(video_info, dict):
1361
+ video_info = {}
1362
+
1363
+ video_status = str(video_info.get("status") or "").strip().lower()
1364
+ video_success = video_info.get("success", None)
1365
+
1366
+ if video_status in ["failed", "error", "not_started", "not_configured"]:
1367
+ return False, f"video.status غير جاهز: {video_status}"
1368
+
1369
+ if video_success is False:
1370
+ return False, "video.success=false."
1371
+
1372
+ if not video_cloud:
1373
+ return False, "cloud_files.video فارغ."
1374
+
1375
+ return True, "الحصة المشتركة جاهزة."
1376
+
1377
+ def find_shared_remedial_package(
1378
+ self,
1379
+ task=None,
1380
+ gap_report=None,
1381
+ lesson=None,
1382
+ student=None,
1383
+ media=None,
1384
+ ):
1385
+ paths = self.get_shared_package_paths(
1386
+ task=task,
1387
+ gap_report=gap_report,
1388
+ lesson=lesson,
1389
+ student=student,
1390
+ media=media,
1391
+ )
1392
+
1393
+ manifest = self.download_json_optional(
1394
+ repo_key="teachers",
1395
+ filename=paths["package_json"],
1396
+ default={},
1397
+ )
1398
+
1399
+ raw_exists = bool(isinstance(manifest, dict) and manifest.get("package_id"))
1400
+
1401
+ if not raw_exists:
1402
+ return {
1403
+ "success": True,
1404
+ "exists": False,
1405
+ "raw_exists": False,
1406
+ "ready": False,
1407
+ "package_id": paths["package_id"],
1408
+ "paths": paths,
1409
+ "manifest": {},
1410
+ "message": "لا توجد حصة علاجية مشتركة لهذا المفتاح.",
1411
+ "version": self.version,
1412
+ }
1413
+
1414
+ ready, reason = self.is_shared_package_ready(manifest)
1415
+
1416
+ if not ready:
1417
+ return {
1418
+ "success": True,
1419
+ "exists": False,
1420
+ "raw_exists": True,
1421
+ "ready": False,
1422
+ "invalid_reason": reason,
1423
+ "package_id": paths["package_id"],
1424
+ "paths": paths,
1425
+ "manifest": manifest,
1426
+ "message": "تم العثور على حصة علاجية مشتركة قديمة لكنها غير جاهزة، وسيتم تجاهلها وإعادة إنشائها.",
1427
+ "version": self.version,
1428
+ }
1429
+
1430
+ return {
1431
+ "success": True,
1432
+ "exists": True,
1433
+ "raw_exists": True,
1434
+ "ready": True,
1435
+ "package_id": paths["package_id"],
1436
+ "paths": paths,
1437
+ "manifest": manifest,
1438
+ "message": "تم العثور على حصة علاجية مشتركة جاهزة.",
1439
+ "version": self.version,
1440
+ }
1441
+
1442
+ def sanitize_gap_report_for_shared(self, gap_report):
1443
+ gap_report = gap_report if isinstance(gap_report, dict) else {}
1444
+
1445
+ wrong_items = gap_report.get("wrong_items") or []
1446
+ sanitized_wrong_items = []
1447
+
1448
+ if isinstance(wrong_items, list):
1449
+ for item in wrong_items[:3]:
1450
+ if not isinstance(item, dict):
1451
+ continue
1452
+
1453
+ sanitized_wrong_items.append({
1454
+ "prompt": item.get("prompt", ""),
1455
+ "correct": item.get("correct", ""),
1456
+ "error_type": item.get("error_type", ""),
1457
+ "skill_id": item.get("skill_id", ""),
1458
+ "skill_title": item.get("skill_title", ""),
1459
+ "difficulty": item.get("difficulty", ""),
1460
+ "explanation": item.get("explanation", ""),
1461
+ "common_wrong_answer": item.get("selected", ""),
1462
+ })
1463
+
1464
+ return {
1465
+ "subject": gap_report.get("subject", ""),
1466
+ "subject_name": gap_report.get("subject_name", ""),
1467
+ "grade": gap_report.get("grade", ""),
1468
+ "badge_id": gap_report.get("badge_id", ""),
1469
+ "badge_title": gap_report.get("badge_title", ""),
1470
+ "skill_id": gap_report.get("skill_id", ""),
1471
+ "skill_title": gap_report.get("skill_title", ""),
1472
+ "global_level": gap_report.get("global_level", ""),
1473
+ "main_error_type": gap_report.get("main_error_type", ""),
1474
+ "error_counts": gap_report.get("error_counts", {}),
1475
+ "mastery_required": gap_report.get("mastery_required", 100),
1476
+ "shared_example_items": sanitized_wrong_items,
1477
+ "privacy_note": "هذا تقرير عام للحصة المشتركة ولا يحتوي هوية الطالب.",
1478
+ }
1479
+
1480
+ def sanitize_lesson_for_shared(self, lesson):
1481
+ lesson = lesson if isinstance(lesson, dict) else {}
1482
+
1483
+ blocked_keys = {
1484
+ "identity",
1485
+ "student",
1486
+ "student_id",
1487
+ "student_name",
1488
+ "task_id",
1489
+ "answers",
1490
+ }
1491
+
1492
+ clean = {}
1493
+
1494
+ for key, value in lesson.items():
1495
+ if key in blocked_keys:
1496
+ continue
1497
+ clean[key] = value
1498
+
1499
+ text = str(clean.get("text") or "")
1500
+
1501
+ text = text.replace(
1502
+ "السؤال الذي تعثر فيه الطالب",
1503
+ "سؤال شائع يحدث فيه الخطأ",
1504
+ )
1505
+ text = text.replace(
1506
+ "إجابة الطالب",
1507
+ "إجابة شائعة خاطئة",
1508
+ )
1509
+ text = text.replace(
1510
+ "هذا يعطينا دليلًا على موضع الخلل، وليس مجرد درجة منخفضة.",
1511
+ "هذا يوضح موضع الخلل الذي تعالجه الحصة.",
1512
+ )
1513
+
1514
+ clean["text"] = text
1515
+ clean["privacy_note"] = "نسخة مشتركة لا تحتوي اسم الطالب ولا هويته."
1516
+
1517
+ if isinstance(clean.get("wrong_items"), list):
1518
+ new_wrong_items = []
1519
+ for item in clean.get("wrong_items", [])[:3]:
1520
+ if not isinstance(item, dict):
1521
+ continue
1522
+
1523
+ new_wrong_items.append({
1524
+ "prompt": item.get("prompt", ""),
1525
+ "correct": item.get("correct", ""),
1526
+ "error_type": item.get("error_type", ""),
1527
+ "skill_id": item.get("skill_id", ""),
1528
+ "skill_title": item.get("skill_title", ""),
1529
+ "difficulty": item.get("difficulty", ""),
1530
+ "explanation": item.get("explanation", ""),
1531
+ "common_wrong_answer": item.get("selected", ""),
1532
+ })
1533
+
1534
+ clean["wrong_items"] = new_wrong_items
1535
+
1536
+ return clean
1537
+
1538
+ def build_shared_package_manifest(
1539
+ self,
1540
+ task=None,
1541
+ lesson=None,
1542
+ media=None,
1543
+ paths=None,
1544
+ cloud_files=None,
1545
+ package_ready=False,
1546
+ ready_reason="",
1547
+ ):
1548
+ task = task if isinstance(task, dict) else {}
1549
+ lesson = lesson if isinstance(lesson, dict) else {}
1550
+ media = media if isinstance(media, dict) else {}
1551
+ paths = paths if isinstance(paths, dict) else self.get_shared_package_paths(
1552
+ task=task,
1553
+ lesson=lesson,
1554
+ media=media,
1555
+ )
1556
+ cloud_files = cloud_files if isinstance(cloud_files, dict) else {}
1557
+
1558
+ gap_report = task.get("gap_report") or {}
1559
+ student = task.get("student") or {}
1560
+
1561
+ fields = paths.get("fields") or self.extract_remedial_fields(
1562
+ task=task,
1563
+ gap_report=gap_report,
1564
+ lesson=lesson,
1565
+ student=student,
1566
+ media=media,
1567
+ )
1568
+
1569
+ video_info = lesson.get("video") if isinstance(lesson.get("video"), dict) else {}
1570
+
1571
+ manifest = {
1572
+ "success": bool(package_ready),
1573
+ "ready": bool(package_ready),
1574
+ "package_id": paths.get("package_id"),
1575
+ "package_type": "shared_remedial_lesson",
1576
+ "storage_version": self.version,
1577
+ "created_at": self.now(),
1578
+ "updated_at": self.now(),
1579
+ "ready_reason": ready_reason,
1580
+ "fields": fields,
1581
+ "repo_key": "teachers",
1582
+ "base_path": paths.get("base_path", ""),
1583
+ "paths": {
1584
+ "package_json": paths.get("package_json", ""),
1585
+ "lesson_json": paths.get("lesson_json", ""),
1586
+ "video": paths.get("video", ""),
1587
+ "audio": paths.get("audio", ""),
1588
+ "media_manifest": paths.get("media_manifest", ""),
1589
+ "scene_plan": paths.get("scene_plan", ""),
1590
+ "narration": paths.get("narration", ""),
1591
+ "slides": paths.get("slides", ""),
1592
+ },
1593
+ "cloud_files": cloud_files,
1594
+ "lesson": self.sanitize_lesson_for_shared(lesson),
1595
+ "gap_summary": self.sanitize_gap_report_for_shared(gap_report),
1596
+ "media_summary": {
1597
+ "mode": media.get("mode", ""),
1598
+ "video_path": cloud_files.get("video", ""),
1599
+ "audio_path": cloud_files.get("audio", ""),
1600
+ "media_manifest_path": cloud_files.get("media_manifest", ""),
1601
+ "scene_plan_path": cloud_files.get("scene_plan", ""),
1602
+ "narration_path": cloud_files.get("narration", ""),
1603
+ "slides_path": cloud_files.get("slides", ""),
1604
+ "slide_count": media.get("slide_count", 0),
1605
+ "source_version": media.get("version", ""),
1606
+ "local_video_status": video_info.get("status", ""),
1607
+ "local_video_success": video_info.get("success", None),
1608
+ },
1609
+ "privacy": {
1610
+ "shared": True,
1611
+ "contains_student_identity": False,
1612
+ "contains_student_name": False,
1613
+ "student_specific_data_location": "students remedial assignment only",
1614
+ },
1615
+ }
1616
+
1617
+ return manifest
1618
+
1619
+ def save_shared_remedial_package(
1620
+ self,
1621
+ task=None,
1622
+ lesson=None,
1623
+ media=None,
1624
+ allow_replace=False,
1625
+ ):
1626
+ task = task if isinstance(task, dict) else {}
1627
+ lesson = lesson if isinstance(lesson, dict) else {}
1628
+ media = media if isinstance(media, dict) else {}
1629
+
1630
+ paths = self.get_shared_package_paths(
1631
+ task=task,
1632
+ lesson=lesson,
1633
+ media=media,
1634
+ )
1635
+
1636
+ existing = self.find_shared_remedial_package(
1637
+ task=task,
1638
+ lesson=lesson,
1639
+ media=media,
1640
+ )
1641
+
1642
+ if existing.get("exists") and not allow_replace:
1643
+ return {
1644
+ "success": True,
1645
+ "created": False,
1646
+ "existing": True,
1647
+ "ready": True,
1648
+ "package_id": paths["package_id"],
1649
+ "paths": paths,
1650
+ "manifest": existing.get("manifest", {}),
1651
+ "message": "الحصة العلاجية المشتركة موجودة مسبقًا وجاهزة.",
1652
+ "version": self.version,
1653
+ }
1654
+
1655
+ cloud_files = {}
1656
+
1657
+ video_path = (
1658
+ media.get("video_path")
1659
+ or media.get("video_file")
1660
+ or (lesson.get("video") or {}).get("local_path")
1661
+ or ""
1662
+ )
1663
+
1664
+ audio_path = (
1665
+ media.get("audio_path")
1666
+ or (lesson.get("video") or {}).get("audio_path")
1667
+ or ""
1668
+ )
1669
+
1670
+ manifest_path = (
1671
+ media.get("manifest_path")
1672
+ or media.get("media_manifest_path")
1673
+ or (lesson.get("video") or {}).get("manifest_path")
1674
+ or ""
1675
+ )
1676
+
1677
+ scene_plan_path = media.get("scene_plan_path") or ""
1678
+ narration_path = media.get("narration_path") or ""
1679
+
1680
+ if video_path and os.path.exists(video_path):
1681
+ result = self.upload_file_optional(
1682
+ repo_key="teachers",
1683
+ local_path=video_path,
1684
+ path_in_repo=paths["video"],
1685
+ commit_message=f"Save shared remedial video: {paths['package_id']}",
1686
+ )
1687
+ if result.get("success"):
1688
+ cloud_files["video"] = paths["video"]
1689
+
1690
+ if audio_path and os.path.exists(audio_path):
1691
+ result = self.upload_file_optional(
1692
+ repo_key="teachers",
1693
+ local_path=audio_path,
1694
+ path_in_repo=paths["audio"],
1695
+ commit_message=f"Save shared remedial audio: {paths['package_id']}",
1696
+ )
1697
+ if result.get("success"):
1698
+ cloud_files["audio"] = paths["audio"]
1699
+
1700
+ if manifest_path and os.path.exists(manifest_path):
1701
+ result = self.upload_file_optional(
1702
+ repo_key="teachers",
1703
+ local_path=manifest_path,
1704
+ path_in_repo=paths["media_manifest"],
1705
+ commit_message=f"Save shared remedial media manifest: {paths['package_id']}",
1706
+ )
1707
+ if result.get("success"):
1708
+ cloud_files["media_manifest"] = paths["media_manifest"]
1709
+
1710
+ if scene_plan_path and os.path.exists(scene_plan_path):
1711
+ result = self.upload_file_optional(
1712
+ repo_key="teachers",
1713
+ local_path=scene_plan_path,
1714
+ path_in_repo=paths["scene_plan"],
1715
+ commit_message=f"Save shared remedial scene plan: {paths['package_id']}",
1716
+ )
1717
+ if result.get("success"):
1718
+ cloud_files["scene_plan"] = paths["scene_plan"]
1719
+
1720
+ if narration_path and os.path.exists(narration_path):
1721
+ result = self.upload_file_optional(
1722
+ repo_key="teachers",
1723
+ local_path=narration_path,
1724
+ path_in_repo=paths["narration"],
1725
+ commit_message=f"Save shared remedial narration: {paths['package_id']}",
1726
+ )
1727
+ if result.get("success"):
1728
+ cloud_files["narration"] = paths["narration"]
1729
+
1730
+ slide_paths = media.get("slide_paths") or []
1731
+ if isinstance(slide_paths, list) and slide_paths:
1732
+ first_slide = slide_paths[0]
1733
+ slides_folder = os.path.dirname(first_slide) if first_slide else ""
1734
+
1735
+ if slides_folder and os.path.isdir(slides_folder):
1736
+ result = self.upload_folder_optional(
1737
+ repo_key="teachers",
1738
+ folder_path=slides_folder,
1739
+ path_in_repo=paths["slides"],
1740
+ commit_message=f"Save shared remedial slides: {paths['package_id']}",
1741
+ )
1742
+ if result.get("success"):
1743
+ cloud_files["slides"] = paths["slides"]
1744
+
1745
+ video_info = lesson.get("video") if isinstance(lesson.get("video"), dict) else {}
1746
+ local_video_status = str(video_info.get("status") or "").strip().lower()
1747
+ local_video_success = video_info.get("success", None)
1748
+
1749
+ package_ready = bool(
1750
+ cloud_files.get("video")
1751
+ and local_video_status == "ready"
1752
+ and local_video_success is not False
1753
+ )
1754
+
1755
+ ready_reason = (
1756
+ "الفيديو محفوظ وجاهز."
1757
+ if package_ready
1758
+ else "لم يتم حفظ فيديو جاهز، لذلك لا تعتبر الحصة المشتركة صالحة للاستخدام."
1759
+ )
1760
+
1761
+ shared_lesson = self.sanitize_lesson_for_shared(lesson)
1762
+
1763
+ self.upload_json_optional(
1764
+ repo_key="teachers",
1765
+ data=shared_lesson,
1766
+ path_in_repo=paths["lesson_json"],
1767
+ local_name=f"{paths['package_id']}_lesson.json",
1768
+ commit_message=f"Save shared remedial lesson JSON: {paths['package_id']}",
1769
+ )
1770
+
1771
+ manifest = self.build_shared_package_manifest(
1772
+ task=task,
1773
+ lesson=lesson,
1774
+ media=media,
1775
+ paths=paths,
1776
+ cloud_files=cloud_files,
1777
+ package_ready=package_ready,
1778
+ ready_reason=ready_reason,
1779
+ )
1780
+
1781
+ upload_manifest = self.upload_json_optional(
1782
+ repo_key="teachers",
1783
+ data=manifest,
1784
+ path_in_repo=paths["package_json"],
1785
+ local_name=f"{paths['package_id']}_package.json",
1786
+ commit_message=f"Save shared remedial package: {paths['package_id']}",
1787
+ )
1788
+
1789
+ return {
1790
+ "success": bool(upload_manifest.get("success") and package_ready),
1791
+ "created": bool(upload_manifest.get("success") and package_ready),
1792
+ "existing": False,
1793
+ "ready": package_ready,
1794
+ "package_id": paths["package_id"],
1795
+ "paths": paths,
1796
+ "cloud_files": cloud_files,
1797
+ "manifest": manifest,
1798
+ "upload_result": upload_manifest,
1799
+ "message": "تم حفظ الحصة العلاجية المشتركة وهي جاهزة." if package_ready else "تم حفظ سجل الحصة لكنه غير جاهز لأن الفيديو غير محفوظ.",
1800
+ "version": self.version,
1801
+ }
1802
+
1803
+ # ======================================================
1804
+ # تكليف الطالب بحصة علاجية مشتركة
1805
+ # ======================================================
1806
+
1807
+ def student_assignment_path(self, identity, subject, badge_id, task_id):
1808
+ identity = self.normalize_identity(identity)
1809
+ subject = self.normalize_subject(subject)
1810
+ badge_id = self.clean_name(badge_id or "unknown_badge", "unknown_badge")
1811
+ task_id = self.clean_name(task_id or "task", "task")
1812
+
1813
+ return (
1814
+ f"{self.student_assignments_root}/"
1815
+ f"{identity}/"
1816
+ f"remedial_assignments/"
1817
+ f"{subject}/"
1818
+ f"{badge_id}/"
1819
+ f"{task_id}.json"
1820
+ )
1821
+
1822
+ def build_student_remedial_assignment(
1823
+ self,
1824
+ task=None,
1825
+ package_result=None,
1826
+ ):
1827
+ task = task if isinstance(task, dict) else {}
1828
+ package_result = package_result if isinstance(package_result, dict) else {}
1829
+
1830
+ gap_report = task.get("gap_report") or {}
1831
+
1832
+ identity = self.normalize_identity(
1833
+ task.get("identity")
1834
+ or gap_report.get("identity")
1835
+ or "student"
1836
+ )
1837
+
1838
+ subject = self.normalize_subject(
1839
+ task.get("subject")
1840
+ or gap_report.get("subject")
1841
+ or "math"
1842
+ )
1843
+
1844
+ badge_id = self.clean_name(
1845
+ task.get("badge_id")
1846
+ or gap_report.get("badge_id")
1847
+ or gap_report.get("skill_id")
1848
+ or "unknown_badge",
1849
+ "unknown_badge",
1850
+ )
1851
+
1852
+ task_id = self.clean_name(
1853
+ task.get("task_id")
1854
+ or f"remedial_{identity}_{badge_id}_{self.short_hash(task)}",
1855
+ "task",
1856
+ )
1857
+
1858
+ assignment_path = self.student_assignment_path(
1859
+ identity=identity,
1860
+ subject=subject,
1861
+ badge_id=badge_id,
1862
+ task_id=task_id,
1863
+ )
1864
+
1865
+ fields = self.extract_remedial_fields(
1866
+ task=task,
1867
+ gap_report=gap_report,
1868
+ lesson={},
1869
+ student=task.get("student") or {},
1870
+ media={},
1871
+ )
1872
+
1873
+ package_ready = bool(package_result.get("success") and package_result.get("ready", True))
1874
+
1875
+ assignment = {
1876
+ "success": True,
1877
+ "assignment_type": "student_remedial_assignment",
1878
+ "identity": identity,
1879
+ "task_id": task_id,
1880
+ "subject": subject,
1881
+ "grade": fields.get("grade"),
1882
+ "badge_id": badge_id,
1883
+ "skill_id": fields.get("skill_id"),
1884
+ "skill_title": fields.get("skill_title"),
1885
+ "main_error_type": fields.get("main_error_type"),
1886
+ "required_before_badge_retry": True,
1887
+ "watched": bool(task.get("watched", False)),
1888
+ "status": "done" if package_ready else task.get("status", "pending"),
1889
+ "lesson_available": bool(package_ready),
1890
+ "package_id": package_result.get("package_id", ""),
1891
+ "package_manifest_path": (package_result.get("paths") or {}).get("package_json", ""),
1892
+ "package_base_path": (package_result.get("paths") or {}).get("base_path", ""),
1893
+ "package_repo_key": "teachers",
1894
+ "created_at": task.get("created_at") or self.now(),
1895
+ "updated_at": self.now(),
1896
+ "watched_at": task.get("watched_at", ""),
1897
+ "source_task": {
1898
+ "task_id": task_id,
1899
+ "status": "done" if package_ready else task.get("status", ""),
1900
+ "video_status": "ready" if package_ready else task.get("video_status", ""),
1901
+ "remedial_key": task.get("remedial_key", ""),
1902
+ },
1903
+ "student_gap_private_summary": {
1904
+ "percentage": gap_report.get("percentage", ""),
1905
+ "correct": gap_report.get("correct", ""),
1906
+ "total": gap_report.get("total", ""),
1907
+ "needs_remedial": gap_report.get("needs_remedial", True),
1908
+ "wrong_count": len(gap_report.get("wrong_items", [])) if isinstance(gap_report.get("wrong_items"), list) else 0,
1909
+ },
1910
+ "privacy_note": "هذا الملف خاص بالطالب، أما الفيديو والحصة العامة محفوظان في remedial_library.",
1911
+ "storage_version": self.version,
1912
+ }
1913
+
1914
+ return assignment_path, assignment
1915
+
1916
+ def save_student_remedial_assignment(
1917
+ self,
1918
+ task=None,
1919
+ package_result=None,
1920
+ ):
1921
+ assignment_path, assignment = self.build_student_remedial_assignment(
1922
+ task=task,
1923
+ package_result=package_result,
1924
+ )
1925
+
1926
+ result = self.upload_json_optional(
1927
+ repo_key="students",
1928
+ data=assignment,
1929
+ path_in_repo=assignment_path,
1930
+ local_name=f"{assignment.get('task_id', 'task')}_assignment.json",
1931
+ commit_message=f"Save student remedial assignment: {assignment.get('identity', '')}",
1932
+ )
1933
+
1934
+ return {
1935
+ "success": bool(result.get("success")),
1936
+ "assignment_path": assignment_path,
1937
+ "assignment": assignment,
1938
+ "upload_result": result,
1939
+ "message": "تم حفظ تكليف الطالب بالحصة العلاجية." if result.get("success") else "فشل حفظ تكليف الطالب.",
1940
+ "version": self.version,
1941
+ }
1942
+
1943
+ def save_remedial_package_and_assignment(
1944
+ self,
1945
+ task=None,
1946
+ lesson=None,
1947
+ media=None,
1948
+ allow_replace=False,
1949
+ ):
1950
+ task = task if isinstance(task, dict) else {}
1951
+ lesson = lesson if isinstance(lesson, dict) else {}
1952
+ media = media if isinstance(media, dict) else {}
1953
+
1954
+ existing = self.find_shared_remedial_package(
1955
+ task=task,
1956
+ lesson=lesson,
1957
+ media=media,
1958
+ )
1959
+
1960
+ if existing.get("exists"):
1961
+ package_result = {
1962
+ "success": True,
1963
+ "created": False,
1964
+ "existing": True,
1965
+ "ready": True,
1966
+ "package_id": existing.get("package_id", ""),
1967
+ "paths": existing.get("paths", {}),
1968
+ "manifest": existing.get("manifest", {}),
1969
+ "message": "تم استخدام حصة علاجية مشتركة موجودة وجاهزة.",
1970
+ "version": self.version,
1971
+ }
1972
+ else:
1973
+ package_result = self.save_shared_remedial_package(
1974
+ task=task,
1975
+ lesson=lesson,
1976
+ media=media,
1977
+ allow_replace=True,
1978
+ )
1979
+
1980
+ assignment_result = self.save_student_remedial_assignment(
1981
+ task=task,
1982
+ package_result=package_result,
1983
+ )
1984
+
1985
+ return {
1986
+ "success": bool(package_result.get("success") and assignment_result.get("success")),
1987
+ "package_result": package_result,
1988
+ "assignment_result": assignment_result,
1989
+ "package_id": package_result.get("package_id", ""),
1990
+ "assignment_path": assignment_result.get("assignment_path", ""),
1991
+ "used_existing_package": bool(package_result.get("existing")),
1992
+ "created_new_package": bool(package_result.get("created")),
1993
+ "package_ready": bool(package_result.get("success")),
1994
+ "message": "تم حفظ الحصة المشتركة وربط الطالب بها." if package_result.get("success") and assignment_result.get("success") else "حدث خطأ أثناء حفظ الحصة أو ربط الطالب.",
1995
+ "version": self.version,
1996
+ }
1997
+
1998
+ def mark_student_remedial_assignment_watched(
1999
+ self,
2000
+ identity,
2001
+ subject,
2002
+ badge_id,
2003
+ task_id,
2004
+ package_id="",
2005
+ ):
2006
+ identity = self.normalize_identity(identity)
2007
+ subject = self.normalize_subject(subject)
2008
+ badge_id = self.clean_name(badge_id or "unknown_badge", "unknown_badge")
2009
+ task_id = self.clean_name(task_id or "task", "task")
2010
+
2011
+ assignment_path = self.student_assignment_path(
2012
+ identity=identity,
2013
+ subject=subject,
2014
+ badge_id=badge_id,
2015
+ task_id=task_id,
2016
+ )
2017
+
2018
+ assignment = self.download_json_optional(
2019
+ repo_key="students",
2020
+ filename=assignment_path,
2021
+ default={},
2022
+ )
2023
+
2024
+ if not assignment:
2025
+ assignment = {
2026
+ "success": True,
2027
+ "assignment_type": "student_remedial_assignment",
2028
+ "identity": identity,
2029
+ "task_id": task_id,
2030
+ "subject": subject,
2031
+ "badge_id": badge_id,
2032
+ "package_id": package_id,
2033
+ "required_before_badge_retry": True,
2034
+ "created_at": self.now(),
2035
+ "privacy_note": "تم إنشاء ملف مشاهدة مختصر لأن التكليف الأصلي غير موجود محليًا.",
2036
+ }
2037
+
2038
+ assignment["watched"] = True
2039
+ assignment["watched_at"] = self.now()
2040
+ assignment["updated_at"] = self.now()
2041
+ assignment["status"] = "watched"
2042
+ assignment["lesson_available"] = True
2043
+ assignment["storage_version"] = self.version
2044
+
2045
+ result = self.upload_json_optional(
2046
+ repo_key="students",
2047
+ data=assignment,
2048
+ path_in_repo=assignment_path,
2049
+ local_name=f"{task_id}_watched_assignment.json",
2050
+ commit_message=f"Mark remedial assignment watched: {identity}",
2051
+ )
2052
+
2053
+ return {
2054
+ "success": bool(result.get("success")),
2055
+ "assignment_path": assignment_path,
2056
+ "assignment": assignment,
2057
+ "upload_result": result,
2058
+ "message": "تم تسجيل مشاهدة الحصة العلاجية." if result.get("success") else "فشل تسجيل مشاهدة الحصة.",
2059
+ "version": self.version,
2060
+ }
2061
+
2062
+ # ======================================================
2063
+ # تنزيل كل شيء أساسي
2064
+ # ======================================================
2065
+
2066
+ def pull_all(self):
2067
+ result = {}
2068
+ result["students"] = self.download_students()
2069
+ result["teachers"] = self.download_teachers()
2070
+ result["system"] = self.download_system()
2071
+
2072
+ return result
2073
+
2074
+ # ======================================================
2075
+ # ملخص
2076
+ # ======================================================
2077
+
2078
+ def summary(self):
2079
+ return {
2080
+ "success": True,
2081
+ "ready": True,
2082
+ "version": self.version,
2083
+ "repositories": {
2084
+ key: {
2085
+ "repo_id": value.get("repo_id"),
2086
+ "repo_type": value.get("repo_type"),
2087
+ "local_folder": value.get("local_folder"),
2088
+ }
2089
+ for key, value in self.repositories.items()
2090
+ },
2091
+ "has_token": bool(self.token),
2092
+ "remedial_library_root": self.remedial_library_root,
2093
+ "student_assignments_root": self.student_assignments_root,
2094
+ "question_reports_storage": {
2095
+ "repo_key": self.question_reports_repo_key,
2096
+ "path_in_repo": self.question_reports_path,
2097
+ },
2098
+ "admin_repository_tools": {
2099
+ "overview": True,
2100
+ "list_files": True,
2101
+ "download_one_file": True,
2102
+ "destructive_actions": False,
2103
+ },
2104
+ "shared_package_validation": {
2105
+ "requires_package_id": True,
2106
+ "requires_ready_not_false": True,
2107
+ "requires_success_not_false": True,
2108
+ "requires_cloud_video": True,
2109
+ "rejects_video_status_failed": True,
2110
+ },
2111
+ "message": "StorageManager جاهز: يتجاهل الحصص العلاجية المشتركة الفاشلة ويعيد توليدها.",
2112
+ }
2113
+
2114
+
2115
+ _MANAGER = None
2116
+
2117
+
2118
+ def get_manager():
2119
+ global _MANAGER
2120
+
2121
+ if _MANAGER is None:
2122
+ _MANAGER = StorageManager()
2123
+
2124
+ return _MANAGER
2125
+
2126
+
2127
+ def load_games_index(*args, **kwargs):
2128
+ return get_manager().load_games_index(*args, **kwargs)
2129
+
2130
+
2131
+ def save_games_index(*args, **kwargs):
2132
+ return get_manager().save_games_index(*args, **kwargs)
2133
+
2134
+
2135
+ def load_general_strategies(*args, **kwargs):
2136
+ return get_manager().load_general_strategies(*args, **kwargs)
2137
+
2138
+
2139
+ def save_general_strategies(*args, **kwargs):
2140
+ return get_manager().save_general_strategies(*args, **kwargs)
2141
+
2142
+
2143
+ def list_repository_files(*args, **kwargs):
2144
+ return get_manager().list_repository_files(*args, **kwargs)
2145
+
2146
+
2147
+ def repository_overview(*args, **kwargs):
2148
+ return get_manager().repository_overview(*args, **kwargs)
2149
+
2150
+
2151
+ def download_repository_file_for_admin(*args, **kwargs):
2152
+ return get_manager().download_repository_file_for_admin(*args, **kwargs)
2153
+
2154
+
2155
+ def question_reports_storage_info(*args, **kwargs):
2156
+ return get_manager().question_reports_storage_info(*args, **kwargs)
2157
+
2158
+
2159
+ def sync_question_reports_from_cloud(*args, **kwargs):
2160
+ return get_manager().sync_question_reports_from_cloud(*args, **kwargs)
2161
+
2162
+
2163
+ def sync_question_reports_to_cloud(*args, **kwargs):
2164
+ return get_manager().sync_question_reports_to_cloud(*args, **kwargs)
2165
+
2166
+
2167
+ def summary():
2168
+ return get_manager().summary()
2169
+
2170
+
2171
+ def save_remedial_package_and_assignment(*args, **kwargs):
2172
+ return get_manager().save_remedial_package_and_assignment(*args, **kwargs)
2173
+
2174
+
2175
+ def find_shared_remedial_package(*args, **kwargs):
2176
+ return get_manager().find_shared_remedial_package(*args, **kwargs)
2177
+
2178
+
2179
+ def save_shared_remedial_package(*args, **kwargs):
2180
+ return get_manager().save_shared_remedial_package(*args, **kwargs)
2181
+
2182
+
2183
+ def save_student_remedial_assignment(*args, **kwargs):
2184
+ return get_manager().save_student_remedial_assignment(*args, **kwargs)
2185
+
2186
+
2187
+ def mark_student_remedial_assignment_watched(*args, **kwargs):
2188
+ return get_manager().mark_student_remedial_assignment_watched(*args, **kwargs)