cwm-lab 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. cwm_lab/.env.example +14 -0
  2. cwm_lab/__init__.py +24 -0
  3. cwm_lab/cache.py +330 -0
  4. cwm_lab/config.yaml.example +18 -0
  5. cwm_lab/engine.py +2165 -0
  6. cwm_lab/exercises/GUIDE_ENSEIGNANT.md +93 -0
  7. cwm_lab/exercises/README.md +43 -0
  8. cwm_lab/exercises/famille/context.json +4 -0
  9. cwm_lab/exercises/famille/donnees.n3 +16 -0
  10. cwm_lab/exercises/famille/enonce.md +60 -0
  11. cwm_lab/exercises/famille/regles.n3 +13 -0
  12. cwm_lab/exercises/recettes/context.json +3 -0
  13. cwm_lab/exercises/recettes/corriges/exo-cholesterol.n3 +31 -0
  14. cwm_lab/exercises/recettes/corriges/exo-iib.n3 +31 -0
  15. cwm_lab/exercises/recettes/corriges/exo-renal.n3 +30 -0
  16. cwm_lab/exercises/recettes/corriges/exo-totaux.n3 +49 -0
  17. cwm_lab/exercises/recettes/enonce.md +206 -0
  18. cwm_lab/exercises/recettes/ingredients.n3 +224 -0
  19. cwm_lab/exercises/recettes/medical.n3 +98 -0
  20. cwm_lab/exercises/recettes/recettes.n3 +90 -0
  21. cwm_lab/exercises/recettes/regles.n3 +161 -0
  22. cwm_lab/server.py +345 -0
  23. cwm_lab/static/app.js +1286 -0
  24. cwm_lab/static/index.html +201 -0
  25. cwm_lab/static/style.css +456 -0
  26. cwm_lab/static/vendor/codemirror/LICENSE.md +40 -0
  27. cwm_lab/static/vendor/codemirror/README.md +56 -0
  28. cwm_lab/static/vendor/codemirror/codemirror.js +12 -0
  29. cwm_lab/static/vendor/codemirror/entry.js +22 -0
  30. cwm_lab/static/vendor/vis/LICENSE.md +21 -0
  31. cwm_lab/static/vendor/vis/README.md +34 -0
  32. cwm_lab/static/vendor/vis/vis-data.min.js +34 -0
  33. cwm_lab/static/vendor/vis/vis-network.min.js +78 -0
  34. cwm_lab-0.3.0.dist-info/METADATA +251 -0
  35. cwm_lab-0.3.0.dist-info/RECORD +39 -0
  36. cwm_lab-0.3.0.dist-info/WHEEL +5 -0
  37. cwm_lab-0.3.0.dist-info/entry_points.txt +2 -0
  38. cwm_lab-0.3.0.dist-info/licenses/LICENSE +201 -0
  39. cwm_lab-0.3.0.dist-info/top_level.txt +1 -0
cwm_lab/.env.example ADDED
@@ -0,0 +1,14 @@
1
+ # P8/P9 — données sensibles / locales. NE PAS COMMITTER.
2
+ #
3
+ # Installation : cp .env.example .env — remplir — chmod 600 .env
4
+ # Absent le fichier, les valeurs par défaut s'appliquent (l'appli
5
+ # démarre sans config).
6
+
7
+ # Cache (P8) : répertoire du cache persisté (défaut ~/.cache/lab_tp)
8
+ #CACHE_DIR=
9
+
10
+ # P9 — IA générative (provider très probablement ProxyIAg, qui gère
11
+ # les quotas en nombre de requêtes et en volume de tokens)
12
+ #IA_PROVIDER=
13
+ #IA_MODEL=
14
+ #IA_API_KEY=
cwm_lab/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """cwm_lab — CWM Lab, outil de TP Web sémantique sur CWM 2.0.
2
+
3
+ Tableau de bord local (backend stdlib + navigateur) pour un TP de
4
+ Web sémantique : cohérence, validité et règles. Voir ../ROADMAP.md.
5
+
6
+ Backend Python **stdlib uniquement** ; le frontend (static/) est servi
7
+ par ``cwm_lab.server``.
8
+ """
9
+
10
+ # Copyright 2026 CWM 2.0 maintainers
11
+ #
12
+ # Licensed under the Apache License, Version 2.0 (the "License");
13
+ # you may not use this file except in compliance with the License.
14
+ # You may obtain a copy of the License at
15
+ #
16
+ # http://www.apache.org/licenses/LICENSE-2.0
17
+ #
18
+ # Unless required by applicable law or agreed to in writing, software
19
+ # distributed under the License is distributed on an "AS IS" BASIS,
20
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ # See the License for the specific language governing permissions and
22
+ # limitations under the License.
23
+
24
+ __version__ = "0.3.0"
cwm_lab/cache.py ADDED
@@ -0,0 +1,330 @@
1
+ """cache — cache à deux niveaux (mémoire + disque) des traitements (P8).
2
+
3
+ En TP, le même traitement (parse, raisonnement, requête, preuve,
4
+ vérification de preuve, graphe, sérialisation) est très
5
+ probablement demandé plusieurs fois : le cache évite de le
6
+ refaire — la seconde occurrence est quasi instantanée et le
7
+ processeur est déchargé.
8
+
9
+ Deux niveaux :
10
+
11
+ - **mémoire** (processus) : hot path, LRU borné en nombre
12
+ d'entrées, TTL court ;
13
+ - **disque** (persisté) : un fichier JSON par clé, survit aux
14
+ redémarrages du serveur — le gain se cumule sur plusieurs
15
+ séances de TP. Borné en taille totale (évacuation du plus
16
+ ancien), TTL long.
17
+
18
+ Le cache est une **optimisation, pas un état** : le serveur
19
+ reste stateless (chaque requête reconstruit son store) ; seule
20
+ la réponse JSON déjà calculée est mémorisée. Clé = SHA-256 de
21
+ l'endpoint + du payload complet : la moindre variation du texte
22
+ force le recalcul. Seuls les résultats **complets et réussis**
23
+ sont cachés (jamais un timeout partiel, jamais une erreur).
24
+ Thread-safe (le serveur est ``ThreadingHTTPServer``) : un
25
+ ``threading.Lock`` unique, écritures disque atomiques
26
+ (``tmp`` + ``os.replace``).
27
+
28
+ Configuration (tous les fichiers **facultatifs** — absents, les
29
+ valeurs par défaut s'appliquent, l'appli démarre sans config) :
30
+
31
+ - ``config.yaml`` (chmod 600) — paramètres non sensibles :
32
+ ``ttl_disk``, ``ttl_memory``, ``max_disk_mb``,
33
+ ``memory_entries``. Format YAML plat (``cle: valeur``, un
34
+ niveau), parseable en stdlib ;
35
+ - ``.env`` (ignoré par git, chmod 600) — données sensibles /
36
+ locales : ``CACHE_DIR`` (défaut ``~/.cache/lab_tp``) et, pour
37
+ la P9, ``IA_PROVIDER`` / ``IA_MODEL`` / ``IA_API_KEY``.
38
+ """
39
+
40
+ # Copyright 2026 CWM 2.0 maintainers
41
+ #
42
+ # Licensed under the Apache License, Version 2.0 (the "License");
43
+ # you may not use this file except in compliance with the License.
44
+ # You may obtain a copy of the License at
45
+ #
46
+ # http://www.apache.org/licenses/LICENSE-2.0
47
+ #
48
+ # Unless required by applicable law or agreed to in writing, software
49
+ # distributed under the License is distributed on an "AS IS" BASIS,
50
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
51
+ # See the License for the specific language governing permissions and
52
+ # limitations under the License.
53
+
54
+ import hashlib
55
+ import json
56
+ import os
57
+ import threading
58
+ import time
59
+
60
+ #: Valeurs par défaut (appliquées si les fichiers de config sont
61
+ #: absents — l'appli démarre sans config).
62
+ DEFAULTS = {
63
+ "cache_dir": os.path.join(os.path.expanduser("~"), ".cache", "lab_tp"),
64
+ "ttl_memory": 300.0, # 5 min
65
+ "ttl_disk": 7 * 86400.0, # 7 jours
66
+ "max_disk_bytes": 200 * 1024 * 1024, # 200 Mo
67
+ "memory_entries": 64,
68
+ "ia_provider": "", # P9 (réservé)
69
+ "ia_model": "", # P9 (réservé)
70
+ "ia_api_key": "", # P9 (réservé)
71
+ }
72
+
73
+
74
+ # ----------------------------------------------------------------------
75
+ # parseurs de config (stdlib, un niveau)
76
+ # ----------------------------------------------------------------------
77
+
78
+ def parse_flat_yaml(text):
79
+ """Parse un YAML **plat** (``cle: valeur``, un niveau).
80
+
81
+ Lignes vides et commentaires (``#``) ignorés. Renvoie un
82
+ dictionnaire de chaînes (la conversion de type est faite par
83
+ :func:`load_config`).
84
+ """
85
+ out = {}
86
+ for line in text.splitlines():
87
+ line = line.strip()
88
+ if not line or line.startswith("#") or ":" not in line:
89
+ continue
90
+ k, _, v = line.partition(":")
91
+ out[k.strip()] = v.strip().strip('"').strip("'")
92
+ return out
93
+
94
+
95
+ def parse_flat_env(text):
96
+ """Parse un ``.env`` (``CLE=value``, un niveau).
97
+
98
+ Lignes vides et commentaires (``#``) ignorés.
99
+ """
100
+ out = {}
101
+ for line in text.splitlines():
102
+ line = line.strip()
103
+ if not line or line.startswith("#") or "=" not in line:
104
+ continue
105
+ k, _, v = line.partition("=")
106
+ out[k.strip()] = v.strip().strip('"').strip("'")
107
+ return out
108
+
109
+
110
+ def _parse_duration(value, default):
111
+ """``"7d"`` / ``"12h"`` / ``"30m"`` / ``"45"`` → secondes."""
112
+ if value is None:
113
+ return default
114
+ s = str(value).strip().lower()
115
+ if not s:
116
+ return default
117
+ units = {"s": 1.0, "m": 60.0, "h": 3600.0, "d": 86400.0}
118
+ try:
119
+ if s[-1] in units:
120
+ return float(s[:-1]) * units[s[-1]]
121
+ return float(s)
122
+ except ValueError:
123
+ return default
124
+
125
+
126
+ def load_config(base_dir=None):
127
+ """Charge la configuration (``config.yaml`` + ``.env``) et applique
128
+ les valeurs par défaut (:data:`DEFAULTS`).
129
+
130
+ ``base_dir`` est le dossier contenant les fichiers de config
131
+ (défaut : le dossier du paquet ``cwm_lab``). Un fichier
132
+ absent, illisible ou mal formé ne bloque pas le démarrage :
133
+ les valeurs par défaut (ou les autres fichiers) s'appliquent.
134
+ """
135
+ if base_dir is None:
136
+ base_dir = os.path.dirname(os.path.abspath(__file__))
137
+ cfg = dict(DEFAULTS)
138
+ # config.yaml — paramètres non sensibles
139
+ try:
140
+ with open(os.path.join(base_dir, "config.yaml"), encoding="utf-8") as f:
141
+ flat = parse_flat_yaml(f.read())
142
+ except OSError:
143
+ flat = {}
144
+ if "ttl_disk" in flat:
145
+ cfg["ttl_disk"] = _parse_duration(flat["ttl_disk"], cfg["ttl_disk"])
146
+ if "ttl_memory" in flat:
147
+ cfg["ttl_memory"] = _parse_duration(flat["ttl_memory"], cfg["ttl_memory"])
148
+ try:
149
+ if "max_disk_mb" in flat:
150
+ cfg["max_disk_bytes"] = int(float(flat["max_disk_mb"])) * 1024 * 1024
151
+ if "memory_entries" in flat:
152
+ cfg["memory_entries"] = int(flat["memory_entries"])
153
+ except ValueError:
154
+ pass
155
+ # .env — données sensibles / locales
156
+ try:
157
+ with open(os.path.join(base_dir, ".env"), encoding="utf-8") as f:
158
+ env = parse_flat_env(f.read())
159
+ except OSError:
160
+ env = {}
161
+ if env.get("CACHE_DIR"):
162
+ cfg["cache_dir"] = os.path.expanduser(env["CACHE_DIR"])
163
+ for key in ("ia_provider", "ia_model", "ia_api_key"):
164
+ env_key = "IA_" + key.split("_", 1)[1].upper()
165
+ if env.get(env_key):
166
+ cfg[key] = env[env_key]
167
+ return cfg
168
+
169
+
170
+ # ----------------------------------------------------------------------
171
+ # cache
172
+ # ----------------------------------------------------------------------
173
+
174
+ def cachable(result):
175
+ """Un résultat n'est mis en cache que s'il est **complet et réussi** :
176
+ dictionnaire avec ``ok: true`` et sans ``timeout`` (jamais un
177
+ timeout partiel, jamais une erreur).
178
+ """
179
+ return (isinstance(result, dict)
180
+ and result.get("ok") is True
181
+ and not result.get("timeout"))
182
+
183
+
184
+ class Cache:
185
+ """Cache à deux niveaux (mémoire LRU + disque persisté), thread-safe.
186
+
187
+ ``config`` est le dictionnaire de :func:`load_config` (ou équivalent
188
+ manuel pour les tests). ``clock`` est injectable (tests de TTL).
189
+ Si le répertoire disque n'est pas créable, le cache dégenère en
190
+ mémoire uniquement (le TP ne bloque jamais).
191
+ """
192
+
193
+ def __init__(self, config, clock=time.time):
194
+ self._lock = threading.Lock()
195
+ self._clock = clock
196
+ self._mem = {} # clé → (expiration, données) ; insertion = LRU
197
+ self._mem_order = [] # ordre d'insertion (défaut Python : dict)
198
+ self._ttl_memory = float(config["ttl_memory"])
199
+ self._ttl_disk = float(config["ttl_disk"])
200
+ self._max_disk_bytes = int(config["max_disk_bytes"])
201
+ self._memory_entries = max(1, int(config["memory_entries"]))
202
+ self._disk_dir = None
203
+ try:
204
+ self._disk_dir = os.path.expanduser(config["cache_dir"])
205
+ os.makedirs(self._disk_dir, exist_ok=True)
206
+ except OSError:
207
+ self._disk_dir = None
208
+
209
+ @property
210
+ def disk_dir(self):
211
+ """Répertoire disque effectif (``None`` si mémoire uniquement)."""
212
+ return self._disk_dir
213
+
214
+ # ------------------------------------------------------------------
215
+ # clé
216
+ # ------------------------------------------------------------------
217
+ @staticmethod
218
+ def make_key(api, payload):
219
+ """Clé = ``<api>/<sha256>`` où sha256 porte sur l'endpoint et le
220
+ **payload complet** (JSON canonique, clés triées) : toute
221
+ variation d'un caractère force le recalcul."""
222
+ canon = json.dumps(payload, sort_keys=True, ensure_ascii=False,
223
+ separators=(",", ":"))
224
+ digest = hashlib.sha256((api + "\x00" + canon).encode("utf-8"))
225
+ # plat (pas de « / ») : un fichier par clé dans le répertoire
226
+ # du cache — l'évacuation par taille scanne un seul niveau
227
+ return api + "-" + digest.hexdigest()
228
+
229
+ # ------------------------------------------------------------------
230
+ # mémoire
231
+ # ------------------------------------------------------------------
232
+ def _mem_get(self, key, now):
233
+ item = self._mem.get(key)
234
+ if item is None:
235
+ return None
236
+ expiry, data = item
237
+ if expiry <= now:
238
+ del self._mem[key]
239
+ return None
240
+ return data
241
+
242
+ def _mem_put(self, key, data, now):
243
+ if key not in self._mem:
244
+ while len(self._mem) >= self._memory_entries:
245
+ oldest = next(iter(self._mem))
246
+ del self._mem[oldest]
247
+ self._mem[key] = (now + self._ttl_memory, data)
248
+
249
+ # ------------------------------------------------------------------
250
+ # disque
251
+ # ------------------------------------------------------------------
252
+ def _disk_path(self, key):
253
+ return os.path.join(self._disk_dir, key + ".json")
254
+
255
+ def _disk_get(self, key, now):
256
+ try:
257
+ with open(self._disk_path(key), "rb") as f:
258
+ obj = json.loads(f.read().decode("utf-8"))
259
+ except (OSError, ValueError):
260
+ return None
261
+ if not isinstance(obj, dict) or "data" not in obj:
262
+ return None
263
+ try:
264
+ if now - float(obj.get("ts", 0)) > self._ttl_disk:
265
+ os.unlink(self._disk_path(key))
266
+ return None
267
+ except OSError:
268
+ return None
269
+ return obj["data"]
270
+
271
+ def _disk_put(self, key, data, now):
272
+ body = json.dumps({"ts": now, "data": data},
273
+ ensure_ascii=False).encode("utf-8")
274
+ path = self._disk_path(key)
275
+ tmp = "%s.tmp%d" % (path, os.getpid())
276
+ with open(tmp, "wb") as f:
277
+ f.write(body)
278
+ os.replace(tmp, path) # atomique : pas de fichier à moitié écrit
279
+
280
+ def _disk_evict(self):
281
+ """Garde le disque sous ``max_disk_bytes`` : fichiers JSON du
282
+ cache, du plus ancien au plus récent (mtime), tant que la
283
+ taille totale dépasse la borne."""
284
+ try:
285
+ entries = []
286
+ for name in os.listdir(self._disk_dir):
287
+ if name.endswith(".json"):
288
+ p = os.path.join(self._disk_dir, name)
289
+ try:
290
+ st = os.stat(p)
291
+ except OSError:
292
+ continue
293
+ entries.append((st.st_mtime, st.st_size, p))
294
+ total = sum(size for _, size, _ in entries)
295
+ if total <= self._max_disk_bytes:
296
+ return
297
+ for _, size, path in sorted(entries): # mtime croissant
298
+ os.unlink(path)
299
+ total -= size
300
+ if total <= self._max_disk_bytes:
301
+ return
302
+ except OSError:
303
+ pass # l'évacuation ne doit jamais bloquer le TP
304
+
305
+ # ------------------------------------------------------------------
306
+ # API publique
307
+ # ------------------------------------------------------------------
308
+ def get(self, key):
309
+ """Renvoie les données cachées sous ``key`` (mémoire d'abord,
310
+ puis disque — un hit disque est promu en mémoire) ou ``None``."""
311
+ with self._lock:
312
+ now = self._clock()
313
+ data = self._mem_get(key, now)
314
+ if data is not None:
315
+ return data
316
+ if self._disk_dir is None:
317
+ return None
318
+ data = self._disk_get(key, now)
319
+ if data is not None:
320
+ self._mem_put(key, data, now)
321
+ return data
322
+
323
+ def put(self, key, data):
324
+ """Mémorise ``data`` sous ``key`` (mémoire + disque persisté)."""
325
+ with self._lock:
326
+ now = self._clock()
327
+ self._mem_put(key, data, now)
328
+ if self._disk_dir is not None:
329
+ self._disk_put(key, data, now)
330
+ self._disk_evict()
@@ -0,0 +1,18 @@
1
+ # P8 — configuration de l'outil TP (paramètres NON sensibles).
2
+ #
3
+ # Installation : cp config.yaml.example config.yaml — compléter
4
+ # — chmod 600 config.yaml
5
+ # Absent le fichier, les valeurs par défaut ci-dessous s'appliquent
6
+ # (l'appli démarre sans config). Format YAML plat (cle: valeur).
7
+
8
+ # Rétention du cache disque (défaut 7 jours) — formats : s, m, h, d
9
+ #ttl_disk: 7d
10
+
11
+ # Rétention du cache mémoire (défaut 5 minutes)
12
+ #ttl_memory: 5m
13
+
14
+ # Taille totale maximale du cache disque, en Mo (défaut 200)
15
+ #max_disk_mb: 200
16
+
17
+ # Nombre d'entrées du cache mémoire (défaut 64)
18
+ #memory_entries: 64