Spaces:
Running on Zero
Running on Zero
Deploy LABEQ source 9c02faa425e7 on ZeroGPU
Browse files- LABEQ_V16_Coaching_Engine.py +2 -1
- README.md +4 -2
- app.py +1 -1
- cloud/cpu_engine.py +116 -0
- cloud/cpu_space_app.py +26 -0
- cloud/space_app.py +27 -3
- grounded_review.py +44 -0
- labeq_engine.py +1 -1
- local_mlx_server.py +3 -0
- mlx_inference.py +3 -0
- requirements.txt +8 -5
- semantic_review.py +14 -2
- source-manifest.json +17 -11
- space_client.js +2 -2
- training/generalization_v3/policy.json +5 -0
LABEQ_V16_Coaching_Engine.py
CHANGED
|
@@ -201,7 +201,8 @@ def reply_v16(self, message, relation="صديق", goal="أبي رد مناسب
|
|
| 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 |
-
|
|
|
|
| 205 |
raw = self._one_generation([{"role":"user","content":prompt}], use_adapter=False, max_tokens=640)
|
| 206 |
return parse_review(raw, message, goal, candidate)
|
| 207 |
|
|
|
|
| 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 |
+
builder=getattr(self,"review_prompt_builder",review_prompt)
|
| 205 |
+
prompt = builder(message, relation, goal, candidate, register)
|
| 206 |
raw = self._one_generation([{"role":"user","content":prompt}], use_adapter=False, max_tokens=640)
|
| 207 |
return parse_review(raw, message, goal, candidate)
|
| 208 |
|
README.md
CHANGED
|
@@ -5,7 +5,7 @@ colorFrom: purple
|
|
| 5 |
colorTo: pink
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: "6.32.0"
|
| 8 |
-
app_file: cloud/
|
| 9 |
python_version: "3.12"
|
| 10 |
pinned: false
|
| 11 |
---
|
|
@@ -22,4 +22,6 @@ Configure the private adapter repository and its exact revision as LABEQ_ADAPTER
|
|
| 22 |
|
| 23 |
Source and team credits are at https://github.com/LeenAlaslani/Labeq.
|
| 24 |
|
| 25 |
-
|
|
|
|
|
|
|
|
|
| 5 |
colorTo: pink
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: "6.32.0"
|
| 8 |
+
app_file: cloud/cpu_space_app.py
|
| 9 |
python_version: "3.12"
|
| 10 |
pinned: false
|
| 11 |
---
|
|
|
|
| 22 |
|
| 23 |
Source and team credits are at https://github.com/LeenAlaslani/Labeq.
|
| 24 |
|
| 25 |
+
Backend: actual CPU Qwen/Faisal at /reply; optional real ZeroGPU inference at /reply_gpu. CPU transport does not establish reply quality.
|
| 26 |
+
|
| 27 |
+
Source commit 9c02faa425e7142408a7c79f5ec5848ca189d672.
|
app.py
CHANGED
|
@@ -45,7 +45,7 @@ MODEL_MODE = os.environ.get("LABEQ_MODEL_MODE", "real" if configured() else "dem
|
|
| 45 |
|
| 46 |
app = FastAPI(title="LABEQ Experience", version="0.1.0")
|
| 47 |
REQUEST_LIMIT = max(0, int(os.getenv("LABEQ_REQUESTS_PER_MINUTE", "30")))
|
| 48 |
-
LIMITED_PATHS = {"/api/reply", "/api/predict", "/api/speak", "/api/transcribe", "/model/gradio_api/call/reply"}
|
| 49 |
request_windows = OrderedDict()
|
| 50 |
|
| 51 |
|
|
|
|
| 45 |
|
| 46 |
app = FastAPI(title="LABEQ Experience", version="0.1.0")
|
| 47 |
REQUEST_LIMIT = max(0, int(os.getenv("LABEQ_REQUESTS_PER_MINUTE", "30")))
|
| 48 |
+
LIMITED_PATHS = {"/api/reply", "/api/predict", "/api/speak", "/api/transcribe", "/model/gradio_api/call/reply", "/model/gradio_api/call/reply_gpu"}
|
| 49 |
request_windows = OrderedDict()
|
| 50 |
|
| 51 |
|
cloud/cpu_engine.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pinned Qwen/Faisal CPU serving with optional real ZeroGPU acceleration.
|
| 2 |
+
|
| 3 |
+
No model choice or adapter promotion is implied by this transport. Private QA
|
| 4 |
+
uses local adapter files; a qualified public deployment can use the existing
|
| 5 |
+
private adapter repository and its already configured Hub read access.
|
| 6 |
+
"""
|
| 7 |
+
from contextlib import nullcontext
|
| 8 |
+
import hashlib
|
| 9 |
+
from importlib.metadata import version
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
from huggingface_hub import snapshot_download
|
| 16 |
+
from cloud.torch_engine import BASE_REVISION,FAISAL_REVISION
|
| 17 |
+
from generation_limits import GenerationBudgetError
|
| 18 |
+
from labeq_engine import LabeqEngine,FAISAL_MODEL_ID,FAISAL_SYSTEM,FAISAL_OPTIONS,make_faisal_task,infer_style_without_faisal,finish_reply
|
| 19 |
+
from writing_policy import read_policy
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ConfiguredTorchEngine(LabeqEngine):
|
| 23 |
+
def __init__(self,device='cpu'):
|
| 24 |
+
if device not in {'cpu','cuda'}:raise ValueError('Expected CPU or CUDA')
|
| 25 |
+
directory=os.getenv('LABEQ_LOCAL_ADAPTER_DIR')
|
| 26 |
+
if directory:
|
| 27 |
+
directory=Path(directory)
|
| 28 |
+
revision=os.getenv('LABEQ_ADAPTER_REVISION','local-private-QA')
|
| 29 |
+
else:
|
| 30 |
+
revision=os.environ['LABEQ_ADAPTER_REVISION']
|
| 31 |
+
directory=Path(snapshot_download(os.environ['LABEQ_ADAPTER_REPO'],revision=revision,
|
| 32 |
+
allow_patterns=['adapter_config.json','adapter_model.safetensors']))
|
| 33 |
+
for filename in ['adapter_config.json','adapter_model.safetensors']:
|
| 34 |
+
if not (directory/filename).is_file():raise FileNotFoundError(filename)
|
| 35 |
+
config=json.loads((directory/'adapter_config.json').read_text())
|
| 36 |
+
if config.get('base_model_name_or_path') not in {'Qwen/Qwen3.5-4B','unsloth/Qwen3.5-4B'}:
|
| 37 |
+
raise ValueError('This backend requires a compatible Qwen3.5-4B adapter')
|
| 38 |
+
super().__init__(directory,use_faisal=True)
|
| 39 |
+
self.device_name=device;self.compute_backend='torch-cpu' if device=='cpu' else 'zerogpu-cuda'
|
| 40 |
+
self.adapter_revision=revision;self.base_revision=BASE_REVISION;self.faisal_revision=FAISAL_REVISION
|
| 41 |
+
digest=hashlib.sha256()
|
| 42 |
+
with (directory/'adapter_model.safetensors').open('rb') as stream:
|
| 43 |
+
while block:=stream.read(1024*1024):digest.update(block)
|
| 44 |
+
self.adapter_sha256=digest.hexdigest()
|
| 45 |
+
label=os.getenv('LABEQ_ADAPTER_LABEL','Saudi pilot LoRA')
|
| 46 |
+
self.generator=f'Qwen3.5-4B + {label} (Transformers, bfloat16, {device})'
|
| 47 |
+
policy=os.getenv('LABEQ_WRITER_POLICY')
|
| 48 |
+
if policy:self.writer_system,self.writer_examples=read_policy(policy)
|
| 49 |
+
self.writer_policy_sha256=hashlib.sha256(Path(policy).read_bytes()).hexdigest() if policy else None
|
| 50 |
+
self.repetition_penalty=float(os.getenv('LABEQ_REPETITION_PENALTY','1.08'))
|
| 51 |
+
if not 1<=self.repetition_penalty<=1.3:raise ValueError('Unsupported repetition penalty')
|
| 52 |
+
self.deadline=0
|
| 53 |
+
self.environment_versions={name:version(name) for name in ['torch','transformers','peft','gradio','spaces','huggingface_hub','accelerate','safetensors']}
|
| 54 |
+
|
| 55 |
+
def load(self):
|
| 56 |
+
with self.lock:
|
| 57 |
+
if self.model is None:
|
| 58 |
+
import torch
|
| 59 |
+
from transformers import AutoModelForImageTextToText,AutoTokenizer
|
| 60 |
+
from peft import PeftModel
|
| 61 |
+
torch.set_num_threads(8)
|
| 62 |
+
tokenizer=AutoTokenizer.from_pretrained('Qwen/Qwen3.5-4B',revision=BASE_REVISION)
|
| 63 |
+
base=AutoModelForImageTextToText.from_pretrained('Qwen/Qwen3.5-4B',revision=BASE_REVISION,
|
| 64 |
+
dtype=torch.bfloat16,attn_implementation='eager',device_map='cpu')
|
| 65 |
+
model=PeftModel.from_pretrained(base,str(self.adapter_dir),adapter_name='saudi',is_trainable=False,torch_device='cpu')
|
| 66 |
+
model.load_adapter(FAISAL_MODEL_ID,adapter_name='faisal',subfolder='adapter',revision=FAISAL_REVISION,is_trainable=False,torch_device='cpu')
|
| 67 |
+
model.to(self.device_name);model.set_adapter('saudi');model.eval()
|
| 68 |
+
self.torch,self.model,self.processor=torch,model,tokenizer
|
| 69 |
+
self.faisal_ready=True
|
| 70 |
+
# reply_v16 calls load at the start; generation never resets this budget.
|
| 71 |
+
self.deadline=time.monotonic()+135
|
| 72 |
+
self.generation_trace=[]
|
| 73 |
+
return self
|
| 74 |
+
|
| 75 |
+
def predict_style(self,message,relation,goal):
|
| 76 |
+
self.load()
|
| 77 |
+
with self.lock:
|
| 78 |
+
try:
|
| 79 |
+
self.model.set_adapter('faisal')
|
| 80 |
+
inputs=self._inputs([{'role':'system','content':FAISAL_SYSTEM},
|
| 81 |
+
{'role':'user','content':json.dumps(make_faisal_task(message,relation,goal),ensure_ascii=False,separators=(',',':'))}])
|
| 82 |
+
ids=[self.processor.encode(chr(65+i),add_special_tokens=False) for i in range(len(FAISAL_OPTIONS))]
|
| 83 |
+
if any(len(x)!=1 for x in ids):raise ValueError('Faisal letters must be single tokens')
|
| 84 |
+
with self.torch.inference_mode():scores=self.model(**inputs,logits_to_keep=1).logits[0,-1,[x[0] for x in ids]]
|
| 85 |
+
style=FAISAL_OPTIONS[int(scores.argmax().item())][0]
|
| 86 |
+
if style!='insufficient':return style,'faisal'
|
| 87 |
+
except Exception as exc:self.faisal_error=type(exc).__name__
|
| 88 |
+
finally:self.model.set_adapter('saudi')
|
| 89 |
+
return infer_style_without_faisal(message,goal),'rule_fallback'
|
| 90 |
+
|
| 91 |
+
def _one_generation(self,messages,retry=False,use_adapter=True,max_tokens=256):
|
| 92 |
+
if self.device_name=='cuda':return super()._one_generation(messages,retry,use_adapter,max_tokens)
|
| 93 |
+
with self.lock:
|
| 94 |
+
remaining=self.deadline-time.monotonic()
|
| 95 |
+
if remaining<=1:raise TimeoutError('CPU reply budget exhausted')
|
| 96 |
+
phase_budget=45 if use_adapter else (30 if max_tokens<=256 else 40)
|
| 97 |
+
self.model.set_adapter('saudi');inputs=self._inputs(messages)
|
| 98 |
+
eos=self.processor.eos_token_id;stop_ids=set(eos if isinstance(eos,(list,tuple)) else [eos])
|
| 99 |
+
options={'max_new_tokens':max_tokens,'max_time':min(phase_budget,remaining-1),
|
| 100 |
+
'do_sample':retry,'repetition_penalty':self.repetition_penalty,'pad_token_id':eos,'eos_token_id':eos,'forced_eos_token_id':None}
|
| 101 |
+
if retry:options.update(temperature=.45,top_p=.85)
|
| 102 |
+
context=nullcontext() if use_adapter else self.model.disable_adapter()
|
| 103 |
+
start=time.monotonic()
|
| 104 |
+
with context,self.torch.inference_mode():outputs=self.model.generate(**inputs,**options)
|
| 105 |
+
ids=outputs[0,inputs['input_ids'].shape[-1]:]
|
| 106 |
+
text=finish_reply(self.processor.decode(ids,skip_special_tokens=True))
|
| 107 |
+
complete=bool(len(ids)) and int(ids[-1]) in stop_ids
|
| 108 |
+
self.last_generation={'generation_tokens':len(ids),'seconds':time.monotonic()-start,
|
| 109 |
+
'finish_reason':'stop' if complete else 'budget','compute_backend':self.compute_backend,
|
| 110 |
+
'phase':'writer' if use_adapter else ('plan' if max_tokens<=256 else 'review'),
|
| 111 |
+
'max_tokens':max_tokens,'max_seconds':options['max_time'],
|
| 112 |
+
'decoded_text':self.processor.decode(ids,skip_special_tokens=True)}
|
| 113 |
+
self.generation_trace.append(dict(self.last_generation))
|
| 114 |
+
if not complete:raise GenerationBudgetError(text)
|
| 115 |
+
if not text:raise RuntimeError('CPU model returned empty text')
|
| 116 |
+
return text
|
cloud/cpu_space_app.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Original LABEQ UI with actual CPU inference and a separate real GPU API."""
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 7 |
+
sys.path.insert(0,str(ROOT))
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def main():
|
| 11 |
+
# The optional real GPU engine needs ZeroGPU emulation before torch imports.
|
| 12 |
+
import spaces
|
| 13 |
+
import uvicorn
|
| 14 |
+
from cloud.cpu_engine import ConfiguredTorchEngine
|
| 15 |
+
from cloud.space_app import create_app
|
| 16 |
+
os.environ['LABEQ_MODEL_MODE']='real'
|
| 17 |
+
cpu=ConfiguredTorchEngine('cpu');gpu=ConfiguredTorchEngine('cuda')
|
| 18 |
+
app=create_app(cpu,lambda function:function,gpu_engine=gpu,max_queue_size=1)
|
| 19 |
+
print('LABEQ: loading actual CPU Qwen, Saudi adapter and Faisal',flush=True)
|
| 20 |
+
cpu.load();gpu.load()
|
| 21 |
+
app.state.gradio_model.update(model_loaded=True,faisal_loaded=cpu.faisal_ready)
|
| 22 |
+
print('LABEQ: CPU reply API ready; optional real GPU endpoint available',flush=True)
|
| 23 |
+
uvicorn.run(app,host='0.0.0.0',port=int(os.getenv('GRADIO_SERVER_PORT',os.getenv('PORT','7860'))))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if __name__=='__main__':main()
|
cloud/space_app.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
"""Serve V16 unchanged at / with queued Gradio callbacks on ZeroGPU."""
|
| 2 |
import os
|
|
|
|
| 3 |
from pathlib import Path
|
| 4 |
import sys
|
| 5 |
|
|
@@ -18,7 +19,7 @@ def gpu_duration(payload):
|
|
| 18 |
return 60 if length <= 800 else 90
|
| 19 |
|
| 20 |
|
| 21 |
-
def create_app(engine, gpu_decorator):
|
| 22 |
import gradio as gr
|
| 23 |
|
| 24 |
from app import app
|
|
@@ -28,11 +29,23 @@ def create_app(engine, gpu_decorator):
|
|
| 28 |
@gpu_decorator
|
| 29 |
def generate(payload):
|
| 30 |
request = ReplyRequest.model_validate(payload)
|
| 31 |
-
|
| 32 |
engine, request.message, request.relation, request.goal, request.style,
|
| 33 |
request.speaker_gender, request.recipient_gender,
|
| 34 |
[turn.model_dump() for turn in request.history], request.generation_mode,
|
| 35 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
with gr.Blocks(title="LABEQ model API") as model_api:
|
| 38 |
request = gr.JSON(visible=False)
|
|
@@ -42,13 +55,24 @@ def create_app(engine, gpu_decorator):
|
|
| 42 |
generate, inputs=request, outputs=response, api_name="reply",
|
| 43 |
concurrency_limit=1,
|
| 44 |
)
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
app.state.gradio_model = {
|
| 47 |
"model_loaded": engine.model is not None,
|
| 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)
|
|
|
|
| 1 |
"""Serve V16 unchanged at / with queued Gradio callbacks on ZeroGPU."""
|
| 2 |
import os
|
| 3 |
+
import json
|
| 4 |
from pathlib import Path
|
| 5 |
import sys
|
| 6 |
|
|
|
|
| 19 |
return 60 if length <= 800 else 90
|
| 20 |
|
| 21 |
|
| 22 |
+
def create_app(engine, gpu_decorator, *, gpu_engine=None, max_queue_size=8):
|
| 23 |
import gradio as gr
|
| 24 |
|
| 25 |
from app import app
|
|
|
|
| 29 |
@gpu_decorator
|
| 30 |
def generate(payload):
|
| 31 |
request = ReplyRequest.model_validate(payload)
|
| 32 |
+
result = reply_v16(
|
| 33 |
engine, request.message, request.relation, request.goal, request.style,
|
| 34 |
request.speaker_gender, request.recipient_gender,
|
| 35 |
[turn.model_dump() for turn in request.history], request.generation_mode,
|
| 36 |
)
|
| 37 |
+
if os.getenv('LABEQ_RETURN_GENERATION_TRACE')=='1':
|
| 38 |
+
result['generation_trace']=getattr(engine,'generation_trace',[])
|
| 39 |
+
return result
|
| 40 |
+
|
| 41 |
+
accelerated=None
|
| 42 |
+
if gpu_engine is not None:
|
| 43 |
+
import spaces
|
| 44 |
+
@spaces.GPU(duration=gpu_duration)
|
| 45 |
+
def accelerated(payload):
|
| 46 |
+
request=ReplyRequest.model_validate(payload)
|
| 47 |
+
return reply_v16(gpu_engine,request.message,request.relation,request.goal,request.style,
|
| 48 |
+
request.speaker_gender,request.recipient_gender,[turn.model_dump() for turn in request.history],request.generation_mode)
|
| 49 |
|
| 50 |
with gr.Blocks(title="LABEQ model API") as model_api:
|
| 51 |
request = gr.JSON(visible=False)
|
|
|
|
| 55 |
generate, inputs=request, outputs=response, api_name="reply",
|
| 56 |
concurrency_limit=1,
|
| 57 |
)
|
| 58 |
+
if accelerated is not None:
|
| 59 |
+
gr.Button('Accelerated model API',visible=False).click(accelerated,inputs=request,outputs=response,
|
| 60 |
+
api_name='reply_gpu',concurrency_limit=1)
|
| 61 |
+
model_api.queue(max_size=max_queue_size, default_concurrency_limit=1)
|
| 62 |
+
manifest_path=ROOT/'source-manifest.json'
|
| 63 |
+
manifest=json.loads(manifest_path.read_text()) if manifest_path.exists() else {}
|
| 64 |
app.state.gradio_model = {
|
| 65 |
"model_loaded": engine.model is not None,
|
| 66 |
"faisal_loaded": engine.faisal_ready,
|
| 67 |
"generator": engine.generator,
|
| 68 |
"adapter_revision": engine.adapter_revision,
|
| 69 |
"base_revision": getattr(engine,"base_revision",None),
|
| 70 |
+
"compute_backend":getattr(engine,"compute_backend",None),
|
| 71 |
+
"adapter_sha256":getattr(engine,"adapter_sha256",None),
|
| 72 |
+
"environment_versions":getattr(engine,"environment_versions",None),
|
| 73 |
+
"source_commit":manifest.get('source_commit'),
|
| 74 |
+
"writer_policy_sha256":getattr(engine,'writer_policy_sha256',None),
|
| 75 |
+
"repetition_penalty":getattr(engine,'repetition_penalty',None),
|
| 76 |
}
|
| 77 |
# The existing FastAPI HTML is the frontend; Gradio only supplies its queue.
|
| 78 |
return gr.mount_gradio_app(app, model_api, path="/model", ssr_mode=False)
|
grounded_review.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Source IDs prevent the reviewer from substituting draft quotes for user evidence.
|
| 2 |
+
|
| 3 |
+
These are source units, not a claim to have extracted every atomic intention.
|
| 4 |
+
The model's judgments remain fallible and require independent evaluation.
|
| 5 |
+
"""
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
+
|
| 9 |
+
REVIEW_MARKER='LABEQ_SOURCE_ID_REVIEW\n'
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def source_units(message,goal):
|
| 13 |
+
if goal.strip() and len(goal.strip())<4:
|
| 14 |
+
return {'r0':message+'\n'+goal}
|
| 15 |
+
parts=[x.strip() for x in re.findall(r'[^.!؟،,;\n]+(?:[.!؟،,;\n]+|$)',message) if x.strip()]
|
| 16 |
+
if not parts or len(parts)>11 or any(len(x)<4 for x in parts):parts=[message]
|
| 17 |
+
parts=list(dict.fromkeys(parts))
|
| 18 |
+
if goal.strip() and goal not in parts:parts.append(goal)
|
| 19 |
+
return {f'r{i}':text for i,text in enumerate(parts)}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def id_review_prompt(message,relation,goal,candidate,register):
|
| 23 |
+
return REVIEW_MARKER+json.dumps({'sources':source_units(message,goal),'relationship':relation,'candidate':candidate,'register':register},ensure_ascii=False)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def review_schema(sources):
|
| 27 |
+
item={'type':'object','properties':{'status':{'type':'string','enum':['met','missing','contradicted']},'reason':{'type':'string'}},'required':['status','reason'],'additionalProperties':False}
|
| 28 |
+
issue={'type':'object','properties':{'quote':{'type':'string'},'reason':{'type':'string'}},'required':['quote','reason'],'additionalProperties':False}
|
| 29 |
+
return {'type':'object','properties':{'checks':{'type':'object','properties':{key:item for key in sources},'required':list(sources),'additionalProperties':False},'unsupported':{'type':'array','items':{'type':'string'},'maxItems':8},'language_issues':{'type':'array','items':issue,'maxItems':8}},'required':['checks','unsupported','language_issues'],'additionalProperties':False}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def attach_source_quotes(raw,sources):
|
| 33 |
+
data=json.loads(raw)
|
| 34 |
+
if not isinstance(data,dict) or set(data)!={'checks','unsupported','language_issues'}:
|
| 35 |
+
raise ValueError('Invalid source-ID review schema')
|
| 36 |
+
if not isinstance(data['checks'],dict) or set(data['checks'])!=set(sources):
|
| 37 |
+
raise ValueError('Every source ID must be reviewed exactly once')
|
| 38 |
+
checks=[]
|
| 39 |
+
for key,quote in sources.items():
|
| 40 |
+
value=data['checks'][key]
|
| 41 |
+
if not isinstance(value,dict) or set(value)!={'status','reason'}:
|
| 42 |
+
raise ValueError('Invalid source-ID check')
|
| 43 |
+
checks.append({'source_quote':quote,**value})
|
| 44 |
+
return json.dumps({'checks':checks,'unsupported':data['unsupported'],'language_issues':data['language_issues']},ensure_ascii=False)
|
labeq_engine.py
CHANGED
|
@@ -218,7 +218,7 @@ class LabeqEngine:
|
|
| 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,
|
| 223 |
"eos_token_id": eos,
|
| 224 |
}
|
|
|
|
| 218 |
gen_kw = {
|
| 219 |
"max_new_tokens": max_tokens,
|
| 220 |
"do_sample": retry,
|
| 221 |
+
"repetition_penalty": getattr(self,"repetition_penalty",1.08),
|
| 222 |
"pad_token_id": pad if pad is not None else eos,
|
| 223 |
"eos_token_id": eos,
|
| 224 |
}
|
local_mlx_server.py
CHANGED
|
@@ -39,6 +39,9 @@ async def lifespan(app):
|
|
| 39 |
os.getenv("LABEQ_WRITER_POLICY") or None,
|
| 40 |
)
|
| 41 |
else:
|
|
|
|
|
|
|
|
|
|
| 42 |
app.state.engine=router
|
| 43 |
yield
|
| 44 |
|
|
|
|
| 39 |
os.getenv("LABEQ_WRITER_POLICY") or None,
|
| 40 |
)
|
| 41 |
else:
|
| 42 |
+
if os.getenv("LABEQ_WRITER_POLICY"):
|
| 43 |
+
from writing_policy import read_policy
|
| 44 |
+
router.writer_system,router.writer_examples=read_policy(os.environ["LABEQ_WRITER_POLICY"])
|
| 45 |
app.state.engine=router
|
| 46 |
yield
|
| 47 |
|
mlx_inference.py
CHANGED
|
@@ -142,6 +142,9 @@ class MlxEngine:
|
|
| 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)
|
|
|
|
| 142 |
self.model, self.processor, self.render(messages),
|
| 143 |
max_tokens=max_tokens, temperature=temperature, verbose=False,
|
| 144 |
)
|
| 145 |
+
self.last_generation={"finish_reason":getattr(result,"finish_reason",None),
|
| 146 |
+
"generation_tokens":getattr(result,"generation_tokens",None),"max_tokens":max_tokens,
|
| 147 |
+
"decoded_text":result.text,"format_cleanup_applied":finish_reply(result.text)!=result.text}
|
| 148 |
if require_complete and getattr(result,"finish_reason",None)=="length":
|
| 149 |
raise GenerationBudgetError(result.text)
|
| 150 |
return finish_reply(result.text)
|
requirements.txt
CHANGED
|
@@ -5,8 +5,11 @@ python-dotenv>=1.0,<2
|
|
| 5 |
python-multipart>=0.0.9,<1
|
| 6 |
pydantic>=2,<3
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
python-multipart>=0.0.9,<1
|
| 6 |
pydantic>=2,<3
|
| 7 |
|
| 8 |
+
# Actual private CPU runtime verified on 2026-11-21.
|
| 9 |
+
transformers==5.23.0
|
| 10 |
+
peft==0.22.0
|
| 11 |
+
accelerate==1.16.0
|
| 12 |
+
safetensors==0.8.0
|
| 13 |
+
huggingface_hub==2.4.0
|
| 14 |
+
# The Space platform supplied torch 2.13.0, spaces 0.52.1 and Gradio 6.32.0.
|
| 15 |
+
# Gradio/Python are pinned in SPACE_README.md; the platform manages CUDA emulation.
|
semantic_review.py
CHANGED
|
@@ -25,7 +25,7 @@ def parse_review(text, message, goal, candidate):
|
|
| 25 |
raw = raw[7:-3].strip()
|
| 26 |
try:
|
| 27 |
obj = json.loads(raw)
|
| 28 |
-
if not isinstance(obj,dict) or set(obj)
|
| 29 |
raise ValueError("schema")
|
| 30 |
if not isinstance(obj["checks"],list) or not 1 <= len(obj["checks"]) <= 12:
|
| 31 |
raise ValueError("checks")
|
|
@@ -48,9 +48,21 @@ def parse_review(text, message, goal, candidate):
|
|
| 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 |
-
|
|
|
|
| 54 |
except (ValueError, TypeError, KeyError):
|
| 55 |
result["error"]="invalid_or_ungrounded_review"
|
| 56 |
return result
|
|
|
|
| 25 |
raw = raw[7:-3].strip()
|
| 26 |
try:
|
| 27 |
obj = json.loads(raw)
|
| 28 |
+
if not isinstance(obj,dict) or set(obj) not in ({"checks","unsupported"},{"checks","unsupported","language_issues"}):
|
| 29 |
raise ValueError("schema")
|
| 30 |
if not isinstance(obj["checks"],list) or not 1 <= len(obj["checks"]) <= 12:
|
| 31 |
raise ValueError("checks")
|
|
|
|
| 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 |
+
language=obj.get("language_issues",[])
|
| 52 |
+
if not isinstance(language,list) or len(language)>8:
|
| 53 |
+
raise ValueError("language issues")
|
| 54 |
+
for issue in language:
|
| 55 |
+
if not isinstance(issue,dict) or set(issue)!={"quote","reason"}:
|
| 56 |
+
raise ValueError("language issue schema")
|
| 57 |
+
quote,reason=issue["quote"],issue["reason"]
|
| 58 |
+
if not isinstance(quote,str) or len(quote.strip())<2 or quote not in candidate:
|
| 59 |
+
raise ValueError("ungrounded language issue")
|
| 60 |
+
if not isinstance(reason,str) or not reason.strip() or len(reason)>220:
|
| 61 |
+
raise ValueError("language issue reason")
|
| 62 |
issues = [f"{c['source_quote']}: {c['reason']}" for c in obj["checks"] if c["status"]!="met"]
|
| 63 |
issues += ["تفصيل غير مسند في الرسالة: " + q for q in obj["unsupported"]]
|
| 64 |
+
issues += ["صياغة تحتاج تعديل: " + x["quote"] + ": " + x["reason"] for x in language]
|
| 65 |
+
result.update(valid=True,checks=obj["checks"],unsupported=obj["unsupported"],language_issues=language,issues=issues)
|
| 66 |
except (ValueError, TypeError, KeyError):
|
| 67 |
result["error"]="invalid_or_ungrounded_review"
|
| 68 |
return result
|
source-manifest.json
CHANGED
|
@@ -1,12 +1,14 @@
|
|
| 1 |
{
|
| 2 |
-
"source_commit": "
|
|
|
|
|
|
|
| 3 |
"files_sha256": {
|
| 4 |
"LABEQ_V15_Goal_Fix.py": "2d14bd8e222abe13ffdcb1a045dadab4e696a1a946ba7ad64efb1edcda939e19",
|
| 5 |
-
"LABEQ_V16_Coaching_Engine.py": "
|
| 6 |
"LICENSE-CODE": "38c1be7cee10dad65385c859f6ea823b77d97485f49e8114e314e175201e4421",
|
| 7 |
-
"README.md": "
|
| 8 |
"app.js": "8d78671f222ad6dfdf98bafa8cd5ebbfa1ed1feb16e9dbc25b34d6646b151240",
|
| 9 |
-
"app.py": "
|
| 10 |
"assets/expression_greet.jpg": "b37ac1f4108d980c48c7224f592dc325abed93a4d554a95311dcc25f3350f679",
|
| 11 |
"assets/expression_happy.jpg": "be420f063a2f5997cdc280b56f241021e2ad0f0600f7092174dd04f81f3da7b8",
|
| 12 |
"assets/expression_sorry.jpg": "d88e3690e0a7fa3d8f326ff7590406889c221e54308dfb11ce271bee21847947",
|
|
@@ -21,7 +23,9 @@
|
|
| 21 |
"assets/maha_mouth_clean_overlay.png": "1e814cfda52cafde46c85bb18d3bc309264d1c3a78d114cc93644961a2e71d82",
|
| 22 |
"assets/maha_mouth_open.png": "f07f6f2c1686c9401d0744bdbf639b446cd57feea946d4c96cc30dcaddaa3536",
|
| 23 |
"character2d.js": "0f87c3cfd32bf0e22a2d6de7c7d69f0c6392bb0d07a3eed69ed9d9bd2ce915b7",
|
| 24 |
-
"cloud/
|
|
|
|
|
|
|
| 25 |
"cloud/torch_engine.py": "fe8dd7e3582c0a168d80b6b89301b9c1226098b5679e6cd25c880b112ccf8d74",
|
| 26 |
"coach.js": "2723a3d7fc45c7f3ebdbf79466809245515ab5ec244fa75657c2a5def79f62b6",
|
| 27 |
"configure_model.py": "9b4421816e5919487dd46d6e37c6282161d5c129793cccca2a1431ab031bf1af",
|
|
@@ -29,22 +33,24 @@
|
|
| 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": "
|
| 35 |
"labeq_v4_core.py": "110efdaa86df0ebfcfa312d44a39a0f60f3355fc7fe31c303f5a4f3c35889b8e",
|
| 36 |
-
"local_mlx_server.py": "
|
| 37 |
-
"mlx_inference.py": "
|
| 38 |
"model_bridge.py": "3c0fa6081ebd9032a5a2194183fd2d759b57afddb5b5579814d0ecea0046343c",
|
| 39 |
"ollama_inference.py": "4aa22f3a8ec8503bbb75a895f79f6a5e4aefd8d3737cf969c84a973e0465f2ec",
|
| 40 |
-
"requirements.txt": "
|
| 41 |
"saudi_register.py": "4b1ba98df5537a65060e568159902e063198490250f4631ccd965692dd41b202",
|
| 42 |
-
"semantic_review.py": "
|
| 43 |
"setup_azure.py": "841c137e5cf11b87eabc09b8869c21908dfacd4ef8cbec5a1e9f53b626259759",
|
| 44 |
"setup_local.py": "2c0673ce4d42de968749eec1528ea2b66ba75b8bba2000a03627921acac7684b",
|
| 45 |
"setup_munsit.py": "72c4ba53da15feff1d67bae60f7d168501705395ae05f1a2450309e4fe0cbe63",
|
| 46 |
-
"space_client.js": "
|
| 47 |
"styles.css": "de8cb891839f0d2824aeca85a198937d6cc0ce8f18a4316f00e1fd168ed3f57d",
|
|
|
|
| 48 |
"verify_azure.py": "a38f440518774349dc5d0da82d565cae31ad9757787e33c05288f1f20f4b777c",
|
| 49 |
"verify_local_model.py": "17781339bb6c6ecd2596df4fc375c99b882e54d682e213d689c889f43789ed2f",
|
| 50 |
"verify_model_connection.py": "3805c6e35202c837314bed57ecfbf31328f99e9d498df253fa5c82d5a69d99ae",
|
|
|
|
| 1 |
{
|
| 2 |
+
"source_commit": "9c02faa425e7142408a7c79f5ec5848ca189d672",
|
| 3 |
+
"backend": "cpu",
|
| 4 |
+
"private_qa_adapter": null,
|
| 5 |
"files_sha256": {
|
| 6 |
"LABEQ_V15_Goal_Fix.py": "2d14bd8e222abe13ffdcb1a045dadab4e696a1a946ba7ad64efb1edcda939e19",
|
| 7 |
+
"LABEQ_V16_Coaching_Engine.py": "c4a6fe0ec21dd5493235c03dbe972e9c83138ac96f7b644ad1e5376cc4a408a4",
|
| 8 |
"LICENSE-CODE": "38c1be7cee10dad65385c859f6ea823b77d97485f49e8114e314e175201e4421",
|
| 9 |
+
"README.md": "330398f26c930069f3cebb3da2de10a8aae1c6f77cf0b02dc0fea6ed24a5d228",
|
| 10 |
"app.js": "8d78671f222ad6dfdf98bafa8cd5ebbfa1ed1feb16e9dbc25b34d6646b151240",
|
| 11 |
+
"app.py": "6984c51a4a07735debbd268dff1e135a41edc4be48b8b4d3ec813727f03b91ad",
|
| 12 |
"assets/expression_greet.jpg": "b37ac1f4108d980c48c7224f592dc325abed93a4d554a95311dcc25f3350f679",
|
| 13 |
"assets/expression_happy.jpg": "be420f063a2f5997cdc280b56f241021e2ad0f0600f7092174dd04f81f3da7b8",
|
| 14 |
"assets/expression_sorry.jpg": "d88e3690e0a7fa3d8f326ff7590406889c221e54308dfb11ce271bee21847947",
|
|
|
|
| 23 |
"assets/maha_mouth_clean_overlay.png": "1e814cfda52cafde46c85bb18d3bc309264d1c3a78d114cc93644961a2e71d82",
|
| 24 |
"assets/maha_mouth_open.png": "f07f6f2c1686c9401d0744bdbf639b446cd57feea946d4c96cc30dcaddaa3536",
|
| 25 |
"character2d.js": "0f87c3cfd32bf0e22a2d6de7c7d69f0c6392bb0d07a3eed69ed9d9bd2ce915b7",
|
| 26 |
+
"cloud/cpu_engine.py": "b5c24533a99baf1024685510506adcf8ea9791149304b52a4643e3bb67470bca",
|
| 27 |
+
"cloud/cpu_space_app.py": "bfe476c23b74f96b6ac23bdd31bb9017429e420202b5ad2c9c59057fd11e0bb9",
|
| 28 |
+
"cloud/space_app.py": "6e2ea2410d68283ccb6cfb2ae62f5192287279ae3ed9799d8a3619bda6295287",
|
| 29 |
"cloud/torch_engine.py": "fe8dd7e3582c0a168d80b6b89301b9c1226098b5679e6cd25c880b112ccf8d74",
|
| 30 |
"coach.js": "2723a3d7fc45c7f3ebdbf79466809245515ab5ec244fa75657c2a5def79f62b6",
|
| 31 |
"configure_model.py": "9b4421816e5919487dd46d6e37c6282161d5c129793cccca2a1431ab031bf1af",
|
|
|
|
| 33 |
"convert_peft_to_mlx.py": "e38de40c0f0342530a74ddef34529f58fe894e4d6bfbefa18719c6496c2e8f4c",
|
| 34 |
"faisal_adapter.example.py": "b505c29e61ef6047731d190476158c119ef7787ec95f95c52f6775bc87432ba2",
|
| 35 |
"generation_limits.py": "ebc97df254abc6582300adf8feb38aee4369119666624c372bd059a7c036d7dc",
|
| 36 |
+
"grounded_review.py": "4e839a1360971b1d3e1cc4532362629b908b17b52272bfc2a4b5cba49acff1ed",
|
| 37 |
"index.html": "2e05d29ea5f4e4b2b280188f5b35321341a4f7a517b56dd23132ab018091d709",
|
| 38 |
"labeq_api.py": "71d550a8c92fe7edab6d05d082b05141c2280d792fdf239c885922aa87d965b9",
|
| 39 |
+
"labeq_engine.py": "4a8286449e510ccac4a94e986cc275aa1db9081dd3be17139f4215a95834f169",
|
| 40 |
"labeq_v4_core.py": "110efdaa86df0ebfcfa312d44a39a0f60f3355fc7fe31c303f5a4f3c35889b8e",
|
| 41 |
+
"local_mlx_server.py": "07ab2c6a5a976fe8982c6f6b11312c6c6bc594ea96eb611461a1cc63e98c5e13",
|
| 42 |
+
"mlx_inference.py": "c72d64511f58bfe13cd0198754722be1a7b1010b78964a211a71ca8567f486c8",
|
| 43 |
"model_bridge.py": "3c0fa6081ebd9032a5a2194183fd2d759b57afddb5b5579814d0ecea0046343c",
|
| 44 |
"ollama_inference.py": "4aa22f3a8ec8503bbb75a895f79f6a5e4aefd8d3737cf969c84a973e0465f2ec",
|
| 45 |
+
"requirements.txt": "d2687d5f0dfae5694be987f8dc0dadb8cb2ce9d2c17e0b68ddbe4216ff4baad9",
|
| 46 |
"saudi_register.py": "4b1ba98df5537a65060e568159902e063198490250f4631ccd965692dd41b202",
|
| 47 |
+
"semantic_review.py": "90f37f07a0e3eed1cd12774ae20cc555f9f01708fb1b05c59a5a4464f7724df7",
|
| 48 |
"setup_azure.py": "841c137e5cf11b87eabc09b8869c21908dfacd4ef8cbec5a1e9f53b626259759",
|
| 49 |
"setup_local.py": "2c0673ce4d42de968749eec1528ea2b66ba75b8bba2000a03627921acac7684b",
|
| 50 |
"setup_munsit.py": "72c4ba53da15feff1d67bae60f7d168501705395ae05f1a2450309e4fe0cbe63",
|
| 51 |
+
"space_client.js": "434bcf0218b2d258999faaad3200efe681f81374963088714fe24124acdd0b21",
|
| 52 |
"styles.css": "de8cb891839f0d2824aeca85a198937d6cc0ce8f18a4316f00e1fd168ed3f57d",
|
| 53 |
+
"training/generalization_v3/policy.json": "c037b70bf124b00edd31c786684c5c5b2847271fbd6cef05a299a1c96890e527",
|
| 54 |
"verify_azure.py": "a38f440518774349dc5d0da82d565cae31ad9757787e33c05288f1f20f4b777c",
|
| 55 |
"verify_local_model.py": "17781339bb6c6ecd2596df4fc375c99b882e54d682e213d689c889f43789ed2f",
|
| 56 |
"verify_model_connection.py": "3805c6e35202c837314bed57ecfbf31328f99e9d498df253fa5c82d5a69d99ae",
|
space_client.js
CHANGED
|
@@ -40,11 +40,11 @@ window.labeqSpaceReply=async function(payload){
|
|
| 40 |
const data=frame.split('\n').filter(line=>line.startsWith('data:')).map(line=>line.slice(5).trimStart()).join('\n');
|
| 41 |
if(event==='error'){
|
| 42 |
let reason='';
|
| 43 |
-
try{
|
| 44 |
if(/quota|runs limit|credits|authenticate/i.test(reason)){
|
| 45 |
throw Error('انتهت حصة GPU المجانية. افتحي التطبيق من صفحة Hugging Face بعد تسجيل الدخول، أو جرّبي لاحقًا.');
|
| 46 |
}
|
| 47 |
-
throw Error('تعذّر
|
| 48 |
}
|
| 49 |
if(event==='complete'){
|
| 50 |
const result=JSON.parse(data)?.[0];
|
|
|
|
| 40 |
const data=frame.split('\n').filter(line=>line.startsWith('data:')).map(line=>line.slice(5).trimStart()).join('\n');
|
| 41 |
if(event==='error'){
|
| 42 |
let reason='';
|
| 43 |
+
try{const detail=JSON.parse(data);reason=typeof detail==='string'?detail:(detail?.error||'')}catch{}
|
| 44 |
if(/quota|runs limit|credits|authenticate/i.test(reason)){
|
| 45 |
throw Error('انتهت حصة GPU المجانية. افتحي التطبيق من صفحة Hugging Face بعد تسجيل الدخول، أو جرّبي لاحقًا.');
|
| 46 |
}
|
| 47 |
+
throw Error('تعذّر توليد رد مكتمل. جرّبي مرة ثانية.');
|
| 48 |
}
|
| 49 |
if(event==='complete'){
|
| 50 |
const result=JSON.parse(data)?.[0];
|
training/generalization_v3/policy.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"system":"You write a message that the USER can send to the other person. Read the entire situation, relationship and goal. Preserve who did what, every requested act, partial agreement, duration and uncertainty. Use natural everyday Saudi Arabic for friends and family, and respectful plain Saudi Arabic for work, university and customers. Use only stated facts. Never invent excuses, deadlines, promises, intentions or alternatives. Obey negative constraints instead of repeating the instructions in the reply. Address the recipient directly from the user's point of view. Preserve known genders; use ungendered wording when gender is unknown. Include all requested meaning in a few connected sentences, without padding. Output only the message, with no explanation, introduction or instructions to the user.",
|
| 3 |
+
"examples":[],
|
| 4 |
+
"provenance":"Experimental long-form SFT instruction; no stock phrase list or held-out reference. Not a claim of measured quality."
|
| 5 |
+
}
|