Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : KA Enrich7# File : kaenrich/worker.py8# Module : Kaenrich9# Repository : https://git.spboucher.ai/ka-enrich10# Project Website : Not specified11# Created : 2026-12-0312# Last Modified : 2026-12-0313#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Travailleur d'extraction : tourne sur le Mac Studio d'inférence (M1M64).4243Lit des lots JSONL déposés par les sites dans un dossier partagé, interroge le44serveur llama.cpp local (sortie contrainte par schéma JSON), valide chaque45réponse et écrit le lot de résultats. Aucune dépendance hors bibliothèque46standard.4748Dossier d'échange (`--root`, sur le stockage partagé) :49 <root>/<site>/in/<lot>.jsonl déposé par le site (écriture atomique)50 <root>/<site>/work/<lot>.jsonl lot pris en charge51 <root>/<site>/out/<lot>.jsonl résultats (écriture atomique)52 <root>/<site>/done/<lot>.jsonl lot d'entrée traité5354Ligne d'entrée : {"uid", "hash", "profile", "text", "fields"?, "context"?}55Ligne de sortie : {"uid", "hash", "model", "spec", "facts", "rejected", "ms"}56"""57from __future__ import annotations5859import argparse60import concurrent.futures as cf61import datetime as dt62import json63import os64import pathlib65import sys66import time67import urllib.error68import urllib.request6970from . import spec71from .validate import validate7273MAX_CHARS = 6000 # au-delà, l'annonce est tronquée (début + fin)747576def clip(text: str, limit: int = MAX_CHARS) -> str:77 text = (text or "").strip()78 if len(text) <= limit:79 return text80 head = int(limit * 0.7)81 return text[:head] + "\n[…]\n" + text[-(limit - head):]828384def parse_answer(content: str) -> dict:85 """Objet JSON d'une réponse, même entourée de texte ou d'une clôture86 ``` (serveurs sans sortie contrainte). Lève ValueError si aucun objet."""87 content = (content or "").strip()88 try:89 obj = json.loads(content)90 if isinstance(obj, dict):91 return obj92 except ValueError:93 pass94 # dernier objet équilibré du texte (un modèle à raisonnement écrit avant)95 end = content.rfind("}")96 while end != -1:97 depth, i = 0, end98 while i >= 0:99 c = content[i]100 if c == "}":101 depth += 1102 elif c == "{":103 depth -= 1104 if depth == 0:105 try:106 obj = json.loads(content[i:end + 1])107 if isinstance(obj, dict):108 return obj109 except ValueError:110 pass111 break112 i -= 1113 end = content.rfind("}", 0, end)114 raise ValueError("aucun objet JSON dans la réponse")115116117class Llama:118 """Client minimal d'une API compatible OpenAI (llama-server, mlx_lm.server).119120 `schema=True` : sortie contrainte par schéma JSON (llama-server).121 `schema=False` : le gabarit JSON est donné dans la consigne et la réponse122 est lue de façon tolérante (serveurs MLX, sans décodage contraint).123 """124125 def __init__(self, url: str, timeout: int = 300, schema: bool = True,126 model: str | None = None):127 self.url = url.rstrip("/")128 self.timeout = timeout129 self.schema = schema130 self.model_name = model131132 def model(self) -> str:133 with urllib.request.urlopen(self.url + "/v1/models", timeout=10) as r:134 data = json.load(r)135 mid = self.model_name or (data.get("data") or [{}])[0].get("id") or "inconnu"136 return os.path.basename(mid.rstrip("/"))137138 def extract(self, profile: str, text: str, fields=None, context=None) -> dict:139 user = spec.user_prompt(profile, text, fields, context)140 body = {"temperature": 0, "max_tokens": 900}141 if self.model_name:142 body["model"] = self.model_name143 if self.schema:144 body["response_format"] = {145 "type": "json_schema",146 "json_schema": {"name": "faits", "strict": True,147 "schema": spec.json_schema(profile, fields)},148 }149 else:150 names = list(spec.json_schema(profile, fields)["required"])151 user += ("\n\nRéponds par un seul objet JSON, sans texte autour, avec "152 "exactement ces clés : " + ", ".join(names) + ". Chaque clé vaut "153 "null ou {\"v\": valeur, \"q\": \"citation\"}.")154 body["max_tokens"] = 1500155 body["messages"] = [156 {"role": "system", "content": spec.system_prompt(profile)},157 {"role": "user", "content": user},158 ]159 req = urllib.request.Request(160 self.url + "/v1/chat/completions", data=json.dumps(body).encode(),161 headers={"Content-Type": "application/json"})162 with urllib.request.urlopen(req, timeout=self.timeout) as r:163 data = json.load(r)164 return parse_answer(data["choices"][0]["message"]["content"])165166167def process_row(llm: Llama, model: str, row: dict) -> dict:168 t0 = time.time()169 profile = row.get("profile") or "louka"170 text = clip(row.get("text") or "")171 context = dict(row.get("context") or {})172 context.setdefault("today", dt.date.today().isoformat())173 out = {"uid": row.get("uid"), "hash": row.get("hash"), "model": model,174 "spec": spec.VERSION, "facts": {}, "rejected": {}}175 if len(text) < 40:176 out["skipped"] = "texte_trop_court"177 return out178 try:179 answer = llm.extract(profile, text, row.get("fields"), context)180 out["facts"], out["rejected"] = validate(profile, text, answer, context["today"])181 except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, KeyError,182 ValueError) as exc:183 out["error"] = f"{type(exc).__name__}: {exc}"[:200]184 out["ms"] = int((time.time() - t0) * 1000)185 return out186187188def process_file(llm: Llama, model: str, src: pathlib.Path, dst: pathlib.Path,189 parallel: int) -> dict:190 rows = [json.loads(line) for line in src.read_text().split("\n") if line.strip()]191 stats = {"rows": len(rows), "facts": 0, "rejected": 0, "errors": 0}192 tmp = dst.with_suffix(".tmp")193 with tmp.open("w") as fh, cf.ThreadPoolExecutor(max_workers=parallel) as pool:194 for res in pool.map(lambda r: process_row(llm, model, r), rows):195 stats["facts"] += len(res["facts"])196 stats["rejected"] += len(res["rejected"])197 stats["errors"] += 1 if res.get("error") else 0198 fh.write(json.dumps(res, ensure_ascii=False) + "\n")199 os.replace(tmp, dst)200 return stats201202203def run_once(root: pathlib.Path, llm: Llama, parallel: int) -> int:204 model = llm.model()205 done = 0206 for site in sorted(p for p in root.iterdir() if p.is_dir()):207 inbox = site / "in"208 if not inbox.is_dir():209 continue210 for d in ("work", "out", "done"):211 (site / d).mkdir(exist_ok=True)212 for src in sorted(inbox.glob("*.jsonl")):213 work = site / "work" / src.name214 try:215 os.replace(src, work) # prise en charge atomique216 except OSError:217 continue218 t0 = time.time()219 stats = process_file(llm, model, work, site / "out" / src.name, parallel)220 os.replace(work, site / "done" / src.name)221 done += 1222 print(f"[ka-enrich] {site.name}/{src.name} : {stats} en "223 f"{time.time() - t0:.0f}s ({model})", flush=True)224 return done225226227def main(argv=None) -> int:228 ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])229 ap.add_argument("--root", required=True, help="dossier d'échange partagé")230 ap.add_argument("--llama", default="http://127.0.0.1:8088")231 ap.add_argument("--parallel", type=int, default=4)232 ap.add_argument("--no-schema", action="store_true",233 help="serveur sans sortie contrainte (mlx_lm.server)")234 ap.add_argument("--model", help="nom du modèle à demander au serveur (MLX)")235 ap.add_argument("--loop", type=int, default=0,236 help="secondes entre deux balayages (0 = un seul passage)")237 args = ap.parse_args(argv)238 # Les machines n ont pas le meme utilisateur sur le stockage partage :239 # dossiers et fichiers d echange restent ouverts aux deux cotes.240 os.umask(0)241 root = pathlib.Path(args.root)242 root.mkdir(parents=True, exist_ok=True)243 llm = Llama(args.llama, schema=not args.no_schema, model=args.model)244 while True:245 try:246 run_once(root, llm, args.parallel)247 except (urllib.error.URLError, OSError) as exc:248 print(f"[ka-enrich] passage interrompu : {exc}", file=sys.stderr, flush=True)249 if not args.loop:250 return 0251 time.sleep(args.loop)252253254if __name__ == "__main__":255 raise SystemExit(main())256