Spaces:
Running
Running
Upload 29 files
Browse files- README.md +53 -94
- herc/__init__.py +3 -0
- herc/__main__.py +30 -0
- herc/config.py +32 -0
- herc/data/lexique_grec.json +79 -0
- herc/events.py +35 -0
- herc/lexicon.py +59 -0
- herc/pipeline.py +183 -0
- herc/recognition.py +25 -0
- herc/server.py +100 -0
- herc/static/app.js +307 -0
- herc/static/index.html +39 -0
- herc/static/style.css +42 -0
- herc/stitching.py +187 -0
- herc/text.py +86 -0
- herc/tiles.py +219 -0
- herc/watcher.py +87 -0
- requirements.txt +6 -30
- tests/conftest.py +3 -10
- tests/helpers.py +25 -0
- tests/test_audit.py +36 -0
- tests/test_lexicon.py +55 -0
- tests/test_pipeline.py +90 -0
- tests/test_stitching.py +78 -0
- tests/test_text.py +42 -0
- tests/test_tiles.py +107 -0
- tests/test_watcher_server.py +120 -0
- tools/ast_audit.py +119 -0
- tools/make_demo_tiles.py +120 -0
README.md
CHANGED
|
@@ -1,108 +1,67 @@
|
|
| 1 |
-
|
| 2 |
-
title: M.O.U.H.
|
| 3 |
-
colorFrom: blue
|
| 4 |
-
colorTo: indigo
|
| 5 |
-
sdk: docker
|
| 6 |
-
app_port: 7860
|
| 7 |
-
pinned: false
|
| 8 |
-
short_description: Moteur hybride SSM + MoE déterministe, vérifié à l'inférence
|
| 9 |
-
---
|
| 10 |
|
| 11 |
-
|
|
|
|
| 12 |
|
| 13 |
-
##
|
| 14 |
-
|
| 15 |
-
Correctifs de l’audit du 11 novembre 2026 : voir [les consignes d’upload](docs/UPLOAD_4.10.2.md). Les routes d’exécution et les journaux de travaux exigent maintenant le secret UNIQUE_ADMIN_KEY.
|
| 16 |
-
|
| 17 |
-
Ce Space entraîne et sert UNIQUE (Qwen2.5-Coder-7B-Instruct + adaptateur LoRA) **sans aucune inférence en ligne** :
|
| 18 |
-
données déposées en JSONL et vérifiées dans le bac à sable, entraînement continu dans le Space lui-même, tableau de
|
| 19 |
-
bord (courbes, historique, console). Matériel requis pour entraîner : un GPU (A10G small). Stockage persistant
|
| 20 |
-
conseillé : sans lui, données et adaptateur sont effacés à chaque redémarrage. Détails : [`docs/ADR-004-LOCAL.md`](docs/ADR-004-LOCAL.md).
|
| 21 |
-
|
| 22 |
-
La suite de ce document décrit le socle M.O.U.H. d'origine (bus JEV, boucle de vérification, nano-modèle).
|
| 23 |
-
|
| 24 |
-
Nano-modèle d'ingénierie logicielle à paradigme **déterministe et logico-symbolique** :
|
| 25 |
-
|
| 26 |
-
- un **bus de décision discret JEV** (Pydantic v2, mode strict) par lequel transite tout échange entre composants ;
|
| 27 |
-
- un **noyau séquentiel hybride** : blocs Gated-SSM (SSD type Mamba-2) et attention globale RoPE, ratio strict **5 SSM : 1 attention** ;
|
| 28 |
-
- un **MoE à 8 experts SwiGLU**, routage **déterministe** (pas de softmax, tri stable, 4 experts actifs par token) ;
|
| 29 |
-
- un **registre de skills** exécutés en bac à sable (Python, Pytest, système de fichiers, Z3) ;
|
| 30 |
-
- une **boucle de vérification à l'inférence** (`TestTimeVerificationLoop`, seuil 0.85) : aucune sortie n'est émise sans certificat ;
|
| 31 |
-
- un **registre d'audit** à chaînage de hachages, une application Gradio qui affiche le bus en temps réel, un Dockerfile pour les Spaces, un entraînement DDP/FSDP, une CI.
|
| 32 |
-
|
| 33 |
-
> **À lire avant tout.** Ce dépôt est l'infrastructure complète et testée, mais **aucun poids entraîné n'est fourni** :
|
| 34 |
-
> le modèle s'initialise aléatoirement et doit être entraîné (`scripts/train.py`) avant de produire du code utile.
|
| 35 |
-
> La boucle de vérification, le bus, les skills et les preuves fonctionnent indépendamment de la qualité du modèle
|
| 36 |
-
> (vous pouvez soumettre votre propre code candidat). Les écarts et limites sont listés dans
|
| 37 |
-
> [`docs/SPEC_TRACEABILITY.md`](docs/SPEC_TRACEABILITY.md).
|
| 38 |
-
|
| 39 |
-
## Incohérence arithmétique de la spécification (et décision prise)
|
| 40 |
-
|
| 41 |
-
La spécification demande à la fois **~1,5 Md de paramètres totaux**, **~400 M actifs par token** et **4 experts actifs sur 8**.
|
| 42 |
-
Ces trois chiffres sont incompatibles : avec 4 experts sur 8, au moins 50 % des paramètres d'experts sont actifs, donc
|
| 43 |
-
1,5 Md au total impose **au moins ~750 M actifs** (voir [`docs/PARAMETERS.md`](docs/PARAMETERS.md)). Trois presets sont livrés,
|
| 44 |
-
chacun vérifié par instanciation réelle :
|
| 45 |
-
|
| 46 |
-
| Preset | Experts actifs | Total | Actifs / token | Honore |
|
| 47 |
-
|---|---|---|---|---|
|
| 48 |
-
| `mouh-1.5b` (**défaut**) | 4 / 8 | 1 511,7 M | 832,3 M | 8 experts, top-4, 1,5 Md |
|
| 49 |
-
| `mouh-a400m` | 4 / 8 | 665,7 M | 400,3 M | 8 experts, top-4, 400 M actifs |
|
| 50 |
-
| `mouh-1.5b-top1` | 1 / 8 | 1 509,8 M | 395,0 M | 1,5 Md et ~400 M actifs (au prix du top-4) |
|
| 51 |
-
| `mouh-tiny` | 4 / 8 | 4,2 M | 2,5 M | tests CPU |
|
| 52 |
-
|
| 53 |
-
## Démarrage rapide
|
| 54 |
|
| 55 |
```bash
|
| 56 |
pip install -r requirements.txt
|
| 57 |
-
python
|
| 58 |
-
python
|
| 59 |
-
|
| 60 |
-
python scripts/train.py --preset mouh-tiny --data ./mon_corpus --max_steps 200
|
| 61 |
```
|
| 62 |
|
| 63 |
-
|
| 64 |
-
import torch
|
| 65 |
-
from mouh.model import MouhForCausalLM, ByteTokenizer, preset_config
|
| 66 |
-
from mouh.jev.types import JevMessageType
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
choice_type, choice_tool = model.decide(ids) # JevChoice typés, jamais de texte brut
|
| 72 |
```
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
```
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
```
|
| 87 |
-
app.py interface Gradio (bus JEV en direct)
|
| 88 |
-
config.json configuration Transformers du preset par défaut
|
| 89 |
-
Dockerfile image Hugging Face Space (SDK docker)
|
| 90 |
-
mouh/jev/ types, bus, routeur, table de routage, audit chaîné
|
| 91 |
-
mouh/model/ config, SSM/attention, MoE, Triton, tokenizer, modèle, pont vers le bus
|
| 92 |
-
mouh/skills/ sandbox, 4 skills, registre versionné + exécuteur
|
| 93 |
-
mouh/verification/ scoring, générateurs, mémoire de corrections, boucle
|
| 94 |
-
mouh/training/ données, entraînement DDP/FSDP
|
| 95 |
-
mouh/service.py diffusion temps réel des événements vers l'UI
|
| 96 |
-
scripts/ train, push_to_hub, count_params, export_config
|
| 97 |
-
tests/ suite de tests (JEV, skills, modèle, Triton, boucle, entraînement, service)
|
| 98 |
-
docs/ architecture, bus JEV, paramètres, déploiement, traçabilité de la spécification
|
| 99 |
-
.github/workflows/ CI + synchronisation vers le Hub
|
| 100 |
-
```
|
| 101 |
|
| 102 |
-
##
|
| 103 |
|
| 104 |
-
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Herculanum — pipeline local d'assemblage, de texte et de glose
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
Surveille un dossier de tuiles, les raccorde sur une vue plane, assemble le texte en ordre de lecture,
|
| 4 |
+
le glose mot à mot avec un lexique grec local et pousse tout en direct vers une interface à trois fenêtres.
|
| 5 |
|
| 6 |
+
## Démarrage
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
```bash
|
| 9 |
pip install -r requirements.txt
|
| 10 |
+
python tools/make_demo_tiles.py ./tiles_output --delay 1 # tuiles de démonstration, une par seconde
|
| 11 |
+
python -m herc --tiles ./tiles_output --column-width 800 # dans un second terminal
|
| 12 |
+
# ouvrir http://127.0.0.1:8000
|
|
|
|
| 13 |
```
|
| 14 |
|
| 15 |
+
Vérifications :
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
```bash
|
| 18 |
+
python -m pytest -q # 77 tests
|
| 19 |
+
python tools/ast_audit.py # audit structurel du Python et du JavaScript
|
|
|
|
| 20 |
```
|
| 21 |
|
| 22 |
+
## Ce que fait chaque partie
|
| 23 |
+
|
| 24 |
+
| Partie | Fichier | Rôle |
|
| 25 |
+
|---|---|---|
|
| 26 |
+
| Worker asynchrone | `herc/watcher.py` | Interroge `./tiles_output` ; une tuile n'est lue que si `<id>.json` et `<id>.png` sont restés identiques deux passages de suite ; une tuile modifiée est relue. |
|
| 27 |
+
| Validation des tuiles | `herc/tiles.py` | Schéma strict, champs inconnus refusés, noms de fichiers restreints, PNG contrôlé dans l'en-tête avant décodage, tailles bornées. |
|
| 28 |
+
| Stitching | `herc/stitching.py` | Corrélation de phase puis NCC sur le recouvrement réel ; origine déclarée affinée de ±16 px au plus ; mosaïque relative recalée dans le repère absolu dès qu'une tuile repérée s'y raccorde ; tuile sans raccord fiable mise en attente puis réessayée. |
|
| 29 |
+
| Texte | `herc/text.py` | Ordre colonne → ligne → x ; part des lettres restituées entre [ ] mesurée. |
|
| 30 |
+
| Lexique | `herc/lexicon.py`, `herc/data/lexique_grec.json` | 74 lemmes et leurs formes ; normalisation sans accents, esprits ni signes de Leyde ; formes ambiguës rendues avec tous leurs lemmes. |
|
| 31 |
+
| Serveur | `herc/server.py` | FastAPI, flux SSE `/api/events`, état `/api/state`, vue plane `/api/mosaic.png` ; écoute locale, CSP stricte, pas de documentation d'API exposée. |
|
| 32 |
+
| Interface | `herc/static/` | 1 : maillage 3D (canvas, sans bibliothèque externe) · 2 : vue plane + texte mot par mot · 3 : glose + statistiques. Tout texte passe par `textContent`. |
|
| 33 |
+
| Audit | `tools/ast_audit.py` | Refuse eval/exec/compile/`__import__`, subprocess, pickle, `os.system`, `shell=True`, `allow_pickle=True`, `torch.load` sans `weights_only=True`, innerHTML, `new Function`… |
|
| 34 |
+
|
| 35 |
+
## Format d'une tuile
|
| 36 |
+
|
| 37 |
+
`tiles_output/<id>.png` (gris 8 ou 16 bits, carte d'encre) et `tiles_output/<id>.json`, écrit **en dernier** :
|
| 38 |
+
|
| 39 |
+
```json
|
| 40 |
+
{
|
| 41 |
+
"id": "c12_t03",
|
| 42 |
+
"validated": true,
|
| 43 |
+
"segment": "PHerc0841/w00",
|
| 44 |
+
"origin_yx": [1280, 2560],
|
| 45 |
+
"surface_xyz": [[x, y, z], [x, y, z], [x, y, z], [x, y, z]],
|
| 46 |
+
"transcription": {
|
| 47 |
+
"source": "human",
|
| 48 |
+
"reviewer": "MHD",
|
| 49 |
+
"words": [{"text": "[ἡδο]νήν", "bbox": [y, x, h, w], "confidence": 0.9}]
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
```
|
| 53 |
|
| 54 |
+
`origin_yx`, `surface_xyz` et `transcription` sont facultatifs. `source` vaut `human`, `model` ou `demo` ;
|
| 55 |
+
la confiance est obligatoire pour `model` et `demo`, et vaut 1 par défaut pour `human`.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
+
## Limites assumées
|
| 58 |
|
| 59 |
+
- **Pas de lecture automatique des lettres.** Une carte d'encre n'est pas du texte. Les mots viennent de
|
| 60 |
+
la transcription jointe à la tuile ; `herc/recognition.py` offre l'emplacement pour brancher un
|
| 61 |
+
reconnaisseur, qui ne rend rien par défaut. Aucune tuile ne reçoit de mots inventés.
|
| 62 |
+
- **Glose, pas traduction.** Chaque mot reçoit le sens de son lemme dans le lexique local, sans syntaxe ;
|
| 63 |
+
les mots absents sont marqués ⟦?⟧. Le lexique est volontairement petit : enrichissez le JSON.
|
| 64 |
+
- **Raccord par l'image** : fiable quand deux tuiles partagent les mêmes pixels (NCC ≈ 1). Le seuil par
|
| 65 |
+
défaut (0,9) rejette les faux pics dus aux lignes de texte répétitives, mesurés jusqu'à 0,73.
|
| 66 |
+
Entre rendus différents de la même surface, baissez-le avec `--min-ncc` et vérifiez les raccords.
|
| 67 |
+
- **Démonstration** : texture synthétique et deux phrases connues d'Épicure, marquées `demo`.
|
herc/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pipeline local d'ingestion, d'assemblage et de glose des tuiles des rouleaux d'Herculanum."""
|
| 2 |
+
|
| 3 |
+
__version__ = "1.0.0"
|
herc/__main__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lancement : python -m herc --tiles ./tiles_output --port 8000"""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import logging
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import uvicorn
|
| 9 |
+
|
| 10 |
+
from .config import Config
|
| 11 |
+
from .server import create_app
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main(argv: list[str] | None = None) -> None:
|
| 15 |
+
parser = argparse.ArgumentParser(description="Pipeline local Herculanum : ingestion, assemblage, glose.")
|
| 16 |
+
parser.add_argument("--tiles", type=Path, default=Path("./tiles_output"), help="dossier surveillé")
|
| 17 |
+
parser.add_argument("--host", default="127.0.0.1", help="adresse d'écoute (locale par défaut)")
|
| 18 |
+
parser.add_argument("--port", type=int, default=8000)
|
| 19 |
+
parser.add_argument("--column-width", type=int, default=0, help="largeur d'une colonne de texte en pixels")
|
| 20 |
+
parser.add_argument("--min-ncc", type=float, default=0.9, help="corrélation minimale pour un raccord")
|
| 21 |
+
parser.add_argument("--poll", type=float, default=0.5, help="intervalle de surveillance (s)")
|
| 22 |
+
args = parser.parse_args(argv)
|
| 23 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s : %(message)s")
|
| 24 |
+
cfg = Config(tiles_dir=args.tiles, column_width=args.column_width, min_ncc=args.min_ncc,
|
| 25 |
+
poll_interval=args.poll)
|
| 26 |
+
uvicorn.run(create_app(cfg), host=args.host, port=args.port, log_level="info")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if __name__ == "__main__":
|
| 30 |
+
main()
|
herc/config.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Paramètres du pipeline ; tous ont une valeur par défaut sûre pour un usage local."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
PACKAGE_DIR = Path(__file__).resolve().parent
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass(frozen=True)
|
| 11 |
+
class Config:
|
| 12 |
+
# Dossier surveillé : chaque tuile = <id>.json (validé) + <id>.png
|
| 13 |
+
tiles_dir: Path = Path("./tiles_output")
|
| 14 |
+
poll_interval: float = 0.5
|
| 15 |
+
# Limites d'entrée (protection contre les fichiers anormaux)
|
| 16 |
+
max_json_bytes: int = 1_000_000
|
| 17 |
+
max_image_bytes: int = 64 * 1024 * 1024
|
| 18 |
+
max_tile_side: int = 4096
|
| 19 |
+
max_words_per_tile: int = 5000
|
| 20 |
+
# Raccordement géométrique
|
| 21 |
+
min_overlap_px: int = 2048 # recouvrement minimal (pixels) pour accepter un raccord
|
| 22 |
+
# Corrélation normalisée minimale sur le recouvrement. Deux tuiles issues du même rendu se
|
| 23 |
+
# recouvrent avec NCC ≈ 1 ; des lignes de texte répétitives donnent de faux pics jusqu'à ~0,75.
|
| 24 |
+
min_ncc: float = 0.9
|
| 25 |
+
refine_radius: int = 16 # correction maximale d'une origine déclarée (pixels)
|
| 26 |
+
phase_candidates: int = 5 # pics de corrélation de phase examinés
|
| 27 |
+
# Ordre de lecture
|
| 28 |
+
column_width: int = 0 # largeur d'une colonne de texte en pixels (0 = une seule colonne)
|
| 29 |
+
line_tolerance: float = 0.6 # écart vertical, en hauteurs de mot, pour changer de ligne
|
| 30 |
+
# Affichage
|
| 31 |
+
mosaic_max_side: int = 2048
|
| 32 |
+
lexicon_path: Path = PACKAGE_DIR / "data" / "lexique_grec.json"
|
herc/data/lexique_grec.json
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"description": "Lexique local minimal : mots-outils et vocabulaire philosophique fréquent dans les papyrus d'Herculanum (Épicure, Philodème). Gloses françaises indicatives. Complétez librement en gardant le format.",
|
| 3 |
+
"entries": [
|
| 4 |
+
{"lemma": "ὁ", "pos": "article", "gloss": "le, la", "forms": ["ὁ", "ἡ", "τό", "τοῦ", "τῆς", "τῷ", "τῇ", "τόν", "τήν", "οἱ", "αἱ", "τά", "τῶν", "τοῖς", "ταῖς", "τούς", "τάς", "τὸ", "τὸν", "τὴν", "τὰ", "τοὺς", "τὰς"]},
|
| 5 |
+
{"lemma": "καί", "pos": "conjonction", "gloss": "et, aussi", "forms": ["καί", "καὶ"]},
|
| 6 |
+
{"lemma": "δέ", "pos": "particule", "gloss": "et, mais", "forms": ["δέ", "δὲ", "δ'"]},
|
| 7 |
+
{"lemma": "γάρ", "pos": "particule", "gloss": "car", "forms": ["γάρ", "γὰρ"]},
|
| 8 |
+
{"lemma": "μέν", "pos": "particule", "gloss": "d'une part", "forms": ["μέν", "μὲν"]},
|
| 9 |
+
{"lemma": "ἀλλά", "pos": "conjonction", "gloss": "mais", "forms": ["ἀλλά", "ἀλλὰ", "ἀλλ'"]},
|
| 10 |
+
{"lemma": "οὐ", "pos": "adverbe", "gloss": "ne… pas", "forms": ["οὐ", "οὐκ", "οὐχ"]},
|
| 11 |
+
{"lemma": "μή", "pos": "adverbe", "gloss": "ne… pas (négation subjective)", "forms": ["μή", "μὴ"]},
|
| 12 |
+
{"lemma": "ἤ", "pos": "conjonction", "gloss": "ou ; que (comparaison)", "forms": ["ἤ", "ἢ"]},
|
| 13 |
+
{"lemma": "ὅτι", "pos": "conjonction", "gloss": "que, parce que", "forms": ["ὅτι"]},
|
| 14 |
+
{"lemma": "ὡς", "pos": "conjonction", "gloss": "comme, que", "forms": ["ὡς"]},
|
| 15 |
+
{"lemma": "ἐν", "pos": "préposition", "gloss": "dans, en", "forms": ["ἐν"]},
|
| 16 |
+
{"lemma": "εἰς", "pos": "préposition", "gloss": "vers, dans", "forms": ["εἰς", "ἐς"]},
|
| 17 |
+
{"lemma": "ἐκ", "pos": "préposition", "gloss": "hors de, depuis", "forms": ["ἐκ", "ἐξ"]},
|
| 18 |
+
{"lemma": "πρός", "pos": "préposition", "gloss": "vers, par rapport à", "forms": ["πρός", "πρὸς"]},
|
| 19 |
+
{"lemma": "περί", "pos": "préposition", "gloss": "au sujet de, autour de", "forms": ["περί", "περὶ"]},
|
| 20 |
+
{"lemma": "διά", "pos": "préposition", "gloss": "à travers ; à cause de", "forms": ["διά", "διὰ", "δι'"]},
|
| 21 |
+
{"lemma": "κατά", "pos": "préposition", "gloss": "selon ; contre", "forms": ["κατά", "κατὰ", "κατ'", "καθ'"]},
|
| 22 |
+
{"lemma": "ἀπό", "pos": "préposition", "gloss": "depuis, loin de", "forms": ["ἀπό", "ἀπὸ", "ἀπ'", "ἀφ'"]},
|
| 23 |
+
{"lemma": "εἰμί", "pos": "verbe", "gloss": "être", "forms": ["εἰμί", "εἶναι", "ἐστί", "ἐστίν", "ἐστι", "ἐστιν", "εἰσί", "εἰσίν", "ἦν", "ὤν", "ὄντα", "ὄντος", "οὖσα"]},
|
| 24 |
+
{"lemma": "λέγω", "pos": "verbe", "gloss": "dire", "forms": ["λέγω", "λέγει", "λέγομεν", "λέγουσι", "λέγουσιν", "λέγειν", "λέγεται"]},
|
| 25 |
+
{"lemma": "ἔχω", "pos": "verbe", "gloss": "avoir, tenir", "forms": ["ἔχω", "ἔχει", "ἔχειν", "ἔχομεν", "ἔχουσι", "ἔχουσιν"]},
|
| 26 |
+
{"lemma": "ζάω", "pos": "verbe", "gloss": "vivre", "forms": ["ζῆν", "ζῇ", "ζῶν"]},
|
| 27 |
+
{"lemma": "ἡδονή", "pos": "nom", "gloss": "plaisir", "forms": ["ἡδονή", "ἡδονῆς", "ἡδονῇ", "ἡδονήν", "ἡδονὴν", "ἡδοναί", "ἡδονῶν", "ἡδονάς"]},
|
| 28 |
+
{"lemma": "ἀρχή", "pos": "nom", "gloss": "principe, commencement", "forms": ["ἀρχή", "ἀρχῆς", "ἀρχῇ", "ἀρχήν", "ἀρχὴν"]},
|
| 29 |
+
{"lemma": "τέλος", "pos": "nom", "gloss": "fin, but", "forms": ["τέλος", "τέλους", "τέλει"]},
|
| 30 |
+
{"lemma": "μακαρίως", "pos": "adverbe", "gloss": "de façon bienheureuse", "forms": ["μακαρίως"]},
|
| 31 |
+
{"lemma": "μακάριος", "pos": "adjectif", "gloss": "bienheureux", "forms": ["μακάριος", "μακάριον", "μακαρίου"]},
|
| 32 |
+
{"lemma": "θάνατος", "pos": "nom", "gloss": "mort", "forms": ["θάνατος", "θανάτου", "θανάτῳ", "θάνατον"]},
|
| 33 |
+
{"lemma": "οὐδείς", "pos": "pronom", "gloss": "personne ; rien", "forms": ["οὐδείς", "οὐδέν", "οὐδὲν", "οὐδενός", "οὐδενί"]},
|
| 34 |
+
{"lemma": "μηδείς", "pos": "pronom", "gloss": "personne ; rien", "forms": ["μηδείς", "μηδέν", "μηδὲν"]},
|
| 35 |
+
{"lemma": "ἐγώ", "pos": "pronom", "gloss": "je, moi ; nous (pluriel)", "forms": ["ἐγώ", "ἐμοῦ", "μου", "ἐμοί", "μοι", "ἐμέ", "με", "ἡμεῖς", "ἡμῶν", "ἡμῖν", "ἡμᾶς"]},
|
| 36 |
+
{"lemma": "τις", "pos": "pronom", "gloss": "quelqu'un, quelque chose", "forms": ["τις", "τι", "τινός", "τινί", "τινα", "τινές", "τινῶν"]},
|
| 37 |
+
{"lemma": "οὗτος", "pos": "pronom", "gloss": "celui-ci, ceci", "forms": ["οὗτος", "αὕτη", "τοῦτο", "τούτου", "ταύτης", "τούτῳ", "τοῦτον", "ταύτην", "οὗτοι", "ταῦτα", "τούτων"]},
|
| 38 |
+
{"lemma": "αὐτός", "pos": "pronom", "gloss": "lui-même ; lui", "forms": ["αὐτός", "αὐτή", "αὐτό", "αὐτοῦ", "αὐτῆς", "αὐτῷ", "αὐτόν", "αὐτήν", "αὐτῶν", "αὐτοῖς", "αὐτούς"]},
|
| 39 |
+
{"lemma": "πᾶς", "pos": "adjectif", "gloss": "tout, chaque", "forms": ["πᾶς", "πᾶσα", "πᾶν", "παντός", "πάντα", "πάντες", "πάντων", "πᾶσι", "πᾶσιν"]},
|
| 40 |
+
{"lemma": "φιλοσοφία", "pos": "nom", "gloss": "philosophie", "forms": ["φιλοσοφία", "φιλοσοφίας", "φιλοσοφίᾳ", "φιλοσοφίαν"]},
|
| 41 |
+
{"lemma": "φιλόσοφος", "pos": "nom", "gloss": "philosophe", "forms": ["φιλόσοφος", "φιλοσόφου", "φιλόσοφον", "φιλόσοφοι", "φιλοσόφων"]},
|
| 42 |
+
{"lemma": "ψυχή", "pos": "nom", "gloss": "âme", "forms": ["ψυχή", "ψυχῆς", "ψυχῇ", "ψυχήν"]},
|
| 43 |
+
{"lemma": "σῶμα", "pos": "nom", "gloss": "corps", "forms": ["σῶμα", "σώματος", "σώματι", "σώματα"]},
|
| 44 |
+
{"lemma": "θεός", "pos": "nom", "gloss": "dieu", "forms": ["θεός", "θεοῦ", "θεῷ", "θεόν", "θεοί", "θεῶν", "θεοῖς", "θεούς"]},
|
| 45 |
+
{"lemma": "φύσις", "pos": "nom", "gloss": "nature", "forms": ["φύσις", "φύσεως", "φύσει", "φύσιν"]},
|
| 46 |
+
{"lemma": "ἀταραξία", "pos": "nom", "gloss": "absence de trouble, tranquillité", "forms": ["ἀταραξία", "ἀταραξίας", "ἀταραξίαν"]},
|
| 47 |
+
{"lemma": "ἀπονία", "pos": "nom", "gloss": "absence de douleur", "forms": ["ἀπονία", "ἀπονίας", "ἀπονίαν"]},
|
| 48 |
+
{"lemma": "πόνος", "pos": "nom", "gloss": "peine, douleur", "forms": ["πόνος", "πόνου", "πόνον", "πόνοι", "πόνων"]},
|
| 49 |
+
{"lemma": "ἀλγηδών", "pos": "nom", "gloss": "douleur", "forms": ["ἀλγηδών", "ἀλγηδόνος", "ἀλγηδόνα"]},
|
| 50 |
+
{"lemma": "φόβος", "pos": "nom", "gloss": "peur", "forms": ["φόβος", "φόβου", "φόβον"]},
|
| 51 |
+
{"lemma": "ἐπιθυμία", "pos": "nom", "gloss": "désir", "forms": ["ἐπιθυμία", "ἐπιθυμίας", "ἐπιθυμίαν", "ἐπιθυμίαι", "ἐπιθυμιῶν"]},
|
| 52 |
+
{"lemma": "ὀργή", "pos": "nom", "gloss": "colère", "forms": ["ὀργή", "ὀργῆς", "ὀργήν"]},
|
| 53 |
+
{"lemma": "φίλος", "pos": "nom", "gloss": "ami", "forms": ["φίλος", "φίλου", "φίλον", "φίλοι", "φίλων", "φίλοις", "φίλους"]},
|
| 54 |
+
{"lemma": "φιλία", "pos": "nom", "gloss": "amitié", "forms": ["φιλία", "φιλίας", "φιλίαν"]},
|
| 55 |
+
{"lemma": "λόγος", "pos": "nom", "gloss": "parole, raison, discours", "forms": ["λόγος", "λόγου", "λόγῳ", "λόγον", "λόγοι", "λόγων", "λόγοις", "λόγους"]},
|
| 56 |
+
{"lemma": "ἀρετή", "pos": "nom", "gloss": "vertu, excellence", "forms": ["ἀρετή", "ἀρετῆς", "ἀρετήν", "ἀρεταί"]},
|
| 57 |
+
{"lemma": "κακία", "pos": "nom", "gloss": "vice", "forms": ["κακία", "κακίας", "κακίαν"]},
|
| 58 |
+
{"lemma": "σοφός", "pos": "adjectif", "gloss": "sage", "forms": ["σοφός", "σοφοῦ", "σοφόν", "σοφοί"]},
|
| 59 |
+
{"lemma": "φρόνησις", "pos": "nom", "gloss": "sagesse pratique, prudence", "forms": ["φρόνησις", "φρονήσεως", "φρόνησιν"]},
|
| 60 |
+
{"lemma": "βίος", "pos": "nom", "gloss": "vie", "forms": ["βίος", "βίου", "βίῳ", "βίον"]},
|
| 61 |
+
{"lemma": "χρόνος", "pos": "nom", "gloss": "temps", "forms": ["χρόνος", "χρόνου", "χρόνον"]},
|
| 62 |
+
{"lemma": "ἀγαθός", "pos": "adjectif", "gloss": "bon ; bien", "forms": ["ἀγαθός", "ἀγαθόν", "ἀγαθοῦ", "ἀγαθά", "ἀγαθῶν"]},
|
| 63 |
+
{"lemma": "κακός", "pos": "adjectif", "gloss": "mauvais ; mal", "forms": ["κακός", "κακόν", "κακοῦ", "κακά", "κακῶν"]},
|
| 64 |
+
{"lemma": "καλός", "pos": "adjectif", "gloss": "beau ; bien", "forms": ["καλός", "καλόν", "καλοῦ", "καλά"]},
|
| 65 |
+
{"lemma": "ἄνθρωπος", "pos": "nom", "gloss": "être humain", "forms": ["ἄνθρωπος", "ἀνθρώπου", "ἄνθρωπον", "ἄνθρωποι", "ἀνθρώπων", "ἀνθρώποις", "ἀνθρώπους"]},
|
| 66 |
+
{"lemma": "ἀλήθεια", "pos": "nom", "gloss": "vérité", "forms": ["ἀλήθεια", "ἀληθείας", "ἀλήθειαν"]},
|
| 67 |
+
{"lemma": "δόξα", "pos": "nom", "gloss": "opinion ; réputation", "forms": ["δόξα", "δόξης", "δόξαν", "δόξαι", "δοξῶν"]},
|
| 68 |
+
{"lemma": "μουσική", "pos": "nom", "gloss": "musique", "forms": ["μουσική", "μουσικῆς", "μουσικήν"]},
|
| 69 |
+
{"lemma": "ποίημα", "pos": "nom", "gloss": "poème", "forms": ["ποίημα", "ποιήματος", "ποιήματα", "ποιημάτων"]},
|
| 70 |
+
{"lemma": "ποιητής", "pos": "nom", "gloss": "poète", "forms": ["ποιητής", "ποιητοῦ", "ποιητήν", "ποιηταί", "ποιητῶν"]},
|
| 71 |
+
{"lemma": "ῥητορική", "pos": "nom", "gloss": "rhétorique", "forms": ["ῥητορική", "ῥητορικῆς", "ῥητορικήν"]},
|
| 72 |
+
{"lemma": "κολακεία", "pos": "nom", "gloss": "flatterie", "forms": ["κολακεία", "κολακείας", "κολακείαν"]},
|
| 73 |
+
{"lemma": "εὐσέβεια", "pos": "nom", "gloss": "piété", "forms": ["εὐσέβεια", "εὐσεβείας", "εὐσέβειαν"]},
|
| 74 |
+
{"lemma": "οἰκονομία", "pos": "nom", "gloss": "administration domestique", "forms": ["οἰκονομία", "οἰκονομίας", "οἰκονομίαν"]},
|
| 75 |
+
{"lemma": "Ἐπίκουρος", "pos": "nom propre", "gloss": "Épicure", "forms": ["Ἐπίκουρος", "Ἐπικούρου", "Ἐπίκουρον", "Ἐπικούρῳ"]},
|
| 76 |
+
{"lemma": "Φιλόδημος", "pos": "nom propre", "gloss": "Philodème", "forms": ["Φιλόδημος", "Φιλοδήμου"]},
|
| 77 |
+
{"lemma": "Ζήνων", "pos": "nom propre", "gloss": "Zénon", "forms": ["Ζήνων", "Ζήνωνος"]}
|
| 78 |
+
]
|
| 79 |
+
}
|
herc/events.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bus d'événements en mémoire vers les clients Server-Sent Events."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import asyncio
|
| 5 |
+
import json
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class EventBus:
|
| 9 |
+
def __init__(self, maxsize: int = 1000):
|
| 10 |
+
self.maxsize = maxsize
|
| 11 |
+
self.subscribers: set[asyncio.Queue] = set()
|
| 12 |
+
|
| 13 |
+
def subscribe(self) -> asyncio.Queue:
|
| 14 |
+
queue: asyncio.Queue = asyncio.Queue(self.maxsize)
|
| 15 |
+
self.subscribers.add(queue)
|
| 16 |
+
return queue
|
| 17 |
+
|
| 18 |
+
def unsubscribe(self, queue: asyncio.Queue) -> None:
|
| 19 |
+
self.subscribers.discard(queue)
|
| 20 |
+
|
| 21 |
+
async def publish(self, event: dict) -> None:
|
| 22 |
+
for queue in list(self.subscribers):
|
| 23 |
+
try:
|
| 24 |
+
queue.put_nowait(event)
|
| 25 |
+
except asyncio.QueueFull:
|
| 26 |
+
# Client trop lent : on vide sa file et on lui demande de relire l'état complet.
|
| 27 |
+
while not queue.empty():
|
| 28 |
+
queue.get_nowait()
|
| 29 |
+
queue.put_nowait({"type": "resync"})
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def sse(event: dict) -> str:
|
| 33 |
+
"""Encode un événement ; json.dumps n'émet jamais de saut de ligne, le format SSE reste valide."""
|
| 34 |
+
data = json.dumps(event, ensure_ascii=False, separators=(",", ":"))
|
| 35 |
+
return f"event: {event['type']}\ndata: {data}\n\n"
|
herc/lexicon.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lexique local de grec ancien : recherche instantanée par forme normalisée.
|
| 2 |
+
|
| 3 |
+
La normalisation retire les signes éditoriaux de Leyde, les accents et esprits, passe en minuscules
|
| 4 |
+
et unifie le sigma final. Plusieurs lemmes peuvent partager une forme normalisée (ex. ἡ / ἤ) :
|
| 5 |
+
tous sont rendus, l'ambiguïté reste visible.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import unicodedata
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
LEIDEN = str.maketrans("", "", "[]()⟨⟩{}.·'’ʼ-")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def normalize(word: str) -> str:
|
| 18 |
+
decomposed = unicodedata.normalize("NFD", word.translate(LEIDEN))
|
| 19 |
+
letters = "".join(c for c in decomposed if unicodedata.category(c) != "Mn")
|
| 20 |
+
return unicodedata.normalize("NFC", letters).lower().replace("ς", "σ")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass(frozen=True)
|
| 24 |
+
class Entry:
|
| 25 |
+
lemma: str
|
| 26 |
+
pos: str
|
| 27 |
+
gloss: str
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Lexicon:
|
| 31 |
+
def __init__(self, entries: list[dict]):
|
| 32 |
+
self.index: dict[str, list[Entry]] = {}
|
| 33 |
+
self.size = 0
|
| 34 |
+
for i, item in enumerate(entries):
|
| 35 |
+
if not isinstance(item, dict) or set(item) != {"lemma", "pos", "gloss", "forms"}:
|
| 36 |
+
raise ValueError(f"entrée {i} du lexique : lemma, pos, gloss, forms requis")
|
| 37 |
+
if not all(isinstance(item[k], str) and item[k] for k in ("lemma", "pos", "gloss")):
|
| 38 |
+
raise ValueError(f"entrée {i} du lexique : textes non vides requis")
|
| 39 |
+
if not isinstance(item["forms"], list) or not item["forms"]:
|
| 40 |
+
raise ValueError(f"entrée {i} du lexique : liste de formes requise")
|
| 41 |
+
entry = Entry(item["lemma"], item["pos"], item["gloss"])
|
| 42 |
+
keys = {normalize(form) for form in [item["lemma"], *item["forms"]]}
|
| 43 |
+
if "" in keys:
|
| 44 |
+
raise ValueError(f"entrée {i} du lexique : forme vide après normalisation")
|
| 45 |
+
for key in keys:
|
| 46 |
+
bucket = self.index.setdefault(key, [])
|
| 47 |
+
if entry not in bucket:
|
| 48 |
+
bucket.append(entry)
|
| 49 |
+
self.size += 1
|
| 50 |
+
|
| 51 |
+
@classmethod
|
| 52 |
+
def load(cls, path: Path) -> "Lexicon":
|
| 53 |
+
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
| 54 |
+
if not isinstance(data, dict) or not isinstance(data.get("entries"), list):
|
| 55 |
+
raise ValueError("lexique : objet {'entries': [...]} requis")
|
| 56 |
+
return cls(data["entries"])
|
| 57 |
+
|
| 58 |
+
def lookup(self, word: str) -> tuple[Entry, ...]:
|
| 59 |
+
return tuple(self.index.get(normalize(word), ()))
|
herc/pipeline.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""État du pipeline : ingestion d'une tuile, placement, assemblage du texte, statistiques.
|
| 2 |
+
|
| 3 |
+
Toutes les méthodes publiques sont protégées par un verrou : le worker les appelle depuis un
|
| 4 |
+
thread, le serveur lit des instantanés cohérents.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import dataclasses
|
| 9 |
+
import io
|
| 10 |
+
import statistics
|
| 11 |
+
import threading
|
| 12 |
+
import time
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
from PIL import Image
|
| 17 |
+
|
| 18 |
+
from . import __version__
|
| 19 |
+
from .config import Config
|
| 20 |
+
from .lexicon import Lexicon
|
| 21 |
+
from .recognition import NullRecognizer, Recognizer
|
| 22 |
+
from .stitching import Mosaic, Placement
|
| 23 |
+
from .text import GlobalWord, assemble
|
| 24 |
+
from .tiles import Tile, TileError, check_words_inside, load_image, parse_tile
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class Pipeline:
|
| 28 |
+
def __init__(self, cfg: Config | None = None, lexicon: Lexicon | None = None,
|
| 29 |
+
recognizer: Recognizer | None = None):
|
| 30 |
+
self.cfg = cfg or Config()
|
| 31 |
+
self.lexicon = lexicon or Lexicon.load(self.cfg.lexicon_path)
|
| 32 |
+
self.recognizer = recognizer or NullRecognizer()
|
| 33 |
+
self.mosaic = Mosaic(self.cfg.min_overlap_px, self.cfg.min_ncc, self.cfg.refine_radius,
|
| 34 |
+
self.cfg.phase_candidates)
|
| 35 |
+
self.lock = threading.RLock()
|
| 36 |
+
self.tiles: dict[str, Tile] = {}
|
| 37 |
+
self.ink_mean: dict[str, float] = {}
|
| 38 |
+
self.pending: dict[str, np.ndarray] = {}
|
| 39 |
+
self.rejected: dict[str, str] = {}
|
| 40 |
+
self.words: list[GlobalWord] = []
|
| 41 |
+
self.version = 0
|
| 42 |
+
self.started = time.time()
|
| 43 |
+
self._composite_cache: tuple[int, tuple | None] | None = None
|
| 44 |
+
|
| 45 |
+
# ------------------------------------------------------------------ ingestion
|
| 46 |
+
def ingest(self, json_path: Path) -> list[dict]:
|
| 47 |
+
"""Traite une tuile ; rend les événements à diffuser (liste vide si non validée)."""
|
| 48 |
+
json_path = Path(json_path)
|
| 49 |
+
with self.lock:
|
| 50 |
+
try:
|
| 51 |
+
tile = parse_tile(json_path, self.cfg)
|
| 52 |
+
if tile is None:
|
| 53 |
+
return []
|
| 54 |
+
array = load_image(tile.image_path, self.cfg)
|
| 55 |
+
check_words_inside(tile, array.shape)
|
| 56 |
+
except (TileError, OSError) as exc:
|
| 57 |
+
return [self._reject(json_path.stem, str(exc))]
|
| 58 |
+
if not tile.words:
|
| 59 |
+
recognized = tuple(self.recognizer.recognize(array, tile))
|
| 60 |
+
if recognized:
|
| 61 |
+
tile = dataclasses.replace(tile, words=recognized, source="model")
|
| 62 |
+
check_words_inside(tile, array.shape)
|
| 63 |
+
|
| 64 |
+
self.rejected.pop(tile.id, None)
|
| 65 |
+
self.pending.pop(tile.id, None)
|
| 66 |
+
self.tiles[tile.id] = tile
|
| 67 |
+
self.ink_mean[tile.id] = float(array.mean())
|
| 68 |
+
events = []
|
| 69 |
+
placement = self.mosaic.place(tile.id, array, tile.origin_yx)
|
| 70 |
+
if placement is None:
|
| 71 |
+
self.pending[tile.id] = array
|
| 72 |
+
events.append({"type": "tile", "tile": self._tile_view(tile.id)})
|
| 73 |
+
elif self.mosaic.reanchored:
|
| 74 |
+
# Toute la mosaïque a été translatée dans le repère absolu : chaque tuile change de position.
|
| 75 |
+
events.extend({"type": "tile", "tile": self._tile_view(t)} for t in sorted(self.mosaic.items))
|
| 76 |
+
events.extend(self._retry_pending())
|
| 77 |
+
else:
|
| 78 |
+
events.append({"type": "tile", "tile": self._tile_view(tile.id)})
|
| 79 |
+
events.extend(self._retry_pending())
|
| 80 |
+
self._reassemble()
|
| 81 |
+
events.append(self.text_event())
|
| 82 |
+
events.append({"type": "stats", "stats": self.stats()})
|
| 83 |
+
return events
|
| 84 |
+
|
| 85 |
+
def _reject(self, name: str, reason: str) -> dict:
|
| 86 |
+
self.rejected[name] = reason
|
| 87 |
+
self.version += 1
|
| 88 |
+
return {"type": "rejected", "name": name, "reason": reason, "stats": self.stats()}
|
| 89 |
+
|
| 90 |
+
def _retry_pending(self) -> list[dict]:
|
| 91 |
+
events = []
|
| 92 |
+
progress = True
|
| 93 |
+
while progress and self.pending:
|
| 94 |
+
progress = False
|
| 95 |
+
for tile_id in sorted(self.pending):
|
| 96 |
+
tile = self.tiles[tile_id]
|
| 97 |
+
if self.mosaic.place(tile_id, self.pending[tile_id], tile.origin_yx) is not None:
|
| 98 |
+
del self.pending[tile_id]
|
| 99 |
+
moved = sorted(self.mosaic.items) if self.mosaic.reanchored else [tile_id]
|
| 100 |
+
events.extend({"type": "tile", "tile": self._tile_view(t)} for t in moved)
|
| 101 |
+
progress = True
|
| 102 |
+
return events
|
| 103 |
+
|
| 104 |
+
def _reassemble(self) -> None:
|
| 105 |
+
placed = [(p, self.tiles[p.tile_id]) for p in self.mosaic.placements()]
|
| 106 |
+
self.words = assemble(placed, self.lexicon, self.cfg.column_width, self.cfg.line_tolerance)
|
| 107 |
+
self.version += 1
|
| 108 |
+
|
| 109 |
+
# ------------------------------------------------------------------ vues
|
| 110 |
+
def _placement(self, tile_id: str) -> Placement | None:
|
| 111 |
+
item = self.mosaic.items.get(tile_id)
|
| 112 |
+
return item[0] if item else None
|
| 113 |
+
|
| 114 |
+
def _tile_view(self, tile_id: str) -> dict:
|
| 115 |
+
tile = self.tiles[tile_id]
|
| 116 |
+
placement = self._placement(tile_id)
|
| 117 |
+
view = {"id": tile.id, "segment": tile.segment, "source": tile.source, "reviewer": tile.reviewer,
|
| 118 |
+
"n_words": len(tile.words), "ink_mean": round(self.ink_mean.get(tile_id, 0.0), 4),
|
| 119 |
+
"status": "placed" if placement else "pending", "placement": None, "corners": None}
|
| 120 |
+
if placement:
|
| 121 |
+
view["placement"] = {"y": placement.y, "x": placement.x, "h": placement.h, "w": placement.w,
|
| 122 |
+
"method": placement.method, "anchor": placement.anchor,
|
| 123 |
+
"ncc": None if placement.ncc is None else round(placement.ncc, 4),
|
| 124 |
+
"shift": list(placement.shift)}
|
| 125 |
+
if tile.surface_xyz:
|
| 126 |
+
view["corners"] = [list(c) for c in tile.surface_xyz]
|
| 127 |
+
else:
|
| 128 |
+
y, x, h, w = placement.y, placement.x, placement.h, placement.w
|
| 129 |
+
view["corners"] = [[x, y, 0.0], [x + w, y, 0.0], [x + w, y + h, 0.0], [x, y + h, 0.0]]
|
| 130 |
+
return view
|
| 131 |
+
|
| 132 |
+
def text_event(self) -> dict:
|
| 133 |
+
return {"type": "text", "version": self.version, "words": [w.view() for w in self.words]}
|
| 134 |
+
|
| 135 |
+
def composite(self):
|
| 136 |
+
with self.lock:
|
| 137 |
+
if self._composite_cache is None or self._composite_cache[0] != self.version:
|
| 138 |
+
self._composite_cache = (self.version, self.mosaic.composite(self.cfg.mosaic_max_side))
|
| 139 |
+
return self._composite_cache[1]
|
| 140 |
+
|
| 141 |
+
def mosaic_png(self) -> bytes | None:
|
| 142 |
+
result = self.composite()
|
| 143 |
+
if result is None:
|
| 144 |
+
return None
|
| 145 |
+
buffer = io.BytesIO()
|
| 146 |
+
Image.fromarray(result[0], mode="L").save(buffer, format="PNG", optimize=False)
|
| 147 |
+
return buffer.getvalue()
|
| 148 |
+
|
| 149 |
+
def stats(self) -> dict:
|
| 150 |
+
with self.lock:
|
| 151 |
+
confidences = [w.confidence for w in self.words]
|
| 152 |
+
sources: dict[str, int] = {}
|
| 153 |
+
for word in self.words:
|
| 154 |
+
sources[word.source or "inconnue"] = sources.get(word.source or "inconnue", 0) + 1
|
| 155 |
+
glossed = sum(1 for w in self.words if w.glosses)
|
| 156 |
+
composite = self.composite()
|
| 157 |
+
return {
|
| 158 |
+
"tiles_processed": len(self.tiles),
|
| 159 |
+
"tiles_placed": len(self.mosaic),
|
| 160 |
+
"tiles_pending": len(self.pending),
|
| 161 |
+
"tiles_rejected": len(self.rejected),
|
| 162 |
+
"words_decoded": len(self.words),
|
| 163 |
+
"words_glossed": glossed,
|
| 164 |
+
"gloss_rate": round(glossed / len(self.words), 4) if self.words else None,
|
| 165 |
+
"mean_confidence": round(statistics.fmean(confidences), 4) if confidences else None,
|
| 166 |
+
"words_by_source": sources,
|
| 167 |
+
"covered_px": composite[1]["covered_px"] if composite else 0,
|
| 168 |
+
"lexicon_entries": self.lexicon.size,
|
| 169 |
+
"uptime_s": round(time.time() - self.started, 1),
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
def snapshot(self) -> dict:
|
| 173 |
+
with self.lock:
|
| 174 |
+
composite = self.composite()
|
| 175 |
+
return {
|
| 176 |
+
"app_version": __version__,
|
| 177 |
+
"version": self.version,
|
| 178 |
+
"tiles": [self._tile_view(t) for t in sorted(self.tiles)],
|
| 179 |
+
"rejected": [{"name": n, "reason": r} for n, r in sorted(self.rejected.items())],
|
| 180 |
+
"words": [w.view() for w in self.words],
|
| 181 |
+
"stats": self.stats(),
|
| 182 |
+
"mosaic": composite[1] if composite else None,
|
| 183 |
+
}
|
herc/recognition.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Point d'extension pour un reconnaisseur de lettres.
|
| 2 |
+
|
| 3 |
+
Aucun reconnaisseur fiable ne lit aujourd'hui des lettres grecques directement sur une carte
|
| 4 |
+
d'encre. Le reconnaisseur par défaut ne rend donc rien : une tuile sans transcription reste
|
| 5 |
+
« non lue », elle est assemblée géométriquement mais n'ajoute aucun mot.
|
| 6 |
+
|
| 7 |
+
Pour brancher un modèle, implémentez `recognize` et passez l'instance à `Pipeline`. Les mots
|
| 8 |
+
rendus seront marqués source="model" et devront porter une confiance dans [0, 1].
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from typing import Protocol
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from .tiles import Tile, Word
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Recognizer(Protocol):
|
| 20 |
+
def recognize(self, image: np.ndarray, tile: Tile) -> tuple[Word, ...]: ...
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class NullRecognizer:
|
| 24 |
+
def recognize(self, image: np.ndarray, tile: Tile) -> tuple[Word, ...]:
|
| 25 |
+
return ()
|
herc/server.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Serveur FastAPI : interface trois fenêtres, état JSON, vue plane PNG et flux SSE."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import asyncio
|
| 5 |
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
| 6 |
+
from contextlib import asynccontextmanager
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from fastapi import FastAPI, Request
|
| 10 |
+
from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse
|
| 11 |
+
from fastapi.staticfiles import StaticFiles
|
| 12 |
+
|
| 13 |
+
from .config import PACKAGE_DIR, Config
|
| 14 |
+
from .events import EventBus, sse
|
| 15 |
+
from .pipeline import Pipeline
|
| 16 |
+
from .watcher import TileWatcher
|
| 17 |
+
|
| 18 |
+
STATIC_DIR = PACKAGE_DIR / "static"
|
| 19 |
+
SECURITY_HEADERS = {
|
| 20 |
+
"Content-Security-Policy": "default-src 'self'; img-src 'self' data: blob:; style-src 'self'; "
|
| 21 |
+
"script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'",
|
| 22 |
+
"X-Content-Type-Options": "nosniff",
|
| 23 |
+
"Referrer-Policy": "no-referrer",
|
| 24 |
+
"X-Frame-Options": "DENY",
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
async def event_stream(bus: EventBus, pipeline: Pipeline, is_disconnected: Callable[[], Awaitable[bool]],
|
| 29 |
+
heartbeat: float = 15.0) -> AsyncIterator[str]:
|
| 30 |
+
queue = bus.subscribe()
|
| 31 |
+
try:
|
| 32 |
+
snapshot = await asyncio.to_thread(pipeline.snapshot)
|
| 33 |
+
yield sse({"type": "snapshot", **snapshot})
|
| 34 |
+
while True:
|
| 35 |
+
if await is_disconnected():
|
| 36 |
+
break
|
| 37 |
+
try:
|
| 38 |
+
event = await asyncio.wait_for(queue.get(), heartbeat)
|
| 39 |
+
except asyncio.TimeoutError:
|
| 40 |
+
yield ": ping\n\n"
|
| 41 |
+
continue
|
| 42 |
+
yield sse(event)
|
| 43 |
+
finally:
|
| 44 |
+
bus.unsubscribe(queue)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def create_app(cfg: Config | None = None, *, pipeline: Pipeline | None = None,
|
| 48 |
+
start_watcher: bool = True) -> FastAPI:
|
| 49 |
+
cfg = cfg or Config()
|
| 50 |
+
pipeline = pipeline or Pipeline(cfg)
|
| 51 |
+
bus = EventBus()
|
| 52 |
+
|
| 53 |
+
@asynccontextmanager
|
| 54 |
+
async def lifespan(app: FastAPI):
|
| 55 |
+
stop = asyncio.Event()
|
| 56 |
+
task = None
|
| 57 |
+
if start_watcher:
|
| 58 |
+
Path(cfg.tiles_dir).mkdir(parents=True, exist_ok=True)
|
| 59 |
+
task = asyncio.create_task(TileWatcher(cfg, pipeline, bus.publish).run(stop))
|
| 60 |
+
yield
|
| 61 |
+
stop.set()
|
| 62 |
+
if task is not None:
|
| 63 |
+
await task
|
| 64 |
+
|
| 65 |
+
app = FastAPI(title="Herculanum — pipeline local", lifespan=lifespan,
|
| 66 |
+
docs_url=None, redoc_url=None, openapi_url=None)
|
| 67 |
+
app.state.pipeline = pipeline
|
| 68 |
+
app.state.bus = bus
|
| 69 |
+
|
| 70 |
+
@app.middleware("http")
|
| 71 |
+
async def security_headers(request: Request, call_next):
|
| 72 |
+
response = await call_next(request)
|
| 73 |
+
for name, value in SECURITY_HEADERS.items():
|
| 74 |
+
response.headers.setdefault(name, value)
|
| 75 |
+
return response
|
| 76 |
+
|
| 77 |
+
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
| 78 |
+
|
| 79 |
+
@app.get("/", include_in_schema=False)
|
| 80 |
+
async def index() -> FileResponse:
|
| 81 |
+
return FileResponse(STATIC_DIR / "index.html", media_type="text/html; charset=utf-8")
|
| 82 |
+
|
| 83 |
+
@app.get("/api/state")
|
| 84 |
+
async def state() -> JSONResponse:
|
| 85 |
+
return JSONResponse(await asyncio.to_thread(pipeline.snapshot))
|
| 86 |
+
|
| 87 |
+
@app.get("/api/mosaic.png")
|
| 88 |
+
async def mosaic() -> Response:
|
| 89 |
+
data = await asyncio.to_thread(pipeline.mosaic_png)
|
| 90 |
+
if data is None:
|
| 91 |
+
return Response(status_code=204)
|
| 92 |
+
return Response(data, media_type="image/png", headers={"Cache-Control": "no-store"})
|
| 93 |
+
|
| 94 |
+
@app.get("/api/events")
|
| 95 |
+
async def events(request: Request) -> StreamingResponse:
|
| 96 |
+
return StreamingResponse(event_stream(bus, pipeline, request.is_disconnected),
|
| 97 |
+
media_type="text/event-stream",
|
| 98 |
+
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"})
|
| 99 |
+
|
| 100 |
+
return app
|
herc/static/app.js
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Interface trois fenêtres. Tout texte venant des tuiles passe par textContent (jamais de HTML injecté).
|
| 2 |
+
"use strict";
|
| 3 |
+
|
| 4 |
+
const state = { tiles: new Map(), words: [], stats: {}, mosaic: null, version: -1, selected: null };
|
| 5 |
+
const shown = new Set();
|
| 6 |
+
const revealQueue = [];
|
| 7 |
+
const mosaicImage = new Image();
|
| 8 |
+
let mosaicVersion = -1;
|
| 9 |
+
|
| 10 |
+
const $ = (id) => document.getElementById(id);
|
| 11 |
+
const el = (tag, cls, text) => {
|
| 12 |
+
const node = document.createElement(tag);
|
| 13 |
+
if (cls) node.className = cls;
|
| 14 |
+
if (text !== undefined) node.textContent = text;
|
| 15 |
+
return node;
|
| 16 |
+
};
|
| 17 |
+
|
| 18 |
+
// ------------------------------------------------------------------ flux SSE
|
| 19 |
+
function connect() {
|
| 20 |
+
const source = new EventSource("/api/events");
|
| 21 |
+
source.onopen = () => setConn(true);
|
| 22 |
+
source.onerror = () => setConn(false); // EventSource se reconnecte seul et reçoit un nouvel instantané
|
| 23 |
+
source.addEventListener("snapshot", (e) => applySnapshot(JSON.parse(e.data)));
|
| 24 |
+
source.addEventListener("tile", (e) => { const t = JSON.parse(e.data).tile; state.tiles.set(t.id, t); renderTiles(); draw3d(); });
|
| 25 |
+
source.addEventListener("text", (e) => { const d = JSON.parse(e.data); setWords(d.words, d.version); });
|
| 26 |
+
source.addEventListener("stats", (e) => { state.stats = JSON.parse(e.data).stats; renderStats(); refreshMosaic(); });
|
| 27 |
+
source.addEventListener("rejected", (e) => {
|
| 28 |
+
const d = JSON.parse(e.data);
|
| 29 |
+
log("Tuile refusée " + d.name + " : " + d.reason, "bad");
|
| 30 |
+
if (d.stats) { state.stats = d.stats; renderStats(); }
|
| 31 |
+
});
|
| 32 |
+
source.addEventListener("resync", () => fetch("/api/state").then((r) => r.json()).then(applySnapshot));
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
function setConn(on) {
|
| 36 |
+
const badge = $("conn");
|
| 37 |
+
badge.textContent = on ? "flux en direct" : "reconnexion…";
|
| 38 |
+
badge.className = "badge " + (on ? "on" : "off");
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
function applySnapshot(snap) {
|
| 42 |
+
state.tiles = new Map(snap.tiles.map((t) => [t.id, t]));
|
| 43 |
+
state.stats = snap.stats;
|
| 44 |
+
state.mosaic = snap.mosaic;
|
| 45 |
+
snap.rejected.forEach((r) => log("Tuile refusée " + r.name + " : " + r.reason, "bad"));
|
| 46 |
+
setWords(snap.words, snap.version);
|
| 47 |
+
renderTiles(); renderStats(); refreshMosaic(); draw3d();
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
function log(message, cls) {
|
| 51 |
+
const item = el("li", cls || "", new Date().toLocaleTimeString() + " · " + message);
|
| 52 |
+
$("log").prepend(item);
|
| 53 |
+
while ($("log").children.length > 80) $("log").lastChild.remove();
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// ------------------------------------------------------------------ fenêtre 2 : texte mot par mot
|
| 57 |
+
function setWords(words, version) {
|
| 58 |
+
state.words = words;
|
| 59 |
+
state.version = version;
|
| 60 |
+
const keys = new Set(words.map((w) => w.key));
|
| 61 |
+
for (const key of [...shown]) if (!keys.has(key)) shown.delete(key);
|
| 62 |
+
revealQueue.length = 0;
|
| 63 |
+
words.forEach((w) => { if (!shown.has(w.key)) revealQueue.push(w.key); });
|
| 64 |
+
renderText();
|
| 65 |
+
renderGloss();
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
function wordClass(w) {
|
| 69 |
+
let cls = "w";
|
| 70 |
+
if (!shown.has(w.key)) cls += " hidden";
|
| 71 |
+
if (w.confidence < 0.5) cls += " low";
|
| 72 |
+
if (!w.glosses.length) cls += " unknown";
|
| 73 |
+
if (state.selected === w.key) cls += " selected";
|
| 74 |
+
return cls;
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
function groupLines(words) {
|
| 78 |
+
const lines = [];
|
| 79 |
+
let current = null;
|
| 80 |
+
for (const w of words) {
|
| 81 |
+
if (!current || current.column !== w.column || current.line !== w.line) {
|
| 82 |
+
current = { column: w.column, line: w.line, words: [] };
|
| 83 |
+
lines.push(current);
|
| 84 |
+
}
|
| 85 |
+
current.words.push(w);
|
| 86 |
+
}
|
| 87 |
+
return lines;
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
function renderText() {
|
| 91 |
+
const box = $("text");
|
| 92 |
+
box.replaceChildren();
|
| 93 |
+
if (!state.words.length) { box.append(el("p", "hint", "Aucun mot transcrit pour l'instant.")); return; }
|
| 94 |
+
let column = null;
|
| 95 |
+
for (const line of groupLines(state.words)) {
|
| 96 |
+
if (line.column !== column) { column = line.column; box.append(el("div", "col-title", "Colonne " + (column + 1))); }
|
| 97 |
+
const row = el("p", "line");
|
| 98 |
+
line.words.forEach((w, i) => {
|
| 99 |
+
const span = el("span", wordClass(w), w.text);
|
| 100 |
+
span.dataset.key = w.key;
|
| 101 |
+
span.title = "confiance " + w.confidence.toFixed(2) + " · source " + (w.source || "?") +
|
| 102 |
+
(w.restored_fraction ? " · restitué " + Math.round(100 * w.restored_fraction) + " %" : "") +
|
| 103 |
+
" · " + (w.glosses.length ? w.glosses.map((g) => g.lemma + " : " + g.gloss).join(" | ") : "absent du lexique");
|
| 104 |
+
span.addEventListener("click", () => select(w.key));
|
| 105 |
+
row.append(span);
|
| 106 |
+
if (i < line.words.length - 1) row.append(document.createTextNode(" "));
|
| 107 |
+
});
|
| 108 |
+
box.append(row);
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
function select(key) {
|
| 113 |
+
state.selected = state.selected === key ? null : key;
|
| 114 |
+
document.querySelectorAll(".w").forEach((n) => n.classList.toggle("selected", n.dataset.key === state.selected));
|
| 115 |
+
drawFlat();
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
setInterval(() => {
|
| 119 |
+
const key = revealQueue.shift();
|
| 120 |
+
if (!key) return;
|
| 121 |
+
shown.add(key);
|
| 122 |
+
document.querySelectorAll('.w[data-key="' + CSS.escape(key) + '"]').forEach((n) => {
|
| 123 |
+
n.classList.remove("hidden"); n.classList.add("appear");
|
| 124 |
+
});
|
| 125 |
+
renderGloss();
|
| 126 |
+
drawFlat();
|
| 127 |
+
}, 90);
|
| 128 |
+
|
| 129 |
+
// ------------------------------------------------------------------ fenêtre 3 : glose et statistiques
|
| 130 |
+
function renderGloss() {
|
| 131 |
+
const box = $("gloss");
|
| 132 |
+
box.replaceChildren();
|
| 133 |
+
for (const line of groupLines(state.words.filter((w) => shown.has(w.key)))) {
|
| 134 |
+
const block = el("div", "gl");
|
| 135 |
+
block.append(el("div", "gr", line.words.map((w) => w.text).join(" ")));
|
| 136 |
+
block.append(el("div", "fr", line.words.map((w) =>
|
| 137 |
+
w.glosses.length ? [...new Set(w.glosses.map((g) => g.gloss))].join(" / ") : "⟦?⟧").join(" · ")));
|
| 138 |
+
box.append(block);
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
function renderStats() {
|
| 143 |
+
const s = state.stats || {};
|
| 144 |
+
const pct = (v) => (v === null || v === undefined ? "—" : Math.round(100 * v) + " %");
|
| 145 |
+
const rows = [
|
| 146 |
+
["Tuiles traitées", s.tiles_processed], ["Tuiles placées", s.tiles_placed],
|
| 147 |
+
["Tuiles en attente de raccord", s.tiles_pending], ["Tuiles refusées", s.tiles_rejected],
|
| 148 |
+
["Mots décodés", s.words_decoded], ["Mots glosés", s.words_glossed + " (" + pct(s.gloss_rate) + ")"],
|
| 149 |
+
["Confiance moyenne", s.mean_confidence === null || s.mean_confidence === undefined ? "—" : s.mean_confidence.toFixed(3)],
|
| 150 |
+
["Mots par source", Object.entries(s.words_by_source || {}).map(([k, v]) => k + " " + v).join(", ") || "—"],
|
| 151 |
+
["Surface couverte (px)", (s.covered_px || 0).toLocaleString("fr-FR")],
|
| 152 |
+
["Entrées du lexique", s.lexicon_entries],
|
| 153 |
+
];
|
| 154 |
+
const body = $("stats").tBodies[0];
|
| 155 |
+
body.replaceChildren();
|
| 156 |
+
for (const [label, value] of rows) {
|
| 157 |
+
const tr = el("tr");
|
| 158 |
+
tr.append(el("td", "", label), el("td", "", String(value ?? "—")));
|
| 159 |
+
body.append(tr);
|
| 160 |
+
}
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
function renderTiles() {
|
| 164 |
+
const list = $("tiles");
|
| 165 |
+
list.replaceChildren();
|
| 166 |
+
for (const t of [...state.tiles.values()].sort((a, b) => a.id.localeCompare(b.id))) {
|
| 167 |
+
const p = t.placement;
|
| 168 |
+
const text = t.id + " · " + t.segment + " · " + (p
|
| 169 |
+
? "posée (" + p.method + (p.ncc !== null ? ", NCC " + p.ncc.toFixed(2) : "") + ") en y=" + p.y + ", x=" + p.x
|
| 170 |
+
: "en attente : aucun recouvrement fiable") + " · " + t.n_words + " mot(s)";
|
| 171 |
+
list.append(el("li", t.status === "pending" ? "pending" : "", text));
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
// ------------------------------------------------------------------ fenêtre 2 : vue plane
|
| 176 |
+
function fitCanvas(canvas) {
|
| 177 |
+
const ratio = window.devicePixelRatio || 1;
|
| 178 |
+
const w = Math.max(1, Math.round(canvas.clientWidth * ratio));
|
| 179 |
+
const h = Math.max(1, Math.round(canvas.clientHeight * ratio));
|
| 180 |
+
if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; }
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
function refreshMosaic() {
|
| 184 |
+
fetch("/api/state").then((r) => r.json()).then((snap) => {
|
| 185 |
+
state.mosaic = snap.mosaic;
|
| 186 |
+
if (!state.mosaic || snap.version === mosaicVersion) { drawFlat(); return; }
|
| 187 |
+
mosaicVersion = snap.version;
|
| 188 |
+
mosaicImage.onload = drawFlat;
|
| 189 |
+
mosaicImage.src = "/api/mosaic.png?v=" + snap.version;
|
| 190 |
+
});
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
function drawFlat() {
|
| 194 |
+
const canvas = $("flat");
|
| 195 |
+
fitCanvas(canvas);
|
| 196 |
+
const ctx = canvas.getContext("2d");
|
| 197 |
+
ctx.fillStyle = "#0b0d11";
|
| 198 |
+
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
| 199 |
+
const m = state.mosaic;
|
| 200 |
+
if (!m || !mosaicImage.complete || !mosaicImage.naturalWidth) {
|
| 201 |
+
ctx.fillStyle = "#9aa3b2"; ctx.font = "14px system-ui";
|
| 202 |
+
ctx.fillText("En attente de tuiles…", 16, 28);
|
| 203 |
+
return;
|
| 204 |
+
}
|
| 205 |
+
const scale = Math.min(canvas.width / m.width, canvas.height / m.height);
|
| 206 |
+
const ox = (canvas.width - m.width * scale) / 2, oy = (canvas.height - m.height * scale) / 2;
|
| 207 |
+
ctx.imageSmoothingEnabled = true;
|
| 208 |
+
ctx.drawImage(mosaicImage, ox, oy, m.width * scale, m.height * scale);
|
| 209 |
+
const toCanvas = (y, x) => [ox + ((x - m.x0) / m.step) * scale, oy + ((y - m.y0) / m.step) * scale];
|
| 210 |
+
ctx.lineWidth = 1;
|
| 211 |
+
for (const t of state.tiles.values()) {
|
| 212 |
+
if (!t.placement) continue;
|
| 213 |
+
const [x, y] = toCanvas(t.placement.y, t.placement.x);
|
| 214 |
+
ctx.strokeStyle = "rgba(217,164,65,.55)";
|
| 215 |
+
ctx.strokeRect(x, y, (t.placement.w / m.step) * scale, (t.placement.h / m.step) * scale);
|
| 216 |
+
}
|
| 217 |
+
for (const w of state.words) {
|
| 218 |
+
if (!shown.has(w.key)) continue;
|
| 219 |
+
const [y, x, h, wd] = w.bbox;
|
| 220 |
+
const [cx, cy] = toCanvas(y, x);
|
| 221 |
+
const hue = Math.round(120 * w.confidence);
|
| 222 |
+
ctx.strokeStyle = w.key === state.selected ? "#4ea8de" : "hsla(" + hue + ",70%,55%,.9)";
|
| 223 |
+
ctx.lineWidth = w.key === state.selected ? 3 : 1.5;
|
| 224 |
+
ctx.strokeRect(cx, cy, (wd / m.step) * scale, (h / m.step) * scale);
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
// ------------------------------------------------------------------ fenêtre 1 : maillage 3D
|
| 229 |
+
const view = { yaw: -0.55, pitch: 0.95, zoom: 1 };
|
| 230 |
+
let drag = null;
|
| 231 |
+
|
| 232 |
+
function draw3d() {
|
| 233 |
+
const canvas = $("mesh");
|
| 234 |
+
fitCanvas(canvas);
|
| 235 |
+
const ctx = canvas.getContext("2d");
|
| 236 |
+
const W = canvas.width, H = canvas.height;
|
| 237 |
+
ctx.fillStyle = "#0b0d11";
|
| 238 |
+
ctx.fillRect(0, 0, W, H);
|
| 239 |
+
const tiles = [...state.tiles.values()].filter((t) => t.corners);
|
| 240 |
+
if (!tiles.length) {
|
| 241 |
+
ctx.fillStyle = "#9aa3b2"; ctx.font = "14px system-ui";
|
| 242 |
+
ctx.fillText("Aucune tuile posée", 16, 28);
|
| 243 |
+
return;
|
| 244 |
+
}
|
| 245 |
+
const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
|
| 246 |
+
tiles.forEach((t) => t.corners.forEach((c) => c.forEach((v, i) => { lo[i] = Math.min(lo[i], v); hi[i] = Math.max(hi[i], v); })));
|
| 247 |
+
const center = lo.map((v, i) => (v + hi[i]) / 2);
|
| 248 |
+
const span = Math.max(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2], 1);
|
| 249 |
+
const cy = Math.cos(view.yaw), sy = Math.sin(view.yaw), cp = Math.cos(view.pitch), sp = Math.sin(view.pitch);
|
| 250 |
+
const project = (p) => {
|
| 251 |
+
const x = (p[0] - center[0]) / span, y = (p[1] - center[1]) / span, z = -(p[2] - center[2]) / span;
|
| 252 |
+
const x1 = x * cy - y * sy, y1 = x * sy + y * cy;
|
| 253 |
+
const y2 = y1 * cp - z * sp, z2 = y1 * sp + z * cp;
|
| 254 |
+
const f = (Math.min(W, H) * 1.6 * view.zoom) / (2.2 + z2);
|
| 255 |
+
return [W / 2 + x1 * f, H / 2 + y2 * f, z2];
|
| 256 |
+
};
|
| 257 |
+
const lerp = (a, b, t) => a.map((v, i) => v + (b[i] - v) * t);
|
| 258 |
+
const bilinear = (c, u, v) => lerp(lerp(c[0], c[1], u), lerp(c[3], c[2], u), v);
|
| 259 |
+
const N = 4;
|
| 260 |
+
const quads = [];
|
| 261 |
+
for (const t of tiles) {
|
| 262 |
+
for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) {
|
| 263 |
+
const pts = [[i / N, j / N], [(i + 1) / N, j / N], [(i + 1) / N, (j + 1) / N], [i / N, (j + 1) / N]]
|
| 264 |
+
.map(([u, v]) => project(bilinear(t.corners, u, v)));
|
| 265 |
+
quads.push({ pts, depth: pts.reduce((s, p) => s + p[2], 0) / 4, tile: t });
|
| 266 |
+
}
|
| 267 |
+
}
|
| 268 |
+
quads.sort((a, b) => b.depth - a.depth);
|
| 269 |
+
for (const q of quads) {
|
| 270 |
+
const shade = Math.round(60 + 160 * (1 - q.tile.ink_mean));
|
| 271 |
+
const words = q.tile.n_words > 0;
|
| 272 |
+
ctx.beginPath();
|
| 273 |
+
q.pts.forEach((p, k) => (k ? ctx.lineTo(p[0], p[1]) : ctx.moveTo(p[0], p[1])));
|
| 274 |
+
ctx.closePath();
|
| 275 |
+
ctx.fillStyle = "rgb(" + shade + "," + Math.round(shade * 0.92) + "," + Math.round(shade * 0.78) + ")";
|
| 276 |
+
ctx.fill();
|
| 277 |
+
ctx.strokeStyle = words ? "rgba(217,164,65,.8)" : "rgba(154,163,178,.45)";
|
| 278 |
+
ctx.lineWidth = 1;
|
| 279 |
+
ctx.stroke();
|
| 280 |
+
}
|
| 281 |
+
ctx.fillStyle = "#9aa3b2"; ctx.font = "12px system-ui";
|
| 282 |
+
ctx.fillText(tiles.length + " tuile(s) · bord ambre : tuile transcrite", 10, H - 10);
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
function setup3dControls() {
|
| 286 |
+
const canvas = $("mesh");
|
| 287 |
+
canvas.addEventListener("pointerdown", (e) => { drag = [e.clientX, e.clientY]; canvas.setPointerCapture(e.pointerId); });
|
| 288 |
+
canvas.addEventListener("pointerup", () => { drag = null; });
|
| 289 |
+
canvas.addEventListener("pointermove", (e) => {
|
| 290 |
+
if (!drag) return;
|
| 291 |
+
view.yaw += (e.clientX - drag[0]) * 0.01;
|
| 292 |
+
view.pitch = Math.max(0.05, Math.min(1.55, view.pitch + (e.clientY - drag[1]) * 0.01));
|
| 293 |
+
drag = [e.clientX, e.clientY];
|
| 294 |
+
draw3d();
|
| 295 |
+
});
|
| 296 |
+
canvas.addEventListener("wheel", (e) => {
|
| 297 |
+
e.preventDefault();
|
| 298 |
+
view.zoom = Math.max(0.3, Math.min(6, view.zoom * (e.deltaY < 0 ? 1.1 : 0.9)));
|
| 299 |
+
draw3d();
|
| 300 |
+
}, { passive: false });
|
| 301 |
+
canvas.addEventListener("dblclick", () => { Object.assign(view, { yaw: -0.55, pitch: 0.95, zoom: 1 }); draw3d(); });
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
window.addEventListener("resize", () => { draw3d(); drawFlat(); });
|
| 305 |
+
setup3dControls();
|
| 306 |
+
renderStats();
|
| 307 |
+
connect();
|
herc/static/index.html
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="fr">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<title>Herculanum — pipeline local</title>
|
| 7 |
+
<link rel="icon" href="data:,">
|
| 8 |
+
<link rel="stylesheet" href="/static/style.css">
|
| 9 |
+
</head>
|
| 10 |
+
<body>
|
| 11 |
+
<header>
|
| 12 |
+
<h1>Herculanum · assemblage, texte et glose</h1>
|
| 13 |
+
<span id="conn" class="badge off">hors ligne</span>
|
| 14 |
+
</header>
|
| 15 |
+
<main>
|
| 16 |
+
<section id="w1" class="pane" aria-labelledby="t1">
|
| 17 |
+
<h2 id="t1">1 · Maillage 3D et tuiles</h2>
|
| 18 |
+
<div class="canvas-wrap"><canvas id="mesh" aria-label="Vue 3D des tuiles posées"></canvas></div>
|
| 19 |
+
<p class="hint">Glisser : rotation · molette : zoom · double-clic : vue initiale</p>
|
| 20 |
+
<ul id="tiles" class="list"></ul>
|
| 21 |
+
</section>
|
| 22 |
+
<section id="w2" class="pane" aria-labelledby="t2">
|
| 23 |
+
<h2 id="t2">2 · Vue plane et texte reconstitué</h2>
|
| 24 |
+
<div class="canvas-wrap flat"><canvas id="flat" aria-label="Vue plane consolidée"></canvas></div>
|
| 25 |
+
<div id="text" lang="grc" aria-live="polite"></div>
|
| 26 |
+
</section>
|
| 27 |
+
<section id="w3" class="pane" aria-labelledby="t3">
|
| 28 |
+
<h2 id="t3">3 · Glose en direct et statistiques</h2>
|
| 29 |
+
<p class="warn">Glose mot à mot tirée du lexique local : aide à la lecture, pas une traduction.
|
| 30 |
+
Les lettres entre [ ] sont restituées, non lues.</p>
|
| 31 |
+
<div id="gloss"></div>
|
| 32 |
+
<table id="stats"><tbody></tbody></table>
|
| 33 |
+
<h3>Journal</h3>
|
| 34 |
+
<ul id="log" class="list"></ul>
|
| 35 |
+
</section>
|
| 36 |
+
</main>
|
| 37 |
+
<script src="/static/app.js"></script>
|
| 38 |
+
</body>
|
| 39 |
+
</html>
|
herc/static/style.css
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
:root {
|
| 2 |
+
--bg: #0f1115; --pane: #171a21; --line: #2a2f3a; --ink: #e8e4d8; --muted: #9aa3b2;
|
| 3 |
+
--accent: #d9a441; --ok: #5bbf86; --warn: #e07a5f; --sel: #4ea8de;
|
| 4 |
+
font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
|
| 5 |
+
}
|
| 6 |
+
* { box-sizing: border-box; }
|
| 7 |
+
body { margin: 0; background: var(--bg); color: var(--ink); height: 100vh; display: flex; flex-direction: column; }
|
| 8 |
+
header { display: flex; align-items: center; justify-content: space-between; padding: .6rem 1rem; border-bottom: 1px solid var(--line); }
|
| 9 |
+
h1 { font-size: 1.05rem; margin: 0; font-weight: 600; letter-spacing: .02em; }
|
| 10 |
+
h2 { font-size: .95rem; margin: 0 0 .5rem; color: var(--accent); }
|
| 11 |
+
h3 { font-size: .85rem; margin: .8rem 0 .3rem; color: var(--muted); }
|
| 12 |
+
main { flex: 1; display: grid; grid-template-columns: 1fr 1.25fr 1fr; gap: .6rem; padding: .6rem; min-height: 0; }
|
| 13 |
+
.pane { background: var(--pane); border: 1px solid var(--line); border-radius: 8px; padding: .7rem; overflow: auto; min-height: 0; display: flex; flex-direction: column; }
|
| 14 |
+
.canvas-wrap { position: relative; width: 100%; height: 46%; min-height: 220px; flex-shrink: 0; background: #0b0d11; border-radius: 6px; }
|
| 15 |
+
.canvas-wrap.flat { height: 42%; }
|
| 16 |
+
canvas { width: 100%; height: 100%; display: block; cursor: grab; }
|
| 17 |
+
.hint { color: var(--muted); font-size: .75rem; margin: .3rem 0; }
|
| 18 |
+
.badge { font-size: .75rem; padding: .15rem .55rem; border-radius: 999px; }
|
| 19 |
+
.badge.on { background: #1f3b2c; color: var(--ok); }
|
| 20 |
+
.badge.off { background: #3b1f1f; color: var(--warn); }
|
| 21 |
+
.list { list-style: none; padding: 0; margin: .3rem 0; font-size: .78rem; color: var(--muted); }
|
| 22 |
+
.list li { padding: .15rem 0; border-bottom: 1px dashed #232833; }
|
| 23 |
+
.list li.pending { color: var(--accent); }
|
| 24 |
+
.list li.bad { color: var(--warn); }
|
| 25 |
+
#text { margin-top: .6rem; font-family: "Gentium Plus", "GFS Didot", "Palatino Linotype", serif; font-size: 1.25rem; line-height: 1.9; }
|
| 26 |
+
.col-title { font-family: system-ui, sans-serif; font-size: .75rem; color: var(--muted); margin-top: .4rem; }
|
| 27 |
+
.line { margin: 0; }
|
| 28 |
+
.w { padding: 0 .12em; border-radius: 3px; cursor: pointer; transition: background .2s, opacity .4s; }
|
| 29 |
+
.w.hidden { opacity: 0; }
|
| 30 |
+
.w.appear { animation: appear .6s ease-out; }
|
| 31 |
+
.w.low { text-decoration: underline dotted var(--warn); }
|
| 32 |
+
.w.unknown { color: #c9b98f; }
|
| 33 |
+
.w.selected { background: rgba(78,168,222,.28); }
|
| 34 |
+
@keyframes appear { from { background: rgba(217,164,65,.45); } to { background: transparent; } }
|
| 35 |
+
.warn { font-size: .78rem; color: var(--muted); border-left: 3px solid var(--accent); padding-left: .5rem; margin: 0 0 .5rem; }
|
| 36 |
+
#gloss .gl { margin-bottom: .55rem; }
|
| 37 |
+
#gloss .gr { font-family: "Gentium Plus", "Palatino Linotype", serif; font-size: 1.02rem; }
|
| 38 |
+
#gloss .fr { color: var(--muted); font-size: .85rem; }
|
| 39 |
+
#stats { width: 100%; border-collapse: collapse; font-size: .82rem; margin-top: .6rem; }
|
| 40 |
+
#stats td { padding: .25rem .3rem; border-bottom: 1px solid #232833; }
|
| 41 |
+
#stats td:last-child { text-align: right; font-variant-numeric: tabular-nums; color: var(--accent); }
|
| 42 |
+
@media (max-width: 1100px) { main { grid-template-columns: 1fr; } .pane { min-height: 70vh; } }
|
herc/stitching.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Raccordement spatial des tuiles sur une vue plane consolidée.
|
| 2 |
+
|
| 3 |
+
Deux cas :
|
| 4 |
+
- origine déclarée : la tuile est posée à cette origine, puis corrigée de quelques pixels au plus
|
| 5 |
+
si une corrélation sur le recouvrement le justifie ;
|
| 6 |
+
- origine déclarée alors que la mosaïque a été commencée sans repère : la tuile est d'abord raccordée
|
| 7 |
+
par l'image, puis toute la mosaïque est translatée dans le repère absolu (recalage) ;
|
| 8 |
+
- sans origine : la tuile est raccordée « en puzzle » contre chaque tuile déjà posée par corrélation
|
| 9 |
+
de phase ; un raccord n'est accepté que si la corrélation normalisée (NCC) mesurée sur le
|
| 10 |
+
recouvrement réel dépasse un seuil et que ce recouvrement est assez grand.
|
| 11 |
+
Une tuile sans raccord fiable reste en attente et est réessayée à chaque nouvelle tuile posée.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from dataclasses import replace as dataclass_replace
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass(frozen=True)
|
| 23 |
+
class Placement:
|
| 24 |
+
tile_id: str
|
| 25 |
+
y: int
|
| 26 |
+
x: int
|
| 27 |
+
h: int
|
| 28 |
+
w: int
|
| 29 |
+
method: str # first | origin | origin+refined | origin+reanchored | matched
|
| 30 |
+
ncc: float | None = None
|
| 31 |
+
anchor: str | None = None # tuile contre laquelle le raccord a été mesuré
|
| 32 |
+
shift: tuple[int, int] = (0, 0) # correction appliquée à l'origine déclarée
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def phase_candidates(a: np.ndarray, b: np.ndarray, count: int = 5) -> list[tuple[int, int]]:
|
| 36 |
+
"""Décalages (dy, dx) candidats de b dans le repère de a, par corrélation de phase.
|
| 37 |
+
|
| 38 |
+
Le zero-padding à (Ha+Hb, Wa+Wb) rend chaque décalage possible unique :
|
| 39 |
+
dy ∈ ]-Hb, Ha[, dx ∈ ]-Wb, Wa[.
|
| 40 |
+
"""
|
| 41 |
+
ha, wa = a.shape
|
| 42 |
+
hb, wb = b.shape
|
| 43 |
+
size = (ha + hb, wa + wb)
|
| 44 |
+
fa = np.fft.rfft2(a - a.mean(), s=size)
|
| 45 |
+
fb = np.fft.rfft2(b - b.mean(), s=size)
|
| 46 |
+
cross = fa * np.conj(fb)
|
| 47 |
+
cross /= np.maximum(np.abs(cross), 1e-12)
|
| 48 |
+
surface = np.fft.irfft2(cross, s=size)
|
| 49 |
+
flat = np.argpartition(surface.ravel(), -count)[-count:]
|
| 50 |
+
flat = flat[np.argsort(surface.ravel()[flat])[::-1]]
|
| 51 |
+
result = []
|
| 52 |
+
for index in flat:
|
| 53 |
+
dy, dx = np.unravel_index(int(index), size)
|
| 54 |
+
dy, dx = int(dy), int(dx)
|
| 55 |
+
if dy >= ha:
|
| 56 |
+
dy -= size[0]
|
| 57 |
+
if dx >= wa:
|
| 58 |
+
dx -= size[1]
|
| 59 |
+
result.append((dy, dx))
|
| 60 |
+
return result
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def overlap_ncc(a: np.ndarray, b: np.ndarray, dy: int, dx: int) -> tuple[float, int]:
|
| 64 |
+
"""NCC entre a et b posée en (dy, dx) dans le repère de a, sur leur recouvrement."""
|
| 65 |
+
y0, y1 = max(0, dy), min(a.shape[0], dy + b.shape[0])
|
| 66 |
+
x0, x1 = max(0, dx), min(a.shape[1], dx + b.shape[1])
|
| 67 |
+
if y1 <= y0 or x1 <= x0:
|
| 68 |
+
return -1.0, 0
|
| 69 |
+
pa = a[y0:y1, x0:x1].astype(np.float64)
|
| 70 |
+
pb = b[y0 - dy:y1 - dy, x0 - dx:x1 - dx].astype(np.float64)
|
| 71 |
+
pa = pa - pa.mean()
|
| 72 |
+
pb = pb - pb.mean()
|
| 73 |
+
denominator = math.sqrt(float((pa * pa).sum() * (pb * pb).sum()))
|
| 74 |
+
if denominator <= 1e-12:
|
| 75 |
+
return -1.0, pa.size
|
| 76 |
+
return float((pa * pb).sum() / denominator), pa.size
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _overlaps(y: int, x: int, h: int, w: int, p: Placement) -> bool:
|
| 80 |
+
return y < p.y + p.h and p.y < y + h and x < p.x + p.w and p.x < x + w
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class Mosaic:
|
| 84 |
+
def __init__(self, min_overlap_px: int = 2048, min_ncc: float = 0.9,
|
| 85 |
+
refine_radius: int = 16, candidates: int = 5):
|
| 86 |
+
self.min_overlap_px = min_overlap_px
|
| 87 |
+
self.min_ncc = min_ncc
|
| 88 |
+
self.refine_radius = refine_radius
|
| 89 |
+
self.candidates = candidates
|
| 90 |
+
self.items: dict[str, tuple[Placement, np.ndarray]] = {}
|
| 91 |
+
self.absolute_frame = False # vrai dès qu'une tuile a été posée sur son origine déclarée
|
| 92 |
+
self.reanchored = False # vrai si le dernier placement a translaté toute la mosaïque
|
| 93 |
+
|
| 94 |
+
def __len__(self) -> int:
|
| 95 |
+
return len(self.items)
|
| 96 |
+
|
| 97 |
+
def remove(self, tile_id: str) -> None:
|
| 98 |
+
self.items.pop(tile_id, None)
|
| 99 |
+
if not any(p.method.startswith("origin") for p, _ in self.items.values()):
|
| 100 |
+
self.absolute_frame = False
|
| 101 |
+
|
| 102 |
+
def _best_match(self, array: np.ndarray, nominal: tuple[int, int] | None):
|
| 103 |
+
h, w = array.shape
|
| 104 |
+
best = None
|
| 105 |
+
for anchor_id, (anchor, anchor_array) in self.items.items():
|
| 106 |
+
if nominal is not None:
|
| 107 |
+
r = self.refine_radius
|
| 108 |
+
if not _overlaps(nominal[0] - r, nominal[1] - r, h + 2 * r, w + 2 * r, anchor):
|
| 109 |
+
continue
|
| 110 |
+
for dy, dx in phase_candidates(anchor_array, array, self.candidates):
|
| 111 |
+
y, x = anchor.y + dy, anchor.x + dx
|
| 112 |
+
if nominal is not None and (abs(y - nominal[0]) > self.refine_radius or
|
| 113 |
+
abs(x - nominal[1]) > self.refine_radius):
|
| 114 |
+
continue
|
| 115 |
+
ncc, pixels = overlap_ncc(anchor_array, array, dy, dx)
|
| 116 |
+
if pixels >= self.min_overlap_px and ncc >= self.min_ncc and (best is None or ncc > best[0]):
|
| 117 |
+
best = (ncc, y, x, anchor_id)
|
| 118 |
+
return best
|
| 119 |
+
|
| 120 |
+
def place(self, tile_id: str, array: np.ndarray, origin: tuple[int, int] | None = None) -> Placement | None:
|
| 121 |
+
if array.ndim != 2:
|
| 122 |
+
raise ValueError("image 2D requise")
|
| 123 |
+
h, w = array.shape
|
| 124 |
+
self.remove(tile_id)
|
| 125 |
+
self.reanchored = False
|
| 126 |
+
if origin is not None and self.items and not self.absolute_frame:
|
| 127 |
+
# Mosaïque relative : la tuile repérée doit d'abord se raccorder par l'image ; sa position
|
| 128 |
+
# mesurée donne alors la translation qui ramène toute la mosaïque dans le repère absolu.
|
| 129 |
+
best = self._best_match(array, None)
|
| 130 |
+
if best is None:
|
| 131 |
+
return None
|
| 132 |
+
ncc, y, x, anchor = best
|
| 133 |
+
dy, dx = origin[0] - y, origin[1] - x
|
| 134 |
+
self.items = {key: (dataclass_replace(p, y=p.y + dy, x=p.x + dx), a) for key, (p, a) in self.items.items()}
|
| 135 |
+
placement = Placement(tile_id, origin[0], origin[1], h, w, "origin+reanchored", ncc, anchor)
|
| 136 |
+
self.items[tile_id] = (placement, array)
|
| 137 |
+
self.absolute_frame = True
|
| 138 |
+
self.reanchored = True
|
| 139 |
+
return placement
|
| 140 |
+
if origin is not None:
|
| 141 |
+
best = self._best_match(array, origin)
|
| 142 |
+
if best is None:
|
| 143 |
+
placement = Placement(tile_id, origin[0], origin[1], h, w, "origin")
|
| 144 |
+
else:
|
| 145 |
+
ncc, y, x, anchor = best
|
| 146 |
+
placement = Placement(tile_id, y, x, h, w, "origin+refined", ncc, anchor,
|
| 147 |
+
(y - origin[0], x - origin[1]))
|
| 148 |
+
self.absolute_frame = True
|
| 149 |
+
elif not self.items:
|
| 150 |
+
placement = Placement(tile_id, 0, 0, h, w, "first")
|
| 151 |
+
else:
|
| 152 |
+
best = self._best_match(array, None)
|
| 153 |
+
if best is None:
|
| 154 |
+
return None
|
| 155 |
+
ncc, y, x, anchor = best
|
| 156 |
+
placement = Placement(tile_id, y, x, h, w, "matched", ncc, anchor)
|
| 157 |
+
self.items[tile_id] = (placement, array)
|
| 158 |
+
return placement
|
| 159 |
+
|
| 160 |
+
def placements(self) -> list[Placement]:
|
| 161 |
+
return [p for p, _ in self.items.values()]
|
| 162 |
+
|
| 163 |
+
def composite(self, max_side: int = 2048):
|
| 164 |
+
"""Vue plane moyennée, sous-échantillonnée ; rend (image uint8, infos) ou None."""
|
| 165 |
+
if not self.items:
|
| 166 |
+
return None
|
| 167 |
+
placements = self.placements()
|
| 168 |
+
y0 = min(p.y for p in placements)
|
| 169 |
+
x0 = min(p.x for p in placements)
|
| 170 |
+
y1 = max(p.y + p.h for p in placements)
|
| 171 |
+
x1 = max(p.x + p.w for p in placements)
|
| 172 |
+
step = max(1, math.ceil(max(y1 - y0, x1 - x0) / max_side))
|
| 173 |
+
height, width = math.ceil((y1 - y0) / step), math.ceil((x1 - x0) / step)
|
| 174 |
+
total = np.zeros((height, width), dtype=np.float64)
|
| 175 |
+
count = np.zeros((height, width), dtype=np.uint16)
|
| 176 |
+
for placement, array in self.items.values():
|
| 177 |
+
sub = array[::step, ::step]
|
| 178 |
+
ty, tx = (placement.y - y0) // step, (placement.x - x0) // step
|
| 179 |
+
sh, sw = min(sub.shape[0], height - ty), min(sub.shape[1], width - tx)
|
| 180 |
+
total[ty:ty + sh, tx:tx + sw] += sub[:sh, :sw]
|
| 181 |
+
count[ty:ty + sh, tx:tx + sw] += 1
|
| 182 |
+
image = np.zeros((height, width), dtype=np.uint8)
|
| 183 |
+
covered = count > 0
|
| 184 |
+
image[covered] = np.clip(np.rint(255 * total[covered] / count[covered]), 0, 255).astype(np.uint8)
|
| 185 |
+
info = {"y0": y0, "x0": x0, "step": step, "height": height, "width": width,
|
| 186 |
+
"covered_px": int(covered.sum()) * step * step}
|
| 187 |
+
return image, info
|
herc/text.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Assemblage du texte : mots des tuiles posées, replacés sur la surface et triés en ordre de lecture.
|
| 2 |
+
|
| 3 |
+
Ordre : colonne (gauche → droite), puis ligne (haut → bas), puis position horizontale.
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import statistics
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
|
| 10 |
+
from .lexicon import Lexicon, normalize
|
| 11 |
+
from .stitching import Placement
|
| 12 |
+
from .tiles import Tile
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@dataclass(frozen=True)
|
| 16 |
+
class GlobalWord:
|
| 17 |
+
key: str
|
| 18 |
+
tile_id: str
|
| 19 |
+
text: str
|
| 20 |
+
normalized: str
|
| 21 |
+
confidence: float
|
| 22 |
+
source: str | None
|
| 23 |
+
bbox: tuple[int, int, int, int] # y, x, h, w dans le repère de la mosaïque
|
| 24 |
+
column: int
|
| 25 |
+
line: int
|
| 26 |
+
restored_fraction: float
|
| 27 |
+
glosses: tuple[dict, ...]
|
| 28 |
+
|
| 29 |
+
def view(self) -> dict:
|
| 30 |
+
return {"key": self.key, "tile_id": self.tile_id, "text": self.text, "normalized": self.normalized,
|
| 31 |
+
"confidence": self.confidence, "source": self.source, "bbox": list(self.bbox),
|
| 32 |
+
"column": self.column, "line": self.line, "restored_fraction": self.restored_fraction,
|
| 33 |
+
"glosses": list(self.glosses)}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def restored_fraction(text: str) -> float:
|
| 37 |
+
"""Part des lettres entre crochets [ ] : restituées par l'éditeur, non lues."""
|
| 38 |
+
letters = restored = 0
|
| 39 |
+
inside = False
|
| 40 |
+
for char in text:
|
| 41 |
+
if char == "[":
|
| 42 |
+
inside = True
|
| 43 |
+
elif char == "]":
|
| 44 |
+
inside = False
|
| 45 |
+
elif char.isalpha():
|
| 46 |
+
letters += 1
|
| 47 |
+
restored += inside
|
| 48 |
+
return round(restored / letters, 4) if letters else 0.0
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def assemble(entries: list[tuple[Placement, Tile]], lexicon: Lexicon,
|
| 52 |
+
column_width: int = 0, line_tolerance: float = 0.6, x_origin: int | None = None) -> list[GlobalWord]:
|
| 53 |
+
"""x_origin : abscisse de début de la première colonne (défaut : bord gauche de la mosaïque)."""
|
| 54 |
+
if x_origin is None:
|
| 55 |
+
x_origin = min((p.x for p, _ in entries), default=0)
|
| 56 |
+
raw = []
|
| 57 |
+
for placement, tile in entries:
|
| 58 |
+
for index, word in enumerate(tile.words):
|
| 59 |
+
y, x, h, w = word.bbox
|
| 60 |
+
gy, gx = placement.y + y, placement.x + x
|
| 61 |
+
column = int((gx - x_origin + w / 2) // column_width) if column_width > 0 else 0
|
| 62 |
+
raw.append((column, gy + h / 2, gx, tile, index, word, (gy, gx, h, w)))
|
| 63 |
+
if not raw:
|
| 64 |
+
return []
|
| 65 |
+
median_height = statistics.median(item[6][2] for item in raw)
|
| 66 |
+
threshold = line_tolerance * median_height
|
| 67 |
+
ordered: list[GlobalWord] = []
|
| 68 |
+
for column in sorted({item[0] for item in raw}):
|
| 69 |
+
items = sorted((i for i in raw if i[0] == column), key=lambda i: (i[1], i[2]))
|
| 70 |
+
lines: list[list] = []
|
| 71 |
+
reference = None
|
| 72 |
+
for item in items:
|
| 73 |
+
if reference is None or item[1] - reference > threshold:
|
| 74 |
+
lines.append([item])
|
| 75 |
+
else:
|
| 76 |
+
lines[-1].append(item)
|
| 77 |
+
reference = statistics.fmean(i[1] for i in lines[-1])
|
| 78 |
+
for line_number, line in enumerate(lines):
|
| 79 |
+
for _, _, _, tile, index, word, bbox in sorted(line, key=lambda i: i[2]):
|
| 80 |
+
entries_found = lexicon.lookup(word.text)
|
| 81 |
+
ordered.append(GlobalWord(
|
| 82 |
+
key=f"{tile.id}:{index}", tile_id=tile.id, text=word.text, normalized=normalize(word.text),
|
| 83 |
+
confidence=word.confidence, source=tile.source, bbox=bbox, column=column, line=line_number,
|
| 84 |
+
restored_fraction=restored_fraction(word.text),
|
| 85 |
+
glosses=tuple({"lemma": e.lemma, "pos": e.pos, "gloss": e.gloss} for e in entries_found)))
|
| 86 |
+
return ordered
|
herc/tiles.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lecture stricte d'une tuile validée : <id>.json (métadonnées) + <id>.png (carte d'encre).
|
| 2 |
+
|
| 3 |
+
Format du JSON (champs inconnus refusés) :
|
| 4 |
+
|
| 5 |
+
{
|
| 6 |
+
"id": "r0_c1", # = nom du fichier, [A-Za-z0-9_-]{1,64}
|
| 7 |
+
"validated": true, # tant que false/absent, la tuile est ignorée
|
| 8 |
+
"segment": "PHerc0841/w00", # facultatif
|
| 9 |
+
"origin_yx": [y, x], # facultatif : position déclarée dans le repère de la surface
|
| 10 |
+
"surface_xyz": [[x,y,z] x 4], # facultatif : coins 3D (haut-gauche, haut-droit, bas-droit, bas-gauche)
|
| 11 |
+
"transcription": { # facultatif
|
| 12 |
+
"source": "human" | "model" | "demo",
|
| 13 |
+
"reviewer": "nom", # facultatif
|
| 14 |
+
"words": [{"text": "ἡδονήν", "bbox": [y, x, h, w], "confidence": 0.9}]
|
| 15 |
+
}
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
Les mots peuvent porter les signes éditoriaux de Leyde ([ ] ( ) ⟨ ⟩ et point souscrit).
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import json
|
| 23 |
+
import math
|
| 24 |
+
import re
|
| 25 |
+
import unicodedata
|
| 26 |
+
from dataclasses import dataclass
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
from PIL import Image
|
| 31 |
+
|
| 32 |
+
from .config import Config
|
| 33 |
+
|
| 34 |
+
ID_RE = re.compile(r"[A-Za-z0-9_-]{1,64}")
|
| 35 |
+
SOURCES = ("human", "model", "demo")
|
| 36 |
+
EDITORIAL = set("[]()⟨⟩{}.·'’ʼ-")
|
| 37 |
+
TOP_LEVEL = {"id", "validated", "segment", "origin_yx", "surface_xyz", "transcription"}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TileError(ValueError):
|
| 41 |
+
"""Tuile refusée ; le message est affiché tel quel dans l'interface."""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@dataclass(frozen=True)
|
| 45 |
+
class Word:
|
| 46 |
+
text: str
|
| 47 |
+
bbox: tuple[int, int, int, int] # y, x, h, w dans le repère de la tuile
|
| 48 |
+
confidence: float
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@dataclass(frozen=True)
|
| 52 |
+
class Tile:
|
| 53 |
+
id: str
|
| 54 |
+
segment: str
|
| 55 |
+
image_path: Path
|
| 56 |
+
origin_yx: tuple[int, int] | None
|
| 57 |
+
surface_xyz: tuple[tuple[float, float, float], ...] | None
|
| 58 |
+
source: str | None
|
| 59 |
+
reviewer: str | None
|
| 60 |
+
words: tuple[Word, ...]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _int(value, name: str, minimum: int | None = None) -> int:
|
| 64 |
+
if type(value) is not int: # bool exclu volontairement
|
| 65 |
+
raise TileError(f"{name} : entier requis")
|
| 66 |
+
if minimum is not None and value < minimum:
|
| 67 |
+
raise TileError(f"{name} : valeur minimale {minimum}")
|
| 68 |
+
return value
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _number(value, name: str) -> float:
|
| 72 |
+
if type(value) not in (int, float) or not math.isfinite(value):
|
| 73 |
+
raise TileError(f"{name} : nombre fini requis")
|
| 74 |
+
return float(value)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _text(value, name: str, max_length: int) -> str:
|
| 78 |
+
if not isinstance(value, str) or not 1 <= len(value) <= max_length:
|
| 79 |
+
raise TileError(f"{name} : texte de 1 à {max_length} caractères requis")
|
| 80 |
+
if any(unicodedata.category(c).startswith("C") for c in value):
|
| 81 |
+
raise TileError(f"{name} : caractères de contrôle interdits")
|
| 82 |
+
return value
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _word_text(value, name: str) -> str:
|
| 86 |
+
text = _text(value, name, 64)
|
| 87 |
+
for char in text:
|
| 88 |
+
if unicodedata.category(char)[0] not in "LM" and char not in EDITORIAL:
|
| 89 |
+
raise TileError(f"{name} : caractère non autorisé U+{ord(char):04X}")
|
| 90 |
+
if not any(unicodedata.category(c)[0] == "L" for c in text):
|
| 91 |
+
raise TileError(f"{name} : au moins une lettre requise")
|
| 92 |
+
return text
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def parse_tile(json_path: Path, cfg: Config) -> Tile | None:
|
| 96 |
+
"""Rend la tuile, None si elle n'est pas encore validée, ou lève TileError."""
|
| 97 |
+
json_path = Path(json_path)
|
| 98 |
+
if json_path.suffix != ".json" or not ID_RE.fullmatch(json_path.stem):
|
| 99 |
+
raise TileError("nom de fichier de tuile invalide (attendu : [A-Za-z0-9_-]{1,64}.json)")
|
| 100 |
+
if json_path.stat().st_size > cfg.max_json_bytes:
|
| 101 |
+
raise TileError("fichier JSON trop volumineux")
|
| 102 |
+
try:
|
| 103 |
+
data = json.loads(json_path.read_text(encoding="utf-8"))
|
| 104 |
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
| 105 |
+
raise TileError(f"JSON illisible : {exc}") from None
|
| 106 |
+
if not isinstance(data, dict):
|
| 107 |
+
raise TileError("objet JSON requis")
|
| 108 |
+
unknown = set(data) - TOP_LEVEL
|
| 109 |
+
if unknown:
|
| 110 |
+
raise TileError("champs inconnus : " + ", ".join(sorted(unknown)))
|
| 111 |
+
if data.get("validated") is not True:
|
| 112 |
+
return None
|
| 113 |
+
if data.get("id") != json_path.stem:
|
| 114 |
+
raise TileError("'id' doit être égal au nom du fichier")
|
| 115 |
+
segment = _text(data.get("segment", "inconnu"), "segment", 120)
|
| 116 |
+
|
| 117 |
+
origin = data.get("origin_yx")
|
| 118 |
+
if origin is not None:
|
| 119 |
+
if not isinstance(origin, list) or len(origin) != 2:
|
| 120 |
+
raise TileError("origin_yx : [y, x] requis")
|
| 121 |
+
origin = (_int(origin[0], "origin_yx[0]"), _int(origin[1], "origin_yx[1]"))
|
| 122 |
+
|
| 123 |
+
surface = data.get("surface_xyz")
|
| 124 |
+
if surface is not None:
|
| 125 |
+
if not isinstance(surface, list) or len(surface) != 4:
|
| 126 |
+
raise TileError("surface_xyz : quatre coins [x, y, z] requis")
|
| 127 |
+
corners = []
|
| 128 |
+
for i, corner in enumerate(surface):
|
| 129 |
+
if not isinstance(corner, list) or len(corner) != 3:
|
| 130 |
+
raise TileError(f"surface_xyz[{i}] : [x, y, z] requis")
|
| 131 |
+
corners.append(tuple(_number(v, f"surface_xyz[{i}]") for v in corner))
|
| 132 |
+
surface = tuple(corners)
|
| 133 |
+
|
| 134 |
+
source = reviewer = None
|
| 135 |
+
words: list[Word] = []
|
| 136 |
+
transcription = data.get("transcription")
|
| 137 |
+
if transcription is not None:
|
| 138 |
+
if not isinstance(transcription, dict) or set(transcription) - {"source", "reviewer", "words"}:
|
| 139 |
+
raise TileError("transcription : champs source, reviewer, words uniquement")
|
| 140 |
+
source = transcription.get("source")
|
| 141 |
+
if source not in SOURCES:
|
| 142 |
+
raise TileError("transcription.source : human, model ou demo")
|
| 143 |
+
if transcription.get("reviewer") is not None:
|
| 144 |
+
reviewer = _text(transcription["reviewer"], "transcription.reviewer", 120)
|
| 145 |
+
raw = transcription.get("words", [])
|
| 146 |
+
if not isinstance(raw, list) or len(raw) > cfg.max_words_per_tile:
|
| 147 |
+
raise TileError(f"transcription.words : liste de {cfg.max_words_per_tile} mots au plus")
|
| 148 |
+
for i, item in enumerate(raw):
|
| 149 |
+
name = f"words[{i}]"
|
| 150 |
+
if not isinstance(item, dict) or set(item) - {"text", "bbox", "confidence"}:
|
| 151 |
+
raise TileError(f"{name} : champs text, bbox, confidence uniquement")
|
| 152 |
+
text = _word_text(item.get("text"), name + ".text")
|
| 153 |
+
bbox = item.get("bbox")
|
| 154 |
+
if not isinstance(bbox, list) or len(bbox) != 4:
|
| 155 |
+
raise TileError(f"{name}.bbox : [y, x, h, w] requis")
|
| 156 |
+
y, x, h, w = (_int(v, name + ".bbox", 0) for v in bbox)
|
| 157 |
+
if h < 1 or w < 1:
|
| 158 |
+
raise TileError(f"{name}.bbox : hauteur et largeur positives requises")
|
| 159 |
+
confidence = item.get("confidence", 1.0 if source == "human" else None)
|
| 160 |
+
if confidence is None:
|
| 161 |
+
raise TileError(f"{name}.confidence requis pour une source {source}")
|
| 162 |
+
confidence = _number(confidence, name + ".confidence")
|
| 163 |
+
if not 0.0 <= confidence <= 1.0:
|
| 164 |
+
raise TileError(f"{name}.confidence : valeur dans [0, 1] requise")
|
| 165 |
+
words.append(Word(text, (y, x, h, w), confidence))
|
| 166 |
+
|
| 167 |
+
return Tile(
|
| 168 |
+
id=json_path.stem,
|
| 169 |
+
segment=segment,
|
| 170 |
+
image_path=json_path.with_suffix(".png"),
|
| 171 |
+
origin_yx=origin,
|
| 172 |
+
surface_xyz=surface,
|
| 173 |
+
source=source,
|
| 174 |
+
reviewer=reviewer,
|
| 175 |
+
words=tuple(words),
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def load_image(path: Path, cfg: Config) -> np.ndarray:
|
| 180 |
+
"""Charge le PNG en float32 dans [0, 1], après contrôle de format et de taille."""
|
| 181 |
+
path = Path(path)
|
| 182 |
+
if not path.is_file():
|
| 183 |
+
raise TileError("image absente : " + path.name)
|
| 184 |
+
if path.stat().st_size > cfg.max_image_bytes:
|
| 185 |
+
raise TileError("image trop volumineuse")
|
| 186 |
+
side = cfg.max_tile_side
|
| 187 |
+
try:
|
| 188 |
+
with Image.open(path) as image:
|
| 189 |
+
if image.format != "PNG":
|
| 190 |
+
raise TileError("image PNG requise")
|
| 191 |
+
width, height = image.size # lu dans l'en-tête, avant décodage
|
| 192 |
+
if not (8 <= width <= side and 8 <= height <= side):
|
| 193 |
+
raise TileError(f"dimensions {width}×{height} hors limites (8 à {side})")
|
| 194 |
+
mode = image.mode
|
| 195 |
+
if mode in ("1", "L", "P", "LA", "RGB", "RGBA"):
|
| 196 |
+
array = np.asarray(image.convert("L"), dtype=np.float32) / 255.0
|
| 197 |
+
elif mode in ("I;16", "I;16B", "I;16L", "I"):
|
| 198 |
+
array = np.clip(np.asarray(image, dtype=np.float32), 0, 65535) / 65535.0
|
| 199 |
+
elif mode == "F":
|
| 200 |
+
array = np.asarray(image, dtype=np.float32)
|
| 201 |
+
if array.size and (array.min() < 0.0 or array.max() > 1.0):
|
| 202 |
+
raise TileError("image flottante hors de [0, 1]")
|
| 203 |
+
else:
|
| 204 |
+
raise TileError(f"mode d'image non pris en charge : {mode}")
|
| 205 |
+
except TileError:
|
| 206 |
+
raise
|
| 207 |
+
except (OSError, ValueError, Image.DecompressionBombError) as exc:
|
| 208 |
+
raise TileError(f"image illisible : {type(exc).__name__}") from None
|
| 209 |
+
if not np.isfinite(array).all():
|
| 210 |
+
raise TileError("image contenant des valeurs non finies")
|
| 211 |
+
return np.ascontiguousarray(array)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def check_words_inside(tile: Tile, shape: tuple[int, int]) -> None:
|
| 215 |
+
height, width = shape
|
| 216 |
+
for i, word in enumerate(tile.words):
|
| 217 |
+
y, x, h, w = word.bbox
|
| 218 |
+
if y + h > height or x + w > width:
|
| 219 |
+
raise TileError(f"words[{i}].bbox déborde de l'image {width}×{height}")
|
herc/watcher.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Worker asynchrone : surveille le dossier d'entrée et ingère chaque tuile une fois stable.
|
| 2 |
+
|
| 3 |
+
Une tuile est prise quand la signature (taille + date) de <id>.json et de <id>.png est identique
|
| 4 |
+
sur deux passages successifs : un fichier en cours d'écriture n'est jamais lu. Une tuile modifiée
|
| 5 |
+
ensuite (validation, correction de transcription) est relue automatiquement.
|
| 6 |
+
Interrogation périodique en bibliothèque standard : aucune dépendance système.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import asyncio
|
| 11 |
+
import logging
|
| 12 |
+
from collections.abc import Awaitable, Callable
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
from .config import Config
|
| 16 |
+
from .pipeline import Pipeline
|
| 17 |
+
from .tiles import ID_RE
|
| 18 |
+
|
| 19 |
+
log = logging.getLogger("herc.watcher")
|
| 20 |
+
Signature = tuple
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TileWatcher:
|
| 24 |
+
def __init__(self, cfg: Config, pipeline: Pipeline, publish: Callable[[dict], Awaitable[None]]):
|
| 25 |
+
self.cfg = cfg
|
| 26 |
+
self.pipeline = pipeline
|
| 27 |
+
self.publish = publish
|
| 28 |
+
self.last: dict[str, Signature] = {}
|
| 29 |
+
self.done: dict[str, Signature] = {}
|
| 30 |
+
|
| 31 |
+
@staticmethod
|
| 32 |
+
def signature(json_path: Path) -> Signature:
|
| 33 |
+
js = json_path.stat()
|
| 34 |
+
png = json_path.with_suffix(".png")
|
| 35 |
+
try:
|
| 36 |
+
ps = png.stat()
|
| 37 |
+
image = (ps.st_size, ps.st_mtime_ns)
|
| 38 |
+
except FileNotFoundError:
|
| 39 |
+
image = None
|
| 40 |
+
return (js.st_size, js.st_mtime_ns, image)
|
| 41 |
+
|
| 42 |
+
def scan(self) -> list[Path]:
|
| 43 |
+
folder = Path(self.cfg.tiles_dir)
|
| 44 |
+
if not folder.is_dir():
|
| 45 |
+
return []
|
| 46 |
+
ready, present = [], set()
|
| 47 |
+
for path in sorted(folder.iterdir()):
|
| 48 |
+
if path.suffix != ".json" or not ID_RE.fullmatch(path.stem) or not path.is_file():
|
| 49 |
+
continue
|
| 50 |
+
present.add(path.name)
|
| 51 |
+
try:
|
| 52 |
+
sig = self.signature(path)
|
| 53 |
+
except FileNotFoundError:
|
| 54 |
+
continue
|
| 55 |
+
if self.done.get(path.name) == sig:
|
| 56 |
+
continue
|
| 57 |
+
if self.last.get(path.name) == sig:
|
| 58 |
+
ready.append(path)
|
| 59 |
+
self.last[path.name] = sig
|
| 60 |
+
for name in set(self.last) - present:
|
| 61 |
+
self.last.pop(name, None)
|
| 62 |
+
self.done.pop(name, None)
|
| 63 |
+
return ready
|
| 64 |
+
|
| 65 |
+
def mark_done(self, path: Path) -> None:
|
| 66 |
+
if path.name in self.last:
|
| 67 |
+
self.done[path.name] = self.last[path.name]
|
| 68 |
+
|
| 69 |
+
async def process(self, path: Path) -> None:
|
| 70 |
+
try:
|
| 71 |
+
events = await asyncio.to_thread(self.pipeline.ingest, path)
|
| 72 |
+
except Exception as exc: # le worker ne doit jamais s'arrêter sur une tuile
|
| 73 |
+
log.exception("échec inattendu sur %s", path.name)
|
| 74 |
+
events = [{"type": "rejected", "name": path.stem, "reason": f"erreur interne : {type(exc).__name__}"}]
|
| 75 |
+
self.mark_done(path)
|
| 76 |
+
for event in events:
|
| 77 |
+
await self.publish(event)
|
| 78 |
+
|
| 79 |
+
async def run(self, stop: asyncio.Event) -> None:
|
| 80 |
+
log.info("surveillance de %s", Path(self.cfg.tiles_dir).resolve())
|
| 81 |
+
while not stop.is_set():
|
| 82 |
+
for path in await asyncio.to_thread(self.scan):
|
| 83 |
+
await self.process(path)
|
| 84 |
+
try:
|
| 85 |
+
await asyncio.wait_for(stop.wait(), self.cfg.poll_interval)
|
| 86 |
+
except asyncio.TimeoutError:
|
| 87 |
+
pass
|
requirements.txt
CHANGED
|
@@ -1,31 +1,7 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
trl==1.17.1
|
| 7 |
-
datasets>=3.0,<6
|
| 8 |
-
accelerate>=1.0
|
| 9 |
-
safetensors>=0.4.5
|
| 10 |
-
huggingface_hub>=2.4,<3
|
| 11 |
-
pydantic>=2.7,<3
|
| 12 |
-
# FIX(AUDIT): version épinglée ; la plage >=5.0,<7 a cassé l'interface à deux reconstructions (4.21.4, 4.21.5).
|
| 13 |
-
gradio==6.32.0
|
| 14 |
-
z3-solver>=4.12
|
| 15 |
pytest>=8.0
|
| 16 |
-
|
| 17 |
-
mujoco>=3.3,<4 # banc d'essai dynamique du laboratoire (v4.5) : corps rigides, contacts, hélices ; CPU, sans rendu
|
| 18 |
-
# v4.6 : bibliothèques du laboratoire, importables par le code de l'agent dans le bac à sable (liste blanche)
|
| 19 |
-
scipy>=1.11,<2 # optimisation, algèbre linéaire, intégration
|
| 20 |
-
sympy>=1.12,<2 # calcul symbolique
|
| 21 |
-
pint>=0.23,<1 # unités physiques
|
| 22 |
-
networkx>=3.2,<4 # graphes
|
| 23 |
-
simpy>=4.1,<5 # simulation à événements discrets
|
| 24 |
-
trimesh>=4.0,<6 # maillages
|
| 25 |
-
manifold3d>=2.4,<4 # géométrie solide constructive (CSG)
|
| 26 |
-
scikit-fem>=9.0,<13 # éléments finis (volumes, plaques)
|
| 27 |
-
control>=0.10,<1 # automatique : fonctions de transfert, stabilité
|
| 28 |
-
tetgen>=0.8,<1 # v4.9 : maillage en tétraèdres des pièces solides (atelier mécanique) ; roue abi3, numpy seul
|
| 29 |
-
|
| 30 |
-
# Laboratoire Vesuvius, imports lourds uniquement dans les jobs manuels.
|
| 31 |
-
-r requirements-vesuvius.txt
|
|
|
|
| 1 |
+
fastapi>=0.110
|
| 2 |
+
uvicorn>=0.29
|
| 3 |
+
numpy>=1.26
|
| 4 |
+
pillow>=10.0
|
| 5 |
+
# tests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
pytest>=8.0
|
| 7 |
+
httpx>=0.27
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/conftest.py
CHANGED
|
@@ -1,13 +1,6 @@
|
|
| 1 |
-
import os
|
| 2 |
import sys
|
| 3 |
from pathlib import Path
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
import torch
|
| 9 |
-
|
| 10 |
-
if not torch.cuda.is_available():
|
| 11 |
-
os.environ.setdefault("TRITON_INTERPRET", "1")
|
| 12 |
-
except ImportError: # pragma: no cover
|
| 13 |
-
pass
|
|
|
|
|
|
|
| 1 |
import sys
|
| 2 |
from pathlib import Path
|
| 3 |
|
| 4 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 5 |
+
sys.path.insert(0, str(ROOT))
|
| 6 |
+
sys.path.insert(0, str(ROOT / "tools"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/helpers.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def texture(height=600, width=800, seed=0):
|
| 9 |
+
rng = np.random.default_rng(seed)
|
| 10 |
+
noise = rng.normal(size=(height, width))
|
| 11 |
+
fy = np.fft.fftfreq(height)[:, None]
|
| 12 |
+
fx = np.fft.rfftfreq(width)[None, :]
|
| 13 |
+
smooth = np.fft.irfft2(np.fft.rfft2(noise) * np.exp(-(fx ** 2 + fy ** 2) * 1500), s=(height, width))
|
| 14 |
+
image = smooth / smooth.std() + rng.normal(scale=0.5, size=(height, width))
|
| 15 |
+
return ((image - image.min()) / (image.max() - image.min())).astype(np.float32)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def write_tile(folder: Path, tile_id: str, array=None, **meta):
|
| 19 |
+
folder.mkdir(parents=True, exist_ok=True)
|
| 20 |
+
if array is None:
|
| 21 |
+
array = texture(64, 64)
|
| 22 |
+
Image.fromarray(np.rint(np.asarray(array) * 255).astype(np.uint8), mode="L").save(folder / f"{tile_id}.png")
|
| 23 |
+
data = {"id": tile_id, "validated": True, **meta}
|
| 24 |
+
(folder / f"{tile_id}.json").write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
| 25 |
+
return folder / f"{tile_id}.json"
|
tests/test_audit.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from ast_audit import audit_javascript, audit_paths, audit_python
|
| 6 |
+
|
| 7 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_project_sources_have_no_unsafe_construct():
|
| 11 |
+
findings = audit_paths([ROOT / "herc", ROOT / "tools", ROOT / "tests"])
|
| 12 |
+
assert findings == [], "\n".join(map(str, findings))
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.mark.parametrize("source", [
|
| 16 |
+
"eval('1')", "exec('x=1')", "__import__('os')", "import subprocess", "from pickle import loads",
|
| 17 |
+
"import os\nos.system('ls')", "from os import popen", "import numpy as np\nnp.load('f', allow_pickle=True)",
|
| 18 |
+
"import torch\ntorch.load('w')", "run('ls', shell=True)", "().__class__.__subclasses__()",
|
| 19 |
+
"import yaml\nyaml.load(s)",
|
| 20 |
+
])
|
| 21 |
+
def test_unsafe_python_is_detected(source):
|
| 22 |
+
assert audit_python(source)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_safe_python_passes():
|
| 26 |
+
assert audit_python("import json\njson.loads('{}')\nimport torch\ntorch.load('w', weights_only=True)") == []
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@pytest.mark.parametrize("source", ["node.innerHTML = x;", "eval(s)", "new Function('a')", "setTimeout('x()', 1)",
|
| 30 |
+
"document.write(x)"])
|
| 31 |
+
def test_unsafe_javascript_is_detected(source):
|
| 32 |
+
assert audit_javascript(source)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_javascript_comments_are_ignored():
|
| 36 |
+
assert audit_javascript("node.textContent = x; // pas de innerHTML") == []
|
tests/test_lexicon.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
|
| 5 |
+
from herc.config import Config
|
| 6 |
+
from herc.lexicon import Lexicon, normalize
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@pytest.fixture(scope="module")
|
| 10 |
+
def lexicon():
|
| 11 |
+
return Lexicon.load(Config().lexicon_path)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_normalization_strips_accents_breathings_leiden_signs_and_final_sigma():
|
| 15 |
+
assert normalize("ἡδονήν") == "ηδονην"
|
| 16 |
+
assert normalize("[ἡδο]νὴν") == "ηδονην"
|
| 17 |
+
assert normalize("Ἐπίκουρος") == "επικουροσ"
|
| 18 |
+
assert normalize("ἡμᾶς") == normalize("ημασ")
|
| 19 |
+
assert normalize("δ'") == "δ"
|
| 20 |
+
assert normalize("λόγῳ") == "λογω" # iota souscrit retiré avec les diacritiques
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_lookup_returns_lemma_and_gloss(lexicon):
|
| 24 |
+
(entry,) = lexicon.lookup("ἡδονήν")
|
| 25 |
+
assert entry.lemma == "ἡδονή" and entry.gloss == "plaisir" and entry.pos == "nom"
|
| 26 |
+
assert lexicon.lookup("θανάτου")[0].lemma == "θάνατος"
|
| 27 |
+
assert lexicon.lookup("[ἡδο]νὴν")[0].lemma == "ἡδονή"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_ambiguous_forms_return_every_lemma(lexicon):
|
| 31 |
+
lemmas = {e.lemma for e in lexicon.lookup("ἢ")}
|
| 32 |
+
assert lemmas == {"ὁ", "ἤ"} # article ἡ et conjonction ἤ ont la même forme normalisée
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_unknown_word_returns_nothing(lexicon):
|
| 36 |
+
assert lexicon.lookup("ξυλοφάγος") == ()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_every_demo_word_is_in_the_lexicon(lexicon):
|
| 40 |
+
from make_demo_tiles import EXPECTED
|
| 41 |
+
assert all(lexicon.lookup(token) for token in EXPECTED.split())
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_bundled_lexicon_is_well_formed(lexicon):
|
| 45 |
+
data = json.loads(Config().lexicon_path.read_text(encoding="utf-8"))
|
| 46 |
+
assert lexicon.size == len(data["entries"]) >= 70
|
| 47 |
+
assert len({e["lemma"] for e in data["entries"]}) == lexicon.size
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@pytest.mark.parametrize("entry", [{"lemma": "x"}, {"lemma": "", "pos": "nom", "gloss": "g", "forms": ["a"]},
|
| 51 |
+
{"lemma": "a", "pos": "nom", "gloss": "g", "forms": []},
|
| 52 |
+
{"lemma": "a", "pos": "nom", "gloss": "g", "forms": ["[]"]}])
|
| 53 |
+
def test_malformed_entries_are_refused(entry):
|
| 54 |
+
with pytest.raises(ValueError):
|
| 55 |
+
Lexicon([entry])
|
tests/test_pipeline.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import random
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from helpers import write_tile
|
| 8 |
+
from herc.config import Config
|
| 9 |
+
from herc.pipeline import Pipeline
|
| 10 |
+
from herc.tiles import Word
|
| 11 |
+
from make_demo_tiles import COLS, EXPECTED, ROWS, STRIDE, build
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@pytest.fixture(scope="module")
|
| 15 |
+
def demo(tmp_path_factory):
|
| 16 |
+
folder = tmp_path_factory.mktemp("demo")
|
| 17 |
+
build(folder)
|
| 18 |
+
return folder
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@pytest.mark.parametrize("seed", [0, 1, 2])
|
| 22 |
+
def test_demo_tiles_in_any_arrival_order_give_exact_positions_and_text(demo, seed):
|
| 23 |
+
pipeline = Pipeline(Config(column_width=800))
|
| 24 |
+
files = sorted(demo.glob("*.json"))
|
| 25 |
+
random.Random(seed).shuffle(files)
|
| 26 |
+
events = [e for f in files for e in pipeline.ingest(f)]
|
| 27 |
+
snapshot = pipeline.snapshot()
|
| 28 |
+
assert len(snapshot["tiles"]) == ROWS * COLS and not pipeline.pending
|
| 29 |
+
for tile in snapshot["tiles"]:
|
| 30 |
+
r, c = int(tile["id"][6]), int(tile["id"][9])
|
| 31 |
+
assert (tile["placement"]["y"], tile["placement"]["x"]) == (r * STRIDE, c * STRIDE)
|
| 32 |
+
assert " ".join(w["text"] for w in snapshot["words"]) == EXPECTED
|
| 33 |
+
stats = snapshot["stats"]
|
| 34 |
+
assert stats["words_decoded"] == len(EXPECTED.split()) == stats["words_glossed"]
|
| 35 |
+
assert stats["words_by_source"] == {"demo": len(EXPECTED.split())}
|
| 36 |
+
assert 0 < stats["mean_confidence"] <= 1 and stats["covered_px"] > 0
|
| 37 |
+
assert {e["type"] for e in events} >= {"tile", "text", "stats"}
|
| 38 |
+
assert pipeline.mosaic_png()[:8] == b"\x89PNG\r\n\x1a\n"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_rejected_tile_is_reported_and_accepted_after_correction(tmp_path):
|
| 42 |
+
pipeline = Pipeline(Config())
|
| 43 |
+
path = write_tile(tmp_path, "t", transcription={"source": "model", "words": [{"text": "λόγος", "bbox": [0, 0, 1, 1]}]})
|
| 44 |
+
(event,) = pipeline.ingest(path)
|
| 45 |
+
assert event["type"] == "rejected" and "confidence" in event["reason"] and pipeline.stats()["tiles_rejected"] == 1
|
| 46 |
+
write_tile(tmp_path, "t", transcription={"source": "model", "words": [{"text": "λόγος", "bbox": [0, 0, 8, 8], "confidence": 0.4}]})
|
| 47 |
+
events = pipeline.ingest(path)
|
| 48 |
+
assert events[0]["tile"]["status"] == "placed" and pipeline.stats()["tiles_rejected"] == 0
|
| 49 |
+
assert pipeline.words[0].glosses[0]["lemma"] == "λόγος"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_unvalidated_tile_produces_no_event_and_missing_image_is_rejected(tmp_path):
|
| 53 |
+
pipeline = Pipeline(Config())
|
| 54 |
+
path = write_tile(tmp_path, "u")
|
| 55 |
+
data = json.loads(path.read_text())
|
| 56 |
+
data["validated"] = False
|
| 57 |
+
path.write_text(json.dumps(data))
|
| 58 |
+
assert pipeline.ingest(path) == [] and pipeline.stats()["tiles_processed"] == 0
|
| 59 |
+
data["validated"] = True
|
| 60 |
+
path.write_text(json.dumps(data))
|
| 61 |
+
(tmp_path / "u.png").unlink()
|
| 62 |
+
assert "absente" in pipeline.ingest(path)[0]["reason"]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def test_reingesting_a_tile_replaces_its_words_without_duplicates(tmp_path):
|
| 66 |
+
pipeline = Pipeline(Config())
|
| 67 |
+
path = write_tile(tmp_path, "t", transcription={"source": "human", "words": [{"text": "καὶ", "bbox": [0, 0, 4, 4]}]})
|
| 68 |
+
pipeline.ingest(path)
|
| 69 |
+
write_tile(tmp_path, "t", transcription={"source": "human", "words": [{"text": "θεός", "bbox": [0, 0, 4, 4]}]})
|
| 70 |
+
pipeline.ingest(path)
|
| 71 |
+
assert [w.text for w in pipeline.words] == ["θεός"] and len(pipeline.mosaic) == 1
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_tile_without_transcription_uses_the_recognizer_and_null_recognizer_adds_nothing(tmp_path):
|
| 75 |
+
class Fixed:
|
| 76 |
+
def recognize(self, image, tile):
|
| 77 |
+
return (Word("ψυχή", (1, 1, 4, 4), 0.7),)
|
| 78 |
+
path = write_tile(tmp_path, "t")
|
| 79 |
+
assert Pipeline(Config()).ingest(path)[-1]["stats"]["words_decoded"] == 0
|
| 80 |
+
pipeline = Pipeline(Config(), recognizer=Fixed())
|
| 81 |
+
pipeline.ingest(path)
|
| 82 |
+
assert pipeline.words[0].source == "model" and pipeline.words[0].confidence == 0.7
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def test_snapshot_is_json_serialisable(demo):
|
| 86 |
+
pipeline = Pipeline(Config(column_width=800))
|
| 87 |
+
pipeline.ingest(next(iter(sorted(demo.glob("*.json")))))
|
| 88 |
+
snapshot = pipeline.snapshot()
|
| 89 |
+
assert json.loads(json.dumps(snapshot, allow_nan=False))["tiles"][0]["corners"]
|
| 90 |
+
assert np.isfinite(snapshot["stats"]["mean_confidence"])
|
tests/test_stitching.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from helpers import texture
|
| 5 |
+
from herc.stitching import Mosaic, overlap_ncc, phase_candidates
|
| 6 |
+
|
| 7 |
+
IMAGE = texture(600, 800, seed=3)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def crop(y, x, h=200, w=240):
|
| 11 |
+
return IMAGE[y:y + h, x:x + w].copy()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@pytest.mark.parametrize("a_yx,b_yx", [((100, 100), (150, 220)), ((200, 300), (120, 180)), ((50, 400), (190, 300))])
|
| 15 |
+
def test_phase_correlation_recovers_positive_and_negative_offsets(a_yx, b_yx):
|
| 16 |
+
a, b = crop(*a_yx), crop(*b_yx)
|
| 17 |
+
expected = (b_yx[0] - a_yx[0], b_yx[1] - a_yx[1])
|
| 18 |
+
assert phase_candidates(a, b)[0] == expected
|
| 19 |
+
ncc, pixels = overlap_ncc(a, b, *expected)
|
| 20 |
+
assert ncc > 0.999 and pixels == (200 - abs(expected[0])) * (240 - abs(expected[1]))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_ncc_without_overlap_or_texture_is_rejected():
|
| 24 |
+
assert overlap_ncc(crop(0, 0), crop(0, 0), 500, 0) == (-1.0, 0)
|
| 25 |
+
flat = np.zeros((50, 50), np.float32)
|
| 26 |
+
assert overlap_ncc(flat, flat, 0, 0)[0] == -1.0
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_puzzle_assembly_without_declared_origins():
|
| 30 |
+
mosaic = Mosaic(min_overlap_px=2000, min_ncc=0.9)
|
| 31 |
+
positions = {"a": (0, 0), "b": (0, 180), "c": (160, 60), "d": (300, 400)}
|
| 32 |
+
first = mosaic.place("a", crop(*positions["a"]))
|
| 33 |
+
assert first.method == "first"
|
| 34 |
+
for tile_id in ("b", "c"):
|
| 35 |
+
placement = mosaic.place(tile_id, crop(*positions[tile_id]))
|
| 36 |
+
assert placement.method == "matched" and (placement.y, placement.x) == positions[tile_id]
|
| 37 |
+
assert placement.ncc > 0.99
|
| 38 |
+
assert mosaic.place("d", crop(*positions["d"])) is None # aucun recouvrement : en attente
|
| 39 |
+
assert mosaic.place("e", crop(150, 300)) is not None
|
| 40 |
+
assert (mosaic.place("d", crop(*positions["d"])).y, mosaic.items["d"][0].x) == positions["d"]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_unrelated_texture_is_never_forced_into_the_mosaic():
|
| 44 |
+
mosaic = Mosaic(min_overlap_px=2000, min_ncc=0.9)
|
| 45 |
+
mosaic.place("a", crop(0, 0))
|
| 46 |
+
assert mosaic.place("noise", texture(200, 240, seed=99)) is None
|
| 47 |
+
assert len(mosaic) == 1
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_declared_origin_is_refined_within_radius_only():
|
| 51 |
+
mosaic = Mosaic(min_overlap_px=2000, min_ncc=0.9, refine_radius=6)
|
| 52 |
+
mosaic.place("a", crop(100, 100), origin=(100, 100))
|
| 53 |
+
refined = mosaic.place("b", crop(150, 250), origin=(147, 254))
|
| 54 |
+
assert (refined.y, refined.x, refined.method, refined.shift) == (150, 250, "origin+refined", (3, -4))
|
| 55 |
+
far = mosaic.place("c", crop(150, 250), origin=(130, 250)) # erreur de 20 px > rayon : origine gardée
|
| 56 |
+
assert (far.y, far.x, far.method) == (130, 250, "origin")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_relative_mosaic_is_reanchored_when_a_tile_with_origin_matches():
|
| 60 |
+
mosaic = Mosaic(min_overlap_px=2000, min_ncc=0.9)
|
| 61 |
+
mosaic.place("a", crop(200, 300))
|
| 62 |
+
mosaic.place("b", crop(250, 450))
|
| 63 |
+
assert (mosaic.items["b"][0].y, mosaic.items["b"][0].x) == (50, 150)
|
| 64 |
+
placed = mosaic.place("c", crop(300, 350), origin=(300, 350))
|
| 65 |
+
assert placed.method == "origin+reanchored" and mosaic.reanchored and mosaic.absolute_frame
|
| 66 |
+
assert {k: (p.y, p.x) for k, (p, _) in mosaic.items.items()} == {"a": (200, 300), "b": (250, 450), "c": (300, 350)}
|
| 67 |
+
assert Mosaic(min_ncc=0.9).place("x", crop(0, 0), origin=(5, 5)).method == "origin"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_composite_averages_overlaps_and_downsamples():
|
| 71 |
+
mosaic = Mosaic(min_overlap_px=2000, min_ncc=0.9)
|
| 72 |
+
mosaic.place("a", crop(0, 0), origin=(0, 0))
|
| 73 |
+
mosaic.place("b", crop(100, 120), origin=(100, 120))
|
| 74 |
+
image, info = mosaic.composite(max_side=180)
|
| 75 |
+
assert info["step"] == 2 and image.shape == (150, 180) and image.dtype == np.uint8
|
| 76 |
+
union = 2 * 200 * 240 - 100 * 120 # aire réelle des deux tuiles moins leur recouvrement
|
| 77 |
+
assert info["covered_px"] % 4 == 0 and abs(info["covered_px"] - union) <= 2 * (200 + 240) * 2
|
| 78 |
+
assert Mosaic().composite() is None
|
tests/test_text.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
from herc.config import Config
|
| 4 |
+
from herc.lexicon import Lexicon
|
| 5 |
+
from herc.stitching import Placement
|
| 6 |
+
from herc.text import assemble, restored_fraction
|
| 7 |
+
from herc.tiles import Tile, Word
|
| 8 |
+
|
| 9 |
+
LEXICON = Lexicon.load(Config().lexicon_path)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def tile(tile_id, words):
|
| 13 |
+
return Tile(tile_id, "s", Path(tile_id + ".png"), None, None, "human", None,
|
| 14 |
+
tuple(Word(t, b, 1.0) for t, b in words))
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_reading_order_is_column_then_line_then_x_across_tiles():
|
| 18 |
+
left = tile("L", [("καὶ", (52, 120, 30, 40)), ("ὁ", (8, 10, 30, 20)), ("λόγος", (55, 10, 30, 80)), ("θεός", (12, 60, 30, 60))])
|
| 19 |
+
right = tile("R", [("ψυχή", (5, 10, 30, 60)), ("φύσις", (50, 10, 30, 60))])
|
| 20 |
+
words = assemble([(Placement("R", 0, 400, 100, 200, "first"), right),
|
| 21 |
+
(Placement("L", 0, 0, 100, 300, "first"), left)], LEXICON, column_width=300)
|
| 22 |
+
assert [w.text for w in words] == ["ὁ", "θεός", "λόγος", "καὶ", "ψυχή", "φύσις"]
|
| 23 |
+
assert [(w.column, w.line) for w in words] == [(0, 0), (0, 0), (0, 1), (0, 1), (1, 0), (1, 1)]
|
| 24 |
+
assert words[4].bbox == (5, 410, 30, 60) and words[4].key == "R:0"
|
| 25 |
+
assert words[0].glosses[0]["gloss"] == "le, la"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_columns_are_measured_from_the_left_edge_of_the_mosaic():
|
| 29 |
+
t = tile("T", [("ὁ", (0, 10, 20, 20)), ("θεός", (0, 320, 20, 40))])
|
| 30 |
+
words = assemble([(Placement("T", 0, -700, 50, 400, "matched"), t)], LEXICON, column_width=300)
|
| 31 |
+
assert [w.column for w in words] == [0, 1]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_restored_letters_are_measured_and_unknown_words_have_no_gloss():
|
| 35 |
+
assert restored_fraction("[ἡδο]νήν") == 0.5
|
| 36 |
+
assert restored_fraction("λόγος") == 0.0
|
| 37 |
+
(word,) = assemble([(Placement("T", 0, 0, 50, 50, "first"), tile("T", [("ξυλοφάγος", (0, 0, 10, 10))]))], LEXICON)
|
| 38 |
+
assert word.glosses == () and word.view()["glosses"] == []
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_no_words_gives_empty_text():
|
| 42 |
+
assert assemble([], LEXICON) == []
|
tests/test_tiles.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
from helpers import write_tile
|
| 8 |
+
from herc.config import Config
|
| 9 |
+
from herc.tiles import TileError, check_words_inside, load_image, parse_tile
|
| 10 |
+
|
| 11 |
+
CFG = Config()
|
| 12 |
+
WORD = {"text": "ἡδονήν", "bbox": [1, 2, 10, 20], "confidence": 0.8}
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_valid_tile_is_parsed_completely(tmp_path):
|
| 16 |
+
path = write_tile(tmp_path, "c1_t2", segment="PHerc0841/w00", origin_yx=[5, -3],
|
| 17 |
+
surface_xyz=[[0, 0, 0], [1, 0, 0], [1, 1, 0.5], [0, 1, 0.5]],
|
| 18 |
+
transcription={"source": "human", "reviewer": "M.", "words": [WORD, {"text": "καὶ", "bbox": [0, 0, 5, 5]}]})
|
| 19 |
+
tile = parse_tile(path, CFG)
|
| 20 |
+
assert tile.id == "c1_t2" and tile.origin_yx == (5, -3) and tile.segment == "PHerc0841/w00"
|
| 21 |
+
assert tile.source == "human" and tile.reviewer == "M." and len(tile.words) == 2
|
| 22 |
+
assert tile.words[1].confidence == 1.0 # défaut seulement pour une lecture humaine
|
| 23 |
+
assert tile.image_path.name == "c1_t2.png" and tile.surface_xyz[2] == (1.0, 1.0, 0.5)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_unvalidated_tile_is_ignored(tmp_path):
|
| 27 |
+
path = write_tile(tmp_path, "a")
|
| 28 |
+
data = json.loads(path.read_text())
|
| 29 |
+
data["validated"] = False
|
| 30 |
+
path.write_text(json.dumps(data))
|
| 31 |
+
assert parse_tile(path, CFG) is None
|
| 32 |
+
del data["validated"]
|
| 33 |
+
path.write_text(json.dumps(data))
|
| 34 |
+
assert parse_tile(path, CFG) is None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@pytest.mark.parametrize("meta,message", [
|
| 38 |
+
({"origin_yx": [True, 1]}, "entier"),
|
| 39 |
+
({"origin_yx": [1]}, "origin_yx"),
|
| 40 |
+
({"surprise": 1}, "inconnus"),
|
| 41 |
+
({"segment": "a\nb"}, "contrôle"),
|
| 42 |
+
({"transcription": {"source": "oracle"}}, "source"),
|
| 43 |
+
({"transcription": {"source": "model", "words": [{"text": "λόγος", "bbox": [0, 0, 1, 1]}]}}, "confidence"),
|
| 44 |
+
({"transcription": {"source": "human", "words": [{**WORD, "confidence": 1.5}]}}, "[0, 1]"),
|
| 45 |
+
({"transcription": {"source": "human", "words": [{**WORD, "confidence": float("nan")}]}}, "fini"),
|
| 46 |
+
({"transcription": {"source": "human", "words": [{**WORD, "text": "<script>"}]}}, "non autorisé"),
|
| 47 |
+
({"transcription": {"source": "human", "words": [{**WORD, "text": "[]"}]}}, "lettre"),
|
| 48 |
+
({"transcription": {"source": "human", "words": [{**WORD, "bbox": [0, 0, 0, 4]}]}}, "positives"),
|
| 49 |
+
({"transcription": {"source": "human", "words": [{**WORD, "bbox": [-1, 0, 2, 4]}]}}, "minimale"),
|
| 50 |
+
({"surface_xyz": [[0, 0, 0]] * 3}, "quatre"),
|
| 51 |
+
])
|
| 52 |
+
def test_invalid_fields_are_refused_with_a_clear_reason(tmp_path, meta, message):
|
| 53 |
+
path = write_tile(tmp_path, "bad", **meta)
|
| 54 |
+
with pytest.raises(TileError, match=message.replace("[", r"\[").replace("]", r"\]")):
|
| 55 |
+
parse_tile(path, CFG)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_id_must_match_file_name_and_names_are_restricted(tmp_path):
|
| 59 |
+
path = write_tile(tmp_path, "a")
|
| 60 |
+
path.write_text(json.dumps({"id": "../../etc/passwd", "validated": True}))
|
| 61 |
+
with pytest.raises(TileError, match="id"):
|
| 62 |
+
parse_tile(path, CFG)
|
| 63 |
+
odd = tmp_path / "a b.json"
|
| 64 |
+
odd.write_text("{}")
|
| 65 |
+
with pytest.raises(TileError, match="nom de fichier"):
|
| 66 |
+
parse_tile(odd, CFG)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_oversized_or_broken_json_is_refused(tmp_path):
|
| 70 |
+
path = write_tile(tmp_path, "a")
|
| 71 |
+
with pytest.raises(TileError, match="volumineux"):
|
| 72 |
+
parse_tile(path, Config(max_json_bytes=5))
|
| 73 |
+
path.write_bytes(b"{\xff")
|
| 74 |
+
with pytest.raises(TileError, match="illisible"):
|
| 75 |
+
parse_tile(path, CFG)
|
| 76 |
+
path.write_text("[1, 2]")
|
| 77 |
+
with pytest.raises(TileError, match="objet"):
|
| 78 |
+
parse_tile(path, CFG)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_images_are_checked_before_decoding(tmp_path):
|
| 82 |
+
write_tile(tmp_path, "a", np.full((40, 30), 0.5))
|
| 83 |
+
image = load_image(tmp_path / "a.png", CFG)
|
| 84 |
+
assert image.shape == (40, 30) and image.dtype == np.float32 and abs(float(image.mean()) - 128 / 255) < 1e-6
|
| 85 |
+
with pytest.raises(TileError, match="hors limites"):
|
| 86 |
+
load_image(tmp_path / "a.png", Config(max_tile_side=32))
|
| 87 |
+
with pytest.raises(TileError, match="absente"):
|
| 88 |
+
load_image(tmp_path / "missing.png", CFG)
|
| 89 |
+
Image.new("L", (16, 16)).save(tmp_path / "jpeg.png", format="JPEG")
|
| 90 |
+
with pytest.raises(TileError, match="PNG"):
|
| 91 |
+
load_image(tmp_path / "jpeg.png", CFG)
|
| 92 |
+
(tmp_path / "junk.png").write_bytes(b"not an image")
|
| 93 |
+
with pytest.raises(TileError, match="illisible"):
|
| 94 |
+
load_image(tmp_path / "junk.png", CFG)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_sixteen_bit_images_are_scaled_to_unit_range(tmp_path):
|
| 98 |
+
Image.fromarray(np.full((10, 10), 65535, dtype=np.uint16)).save(tmp_path / "h.png")
|
| 99 |
+
assert float(load_image(tmp_path / "h.png", CFG).max()) == 1.0
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_word_boxes_must_lie_inside_the_image(tmp_path):
|
| 103 |
+
path = write_tile(tmp_path, "a", np.zeros((20, 20)),
|
| 104 |
+
transcription={"source": "human", "words": [{"text": "καὶ", "bbox": [15, 0, 10, 5]}]})
|
| 105 |
+
tile = parse_tile(path, CFG)
|
| 106 |
+
with pytest.raises(TileError, match="déborde"):
|
| 107 |
+
check_words_inside(tile, (20, 20))
|
tests/test_watcher_server.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
from fastapi.testclient import TestClient
|
| 5 |
+
|
| 6 |
+
from helpers import write_tile
|
| 7 |
+
from herc.config import Config
|
| 8 |
+
from herc.events import EventBus, sse
|
| 9 |
+
from herc.pipeline import Pipeline
|
| 10 |
+
from herc.server import create_app, event_stream
|
| 11 |
+
from herc.watcher import TileWatcher
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
async def _noop(event):
|
| 15 |
+
return None
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_a_tile_is_ingested_only_once_it_is_stable(tmp_path):
|
| 19 |
+
cfg = Config(tiles_dir=tmp_path)
|
| 20 |
+
watcher = TileWatcher(cfg, Pipeline(cfg), _noop)
|
| 21 |
+
path = write_tile(tmp_path, "a")
|
| 22 |
+
(tmp_path / "notes.txt").write_text("ignoré")
|
| 23 |
+
(tmp_path / "bad name.json").write_text("{}")
|
| 24 |
+
assert watcher.scan() == [] # premier passage : signature enregistrée
|
| 25 |
+
assert watcher.scan() == [path] # second passage identique : tuile prête
|
| 26 |
+
watcher.mark_done(path)
|
| 27 |
+
assert watcher.scan() == [] # déjà traitée
|
| 28 |
+
data = json.loads(path.read_text())
|
| 29 |
+
data["segment"] = "corrigé"
|
| 30 |
+
path.write_text(json.dumps(data))
|
| 31 |
+
assert watcher.scan() == []
|
| 32 |
+
assert watcher.scan() == [path] # modifiée puis stable : relue
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_worker_loop_publishes_events_and_stops_cleanly(tmp_path):
|
| 36 |
+
cfg = Config(tiles_dir=tmp_path, poll_interval=0.02)
|
| 37 |
+
published = []
|
| 38 |
+
|
| 39 |
+
async def publish(event):
|
| 40 |
+
published.append(event)
|
| 41 |
+
|
| 42 |
+
async def scenario():
|
| 43 |
+
stop = asyncio.Event()
|
| 44 |
+
task = asyncio.create_task(TileWatcher(cfg, Pipeline(cfg), publish).run(stop))
|
| 45 |
+
write_tile(tmp_path, "a", transcription={"source": "human", "words": [{"text": "λόγος", "bbox": [0, 0, 5, 5]}]})
|
| 46 |
+
(tmp_path / "b.json").write_text("{broken")
|
| 47 |
+
for _ in range(200):
|
| 48 |
+
await asyncio.sleep(0.02)
|
| 49 |
+
if any(e["type"] == "text" for e in published) and any(e["type"] == "rejected" for e in published):
|
| 50 |
+
break
|
| 51 |
+
stop.set()
|
| 52 |
+
await asyncio.wait_for(task, 2)
|
| 53 |
+
|
| 54 |
+
asyncio.run(scenario())
|
| 55 |
+
text = [e for e in published if e["type"] == "text"][-1]
|
| 56 |
+
assert [w["text"] for w in text["words"]] == ["λόγος"]
|
| 57 |
+
assert any(e["type"] == "rejected" and e["name"] == "b" for e in published)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def test_event_bus_resyncs_slow_clients_and_sse_format_is_single_line_json():
|
| 61 |
+
async def scenario():
|
| 62 |
+
bus = EventBus(maxsize=2)
|
| 63 |
+
queue = bus.subscribe()
|
| 64 |
+
for i in range(3):
|
| 65 |
+
await bus.publish({"type": "stats", "n": i})
|
| 66 |
+
return [queue.get_nowait() for _ in range(queue.qsize())]
|
| 67 |
+
assert asyncio.run(scenario()) == [{"type": "resync"}]
|
| 68 |
+
encoded = sse({"type": "text", "words": [{"text": "a\nb"}]})
|
| 69 |
+
assert encoded.startswith("event: text\ndata: ") and encoded.endswith("\n\n") and encoded.count("\n") == 3
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_event_stream_starts_with_snapshot_then_relays_events():
|
| 73 |
+
async def scenario():
|
| 74 |
+
bus = EventBus()
|
| 75 |
+
calls = {"n": 0}
|
| 76 |
+
|
| 77 |
+
async def disconnected():
|
| 78 |
+
calls["n"] += 1
|
| 79 |
+
return calls["n"] > 1
|
| 80 |
+
|
| 81 |
+
stream = event_stream(bus, Pipeline(Config()), disconnected, heartbeat=0.05)
|
| 82 |
+
first = await stream.__anext__()
|
| 83 |
+
await bus.publish({"type": "stats", "stats": {}})
|
| 84 |
+
second = await stream.__anext__()
|
| 85 |
+
await stream.aclose()
|
| 86 |
+
return first, second, len(bus.subscribers)
|
| 87 |
+
first, second, remaining = asyncio.run(scenario())
|
| 88 |
+
assert first.startswith("event: snapshot") and '"tiles":[]' in first
|
| 89 |
+
assert second.startswith("event: stats") and remaining == 0
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_http_endpoints_serve_interface_state_and_mosaic_with_security_headers(tmp_path):
|
| 93 |
+
cfg = Config(tiles_dir=tmp_path)
|
| 94 |
+
pipeline = Pipeline(cfg)
|
| 95 |
+
with TestClient(create_app(cfg, pipeline=pipeline, start_watcher=False)) as client:
|
| 96 |
+
page = client.get("/")
|
| 97 |
+
assert page.status_code == 200 and "3 · Glose en direct" in page.text
|
| 98 |
+
assert "script-src 'self'" in page.headers["content-security-policy"]
|
| 99 |
+
assert page.headers["x-content-type-options"] == "nosniff"
|
| 100 |
+
assert client.get("/static/app.js").status_code == 200
|
| 101 |
+
assert client.get("/api/mosaic.png").status_code == 204
|
| 102 |
+
pipeline.ingest(write_tile(tmp_path, "a", transcription={"source": "human", "words": [{"text": "θεός", "bbox": [0, 0, 5, 5]}]}))
|
| 103 |
+
state = client.get("/api/state").json()
|
| 104 |
+
assert state["stats"]["tiles_placed"] == 1 and state["words"][0]["glosses"][0]["gloss"] == "dieu"
|
| 105 |
+
image = client.get("/api/mosaic.png")
|
| 106 |
+
assert image.status_code == 200 and image.content[:4] == b"\x89PNG"
|
| 107 |
+
assert client.get("/docs").status_code == 404
|
| 108 |
+
assert client.get("/static/../herc/server.py").status_code == 404
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def test_application_lifespan_runs_the_worker_on_the_folder(tmp_path):
|
| 112 |
+
cfg = Config(tiles_dir=tmp_path / "in", poll_interval=0.02)
|
| 113 |
+
pipeline = Pipeline(cfg)
|
| 114 |
+
with TestClient(create_app(cfg, pipeline=pipeline)) as client:
|
| 115 |
+
write_tile(cfg.tiles_dir, "a")
|
| 116 |
+
for _ in range(200):
|
| 117 |
+
if client.get("/api/state").json()["stats"]["tiles_placed"]:
|
| 118 |
+
break
|
| 119 |
+
asyncio.run(asyncio.sleep(0.02))
|
| 120 |
+
assert client.get("/api/state").json()["stats"]["tiles_placed"] == 1
|
tools/ast_audit.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Vérification structurelle : refuse les constructions dangereuses dans le code Python et le JavaScript.
|
| 2 |
+
|
| 3 |
+
Usage : python tools/ast_audit.py [chemins...] (défaut : herc tools tests)
|
| 4 |
+
Code de sortie 1 si une constatation est faite.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import ast
|
| 9 |
+
import re
|
| 10 |
+
import sys
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
FORBIDDEN_CALLS = {"eval", "exec", "compile", "__import__", "input", "breakpoint", "globals", "vars"}
|
| 15 |
+
FORBIDDEN_MODULES = {"subprocess", "pickle", "cPickle", "marshal", "shelve", "ctypes", "pty", "telnetlib", "dill"}
|
| 16 |
+
FORBIDDEN_OS = re.compile(r"^(system|popen|exec\w*|spawn\w*|fork\w*|kill\w*)$")
|
| 17 |
+
JS_PATTERNS = {
|
| 18 |
+
r"\beval\s*\(": "eval",
|
| 19 |
+
r"\bnew\s+Function\s*\(": "new Function",
|
| 20 |
+
r"\.innerHTML\b": "innerHTML",
|
| 21 |
+
r"\.outerHTML\b": "outerHTML",
|
| 22 |
+
r"\binsertAdjacentHTML\b": "insertAdjacentHTML",
|
| 23 |
+
r"\bdocument\.write\b": "document.write",
|
| 24 |
+
r"\bsetTimeout\s*\(\s*['\"]": "setTimeout(chaîne)",
|
| 25 |
+
r"\bsetInterval\s*\(\s*['\"]": "setInterval(chaîne)",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass(frozen=True)
|
| 30 |
+
class Finding:
|
| 31 |
+
path: str
|
| 32 |
+
line: int
|
| 33 |
+
message: str
|
| 34 |
+
|
| 35 |
+
def __str__(self) -> str:
|
| 36 |
+
return f"{self.path}:{self.line}: {self.message}"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _dotted(node: ast.AST) -> str:
|
| 40 |
+
if isinstance(node, ast.Name):
|
| 41 |
+
return node.id
|
| 42 |
+
if isinstance(node, ast.Attribute):
|
| 43 |
+
return _dotted(node.value) + "." + node.attr
|
| 44 |
+
return ""
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def audit_python(source: str, path: str = "<source>") -> list[Finding]:
|
| 48 |
+
findings: list[Finding] = []
|
| 49 |
+
tree = ast.parse(source, filename=path)
|
| 50 |
+
for node in ast.walk(tree):
|
| 51 |
+
if isinstance(node, ast.Import):
|
| 52 |
+
for alias in node.names:
|
| 53 |
+
if alias.name.split(".")[0] in FORBIDDEN_MODULES:
|
| 54 |
+
findings.append(Finding(path, node.lineno, f"import interdit : {alias.name}"))
|
| 55 |
+
elif isinstance(node, ast.ImportFrom):
|
| 56 |
+
module = (node.module or "").split(".")[0]
|
| 57 |
+
if module in FORBIDDEN_MODULES:
|
| 58 |
+
findings.append(Finding(path, node.lineno, f"import interdit : {node.module}"))
|
| 59 |
+
if module == "os" and any(FORBIDDEN_OS.match(a.name) for a in node.names):
|
| 60 |
+
findings.append(Finding(path, node.lineno, "import d'une fonction os d'exécution"))
|
| 61 |
+
elif isinstance(node, ast.Call):
|
| 62 |
+
name = _dotted(node.func)
|
| 63 |
+
if name in FORBIDDEN_CALLS:
|
| 64 |
+
findings.append(Finding(path, node.lineno, f"appel interdit : {name}()"))
|
| 65 |
+
parts = name.split(".")
|
| 66 |
+
if len(parts) == 2 and parts[0] == "os" and FORBIDDEN_OS.match(parts[1]):
|
| 67 |
+
findings.append(Finding(path, node.lineno, f"appel interdit : {name}()"))
|
| 68 |
+
if name in ("yaml.load", "yaml.unsafe_load", "tempfile.mktemp"):
|
| 69 |
+
findings.append(Finding(path, node.lineno, f"appel interdit : {name}()"))
|
| 70 |
+
if name.endswith("torch.load") or name == "torch.load":
|
| 71 |
+
if not any(k.arg == "weights_only" and isinstance(k.value, ast.Constant) and k.value.value is True
|
| 72 |
+
for k in node.keywords):
|
| 73 |
+
findings.append(Finding(path, node.lineno, "torch.load sans weights_only=True"))
|
| 74 |
+
for keyword in node.keywords:
|
| 75 |
+
if keyword.arg in ("shell", "allow_pickle") and isinstance(keyword.value, ast.Constant) \
|
| 76 |
+
and keyword.value.value is True:
|
| 77 |
+
findings.append(Finding(path, node.lineno, f"argument interdit : {keyword.arg}=True"))
|
| 78 |
+
elif isinstance(node, ast.Attribute) and node.attr in ("__subclasses__", "__globals__", "__builtins__", "__code__"):
|
| 79 |
+
findings.append(Finding(path, node.lineno, f"introspection interdite : .{node.attr}"))
|
| 80 |
+
return findings
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def audit_javascript(source: str, path: str = "<script>") -> list[Finding]:
|
| 84 |
+
findings = []
|
| 85 |
+
for number, line in enumerate(source.splitlines(), 1):
|
| 86 |
+
code = line.split("//", 1)[0]
|
| 87 |
+
for pattern, label in JS_PATTERNS.items():
|
| 88 |
+
if re.search(pattern, code):
|
| 89 |
+
findings.append(Finding(path, number, f"JavaScript interdit : {label}"))
|
| 90 |
+
return findings
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def audit_paths(paths: list[Path]) -> list[Finding]:
|
| 94 |
+
findings: list[Finding] = []
|
| 95 |
+
for root in paths:
|
| 96 |
+
files = [root] if root.is_file() else sorted(root.rglob("*"))
|
| 97 |
+
for file in files:
|
| 98 |
+
if "__pycache__" in file.parts or not file.is_file():
|
| 99 |
+
continue
|
| 100 |
+
if file.suffix == ".py":
|
| 101 |
+
findings += audit_python(file.read_text(encoding="utf-8"), str(file))
|
| 102 |
+
elif file.suffix == ".js":
|
| 103 |
+
findings += audit_javascript(file.read_text(encoding="utf-8"), str(file))
|
| 104 |
+
return findings
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def main(argv: list[str]) -> int:
|
| 108 |
+
base = Path(__file__).resolve().parent.parent
|
| 109 |
+
paths = [Path(a) for a in argv] or [base / "herc", base / "tools", base / "tests"]
|
| 110 |
+
findings = audit_paths(paths)
|
| 111 |
+
for finding in findings:
|
| 112 |
+
print(finding)
|
| 113 |
+
count = sum(1 for p in paths for f in (p.rglob("*") if p.is_dir() else [p]) if f.suffix in (".py", ".js"))
|
| 114 |
+
print(f"audit AST : {count} fichier(s), {len(findings)} constatation(s)")
|
| 115 |
+
return 1 if findings else 0
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
sys.exit(main(sys.argv[1:]))
|
tools/make_demo_tiles.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Génère des tuiles de DÉMONSTRATION dans un dossier (défaut : ./tiles_output).
|
| 2 |
+
|
| 3 |
+
Image : texture synthétique (pas un scan réel), découpée en 3 × 4 tuiles qui se recouvrent.
|
| 4 |
+
Seule la première tuile déclare son origine ; les autres sont raccordées par l'image.
|
| 5 |
+
Texte : deux phrases connues d'Épicure, marquées source="demo" :
|
| 6 |
+
- Lettre à Ménécée 128 : « τὴν ἡδονὴν ἀρχὴν καὶ τέλος λέγομεν εἶναι τοῦ μακαρίως ζῆν »
|
| 7 |
+
- Maxime capitale 2 : « ὁ θάνατος οὐδὲν πρὸς ἡμᾶς »
|
| 8 |
+
|
| 9 |
+
Usage : python tools/make_demo_tiles.py [dossier] [--delay 1.5]
|
| 10 |
+
Avec --delay, les tuiles arrivent une à une dans un ordre mélangé, comme en production.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import json
|
| 16 |
+
import random
|
| 17 |
+
import time
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
from PIL import Image
|
| 22 |
+
|
| 23 |
+
TILE, STRIDE, ROWS, COLS = 448, 384, 3, 4
|
| 24 |
+
HEIGHT, WIDTH = STRIDE * (ROWS - 1) + TILE, STRIDE * (COLS - 1) + TILE
|
| 25 |
+
COLUMN_WIDTH = 800
|
| 26 |
+
LINES = [
|
| 27 |
+
(0, 100, "τὴν [ἡδο]νὴν ἀρχὴν"),
|
| 28 |
+
(0, 200, "καὶ τέλος λέγομεν"),
|
| 29 |
+
(0, 300, "εἶναι τοῦ μακαρίως ζῆν"),
|
| 30 |
+
(1, 100, "ὁ θάνατος οὐδὲν"),
|
| 31 |
+
(1, 200, "πρὸς ἡμᾶς"),
|
| 32 |
+
]
|
| 33 |
+
EXPECTED = " ".join(text for _, _, text in LINES)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def texture(seed: int = 841) -> np.ndarray:
|
| 37 |
+
rng = np.random.default_rng(seed)
|
| 38 |
+
noise = rng.normal(size=(HEIGHT, WIDTH))
|
| 39 |
+
fy = np.fft.fftfreq(HEIGHT)[:, None]
|
| 40 |
+
fx = np.fft.rfftfreq(WIDTH)[None, :]
|
| 41 |
+
smooth = np.fft.irfft2(np.fft.rfft2(noise) * np.exp(-(fx ** 2 + fy ** 2) * 2000), s=(HEIGHT, WIDTH))
|
| 42 |
+
fine = rng.normal(scale=0.15, size=(HEIGHT, WIDTH))
|
| 43 |
+
image = smooth / smooth.std() * 0.25 + fine * 0.3
|
| 44 |
+
return (image - image.min()) / (image.max() - image.min()) * 0.6
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def layout() -> list[tuple[str, tuple[int, int, int, int]]]:
|
| 48 |
+
"""Mots positionnés de sorte que chacun tienne entier dans au moins une tuile."""
|
| 49 |
+
words = []
|
| 50 |
+
for column, y, text in LINES:
|
| 51 |
+
x = column * COLUMN_WIDTH + 40
|
| 52 |
+
for token in text.split():
|
| 53 |
+
width = 16 * len(token) + 10
|
| 54 |
+
if not any(STRIDE * c <= x and x + width <= STRIDE * c + TILE for c in range(COLS)):
|
| 55 |
+
x = min(STRIDE * c for c in range(COLS) if STRIDE * c > x)
|
| 56 |
+
if x + width > (column + 1) * COLUMN_WIDTH - 20:
|
| 57 |
+
raise RuntimeError("ligne de démonstration trop longue pour sa colonne : " + text)
|
| 58 |
+
words.append((token, (y, x, 44, width)))
|
| 59 |
+
x += width + 20
|
| 60 |
+
return words
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def build(out: Path, delay: float = 0.0, seed: int = 841) -> list[str]:
|
| 64 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 65 |
+
image = texture(seed)
|
| 66 |
+
words = layout()
|
| 67 |
+
for _, (y, x, h, w) in words: # traits d'encre factices, pour que la vue plane montre les mots
|
| 68 |
+
image[y + 8:y + h - 8, x + 4:x + w - 4] += 0.35
|
| 69 |
+
image = np.clip(image, 0, 1)
|
| 70 |
+
owner: dict[int, str] = {}
|
| 71 |
+
tiles = []
|
| 72 |
+
for r in range(ROWS):
|
| 73 |
+
for c in range(COLS):
|
| 74 |
+
tile_id = f"demo_r{r}_c{c}"
|
| 75 |
+
y0, x0 = r * STRIDE, c * STRIDE
|
| 76 |
+
own = []
|
| 77 |
+
for index, (token, (y, x, h, w)) in enumerate(words):
|
| 78 |
+
if index not in owner and y0 <= y and y + h <= y0 + TILE and x0 <= x and x + w <= x0 + TILE:
|
| 79 |
+
owner[index] = tile_id
|
| 80 |
+
conf = round(0.55 + 0.4 * ((index * 37) % 10) / 10, 2)
|
| 81 |
+
own.append({"text": token, "bbox": [y - y0, x - x0, h, w], "confidence": conf})
|
| 82 |
+
corners = [[x0 + dx, y0 + dy, float(40 * np.sin((x0 + dx) / 300))]
|
| 83 |
+
for dx, dy in ((0, 0), (TILE, 0), (TILE, TILE), (0, TILE))]
|
| 84 |
+
meta = {"id": tile_id, "validated": True, "segment": "DÉMO (texture synthétique)",
|
| 85 |
+
"surface_xyz": corners,
|
| 86 |
+
"transcription": {"source": "demo", "reviewer": "générateur de démonstration", "words": own}}
|
| 87 |
+
if (r, c) == (0, 0):
|
| 88 |
+
meta["origin_yx"] = [y0, x0]
|
| 89 |
+
tiles.append((tile_id, image[y0:y0 + TILE, x0:x0 + TILE], meta))
|
| 90 |
+
if len(owner) != len(words):
|
| 91 |
+
raise RuntimeError("un mot de démonstration ne tient dans aucune tuile")
|
| 92 |
+
order = list(range(len(tiles)))
|
| 93 |
+
if delay:
|
| 94 |
+
rng = random.Random(seed)
|
| 95 |
+
order = [0] + rng.sample(order[1:], len(order) - 1)
|
| 96 |
+
written = []
|
| 97 |
+
for i in order:
|
| 98 |
+
tile_id, array, meta = tiles[i]
|
| 99 |
+
Image.fromarray(np.rint(array * 255).astype(np.uint8), mode="L").save(out / f"{tile_id}.png")
|
| 100 |
+
tmp = out / f".{tile_id}.json.tmp"
|
| 101 |
+
tmp.write_text(json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
|
| 102 |
+
tmp.replace(out / f"{tile_id}.json") # écriture atomique : la tuile apparaît validée d'un coup
|
| 103 |
+
written.append(tile_id)
|
| 104 |
+
if delay:
|
| 105 |
+
print("tuile écrite :", tile_id, flush=True)
|
| 106 |
+
time.sleep(delay)
|
| 107 |
+
return written
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def main() -> None:
|
| 111 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 112 |
+
parser.add_argument("out", nargs="?", type=Path, default=Path("./tiles_output"))
|
| 113 |
+
parser.add_argument("--delay", type=float, default=0.0)
|
| 114 |
+
args = parser.parse_args()
|
| 115 |
+
build(args.out, args.delay)
|
| 116 |
+
print(f"{ROWS * COLS} tuiles de démonstration dans {args.out} ; lancez le serveur avec --column-width {COLUMN_WIDTH}")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
main()
|