Spaces:
Sleeping
Sleeping
Deploy LABEQ source eb61c869b169 on ZeroGPU
Browse files- LABEQ_V15_Goal_Fix.py +3 -3
- LABEQ_V16_Coaching_Engine.py +85 -80
- README.md +3 -2
- app.js +4 -3
- cloud/space_app.py +6 -2
- cloud/torch_engine.py +4 -2
- convert_mlx_to_peft.py +29 -4
- generation_limits.py +7 -0
- labeq_engine.py +8 -3
- local_mlx_server.py +18 -4
- mlx_inference.py +9 -5
- model_bridge.py +3 -2
- ollama_inference.py +82 -0
- semantic_review.py +56 -0
- source-manifest.json +18 -14
- space_client.js +1 -1
- writing_policy.py +18 -0
LABEQ_V15_Goal_Fix.py
CHANGED
|
@@ -130,7 +130,7 @@ def install(engine=None) -> None:
|
|
| 130 |
finally:
|
| 131 |
_ACTIVE.reset(token)
|
| 132 |
|
| 133 |
-
def generate_with_intent(self, messages, retry=False, use_adapter=True):
|
| 134 |
context = _ACTIVE.get()
|
| 135 |
if context and messages:
|
| 136 |
new_messages = [dict(m) for m in messages]
|
|
@@ -145,8 +145,8 @@ def install(engine=None) -> None:
|
|
| 145 |
guidance += "\n- هذه أخطاء الصياغة السابقة التي يجب تصحيحها: " + "؛ ".join(flags)
|
| 146 |
guidance += "\n- أعيدي بناء الرد بناءً على تفاصيل الموقف، لا تبدلي كلمات الرد السابق فقط."
|
| 147 |
new_messages[target_idx]["content"] = str(new_messages[target_idx].get("content", "")) + "\n\n" + guidance
|
| 148 |
-
return old_generate(self, new_messages, retry=retry, use_adapter=use_adapter)
|
| 149 |
-
return old_generate(self, messages, retry=retry, use_adapter=use_adapter)
|
| 150 |
|
| 151 |
def quality_with_intent(reply, relation="", goal="", original=""):
|
| 152 |
flags = list(old_quality(reply, relation, goal, original))
|
|
|
|
| 130 |
finally:
|
| 131 |
_ACTIVE.reset(token)
|
| 132 |
|
| 133 |
+
def generate_with_intent(self, messages, retry=False, use_adapter=True, **generation_kwargs):
|
| 134 |
context = _ACTIVE.get()
|
| 135 |
if context and messages:
|
| 136 |
new_messages = [dict(m) for m in messages]
|
|
|
|
| 145 |
guidance += "\n- هذه أخطاء الصياغة السابقة التي يجب تصحيحها: " + "؛ ".join(flags)
|
| 146 |
guidance += "\n- أعيدي بناء الرد بناءً على تفاصيل الموقف، لا تبدلي كلمات الرد السابق فقط."
|
| 147 |
new_messages[target_idx]["content"] = str(new_messages[target_idx].get("content", "")) + "\n\n" + guidance
|
| 148 |
+
return old_generate(self, new_messages, retry=retry, use_adapter=use_adapter, **generation_kwargs)
|
| 149 |
+
return old_generate(self, messages, retry=retry, use_adapter=use_adapter, **generation_kwargs)
|
| 150 |
|
| 151 |
def quality_with_intent(reply, relation="", goal="", original=""):
|
| 152 |
flags = list(old_quality(reply, relation, goal, original))
|
LABEQ_V16_Coaching_Engine.py
CHANGED
|
@@ -13,10 +13,10 @@ heuristic/model-reviewed, not externally validated or guaranteed.
|
|
| 13 |
"""
|
| 14 |
from __future__ import annotations
|
| 15 |
|
|
|
|
| 16 |
from difflib import SequenceMatcher
|
| 17 |
import re
|
| 18 |
|
| 19 |
-
from LABEQ_V15_Goal_Fix import alignment_flags, brief_for, intent_guidance
|
| 20 |
from saudi_register import (
|
| 21 |
SAUDI_EXAMPLES, SAUDI_SYSTEM, clean_writing, explicit_fusha,
|
| 22 |
normalize_saudi, register_instruction, register_warnings, writing_style,
|
|
@@ -50,13 +50,13 @@ def parse_plan(text):
|
|
| 50 |
def style_instruction(style, goal, message):
|
| 51 |
# Style describes HOW to say it, never replaces WHAT the user needs.
|
| 52 |
defaults = {
|
| 53 |
-
"polite": "
|
| 54 |
-
"firm": "حا
|
| 55 |
-
"diplomatic": "
|
| 56 |
-
"clarify": "
|
| 57 |
-
"apology": "
|
| 58 |
-
"formal": "
|
| 59 |
-
"مختصر": "مختصر
|
| 60 |
}
|
| 61 |
if style in defaults: return defaults[style]
|
| 62 |
return defaults["polite"]
|
|
@@ -119,15 +119,6 @@ def _parse_review(text):
|
|
| 119 |
return None,""
|
| 120 |
|
| 121 |
|
| 122 |
-
def semantic_review_issue(issue):
|
| 123 |
-
"""Only specific meaning concerns can trigger a model-directed rewrite."""
|
| 124 |
-
return bool(re.search(
|
| 125 |
-
r"(?:وعد|وعود|موعد|التزام).*(?:يناقض|يتعارض|غير مذكور|غير مؤكد)|"
|
| 126 |
-
r"(?:اختلق|اختلاق|غير مذكور).*(?:سبب|موعد|وعد|خطأ)|"
|
| 127 |
-
r"(?:أغفل|تجاهل|يتجاهل).*(?:الهدف|المتابعة|الاعتذار|التكرار)|"
|
| 128 |
-
r"غيّر الهدف|عكس الأدوار", issue or "",
|
| 129 |
-
))
|
| 130 |
-
|
| 131 |
|
| 132 |
def reply_v16(self, message, relation="صديق", goal="أبي رد مناسب وواضح",
|
| 133 |
style="تلقائي", speaker_gender="غير محدد", recipient_gender="غير محدد",
|
|
@@ -156,96 +147,110 @@ def reply_v16(self, message, relation="صديق", goal="أبي رد مناسب
|
|
| 156 |
"انتبهي: [تفسير خاطئ واحد يجب تجنبه]\n"
|
| 157 |
f"الموقف: {message}\nالعلاقة: {relation}\nهدف المستخدم: {goal}"
|
| 158 |
)
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
plan=parse_plan(plan_raw)
|
| 161 |
# Phase 2: real response by Saudi LoRA. Keep the user's facts as the source of truth.
|
| 162 |
register = register_instruction(relation, style_key, modifier)
|
| 163 |
-
gen_system =
|
| 164 |
-
|
|
|
|
| 165 |
style_line=style_instruction(style_key,goal,message)
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
return (
|
| 169 |
f"الموقف: {message}\nالعلاقة: {relation}\nالهدف: {goal}\n"
|
| 170 |
-
f"الأسلوب: {writing_style(style_key, modifier)}\n
|
| 171 |
-
|
| 172 |
-
f"{intent_guidance(brief)}\n"
|
| 173 |
-
# The generated coaching plan is advisory; it must not introduce facts into the draft.
|
| 174 |
-
+ f"طريقة الكتابة: {register}\n"
|
| 175 |
-
+ (f"{modifier}\n" if modifier else "")
|
| 176 |
-
+ (f"ملاحظة للمراجعة: {extra}\n" if extra else "")
|
| 177 |
-
+ "اكتبي نص الرسالة السعودية للطرف الآخر مباشرة. الرسالة فقط."
|
| 178 |
)
|
| 179 |
-
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
raw = clean_writing(self._one_generation(
|
| 182 |
[{"role":"system","content":gen_system}] + examples
|
| 183 |
-
+ [{"role":"user","content":gen_prompt(extra)}], retry=retry,
|
| 184 |
), modifier)
|
| 185 |
text, edits = normalize_saudi(raw, modifier, message + " " + goal)
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
first=
|
| 189 |
def check(candidate):
|
| 190 |
return list(dict.fromkeys(
|
| 191 |
local_warnings(candidate, message, goal, style_key, previous)
|
| 192 |
+ quality_flags(candidate, relation, goal, message)
|
| 193 |
-
+ alignment_flags(candidate, brief)
|
| 194 |
+ register_warnings(candidate, modifier)
|
| 195 |
))
|
| 196 |
-
#
|
|
|
|
| 197 |
def review(candidate):
|
| 198 |
-
prompt = (
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
"
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
# Concrete register/intent diagnostics drive the bounded rewrite; the model's
|
| 217 |
-
# remaining concerns are still returned to the user as review warnings.
|
| 218 |
-
reviewed, issue = review(first)
|
| 219 |
-
if reviewed is False:
|
| 220 |
-
flags.append(issue)
|
| 221 |
-
if semantic_review_issue(issue):
|
| 222 |
-
hard_flags.append(issue)
|
| 223 |
-
was_retried = bool(hard_flags)
|
| 224 |
if was_retried:
|
| 225 |
try:
|
| 226 |
-
|
| 227 |
-
revised =
|
| 228 |
if revised.strip():
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
if not first.strip():raise RuntimeError("المودل لم يولد ردًا")
|
| 241 |
coach={k:v for k,v in plan.items() if v}
|
| 242 |
return {
|
| 243 |
"reply":first.strip(),"style_used":_style_display(style_key),"router_source":router_source,
|
| 244 |
-
"reply_source":"qwen_lora_generated", "style_key":style_key if style_key in {"polite","firm","diplomatic","apology","clarify"} else (selected or "polite"),
|
| 245 |
"generator":self.generator if hasattr(self, "generator") else "Qwen3.5-4B + Saudi LoRA",
|
| 246 |
"coaching":coach,"review_status":"flagged" if flags else ("model_reviewed" if reviewed else "unverified"),
|
| 247 |
"needs_review":bool(flags), "quality_warnings":list(dict.fromkeys(flags)),"was_retried":was_retried,
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
| 249 |
}
|
| 250 |
|
| 251 |
|
|
|
|
| 13 |
"""
|
| 14 |
from __future__ import annotations
|
| 15 |
|
| 16 |
+
from semantic_review import parse_review, review_prompt
|
| 17 |
from difflib import SequenceMatcher
|
| 18 |
import re
|
| 19 |
|
|
|
|
| 20 |
from saudi_register import (
|
| 21 |
SAUDI_EXAMPLES, SAUDI_SYSTEM, clean_writing, explicit_fusha,
|
| 22 |
normalize_saudi, register_instruction, register_warnings, writing_style,
|
|
|
|
| 50 |
def style_instruction(style, goal, message):
|
| 51 |
# Style describes HOW to say it, never replaces WHAT the user needs.
|
| 52 |
defaults = {
|
| 53 |
+
"polite": "نبرة لطيفة ومحترمة. حافظ على كل ما طلبه الشخص، ولا تضف اعتذارا أو وعدا أو طلبا من عندك.",
|
| 54 |
+
"firm": "نبرة واضحة وثابتة باحترام. التزم بنفس حدود المستخدم ونطاقها ومدتها؛ لا تخترع حصة مساعدة أو موعدا أو بديلا.",
|
| 55 |
+
"diplomatic": "نبرة هادئة ومراعية للعلاقة. نفذ مقصد المستخدم كامل بدون افتراض اختلاف آراء أو استبدال طلبه بحوار عام.",
|
| 56 |
+
"clarify": "نبرة استيضاح مهذبة. اطلب نفس التوضيح أو الإجراء اللي يريده المستخدم، ولا تحول طلب تنفيذ إجراء إلى سؤال عن سببه.",
|
| 57 |
+
"apology": "نبرة صادقة ومراعية للأثر. إذا طلب الشخص الاعتذار فاكتب اعتذاره هو، واحفظ تحمله للمسؤولية وحدوده؛ لا تنسب له خطأ أو عذرا غير مذكور.",
|
| 58 |
+
"formal": "نبرة سعودية مهنية ومحترمة، واضحة وطبيعية بدون تكلف، مع حفظ كامل المقصد.",
|
| 59 |
+
"مختصر": "صياغة مختصرة تحفظ كل المطلوب والقيود؛ لا تختصر على حساب المعنى.",
|
| 60 |
}
|
| 61 |
if style in defaults: return defaults[style]
|
| 62 |
return defaults["polite"]
|
|
|
|
| 119 |
return None,""
|
| 120 |
|
| 121 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
def reply_v16(self, message, relation="صديق", goal="أبي رد مناسب وواضح",
|
| 124 |
style="تلقائي", speaker_gender="غير محدد", recipient_gender="غير محدد",
|
|
|
|
| 147 |
"انتبهي: [تفسير خاطئ واحد يجب تجنبه]\n"
|
| 148 |
f"الموقف: {message}\nالعلاقة: {relation}\nهدف المستخدم: {goal}"
|
| 149 |
)
|
| 150 |
+
coaching_error = None
|
| 151 |
+
try:
|
| 152 |
+
plan_raw=self._one_generation([{"role":"user","content":plan_prompt}],use_adapter=False,max_tokens=256)
|
| 153 |
+
except Exception as exc:
|
| 154 |
+
plan_raw=""
|
| 155 |
+
coaching_error=type(exc).__name__
|
| 156 |
plan=parse_plan(plan_raw)
|
| 157 |
# Phase 2: real response by Saudi LoRA. Keep the user's facts as the source of truth.
|
| 158 |
register = register_instruction(relation, style_key, modifier)
|
| 159 |
+
gen_system = getattr(self, "writer_system", SAUDI_SYSTEM)
|
| 160 |
+
selected_examples = getattr(self, "writer_examples", SAUDI_EXAMPLES)
|
| 161 |
+
examples = [] if explicit_fusha(modifier) else [dict(item) for item in selected_examples]
|
| 162 |
style_line=style_instruction(style_key,goal,message)
|
| 163 |
+
def gen_prompt(extra="", reference=""):
|
| 164 |
+
prompt = (
|
|
|
|
| 165 |
f"الموقف: {message}\nالعلاقة: {relation}\nالهدف: {goal}\n"
|
| 166 |
+
f"الأسلوب: {writing_style(style_key, modifier)}\n"
|
| 167 |
+
"اكتب الرسالة للطرف الآخر، واحفظ كل الطلبات والقيود بدون اختصار يضيع المعنى."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
)
|
| 169 |
+
# Faisal's selected action controls tone; original facts and all user
|
| 170 |
+
# requirements stay authoritative, including for a manual override.
|
| 171 |
+
prompt += f"\nطريقة التواصل: {_style_display(style_key)}\n{style_line}"
|
| 172 |
+
if speaker_gender != "غير محدد":
|
| 173 |
+
prompt += f"\nجنس المتحدث: {speaker_gender}"
|
| 174 |
+
if recipient_gender != "غير محدد":
|
| 175 |
+
prompt += f"\nجنس المخاطب: {recipient_gender}"
|
| 176 |
+
if modifier:
|
| 177 |
+
prompt += f"\n{modifier}\nطريقة الكتابة: {register}"
|
| 178 |
+
if reference:
|
| 179 |
+
prompt += (
|
| 180 |
+
"\nنص سابق مطلوب تعديل صياغته فقط، وليس مصدرا للحقائق؛ الموقف والهدف هما الأصل:\n"
|
| 181 |
+
+ reference
|
| 182 |
+
)
|
| 183 |
+
if extra:
|
| 184 |
+
prompt += f"\nملاحظة للمراجعة: {extra}"
|
| 185 |
+
return prompt
|
| 186 |
+
def generate(extra="", retry=False, reference=""):
|
| 187 |
raw = clean_writing(self._one_generation(
|
| 188 |
[{"role":"system","content":gen_system}] + examples
|
| 189 |
+
+ [{"role":"user","content":gen_prompt(extra, reference or (previous if modifier else ""))}], retry=retry, max_tokens=256,
|
| 190 |
), modifier)
|
| 191 |
text, edits = normalize_saudi(raw, modifier, message + " " + goal)
|
| 192 |
+
return {"reply":text,"draft_before_register_normalization":raw,"register_normalization":edits}
|
| 193 |
+
selected_record=generate()
|
| 194 |
+
first=selected_record["reply"]
|
| 195 |
def check(candidate):
|
| 196 |
return list(dict.fromkeys(
|
| 197 |
local_warnings(candidate, message, goal, style_key, previous)
|
| 198 |
+ quality_flags(candidate, relation, goal, message)
|
|
|
|
| 199 |
+ register_warnings(candidate, modifier)
|
| 200 |
))
|
| 201 |
+
# A grounded failure triggers repair regardless of the words used in its reason.
|
| 202 |
+
# This is same-family model feedback, not independent semantic validation.
|
| 203 |
def review(candidate):
|
| 204 |
+
prompt = review_prompt(message, relation, goal, candidate, register)
|
| 205 |
+
raw = self._one_generation([{"role":"user","content":prompt}], use_adapter=False, max_tokens=640)
|
| 206 |
+
return parse_review(raw, message, goal, candidate)
|
| 207 |
+
|
| 208 |
+
def assess(candidate):
|
| 209 |
+
hard = check(candidate)
|
| 210 |
+
try:
|
| 211 |
+
judgment = review(candidate)
|
| 212 |
+
except Exception as exc:
|
| 213 |
+
judgment = {"valid":False,"checks":[],"unsupported":[],"issues":[],
|
| 214 |
+
"error":"review_generation_failed","error_type":type(exc).__name__}
|
| 215 |
+
issues = list(dict.fromkeys(hard + judgment["issues"]))
|
| 216 |
+
return hard, judgment, issues
|
| 217 |
+
|
| 218 |
+
hard, judgment, flags = assess(first)
|
| 219 |
+
attempts = [{**selected_record, "review":judgment, "warnings":flags}]
|
| 220 |
+
was_retried = bool(flags)
|
| 221 |
+
retry_error = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
if was_retried:
|
| 223 |
try:
|
| 224 |
+
revised_record = generate("أصلح الملاحظات مع حفظ كل قيود النص الأصلي: " + "؛ ".join(flags), retry=True, reference=first)
|
| 225 |
+
revised = revised_record["reply"]
|
| 226 |
if revised.strip():
|
| 227 |
+
new_hard, new_judgment, new_flags = assess(revised)
|
| 228 |
+
attempts.append({**revised_record, "review":new_judgment, "warnings":new_flags})
|
| 229 |
+
# An invalid review can never clear a previous grounded concern.
|
| 230 |
+
old_rank = (not judgment["valid"], len(flags))
|
| 231 |
+
new_rank = (not new_judgment["valid"], len(new_flags))
|
| 232 |
+
if not first.strip() or new_rank < old_rank:
|
| 233 |
+
first, hard, judgment, flags = revised, new_hard, new_judgment, new_flags
|
| 234 |
+
selected_record = revised_record
|
| 235 |
+
except Exception as exc:
|
| 236 |
+
retry_error = type(exc).__name__
|
| 237 |
+
reviewed = judgment["valid"] and not judgment["issues"]
|
| 238 |
+
if not judgment["valid"]:
|
| 239 |
+
flags.append("تعذر التحقق من المراجعة الدلالية؛ الصياغة تحتاج مراجعة")
|
| 240 |
+
if retry_error:
|
| 241 |
+
flags.append("لم تكتمل محاولة إعادة الصياغة")
|
| 242 |
if not first.strip():raise RuntimeError("المودل لم يولد ردًا")
|
| 243 |
coach={k:v for k,v in plan.items() if v}
|
| 244 |
return {
|
| 245 |
"reply":first.strip(),"style_used":_style_display(style_key),"router_source":router_source,
|
| 246 |
+
"reply_source":getattr(self,"reply_source","qwen_lora_generated"), "style_key":style_key if style_key in {"polite","firm","diplomatic","apology","clarify"} else (selected or "polite"),
|
| 247 |
"generator":self.generator if hasattr(self, "generator") else "Qwen3.5-4B + Saudi LoRA",
|
| 248 |
"coaching":coach,"review_status":"flagged" if flags else ("model_reviewed" if reviewed else "unverified"),
|
| 249 |
"needs_review":bool(flags), "quality_warnings":list(dict.fromkeys(flags)),"was_retried":was_retried,
|
| 250 |
+
"semantic_review":judgment, "generation_candidates":attempts, "retry_error":retry_error,
|
| 251 |
+
"coaching_status":"model_generated" if coach else "unavailable", "coaching_error":coaching_error,
|
| 252 |
+
"draft_before_register_normalization":selected_record["draft_before_register_normalization"],
|
| 253 |
+
"register_normalization":selected_record["register_normalization"],
|
| 254 |
}
|
| 255 |
|
| 256 |
|
README.md
CHANGED
|
@@ -4,6 +4,7 @@ emoji: 💜
|
|
| 4 |
colorFrom: purple
|
| 5 |
colorTo: pink
|
| 6 |
sdk: gradio
|
|
|
|
| 7 |
app_file: cloud/space_app.py
|
| 8 |
python_version: "3.12"
|
| 9 |
pinned: false
|
|
@@ -13,7 +14,7 @@ pinned: false
|
|
| 13 |
|
| 14 |
Saudi Arabic communication coaching with the V16 interface, original Maha artwork, Qwen3.5-4B with a Saudi pilot LoRA adapter, and the original Faisal decision adapter. Requests use Gradio's queue and Hugging Face ZeroGPU.
|
| 15 |
|
| 16 |
-
The Saudi LoRA v2 candidate completed two epochs locally. Its held-out review found intent and dialect failures, so the pilot remains the configured research baseline. Replies require user review.
|
| 17 |
|
| 18 |
Faisal is Omer Nacar's Jev-inspired Arabic decision model under CC BY-NC 4.0. This Space is an attributed noncommercial research demonstration.
|
| 19 |
|
|
@@ -21,4 +22,4 @@ Configure the private adapter repository and its exact revision as LABEQ_ADAPTER
|
|
| 21 |
|
| 22 |
Source and team credits are at https://github.com/LeenAlaslani/Labeq.
|
| 23 |
|
| 24 |
-
Source commit
|
|
|
|
| 4 |
colorFrom: purple
|
| 5 |
colorTo: pink
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: "6.32.0"
|
| 8 |
app_file: cloud/space_app.py
|
| 9 |
python_version: "3.12"
|
| 10 |
pinned: false
|
|
|
|
| 14 |
|
| 15 |
Saudi Arabic communication coaching with the V16 interface, original Maha artwork, Qwen3.5-4B with a Saudi pilot LoRA adapter, and the original Faisal decision adapter. Requests use Gradio's queue and Hugging Face ZeroGPU.
|
| 16 |
|
| 17 |
+
The Saudi LoRA v2 candidate completed two epochs locally. Its held-out review found intent and dialect failures, so the pilot remains the configured research baseline. A separate completed compositional experiment reached 5/16 strict local diagnostic passes under assistant assessment and was also not promoted. Replies require user review. Detailed methods, unsuccessful outputs and new application screenshots are recorded in the GitHub generalization report.
|
| 18 |
|
| 19 |
Faisal is Omer Nacar's Jev-inspired Arabic decision model under CC BY-NC 4.0. This Space is an attributed noncommercial research demonstration.
|
| 20 |
|
|
|
|
| 22 |
|
| 23 |
Source and team credits are at https://github.com/LeenAlaslani/Labeq.
|
| 24 |
|
| 25 |
+
Source commit eb61c869b169d6a3018fb1814628a3cd567003c8.
|
app.js
CHANGED
|
@@ -8,7 +8,7 @@ const state = {
|
|
| 8 |
hasResult:false, editingScenario:true, mock:true, confidence:null, started:false,
|
| 9 |
voiceOn:true, currentSpeech:'', speechId:0, audio:null, recording:false,
|
| 10 |
recognition:null, recorder:null, audioCtx:null, analyzeBusy:false,
|
| 11 |
-
modelReply:'', modelStyleUsed:'', routerSource:'', replySource:'', needsReview:false, qualityWarnings:[], variantBusy:false, version:0, comparison:null, coaching:{}, reviewStatus:'unverified'
|
| 12 |
};
|
| 13 |
let capabilities={tts:false,stt:false,model_mode:'demo',voice_name:''};
|
| 14 |
let modelHealth={configured:null,reachable:null,model_loaded:null,faisal_loaded:null};
|
|
@@ -313,7 +313,8 @@ function renderResult(){
|
|
| 313 |
$('styleChoices').hidden=true;$('changeStyleBtn').setAttribute('aria-expanded','false');$('nav3').classList.add('active');setContextMood();
|
| 314 |
if(!state.mock){
|
| 315 |
const who=state.routerSource==='faisal'?'الأسلوب اقترحه فيصل':state.routerSource==='rule_fallback'?'الأسلوب حددته قواعد احتياطية':state.routerSource==='user_selected'?'الأسلوب اخترتيه بنفسك':'مصدر الأسلوب غير محدد';
|
| 316 |
-
|
|
|
|
| 317 |
}else{
|
| 318 |
$('confidenceNote').textContent='هذه صياغة تجريبية وليست نتيجة مودل.';
|
| 319 |
}
|
|
@@ -337,7 +338,7 @@ async function requestActualReply({styleKey=null,tone=state.tone,instruction=nul
|
|
| 337 |
return body;
|
| 338 |
}
|
| 339 |
function useRealReply(data,styleFallback=null){
|
| 340 |
-
state.modelReply=data.reply; state.modelStyleUsed=data.style_used||'';
|
| 341 |
state.routerSource=data.router_source||'unknown';state.replySource=data.reply_source||'unknown';
|
| 342 |
state.needsReview=!!data.needs_review;state.qualityWarnings=data.quality_warnings||[];
|
| 343 |
state.coaching=data.coaching||{};state.reviewStatus=data.review_status||'unverified';
|
|
|
|
| 8 |
hasResult:false, editingScenario:true, mock:true, confidence:null, started:false,
|
| 9 |
voiceOn:true, currentSpeech:'', speechId:0, audio:null, recording:false,
|
| 10 |
recognition:null, recorder:null, audioCtx:null, analyzeBusy:false,
|
| 11 |
+
modelReply:'', modelGenerator:'', modelStyleUsed:'', routerSource:'', replySource:'', needsReview:false, qualityWarnings:[], variantBusy:false, version:0, comparison:null, coaching:{}, reviewStatus:'unverified'
|
| 12 |
};
|
| 13 |
let capabilities={tts:false,stt:false,model_mode:'demo',voice_name:''};
|
| 14 |
let modelHealth={configured:null,reachable:null,model_loaded:null,faisal_loaded:null};
|
|
|
|
| 313 |
$('styleChoices').hidden=true;$('changeStyleBtn').setAttribute('aria-expanded','false');$('nav3').classList.add('active');setContextMood();
|
| 314 |
if(!state.mock){
|
| 315 |
const who=state.routerSource==='faisal'?'الأسلوب اقترحه فيصل':state.routerSource==='rule_fallback'?'الأسلوب حددته قواعد احتياطية':state.routerSource==='user_selected'?'الأسلوب اخترتيه بنفسك':'مصدر الأسلوب غير محدد';
|
| 316 |
+
const writer=state.replySource==='qwen_lora_generated'?'Qwen + LoRA':(state.modelGenerator.split('(')[0].trim()||'نموذج اللغة');
|
| 317 |
+
$('confidenceNote').textContent=who+' · الرد من '+writer+' · راجعي المعنى قبل الإرسال'+(state.needsReview?' · رُصدت ملاحظة جودة':'');
|
| 318 |
}else{
|
| 319 |
$('confidenceNote').textContent='هذه صياغة تجريبية وليست نتيجة مودل.';
|
| 320 |
}
|
|
|
|
| 338 |
return body;
|
| 339 |
}
|
| 340 |
function useRealReply(data,styleFallback=null){
|
| 341 |
+
state.modelReply=data.reply; state.modelGenerator=typeof data.generator==='string'?data.generator:''; state.modelStyleUsed=data.style_used||'';
|
| 342 |
state.routerSource=data.router_source||'unknown';state.replySource=data.reply_source||'unknown';
|
| 343 |
state.needsReview=!!data.needs_review;state.qualityWarnings=data.quality_warnings||[];
|
| 344 |
state.coaching=data.coaching||{};state.reviewStatus=data.review_status||'unverified';
|
cloud/space_app.py
CHANGED
|
@@ -9,10 +9,13 @@ sys.path.insert(0, str(ROOT))
|
|
| 9 |
|
| 10 |
def gpu_duration(payload):
|
| 11 |
if not isinstance(payload, dict):
|
| 12 |
-
return
|
| 13 |
length = len(str(payload.get("message", ""))) + len(str(payload.get("goal", "")))
|
| 14 |
length += len(str(payload.get("history", "")))
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
def create_app(engine, gpu_decorator):
|
|
@@ -45,6 +48,7 @@ def create_app(engine, gpu_decorator):
|
|
| 45 |
"faisal_loaded": engine.faisal_ready,
|
| 46 |
"generator": engine.generator,
|
| 47 |
"adapter_revision": engine.adapter_revision,
|
|
|
|
| 48 |
}
|
| 49 |
# The existing FastAPI HTML is the frontend; Gradio only supplies its queue.
|
| 50 |
return gr.mount_gradio_app(app, model_api, path="/model", ssr_mode=False)
|
|
|
|
| 9 |
|
| 10 |
def gpu_duration(payload):
|
| 11 |
if not isinstance(payload, dict):
|
| 12 |
+
return 60
|
| 13 |
length = len(str(payload.get("message", ""))) + len(str(payload.get("goal", "")))
|
| 14 |
length += len(str(payload.get("history", "")))
|
| 15 |
+
# A grounded JSON review has a larger budget than the old one-line review.
|
| 16 |
+
# Reserve enough time for the plan, routing, two drafts and two reviews;
|
| 17 |
+
# this is a reservation, not a measured latency or a paid resource change.
|
| 18 |
+
return 60 if length <= 800 else 90
|
| 19 |
|
| 20 |
|
| 21 |
def create_app(engine, gpu_decorator):
|
|
|
|
| 48 |
"faisal_loaded": engine.faisal_ready,
|
| 49 |
"generator": engine.generator,
|
| 50 |
"adapter_revision": engine.adapter_revision,
|
| 51 |
+
"base_revision": getattr(engine,"base_revision",None),
|
| 52 |
}
|
| 53 |
# The existing FastAPI HTML is the frontend; Gradio only supplies its queue.
|
| 54 |
return gr.mount_gradio_app(app, model_api, path="/model", ssr_mode=False)
|
cloud/torch_engine.py
CHANGED
|
@@ -7,6 +7,7 @@ from labeq_engine import FAISAL_MODEL_ID, LabeqEngine
|
|
| 7 |
|
| 8 |
|
| 9 |
FAISAL_REVISION = "38849bdac4b7850c19587f78f5fe16c38adefac1"
|
|
|
|
| 10 |
|
| 11 |
|
| 12 |
class SpaceEngine(LabeqEngine):
|
|
@@ -21,6 +22,7 @@ class SpaceEngine(LabeqEngine):
|
|
| 21 |
label = os.getenv("LABEQ_ADAPTER_LABEL", "Saudi LoRA pilot")
|
| 22 |
self.generator = f"Qwen3.5-4B + {label} (Transformers, bfloat16)"
|
| 23 |
self.adapter_revision = revision
|
|
|
|
| 24 |
|
| 25 |
def load(self):
|
| 26 |
with self.lock:
|
|
@@ -31,9 +33,9 @@ class SpaceEngine(LabeqEngine):
|
|
| 31 |
from peft import PeftModel
|
| 32 |
|
| 33 |
base_id = "Qwen/Qwen3.5-4B"
|
| 34 |
-
tokenizer = AutoTokenizer.from_pretrained(base_id)
|
| 35 |
base = AutoModelForImageTextToText.from_pretrained(
|
| 36 |
-
base_id, dtype=torch.bfloat16,
|
| 37 |
attn_implementation="eager",
|
| 38 |
)
|
| 39 |
model = PeftModel.from_pretrained(
|
|
|
|
| 7 |
|
| 8 |
|
| 9 |
FAISAL_REVISION = "38849bdac4b7850c19587f78f5fe16c38adefac1"
|
| 10 |
+
BASE_REVISION = "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a"
|
| 11 |
|
| 12 |
|
| 13 |
class SpaceEngine(LabeqEngine):
|
|
|
|
| 22 |
label = os.getenv("LABEQ_ADAPTER_LABEL", "Saudi LoRA pilot")
|
| 23 |
self.generator = f"Qwen3.5-4B + {label} (Transformers, bfloat16)"
|
| 24 |
self.adapter_revision = revision
|
| 25 |
+
self.base_revision = BASE_REVISION
|
| 26 |
|
| 27 |
def load(self):
|
| 28 |
with self.lock:
|
|
|
|
| 33 |
from peft import PeftModel
|
| 34 |
|
| 35 |
base_id = "Qwen/Qwen3.5-4B"
|
| 36 |
+
tokenizer = AutoTokenizer.from_pretrained(base_id,revision=BASE_REVISION)
|
| 37 |
base = AutoModelForImageTextToText.from_pretrained(
|
| 38 |
+
base_id, revision=BASE_REVISION, dtype=torch.bfloat16,
|
| 39 |
attn_implementation="eager",
|
| 40 |
)
|
| 41 |
model = PeftModel.from_pretrained(
|
convert_mlx_to_peft.py
CHANGED
|
@@ -11,11 +11,30 @@ from safetensors.numpy import load_file, save_file
|
|
| 11 |
|
| 12 |
KEY = re.compile(
|
| 13 |
r"language_model\.model\.(layers\.\d+\.(?:mlp\.(?:down_proj|gate_proj|up_proj)"
|
| 14 |
-
r"|self_attn\.(?:q_proj|k_proj|v_proj|o_proj)
|
|
|
|
| 15 |
)
|
| 16 |
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
def convert(source: Path, destination: Path):
|
|
|
|
|
|
|
| 19 |
config = json.loads((source / "adapter_config.json").read_text())
|
| 20 |
parameters = config["lora_parameters"]
|
| 21 |
rank, scale = parameters["rank"], parameters["scale"]
|
|
@@ -42,12 +61,18 @@ def convert(source: Path, destination: Path):
|
|
| 42 |
random = np.random.default_rng(3407)
|
| 43 |
for key, pair in pairs.items():
|
| 44 |
a, b = pair["a"], pair["b"]
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
prefix = f"base_model.model.model.language_model.{key}"
|
| 47 |
peft_a, peft_b = (converted[prefix + f".lora_{side}.weight"] for side in ("A", "B"))
|
| 48 |
np.testing.assert_allclose(
|
| 49 |
-
(x @ a) @ b
|
| 50 |
-
|
|
|
|
| 51 |
)
|
| 52 |
destination.mkdir(parents=True, exist_ok=False)
|
| 53 |
save_file(converted, str(destination / "adapter_model.safetensors"))
|
|
|
|
| 11 |
|
| 12 |
KEY = re.compile(
|
| 13 |
r"language_model\.model\.(layers\.\d+\.(?:mlp\.(?:down_proj|gate_proj|up_proj)"
|
| 14 |
+
r"|self_attn\.(?:q_proj|k_proj|v_proj|o_proj)"
|
| 15 |
+
r"|linear_attn\.(?:in_proj_qkv|out_proj)))\.lora_([ab])"
|
| 16 |
)
|
| 17 |
|
| 18 |
|
| 19 |
+
def expected_shape(path):
|
| 20 |
+
"""Input/output sizes of the supported Qwen3.5-4B language projections."""
|
| 21 |
+
_, layer, kind, suffix = path.split(".")
|
| 22 |
+
if not 0 <= int(layer) < 32:
|
| 23 |
+
raise ValueError("Unexpected Qwen3.5-4B layer index")
|
| 24 |
+
full_attention = int(layer) % 4 == 3
|
| 25 |
+
if kind == "mlp":
|
| 26 |
+
return (9216, 2560) if suffix == "down_proj" else (2560, 9216)
|
| 27 |
+
if kind == "self_attn" and full_attention:
|
| 28 |
+
return {"q_proj":(2560,8192), "k_proj":(2560,1024),
|
| 29 |
+
"v_proj":(2560,1024), "o_proj":(4096,2560)}[suffix]
|
| 30 |
+
if kind == "linear_attn" and not full_attention:
|
| 31 |
+
return {"in_proj_qkv":(2560,8192), "out_proj":(4096,2560)}[suffix]
|
| 32 |
+
raise ValueError("Projection does not match this layer's attention type")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
def convert(source: Path, destination: Path):
|
| 36 |
+
if destination.exists():
|
| 37 |
+
raise FileExistsError(destination)
|
| 38 |
config = json.loads((source / "adapter_config.json").read_text())
|
| 39 |
parameters = config["lora_parameters"]
|
| 40 |
rank, scale = parameters["rank"], parameters["scale"]
|
|
|
|
| 61 |
random = np.random.default_rng(3407)
|
| 62 |
for key, pair in pairs.items():
|
| 63 |
a, b = pair["a"], pair["b"]
|
| 64 |
+
input_size, output_size = expected_shape(key)
|
| 65 |
+
if a.shape != (input_size, rank) or b.shape != (rank, output_size):
|
| 66 |
+
raise ValueError(f"Qwen3.5-4B projection shape mismatch: {key}")
|
| 67 |
+
# Use float64 for this algebra check: BLAS accumulation with a
|
| 68 |
+
# transposed layout can differ in float32 without changing any weight.
|
| 69 |
+
x = random.normal(size=(1, a.shape[0]))
|
| 70 |
prefix = f"base_model.model.model.language_model.{key}"
|
| 71 |
peft_a, peft_b = (converted[prefix + f".lora_{side}.weight"] for side in ("A", "B"))
|
| 72 |
np.testing.assert_allclose(
|
| 73 |
+
(x @ a.astype(np.float64)) @ b.astype(np.float64) * scale,
|
| 74 |
+
(x @ peft_a.astype(np.float64).T) @ peft_b.astype(np.float64).T * (alpha / rank),
|
| 75 |
+
rtol=1e-10, atol=1e-10,
|
| 76 |
)
|
| 77 |
destination.mkdir(parents=True, exist_ok=False)
|
| 78 |
save_file(converted, str(destination / "adapter_model.safetensors"))
|
generation_limits.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Signal incomplete provider output without presenting it as a finished reply."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class GenerationBudgetError(RuntimeError):
|
| 5 |
+
def __init__(self, text):
|
| 6 |
+
super().__init__("Model output exhausted its token budget")
|
| 7 |
+
self.partial_text = text
|
labeq_engine.py
CHANGED
|
@@ -205,7 +205,7 @@ class LabeqEngine:
|
|
| 205 |
finally:
|
| 206 |
self.model.set_adapter("saudi")
|
| 207 |
|
| 208 |
-
def _one_generation(self, messages: list[dict], retry: bool = False, use_adapter: bool = True) -> str:
|
| 209 |
with self.lock:
|
| 210 |
self.model.set_adapter("saudi")
|
| 211 |
inputs = self._inputs(messages)
|
|
@@ -216,7 +216,7 @@ class LabeqEngine:
|
|
| 216 |
if pad is None and hasattr(self.processor, 'tokenizer'):
|
| 217 |
pad = self.processor.tokenizer.pad_token_id
|
| 218 |
gen_kw = {
|
| 219 |
-
"max_new_tokens":
|
| 220 |
"do_sample": retry,
|
| 221 |
"repetition_penalty": 1.08,
|
| 222 |
"pad_token_id": pad if pad is not None else eos,
|
|
@@ -229,7 +229,12 @@ class LabeqEngine:
|
|
| 229 |
outputs = self.model.generate(**inputs, **gen_kw)
|
| 230 |
token_ids = outputs[0, inputs["input_ids"].shape[-1]:]
|
| 231 |
decoder = self.processor.decode if hasattr(self.processor, "decode") else self.processor.tokenizer.decode
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
|
| 234 |
def reply(self, message: str, relation: str = "صديق", goal: str = "أبي رد مناسب وواضح",
|
| 235 |
style: str = "تلقائي", speaker_gender: str = "غير محدد",
|
|
|
|
| 205 |
finally:
|
| 206 |
self.model.set_adapter("saudi")
|
| 207 |
|
| 208 |
+
def _one_generation(self, messages: list[dict], retry: bool = False, use_adapter: bool = True, max_tokens: int = 256) -> str:
|
| 209 |
with self.lock:
|
| 210 |
self.model.set_adapter("saudi")
|
| 211 |
inputs = self._inputs(messages)
|
|
|
|
| 216 |
if pad is None and hasattr(self.processor, 'tokenizer'):
|
| 217 |
pad = self.processor.tokenizer.pad_token_id
|
| 218 |
gen_kw = {
|
| 219 |
+
"max_new_tokens": max_tokens,
|
| 220 |
"do_sample": retry,
|
| 221 |
"repetition_penalty": 1.08,
|
| 222 |
"pad_token_id": pad if pad is not None else eos,
|
|
|
|
| 229 |
outputs = self.model.generate(**inputs, **gen_kw)
|
| 230 |
token_ids = outputs[0, inputs["input_ids"].shape[-1]:]
|
| 231 |
decoder = self.processor.decode if hasattr(self.processor, "decode") else self.processor.tokenizer.decode
|
| 232 |
+
text=finish_reply(decoder(token_ids, skip_special_tokens=True))
|
| 233 |
+
stop_ids=set(eos if isinstance(eos,(list,tuple)) else [eos])
|
| 234 |
+
if len(token_ids)>=max_tokens and int(token_ids[-1]) not in stop_ids:
|
| 235 |
+
from generation_limits import GenerationBudgetError
|
| 236 |
+
raise GenerationBudgetError(text)
|
| 237 |
+
return text
|
| 238 |
|
| 239 |
def reply(self, message: str, relation: str = "صديق", goal: str = "أبي رد مناسب وواضح",
|
| 240 |
style: str = "تلقائي", speaker_gender: str = "غير محدد",
|
local_mlx_server.py
CHANGED
|
@@ -22,12 +22,24 @@ async def lifespan(app):
|
|
| 22 |
if len(secret) < 16:
|
| 23 |
raise RuntimeError("Configure LABEQ_API_KEY or run bash prepare_local.sh")
|
| 24 |
app.state.secret = secret
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
| 26 |
os.getenv("LABEQ_MLX_MODEL", "mlx-community/Qwen3.5-4B-MLX-4bit"),
|
| 27 |
-
os.getenv("LABEQ_MLX_ADAPTER_DIR", str(ROOT / "mlx_adapter")),
|
| 28 |
os.getenv("LABEQ_MLX_FAISAL_DIR") or None,
|
| 29 |
os.getenv("LABEQ_MLX_ADAPTER_LABEL", "Saudi LoRA"),
|
| 30 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
yield
|
| 32 |
|
| 33 |
|
|
@@ -38,9 +50,11 @@ app = FastAPI(title="LABEQ MLX inference", lifespan=lifespan, docs_url=None, red
|
|
| 38 |
def health():
|
| 39 |
engine = getattr(app.state, "engine", None)
|
| 40 |
return {
|
| 41 |
-
"service": "labeq-mac", "status": "online", "backend": "mlx-vlm",
|
| 42 |
-
"model_loaded": engine is not None,
|
|
|
|
| 43 |
"faisal_loaded": bool(engine and engine.faisal_ready),
|
|
|
|
| 44 |
}
|
| 45 |
|
| 46 |
|
|
|
|
| 22 |
if len(secret) < 16:
|
| 23 |
raise RuntimeError("Configure LABEQ_API_KEY or run bash prepare_local.sh")
|
| 24 |
app.state.secret = secret
|
| 25 |
+
backend=os.getenv("LABEQ_WRITER_BACKEND","mlx")
|
| 26 |
+
if backend not in {"mlx","ollama"}:
|
| 27 |
+
raise RuntimeError("LABEQ_WRITER_BACKEND must be mlx or ollama")
|
| 28 |
+
router=MlxEngine(
|
| 29 |
os.getenv("LABEQ_MLX_MODEL", "mlx-community/Qwen3.5-4B-MLX-4bit"),
|
| 30 |
+
os.getenv("LABEQ_MLX_ADAPTER_DIR", str(ROOT / "mlx_adapter")) if backend=="mlx" else None,
|
| 31 |
os.getenv("LABEQ_MLX_FAISAL_DIR") or None,
|
| 32 |
os.getenv("LABEQ_MLX_ADAPTER_LABEL", "Saudi LoRA"),
|
| 33 |
)
|
| 34 |
+
if backend=="ollama":
|
| 35 |
+
from ollama_inference import OllamaEngine
|
| 36 |
+
app.state.engine=OllamaEngine(
|
| 37 |
+
router,os.environ["LABEQ_OLLAMA_MODEL"],
|
| 38 |
+
os.getenv("LABEQ_OLLAMA_URL","http://127.0.0.1:11434"),
|
| 39 |
+
os.getenv("LABEQ_WRITER_POLICY") or None,
|
| 40 |
+
)
|
| 41 |
+
else:
|
| 42 |
+
app.state.engine=router
|
| 43 |
yield
|
| 44 |
|
| 45 |
|
|
|
|
| 50 |
def health():
|
| 51 |
engine = getattr(app.state, "engine", None)
|
| 52 |
return {
|
| 53 |
+
"service": "labeq-mac", "status": "online", "backend": "ollama+mlx-vlm" if engine and hasattr(engine,"model_tag") else "mlx-vlm",
|
| 54 |
+
"model_loaded": engine is not None,
|
| 55 |
+
"adapter_loaded": bool(engine and getattr(engine,"adapters",{}).get("saudi")),
|
| 56 |
"faisal_loaded": bool(engine and engine.faisal_ready),
|
| 57 |
+
"generator": getattr(engine,"generator",None),
|
| 58 |
}
|
| 59 |
|
| 60 |
|
mlx_inference.py
CHANGED
|
@@ -5,6 +5,7 @@ from pathlib import Path
|
|
| 5 |
import re
|
| 6 |
|
| 7 |
from LABEQ_V16_Coaching_Engine import reply_v16
|
|
|
|
| 8 |
from labeq_engine import (
|
| 9 |
FAISAL_OPTIONS, FAISAL_SYSTEM, finish_reply, infer_style_without_faisal, make_faisal_task,
|
| 10 |
)
|
|
@@ -27,9 +28,10 @@ class MlxEngine:
|
|
| 27 |
self.tokenizer = self.processor.tokenizer
|
| 28 |
self.base_layers = {}
|
| 29 |
self.adapters = {"base": {}}
|
| 30 |
-
self.adapters["saudi"] = self._adapter_layers(response_dir)
|
| 31 |
self.faisal_ready = False
|
| 32 |
-
self.generator = f"Qwen3.5-4B + {adapter_label} (MLX 4-bit)"
|
|
|
|
| 33 |
if faisal_dir:
|
| 34 |
try:
|
| 35 |
self.adapters["faisal"] = self._adapter_layers(faisal_dir)
|
|
@@ -132,7 +134,7 @@ class MlxEngine:
|
|
| 132 |
messages, tokenize=False, add_generation_prompt=True, enable_thinking=False,
|
| 133 |
)
|
| 134 |
|
| 135 |
-
def generate(self, messages, adapter, max_tokens=125, temperature=0.0):
|
| 136 |
from mlx_vlm import generate
|
| 137 |
|
| 138 |
with self.select(adapter):
|
|
@@ -140,9 +142,11 @@ class MlxEngine:
|
|
| 140 |
self.model, self.processor, self.render(messages),
|
| 141 |
max_tokens=max_tokens, temperature=temperature, verbose=False,
|
| 142 |
)
|
|
|
|
|
|
|
| 143 |
return finish_reply(result.text)
|
| 144 |
|
| 145 |
-
def _one_generation(self, messages, retry=False, use_adapter=True):
|
| 146 |
-
return self.generate(messages, "saudi" if use_adapter else "base", temperature=0.45 if retry else 0.0)
|
| 147 |
|
| 148 |
reply = reply_v16
|
|
|
|
| 5 |
import re
|
| 6 |
|
| 7 |
from LABEQ_V16_Coaching_Engine import reply_v16
|
| 8 |
+
from generation_limits import GenerationBudgetError
|
| 9 |
from labeq_engine import (
|
| 10 |
FAISAL_OPTIONS, FAISAL_SYSTEM, finish_reply, infer_style_without_faisal, make_faisal_task,
|
| 11 |
)
|
|
|
|
| 28 |
self.tokenizer = self.processor.tokenizer
|
| 29 |
self.base_layers = {}
|
| 30 |
self.adapters = {"base": {}}
|
| 31 |
+
self.adapters["saudi"] = self._adapter_layers(response_dir) if response_dir else {}
|
| 32 |
self.faisal_ready = False
|
| 33 |
+
self.generator = f"Qwen3.5-4B + {adapter_label} (MLX 4-bit)" if response_dir else "Qwen3.5-4B (MLX 4-bit, base)"
|
| 34 |
+
self.reply_source = "qwen_lora_generated" if response_dir else "qwen_base_generated"
|
| 35 |
if faisal_dir:
|
| 36 |
try:
|
| 37 |
self.adapters["faisal"] = self._adapter_layers(faisal_dir)
|
|
|
|
| 134 |
messages, tokenize=False, add_generation_prompt=True, enable_thinking=False,
|
| 135 |
)
|
| 136 |
|
| 137 |
+
def generate(self, messages, adapter, max_tokens=125, temperature=0.0, require_complete=False):
|
| 138 |
from mlx_vlm import generate
|
| 139 |
|
| 140 |
with self.select(adapter):
|
|
|
|
| 142 |
self.model, self.processor, self.render(messages),
|
| 143 |
max_tokens=max_tokens, temperature=temperature, verbose=False,
|
| 144 |
)
|
| 145 |
+
if require_complete and getattr(result,"finish_reason",None)=="length":
|
| 146 |
+
raise GenerationBudgetError(result.text)
|
| 147 |
return finish_reply(result.text)
|
| 148 |
|
| 149 |
+
def _one_generation(self, messages, retry=False, use_adapter=True, max_tokens=256):
|
| 150 |
+
return self.generate(messages, "saudi" if use_adapter else "base", temperature=0.45 if retry else 0.0, max_tokens=max_tokens, require_complete=True)
|
| 151 |
|
| 152 |
reply = reply_v16
|
model_bridge.py
CHANGED
|
@@ -100,9 +100,9 @@ async def remote_reply(payload: dict) -> dict:
|
|
| 100 |
if not isinstance(reply, str) or not reply.strip():
|
| 101 |
raise HTTPException(502, "المودل لم يُرجع نص رد صالحًا.")
|
| 102 |
source = data.get("reply_source", "unknown")
|
| 103 |
-
if source
|
| 104 |
# Explicitly reject curated responses in real-only UI mode.
|
| 105 |
-
raise HTTPException(502, "المودل لم يرجع رد
|
| 106 |
key = data.get("style_key")
|
| 107 |
if not isinstance(key, str) or key not in ALLOWED_KEYS:
|
| 108 |
label = data.get("style_used")
|
|
@@ -124,6 +124,7 @@ async def remote_reply(payload: dict) -> dict:
|
|
| 124 |
if isinstance(register_edits, list) else [],
|
| 125 |
"draft_before_register_normalization": raw_draft[:1200] if isinstance(raw_draft, str) else None,
|
| 126 |
"needs_review": bool(data.get("needs_review", False)),
|
|
|
|
| 127 |
"quality_warnings": [item[:180] for item in warnings if isinstance(item, str)][:5]
|
| 128 |
if isinstance(warnings, list) else [],
|
| 129 |
"generator": data.get("generator") if isinstance(data.get("generator"), str) else None,
|
|
|
|
| 100 |
if not isinstance(reply, str) or not reply.strip():
|
| 101 |
raise HTTPException(502, "المودل لم يُرجع نص رد صالحًا.")
|
| 102 |
source = data.get("reply_source", "unknown")
|
| 103 |
+
if source not in {"qwen_lora_generated","qwen_base_generated","ollama_generated"} or data.get("mock") is True:
|
| 104 |
# Explicitly reject curated responses in real-only UI mode.
|
| 105 |
+
raise HTTPException(502, "المودل لم يرجع ردًا مولدًا من خادم حقيقي مدعوم.")
|
| 106 |
key = data.get("style_key")
|
| 107 |
if not isinstance(key, str) or key not in ALLOWED_KEYS:
|
| 108 |
label = data.get("style_used")
|
|
|
|
| 124 |
if isinstance(register_edits, list) else [],
|
| 125 |
"draft_before_register_normalization": raw_draft[:1200] if isinstance(raw_draft, str) else None,
|
| 126 |
"needs_review": bool(data.get("needs_review", False)),
|
| 127 |
+
"was_retried": data.get("was_retried") is True,
|
| 128 |
"quality_warnings": [item[:180] for item in warnings if isinstance(item, str)][:5]
|
| 129 |
if isinstance(warnings, list) else [],
|
| 130 |
"generator": data.get("generator") if isinstance(data.get("generator"), str) else None,
|
ollama_inference.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real local generation with a configurable Ollama model and separate Faisal routing."""
|
| 2 |
+
import json
|
| 3 |
+
from urllib.parse import urlparse
|
| 4 |
+
from urllib.request import Request, urlopen
|
| 5 |
+
|
| 6 |
+
from LABEQ_V16_Coaching_Engine import reply_v16
|
| 7 |
+
from generation_limits import GenerationBudgetError
|
| 8 |
+
from labeq_engine import finish_reply
|
| 9 |
+
from writing_policy import read_policy
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class OllamaEngine:
|
| 13 |
+
reply_source = "ollama_generated"
|
| 14 |
+
|
| 15 |
+
def __init__(self, router, model, base_url="http://127.0.0.1:11434", policy=None):
|
| 16 |
+
parsed = urlparse(base_url)
|
| 17 |
+
if parsed.username or parsed.password or parsed.query or parsed.fragment:
|
| 18 |
+
raise ValueError("Use an Ollama base URL without credentials, query or fragment")
|
| 19 |
+
if parsed.scheme != "https" and not (
|
| 20 |
+
parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"}
|
| 21 |
+
):
|
| 22 |
+
raise ValueError("Ollama requires HTTPS or loopback HTTP")
|
| 23 |
+
if not isinstance(model, str) or not model.strip():
|
| 24 |
+
raise ValueError("Configure an actual Ollama model tag")
|
| 25 |
+
self.router, self.model_tag, self.base_url = router, model, base_url.rstrip("/")
|
| 26 |
+
details = self._request("/api/show", {"model":model})
|
| 27 |
+
capabilities = details.get("capabilities")
|
| 28 |
+
if capabilities is not None and "completion" not in capabilities:
|
| 29 |
+
raise ValueError("The configured Ollama model cannot generate messages")
|
| 30 |
+
quant = details.get("details", {}).get("quantization_level", "unspecified precision")
|
| 31 |
+
self.generator = f"{model} (Ollama, {quant})"
|
| 32 |
+
if policy:
|
| 33 |
+
self.writer_system,self.writer_examples=read_policy(policy)
|
| 34 |
+
loaded=self._request("/api/generate",{
|
| 35 |
+
"model":model,"keep_alive":300,"options":{"num_ctx":4096},
|
| 36 |
+
})
|
| 37 |
+
if loaded.get("done") is not True:
|
| 38 |
+
raise RuntimeError("Ollama did not finish loading the configured writer")
|
| 39 |
+
|
| 40 |
+
@property
|
| 41 |
+
def model(self):
|
| 42 |
+
return self.router.model
|
| 43 |
+
|
| 44 |
+
@property
|
| 45 |
+
def faisal_ready(self):
|
| 46 |
+
return self.router.faisal_ready
|
| 47 |
+
|
| 48 |
+
def load(self):
|
| 49 |
+
return self
|
| 50 |
+
|
| 51 |
+
def predict_style(self, message, relation, goal):
|
| 52 |
+
return self.router.predict_style(message,relation,goal)
|
| 53 |
+
|
| 54 |
+
def _request(self, endpoint, payload):
|
| 55 |
+
request = Request(
|
| 56 |
+
self.base_url+endpoint, data=json.dumps(payload,ensure_ascii=False).encode("utf-8"),
|
| 57 |
+
headers={"Content-Type":"application/json"}, method="POST",
|
| 58 |
+
)
|
| 59 |
+
with urlopen(request,timeout=120) as response:
|
| 60 |
+
result=json.load(response)
|
| 61 |
+
if not isinstance(result,dict) or result.get("error"):
|
| 62 |
+
raise RuntimeError("Ollama did not return a successful model response")
|
| 63 |
+
return result
|
| 64 |
+
|
| 65 |
+
def _one_generation(self, messages, retry=False, use_adapter=True, max_tokens=256):
|
| 66 |
+
# No response adapter is claimed: the Qwen3.5 Faisal LoRA is used only
|
| 67 |
+
# by the separate router; the configured writer is identified above.
|
| 68 |
+
result=self._request("/api/chat", {
|
| 69 |
+
"model":self.model_tag, "messages":messages, "stream":False, "keep_alive":300,
|
| 70 |
+
"options":{"temperature":0.2 if retry else 0, "seed":3407,
|
| 71 |
+
"num_predict":max_tokens, "num_ctx":4096, "repeat_penalty":1.0},
|
| 72 |
+
})
|
| 73 |
+
self.last_generation={"tokens":result.get("eval_count"),"done_reason":result.get("done_reason"),
|
| 74 |
+
"max_tokens":max_tokens,"model":result.get("model",self.model_tag)}
|
| 75 |
+
text=result.get("message",{}).get("content")
|
| 76 |
+
if not isinstance(text,str) or not text.strip():
|
| 77 |
+
raise RuntimeError("Ollama did not generate a message")
|
| 78 |
+
if result.get("done_reason")=="length":
|
| 79 |
+
raise GenerationBudgetError(text)
|
| 80 |
+
return finish_reply(text)
|
| 81 |
+
|
| 82 |
+
reply=reply_v16
|
semantic_review.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evidence-anchored model diagnostics, not an independent quality certificate."""
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def review_prompt(message, relation, goal, candidate, register):
|
| 6 |
+
return (
|
| 7 |
+
"راجع الرسالة مقابل طلب المستخدم. استخرج كل طلب وقيد مهم من النص الأصلي، "
|
| 8 |
+
"وقيّم كل واحد منفصلا. فرّق بين الفعل المطلوب، والأثر على العلاقة، وما منع المستخدم إضافته. "
|
| 9 |
+
"لا تختزل طلبات متعددة إلى عنوان عام. لا تضف شروطا من عندك ولا تطلب عذرا أو وعدا لم يطلبه المستخدم. "
|
| 10 |
+
"source_quote اقتباس حرفي قصير من الموقف أو الهدف يثبت الشرط. "
|
| 11 |
+
"status إما met أو missing أو contradicted. reason سبب لا يتجاوز 12 كلمة يصف الخلل إن وجد. "
|
| 12 |
+
"unsupported قائمة اقتباسات حرفية من الرسالة تتضمن حقائق أو أعذارا أو وعودا غير مسندة، "
|
| 13 |
+
"وليست مجرد اختلاف في الأسلوب. إذا لا يوجد خلها فارغة. "
|
| 14 |
+
"اكتب JSON فقط بهذا الشكل: "
|
| 15 |
+
'{"checks":[{"source_quote":"...","status":"met","reason":""}],"unsupported":[]}\n'
|
| 16 |
+
f"طريقة الكتابة: {register}\nالموقف: {message}\nالعلاقة: {relation}\nالهدف: {goal}\nالرسالة: {candidate}"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def parse_review(text, message, goal, candidate):
|
| 21 |
+
"""Reject malformed, truncated or ungrounded judgments instead of calling them a pass."""
|
| 22 |
+
result = {"valid":False, "checks":[], "unsupported":[], "issues":[]}
|
| 23 |
+
raw = (text or "").strip()
|
| 24 |
+
if raw.startswith("```json") and raw.endswith("```"):
|
| 25 |
+
raw = raw[7:-3].strip()
|
| 26 |
+
try:
|
| 27 |
+
obj = json.loads(raw)
|
| 28 |
+
if not isinstance(obj,dict) or set(obj)!={"checks","unsupported"}:
|
| 29 |
+
raise ValueError("schema")
|
| 30 |
+
if not isinstance(obj["checks"],list) or not 1 <= len(obj["checks"]) <= 12:
|
| 31 |
+
raise ValueError("checks")
|
| 32 |
+
if not isinstance(obj["unsupported"],list) or len(obj["unsupported"])>8:
|
| 33 |
+
raise ValueError("unsupported")
|
| 34 |
+
source = message + "\n" + goal
|
| 35 |
+
seen = set()
|
| 36 |
+
for check in obj["checks"]:
|
| 37 |
+
if not isinstance(check,dict) or set(check)!={"source_quote","status","reason"}:
|
| 38 |
+
raise ValueError("check schema")
|
| 39 |
+
quote,status,reason = (check[k] for k in ("source_quote","status","reason"))
|
| 40 |
+
if not all(isinstance(x,str) for x in (quote,status,reason)):
|
| 41 |
+
raise ValueError("types")
|
| 42 |
+
if len(quote.strip())<4 or quote not in source or quote in seen:
|
| 43 |
+
raise ValueError("ungrounded or duplicated source")
|
| 44 |
+
if status not in {"met","missing","contradicted"} or len(reason)>220:
|
| 45 |
+
raise ValueError("status or reason")
|
| 46 |
+
if status!="met" and not reason.strip():
|
| 47 |
+
raise ValueError("missing reason")
|
| 48 |
+
seen.add(quote)
|
| 49 |
+
if any(not isinstance(q,str) or len(q.strip())<4 or q not in candidate for q in obj["unsupported"]):
|
| 50 |
+
raise ValueError("ungrounded candidate quote")
|
| 51 |
+
issues = [f"{c['source_quote']}: {c['reason']}" for c in obj["checks"] if c["status"]!="met"]
|
| 52 |
+
issues += ["تفصيل غير مسند في الرسالة: " + q for q in obj["unsupported"]]
|
| 53 |
+
result.update(valid=True,checks=obj["checks"],unsupported=obj["unsupported"],issues=issues)
|
| 54 |
+
except (ValueError, TypeError, KeyError):
|
| 55 |
+
result["error"]="invalid_or_ungrounded_review"
|
| 56 |
+
return result
|
source-manifest.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
{
|
| 2 |
-
"source_commit": "
|
| 3 |
"files_sha256": {
|
| 4 |
-
"LABEQ_V15_Goal_Fix.py": "
|
| 5 |
-
"LABEQ_V16_Coaching_Engine.py": "
|
| 6 |
"LICENSE-CODE": "38c1be7cee10dad65385c859f6ea823b77d97485f49e8114e314e175201e4421",
|
| 7 |
-
"README.md": "
|
| 8 |
-
"app.js": "
|
| 9 |
"app.py": "3258967735045064db7997c5e0153288b124760c8c3409dc5363f9b24aa058e8",
|
| 10 |
"assets/expression_greet.jpg": "b37ac1f4108d980c48c7224f592dc325abed93a4d554a95311dcc25f3350f679",
|
| 11 |
"assets/expression_happy.jpg": "be420f063a2f5997cdc280b56f241021e2ad0f0600f7092174dd04f81f3da7b8",
|
|
@@ -21,30 +21,34 @@
|
|
| 21 |
"assets/maha_mouth_clean_overlay.png": "1e814cfda52cafde46c85bb18d3bc309264d1c3a78d114cc93644961a2e71d82",
|
| 22 |
"assets/maha_mouth_open.png": "f07f6f2c1686c9401d0744bdbf639b446cd57feea946d4c96cc30dcaddaa3536",
|
| 23 |
"character2d.js": "0f87c3cfd32bf0e22a2d6de7c7d69f0c6392bb0d07a3eed69ed9d9bd2ce915b7",
|
| 24 |
-
"cloud/space_app.py": "
|
| 25 |
-
"cloud/torch_engine.py": "
|
| 26 |
"coach.js": "2723a3d7fc45c7f3ebdbf79466809245515ab5ec244fa75657c2a5def79f62b6",
|
| 27 |
"configure_model.py": "9b4421816e5919487dd46d6e37c6282161d5c129793cccca2a1431ab031bf1af",
|
| 28 |
-
"convert_mlx_to_peft.py": "
|
| 29 |
"convert_peft_to_mlx.py": "e38de40c0f0342530a74ddef34529f58fe894e4d6bfbefa18719c6496c2e8f4c",
|
| 30 |
"faisal_adapter.example.py": "b505c29e61ef6047731d190476158c119ef7787ec95f95c52f6775bc87432ba2",
|
|
|
|
| 31 |
"index.html": "2e05d29ea5f4e4b2b280188f5b35321341a4f7a517b56dd23132ab018091d709",
|
| 32 |
"labeq_api.py": "71d550a8c92fe7edab6d05d082b05141c2280d792fdf239c885922aa87d965b9",
|
| 33 |
-
"labeq_engine.py": "
|
| 34 |
"labeq_v4_core.py": "110efdaa86df0ebfcfa312d44a39a0f60f3355fc7fe31c303f5a4f3c35889b8e",
|
| 35 |
-
"local_mlx_server.py": "
|
| 36 |
-
"mlx_inference.py": "
|
| 37 |
-
"model_bridge.py": "
|
|
|
|
| 38 |
"requirements.txt": "cb053ad4286f10d752964cf9f655bc156b0e8e17300e61e65bdf3f062c352b2f",
|
| 39 |
"saudi_register.py": "4b1ba98df5537a65060e568159902e063198490250f4631ccd965692dd41b202",
|
|
|
|
| 40 |
"setup_azure.py": "841c137e5cf11b87eabc09b8869c21908dfacd4ef8cbec5a1e9f53b626259759",
|
| 41 |
"setup_local.py": "2c0673ce4d42de968749eec1528ea2b66ba75b8bba2000a03627921acac7684b",
|
| 42 |
"setup_munsit.py": "72c4ba53da15feff1d67bae60f7d168501705395ae05f1a2450309e4fe0cbe63",
|
| 43 |
-
"space_client.js": "
|
| 44 |
"styles.css": "de8cb891839f0d2824aeca85a198937d6cc0ce8f18a4316f00e1fd168ed3f57d",
|
| 45 |
"verify_azure.py": "a38f440518774349dc5d0da82d565cae31ad9757787e33c05288f1f20f4b777c",
|
| 46 |
"verify_local_model.py": "17781339bb6c6ecd2596df4fc375c99b882e54d682e213d689c889f43789ed2f",
|
| 47 |
"verify_model_connection.py": "3805c6e35202c837314bed57ecfbf31328f99e9d498df253fa5c82d5a69d99ae",
|
| 48 |
-
"verify_munsit.py": "7026b2a28d5a52823d0d6bcbb18e791cbb2ef2b1c32d3047800e3efa25cc8dd3"
|
|
|
|
| 49 |
}
|
| 50 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"source_commit": "eb61c869b169d6a3018fb1814628a3cd567003c8",
|
| 3 |
"files_sha256": {
|
| 4 |
+
"LABEQ_V15_Goal_Fix.py": "2d14bd8e222abe13ffdcb1a045dadab4e696a1a946ba7ad64efb1edcda939e19",
|
| 5 |
+
"LABEQ_V16_Coaching_Engine.py": "37f80a1954bf999d39f49f799c911299931dde47dd3e3372642a8eaf27ecd550",
|
| 6 |
"LICENSE-CODE": "38c1be7cee10dad65385c859f6ea823b77d97485f49e8114e314e175201e4421",
|
| 7 |
+
"README.md": "dd18e32265b5c91e8d1ccddb70b425f55c0c3031132beef22a1e633d4a52bb26",
|
| 8 |
+
"app.js": "8d78671f222ad6dfdf98bafa8cd5ebbfa1ed1feb16e9dbc25b34d6646b151240",
|
| 9 |
"app.py": "3258967735045064db7997c5e0153288b124760c8c3409dc5363f9b24aa058e8",
|
| 10 |
"assets/expression_greet.jpg": "b37ac1f4108d980c48c7224f592dc325abed93a4d554a95311dcc25f3350f679",
|
| 11 |
"assets/expression_happy.jpg": "be420f063a2f5997cdc280b56f241021e2ad0f0600f7092174dd04f81f3da7b8",
|
|
|
|
| 21 |
"assets/maha_mouth_clean_overlay.png": "1e814cfda52cafde46c85bb18d3bc309264d1c3a78d114cc93644961a2e71d82",
|
| 22 |
"assets/maha_mouth_open.png": "f07f6f2c1686c9401d0744bdbf639b446cd57feea946d4c96cc30dcaddaa3536",
|
| 23 |
"character2d.js": "0f87c3cfd32bf0e22a2d6de7c7d69f0c6392bb0d07a3eed69ed9d9bd2ce915b7",
|
| 24 |
+
"cloud/space_app.py": "10debd86055bd2cc8e3f05def277d8b4222bc8fa4f347f53e7764b627b8aa921",
|
| 25 |
+
"cloud/torch_engine.py": "fe8dd7e3582c0a168d80b6b89301b9c1226098b5679e6cd25c880b112ccf8d74",
|
| 26 |
"coach.js": "2723a3d7fc45c7f3ebdbf79466809245515ab5ec244fa75657c2a5def79f62b6",
|
| 27 |
"configure_model.py": "9b4421816e5919487dd46d6e37c6282161d5c129793cccca2a1431ab031bf1af",
|
| 28 |
+
"convert_mlx_to_peft.py": "110cdf6ed87a6b66392d66782ee7eda8586f2fdcd063f28c5dcc203ff43cac67",
|
| 29 |
"convert_peft_to_mlx.py": "e38de40c0f0342530a74ddef34529f58fe894e4d6bfbefa18719c6496c2e8f4c",
|
| 30 |
"faisal_adapter.example.py": "b505c29e61ef6047731d190476158c119ef7787ec95f95c52f6775bc87432ba2",
|
| 31 |
+
"generation_limits.py": "ebc97df254abc6582300adf8feb38aee4369119666624c372bd059a7c036d7dc",
|
| 32 |
"index.html": "2e05d29ea5f4e4b2b280188f5b35321341a4f7a517b56dd23132ab018091d709",
|
| 33 |
"labeq_api.py": "71d550a8c92fe7edab6d05d082b05141c2280d792fdf239c885922aa87d965b9",
|
| 34 |
+
"labeq_engine.py": "b3168444ea8c9eb706d6407478fed44eaed67acae6fb4ded19b997a4ec7e81f1",
|
| 35 |
"labeq_v4_core.py": "110efdaa86df0ebfcfa312d44a39a0f60f3355fc7fe31c303f5a4f3c35889b8e",
|
| 36 |
+
"local_mlx_server.py": "0831277e4c1d7a97636a6ae89eeaa05b69c70ba98534628b76fe6fb5545c5348",
|
| 37 |
+
"mlx_inference.py": "27f7c824255f91863a2552faeaf820c040b8f3e792269953a0e7bfb75bcc5e2c",
|
| 38 |
+
"model_bridge.py": "3c0fa6081ebd9032a5a2194183fd2d759b57afddb5b5579814d0ecea0046343c",
|
| 39 |
+
"ollama_inference.py": "4aa22f3a8ec8503bbb75a895f79f6a5e4aefd8d3737cf969c84a973e0465f2ec",
|
| 40 |
"requirements.txt": "cb053ad4286f10d752964cf9f655bc156b0e8e17300e61e65bdf3f062c352b2f",
|
| 41 |
"saudi_register.py": "4b1ba98df5537a65060e568159902e063198490250f4631ccd965692dd41b202",
|
| 42 |
+
"semantic_review.py": "83c1f90dca89eecfc37f33bce6f967c7b189b077a8997d2c1bac860e5dd02fe8",
|
| 43 |
"setup_azure.py": "841c137e5cf11b87eabc09b8869c21908dfacd4ef8cbec5a1e9f53b626259759",
|
| 44 |
"setup_local.py": "2c0673ce4d42de968749eec1528ea2b66ba75b8bba2000a03627921acac7684b",
|
| 45 |
"setup_munsit.py": "72c4ba53da15feff1d67bae60f7d168501705395ae05f1a2450309e4fe0cbe63",
|
| 46 |
+
"space_client.js": "61967f5e56fe0010c4b2b502c40a6e3ea457b3e9de4bc63235cc0c3f32b6b00c",
|
| 47 |
"styles.css": "de8cb891839f0d2824aeca85a198937d6cc0ce8f18a4316f00e1fd168ed3f57d",
|
| 48 |
"verify_azure.py": "a38f440518774349dc5d0da82d565cae31ad9757787e33c05288f1f20f4b777c",
|
| 49 |
"verify_local_model.py": "17781339bb6c6ecd2596df4fc375c99b882e54d682e213d689c889f43789ed2f",
|
| 50 |
"verify_model_connection.py": "3805c6e35202c837314bed57ecfbf31328f99e9d498df253fa5c82d5a69d99ae",
|
| 51 |
+
"verify_munsit.py": "7026b2a28d5a52823d0d6bcbb18e791cbb2ef2b1c32d3047800e3efa25cc8dd3",
|
| 52 |
+
"writing_policy.py": "8454520b31b61e3a2041df615ad62a7e720f62d7c0dd338c6ab1a2ca6b2d1fa7"
|
| 53 |
}
|
| 54 |
}
|
space_client.js
CHANGED
|
@@ -48,7 +48,7 @@ window.labeqSpaceReply=async function(payload){
|
|
| 48 |
}
|
| 49 |
if(event==='complete'){
|
| 50 |
const result=JSON.parse(data)?.[0];
|
| 51 |
-
if(!result||result.
|
| 52 |
return {...result,style:result.style_key,mock:false};
|
| 53 |
}
|
| 54 |
}
|
|
|
|
| 48 |
}
|
| 49 |
if(event==='complete'){
|
| 50 |
const result=JSON.parse(data)?.[0];
|
| 51 |
+
if(!result||typeof result.reply!=='string'||!result.reply.trim()||!['qwen_lora_generated','qwen_base_generated','ollama_generated'].includes(result.reply_source)||result.mock===true)throw Error('رجع المودل استجابة غير صالحة.');
|
| 52 |
return {...result,style:result.style_key,mock:false};
|
| 53 |
}
|
| 54 |
}
|
writing_policy.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read a writing prompt policy without executing code or loading model weights."""
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def read_policy(path):
|
| 7 |
+
settings=json.loads(Path(path).read_text(encoding="utf-8"))
|
| 8 |
+
system,examples=settings.get("system"),settings.get("examples",[])
|
| 9 |
+
if not isinstance(system,str) or not system.strip() or not isinstance(examples,list):
|
| 10 |
+
raise ValueError("Writing policy must have a system string and an examples list")
|
| 11 |
+
if len(examples)>10 or len(examples)%2:
|
| 12 |
+
raise ValueError("Writing examples must be at most five complete pairs")
|
| 13 |
+
for i,example in enumerate(examples):
|
| 14 |
+
if not isinstance(example,dict) or example.get("role")!=("user" if i%2==0 else "assistant"):
|
| 15 |
+
raise ValueError("Writing examples must alternate user and assistant")
|
| 16 |
+
if not isinstance(example.get("content"),str) or not example["content"].strip():
|
| 17 |
+
raise ValueError("Writing examples must contain text")
|
| 18 |
+
return system,[{"role":e["role"],"content":e["content"]} for e in examples]
|