Compare commits
451 Commits
dd16c88007
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00eb9f26f6 | ||
|
|
141f69ceaa | ||
|
|
2baad68060 | ||
|
|
25e5a7415a | ||
|
|
545c8676b0 | ||
|
|
2f34ee9ede | ||
|
|
5a154b744d | ||
|
|
f39cbe9283 | ||
|
|
5abdfa202e | ||
|
|
9b0e310978 | ||
|
|
46c2acb2f4 | ||
|
|
b8f1b71652 | ||
|
|
6a165b36e5 | ||
|
|
9dddd80d7a | ||
|
|
20a0585eb1 | ||
|
|
4561320e0d | ||
|
|
596864431b | ||
|
|
c8027eb7f9 | ||
|
|
ba0f659d1e | ||
|
|
50bfd6e902 | ||
|
|
0599c72cc1 | ||
|
|
5fad2d420d | ||
|
|
c8e5e498b5 | ||
|
|
261f686dac | ||
|
|
3d3c2b30db | ||
|
|
1d22f649ae | ||
|
|
610825ac14 | ||
|
|
6aec4742e5 | ||
|
|
0491c2eb84 | ||
|
|
f2bc62b4f5 | ||
|
|
674c9e949e | ||
|
|
e131aa719e | ||
|
|
17f0fdb2ed | ||
|
|
d4353d76fb | ||
|
|
b42f394833 | ||
|
|
c1a903537b | ||
|
|
7085c87618 | ||
|
|
1b7e095176 | ||
|
|
dcb873db35 | ||
|
|
fd39d13d06 | ||
|
|
c5733a171b | ||
|
|
18213f0bde | ||
|
|
cd8eb6ce46 | ||
|
|
2c2bdf903a | ||
|
|
947ff6bdcb | ||
|
|
92e4021898 | ||
|
|
108f1b1a2a | ||
|
|
48de4d98cd | ||
|
|
b5900f1aff | ||
|
|
baac98f837 | ||
|
|
496d34d822 | ||
|
|
709e41e050 | ||
|
|
7b3e8c576d | ||
|
|
868f99f109 | ||
|
|
dc25f243a4 | ||
|
|
c62ff7cd31 | ||
|
|
5d91698c3b | ||
|
|
5fa5767c9a | ||
|
|
693803fb7c | ||
|
|
31089df36f | ||
|
|
7b294f9150 | ||
|
|
8b29d20940 | ||
|
|
12b194ad1a | ||
|
|
058eadb0e4 | ||
|
|
5da9a550bf | ||
|
|
52637778b9 | ||
|
|
f6372b8c69 | ||
|
|
909d0729f6 | ||
|
|
04fa01661c | ||
|
|
bf9d24e108 | ||
|
|
0f17eb3cd9 | ||
|
|
5244e10728 | ||
|
|
a6c5f56003 | ||
|
|
584e07eb21 | ||
|
|
54b1c7d7d7 | ||
|
|
d8a2331038 | ||
|
|
ad78e26143 | ||
|
|
4f4e6c31fa | ||
|
|
7ffa4c90f9 | ||
|
|
656cadbb1e | ||
|
|
757c8460c9 | ||
|
|
501de4374a | ||
|
|
774bbc50d3 | ||
|
|
9ceee4e07c | ||
|
|
f23aaaea51 | ||
|
|
cde13c9623 | ||
|
|
2e42167c73 | ||
|
|
5eff4cf877 | ||
|
|
7f4b8757ff | ||
|
|
7263328edb | ||
|
|
8c482ce8dd | ||
|
|
00f7a7154c | ||
|
|
9c5e950c99 | ||
|
|
6e494a43ab | ||
|
|
53b0d77853 | ||
|
|
aed0edbf6d | ||
|
|
9e2c301723 | ||
|
|
633e301bfd | ||
|
|
9b5e8c6b35 | ||
|
|
682b306e51 | ||
|
|
3e3116d2fd | ||
|
|
9a8ce69782 | ||
|
|
66f8a7b708 | ||
|
|
3b78baf37f | ||
|
|
2828871e42 | ||
|
|
5c96def4ec | ||
|
|
611e1ee33d | ||
|
|
49d5212f0c | ||
|
|
e6f8e12f44 | ||
|
|
aabd849e35 | ||
|
|
d1e7dd1c4a | ||
|
|
71e1b10ac7 | ||
|
|
21b69e06be | ||
|
|
0168ab1a67 | ||
|
|
925f4356ce | ||
|
|
cc4cb3bc2f | ||
|
|
0685fb12da | ||
|
|
96ea23164d | ||
|
|
a8773d5b00 | ||
|
|
9f68bd3425 | ||
|
|
469f09d1e1 | ||
|
|
3bb04b25ab | ||
|
|
85fe0a73d6 | ||
|
|
eaade3cad2 | ||
|
|
d26a9f60ab | ||
|
|
d26233b5b3 | ||
|
|
e019dde01b | ||
|
|
5af5d821a5 | ||
|
|
525de55791 | ||
|
|
f860eb66e6 | ||
|
|
a73ddce43d | ||
|
|
47e83d90bd | ||
|
|
76cd1ac020 | ||
|
|
256df820cd | ||
|
|
7773c51304 | ||
|
|
83c058e400 | ||
|
|
34680732f8 | ||
|
|
c42924a94a | ||
|
|
9ea217bdfc | ||
|
|
4feec7c7b7 | ||
|
|
ed7fc99fc4 | ||
|
|
7fbcae954b | ||
|
|
f931091b57 | ||
|
|
f34340de9c | ||
|
|
55de6c21d2 | ||
|
|
52b66ebe07 | ||
|
|
424e5c51d4 | ||
|
|
12b4c61bac | ||
|
|
d9b2aa82e9 | ||
|
|
364086b86e | ||
|
|
fe754398c0 | ||
|
|
be86a7d14d | ||
|
|
19a5f69272 | ||
|
|
ea09fc75df | ||
|
|
410d36f3de | ||
|
|
72ce4420cb | ||
|
|
63dfb4d06f | ||
|
|
08a91ba2be | ||
|
|
49a36364a8 | ||
|
|
14fd8e0b1e | ||
|
|
247b79674d | ||
|
|
40815dafd1 | ||
|
|
2a21127f01 | ||
|
|
9d34c5201e | ||
|
|
d54814fa70 | ||
|
|
d6f4944bcc | ||
|
|
ee0d9c881e | ||
|
|
65f4ce1947 | ||
|
|
4e668660a7 | ||
|
|
7a6eadde8b | ||
|
|
4e809c3860 | ||
|
|
dccbb909bc | ||
|
|
be7f5f1872 | ||
|
|
c695b659fb | ||
|
|
a1e079b911 | ||
|
|
f5d5d6c59c | ||
|
|
4a44ad7986 | ||
|
|
7b3319be2e | ||
|
|
882b177fc3 | ||
|
|
1fae39dbb8 | ||
|
|
46c8c28d34 | ||
|
|
4000110501 | ||
|
|
2acf8696bf | ||
|
|
c0e1118870 | ||
|
|
f31a7175a2 | ||
|
|
bacbfd88f1 | ||
|
|
2c63beff04 | ||
|
|
82433b4bad | ||
|
|
d889a6959e | ||
|
|
bc1804ad18 | ||
|
|
45b83560fd | ||
|
|
e4fa634a63 | ||
|
|
76ba83eecb | ||
|
|
04092a0a66 | ||
|
|
7fafd297e7 | ||
|
|
7ac09b5941 | ||
|
|
1f7989cfc2 | ||
|
|
ef5aed6a98 | ||
|
|
7dc00e737a | ||
|
|
a579c31ddb | ||
|
|
0f9c0d2ad0 | ||
|
|
278067fe20 | ||
|
|
d76fb2a9c8 | ||
|
|
9681fcbd05 | ||
|
|
4290f70885 | ||
|
|
5c935eec23 | ||
|
|
c4a5cd2d8a | ||
|
|
bc5ab29c06 | ||
|
|
7c5d95b858 | ||
|
|
65059471cf | ||
|
|
58c9565ba5 | ||
|
|
92a7b85c2d | ||
|
|
5f89913a9a | ||
|
|
3c7fc43f43 | ||
|
|
6bfa9eed86 | ||
|
|
7750b2a05f | ||
|
|
e3395ae8cf | ||
|
|
df30d4eae3 | ||
|
|
2e6ab3a646 | ||
|
|
cc5ee74921 | ||
|
|
21d37b5da1 | ||
|
|
19cbbf310a | ||
|
|
fc0ab84e40 | ||
|
|
050d410ba0 | ||
|
|
038eaf783c | ||
|
|
432eee3694 | ||
|
|
8e4cbd84c2 | ||
|
|
f9d71d50d1 | ||
|
|
c09838e91c | ||
|
|
3fd6523872 | ||
|
|
e56391b0c3 | ||
|
|
a3e2a7f994 | ||
|
|
f655db30e4 | ||
|
|
c894a0feeb | ||
|
|
8ef4c089cf | ||
|
|
821e5481c2 | ||
|
|
b98ea33a3a | ||
|
|
f139d0903e | ||
|
|
962bbbe9f6 | ||
|
|
9da45c2a59 | ||
|
|
64447ad352 | ||
|
|
00cbf266cb | ||
|
|
f9bad7beaa | ||
|
|
143e41ec76 | ||
|
|
ec287fd12e | ||
|
|
98f7f7d7d5 | ||
|
|
a19bca6060 | ||
|
|
7a76697f95 | ||
|
|
5359a4cc2b | ||
|
|
a25214126d | ||
|
|
fd79d5e4fa | ||
|
|
19b93f7762 | ||
|
|
a079ffe8e9 | ||
|
|
6e1d715d0d | ||
|
|
d66efdecf5 | ||
|
|
d36972b464 | ||
|
|
f30e526917 | ||
|
|
438a4495c7 | ||
|
|
902de027f4 | ||
|
|
b1cdb2531c | ||
|
|
ab30e8b17a | ||
|
|
b0e1fbc8d6 | ||
|
|
872b47f691 | ||
|
|
bbf0a5720e | ||
|
|
29d3c1caf5 | ||
|
|
aae8a96aa2 | ||
|
|
2b73d9beec | ||
|
|
324f39a9cc | ||
|
|
febd0a2f84 | ||
|
|
43b1f8be58 | ||
|
|
43dec5dd91 | ||
|
|
dfce8415d7 | ||
|
|
92a52a3199 | ||
|
|
427fecdce0 | ||
|
|
9fb3229270 | ||
|
|
91625a2646 | ||
|
|
02ae6249ca | ||
|
|
cf995f2d52 | ||
|
|
0340204c1f | ||
|
|
729ebff63c | ||
|
|
6668661895 | ||
|
|
eeee61108a | ||
|
|
1653e7cff4 | ||
|
|
86ae71fd65 | ||
|
|
ba513968c5 | ||
|
|
f717e1c0df | ||
|
|
934b5648a2 | ||
|
|
fe7339c7a1 | ||
|
|
3aa4a63257 | ||
|
|
6b9b280ba3 | ||
|
|
1d34785e2b | ||
|
|
5b5213c2b9 | ||
|
|
fbbec6cf5e | ||
|
|
a6951940b9 | ||
|
|
4a8d43fd71 | ||
|
|
bcd55e12d7 | ||
|
|
2bd63ec402 | ||
|
|
39a4d8564c | ||
|
|
1162eac7b4 | ||
|
|
28352f5bab | ||
|
|
c3f1547e32 | ||
|
|
4a15d46dfd | ||
|
|
b83b38e7f2 | ||
|
|
a994ddee83 | ||
|
|
c2c082d4b4 | ||
|
|
d6f51e4418 | ||
|
|
703e110bab | ||
|
|
41ff7671cd | ||
|
|
8e42e36ee4 | ||
|
|
24e1e93b5b | ||
|
|
846292f632 | ||
|
|
4280298e02 | ||
|
|
4f2fb0e94c | ||
|
|
61c8169f9e | ||
|
|
e9ccd1e35c | ||
|
|
d335a7bbf3 | ||
|
|
1f527fcd49 | ||
|
|
8349c28f54 | ||
|
|
71a1b5f058 | ||
|
|
c743a38eaf | ||
|
|
90c1efd9b0 | ||
|
|
06d63d18f9 | ||
|
|
3e65b14b83 | ||
|
|
40ac593d28 | ||
|
|
ea69239e06 | ||
|
|
bb90d1ba94 | ||
|
|
685d135be5 | ||
|
|
e2c2acdf86 | ||
|
|
3cc496f7f3 | ||
|
|
a6069631cc | ||
|
|
ced5bb3dd3 | ||
|
|
2fdf3ff868 | ||
|
|
2e21a4b6d0 | ||
|
|
d98dba9098 | ||
|
|
cd13eca290 | ||
|
|
aa7db43f02 | ||
|
|
4afd5bd8e8 | ||
|
|
7d19145edb | ||
|
|
35f2706098 | ||
|
|
0ee92e7210 | ||
|
|
4949863bd7 | ||
|
|
efbe15f895 | ||
|
|
c3da131129 | ||
|
|
b81baa1d16 | ||
|
|
2010cab894 | ||
|
|
bc13978bc1 | ||
|
|
2f51ac617f | ||
|
|
8a5f2aa188 | ||
|
|
d182d87f26 | ||
|
|
87efc1b4ba | ||
|
|
dd7087cd6d | ||
|
|
7282a220d6 | ||
|
|
b5d5371f72 | ||
|
|
41e47baf13 | ||
|
|
8a60f4bf30 | ||
|
|
e3ee1de790 | ||
|
|
b91f799ccf | ||
|
|
2df2a01a8b | ||
|
|
e2ad93fd57 | ||
|
|
2cbdfc56f3 | ||
|
|
840918df2a | ||
|
|
eb3fc05cdc | ||
|
|
9dbb5fa708 | ||
|
|
f468c30112 | ||
|
|
618c82ef42 | ||
|
|
080fcb5e3c | ||
|
|
bcd97e7d78 | ||
|
|
7f8615b8c1 | ||
|
|
2055597ba4 | ||
|
|
ad28f9420a | ||
|
|
6314e60464 | ||
|
|
d530738b12 | ||
|
|
ca7d44e543 | ||
|
|
e44e319ccf | ||
|
|
6bb023bdc1 | ||
|
|
13553fc5e6 | ||
|
|
964c916a81 | ||
|
|
13510b62cc | ||
|
|
3a791179af | ||
|
|
f65bd11919 | ||
|
|
785b4d7655 | ||
|
|
2716495250 | ||
|
|
23b7840ea7 | ||
|
|
34adb437d0 | ||
|
|
ceaef9c6a6 | ||
|
|
9047339f0d | ||
|
|
2592ef233b | ||
|
|
256efef3ea | ||
|
|
4610137ecc | ||
|
|
fb46450802 | ||
|
|
11126c4436 | ||
|
|
7a0ded7562 | ||
|
|
04be24a89e | ||
|
|
cf9dde9876 | ||
|
|
60c4138660 | ||
|
|
7005b18561 | ||
|
|
e60254bc75 | ||
|
|
156a818246 | ||
|
|
eb45bb4879 | ||
|
|
2763631711 | ||
|
|
9a5a35bff1 | ||
|
|
931ab92c92 | ||
|
|
853638b03c | ||
|
|
d98359fceb | ||
|
|
e1ae5d5fa9 | ||
|
|
4e8ea77140 | ||
|
|
e8ba5ec073 | ||
|
|
02631dc4e0 | ||
|
|
a5635e0c43 | ||
|
|
7a1bd5e82d | ||
|
|
b0bfc0a960 | ||
|
|
a5df2b6e15 | ||
|
|
14c8bb5da0 | ||
|
|
4532f68173 | ||
|
|
391449fedf | ||
|
|
cb2b924a7b | ||
|
|
8f3a50b981 | ||
|
|
0f821afb23 | ||
|
|
2ad391e4e4 | ||
|
|
e0decac7a0 | ||
|
|
d39d249daa | ||
|
|
538d5c732e | ||
|
|
b9c3c47a37 | ||
|
|
9912997187 | ||
|
|
2ec4d8aabd | ||
|
|
24366880ad | ||
|
|
20b341d839 | ||
|
|
d5be7b6f77 | ||
|
|
b7ae36e92b | ||
|
|
9ea77ba157 | ||
|
|
4f9cf3b9e8 | ||
|
|
b8a9493310 | ||
|
|
68a6b97654 | ||
|
|
af1b12c97d | ||
|
|
770aea611f | ||
|
|
1a2efbf075 | ||
|
|
cd12755da6 | ||
|
|
40cfc1acdd | ||
|
|
aa136a9f80 | ||
|
|
e6858010c2 | ||
|
|
1cc69d6b5e | ||
|
|
293e7914d8 | ||
|
|
a58dfca1d8 | ||
|
|
fd99d4f875 | ||
|
|
1e0c6bb4b5 | ||
|
|
e6dc3fcdd7 | ||
|
|
edbdac3203 | ||
|
|
99573a46ef | ||
|
|
6ad4b84584 | ||
|
|
f94a3836f8 | ||
|
|
34c649c8be |
@@ -256,3 +256,45 @@ ssh macmini "cd /Users/benjaminadmin/Projekte/breakpilot-lehrer && git push all
|
||||
| `website/app/admin/klausur-korrektur/` | Korrektur-Workspace |
|
||||
| `backend-lehrer/classroom_api.py` | Classroom Engine |
|
||||
| `backend-lehrer/state_engine_api.py` | State Engine |
|
||||
|
||||
---
|
||||
|
||||
## Code-Qualitaet Guardrails (NON-NEGOTIABLE)
|
||||
|
||||
> Vollstaendige Details: `.claude/rules/architecture.md`
|
||||
> Ausnahmen: `.claude/rules/loc-exceptions.txt`
|
||||
|
||||
### File Size Budget
|
||||
|
||||
- **Hard Cap: 500 LOC** pro Datei
|
||||
- Wenn eine Aenderung eine Datei ueber 500 LOC bringen wuerde: **erst splitten, dann aendern**
|
||||
- Ausnahmen nur mit Begruendung in `loc-exceptions.txt` + `[guardrail-change]` Commit-Marker
|
||||
|
||||
### Architektur
|
||||
|
||||
- **Python:** Routes duenn → Business Logic in Services → Persistenz in Repositories
|
||||
- **Go:** Handler ≤40 LOC → Service-Layer → Repository-Pattern
|
||||
- **TypeScript/Next.js:** page.tsx duenn → Server Actions, Queries, Components auslagern
|
||||
- **Types:** Monolithische types.ts frueh splitten, types.ts + types/ Shadowing vermeiden
|
||||
|
||||
### Workflow (bei jeder Aenderung)
|
||||
|
||||
1. Datei lesen + LOC pruefen
|
||||
2. Wenn nahe am Budget → erst splitten
|
||||
3. Minimale kohaerente Aenderung
|
||||
4. Verifikation (Tests + Lint)
|
||||
5. Zusammenfassung: Was geaendert, was verifiziert, Restrisiko
|
||||
|
||||
### Commit-Marker
|
||||
|
||||
- `[migration-approved]` — Schema-/Migrations-Aenderungen
|
||||
- `[guardrail-change]` — Aenderungen an .claude/**, scripts/check-loc.sh
|
||||
- `[split-required]` — Aenderung beginnt mit Datei-Split
|
||||
- `[interface-change]` — Public API Contracts geaendert
|
||||
|
||||
### LOC-Check ausfuehren
|
||||
|
||||
```bash
|
||||
bash scripts/check-loc.sh --changed # nur geaenderte Dateien
|
||||
bash scripts/check-loc.sh --all # alle Dateien (zeigt alle Violations)
|
||||
```
|
||||
|
||||
46
.claude/rules/architecture.md
Normal file
46
.claude/rules/architecture.md
Normal file
@@ -0,0 +1,46 @@
|
||||
# Architecture Rule — BreakPilot Lehrer
|
||||
|
||||
## File Size Budget
|
||||
|
||||
Hard default: **500 LOC max** per file.
|
||||
Soft targets:
|
||||
- Handler/Router/Service: 300-400 LOC
|
||||
- Models/Schemas/Types: 200-300 LOC
|
||||
- Utilities: 100-200 LOC
|
||||
|
||||
Ausnahmen nur in `.claude/rules/loc-exceptions.txt` mit Begruendung.
|
||||
|
||||
## Split-Trigger
|
||||
|
||||
Sofort splitten wenn:
|
||||
- Datei ueberschreitet 500 LOC
|
||||
- Datei wuerde nach Aenderung 500 LOC ueberschreiten
|
||||
- Datei mischt Transport + Business Logic + Persistence
|
||||
- Datei enthaelt mehrere unabhaengig testbare Verantwortlichkeiten
|
||||
|
||||
## Python (backend-lehrer, klausur-service, voice-service)
|
||||
|
||||
- Routes duenn halten — Business Logic in Services
|
||||
- Persistenz in Repositories/Data-Access-Module
|
||||
- Pydantic Schemas nach Domain splitten
|
||||
- Zirkulaere Imports vermeiden
|
||||
|
||||
## Go (school-service, edu-search-service)
|
||||
|
||||
- Handler duenn halten (≤40 LOC)
|
||||
- Business Logic in Services/Use-Cases
|
||||
- Transport/Request-Decoding getrennt von Domain-Logik
|
||||
|
||||
## TypeScript / Next.js (admin-lehrer, studio-v2, website)
|
||||
|
||||
- page.tsx duenn halten — Server Actions, Queries, Forms auslagern
|
||||
- Monolithische types.ts frueh splitten
|
||||
- types.ts + types/ Shadowing vermeiden
|
||||
- Shared Client/Server Types explizit trennen
|
||||
|
||||
## Entscheidungsreihenfolge
|
||||
|
||||
1. Bestehendes kleines kohaeesives Modul wiederverwenden
|
||||
2. Neues Modul in der Naehe erstellen
|
||||
3. Ueberfuellte Datei splitten, neues Verhalten in richtiges Split-Modul
|
||||
4. Nur als letzter Ausweg: Grosse bestehende Datei erweitern
|
||||
20
.claude/rules/loc-exceptions.txt
Normal file
20
.claude/rules/loc-exceptions.txt
Normal file
@@ -0,0 +1,20 @@
|
||||
# LOC Exceptions — BreakPilot Lehrer
|
||||
# Format: <glob> | owner=<person> | reason=<why> | review=<date>
|
||||
#
|
||||
# Jede Ausnahme braucht Begruendung und Review-Datum.
|
||||
# Temporaere Ausnahmen muessen mit [guardrail-change] Commit-Marker versehen werden.
|
||||
|
||||
# Generated / Build Artifacts
|
||||
**/node_modules/** | owner=infra | reason=npm packages | review=permanent
|
||||
**/.next/** | owner=infra | reason=Next.js build output | review=permanent
|
||||
**/__pycache__/** | owner=infra | reason=Python bytecode | review=permanent
|
||||
**/venv/** | owner=infra | reason=Python virtualenv | review=permanent
|
||||
|
||||
# Test-Dateien (duerfen groesser sein fuer Table-Driven Tests)
|
||||
**/tests/test_cv_vocab_pipeline.py | owner=klausur | reason=umfangreiche OCR Pipeline Tests | review=2026-07-01
|
||||
**/tests/test_rbac.py | owner=klausur | reason=RBAC Test-Matrix | review=2026-07-01
|
||||
**/tests/test_grid_editor_api.py | owner=klausur | reason=Grid Editor Integrationstests | review=2026-07-01
|
||||
|
||||
# Legacy — TEMPORAER bis Refactoring abgeschlossen
|
||||
# Dateien hier werden Phase fuer Phase abgearbeitet und entfernt.
|
||||
# KEINE neuen Ausnahmen ohne [guardrail-change] Commit-Marker!
|
||||
237
.claude/rules/ocr-pipeline-extensions.md
Normal file
237
.claude/rules/ocr-pipeline-extensions.md
Normal file
@@ -0,0 +1,237 @@
|
||||
# OCR Pipeline Erweiterungen - Entwicklerdokumentation
|
||||
|
||||
**Status:** Produktiv
|
||||
**Letzte Aktualisierung:** 2026-04-15
|
||||
**URL:** https://macmini:3002/ai/ocr-kombi
|
||||
|
||||
---
|
||||
|
||||
## Uebersicht
|
||||
|
||||
Erweiterungen der OCR Kombi Pipeline (14 Steps, 0-13):
|
||||
- **SmartSpellChecker** — LLM-freie OCR-Korrektur mit Spracherkennung
|
||||
- **Box-Grid-Review** (Step 11) — Eingebettete Boxen verarbeiten
|
||||
- **Ansicht/Spreadsheet** (Step 12) — Fortune Sheet Excel-Editor
|
||||
|
||||
---
|
||||
|
||||
## Pipeline Steps
|
||||
|
||||
| Step | ID | Name | Komponente |
|
||||
|------|----|------|------------|
|
||||
| 0 | upload | Upload | StepUpload |
|
||||
| 1 | orientation | Orientierung | StepOrientation |
|
||||
| 2 | page-split | Seitentrennung | StepPageSplit |
|
||||
| 3 | deskew | Begradigung | StepDeskew |
|
||||
| 4 | dewarp | Entzerrung | StepDewarp |
|
||||
| 5 | content-crop | Zuschneiden | StepContentCrop |
|
||||
| 6 | ocr | OCR | StepOcr |
|
||||
| 7 | structure | Strukturerkennung | StepStructure |
|
||||
| 8 | grid-build | Grid-Aufbau | StepGridBuild |
|
||||
| 9 | grid-review | Grid-Review | StepGridReview |
|
||||
| 10 | gutter-repair | Wortkorrektur | StepGutterRepair |
|
||||
| **11** | **box-review** | **Box-Review** | **StepBoxGridReview** |
|
||||
| **12** | **ansicht** | **Ansicht** | **StepAnsicht** |
|
||||
| 13 | ground-truth | Ground Truth | StepGroundTruth |
|
||||
|
||||
Step-Definitionen: `admin-lehrer/app/(admin)/ai/ocr-kombi/types.ts`
|
||||
|
||||
---
|
||||
|
||||
## SmartSpellChecker
|
||||
|
||||
**Datei:** `klausur-service/backend/smart_spell.py`
|
||||
**Tests:** `tests/test_smart_spell.py` (43 Tests)
|
||||
**Lizenz:** Nur pyspellchecker (MIT) — kein LLM, kein Hunspell
|
||||
|
||||
### Features
|
||||
|
||||
| Feature | Methode |
|
||||
|---------|---------|
|
||||
| Spracherkennung | Dual-Dictionary EN/DE Heuristik |
|
||||
| a/I Disambiguation | Bigram-Kontext (Folgewort-Lookup) |
|
||||
| Boundary Repair | Frequenz-basiert: `Pound sand`→`Pounds and` |
|
||||
| Context Split | `anew`→`a new` (Allow/Deny-Liste) |
|
||||
| Multi-Digit | BFS: `sch00l`→`school` |
|
||||
| Cross-Language Guard | DE-Woerter in EN-Spalte nicht falsch korrigieren |
|
||||
| Umlaut-Korrektur | `Schuler`→`Schueler` |
|
||||
| IPA-Schutz | Inhalte in [Klammern] nie aendern |
|
||||
| Slash→l | `p/`→`pl` (kursives l als / erkannt) |
|
||||
| Abkuerzungen | 120+ aus `_KNOWN_ABBREVIATIONS` |
|
||||
|
||||
### Integration
|
||||
|
||||
```python
|
||||
# In cv_review.py (LLM Review Step):
|
||||
from smart_spell import SmartSpellChecker
|
||||
_smart = SmartSpellChecker()
|
||||
result = _smart.correct_text(text, lang="en") # oder "de" oder "auto"
|
||||
|
||||
# In grid_editor_api.py (Grid Build + Box Build):
|
||||
# Automatisch nach Grid-Aufbau und Box-Grid-Aufbau
|
||||
```
|
||||
|
||||
### Frequenz-Scoring
|
||||
|
||||
Boundary Repair vergleicht Wort-Frequenz-Produkte:
|
||||
- `old_freq = word_freq(w1) * word_freq(w2)`
|
||||
- `new_freq = word_freq(repaired_w1) * word_freq(repaired_w2)`
|
||||
- Akzeptiert wenn `new_freq > old_freq * 5`
|
||||
- Abkuerzungs-Bonus nur wenn Original-Woerter selten (freq < 1e-6)
|
||||
|
||||
---
|
||||
|
||||
## Box-Grid-Review (Step 11)
|
||||
|
||||
**Frontend:** `admin-lehrer/components/ocr-kombi/StepBoxGridReview.tsx`
|
||||
**Backend:** `klausur-service/backend/cv_box_layout.py`, `grid_editor_api.py`
|
||||
**Tests:** `tests/test_box_layout.py` (13 Tests)
|
||||
|
||||
### Backend-Endpoints
|
||||
|
||||
```
|
||||
POST /api/v1/ocr-pipeline/sessions/{id}/build-box-grids
|
||||
```
|
||||
|
||||
Verarbeitet alle erkannten Boxen aus `structure_result`:
|
||||
1. Filtert Header/Footer-Boxen (obere/untere 7% der Bildhoehe)
|
||||
2. Extrahiert OCR-Woerter pro Box aus `raw_paddle_words`
|
||||
3. Klassifiziert Layout: `flowing` | `columnar` | `bullet_list` | `header_only`
|
||||
4. Baut Grid mit layout-spezifischer Logik
|
||||
5. Wendet SmartSpellChecker an
|
||||
|
||||
### Box Layout Klassifikation (`cv_box_layout.py`)
|
||||
|
||||
| Layout | Erkennung | Grid-Aufbau |
|
||||
|--------|-----------|-------------|
|
||||
| `header_only` | ≤5 Woerter oder 1 Zeile | 1 Zelle, alles zusammen |
|
||||
| `flowing` | Gleichmaessige Zeilenbreite | 1 Spalte, Bullet-Gruppierung per Einrueckung |
|
||||
| `bullet_list` | ≥40% Zeilen mit Bullet-Marker | 1 Spalte, Bullet-Items |
|
||||
| `columnar` | Mehrere X-Cluster | Standard-Spaltenerkennung |
|
||||
|
||||
### Bullet-Einrueckung
|
||||
|
||||
Erkennung ueber Left-Edge-Analyse:
|
||||
- Minimale Einrueckung = Bullet-Ebene
|
||||
- Zeilen mit >15px mehr Einrueckung = Folgezeilen
|
||||
- Folgezeilen werden mit `\n` in die Bullet-Zelle integriert
|
||||
- Fehlende `•` Marker werden automatisch ergaenzt
|
||||
|
||||
### Colspan-Erkennung (`grid_editor_helpers.py`)
|
||||
|
||||
Generische Funktion `_detect_colspan_cells()`:
|
||||
- Laeuft nach `_build_cells()` fuer ALLE Zonen
|
||||
- Nutzt Original-Wort-Bloecke (vor `_split_cross_column_words`)
|
||||
- Wort-Block der ueber Spaltengrenze reicht → `spanning_header` mit `colspan=N`
|
||||
- Beispiel: "In Britain you pay with pounds and pence." ueber 2 Spalten
|
||||
|
||||
### Spalten-Erkennung in Boxen
|
||||
|
||||
Fuer kleine Zonen (≤60 Woerter):
|
||||
- `gap_threshold = max(median_h * 1.0, 25)` statt `3x median`
|
||||
- PaddleOCR liefert Multi-Word-Bloecke → alle Gaps sind Spalten-Gaps
|
||||
|
||||
---
|
||||
|
||||
## Ansicht / Spreadsheet (Step 12)
|
||||
|
||||
**Frontend:** `admin-lehrer/components/ocr-kombi/StepAnsicht.tsx`, `SpreadsheetView.tsx`
|
||||
**Bibliothek:** `@fortune-sheet/react` (MIT, v1.0.4)
|
||||
|
||||
### Architektur
|
||||
|
||||
Split-View:
|
||||
- **Links:** Original-Scan mit OCR-Overlay (`/image/words-overlay`)
|
||||
- **Rechts:** Fortune Sheet Spreadsheet mit Multi-Sheet-Tabs
|
||||
|
||||
### Multi-Sheet Ansatz
|
||||
|
||||
Jede Zone wird ein eigenes Sheet-Tab:
|
||||
- Sheet "Vokabeln" — Hauptgrid mit EN/DE Spalten
|
||||
- Sheet "Pounds and euros" — Box 1 mit eigenen 4 Spalten
|
||||
- Sheet "German leihen" — Box 2 als Fliesstexttext
|
||||
|
||||
Grund: Spaltenbreiten sind pro Zone unterschiedlich optimiert. Excel-Limitation: Spaltenbreite gilt fuer die ganze Spalte.
|
||||
|
||||
### Zell-Formatierung
|
||||
|
||||
| Format | Quelle | Fortune Sheet Property |
|
||||
|--------|--------|----------------------|
|
||||
| Fett | `is_header`, `is_bold`, groessere Schrift | `bl: 1` |
|
||||
| Schriftfarbe | OCR word_boxes color | `fc: '#hex'` |
|
||||
| Hintergrund | Box bg_hex, Header | `bg: '#hex08'` |
|
||||
| Text-Wrap | Mehrzeilige Zellen (\n) | `tb: '2'` |
|
||||
| Vertikal oben | Mehrzeilige Zellen | `vt: 0` |
|
||||
| Groessere Schrift | word_box height >1.3x median | `fs: 12` |
|
||||
|
||||
### Spaltenbreiten
|
||||
|
||||
Auto-Fit: `max(laengster_text * 7.5 + 16, original_px * scaleFactor)`
|
||||
|
||||
### Toolbar
|
||||
|
||||
`undo, redo, font-bold, font-italic, font-strikethrough, font-color, background, font-size, horizontal-align, vertical-align, text-wrap, merge-cell, border`
|
||||
|
||||
---
|
||||
|
||||
## Unified Grid (Backend)
|
||||
|
||||
**Datei:** `klausur-service/backend/unified_grid.py`
|
||||
**Tests:** `tests/test_unified_grid.py` (10 Tests)
|
||||
|
||||
Mergt alle Zonen in ein einzelnes Grid (fuer Export/Analyse):
|
||||
|
||||
```
|
||||
POST /api/v1/ocr-pipeline/sessions/{id}/build-unified-grid
|
||||
GET /api/v1/ocr-pipeline/sessions/{id}/unified-grid
|
||||
```
|
||||
|
||||
- Dominante Zeilenhoehe = Median der Content-Row-Abstaende
|
||||
- Full-Width Boxen: Rows direkt integriert
|
||||
- Partial-Width Boxen: Extra-Rows eingefuegt wenn Box mehr Zeilen hat
|
||||
- Box-Zellen mit `source_zone_type: "box"` und `box_region` Metadaten
|
||||
|
||||
---
|
||||
|
||||
## Dateistruktur
|
||||
|
||||
### Backend (klausur-service)
|
||||
|
||||
| Datei | Zeilen | Beschreibung |
|
||||
|-------|--------|--------------|
|
||||
| `grid_build_core.py` | 1943 | `_build_grid_core()` — Haupt-Grid-Aufbau |
|
||||
| `grid_editor_api.py` | 474 | REST-Endpoints (build, save, get, gutter, box, unified) |
|
||||
| `grid_editor_helpers.py` | 1737 | Helper: Spalten, Rows, Cells, Colspan, Header |
|
||||
| `smart_spell.py` | 587 | SmartSpellChecker |
|
||||
| `cv_box_layout.py` | 339 | Box-Layout-Klassifikation + Grid-Aufbau |
|
||||
| `unified_grid.py` | 425 | Unified Grid Builder |
|
||||
|
||||
### Frontend (admin-lehrer)
|
||||
|
||||
| Datei | Zeilen | Beschreibung |
|
||||
|-------|--------|--------------|
|
||||
| `StepBoxGridReview.tsx` | 283 | Box-Review Step 11 |
|
||||
| `StepAnsicht.tsx` | 112 | Ansicht Step 12 (Split-View) |
|
||||
| `SpreadsheetView.tsx` | ~160 | Fortune Sheet Integration |
|
||||
| `GridTable.tsx` | 652 | Grid-Editor Tabelle (Steps 9-11) |
|
||||
| `useGridEditor.ts` | 985 | Grid-Editor Hook |
|
||||
|
||||
### Tests
|
||||
|
||||
| Datei | Tests | Beschreibung |
|
||||
|-------|-------|--------------|
|
||||
| `test_smart_spell.py` | 43 | Spracherkennung, Boundary Repair, IPA-Schutz |
|
||||
| `test_box_layout.py` | 13 | Layout-Klassifikation, Bullet-Gruppierung |
|
||||
| `test_unified_grid.py` | 10 | Unified Grid, Box-Klassifikation |
|
||||
| **Gesamt** | **66** | |
|
||||
|
||||
---
|
||||
|
||||
## Aenderungshistorie
|
||||
|
||||
| Datum | Aenderung |
|
||||
|-------|-----------|
|
||||
| 2026-04-15 | Fortune Sheet Multi-Sheet Tabs, Bullet-Points, Auto-Fit, Refactoring |
|
||||
| 2026-04-14 | Unified Grid, Ansicht Step, Colspan-Erkennung |
|
||||
| 2026-04-13 | Box-Grid-Review Step, Spalten in Boxen, Header/Footer Filter |
|
||||
| 2026-04-12 | SmartSpellChecker, Frequency Scoring, IPA-Schutz, Vocab-Worksheet Refactoring |
|
||||
@@ -188,11 +188,35 @@ ssh macmini "docker compose up -d klausur-service studio-v2"
|
||||
|
||||
---
|
||||
|
||||
## Frontend Refactoring (2026-04-12)
|
||||
|
||||
`page.tsx` wurde von 2337 Zeilen in 14 Dateien aufgeteilt:
|
||||
|
||||
```
|
||||
studio-v2/app/vocab-worksheet/
|
||||
├── page.tsx # 198 Zeilen — Orchestrator
|
||||
├── types.ts # Interfaces, VocabWorksheetHook
|
||||
├── constants.ts # API-Base, Formats, Defaults
|
||||
├── useVocabWorksheet.ts # 843 Zeilen — Custom Hook (alle State + Logik)
|
||||
└── components/
|
||||
├── UploadScreen.tsx # Session-Liste + Dokument-Auswahl
|
||||
├── PageSelection.tsx # PDF-Seitenauswahl
|
||||
├── VocabularyTab.tsx # Vokabel-Tabelle + IPA/Silben
|
||||
├── WorksheetTab.tsx # Format-Auswahl + Konfiguration
|
||||
├── ExportTab.tsx # PDF-Download
|
||||
├── OcrSettingsPanel.tsx # OCR-Filter Einstellungen
|
||||
├── FullscreenPreview.tsx # Vollbild-Vorschau Modal
|
||||
├── QRCodeModal.tsx # QR-Upload Modal
|
||||
└── OcrComparisonModal.tsx # OCR-Vergleich Modal
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Erweiterung: Neue Formate hinzufuegen
|
||||
|
||||
1. **Backend**: Neuen Generator in `klausur-service/backend/` erstellen
|
||||
2. **API**: Neuen Endpoint in `vocab_worksheet_api.py` hinzufuegen
|
||||
3. **Frontend**: Format zu `worksheetFormats` Array in `page.tsx` hinzufuegen
|
||||
3. **Frontend**: Format zu `worksheetFormats` Array in `constants.ts` hinzufuegen
|
||||
4. **Doku**: Diese Datei aktualisieren
|
||||
|
||||
---
|
||||
|
||||
9
.claude/settings.json
Normal file
9
.claude/settings.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash",
|
||||
"Write",
|
||||
"Read"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ OLLAMA_TIMEOUT=120
|
||||
|
||||
# OCR-Pipeline: LLM-Review (Schritt 6)
|
||||
# Kleine Modelle reichen fuer Zeichen-Korrekturen (0->O, 1->l, 5->S)
|
||||
# Optionen: qwen3:0.6b, qwen3:1.7b, gemma3:1b, qwen3:30b-a3b
|
||||
# Optionen: qwen3:0.6b, qwen3:1.7b, gemma3:1b, qwen3.5:35b-a3b
|
||||
OLLAMA_REVIEW_MODEL=qwen3:0.6b
|
||||
# Eintraege pro Ollama-Call. Groesser = weniger HTTP-Overhead.
|
||||
OLLAMA_REVIEW_BATCH_SIZE=20
|
||||
|
||||
36
AGENTS.go.md
Normal file
36
AGENTS.go.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# AGENTS.go.md — Go/Gin Konventionen
|
||||
|
||||
## Architektur
|
||||
|
||||
- `handlers/`: HTTP Transport nur — Decode, Validate, Call Service, Encode Response
|
||||
- `service/` oder `usecase/`: Business Logic
|
||||
- `repo/`: Storage/Integration
|
||||
- `model/` oder `domain/`: Domain Entities
|
||||
- `tests/`: Table-driven Tests bevorzugen
|
||||
|
||||
## Regeln
|
||||
|
||||
1. Handler ≤40 LOC — nur Decode → Service → Encode
|
||||
2. Business Logic NICHT in Handlers verstecken
|
||||
3. Grosse Handler nach Resource/Verb splitten
|
||||
4. Request/Response DTOs nah am Transport halten
|
||||
5. Interfaces nur an echten Boundaries (nicht ueberall fuer Mocks)
|
||||
6. Keine Giant-Utility-Dateien
|
||||
7. Generated Files nicht manuell editieren
|
||||
|
||||
## Split-Trigger
|
||||
|
||||
- Handler-Datei ueberschreitet 400-500 LOC
|
||||
- Unrelated Endpoints zusammengruppiert
|
||||
- Encoding/Decoding dominiert die Handler-Datei
|
||||
- Service-Logik und Transport-Logik gemischt
|
||||
|
||||
## Verifikation
|
||||
|
||||
```bash
|
||||
gofmt -l . | grep -q . && exit 1
|
||||
go vet ./...
|
||||
golangci-lint run --timeout=5m
|
||||
go test -race ./...
|
||||
go build ./...
|
||||
```
|
||||
36
AGENTS.python.md
Normal file
36
AGENTS.python.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# AGENTS.python.md — Python/FastAPI Konventionen
|
||||
|
||||
## Architektur
|
||||
|
||||
- `routes/` oder `api/`: Request/Response nur — kein Business Logic
|
||||
- `services/`: Business Logic
|
||||
- `repositories/`: Persistenz/Data Access
|
||||
- `schemas/`: Pydantic Models, nach Domain gesplittet
|
||||
- `tests/`: Spiegelt Produktions-Layout
|
||||
|
||||
## Regeln
|
||||
|
||||
1. Route-Dateien duenn halten (≤300 LOC)
|
||||
2. Wenn eine Route-Datei 300-400 LOC erreicht → nach Resource/Operation splitten
|
||||
3. Schema-Dateien nach Domain splitten wenn sie wachsen
|
||||
4. Modul-Level Singleton-Kopplung vermeiden (Tests patchen falsches Symbol)
|
||||
5. Patch immer das Symbol das vom getesteten Modul importiert wird
|
||||
6. Dependency Injection bevorzugen statt versteckte Imports
|
||||
7. Pydantic v2: `from __future__ import annotations` NICHT verwenden (bricht Pydantic)
|
||||
8. Migrationen getrennt von Refactorings halten
|
||||
|
||||
## Split-Trigger
|
||||
|
||||
- Datei naehert sich oder ueberschreitet 500 LOC
|
||||
- Zirkulaere Imports erscheinen
|
||||
- Tests brauchen tiefes Patching
|
||||
- API-Schemas mischen verschiedene Domains
|
||||
- Service-Datei macht Transport UND DB-Logik
|
||||
|
||||
## Verifikation
|
||||
|
||||
```bash
|
||||
ruff check .
|
||||
mypy . --ignore-missing-imports --no-error-summary
|
||||
pytest tests/ -x -q --no-header
|
||||
```
|
||||
55
AGENTS.typescript.md
Normal file
55
AGENTS.typescript.md
Normal file
@@ -0,0 +1,55 @@
|
||||
# AGENTS.typescript.md — Next.js Konventionen
|
||||
|
||||
## Architektur
|
||||
|
||||
- `app/.../page.tsx`: Minimale Seiten-Komposition (≤250 LOC)
|
||||
- `app/.../actions.ts`: Server Actions
|
||||
- `app/.../queries.ts`: Data Loading
|
||||
- `app/.../_components/`: View-Teile (Colocation)
|
||||
- `app/.../_hooks/`: Seiten-spezifische Hooks (Colocation)
|
||||
- `types/` oder `types/*.ts`: Domain-spezifische Types
|
||||
- `schemas/`: Zod/Validierungs-Schemas
|
||||
- `lib/`: Shared Utilities
|
||||
|
||||
## Regeln
|
||||
|
||||
1. page.tsx duenn halten (≤250 LOC)
|
||||
2. Grosse Seiten frueh in Sections/Components splitten
|
||||
3. KEINE einzelne types.ts als Catch-All
|
||||
4. types.ts UND types/ Shadowing vermeiden (eines waehlen!)
|
||||
5. Server/Client Module-Grenzen explizit halten
|
||||
6. Pure Helpers und schmale Props bevorzugen
|
||||
7. API-Client Types getrennt von handgeschriebenen Domain Types
|
||||
|
||||
## Colocation Pattern (bevorzugt)
|
||||
|
||||
```
|
||||
app/(admin)/ai/rag/
|
||||
page.tsx ← duenn, komponiert nur
|
||||
_components/
|
||||
SearchPanel.tsx
|
||||
ResultsTable.tsx
|
||||
FilterBar.tsx
|
||||
_hooks/
|
||||
useRagSearch.ts
|
||||
actions.ts ← Server Actions
|
||||
queries.ts ← Data Fetching
|
||||
```
|
||||
|
||||
## Split-Trigger
|
||||
|
||||
- page.tsx ueberschreitet 250-350 LOC
|
||||
- types.ts ueberschreitet 200-300 LOC
|
||||
- Form-Logik, Server Actions und Rendering in einer Datei
|
||||
- Mehrere unabhaengig testbare Sections vorhanden
|
||||
- Imports werden broechig
|
||||
|
||||
## Verifikation
|
||||
|
||||
```bash
|
||||
npx tsc --noEmit
|
||||
npm run lint
|
||||
npm run build
|
||||
```
|
||||
|
||||
> `npm run build` ist PFLICHT — `tsc` allein reicht nicht.
|
||||
@@ -1,396 +0,0 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* GPU Infrastructure Admin Page
|
||||
*
|
||||
* vast.ai GPU Management for LLM Processing
|
||||
* Part of KI-Werkzeuge
|
||||
*/
|
||||
|
||||
import { useEffect, useState, useCallback } from 'react'
|
||||
import { PagePurpose } from '@/components/common/PagePurpose'
|
||||
import { AIToolsSidebarResponsive } from '@/components/ai/AIToolsSidebar'
|
||||
|
||||
interface VastStatus {
|
||||
instance_id: number | null
|
||||
status: string
|
||||
gpu_name: string | null
|
||||
dph_total: number | null
|
||||
endpoint_base_url: string | null
|
||||
last_activity: string | null
|
||||
auto_shutdown_in_minutes: number | null
|
||||
total_runtime_hours: number | null
|
||||
total_cost_usd: number | null
|
||||
account_credit: number | null
|
||||
account_total_spend: number | null
|
||||
session_runtime_minutes: number | null
|
||||
session_cost_usd: number | null
|
||||
message: string | null
|
||||
error?: string
|
||||
}
|
||||
|
||||
export default function GPUInfrastructurePage() {
|
||||
const [status, setStatus] = useState<VastStatus | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [actionLoading, setActionLoading] = useState<string | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
|
||||
const API_PROXY = '/api/admin/gpu'
|
||||
|
||||
const fetchStatus = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const response = await fetch(API_PROXY)
|
||||
const data = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || `HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
setStatus(data)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Verbindungsfehler')
|
||||
setStatus({
|
||||
instance_id: null,
|
||||
status: 'error',
|
||||
gpu_name: null,
|
||||
dph_total: null,
|
||||
endpoint_base_url: null,
|
||||
last_activity: null,
|
||||
auto_shutdown_in_minutes: null,
|
||||
total_runtime_hours: null,
|
||||
total_cost_usd: null,
|
||||
account_credit: null,
|
||||
account_total_spend: null,
|
||||
session_runtime_minutes: null,
|
||||
session_cost_usd: null,
|
||||
message: 'Verbindung fehlgeschlagen'
|
||||
})
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchStatus()
|
||||
}, [fetchStatus])
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(fetchStatus, 30000)
|
||||
return () => clearInterval(interval)
|
||||
}, [fetchStatus])
|
||||
|
||||
const powerOn = async () => {
|
||||
setActionLoading('on')
|
||||
setError(null)
|
||||
setMessage(null)
|
||||
|
||||
try {
|
||||
const response = await fetch(API_PROXY, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'on' }),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || data.detail || 'Aktion fehlgeschlagen')
|
||||
}
|
||||
|
||||
setMessage('Start angefordert')
|
||||
setTimeout(fetchStatus, 3000)
|
||||
setTimeout(fetchStatus, 10000)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Fehler beim Starten')
|
||||
fetchStatus()
|
||||
} finally {
|
||||
setActionLoading(null)
|
||||
}
|
||||
}
|
||||
|
||||
const powerOff = async () => {
|
||||
setActionLoading('off')
|
||||
setError(null)
|
||||
setMessage(null)
|
||||
|
||||
try {
|
||||
const response = await fetch(API_PROXY, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'off' }),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || data.detail || 'Aktion fehlgeschlagen')
|
||||
}
|
||||
|
||||
setMessage('Stop angefordert')
|
||||
setTimeout(fetchStatus, 3000)
|
||||
setTimeout(fetchStatus, 10000)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Fehler beim Stoppen')
|
||||
fetchStatus()
|
||||
} finally {
|
||||
setActionLoading(null)
|
||||
}
|
||||
}
|
||||
|
||||
const getStatusBadge = (s: string) => {
|
||||
const baseClasses = 'px-3 py-1 rounded-full text-sm font-semibold uppercase'
|
||||
switch (s) {
|
||||
case 'running':
|
||||
return `${baseClasses} bg-green-100 text-green-800`
|
||||
case 'stopped':
|
||||
case 'exited':
|
||||
return `${baseClasses} bg-red-100 text-red-800`
|
||||
case 'loading':
|
||||
case 'scheduling':
|
||||
case 'creating':
|
||||
case 'starting...':
|
||||
case 'stopping...':
|
||||
return `${baseClasses} bg-yellow-100 text-yellow-800`
|
||||
default:
|
||||
return `${baseClasses} bg-slate-100 text-slate-600`
|
||||
}
|
||||
}
|
||||
|
||||
const getCreditColor = (credit: number | null) => {
|
||||
if (credit === null) return 'text-slate-500'
|
||||
if (credit < 5) return 'text-red-600'
|
||||
if (credit < 15) return 'text-yellow-600'
|
||||
return 'text-green-600'
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Page Purpose */}
|
||||
<PagePurpose
|
||||
title="GPU Infrastruktur"
|
||||
purpose="Verwalten Sie die vast.ai GPU-Instanzen fuer LLM-Verarbeitung und OCR. Starten/Stoppen Sie GPUs bei Bedarf und ueberwachen Sie Kosten in Echtzeit."
|
||||
audience={['DevOps', 'Entwickler', 'System-Admins']}
|
||||
architecture={{
|
||||
services: ['vast.ai API', 'Ollama', 'VLLM'],
|
||||
databases: ['PostgreSQL (Logs)'],
|
||||
}}
|
||||
relatedPages={[
|
||||
{ name: 'LLM Vergleich', href: '/ai/llm-compare', description: 'KI-Provider testen' },
|
||||
{ name: 'Test Quality (BQAS)', href: '/ai/test-quality', description: 'Golden Suite & Tests' },
|
||||
{ name: 'Magic Help', href: '/ai/magic-help', description: 'TrOCR Testing' },
|
||||
]}
|
||||
collapsible={true}
|
||||
defaultCollapsed={true}
|
||||
/>
|
||||
|
||||
{/* KI-Werkzeuge Sidebar */}
|
||||
<AIToolsSidebarResponsive currentTool="gpu" />
|
||||
|
||||
{/* Status Cards */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6 mb-6">
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-6">
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 mb-2">Status</div>
|
||||
{loading ? (
|
||||
<span className="px-3 py-1 rounded-full text-sm font-semibold bg-slate-100 text-slate-600">
|
||||
Laden...
|
||||
</span>
|
||||
) : (
|
||||
<span className={getStatusBadge(
|
||||
actionLoading === 'on' ? 'starting...' :
|
||||
actionLoading === 'off' ? 'stopping...' :
|
||||
status?.status || 'unknown'
|
||||
)}>
|
||||
{actionLoading === 'on' ? 'starting...' :
|
||||
actionLoading === 'off' ? 'stopping...' :
|
||||
status?.status || 'unbekannt'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 mb-2">GPU</div>
|
||||
<div className="font-semibold text-slate-900">
|
||||
{status?.gpu_name || '-'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 mb-2">Kosten/h</div>
|
||||
<div className="font-semibold text-slate-900">
|
||||
{status?.dph_total ? `$${status.dph_total.toFixed(3)}` : '-'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 mb-2">Auto-Stop</div>
|
||||
<div className="font-semibold text-slate-900">
|
||||
{status && status.auto_shutdown_in_minutes !== null
|
||||
? `${status.auto_shutdown_in_minutes} min`
|
||||
: '-'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 mb-2">Budget</div>
|
||||
<div className={`font-bold text-lg ${getCreditColor(status?.account_credit ?? null)}`}>
|
||||
{status && status.account_credit !== null
|
||||
? `$${status.account_credit.toFixed(2)}`
|
||||
: '-'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 mb-2">Session</div>
|
||||
<div className="font-semibold text-slate-900">
|
||||
{status && status.session_runtime_minutes !== null && status.session_cost_usd !== null
|
||||
? `${Math.round(status.session_runtime_minutes)} min / $${status.session_cost_usd.toFixed(3)}`
|
||||
: '-'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Buttons */}
|
||||
<div className="flex items-center gap-4 mt-6 pt-6 border-t border-slate-200">
|
||||
<button
|
||||
onClick={powerOn}
|
||||
disabled={actionLoading !== null || status?.status === 'running'}
|
||||
className="px-6 py-2 bg-orange-600 text-white rounded-lg font-medium hover:bg-orange-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
Starten
|
||||
</button>
|
||||
<button
|
||||
onClick={powerOff}
|
||||
disabled={actionLoading !== null || status?.status !== 'running'}
|
||||
className="px-6 py-2 bg-red-600 text-white rounded-lg font-medium hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
Stoppen
|
||||
</button>
|
||||
<button
|
||||
onClick={fetchStatus}
|
||||
disabled={loading}
|
||||
className="px-4 py-2 border border-slate-300 text-slate-700 rounded-lg font-medium hover:bg-slate-50 disabled:opacity-50 transition-colors"
|
||||
>
|
||||
{loading ? 'Aktualisiere...' : 'Aktualisieren'}
|
||||
</button>
|
||||
|
||||
{message && (
|
||||
<span className="ml-4 text-sm text-green-600 font-medium">{message}</span>
|
||||
)}
|
||||
{error && (
|
||||
<span className="ml-4 text-sm text-red-600 font-medium">{error}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Extended Stats */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<h3 className="font-semibold text-slate-900 mb-4">Kosten-Uebersicht</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">Session Laufzeit</span>
|
||||
<span className="font-semibold">
|
||||
{status && status.session_runtime_minutes !== null
|
||||
? `${Math.round(status.session_runtime_minutes)} Minuten`
|
||||
: '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">Session Kosten</span>
|
||||
<span className="font-semibold">
|
||||
{status && status.session_cost_usd !== null
|
||||
? `$${status.session_cost_usd.toFixed(4)}`
|
||||
: '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center pt-4 border-t border-slate-100">
|
||||
<span className="text-slate-600">Gesamtlaufzeit</span>
|
||||
<span className="font-semibold">
|
||||
{status && status.total_runtime_hours !== null
|
||||
? `${status.total_runtime_hours.toFixed(1)} Stunden`
|
||||
: '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">Gesamtkosten</span>
|
||||
<span className="font-semibold">
|
||||
{status && status.total_cost_usd !== null
|
||||
? `$${status.total_cost_usd.toFixed(2)}`
|
||||
: '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">vast.ai Ausgaben</span>
|
||||
<span className="font-semibold">
|
||||
{status && status.account_total_spend !== null
|
||||
? `$${status.account_total_spend.toFixed(2)}`
|
||||
: '-'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<h3 className="font-semibold text-slate-900 mb-4">Instanz-Details</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">Instanz ID</span>
|
||||
<span className="font-mono text-sm">
|
||||
{status?.instance_id || '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">GPU</span>
|
||||
<span className="font-semibold">
|
||||
{status?.gpu_name || '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">Stundensatz</span>
|
||||
<span className="font-semibold">
|
||||
{status?.dph_total ? `$${status.dph_total.toFixed(4)}/h` : '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">Letzte Aktivitaet</span>
|
||||
<span className="text-sm">
|
||||
{status?.last_activity
|
||||
? new Date(status.last_activity).toLocaleString('de-DE')
|
||||
: '-'}
|
||||
</span>
|
||||
</div>
|
||||
{status?.endpoint_base_url && status.status === 'running' && (
|
||||
<div className="pt-4 border-t border-slate-100">
|
||||
<div className="text-slate-600 text-sm mb-1">Endpoint</div>
|
||||
<code className="text-xs bg-slate-100 px-2 py-1 rounded block overflow-x-auto">
|
||||
{status.endpoint_base_url}
|
||||
</code>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Info */}
|
||||
<div className="bg-violet-50 border border-violet-200 rounded-xl p-4">
|
||||
<div className="flex gap-3">
|
||||
<svg className="w-5 h-5 text-violet-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<div>
|
||||
<h4 className="font-semibold text-violet-900">Auto-Shutdown</h4>
|
||||
<p className="text-sm text-violet-800 mt-1">
|
||||
Die GPU-Instanz wird automatisch gestoppt, wenn sie laengere Zeit inaktiv ist.
|
||||
Der Status wird alle 30 Sekunden automatisch aktualisiert.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,503 +0,0 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* LLM Comparison Tool
|
||||
*
|
||||
* Vergleicht Antworten von verschiedenen LLM-Providern:
|
||||
* - OpenAI/ChatGPT
|
||||
* - Claude
|
||||
* - Self-hosted + Tavily
|
||||
* - Self-hosted + EduSearch
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { PagePurpose } from '@/components/common/PagePurpose'
|
||||
import { AIToolsSidebarResponsive } from '@/components/ai/AIToolsSidebar'
|
||||
|
||||
interface LLMResponse {
|
||||
provider: string
|
||||
model: string
|
||||
response: string
|
||||
latency_ms: number
|
||||
tokens_used?: number
|
||||
search_results?: Array<{
|
||||
title: string
|
||||
url: string
|
||||
content: string
|
||||
score?: number
|
||||
}>
|
||||
error?: string
|
||||
timestamp: string
|
||||
}
|
||||
|
||||
interface ComparisonResult {
|
||||
comparison_id: string
|
||||
prompt: string
|
||||
system_prompt?: string
|
||||
responses: LLMResponse[]
|
||||
created_at: string
|
||||
}
|
||||
|
||||
const providerColors: Record<string, { bg: string; border: string; text: string }> = {
|
||||
openai: { bg: 'bg-emerald-50', border: 'border-emerald-300', text: 'text-emerald-700' },
|
||||
claude: { bg: 'bg-orange-50', border: 'border-orange-300', text: 'text-orange-700' },
|
||||
selfhosted_tavily: { bg: 'bg-blue-50', border: 'border-blue-300', text: 'text-blue-700' },
|
||||
selfhosted_edusearch: { bg: 'bg-purple-50', border: 'border-purple-300', text: 'text-purple-700' },
|
||||
}
|
||||
|
||||
const providerLabels: Record<string, string> = {
|
||||
openai: 'OpenAI GPT-4o-mini',
|
||||
claude: 'Claude 3.5 Sonnet',
|
||||
selfhosted_tavily: 'Self-hosted + Tavily',
|
||||
selfhosted_edusearch: 'Self-hosted + EduSearch',
|
||||
}
|
||||
|
||||
export default function LLMComparePage() {
|
||||
// State
|
||||
const [prompt, setPrompt] = useState('')
|
||||
const [systemPrompt, setSystemPrompt] = useState('Du bist ein hilfreicher Assistent fuer Lehrkraefte in Deutschland.')
|
||||
|
||||
// Provider toggles
|
||||
const [enableOpenAI, setEnableOpenAI] = useState(true)
|
||||
const [enableClaude, setEnableClaude] = useState(true)
|
||||
const [enableTavily, setEnableTavily] = useState(true)
|
||||
const [enableEduSearch, setEnableEduSearch] = useState(true)
|
||||
|
||||
// Parameters
|
||||
const [model, setModel] = useState('llama3.2:3b')
|
||||
const [temperature, setTemperature] = useState(0.7)
|
||||
const [maxTokens, setMaxTokens] = useState(2048)
|
||||
|
||||
// Results
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [result, setResult] = useState<ComparisonResult | null>(null)
|
||||
const [history, setHistory] = useState<ComparisonResult[]>([])
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
// UI State
|
||||
const [showSettings, setShowSettings] = useState(false)
|
||||
const [showHistory, setShowHistory] = useState(false)
|
||||
|
||||
// API Base URL
|
||||
const API_URL = process.env.NEXT_PUBLIC_LLM_GATEWAY_URL || 'http://localhost:8082'
|
||||
const API_KEY = process.env.NEXT_PUBLIC_LLM_API_KEY || 'dev-key'
|
||||
|
||||
// Load history
|
||||
const loadHistory = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/v1/comparison/history?limit=20`, {
|
||||
headers: { Authorization: `Bearer ${API_KEY}` },
|
||||
})
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setHistory(data.comparisons || [])
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load history:', e)
|
||||
}
|
||||
}, [API_URL, API_KEY])
|
||||
|
||||
useEffect(() => {
|
||||
loadHistory()
|
||||
}, [loadHistory])
|
||||
|
||||
const runComparison = async () => {
|
||||
if (!prompt.trim()) {
|
||||
setError('Bitte geben Sie einen Prompt ein')
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
setResult(null)
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/v1/comparison/run`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${API_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
prompt,
|
||||
system_prompt: systemPrompt || undefined,
|
||||
enable_openai: enableOpenAI,
|
||||
enable_claude: enableClaude,
|
||||
enable_selfhosted_tavily: enableTavily,
|
||||
enable_selfhosted_edusearch: enableEduSearch,
|
||||
selfhosted_model: model,
|
||||
temperature,
|
||||
max_tokens: maxTokens,
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`API Error: ${response.status}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
setResult(data)
|
||||
loadHistory()
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const ResponseCard = ({ response }: { response: LLMResponse }) => {
|
||||
const colors = providerColors[response.provider] || {
|
||||
bg: 'bg-slate-50',
|
||||
border: 'border-slate-300',
|
||||
text: 'text-slate-700',
|
||||
}
|
||||
const label = providerLabels[response.provider] || response.provider
|
||||
|
||||
return (
|
||||
<div className={`rounded-xl border-2 ${colors.border} ${colors.bg} overflow-hidden`}>
|
||||
<div className={`px-4 py-3 border-b ${colors.border} flex items-center justify-between`}>
|
||||
<div>
|
||||
<h3 className={`font-semibold ${colors.text}`}>{label}</h3>
|
||||
<p className="text-xs text-slate-500">{response.model}</p>
|
||||
</div>
|
||||
<div className="text-right text-xs text-slate-500">
|
||||
<div>{response.latency_ms}ms</div>
|
||||
{response.tokens_used && <div>{response.tokens_used} tokens</div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-4">
|
||||
{response.error ? (
|
||||
<div className="text-red-600 text-sm">
|
||||
<strong>Fehler:</strong> {response.error}
|
||||
</div>
|
||||
) : (
|
||||
<pre className="whitespace-pre-wrap text-sm text-slate-700 font-sans">
|
||||
{response.response}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{response.search_results && response.search_results.length > 0 && (
|
||||
<div className="px-4 pb-4">
|
||||
<details className="text-xs">
|
||||
<summary className="cursor-pointer text-slate-500 hover:text-slate-700">
|
||||
{response.search_results.length} Suchergebnisse anzeigen
|
||||
</summary>
|
||||
<ul className="mt-2 space-y-2">
|
||||
{response.search_results.map((sr, idx) => (
|
||||
<li key={idx} className="bg-white rounded p-2 border border-slate-200">
|
||||
<a
|
||||
href={sr.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:underline font-medium"
|
||||
>
|
||||
{sr.title || 'Untitled'}
|
||||
</a>
|
||||
<p className="text-slate-500 truncate">{sr.content}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Page Purpose */}
|
||||
<PagePurpose
|
||||
title="LLM Vergleich"
|
||||
purpose="Vergleichen Sie Antworten verschiedener KI-Provider (OpenAI, Claude, Self-hosted) fuer Qualitaetssicherung. Optimieren Sie Parameter und System Prompts fuer beste Ergebnisse. Standalone-Werkzeug ohne direkten Datenfluss zur KI-Pipeline."
|
||||
audience={['Entwickler', 'Data Scientists', 'QA']}
|
||||
architecture={{
|
||||
services: ['llm-gateway (Python)', 'Ollama', 'OpenAI API', 'Claude API'],
|
||||
databases: ['PostgreSQL (History)', 'Qdrant (RAG)'],
|
||||
}}
|
||||
relatedPages={[
|
||||
{ name: 'Test Quality (BQAS)', href: '/ai/test-quality', description: 'Golden Suite & Synthetic Tests' },
|
||||
{ name: 'GPU Infrastruktur', href: '/ai/gpu', description: 'GPU-Ressourcen verwalten' },
|
||||
{ name: 'Agent Management', href: '/ai/agents', description: 'Multi-Agent System' },
|
||||
]}
|
||||
collapsible={true}
|
||||
defaultCollapsed={true}
|
||||
/>
|
||||
|
||||
{/* KI-Werkzeuge Sidebar */}
|
||||
<AIToolsSidebarResponsive currentTool="llm-compare" />
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Left Column: Input & Settings */}
|
||||
<div className="lg:col-span-1 space-y-4">
|
||||
{/* Prompt Input */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-4">
|
||||
<h2 className="font-semibold text-slate-900 mb-3">Prompt</h2>
|
||||
|
||||
{/* System Prompt */}
|
||||
<div className="mb-3">
|
||||
<label className="block text-sm text-slate-600 mb-1">System Prompt</label>
|
||||
<textarea
|
||||
value={systemPrompt}
|
||||
onChange={(e) => setSystemPrompt(e.target.value)}
|
||||
rows={3}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm resize-none"
|
||||
placeholder="System Prompt (optional)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* User Prompt */}
|
||||
<div className="mb-3">
|
||||
<label className="block text-sm text-slate-600 mb-1">User Prompt</label>
|
||||
<textarea
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
rows={4}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm resize-none"
|
||||
placeholder="z.B.: Erstelle ein Arbeitsblatt zum Thema Bruchrechnung fuer Klasse 6..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Provider Toggles */}
|
||||
<div className="mb-4">
|
||||
<label className="block text-sm text-slate-600 mb-2">Provider</label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={enableOpenAI}
|
||||
onChange={(e) => setEnableOpenAI(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
OpenAI
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={enableClaude}
|
||||
onChange={(e) => setEnableClaude(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
Claude
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={enableTavily}
|
||||
onChange={(e) => setEnableTavily(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
Self + Tavily
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={enableEduSearch}
|
||||
onChange={(e) => setEnableEduSearch(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
Self + EduSearch
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Run Button */}
|
||||
<button
|
||||
onClick={runComparison}
|
||||
disabled={isLoading || !prompt.trim()}
|
||||
className="w-full py-3 bg-teal-600 text-white rounded-lg font-medium hover:bg-teal-700 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{isLoading ? (
|
||||
<span className="flex items-center justify-center gap-2">
|
||||
<svg className="animate-spin w-5 h-5" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
Vergleiche...
|
||||
</span>
|
||||
) : (
|
||||
'Vergleich starten'
|
||||
)}
|
||||
</button>
|
||||
|
||||
{error && (
|
||||
<div className="mt-3 p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Settings Panel */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<button
|
||||
onClick={() => setShowSettings(!showSettings)}
|
||||
className="w-full px-4 py-3 flex items-center justify-between hover:bg-slate-50"
|
||||
>
|
||||
<span className="font-semibold text-slate-900">Parameter</span>
|
||||
<svg
|
||||
className={`w-5 h-5 transition-transform ${showSettings ? 'rotate-180' : ''}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{showSettings && (
|
||||
<div className="p-4 border-t border-slate-200 space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm text-slate-600 mb-1">Self-hosted Modell</label>
|
||||
<select
|
||||
value={model}
|
||||
onChange={(e) => setModel(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm"
|
||||
>
|
||||
<option value="llama3.2:3b">Llama 3.2 3B</option>
|
||||
<option value="llama3.1:8b">Llama 3.1 8B</option>
|
||||
<option value="mistral:7b">Mistral 7B</option>
|
||||
<option value="qwen2.5:7b">Qwen 2.5 7B</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-slate-600 mb-1">
|
||||
Temperature: {temperature.toFixed(2)}
|
||||
</label>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="2"
|
||||
step="0.1"
|
||||
value={temperature}
|
||||
onChange={(e) => setTemperature(parseFloat(e.target.value))}
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-slate-600 mb-1">Max Tokens: {maxTokens}</label>
|
||||
<input
|
||||
type="range"
|
||||
min="256"
|
||||
max="4096"
|
||||
step="256"
|
||||
value={maxTokens}
|
||||
onChange={(e) => setMaxTokens(parseInt(e.target.value))}
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* History Panel */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
|
||||
<button
|
||||
onClick={() => setShowHistory(!showHistory)}
|
||||
className="w-full px-4 py-3 flex items-center justify-between hover:bg-slate-50"
|
||||
>
|
||||
<span className="font-semibold text-slate-900">Verlauf ({history.length})</span>
|
||||
<svg
|
||||
className={`w-5 h-5 transition-transform ${showHistory ? 'rotate-180' : ''}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{showHistory && history.length > 0 && (
|
||||
<div className="border-t border-slate-200 max-h-64 overflow-y-auto">
|
||||
{history.map((h) => (
|
||||
<button
|
||||
key={h.comparison_id}
|
||||
onClick={() => {
|
||||
setResult(h)
|
||||
setPrompt(h.prompt)
|
||||
if (h.system_prompt) setSystemPrompt(h.system_prompt)
|
||||
}}
|
||||
className="w-full px-4 py-2 text-left hover:bg-slate-50 border-b border-slate-100 last:border-0"
|
||||
>
|
||||
<div className="text-sm text-slate-700 truncate">{h.prompt}</div>
|
||||
<div className="text-xs text-slate-400">
|
||||
{new Date(h.created_at).toLocaleString('de-DE')}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Column: Results */}
|
||||
<div className="lg:col-span-2">
|
||||
{result ? (
|
||||
<div className="space-y-4">
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-slate-900">Ergebnisse</h2>
|
||||
<p className="text-sm text-slate-500">ID: {result.comparison_id}</p>
|
||||
</div>
|
||||
<div className="text-sm text-slate-500">
|
||||
{new Date(result.created_at).toLocaleString('de-DE')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 p-3 bg-slate-50 rounded-lg">
|
||||
<p className="text-sm text-slate-700">{result.prompt}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 xl:grid-cols-2 gap-4">
|
||||
{result.responses.map((response, idx) => (
|
||||
<ResponseCard key={`${response.provider}-${idx}`} response={response} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-12 text-center">
|
||||
<svg
|
||||
className="w-16 h-16 mx-auto text-slate-300 mb-4"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.5}
|
||||
d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z"
|
||||
/>
|
||||
</svg>
|
||||
<h3 className="text-lg font-medium text-slate-700 mb-2">LLM-Vergleich starten</h3>
|
||||
<p className="text-slate-500 max-w-md mx-auto">
|
||||
Geben Sie einen Prompt ein und klicken Sie auf "Vergleich starten", um
|
||||
die Antworten verschiedener LLM-Provider zu vergleichen.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Info Box */}
|
||||
<div className="mt-8 bg-teal-50 border border-teal-200 rounded-xl p-6">
|
||||
<div className="flex items-start gap-4">
|
||||
<svg className="w-6 h-6 text-teal-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<div>
|
||||
<h3 className="font-semibold text-teal-900">Qualitaetssicherung</h3>
|
||||
<p className="text-sm text-teal-800 mt-1">
|
||||
Dieses Tool dient zur Qualitaetssicherung der KI-Antworten. Vergleichen Sie verschiedene Provider,
|
||||
um die optimalen Parameter und System Prompts zu finden. Die Ergebnisse werden fuer Audits gespeichert.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
420
admin-lehrer/app/(admin)/ai/ocr-ground-truth/page.tsx
Normal file
420
admin-lehrer/app/(admin)/ai/ocr-ground-truth/page.tsx
Normal file
@@ -0,0 +1,420 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* Ground-Truth Queue & Progress
|
||||
*
|
||||
* Overview page showing all sessions with their GT status.
|
||||
* Clicking a session opens it in the Kombi Pipeline (/ai/ocr-overlay)
|
||||
* where the actual review (split-view, inline edit, GT marking) happens.
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { PagePurpose } from '@/components/common/PagePurpose'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface Session {
|
||||
id: string
|
||||
name: string
|
||||
filename: string
|
||||
status: string
|
||||
created_at: string
|
||||
document_category: string | null
|
||||
has_ground_truth: boolean
|
||||
}
|
||||
|
||||
interface GTSession {
|
||||
session_id: string
|
||||
name: string
|
||||
filename: string
|
||||
document_category: string | null
|
||||
pipeline: string | null
|
||||
saved_at: string | null
|
||||
summary: {
|
||||
total_zones: number
|
||||
total_columns: number
|
||||
total_rows: number
|
||||
total_cells: number
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Component
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export default function GroundTruthQueuePage() {
|
||||
const router = useRouter()
|
||||
const [allSessions, setAllSessions] = useState<Session[]>([])
|
||||
const [gtSessions, setGtSessions] = useState<GTSession[]>([])
|
||||
const [filter, setFilter] = useState<'all' | 'unreviewed' | 'reviewed'>('all')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [selectedSessions, setSelectedSessions] = useState<Set<string>>(new Set())
|
||||
const [marking, setMarking] = useState(false)
|
||||
const [markResult, setMarkResult] = useState<string | null>(null)
|
||||
|
||||
// Load sessions + GT sessions
|
||||
const loadData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const [sessRes, gtRes] = await Promise.all([
|
||||
fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions?limit=200`),
|
||||
fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/ground-truth-sessions`),
|
||||
])
|
||||
|
||||
if (sessRes.ok) {
|
||||
const data = await sessRes.json()
|
||||
const gtSet = new Set<string>()
|
||||
|
||||
if (gtRes.ok) {
|
||||
const gtData = await gtRes.json()
|
||||
const gts: GTSession[] = gtData.sessions || []
|
||||
setGtSessions(gts)
|
||||
for (const g of gts) gtSet.add(g.session_id)
|
||||
}
|
||||
|
||||
const sessions: Session[] = (data.sessions || [])
|
||||
.filter((s: any) => !s.parent_session_id)
|
||||
.map((s: any) => ({
|
||||
id: s.id,
|
||||
name: s.name || '',
|
||||
filename: s.filename || '',
|
||||
status: s.status || 'active',
|
||||
created_at: s.created_at || '',
|
||||
document_category: s.document_category || null,
|
||||
has_ground_truth: gtSet.has(s.id),
|
||||
}))
|
||||
setAllSessions(sessions)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load data:', e)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
loadData()
|
||||
}, [loadData])
|
||||
|
||||
// Filtered sessions
|
||||
const filteredSessions = allSessions.filter((s) => {
|
||||
if (filter === 'unreviewed') return !s.has_ground_truth
|
||||
if (filter === 'reviewed') return s.has_ground_truth
|
||||
return true
|
||||
})
|
||||
|
||||
const reviewedCount = allSessions.filter((s) => s.has_ground_truth).length
|
||||
const totalCount = allSessions.length
|
||||
const pct = totalCount > 0 ? Math.round((reviewedCount / totalCount) * 100) : 0
|
||||
|
||||
// Open session in Kombi pipeline
|
||||
const openInPipeline = (sessionId: string) => {
|
||||
router.push(`/ai/ocr-overlay?session=${sessionId}&mode=kombi`)
|
||||
}
|
||||
|
||||
// Batch mark as GT
|
||||
const batchMark = async () => {
|
||||
setMarking(true)
|
||||
let success = 0
|
||||
for (const sid of selectedSessions) {
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sid}/mark-ground-truth?pipeline=kombi`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
if (res.ok) success++
|
||||
} catch {
|
||||
/* skip */
|
||||
}
|
||||
}
|
||||
setSelectedSessions(new Set())
|
||||
setMarking(false)
|
||||
setMarkResult(`${success} Sessions als Ground Truth markiert`)
|
||||
setTimeout(() => setMarkResult(null), 3000)
|
||||
loadData()
|
||||
}
|
||||
|
||||
const toggleSelect = (id: string) => {
|
||||
setSelectedSessions((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(id)) next.delete(id)
|
||||
else next.add(id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const selectAll = () => {
|
||||
if (selectedSessions.size === filteredSessions.length) {
|
||||
setSelectedSessions(new Set())
|
||||
} else {
|
||||
setSelectedSessions(new Set(filteredSessions.map((s) => s.id)))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="max-w-5xl mx-auto p-4 space-y-4">
|
||||
<PagePurpose
|
||||
title="Ground Truth Queue"
|
||||
purpose="Uebersicht aller OCR-Sessions und deren Ground-Truth-Status. Zum Pruefen und Korrigieren eine Session oeffnen — sie wird im Kombi-Modus (OCR Overlay) bearbeitet."
|
||||
audience={['Entwickler', 'QA']}
|
||||
defaultCollapsed
|
||||
architecture={{
|
||||
services: ['klausur-service (FastAPI, Port 8086)'],
|
||||
databases: ['PostgreSQL (ocr_pipeline_sessions)'],
|
||||
}}
|
||||
relatedPages={[
|
||||
{
|
||||
name: 'Kombi Pipeline',
|
||||
href: '/ai/ocr-overlay',
|
||||
description: 'Sessions bearbeiten und GT markieren',
|
||||
},
|
||||
{
|
||||
name: 'OCR Regression',
|
||||
href: '/ai/ocr-regression',
|
||||
description: 'Regressions-Tests',
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
{/* Progress Bar */}
|
||||
<div className="bg-white rounded-lg border border-slate-200 p-4">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h2 className="text-lg font-bold text-slate-900">
|
||||
Ground Truth Fortschritt
|
||||
</h2>
|
||||
<span className="text-sm text-slate-500">
|
||||
{reviewedCount} von {totalCount} markiert ({pct}%)
|
||||
</span>
|
||||
</div>
|
||||
<div className="w-full bg-slate-100 rounded-full h-2.5">
|
||||
<div
|
||||
className="bg-teal-500 h-2.5 rounded-full transition-all duration-500"
|
||||
style={{ width: `${pct}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 mt-2 text-xs text-slate-500">
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="w-2 h-2 rounded-full bg-teal-400" />
|
||||
{reviewedCount} Ground Truth
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="w-2 h-2 rounded-full bg-slate-300" />
|
||||
{totalCount - reviewedCount} offen
|
||||
</span>
|
||||
<span>
|
||||
{gtSessions.reduce((sum, g) => sum + g.summary.total_cells, 0)}{' '}
|
||||
Referenz-Zellen gesamt
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filter + Actions */}
|
||||
<div className="flex items-center gap-4 flex-wrap">
|
||||
<div className="flex gap-1 bg-slate-100 rounded-lg p-1">
|
||||
{(['all', 'unreviewed', 'reviewed'] as const).map((f) => (
|
||||
<button
|
||||
key={f}
|
||||
onClick={() => setFilter(f)}
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${
|
||||
filter === f
|
||||
? 'bg-white text-slate-900 shadow-sm font-medium'
|
||||
: 'text-slate-500 hover:text-slate-700'
|
||||
}`}
|
||||
>
|
||||
{f === 'all'
|
||||
? 'Alle'
|
||||
: f === 'unreviewed'
|
||||
? 'Offen'
|
||||
: 'Ground Truth'}
|
||||
<span className="ml-1 text-xs text-slate-400">
|
||||
(
|
||||
{
|
||||
allSessions.filter((s) =>
|
||||
f === 'unreviewed'
|
||||
? !s.has_ground_truth
|
||||
: f === 'reviewed'
|
||||
? s.has_ground_truth
|
||||
: true,
|
||||
).length
|
||||
}
|
||||
)
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
{selectedSessions.size > 0 && (
|
||||
<button
|
||||
onClick={batchMark}
|
||||
disabled={marking}
|
||||
className="px-3 py-1.5 bg-teal-600 text-white text-sm rounded-lg hover:bg-teal-700 disabled:opacity-50"
|
||||
>
|
||||
{marking
|
||||
? 'Markiere...'
|
||||
: `${selectedSessions.size} als GT markieren`}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={selectAll}
|
||||
className="px-3 py-1.5 text-sm text-slate-500 hover:text-slate-700 border border-slate-200 rounded-lg hover:bg-slate-50"
|
||||
>
|
||||
{selectedSessions.size === filteredSessions.length
|
||||
? 'Keine auswaehlen'
|
||||
: 'Alle auswaehlen'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Toast */}
|
||||
{markResult && (
|
||||
<div className="p-3 rounded-lg text-sm bg-emerald-50 text-emerald-700 border border-emerald-200">
|
||||
{markResult}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Session List */}
|
||||
{loading ? (
|
||||
<div className="text-center py-12 text-slate-400">
|
||||
Lade Sessions...
|
||||
</div>
|
||||
) : filteredSessions.length === 0 ? (
|
||||
<div className="text-center py-12 text-slate-400">
|
||||
<p className="text-lg">Keine Sessions in dieser Ansicht</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white rounded-lg border border-slate-200 overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-200 bg-slate-50 text-left text-slate-500">
|
||||
<th className="px-4 py-2 w-8">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={
|
||||
selectedSessions.size === filteredSessions.length &&
|
||||
filteredSessions.length > 0
|
||||
}
|
||||
onChange={selectAll}
|
||||
className="rounded border-slate-300"
|
||||
/>
|
||||
</th>
|
||||
<th className="px-4 py-2 font-medium">Status</th>
|
||||
<th className="px-4 py-2 font-medium">Session</th>
|
||||
<th className="px-4 py-2 font-medium">Kategorie</th>
|
||||
<th className="px-4 py-2 font-medium">Erstellt</th>
|
||||
<th className="px-4 py-2 font-medium text-right">
|
||||
Aktion
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filteredSessions.map((s) => {
|
||||
const gt = gtSessions.find((g) => g.session_id === s.id)
|
||||
return (
|
||||
<tr
|
||||
key={s.id}
|
||||
className="border-b border-slate-50 hover:bg-slate-50 transition-colors"
|
||||
>
|
||||
<td className="px-4 py-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedSessions.has(s.id)}
|
||||
onChange={() => toggleSelect(s.id)}
|
||||
className="rounded border-slate-300"
|
||||
/>
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
{s.has_ground_truth ? (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-700 border border-emerald-200">
|
||||
<svg
|
||||
className="w-3 h-3"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M5 13l4 4L19 7"
|
||||
/>
|
||||
</svg>
|
||||
GT
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-500 border border-slate-200">
|
||||
Offen
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex-shrink-0 w-8 h-8 rounded bg-slate-100 overflow-hidden">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${s.id}/thumbnail?size=64`}
|
||||
alt=""
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
onError={(e) => {
|
||||
;(e.target as HTMLImageElement).style.display =
|
||||
'none'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium text-slate-900 truncate">
|
||||
{s.name || s.filename || s.id.slice(0, 8)}
|
||||
</div>
|
||||
{gt && (
|
||||
<div className="text-xs text-slate-400">
|
||||
{gt.summary.total_cells} Zellen,{' '}
|
||||
{gt.summary.total_zones} Zonen
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
{s.document_category ? (
|
||||
<span className="text-xs bg-slate-100 px-1.5 py-0.5 rounded text-slate-600">
|
||||
{s.document_category}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs text-slate-300">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-slate-500">
|
||||
{new Date(s.created_at).toLocaleDateString('de-DE', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: '2-digit',
|
||||
})}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-right">
|
||||
<button
|
||||
onClick={() => openInPipeline(s.id)}
|
||||
className="px-3 py-1 text-xs bg-teal-600 text-white rounded hover:bg-teal-700 transition-colors"
|
||||
>
|
||||
{s.has_ground_truth
|
||||
? 'Ueberpruefen'
|
||||
: 'Im Kombi-Modus oeffnen'}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
173
admin-lehrer/app/(admin)/ai/ocr-kombi/page.tsx
Normal file
173
admin-lehrer/app/(admin)/ai/ocr-kombi/page.tsx
Normal file
@@ -0,0 +1,173 @@
|
||||
'use client'
|
||||
|
||||
import { Suspense } from 'react'
|
||||
import { PagePurpose } from '@/components/common/PagePurpose'
|
||||
import { KombiStepper } from '@/components/ocr-kombi/KombiStepper'
|
||||
import { SessionList } from '@/components/ocr-kombi/SessionList'
|
||||
import { SessionHeader } from '@/components/ocr-kombi/SessionHeader'
|
||||
import { StepUpload } from '@/components/ocr-kombi/StepUpload'
|
||||
import { StepOrientation } from '@/components/ocr-kombi/StepOrientation'
|
||||
import { StepPageSplit } from '@/components/ocr-kombi/StepPageSplit'
|
||||
import { StepDeskew } from '@/components/ocr-kombi/StepDeskew'
|
||||
import { StepDewarp } from '@/components/ocr-kombi/StepDewarp'
|
||||
import { StepContentCrop } from '@/components/ocr-kombi/StepContentCrop'
|
||||
import { StepOcr } from '@/components/ocr-kombi/StepOcr'
|
||||
import { StepStructure } from '@/components/ocr-kombi/StepStructure'
|
||||
import { StepGridBuild } from '@/components/ocr-kombi/StepGridBuild'
|
||||
import { StepGridReview } from '@/components/ocr-kombi/StepGridReview'
|
||||
import { StepGutterRepair } from '@/components/ocr-kombi/StepGutterRepair'
|
||||
import { StepBoxGridReview } from '@/components/ocr-kombi/StepBoxGridReview'
|
||||
import { StepAnsicht } from '@/components/ocr-kombi/StepAnsicht'
|
||||
import { StepGroundTruth } from '@/components/ocr-kombi/StepGroundTruth'
|
||||
import { useKombiPipeline } from './useKombiPipeline'
|
||||
|
||||
function OcrKombiContent() {
|
||||
const {
|
||||
currentStep,
|
||||
sessionId,
|
||||
sessionName,
|
||||
loadingSessions,
|
||||
activeCategory,
|
||||
isGroundTruth,
|
||||
pageNumber,
|
||||
steps,
|
||||
gridSaveRef,
|
||||
groupedSessions,
|
||||
loadSessions,
|
||||
openSession,
|
||||
handleStepClick,
|
||||
handleNext,
|
||||
handleNewSession,
|
||||
deleteSession,
|
||||
renameSession,
|
||||
updateCategory,
|
||||
setSessionId,
|
||||
setSessionName,
|
||||
setIsGroundTruth,
|
||||
} = useKombiPipeline()
|
||||
|
||||
const renderStep = () => {
|
||||
switch (currentStep) {
|
||||
case 0:
|
||||
return (
|
||||
<StepUpload
|
||||
sessionId={sessionId}
|
||||
onUploaded={(sid, name) => {
|
||||
setSessionId(sid)
|
||||
setSessionName(name)
|
||||
loadSessions()
|
||||
}}
|
||||
onNext={handleNext}
|
||||
/>
|
||||
)
|
||||
case 1:
|
||||
return (
|
||||
<StepOrientation
|
||||
sessionId={sessionId}
|
||||
onNext={() => handleNext()}
|
||||
onSessionList={() => { loadSessions(); handleNewSession() }}
|
||||
/>
|
||||
)
|
||||
case 2:
|
||||
return (
|
||||
<StepPageSplit
|
||||
sessionId={sessionId}
|
||||
sessionName={sessionName}
|
||||
onNext={handleNext}
|
||||
onSplitComplete={(childId, childName) => {
|
||||
// Switch to the first child session and refresh the list
|
||||
setSessionId(childId)
|
||||
setSessionName(childName)
|
||||
loadSessions()
|
||||
}}
|
||||
/>
|
||||
)
|
||||
case 3:
|
||||
return <StepDeskew sessionId={sessionId} onNext={handleNext} />
|
||||
case 4:
|
||||
return <StepDewarp sessionId={sessionId} onNext={handleNext} />
|
||||
case 5:
|
||||
return <StepContentCrop sessionId={sessionId} onNext={handleNext} />
|
||||
case 6:
|
||||
return <StepOcr sessionId={sessionId} onNext={handleNext} />
|
||||
case 7:
|
||||
return <StepStructure sessionId={sessionId} onNext={handleNext} />
|
||||
case 8:
|
||||
return <StepGridBuild sessionId={sessionId} onNext={handleNext} />
|
||||
case 9:
|
||||
return <StepGridReview sessionId={sessionId} onNext={handleNext} saveRef={gridSaveRef} />
|
||||
case 10:
|
||||
return <StepGutterRepair sessionId={sessionId} onNext={handleNext} />
|
||||
case 11:
|
||||
return <StepBoxGridReview sessionId={sessionId} onNext={handleNext} />
|
||||
case 12:
|
||||
return <StepAnsicht sessionId={sessionId} onNext={handleNext} />
|
||||
case 13:
|
||||
return (
|
||||
<StepGroundTruth
|
||||
sessionId={sessionId}
|
||||
isGroundTruth={isGroundTruth}
|
||||
onMarked={() => setIsGroundTruth(true)}
|
||||
gridSaveRef={gridSaveRef}
|
||||
/>
|
||||
)
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PagePurpose
|
||||
title="OCR Kombi Pipeline"
|
||||
purpose="Modulare 11-Schritt-Pipeline: Upload, Vorverarbeitung, Dual-Engine-OCR (PP-OCRv5 + Tesseract), Strukturerkennung, Grid-Aufbau und Review. Multi-Page-Dokument-Unterstuetzung."
|
||||
audience={['Entwickler']}
|
||||
architecture={{
|
||||
services: ['klausur-service (FastAPI)', 'OpenCV', 'Tesseract', 'PaddleOCR'],
|
||||
databases: ['PostgreSQL Sessions'],
|
||||
}}
|
||||
relatedPages={[
|
||||
{ name: 'OCR Regression', href: '/ai/ocr-regression', description: 'Regressionstests' },
|
||||
]}
|
||||
defaultCollapsed
|
||||
/>
|
||||
|
||||
<SessionList
|
||||
items={groupedSessions()}
|
||||
loading={loadingSessions}
|
||||
activeSessionId={sessionId}
|
||||
onOpenSession={(sid) => openSession(sid)}
|
||||
onNewSession={handleNewSession}
|
||||
onDeleteSession={deleteSession}
|
||||
onRenameSession={renameSession}
|
||||
onUpdateCategory={updateCategory}
|
||||
/>
|
||||
|
||||
{sessionId && sessionName && (
|
||||
<SessionHeader
|
||||
sessionName={sessionName}
|
||||
activeCategory={activeCategory}
|
||||
isGroundTruth={isGroundTruth}
|
||||
pageNumber={pageNumber}
|
||||
onUpdateCategory={(cat) => updateCategory(sessionId, cat)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<KombiStepper
|
||||
steps={steps}
|
||||
currentStep={currentStep}
|
||||
onStepClick={handleStepClick}
|
||||
/>
|
||||
|
||||
<div className="min-h-[400px]">{renderStep()}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function OcrKombiPage() {
|
||||
return (
|
||||
<Suspense fallback={<div className="p-4 text-sm text-gray-400">Lade...</div>}>
|
||||
<OcrKombiContent />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
266
admin-lehrer/app/(admin)/ai/ocr-kombi/types.ts
Normal file
266
admin-lehrer/app/(admin)/ai/ocr-kombi/types.ts
Normal file
@@ -0,0 +1,266 @@
|
||||
// OCR Pipeline Types — migrated from deleted ocr-pipeline/types.ts
|
||||
|
||||
export type PipelineStepStatus = 'pending' | 'active' | 'completed' | 'failed' | 'skipped'
|
||||
|
||||
export interface PipelineStep {
|
||||
id: string
|
||||
name: string
|
||||
icon: string
|
||||
status: PipelineStepStatus
|
||||
}
|
||||
|
||||
export type DocumentCategory =
|
||||
| 'vokabelseite' | 'woerterbuch' | 'buchseite' | 'arbeitsblatt' | 'klausurseite'
|
||||
| 'mathearbeit' | 'statistik' | 'zeitung' | 'formular' | 'handschrift' | 'sonstiges'
|
||||
|
||||
export const DOCUMENT_CATEGORIES: { value: DocumentCategory; label: string; icon: string }[] = [
|
||||
{ value: 'vokabelseite', label: 'Vokabelseite', icon: '📖' },
|
||||
{ value: 'woerterbuch', label: 'Woerterbuch', icon: '📕' },
|
||||
{ value: 'buchseite', label: 'Buchseite', icon: '📚' },
|
||||
{ value: 'arbeitsblatt', label: 'Arbeitsblatt', icon: '📝' },
|
||||
{ value: 'klausurseite', label: 'Klausurseite', icon: '📄' },
|
||||
{ value: 'mathearbeit', label: 'Mathearbeit', icon: '🔢' },
|
||||
{ value: 'statistik', label: 'Statistik', icon: '📊' },
|
||||
{ value: 'zeitung', label: 'Zeitung', icon: '📰' },
|
||||
{ value: 'formular', label: 'Formular', icon: '📋' },
|
||||
{ value: 'handschrift', label: 'Handschrift', icon: '✍️' },
|
||||
{ value: 'sonstiges', label: 'Sonstiges', icon: '📎' },
|
||||
]
|
||||
|
||||
export interface SessionListItem {
|
||||
id: string
|
||||
name: string
|
||||
filename: string
|
||||
status: string
|
||||
current_step: number
|
||||
document_category?: DocumentCategory
|
||||
doc_type?: string
|
||||
parent_session_id?: string
|
||||
document_group_id?: string
|
||||
page_number?: number
|
||||
is_ground_truth?: boolean
|
||||
created_at: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
export interface SubSession {
|
||||
id: string
|
||||
name: string
|
||||
box_index: number
|
||||
current_step?: number
|
||||
status?: string
|
||||
}
|
||||
|
||||
export interface OrientationResult {
|
||||
orientation_degrees: number
|
||||
corrected: boolean
|
||||
duration_seconds: number
|
||||
}
|
||||
|
||||
export interface CropResult {
|
||||
crop_applied: boolean
|
||||
crop_rect?: { x: number; y: number; width: number; height: number }
|
||||
crop_rect_pct?: { x: number; y: number; width: number; height: number }
|
||||
original_size: { width: number; height: number }
|
||||
cropped_size: { width: number; height: number }
|
||||
detected_format?: string
|
||||
format_confidence?: number
|
||||
aspect_ratio?: number
|
||||
border_fractions?: { top: number; bottom: number; left: number; right: number }
|
||||
skipped?: boolean
|
||||
duration_seconds?: number
|
||||
}
|
||||
|
||||
export interface DeskewResult {
|
||||
session_id: string
|
||||
angle_hough: number
|
||||
angle_word_alignment: number
|
||||
angle_iterative?: number
|
||||
angle_residual?: number
|
||||
angle_textline?: number
|
||||
angle_applied: number
|
||||
method_used: 'hough' | 'word_alignment' | 'manual' | 'iterative' | 'two_pass' | 'three_pass' | 'manual_combined'
|
||||
confidence: number
|
||||
duration_seconds: number
|
||||
deskewed_image_url: string
|
||||
binarized_image_url: string
|
||||
}
|
||||
|
||||
export interface DewarpDetection {
|
||||
method: string
|
||||
shear_degrees: number
|
||||
confidence: number
|
||||
}
|
||||
|
||||
export interface DewarpResult {
|
||||
session_id: string
|
||||
method_used: string
|
||||
shear_degrees: number
|
||||
confidence: number
|
||||
duration_seconds: number
|
||||
dewarped_image_url: string
|
||||
detections?: DewarpDetection[]
|
||||
}
|
||||
|
||||
export interface SessionInfo {
|
||||
session_id: string
|
||||
filename: string
|
||||
name?: string
|
||||
image_width: number
|
||||
image_height: number
|
||||
original_image_url: string
|
||||
current_step?: number
|
||||
document_category?: DocumentCategory
|
||||
doc_type?: string
|
||||
orientation_result?: OrientationResult
|
||||
crop_result?: CropResult
|
||||
deskew_result?: DeskewResult
|
||||
dewarp_result?: DewarpResult
|
||||
sub_sessions?: SubSession[]
|
||||
parent_session_id?: string
|
||||
box_index?: number
|
||||
document_group_id?: string
|
||||
page_number?: number
|
||||
}
|
||||
|
||||
export interface StructureGraphic {
|
||||
x: number; y: number; w: number; h: number
|
||||
area: number; shape: string; color_name: string; color_hex: string; confidence: number
|
||||
}
|
||||
|
||||
export interface ExcludeRegion {
|
||||
x: number; y: number; w: number; h: number; label?: string
|
||||
}
|
||||
|
||||
export interface StructureBox {
|
||||
x: number; y: number; w: number; h: number
|
||||
confidence: number; border_thickness: number
|
||||
bg_color_name?: string; bg_color_hex?: string
|
||||
}
|
||||
|
||||
export interface StructureZone {
|
||||
index: number; zone_type: 'content' | 'box'
|
||||
x: number; y: number; w: number; h: number
|
||||
}
|
||||
|
||||
export interface DocLayoutRegion {
|
||||
x: number; y: number; w: number; h: number
|
||||
class_name: string; confidence: number
|
||||
}
|
||||
|
||||
export interface StructureResult {
|
||||
image_width: number; image_height: number
|
||||
content_bounds: { x: number; y: number; w: number; h: number }
|
||||
boxes: StructureBox[]; zones: StructureZone[]
|
||||
graphics: StructureGraphic[]; exclude_regions?: ExcludeRegion[]
|
||||
color_pixel_counts: Record<string, number>
|
||||
has_words: boolean; word_count: number
|
||||
border_ghosts_removed?: number; duration_seconds: number
|
||||
layout_regions?: DocLayoutRegion[]
|
||||
detection_method?: 'opencv' | 'ppdoclayout'
|
||||
}
|
||||
|
||||
export interface WordBbox { x: number; y: number; w: number; h: number }
|
||||
|
||||
export interface OcrWordBox {
|
||||
text: string; left: number; top: number; width: number; height: number; conf: number
|
||||
color?: string; color_name?: string; recovered?: boolean
|
||||
}
|
||||
|
||||
export interface ColumnMeta { index: number; type: string; x: number; width: number }
|
||||
|
||||
export interface GridCell {
|
||||
cell_id: string; row_index: number; col_index: number; col_type: string
|
||||
text: string; confidence: number; bbox_px: WordBbox; bbox_pct: WordBbox
|
||||
ocr_engine?: string; is_bold?: boolean
|
||||
status?: 'pending' | 'confirmed' | 'edited' | 'skipped'
|
||||
word_boxes?: OcrWordBox[]
|
||||
}
|
||||
|
||||
export interface WordEntry {
|
||||
row_index: number; english: string; german: string; example: string
|
||||
source_page?: string; marker?: string; confidence: number
|
||||
bbox: WordBbox; bbox_en: WordBbox | null; bbox_de: WordBbox | null; bbox_ex: WordBbox | null
|
||||
bbox_ref?: WordBbox | null; bbox_marker?: WordBbox | null
|
||||
status?: 'pending' | 'confirmed' | 'edited' | 'skipped'
|
||||
}
|
||||
|
||||
export interface GridResult {
|
||||
cells: GridCell[]
|
||||
grid_shape: { rows: number; cols: number; total_cells: number }
|
||||
columns_used: ColumnMeta[]
|
||||
layout: 'vocab' | 'generic'
|
||||
image_width: number; image_height: number; duration_seconds: number
|
||||
ocr_engine?: string; vocab_entries?: WordEntry[]; entries?: WordEntry[]; entry_count?: number
|
||||
summary: {
|
||||
total_cells: number; non_empty_cells: number; low_confidence: number
|
||||
total_entries?: number; with_english?: number; with_german?: number
|
||||
}
|
||||
llm_review?: {
|
||||
changes: { row_index: number; field: string; old: string; new: string }[]
|
||||
model_used: string; duration_ms: number; entries_corrected: number
|
||||
applied_count?: number; applied_at?: string
|
||||
}
|
||||
}
|
||||
|
||||
// --- Kombi V2 Pipeline ---
|
||||
|
||||
export const KOMBI_V2_STEPS: PipelineStep[] = [
|
||||
{ id: 'upload', name: 'Upload', icon: '📤', status: 'pending' },
|
||||
{ id: 'orientation', name: 'Orientierung', icon: '🔄', status: 'pending' },
|
||||
{ id: 'page-split', name: 'Seitentrennung', icon: '📖', status: 'pending' },
|
||||
{ id: 'deskew', name: 'Begradigung', icon: '📐', status: 'pending' },
|
||||
{ id: 'dewarp', name: 'Entzerrung', icon: '🔧', status: 'pending' },
|
||||
{ id: 'content-crop', name: 'Zuschneiden', icon: '✂️', status: 'pending' },
|
||||
{ id: 'ocr', name: 'OCR', icon: '🔀', status: 'pending' },
|
||||
{ id: 'structure', name: 'Strukturerkennung', icon: '🔍', status: 'pending' },
|
||||
{ id: 'grid-build', name: 'Grid-Aufbau', icon: '🧱', status: 'pending' },
|
||||
{ id: 'grid-review', name: 'Grid-Review', icon: '📊', status: 'pending' },
|
||||
{ id: 'gutter-repair', name: 'Wortkorrektur', icon: '🩹', status: 'pending' },
|
||||
{ id: 'box-review', name: 'Box-Review', icon: '📦', status: 'pending' },
|
||||
{ id: 'ansicht', name: 'Ansicht', icon: '👁️', status: 'pending' },
|
||||
{ id: 'ground-truth', name: 'Ground Truth', icon: '✅', status: 'pending' },
|
||||
]
|
||||
|
||||
export const KOMBI_V2_UI_TO_DB: Record<number, number> = {
|
||||
0: 1, 1: 2, 2: 2, 3: 3, 4: 4, 5: 5, 6: 8, 7: 9, 8: 10, 9: 11, 10: 11, 11: 11, 12: 11, 13: 12,
|
||||
}
|
||||
|
||||
export function dbStepToKombiV2Ui(dbStep: number): number {
|
||||
if (dbStep <= 1) return 0
|
||||
if (dbStep === 2) return 1
|
||||
if (dbStep === 3) return 3
|
||||
if (dbStep === 4) return 4
|
||||
if (dbStep === 5) return 5
|
||||
if (dbStep <= 8) return 6
|
||||
if (dbStep === 9) return 7
|
||||
if (dbStep === 10) return 8
|
||||
if (dbStep === 11) return 9
|
||||
return 13
|
||||
}
|
||||
|
||||
export interface DocumentGroup {
|
||||
group_id: string; title: string; page_count: number; sessions: DocumentGroupSession[]
|
||||
}
|
||||
|
||||
export interface DocumentGroupSession {
|
||||
id: string; name: string; page_number: number; current_step: number
|
||||
status: string; document_category?: DocumentCategory; created_at: string
|
||||
}
|
||||
|
||||
export type OcrEngineSource = 'both' | 'paddle_only' | 'tesseract_only' | 'conflict_paddle' | 'conflict_tesseract'
|
||||
|
||||
export interface OcrTransparentWord {
|
||||
text: string; left: number; top: number; width: number; height: number
|
||||
conf: number; engine_source: OcrEngineSource
|
||||
}
|
||||
|
||||
export interface OcrTransparentResult {
|
||||
raw_tesseract: { words: OcrTransparentWord[] }
|
||||
raw_paddle: { words: OcrTransparentWord[] }
|
||||
merged: { words: OcrTransparentWord[] }
|
||||
stats: {
|
||||
total_words: number; both_agree: number; paddle_only: number
|
||||
tesseract_only: number; conflict_paddle_wins: number; conflict_tesseract_wins: number
|
||||
}
|
||||
}
|
||||
298
admin-lehrer/app/(admin)/ai/ocr-kombi/useKombiPipeline.ts
Normal file
298
admin-lehrer/app/(admin)/ai/ocr-kombi/useKombiPipeline.ts
Normal file
@@ -0,0 +1,298 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState, useRef } from 'react'
|
||||
import { useSearchParams } from 'next/navigation'
|
||||
import type { PipelineStep, DocumentCategory, SessionListItem } from './types'
|
||||
import { KOMBI_V2_STEPS, dbStepToKombiV2Ui } from './types'
|
||||
|
||||
export type { SessionListItem }
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
/** Groups sessions by document_group_id for the session list */
|
||||
export interface DocumentGroupView {
|
||||
group_id: string
|
||||
title: string
|
||||
sessions: SessionListItem[]
|
||||
page_count: number
|
||||
}
|
||||
|
||||
function initSteps(): PipelineStep[] {
|
||||
return KOMBI_V2_STEPS.map((s, i) => ({
|
||||
...s,
|
||||
status: i === 0 ? 'active' : 'pending',
|
||||
}))
|
||||
}
|
||||
|
||||
export function useKombiPipeline() {
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [sessionId, setSessionId] = useState<string | null>(null)
|
||||
const [sessionName, setSessionName] = useState('')
|
||||
const [sessions, setSessions] = useState<SessionListItem[]>([])
|
||||
const [loadingSessions, setLoadingSessions] = useState(true)
|
||||
const [activeCategory, setActiveCategory] = useState<DocumentCategory | undefined>(undefined)
|
||||
const [isGroundTruth, setIsGroundTruth] = useState(false)
|
||||
const [pageNumber, setPageNumber] = useState<number | null>(null)
|
||||
const [steps, setSteps] = useState<PipelineStep[]>(initSteps())
|
||||
|
||||
const searchParams = useSearchParams()
|
||||
const deepLinkHandled = useRef(false)
|
||||
const gridSaveRef = useRef<(() => Promise<void>) | null>(null)
|
||||
|
||||
// ---- Session loading ----
|
||||
|
||||
const loadSessions = useCallback(async () => {
|
||||
setLoadingSessions(true)
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions`)
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setSessions((data.sessions || []).filter((s: SessionListItem) => !s.parent_session_id))
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load sessions:', e)
|
||||
} finally {
|
||||
setLoadingSessions(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => { loadSessions() }, [loadSessions])
|
||||
|
||||
// ---- Group sessions by document_group_id ----
|
||||
|
||||
const groupedSessions = useCallback((): (SessionListItem | DocumentGroupView)[] => {
|
||||
const groups = new Map<string, SessionListItem[]>()
|
||||
const ungrouped: SessionListItem[] = []
|
||||
|
||||
for (const s of sessions) {
|
||||
if (s.document_group_id) {
|
||||
const existing = groups.get(s.document_group_id) || []
|
||||
existing.push(s)
|
||||
groups.set(s.document_group_id, existing)
|
||||
} else {
|
||||
ungrouped.push(s)
|
||||
}
|
||||
}
|
||||
|
||||
const result: (SessionListItem | DocumentGroupView)[] = []
|
||||
|
||||
// Sort groups by earliest created_at
|
||||
const sortedGroups = Array.from(groups.entries()).sort((a, b) => {
|
||||
const aTime = Math.min(...a[1].map(s => new Date(s.created_at).getTime()))
|
||||
const bTime = Math.min(...b[1].map(s => new Date(s.created_at).getTime()))
|
||||
return bTime - aTime
|
||||
})
|
||||
|
||||
for (const [groupId, groupSessions] of sortedGroups) {
|
||||
groupSessions.sort((a, b) => (a.page_number || 0) - (b.page_number || 0))
|
||||
// Extract base title (remove " — S. X" suffix)
|
||||
const baseName = groupSessions[0]?.name?.replace(/ — S\. \d+$/, '') || 'Dokument'
|
||||
result.push({
|
||||
group_id: groupId,
|
||||
title: baseName,
|
||||
sessions: groupSessions,
|
||||
page_count: groupSessions.length,
|
||||
})
|
||||
}
|
||||
|
||||
for (const s of ungrouped) {
|
||||
result.push(s)
|
||||
}
|
||||
|
||||
// Sort by creation time (most recent first)
|
||||
const getTime = (item: SessionListItem | DocumentGroupView): number => {
|
||||
if ('group_id' in item) {
|
||||
return Math.min(...item.sessions.map((s: SessionListItem) => new Date(s.created_at).getTime()))
|
||||
}
|
||||
return new Date(item.created_at).getTime()
|
||||
}
|
||||
result.sort((a, b) => getTime(b) - getTime(a))
|
||||
|
||||
return result
|
||||
}, [sessions])
|
||||
|
||||
// ---- Open session ----
|
||||
|
||||
const openSession = useCallback(async (sid: string) => {
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sid}`)
|
||||
if (!res.ok) return
|
||||
const data = await res.json()
|
||||
|
||||
setSessionId(sid)
|
||||
setSessionName(data.name || data.filename || '')
|
||||
setActiveCategory(data.document_category || undefined)
|
||||
setIsGroundTruth(!!data.ground_truth?.build_grid_reference)
|
||||
setPageNumber(data.grid_editor_result?.page_number?.number ?? null)
|
||||
|
||||
// Determine UI step from DB state
|
||||
const dbStep = data.current_step || 1
|
||||
const hasGrid = !!data.grid_editor_result
|
||||
const hasStructure = !!data.structure_result
|
||||
const hasWords = !!data.word_result
|
||||
const hasGutterRepair = !!(data.ground_truth?.gutter_repair)
|
||||
|
||||
let uiStep: number
|
||||
if (hasGrid && hasGutterRepair) {
|
||||
uiStep = 10 // gutter-repair (already analysed)
|
||||
} else if (hasGrid) {
|
||||
uiStep = 9 // grid-review
|
||||
} else if (hasStructure) {
|
||||
uiStep = 8 // grid-build
|
||||
} else if (hasWords) {
|
||||
uiStep = 7 // structure
|
||||
} else {
|
||||
uiStep = dbStepToKombiV2Ui(dbStep)
|
||||
}
|
||||
|
||||
// Sessions only exist after upload, so always skip the upload step
|
||||
if (uiStep === 0) {
|
||||
uiStep = 1
|
||||
}
|
||||
|
||||
setSteps(
|
||||
KOMBI_V2_STEPS.map((s, i) => ({
|
||||
...s,
|
||||
status: i < uiStep ? 'completed' : i === uiStep ? 'active' : 'pending',
|
||||
})),
|
||||
)
|
||||
setCurrentStep(uiStep)
|
||||
} catch (e) {
|
||||
console.error('Failed to open session:', e)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// ---- Deep link handling ----
|
||||
|
||||
useEffect(() => {
|
||||
if (deepLinkHandled.current) return
|
||||
const urlSession = searchParams.get('session')
|
||||
const urlStep = searchParams.get('step')
|
||||
if (urlSession) {
|
||||
deepLinkHandled.current = true
|
||||
openSession(urlSession).then(() => {
|
||||
if (urlStep) {
|
||||
const stepIdx = parseInt(urlStep, 10)
|
||||
if (!isNaN(stepIdx) && stepIdx >= 0 && stepIdx < KOMBI_V2_STEPS.length) {
|
||||
setCurrentStep(stepIdx)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}, [searchParams, openSession])
|
||||
|
||||
// ---- Step navigation ----
|
||||
|
||||
const goToStep = useCallback((step: number) => {
|
||||
setCurrentStep(step)
|
||||
setSteps(prev =>
|
||||
prev.map((s, i) => ({
|
||||
...s,
|
||||
status: i < step ? 'completed' : i === step ? 'active' : 'pending',
|
||||
})),
|
||||
)
|
||||
}, [])
|
||||
|
||||
const handleStepClick = useCallback((index: number) => {
|
||||
if (index <= currentStep || steps[index].status === 'completed') {
|
||||
setCurrentStep(index)
|
||||
}
|
||||
}, [currentStep, steps])
|
||||
|
||||
const handleNext = useCallback(() => {
|
||||
if (currentStep >= steps.length - 1) {
|
||||
// Last step → return to session list
|
||||
setSteps(initSteps())
|
||||
setCurrentStep(0)
|
||||
setSessionId(null)
|
||||
loadSessions()
|
||||
return
|
||||
}
|
||||
|
||||
const nextStep = currentStep + 1
|
||||
setSteps(prev =>
|
||||
prev.map((s, i) => {
|
||||
if (i === currentStep) return { ...s, status: 'completed' }
|
||||
if (i === nextStep) return { ...s, status: 'active' }
|
||||
return s
|
||||
}),
|
||||
)
|
||||
setCurrentStep(nextStep)
|
||||
}, [currentStep, steps, loadSessions])
|
||||
|
||||
// ---- Session CRUD ----
|
||||
|
||||
const handleNewSession = useCallback(() => {
|
||||
setSessionId(null)
|
||||
setSessionName('')
|
||||
setCurrentStep(0)
|
||||
setSteps(initSteps())
|
||||
}, [])
|
||||
|
||||
const deleteSession = useCallback(async (sid: string) => {
|
||||
try {
|
||||
await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sid}`, { method: 'DELETE' })
|
||||
setSessions(prev => prev.filter(s => s.id !== sid))
|
||||
if (sessionId === sid) handleNewSession()
|
||||
} catch (e) {
|
||||
console.error('Failed to delete session:', e)
|
||||
}
|
||||
}, [sessionId, handleNewSession])
|
||||
|
||||
const renameSession = useCallback(async (sid: string, newName: string) => {
|
||||
try {
|
||||
await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: newName }),
|
||||
})
|
||||
setSessions(prev => prev.map(s => s.id === sid ? { ...s, name: newName } : s))
|
||||
if (sessionId === sid) setSessionName(newName)
|
||||
} catch (e) {
|
||||
console.error('Failed to rename session:', e)
|
||||
}
|
||||
}, [sessionId])
|
||||
|
||||
const updateCategory = useCallback(async (sid: string, category: DocumentCategory) => {
|
||||
try {
|
||||
await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ document_category: category }),
|
||||
})
|
||||
setSessions(prev => prev.map(s => s.id === sid ? { ...s, document_category: category } : s))
|
||||
if (sessionId === sid) setActiveCategory(category)
|
||||
} catch (e) {
|
||||
console.error('Failed to update category:', e)
|
||||
}
|
||||
}, [sessionId])
|
||||
|
||||
return {
|
||||
// State
|
||||
currentStep,
|
||||
sessionId,
|
||||
sessionName,
|
||||
sessions,
|
||||
loadingSessions,
|
||||
activeCategory,
|
||||
isGroundTruth,
|
||||
pageNumber,
|
||||
steps,
|
||||
gridSaveRef,
|
||||
// Computed
|
||||
groupedSessions,
|
||||
// Actions
|
||||
loadSessions,
|
||||
openSession,
|
||||
goToStep,
|
||||
handleStepClick,
|
||||
handleNext,
|
||||
handleNewSession,
|
||||
deleteSession,
|
||||
renameSession,
|
||||
updateCategory,
|
||||
setSessionId,
|
||||
setSessionName,
|
||||
setIsGroundTruth,
|
||||
}
|
||||
}
|
||||
@@ -1,409 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { PagePurpose } from '@/components/common/PagePurpose'
|
||||
import { PipelineStepper } from '@/components/ocr-pipeline/PipelineStepper'
|
||||
import { StepDeskew } from '@/components/ocr-pipeline/StepDeskew'
|
||||
import { StepDewarp } from '@/components/ocr-pipeline/StepDewarp'
|
||||
import { StepColumnDetection } from '@/components/ocr-pipeline/StepColumnDetection'
|
||||
import { StepRowDetection } from '@/components/ocr-pipeline/StepRowDetection'
|
||||
import { StepWordRecognition } from '@/components/ocr-pipeline/StepWordRecognition'
|
||||
import { StepLlmReview } from '@/components/ocr-pipeline/StepLlmReview'
|
||||
import { StepReconstruction } from '@/components/ocr-pipeline/StepReconstruction'
|
||||
import { StepGroundTruth } from '@/components/ocr-pipeline/StepGroundTruth'
|
||||
import { PIPELINE_STEPS, type PipelineStep, type SessionListItem, type DocumentTypeResult } from './types'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
export default function OcrPipelinePage() {
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [sessionId, setSessionId] = useState<string | null>(null)
|
||||
const [sessionName, setSessionName] = useState<string>('')
|
||||
const [sessions, setSessions] = useState<SessionListItem[]>([])
|
||||
const [loadingSessions, setLoadingSessions] = useState(true)
|
||||
const [editingName, setEditingName] = useState<string | null>(null)
|
||||
const [editNameValue, setEditNameValue] = useState('')
|
||||
const [docTypeResult, setDocTypeResult] = useState<DocumentTypeResult | null>(null)
|
||||
const [steps, setSteps] = useState<PipelineStep[]>(
|
||||
PIPELINE_STEPS.map((s, i) => ({
|
||||
...s,
|
||||
status: i === 0 ? 'active' : 'pending',
|
||||
})),
|
||||
)
|
||||
|
||||
// Load session list on mount
|
||||
useEffect(() => {
|
||||
loadSessions()
|
||||
}, [])
|
||||
|
||||
const loadSessions = async () => {
|
||||
setLoadingSessions(true)
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions`)
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setSessions(data.sessions || [])
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load sessions:', e)
|
||||
} finally {
|
||||
setLoadingSessions(false)
|
||||
}
|
||||
}
|
||||
|
||||
const openSession = useCallback(async (sid: string) => {
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sid}`)
|
||||
if (!res.ok) return
|
||||
const data = await res.json()
|
||||
|
||||
setSessionId(sid)
|
||||
setSessionName(data.name || data.filename || '')
|
||||
|
||||
// Restore doc type result if available
|
||||
const savedDocType: DocumentTypeResult | null = data.doc_type_result || null
|
||||
setDocTypeResult(savedDocType)
|
||||
|
||||
// Determine which step to jump to based on current_step
|
||||
const dbStep = data.current_step || 1
|
||||
// Steps: 1=deskew, 2=dewarp, 3=columns, ...
|
||||
// UI steps are 0-indexed: 0=deskew, 1=dewarp, 2=columns, ...
|
||||
const uiStep = Math.max(0, dbStep - 1)
|
||||
const skipSteps = savedDocType?.skip_steps || []
|
||||
|
||||
setSteps(
|
||||
PIPELINE_STEPS.map((s, i) => ({
|
||||
...s,
|
||||
status: skipSteps.includes(s.id)
|
||||
? 'skipped'
|
||||
: i < uiStep ? 'completed' : i === uiStep ? 'active' : 'pending',
|
||||
})),
|
||||
)
|
||||
setCurrentStep(uiStep)
|
||||
} catch (e) {
|
||||
console.error('Failed to open session:', e)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const deleteSession = useCallback(async (sid: string) => {
|
||||
try {
|
||||
await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sid}`, { method: 'DELETE' })
|
||||
setSessions((prev) => prev.filter((s) => s.id !== sid))
|
||||
if (sessionId === sid) {
|
||||
setSessionId(null)
|
||||
setCurrentStep(0)
|
||||
setDocTypeResult(null)
|
||||
setSteps(PIPELINE_STEPS.map((s, i) => ({ ...s, status: i === 0 ? 'active' : 'pending' })))
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to delete session:', e)
|
||||
}
|
||||
}, [sessionId])
|
||||
|
||||
const renameSession = useCallback(async (sid: string, newName: string) => {
|
||||
try {
|
||||
await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: newName }),
|
||||
})
|
||||
setSessions((prev) => prev.map((s) => (s.id === sid ? { ...s, name: newName } : s)))
|
||||
if (sessionId === sid) setSessionName(newName)
|
||||
} catch (e) {
|
||||
console.error('Failed to rename session:', e)
|
||||
}
|
||||
setEditingName(null)
|
||||
}, [sessionId])
|
||||
|
||||
const handleStepClick = (index: number) => {
|
||||
if (index <= currentStep || steps[index].status === 'completed') {
|
||||
setCurrentStep(index)
|
||||
}
|
||||
}
|
||||
|
||||
const goToStep = (step: number) => {
|
||||
setCurrentStep(step)
|
||||
setSteps((prev) =>
|
||||
prev.map((s, i) => ({
|
||||
...s,
|
||||
status: i < step ? 'completed' : i === step ? 'active' : 'pending',
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
const handleNext = () => {
|
||||
if (currentStep >= steps.length - 1) return
|
||||
|
||||
// Find the next non-skipped step
|
||||
const skipSteps = docTypeResult?.skip_steps || []
|
||||
let nextStep = currentStep + 1
|
||||
while (nextStep < steps.length && skipSteps.includes(PIPELINE_STEPS[nextStep]?.id)) {
|
||||
nextStep++
|
||||
}
|
||||
if (nextStep >= steps.length) nextStep = steps.length - 1
|
||||
|
||||
setSteps((prev) =>
|
||||
prev.map((s, i) => {
|
||||
if (i === currentStep) return { ...s, status: 'completed' }
|
||||
if (i === nextStep) return { ...s, status: 'active' }
|
||||
// Mark skipped steps between current and next
|
||||
if (i > currentStep && i < nextStep && skipSteps.includes(PIPELINE_STEPS[i]?.id)) {
|
||||
return { ...s, status: 'skipped' }
|
||||
}
|
||||
return s
|
||||
}),
|
||||
)
|
||||
setCurrentStep(nextStep)
|
||||
}
|
||||
|
||||
const handleDeskewComplete = (sid: string) => {
|
||||
setSessionId(sid)
|
||||
// Reload session list to show the new session
|
||||
loadSessions()
|
||||
handleNext()
|
||||
}
|
||||
|
||||
const handleDewarpNext = async () => {
|
||||
// Auto-detect document type after dewarp, then advance
|
||||
if (sessionId) {
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/detect-type`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
if (res.ok) {
|
||||
const data: DocumentTypeResult = await res.json()
|
||||
setDocTypeResult(data)
|
||||
|
||||
// Mark skipped steps immediately
|
||||
const skipSteps = data.skip_steps || []
|
||||
if (skipSteps.length > 0) {
|
||||
setSteps((prev) =>
|
||||
prev.map((s) =>
|
||||
skipSteps.includes(s.id) ? { ...s, status: 'skipped' } : s,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Doc type detection failed:', e)
|
||||
// Not critical — continue without it
|
||||
}
|
||||
}
|
||||
handleNext()
|
||||
}
|
||||
|
||||
const handleDocTypeChange = (newDocType: DocumentTypeResult['doc_type']) => {
|
||||
if (!docTypeResult) return
|
||||
|
||||
// Build new skip_steps based on doc type
|
||||
let skipSteps: string[] = []
|
||||
if (newDocType === 'full_text') {
|
||||
skipSteps = ['columns', 'rows']
|
||||
}
|
||||
// vocab_table and generic_table: no skips
|
||||
|
||||
const updated: DocumentTypeResult = {
|
||||
...docTypeResult,
|
||||
doc_type: newDocType,
|
||||
skip_steps: skipSteps,
|
||||
pipeline: newDocType === 'full_text' ? 'full_page' : 'cell_first',
|
||||
}
|
||||
setDocTypeResult(updated)
|
||||
|
||||
// Update step statuses
|
||||
setSteps((prev) =>
|
||||
prev.map((s) => {
|
||||
if (skipSteps.includes(s.id)) return { ...s, status: 'skipped' as const }
|
||||
if (s.status === 'skipped') return { ...s, status: 'pending' as const }
|
||||
return s
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const handleNewSession = () => {
|
||||
setSessionId(null)
|
||||
setSessionName('')
|
||||
setCurrentStep(0)
|
||||
setDocTypeResult(null)
|
||||
setSteps(PIPELINE_STEPS.map((s, i) => ({ ...s, status: i === 0 ? 'active' : 'pending' })))
|
||||
}
|
||||
|
||||
const stepNames: Record<number, string> = {
|
||||
1: 'Begradigung',
|
||||
2: 'Entzerrung',
|
||||
3: 'Spalten',
|
||||
4: 'Zeilen',
|
||||
5: 'Woerter',
|
||||
6: 'Korrektur',
|
||||
7: 'Rekonstruktion',
|
||||
8: 'Validierung',
|
||||
}
|
||||
|
||||
const reprocessFromStep = useCallback(async (uiStep: number) => {
|
||||
if (!sessionId) return
|
||||
const dbStep = uiStep + 1 // UI is 0-indexed, DB is 1-indexed
|
||||
if (!confirm(`Ab Schritt ${dbStep} (${stepNames[dbStep] || '?'}) neu verarbeiten? Nachfolgende Daten werden geloescht.`)) return
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/reprocess`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ from_step: dbStep }),
|
||||
})
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}))
|
||||
console.error('Reprocess failed:', data.detail || res.status)
|
||||
return
|
||||
}
|
||||
// Reset UI steps
|
||||
goToStep(uiStep)
|
||||
} catch (e) {
|
||||
console.error('Reprocess error:', e)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [sessionId, goToStep])
|
||||
|
||||
const renderStep = () => {
|
||||
switch (currentStep) {
|
||||
case 0:
|
||||
return <StepDeskew sessionId={sessionId} onNext={handleDeskewComplete} />
|
||||
case 1:
|
||||
return <StepDewarp sessionId={sessionId} onNext={handleDewarpNext} />
|
||||
case 2:
|
||||
return <StepColumnDetection sessionId={sessionId} onNext={handleNext} />
|
||||
case 3:
|
||||
return <StepRowDetection sessionId={sessionId} onNext={handleNext} />
|
||||
case 4:
|
||||
return <StepWordRecognition sessionId={sessionId} onNext={handleNext} goToStep={goToStep} />
|
||||
case 5:
|
||||
return <StepLlmReview sessionId={sessionId} onNext={handleNext} />
|
||||
case 6:
|
||||
return <StepReconstruction sessionId={sessionId} onNext={handleNext} />
|
||||
case 7:
|
||||
return <StepGroundTruth />
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PagePurpose
|
||||
title="OCR Pipeline"
|
||||
purpose="Schrittweise Seitenrekonstruktion: Scan begradigen, Spalten erkennen, Woerter lokalisieren und die Seite Wort fuer Wort nachbauen. Ziel: 10 Vokabelseiten fehlerfrei rekonstruieren."
|
||||
audience={['Entwickler', 'Data Scientists']}
|
||||
architecture={{
|
||||
services: ['klausur-service (FastAPI)', 'OpenCV', 'Tesseract'],
|
||||
databases: ['PostgreSQL Sessions'],
|
||||
}}
|
||||
relatedPages={[
|
||||
{ name: 'OCR Vergleich', href: '/ai/ocr-compare', description: 'Methoden-Vergleich' },
|
||||
{ name: 'OCR-Labeling', href: '/ai/ocr-labeling', description: 'Trainingsdaten' },
|
||||
]}
|
||||
defaultCollapsed
|
||||
/>
|
||||
|
||||
{/* Session List */}
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
Sessions
|
||||
</h3>
|
||||
<button
|
||||
onClick={handleNewSession}
|
||||
className="text-xs px-3 py-1.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors"
|
||||
>
|
||||
+ Neue Session
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loadingSessions ? (
|
||||
<div className="text-sm text-gray-400 py-2">Lade Sessions...</div>
|
||||
) : sessions.length === 0 ? (
|
||||
<div className="text-sm text-gray-400 py-2">Noch keine Sessions vorhanden.</div>
|
||||
) : (
|
||||
<div className="space-y-1 max-h-48 overflow-y-auto">
|
||||
{sessions.map((s) => (
|
||||
<div
|
||||
key={s.id}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors cursor-pointer ${
|
||||
sessionId === s.id
|
||||
? 'bg-teal-50 dark:bg-teal-900/30 border border-teal-200 dark:border-teal-700'
|
||||
: 'hover:bg-gray-50 dark:hover:bg-gray-700/50'
|
||||
}`}
|
||||
>
|
||||
<div className="flex-1 min-w-0" onClick={() => openSession(s.id)}>
|
||||
{editingName === s.id ? (
|
||||
<input
|
||||
autoFocus
|
||||
value={editNameValue}
|
||||
onChange={(e) => setEditNameValue(e.target.value)}
|
||||
onBlur={() => renameSession(s.id, editNameValue)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') renameSession(s.id, editNameValue)
|
||||
if (e.key === 'Escape') setEditingName(null)
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="w-full px-1 py-0.5 text-sm border rounded dark:bg-gray-700 dark:border-gray-600"
|
||||
/>
|
||||
) : (
|
||||
<div className="truncate font-medium text-gray-700 dark:text-gray-300">
|
||||
{s.name || s.filename}
|
||||
</div>
|
||||
)}
|
||||
<div className="text-xs text-gray-400 flex gap-2">
|
||||
<span>{new Date(s.created_at).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit' })}</span>
|
||||
<span>Schritt {s.current_step}: {stepNames[s.current_step] || '?'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setEditNameValue(s.name || s.filename)
|
||||
setEditingName(s.id)
|
||||
}}
|
||||
className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
|
||||
title="Umbenennen"
|
||||
>
|
||||
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (confirm('Session loeschen?')) deleteSession(s.id)
|
||||
}}
|
||||
className="p-1 text-gray-400 hover:text-red-500"
|
||||
title="Loeschen"
|
||||
>
|
||||
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Active session name */}
|
||||
{sessionId && sessionName && (
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
Aktive Session: <span className="font-medium text-gray-700 dark:text-gray-300">{sessionName}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<PipelineStepper
|
||||
steps={steps}
|
||||
currentStep={currentStep}
|
||||
onStepClick={handleStepClick}
|
||||
onReprocess={sessionId ? reprocessFromStep : undefined}
|
||||
docTypeResult={docTypeResult}
|
||||
onDocTypeChange={handleDocTypeChange}
|
||||
/>
|
||||
|
||||
<div className="min-h-[400px]">{renderStep()}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
export type PipelineStepStatus = 'pending' | 'active' | 'completed' | 'failed' | 'skipped'
|
||||
|
||||
export interface PipelineStep {
|
||||
id: string
|
||||
name: string
|
||||
icon: string
|
||||
status: PipelineStepStatus
|
||||
}
|
||||
|
||||
export interface SessionListItem {
|
||||
id: string
|
||||
name: string
|
||||
filename: string
|
||||
status: string
|
||||
current_step: number
|
||||
created_at: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
export interface DocumentTypeResult {
|
||||
doc_type: 'vocab_table' | 'full_text' | 'generic_table'
|
||||
confidence: number
|
||||
pipeline: 'cell_first' | 'full_page'
|
||||
skip_steps: string[]
|
||||
features?: Record<string, unknown>
|
||||
duration_seconds?: number
|
||||
}
|
||||
|
||||
export interface SessionInfo {
|
||||
session_id: string
|
||||
filename: string
|
||||
name?: string
|
||||
image_width: number
|
||||
image_height: number
|
||||
original_image_url: string
|
||||
current_step?: number
|
||||
deskew_result?: DeskewResult
|
||||
dewarp_result?: DewarpResult
|
||||
column_result?: ColumnResult
|
||||
row_result?: RowResult
|
||||
word_result?: GridResult
|
||||
doc_type_result?: DocumentTypeResult
|
||||
}
|
||||
|
||||
export interface DeskewResult {
|
||||
session_id: string
|
||||
angle_hough: number
|
||||
angle_word_alignment: number
|
||||
angle_applied: number
|
||||
method_used: 'hough' | 'word_alignment' | 'manual'
|
||||
confidence: number
|
||||
duration_seconds: number
|
||||
deskewed_image_url: string
|
||||
binarized_image_url: string
|
||||
}
|
||||
|
||||
export interface DeskewGroundTruth {
|
||||
is_correct: boolean
|
||||
corrected_angle?: number
|
||||
notes?: string
|
||||
}
|
||||
|
||||
export interface DewarpDetection {
|
||||
method: string
|
||||
shear_degrees: number
|
||||
confidence: number
|
||||
}
|
||||
|
||||
export interface DewarpResult {
|
||||
session_id: string
|
||||
method_used: string
|
||||
shear_degrees: number
|
||||
confidence: number
|
||||
duration_seconds: number
|
||||
dewarped_image_url: string
|
||||
detections?: DewarpDetection[]
|
||||
}
|
||||
|
||||
export interface DewarpGroundTruth {
|
||||
is_correct: boolean
|
||||
corrected_shear?: number
|
||||
notes?: string
|
||||
}
|
||||
|
||||
export interface PageRegion {
|
||||
type: 'column_en' | 'column_de' | 'column_example' | 'page_ref'
|
||||
| 'column_marker' | 'column_text' | 'column_ignore' | 'header' | 'footer'
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
classification_confidence?: number
|
||||
classification_method?: string
|
||||
}
|
||||
|
||||
export interface ColumnResult {
|
||||
columns: PageRegion[]
|
||||
duration_seconds: number
|
||||
}
|
||||
|
||||
export interface ColumnGroundTruth {
|
||||
is_correct: boolean
|
||||
corrected_columns?: PageRegion[]
|
||||
notes?: string
|
||||
}
|
||||
|
||||
export interface ManualColumnDivider {
|
||||
xPercent: number // Position in % of image width (0-100)
|
||||
}
|
||||
|
||||
export type ColumnTypeKey = PageRegion['type']
|
||||
|
||||
export interface RowResult {
|
||||
rows: RowItem[]
|
||||
summary: Record<string, number>
|
||||
total_rows: number
|
||||
duration_seconds: number
|
||||
}
|
||||
|
||||
export interface RowItem {
|
||||
index: number
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
word_count: number
|
||||
row_type: 'content' | 'header' | 'footer'
|
||||
gap_before: number
|
||||
}
|
||||
|
||||
export interface RowGroundTruth {
|
||||
is_correct: boolean
|
||||
corrected_rows?: RowItem[]
|
||||
notes?: string
|
||||
}
|
||||
|
||||
export interface WordBbox {
|
||||
x: number
|
||||
y: number
|
||||
w: number
|
||||
h: number
|
||||
}
|
||||
|
||||
export interface GridCell {
|
||||
cell_id: string // "R03_C1"
|
||||
row_index: number
|
||||
col_index: number
|
||||
col_type: string
|
||||
text: string
|
||||
confidence: number
|
||||
bbox_px: WordBbox
|
||||
bbox_pct: WordBbox
|
||||
ocr_engine?: string
|
||||
status?: 'pending' | 'confirmed' | 'edited' | 'skipped'
|
||||
}
|
||||
|
||||
export interface ColumnMeta {
|
||||
index: number
|
||||
type: string
|
||||
x: number
|
||||
width: number
|
||||
}
|
||||
|
||||
export interface GridResult {
|
||||
cells: GridCell[]
|
||||
grid_shape: { rows: number; cols: number; total_cells: number }
|
||||
columns_used: ColumnMeta[]
|
||||
layout: 'vocab' | 'generic'
|
||||
image_width: number
|
||||
image_height: number
|
||||
duration_seconds: number
|
||||
ocr_engine?: string
|
||||
vocab_entries?: WordEntry[] // Only when layout='vocab'
|
||||
entries?: WordEntry[] // Backwards compat alias for vocab_entries
|
||||
entry_count?: number
|
||||
summary: {
|
||||
total_cells: number
|
||||
non_empty_cells: number
|
||||
low_confidence: number
|
||||
// Only when layout='vocab':
|
||||
total_entries?: number
|
||||
with_english?: number
|
||||
with_german?: number
|
||||
}
|
||||
llm_review?: {
|
||||
changes: { row_index: number; field: string; old: string; new: string }[]
|
||||
model_used: string
|
||||
duration_ms: number
|
||||
entries_corrected: number
|
||||
applied_count?: number
|
||||
applied_at?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface WordEntry {
|
||||
row_index: number
|
||||
english: string
|
||||
german: string
|
||||
example: string
|
||||
source_page?: string
|
||||
marker?: string
|
||||
confidence: number
|
||||
bbox: WordBbox
|
||||
bbox_en: WordBbox | null
|
||||
bbox_de: WordBbox | null
|
||||
bbox_ex: WordBbox | null
|
||||
bbox_ref?: WordBbox | null
|
||||
bbox_marker?: WordBbox | null
|
||||
status?: 'pending' | 'confirmed' | 'edited' | 'skipped'
|
||||
}
|
||||
|
||||
/** @deprecated Use GridResult instead */
|
||||
export interface WordResult {
|
||||
entries: WordEntry[]
|
||||
entry_count: number
|
||||
image_width: number
|
||||
image_height: number
|
||||
duration_seconds: number
|
||||
ocr_engine?: string
|
||||
summary: {
|
||||
total_entries: number
|
||||
with_english: number
|
||||
with_german: number
|
||||
low_confidence: number
|
||||
}
|
||||
}
|
||||
|
||||
export interface WordGroundTruth {
|
||||
is_correct: boolean
|
||||
corrected_entries?: WordEntry[]
|
||||
notes?: string
|
||||
}
|
||||
|
||||
export const PIPELINE_STEPS: PipelineStep[] = [
|
||||
{ id: 'deskew', name: 'Begradigung', icon: '📐', status: 'pending' },
|
||||
{ id: 'dewarp', name: 'Entzerrung', icon: '🔧', status: 'pending' },
|
||||
{ id: 'columns', name: 'Spalten', icon: '📊', status: 'pending' },
|
||||
{ id: 'rows', name: 'Zeilen', icon: '📏', status: 'pending' },
|
||||
{ id: 'words', name: 'Woerter', icon: '🔤', status: 'pending' },
|
||||
{ id: 'llm-review', name: 'Korrektur', icon: '✏️', status: 'pending' },
|
||||
{ id: 'reconstruction', name: 'Rekonstruktion', icon: '🏗️', status: 'pending' },
|
||||
{ id: 'ground-truth', name: 'Validierung', icon: '✅', status: 'pending' },
|
||||
]
|
||||
403
admin-lehrer/app/(admin)/ai/ocr-regression/page.tsx
Normal file
403
admin-lehrer/app/(admin)/ai/ocr-regression/page.tsx
Normal file
@@ -0,0 +1,403 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* OCR Regression Dashboard
|
||||
*
|
||||
* Shows all ground-truth sessions, runs regression tests,
|
||||
* displays pass/fail results with diff details, and shows history.
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { PagePurpose } from '@/components/common/PagePurpose'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface GTSession {
|
||||
session_id: string
|
||||
name: string
|
||||
filename: string
|
||||
document_category: string | null
|
||||
pipeline: string | null
|
||||
saved_at: string | null
|
||||
summary: {
|
||||
total_zones: number
|
||||
total_columns: number
|
||||
total_rows: number
|
||||
total_cells: number
|
||||
}
|
||||
}
|
||||
|
||||
interface DiffSummary {
|
||||
structural_changes: number
|
||||
cells_missing: number
|
||||
cells_added: number
|
||||
text_changes: number
|
||||
col_type_changes: number
|
||||
}
|
||||
|
||||
interface RegressionResult {
|
||||
session_id: string
|
||||
name: string
|
||||
status: 'pass' | 'fail' | 'error'
|
||||
error?: string
|
||||
diff_summary?: DiffSummary
|
||||
reference_summary?: Record<string, number>
|
||||
current_summary?: Record<string, number>
|
||||
structural_diffs?: Array<{ field: string; reference: number; current: number }>
|
||||
cell_diffs?: Array<{ type: string; cell_id: string; reference?: string; current?: string }>
|
||||
}
|
||||
|
||||
interface RegressionRun {
|
||||
id: string
|
||||
run_at: string
|
||||
status: string
|
||||
total: number
|
||||
passed: number
|
||||
failed: number
|
||||
errors: number
|
||||
duration_ms: number
|
||||
triggered_by: string
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function StatusBadge({ status }: { status: string }) {
|
||||
const cls =
|
||||
status === 'pass'
|
||||
? 'bg-emerald-100 text-emerald-800 border-emerald-200'
|
||||
: status === 'fail'
|
||||
? 'bg-red-100 text-red-800 border-red-200'
|
||||
: 'bg-amber-100 text-amber-800 border-amber-200'
|
||||
return (
|
||||
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium border ${cls}`}>
|
||||
{status === 'pass' ? 'Pass' : status === 'fail' ? 'Fail' : 'Error'}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function formatDate(iso: string | null) {
|
||||
if (!iso) return '—'
|
||||
return new Date(iso).toLocaleString('de-DE', {
|
||||
day: '2-digit', month: '2-digit', year: 'numeric',
|
||||
hour: '2-digit', minute: '2-digit',
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Component
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export default function OCRRegressionPage() {
|
||||
const [sessions, setSessions] = useState<GTSession[]>([])
|
||||
const [results, setResults] = useState<RegressionResult[]>([])
|
||||
const [history, setHistory] = useState<RegressionRun[]>([])
|
||||
const [running, setRunning] = useState(false)
|
||||
const [overallStatus, setOverallStatus] = useState<string | null>(null)
|
||||
const [durationMs, setDurationMs] = useState<number | null>(null)
|
||||
const [expandedSession, setExpandedSession] = useState<string | null>(null)
|
||||
const [tab, setTab] = useState<'current' | 'history'>('current')
|
||||
|
||||
// Load ground-truth sessions
|
||||
const loadSessions = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/ground-truth-sessions`)
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setSessions(data.sessions || [])
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load GT sessions:', e)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Load history
|
||||
const loadHistory = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/regression/history?limit=20`)
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setHistory(data.runs || [])
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load history:', e)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
loadSessions()
|
||||
loadHistory()
|
||||
}, [loadSessions, loadHistory])
|
||||
|
||||
// Run all regressions
|
||||
const runAll = async () => {
|
||||
setRunning(true)
|
||||
setResults([])
|
||||
setOverallStatus(null)
|
||||
setDurationMs(null)
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/regression/run?triggered_by=manual`, {
|
||||
method: 'POST',
|
||||
})
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setResults(data.results || [])
|
||||
setOverallStatus(data.status)
|
||||
setDurationMs(data.duration_ms)
|
||||
loadHistory()
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Regression run failed:', e)
|
||||
setOverallStatus('error')
|
||||
} finally {
|
||||
setRunning(false)
|
||||
}
|
||||
}
|
||||
|
||||
const totalPass = results.filter(r => r.status === 'pass').length
|
||||
const totalFail = results.filter(r => r.status === 'fail').length
|
||||
const totalError = results.filter(r => r.status === 'error').length
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="max-w-7xl mx-auto p-6 space-y-6">
|
||||
<PagePurpose
|
||||
title="OCR Regression Tests"
|
||||
purpose="Automatische Regressions-Tests fuer die OCR-Pipeline: Ground-Truth Sessions neu auswerten und gegen Referenz-Ergebnisse vergleichen."
|
||||
audience={['Entwickler', 'QA']}
|
||||
defaultCollapsed
|
||||
architecture={{
|
||||
services: ['klausur-service (FastAPI, Port 8086)'],
|
||||
databases: ['PostgreSQL (regression_runs, ocr_pipeline_sessions)'],
|
||||
}}
|
||||
relatedPages={[
|
||||
{ name: 'OCR Pipeline', href: '/ai/ocr-pipeline', description: 'OCR-Pipeline ausfuehren' },
|
||||
{ name: 'Ground Truth Review', href: '/ai/ocr-ground-truth', description: 'Sessions pruefen & markieren' },
|
||||
]}
|
||||
/>
|
||||
|
||||
{/* Header + Run Button */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-900">OCR Regression Tests</h1>
|
||||
<p className="text-sm text-slate-500 mt-1">
|
||||
{sessions.length} Ground-Truth Session{sessions.length !== 1 ? 's' : ''}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={runAll}
|
||||
disabled={running || sessions.length === 0}
|
||||
className="inline-flex items-center gap-2 px-4 py-2.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50 disabled:cursor-not-allowed font-medium transition-colors"
|
||||
>
|
||||
{running ? (
|
||||
<>
|
||||
<svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
|
||||
</svg>
|
||||
Laeuft...
|
||||
</>
|
||||
) : (
|
||||
'Alle Tests starten'
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Overall Result Banner */}
|
||||
{overallStatus && (
|
||||
<div className={`rounded-lg p-4 border ${
|
||||
overallStatus === 'pass'
|
||||
? 'bg-emerald-50 border-emerald-200'
|
||||
: 'bg-red-50 border-red-200'
|
||||
}`}>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<StatusBadge status={overallStatus} />
|
||||
<span className="font-medium text-slate-900">
|
||||
{totalPass} bestanden, {totalFail} fehlgeschlagen, {totalError} Fehler
|
||||
</span>
|
||||
</div>
|
||||
{durationMs !== null && (
|
||||
<span className="text-sm text-slate-500">{(durationMs / 1000).toFixed(1)}s</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="border-b border-slate-200">
|
||||
<nav className="flex gap-4">
|
||||
{(['current', 'history'] as const).map(t => (
|
||||
<button
|
||||
key={t}
|
||||
onClick={() => setTab(t)}
|
||||
className={`pb-3 px-1 text-sm font-medium border-b-2 transition-colors ${
|
||||
tab === t
|
||||
? 'border-teal-500 text-teal-600'
|
||||
: 'border-transparent text-slate-500 hover:text-slate-700'
|
||||
}`}
|
||||
>
|
||||
{t === 'current' ? 'Aktuelle Ergebnisse' : 'Verlauf'}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* Current Results Tab */}
|
||||
{tab === 'current' && (
|
||||
<div className="space-y-3">
|
||||
{results.length === 0 && !running && (
|
||||
<div className="text-center py-12 text-slate-400">
|
||||
<p className="text-lg">Keine Ergebnisse</p>
|
||||
<p className="text-sm mt-1">Klicken Sie "Alle Tests starten" um die Regression zu laufen.</p>
|
||||
</div>
|
||||
)}
|
||||
{results.map(r => (
|
||||
<div
|
||||
key={r.session_id}
|
||||
className="bg-white rounded-lg border border-slate-200 overflow-hidden"
|
||||
>
|
||||
<div
|
||||
className="flex items-center justify-between px-4 py-3 cursor-pointer hover:bg-slate-50 transition-colors"
|
||||
onClick={() => setExpandedSession(expandedSession === r.session_id ? null : r.session_id)}
|
||||
>
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<StatusBadge status={r.status} />
|
||||
<span className="font-medium text-slate-900 truncate">{r.name || r.session_id}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-sm text-slate-500">
|
||||
{r.diff_summary && (
|
||||
<span>
|
||||
{r.diff_summary.text_changes} Text, {r.diff_summary.structural_changes} Struktur
|
||||
</span>
|
||||
)}
|
||||
{r.error && <span className="text-red-500">{r.error}</span>}
|
||||
<svg className={`w-4 h-4 transition-transform ${expandedSession === r.session_id ? 'rotate-180' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Expanded Details */}
|
||||
{expandedSession === r.session_id && r.status === 'fail' && (
|
||||
<div className="border-t border-slate-100 px-4 py-3 bg-slate-50 space-y-3">
|
||||
{/* Structural Diffs */}
|
||||
{r.structural_diffs && r.structural_diffs.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-xs font-medium text-slate-500 uppercase mb-1">Strukturelle Aenderungen</h4>
|
||||
<div className="space-y-1">
|
||||
{r.structural_diffs.map((d, i) => (
|
||||
<div key={i} className="text-sm">
|
||||
<span className="font-mono text-slate-600">{d.field}</span>: {d.reference} → {d.current}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* Cell Diffs */}
|
||||
{r.cell_diffs && r.cell_diffs.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-xs font-medium text-slate-500 uppercase mb-1">
|
||||
Zellen-Aenderungen ({r.cell_diffs.length})
|
||||
</h4>
|
||||
<div className="max-h-60 overflow-y-auto space-y-1">
|
||||
{r.cell_diffs.slice(0, 50).map((d, i) => (
|
||||
<div key={i} className="text-sm font-mono bg-white rounded px-2 py-1 border border-slate-100">
|
||||
<span className={`text-xs px-1 rounded ${
|
||||
d.type === 'text_change' ? 'bg-amber-100 text-amber-700'
|
||||
: d.type === 'cell_missing' ? 'bg-red-100 text-red-700'
|
||||
: 'bg-blue-100 text-blue-700'
|
||||
}`}>
|
||||
{d.type}
|
||||
</span>{' '}
|
||||
<span className="text-slate-500">{d.cell_id}</span>
|
||||
{d.reference && (
|
||||
<>
|
||||
{' '}<span className="line-through text-red-400">{d.reference}</span>
|
||||
</>
|
||||
)}
|
||||
{d.current && (
|
||||
<>
|
||||
{' '}<span className="text-emerald-600">{d.current}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{r.cell_diffs.length > 50 && (
|
||||
<p className="text-xs text-slate-400">... und {r.cell_diffs.length - 50} weitere</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Ground Truth Sessions Overview (when no results yet) */}
|
||||
{results.length === 0 && sessions.length > 0 && (
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-slate-700 mb-2">Ground-Truth Sessions</h3>
|
||||
<div className="grid gap-2">
|
||||
{sessions.map(s => (
|
||||
<div key={s.session_id} className="bg-white rounded-lg border border-slate-200 px-4 py-3 flex items-center justify-between">
|
||||
<div>
|
||||
<span className="font-medium text-slate-900">{s.name || s.session_id}</span>
|
||||
<span className="text-sm text-slate-400 ml-2">{s.filename}</span>
|
||||
</div>
|
||||
<div className="text-sm text-slate-500">
|
||||
{s.summary.total_cells} Zellen, {s.summary.total_zones} Zonen
|
||||
{s.pipeline && <span className="ml-2 text-xs bg-slate-100 px-1.5 py-0.5 rounded">{s.pipeline}</span>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* History Tab */}
|
||||
{tab === 'history' && (
|
||||
<div className="space-y-2">
|
||||
{history.length === 0 ? (
|
||||
<p className="text-center py-8 text-slate-400">Noch keine Laeufe aufgezeichnet.</p>
|
||||
) : (
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-200 text-left text-slate-500">
|
||||
<th className="pb-2 font-medium">Datum</th>
|
||||
<th className="pb-2 font-medium">Status</th>
|
||||
<th className="pb-2 font-medium text-right">Gesamt</th>
|
||||
<th className="pb-2 font-medium text-right">Pass</th>
|
||||
<th className="pb-2 font-medium text-right">Fail</th>
|
||||
<th className="pb-2 font-medium text-right">Dauer</th>
|
||||
<th className="pb-2 font-medium">Trigger</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{history.map(run => (
|
||||
<tr key={run.id} className="border-b border-slate-100 hover:bg-slate-50">
|
||||
<td className="py-2">{formatDate(run.run_at)}</td>
|
||||
<td className="py-2"><StatusBadge status={run.status} /></td>
|
||||
<td className="py-2 text-right">{run.total}</td>
|
||||
<td className="py-2 text-right text-emerald-600">{run.passed}</td>
|
||||
<td className="py-2 text-right text-red-600">{run.failed + run.errors}</td>
|
||||
<td className="py-2 text-right text-slate-500">{(run.duration_ms / 1000).toFixed(1)}s</td>
|
||||
<td className="py-2 text-slate-400">{run.triggered_by}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
252
admin-lehrer/app/(admin)/ai/rag/__tests__/rag-documents.test.ts
Normal file
252
admin-lehrer/app/(admin)/ai/rag/__tests__/rag-documents.test.ts
Normal file
@@ -0,0 +1,252 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import ragData from '../rag-documents.json'
|
||||
|
||||
/**
|
||||
* Tests fuer rag-documents.json — Branchen-Regulierungs-Matrix
|
||||
*
|
||||
* Validiert die JSON-Struktur, Branchen-Zuordnung und Datenintegritaet
|
||||
* der 320 Dokumente fuer die RAG Landkarte.
|
||||
*/
|
||||
|
||||
const VALID_INDUSTRY_IDS = ragData.industries.map((i: any) => i.id)
|
||||
const VALID_DOC_TYPE_IDS = ragData.doc_types.map((dt: any) => dt.id)
|
||||
|
||||
describe('rag-documents.json — Struktur', () => {
|
||||
it('sollte doc_types, industries und documents enthalten', () => {
|
||||
expect(ragData).toHaveProperty('doc_types')
|
||||
expect(ragData).toHaveProperty('industries')
|
||||
expect(ragData).toHaveProperty('documents')
|
||||
expect(Array.isArray(ragData.doc_types)).toBe(true)
|
||||
expect(Array.isArray(ragData.industries)).toBe(true)
|
||||
expect(Array.isArray(ragData.documents)).toBe(true)
|
||||
})
|
||||
|
||||
it('sollte genau 10 Branchen haben (VDMA/VDA/BDI)', () => {
|
||||
expect(ragData.industries).toHaveLength(10)
|
||||
const ids = ragData.industries.map((i: any) => i.id)
|
||||
expect(ids).toContain('automotive')
|
||||
expect(ids).toContain('maschinenbau')
|
||||
expect(ids).toContain('elektrotechnik')
|
||||
expect(ids).toContain('chemie')
|
||||
expect(ids).toContain('metall')
|
||||
expect(ids).toContain('energie')
|
||||
expect(ids).toContain('transport')
|
||||
expect(ids).toContain('handel')
|
||||
expect(ids).toContain('konsumgueter')
|
||||
expect(ids).toContain('bau')
|
||||
})
|
||||
|
||||
it('sollte keine Pseudo-Branchen enthalten (IoT, KI, HR, KRITIS, etc.)', () => {
|
||||
const ids = ragData.industries.map((i: any) => i.id)
|
||||
expect(ids).not.toContain('iot')
|
||||
expect(ids).not.toContain('ai')
|
||||
expect(ids).not.toContain('hr')
|
||||
expect(ids).not.toContain('kritis')
|
||||
expect(ids).not.toContain('ecommerce')
|
||||
expect(ids).not.toContain('tech')
|
||||
expect(ids).not.toContain('media')
|
||||
expect(ids).not.toContain('public')
|
||||
})
|
||||
|
||||
it('sollte 17 Dokumenttypen haben', () => {
|
||||
expect(ragData.doc_types.length).toBe(17)
|
||||
})
|
||||
|
||||
it('sollte mindestens 300 Dokumente haben', () => {
|
||||
expect(ragData.documents.length).toBeGreaterThanOrEqual(300)
|
||||
})
|
||||
|
||||
it('sollte jede Branche name und icon haben', () => {
|
||||
ragData.industries.forEach((ind: any) => {
|
||||
expect(ind).toHaveProperty('id')
|
||||
expect(ind).toHaveProperty('name')
|
||||
expect(ind).toHaveProperty('icon')
|
||||
expect(ind.name.length).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
it('sollte jeden doc_type mit id, label, icon und sort haben', () => {
|
||||
ragData.doc_types.forEach((dt: any) => {
|
||||
expect(dt).toHaveProperty('id')
|
||||
expect(dt).toHaveProperty('label')
|
||||
expect(dt).toHaveProperty('icon')
|
||||
expect(dt).toHaveProperty('sort')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('rag-documents.json — Dokument-Validierung', () => {
|
||||
it('sollte keine doppelten Codes haben', () => {
|
||||
const codes = ragData.documents.map((d: any) => d.code)
|
||||
const unique = new Set(codes)
|
||||
expect(unique.size).toBe(codes.length)
|
||||
})
|
||||
|
||||
it('sollte Pflichtfelder bei jedem Dokument haben', () => {
|
||||
ragData.documents.forEach((doc: any) => {
|
||||
expect(doc).toHaveProperty('code')
|
||||
expect(doc).toHaveProperty('name')
|
||||
expect(doc).toHaveProperty('doc_type')
|
||||
expect(doc).toHaveProperty('industries')
|
||||
expect(doc).toHaveProperty('in_rag')
|
||||
expect(doc).toHaveProperty('rag_collection')
|
||||
expect(doc.code.length).toBeGreaterThan(0)
|
||||
expect(doc.name.length).toBeGreaterThan(0)
|
||||
expect(Array.isArray(doc.industries)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
it('sollte nur gueltige doc_type IDs verwenden', () => {
|
||||
ragData.documents.forEach((doc: any) => {
|
||||
expect(VALID_DOC_TYPE_IDS).toContain(doc.doc_type)
|
||||
})
|
||||
})
|
||||
|
||||
it('sollte nur gueltige industry IDs verwenden (oder "all")', () => {
|
||||
ragData.documents.forEach((doc: any) => {
|
||||
doc.industries.forEach((ind: string) => {
|
||||
if (ind !== 'all') {
|
||||
expect(VALID_INDUSTRY_IDS).toContain(ind)
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('sollte gueltige rag_collection Namen verwenden', () => {
|
||||
const validCollections = [
|
||||
'bp_compliance_ce',
|
||||
'bp_compliance_gesetze',
|
||||
'bp_compliance_datenschutz',
|
||||
'bp_dsfa_corpus',
|
||||
'bp_legal_templates',
|
||||
'bp_compliance_recht',
|
||||
'bp_nibis_eh',
|
||||
]
|
||||
ragData.documents.forEach((doc: any) => {
|
||||
expect(validCollections).toContain(doc.rag_collection)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('rag-documents.json — Branchen-Zuordnungslogik', () => {
|
||||
const findDoc = (code: string) => ragData.documents.find((d: any) => d.code === code)
|
||||
|
||||
describe('Horizontale Regulierungen (alle Branchen)', () => {
|
||||
const horizontalCodes = [
|
||||
'GDPR', 'BDSG_FULL', 'EPRIVACY', 'TDDDG', 'AIACT', 'CRA',
|
||||
'NIS2', 'GPSR', 'PLD', 'EUCSA', 'DATAACT',
|
||||
]
|
||||
|
||||
horizontalCodes.forEach((code) => {
|
||||
it(`${code} sollte fuer alle Branchen gelten`, () => {
|
||||
const doc = findDoc(code)
|
||||
if (doc) {
|
||||
expect(doc.industries).toContain('all')
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('Sektorspezifische Regulierungen', () => {
|
||||
it('Maschinenverordnung sollte Maschinenbau, Automotive, Elektrotechnik enthalten', () => {
|
||||
const doc = findDoc('MACHINERY_REG')
|
||||
if (doc) {
|
||||
expect(doc.industries).toContain('maschinenbau')
|
||||
expect(doc.industries).toContain('automotive')
|
||||
expect(doc.industries).toContain('elektrotechnik')
|
||||
expect(doc.industries).not.toContain('all')
|
||||
}
|
||||
})
|
||||
|
||||
it('ElektroG sollte Elektrotechnik und Automotive enthalten', () => {
|
||||
const doc = findDoc('DE_ELEKTROG')
|
||||
if (doc) {
|
||||
expect(doc.industries).toContain('elektrotechnik')
|
||||
expect(doc.industries).toContain('automotive')
|
||||
}
|
||||
})
|
||||
|
||||
it('BattDG sollte Automotive und Elektrotechnik enthalten', () => {
|
||||
const doc = findDoc('DE_BATTDG')
|
||||
if (doc) {
|
||||
expect(doc.industries).toContain('automotive')
|
||||
expect(doc.industries).toContain('elektrotechnik')
|
||||
}
|
||||
})
|
||||
|
||||
it('ENISA ICS/SCADA sollte Energie, Maschinenbau, Chemie enthalten', () => {
|
||||
const doc = findDoc('ENISA_ICS_SCADA')
|
||||
if (doc) {
|
||||
expect(doc.industries).toContain('energie')
|
||||
expect(doc.industries).toContain('maschinenbau')
|
||||
expect(doc.industries).toContain('chemie')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('Nicht zutreffende Regulierungen (Finanz/Medizin/Plattformen)', () => {
|
||||
const emptyIndustryCodes = ['DORA', 'PSD2', 'MiCA', 'AMLR', 'EHDS', 'DSA', 'DMA', 'MDR']
|
||||
|
||||
emptyIndustryCodes.forEach((code) => {
|
||||
it(`${code} sollte keine Branchen-Zuordnung haben`, () => {
|
||||
const doc = findDoc(code)
|
||||
if (doc) {
|
||||
expect(doc.industries).toHaveLength(0)
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('BSI-TR-03161 (DiGA) sollte nicht zutreffend sein', () => {
|
||||
['BSI-TR-03161-1', 'BSI-TR-03161-2', 'BSI-TR-03161-3'].forEach((code) => {
|
||||
it(`${code} sollte keine Branchen-Zuordnung haben`, () => {
|
||||
const doc = findDoc(code)
|
||||
if (doc) {
|
||||
expect(doc.industries).toHaveLength(0)
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('rag-documents.json — Applicability Notes', () => {
|
||||
it('sollte applicability_note bei Dokumenten mit description haben', () => {
|
||||
const withDescription = ragData.documents.filter((d: any) => d.description)
|
||||
const withNote = withDescription.filter((d: any) => d.applicability_note)
|
||||
// Mindestens 90% der Dokumente mit Beschreibung sollten eine Note haben
|
||||
expect(withNote.length / withDescription.length).toBeGreaterThan(0.9)
|
||||
})
|
||||
|
||||
it('horizontale Regulierungen sollten "alle Branchen" in der Note erwaehnen', () => {
|
||||
const gdpr = ragData.documents.find((d: any) => d.code === 'GDPR')
|
||||
if (gdpr?.applicability_note) {
|
||||
expect(gdpr.applicability_note.toLowerCase()).toContain('alle branchen')
|
||||
}
|
||||
})
|
||||
|
||||
it('nicht zutreffende sollten "nicht zutreffend" in der Note erwaehnen', () => {
|
||||
const dora = ragData.documents.find((d: any) => d.code === 'DORA')
|
||||
if (dora?.applicability_note) {
|
||||
expect(dora.applicability_note.toLowerCase()).toContain('nicht zutreffend')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('rag-documents.json — Dokumenttyp-Verteilung', () => {
|
||||
it('sollte Dokumente in jedem doc_type haben', () => {
|
||||
ragData.doc_types.forEach((dt: any) => {
|
||||
const count = ragData.documents.filter((d: any) => d.doc_type === dt.id).length
|
||||
expect(count).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
it('sollte EU-Verordnungen als groesste Kategorie haben (mind. 15)', () => {
|
||||
const euRegs = ragData.documents.filter((d: any) => d.doc_type === 'eu_regulation')
|
||||
expect(euRegs.length).toBeGreaterThanOrEqual(15)
|
||||
})
|
||||
|
||||
it('sollte EDPB Leitlinien als umfangreichste Kategorie haben (mind. 40)', () => {
|
||||
const edpb = ragData.documents.filter((d: any) => d.doc_type === 'edpb_guideline')
|
||||
expect(edpb.length).toBeGreaterThanOrEqual(40)
|
||||
})
|
||||
})
|
||||
@@ -32,6 +32,10 @@ const COLLECTIONS = [
|
||||
'bp_compliance_gesetze',
|
||||
'bp_compliance_ce',
|
||||
'bp_compliance_datenschutz',
|
||||
'bp_dsfa_corpus',
|
||||
'bp_compliance_recht',
|
||||
'bp_legal_templates',
|
||||
'bp_nibis_eh',
|
||||
]
|
||||
|
||||
export function ChunkBrowserQA({ apiProxy }: ChunkBrowserQAProps) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -26,6 +26,13 @@ export const REGULATIONS_IN_RAG: Record<string, RagRegulationEntry> = {
|
||||
E_COMMERCE_RL: { collection: 'bp_compliance_ce', chunks: 197, qdrant_id: 'eu_2000_31' },
|
||||
VERBRAUCHERRECHTE_RL: { collection: 'bp_compliance_ce', chunks: 266, qdrant_id: 'eu_2011_83' },
|
||||
DIGITALE_INHALTE_RL: { collection: 'bp_compliance_ce', chunks: 321, qdrant_id: 'eu_2019_770' },
|
||||
// Verbraucherschutz EU-Richtlinien (Phase H2 Ingestion)
|
||||
WARENKAUF_RL: { collection: 'bp_compliance_ce', chunks: 0, qdrant_id: 'sgd' },
|
||||
KLAUSEL_RL: { collection: 'bp_compliance_ce', chunks: 0, qdrant_id: 'uctd' },
|
||||
UNLAUTERE_PRAKTIKEN_RL: { collection: 'bp_compliance_ce', chunks: 0, qdrant_id: 'ucpd' },
|
||||
PREISANGABEN_RL: { collection: 'bp_compliance_ce', chunks: 0, qdrant_id: 'pid' },
|
||||
OMNIBUS_RL: { collection: 'bp_compliance_ce', chunks: 0, qdrant_id: 'omn' },
|
||||
BATTERIE_VO: { collection: 'bp_compliance_ce', chunks: 0, qdrant_id: 'battvo' },
|
||||
DMA: { collection: 'bp_compliance_ce', chunks: 701, qdrant_id: 'eu_2022_1925' },
|
||||
DPF: { collection: 'bp_compliance_ce', chunks: 2464, qdrant_id: 'dpf' },
|
||||
EUCSA: { collection: 'bp_compliance_ce', chunks: 558, qdrant_id: 'eucsa' },
|
||||
@@ -68,6 +75,24 @@ export const REGULATIONS_IN_RAG: Record<string, RagRegulationEntry> = {
|
||||
DE_USTG_RET: { collection: 'bp_compliance_gesetze', chunks: 1071, qdrant_id: 'de_ustg_ret' },
|
||||
DE_URHG: { collection: 'bp_compliance_gesetze', chunks: 626, qdrant_id: 'urhg_komplett' },
|
||||
|
||||
// === DE Verbraucherschutz-Gesetze (bp_compliance_gesetze) — Phase H1 (Run #701) ===
|
||||
DE_PANGV: { collection: 'bp_compliance_gesetze', chunks: 99, qdrant_id: 'pangv' },
|
||||
DE_VSBG: { collection: 'bp_compliance_gesetze', chunks: 113, qdrant_id: 'vsbg' },
|
||||
DE_PRODHAFTG: { collection: 'bp_compliance_gesetze', chunks: 26, qdrant_id: 'prodhaftg' },
|
||||
DE_VERPACKG: { collection: 'bp_compliance_gesetze', chunks: 338, qdrant_id: 'verpackg' },
|
||||
DE_ELEKTROG: { collection: 'bp_compliance_gesetze', chunks: 344, qdrant_id: 'elektrog' },
|
||||
DE_BATTDG: { collection: 'bp_compliance_gesetze', chunks: 307, qdrant_id: 'battdg' },
|
||||
DE_BFSG: { collection: 'bp_compliance_gesetze', chunks: 221, qdrant_id: 'bfsg' },
|
||||
DE_UWG: { collection: 'bp_compliance_gesetze', chunks: 157, qdrant_id: 'uwg' },
|
||||
DE_GEWO: { collection: 'bp_compliance_gesetze', chunks: 0, qdrant_id: 'gewo' }, // Pending: Re-run noetig (Timeout)
|
||||
// BGB in Teilen (statt 2.7MB komplett)
|
||||
DE_BGB_AGB_305: { collection: 'bp_compliance_gesetze', chunks: 0, qdrant_id: 'bgb_agb' }, // §§ 305-310
|
||||
DE_BGB_FERNABSATZ: { collection: 'bp_compliance_gesetze', chunks: 0, qdrant_id: 'bgb_fernabsatz' }, // §§ 312-312k
|
||||
DE_BGB_KAUFRECHT: { collection: 'bp_compliance_gesetze', chunks: 0, qdrant_id: 'bgb_kaufrecht' }, // §§ 433-480
|
||||
DE_BGB_WIDERRUF: { collection: 'bp_compliance_gesetze', chunks: 0, qdrant_id: 'bgb_widerruf' }, // §§ 355-361
|
||||
DE_BGB_DIGITAL: { collection: 'bp_compliance_gesetze', chunks: 0, qdrant_id: 'bgb_digital' }, // §§ 327-327u
|
||||
DE_EGBGB_WIDERRUF: { collection: 'bp_compliance_gesetze', chunks: 0, qdrant_id: 'egbgb' }, // Muster-Widerrufsbelehrung
|
||||
|
||||
// === BSI Standards (bp_compliance_gesetze) ===
|
||||
'BSI-TR-03161-1': { collection: 'bp_compliance_gesetze', chunks: 138, qdrant_id: 'bsi_tr_03161_1' },
|
||||
'BSI-TR-03161-2': { collection: 'bp_compliance_gesetze', chunks: 124, qdrant_id: 'bsi_tr_03161_2' },
|
||||
@@ -109,7 +134,7 @@ export const REGULATIONS_IN_RAG: Record<string, RagRegulationEntry> = {
|
||||
HU_INFOTV: { collection: 'bp_compliance_gesetze', chunks: 747, qdrant_id: 'hu_info_tv' },
|
||||
LU_DPA_LAW: { collection: 'bp_compliance_gesetze', chunks: 2, qdrant_id: 'lu_dpa_law' },
|
||||
|
||||
// === EDPB Guidelines (bp_compliance_datenschutz) ===
|
||||
// === EDPB Guidelines (bp_compliance_datenschutz) — alt (ingest-legal-corpus.sh) ===
|
||||
EDPB_GUIDELINES_5_2020: { collection: 'bp_compliance_datenschutz', chunks: 236, qdrant_id: 'edpb_05_2020' },
|
||||
EDPB_GUIDELINES_7_2020: { collection: 'bp_compliance_datenschutz', chunks: 347, qdrant_id: 'edpb_guidelines_7_2020' },
|
||||
EDPB_GUIDELINES_1_2020: { collection: 'bp_compliance_datenschutz', chunks: 337, qdrant_id: 'edpb_01_2020' },
|
||||
@@ -119,8 +144,73 @@ export const REGULATIONS_IN_RAG: Record<string, RagRegulationEntry> = {
|
||||
EDPB_GUIDELINES_4_2019: { collection: 'bp_compliance_datenschutz', chunks: 202, qdrant_id: 'edpb_04_2019' },
|
||||
EDPB_GUIDELINES_9_2022: { collection: 'bp_compliance_datenschutz', chunks: 243, qdrant_id: 'edpb_09_2022' },
|
||||
EDPB_DPIA_LIST: { collection: 'bp_compliance_datenschutz', chunks: 29, qdrant_id: 'edpb_dpia_list' },
|
||||
EDPB_LEGITIMATE_INTEREST: { collection: 'bp_compliance_datenschutz', chunks: 336, qdrant_id: 'edpb_legitimate_interest' },
|
||||
EDPS_DPIA_LIST: { collection: 'bp_compliance_datenschutz', chunks: 35, qdrant_id: 'edps_dpia_list' },
|
||||
EDPB_LEGITIMATE_INTEREST: { collection: 'bp_compliance_datenschutz', chunks: 672, qdrant_id: 'edpb_legitimate_interest' },
|
||||
EDPS_DPIA_LIST: { collection: 'bp_compliance_datenschutz', chunks: 73, qdrant_id: 'edps_dpia_list' },
|
||||
|
||||
// === EDPB Guidelines (bp_compliance_datenschutz) — neu (edpb-crawler.py) ===
|
||||
EDPB_ACCESS_01_2022: { collection: 'bp_compliance_datenschutz', chunks: 1020, qdrant_id: 'edpb_access_01_2022' },
|
||||
EDPB_ARTICLE48_02_2024: { collection: 'bp_compliance_datenschutz', chunks: 158, qdrant_id: 'edpb_article48_02_2024' },
|
||||
EDPB_BCR_01_2022: { collection: 'bp_compliance_datenschutz', chunks: 384, qdrant_id: 'edpb_bcr_01_2022' },
|
||||
EDPB_BREACH_09_2022: { collection: 'bp_compliance_datenschutz', chunks: 486, qdrant_id: 'edpb_breach_09_2022' },
|
||||
EDPB_CERTIFICATION_01_2018: { collection: 'bp_compliance_datenschutz', chunks: 160, qdrant_id: 'edpb_certification_01_2018' },
|
||||
EDPB_CERTIFICATION_01_2019: { collection: 'bp_compliance_datenschutz', chunks: 160, qdrant_id: 'edpb_certification_01_2019' },
|
||||
EDPB_CONNECTED_VEHICLES_01_2020: { collection: 'bp_compliance_datenschutz', chunks: 482, qdrant_id: 'edpb_connected_vehicles_01_2020' },
|
||||
EDPB_CONSENT_05_2020: { collection: 'bp_compliance_datenschutz', chunks: 247, qdrant_id: 'edpb_consent_05_2020' },
|
||||
EDPB_CONTROLLER_PROCESSOR_07_2020: { collection: 'bp_compliance_datenschutz', chunks: 694, qdrant_id: 'edpb_controller_processor_07_2020' },
|
||||
EDPB_COOKIE_TASKFORCE_2023: { collection: 'bp_compliance_datenschutz', chunks: 78, qdrant_id: 'edpb_cookie_taskforce_2023' },
|
||||
EDPB_DARK_PATTERNS_03_2022: { collection: 'bp_compliance_datenschutz', chunks: 413, qdrant_id: 'edpb_dark_patterns_03_2022' },
|
||||
EDPB_DPBD_04_2019: { collection: 'bp_compliance_datenschutz', chunks: 216, qdrant_id: 'edpb_dpbd_04_2019' },
|
||||
EDPB_DPIA_LIST_RECOMMENDATION: { collection: 'bp_compliance_datenschutz', chunks: 31, qdrant_id: 'edpb_dpia_list_recommendation' },
|
||||
EDPB_EPRIVACY_02_2023: { collection: 'bp_compliance_datenschutz', chunks: 188, qdrant_id: 'edpb_eprivacy_02_2023' },
|
||||
EDPB_FACIAL_RECOGNITION_05_2022: { collection: 'bp_compliance_datenschutz', chunks: 396, qdrant_id: 'edpb_facial_recognition_05_2022' },
|
||||
EDPB_FINES_04_2022: { collection: 'bp_compliance_datenschutz', chunks: 346, qdrant_id: 'edpb_fines_04_2022' },
|
||||
EDPB_GEOLOCATION_04_2020: { collection: 'bp_compliance_datenschutz', chunks: 108, qdrant_id: 'edpb_geolocation_04_2020' },
|
||||
EDPB_GL_2_2019: { collection: 'bp_compliance_datenschutz', chunks: 107, qdrant_id: 'edpb_gl_2_2019' },
|
||||
EDPB_HEALTH_DATA_03_2020: { collection: 'bp_compliance_datenschutz', chunks: 182, qdrant_id: 'edpb_health_data_03_2020' },
|
||||
EDPB_LEGAL_BASIS_02_2019: { collection: 'bp_compliance_datenschutz', chunks: 107, qdrant_id: 'edpb_legal_basis_02_2019' },
|
||||
EDPB_LEGITIMATE_INTEREST_01_2024: { collection: 'bp_compliance_datenschutz', chunks: 336, qdrant_id: 'edpb_legitimate_interest_01_2024' },
|
||||
EDPB_RTBF_05_2019: { collection: 'bp_compliance_datenschutz', chunks: 111, qdrant_id: 'edpb_rtbf_05_2019' },
|
||||
EDPB_RRO_09_2020: { collection: 'bp_compliance_datenschutz', chunks: 82, qdrant_id: 'edpb_rro_09_2020' },
|
||||
EDPB_SOCIAL_MEDIA_08_2020: { collection: 'bp_compliance_datenschutz', chunks: 333, qdrant_id: 'edpb_social_media_08_2020' },
|
||||
EDPB_TRANSFERS_01_2020: { collection: 'bp_compliance_datenschutz', chunks: 337, qdrant_id: 'edpb_transfers_01_2020' },
|
||||
EDPB_TRANSFERS_07_2020: { collection: 'bp_compliance_datenschutz', chunks: 337, qdrant_id: 'edpb_transfers_07_2020' },
|
||||
EDPB_VIDEO_03_2019: { collection: 'bp_compliance_datenschutz', chunks: 204, qdrant_id: 'edpb_video_03_2019' },
|
||||
EDPB_VVA_02_2021: { collection: 'bp_compliance_datenschutz', chunks: 273, qdrant_id: 'edpb_vva_02_2021' },
|
||||
|
||||
// === EDPS Guidance (bp_compliance_datenschutz) ===
|
||||
EDPS_DIGITAL_ETHICS_2018: { collection: 'bp_compliance_datenschutz', chunks: 404, qdrant_id: 'edps_digital_ethics_2018' },
|
||||
EDPS_GENAI_ORIENTATIONS_2024: { collection: 'bp_compliance_datenschutz', chunks: 274, qdrant_id: 'edps_genai_orientations_2024' },
|
||||
|
||||
// === WP29 Endorsed (bp_compliance_datenschutz) ===
|
||||
WP242_PORTABILITY: { collection: 'bp_compliance_datenschutz', chunks: 141, qdrant_id: 'wp242_portability' },
|
||||
WP243_DPO: { collection: 'bp_compliance_datenschutz', chunks: 54, qdrant_id: 'wp243_dpo' },
|
||||
WP244_PROFILING: { collection: 'bp_compliance_datenschutz', chunks: 247, qdrant_id: 'wp244_profiling' },
|
||||
WP248_DPIA: { collection: 'bp_compliance_datenschutz', chunks: 288, qdrant_id: 'wp248_dpia' },
|
||||
WP250_BREACH: { collection: 'bp_compliance_datenschutz', chunks: 201, qdrant_id: 'wp250_breach' },
|
||||
WP259_CONSENT: { collection: 'bp_compliance_datenschutz', chunks: 496, qdrant_id: 'wp259_consent' },
|
||||
WP260_TRANSPARENCY: { collection: 'bp_compliance_datenschutz', chunks: 558, qdrant_id: 'wp260_transparency' },
|
||||
|
||||
// === DSFA Muss-Listen (bp_dsfa_corpus) ===
|
||||
DSFA_BFDI_BUND: { collection: 'bp_dsfa_corpus', chunks: 17, qdrant_id: 'dsfa_bfdi_bund' },
|
||||
DSFA_DSK_GEMEINSAM: { collection: 'bp_dsfa_corpus', chunks: 35, qdrant_id: 'dsfa_dsk_gemeinsam' },
|
||||
DSFA_BW: { collection: 'bp_dsfa_corpus', chunks: 41, qdrant_id: 'dsfa_bw' },
|
||||
DSFA_BY: { collection: 'bp_dsfa_corpus', chunks: 35, qdrant_id: 'dsfa_by' },
|
||||
DSFA_BE_OE: { collection: 'bp_dsfa_corpus', chunks: 31, qdrant_id: 'dsfa_be_oe' },
|
||||
DSFA_BE_NOE: { collection: 'bp_dsfa_corpus', chunks: 48, qdrant_id: 'dsfa_be_noe' },
|
||||
DSFA_BB_OE: { collection: 'bp_dsfa_corpus', chunks: 43, qdrant_id: 'dsfa_bb_oe' },
|
||||
DSFA_BB_NOE: { collection: 'bp_dsfa_corpus', chunks: 53, qdrant_id: 'dsfa_bb_noe' },
|
||||
DSFA_HB: { collection: 'bp_dsfa_corpus', chunks: 44, qdrant_id: 'dsfa_hb' },
|
||||
DSFA_HH_OE: { collection: 'bp_dsfa_corpus', chunks: 58, qdrant_id: 'dsfa_hh_oe' },
|
||||
DSFA_HH_NOE: { collection: 'bp_dsfa_corpus', chunks: 53, qdrant_id: 'dsfa_hh_noe' },
|
||||
DSFA_MV: { collection: 'bp_dsfa_corpus', chunks: 32, qdrant_id: 'dsfa_mv' },
|
||||
DSFA_NI: { collection: 'bp_dsfa_corpus', chunks: 47, qdrant_id: 'dsfa_ni' },
|
||||
DSFA_RP: { collection: 'bp_dsfa_corpus', chunks: 25, qdrant_id: 'dsfa_rp' },
|
||||
DSFA_SL: { collection: 'bp_dsfa_corpus', chunks: 35, qdrant_id: 'dsfa_sl' },
|
||||
DSFA_SN: { collection: 'bp_dsfa_corpus', chunks: 18, qdrant_id: 'dsfa_sn' },
|
||||
DSFA_ST_OE: { collection: 'bp_dsfa_corpus', chunks: 57, qdrant_id: 'dsfa_st_oe' },
|
||||
DSFA_ST_NOE: { collection: 'bp_dsfa_corpus', chunks: 35, qdrant_id: 'dsfa_st_noe' },
|
||||
DSFA_SH: { collection: 'bp_dsfa_corpus', chunks: 44, qdrant_id: 'dsfa_sh' },
|
||||
DSFA_TH: { collection: 'bp_dsfa_corpus', chunks: 48, qdrant_id: 'dsfa_th' },
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -152,6 +242,12 @@ export const REGULATION_INFO: RegulationInfo[] = [
|
||||
{ code: 'DSM', name: 'DSM-Urheberrechtsrichtlinie', type: 'eu_directive' },
|
||||
{ code: 'PLD', name: 'Produkthaftungsrichtlinie', type: 'eu_directive' },
|
||||
{ code: 'GPSR', name: 'General Product Safety', type: 'eu_regulation' },
|
||||
{ code: 'WARENKAUF_RL', name: 'Warenkauf-RL', type: 'eu_directive' },
|
||||
{ code: 'KLAUSEL_RL', name: 'Klausel-RL', type: 'eu_directive' },
|
||||
{ code: 'UNLAUTERE_PRAKTIKEN_RL', name: 'UGP-RL', type: 'eu_directive' },
|
||||
{ code: 'PREISANGABEN_RL', name: 'Preisangaben-RL', type: 'eu_directive' },
|
||||
{ code: 'OMNIBUS_RL', name: 'Omnibus-RL', type: 'eu_directive' },
|
||||
{ code: 'BATTERIE_VO', name: 'Batterieverordnung', type: 'eu_regulation' },
|
||||
{ code: 'E_COMMERCE_RL', name: 'E-Commerce-Richtlinie', type: 'eu_directive' },
|
||||
{ code: 'VERBRAUCHERRECHTE_RL', name: 'Verbraucherrechte-RL', type: 'eu_directive' },
|
||||
{ code: 'DIGITALE_INHALTE_RL', name: 'Digitale-Inhalte-RL', type: 'eu_directive' },
|
||||
@@ -180,6 +276,22 @@ export const REGULATION_INFO: RegulationInfo[] = [
|
||||
{ code: 'DE_GESCHGEHG', name: 'GeschGehG', type: 'de_law' },
|
||||
{ code: 'DE_USTG_RET', name: 'UStG', type: 'de_law' },
|
||||
{ code: 'DE_URHG', name: 'UrhG', type: 'de_law' },
|
||||
// DE Verbraucherschutz
|
||||
{ code: 'DE_PANGV', name: 'PAngV', type: 'de_law' },
|
||||
{ code: 'DE_VSBG', name: 'VSBG', type: 'de_law' },
|
||||
{ code: 'DE_PRODHAFTG', name: 'ProdHaftG', type: 'de_law' },
|
||||
{ code: 'DE_VERPACKG', name: 'VerpackG', type: 'de_law' },
|
||||
{ code: 'DE_ELEKTROG', name: 'ElektroG', type: 'de_law' },
|
||||
{ code: 'DE_BATTDG', name: 'BattDG', type: 'de_law' },
|
||||
{ code: 'DE_BFSG', name: 'BFSG', type: 'de_law' },
|
||||
{ code: 'DE_UWG', name: 'UWG', type: 'de_law' },
|
||||
{ code: 'DE_GEWO', name: 'GewO', type: 'de_law' },
|
||||
{ code: 'DE_BGB_AGB_305', name: 'BGB AGB-Recht §§305-310', type: 'de_law' },
|
||||
{ code: 'DE_BGB_FERNABSATZ', name: 'BGB Fernabsatz §§312-312k', type: 'de_law' },
|
||||
{ code: 'DE_BGB_KAUFRECHT', name: 'BGB Kaufrecht §§433-480', type: 'de_law' },
|
||||
{ code: 'DE_BGB_WIDERRUF', name: 'BGB Widerruf §§355-361', type: 'de_law' },
|
||||
{ code: 'DE_BGB_DIGITAL', name: 'BGB Digital §§327-327u', type: 'de_law' },
|
||||
{ code: 'DE_EGBGB_WIDERRUF', name: 'EGBGB Widerrufsbelehrung', type: 'de_law' },
|
||||
// BSI
|
||||
{ code: 'BSI-TR-03161-1', name: 'BSI-TR Teil 1', type: 'bsi_standard' },
|
||||
{ code: 'BSI-TR-03161-2', name: 'BSI-TR Teil 2', type: 'bsi_standard' },
|
||||
@@ -217,18 +329,79 @@ export const REGULATION_INFO: RegulationInfo[] = [
|
||||
{ code: 'CZ_ZOU', name: 'Zakon Tschechien', type: 'national_law' },
|
||||
{ code: 'HU_INFOTV', name: 'Infotv. Ungarn', type: 'national_law' },
|
||||
{ code: 'LU_DPA_LAW', name: 'Datenschutzgesetz Luxemburg', type: 'national_law' },
|
||||
// EDPB
|
||||
// EDPB Guidelines (alt)
|
||||
{ code: 'EDPB_GUIDELINES_5_2020', name: 'EDPB GL Einwilligung', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_GUIDELINES_7_2020', name: 'EDPB GL C/P Konzepte', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_GUIDELINES_1_2020', name: 'EDPB GL Fahrzeuge', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_GUIDELINES_1_2022', name: 'EDPB GL Bussgelder', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_GUIDELINES_2_2023', name: 'EDPB GL Art. 37 Scope', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_GUIDELINES_2_2024', name: 'EDPB GL 2024', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_GUIDELINES_2_2024', name: 'EDPB GL Art. 48', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_GUIDELINES_4_2019', name: 'EDPB GL Art. 25 DPbD', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_GUIDELINES_9_2022', name: 'EDPB GL Datenschutzverletzung', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_DPIA_LIST', name: 'EDPB DPIA-Liste', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_LEGITIMATE_INTEREST', name: 'EDPB Berecht. Interesse', type: 'eu_guideline' },
|
||||
{ code: 'EDPS_DPIA_LIST', name: 'EDPS DPIA-Liste', type: 'eu_guideline' },
|
||||
// EDPB Guidelines (neu — Crawler)
|
||||
{ code: 'EDPB_ACCESS_01_2022', name: 'EDPB GL Auskunftsrecht', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_ARTICLE48_02_2024', name: 'EDPB GL Art. 48', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_BCR_01_2022', name: 'EDPB GL BCR', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_BREACH_09_2022', name: 'EDPB GL Datenpannen', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_CERTIFICATION_01_2018', name: 'EDPB GL Zertifizierung', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_CERTIFICATION_01_2019', name: 'EDPB GL Zertifizierung 2019', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_CONNECTED_VEHICLES_01_2020', name: 'EDPB GL Vernetzte Fahrzeuge', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_CONSENT_05_2020', name: 'EDPB GL Consent', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_CONTROLLER_PROCESSOR_07_2020', name: 'EDPB GL Verantwortliche/Auftragsverarbeiter', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_COOKIE_TASKFORCE_2023', name: 'EDPB Cookie-Banner Taskforce', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_DARK_PATTERNS_03_2022', name: 'EDPB GL Dark Patterns', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_DPBD_04_2019', name: 'EDPB GL Data Protection by Design', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_DPIA_LIST_RECOMMENDATION', name: 'EDPB DPIA-Empfehlung', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_EPRIVACY_02_2023', name: 'EDPB GL ePrivacy', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_FACIAL_RECOGNITION_05_2022', name: 'EDPB GL Gesichtserkennung', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_FINES_04_2022', name: 'EDPB GL Bussgeldberechnung', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_GEOLOCATION_04_2020', name: 'EDPB GL Geolokalisierung', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_GL_2_2019', name: 'EDPB GL Video-Ueberwachung', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_HEALTH_DATA_03_2020', name: 'EDPB GL Gesundheitsdaten', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_LEGAL_BASIS_02_2019', name: 'EDPB GL Rechtsgrundlage Art. 6(1)(b)', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_LEGITIMATE_INTEREST_01_2024', name: 'EDPB GL Berecht. Interesse 2024', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_RTBF_05_2019', name: 'EDPB GL Recht auf Vergessenwerden', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_RRO_09_2020', name: 'EDPB GL Relevant & Reasoned Objection', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_SOCIAL_MEDIA_08_2020', name: 'EDPB GL Social Media Targeting', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_TRANSFERS_01_2020', name: 'EDPB GL Uebermittlungen Art. 49', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_TRANSFERS_07_2020', name: 'EDPB GL Drittlandtransfers', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_VIDEO_03_2019', name: 'EDPB GL Videoueberwachung', type: 'eu_guideline' },
|
||||
{ code: 'EDPB_VVA_02_2021', name: 'EDPB GL Virtuelle Sprachassistenten', type: 'eu_guideline' },
|
||||
// EDPS
|
||||
{ code: 'EDPS_DIGITAL_ETHICS_2018', name: 'EDPS Digitale Ethik', type: 'eu_guideline' },
|
||||
{ code: 'EDPS_GENAI_ORIENTATIONS_2024', name: 'EDPS GenAI Orientierungen', type: 'eu_guideline' },
|
||||
// WP29 Endorsed
|
||||
{ code: 'WP242_PORTABILITY', name: 'WP242 Datenportabilitaet', type: 'wp29_endorsed' },
|
||||
{ code: 'WP243_DPO', name: 'WP243 Datenschutzbeauftragter', type: 'wp29_endorsed' },
|
||||
{ code: 'WP244_PROFILING', name: 'WP244 Profiling', type: 'wp29_endorsed' },
|
||||
{ code: 'WP248_DPIA', name: 'WP248 DSFA', type: 'wp29_endorsed' },
|
||||
{ code: 'WP250_BREACH', name: 'WP250 Datenpannen', type: 'wp29_endorsed' },
|
||||
{ code: 'WP259_CONSENT', name: 'WP259 Einwilligung', type: 'wp29_endorsed' },
|
||||
{ code: 'WP260_TRANSPARENCY', name: 'WP260 Transparenz', type: 'wp29_endorsed' },
|
||||
// DSFA Muss-Listen
|
||||
{ code: 'DSFA_BFDI_BUND', name: 'DSFA BfDI Bund', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_DSK_GEMEINSAM', name: 'DSFA DSK Gemeinsam', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_BW', name: 'DSFA Baden-Wuerttemberg', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_BY', name: 'DSFA Bayern', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_BE_OE', name: 'DSFA Berlin oeffentlich', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_BE_NOE', name: 'DSFA Berlin nicht-oeffentlich', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_BB_OE', name: 'DSFA Brandenburg oeffentlich', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_BB_NOE', name: 'DSFA Brandenburg nicht-oeffentlich', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_HB', name: 'DSFA Bremen', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_HH_OE', name: 'DSFA Hamburg oeffentlich', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_HH_NOE', name: 'DSFA Hamburg nicht-oeffentlich', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_MV', name: 'DSFA Mecklenburg-Vorpommern', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_NI', name: 'DSFA Niedersachsen', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_RP', name: 'DSFA Rheinland-Pfalz', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_SL', name: 'DSFA Saarland', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_SN', name: 'DSFA Sachsen', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_ST_OE', name: 'DSFA Sachsen-Anhalt oeffentlich', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_ST_NOE', name: 'DSFA Sachsen-Anhalt nicht-oeffentlich', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_SH', name: 'DSFA Schleswig-Holstein', type: 'dsfa_mussliste' },
|
||||
{ code: 'DSFA_TH', name: 'DSFA Thueringen', type: 'dsfa_mussliste' },
|
||||
// International Standards
|
||||
{ code: 'NIST_SSDF', name: 'NIST SSDF', type: 'international_standard' },
|
||||
{ code: 'NIST_CSF_2', name: 'NIST CSF 2.0', type: 'international_standard' },
|
||||
|
||||
4332
admin-lehrer/app/(admin)/ai/rag/rag-documents.json
Normal file
4332
admin-lehrer/app/(admin)/ai/rag/rag-documents.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1430,7 +1430,6 @@ export default function TestQualityPage() {
|
||||
databases: ['Qdrant', 'PostgreSQL'],
|
||||
}}
|
||||
relatedPages={[
|
||||
{ name: 'LLM Vergleich', href: '/ai/llm-compare', description: 'Provider-Vergleich' },
|
||||
{ name: 'GPU Infrastruktur', href: '/ai/gpu', description: 'GPU-Ressourcen verwalten' },
|
||||
{ name: 'RAG Management', href: '/ai/rag', description: 'Training Data & RAG Pipelines' },
|
||||
]}
|
||||
|
||||
@@ -1,594 +0,0 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* Voice Service Admin Page (migrated from website/admin/voice)
|
||||
*
|
||||
* Displays:
|
||||
* - Voice-First Architecture Overview
|
||||
* - Developer Guide Content
|
||||
* - Live Voice Demo (embedded from studio-v2)
|
||||
* - Task State Machine Documentation
|
||||
* - DSGVO Compliance Information
|
||||
*/
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { PagePurpose } from '@/components/common/PagePurpose'
|
||||
|
||||
type TabType = 'overview' | 'demo' | 'tasks' | 'intents' | 'dsgvo' | 'api'
|
||||
|
||||
// Task State Machine data
|
||||
const TASK_STATES = [
|
||||
{ state: 'DRAFT', description: 'Task erstellt, noch nicht verarbeitet', color: 'bg-gray-100 text-gray-800', next: ['QUEUED', 'PAUSED'] },
|
||||
{ state: 'QUEUED', description: 'In Warteschlange fuer Verarbeitung', color: 'bg-blue-100 text-blue-800', next: ['RUNNING', 'PAUSED'] },
|
||||
{ state: 'RUNNING', description: 'Wird aktuell verarbeitet', color: 'bg-yellow-100 text-yellow-800', next: ['READY', 'PAUSED'] },
|
||||
{ state: 'READY', description: 'Fertig, wartet auf User-Bestaetigung', color: 'bg-green-100 text-green-800', next: ['APPROVED', 'REJECTED', 'PAUSED'] },
|
||||
{ state: 'APPROVED', description: 'Vom User bestaetigt', color: 'bg-emerald-100 text-emerald-800', next: ['COMPLETED'] },
|
||||
{ state: 'REJECTED', description: 'Vom User abgelehnt', color: 'bg-red-100 text-red-800', next: ['DRAFT'] },
|
||||
{ state: 'COMPLETED', description: 'Erfolgreich abgeschlossen', color: 'bg-teal-100 text-teal-800', next: [] },
|
||||
{ state: 'EXPIRED', description: 'TTL ueberschritten', color: 'bg-orange-100 text-orange-800', next: [] },
|
||||
{ state: 'PAUSED', description: 'Vom User pausiert', color: 'bg-purple-100 text-purple-800', next: ['DRAFT', 'QUEUED', 'RUNNING', 'READY'] },
|
||||
]
|
||||
|
||||
// Intent Types (22 types organized by group)
|
||||
const INTENT_GROUPS = [
|
||||
{
|
||||
group: 'Notizen',
|
||||
color: 'bg-blue-50 border-blue-200',
|
||||
intents: [
|
||||
{ type: 'student_observation', example: 'Notiz zu Max: heute wiederholt gestoert', description: 'Schuelerbeobachtungen' },
|
||||
{ type: 'reminder', example: 'Erinner mich morgen an Konferenz', description: 'Erinnerungen setzen' },
|
||||
{ type: 'homework_check', example: '7b Mathe Hausaufgabe kontrollieren', description: 'Hausaufgaben pruefen' },
|
||||
{ type: 'conference_topic', example: 'Thema Lehrerkonferenz: iPad-Regeln', description: 'Konferenzthemen' },
|
||||
{ type: 'correction_thought', example: 'Aufgabe 3: haeufiger Fehler erklaeren', description: 'Korrekturgedanken' },
|
||||
]
|
||||
},
|
||||
{
|
||||
group: 'Content-Generierung',
|
||||
color: 'bg-green-50 border-green-200',
|
||||
intents: [
|
||||
{ type: 'worksheet_generate', example: 'Erstelle 3 Lueckentexte zu Vokabeln', description: 'Arbeitsblaetter erstellen' },
|
||||
{ type: 'quiz_generate', example: '10-Minuten Vokabeltest mit Loesungen', description: 'Quiz/Tests erstellen' },
|
||||
{ type: 'quick_activity', example: '10 Minuten Einstieg, 5 Aufgaben', description: 'Schnelle Aktivitaeten' },
|
||||
{ type: 'differentiation', example: 'Zwei Schwierigkeitsstufen: Basis und Plus', description: 'Differenzierung' },
|
||||
]
|
||||
},
|
||||
{
|
||||
group: 'Kommunikation',
|
||||
color: 'bg-yellow-50 border-yellow-200',
|
||||
intents: [
|
||||
{ type: 'parent_letter', example: 'Neutraler Elternbrief wegen Stoerungen', description: 'Elternbriefe erstellen' },
|
||||
{ type: 'class_message', example: 'Nachricht an 8a: Hausaufgaben bis Mittwoch', description: 'Klassennachrichten' },
|
||||
]
|
||||
},
|
||||
{
|
||||
group: 'Canvas-Editor',
|
||||
color: 'bg-purple-50 border-purple-200',
|
||||
intents: [
|
||||
{ type: 'canvas_edit', example: 'Ueberschriften groesser, Zeilenabstand kleiner', description: 'Formatierung aendern' },
|
||||
{ type: 'canvas_layout', example: 'Alles auf eine Seite, Drucklayout A4', description: 'Layout anpassen' },
|
||||
{ type: 'canvas_element', example: 'Kasten fuer Merke hinzufuegen', description: 'Elemente hinzufuegen' },
|
||||
{ type: 'canvas_image', example: 'Bild 2 nach links, Pfeil auf Aufgabe 3', description: 'Bilder positionieren' },
|
||||
]
|
||||
},
|
||||
{
|
||||
group: 'RAG & Korrektur',
|
||||
color: 'bg-pink-50 border-pink-200',
|
||||
intents: [
|
||||
{ type: 'operator_checklist', example: 'Operatoren-Checkliste fuer diese Aufgabe', description: 'Operatoren abrufen' },
|
||||
{ type: 'eh_passage', example: 'Erwartungshorizont-Passage zu diesem Thema', description: 'EH-Passagen suchen' },
|
||||
{ type: 'feedback_suggestion', example: 'Kurze Feedbackformulierung vorschlagen', description: 'Feedback vorschlagen' },
|
||||
]
|
||||
},
|
||||
{
|
||||
group: 'Follow-up (TaskOrchestrator)',
|
||||
color: 'bg-teal-50 border-teal-200',
|
||||
intents: [
|
||||
{ type: 'task_summary', example: 'Fasse alle offenen Tasks zusammen', description: 'Task-Uebersicht' },
|
||||
{ type: 'convert_note', example: 'Mach aus der Notiz von gestern einen Elternbrief', description: 'Notizen konvertieren' },
|
||||
{ type: 'schedule_reminder', example: 'Erinner mich morgen an das Gespraech mit Max', description: 'Erinnerungen planen' },
|
||||
]
|
||||
},
|
||||
]
|
||||
|
||||
// DSGVO Data Categories
|
||||
const DSGVO_CATEGORIES = [
|
||||
{ category: 'Audio', processing: 'NUR transient im RAM, NIEMALS persistiert', storage: 'Keine', ttl: '-', icon: '🎤', risk: 'low' },
|
||||
{ category: 'PII (Schuelernamen)', processing: 'NUR auf Lehrergeraet', storage: 'Client-side', ttl: '-', icon: '👤', risk: 'high' },
|
||||
{ category: 'Pseudonyme', processing: 'Server erlaubt (student_ref, class_ref)', storage: 'Valkey Cache', ttl: '24h', icon: '🔢', risk: 'low' },
|
||||
{ category: 'Transkripte', processing: 'NUR verschluesselt (AES-256-GCM)', storage: 'PostgreSQL', ttl: '7 Tage', icon: '📝', risk: 'medium' },
|
||||
{ category: 'Task States', processing: 'TaskOrchestrator', storage: 'Valkey', ttl: '30 Tage', icon: '📋', risk: 'low' },
|
||||
{ category: 'Audit Logs', processing: 'Nur truncated IDs, keine PII', storage: 'PostgreSQL', ttl: '90 Tage', icon: '📊', risk: 'low' },
|
||||
]
|
||||
|
||||
// API Endpoints
|
||||
const API_ENDPOINTS = [
|
||||
{ method: 'POST', path: '/api/v1/sessions', description: 'Voice Session erstellen' },
|
||||
{ method: 'GET', path: '/api/v1/sessions/{id}', description: 'Session Status abrufen' },
|
||||
{ method: 'DELETE', path: '/api/v1/sessions/{id}', description: 'Session beenden' },
|
||||
{ method: 'GET', path: '/api/v1/sessions/{id}/tasks', description: 'Pending Tasks abrufen' },
|
||||
{ method: 'POST', path: '/api/v1/tasks', description: 'Task erstellen' },
|
||||
{ method: 'GET', path: '/api/v1/tasks/{id}', description: 'Task Status abrufen' },
|
||||
{ method: 'PUT', path: '/api/v1/tasks/{id}/transition', description: 'Task State aendern' },
|
||||
{ method: 'DELETE', path: '/api/v1/tasks/{id}', description: 'Task loeschen' },
|
||||
{ method: 'WS', path: '/ws/voice', description: 'Voice Streaming (WebSocket)' },
|
||||
{ method: 'GET', path: '/health', description: 'Health Check' },
|
||||
]
|
||||
|
||||
export default function VoiceMatrixPage() {
|
||||
const [activeTab, setActiveTab] = useState<TabType>('overview')
|
||||
const [demoLoaded, setDemoLoaded] = useState(false)
|
||||
|
||||
const tabs = [
|
||||
{ id: 'overview', name: 'Architektur', icon: '🏗️' },
|
||||
{ id: 'demo', name: 'Live Demo', icon: '🎤' },
|
||||
{ id: 'tasks', name: 'Task States', icon: '📋' },
|
||||
{ id: 'intents', name: 'Intents (22)', icon: '🎯' },
|
||||
{ id: 'dsgvo', name: 'DSGVO', icon: '🔒' },
|
||||
{ id: 'api', name: 'API', icon: '🔌' },
|
||||
]
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Page Purpose */}
|
||||
<PagePurpose
|
||||
title="Voice Service"
|
||||
purpose="Voice-First Interface mit PersonaPlex-7B & TaskOrchestrator. Konfigurieren und testen Sie den Voice-Service fuer Lehrer-Interaktionen per Sprache."
|
||||
audience={['Entwickler', 'Admins']}
|
||||
architecture={{
|
||||
services: ['voice-service (Python, Port 8091)', 'studio-v2 (Next.js)', 'valkey (Cache)'],
|
||||
databases: ['PostgreSQL', 'Valkey Cache'],
|
||||
}}
|
||||
relatedPages={[
|
||||
{ name: 'Matrix & Jitsi', href: '/communication/matrix', description: 'Kommunikation Monitoring' },
|
||||
{ name: 'LLM Vergleich', href: '/ai/llm-compare', description: 'KI-Provider vergleichen' },
|
||||
{ name: 'GPU Infrastruktur', href: '/infrastructure/gpu', description: 'GPU fuer Voice-Service' },
|
||||
]}
|
||||
collapsible={true}
|
||||
defaultCollapsed={false}
|
||||
/>
|
||||
|
||||
{/* Quick Links */}
|
||||
<div className="mb-6 flex flex-wrap gap-3">
|
||||
<a
|
||||
href="https://macmini:3001/voice-test"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" />
|
||||
</svg>
|
||||
Voice Test (Studio)
|
||||
</a>
|
||||
<a
|
||||
href="https://macmini:8091/health"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 px-4 py-2 bg-green-100 text-green-700 rounded-lg hover:bg-green-200 transition-colors"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
Health Check
|
||||
</a>
|
||||
<Link
|
||||
href="/development/docs"
|
||||
className="flex items-center gap-2 px-4 py-2 bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200 transition-colors"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
||||
</svg>
|
||||
Developer Docs
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Stats Overview */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-6 gap-4 mb-6">
|
||||
<div className="bg-white rounded-lg shadow p-4">
|
||||
<div className="text-3xl font-bold text-teal-600">8091</div>
|
||||
<div className="text-sm text-slate-500">Port</div>
|
||||
</div>
|
||||
<div className="bg-white rounded-lg shadow p-4">
|
||||
<div className="text-3xl font-bold text-blue-600">22</div>
|
||||
<div className="text-sm text-slate-500">Task Types</div>
|
||||
</div>
|
||||
<div className="bg-white rounded-lg shadow p-4">
|
||||
<div className="text-3xl font-bold text-purple-600">9</div>
|
||||
<div className="text-sm text-slate-500">Task States</div>
|
||||
</div>
|
||||
<div className="bg-white rounded-lg shadow p-4">
|
||||
<div className="text-3xl font-bold text-green-600">24kHz</div>
|
||||
<div className="text-sm text-slate-500">Audio Rate</div>
|
||||
</div>
|
||||
<div className="bg-white rounded-lg shadow p-4">
|
||||
<div className="text-3xl font-bold text-orange-600">80ms</div>
|
||||
<div className="text-sm text-slate-500">Frame Size</div>
|
||||
</div>
|
||||
<div className="bg-white rounded-lg shadow p-4">
|
||||
<div className="text-3xl font-bold text-red-600">0</div>
|
||||
<div className="text-sm text-slate-500">Audio Persist</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="bg-white rounded-lg shadow mb-6">
|
||||
<div className="border-b border-slate-200 px-4">
|
||||
<div className="flex gap-1 overflow-x-auto">
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
onClick={() => setActiveTab(tab.id as TabType)}
|
||||
className={`px-4 py-3 text-sm font-medium whitespace-nowrap transition-colors border-b-2 ${
|
||||
activeTab === tab.id
|
||||
? 'border-teal-600 text-teal-600'
|
||||
: 'border-transparent text-slate-500 hover:text-slate-700'
|
||||
}`}
|
||||
>
|
||||
<span className="mr-2">{tab.icon}</span>
|
||||
{tab.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-6">
|
||||
{/* Overview Tab */}
|
||||
{activeTab === 'overview' && (
|
||||
<div className="space-y-6">
|
||||
<h3 className="text-lg font-semibold text-slate-900">Voice-First Architektur</h3>
|
||||
|
||||
{/* Architecture Diagram */}
|
||||
<div className="bg-slate-50 rounded-lg p-6 font-mono text-sm overflow-x-auto">
|
||||
<pre className="text-slate-700">{`
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ LEHRERGERAET (PWA / App) │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ VoiceCapture.tsx │ voice-encryption.ts │ voice-api.ts │ │
|
||||
│ │ Mikrofon │ AES-256-GCM │ WebSocket Client │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
└───────────────────────────┬──────────────────────────────────────┘
|
||||
│ WebSocket (wss://)
|
||||
▼
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
│ VOICE SERVICE (Port 8091) │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ main.py │ streaming.py │ sessions.py │ tasks.py │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ task_orchestrator.py │ intent_router.py │ encryption │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
└───────────────────────────┬──────────────────────────────────────┘
|
||||
│
|
||||
┌──────────────────┼──────────────────┐
|
||||
▼ ▼ ▼
|
||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||
│ PersonaPlex-7B │ │ Ollama Fallback │ │ Valkey Cache │
|
||||
│ (A100 GPU) │ │ (Mac Mini) │ │ (Sessions) │
|
||||
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
||||
`}</pre>
|
||||
</div>
|
||||
|
||||
{/* Technology Stack */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
|
||||
<h4 className="font-semibold text-blue-800 mb-2">Voice Model (Produktion)</h4>
|
||||
<p className="text-sm text-blue-700">PersonaPlex-7B (NVIDIA)</p>
|
||||
<p className="text-xs text-blue-600 mt-1">Full-Duplex Speech-to-Speech</p>
|
||||
<p className="text-xs text-blue-500">Lizenz: MIT + NVIDIA Open Model</p>
|
||||
</div>
|
||||
<div className="bg-green-50 border border-green-200 rounded-lg p-4">
|
||||
<h4 className="font-semibold text-green-800 mb-2">Agent Orchestration</h4>
|
||||
<p className="text-sm text-green-700">TaskOrchestrator</p>
|
||||
<p className="text-xs text-green-600 mt-1">Task State Machine</p>
|
||||
<p className="text-xs text-green-500">Lizenz: Proprietary</p>
|
||||
</div>
|
||||
<div className="bg-purple-50 border border-purple-200 rounded-lg p-4">
|
||||
<h4 className="font-semibold text-purple-800 mb-2">Audio Codec</h4>
|
||||
<p className="text-sm text-purple-700">Mimi (24kHz, 80ms)</p>
|
||||
<p className="text-xs text-purple-600 mt-1">Low-Latency Streaming</p>
|
||||
<p className="text-xs text-purple-500">Lizenz: MIT</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Key Files */}
|
||||
<div>
|
||||
<h4 className="font-semibold text-slate-800 mb-3">Wichtige Dateien</h4>
|
||||
<div className="bg-white border border-slate-200 rounded-lg overflow-hidden">
|
||||
<table className="min-w-full divide-y divide-slate-200">
|
||||
<thead className="bg-slate-50">
|
||||
<tr>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium text-slate-500 uppercase">Datei</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium text-slate-500 uppercase">Beschreibung</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-200">
|
||||
<tr><td className="px-4 py-2 font-mono text-sm">voice-service/main.py</td><td className="px-4 py-2 text-sm text-slate-600">FastAPI Entry, WebSocket Handler</td></tr>
|
||||
<tr><td className="px-4 py-2 font-mono text-sm">voice-service/services/task_orchestrator.py</td><td className="px-4 py-2 text-sm text-slate-600">Task State Machine</td></tr>
|
||||
<tr><td className="px-4 py-2 font-mono text-sm">voice-service/services/intent_router.py</td><td className="px-4 py-2 text-sm text-slate-600">Intent Detection (22 Types)</td></tr>
|
||||
<tr><td className="px-4 py-2 font-mono text-sm">voice-service/services/encryption_service.py</td><td className="px-4 py-2 text-sm text-slate-600">Namespace Key Management</td></tr>
|
||||
<tr><td className="px-4 py-2 font-mono text-sm">studio-v2/components/voice/VoiceCapture.tsx</td><td className="px-4 py-2 text-sm text-slate-600">Frontend Mikrofon + Crypto</td></tr>
|
||||
<tr><td className="px-4 py-2 font-mono text-sm">studio-v2/lib/voice/voice-encryption.ts</td><td className="px-4 py-2 text-sm text-slate-600">AES-256-GCM Client-side</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Demo Tab */}
|
||||
{activeTab === 'demo' && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold text-slate-900">Live Voice Demo</h3>
|
||||
<a
|
||||
href="https://macmini:3001/voice-test"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sm text-teal-600 hover:text-teal-700 flex items-center gap-1"
|
||||
>
|
||||
In neuem Tab oeffnen
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="bg-slate-100 rounded-lg p-4 text-sm text-slate-600 mb-4">
|
||||
<p><strong>Hinweis:</strong> Die Demo erfordert, dass der Voice Service (Port 8091) und das Studio-v2 Frontend (Port 3001) laufen.</p>
|
||||
<code className="block mt-2 bg-slate-200 p-2 rounded">docker compose up -d voice-service && cd studio-v2 && npm run dev</code>
|
||||
</div>
|
||||
|
||||
{/* Embedded Demo */}
|
||||
<div className="relative bg-slate-900 rounded-lg overflow-hidden" style={{ height: '600px' }}>
|
||||
{!demoLoaded && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<button
|
||||
onClick={() => setDemoLoaded(true)}
|
||||
className="px-6 py-3 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors flex items-center gap-2"
|
||||
>
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
Voice Demo laden
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{demoLoaded && (
|
||||
<iframe
|
||||
src="https://macmini:3001/voice-test?embed=true"
|
||||
className="w-full h-full border-0"
|
||||
title="Voice Demo"
|
||||
allow="microphone"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Task States Tab */}
|
||||
{activeTab === 'tasks' && (
|
||||
<div className="space-y-6">
|
||||
<h3 className="text-lg font-semibold text-slate-900">Task State Machine (TaskOrchestrator)</h3>
|
||||
|
||||
{/* State Diagram */}
|
||||
<div className="bg-slate-50 rounded-lg p-6 font-mono text-sm overflow-x-auto">
|
||||
<pre className="text-slate-700">{`
|
||||
DRAFT → QUEUED → RUNNING → READY
|
||||
│
|
||||
┌───────────┴───────────┐
|
||||
│ │
|
||||
APPROVED REJECTED
|
||||
│ │
|
||||
COMPLETED DRAFT (revision)
|
||||
|
||||
Any State → EXPIRED (TTL)
|
||||
Any State → PAUSED (User Interrupt)
|
||||
`}</pre>
|
||||
</div>
|
||||
|
||||
{/* States Table */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{TASK_STATES.map((state) => (
|
||||
<div key={state.state} className={`${state.color} rounded-lg p-4`}>
|
||||
<div className="font-semibold text-lg">{state.state}</div>
|
||||
<p className="text-sm mt-1">{state.description}</p>
|
||||
{state.next.length > 0 && (
|
||||
<div className="mt-2 text-xs">
|
||||
<span className="opacity-75">Naechste:</span>{' '}
|
||||
{state.next.join(', ')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Intents Tab */}
|
||||
{activeTab === 'intents' && (
|
||||
<div className="space-y-6">
|
||||
<h3 className="text-lg font-semibold text-slate-900">Intent Types (22 unterstuetzte Typen)</h3>
|
||||
|
||||
{INTENT_GROUPS.map((group) => (
|
||||
<div key={group.group} className={`${group.color} border rounded-lg p-4`}>
|
||||
<h4 className="font-semibold text-slate-800 mb-3">{group.group}</h4>
|
||||
<div className="space-y-2">
|
||||
{group.intents.map((intent) => (
|
||||
<div key={intent.type} className="bg-white rounded-lg p-3 shadow-sm">
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<code className="text-sm font-mono text-teal-700 bg-teal-50 px-2 py-0.5 rounded">
|
||||
{intent.type}
|
||||
</code>
|
||||
<p className="text-sm text-slate-600 mt-1">{intent.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 text-xs text-slate-500 italic">
|
||||
Beispiel: "{intent.example}"
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* DSGVO Tab */}
|
||||
{activeTab === 'dsgvo' && (
|
||||
<div className="space-y-6">
|
||||
<h3 className="text-lg font-semibold text-slate-900">DSGVO-Compliance</h3>
|
||||
|
||||
{/* Key Principles */}
|
||||
<div className="bg-green-50 border border-green-200 rounded-lg p-4">
|
||||
<h4 className="font-semibold text-green-800 mb-2">Kernprinzipien</h4>
|
||||
<ul className="list-disc list-inside text-sm text-green-700 space-y-1">
|
||||
<li><strong>Audio NIEMALS persistiert</strong> - Nur transient im RAM</li>
|
||||
<li><strong>Namespace-Verschluesselung</strong> - Key nur auf Lehrergeraet</li>
|
||||
<li><strong>Keine Klartext-PII serverseitig</strong> - Nur verschluesselt oder pseudonymisiert</li>
|
||||
<li><strong>TTL-basierte Auto-Loeschung</strong> - 7/30/90 Tage je nach Kategorie</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Data Categories Table */}
|
||||
<div className="bg-white border border-slate-200 rounded-lg overflow-hidden">
|
||||
<table className="min-w-full divide-y divide-slate-200">
|
||||
<thead className="bg-slate-50">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Kategorie</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Verarbeitung</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Speicherort</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">TTL</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Risiko</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-200">
|
||||
{DSGVO_CATEGORIES.map((cat) => (
|
||||
<tr key={cat.category}>
|
||||
<td className="px-4 py-3">
|
||||
<span className="mr-2">{cat.icon}</span>
|
||||
<span className="font-medium">{cat.category}</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm text-slate-600">{cat.processing}</td>
|
||||
<td className="px-4 py-3 text-sm text-slate-600">{cat.storage}</td>
|
||||
<td className="px-4 py-3 text-sm text-slate-600">{cat.ttl}</td>
|
||||
<td className="px-4 py-3">
|
||||
<span className={`px-2 py-1 rounded text-xs font-medium ${
|
||||
cat.risk === 'low' ? 'bg-green-100 text-green-700' :
|
||||
cat.risk === 'medium' ? 'bg-yellow-100 text-yellow-700' :
|
||||
'bg-red-100 text-red-700'
|
||||
}`}>
|
||||
{cat.risk.toUpperCase()}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Audit Log Info */}
|
||||
<div className="bg-slate-50 border border-slate-200 rounded-lg p-4">
|
||||
<h4 className="font-semibold text-slate-800 mb-2">Audit Logs (ohne PII)</h4>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-green-600 font-medium">Erlaubt:</span>
|
||||
<ul className="list-disc list-inside text-slate-600 mt-1">
|
||||
<li>ref_id (truncated)</li>
|
||||
<li>content_type</li>
|
||||
<li>size_bytes</li>
|
||||
<li>ttl_hours</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-red-600 font-medium">Verboten:</span>
|
||||
<ul className="list-disc list-inside text-slate-600 mt-1">
|
||||
<li>user_name</li>
|
||||
<li>content / transcript</li>
|
||||
<li>email</li>
|
||||
<li>student_name</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* API Tab */}
|
||||
{activeTab === 'api' && (
|
||||
<div className="space-y-6">
|
||||
<h3 className="text-lg font-semibold text-slate-900">Voice Service API (Port 8091)</h3>
|
||||
|
||||
{/* REST Endpoints */}
|
||||
<div className="bg-white border border-slate-200 rounded-lg overflow-hidden">
|
||||
<table className="min-w-full divide-y divide-slate-200">
|
||||
<thead className="bg-slate-50">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Methode</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Endpoint</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Beschreibung</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-200">
|
||||
{API_ENDPOINTS.map((ep, idx) => (
|
||||
<tr key={idx}>
|
||||
<td className="px-4 py-3">
|
||||
<span className={`px-2 py-1 rounded text-xs font-medium ${
|
||||
ep.method === 'GET' ? 'bg-green-100 text-green-700' :
|
||||
ep.method === 'POST' ? 'bg-blue-100 text-blue-700' :
|
||||
ep.method === 'PUT' ? 'bg-yellow-100 text-yellow-700' :
|
||||
ep.method === 'DELETE' ? 'bg-red-100 text-red-700' :
|
||||
'bg-purple-100 text-purple-700'
|
||||
}`}>
|
||||
{ep.method}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 font-mono text-sm">{ep.path}</td>
|
||||
<td className="px-4 py-3 text-sm text-slate-600">{ep.description}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* WebSocket Protocol */}
|
||||
<div className="bg-slate-50 rounded-lg p-4">
|
||||
<h4 className="font-semibold text-slate-800 mb-3">WebSocket Protocol</h4>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
|
||||
<div className="bg-white rounded-lg p-3 border border-slate-200">
|
||||
<div className="font-medium text-slate-700 mb-2">Client → Server</div>
|
||||
<ul className="list-disc list-inside text-slate-600 space-y-1">
|
||||
<li><code className="bg-slate-100 px-1 rounded">Binary</code>: Int16 PCM Audio (24kHz, 80ms)</li>
|
||||
<li><code className="bg-slate-100 px-1 rounded">JSON</code>: {`{type: "config|end_turn|interrupt"}`}</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div className="bg-white rounded-lg p-3 border border-slate-200">
|
||||
<div className="font-medium text-slate-700 mb-2">Server → Client</div>
|
||||
<ul className="list-disc list-inside text-slate-600 space-y-1">
|
||||
<li><code className="bg-slate-100 px-1 rounded">Binary</code>: Audio Response (base64)</li>
|
||||
<li><code className="bg-slate-100 px-1 rounded">JSON</code>: {`{type: "transcript|intent|status|error"}`}</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Example curl commands */}
|
||||
<div className="bg-slate-900 rounded-lg p-4 text-sm">
|
||||
<h4 className="font-semibold text-slate-300 mb-3">Beispiel: Session erstellen</h4>
|
||||
<pre className="text-green-400 overflow-x-auto">{`curl -X POST https://macmini:8091/api/v1/sessions \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{
|
||||
"namespace_id": "ns-12345678abcdef12345678abcdef12",
|
||||
"key_hash": "sha256:dGVzdGtleWhhc2h0ZXN0a2V5aGFzaHRlc3Q=",
|
||||
"device_type": "pwa"
|
||||
}'`}</pre>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,635 +0,0 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* Video & Chat Admin Page
|
||||
*
|
||||
* Matrix & Jitsi Monitoring Dashboard
|
||||
* Provides system statistics, active calls, user metrics, and service health
|
||||
* Migrated from website/app/admin/communication
|
||||
*/
|
||||
|
||||
import { useEffect, useState, useCallback } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { PagePurpose } from '@/components/common/PagePurpose'
|
||||
import { getModuleByHref } from '@/lib/navigation'
|
||||
|
||||
interface MatrixStats {
|
||||
total_users: number
|
||||
active_users: number
|
||||
total_rooms: number
|
||||
active_rooms: number
|
||||
messages_today: number
|
||||
messages_this_week: number
|
||||
status: 'online' | 'offline' | 'degraded'
|
||||
}
|
||||
|
||||
interface JitsiStats {
|
||||
active_meetings: number
|
||||
total_participants: number
|
||||
meetings_today: number
|
||||
average_duration_minutes: number
|
||||
peak_concurrent_users: number
|
||||
total_minutes_today: number
|
||||
status: 'online' | 'offline' | 'degraded'
|
||||
}
|
||||
|
||||
interface TrafficStats {
|
||||
matrix: {
|
||||
bandwidth_in_mb: number
|
||||
bandwidth_out_mb: number
|
||||
messages_per_minute: number
|
||||
media_uploads_today: number
|
||||
media_size_mb: number
|
||||
}
|
||||
jitsi: {
|
||||
bandwidth_in_mb: number
|
||||
bandwidth_out_mb: number
|
||||
video_streams_active: number
|
||||
audio_streams_active: number
|
||||
estimated_hourly_gb: number
|
||||
}
|
||||
total: {
|
||||
bandwidth_in_mb: number
|
||||
bandwidth_out_mb: number
|
||||
estimated_monthly_gb: number
|
||||
}
|
||||
}
|
||||
|
||||
interface CommunicationStats {
|
||||
matrix: MatrixStats
|
||||
jitsi: JitsiStats
|
||||
traffic?: TrafficStats
|
||||
last_updated: string
|
||||
}
|
||||
|
||||
interface ActiveMeeting {
|
||||
room_name: string
|
||||
display_name: string
|
||||
participants: number
|
||||
started_at: string
|
||||
duration_minutes: number
|
||||
}
|
||||
|
||||
interface RecentRoom {
|
||||
room_id: string
|
||||
name: string
|
||||
member_count: number
|
||||
last_activity: string
|
||||
room_type: 'class' | 'parent' | 'staff' | 'general'
|
||||
}
|
||||
|
||||
export default function VideoChatPage() {
|
||||
const [stats, setStats] = useState<CommunicationStats | null>(null)
|
||||
const [activeMeetings, setActiveMeetings] = useState<ActiveMeeting[]>([])
|
||||
const [recentRooms, setRecentRooms] = useState<RecentRoom[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const moduleInfo = getModuleByHref('/communication/video-chat')
|
||||
|
||||
// Use local API proxy
|
||||
const fetchStats = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch('/api/admin/communication/stats')
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`)
|
||||
}
|
||||
const data = await response.json()
|
||||
setStats(data)
|
||||
setActiveMeetings(data.active_meetings || [])
|
||||
setRecentRooms(data.recent_rooms || [])
|
||||
setError(null)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Verbindungsfehler')
|
||||
// Set mock data for display purposes when API unavailable
|
||||
setStats({
|
||||
matrix: {
|
||||
total_users: 0,
|
||||
active_users: 0,
|
||||
total_rooms: 0,
|
||||
active_rooms: 0,
|
||||
messages_today: 0,
|
||||
messages_this_week: 0,
|
||||
status: 'offline'
|
||||
},
|
||||
jitsi: {
|
||||
active_meetings: 0,
|
||||
total_participants: 0,
|
||||
meetings_today: 0,
|
||||
average_duration_minutes: 0,
|
||||
peak_concurrent_users: 0,
|
||||
total_minutes_today: 0,
|
||||
status: 'offline'
|
||||
},
|
||||
last_updated: new Date().toISOString()
|
||||
})
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchStats()
|
||||
}, [fetchStats])
|
||||
|
||||
// Auto-refresh every 15 seconds
|
||||
useEffect(() => {
|
||||
const interval = setInterval(fetchStats, 15000)
|
||||
return () => clearInterval(interval)
|
||||
}, [fetchStats])
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
const baseClasses = 'px-3 py-1 rounded-full text-xs font-semibold uppercase'
|
||||
switch (status) {
|
||||
case 'online':
|
||||
return `${baseClasses} bg-green-100 text-green-800`
|
||||
case 'degraded':
|
||||
return `${baseClasses} bg-yellow-100 text-yellow-800`
|
||||
case 'offline':
|
||||
return `${baseClasses} bg-red-100 text-red-800`
|
||||
default:
|
||||
return `${baseClasses} bg-slate-100 text-slate-600`
|
||||
}
|
||||
}
|
||||
|
||||
const getRoomTypeBadge = (type: string) => {
|
||||
const baseClasses = 'px-2 py-0.5 rounded text-xs font-medium'
|
||||
switch (type) {
|
||||
case 'class':
|
||||
return `${baseClasses} bg-blue-100 text-blue-700`
|
||||
case 'parent':
|
||||
return `${baseClasses} bg-purple-100 text-purple-700`
|
||||
case 'staff':
|
||||
return `${baseClasses} bg-orange-100 text-orange-700`
|
||||
default:
|
||||
return `${baseClasses} bg-slate-100 text-slate-600`
|
||||
}
|
||||
}
|
||||
|
||||
const formatDuration = (minutes: number) => {
|
||||
if (minutes < 60) return `${Math.round(minutes)} Min.`
|
||||
const hours = Math.floor(minutes / 60)
|
||||
const mins = Math.round(minutes % 60)
|
||||
return `${hours}h ${mins}m`
|
||||
}
|
||||
|
||||
const formatTimeAgo = (dateStr: string) => {
|
||||
const date = new Date(dateStr)
|
||||
const now = new Date()
|
||||
const diffMs = now.getTime() - date.getTime()
|
||||
const diffMins = Math.floor(diffMs / 60000)
|
||||
|
||||
if (diffMins < 1) return 'gerade eben'
|
||||
if (diffMins < 60) return `vor ${diffMins} Min.`
|
||||
if (diffMins < 1440) return `vor ${Math.floor(diffMins / 60)} Std.`
|
||||
return `vor ${Math.floor(diffMins / 1440)} Tagen`
|
||||
}
|
||||
|
||||
// Traffic estimation helpers for SysEleven planning
|
||||
const calculateEstimatedTraffic = (direction: 'in' | 'out'): number => {
|
||||
const messages = stats?.matrix?.messages_today || 0
|
||||
const callMinutes = stats?.jitsi?.total_minutes_today || 0
|
||||
const participants = stats?.jitsi?.total_participants || 0
|
||||
|
||||
const messageTrafficMB = messages * 0.002
|
||||
const videoTrafficMB = callMinutes * participants * 0.011
|
||||
|
||||
if (direction === 'in') {
|
||||
return messageTrafficMB * 0.3 + videoTrafficMB * 0.4
|
||||
}
|
||||
return messageTrafficMB * 0.7 + videoTrafficMB * 0.6
|
||||
}
|
||||
|
||||
const calculateHourlyEstimate = (): number => {
|
||||
const activeParticipants = stats?.jitsi?.total_participants || 0
|
||||
return activeParticipants * 0.675
|
||||
}
|
||||
|
||||
const calculateMonthlyEstimate = (): number => {
|
||||
const dailyCallMinutes = stats?.jitsi?.total_minutes_today || 0
|
||||
const avgParticipants = stats?.jitsi?.peak_concurrent_users || 1
|
||||
const monthlyMinutes = dailyCallMinutes * 22
|
||||
return (monthlyMinutes * avgParticipants * 11) / 1024
|
||||
}
|
||||
|
||||
const getResourceRecommendation = (): string => {
|
||||
const peakUsers = stats?.jitsi?.peak_concurrent_users || 0
|
||||
const monthlyGB = calculateMonthlyEstimate()
|
||||
|
||||
if (monthlyGB < 10 || peakUsers < 5) {
|
||||
return 'Starter (1 vCPU, 2GB RAM, 100GB Traffic)'
|
||||
} else if (monthlyGB < 50 || peakUsers < 20) {
|
||||
return 'Standard (2 vCPU, 4GB RAM, 500GB Traffic)'
|
||||
} else if (monthlyGB < 200 || peakUsers < 50) {
|
||||
return 'Professional (4 vCPU, 8GB RAM, 2TB Traffic)'
|
||||
} else {
|
||||
return 'Enterprise (8+ vCPU, 16GB+ RAM, Unlimited Traffic)'
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Page Purpose */}
|
||||
<PagePurpose
|
||||
title={moduleInfo?.module.name || 'Video & Chat'}
|
||||
purpose={moduleInfo?.module.purpose || 'Matrix & Jitsi Monitoring Dashboard'}
|
||||
audience={moduleInfo?.module.audience || ['Admins', 'DevOps']}
|
||||
architecture={{
|
||||
services: ['synapse (Matrix)', 'jitsi-meet', 'prosody', 'jvb'],
|
||||
databases: ['PostgreSQL', 'synapse-db'],
|
||||
}}
|
||||
collapsible={true}
|
||||
defaultCollapsed={true}
|
||||
/>
|
||||
|
||||
{/* Quick Actions */}
|
||||
<div className="flex gap-3 mb-6">
|
||||
<Link
|
||||
href="/communication/video-chat/wizard"
|
||||
className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors text-sm font-medium"
|
||||
>
|
||||
Test Wizard starten
|
||||
</Link>
|
||||
<button
|
||||
onClick={fetchStats}
|
||||
disabled={loading}
|
||||
className="px-4 py-2 border border-slate-300 rounded-lg hover:bg-slate-50 disabled:opacity-50 text-sm"
|
||||
>
|
||||
{loading ? 'Lade...' : 'Aktualisieren'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Service Status Overview */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
|
||||
{/* Matrix Status Card */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
|
||||
<svg className="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-slate-900">Matrix (Synapse)</h3>
|
||||
<p className="text-sm text-slate-500">E2EE Messaging</p>
|
||||
</div>
|
||||
</div>
|
||||
<span className={getStatusBadge(stats?.matrix.status || 'offline')}>
|
||||
{stats?.matrix.status || 'offline'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<div className="text-2xl font-bold text-slate-900">{stats?.matrix.total_users || 0}</div>
|
||||
<div className="text-xs text-slate-500">Benutzer</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-bold text-slate-900">{stats?.matrix.active_users || 0}</div>
|
||||
<div className="text-xs text-slate-500">Aktiv</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-bold text-slate-900">{stats?.matrix.total_rooms || 0}</div>
|
||||
<div className="text-xs text-slate-500">Raeume</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 pt-4 border-t border-slate-100">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-slate-500">Nachrichten heute</span>
|
||||
<span className="font-medium">{stats?.matrix.messages_today || 0}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm mt-1">
|
||||
<span className="text-slate-500">Diese Woche</span>
|
||||
<span className="font-medium">{stats?.matrix.messages_this_week || 0}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Jitsi Status Card */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
|
||||
<svg className="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-slate-900">Jitsi Meet</h3>
|
||||
<p className="text-sm text-slate-500">Videokonferenzen</p>
|
||||
</div>
|
||||
</div>
|
||||
<span className={getStatusBadge(stats?.jitsi.status || 'offline')}>
|
||||
{stats?.jitsi.status || 'offline'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<div className="text-2xl font-bold text-green-600">{stats?.jitsi.active_meetings || 0}</div>
|
||||
<div className="text-xs text-slate-500">Live Calls</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-bold text-slate-900">{stats?.jitsi.total_participants || 0}</div>
|
||||
<div className="text-xs text-slate-500">Teilnehmer</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-bold text-slate-900">{stats?.jitsi.meetings_today || 0}</div>
|
||||
<div className="text-xs text-slate-500">Calls heute</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 pt-4 border-t border-slate-100">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-slate-500">Durchschnittliche Dauer</span>
|
||||
<span className="font-medium">{formatDuration(stats?.jitsi.average_duration_minutes || 0)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm mt-1">
|
||||
<span className="text-slate-500">Peak gleichzeitig</span>
|
||||
<span className="font-medium">{stats?.jitsi.peak_concurrent_users || 0} Nutzer</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Traffic & Bandwidth Statistics */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6 mb-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 bg-emerald-100 rounded-lg flex items-center justify-center">
|
||||
<svg className="w-6 h-6 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-slate-900">Traffic & Bandbreite</h3>
|
||||
<p className="text-sm text-slate-500">SysEleven Ressourcenplanung</p>
|
||||
</div>
|
||||
</div>
|
||||
<span className="px-3 py-1 rounded-full text-xs font-semibold uppercase bg-emerald-100 text-emerald-800">
|
||||
Live
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
|
||||
<div className="bg-slate-50 rounded-lg p-4">
|
||||
<div className="text-xs text-slate-500 mb-1">Eingehend (heute)</div>
|
||||
<div className="text-2xl font-bold text-slate-900">
|
||||
{stats?.traffic?.total?.bandwidth_in_mb?.toFixed(1) || calculateEstimatedTraffic('in').toFixed(1)} MB
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-slate-50 rounded-lg p-4">
|
||||
<div className="text-xs text-slate-500 mb-1">Ausgehend (heute)</div>
|
||||
<div className="text-2xl font-bold text-slate-900">
|
||||
{stats?.traffic?.total?.bandwidth_out_mb?.toFixed(1) || calculateEstimatedTraffic('out').toFixed(1)} MB
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-slate-50 rounded-lg p-4">
|
||||
<div className="text-xs text-slate-500 mb-1">Geschaetzt/Stunde</div>
|
||||
<div className="text-2xl font-bold text-blue-600">
|
||||
{stats?.traffic?.jitsi?.estimated_hourly_gb?.toFixed(2) || calculateHourlyEstimate().toFixed(2)} GB
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-slate-50 rounded-lg p-4">
|
||||
<div className="text-xs text-slate-500 mb-1">Geschaetzt/Monat</div>
|
||||
<div className="text-2xl font-bold text-emerald-600">
|
||||
{stats?.traffic?.total?.estimated_monthly_gb?.toFixed(1) || calculateMonthlyEstimate().toFixed(1)} GB
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{/* Matrix Traffic */}
|
||||
<div className="border border-slate-200 rounded-lg p-4">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<div className="w-3 h-3 bg-purple-500 rounded-full"></div>
|
||||
<span className="text-sm font-medium text-slate-700">Matrix Messaging</span>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-500">Nachrichten/Min</span>
|
||||
<span className="font-medium">{stats?.traffic?.matrix?.messages_per_minute || Math.round((stats?.matrix?.messages_today || 0) / (new Date().getHours() || 1) / 60)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-500">Media Uploads heute</span>
|
||||
<span className="font-medium">{stats?.traffic?.matrix?.media_uploads_today || 0}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-500">Media Groesse</span>
|
||||
<span className="font-medium">{stats?.traffic?.matrix?.media_size_mb?.toFixed(1) || '0.0'} MB</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Jitsi Traffic */}
|
||||
<div className="border border-slate-200 rounded-lg p-4">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<div className="w-3 h-3 bg-blue-500 rounded-full"></div>
|
||||
<span className="text-sm font-medium text-slate-700">Jitsi Video</span>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-500">Video Streams aktiv</span>
|
||||
<span className="font-medium">{stats?.traffic?.jitsi?.video_streams_active || (stats?.jitsi?.total_participants || 0)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-500">Audio Streams aktiv</span>
|
||||
<span className="font-medium">{stats?.traffic?.jitsi?.audio_streams_active || (stats?.jitsi?.total_participants || 0)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-500">Bitrate geschaetzt</span>
|
||||
<span className="font-medium">{((stats?.jitsi?.total_participants || 0) * 1.5).toFixed(1)} Mbps</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* SysEleven Recommendation */}
|
||||
<div className="mt-4 p-4 bg-emerald-50 border border-emerald-200 rounded-lg">
|
||||
<h4 className="text-sm font-semibold text-emerald-800 mb-2">SysEleven Empfehlung</h4>
|
||||
<div className="text-sm text-emerald-700">
|
||||
<p>Basierend auf aktuellem Traffic: <strong>{getResourceRecommendation()}</strong></p>
|
||||
<p className="mt-1 text-xs text-emerald-600">
|
||||
Peak Teilnehmer: {stats?.jitsi?.peak_concurrent_users || 0} |
|
||||
Durchschnittliche Call-Dauer: {stats?.jitsi?.average_duration_minutes?.toFixed(0) || 0} Min. |
|
||||
Calls heute: {stats?.jitsi?.meetings_today || 0}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Active Meetings */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6 mb-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="font-semibold text-slate-900">Aktive Meetings</h3>
|
||||
</div>
|
||||
|
||||
{activeMeetings.length === 0 ? (
|
||||
<div className="text-center py-8 text-slate-500">
|
||||
<svg className="w-12 h-12 mx-auto mb-3 text-slate-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<p>Keine aktiven Meetings</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="text-left text-xs text-slate-500 uppercase border-b border-slate-200">
|
||||
<th className="pb-3 pr-4">Meeting</th>
|
||||
<th className="pb-3 pr-4">Teilnehmer</th>
|
||||
<th className="pb-3 pr-4">Gestartet</th>
|
||||
<th className="pb-3">Dauer</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{activeMeetings.map((meeting, idx) => (
|
||||
<tr key={idx} className="text-sm">
|
||||
<td className="py-3 pr-4">
|
||||
<div className="font-medium text-slate-900">{meeting.display_name}</div>
|
||||
<div className="text-xs text-slate-500">{meeting.room_name}</div>
|
||||
</td>
|
||||
<td className="py-3 pr-4">
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<span className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
|
||||
{meeting.participants}
|
||||
</span>
|
||||
</td>
|
||||
<td className="py-3 pr-4 text-slate-500">{formatTimeAgo(meeting.started_at)}</td>
|
||||
<td className="py-3 font-medium">{formatDuration(meeting.duration_minutes)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Recent Chat Rooms & Usage Stats */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<h3 className="font-semibold text-slate-900 mb-4">Aktive Chat-Raeume</h3>
|
||||
|
||||
{recentRooms.length === 0 ? (
|
||||
<div className="text-center py-6 text-slate-500">
|
||||
<p>Keine aktiven Raeume</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{recentRooms.slice(0, 5).map((room, idx) => (
|
||||
<div key={idx} className="flex items-center justify-between p-3 bg-slate-50 rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-slate-200 rounded-lg flex items-center justify-center">
|
||||
<svg className="w-4 h-4 text-slate-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-medium text-slate-900 text-sm">{room.name}</div>
|
||||
<div className="text-xs text-slate-500">{room.member_count} Mitglieder</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={getRoomTypeBadge(room.room_type)}>{room.room_type}</span>
|
||||
<span className="text-xs text-slate-400">{formatTimeAgo(room.last_activity)}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Usage Statistics */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<h3 className="font-semibold text-slate-900 mb-4">Nutzungsstatistiken</h3>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<div className="flex justify-between text-sm mb-1">
|
||||
<span className="text-slate-600">Call-Minuten heute</span>
|
||||
<span className="font-semibold">{stats?.jitsi.total_minutes_today || 0} Min.</span>
|
||||
</div>
|
||||
<div className="w-full bg-slate-100 rounded-full h-2">
|
||||
<div
|
||||
className="bg-blue-600 h-2 rounded-full transition-all"
|
||||
style={{ width: `${Math.min((stats?.jitsi.total_minutes_today || 0) / 500 * 100, 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex justify-between text-sm mb-1">
|
||||
<span className="text-slate-600">Aktive Chat-Raeume</span>
|
||||
<span className="font-semibold">{stats?.matrix.active_rooms || 0} / {stats?.matrix.total_rooms || 0}</span>
|
||||
</div>
|
||||
<div className="w-full bg-slate-100 rounded-full h-2">
|
||||
<div
|
||||
className="bg-purple-600 h-2 rounded-full transition-all"
|
||||
style={{ width: `${stats?.matrix.total_rooms ? ((stats.matrix.active_rooms / stats.matrix.total_rooms) * 100) : 0}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex justify-between text-sm mb-1">
|
||||
<span className="text-slate-600">Aktive Nutzer</span>
|
||||
<span className="font-semibold">{stats?.matrix.active_users || 0} / {stats?.matrix.total_users || 0}</span>
|
||||
</div>
|
||||
<div className="w-full bg-slate-100 rounded-full h-2">
|
||||
<div
|
||||
className="bg-green-600 h-2 rounded-full transition-all"
|
||||
style={{ width: `${stats?.matrix.total_users ? ((stats.matrix.active_users / stats.matrix.total_users) * 100) : 0}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick Actions */}
|
||||
<div className="mt-6 pt-4 border-t border-slate-100">
|
||||
<h4 className="text-sm font-medium text-slate-700 mb-3">Schnellaktionen</h4>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<a
|
||||
href="http://localhost:8448/_synapse/admin"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="px-3 py-1.5 text-sm bg-purple-100 text-purple-700 rounded-lg hover:bg-purple-200 transition-colors"
|
||||
>
|
||||
Synapse Admin
|
||||
</a>
|
||||
<a
|
||||
href="http://localhost:8443"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="px-3 py-1.5 text-sm bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition-colors"
|
||||
>
|
||||
Jitsi Meet
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Connection Info */}
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
|
||||
<div className="flex gap-3">
|
||||
<svg className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<div>
|
||||
<h4 className="font-semibold text-blue-900">Service Konfiguration</h4>
|
||||
<p className="text-sm text-blue-800 mt-1">
|
||||
<strong>Matrix Homeserver:</strong> http://localhost:8448 (Synapse)<br />
|
||||
<strong>Jitsi Meet:</strong> http://localhost:8443<br />
|
||||
<strong>Auto-Refresh:</strong> Alle 15 Sekunden
|
||||
</p>
|
||||
{error && (
|
||||
<p className="text-sm text-red-600 mt-2">
|
||||
<strong>Fehler:</strong> {error} - Backend nicht erreichbar
|
||||
</p>
|
||||
)}
|
||||
{stats?.last_updated && (
|
||||
<p className="text-xs text-blue-600 mt-2">
|
||||
Letzte Aktualisierung: {new Date(stats.last_updated).toLocaleString('de-DE')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,366 +0,0 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* Video & Chat Wizard Page
|
||||
*
|
||||
* Interactive learning and testing wizard for Matrix & Jitsi integration
|
||||
* Migrated from website/app/admin/communication/wizard
|
||||
*/
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import {
|
||||
WizardStepper,
|
||||
WizardNavigation,
|
||||
EducationCard,
|
||||
ArchitectureContext,
|
||||
TestRunner,
|
||||
TestSummary,
|
||||
type WizardStep,
|
||||
type TestCategoryResult,
|
||||
type FullTestResults,
|
||||
type EducationContent,
|
||||
type ArchitectureContextType,
|
||||
} from '@/components/wizard'
|
||||
|
||||
// ==============================================
|
||||
// Constants
|
||||
// ==============================================
|
||||
|
||||
const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:8000'
|
||||
|
||||
const STEPS: WizardStep[] = [
|
||||
{ id: 'welcome', name: 'Willkommen', icon: '👋', status: 'pending' },
|
||||
{ id: 'api-health', name: 'API Status', icon: '💚', status: 'pending', category: 'api-health' },
|
||||
{ id: 'matrix', name: 'Matrix', icon: '💬', status: 'pending', category: 'matrix' },
|
||||
{ id: 'jitsi', name: 'Jitsi', icon: '📹', status: 'pending', category: 'jitsi' },
|
||||
{ id: 'summary', name: 'Zusammenfassung', icon: '📊', status: 'pending' },
|
||||
]
|
||||
|
||||
const EDUCATION_CONTENT: Record<string, EducationContent> = {
|
||||
'welcome': {
|
||||
title: 'Willkommen zum Video & Chat Wizard',
|
||||
content: [
|
||||
'Sichere Kommunikation ist das Rueckgrat moderner Bildungsplattformen.',
|
||||
'',
|
||||
'BreakPilot nutzt zwei Open-Source Systeme:',
|
||||
'• Matrix Synapse: Dezentraler Messenger (Ende-zu-Ende verschluesselt)',
|
||||
'• Jitsi Meet: Video-Konferenzen (WebRTC-basiert)',
|
||||
'',
|
||||
'Beide Systeme sind DSGVO-konform und self-hosted.',
|
||||
'',
|
||||
'In diesem Wizard testen wir:',
|
||||
'• Matrix Homeserver und Federation',
|
||||
'• Jitsi Video-Konferenz Server',
|
||||
'• Integration mit der Schulverwaltung',
|
||||
],
|
||||
},
|
||||
'api-health': {
|
||||
title: 'Communication API - Backend Integration',
|
||||
content: [
|
||||
'Die Communication API verbindet Matrix und Jitsi mit BreakPilot.',
|
||||
'',
|
||||
'Funktionen:',
|
||||
'• Automatische Raum-Erstellung fuer Klassen',
|
||||
'• Eltern-Lehrer DM-Raeume',
|
||||
'• Meeting-Planung mit Kalender-Integration',
|
||||
'• Benachrichtigungen bei neuen Nachrichten',
|
||||
'',
|
||||
'Endpunkte:',
|
||||
'• /api/v1/communication/admin/stats',
|
||||
'• /api/v1/communication/admin/matrix/users',
|
||||
'• /api/v1/communication/rooms',
|
||||
],
|
||||
},
|
||||
'matrix': {
|
||||
title: 'Matrix Synapse - Dezentraler Messenger',
|
||||
content: [
|
||||
'Matrix ist ein offenes Protokoll fuer sichere Kommunikation.',
|
||||
'',
|
||||
'Vorteile gegenueber WhatsApp/Teams:',
|
||||
'• Ende-zu-Ende Verschluesselung (E2EE)',
|
||||
'• Dezentral: Kein Single Point of Failure',
|
||||
'• Federation: Kommunikation mit anderen Schulen',
|
||||
'• Self-Hosted: Volle Datenkontrolle',
|
||||
'',
|
||||
'Raum-Typen in BreakPilot:',
|
||||
'• Klassen-Info (Ankuendigungen)',
|
||||
'• Elternvertreter-Raum',
|
||||
'• Lehrer-Eltern DM',
|
||||
'• Fachgruppen',
|
||||
],
|
||||
},
|
||||
'jitsi': {
|
||||
title: 'Jitsi Meet - Video-Konferenzen',
|
||||
content: [
|
||||
'Jitsi ist eine Open-Source Alternative zu Zoom/Teams.',
|
||||
'',
|
||||
'Features:',
|
||||
'• WebRTC: Keine Software-Installation noetig',
|
||||
'• Bildschirmfreigabe und Whiteboard',
|
||||
'• Breakout-Raeume fuer Gruppenarbeit',
|
||||
'• Aufzeichnung (optional, lokal)',
|
||||
'',
|
||||
'Anwendungsfaelle:',
|
||||
'• Elternsprechtage (online)',
|
||||
'• Fernunterricht bei Schulausfall',
|
||||
'• Lehrerkonferenzen',
|
||||
'• Foerdergespraeche',
|
||||
],
|
||||
},
|
||||
'summary': {
|
||||
title: 'Test-Zusammenfassung',
|
||||
content: [
|
||||
'Hier sehen Sie eine Uebersicht aller durchgefuehrten Tests:',
|
||||
'• Matrix Homeserver Verfuegbarkeit',
|
||||
'• Jitsi Server Status',
|
||||
'• API-Integration',
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
const ARCHITECTURE_CONTEXTS: Record<string, ArchitectureContextType> = {
|
||||
'api-health': {
|
||||
layer: 'api',
|
||||
services: ['backend', 'consent-service'],
|
||||
dependencies: ['PostgreSQL', 'Matrix Synapse', 'Jitsi'],
|
||||
dataFlow: ['Browser', 'FastAPI', 'Go Service', 'Matrix/Jitsi'],
|
||||
},
|
||||
'matrix': {
|
||||
layer: 'service',
|
||||
services: ['matrix'],
|
||||
dependencies: ['PostgreSQL', 'Federation', 'TURN Server'],
|
||||
dataFlow: ['Element Client', 'Matrix Synapse', 'Federation', 'PostgreSQL'],
|
||||
},
|
||||
'jitsi': {
|
||||
layer: 'service',
|
||||
services: ['jitsi'],
|
||||
dependencies: ['Prosody XMPP', 'JVB', 'TURN/STUN'],
|
||||
dataFlow: ['Browser', 'Nginx', 'Prosody', 'Jitsi Videobridge'],
|
||||
},
|
||||
}
|
||||
|
||||
// ==============================================
|
||||
// Main Component
|
||||
// ==============================================
|
||||
|
||||
export default function VideoChatWizardPage() {
|
||||
const [currentStep, setCurrentStep] = useState(0)
|
||||
const [steps, setSteps] = useState<WizardStep[]>(STEPS)
|
||||
const [categoryResults, setCategoryResults] = useState<Record<string, TestCategoryResult>>({})
|
||||
const [fullResults, setFullResults] = useState<FullTestResults | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const currentStepData = steps[currentStep]
|
||||
const isTestStep = currentStepData?.category !== undefined
|
||||
const isWelcome = currentStepData?.id === 'welcome'
|
||||
const isSummary = currentStepData?.id === 'summary'
|
||||
|
||||
const runCategoryTest = async (category: string) => {
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const response = await fetch(`${BACKEND_URL}/api/admin/communication-tests/${category}`, {
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
|
||||
}
|
||||
|
||||
const result: TestCategoryResult = await response.json()
|
||||
setCategoryResults((prev) => ({ ...prev, [category]: result }))
|
||||
|
||||
setSteps((prev) =>
|
||||
prev.map((step) =>
|
||||
step.category === category
|
||||
? { ...step, status: result.failed === 0 ? 'completed' : 'failed' }
|
||||
: step
|
||||
)
|
||||
)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unbekannter Fehler')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const runAllTests = async () => {
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const response = await fetch(`${BACKEND_URL}/api/admin/communication-tests/run-all`, {
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
|
||||
}
|
||||
|
||||
const results: FullTestResults = await response.json()
|
||||
setFullResults(results)
|
||||
|
||||
setSteps((prev) =>
|
||||
prev.map((step) => {
|
||||
if (step.category) {
|
||||
const catResult = results.categories.find((c) => c.category === step.category)
|
||||
if (catResult) {
|
||||
return { ...step, status: catResult.failed === 0 ? 'completed' : 'failed' }
|
||||
}
|
||||
}
|
||||
return step
|
||||
})
|
||||
)
|
||||
|
||||
const newCategoryResults: Record<string, TestCategoryResult> = {}
|
||||
results.categories.forEach((cat) => {
|
||||
newCategoryResults[cat.category] = cat
|
||||
})
|
||||
setCategoryResults(newCategoryResults)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unbekannter Fehler')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const goToNext = () => {
|
||||
if (currentStep < steps.length - 1) {
|
||||
setSteps((prev) =>
|
||||
prev.map((step, idx) =>
|
||||
idx === currentStep && step.status === 'pending'
|
||||
? { ...step, status: 'completed' }
|
||||
: step
|
||||
)
|
||||
)
|
||||
setCurrentStep((prev) => prev + 1)
|
||||
}
|
||||
}
|
||||
|
||||
const goToPrev = () => {
|
||||
if (currentStep > 0) {
|
||||
setCurrentStep((prev) => prev - 1)
|
||||
}
|
||||
}
|
||||
|
||||
const handleStepClick = (index: number) => {
|
||||
if (index <= currentStep || steps[index - 1]?.status !== 'pending') {
|
||||
setCurrentStep(index)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Header */}
|
||||
<div className="bg-white rounded-lg border border-slate-200 p-4 mb-6 flex items-center justify-between">
|
||||
<div className="flex items-center">
|
||||
<span className="text-3xl mr-3">💬</span>
|
||||
<div>
|
||||
<h2 className="text-lg font-bold text-gray-800">Video & Chat Test Wizard</h2>
|
||||
<p className="text-sm text-gray-600">Matrix Messenger & Jitsi Video</p>
|
||||
</div>
|
||||
</div>
|
||||
<Link href="/communication/video-chat" className="text-blue-600 hover:text-blue-800 text-sm">
|
||||
← Zurueck zu Video & Chat
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Stepper */}
|
||||
<div className="bg-white rounded-lg border border-slate-200 p-6 mb-6">
|
||||
<WizardStepper steps={steps} currentStep={currentStep} onStepClick={handleStepClick} />
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="bg-white rounded-lg border border-slate-200 p-6">
|
||||
<div className="flex items-center mb-6">
|
||||
<span className="text-3xl mr-3">{currentStepData?.icon}</span>
|
||||
<div>
|
||||
<h2 className="text-xl font-bold text-gray-800">
|
||||
Schritt {currentStep + 1}: {currentStepData?.name}
|
||||
</h2>
|
||||
<p className="text-gray-500 text-sm">
|
||||
{currentStep + 1} von {steps.length}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<EducationCard content={EDUCATION_CONTENT[currentStepData?.id || '']} />
|
||||
|
||||
{isTestStep && currentStepData?.category && ARCHITECTURE_CONTEXTS[currentStepData.category] && (
|
||||
<ArchitectureContext
|
||||
context={ARCHITECTURE_CONTEXTS[currentStepData.category]}
|
||||
currentStep={currentStepData.name}
|
||||
/>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 rounded-lg p-4 mb-6">
|
||||
<strong>Fehler:</strong> {error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isWelcome && (
|
||||
<div className="text-center py-8">
|
||||
<button
|
||||
onClick={goToNext}
|
||||
className="bg-blue-600 text-white px-8 py-3 rounded-lg font-medium hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
Wizard starten
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isTestStep && currentStepData?.category && (
|
||||
<TestRunner
|
||||
category={currentStepData.category}
|
||||
categoryResult={categoryResults[currentStepData.category]}
|
||||
isLoading={isLoading}
|
||||
onRunTests={() => runCategoryTest(currentStepData.category!)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isSummary && (
|
||||
<div>
|
||||
{!fullResults ? (
|
||||
<div className="text-center py-8">
|
||||
<p className="text-gray-600 mb-4">
|
||||
Fuehren Sie alle Tests aus um eine Zusammenfassung zu sehen.
|
||||
</p>
|
||||
<button
|
||||
onClick={runAllTests}
|
||||
disabled={isLoading}
|
||||
className={`px-6 py-3 rounded-lg font-medium transition-colors ${
|
||||
isLoading
|
||||
? 'bg-gray-400 cursor-not-allowed'
|
||||
: 'bg-blue-600 text-white hover:bg-blue-700'
|
||||
}`}
|
||||
>
|
||||
{isLoading ? 'Alle Tests laufen...' : 'Alle Tests ausfuehren'}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<TestSummary results={fullResults} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<WizardNavigation
|
||||
currentStep={currentStep}
|
||||
totalSteps={steps.length}
|
||||
onPrev={goToPrev}
|
||||
onNext={goToNext}
|
||||
showNext={!isSummary}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="text-center text-gray-500 text-sm mt-6">
|
||||
Diese Tests pruefen die Matrix- und Jitsi-Integration.
|
||||
Bei Fragen wenden Sie sich an das IT-Team.
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -24,7 +24,6 @@ export default function DevelopmentPage() {
|
||||
}}
|
||||
relatedPages={[
|
||||
{ name: 'GPU Infrastruktur', href: '/infrastructure/gpu', description: 'GPU fuer Voice/Game' },
|
||||
{ name: 'LLM Vergleich', href: '/ai/llm-compare', description: 'LLM fuer Voice/Game' },
|
||||
]}
|
||||
collapsible={true}
|
||||
defaultCollapsed={false}
|
||||
|
||||
@@ -149,7 +149,6 @@ const ADMIN_SCREENS: ScreenDefinition[] = [
|
||||
{ id: 'admin-obligations', name: 'Pflichten', description: 'NIS2, DSGVO, AI Act', category: 'sdk', icon: '⚡', url: '/sdk/obligations' },
|
||||
|
||||
// === KI & AUTOMATISIERUNG (Teal #14b8a6) ===
|
||||
{ id: 'admin-llm-compare', name: 'LLM Vergleich', description: 'KI-Provider Vergleich', category: 'ai', icon: '🤖', url: '/ai/llm-compare' },
|
||||
{ id: 'admin-rag', name: 'Daten & RAG', description: 'Training Data & RAG', category: 'ai', icon: '🗄️', url: '/ai/rag' },
|
||||
{ id: 'admin-ocr-labeling', name: 'OCR-Labeling', description: 'Handschrift-Training', category: 'ai', icon: '✍️', url: '/ai/ocr-labeling' },
|
||||
{ id: 'admin-magic-help', name: 'Magic Help', description: 'TrOCR Handschrift-OCR', category: 'ai', icon: '🪄', url: '/ai/magic-help' },
|
||||
@@ -196,7 +195,6 @@ const ADMIN_CONNECTIONS: ConnectionDef[] = [
|
||||
{ source: 'admin-dashboard', target: 'admin-backlog', label: 'Go-Live' },
|
||||
{ source: 'admin-dashboard', target: 'admin-compliance-hub', label: 'Compliance' },
|
||||
{ source: 'admin-onboarding', target: 'admin-consent' },
|
||||
{ source: 'admin-onboarding', target: 'admin-llm-compare' },
|
||||
{ source: 'admin-rbac', target: 'admin-consent' },
|
||||
|
||||
// === DSGVO FLOW ===
|
||||
@@ -224,7 +222,6 @@ const ADMIN_CONNECTIONS: ConnectionDef[] = [
|
||||
{ source: 'admin-dsms', target: 'admin-compliance-workflow' },
|
||||
|
||||
// === KI & AUTOMATISIERUNG FLOW ===
|
||||
{ source: 'admin-llm-compare', target: 'admin-rag', label: 'Daten' },
|
||||
{ source: 'admin-rag', target: 'admin-quality' },
|
||||
{ source: 'admin-rag', target: 'admin-agents' },
|
||||
{ source: 'admin-ocr-labeling', target: 'admin-magic-help', label: 'Training' },
|
||||
|
||||
@@ -1,665 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import {
|
||||
GitBranch,
|
||||
Terminal,
|
||||
Server,
|
||||
Database,
|
||||
CheckCircle2,
|
||||
ArrowRight,
|
||||
Laptop,
|
||||
HardDrive,
|
||||
RefreshCw,
|
||||
Clock,
|
||||
Shield,
|
||||
Users,
|
||||
FileCode,
|
||||
Play,
|
||||
Eye,
|
||||
Download,
|
||||
AlertTriangle,
|
||||
Info,
|
||||
Container
|
||||
} from 'lucide-react'
|
||||
|
||||
interface WorkflowStep {
|
||||
id: number
|
||||
title: string
|
||||
description: string
|
||||
command?: string
|
||||
icon: React.ReactNode
|
||||
location: 'macbook' | 'macmini'
|
||||
}
|
||||
|
||||
interface BackupInfo {
|
||||
lastRun: string | null
|
||||
nextRun: string
|
||||
status: 'ok' | 'warning' | 'error'
|
||||
}
|
||||
|
||||
export default function WorkflowPage() {
|
||||
const [activeStep, setActiveStep] = useState<number>(1)
|
||||
const [backupInfo, setBackupInfo] = useState<BackupInfo>({
|
||||
lastRun: null,
|
||||
nextRun: '02:00 Uhr',
|
||||
status: 'ok'
|
||||
})
|
||||
|
||||
const workflowSteps: WorkflowStep[] = [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Code bearbeiten',
|
||||
description: 'Arbeite mit Claude Code im Terminal. Beschreibe was du brauchst und Claude schreibt den Code.',
|
||||
command: 'claude',
|
||||
icon: <Terminal className="h-6 w-6" />,
|
||||
location: 'macbook'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'Änderungen stagen',
|
||||
description: 'Füge die geänderten Dateien zum nächsten Commit hinzu.',
|
||||
command: 'git add <dateien>',
|
||||
icon: <FileCode className="h-6 w-6" />,
|
||||
location: 'macbook'
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: 'Commit erstellen',
|
||||
description: 'Erstelle einen Commit mit einer aussagekräftigen Nachricht.',
|
||||
command: 'git commit -m "feat: neue Funktion"',
|
||||
icon: <GitBranch className="h-6 w-6" />,
|
||||
location: 'macbook'
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
title: 'Push zum Server',
|
||||
description: 'Sende die Änderungen an den Mac Mini. Dies startet automatisch die CI/CD Pipeline.',
|
||||
command: 'git push origin main',
|
||||
icon: <ArrowRight className="h-6 w-6" />,
|
||||
location: 'macbook'
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
title: 'CI/CD Pipeline',
|
||||
description: 'Woodpecker führt automatisch Tests aus und baut die Container.',
|
||||
command: '(automatisch)',
|
||||
icon: <RefreshCw className="h-6 w-6" />,
|
||||
location: 'macmini'
|
||||
},
|
||||
{
|
||||
id: 6,
|
||||
title: 'Integration Tests',
|
||||
description: 'Docker Compose Test-Umgebung mit Backend, DB und Consent-Service fuer vollstaendige E2E-Tests.',
|
||||
command: 'docker compose -f docker-compose.test.yml up -d',
|
||||
icon: <Container className="h-6 w-6" />,
|
||||
location: 'macmini'
|
||||
},
|
||||
{
|
||||
id: 7,
|
||||
title: 'Frontend testen',
|
||||
description: 'Teste die Änderungen im Browser auf dem Mac Mini.',
|
||||
command: 'http://macmini:3000',
|
||||
icon: <Eye className="h-6 w-6" />,
|
||||
location: 'macbook'
|
||||
}
|
||||
]
|
||||
|
||||
const services = [
|
||||
{ name: 'Website', url: 'http://macmini:3000', port: 3000, status: 'running' },
|
||||
{ name: 'Admin v2', url: 'http://macmini:3002', port: 3002, status: 'running' },
|
||||
{ name: 'Studio v2', url: 'http://macmini:3001', port: 3001, status: 'running' },
|
||||
{ name: 'Backend', url: 'http://macmini:8000', port: 8000, status: 'running' },
|
||||
{ name: 'Gitea', url: 'http://macmini:3003', port: 3003, status: 'running' },
|
||||
{ name: 'Klausur-Service', url: 'http://macmini:8086', port: 8086, status: 'running' },
|
||||
]
|
||||
|
||||
const commitTypes = [
|
||||
{ type: 'feat:', description: 'Neue Funktion', example: 'feat: add user login' },
|
||||
{ type: 'fix:', description: 'Bugfix', example: 'fix: resolve login timeout' },
|
||||
{ type: 'docs:', description: 'Dokumentation', example: 'docs: update API docs' },
|
||||
{ type: 'style:', description: 'Formatierung', example: 'style: fix indentation' },
|
||||
{ type: 'refactor:', description: 'Code-Umbau', example: 'refactor: extract helper' },
|
||||
{ type: 'test:', description: 'Tests', example: 'test: add unit tests' },
|
||||
{ type: 'chore:', description: 'Wartung', example: 'chore: update deps' },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{/* Header */}
|
||||
<div className="bg-gradient-to-r from-indigo-600 to-purple-600 rounded-2xl p-8 text-white">
|
||||
<h1 className="text-3xl font-bold mb-2">Entwicklungs-Workflow</h1>
|
||||
<p className="text-indigo-100">
|
||||
Wie wir bei BreakPilot entwickeln - von der Idee bis zum Deployment
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Architecture Overview */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<h2 className="text-xl font-semibold text-slate-900 mb-4 flex items-center gap-2">
|
||||
<Server className="h-5 w-5 text-indigo-600" />
|
||||
Systemarchitektur
|
||||
</h2>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* MacBook */}
|
||||
<div className="bg-slate-50 rounded-xl p-5 border-2 border-slate-200">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="p-2 bg-blue-100 rounded-lg">
|
||||
<Laptop className="h-6 w-6 text-blue-600" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-slate-900">MacBook (Entwicklung)</h3>
|
||||
<p className="text-sm text-slate-500">Dein Arbeitsplatz</p>
|
||||
</div>
|
||||
</div>
|
||||
<ul className="space-y-2 text-sm">
|
||||
<li className="flex items-center gap-2">
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
<span>Terminal + Claude Code</span>
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
<span>Lokales Git Repository</span>
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
<span>Browser für Frontend-Tests</span>
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-4 w-4 text-amber-500" />
|
||||
<span>Backup manuell (MacBook nachts aus)</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Mac Mini */}
|
||||
<div className="bg-slate-50 rounded-xl p-5 border-2 border-indigo-200">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="p-2 bg-indigo-100 rounded-lg">
|
||||
<HardDrive className="h-6 w-6 text-indigo-600" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-slate-900">Mac Mini (Server)</h3>
|
||||
<p className="text-sm text-slate-500">192.168.178.100</p>
|
||||
</div>
|
||||
</div>
|
||||
<ul className="space-y-2 text-sm">
|
||||
<li className="flex items-center gap-2">
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
<span>Gitea (Git Server)</span>
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
<span>Woodpecker (CI/CD)</span>
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
<span>Docker Container (alle Services)</span>
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
<span>PostgreSQL Datenbank</span>
|
||||
</li>
|
||||
<li className="flex items-center gap-2">
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
<span>Automatisches Backup (02:00 Uhr lokal)</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Workflow Steps */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<h2 className="text-xl font-semibold text-slate-900 mb-6 flex items-center gap-2">
|
||||
<Play className="h-5 w-5 text-indigo-600" />
|
||||
Entwicklungs-Schritte
|
||||
</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
{workflowSteps.map((step, index) => (
|
||||
<div
|
||||
key={step.id}
|
||||
className={`relative flex items-start gap-4 p-4 rounded-xl transition-all cursor-pointer ${
|
||||
activeStep === step.id
|
||||
? 'bg-indigo-50 border-2 border-indigo-300'
|
||||
: 'bg-slate-50 border-2 border-transparent hover:border-slate-200'
|
||||
}`}
|
||||
onClick={() => setActiveStep(step.id)}
|
||||
>
|
||||
{/* Step Number */}
|
||||
<div className={`flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center font-bold ${
|
||||
activeStep === step.id
|
||||
? 'bg-indigo-600 text-white'
|
||||
: 'bg-slate-200 text-slate-600'
|
||||
}`}>
|
||||
{step.id}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-grow">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h3 className="font-semibold text-slate-900">{step.title}</h3>
|
||||
<span className={`text-xs px-2 py-0.5 rounded-full ${
|
||||
step.location === 'macbook'
|
||||
? 'bg-blue-100 text-blue-700'
|
||||
: 'bg-purple-100 text-purple-700'
|
||||
}`}>
|
||||
{step.location === 'macbook' ? 'MacBook' : 'Mac Mini'}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-slate-600 mb-2">{step.description}</p>
|
||||
{step.command && (
|
||||
<code className="text-xs bg-slate-800 text-green-400 px-3 py-1.5 rounded-lg font-mono">
|
||||
{step.command}
|
||||
</code>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Icon */}
|
||||
<div className={`flex-shrink-0 p-2 rounded-lg ${
|
||||
activeStep === step.id ? 'bg-indigo-100 text-indigo-600' : 'bg-slate-100 text-slate-400'
|
||||
}`}>
|
||||
{step.icon}
|
||||
</div>
|
||||
|
||||
{/* Connector Line */}
|
||||
{index < workflowSteps.length - 1 && (
|
||||
<div className="absolute left-9 top-14 w-0.5 h-8 bg-slate-200" />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Services & URLs */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<h2 className="text-xl font-semibold text-slate-900 mb-4 flex items-center gap-2">
|
||||
<Eye className="h-5 w-5 text-indigo-600" />
|
||||
Services & URLs zum Testen
|
||||
</h2>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
|
||||
{services.map((service) => (
|
||||
<a
|
||||
key={service.name}
|
||||
href={service.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center justify-between p-4 bg-slate-50 rounded-lg hover:bg-slate-100 transition-colors border border-slate-200"
|
||||
>
|
||||
<div>
|
||||
<h3 className="font-medium text-slate-900">{service.name}</h3>
|
||||
<p className="text-sm text-slate-500">Port {service.port}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
|
||||
<ArrowRight className="h-4 w-4 text-slate-400" />
|
||||
</div>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Commit Convention */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<h2 className="text-xl font-semibold text-slate-900 mb-4 flex items-center gap-2">
|
||||
<GitBranch className="h-5 w-5 text-indigo-600" />
|
||||
Commit-Konventionen
|
||||
</h2>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
|
||||
{commitTypes.map((item) => (
|
||||
<div key={item.type} className="bg-slate-50 rounded-lg p-3 border border-slate-200">
|
||||
<code className="text-sm font-bold text-indigo-600">{item.type}</code>
|
||||
<p className="text-sm text-slate-600 mt-1">{item.description}</p>
|
||||
<p className="text-xs text-slate-400 mt-1 font-mono">{item.example}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Backup Info */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<h2 className="text-xl font-semibold text-slate-900 mb-4 flex items-center gap-2">
|
||||
<Shield className="h-5 w-5 text-indigo-600" />
|
||||
Backup & Sicherheit
|
||||
</h2>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
{/* Mac Mini - Automatisches lokales Backup */}
|
||||
<div className="bg-green-50 rounded-xl p-5 border border-green-200">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<Clock className="h-5 w-5 text-green-600" />
|
||||
<h3 className="font-semibold text-green-900">Mac Mini (Auto)</h3>
|
||||
</div>
|
||||
<ul className="space-y-2 text-sm text-green-800">
|
||||
<li>• Automatisch um 02:00 Uhr</li>
|
||||
<li>• PostgreSQL-Dump lokal</li>
|
||||
<li>• Git Repository gesichert</li>
|
||||
<li>• 7 Tage Aufbewahrung</li>
|
||||
</ul>
|
||||
<div className="mt-4 p-3 bg-green-100 rounded-lg">
|
||||
<code className="text-xs text-green-700 font-mono">
|
||||
~/Projekte/backup-logs/
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* MacBook - Manuelles Backup */}
|
||||
<div className="bg-amber-50 rounded-xl p-5 border border-amber-200">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<AlertTriangle className="h-5 w-5 text-amber-600" />
|
||||
<h3 className="font-semibold text-amber-900">MacBook (Manuell)</h3>
|
||||
</div>
|
||||
<ul className="space-y-2 text-sm text-amber-800">
|
||||
<li>• MacBook nachts aus (02:00)</li>
|
||||
<li>• Keine Auto-Synchronisation</li>
|
||||
<li>• Backup manuell anstoßen</li>
|
||||
</ul>
|
||||
<div className="mt-4 p-3 bg-amber-100 rounded-lg">
|
||||
<code className="text-xs text-amber-700 font-mono">
|
||||
rsync -avz macmini:~/Projekte/ ~/Projekte/
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Manuelles Backup starten */}
|
||||
<div className="bg-blue-50 rounded-xl p-5 border border-blue-200">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<Download className="h-5 w-5 text-blue-600" />
|
||||
<h3 className="font-semibold text-blue-900">Backup Script</h3>
|
||||
</div>
|
||||
<p className="text-sm text-blue-800 mb-3">
|
||||
Backup jederzeit manuell starten:
|
||||
</p>
|
||||
<code className="block text-xs bg-slate-800 text-green-400 p-3 rounded-lg font-mono">
|
||||
~/Projekte/breakpilot-pwa/scripts/daily-backup.sh
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick Commands */}
|
||||
<div className="bg-slate-800 rounded-xl p-6 text-white">
|
||||
<h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
|
||||
<Terminal className="h-5 w-5 text-green-400" />
|
||||
Wichtige Befehle
|
||||
</h2>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 font-mono text-sm">
|
||||
<div className="bg-slate-900 rounded-lg p-4">
|
||||
<p className="text-slate-400 mb-2"># CI/CD Logs ansehen</p>
|
||||
<code className="text-green-400">ssh macmini "docker logs breakpilot-pwa-backend --tail 50"</code>
|
||||
</div>
|
||||
<div className="bg-slate-900 rounded-lg p-4">
|
||||
<p className="text-slate-400 mb-2"># Container neu starten</p>
|
||||
<code className="text-green-400">ssh macmini "docker compose restart backend"</code>
|
||||
</div>
|
||||
<div className="bg-slate-900 rounded-lg p-4">
|
||||
<p className="text-slate-400 mb-2"># Alle Container Status</p>
|
||||
<code className="text-green-400">ssh macmini "docker ps"</code>
|
||||
</div>
|
||||
<div className="bg-slate-900 rounded-lg p-4">
|
||||
<p className="text-slate-400 mb-2"># Pipeline Status (Gitea)</p>
|
||||
<code className="text-green-400">open http://macmini:3003</code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Team Workflow with Feature Branches */}
|
||||
<div className="bg-indigo-50 rounded-xl border border-indigo-200 p-6">
|
||||
<h2 className="text-xl font-semibold text-indigo-900 mb-4 flex items-center gap-2">
|
||||
<GitBranch className="h-5 w-5 text-indigo-600" />
|
||||
Team-Workflow (3+ Entwickler)
|
||||
</h2>
|
||||
|
||||
<div className="bg-white rounded-xl p-5 mb-4">
|
||||
<h3 className="font-semibold text-slate-900 mb-3">Feature Branch Workflow</h3>
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<code className="bg-slate-100 px-2 py-1 rounded">main</code>
|
||||
<ArrowRight className="h-4 w-4 text-slate-400" />
|
||||
<code className="bg-blue-100 text-blue-700 px-2 py-1 rounded">feature/neue-funktion</code>
|
||||
<ArrowRight className="h-4 w-4 text-slate-400" />
|
||||
<span className="text-slate-600">Entwicklung</span>
|
||||
<ArrowRight className="h-4 w-4 text-slate-400" />
|
||||
<span className="bg-purple-100 text-purple-700 px-2 py-1 rounded">Pull Request</span>
|
||||
<ArrowRight className="h-4 w-4 text-slate-400" />
|
||||
<span className="bg-green-100 text-green-700 px-2 py-1 rounded">Code Review</span>
|
||||
<ArrowRight className="h-4 w-4 text-slate-400" />
|
||||
<code className="bg-slate-100 px-2 py-1 rounded">main</code>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="bg-white rounded-lg p-4 border border-indigo-100">
|
||||
<h4 className="font-medium text-slate-900 mb-2">1. Feature Branch erstellen</h4>
|
||||
<code className="block text-xs bg-slate-800 text-green-400 p-2 rounded font-mono">
|
||||
git checkout -b feature/mein-feature
|
||||
</code>
|
||||
</div>
|
||||
<div className="bg-white rounded-lg p-4 border border-indigo-100">
|
||||
<h4 className="font-medium text-slate-900 mb-2">2. Änderungen committen</h4>
|
||||
<code className="block text-xs bg-slate-800 text-green-400 p-2 rounded font-mono">
|
||||
git commit -m "feat: beschreibung"
|
||||
</code>
|
||||
</div>
|
||||
<div className="bg-white rounded-lg p-4 border border-indigo-100">
|
||||
<h4 className="font-medium text-slate-900 mb-2">3. Branch pushen</h4>
|
||||
<code className="block text-xs bg-slate-800 text-green-400 p-2 rounded font-mono">
|
||||
git push -u origin feature/mein-feature
|
||||
</code>
|
||||
</div>
|
||||
<div className="bg-white rounded-lg p-4 border border-indigo-100">
|
||||
<h4 className="font-medium text-slate-900 mb-2">4. Pull Request in Gitea</h4>
|
||||
<code className="block text-xs bg-slate-800 text-green-400 p-2 rounded font-mono">
|
||||
http://macmini:3003 → Pull Request
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 p-4 bg-indigo-100 rounded-lg">
|
||||
<h4 className="font-medium text-indigo-900 mb-2">Branch-Namenskonvention</h4>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-2 text-sm">
|
||||
<div><code className="text-indigo-700">feature/</code> Neue Funktion</div>
|
||||
<div><code className="text-indigo-700">fix/</code> Bugfix</div>
|
||||
<div><code className="text-indigo-700">hotfix/</code> Dringender Fix</div>
|
||||
<div><code className="text-indigo-700">refactor/</code> Code-Umbau</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Team Rules */}
|
||||
<div className="bg-amber-50 rounded-xl border border-amber-200 p-6">
|
||||
<h2 className="text-xl font-semibold text-amber-900 mb-4 flex items-center gap-2">
|
||||
<Users className="h-5 w-5 text-amber-600" />
|
||||
Team-Regeln
|
||||
</h2>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<CheckCircle2 className="h-5 w-5 text-green-600 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h3 className="font-medium text-slate-900">Feature Branches nutzen</h3>
|
||||
<p className="text-sm text-slate-600">Nie direkt auf main pushen - immer über Pull Request</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<CheckCircle2 className="h-5 w-5 text-green-600 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h3 className="font-medium text-slate-900">Code Review erforderlich</h3>
|
||||
<p className="text-sm text-slate-600">Mindestens 1 Approval vor dem Merge</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<CheckCircle2 className="h-5 w-5 text-green-600 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h3 className="font-medium text-slate-900">Tests müssen grün sein</h3>
|
||||
<p className="text-sm text-slate-600">CI/CD Pipeline muss erfolgreich durchlaufen</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<CheckCircle2 className="h-5 w-5 text-green-600 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h3 className="font-medium text-slate-900">Aussagekräftige Commits</h3>
|
||||
<p className="text-sm text-slate-600">Nutze Conventional Commits (feat:, fix:, etc.)</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<CheckCircle2 className="h-5 w-5 text-green-600 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h3 className="font-medium text-slate-900">Branch aktuell halten</h3>
|
||||
<p className="text-sm text-slate-600">Regelmäßig main in deinen Branch mergen</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertTriangle className="h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h3 className="font-medium text-slate-900">Nie Force-Push auf main</h3>
|
||||
<p className="text-sm text-slate-600">Geschichte von main nie überschreiben</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* CI/CD Infrastruktur - Automatisierte OAuth Integration */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<h2 className="text-xl font-semibold text-slate-900 mb-4 flex items-center gap-2">
|
||||
<Shield className="h-5 w-5 text-indigo-600" />
|
||||
CI/CD Infrastruktur (Automatisiert)
|
||||
</h2>
|
||||
|
||||
<div className="bg-blue-50 rounded-xl p-4 mb-6 border border-blue-200">
|
||||
<div className="flex items-start gap-3">
|
||||
<Info className="h-5 w-5 text-blue-600 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h4 className="font-medium text-blue-900">Warum automatisiert?</h4>
|
||||
<p className="text-sm text-blue-800 mt-1">
|
||||
Die OAuth-Integration zwischen Woodpecker und Gitea ist vollautomatisiert.
|
||||
Dies ist eine DevSecOps Best Practice: Credentials werden in HashiCorp Vault gespeichert
|
||||
und können bei Bedarf automatisch regeneriert werden.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Architektur */}
|
||||
<div className="bg-slate-50 rounded-xl p-5 border border-slate-200">
|
||||
<h3 className="font-semibold text-slate-900 mb-3">Architektur</h3>
|
||||
<div className="space-y-3 text-sm">
|
||||
<div className="flex items-center gap-3 p-2 bg-white rounded-lg border">
|
||||
<div className="w-3 h-3 bg-green-500 rounded-full" />
|
||||
<span className="font-medium">Gitea</span>
|
||||
<span className="text-slate-500">Port 3003</span>
|
||||
<span className="text-xs text-slate-400 ml-auto">Git Server</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-center">
|
||||
<ArrowRight className="h-4 w-4 text-slate-400 rotate-90" />
|
||||
<span className="text-xs text-slate-500 ml-2">OAuth 2.0</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 p-2 bg-white rounded-lg border">
|
||||
<div className="w-3 h-3 bg-blue-500 rounded-full" />
|
||||
<span className="font-medium">Woodpecker</span>
|
||||
<span className="text-slate-500">Port 8090</span>
|
||||
<span className="text-xs text-slate-400 ml-auto">CI/CD Server</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-center">
|
||||
<ArrowRight className="h-4 w-4 text-slate-400 rotate-90" />
|
||||
<span className="text-xs text-slate-500 ml-2">Credentials</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 p-2 bg-white rounded-lg border">
|
||||
<div className="w-3 h-3 bg-purple-500 rounded-full" />
|
||||
<span className="font-medium">Vault</span>
|
||||
<span className="text-slate-500">Port 8200</span>
|
||||
<span className="text-xs text-slate-400 ml-auto">Secrets Manager</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Credentials Speicherort */}
|
||||
<div className="bg-slate-50 rounded-xl p-5 border border-slate-200">
|
||||
<h3 className="font-semibold text-slate-900 mb-3">Credentials Speicherorte</h3>
|
||||
<div className="space-y-3 text-sm">
|
||||
<div className="p-3 bg-white rounded-lg border">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Database className="h-4 w-4 text-purple-500" />
|
||||
<span className="font-medium">HashiCorp Vault</span>
|
||||
</div>
|
||||
<code className="text-xs bg-slate-100 px-2 py-1 rounded">
|
||||
secret/cicd/woodpecker
|
||||
</code>
|
||||
<p className="text-xs text-slate-500 mt-1">Client ID + Secret (Quelle der Wahrheit)</p>
|
||||
</div>
|
||||
<div className="p-3 bg-white rounded-lg border">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<FileCode className="h-4 w-4 text-blue-500" />
|
||||
<span className="font-medium">.env Datei</span>
|
||||
</div>
|
||||
<code className="text-xs bg-slate-100 px-2 py-1 rounded">
|
||||
WOODPECKER_GITEA_CLIENT/SECRET
|
||||
</code>
|
||||
<p className="text-xs text-slate-500 mt-1">Für Docker Compose (aus Vault geladen)</p>
|
||||
</div>
|
||||
<div className="p-3 bg-white rounded-lg border">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Database className="h-4 w-4 text-green-500" />
|
||||
<span className="font-medium">Gitea PostgreSQL</span>
|
||||
</div>
|
||||
<code className="text-xs bg-slate-100 px-2 py-1 rounded">
|
||||
oauth2_application
|
||||
</code>
|
||||
<p className="text-xs text-slate-500 mt-1">OAuth App Registration (gehashtes Secret)</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Troubleshooting */}
|
||||
<div className="mt-6 bg-amber-50 rounded-xl p-5 border border-amber-200">
|
||||
<h3 className="font-semibold text-amber-900 mb-3 flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-amber-600" />
|
||||
Troubleshooting: OAuth Fehler beheben
|
||||
</h3>
|
||||
<p className="text-sm text-amber-800 mb-3">
|
||||
Falls der Fehler "Client ID not registered" oder "user does not exist" auftritt:
|
||||
</p>
|
||||
<div className="bg-slate-800 rounded-lg p-4 font-mono text-sm">
|
||||
<p className="text-slate-400"># Credentials automatisch regenerieren</p>
|
||||
<p className="text-green-400">./scripts/sync-woodpecker-credentials.sh --regenerate</p>
|
||||
<p className="text-slate-400 mt-2"># Oder manuell: Vault → Gitea → .env → Restart</p>
|
||||
<p className="text-green-400">rsync .env macmini:~/Projekte/breakpilot-pwa/</p>
|
||||
<p className="text-green-400">ssh macmini "cd ~/Projekte/breakpilot-pwa && docker compose up -d --force-recreate woodpecker-server"</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Team Members Info */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<h2 className="text-xl font-semibold text-slate-900 mb-4 flex items-center gap-2">
|
||||
<Users className="h-5 w-5 text-indigo-600" />
|
||||
Team-Kommunikation
|
||||
</h2>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="bg-slate-50 rounded-lg p-4 text-center">
|
||||
<div className="text-3xl mb-2">💬</div>
|
||||
<h3 className="font-medium text-slate-900">Pull Request Kommentare</h3>
|
||||
<p className="text-sm text-slate-600 mt-1">Code-Diskussionen im PR</p>
|
||||
</div>
|
||||
<div className="bg-slate-50 rounded-lg p-4 text-center">
|
||||
<div className="text-3xl mb-2">📋</div>
|
||||
<h3 className="font-medium text-slate-900">Issues in Gitea</h3>
|
||||
<p className="text-sm text-slate-600 mt-1">Bugs & Features tracken</p>
|
||||
</div>
|
||||
<div className="bg-slate-50 rounded-lg p-4 text-center">
|
||||
<div className="text-3xl mb-2">🔔</div>
|
||||
<h3 className="font-medium text-slate-900">CI/CD Notifications</h3>
|
||||
<p className="text-sm text-slate-600 mt-1">Pipeline-Status per Mail</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,391 +0,0 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* GPU Infrastructure Admin Page
|
||||
*
|
||||
* vast.ai GPU Management for LLM Processing
|
||||
*/
|
||||
|
||||
import { useEffect, useState, useCallback } from 'react'
|
||||
import { PagePurpose } from '@/components/common/PagePurpose'
|
||||
|
||||
interface VastStatus {
|
||||
instance_id: number | null
|
||||
status: string
|
||||
gpu_name: string | null
|
||||
dph_total: number | null
|
||||
endpoint_base_url: string | null
|
||||
last_activity: string | null
|
||||
auto_shutdown_in_minutes: number | null
|
||||
total_runtime_hours: number | null
|
||||
total_cost_usd: number | null
|
||||
account_credit: number | null
|
||||
account_total_spend: number | null
|
||||
session_runtime_minutes: number | null
|
||||
session_cost_usd: number | null
|
||||
message: string | null
|
||||
error?: string
|
||||
}
|
||||
|
||||
export default function GPUInfrastructurePage() {
|
||||
const [status, setStatus] = useState<VastStatus | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [actionLoading, setActionLoading] = useState<string | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
|
||||
const API_PROXY = '/api/admin/gpu'
|
||||
|
||||
const fetchStatus = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const response = await fetch(API_PROXY)
|
||||
const data = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || `HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
setStatus(data)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Verbindungsfehler')
|
||||
setStatus({
|
||||
instance_id: null,
|
||||
status: 'error',
|
||||
gpu_name: null,
|
||||
dph_total: null,
|
||||
endpoint_base_url: null,
|
||||
last_activity: null,
|
||||
auto_shutdown_in_minutes: null,
|
||||
total_runtime_hours: null,
|
||||
total_cost_usd: null,
|
||||
account_credit: null,
|
||||
account_total_spend: null,
|
||||
session_runtime_minutes: null,
|
||||
session_cost_usd: null,
|
||||
message: 'Verbindung fehlgeschlagen'
|
||||
})
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchStatus()
|
||||
}, [fetchStatus])
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(fetchStatus, 30000)
|
||||
return () => clearInterval(interval)
|
||||
}, [fetchStatus])
|
||||
|
||||
const powerOn = async () => {
|
||||
setActionLoading('on')
|
||||
setError(null)
|
||||
setMessage(null)
|
||||
|
||||
try {
|
||||
const response = await fetch(API_PROXY, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'on' }),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || data.detail || 'Aktion fehlgeschlagen')
|
||||
}
|
||||
|
||||
setMessage('Start angefordert')
|
||||
setTimeout(fetchStatus, 3000)
|
||||
setTimeout(fetchStatus, 10000)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Fehler beim Starten')
|
||||
fetchStatus()
|
||||
} finally {
|
||||
setActionLoading(null)
|
||||
}
|
||||
}
|
||||
|
||||
const powerOff = async () => {
|
||||
setActionLoading('off')
|
||||
setError(null)
|
||||
setMessage(null)
|
||||
|
||||
try {
|
||||
const response = await fetch(API_PROXY, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'off' }),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || data.detail || 'Aktion fehlgeschlagen')
|
||||
}
|
||||
|
||||
setMessage('Stop angefordert')
|
||||
setTimeout(fetchStatus, 3000)
|
||||
setTimeout(fetchStatus, 10000)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Fehler beim Stoppen')
|
||||
fetchStatus()
|
||||
} finally {
|
||||
setActionLoading(null)
|
||||
}
|
||||
}
|
||||
|
||||
const getStatusBadge = (s: string) => {
|
||||
const baseClasses = 'px-3 py-1 rounded-full text-sm font-semibold uppercase'
|
||||
switch (s) {
|
||||
case 'running':
|
||||
return `${baseClasses} bg-green-100 text-green-800`
|
||||
case 'stopped':
|
||||
case 'exited':
|
||||
return `${baseClasses} bg-red-100 text-red-800`
|
||||
case 'loading':
|
||||
case 'scheduling':
|
||||
case 'creating':
|
||||
case 'starting...':
|
||||
case 'stopping...':
|
||||
return `${baseClasses} bg-yellow-100 text-yellow-800`
|
||||
default:
|
||||
return `${baseClasses} bg-slate-100 text-slate-600`
|
||||
}
|
||||
}
|
||||
|
||||
const getCreditColor = (credit: number | null) => {
|
||||
if (credit === null) return 'text-slate-500'
|
||||
if (credit < 5) return 'text-red-600'
|
||||
if (credit < 15) return 'text-yellow-600'
|
||||
return 'text-green-600'
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Page Purpose */}
|
||||
<PagePurpose
|
||||
title="GPU Infrastruktur"
|
||||
purpose="Verwalten Sie die vast.ai GPU-Instanzen fuer LLM-Verarbeitung und OCR. Starten/Stoppen Sie GPUs bei Bedarf und ueberwachen Sie Kosten in Echtzeit."
|
||||
audience={['DevOps', 'Entwickler', 'System-Admins']}
|
||||
architecture={{
|
||||
services: ['vast.ai API', 'Ollama', 'VLLM'],
|
||||
databases: ['PostgreSQL (Logs)'],
|
||||
}}
|
||||
relatedPages={[
|
||||
{ name: 'LLM Vergleich', href: '/ai/llm-compare', description: 'KI-Provider testen' },
|
||||
{ name: 'Security', href: '/infrastructure/security', description: 'DevSecOps Dashboard' },
|
||||
{ name: 'Builds', href: '/infrastructure/builds', description: 'CI/CD Pipeline' },
|
||||
]}
|
||||
collapsible={true}
|
||||
defaultCollapsed={true}
|
||||
/>
|
||||
|
||||
{/* Status Cards */}
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6 mb-6">
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-6">
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 mb-2">Status</div>
|
||||
{loading ? (
|
||||
<span className="px-3 py-1 rounded-full text-sm font-semibold bg-slate-100 text-slate-600">
|
||||
Laden...
|
||||
</span>
|
||||
) : (
|
||||
<span className={getStatusBadge(
|
||||
actionLoading === 'on' ? 'starting...' :
|
||||
actionLoading === 'off' ? 'stopping...' :
|
||||
status?.status || 'unknown'
|
||||
)}>
|
||||
{actionLoading === 'on' ? 'starting...' :
|
||||
actionLoading === 'off' ? 'stopping...' :
|
||||
status?.status || 'unbekannt'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 mb-2">GPU</div>
|
||||
<div className="font-semibold text-slate-900">
|
||||
{status?.gpu_name || '-'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 mb-2">Kosten/h</div>
|
||||
<div className="font-semibold text-slate-900">
|
||||
{status?.dph_total ? `$${status.dph_total.toFixed(3)}` : '-'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 mb-2">Auto-Stop</div>
|
||||
<div className="font-semibold text-slate-900">
|
||||
{status && status.auto_shutdown_in_minutes !== null
|
||||
? `${status.auto_shutdown_in_minutes} min`
|
||||
: '-'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 mb-2">Budget</div>
|
||||
<div className={`font-bold text-lg ${getCreditColor(status?.account_credit ?? null)}`}>
|
||||
{status && status.account_credit !== null
|
||||
? `$${status.account_credit.toFixed(2)}`
|
||||
: '-'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="text-sm text-slate-500 mb-2">Session</div>
|
||||
<div className="font-semibold text-slate-900">
|
||||
{status && status.session_runtime_minutes !== null && status.session_cost_usd !== null
|
||||
? `${Math.round(status.session_runtime_minutes)} min / $${status.session_cost_usd.toFixed(3)}`
|
||||
: '-'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Buttons */}
|
||||
<div className="flex items-center gap-4 mt-6 pt-6 border-t border-slate-200">
|
||||
<button
|
||||
onClick={powerOn}
|
||||
disabled={actionLoading !== null || status?.status === 'running'}
|
||||
className="px-6 py-2 bg-orange-600 text-white rounded-lg font-medium hover:bg-orange-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
Starten
|
||||
</button>
|
||||
<button
|
||||
onClick={powerOff}
|
||||
disabled={actionLoading !== null || status?.status !== 'running'}
|
||||
className="px-6 py-2 bg-red-600 text-white rounded-lg font-medium hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
Stoppen
|
||||
</button>
|
||||
<button
|
||||
onClick={fetchStatus}
|
||||
disabled={loading}
|
||||
className="px-4 py-2 border border-slate-300 text-slate-700 rounded-lg font-medium hover:bg-slate-50 disabled:opacity-50 transition-colors"
|
||||
>
|
||||
{loading ? 'Aktualisiere...' : 'Aktualisieren'}
|
||||
</button>
|
||||
|
||||
{message && (
|
||||
<span className="ml-4 text-sm text-green-600 font-medium">{message}</span>
|
||||
)}
|
||||
{error && (
|
||||
<span className="ml-4 text-sm text-red-600 font-medium">{error}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Extended Stats */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<h3 className="font-semibold text-slate-900 mb-4">Kosten-Uebersicht</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">Session Laufzeit</span>
|
||||
<span className="font-semibold">
|
||||
{status && status.session_runtime_minutes !== null
|
||||
? `${Math.round(status.session_runtime_minutes)} Minuten`
|
||||
: '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">Session Kosten</span>
|
||||
<span className="font-semibold">
|
||||
{status && status.session_cost_usd !== null
|
||||
? `$${status.session_cost_usd.toFixed(4)}`
|
||||
: '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center pt-4 border-t border-slate-100">
|
||||
<span className="text-slate-600">Gesamtlaufzeit</span>
|
||||
<span className="font-semibold">
|
||||
{status && status.total_runtime_hours !== null
|
||||
? `${status.total_runtime_hours.toFixed(1)} Stunden`
|
||||
: '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">Gesamtkosten</span>
|
||||
<span className="font-semibold">
|
||||
{status && status.total_cost_usd !== null
|
||||
? `$${status.total_cost_usd.toFixed(2)}`
|
||||
: '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">vast.ai Ausgaben</span>
|
||||
<span className="font-semibold">
|
||||
{status && status.account_total_spend !== null
|
||||
? `$${status.account_total_spend.toFixed(2)}`
|
||||
: '-'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-6">
|
||||
<h3 className="font-semibold text-slate-900 mb-4">Instanz-Details</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">Instanz ID</span>
|
||||
<span className="font-mono text-sm">
|
||||
{status?.instance_id || '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">GPU</span>
|
||||
<span className="font-semibold">
|
||||
{status?.gpu_name || '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">Stundensatz</span>
|
||||
<span className="font-semibold">
|
||||
{status?.dph_total ? `$${status.dph_total.toFixed(4)}/h` : '-'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-slate-600">Letzte Aktivitaet</span>
|
||||
<span className="text-sm">
|
||||
{status?.last_activity
|
||||
? new Date(status.last_activity).toLocaleString('de-DE')
|
||||
: '-'}
|
||||
</span>
|
||||
</div>
|
||||
{status?.endpoint_base_url && status.status === 'running' && (
|
||||
<div className="pt-4 border-t border-slate-100">
|
||||
<div className="text-slate-600 text-sm mb-1">Endpoint</div>
|
||||
<code className="text-xs bg-slate-100 px-2 py-1 rounded block overflow-x-auto">
|
||||
{status.endpoint_base_url}
|
||||
</code>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Info */}
|
||||
<div className="bg-orange-50 border border-orange-200 rounded-xl p-4">
|
||||
<div className="flex gap-3">
|
||||
<svg className="w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<div>
|
||||
<h4 className="font-semibold text-orange-900">Auto-Shutdown</h4>
|
||||
<p className="text-sm text-orange-800 mt-1">
|
||||
Die GPU-Instanz wird automatisch gestoppt, wenn sie laengere Zeit inaktiv ist.
|
||||
Der Status wird alle 30 Sekunden automatisch aktualisiert.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -51,13 +51,9 @@ const INFRASTRUCTURE_COMPONENTS: Component[] = [
|
||||
// ===== DATABASES =====
|
||||
{ type: 'service', name: 'PostgreSQL', version: '16-alpine', category: 'database', port: '5432', description: 'Hauptdatenbank', license: 'PostgreSQL', sourceUrl: 'https://github.com/postgres/postgres' },
|
||||
{ type: 'service', name: 'Synapse PostgreSQL', version: '16-alpine', category: 'database', port: '-', description: 'Matrix Datenbank', license: 'PostgreSQL', sourceUrl: 'https://github.com/postgres/postgres' },
|
||||
{ type: 'service', name: 'ERPNext MariaDB', version: '10.6', category: 'database', port: '-', description: 'ERPNext Datenbank', license: 'GPL-2.0', sourceUrl: 'https://github.com/MariaDB/server' },
|
||||
{ type: 'service', name: 'MongoDB', version: '7.0', category: 'database', port: '27017', description: 'LibreChat Datenbank', license: 'SSPL-1.0', sourceUrl: 'https://github.com/mongodb/mongo' },
|
||||
|
||||
// ===== CACHE & QUEUE =====
|
||||
{ type: 'service', name: 'Valkey', version: '8-alpine', category: 'cache', port: '6379', description: 'In-Memory Cache & Sessions (Redis OSS Fork)', license: 'BSD-3-Clause', sourceUrl: 'https://github.com/valkey-io/valkey' },
|
||||
{ type: 'service', name: 'ERPNext Valkey Queue', version: 'alpine', category: 'cache', port: '-', description: 'Job Queue', license: 'BSD-3-Clause', sourceUrl: 'https://github.com/valkey-io/valkey' },
|
||||
{ type: 'service', name: 'ERPNext Valkey Cache', version: 'alpine', category: 'cache', port: '-', description: 'Cache Layer', license: 'BSD-3-Clause', sourceUrl: 'https://github.com/valkey-io/valkey' },
|
||||
|
||||
// ===== SEARCH ENGINES =====
|
||||
{ type: 'service', name: 'Qdrant', version: '1.7.4', category: 'search', port: '6333', description: 'Vector Database (RAG/Embeddings)', license: 'Apache-2.0', sourceUrl: 'https://github.com/qdrant/qdrant' },
|
||||
@@ -66,8 +62,6 @@ const INFRASTRUCTURE_COMPONENTS: Component[] = [
|
||||
|
||||
// ===== OBJECT STORAGE =====
|
||||
{ type: 'service', name: 'MinIO', version: 'latest', category: 'storage', port: '9000/9001', description: 'S3-kompatibel Object Storage', license: 'AGPL-3.0', sourceUrl: 'https://github.com/minio/minio' },
|
||||
{ type: 'service', name: 'IPFS (Kubo)', version: '0.24', category: 'storage', port: '5001', description: 'Dezentrales Speichersystem', license: 'MIT/Apache-2.0', sourceUrl: 'https://github.com/ipfs/kubo' },
|
||||
{ type: 'service', name: 'DSMS Gateway', version: '1.0', category: 'storage', port: '8082', description: 'IPFS REST API', license: 'Proprietary', sourceUrl: '-' },
|
||||
|
||||
// ===== SECURITY =====
|
||||
{ type: 'service', name: 'HashiCorp Vault', version: '1.15', category: 'security', port: '8200', description: 'Secrets Management', license: 'BUSL-1.1', sourceUrl: 'https://github.com/hashicorp/vault' },
|
||||
@@ -83,36 +77,19 @@ const INFRASTRUCTURE_COMPONENTS: Component[] = [
|
||||
{ type: 'service', name: 'Jibri', version: 'stable-9823', category: 'communication', port: '-', description: 'Recording & Streaming Service', license: 'Apache-2.0', sourceUrl: 'https://github.com/jitsi/jibri' },
|
||||
|
||||
// ===== APPLICATION SERVICES (Python) =====
|
||||
{ type: 'service', name: 'Python Backend (FastAPI)', version: '3.12', category: 'application', port: '8000', description: 'Haupt-Backend API, Studio & Alerts Agent', license: 'Proprietary', sourceUrl: '-' },
|
||||
{ type: 'service', name: 'Python Backend (FastAPI)', version: '3.12', category: 'application', port: '8000', description: 'Lehrer Backend API (Klausuren, E-Mail, Alerts)', license: 'Proprietary', sourceUrl: '-' },
|
||||
{ type: 'service', name: 'Klausur Service', version: '1.0', category: 'application', port: '8086', description: 'Abitur-Klausurkorrektur (BYOEH)', license: 'Proprietary', sourceUrl: '-' },
|
||||
{ type: 'service', name: 'Compliance Module', version: '2.0', category: 'application', port: '8000', description: 'GRC Framework (19 Regulations, 558 Requirements, AI)', license: 'Proprietary', sourceUrl: '-' },
|
||||
{ type: 'service', name: 'Transcription Worker', version: '1.0', category: 'application', port: '-', description: 'Whisper + pyannote Transkription', license: 'Proprietary', sourceUrl: '-' },
|
||||
|
||||
// ===== APPLICATION SERVICES (Go) =====
|
||||
{ type: 'service', name: 'Go Consent Service', version: '1.21', category: 'application', port: '8081', description: 'DSGVO Consent Management', license: 'Proprietary', sourceUrl: '-' },
|
||||
{ type: 'service', name: 'Go School Service', version: '1.21', category: 'application', port: '8084', description: 'Klausuren, Noten, Zeugnisse', license: 'Proprietary', sourceUrl: '-' },
|
||||
{ type: 'service', name: 'Go Billing Service', version: '1.21', category: 'application', port: '8083', description: 'Stripe Billing Integration', license: 'Proprietary', sourceUrl: '-' },
|
||||
|
||||
// ===== APPLICATION SERVICES (Node.js) =====
|
||||
{ type: 'service', name: 'Next.js Admin Frontend', version: '15.1', category: 'application', port: '3000', description: 'Admin Dashboard (React)', license: 'Proprietary', sourceUrl: '-' },
|
||||
{ type: 'service', name: 'H5P Content Service', version: 'latest', category: 'application', port: '8085', description: 'Interaktive Inhalte', license: 'MIT', sourceUrl: 'https://github.com/h5p/h5p-server' },
|
||||
{ type: 'service', name: 'Policy Vault (NestJS)', version: '1.0', category: 'application', port: '3001', description: 'Richtlinien-Verwaltung API', license: 'Proprietary', sourceUrl: '-' },
|
||||
{ type: 'service', name: 'Policy Vault (Angular)', version: '17', category: 'application', port: '4200', description: 'Richtlinien-Verwaltung UI', license: 'Proprietary', sourceUrl: '-' },
|
||||
|
||||
// ===== APPLICATION SERVICES (Vue) =====
|
||||
{ type: 'service', name: 'Creator Studio (Vue 3)', version: '3.4', category: 'application', port: '-', description: 'Content Creation UI', license: 'Proprietary', sourceUrl: '-' },
|
||||
|
||||
// ===== AI/LLM SERVICES =====
|
||||
{ type: 'service', name: 'LibreChat', version: 'latest', category: 'ai', port: '3080', description: 'Multi-LLM Chat Interface', license: 'MIT', sourceUrl: 'https://github.com/danny-avila/LibreChat' },
|
||||
{ type: 'service', name: 'RAGFlow', version: 'latest', category: 'ai', port: '9380', description: 'RAG Pipeline Service', license: 'Apache-2.0', sourceUrl: 'https://github.com/infiniflow/ragflow' },
|
||||
|
||||
// ===== ERP =====
|
||||
{ type: 'service', name: 'ERPNext', version: 'v15', category: 'erp', port: '8090', description: 'Open Source ERP System', license: 'GPL-3.0', sourceUrl: 'https://github.com/frappe/erpnext' },
|
||||
{ type: 'service', name: 'Next.js Admin Frontend', version: '15.1', category: 'application', port: '3002', description: 'Admin Lehrer Dashboard (React)', license: 'Proprietary', sourceUrl: '-' },
|
||||
|
||||
// ===== CI/CD & VERSION CONTROL =====
|
||||
{ type: 'service', name: 'Woodpecker CI', version: '2.x', category: 'cicd', port: '8082', description: 'Self-hosted CI/CD Pipeline (Drone Fork)', license: 'Apache-2.0', sourceUrl: 'https://github.com/woodpecker-ci/woodpecker' },
|
||||
{ type: 'service', name: 'Gitea', version: '1.21', category: 'cicd', port: '3003', description: 'Self-hosted Git Service', license: 'MIT', sourceUrl: 'https://github.com/go-gitea/gitea' },
|
||||
{ type: 'service', name: 'Dokploy', version: '0.26.7', category: 'cicd', port: '3000', description: 'Self-hosted PaaS (Vercel/Heroku Alternative)', license: 'Apache-2.0', sourceUrl: 'https://github.com/Dokploy/dokploy' },
|
||||
|
||||
// ===== DEVELOPMENT =====
|
||||
{ type: 'service', name: 'Mailpit', version: 'latest', category: 'development', port: '8025/1025', description: 'E-Mail Testing (SMTP Catch-All)', license: 'MIT', sourceUrl: 'https://github.com/axllent/mailpit' },
|
||||
@@ -184,10 +161,7 @@ const PYTHON_PACKAGES: Component[] = [
|
||||
{ type: 'library', name: 'structlog', version: '24.x', category: 'python', description: 'Structured Logging', license: 'Apache-2.0', sourceUrl: 'https://github.com/hynek/structlog' },
|
||||
{ type: 'library', name: 'feedparser', version: '6.x', category: 'python', description: 'RSS/Atom Feed Parser (Alerts Agent)', license: 'BSD-2-Clause', sourceUrl: 'https://github.com/kurtmckee/feedparser' },
|
||||
{ type: 'library', name: 'APScheduler', version: '3.x', category: 'python', description: 'AsyncIO Job Scheduler (Alerts Agent)', license: 'MIT', sourceUrl: 'https://github.com/agronholm/apscheduler' },
|
||||
{ type: 'library', name: 'beautifulsoup4', version: '4.x', category: 'python', description: 'HTML Parser (Email Parsing, Compliance Scraper)', license: 'MIT', sourceUrl: 'https://code.launchpad.net/beautifulsoup' },
|
||||
{ type: 'library', name: 'lxml', version: '5.x', category: 'python', description: 'XML/HTML Parser (EUR-Lex Scraping)', license: 'BSD-3-Clause', sourceUrl: 'https://github.com/lxml/lxml' },
|
||||
{ type: 'library', name: 'PyMuPDF', version: '1.24+', category: 'python', description: 'PDF Parser (BSI-TR Extraction)', license: 'AGPL-3.0', sourceUrl: 'https://github.com/pymupdf/PyMuPDF' },
|
||||
{ type: 'library', name: 'pdfplumber', version: '0.11+', category: 'python', description: 'PDF Table Extraction (Compliance Docs)', license: 'MIT', sourceUrl: 'https://github.com/jsvine/pdfplumber' },
|
||||
{ type: 'library', name: 'beautifulsoup4', version: '4.x', category: 'python', description: 'HTML Parser (Email Parsing)', license: 'MIT', sourceUrl: 'https://code.launchpad.net/beautifulsoup' },
|
||||
{ type: 'library', name: 'websockets', version: '14.x', category: 'python', description: 'WebSocket Support (Voice Streaming)', license: 'BSD-3-Clause', sourceUrl: 'https://github.com/python-websockets/websockets' },
|
||||
{ type: 'library', name: 'soundfile', version: '0.13+', category: 'python', description: 'Audio File Processing (Voice Service)', license: 'BSD-3-Clause', sourceUrl: 'https://github.com/bastibe/python-soundfile' },
|
||||
{ type: 'library', name: 'scipy', version: '1.14+', category: 'python', description: 'Signal Processing (Audio)', license: 'BSD-3-Clause', sourceUrl: 'https://github.com/scipy/scipy' },
|
||||
@@ -200,7 +174,8 @@ const GO_MODULES: Component[] = [
|
||||
{ type: 'library', name: 'gin-gonic/gin', version: '1.9+', category: 'go', description: 'Web Framework', license: 'MIT', sourceUrl: 'https://github.com/gin-gonic/gin' },
|
||||
{ type: 'library', name: 'gorm.io/gorm', version: '1.25+', category: 'go', description: 'ORM', license: 'MIT', sourceUrl: 'https://github.com/go-gorm/gorm' },
|
||||
{ type: 'library', name: 'golang-jwt/jwt', version: 'v5', category: 'go', description: 'JWT Library', license: 'MIT', sourceUrl: 'https://github.com/golang-jwt/jwt' },
|
||||
{ type: 'library', name: 'stripe/stripe-go', version: 'v76', category: 'go', description: 'Stripe SDK', license: 'MIT', sourceUrl: 'https://github.com/stripe/stripe-go' },
|
||||
{ type: 'library', name: 'opensearch-project/opensearch-go', version: '4.x', category: 'go', description: 'OpenSearch Client (edu-search-service)', license: 'Apache-2.0', sourceUrl: 'https://github.com/opensearch-project/opensearch-go' },
|
||||
{ type: 'library', name: 'lib/pq', version: '1.10+', category: 'go', description: 'PostgreSQL Driver (school-service)', license: 'MIT', sourceUrl: 'https://github.com/lib/pq' },
|
||||
{ type: 'library', name: 'spf13/viper', version: 'latest', category: 'go', description: 'Configuration', license: 'MIT', sourceUrl: 'https://github.com/spf13/viper' },
|
||||
{ type: 'library', name: 'uber-go/zap', version: 'latest', category: 'go', description: 'Structured Logging', license: 'MIT', sourceUrl: 'https://github.com/uber-go/zap' },
|
||||
{ type: 'library', name: 'swaggo/swag', version: 'latest', category: 'go', description: 'Swagger Docs', license: 'MIT', sourceUrl: 'https://github.com/swaggo/swag' },
|
||||
@@ -210,15 +185,10 @@ const GO_MODULES: Component[] = [
|
||||
const NODE_PACKAGES: Component[] = [
|
||||
{ type: 'library', name: 'Next.js', version: '15.1', category: 'nodejs', description: 'React Framework', license: 'MIT', sourceUrl: 'https://github.com/vercel/next.js' },
|
||||
{ type: 'library', name: 'React', version: '19', category: 'nodejs', description: 'UI Library', license: 'MIT', sourceUrl: 'https://github.com/facebook/react' },
|
||||
{ type: 'library', name: 'Vue.js', version: '3.4', category: 'nodejs', description: 'UI Framework (Creator Studio)', license: 'MIT', sourceUrl: 'https://github.com/vuejs/core' },
|
||||
{ type: 'library', name: 'Angular', version: '17', category: 'nodejs', description: 'UI Framework (Policy Vault)', license: 'MIT', sourceUrl: 'https://github.com/angular/angular' },
|
||||
{ type: 'library', name: 'NestJS', version: '10', category: 'nodejs', description: 'Node.js Framework', license: 'MIT', sourceUrl: 'https://github.com/nestjs/nest' },
|
||||
{ type: 'library', name: 'TypeScript', version: '5.x', category: 'nodejs', description: 'Type System', license: 'Apache-2.0', sourceUrl: 'https://github.com/microsoft/TypeScript' },
|
||||
{ type: 'library', name: 'Tailwind CSS', version: '3.4', category: 'nodejs', description: 'Utility CSS', license: 'MIT', sourceUrl: 'https://github.com/tailwindlabs/tailwindcss' },
|
||||
{ type: 'library', name: 'Prisma', version: '5.x', category: 'nodejs', description: 'ORM (Policy Vault)', license: 'Apache-2.0', sourceUrl: 'https://github.com/prisma/prisma' },
|
||||
{ type: 'library', name: 'Material Design Icons', version: 'latest', category: 'nodejs', description: 'Icon-System (Companion UI, Studio)', license: 'Apache-2.0', sourceUrl: 'https://github.com/google/material-design-icons' },
|
||||
{ type: 'library', name: 'Recharts', version: '2.12', category: 'nodejs', description: 'React Charts (Compliance Dashboard)', license: 'MIT', sourceUrl: 'https://github.com/recharts/recharts' },
|
||||
{ type: 'library', name: 'React Flow', version: '11.x', category: 'nodejs', description: 'Node-basierte Flow-Diagramme (Screen Flow)', license: 'MIT', sourceUrl: 'https://github.com/xyflow/xyflow' },
|
||||
{ type: 'library', name: 'Recharts', version: '2.12', category: 'nodejs', description: 'React Charts (Admin Dashboard)', license: 'MIT', sourceUrl: 'https://github.com/recharts/recharts' },
|
||||
{ type: 'library', name: 'Playwright', version: '1.50', category: 'nodejs', description: 'E2E Testing Framework (SDK Tests)', license: 'Apache-2.0', sourceUrl: 'https://github.com/microsoft/playwright' },
|
||||
{ type: 'library', name: 'Vitest', version: '4.x', category: 'nodejs', description: 'Unit Testing Framework', license: 'MIT', sourceUrl: 'https://github.com/vitest-dev/vitest' },
|
||||
{ type: 'library', name: 'jsPDF', version: '4.x', category: 'nodejs', description: 'PDF Generation (SDK Export)', license: 'MIT', sourceUrl: 'https://github.com/parallax/jsPDF' },
|
||||
@@ -357,9 +327,7 @@ export default function SBOMPage() {
|
||||
case 'communication': return 'bg-yellow-100 text-yellow-800'
|
||||
case 'storage': return 'bg-orange-100 text-orange-800'
|
||||
case 'search': return 'bg-pink-100 text-pink-800'
|
||||
case 'erp': return 'bg-indigo-100 text-indigo-800'
|
||||
case 'cache': return 'bg-cyan-100 text-cyan-800'
|
||||
case 'ai': return 'bg-violet-100 text-violet-800'
|
||||
case 'development': return 'bg-gray-100 text-gray-800'
|
||||
case 'cicd': return 'bg-orange-100 text-orange-800'
|
||||
case 'python': return 'bg-emerald-100 text-emerald-800'
|
||||
@@ -415,7 +383,7 @@ export default function SBOMPage() {
|
||||
<div>
|
||||
<PagePurpose
|
||||
title="SBOM"
|
||||
purpose="Software Bill of Materials - Alle Komponenten & Abhaengigkeiten der Breakpilot-Plattform. Wichtig fuer Supply-Chain-Security, Compliance-Audits und Lizenz-Pruefung."
|
||||
purpose="Software Bill of Materials - Alle Komponenten & Abhaengigkeiten der Breakpilot Lehrer-Plattform. Wichtig fuer Supply-Chain-Security, Compliance-Audits und Lizenz-Pruefung."
|
||||
audience={['DevOps', 'Compliance', 'Security', 'Auditoren']}
|
||||
gdprArticles={['Art. 32 (Sicherheit der Verarbeitung)']}
|
||||
architecture={{
|
||||
@@ -654,7 +622,7 @@ export default function SBOMPage() {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `breakpilot-sbom-${new Date().toISOString().split('T')[0]}.json`
|
||||
a.download = `breakpilot-lehrer-sbom-${new Date().toISOString().split('T')[0]}.json`
|
||||
a.click()
|
||||
}}
|
||||
className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors flex items-center gap-2"
|
||||
|
||||
@@ -335,7 +335,6 @@ export default function RBACPage() {
|
||||
}}
|
||||
relatedPages={[
|
||||
{ name: 'Audit Trail', href: '/sdk/audit-report', description: 'LLM-Operationen protokollieren' },
|
||||
{ name: 'LLM Vergleich', href: '/ai/llm-compare', description: 'KI-Provider testen' },
|
||||
]}
|
||||
/>
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Metadata } from 'next'
|
||||
import localFont from 'next/font/local'
|
||||
import { Noto_Sans } from 'next/font/google'
|
||||
import './globals.css'
|
||||
|
||||
const inter = localFont({
|
||||
@@ -8,6 +9,12 @@ const inter = localFont({
|
||||
display: 'swap',
|
||||
})
|
||||
|
||||
const notoSans = Noto_Sans({
|
||||
subsets: ['latin', 'latin-ext'],
|
||||
variable: '--font-noto-sans',
|
||||
display: 'swap',
|
||||
})
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'BreakPilot Admin Lehrer KI',
|
||||
description: 'Neues Admin-Frontend mit verbesserter Navigation und Rollen-System',
|
||||
@@ -20,7 +27,7 @@ export default function RootLayout({
|
||||
}) {
|
||||
return (
|
||||
<html lang="de">
|
||||
<body className={inter.className}>{children}</body>
|
||||
<body className={`${inter.className} ${notoSans.variable}`}>{children}</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
import Link from 'next/link'
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
export type AIToolId = 'llm-compare' | 'test-quality' | 'gpu' | 'ocr-compare' | 'ocr-labeling' | 'rag-pipeline' | 'magic-help'
|
||||
export type AIToolId = 'test-quality' | 'gpu' | 'ocr-compare' | 'ocr-labeling' | 'rag-pipeline' | 'magic-help'
|
||||
|
||||
export interface AIToolModule {
|
||||
id: AIToolId
|
||||
@@ -25,13 +25,6 @@ export interface AIToolModule {
|
||||
}
|
||||
|
||||
export const AI_TOOLS_MODULES: AIToolModule[] = [
|
||||
{
|
||||
id: 'llm-compare',
|
||||
name: 'LLM Vergleich',
|
||||
href: '/ai/llm-compare',
|
||||
description: 'KI-Provider vergleichen',
|
||||
icon: '⚖️',
|
||||
},
|
||||
{
|
||||
id: 'test-quality',
|
||||
name: 'Test Quality (BQAS)',
|
||||
@@ -93,13 +86,6 @@ export interface AIToolsSidebarResponsiveProps extends AIToolsSidebarProps {
|
||||
// Icons für die Tools
|
||||
const ToolIcon = ({ id }: { id: string }) => {
|
||||
switch (id) {
|
||||
case 'llm-compare':
|
||||
return (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
|
||||
d="M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3" />
|
||||
</svg>
|
||||
)
|
||||
case 'test-quality':
|
||||
return (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
@@ -228,8 +214,6 @@ export function AIToolsSidebar({
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<span title="GPU Infrastruktur">🖥️</span>
|
||||
<span className="text-slate-400">→</span>
|
||||
<span title="LLM Vergleich">⚖️</span>
|
||||
<span className="text-slate-400">→</span>
|
||||
<span title="Test Quality">🧪</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -241,9 +225,6 @@ export function AIToolsSidebar({
|
||||
{/* Quick Info zum aktuellen Tool */}
|
||||
<div className="pt-2 border-t border-slate-200 dark:border-gray-700">
|
||||
<div className="text-xs text-slate-500 dark:text-slate-400 px-1">
|
||||
{currentTool === 'llm-compare' && (
|
||||
<span>Vergleichen Sie LLM-Antworten verschiedener Provider</span>
|
||||
)}
|
||||
{currentTool === 'test-quality' && (
|
||||
<span>Ueberwachen Sie die Qualitaet der KI-Ausgaben</span>
|
||||
)}
|
||||
@@ -387,11 +368,6 @@ export function AIToolsSidebarResponsive({
|
||||
<span className="text-xs text-slate-500 mt-1">GPU</span>
|
||||
</div>
|
||||
<span className="text-slate-400">→</span>
|
||||
<div className="flex flex-col items-center">
|
||||
<span className="text-2xl">⚖️</span>
|
||||
<span className="text-xs text-slate-500 mt-1">LLM</span>
|
||||
</div>
|
||||
<span className="text-slate-400">→</span>
|
||||
<div className="flex flex-col items-center">
|
||||
<span className="text-2xl">🧪</span>
|
||||
<span className="text-xs text-slate-500 mt-1">BQAS</span>
|
||||
@@ -405,11 +381,6 @@ export function AIToolsSidebarResponsive({
|
||||
{/* Quick Info */}
|
||||
<div className="pt-4 border-t border-slate-200 dark:border-gray-700">
|
||||
<div className="text-sm text-slate-600 dark:text-slate-400 p-3 bg-slate-50 dark:bg-gray-800 rounded-xl">
|
||||
{currentTool === 'llm-compare' && (
|
||||
<>
|
||||
<strong className="text-slate-700 dark:text-slate-300">Aktuell:</strong> LLM-Antworten verschiedener Provider vergleichen
|
||||
</>
|
||||
)}
|
||||
{currentTool === 'test-quality' && (
|
||||
<>
|
||||
<strong className="text-slate-700 dark:text-slate-300">Aktuell:</strong> Qualitaet der KI-Ausgaben ueberwachen
|
||||
|
||||
304
admin-lehrer/components/grid-editor/GridEditor.tsx
Normal file
304
admin-lehrer/components/grid-editor/GridEditor.tsx
Normal file
@@ -0,0 +1,304 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useGridEditor } from './useGridEditor'
|
||||
import type { GridZone } from './types'
|
||||
import { GridToolbar } from './GridToolbar'
|
||||
import { GridTable } from './GridTable'
|
||||
import { GridImageOverlay } from './GridImageOverlay'
|
||||
|
||||
interface GridEditorProps {
|
||||
sessionId: string | null
|
||||
onNext?: () => void
|
||||
}
|
||||
|
||||
export function GridEditor({ sessionId, onNext }: GridEditorProps) {
|
||||
const {
|
||||
grid,
|
||||
loading,
|
||||
saving,
|
||||
error,
|
||||
dirty,
|
||||
selectedCell,
|
||||
setSelectedCell,
|
||||
buildGrid,
|
||||
loadGrid,
|
||||
saveGrid,
|
||||
updateCellText,
|
||||
toggleColumnBold,
|
||||
toggleRowHeader,
|
||||
undo,
|
||||
redo,
|
||||
canUndo,
|
||||
canRedo,
|
||||
getAdjacentCell,
|
||||
deleteColumn,
|
||||
addColumn,
|
||||
deleteRow,
|
||||
addRow,
|
||||
ipaMode,
|
||||
setIpaMode,
|
||||
syllableMode,
|
||||
setSyllableMode,
|
||||
} = useGridEditor(sessionId)
|
||||
|
||||
const [showOverlay, setShowOverlay] = useState(false)
|
||||
|
||||
// Load grid on mount
|
||||
useEffect(() => {
|
||||
if (sessionId) {
|
||||
loadGrid()
|
||||
}
|
||||
}, [sessionId, loadGrid])
|
||||
|
||||
// Keyboard shortcuts
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'z' && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
undo()
|
||||
} else if ((e.metaKey || e.ctrlKey) && e.key === 'z' && e.shiftKey) {
|
||||
e.preventDefault()
|
||||
redo()
|
||||
} else if ((e.metaKey || e.ctrlKey) && e.key === 's') {
|
||||
e.preventDefault()
|
||||
saveGrid()
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', handler)
|
||||
return () => window.removeEventListener('keydown', handler)
|
||||
}, [undo, redo, saveGrid])
|
||||
|
||||
const handleNavigate = useCallback(
|
||||
(cellId: string, direction: 'up' | 'down' | 'left' | 'right') => {
|
||||
const target = getAdjacentCell(cellId, direction)
|
||||
if (target) {
|
||||
setSelectedCell(target)
|
||||
// Focus the input
|
||||
setTimeout(() => {
|
||||
const el = document.getElementById(`cell-${target}`)
|
||||
if (el) {
|
||||
el.focus()
|
||||
if (el instanceof HTMLInputElement) el.select()
|
||||
}
|
||||
}, 0)
|
||||
}
|
||||
},
|
||||
[getAdjacentCell, setSelectedCell],
|
||||
)
|
||||
|
||||
if (!sessionId) {
|
||||
return (
|
||||
<div className="text-center py-12 text-gray-400">
|
||||
Keine Session ausgewaehlt.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
<div className="flex items-center gap-3 text-gray-500 dark:text-gray-400">
|
||||
<svg className="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
Grid wird aufgebaut...
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
|
||||
<p className="text-sm text-red-700 dark:text-red-300">
|
||||
Fehler: {error}
|
||||
</p>
|
||||
<button
|
||||
onClick={buildGrid}
|
||||
className="mt-2 text-xs px-3 py-1.5 bg-red-600 text-white rounded hover:bg-red-700"
|
||||
>
|
||||
Erneut versuchen
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!grid || !grid.zones.length) {
|
||||
return (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-gray-400 mb-4">Kein Grid vorhanden.</p>
|
||||
<button
|
||||
onClick={buildGrid}
|
||||
className="px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 text-sm"
|
||||
>
|
||||
Grid aus OCR-Ergebnissen erstellen
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Summary bar */}
|
||||
<div className="flex items-center gap-4 text-xs text-gray-500 dark:text-gray-400">
|
||||
<span>{grid.summary.total_zones} Zone(n)</span>
|
||||
<span>{grid.summary.total_columns} Spalten</span>
|
||||
<span>{grid.summary.total_rows} Zeilen</span>
|
||||
<span>{grid.summary.total_cells} Zellen</span>
|
||||
{grid.boxes_detected > 0 && (
|
||||
<span className="text-amber-600 dark:text-amber-400">
|
||||
{grid.boxes_detected} Box(en) erkannt
|
||||
</span>
|
||||
)}
|
||||
{grid.summary.color_stats && Object.entries(grid.summary.color_stats)
|
||||
.filter(([name]) => name !== 'black')
|
||||
.map(([name, count]) => (
|
||||
<span key={name} className="inline-flex items-center gap-1">
|
||||
<span className="w-2 h-2 rounded-full" style={{ backgroundColor: {
|
||||
red: '#dc2626', blue: '#2563eb', green: '#16a34a',
|
||||
orange: '#ea580c', purple: '#9333ea', yellow: '#ca8a04',
|
||||
}[name] || '#6b7280' }} />
|
||||
<span>{count} {name}</span>
|
||||
</span>
|
||||
))
|
||||
}
|
||||
{(grid.summary.recovered_colored ?? 0) > 0 && (
|
||||
<span className="text-purple-600 dark:text-purple-400">
|
||||
+{grid.summary.recovered_colored} recovered
|
||||
</span>
|
||||
)}
|
||||
{grid.dictionary_detection?.is_dictionary && (
|
||||
<span className="px-1.5 py-0.5 rounded bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border border-blue-200 dark:border-blue-800">
|
||||
Woerterbuch ({Math.round(grid.dictionary_detection.confidence * 100)}%)
|
||||
</span>
|
||||
)}
|
||||
{grid.page_number?.text && (
|
||||
<span className="px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 border border-gray-200 dark:border-gray-600">
|
||||
S. {grid.page_number.text}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-gray-400">
|
||||
{grid.duration_seconds.toFixed(1)}s
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Toolbar */}
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-2">
|
||||
<GridToolbar
|
||||
dirty={dirty}
|
||||
saving={saving}
|
||||
canUndo={canUndo}
|
||||
canRedo={canRedo}
|
||||
showOverlay={showOverlay}
|
||||
ipaMode={ipaMode}
|
||||
syllableMode={syllableMode}
|
||||
onSave={saveGrid}
|
||||
onUndo={undo}
|
||||
onRedo={redo}
|
||||
onRebuild={buildGrid}
|
||||
onToggleOverlay={() => setShowOverlay(!showOverlay)}
|
||||
onIpaModeChange={setIpaMode}
|
||||
onSyllableModeChange={setSyllableMode}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Image overlay */}
|
||||
{showOverlay && (
|
||||
<GridImageOverlay sessionId={sessionId} grid={grid} />
|
||||
)}
|
||||
|
||||
{/* Zone tables — group vsplit zones side by side */}
|
||||
<div className="space-y-4">
|
||||
{(() => {
|
||||
// Group consecutive zones with same vsplit_group
|
||||
const groups: GridZone[][] = []
|
||||
for (const zone of grid.zones) {
|
||||
const prev = groups[groups.length - 1]
|
||||
if (
|
||||
prev &&
|
||||
zone.vsplit_group != null &&
|
||||
prev[0].vsplit_group === zone.vsplit_group
|
||||
) {
|
||||
prev.push(zone)
|
||||
} else {
|
||||
groups.push([zone])
|
||||
}
|
||||
}
|
||||
return groups.map((group) =>
|
||||
group.length === 1 ? (
|
||||
<div
|
||||
key={group[0].zone_index}
|
||||
className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden"
|
||||
>
|
||||
<GridTable
|
||||
zone={group[0]}
|
||||
layoutMetrics={grid.layout_metrics}
|
||||
selectedCell={selectedCell}
|
||||
onSelectCell={setSelectedCell}
|
||||
onCellTextChange={updateCellText}
|
||||
onToggleColumnBold={toggleColumnBold}
|
||||
onToggleRowHeader={toggleRowHeader}
|
||||
onNavigate={handleNavigate}
|
||||
onDeleteColumn={deleteColumn}
|
||||
onAddColumn={addColumn}
|
||||
onDeleteRow={deleteRow}
|
||||
onAddRow={addRow}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
key={`vsplit-${group[0].vsplit_group}`}
|
||||
className="flex gap-2"
|
||||
>
|
||||
{group.map((zone) => (
|
||||
<div
|
||||
key={zone.zone_index}
|
||||
className="flex-1 min-w-0 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden"
|
||||
>
|
||||
<GridTable
|
||||
zone={zone}
|
||||
layoutMetrics={grid.layout_metrics}
|
||||
selectedCell={selectedCell}
|
||||
onSelectCell={setSelectedCell}
|
||||
onCellTextChange={updateCellText}
|
||||
onToggleColumnBold={toggleColumnBold}
|
||||
onToggleRowHeader={toggleRowHeader}
|
||||
onNavigate={handleNavigate}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
)
|
||||
})()}
|
||||
</div>
|
||||
|
||||
{/* Tip */}
|
||||
<div className="text-[11px] text-gray-400 dark:text-gray-500 flex items-center gap-4">
|
||||
<span>Tab: naechste Zelle</span>
|
||||
<span>Enter: Zeile runter</span>
|
||||
<span>Spalte fett: Klick auf Spaltenkopf</span>
|
||||
<span>Header: Klick auf Zeilennummer</span>
|
||||
<span>Ctrl+Z/Y: Undo/Redo</span>
|
||||
<span>Ctrl+S: Speichern</span>
|
||||
</div>
|
||||
|
||||
{/* Next step button */}
|
||||
{onNext && (
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
onClick={async () => {
|
||||
if (dirty) await saveGrid()
|
||||
onNext()
|
||||
}}
|
||||
className="px-4 py-2 bg-teal-600 text-white text-sm rounded-lg hover:bg-teal-700 transition-colors"
|
||||
>
|
||||
Fertig
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
98
admin-lehrer/components/grid-editor/GridImageOverlay.tsx
Normal file
98
admin-lehrer/components/grid-editor/GridImageOverlay.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
'use client'
|
||||
|
||||
import type { StructuredGrid } from './types'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface GridImageOverlayProps {
|
||||
sessionId: string
|
||||
grid: StructuredGrid
|
||||
}
|
||||
|
||||
const ZONE_COLORS = [
|
||||
{ border: 'rgba(20,184,166,0.7)', fill: 'rgba(20,184,166,0.05)' }, // teal
|
||||
{ border: 'rgba(245,158,11,0.7)', fill: 'rgba(245,158,11,0.05)' }, // amber
|
||||
{ border: 'rgba(99,102,241,0.7)', fill: 'rgba(99,102,241,0.05)' }, // indigo
|
||||
{ border: 'rgba(236,72,153,0.7)', fill: 'rgba(236,72,153,0.05)' }, // pink
|
||||
]
|
||||
|
||||
export function GridImageOverlay({ sessionId, grid }: GridImageOverlayProps) {
|
||||
const imgUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
|
||||
return (
|
||||
<div className="relative w-full overflow-auto border border-gray-200 dark:border-gray-700 rounded-lg bg-gray-100 dark:bg-gray-900">
|
||||
<div className="relative inline-block">
|
||||
{/* Source image */}
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={imgUrl}
|
||||
alt="OCR Scan"
|
||||
className="block max-w-full"
|
||||
style={{ imageRendering: 'auto' }}
|
||||
/>
|
||||
|
||||
{/* SVG overlay */}
|
||||
<svg
|
||||
className="absolute inset-0 w-full h-full pointer-events-none"
|
||||
viewBox={`0 0 ${grid.image_width} ${grid.image_height}`}
|
||||
preserveAspectRatio="xMinYMin meet"
|
||||
>
|
||||
{grid.zones.map((zone) => {
|
||||
const colors = ZONE_COLORS[zone.zone_index % ZONE_COLORS.length]
|
||||
const b = zone.bbox_px
|
||||
|
||||
return (
|
||||
<g key={zone.zone_index}>
|
||||
{/* Zone border */}
|
||||
<rect
|
||||
x={b.x} y={b.y} width={b.w} height={b.h}
|
||||
fill={colors.fill}
|
||||
stroke={colors.border}
|
||||
strokeWidth={zone.zone_type === 'box' ? 3 : 1.5}
|
||||
strokeDasharray={zone.zone_type === 'box' ? undefined : '6 3'}
|
||||
/>
|
||||
|
||||
{/* Column separators */}
|
||||
{zone.columns.slice(1).map((col) => (
|
||||
<line
|
||||
key={`col-${col.index}`}
|
||||
x1={col.x_min_px} y1={b.y}
|
||||
x2={col.x_min_px} y2={b.y + b.h}
|
||||
stroke={colors.border}
|
||||
strokeWidth={1}
|
||||
strokeDasharray="4 2"
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Row separators */}
|
||||
{zone.rows.slice(1).map((row) => (
|
||||
<line
|
||||
key={`row-${row.index}`}
|
||||
x1={b.x} y1={row.y_min_px}
|
||||
x2={b.x + b.w} y2={row.y_min_px}
|
||||
stroke={colors.border}
|
||||
strokeWidth={0.5}
|
||||
strokeDasharray="3 3"
|
||||
opacity={0.5}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Zone label */}
|
||||
<text
|
||||
x={b.x + 4} y={b.y + 14}
|
||||
fill={colors.border}
|
||||
fontSize={12}
|
||||
fontWeight="bold"
|
||||
fontFamily="monospace"
|
||||
>
|
||||
{zone.zone_type === 'box' ? 'BOX' : 'CONTENT'} Z{zone.zone_index}
|
||||
{' '}({zone.columns.length}x{zone.rows.length})
|
||||
</text>
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
652
admin-lehrer/components/grid-editor/GridTable.tsx
Normal file
652
admin-lehrer/components/grid-editor/GridTable.tsx
Normal file
@@ -0,0 +1,652 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { GridZone, LayoutMetrics } from './types'
|
||||
|
||||
interface GridTableProps {
|
||||
zone: GridZone
|
||||
layoutMetrics?: LayoutMetrics
|
||||
selectedCell: string | null
|
||||
selectedCells?: Set<string>
|
||||
onSelectCell: (cellId: string) => void
|
||||
onToggleCellSelection?: (cellId: string) => void
|
||||
onCellTextChange: (cellId: string, text: string) => void
|
||||
onToggleColumnBold: (zoneIndex: number, colIndex: number) => void
|
||||
onToggleRowHeader: (zoneIndex: number, rowIndex: number) => void
|
||||
onNavigate: (cellId: string, direction: 'up' | 'down' | 'left' | 'right') => void
|
||||
onDeleteColumn?: (zoneIndex: number, colIndex: number) => void
|
||||
onAddColumn?: (zoneIndex: number, afterColIndex: number) => void
|
||||
onDeleteRow?: (zoneIndex: number, rowIndex: number) => void
|
||||
onAddRow?: (zoneIndex: number, afterRowIndex: number) => void
|
||||
onSetCellColor?: (cellId: string, color: string | null | undefined) => void
|
||||
}
|
||||
|
||||
/** Color palette for the right-click cell color menu. */
|
||||
const COLOR_OPTIONS: { label: string; value: string | null }[] = [
|
||||
{ label: 'Rot', value: '#dc2626' },
|
||||
{ label: 'Gruen', value: '#16a34a' },
|
||||
{ label: 'Blau', value: '#2563eb' },
|
||||
{ label: 'Orange', value: '#ea580c' },
|
||||
{ label: 'Lila', value: '#9333ea' },
|
||||
{ label: 'Schwarz', value: null },
|
||||
]
|
||||
|
||||
/** Gutter width for row numbers (px). */
|
||||
const ROW_NUM_WIDTH = 36
|
||||
|
||||
/** Minimum column width in px so columns remain usable. */
|
||||
const MIN_COL_WIDTH = 80
|
||||
|
||||
/** Minimum row height in px. */
|
||||
const MIN_ROW_HEIGHT = 26
|
||||
|
||||
export function GridTable({
|
||||
zone,
|
||||
layoutMetrics,
|
||||
selectedCell,
|
||||
selectedCells,
|
||||
onSelectCell,
|
||||
onToggleCellSelection,
|
||||
onCellTextChange,
|
||||
onToggleColumnBold,
|
||||
onToggleRowHeader,
|
||||
onNavigate,
|
||||
onDeleteColumn,
|
||||
onAddColumn,
|
||||
onDeleteRow,
|
||||
onAddRow,
|
||||
onSetCellColor,
|
||||
}: GridTableProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const [containerWidth, setContainerWidth] = useState(0)
|
||||
const [colorMenu, setColorMenu] = useState<{ cellId: string; x: number; y: number } | null>(null)
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Observe container width for scaling
|
||||
// ----------------------------------------------------------------
|
||||
useEffect(() => {
|
||||
const el = containerRef.current
|
||||
if (!el) return
|
||||
const ro = new ResizeObserver(([entry]) => {
|
||||
setContainerWidth(entry.contentRect.width)
|
||||
})
|
||||
ro.observe(el)
|
||||
return () => ro.disconnect()
|
||||
}, [])
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Compute column widths from OCR measurements
|
||||
// ----------------------------------------------------------------
|
||||
// Use the actual total column span as reference width — NOT zone.bbox_px.w.
|
||||
// When union columns are applied across content zones, column boundaries
|
||||
// can extend beyond the zone's bbox, causing overflow if we scale by
|
||||
// the smaller zone width.
|
||||
const [colWidthOverrides, setColWidthOverrides] = useState<number[] | null>(null)
|
||||
|
||||
const columnWidthsPx = zone.columns.map((col) => col.x_max_px - col.x_min_px)
|
||||
const totalColWidthPx = columnWidthsPx.reduce((sum, w) => sum + w, 0)
|
||||
const zoneWidthPx = totalColWidthPx > 0
|
||||
? totalColWidthPx
|
||||
: (zone.bbox_px.w || layoutMetrics?.page_width_px || 1)
|
||||
const scale = containerWidth > 0 ? (containerWidth - ROW_NUM_WIDTH) / zoneWidthPx : 1
|
||||
|
||||
const effectiveColWidths = (colWidthOverrides ?? columnWidthsPx).map(
|
||||
(w) => Math.max(MIN_COL_WIDTH, w * scale),
|
||||
)
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Compute row heights from OCR measurements
|
||||
// ----------------------------------------------------------------
|
||||
const avgRowHeightPx = layoutMetrics?.avg_row_height_px ?? 30
|
||||
const [rowHeightOverrides, setRowHeightOverrides] = useState<Map<number, number>>(new Map())
|
||||
|
||||
const getRowHeight = (rowIndex: number, isHeader: boolean): number => {
|
||||
if (rowHeightOverrides.has(rowIndex)) {
|
||||
return rowHeightOverrides.get(rowIndex)!
|
||||
}
|
||||
const row = zone.rows.find((r) => r.index === rowIndex)
|
||||
if (!row) return Math.max(MIN_ROW_HEIGHT, avgRowHeightPx * scale)
|
||||
|
||||
// Multi-line cells (containing \n): expand height based on line count
|
||||
const rowCells = zone.cells.filter((c) => c.row_index === rowIndex)
|
||||
const maxLines = Math.max(1, ...rowCells.map((c) => (c.text ?? '').split('\n').length))
|
||||
if (maxLines > 1) {
|
||||
const lineH = Math.max(MIN_ROW_HEIGHT, avgRowHeightPx * scale)
|
||||
return lineH * maxLines
|
||||
}
|
||||
|
||||
if (isHeader) {
|
||||
const measuredH = row.y_max_px - row.y_min_px
|
||||
return Math.max(MIN_ROW_HEIGHT, measuredH * scale)
|
||||
}
|
||||
return Math.max(MIN_ROW_HEIGHT, avgRowHeightPx * scale)
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Font size from layout metrics
|
||||
// ----------------------------------------------------------------
|
||||
const baseFontSize = layoutMetrics?.font_size_suggestion_px
|
||||
? Math.max(11, layoutMetrics.font_size_suggestion_px * scale)
|
||||
: 13
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Keyboard navigation
|
||||
// ----------------------------------------------------------------
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent, cellId: string) => {
|
||||
if (e.key === 'Tab') {
|
||||
e.preventDefault()
|
||||
onNavigate(cellId, e.shiftKey ? 'left' : 'right')
|
||||
} else if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
onNavigate(cellId, 'down')
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
onNavigate(cellId, 'up')
|
||||
} else if (e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
onNavigate(cellId, 'down')
|
||||
} else if (e.key === 'ArrowLeft' && e.altKey) {
|
||||
e.preventDefault()
|
||||
onNavigate(cellId, 'left')
|
||||
} else if (e.key === 'ArrowRight' && e.altKey) {
|
||||
e.preventDefault()
|
||||
onNavigate(cellId, 'right')
|
||||
} else if (e.key === 'Escape') {
|
||||
;(e.target as HTMLElement).blur()
|
||||
}
|
||||
},
|
||||
[onNavigate],
|
||||
)
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Cell lookup
|
||||
// ----------------------------------------------------------------
|
||||
const cellMap = new Map<string, (typeof zone.cells)[0]>()
|
||||
for (const cell of zone.cells) {
|
||||
cellMap.set(`${cell.row_index}_${cell.col_index}`, cell)
|
||||
}
|
||||
|
||||
/** Dominant non-black color from a cell's word_boxes, or null.
|
||||
* `color_override` takes priority when set. */
|
||||
const getCellColor = (cell: (typeof zone.cells)[0] | undefined): string | null => {
|
||||
if (!cell) return null
|
||||
// Manual override: explicit color or null (= "clear color bar")
|
||||
if (cell.color_override !== undefined) return cell.color_override ?? null
|
||||
if (!cell.word_boxes?.length) return null
|
||||
for (const wb of cell.word_boxes) {
|
||||
if (wb.color_name && wb.color_name !== 'black' && wb.color) {
|
||||
return wb.color
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Column resize (drag)
|
||||
// ----------------------------------------------------------------
|
||||
const handleColResizeStart = useCallback(
|
||||
(colIndex: number, startX: number) => {
|
||||
const baseWidths = colWidthOverrides ?? [...columnWidthsPx]
|
||||
|
||||
const handleMouseMove = (e: MouseEvent) => {
|
||||
const deltaPx = (e.clientX - startX) / scale
|
||||
const newWidths = [...baseWidths]
|
||||
newWidths[colIndex] = Math.max(20, baseWidths[colIndex] + deltaPx)
|
||||
// Steal from next column to keep total constant
|
||||
if (colIndex + 1 < newWidths.length) {
|
||||
newWidths[colIndex + 1] = Math.max(20, baseWidths[colIndex + 1] - deltaPx)
|
||||
}
|
||||
setColWidthOverrides(newWidths)
|
||||
}
|
||||
|
||||
const handleMouseUp = () => {
|
||||
document.removeEventListener('mousemove', handleMouseMove)
|
||||
document.removeEventListener('mouseup', handleMouseUp)
|
||||
document.body.style.cursor = ''
|
||||
document.body.style.userSelect = ''
|
||||
}
|
||||
|
||||
document.body.style.cursor = 'col-resize'
|
||||
document.body.style.userSelect = 'none'
|
||||
document.addEventListener('mousemove', handleMouseMove)
|
||||
document.addEventListener('mouseup', handleMouseUp)
|
||||
},
|
||||
[colWidthOverrides, columnWidthsPx, scale],
|
||||
)
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Row resize (drag)
|
||||
// ----------------------------------------------------------------
|
||||
const handleRowResizeStart = useCallback(
|
||||
(rowIndex: number, startY: number, currentHeight: number) => {
|
||||
const handleMouseMove = (e: MouseEvent) => {
|
||||
const delta = e.clientY - startY
|
||||
const newH = Math.max(MIN_ROW_HEIGHT, currentHeight + delta)
|
||||
setRowHeightOverrides((prev) => {
|
||||
const next = new Map(prev)
|
||||
next.set(rowIndex, newH)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const handleMouseUp = () => {
|
||||
document.removeEventListener('mousemove', handleMouseMove)
|
||||
document.removeEventListener('mouseup', handleMouseUp)
|
||||
document.body.style.cursor = ''
|
||||
document.body.style.userSelect = ''
|
||||
}
|
||||
|
||||
document.body.style.cursor = 'row-resize'
|
||||
document.body.style.userSelect = 'none'
|
||||
document.addEventListener('mousemove', handleMouseMove)
|
||||
document.addEventListener('mouseup', handleMouseUp)
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
const isBoxZone = zone.zone_type === 'box'
|
||||
const numCols = zone.columns.length
|
||||
|
||||
// CSS Grid template for columns: row-number gutter + proportional columns
|
||||
const gridTemplateCols = `${ROW_NUM_WIDTH}px ${effectiveColWidths.map((w) => `${w.toFixed(1)}px`).join(' ')}`
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={`overflow-x-auto ${isBoxZone ? 'border-2 border-gray-400 dark:border-gray-500 rounded-lg' : ''}`}
|
||||
>
|
||||
{/* Zone label */}
|
||||
<div className="flex items-center gap-2 px-2 py-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
<span
|
||||
className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${
|
||||
isBoxZone
|
||||
? 'bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-300 border border-amber-200 dark:border-amber-800'
|
||||
: 'bg-gray-50 dark:bg-gray-800 text-gray-500 dark:text-gray-400 border border-gray-200 dark:border-gray-700'
|
||||
}`}
|
||||
>
|
||||
{isBoxZone ? 'Box' : 'Inhalt'} Zone {zone.zone_index}
|
||||
</span>
|
||||
<span>
|
||||
{zone.columns.length} Spalten, {zone.rows.length} Zeilen, {zone.cells.length} Zellen
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* ============================================================ */}
|
||||
{/* CSS Grid — column headers */}
|
||||
{/* ============================================================ */}
|
||||
<div
|
||||
style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: gridTemplateCols,
|
||||
fontFamily: "var(--font-noto-sans, 'Noto Sans'), 'Inter', system-ui, sans-serif",
|
||||
fontSize: `${baseFontSize}px`,
|
||||
}}
|
||||
>
|
||||
{/* Header: row-number corner */}
|
||||
<div className="sticky left-0 z-10 px-1 py-1.5 text-[10px] text-gray-400 dark:text-gray-500 border-b border-r border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50" />
|
||||
|
||||
{/* Header: column labels with resize handles + delete/add */}
|
||||
{zone.columns.map((col, ci) => (
|
||||
<div
|
||||
key={col.index}
|
||||
className={`group/colhdr relative px-2 py-1.5 text-xs font-medium border-b border-r border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 cursor-pointer select-none transition-colors hover:bg-gray-100 dark:hover:bg-gray-700 ${
|
||||
col.bold ? 'text-teal-700 dark:text-teal-300' : 'text-gray-600 dark:text-gray-400'
|
||||
}`}
|
||||
onClick={() => onToggleColumnBold(zone.zone_index, col.index)}
|
||||
title={`Spalte ${col.index + 1} — Klick fuer Fett-Toggle`}
|
||||
>
|
||||
<div className="flex items-center gap-1 justify-center truncate">
|
||||
<span>{col.label}</span>
|
||||
{col.bold && (
|
||||
<span className="text-[9px] px-1 py-0 rounded bg-teal-100 dark:bg-teal-900/40 text-teal-600 dark:text-teal-400">
|
||||
B
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{/* Delete column button (visible on hover) */}
|
||||
{onDeleteColumn && numCols > 1 && (
|
||||
<button
|
||||
className="absolute top-0 left-0 w-4 h-4 flex items-center justify-center bg-red-500 text-white rounded-br text-[9px] leading-none opacity-0 group-hover/colhdr:opacity-100 transition-opacity z-30"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (confirm(`Spalte "${col.label}" loeschen?`)) {
|
||||
onDeleteColumn(zone.zone_index, col.index)
|
||||
}
|
||||
}}
|
||||
title={`Spalte "${col.label}" loeschen`}
|
||||
>
|
||||
x
|
||||
</button>
|
||||
)}
|
||||
{/* Add column button — small icon at bottom-right, below resize handle */}
|
||||
{onAddColumn && (
|
||||
<button
|
||||
className="absolute -right-[7px] -bottom-[7px] w-[14px] h-[14px] flex items-center justify-center text-teal-500 opacity-0 group-hover/colhdr:opacity-100 transition-opacity z-30 hover:bg-teal-100 dark:hover:bg-teal-900/40 rounded-full bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onAddColumn(zone.zone_index, col.index)
|
||||
}}
|
||||
title={`Spalte nach "${col.label}" einfuegen`}
|
||||
>
|
||||
<svg className="w-2.5 h-2.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
{/* Right-edge resize handle — wide grab area, highest z-index */}
|
||||
{ci < numCols - 1 && (
|
||||
<div
|
||||
className="absolute top-0 -right-[4px] w-[9px] h-full cursor-col-resize hover:bg-teal-400/40 z-40"
|
||||
onMouseDown={(e) => {
|
||||
e.stopPropagation()
|
||||
handleColResizeStart(ci, e.clientX)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* ============================================================ */}
|
||||
{/* Data rows */}
|
||||
{/* ============================================================ */}
|
||||
{zone.rows.map((row) => {
|
||||
const rowH = getRowHeight(row.index, row.is_header)
|
||||
const isSpanning = zone.cells.some(
|
||||
(c) => c.row_index === row.index && c.col_type === 'spanning_header',
|
||||
)
|
||||
|
||||
return (
|
||||
<div key={row.index} style={{ display: 'contents' }}>
|
||||
{/* Row number cell */}
|
||||
<div
|
||||
className={`group/rowhdr relative sticky left-0 z-10 flex items-center justify-center text-[10px] border-b border-r border-gray-200 dark:border-gray-700 cursor-pointer select-none transition-colors hover:bg-gray-100 dark:hover:bg-gray-700 ${
|
||||
row.is_header
|
||||
? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 font-medium'
|
||||
: row.is_footer
|
||||
? 'bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400 font-medium'
|
||||
: 'bg-gray-50 dark:bg-gray-800/50 text-gray-400 dark:text-gray-500'
|
||||
}`}
|
||||
style={{ height: `${rowH}px` }}
|
||||
onClick={() => onToggleRowHeader(zone.zone_index, row.index)}
|
||||
title={`Zeile ${row.index + 1} — Klick: ${row.is_header ? 'Footer' : row.is_footer ? 'Normal' : 'Header'}`}
|
||||
>
|
||||
{row.index + 1}
|
||||
{row.is_header && <span className="block text-[8px]">H</span>}
|
||||
{row.is_footer && <span className="block text-[8px]">F</span>}
|
||||
{/* Delete row button (visible on hover) */}
|
||||
{onDeleteRow && zone.rows.length > 1 && (
|
||||
<button
|
||||
className="absolute top-0 left-0 w-4 h-4 flex items-center justify-center bg-red-500 text-white rounded-br text-[9px] leading-none opacity-0 group-hover/rowhdr:opacity-100 transition-opacity z-30"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (confirm(`Zeile ${row.index + 1} loeschen?`)) {
|
||||
onDeleteRow(zone.zone_index, row.index)
|
||||
}
|
||||
}}
|
||||
title={`Zeile ${row.index + 1} loeschen`}
|
||||
>
|
||||
x
|
||||
</button>
|
||||
)}
|
||||
{/* Add row button (visible on hover, below this row) */}
|
||||
{onAddRow && (
|
||||
<button
|
||||
className="absolute -bottom-[7px] left-0 w-full h-[14px] flex items-center justify-center text-teal-500 opacity-0 group-hover/rowhdr:opacity-100 transition-opacity z-30 hover:bg-teal-100 dark:hover:bg-teal-900/40 rounded"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onAddRow(zone.zone_index, row.index)
|
||||
}}
|
||||
title={`Zeile nach ${row.index + 1} einfuegen`}
|
||||
>
|
||||
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
{/* Bottom-edge resize handle */}
|
||||
<div
|
||||
className="absolute bottom-0 left-0 w-full h-[4px] cursor-row-resize hover:bg-teal-400/40 z-20"
|
||||
onMouseDown={(e) => {
|
||||
e.stopPropagation()
|
||||
handleRowResizeStart(row.index, e.clientY, rowH)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Cells — spanning header or normal columns */}
|
||||
{isSpanning ? (
|
||||
<>
|
||||
{zone.cells
|
||||
.filter((c) => c.row_index === row.index && c.col_type === 'spanning_header')
|
||||
.sort((a, b) => a.col_index - b.col_index)
|
||||
.map((spanCell) => {
|
||||
const colspan = spanCell.colspan || numCols
|
||||
const cellId = spanCell.cell_id
|
||||
const isSelected = selectedCell === cellId
|
||||
const cellColor = getCellColor(spanCell)
|
||||
const gridColStart = spanCell.col_index + 2
|
||||
const gridColEnd = gridColStart + colspan
|
||||
return (
|
||||
<div
|
||||
key={cellId}
|
||||
className={`border-b border-r border-gray-200 dark:border-gray-700 bg-blue-50/50 dark:bg-blue-900/10 flex items-center ${
|
||||
isSelected ? 'ring-2 ring-teal-500 ring-inset z-10' : ''
|
||||
}`}
|
||||
style={{ gridColumn: `${gridColStart} / ${gridColEnd}`, height: `${rowH}px` }}
|
||||
>
|
||||
{cellColor && (
|
||||
<span className="flex-shrink-0 w-1.5 self-stretch rounded-l-sm" style={{ backgroundColor: cellColor }} />
|
||||
)}
|
||||
<input
|
||||
id={`cell-${cellId}`}
|
||||
type="text"
|
||||
value={spanCell.text}
|
||||
onChange={(e) => onCellTextChange(cellId, e.target.value)}
|
||||
onFocus={() => onSelectCell(cellId)}
|
||||
onKeyDown={(e) => handleKeyDown(e, cellId)}
|
||||
className="w-full px-3 py-1 bg-transparent border-0 outline-none text-center"
|
||||
style={{ color: cellColor || undefined }}
|
||||
spellCheck={false}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</>
|
||||
) : (
|
||||
zone.columns.map((col) => {
|
||||
const cell = cellMap.get(`${row.index}_${col.index}`)
|
||||
const cellId =
|
||||
cell?.cell_id ??
|
||||
`Z${zone.zone_index}_R${String(row.index).padStart(2, '0')}_C${col.index}`
|
||||
const isSelected = selectedCell === cellId
|
||||
const isBold = col.bold || cell?.is_bold
|
||||
const isLowConf = cell && cell.confidence > 0 && cell.confidence < 60
|
||||
const isMultiSelected = selectedCells?.has(cellId)
|
||||
// Show per-word colored display only when word_boxes
|
||||
// match the cell text. Post-processing steps (e.g. 5h
|
||||
// slash-IPA → bracket conversion) modify cell.text but
|
||||
// not individual word_boxes, so we fall back to the
|
||||
// plain input when they diverge.
|
||||
const wbText = cell?.word_boxes?.map((wb) => wb.text).join(' ') ?? ''
|
||||
const textMatches = !cell?.text || wbText === cell.text
|
||||
// Color: prefer manual override, else word_boxes when text matches
|
||||
const hasOverride = cell?.color_override !== undefined
|
||||
const cellColor = hasOverride ? getCellColor(cell) : (textMatches ? getCellColor(cell) : null)
|
||||
const hasColoredWords =
|
||||
!hasOverride &&
|
||||
textMatches &&
|
||||
(cell?.word_boxes?.some(
|
||||
(wb) => wb.color_name && wb.color_name !== 'black',
|
||||
) ?? false)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={col.index}
|
||||
className={`relative border-b border-r border-gray-200 dark:border-gray-700 flex items-center ${
|
||||
isSelected ? 'ring-2 ring-teal-500 ring-inset z-10' : ''
|
||||
} ${isMultiSelected ? 'bg-teal-50/60 dark:bg-teal-900/20' : ''} ${
|
||||
isLowConf && !isMultiSelected ? 'bg-amber-50/50 dark:bg-amber-900/10' : ''
|
||||
} ${row.is_header && !isMultiSelected ? 'bg-blue-50/50 dark:bg-blue-900/10' : ''}`}
|
||||
style={{
|
||||
height: `${rowH}px`,
|
||||
...(cell?.box_region?.bg_hex ? {
|
||||
backgroundColor: `${cell.box_region.bg_hex}12`,
|
||||
borderLeft: cell.box_region.border ? `3px solid ${cell.box_region.bg_hex}60` : undefined,
|
||||
} : {}),
|
||||
}}
|
||||
onContextMenu={(e) => {
|
||||
if (onSetCellColor) {
|
||||
e.preventDefault()
|
||||
setColorMenu({ cellId, x: e.clientX, y: e.clientY })
|
||||
}
|
||||
}}
|
||||
>
|
||||
{cellColor && (
|
||||
<span
|
||||
className="flex-shrink-0 w-1.5 self-stretch rounded-l-sm"
|
||||
style={{ backgroundColor: cellColor }}
|
||||
title={`Farbe: ${cell?.word_boxes?.find((wb) => wb.color_name !== 'black')?.color_name}`}
|
||||
/>
|
||||
)}
|
||||
{/* Per-word colored display when not editing */}
|
||||
{(() => {
|
||||
const cellText = cell?.text ?? ''
|
||||
const isMultiLine = cellText.includes('\n')
|
||||
if (hasColoredWords && !isSelected) {
|
||||
return (
|
||||
<div
|
||||
className={`w-full px-2 cursor-text truncate ${isBold ? 'font-bold' : 'font-normal'}`}
|
||||
onClick={(e) => {
|
||||
if ((e.metaKey || e.ctrlKey) && onToggleCellSelection) {
|
||||
onToggleCellSelection(cellId)
|
||||
} else {
|
||||
onSelectCell(cellId)
|
||||
setTimeout(() => document.getElementById(`cell-${cellId}`)?.focus(), 0)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{cell!.word_boxes!.map((wb, i) => (
|
||||
<span
|
||||
key={i}
|
||||
style={
|
||||
wb.color_name && wb.color_name !== 'black'
|
||||
? { color: wb.color }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{wb.text}
|
||||
{i < cell!.word_boxes!.length - 1 ? ' ' : ''}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (isMultiLine) {
|
||||
return (
|
||||
<textarea
|
||||
id={`cell-${cellId}`}
|
||||
value={cellText}
|
||||
onChange={(e) => onCellTextChange(cellId, e.target.value)}
|
||||
onFocus={() => onSelectCell(cellId)}
|
||||
onClick={(e) => {
|
||||
if ((e.metaKey || e.ctrlKey) && onToggleCellSelection) {
|
||||
e.preventDefault()
|
||||
onToggleCellSelection(cellId)
|
||||
}
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Tab') {
|
||||
e.preventDefault()
|
||||
onNavigate(cellId, e.shiftKey ? 'left' : 'right')
|
||||
}
|
||||
}}
|
||||
rows={cellText.split('\n').length}
|
||||
className={`w-full px-2 bg-transparent border-0 outline-none resize-none ${
|
||||
isBold ? 'font-bold' : 'font-normal'
|
||||
}`}
|
||||
style={{ color: cellColor || undefined }}
|
||||
spellCheck={false}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<input
|
||||
id={`cell-${cellId}`}
|
||||
type="text"
|
||||
value={cellText}
|
||||
onChange={(e) => onCellTextChange(cellId, e.target.value)}
|
||||
onFocus={() => onSelectCell(cellId)}
|
||||
onClick={(e) => {
|
||||
if ((e.metaKey || e.ctrlKey) && onToggleCellSelection) {
|
||||
e.preventDefault()
|
||||
onToggleCellSelection(cellId)
|
||||
}
|
||||
}}
|
||||
onKeyDown={(e) => handleKeyDown(e, cellId)}
|
||||
className={`w-full px-2 bg-transparent border-0 outline-none ${
|
||||
isBold ? 'font-bold' : 'font-normal'
|
||||
}`}
|
||||
style={{ color: cellColor || undefined }}
|
||||
spellCheck={false}
|
||||
/>
|
||||
)
|
||||
})()}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Color context menu (right-click) */}
|
||||
{colorMenu && onSetCellColor && (
|
||||
<div
|
||||
className="fixed inset-0 z-50"
|
||||
onClick={() => setColorMenu(null)}
|
||||
onContextMenu={(e) => { e.preventDefault(); setColorMenu(null) }}
|
||||
>
|
||||
<div
|
||||
className="absolute bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 py-1 min-w-[140px]"
|
||||
style={{ left: colorMenu.x, top: colorMenu.y }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="px-3 py-1 text-[10px] text-gray-400 dark:text-gray-500 font-medium uppercase tracking-wider">
|
||||
Textfarbe
|
||||
</div>
|
||||
{COLOR_OPTIONS.map((opt) => (
|
||||
<button
|
||||
key={opt.label}
|
||||
className="w-full px-3 py-1.5 text-xs text-left hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2"
|
||||
onClick={() => {
|
||||
onSetCellColor(colorMenu.cellId, opt.value)
|
||||
setColorMenu(null)
|
||||
}}
|
||||
>
|
||||
{opt.value ? (
|
||||
<span className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: opt.value }} />
|
||||
) : (
|
||||
<span className="w-3 h-3 rounded-full flex-shrink-0 border border-gray-300 dark:border-gray-600" />
|
||||
)}
|
||||
<span>{opt.label}</span>
|
||||
</button>
|
||||
))}
|
||||
<div className="border-t border-gray-100 dark:border-gray-700 mt-1 pt-1">
|
||||
<button
|
||||
className="w-full px-3 py-1.5 text-xs text-left hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-500 dark:text-gray-400"
|
||||
onClick={() => {
|
||||
onSetCellColor(colorMenu.cellId, undefined)
|
||||
setColorMenu(null)
|
||||
}}
|
||||
>
|
||||
Farbe zuruecksetzen (OCR)
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
170
admin-lehrer/components/grid-editor/GridToolbar.tsx
Normal file
170
admin-lehrer/components/grid-editor/GridToolbar.tsx
Normal file
@@ -0,0 +1,170 @@
|
||||
'use client'
|
||||
|
||||
import type { IpaMode, SyllableMode } from './useGridEditor'
|
||||
|
||||
interface GridToolbarProps {
|
||||
dirty: boolean
|
||||
saving: boolean
|
||||
canUndo: boolean
|
||||
canRedo: boolean
|
||||
showOverlay: boolean
|
||||
ipaMode: IpaMode
|
||||
syllableMode: SyllableMode
|
||||
onSave: () => void
|
||||
onUndo: () => void
|
||||
onRedo: () => void
|
||||
onRebuild: () => void
|
||||
onToggleOverlay: () => void
|
||||
onIpaModeChange: (mode: IpaMode) => void
|
||||
onSyllableModeChange: (mode: SyllableMode) => void
|
||||
}
|
||||
|
||||
const IPA_LABELS: Record<IpaMode, string> = {
|
||||
auto: 'IPA: Auto',
|
||||
en: 'IPA: nur EN',
|
||||
de: 'IPA: nur DE',
|
||||
all: 'IPA: Alle',
|
||||
none: 'IPA: Aus',
|
||||
}
|
||||
|
||||
const SYLLABLE_LABELS: Record<SyllableMode, string> = {
|
||||
auto: 'Silben: Original',
|
||||
en: 'Silben: nur EN',
|
||||
de: 'Silben: nur DE',
|
||||
all: 'Silben: Alle',
|
||||
none: 'Silben: Aus',
|
||||
}
|
||||
|
||||
export function GridToolbar({
|
||||
dirty,
|
||||
saving,
|
||||
canUndo,
|
||||
canRedo,
|
||||
showOverlay,
|
||||
ipaMode,
|
||||
syllableMode,
|
||||
onSave,
|
||||
onUndo,
|
||||
onRedo,
|
||||
onRebuild,
|
||||
onToggleOverlay,
|
||||
onIpaModeChange,
|
||||
onSyllableModeChange,
|
||||
}: GridToolbarProps) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{/* Undo / Redo */}
|
||||
<div className="flex items-center gap-1 border-r border-gray-200 dark:border-gray-700 pr-2">
|
||||
<button
|
||||
onClick={onUndo}
|
||||
disabled={!canUndo}
|
||||
className="p-1.5 rounded hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-30 disabled:cursor-not-allowed"
|
||||
title="Rueckgaengig (Ctrl+Z)"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M3 10h10a5 5 0 015 5v2M3 10l4-4M3 10l4 4" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
onClick={onRedo}
|
||||
disabled={!canRedo}
|
||||
className="p-1.5 rounded hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-30 disabled:cursor-not-allowed"
|
||||
title="Wiederholen (Ctrl+Shift+Z)"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M21 10H11a5 5 0 00-5 5v2M21 10l-4-4M21 10l-4 4" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Overlay toggle */}
|
||||
<button
|
||||
onClick={onToggleOverlay}
|
||||
className={`flex items-center gap-1 px-2.5 py-1.5 text-xs rounded-md border transition-colors ${
|
||||
showOverlay
|
||||
? 'bg-teal-50 dark:bg-teal-900/30 border-teal-300 dark:border-teal-700 text-teal-700 dark:text-teal-300'
|
||||
: 'border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
title="Grid auf Bild anzeigen"
|
||||
>
|
||||
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z" />
|
||||
</svg>
|
||||
Bild-Overlay
|
||||
</button>
|
||||
|
||||
{/* IPA mode */}
|
||||
<div className="flex items-center gap-1">
|
||||
<select
|
||||
value={ipaMode}
|
||||
onChange={(e) => onIpaModeChange(e.target.value as IpaMode)}
|
||||
className="px-2 py-1.5 text-xs rounded-md border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-400"
|
||||
title="Lautschrift (IPA): Auto = nur erkannte EN-Woerter, DE = deutsches IPA (Wiktionary), Alle = EN + DE, Aus = keine"
|
||||
>
|
||||
{(Object.keys(IPA_LABELS) as IpaMode[]).map((m) => (
|
||||
<option key={m} value={m}>{IPA_LABELS[m]}</option>
|
||||
))}
|
||||
</select>
|
||||
{(ipaMode === 'de' || ipaMode === 'all') && (
|
||||
<span
|
||||
className="text-[9px] text-gray-400 dark:text-gray-500 cursor-help"
|
||||
title="DE-Lautschrift: Wiktionary (CC-BY-SA 4.0) + epitran (MIT). EN-Lautschrift: Britfone (MIT) + eng_to_ipa (MIT)."
|
||||
>
|
||||
CC-BY-SA
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Syllable mode */}
|
||||
<select
|
||||
value={syllableMode}
|
||||
onChange={(e) => onSyllableModeChange(e.target.value as SyllableMode)}
|
||||
className="px-2 py-1.5 text-xs rounded-md border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-400"
|
||||
title="Silbentrennung: Original = nur wo im Scan vorhanden, Alle = fuer alle Woerter, Aus = keine"
|
||||
>
|
||||
{(Object.keys(SYLLABLE_LABELS) as SyllableMode[]).map((m) => (
|
||||
<option key={m} value={m}>{SYLLABLE_LABELS[m]}</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
{/* Rebuild */}
|
||||
<button
|
||||
onClick={onRebuild}
|
||||
className="flex items-center gap-1 px-2.5 py-1.5 text-xs rounded-md border border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
|
||||
title="Grid neu berechnen"
|
||||
>
|
||||
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
|
||||
</svg>
|
||||
Neu berechnen
|
||||
</button>
|
||||
|
||||
{/* Spacer */}
|
||||
<div className="flex-1" />
|
||||
|
||||
{/* Save */}
|
||||
<button
|
||||
onClick={onSave}
|
||||
disabled={!dirty || saving}
|
||||
className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${
|
||||
dirty
|
||||
? 'bg-teal-600 text-white hover:bg-teal-700'
|
||||
: 'bg-gray-100 dark:bg-gray-800 text-gray-400 cursor-not-allowed'
|
||||
}`}
|
||||
title="Speichern (Ctrl+S)"
|
||||
>
|
||||
{saving ? (
|
||||
<svg className="w-3.5 h-3.5 animate-spin" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
|
||||
</svg>
|
||||
)}
|
||||
{saving ? 'Speichert...' : dirty ? 'Speichern' : 'Gespeichert'}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
386
admin-lehrer/components/grid-editor/ImageLayoutEditor.tsx
Normal file
386
admin-lehrer/components/grid-editor/ImageLayoutEditor.tsx
Normal file
@@ -0,0 +1,386 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* ImageLayoutEditor — SVG overlay on the original scan image.
|
||||
*
|
||||
* Shows draggable vertical column dividers and horizontal guidelines
|
||||
* (margins, header/footer zones). Double-click to add a column,
|
||||
* click the × on a divider to remove it.
|
||||
*/
|
||||
|
||||
import { useCallback, useRef } from 'react'
|
||||
import type { GridZone, LayoutDividers } from './types'
|
||||
|
||||
interface ImageLayoutEditorProps {
|
||||
imageUrl: string
|
||||
zones: GridZone[]
|
||||
imageWidth: number
|
||||
layoutDividers?: LayoutDividers
|
||||
zoom: number
|
||||
onZoomChange: (zoom: number) => void
|
||||
onColumnDividerMove: (zoneIndex: number, boundaryIndex: number, newXPct: number) => void
|
||||
onHorizontalsChange: (horizontals: LayoutDividers['horizontals']) => void
|
||||
onCommitUndo: () => void
|
||||
onSplitColumnAt: (zoneIndex: number, xPct: number) => void
|
||||
onDeleteColumn: (zoneIndex: number, colIndex: number) => void
|
||||
}
|
||||
|
||||
const HORIZ_COLORS: Record<string, string> = {
|
||||
top_margin: 'rgba(239, 68, 68, 0.6)',
|
||||
header_bottom: 'rgba(59, 130, 246, 0.6)',
|
||||
footer_top: 'rgba(249, 115, 22, 0.6)',
|
||||
bottom_margin: 'rgba(239, 68, 68, 0.6)',
|
||||
}
|
||||
|
||||
const HORIZ_LABELS: Record<string, string> = {
|
||||
top_margin: 'Rand oben',
|
||||
header_bottom: 'Kopfzeile',
|
||||
footer_top: 'Fusszeile',
|
||||
bottom_margin: 'Rand unten',
|
||||
}
|
||||
|
||||
const HORIZ_DEFAULTS: Record<string, number> = {
|
||||
top_margin: 3,
|
||||
header_bottom: 10,
|
||||
footer_top: 92,
|
||||
bottom_margin: 97,
|
||||
}
|
||||
|
||||
function clamp(val: number, min: number, max: number) {
|
||||
return Math.max(min, Math.min(max, val))
|
||||
}
|
||||
|
||||
export function ImageLayoutEditor({
|
||||
imageUrl,
|
||||
zones,
|
||||
layoutDividers,
|
||||
zoom,
|
||||
onZoomChange,
|
||||
onColumnDividerMove,
|
||||
onHorizontalsChange,
|
||||
onCommitUndo,
|
||||
onSplitColumnAt,
|
||||
onDeleteColumn,
|
||||
}: ImageLayoutEditorProps) {
|
||||
const wrapperRef = useRef<HTMLDivElement>(null)
|
||||
const draggingRef = useRef<
|
||||
| { type: 'col'; zoneIndex: number; boundaryIndex: number }
|
||||
| { type: 'horiz'; key: string }
|
||||
| null
|
||||
>(null)
|
||||
const horizontalsRef = useRef(layoutDividers?.horizontals ?? {})
|
||||
horizontalsRef.current = layoutDividers?.horizontals ?? {}
|
||||
|
||||
const horizontals = layoutDividers?.horizontals ?? {}
|
||||
|
||||
// Compute column boundaries for each zone
|
||||
const zoneBoundaries = zones.map((zone) => {
|
||||
const sorted = [...zone.columns].sort((a, b) => a.index - b.index)
|
||||
const boundaries: number[] = []
|
||||
if (sorted.length > 0) {
|
||||
const hasValidPct = sorted.some((c) => c.x_max_pct > 0)
|
||||
if (hasValidPct) {
|
||||
boundaries.push(sorted[0].x_min_pct)
|
||||
for (const col of sorted) {
|
||||
boundaries.push(col.x_max_pct)
|
||||
}
|
||||
} else {
|
||||
// Fallback: evenly distribute within zone bbox
|
||||
const zoneX = zone.bbox_pct.x || 0
|
||||
const zoneW = zone.bbox_pct.w || 100
|
||||
for (let i = 0; i <= sorted.length; i++) {
|
||||
boundaries.push(zoneX + (i / sorted.length) * zoneW)
|
||||
}
|
||||
}
|
||||
}
|
||||
return { zone, boundaries }
|
||||
})
|
||||
|
||||
const startDrag = useCallback(
|
||||
(
|
||||
info: NonNullable<typeof draggingRef.current>,
|
||||
e: React.MouseEvent,
|
||||
) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
draggingRef.current = info
|
||||
onCommitUndo()
|
||||
|
||||
const handleMove = (ev: MouseEvent) => {
|
||||
const wrap = wrapperRef.current
|
||||
if (!wrap || !draggingRef.current) return
|
||||
const rect = wrap.getBoundingClientRect()
|
||||
const xPct = clamp(((ev.clientX - rect.left) / rect.width) * 100, 0, 100)
|
||||
const yPct = clamp(((ev.clientY - rect.top) / rect.height) * 100, 0, 100)
|
||||
|
||||
if (draggingRef.current.type === 'col') {
|
||||
onColumnDividerMove(
|
||||
draggingRef.current.zoneIndex,
|
||||
draggingRef.current.boundaryIndex,
|
||||
xPct,
|
||||
)
|
||||
} else {
|
||||
onHorizontalsChange({
|
||||
...horizontalsRef.current,
|
||||
[draggingRef.current.key]: yPct,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleUp = () => {
|
||||
draggingRef.current = null
|
||||
document.removeEventListener('mousemove', handleMove)
|
||||
document.removeEventListener('mouseup', handleUp)
|
||||
document.body.style.cursor = ''
|
||||
document.body.style.userSelect = ''
|
||||
}
|
||||
|
||||
document.body.style.cursor = info.type === 'col' ? 'col-resize' : 'row-resize'
|
||||
document.body.style.userSelect = 'none'
|
||||
document.addEventListener('mousemove', handleMove)
|
||||
document.addEventListener('mouseup', handleUp)
|
||||
},
|
||||
[onColumnDividerMove, onHorizontalsChange, onCommitUndo],
|
||||
)
|
||||
|
||||
const toggleHorizontal = (key: string) => {
|
||||
const current = horizontals[key as keyof typeof horizontals]
|
||||
if (current != null) {
|
||||
const next = { ...horizontals }
|
||||
delete next[key as keyof typeof next]
|
||||
onHorizontalsChange(next)
|
||||
} else {
|
||||
onCommitUndo()
|
||||
onHorizontalsChange({
|
||||
...horizontals,
|
||||
[key]: HORIZ_DEFAULTS[key],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleDoubleClick = (e: React.MouseEvent) => {
|
||||
const wrap = wrapperRef.current
|
||||
if (!wrap) return
|
||||
const rect = wrap.getBoundingClientRect()
|
||||
const xPct = clamp(((e.clientX - rect.left) / rect.width) * 100, 0, 100)
|
||||
const yPct = clamp(((e.clientY - rect.top) / rect.height) * 100, 0, 100)
|
||||
|
||||
// Find which zone this click is in
|
||||
for (const { zone } of zoneBoundaries) {
|
||||
const zy = zone.bbox_pct.y || 0
|
||||
const zh = zone.bbox_pct.h || 100
|
||||
if (yPct >= zy && yPct <= zy + zh) {
|
||||
onSplitColumnAt(zone.zone_index, xPct)
|
||||
return
|
||||
}
|
||||
}
|
||||
// Fallback: use first zone
|
||||
if (zones.length > 0) {
|
||||
onSplitColumnAt(zones[0].zone_index, xPct)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-3 py-2 border-b border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
|
||||
<span className="text-xs font-medium text-gray-600 dark:text-gray-400">
|
||||
Layout-Editor
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => onZoomChange(Math.max(50, zoom - 25))}
|
||||
className="px-2 py-0.5 text-xs bg-gray-200 dark:bg-gray-700 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
-
|
||||
</button>
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400 w-10 text-center">
|
||||
{zoom}%
|
||||
</span>
|
||||
<button
|
||||
onClick={() => onZoomChange(Math.min(300, zoom + 25))}
|
||||
className="px-2 py-0.5 text-xs bg-gray-200 dark:bg-gray-700 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onZoomChange(100)}
|
||||
className="px-2 py-0.5 text-xs bg-gray-200 dark:bg-gray-700 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
Fit
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Horizontal line toggles */}
|
||||
<div className="flex items-center gap-1.5 px-3 py-1.5 border-b border-gray-100 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/30 flex-wrap">
|
||||
{Object.entries(HORIZ_LABELS).map(([key, label]) => {
|
||||
const isActive = horizontals[key as keyof typeof horizontals] != null
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => toggleHorizontal(key)}
|
||||
className={`px-2 py-0.5 text-[10px] rounded border transition-colors ${
|
||||
isActive
|
||||
? 'font-medium'
|
||||
: 'border-gray-200 dark:border-gray-700 text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400'
|
||||
}`}
|
||||
style={
|
||||
isActive
|
||||
? {
|
||||
color: HORIZ_COLORS[key],
|
||||
borderColor: HORIZ_COLORS[key] + '80',
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
<span className="text-[10px] text-gray-400 dark:text-gray-500 ml-auto">
|
||||
Doppelklick = Spalte einfuegen
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Scrollable image with SVG overlay */}
|
||||
<div className="flex-1 overflow-auto p-2">
|
||||
<div
|
||||
ref={wrapperRef}
|
||||
style={{ width: `${zoom}%`, position: 'relative', maxWidth: 'none' }}
|
||||
onDoubleClick={handleDoubleClick}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt="Original scan"
|
||||
style={{ width: '100%', display: 'block' }}
|
||||
draggable={false}
|
||||
/>
|
||||
{/* SVG overlay */}
|
||||
<svg
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
viewBox="0 0 100 100"
|
||||
preserveAspectRatio="none"
|
||||
>
|
||||
{/* Column boundary lines per zone */}
|
||||
{zoneBoundaries.map(({ zone, boundaries }) =>
|
||||
boundaries.map((xPct, bi) => {
|
||||
const yTop = zone.bbox_pct.y || 0
|
||||
const yBottom = (zone.bbox_pct.y || 0) + (zone.bbox_pct.h || 100)
|
||||
const isEdge = bi === 0 || bi === boundaries.length - 1
|
||||
const isInterior = bi > 0 && bi < boundaries.length - 1
|
||||
return (
|
||||
<g key={`z${zone.zone_index}-b${bi}`}>
|
||||
{/* Wide invisible hit area */}
|
||||
<rect
|
||||
x={xPct - 0.8}
|
||||
y={yTop}
|
||||
width={1.6}
|
||||
height={yBottom - yTop}
|
||||
fill="transparent"
|
||||
style={{ cursor: 'col-resize', pointerEvents: 'all' }}
|
||||
onMouseDown={(e) =>
|
||||
startDrag(
|
||||
{ type: 'col', zoneIndex: zone.zone_index, boundaryIndex: bi },
|
||||
e,
|
||||
)
|
||||
}
|
||||
/>
|
||||
{/* Visible line */}
|
||||
<line
|
||||
x1={xPct}
|
||||
y1={yTop}
|
||||
x2={xPct}
|
||||
y2={yBottom}
|
||||
stroke={isEdge ? 'rgba(20, 184, 166, 0.35)' : 'rgba(20, 184, 166, 0.7)'}
|
||||
strokeWidth={isEdge ? 0.15 : 0.25}
|
||||
strokeDasharray={isEdge ? '0.8,0.4' : '0.5,0.3'}
|
||||
style={{ pointerEvents: 'none' }}
|
||||
/>
|
||||
{/* Delete button for interior dividers */}
|
||||
{isInterior && zone.columns.length > 1 && (
|
||||
<g
|
||||
style={{ pointerEvents: 'all', cursor: 'pointer' }}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onDeleteColumn(zone.zone_index, bi)
|
||||
}}
|
||||
>
|
||||
<circle
|
||||
cx={xPct}
|
||||
cy={Math.max(yTop + 1.5, 1.5)}
|
||||
r={1.2}
|
||||
fill="rgba(239, 68, 68, 0.8)"
|
||||
/>
|
||||
<text
|
||||
x={xPct}
|
||||
y={Math.max(yTop + 1.5, 1.5) + 0.5}
|
||||
textAnchor="middle"
|
||||
fill="white"
|
||||
fontSize="1.4"
|
||||
fontWeight="bold"
|
||||
style={{ pointerEvents: 'none' }}
|
||||
>
|
||||
x
|
||||
</text>
|
||||
</g>
|
||||
)}
|
||||
</g>
|
||||
)
|
||||
}),
|
||||
)}
|
||||
|
||||
{/* Horizontal guideline lines */}
|
||||
{Object.entries(horizontals).map(([key, yPct]) => {
|
||||
if (yPct == null) return null
|
||||
const color = HORIZ_COLORS[key] ?? 'rgba(156, 163, 175, 0.6)'
|
||||
return (
|
||||
<g key={`horiz-${key}`}>
|
||||
{/* Wide invisible hit area */}
|
||||
<rect
|
||||
x={0}
|
||||
y={yPct - 0.6}
|
||||
width={100}
|
||||
height={1.2}
|
||||
fill="transparent"
|
||||
style={{ cursor: 'row-resize', pointerEvents: 'all' }}
|
||||
onMouseDown={(e) => startDrag({ type: 'horiz', key }, e)}
|
||||
/>
|
||||
{/* Visible line */}
|
||||
<line
|
||||
x1={0}
|
||||
y1={yPct}
|
||||
x2={100}
|
||||
y2={yPct}
|
||||
stroke={color}
|
||||
strokeWidth={0.2}
|
||||
strokeDasharray="1,0.5"
|
||||
style={{ pointerEvents: 'none' }}
|
||||
/>
|
||||
{/* Label */}
|
||||
<text
|
||||
x={1}
|
||||
y={yPct - 0.5}
|
||||
fill={color}
|
||||
fontSize="1.6"
|
||||
style={{ pointerEvents: 'none' }}
|
||||
>
|
||||
{HORIZ_LABELS[key]}
|
||||
</text>
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
6
admin-lehrer/components/grid-editor/index.ts
Normal file
6
admin-lehrer/components/grid-editor/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export { GridEditor } from './GridEditor'
|
||||
export { GridTable } from './GridTable'
|
||||
export { GridToolbar } from './GridToolbar'
|
||||
export { GridImageOverlay } from './GridImageOverlay'
|
||||
export { useGridEditor } from './useGridEditor'
|
||||
export type * from './types'
|
||||
156
admin-lehrer/components/grid-editor/types.ts
Normal file
156
admin-lehrer/components/grid-editor/types.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
import type { OcrWordBox } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
// Re-export for convenience
|
||||
export type { OcrWordBox }
|
||||
|
||||
/** Layout metrics derived from OCR word positions for faithful grid reconstruction. */
|
||||
export interface LayoutMetrics {
|
||||
page_width_px: number
|
||||
page_height_px: number
|
||||
avg_row_height_px: number
|
||||
font_size_suggestion_px: number
|
||||
}
|
||||
|
||||
/** Dictionary detection result from backend analysis. */
|
||||
export interface DictionaryDetection {
|
||||
is_dictionary: boolean
|
||||
confidence: number
|
||||
signals: Record<string, unknown>
|
||||
article_col_index: number | null
|
||||
headword_col_index: number | null
|
||||
}
|
||||
|
||||
/** Page number extracted from footer region of the scan. */
|
||||
export interface PageNumber {
|
||||
text: string
|
||||
y_pct: number
|
||||
number?: number
|
||||
}
|
||||
|
||||
/** A complete structured grid with zones, ready for the Excel-like editor. */
|
||||
export interface StructuredGrid {
|
||||
session_id: string
|
||||
image_width: number
|
||||
image_height: number
|
||||
zones: GridZone[]
|
||||
boxes_detected: number
|
||||
summary: GridSummary
|
||||
formatting: GridFormatting
|
||||
layout_metrics?: LayoutMetrics
|
||||
dictionary_detection?: DictionaryDetection
|
||||
page_number?: PageNumber | null
|
||||
duration_seconds: number
|
||||
edited?: boolean
|
||||
layout_dividers?: LayoutDividers
|
||||
}
|
||||
|
||||
export interface GridSummary {
|
||||
total_zones: number
|
||||
total_columns: number
|
||||
total_rows: number
|
||||
total_cells: number
|
||||
total_words: number
|
||||
recovered_colored?: number
|
||||
color_stats?: Record<string, number>
|
||||
}
|
||||
|
||||
export interface GridFormatting {
|
||||
bold_columns: number[]
|
||||
header_rows: number[]
|
||||
}
|
||||
|
||||
/** A horizontal zone of the page — either content or a bordered box. */
|
||||
export interface GridZone {
|
||||
zone_index: number
|
||||
zone_type: 'content' | 'box'
|
||||
bbox_px: BBox
|
||||
bbox_pct: BBox
|
||||
border: ZoneBorder | null
|
||||
word_count: number
|
||||
columns: GridColumn[]
|
||||
rows: GridRow[]
|
||||
cells: GridEditorCell[]
|
||||
header_rows: number[]
|
||||
layout_hint?: 'left_of_vsplit' | 'right_of_vsplit' | 'middle_of_vsplit'
|
||||
vsplit_group?: number
|
||||
box_layout_type?: 'flowing' | 'columnar' | 'bullet_list' | 'header_only'
|
||||
box_grid_reviewed?: boolean
|
||||
box_bg_color?: string
|
||||
box_bg_hex?: string
|
||||
}
|
||||
|
||||
export interface BBox {
|
||||
x: number
|
||||
y: number
|
||||
w: number
|
||||
h: number
|
||||
}
|
||||
|
||||
export interface ZoneBorder {
|
||||
thickness: number
|
||||
confidence: number
|
||||
}
|
||||
|
||||
export interface GridColumn {
|
||||
index: number
|
||||
label: string
|
||||
x_min_px: number
|
||||
x_max_px: number
|
||||
x_min_pct: number
|
||||
x_max_pct: number
|
||||
bold: boolean
|
||||
}
|
||||
|
||||
export interface GridRow {
|
||||
index: number
|
||||
y_min_px: number
|
||||
y_max_px: number
|
||||
y_min_pct: number
|
||||
y_max_pct: number
|
||||
is_header: boolean
|
||||
is_footer?: boolean
|
||||
}
|
||||
|
||||
export interface GridEditorCell {
|
||||
cell_id: string
|
||||
zone_index: number
|
||||
row_index: number
|
||||
col_index: number
|
||||
col_type: string
|
||||
text: string
|
||||
confidence: number
|
||||
bbox_px: BBox
|
||||
bbox_pct: BBox
|
||||
word_boxes: OcrWordBox[]
|
||||
ocr_engine: string
|
||||
is_bold: boolean
|
||||
/** Manual color override: hex string or null to clear. */
|
||||
color_override?: string | null
|
||||
/** Number of columns this cell spans (merged cell). Default 1. */
|
||||
colspan?: number
|
||||
/** Source zone type when in unified grid. */
|
||||
source_zone_type?: 'content' | 'box'
|
||||
/** Box visual metadata for cells from box zones. */
|
||||
box_region?: {
|
||||
bg_hex?: string
|
||||
bg_color?: string
|
||||
border?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
/** Layout dividers for the visual column/margin editor on the original image. */
|
||||
export interface LayoutDividers {
|
||||
horizontals: {
|
||||
top_margin?: number
|
||||
header_bottom?: number
|
||||
footer_top?: number
|
||||
bottom_margin?: number
|
||||
}
|
||||
}
|
||||
|
||||
/** Cell formatting applied by the user in the editor. */
|
||||
export interface CellFormatting {
|
||||
bold: boolean
|
||||
fontSize: 'small' | 'normal' | 'large'
|
||||
align: 'left' | 'center' | 'right'
|
||||
}
|
||||
1035
admin-lehrer/components/grid-editor/useGridEditor.ts
Normal file
1035
admin-lehrer/components/grid-editor/useGridEditor.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -194,10 +194,8 @@ export function Sidebar({ onRoleChange }: SidebarProps) {
|
||||
{/* Categories */}
|
||||
<div className="px-2 space-y-1">
|
||||
{visibleCategories.map((category) => {
|
||||
const categoryHref = category.id === 'compliance-sdk' ? '/sdk' : `/${category.id}`
|
||||
const isCategoryActive = category.id === 'compliance-sdk'
|
||||
? category.modules.some(m => pathname.startsWith(m.href))
|
||||
: pathname.startsWith(categoryHref)
|
||||
const categoryHref = `/${category.id}`
|
||||
const isCategoryActive = pathname.startsWith(categoryHref)
|
||||
|
||||
return (
|
||||
<div key={category.id}>
|
||||
|
||||
59
admin-lehrer/components/ocr-kombi/KombiStepper.tsx
Normal file
59
admin-lehrer/components/ocr-kombi/KombiStepper.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
'use client'
|
||||
|
||||
import type { PipelineStep } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
interface KombiStepperProps {
|
||||
steps: PipelineStep[]
|
||||
currentStep: number
|
||||
onStepClick: (index: number) => void
|
||||
}
|
||||
|
||||
export function KombiStepper({ steps, currentStep, onStepClick }: KombiStepperProps) {
|
||||
return (
|
||||
<div className="flex items-center gap-0.5 px-3 py-2.5 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-x-auto">
|
||||
{steps.map((step, index) => {
|
||||
const isActive = index === currentStep
|
||||
const isCompleted = step.status === 'completed'
|
||||
const isFailed = step.status === 'failed'
|
||||
const isSkipped = step.status === 'skipped'
|
||||
const isClickable = (index <= currentStep || isCompleted) && !isSkipped
|
||||
|
||||
return (
|
||||
<div key={step.id} className="flex items-center flex-shrink-0">
|
||||
{index > 0 && (
|
||||
<div
|
||||
className={`h-0.5 w-4 mx-0.5 ${
|
||||
isSkipped
|
||||
? 'bg-gray-200 dark:bg-gray-700 border-t border-dashed border-gray-400'
|
||||
: index <= currentStep ? 'bg-teal-400' : 'bg-gray-300 dark:bg-gray-600'
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
onClick={() => isClickable && onStepClick(index)}
|
||||
disabled={!isClickable}
|
||||
className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium transition-all whitespace-nowrap ${
|
||||
isSkipped
|
||||
? 'bg-gray-100 text-gray-400 dark:bg-gray-800 dark:text-gray-600 line-through'
|
||||
: isActive
|
||||
? 'bg-teal-100 text-teal-700 dark:bg-teal-900/40 dark:text-teal-300 ring-2 ring-teal-400'
|
||||
: isCompleted
|
||||
? 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300'
|
||||
: isFailed
|
||||
? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'
|
||||
: 'text-gray-400 dark:text-gray-500'
|
||||
} ${isClickable ? 'cursor-pointer hover:opacity-80' : 'cursor-default'}`}
|
||||
title={step.name}
|
||||
>
|
||||
<span className="text-sm">
|
||||
{isSkipped ? '-' : isCompleted ? '\u2713' : isFailed ? '\u2717' : step.icon}
|
||||
</span>
|
||||
<span className="hidden lg:inline">{step.name}</span>
|
||||
<span className="lg:hidden">{index + 1}</span>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
73
admin-lehrer/components/ocr-kombi/SessionHeader.tsx
Normal file
73
admin-lehrer/components/ocr-kombi/SessionHeader.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { DOCUMENT_CATEGORIES, type DocumentCategory } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
interface SessionHeaderProps {
|
||||
sessionName: string
|
||||
activeCategory?: DocumentCategory
|
||||
isGroundTruth: boolean
|
||||
pageNumber?: number | null
|
||||
onUpdateCategory: (category: DocumentCategory) => void
|
||||
}
|
||||
|
||||
export function SessionHeader({
|
||||
sessionName,
|
||||
activeCategory,
|
||||
isGroundTruth,
|
||||
pageNumber,
|
||||
onUpdateCategory,
|
||||
}: SessionHeaderProps) {
|
||||
const [showCategoryPicker, setShowCategoryPicker] = useState(false)
|
||||
|
||||
const catInfo = DOCUMENT_CATEGORIES.find(c => c.value === activeCategory)
|
||||
|
||||
return (
|
||||
<div className="relative flex items-center gap-3 text-sm text-gray-500 dark:text-gray-400">
|
||||
<span>
|
||||
Aktive Session:{' '}
|
||||
<span className="font-medium text-gray-700 dark:text-gray-300">{sessionName}</span>
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setShowCategoryPicker(!showCategoryPicker)}
|
||||
className={`text-xs px-2.5 py-1 rounded-full border transition-colors ${
|
||||
activeCategory
|
||||
? 'bg-teal-50 dark:bg-teal-900/30 border-teal-200 dark:border-teal-700 text-teal-700 dark:text-teal-300 hover:bg-teal-100'
|
||||
: 'bg-amber-50 dark:bg-amber-900/20 border-amber-300 dark:border-amber-700 text-amber-700 dark:text-amber-300 hover:bg-amber-100 animate-pulse'
|
||||
}`}
|
||||
>
|
||||
{catInfo ? `${catInfo.icon} ${catInfo.label}` : 'Kategorie setzen'}
|
||||
</button>
|
||||
{pageNumber != null && (
|
||||
<span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-300">
|
||||
S. {pageNumber}
|
||||
</span>
|
||||
)}
|
||||
{isGroundTruth && (
|
||||
<span className="text-xs px-2 py-0.5 rounded-full bg-amber-50 dark:bg-amber-900/20 border border-amber-300 dark:border-amber-700 text-amber-700 dark:text-amber-300">
|
||||
GT
|
||||
</span>
|
||||
)}
|
||||
{showCategoryPicker && (
|
||||
<div className="absolute left-0 top-full mt-1 z-20 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg p-2 grid grid-cols-2 gap-1 w-64">
|
||||
{DOCUMENT_CATEGORIES.map(cat => (
|
||||
<button
|
||||
key={cat.value}
|
||||
onClick={() => {
|
||||
onUpdateCategory(cat.value)
|
||||
setShowCategoryPicker(false)
|
||||
}}
|
||||
className={`text-xs px-2 py-1.5 rounded-md text-left transition-colors ${
|
||||
activeCategory === cat.value
|
||||
? 'bg-teal-100 dark:bg-teal-900/40 text-teal-700 dark:text-teal-300'
|
||||
: 'hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-600 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
{cat.icon} {cat.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
376
admin-lehrer/components/ocr-kombi/SessionList.tsx
Normal file
376
admin-lehrer/components/ocr-kombi/SessionList.tsx
Normal file
@@ -0,0 +1,376 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { DOCUMENT_CATEGORIES, type DocumentCategory } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
import type { SessionListItem, DocumentGroupView } from '@/app/(admin)/ai/ocr-kombi/useKombiPipeline'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface SessionListProps {
|
||||
items: (SessionListItem | DocumentGroupView)[]
|
||||
loading: boolean
|
||||
activeSessionId: string | null
|
||||
onOpenSession: (sid: string) => void
|
||||
onNewSession: () => void
|
||||
onDeleteSession: (sid: string) => void
|
||||
onRenameSession: (sid: string, newName: string) => void
|
||||
onUpdateCategory: (sid: string, category: DocumentCategory) => void
|
||||
}
|
||||
|
||||
function isGroup(item: SessionListItem | DocumentGroupView): item is DocumentGroupView {
|
||||
return 'group_id' in item
|
||||
}
|
||||
|
||||
export function SessionList({
|
||||
items,
|
||||
loading,
|
||||
activeSessionId,
|
||||
onOpenSession,
|
||||
onNewSession,
|
||||
onDeleteSession,
|
||||
onRenameSession,
|
||||
onUpdateCategory,
|
||||
}: SessionListProps) {
|
||||
const [editingName, setEditingName] = useState<string | null>(null)
|
||||
const [editNameValue, setEditNameValue] = useState('')
|
||||
const [editingCategory, setEditingCategory] = useState<string | null>(null)
|
||||
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set())
|
||||
|
||||
const toggleGroup = (groupId: string) => {
|
||||
setExpandedGroups(prev => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(groupId)) next.delete(groupId)
|
||||
else next.add(groupId)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
Sessions ({items.length})
|
||||
</h3>
|
||||
<button
|
||||
onClick={onNewSession}
|
||||
className="text-xs px-3 py-1.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors"
|
||||
>
|
||||
+ Neue Session
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="text-sm text-gray-400 py-2">Lade Sessions...</div>
|
||||
) : items.length === 0 ? (
|
||||
<div className="text-sm text-gray-400 py-2">Noch keine Sessions vorhanden.</div>
|
||||
) : (
|
||||
<div className="space-y-1.5 max-h-[320px] overflow-y-auto">
|
||||
{items.map(item =>
|
||||
isGroup(item) ? (
|
||||
<GroupRow
|
||||
key={item.group_id}
|
||||
group={item}
|
||||
expanded={expandedGroups.has(item.group_id)}
|
||||
activeSessionId={activeSessionId}
|
||||
onToggle={() => toggleGroup(item.group_id)}
|
||||
onOpenSession={onOpenSession}
|
||||
onDeleteSession={onDeleteSession}
|
||||
/>
|
||||
) : (
|
||||
<SessionRow
|
||||
key={item.id}
|
||||
session={item}
|
||||
isActive={activeSessionId === item.id}
|
||||
editingName={editingName}
|
||||
editNameValue={editNameValue}
|
||||
editingCategory={editingCategory}
|
||||
onOpenSession={() => onOpenSession(item.id)}
|
||||
onStartRename={() => {
|
||||
setEditNameValue(item.name || item.filename)
|
||||
setEditingName(item.id)
|
||||
}}
|
||||
onFinishRename={(newName) => {
|
||||
onRenameSession(item.id, newName)
|
||||
setEditingName(null)
|
||||
}}
|
||||
onCancelRename={() => setEditingName(null)}
|
||||
onEditNameChange={setEditNameValue}
|
||||
onToggleCategory={() => setEditingCategory(editingCategory === item.id ? null : item.id)}
|
||||
onUpdateCategory={(cat) => {
|
||||
onUpdateCategory(item.id, cat)
|
||||
setEditingCategory(null)
|
||||
}}
|
||||
onDelete={() => {
|
||||
if (confirm('Session loeschen?')) onDeleteSession(item.id)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---- Group row (multi-page document) ----
|
||||
|
||||
function GroupRow({
|
||||
group,
|
||||
expanded,
|
||||
activeSessionId,
|
||||
onToggle,
|
||||
onOpenSession,
|
||||
onDeleteSession,
|
||||
}: {
|
||||
group: DocumentGroupView
|
||||
expanded: boolean
|
||||
activeSessionId: string | null
|
||||
onToggle: () => void
|
||||
onOpenSession: (sid: string) => void
|
||||
onDeleteSession: (sid: string) => void
|
||||
}) {
|
||||
const isActive = group.sessions.some(s => s.id === activeSessionId)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
onClick={onToggle}
|
||||
className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm cursor-pointer transition-colors ${
|
||||
isActive
|
||||
? 'bg-teal-50 dark:bg-teal-900/30 border border-teal-200 dark:border-teal-700'
|
||||
: 'hover:bg-gray-50 dark:hover:bg-gray-700/50'
|
||||
}`}
|
||||
>
|
||||
<span className="text-base">{expanded ? '\u25BC' : '\u25B6'}</span>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="truncate font-medium text-gray-700 dark:text-gray-300">
|
||||
{group.title}
|
||||
</div>
|
||||
<div className="text-xs text-gray-400">
|
||||
{group.page_count} Seiten
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
{group.sessions.some(s => s.is_ground_truth) && (
|
||||
<span className="text-[10px] px-1.5 py-0.5 rounded-full bg-amber-100 dark:bg-amber-900/30 border border-amber-300 dark:border-amber-700 text-amber-700 dark:text-amber-300">
|
||||
GT {group.sessions.filter(s => s.is_ground_truth).length}/{group.sessions.length}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-xs px-2 py-0.5 rounded-full bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 text-blue-600 dark:text-blue-400">
|
||||
Dokument
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{expanded && (
|
||||
<div className="ml-6 mt-1 space-y-1 border-l-2 border-gray-200 dark:border-gray-700 pl-3">
|
||||
{group.sessions.map(s => (
|
||||
<div
|
||||
key={s.id}
|
||||
className={`flex items-center gap-2 px-2 py-1.5 rounded text-xs cursor-pointer transition-colors ${
|
||||
activeSessionId === s.id
|
||||
? 'bg-teal-50 dark:bg-teal-900/30 text-teal-700 dark:text-teal-300'
|
||||
: 'hover:bg-gray-50 dark:hover:bg-gray-700/50 text-gray-600 dark:text-gray-400'
|
||||
}`}
|
||||
onClick={() => onOpenSession(s.id)}
|
||||
>
|
||||
{/* Thumbnail */}
|
||||
<div className="flex-shrink-0 w-8 h-8 rounded overflow-hidden bg-gray-100 dark:bg-gray-700">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${s.id}/thumbnail?size=64`}
|
||||
alt=""
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
onError={(e) => { (e.target as HTMLImageElement).style.display = 'none' }}
|
||||
/>
|
||||
</div>
|
||||
<span className="truncate flex-1">S. {s.page_number || '?'}</span>
|
||||
{s.is_ground_truth && (
|
||||
<span className="text-[9px] px-1 py-0.5 rounded bg-amber-100 dark:bg-amber-900/30 border border-amber-300 dark:border-amber-700 text-amber-700 dark:text-amber-300">GT</span>
|
||||
)}
|
||||
<span className="text-[10px] text-gray-400">Step {s.current_step}</span>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (confirm('Seite loeschen?')) onDeleteSession(s.id)
|
||||
}}
|
||||
className="p-0.5 text-gray-400 hover:text-red-500"
|
||||
title="Loeschen"
|
||||
>
|
||||
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---- Single session row ----
|
||||
|
||||
function SessionRow({
|
||||
session,
|
||||
isActive,
|
||||
editingName,
|
||||
editNameValue,
|
||||
editingCategory,
|
||||
onOpenSession,
|
||||
onStartRename,
|
||||
onFinishRename,
|
||||
onCancelRename,
|
||||
onEditNameChange,
|
||||
onToggleCategory,
|
||||
onUpdateCategory,
|
||||
onDelete,
|
||||
}: {
|
||||
session: SessionListItem
|
||||
isActive: boolean
|
||||
editingName: string | null
|
||||
editNameValue: string
|
||||
editingCategory: string | null
|
||||
onOpenSession: () => void
|
||||
onStartRename: () => void
|
||||
onFinishRename: (name: string) => void
|
||||
onCancelRename: () => void
|
||||
onEditNameChange: (val: string) => void
|
||||
onToggleCategory: () => void
|
||||
onUpdateCategory: (cat: DocumentCategory) => void
|
||||
onDelete: () => void
|
||||
}) {
|
||||
const catInfo = DOCUMENT_CATEGORIES.find(c => c.value === session.document_category)
|
||||
const isEditing = editingName === session.id
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`relative flex items-start gap-3 px-3 py-2.5 rounded-lg text-sm transition-colors cursor-pointer ${
|
||||
isActive
|
||||
? 'bg-teal-50 dark:bg-teal-900/30 border border-teal-200 dark:border-teal-700'
|
||||
: 'hover:bg-gray-50 dark:hover:bg-gray-700/50'
|
||||
}`}
|
||||
>
|
||||
{/* Thumbnail */}
|
||||
<div
|
||||
className="flex-shrink-0 w-12 h-12 rounded-md overflow-hidden bg-gray-100 dark:bg-gray-700"
|
||||
onClick={onOpenSession}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${session.id}/thumbnail?size=96`}
|
||||
alt=""
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
onError={(e) => { (e.target as HTMLImageElement).style.display = 'none' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Info */}
|
||||
<div className="flex-1 min-w-0" onClick={onOpenSession}>
|
||||
{isEditing ? (
|
||||
<input
|
||||
autoFocus
|
||||
value={editNameValue}
|
||||
onChange={(e) => onEditNameChange(e.target.value)}
|
||||
onBlur={() => onFinishRename(editNameValue)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') onFinishRename(editNameValue)
|
||||
if (e.key === 'Escape') onCancelRename()
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="w-full px-1 py-0.5 text-sm border rounded dark:bg-gray-700 dark:border-gray-600"
|
||||
/>
|
||||
) : (
|
||||
<div className="truncate font-medium text-gray-700 dark:text-gray-300">
|
||||
{session.name || session.filename}
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
navigator.clipboard.writeText(session.id)
|
||||
const btn = e.currentTarget
|
||||
btn.textContent = 'Kopiert!'
|
||||
setTimeout(() => { btn.textContent = `ID: ${session.id.slice(0, 8)}` }, 1500)
|
||||
}}
|
||||
className="text-[10px] font-mono text-gray-400 hover:text-teal-500 transition-colors"
|
||||
title={`Volle ID: ${session.id} — Klick zum Kopieren`}
|
||||
>
|
||||
ID: {session.id.slice(0, 8)}
|
||||
</button>
|
||||
<div className="text-xs text-gray-400 mt-0.5">
|
||||
{new Date(session.created_at).toLocaleDateString('de-DE', {
|
||||
day: '2-digit', month: '2-digit', year: '2-digit',
|
||||
hour: '2-digit', minute: '2-digit',
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Category + GT badge */}
|
||||
<div className="flex flex-col gap-1 items-end flex-shrink-0" onClick={(e) => e.stopPropagation()}>
|
||||
<button
|
||||
onClick={onToggleCategory}
|
||||
className={`text-[10px] px-1.5 py-0.5 rounded-full border transition-colors ${
|
||||
catInfo
|
||||
? 'bg-teal-50 dark:bg-teal-900/30 border-teal-200 dark:border-teal-700 text-teal-700 dark:text-teal-300'
|
||||
: 'bg-gray-50 dark:bg-gray-700 border-gray-200 dark:border-gray-600 text-gray-400 hover:text-gray-600'
|
||||
}`}
|
||||
title="Kategorie setzen"
|
||||
>
|
||||
{catInfo ? `${catInfo.icon} ${catInfo.label}` : '+ Kategorie'}
|
||||
</button>
|
||||
{session.is_ground_truth && (
|
||||
<span className="text-[10px] px-1.5 py-0.5 rounded-full bg-amber-100 dark:bg-amber-900/30 border border-amber-300 dark:border-amber-700 text-amber-700 dark:text-amber-300" title="Ground Truth markiert">
|
||||
GT
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex flex-col gap-0.5 flex-shrink-0">
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); onStartRename() }}
|
||||
className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
|
||||
title="Umbenennen"
|
||||
>
|
||||
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); onDelete() }}
|
||||
className="p-1 text-gray-400 hover:text-red-500"
|
||||
title="Loeschen"
|
||||
>
|
||||
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Category dropdown */}
|
||||
{editingCategory === session.id && (
|
||||
<div
|
||||
className="absolute right-0 top-full mt-1 z-20 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg p-2 grid grid-cols-2 gap-1 w-64"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{DOCUMENT_CATEGORIES.map(cat => (
|
||||
<button
|
||||
key={cat.value}
|
||||
onClick={() => onUpdateCategory(cat.value)}
|
||||
className={`text-xs px-2 py-1.5 rounded-md text-left transition-colors ${
|
||||
session.document_category === cat.value
|
||||
? 'bg-teal-100 dark:bg-teal-900/40 text-teal-700 dark:text-teal-300'
|
||||
: 'hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-600 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
{cat.icon} {cat.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
241
admin-lehrer/components/ocr-kombi/SpreadsheetView.tsx
Normal file
241
admin-lehrer/components/ocr-kombi/SpreadsheetView.tsx
Normal file
@@ -0,0 +1,241 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* SpreadsheetView — Fortune Sheet with multi-sheet support.
|
||||
*
|
||||
* Each zone (content + boxes) becomes its own Excel sheet tab,
|
||||
* so each can have independent column widths optimized for its content.
|
||||
*/
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import dynamic from 'next/dynamic'
|
||||
|
||||
const Workbook = dynamic(
|
||||
() => import('@fortune-sheet/react').then((m) => m.Workbook),
|
||||
{ ssr: false, loading: () => <div className="py-8 text-center text-sm text-gray-400">Spreadsheet wird geladen...</div> },
|
||||
)
|
||||
|
||||
import '@fortune-sheet/react/dist/index.css'
|
||||
|
||||
import type { GridZone } from '@/components/grid-editor/types'
|
||||
|
||||
interface SpreadsheetViewProps {
|
||||
gridData: any
|
||||
height?: number
|
||||
}
|
||||
|
||||
/** No expansion — keep multi-line cells as single cells with \n and text-wrap. */
|
||||
|
||||
/** Convert a single zone to a Fortune Sheet sheet object. */
|
||||
function zoneToSheet(zone: GridZone, sheetIndex: number, isFirst: boolean): any {
|
||||
const isBox = zone.zone_type === 'box'
|
||||
const boxColor = (zone as any).box_bg_hex || ''
|
||||
|
||||
// Sheet name
|
||||
let name: string
|
||||
if (!isBox) {
|
||||
name = 'Vokabeln'
|
||||
} else {
|
||||
const firstText = zone.cells?.[0]?.text ?? `Box ${sheetIndex}`
|
||||
const cleaned = firstText.replace(/[^\w\s\u00C0-\u024F„"]/g, '').trim()
|
||||
name = cleaned.length > 25 ? cleaned.slice(0, 25) + '…' : cleaned || `Box ${sheetIndex}`
|
||||
}
|
||||
|
||||
const numCols = zone.columns?.length || 1
|
||||
const numRows = zone.rows?.length || 0
|
||||
const expandedCells = zone.cells || []
|
||||
|
||||
// Compute zone-wide median word height for font-size detection
|
||||
const allWordHeights = zone.cells
|
||||
.flatMap((c: any) => (c.word_boxes || []).map((wb: any) => wb.height || 0))
|
||||
.filter((h: number) => h > 0)
|
||||
const medianWordH = allWordHeights.length
|
||||
? [...allWordHeights].sort((a, b) => a - b)[Math.floor(allWordHeights.length / 2)]
|
||||
: 0
|
||||
|
||||
// Build celldata
|
||||
const celldata: any[] = []
|
||||
const merges: Record<string, any> = {}
|
||||
|
||||
for (const cell of expandedCells) {
|
||||
const r = cell.row_index
|
||||
const c = cell.col_index
|
||||
const text = cell.text ?? ''
|
||||
|
||||
// Row metadata
|
||||
const row = zone.rows?.find((rr) => rr.index === r)
|
||||
const isHeader = row?.is_header ?? false
|
||||
|
||||
// Font size detection from word_boxes
|
||||
const avgWbH = cell.word_boxes?.length
|
||||
? cell.word_boxes.reduce((s: number, wb: any) => s + (wb.height || 0), 0) / cell.word_boxes.length
|
||||
: 0
|
||||
const isLargerFont = avgWbH > 0 && medianWordH > 0 && avgWbH > medianWordH * 1.3
|
||||
|
||||
const v: any = { v: text, m: text }
|
||||
|
||||
// Bold: headers, is_bold, larger font
|
||||
if (cell.is_bold || isHeader || isLargerFont) {
|
||||
v.bl = 1
|
||||
}
|
||||
|
||||
// Larger font for box titles
|
||||
if (isLargerFont && isBox) {
|
||||
v.fs = 12
|
||||
}
|
||||
|
||||
// Multi-line text (bullets with \n): enable text wrap + vertical top align
|
||||
// Add bullet marker (•) if multi-line and no bullet present
|
||||
if (text.includes('\n') && !isHeader) {
|
||||
if (!text.startsWith('•') && !text.startsWith('-') && !text.startsWith('–') && r > 0) {
|
||||
text = '• ' + text
|
||||
v.v = text
|
||||
v.m = text
|
||||
}
|
||||
v.tb = '2' // text wrap
|
||||
v.vt = 0 // vertical align: top
|
||||
}
|
||||
|
||||
// Header row background
|
||||
if (isHeader) {
|
||||
v.bg = isBox ? `${boxColor || '#2563eb'}18` : '#f0f4ff'
|
||||
}
|
||||
|
||||
// Box cells: light tinted background
|
||||
if (isBox && !isHeader && boxColor) {
|
||||
v.bg = `${boxColor}08`
|
||||
}
|
||||
|
||||
// Text color from OCR
|
||||
const color = cell.color_override
|
||||
?? cell.word_boxes?.find((wb: any) => wb.color_name && wb.color_name !== 'black')?.color
|
||||
if (color) v.fc = color
|
||||
|
||||
celldata.push({ r, c, v })
|
||||
|
||||
// Colspan → merge
|
||||
const colspan = cell.colspan || 0
|
||||
if (colspan > 1 || cell.col_type === 'spanning_header') {
|
||||
const cs = colspan || numCols
|
||||
merges[`${r}_${c}`] = { r, c, rs: 1, cs }
|
||||
}
|
||||
}
|
||||
|
||||
// Column widths — auto-fit based on longest text
|
||||
const columnlen: Record<string, number> = {}
|
||||
for (const col of (zone.columns || [])) {
|
||||
const colCells = expandedCells.filter(
|
||||
(c: any) => c.col_index === col.index && c.col_type !== 'spanning_header'
|
||||
)
|
||||
let maxTextLen = 0
|
||||
for (const c of colCells) {
|
||||
const len = (c.text ?? '').length
|
||||
if (len > maxTextLen) maxTextLen = len
|
||||
}
|
||||
const autoWidth = Math.max(60, maxTextLen * 7.5 + 16)
|
||||
const pxW = (col.x_max_px ?? 0) - (col.x_min_px ?? 0)
|
||||
const scaledPxW = Math.max(60, Math.round(pxW * (numCols <= 2 ? 0.6 : 0.4)))
|
||||
columnlen[String(col.index)] = Math.round(Math.max(autoWidth, scaledPxW))
|
||||
}
|
||||
|
||||
// Row heights — taller for multi-line cells
|
||||
const rowlen: Record<string, number> = {}
|
||||
for (const row of (zone.rows || [])) {
|
||||
const rowCells = expandedCells.filter((c: any) => c.row_index === row.index)
|
||||
const maxLines = Math.max(1, ...rowCells.map((c: any) => (c.text ?? '').split('\n').length))
|
||||
const baseH = 24
|
||||
rowlen[String(row.index)] = Math.max(baseH, baseH * maxLines)
|
||||
}
|
||||
|
||||
// Border info
|
||||
const borderInfo: any[] = []
|
||||
|
||||
// Box: colored outside border
|
||||
if (isBox && boxColor && numRows > 0 && numCols > 0) {
|
||||
borderInfo.push({
|
||||
rangeType: 'range',
|
||||
borderType: 'border-outside',
|
||||
color: boxColor,
|
||||
style: 5,
|
||||
range: [{ row: [0, numRows - 1], column: [0, numCols - 1] }],
|
||||
})
|
||||
borderInfo.push({
|
||||
rangeType: 'range',
|
||||
borderType: 'border-inside',
|
||||
color: `${boxColor}40`,
|
||||
style: 1,
|
||||
range: [{ row: [0, numRows - 1], column: [0, numCols - 1] }],
|
||||
})
|
||||
}
|
||||
|
||||
// Content zone: light grid lines
|
||||
if (!isBox && numRows > 0 && numCols > 0) {
|
||||
borderInfo.push({
|
||||
rangeType: 'range',
|
||||
borderType: 'border-all',
|
||||
color: '#e5e7eb',
|
||||
style: 1,
|
||||
range: [{ row: [0, numRows - 1], column: [0, numCols - 1] }],
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
name,
|
||||
id: `zone_${zone.zone_index}`,
|
||||
celldata,
|
||||
row: numRows,
|
||||
column: Math.max(numCols, 1),
|
||||
status: isFirst ? 1 : 0,
|
||||
color: isBox ? boxColor : undefined,
|
||||
config: {
|
||||
merge: Object.keys(merges).length > 0 ? merges : undefined,
|
||||
columnlen,
|
||||
rowlen,
|
||||
borderInfo: borderInfo.length > 0 ? borderInfo : undefined,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function SpreadsheetView({ gridData, height = 600 }: SpreadsheetViewProps) {
|
||||
const sheets = useMemo(() => {
|
||||
if (!gridData?.zones) return []
|
||||
|
||||
const sorted = [...gridData.zones].sort((a: GridZone, b: GridZone) => {
|
||||
if (a.zone_type === 'content' && b.zone_type !== 'content') return -1
|
||||
if (a.zone_type !== 'content' && b.zone_type === 'content') return 1
|
||||
return (a.bbox_px?.y ?? 0) - (b.bbox_px?.y ?? 0)
|
||||
})
|
||||
|
||||
return sorted
|
||||
.filter((z: GridZone) => z.cells && z.cells.length > 0)
|
||||
.map((z: GridZone, i: number) => zoneToSheet(z, i, i === 0))
|
||||
}, [gridData])
|
||||
|
||||
const maxRows = Math.max(0, ...sheets.map((s: any) => s.row || 0))
|
||||
const estimatedHeight = Math.max(height, maxRows * 26 + 80)
|
||||
|
||||
if (sheets.length === 0) {
|
||||
return <div className="p-4 text-center text-gray-400">Keine Daten für Spreadsheet.</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ width: '100%', height: `${estimatedHeight}px` }}>
|
||||
<Workbook
|
||||
data={sheets}
|
||||
lang="en"
|
||||
showToolbar
|
||||
showFormulaBar={false}
|
||||
showSheetTabs
|
||||
toolbarItems={[
|
||||
'undo', 'redo', '|',
|
||||
'font-bold', 'font-italic', 'font-strikethrough', '|',
|
||||
'font-color', 'background', '|',
|
||||
'font-size', '|',
|
||||
'horizontal-align', 'vertical-align', '|',
|
||||
'text-wrap', 'merge-cell', '|',
|
||||
'border',
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
110
admin-lehrer/components/ocr-kombi/StepAnsicht.tsx
Normal file
110
admin-lehrer/components/ocr-kombi/StepAnsicht.tsx
Normal file
@@ -0,0 +1,110 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* StepAnsicht — Excel-like Spreadsheet View.
|
||||
*
|
||||
* Left: Original scan with OCR word overlay
|
||||
* Right: Fortune Sheet spreadsheet with multi-sheet tabs per zone
|
||||
*/
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import dynamic from 'next/dynamic'
|
||||
|
||||
const SpreadsheetView = dynamic(
|
||||
() => import('./SpreadsheetView').then((m) => m.SpreadsheetView),
|
||||
{ ssr: false, loading: () => <div className="py-8 text-center text-sm text-gray-400">Spreadsheet wird geladen...</div> },
|
||||
)
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface StepAnsichtProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
export function StepAnsicht({ sessionId, onNext }: StepAnsichtProps) {
|
||||
const [gridData, setGridData] = useState<any>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const leftRef = useRef<HTMLDivElement>(null)
|
||||
const [leftHeight, setLeftHeight] = useState(600)
|
||||
|
||||
// Load grid data on mount
|
||||
useEffect(() => {
|
||||
if (!sessionId) return
|
||||
;(async () => {
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/grid-editor`)
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||
setGridData(await res.json())
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Fehler beim Laden')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
})()
|
||||
}, [sessionId])
|
||||
|
||||
// Track left panel height
|
||||
useEffect(() => {
|
||||
if (!leftRef.current) return
|
||||
const ro = new ResizeObserver(([e]) => setLeftHeight(e.contentRect.height))
|
||||
ro.observe(leftRef.current)
|
||||
return () => ro.disconnect()
|
||||
}, [])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
<div className="w-8 h-8 border-4 border-teal-500 border-t-transparent rounded-full animate-spin" />
|
||||
<span className="ml-3 text-gray-500">Lade Spreadsheet...</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error || !gridData) {
|
||||
return (
|
||||
<div className="p-8 text-center">
|
||||
<p className="text-red-500 mb-4">{error || 'Keine Grid-Daten.'}</p>
|
||||
<button onClick={onNext} className="px-5 py-2 bg-teal-600 text-white rounded-lg">Weiter →</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">Ansicht — Spreadsheet</h3>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
Jede Zone als eigenes Sheet-Tab. Spaltenbreiten pro Sheet optimiert.
|
||||
</p>
|
||||
</div>
|
||||
<button onClick={onNext} className="px-5 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 text-sm font-medium">
|
||||
Weiter →
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Split view */}
|
||||
<div className="flex gap-2">
|
||||
{/* LEFT: Original + OCR overlay */}
|
||||
<div ref={leftRef} className="w-1/3 border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden bg-white dark:bg-gray-900 flex-shrink-0">
|
||||
<div className="px-2 py-1 bg-black/60 text-white text-[10px] font-medium">Original + OCR</div>
|
||||
{sessionId && (
|
||||
<img
|
||||
src={`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/words-overlay`}
|
||||
alt="Original + OCR"
|
||||
className="w-full h-auto"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* RIGHT: Fortune Sheet — height adapts to content */}
|
||||
<div className="flex-1 border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden bg-white dark:bg-gray-900">
|
||||
<SpreadsheetView gridData={gridData} height={Math.max(700, leftHeight)} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
283
admin-lehrer/components/ocr-kombi/StepBoxGridReview.tsx
Normal file
283
admin-lehrer/components/ocr-kombi/StepBoxGridReview.tsx
Normal file
@@ -0,0 +1,283 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useGridEditor } from '@/components/grid-editor/useGridEditor'
|
||||
import type { GridZone } from '@/components/grid-editor/types'
|
||||
import { GridTable } from '@/components/grid-editor/GridTable'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
type BoxLayoutType = 'flowing' | 'columnar' | 'bullet_list' | 'header_only'
|
||||
|
||||
const LAYOUT_LABELS: Record<BoxLayoutType, string> = {
|
||||
flowing: 'Fließtext',
|
||||
columnar: 'Tabelle/Spalten',
|
||||
bullet_list: 'Aufzählung',
|
||||
header_only: 'Überschrift',
|
||||
}
|
||||
|
||||
interface StepBoxGridReviewProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
export function StepBoxGridReview({ sessionId, onNext }: StepBoxGridReviewProps) {
|
||||
const {
|
||||
grid,
|
||||
loading,
|
||||
saving,
|
||||
error,
|
||||
dirty,
|
||||
selectedCell,
|
||||
setSelectedCell,
|
||||
loadGrid,
|
||||
saveGrid,
|
||||
updateCellText,
|
||||
toggleColumnBold,
|
||||
toggleRowHeader,
|
||||
undo,
|
||||
redo,
|
||||
canUndo,
|
||||
canRedo,
|
||||
getAdjacentCell,
|
||||
commitUndoPoint,
|
||||
selectedCells,
|
||||
toggleCellSelection,
|
||||
clearCellSelection,
|
||||
toggleSelectedBold,
|
||||
setCellColor,
|
||||
deleteColumn,
|
||||
addColumn,
|
||||
deleteRow,
|
||||
addRow,
|
||||
} = useGridEditor(sessionId)
|
||||
|
||||
const [building, setBuilding] = useState(false)
|
||||
const [buildError, setBuildError] = useState<string | null>(null)
|
||||
|
||||
// Load grid on mount
|
||||
useEffect(() => {
|
||||
if (sessionId) loadGrid()
|
||||
}, [sessionId]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Get box zones
|
||||
const boxZones: GridZone[] = (grid?.zones || []).filter(
|
||||
(z: GridZone) => z.zone_type === 'box'
|
||||
)
|
||||
|
||||
// Build box grids via backend
|
||||
const buildBoxGrids = useCallback(async (overrides?: Record<string, string>) => {
|
||||
if (!sessionId) return
|
||||
setBuilding(true)
|
||||
setBuildError(null)
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/build-box-grids`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ overrides: overrides || {} }),
|
||||
},
|
||||
)
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}))
|
||||
throw new Error(data.detail || `HTTP ${res.status}`)
|
||||
}
|
||||
await loadGrid()
|
||||
} catch (e) {
|
||||
setBuildError(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setBuilding(false)
|
||||
}
|
||||
}, [sessionId, loadGrid])
|
||||
|
||||
// Handle layout type change for a specific box zone
|
||||
const changeLayoutType = useCallback(async (boxIdx: number, layoutType: string) => {
|
||||
await buildBoxGrids({ [String(boxIdx)]: layoutType })
|
||||
}, [buildBoxGrids])
|
||||
|
||||
// Auto-build once on first load if box zones have no cells
|
||||
const autoBuildDone = useRef(false)
|
||||
useEffect(() => {
|
||||
if (!grid || loading || building || autoBuildDone.current) return
|
||||
const needsBuild = boxZones.some(z => !z.cells || z.cells.length === 0)
|
||||
if (needsBuild && sessionId) {
|
||||
autoBuildDone.current = true
|
||||
buildBoxGrids()
|
||||
}
|
||||
}, [grid, loading]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
<div className="w-8 h-8 border-4 border-teal-500 border-t-transparent rounded-full animate-spin" />
|
||||
<span className="ml-3 text-gray-500">Lade Grid...</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// No boxes after build attempt — skip step
|
||||
if (!building && boxZones.length === 0) {
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-8 text-center">
|
||||
<div className="text-4xl mb-3">📦</div>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
|
||||
Keine Boxen erkannt
|
||||
</h3>
|
||||
<p className="text-gray-500 dark:text-gray-400 mb-6">
|
||||
Auf dieser Seite wurden keine eingebetteten Boxen (Grammatik-Tipps, Übungen etc.) erkannt.
|
||||
</p>
|
||||
<button
|
||||
onClick={onNext}
|
||||
className="px-6 py-2.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors font-medium"
|
||||
>
|
||||
Weiter →
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
Box-Review ({boxZones.length} {boxZones.length === 1 ? 'Box' : 'Boxen'})
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
Eingebettete Boxen prüfen und korrigieren. Layout-Typ kann pro Box angepasst werden.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{dirty && (
|
||||
<button
|
||||
onClick={saveGrid}
|
||||
disabled={saving}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium disabled:opacity-50"
|
||||
>
|
||||
{saving ? 'Speichere...' : 'Speichern'}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => buildBoxGrids()}
|
||||
disabled={building}
|
||||
className="px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors text-sm font-medium disabled:opacity-50"
|
||||
>
|
||||
{building ? 'Verarbeite...' : 'Alle Boxen neu aufbauen'}
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
if (dirty) await saveGrid()
|
||||
onNext()
|
||||
}}
|
||||
className="px-5 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors text-sm font-medium"
|
||||
>
|
||||
Weiter →
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Errors */}
|
||||
{(error || buildError) && (
|
||||
<div className="p-3 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg text-red-700 dark:text-red-300 text-sm">
|
||||
{error || buildError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{building && (
|
||||
<div className="flex items-center gap-3 p-4 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg">
|
||||
<div className="w-5 h-5 border-2 border-amber-500 border-t-transparent rounded-full animate-spin" />
|
||||
<span className="text-amber-700 dark:text-amber-300 text-sm">Box-Grids werden aufgebaut...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Box zones */}
|
||||
{boxZones.map((zone, boxIdx) => {
|
||||
const boxColor = zone.box_bg_hex || '#d97706' // amber fallback
|
||||
const boxColorName = zone.box_bg_color || 'box'
|
||||
return (
|
||||
<div
|
||||
key={zone.zone_index}
|
||||
className="bg-white dark:bg-gray-800 rounded-xl overflow-hidden"
|
||||
style={{ border: `3px solid ${boxColor}` }}
|
||||
>
|
||||
{/* Box header */}
|
||||
<div
|
||||
className="flex items-center justify-between px-4 py-3 border-b"
|
||||
style={{ backgroundColor: `${boxColor}15`, borderColor: `${boxColor}30` }}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div
|
||||
className="w-8 h-8 rounded-lg flex items-center justify-center text-white text-sm font-bold"
|
||||
style={{ backgroundColor: boxColor }}
|
||||
>
|
||||
{boxIdx + 1}
|
||||
</div>
|
||||
<div>
|
||||
<span className="font-medium text-gray-900 dark:text-white">
|
||||
Box {boxIdx + 1}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400 ml-2">
|
||||
{zone.bbox_px?.w}x{zone.bbox_px?.h}px
|
||||
{zone.cells?.length ? ` | ${zone.cells.length} Zellen` : ''}
|
||||
{zone.box_layout_type ? ` | ${LAYOUT_LABELS[zone.box_layout_type as BoxLayoutType] || zone.box_layout_type}` : ''}
|
||||
{boxColorName !== 'box' ? ` | ${boxColorName}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-gray-500 dark:text-gray-400">Layout:</label>
|
||||
<select
|
||||
value={zone.box_layout_type || 'flowing'}
|
||||
onChange={(e) => changeLayoutType(boxIdx, e.target.value)}
|
||||
disabled={building}
|
||||
className="text-xs px-2 py-1 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-200"
|
||||
>
|
||||
{Object.entries(LAYOUT_LABELS).map(([key, label]) => (
|
||||
<option key={key} value={key}>{label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Box grid table */}
|
||||
<div className="p-3">
|
||||
{zone.cells && zone.cells.length > 0 ? (
|
||||
<GridTable
|
||||
zone={zone}
|
||||
selectedCell={selectedCell}
|
||||
selectedCells={selectedCells}
|
||||
onSelectCell={setSelectedCell}
|
||||
onCellTextChange={updateCellText}
|
||||
onToggleColumnBold={toggleColumnBold}
|
||||
onToggleRowHeader={toggleRowHeader}
|
||||
onNavigate={(cellId, dir) => {
|
||||
const next = getAdjacentCell(cellId, dir)
|
||||
if (next) setSelectedCell(next)
|
||||
}}
|
||||
onDeleteColumn={deleteColumn}
|
||||
onAddColumn={addColumn}
|
||||
onDeleteRow={deleteRow}
|
||||
onAddRow={addRow}
|
||||
onToggleCellSelection={toggleCellSelection}
|
||||
onSetCellColor={setCellColor}
|
||||
/>
|
||||
) : (
|
||||
<div className="text-center py-8 text-gray-400">
|
||||
<p className="text-sm">Keine Zellen erkannt.</p>
|
||||
<button
|
||||
onClick={() => buildBoxGrids({ [String(boxIdx)]: 'flowing' })}
|
||||
className="mt-2 text-xs text-amber-600 hover:text-amber-700"
|
||||
>
|
||||
Als Fließtext verarbeiten
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
13
admin-lehrer/components/ocr-kombi/StepContentCrop.tsx
Normal file
13
admin-lehrer/components/ocr-kombi/StepContentCrop.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
'use client'
|
||||
|
||||
import { StepCrop as BaseStepCrop } from '@/components/ocr-pipeline/StepCrop'
|
||||
|
||||
interface StepContentCropProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
/** Thin wrapper around the shared StepCrop component */
|
||||
export function StepContentCrop({ sessionId, onNext }: StepContentCropProps) {
|
||||
return <BaseStepCrop key={sessionId} sessionId={sessionId} onNext={onNext} />
|
||||
}
|
||||
13
admin-lehrer/components/ocr-kombi/StepDeskew.tsx
Normal file
13
admin-lehrer/components/ocr-kombi/StepDeskew.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
'use client'
|
||||
|
||||
import { StepDeskew as BaseStepDeskew } from '@/components/ocr-pipeline/StepDeskew'
|
||||
|
||||
interface StepDeskewProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
/** Thin wrapper around the shared StepDeskew component */
|
||||
export function StepDeskew({ sessionId, onNext }: StepDeskewProps) {
|
||||
return <BaseStepDeskew key={sessionId} sessionId={sessionId} onNext={onNext} />
|
||||
}
|
||||
13
admin-lehrer/components/ocr-kombi/StepDewarp.tsx
Normal file
13
admin-lehrer/components/ocr-kombi/StepDewarp.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
'use client'
|
||||
|
||||
import { StepDewarp as BaseStepDewarp } from '@/components/ocr-pipeline/StepDewarp'
|
||||
|
||||
interface StepDewarpProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
/** Thin wrapper around the shared StepDewarp component */
|
||||
export function StepDewarp({ sessionId, onNext }: StepDewarpProps) {
|
||||
return <BaseStepDewarp key={sessionId} sessionId={sessionId} onNext={onNext} />
|
||||
}
|
||||
117
admin-lehrer/components/ocr-kombi/StepGridBuild.tsx
Normal file
117
admin-lehrer/components/ocr-kombi/StepGridBuild.tsx
Normal file
@@ -0,0 +1,117 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface StepGridBuildProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 9: Grid Build.
|
||||
* Triggers the build-grid endpoint and shows progress.
|
||||
*/
|
||||
export function StepGridBuild({ sessionId, onNext }: StepGridBuildProps) {
|
||||
const [building, setBuilding] = useState(false)
|
||||
const [result, setResult] = useState<{ rows: number; cols: number; cells: number } | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
const [autoTriggered, setAutoTriggered] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionId || autoTriggered) return
|
||||
// Check if grid already exists
|
||||
checkExistingGrid()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [sessionId])
|
||||
|
||||
const checkExistingGrid = async () => {
|
||||
if (!sessionId) return
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/grid-editor`)
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
// Use grid-editor summary (accurate zone-based counts)
|
||||
const summary = data.summary
|
||||
if (summary) {
|
||||
setResult({ rows: summary.total_rows || 0, cols: summary.total_columns || 0, cells: summary.total_cells || 0 })
|
||||
return
|
||||
}
|
||||
}
|
||||
} catch { /* no existing grid */ }
|
||||
|
||||
// Auto-trigger build
|
||||
setAutoTriggered(true)
|
||||
buildGrid()
|
||||
}
|
||||
|
||||
const buildGrid = async () => {
|
||||
if (!sessionId) return
|
||||
setBuilding(true)
|
||||
setError('')
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/build-grid`, {
|
||||
method: 'POST',
|
||||
})
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}))
|
||||
throw new Error(data.detail || `Grid-Build fehlgeschlagen (${res.status})`)
|
||||
}
|
||||
const data = await res.json()
|
||||
// Use grid-editor summary (zone-based, more accurate than word_result.grid_shape)
|
||||
const summary = data.summary
|
||||
if (summary) {
|
||||
setResult({ rows: summary.total_rows || 0, cols: summary.total_columns || 0, cells: summary.total_cells || 0 })
|
||||
} else {
|
||||
const shape = data.grid_shape || { rows: 0, cols: 0, total_cells: 0 }
|
||||
setResult({ rows: shape.rows, cols: shape.cols, cells: shape.total_cells })
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setBuilding(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{building && (
|
||||
<div className="flex items-center gap-3 p-6 bg-blue-50 dark:bg-blue-900/20 rounded-xl border border-blue-200 dark:border-blue-800">
|
||||
<div className="animate-spin w-5 h-5 border-2 border-blue-400 border-t-transparent rounded-full" />
|
||||
<span className="text-sm text-blue-600 dark:text-blue-400">Grid wird aufgebaut...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<div className="space-y-3">
|
||||
<div className="p-4 bg-green-50 dark:bg-green-900/20 rounded-xl border border-green-200 dark:border-green-800">
|
||||
<div className="text-sm font-medium text-green-700 dark:text-green-300">
|
||||
Grid erstellt: {result.rows} Zeilen, {result.cols} Spalten, {result.cells} Zellen
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={onNext}
|
||||
className="px-4 py-2 bg-teal-600 text-white text-sm rounded-lg hover:bg-teal-700"
|
||||
>
|
||||
Weiter zum Review
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="space-y-3">
|
||||
<div className="text-sm text-red-500 bg-red-50 dark:bg-red-900/20 p-3 rounded-lg">
|
||||
{error}
|
||||
</div>
|
||||
<button
|
||||
onClick={buildGrid}
|
||||
className="px-4 py-2 bg-orange-600 text-white text-sm rounded-lg hover:bg-orange-700"
|
||||
>
|
||||
Erneut versuchen
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
15
admin-lehrer/components/ocr-kombi/StepGridReview.tsx
Normal file
15
admin-lehrer/components/ocr-kombi/StepGridReview.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
'use client'
|
||||
|
||||
import { StepGridReview as BaseStepGridReview } from '@/components/ocr-pipeline/StepGridReview'
|
||||
import type { MutableRefObject } from 'react'
|
||||
|
||||
interface StepGridReviewProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
saveRef: MutableRefObject<(() => Promise<void>) | null>
|
||||
}
|
||||
|
||||
/** Thin wrapper around the shared StepGridReview component */
|
||||
export function StepGridReview({ sessionId, onNext, saveRef }: StepGridReviewProps) {
|
||||
return <BaseStepGridReview sessionId={sessionId} onNext={onNext} saveRef={saveRef} />
|
||||
}
|
||||
295
admin-lehrer/components/ocr-kombi/StepGroundTruth.tsx
Normal file
295
admin-lehrer/components/ocr-kombi/StepGroundTruth.tsx
Normal file
@@ -0,0 +1,295 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useGridEditor } from '@/components/grid-editor/useGridEditor'
|
||||
import { GridTable } from '@/components/grid-editor/GridTable'
|
||||
import { ImageLayoutEditor } from '@/components/grid-editor/ImageLayoutEditor'
|
||||
import type { GridZone } from '@/components/grid-editor/types'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface StepGroundTruthProps {
|
||||
sessionId: string | null
|
||||
isGroundTruth: boolean
|
||||
onMarked: () => void
|
||||
gridSaveRef: React.MutableRefObject<(() => Promise<void>) | null>
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 12: Ground Truth marking.
|
||||
*
|
||||
* Shows the full Grid-Review view (original image + table) so the user
|
||||
* can verify the final result before marking as Ground Truth reference.
|
||||
*/
|
||||
export function StepGroundTruth({ sessionId, isGroundTruth, onMarked, gridSaveRef }: StepGroundTruthProps) {
|
||||
const {
|
||||
grid,
|
||||
loading,
|
||||
saving,
|
||||
error,
|
||||
dirty,
|
||||
selectedCell,
|
||||
selectedCells,
|
||||
setSelectedCell,
|
||||
loadGrid,
|
||||
saveGrid,
|
||||
updateCellText,
|
||||
toggleColumnBold,
|
||||
toggleRowHeader,
|
||||
undo,
|
||||
redo,
|
||||
canUndo,
|
||||
canRedo,
|
||||
getAdjacentCell,
|
||||
deleteColumn,
|
||||
addColumn,
|
||||
deleteRow,
|
||||
addRow,
|
||||
toggleCellSelection,
|
||||
clearCellSelection,
|
||||
toggleSelectedBold,
|
||||
setCellColor,
|
||||
} = useGridEditor(sessionId)
|
||||
|
||||
const [showImage, setShowImage] = useState(true)
|
||||
const [zoom, setZoom] = useState(100)
|
||||
const [markSaving, setMarkSaving] = useState(false)
|
||||
const [message, setMessage] = useState('')
|
||||
|
||||
// Expose save function via ref
|
||||
useEffect(() => {
|
||||
if (gridSaveRef) {
|
||||
gridSaveRef.current = async () => {
|
||||
if (dirty) await saveGrid()
|
||||
}
|
||||
return () => { gridSaveRef.current = null }
|
||||
}
|
||||
}, [gridSaveRef, dirty, saveGrid])
|
||||
|
||||
// Load grid on mount
|
||||
useEffect(() => {
|
||||
if (sessionId) loadGrid()
|
||||
}, [sessionId, loadGrid])
|
||||
|
||||
// Keyboard shortcuts
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'z' && !e.shiftKey) {
|
||||
e.preventDefault(); undo()
|
||||
} else if ((e.metaKey || e.ctrlKey) && e.key === 'z' && e.shiftKey) {
|
||||
e.preventDefault(); redo()
|
||||
} else if ((e.metaKey || e.ctrlKey) && e.key === 's') {
|
||||
e.preventDefault(); saveGrid()
|
||||
} else if ((e.metaKey || e.ctrlKey) && e.key === 'b') {
|
||||
e.preventDefault()
|
||||
if (selectedCells.size > 0) toggleSelectedBold()
|
||||
} else if (e.key === 'Escape') {
|
||||
clearCellSelection()
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', handler)
|
||||
return () => window.removeEventListener('keydown', handler)
|
||||
}, [undo, redo, saveGrid, selectedCells, toggleSelectedBold, clearCellSelection])
|
||||
|
||||
const handleNavigate = useCallback(
|
||||
(cellId: string, direction: 'up' | 'down' | 'left' | 'right') => {
|
||||
const target = getAdjacentCell(cellId, direction)
|
||||
if (target) {
|
||||
setSelectedCell(target)
|
||||
setTimeout(() => {
|
||||
const el = document.getElementById(`cell-${target}`)
|
||||
if (el) {
|
||||
el.focus()
|
||||
if (el instanceof HTMLInputElement) el.select()
|
||||
}
|
||||
}, 0)
|
||||
}
|
||||
},
|
||||
[getAdjacentCell, setSelectedCell],
|
||||
)
|
||||
|
||||
const handleMark = async () => {
|
||||
if (!sessionId) return
|
||||
setMarkSaving(true)
|
||||
setMessage('')
|
||||
try {
|
||||
if (dirty) await saveGrid()
|
||||
const res = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/mark-ground-truth?pipeline=kombi`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '')
|
||||
throw new Error(`Ground Truth fehlgeschlagen (${res.status}): ${body}`)
|
||||
}
|
||||
const data = await res.json()
|
||||
setMessage(`Ground Truth gespeichert (${data.cells_saved} Zellen)`)
|
||||
onMarked()
|
||||
} catch (e) {
|
||||
setMessage(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setMarkSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!sessionId) {
|
||||
return <div className="text-center py-12 text-gray-400">Keine Session ausgewaehlt.</div>
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
<div className="flex items-center gap-3 text-gray-500 dark:text-gray-400">
|
||||
<svg className="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
Grid wird geladen...
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
|
||||
<p className="text-sm text-red-700 dark:text-red-300">Fehler: {error}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!grid || !grid.zones.length) {
|
||||
return <div className="text-center py-12 text-gray-400">Kein Grid vorhanden.</div>
|
||||
}
|
||||
|
||||
const imageUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* GT Header Bar */}
|
||||
<div className="flex items-center justify-between p-3 bg-amber-50 dark:bg-amber-900/10 rounded-xl border border-amber-200 dark:border-amber-800">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-amber-700 dark:text-amber-300">
|
||||
Ground Truth
|
||||
{isGroundTruth && <span className="ml-2 text-xs font-normal text-amber-500">(bereits markiert)</span>}
|
||||
</h3>
|
||||
<p className="text-xs text-amber-600 dark:text-amber-400 mt-0.5">
|
||||
Pruefen Sie das Ergebnis und markieren Sie es als Referenz fuer Regressionstests.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{dirty && (
|
||||
<button
|
||||
onClick={saveGrid}
|
||||
disabled={saving}
|
||||
className="px-3 py-1.5 text-xs bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50"
|
||||
>
|
||||
{saving ? 'Speichere...' : 'Speichern'}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={handleMark}
|
||||
disabled={markSaving}
|
||||
className="px-4 py-1.5 text-xs bg-amber-600 text-white rounded-lg hover:bg-amber-700 disabled:opacity-50"
|
||||
>
|
||||
{markSaving ? 'Speichere...' : isGroundTruth ? 'GT aktualisieren' : 'Als Ground Truth markieren'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{message && (
|
||||
<div className={`text-sm p-2 rounded ${message.includes('fehlgeschlagen') ? 'text-red-500 bg-red-50 dark:bg-red-900/20' : 'text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/10'}`}>
|
||||
{message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stats */}
|
||||
<div className="flex items-center gap-4 text-xs flex-wrap">
|
||||
<span className="text-gray-500 dark:text-gray-400">
|
||||
{grid.summary.total_zones} Zone(n), {grid.summary.total_columns} Spalten,{' '}
|
||||
{grid.summary.total_rows} Zeilen, {grid.summary.total_cells} Zellen
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setShowImage(!showImage)}
|
||||
className={`px-2.5 py-1 rounded text-xs border transition-colors ${
|
||||
showImage
|
||||
? 'bg-teal-50 dark:bg-teal-900/30 border-teal-200 dark:border-teal-700 text-teal-700 dark:text-teal-300'
|
||||
: 'bg-gray-50 dark:bg-gray-800 border-gray-200 dark:border-gray-700 text-gray-500 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
{showImage ? 'Bild ausblenden' : 'Bild einblenden'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Split View: Image left + Grid right */}
|
||||
<div className={showImage ? 'grid grid-cols-2 gap-3' : ''} style={{ minHeight: '55vh' }}>
|
||||
{showImage && (
|
||||
<ImageLayoutEditor
|
||||
imageUrl={imageUrl}
|
||||
zones={grid.zones}
|
||||
imageWidth={grid.image_width}
|
||||
layoutDividers={grid.layout_dividers}
|
||||
zoom={zoom}
|
||||
onZoomChange={setZoom}
|
||||
onColumnDividerMove={() => {}}
|
||||
onHorizontalsChange={() => {}}
|
||||
onCommitUndo={() => {}}
|
||||
onSplitColumnAt={() => {}}
|
||||
onDeleteColumn={() => {}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
{(() => {
|
||||
const groups: GridZone[][] = []
|
||||
for (const zone of grid.zones) {
|
||||
const prev = groups[groups.length - 1]
|
||||
if (prev && zone.vsplit_group != null && prev[0].vsplit_group === zone.vsplit_group) {
|
||||
prev.push(zone)
|
||||
} else {
|
||||
groups.push([zone])
|
||||
}
|
||||
}
|
||||
return groups.map((group) => (
|
||||
<div key={group[0].vsplit_group ?? group[0].zone_index}>
|
||||
<div className={`${group.length > 1 ? 'flex gap-2' : ''}`}>
|
||||
{group.map((zone) => (
|
||||
<div
|
||||
key={zone.zone_index}
|
||||
className={`${group.length > 1 ? 'flex-1 min-w-0' : ''} bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700`}
|
||||
>
|
||||
<GridTable
|
||||
zone={zone}
|
||||
layoutMetrics={grid.layout_metrics}
|
||||
selectedCell={selectedCell}
|
||||
selectedCells={selectedCells}
|
||||
onSelectCell={setSelectedCell}
|
||||
onToggleCellSelection={toggleCellSelection}
|
||||
onCellTextChange={updateCellText}
|
||||
onToggleColumnBold={toggleColumnBold}
|
||||
onToggleRowHeader={toggleRowHeader}
|
||||
onNavigate={handleNavigate}
|
||||
onDeleteColumn={deleteColumn}
|
||||
onAddColumn={addColumn}
|
||||
onDeleteRow={deleteRow}
|
||||
onAddRow={addRow}
|
||||
onSetCellColor={setCellColor}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Keyboard tips */}
|
||||
<div className="text-[11px] text-gray-400 dark:text-gray-500 flex items-center gap-4">
|
||||
<span>Tab: naechste Zelle</span>
|
||||
<span>Ctrl+Z/Y: Undo/Redo</span>
|
||||
<span>Ctrl+S: Speichern</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
422
admin-lehrer/components/ocr-kombi/StepGutterRepair.tsx
Normal file
422
admin-lehrer/components/ocr-kombi/StepGutterRepair.tsx
Normal file
@@ -0,0 +1,422 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface GutterSuggestion {
|
||||
id: string
|
||||
type: 'hyphen_join' | 'spell_fix'
|
||||
zone_index: number
|
||||
row_index: number
|
||||
col_index: number
|
||||
col_type: string
|
||||
cell_id: string
|
||||
original_text: string
|
||||
suggested_text: string
|
||||
next_row_index: number
|
||||
next_row_cell_id: string
|
||||
next_row_text: string
|
||||
missing_chars: string
|
||||
display_parts: string[]
|
||||
alternatives: string[]
|
||||
confidence: number
|
||||
reason: string
|
||||
}
|
||||
|
||||
interface GutterRepairResult {
|
||||
suggestions: GutterSuggestion[]
|
||||
stats: {
|
||||
words_checked: number
|
||||
gutter_candidates: number
|
||||
suggestions_found: number
|
||||
error?: string
|
||||
}
|
||||
duration_seconds: number
|
||||
}
|
||||
|
||||
interface StepGutterRepairProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 11: Gutter Repair (Wortkorrektur).
|
||||
* Detects words truncated at the book gutter and proposes corrections.
|
||||
* User can accept/reject each suggestion individually or in batch.
|
||||
*/
|
||||
export function StepGutterRepair({ sessionId, onNext }: StepGutterRepairProps) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [applying, setApplying] = useState(false)
|
||||
const [result, setResult] = useState<GutterRepairResult | null>(null)
|
||||
const [accepted, setAccepted] = useState<Set<string>>(new Set())
|
||||
const [rejected, setRejected] = useState<Set<string>>(new Set())
|
||||
const [selectedText, setSelectedText] = useState<Record<string, string>>({})
|
||||
const [applied, setApplied] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [applyMessage, setApplyMessage] = useState('')
|
||||
|
||||
const analyse = useCallback(async () => {
|
||||
if (!sessionId) return
|
||||
setLoading(true)
|
||||
setError('')
|
||||
setApplied(false)
|
||||
setApplyMessage('')
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/gutter-repair`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}))
|
||||
throw new Error(body.detail || `Analyse fehlgeschlagen (${res.status})`)
|
||||
}
|
||||
const data: GutterRepairResult = await res.json()
|
||||
setResult(data)
|
||||
// Auto-accept all suggestions with high confidence
|
||||
const autoAccept = new Set<string>()
|
||||
for (const s of data.suggestions) {
|
||||
if (s.confidence >= 0.85) {
|
||||
autoAccept.add(s.id)
|
||||
}
|
||||
}
|
||||
setAccepted(autoAccept)
|
||||
setRejected(new Set())
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [sessionId])
|
||||
|
||||
// Auto-trigger analysis on mount
|
||||
useEffect(() => {
|
||||
if (sessionId) analyse()
|
||||
}, [sessionId, analyse])
|
||||
|
||||
const toggleSuggestion = (id: string) => {
|
||||
setAccepted(prev => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(id)) {
|
||||
next.delete(id)
|
||||
setRejected(r => new Set(r).add(id))
|
||||
} else {
|
||||
next.add(id)
|
||||
setRejected(r => { const n = new Set(r); n.delete(id); return n })
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const acceptAll = () => {
|
||||
if (!result) return
|
||||
setAccepted(new Set(result.suggestions.map(s => s.id)))
|
||||
setRejected(new Set())
|
||||
}
|
||||
|
||||
const rejectAll = () => {
|
||||
if (!result) return
|
||||
setRejected(new Set(result.suggestions.map(s => s.id)))
|
||||
setAccepted(new Set())
|
||||
}
|
||||
|
||||
const applyAccepted = async () => {
|
||||
if (!sessionId || accepted.size === 0) return
|
||||
setApplying(true)
|
||||
setApplyMessage('')
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/gutter-repair/apply`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
accepted: Array.from(accepted),
|
||||
text_overrides: selectedText,
|
||||
}),
|
||||
},
|
||||
)
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}))
|
||||
throw new Error(body.detail || `Anwenden fehlgeschlagen (${res.status})`)
|
||||
}
|
||||
const data = await res.json()
|
||||
setApplied(true)
|
||||
setApplyMessage(`${data.applied_count} Korrektur(en) angewendet.`)
|
||||
} catch (e) {
|
||||
setApplyMessage(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setApplying(false)
|
||||
}
|
||||
}
|
||||
|
||||
const suggestions = result?.suggestions || []
|
||||
const hasSuggestions = suggestions.length > 0
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
Wortkorrektur (Buchfalz)
|
||||
</h3>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
Erkennt abgeschnittene oder unscharfe Woerter am Buchfalz und Bindestrich-Trennungen ueber Zeilen hinweg.
|
||||
</p>
|
||||
</div>
|
||||
{result && !loading && (
|
||||
<button
|
||||
onClick={analyse}
|
||||
className="px-3 py-1.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600"
|
||||
>
|
||||
Erneut analysieren
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Loading */}
|
||||
{loading && (
|
||||
<div className="flex items-center gap-3 p-6 bg-blue-50 dark:bg-blue-900/20 rounded-xl border border-blue-200 dark:border-blue-800">
|
||||
<div className="animate-spin w-5 h-5 border-2 border-blue-400 border-t-transparent rounded-full" />
|
||||
<span className="text-sm text-blue-600 dark:text-blue-400">Analysiere Woerter am Buchfalz...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="space-y-3">
|
||||
<div className="text-sm text-red-500 bg-red-50 dark:bg-red-900/20 p-3 rounded-lg">
|
||||
{error}
|
||||
</div>
|
||||
<button
|
||||
onClick={analyse}
|
||||
className="px-4 py-2 bg-orange-600 text-white text-sm rounded-lg hover:bg-orange-700"
|
||||
>
|
||||
Erneut versuchen
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* No suggestions */}
|
||||
{result && !hasSuggestions && !loading && (
|
||||
<div className="p-4 bg-green-50 dark:bg-green-900/20 rounded-xl border border-green-200 dark:border-green-800">
|
||||
<div className="text-sm font-medium text-green-700 dark:text-green-300">
|
||||
Keine Buchfalz-Fehler erkannt.
|
||||
</div>
|
||||
<div className="text-xs text-green-600 dark:text-green-400 mt-1">
|
||||
{result.stats.words_checked} Woerter geprueft, {result.stats.gutter_candidates} Kandidaten am Rand analysiert.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Suggestions list */}
|
||||
{hasSuggestions && !loading && (
|
||||
<>
|
||||
{/* Stats bar */}
|
||||
<div className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{suggestions.length} Vorschlag/Vorschlaege ·{' '}
|
||||
{result!.stats.words_checked} Woerter geprueft ·{' '}
|
||||
{result!.duration_seconds}s
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={acceptAll}
|
||||
disabled={applied}
|
||||
className="px-2 py-1 text-xs bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 rounded hover:bg-green-200 dark:hover:bg-green-900/50 disabled:opacity-50"
|
||||
>
|
||||
Alle akzeptieren
|
||||
</button>
|
||||
<button
|
||||
onClick={rejectAll}
|
||||
disabled={applied}
|
||||
className="px-2 py-1 text-xs bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 rounded hover:bg-red-200 dark:hover:bg-red-900/50 disabled:opacity-50"
|
||||
>
|
||||
Alle ablehnen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Suggestion cards */}
|
||||
<div className="space-y-2">
|
||||
{suggestions.map((s) => {
|
||||
const isAccepted = accepted.has(s.id)
|
||||
const isRejected = rejected.has(s.id)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={s.id}
|
||||
className={`p-3 rounded-lg border transition-colors ${
|
||||
applied
|
||||
? isAccepted
|
||||
? 'bg-green-50 dark:bg-green-900/10 border-green-200 dark:border-green-800'
|
||||
: 'bg-gray-50 dark:bg-gray-800/50 border-gray-200 dark:border-gray-700 opacity-60'
|
||||
: isAccepted
|
||||
? 'bg-green-50 dark:bg-green-900/10 border-green-300 dark:border-green-700'
|
||||
: isRejected
|
||||
? 'bg-red-50 dark:bg-red-900/10 border-red-200 dark:border-red-800 opacity-60'
|
||||
: 'bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
{/* Left: suggestion details */}
|
||||
<div className="flex-1 min-w-0">
|
||||
{/* Type badge */}
|
||||
<div className="flex items-center gap-2 mb-1.5">
|
||||
<span className={`inline-flex px-1.5 py-0.5 text-[10px] font-medium rounded ${
|
||||
s.type === 'hyphen_join'
|
||||
? 'bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300'
|
||||
: 'bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-300'
|
||||
}`}>
|
||||
{s.type === 'hyphen_join' ? 'Zeilenumbruch' : 'Buchfalz-Korrektur'}
|
||||
</span>
|
||||
<span className="text-[10px] text-gray-400">
|
||||
Zeile {s.row_index + 1}, Spalte {s.col_index + 1}
|
||||
{s.col_type && ` (${s.col_type.replace('column_', '')})`}
|
||||
</span>
|
||||
<span className={`text-[10px] ${
|
||||
s.confidence >= 0.9 ? 'text-green-500' :
|
||||
s.confidence >= 0.7 ? 'text-yellow-500' : 'text-red-500'
|
||||
}`}>
|
||||
{Math.round(s.confidence * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Correction display */}
|
||||
{s.type === 'hyphen_join' ? (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="font-mono text-red-600 dark:text-red-400 line-through">
|
||||
{s.original_text}
|
||||
</span>
|
||||
<span className="text-gray-400 text-xs">Z.{s.row_index + 1}</span>
|
||||
<span className="text-gray-300 dark:text-gray-600">+</span>
|
||||
<span className="font-mono text-red-600 dark:text-red-400 line-through">
|
||||
{s.next_row_text.split(' ')[0]}
|
||||
</span>
|
||||
<span className="text-gray-400 text-xs">Z.{s.next_row_index + 1}</span>
|
||||
<span className="text-gray-400">→</span>
|
||||
<span className="font-mono text-green-600 dark:text-green-400 font-semibold">
|
||||
{s.suggested_text}
|
||||
</span>
|
||||
</div>
|
||||
{s.missing_chars && (
|
||||
<div className="text-[10px] text-gray-400">
|
||||
Fehlende Zeichen: <span className="font-mono font-semibold">{s.missing_chars}</span>
|
||||
{' '}· Darstellung: <span className="font-mono">{s.display_parts.join(' | ')}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="font-mono text-red-600 dark:text-red-400 line-through">
|
||||
{s.original_text}
|
||||
</span>
|
||||
<span className="text-gray-400">→</span>
|
||||
<span className="font-mono text-green-600 dark:text-green-400 font-semibold">
|
||||
{selectedText[s.id] || s.suggested_text}
|
||||
</span>
|
||||
</div>
|
||||
{/* Alternatives: show other candidates the user can pick */}
|
||||
{s.alternatives && s.alternatives.length > 0 && !applied && (
|
||||
<div className="flex items-center gap-1.5 flex-wrap">
|
||||
<span className="text-[10px] text-gray-400">Alternativen:</span>
|
||||
{[s.suggested_text, ...s.alternatives].map((alt) => {
|
||||
const isSelected = (selectedText[s.id] || s.suggested_text) === alt
|
||||
return (
|
||||
<button
|
||||
key={alt}
|
||||
onClick={() => setSelectedText(prev => ({ ...prev, [s.id]: alt }))}
|
||||
className={`px-1.5 py-0.5 text-[11px] font-mono rounded transition-colors ${
|
||||
isSelected
|
||||
? 'bg-green-200 dark:bg-green-800 text-green-800 dark:text-green-200 font-semibold'
|
||||
: 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
{alt}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Right: accept/reject toggle */}
|
||||
{!applied && (
|
||||
<button
|
||||
onClick={() => toggleSuggestion(s.id)}
|
||||
className={`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-sm transition-colors ${
|
||||
isAccepted
|
||||
? 'bg-green-500 text-white hover:bg-green-600'
|
||||
: isRejected
|
||||
? 'bg-red-400 text-white hover:bg-red-500'
|
||||
: 'bg-gray-200 dark:bg-gray-600 text-gray-500 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500'
|
||||
}`}
|
||||
title={isAccepted ? 'Akzeptiert (klicken zum Ablehnen)' : isRejected ? 'Abgelehnt (klicken zum Akzeptieren)' : 'Klicken zum Akzeptieren'}
|
||||
>
|
||||
{isAccepted ? '\u2713' : isRejected ? '\u2717' : '?'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Apply / Next buttons */}
|
||||
<div className="flex items-center gap-3 pt-2">
|
||||
{!applied ? (
|
||||
<button
|
||||
onClick={applyAccepted}
|
||||
disabled={applying || accepted.size === 0}
|
||||
className="px-4 py-2 bg-teal-600 text-white text-sm rounded-lg hover:bg-teal-700 disabled:opacity-50"
|
||||
>
|
||||
{applying ? 'Wird angewendet...' : `${accepted.size} Korrektur(en) anwenden`}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={onNext}
|
||||
className="px-4 py-2 bg-teal-600 text-white text-sm rounded-lg hover:bg-teal-700"
|
||||
>
|
||||
Weiter zu Ground Truth
|
||||
</button>
|
||||
)}
|
||||
{!applied && (
|
||||
<button
|
||||
onClick={onNext}
|
||||
className="px-4 py-2 text-sm text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200"
|
||||
>
|
||||
Ueberspringen
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Apply result message */}
|
||||
{applyMessage && (
|
||||
<div className={`text-sm p-2 rounded ${
|
||||
applyMessage.includes('fehlgeschlagen')
|
||||
? 'text-red-500 bg-red-50 dark:bg-red-900/20'
|
||||
: 'text-green-600 dark:text-green-400 bg-green-50 dark:bg-green-900/20'
|
||||
}`}>
|
||||
{applyMessage}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Skip button when no suggestions */}
|
||||
{result && !hasSuggestions && !loading && (
|
||||
<button
|
||||
onClick={onNext}
|
||||
className="px-4 py-2 bg-teal-600 text-white text-sm rounded-lg hover:bg-teal-700"
|
||||
>
|
||||
Weiter zu Ground Truth
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
30
admin-lehrer/components/ocr-kombi/StepOcr.tsx
Normal file
30
admin-lehrer/components/ocr-kombi/StepOcr.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
'use client'
|
||||
|
||||
import { PaddleDirectStep } from '@/components/ocr-overlay/PaddleDirectStep'
|
||||
|
||||
interface StepOcrProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 7: OCR (Kombi mode = PaddleOCR + Tesseract).
|
||||
*
|
||||
* Phase 1: Uses the existing PaddleDirectStep with kombi endpoint.
|
||||
* Phase 3 (later) will add transparent 3-phase progress + engine comparison.
|
||||
*/
|
||||
export function StepOcr({ sessionId, onNext }: StepOcrProps) {
|
||||
return (
|
||||
<PaddleDirectStep
|
||||
sessionId={sessionId}
|
||||
onNext={onNext}
|
||||
endpoint="paddle-kombi"
|
||||
title="Kombi-Modus"
|
||||
description="PP-OCRv5 und Tesseract laufen parallel. Koordinaten werden gewichtet gemittelt fuer optimale Positionierung."
|
||||
icon="🔀"
|
||||
buttonLabel="PP-OCRv5 + Tesseract starten"
|
||||
runningLabel="PP-OCRv5 + Tesseract laufen..."
|
||||
engineKey="kombi"
|
||||
/>
|
||||
)
|
||||
}
|
||||
21
admin-lehrer/components/ocr-kombi/StepOrientation.tsx
Normal file
21
admin-lehrer/components/ocr-kombi/StepOrientation.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
'use client'
|
||||
|
||||
import { StepOrientation as BaseStepOrientation } from '@/components/ocr-pipeline/StepOrientation'
|
||||
|
||||
interface StepOrientationProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
onSessionList: () => void
|
||||
}
|
||||
|
||||
/** Thin wrapper — adapts the shared StepOrientation to the Kombi pipeline's simpler onNext() */
|
||||
export function StepOrientation({ sessionId, onNext, onSessionList }: StepOrientationProps) {
|
||||
return (
|
||||
<BaseStepOrientation
|
||||
key={sessionId}
|
||||
sessionId={sessionId}
|
||||
onNext={() => onNext()}
|
||||
onSessionList={onSessionList}
|
||||
/>
|
||||
)
|
||||
}
|
||||
198
admin-lehrer/components/ocr-kombi/StepPageSplit.tsx
Normal file
198
admin-lehrer/components/ocr-kombi/StepPageSplit.tsx
Normal file
@@ -0,0 +1,198 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface PageSplitResult {
|
||||
multi_page: boolean
|
||||
page_count?: number
|
||||
page_splits?: { x: number; y: number; width: number; height: number; page_index: number }[]
|
||||
sub_sessions?: { id: string; name: string; page_index: number }[]
|
||||
used_original?: boolean
|
||||
duration_seconds?: number
|
||||
}
|
||||
|
||||
interface StepPageSplitProps {
|
||||
sessionId: string | null
|
||||
sessionName: string
|
||||
onNext: () => void
|
||||
onSplitComplete: (firstChildId: string, firstChildName: string) => void
|
||||
}
|
||||
|
||||
export function StepPageSplit({ sessionId, sessionName, onNext, onSplitComplete }: StepPageSplitProps) {
|
||||
const [detecting, setDetecting] = useState(false)
|
||||
const [splitResult, setSplitResult] = useState<PageSplitResult | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
const didDetect = useRef(false)
|
||||
|
||||
// Auto-detect page split when step opens
|
||||
useEffect(() => {
|
||||
if (!sessionId || didDetect.current) return
|
||||
didDetect.current = true
|
||||
detectPageSplit()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [sessionId])
|
||||
|
||||
const detectPageSplit = async () => {
|
||||
if (!sessionId) return
|
||||
setDetecting(true)
|
||||
setError('')
|
||||
try {
|
||||
// First check if this session was already split (status='split')
|
||||
const sessionRes = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}`)
|
||||
if (sessionRes.ok) {
|
||||
const sessionData = await sessionRes.json()
|
||||
if (sessionData.status === 'split' && sessionData.crop_result?.multi_page) {
|
||||
// Already split — find the child sessions in the session list
|
||||
const listRes = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions`)
|
||||
if (listRes.ok) {
|
||||
const listData = await listRes.json()
|
||||
// Child sessions have names like "ParentName — Seite N"
|
||||
const baseName = sessionName || sessionData.name || ''
|
||||
const children = (listData.sessions || [])
|
||||
.filter((s: { name?: string }) => s.name?.startsWith(baseName + ' — '))
|
||||
.sort((a: { name: string }, b: { name: string }) => a.name.localeCompare(b.name))
|
||||
if (children.length > 0) {
|
||||
setSplitResult({
|
||||
multi_page: true,
|
||||
page_count: children.length,
|
||||
sub_sessions: children.map((s: { id: string; name: string }, i: number) => ({
|
||||
id: s.id, name: s.name, page_index: i,
|
||||
})),
|
||||
})
|
||||
onSplitComplete(children[0].id, children[0].name)
|
||||
setDetecting(false)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Run page-split detection
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/page-split`, {
|
||||
method: 'POST',
|
||||
})
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}))
|
||||
throw new Error(data.detail || 'Seitentrennung fehlgeschlagen')
|
||||
}
|
||||
const data: PageSplitResult = await res.json()
|
||||
setSplitResult(data)
|
||||
|
||||
if (data.multi_page && data.sub_sessions?.length) {
|
||||
// Rename sub-sessions to "Title — S. 1", "Title — S. 2"
|
||||
const baseName = sessionName || 'Dokument'
|
||||
for (let i = 0; i < data.sub_sessions.length; i++) {
|
||||
const sub = data.sub_sessions[i]
|
||||
const newName = `${baseName} — S. ${i + 1}`
|
||||
await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sub.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: newName }),
|
||||
}).catch(() => {})
|
||||
sub.name = newName
|
||||
}
|
||||
|
||||
// Signal parent to switch to the first child session
|
||||
onSplitComplete(data.sub_sessions[0].id, data.sub_sessions[0].name)
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setDetecting(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!sessionId) return null
|
||||
|
||||
const imageUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/oriented`
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Image */}
|
||||
<div className="relative rounded-lg overflow-hidden bg-gray-100 dark:bg-gray-700">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt="Orientiertes Bild"
|
||||
className="w-full object-contain max-h-[500px]"
|
||||
onError={(e) => {
|
||||
// Fallback to non-oriented image
|
||||
(e.target as HTMLImageElement).src =
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image`
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Detection status */}
|
||||
{detecting && (
|
||||
<div className="flex items-center gap-2 text-teal-600 dark:text-teal-400 text-sm">
|
||||
<div className="animate-spin w-4 h-4 border-2 border-teal-500 border-t-transparent rounded-full" />
|
||||
Doppelseiten-Erkennung laeuft...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Detection result */}
|
||||
{splitResult && !detecting && (
|
||||
splitResult.multi_page ? (
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-700 p-4 space-y-2">
|
||||
<div className="text-sm font-medium text-blue-700 dark:text-blue-300">
|
||||
Doppelseite erkannt — {splitResult.page_count} Seiten getrennt
|
||||
</div>
|
||||
<p className="text-xs text-blue-600 dark:text-blue-400">
|
||||
Jede Seite wird als eigene Session weiterverarbeitet (eigene Begradigung, Entzerrung, etc.).
|
||||
{splitResult.used_original && ' Trennung auf Originalbild, da Orientierung die Doppelseite gedreht hat.'}
|
||||
</p>
|
||||
<div className="flex gap-2 mt-2">
|
||||
{splitResult.sub_sessions?.map(s => (
|
||||
<span
|
||||
key={s.id}
|
||||
className="text-xs px-2.5 py-1 rounded-md bg-blue-100 dark:bg-blue-800/40 text-blue-700 dark:text-blue-300 font-medium"
|
||||
>
|
||||
{s.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{splitResult.duration_seconds != null && (
|
||||
<div className="text-xs text-gray-400">{splitResult.duration_seconds.toFixed(1)}s</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-green-50 dark:bg-green-900/20 rounded-lg border border-green-200 dark:border-green-800 p-4">
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-green-700 dark:text-green-300">
|
||||
<span>✓</span> Einzelseite — keine Trennung noetig
|
||||
</div>
|
||||
{splitResult.duration_seconds != null && (
|
||||
<div className="text-xs text-gray-400 mt-1">{splitResult.duration_seconds.toFixed(1)}s</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="text-sm text-red-500 bg-red-50 dark:bg-red-900/20 p-3 rounded-lg">
|
||||
{error}
|
||||
<button
|
||||
onClick={() => { didDetect.current = false; detectPageSplit() }}
|
||||
className="ml-2 text-teal-600 hover:underline"
|
||||
>
|
||||
Erneut versuchen
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Next button — only show when detection is done */}
|
||||
{(splitResult || error) && !detecting && (
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
onClick={onNext}
|
||||
className="px-6 py-2.5 bg-teal-600 text-white text-sm font-medium rounded-lg hover:bg-teal-700 transition-colors"
|
||||
>
|
||||
Weiter →
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
13
admin-lehrer/components/ocr-kombi/StepStructure.tsx
Normal file
13
admin-lehrer/components/ocr-kombi/StepStructure.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
'use client'
|
||||
|
||||
import { StepStructureDetection } from '@/components/ocr-pipeline/StepStructureDetection'
|
||||
|
||||
interface StepStructureProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
/** Thin wrapper around the shared StepStructureDetection component */
|
||||
export function StepStructure({ sessionId, onNext }: StepStructureProps) {
|
||||
return <StepStructureDetection sessionId={sessionId} onNext={onNext} />
|
||||
}
|
||||
303
admin-lehrer/components/ocr-kombi/StepUpload.tsx
Normal file
303
admin-lehrer/components/ocr-kombi/StepUpload.tsx
Normal file
@@ -0,0 +1,303 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useCallback, useEffect } from 'react'
|
||||
import { DOCUMENT_CATEGORIES, type DocumentCategory } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface StepUploadProps {
|
||||
sessionId: string | null
|
||||
onUploaded: (sessionId: string, name: string) => void
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
export function StepUpload({ sessionId, onUploaded, onNext }: StepUploadProps) {
|
||||
const [dragging, setDragging] = useState(false)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [preview, setPreview] = useState<string | null>(null)
|
||||
const [title, setTitle] = useState('')
|
||||
const [category, setCategory] = useState<DocumentCategory>('vokabelseite')
|
||||
const [error, setError] = useState('')
|
||||
|
||||
// Clean up preview URL on unmount
|
||||
useEffect(() => {
|
||||
return () => { if (preview) URL.revokeObjectURL(preview) }
|
||||
}, [preview])
|
||||
|
||||
const handleFileSelect = useCallback((file: File) => {
|
||||
setSelectedFile(file)
|
||||
setError('')
|
||||
if (file.type.startsWith('image/')) {
|
||||
setPreview(URL.createObjectURL(file))
|
||||
} else {
|
||||
setPreview(null)
|
||||
}
|
||||
// Auto-fill title from filename if empty
|
||||
if (!title.trim()) {
|
||||
setTitle(file.name.replace(/\.[^.]+$/, ''))
|
||||
}
|
||||
}, [title])
|
||||
|
||||
const handleUpload = useCallback(async () => {
|
||||
if (!selectedFile) return
|
||||
setUploading(true)
|
||||
setError('')
|
||||
|
||||
try {
|
||||
const formData = new FormData()
|
||||
formData.append('file', selectedFile)
|
||||
if (title.trim()) formData.append('name', title.trim())
|
||||
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}))
|
||||
throw new Error(data.detail || `Upload fehlgeschlagen (${res.status})`)
|
||||
}
|
||||
|
||||
const data = await res.json()
|
||||
const sid = data.session_id || data.id
|
||||
|
||||
// Set category
|
||||
if (category) {
|
||||
await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ document_category: category }),
|
||||
})
|
||||
}
|
||||
|
||||
onUploaded(sid, title.trim() || selectedFile.name)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setUploading(false)
|
||||
}
|
||||
}, [selectedFile, title, category, onUploaded])
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setDragging(false)
|
||||
const file = e.dataTransfer.files[0]
|
||||
if (file) handleFileSelect(file)
|
||||
}, [handleFileSelect])
|
||||
|
||||
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) handleFileSelect(file)
|
||||
}, [handleFileSelect])
|
||||
|
||||
const clearFile = useCallback(() => {
|
||||
setSelectedFile(null)
|
||||
if (preview) URL.revokeObjectURL(preview)
|
||||
setPreview(null)
|
||||
}, [preview])
|
||||
|
||||
// ---- Phase 2: Uploaded → show result + "Weiter" ----
|
||||
if (sessionId) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4">
|
||||
<div className="flex items-center gap-2 text-green-700 dark:text-green-300 text-sm font-medium mb-3">
|
||||
<span>✓</span> Dokument hochgeladen
|
||||
</div>
|
||||
<div className="flex gap-4">
|
||||
<div className="w-48 h-64 rounded-lg overflow-hidden bg-gray-100 dark:bg-gray-700 flex-shrink-0 border border-gray-200 dark:border-gray-600">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image`}
|
||||
alt="Hochgeladenes Dokument"
|
||||
className="w-full h-full object-contain"
|
||||
onError={(e) => { (e.target as HTMLImageElement).style.display = 'none' }}
|
||||
/>
|
||||
</div>
|
||||
<div className="text-sm text-gray-600 dark:text-gray-400">
|
||||
<div className="font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
{title || 'Dokument'}
|
||||
</div>
|
||||
<div className="text-xs text-gray-400 mt-1">
|
||||
Kategorie: {DOCUMENT_CATEGORIES.find(c => c.value === category)?.label || category}
|
||||
</div>
|
||||
<div className="text-xs font-mono text-gray-400 mt-1">
|
||||
Session: {sessionId.slice(0, 8)}...
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
onClick={onNext}
|
||||
className="px-6 py-2.5 bg-teal-600 text-white text-sm font-medium rounded-lg hover:bg-teal-700 transition-colors"
|
||||
>
|
||||
Weiter →
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---- Phase 1b: File selected → preview + "Hochladen" ----
|
||||
if (selectedFile) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Title input */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Titel
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="z.B. Vokabeln Unit 3"
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Category selector */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Kategorie
|
||||
</label>
|
||||
<div className="grid grid-cols-4 gap-1.5">
|
||||
{DOCUMENT_CATEGORIES.map(cat => (
|
||||
<button
|
||||
key={cat.value}
|
||||
onClick={() => setCategory(cat.value)}
|
||||
className={`text-xs px-2 py-1.5 rounded-md text-left transition-colors ${
|
||||
category === cat.value
|
||||
? 'bg-teal-100 dark:bg-teal-900/40 text-teal-700 dark:text-teal-300 ring-1 ring-teal-400'
|
||||
: 'bg-gray-50 dark:bg-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
{cat.icon} {cat.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* File preview */}
|
||||
<div className="border border-gray-200 dark:border-gray-700 rounded-xl p-4">
|
||||
<div className="flex items-start gap-4">
|
||||
{preview ? (
|
||||
<div className="w-36 h-48 rounded-lg overflow-hidden bg-gray-100 dark:bg-gray-700 flex-shrink-0 border border-gray-200 dark:border-gray-600">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={preview} alt="Vorschau" className="w-full h-full object-contain" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-36 h-48 rounded-lg bg-gray-100 dark:bg-gray-700 flex-shrink-0 flex items-center justify-center border border-gray-200 dark:border-gray-600">
|
||||
<span className="text-3xl">📄</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-sm text-gray-700 dark:text-gray-300 truncate">
|
||||
{selectedFile.name}
|
||||
</div>
|
||||
<div className="text-xs text-gray-400 mt-1">
|
||||
{(selectedFile.size / 1024 / 1024).toFixed(1)} MB
|
||||
</div>
|
||||
<button
|
||||
onClick={clearFile}
|
||||
className="text-xs text-red-500 hover:text-red-700 mt-2"
|
||||
>
|
||||
Andere Datei waehlen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleUpload}
|
||||
disabled={uploading}
|
||||
className="mt-4 w-full px-4 py-2.5 bg-teal-600 text-white text-sm font-medium rounded-lg hover:bg-teal-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
{uploading ? 'Wird hochgeladen...' : 'Hochladen'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="text-sm text-red-500 bg-red-50 dark:bg-red-900/20 p-3 rounded-lg">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---- Phase 1a: No file → drop zone ----
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Title input */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Titel (optional)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="z.B. Vokabeln Unit 3"
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Category selector */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Kategorie
|
||||
</label>
|
||||
<div className="grid grid-cols-4 gap-1.5">
|
||||
{DOCUMENT_CATEGORIES.map(cat => (
|
||||
<button
|
||||
key={cat.value}
|
||||
onClick={() => setCategory(cat.value)}
|
||||
className={`text-xs px-2 py-1.5 rounded-md text-left transition-colors ${
|
||||
category === cat.value
|
||||
? 'bg-teal-100 dark:bg-teal-900/40 text-teal-700 dark:text-teal-300 ring-1 ring-teal-400'
|
||||
: 'bg-gray-50 dark:bg-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
{cat.icon} {cat.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Drop zone */}
|
||||
<div
|
||||
onDragOver={(e) => { e.preventDefault(); setDragging(true) }}
|
||||
onDragLeave={() => setDragging(false)}
|
||||
onDrop={handleDrop}
|
||||
className={`border-2 border-dashed rounded-xl p-12 text-center transition-colors ${
|
||||
dragging
|
||||
? 'border-teal-400 bg-teal-50 dark:bg-teal-900/20'
|
||||
: 'border-gray-300 dark:border-gray-600 hover:border-gray-400'
|
||||
}`}
|
||||
>
|
||||
<div className="text-4xl mb-3">📤</div>
|
||||
<div className="text-sm text-gray-600 dark:text-gray-400 mb-2">
|
||||
Bild oder PDF hierher ziehen
|
||||
</div>
|
||||
<label className="inline-block px-4 py-2 bg-teal-600 text-white text-sm rounded-lg cursor-pointer hover:bg-teal-700">
|
||||
Datei auswaehlen
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*,.pdf"
|
||||
onChange={handleInputChange}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="text-sm text-red-500 bg-red-50 dark:bg-red-900/20 p-3 rounded-lg">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
231
admin-lehrer/components/ocr-overlay/KombiCompareStep.tsx
Normal file
231
admin-lehrer/components/ocr-overlay/KombiCompareStep.tsx
Normal file
@@ -0,0 +1,231 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { OverlayReconstruction } from './OverlayReconstruction'
|
||||
import type { GridCell } from '@/app/(admin)/ai/ocr-overlay/types'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
type Phase = 'idle' | 'running' | 'compare'
|
||||
|
||||
interface KombiResult {
|
||||
cells: GridCell[]
|
||||
image_width: number
|
||||
image_height: number
|
||||
duration_seconds: number
|
||||
summary: {
|
||||
total_cells: number
|
||||
non_empty_cells: number
|
||||
merged_words: number
|
||||
[key: string]: unknown
|
||||
}
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
interface KombiCompareStepProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
export function KombiCompareStep({ sessionId, onNext }: KombiCompareStepProps) {
|
||||
const [phase, setPhase] = useState<Phase>('idle')
|
||||
const [error, setError] = useState('')
|
||||
const [paddleResult, setPaddleResult] = useState<KombiResult | null>(null)
|
||||
const [rapidResult, setRapidResult] = useState<KombiResult | null>(null)
|
||||
const [paddleStatus, setPaddleStatus] = useState<'pending' | 'running' | 'done' | 'error'>('pending')
|
||||
const [rapidStatus, setRapidStatus] = useState<'pending' | 'running' | 'done' | 'error'>('pending')
|
||||
|
||||
const runBothEngines = async () => {
|
||||
if (!sessionId) return
|
||||
setPhase('running')
|
||||
setError('')
|
||||
setPaddleStatus('running')
|
||||
setRapidStatus('running')
|
||||
setPaddleResult(null)
|
||||
setRapidResult(null)
|
||||
|
||||
const fetchEngine = async (
|
||||
endpoint: string,
|
||||
setResult: (r: KombiResult) => void,
|
||||
setStatus: (s: 'pending' | 'running' | 'done' | 'error') => void,
|
||||
) => {
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/${endpoint}`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}))
|
||||
throw new Error(body.detail || `HTTP ${res.status}`)
|
||||
}
|
||||
const data = await res.json()
|
||||
setResult(data)
|
||||
setStatus('done')
|
||||
} catch (e: unknown) {
|
||||
setStatus('error')
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await Promise.all([
|
||||
fetchEngine('paddle-kombi', setPaddleResult, setPaddleStatus),
|
||||
fetchEngine('rapid-kombi', setRapidResult, setRapidStatus),
|
||||
])
|
||||
setPhase('compare')
|
||||
} catch (e: unknown) {
|
||||
// At least one failed — still show compare if the other succeeded
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
setPhase('compare')
|
||||
}
|
||||
}
|
||||
|
||||
if (phase === 'idle') {
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-8 text-center">
|
||||
<div className="text-4xl mb-3">⚖️</div>
|
||||
<h3 className="text-lg font-semibold text-gray-800 dark:text-gray-200 mb-2">
|
||||
Kombi-Vergleich
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 mb-6 max-w-lg mx-auto">
|
||||
Beide Kombi-Modi (Paddle + Tesseract vs. RapidOCR + Tesseract) laufen parallel.
|
||||
Die Ergebnisse werden nebeneinander angezeigt, damit die Qualitaet direkt verglichen werden kann.
|
||||
</p>
|
||||
<button
|
||||
onClick={runBothEngines}
|
||||
disabled={!sessionId}
|
||||
className="px-5 py-2.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-medium"
|
||||
>
|
||||
Beide Kombi-Modi starten
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (phase === 'running' && !paddleResult && !rapidResult) {
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-8">
|
||||
<div className="flex items-center justify-center gap-8">
|
||||
<EngineStatusCard label="Paddle + Tesseract" status={paddleStatus} />
|
||||
<EngineStatusCard label="RapidOCR + Tesseract" status={rapidStatus} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// compare phase
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{error && (
|
||||
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3 text-sm text-red-700 dark:text-red-300">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
Side-by-Side Vergleich
|
||||
</h3>
|
||||
<button
|
||||
onClick={() => { setPhase('idle'); setPaddleResult(null); setRapidResult(null) }}
|
||||
className="text-xs px-3 py-1.5 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
|
||||
>
|
||||
Neu starten
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{/* Left: Paddle-Kombi */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
🔀 Paddle + Tesseract
|
||||
</span>
|
||||
{paddleStatus === 'error' && (
|
||||
<span className="text-xs text-red-500">Fehler</span>
|
||||
)}
|
||||
</div>
|
||||
{paddleResult ? (
|
||||
<>
|
||||
<OverlayReconstruction
|
||||
sessionId={sessionId}
|
||||
onNext={() => {}}
|
||||
wordResultOverride={paddleResult}
|
||||
/>
|
||||
<StatsBar result={paddleResult} engine="Paddle-Kombi" />
|
||||
</>
|
||||
) : (
|
||||
<div className="bg-gray-50 dark:bg-gray-900 rounded-lg p-12 text-center text-sm text-gray-400">
|
||||
{paddleStatus === 'running' ? 'Laeuft...' : 'Fehlgeschlagen'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Right: Rapid-Kombi */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
⚡ RapidOCR + Tesseract
|
||||
</span>
|
||||
{rapidStatus === 'error' && (
|
||||
<span className="text-xs text-red-500">Fehler</span>
|
||||
)}
|
||||
</div>
|
||||
{rapidResult ? (
|
||||
<>
|
||||
<OverlayReconstruction
|
||||
sessionId={sessionId}
|
||||
onNext={() => {}}
|
||||
wordResultOverride={rapidResult}
|
||||
/>
|
||||
<StatsBar result={rapidResult} engine="Rapid-Kombi" />
|
||||
</>
|
||||
) : (
|
||||
<div className="bg-gray-50 dark:bg-gray-900 rounded-lg p-12 text-center text-sm text-gray-400">
|
||||
{rapidStatus === 'running' ? 'Laeuft...' : 'Fehlgeschlagen'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
onClick={onNext}
|
||||
className="px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors text-sm font-medium"
|
||||
>
|
||||
Fertig
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function EngineStatusCard({ label, status }: { label: string; status: string }) {
|
||||
return (
|
||||
<div className="flex items-center gap-3 bg-gray-50 dark:bg-gray-900 rounded-lg px-5 py-4">
|
||||
{status === 'running' && (
|
||||
<div className="w-5 h-5 border-2 border-teal-400 border-t-transparent rounded-full animate-spin" />
|
||||
)}
|
||||
{status === 'done' && <span className="text-green-500 text-lg">✓</span>}
|
||||
{status === 'error' && <span className="text-red-500 text-lg">✗</span>}
|
||||
{status === 'pending' && <span className="text-gray-400 text-lg">○</span>}
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300">{label}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function StatsBar({ result, engine }: { result: KombiResult; engine: string }) {
|
||||
const nonEmpty = result.summary?.non_empty_cells ?? 0
|
||||
const totalCells = result.summary?.total_cells ?? 0
|
||||
const merged = result.summary?.merged_words ?? 0
|
||||
const duration = result.duration_seconds ?? 0
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-3 text-[11px] text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-900 rounded-lg px-3 py-2">
|
||||
<span className="font-medium text-gray-600 dark:text-gray-300">{engine}</span>
|
||||
<span>{merged} Woerter</span>
|
||||
<span>{nonEmpty}/{totalCells} Zellen</span>
|
||||
<span>{duration.toFixed(2)}s</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
644
admin-lehrer/components/ocr-overlay/OverlayReconstruction.tsx
Normal file
644
admin-lehrer/components/ocr-overlay/OverlayReconstruction.tsx
Normal file
@@ -0,0 +1,644 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { GridResult, GridCell, RowResult, RowItem } from '@/app/(admin)/ai/ocr-overlay/types'
|
||||
import { usePixelWordPositions } from './usePixelWordPositions'
|
||||
import { useSlideWordPositions } from './useSlideWordPositions'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface OverlayReconstructionProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
/** When set, use this data directly instead of fetching from the session API. */
|
||||
wordResultOverride?: { cells: GridCell[]; image_width: number; image_height: number; [key: string]: unknown }
|
||||
}
|
||||
|
||||
interface EditableCell {
|
||||
cellId: string
|
||||
text: string
|
||||
originalText: string
|
||||
bboxPct: { x: number; y: number; w: number; h: number }
|
||||
colType: string
|
||||
rowIndex: number
|
||||
colIndex: number
|
||||
}
|
||||
|
||||
type UndoAction = { cellId: string; oldText: string; newText: string }
|
||||
|
||||
export function OverlayReconstruction({ sessionId, onNext, wordResultOverride }: OverlayReconstructionProps) {
|
||||
const [status, setStatus] = useState<'loading' | 'ready' | 'saving' | 'saved' | 'error'>('loading')
|
||||
const [error, setError] = useState('')
|
||||
const [cells, setCells] = useState<EditableCell[]>([])
|
||||
const [gridCells, setGridCells] = useState<GridCell[]>([])
|
||||
const [editedTexts, setEditedTexts] = useState<Map<string, string>>(new Map())
|
||||
|
||||
// Undo/Redo
|
||||
const [undoStack, setUndoStack] = useState<UndoAction[]>([])
|
||||
const [redoStack, setRedoStack] = useState<UndoAction[]>([])
|
||||
|
||||
// Overlay state
|
||||
const [rows, setRows] = useState<RowItem[]>([])
|
||||
const [imageNaturalSize, setImageNaturalSize] = useState<{ w: number; h: number } | null>(null)
|
||||
const [fontScale, setFontScale] = useState(0.7)
|
||||
const [globalBold, setGlobalBold] = useState(false)
|
||||
const [imageRotation, setImageRotation] = useState<0 | 180>(0)
|
||||
const [textOpacity, setTextOpacity] = useState(100)
|
||||
const [textColor, setTextColor] = useState<'red' | 'blue' | 'black'>('red')
|
||||
const [positioningMode, setPositioningMode] = useState<'cluster' | 'slide'>('slide')
|
||||
const reconRef = useRef<HTMLDivElement>(null)
|
||||
const [reconWidth, setReconWidth] = useState(0)
|
||||
|
||||
// Pixel-based word positions (both algorithms run, toggle selects which to use)
|
||||
const overlayImageUrl = sessionId
|
||||
? `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
: ''
|
||||
const clusterPositions = usePixelWordPositions(
|
||||
overlayImageUrl,
|
||||
gridCells,
|
||||
status === 'ready',
|
||||
imageRotation,
|
||||
)
|
||||
const slidePositions = useSlideWordPositions(
|
||||
overlayImageUrl,
|
||||
gridCells,
|
||||
status === 'ready',
|
||||
imageRotation,
|
||||
)
|
||||
const cellWordPositions = positioningMode === 'slide' ? slidePositions : clusterPositions
|
||||
|
||||
// Track container width
|
||||
useEffect(() => {
|
||||
const el = reconRef.current
|
||||
if (!el) return
|
||||
const obs = new ResizeObserver(entries => {
|
||||
for (const entry of entries) setReconWidth(entry.contentRect.width)
|
||||
})
|
||||
obs.observe(el)
|
||||
return () => obs.disconnect()
|
||||
}, [status])
|
||||
|
||||
// Load session data
|
||||
useEffect(() => {
|
||||
if (wordResultOverride) {
|
||||
applyWordResult(wordResultOverride)
|
||||
return
|
||||
}
|
||||
if (!sessionId) return
|
||||
loadSessionData()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [sessionId, wordResultOverride])
|
||||
|
||||
const applyWordResult = (wordResult: { cells: GridCell[]; image_width: number; image_height: number; [key: string]: unknown }) => {
|
||||
const rawGridCells: GridCell[] = wordResult.cells || []
|
||||
setGridCells(rawGridCells)
|
||||
|
||||
const editableCells: EditableCell[] = rawGridCells.map(c => ({
|
||||
cellId: c.cell_id,
|
||||
text: c.text,
|
||||
originalText: c.text,
|
||||
bboxPct: c.bbox_pct,
|
||||
colType: c.col_type,
|
||||
rowIndex: c.row_index,
|
||||
colIndex: c.col_index,
|
||||
}))
|
||||
setCells(editableCells)
|
||||
setEditedTexts(new Map())
|
||||
setUndoStack([])
|
||||
setRedoStack([])
|
||||
|
||||
if (wordResult.image_width && wordResult.image_height) {
|
||||
setImageNaturalSize({ w: wordResult.image_width, h: wordResult.image_height })
|
||||
}
|
||||
|
||||
setStatus('ready')
|
||||
}
|
||||
|
||||
const loadSessionData = async () => {
|
||||
if (!sessionId) return
|
||||
setStatus('loading')
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}`)
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||
const data = await res.json()
|
||||
|
||||
const wordResult: GridResult | undefined = data.word_result
|
||||
if (!wordResult) {
|
||||
setError('Keine Worterkennungsdaten gefunden. Bitte zuerst den Woerter-Schritt abschliessen.')
|
||||
setStatus('error')
|
||||
return
|
||||
}
|
||||
|
||||
applyWordResult(wordResult as unknown as { cells: GridCell[]; image_width: number; image_height: number })
|
||||
|
||||
// Load rows
|
||||
const rowResult: RowResult | undefined = data.row_result
|
||||
if (rowResult?.rows) setRows(rowResult.rows)
|
||||
} catch (e: unknown) {
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
setStatus('error')
|
||||
}
|
||||
}
|
||||
|
||||
const handleTextChange = useCallback((cellId: string, newText: string) => {
|
||||
setEditedTexts(prev => {
|
||||
const oldText = prev.get(cellId)
|
||||
const cell = cells.find(c => c.cellId === cellId)
|
||||
const prevText = oldText ?? cell?.text ?? ''
|
||||
|
||||
setUndoStack(stack => [...stack, { cellId, oldText: prevText, newText }])
|
||||
setRedoStack([])
|
||||
|
||||
const next = new Map(prev)
|
||||
next.set(cellId, newText)
|
||||
return next
|
||||
})
|
||||
}, [cells])
|
||||
|
||||
const undo = useCallback(() => {
|
||||
setUndoStack(stack => {
|
||||
if (stack.length === 0) return stack
|
||||
const action = stack[stack.length - 1]
|
||||
const newStack = stack.slice(0, -1)
|
||||
setRedoStack(rs => [...rs, action])
|
||||
setEditedTexts(prev => {
|
||||
const next = new Map(prev)
|
||||
next.set(action.cellId, action.oldText)
|
||||
return next
|
||||
})
|
||||
return newStack
|
||||
})
|
||||
}, [])
|
||||
|
||||
const redo = useCallback(() => {
|
||||
setRedoStack(stack => {
|
||||
if (stack.length === 0) return stack
|
||||
const action = stack[stack.length - 1]
|
||||
const newStack = stack.slice(0, -1)
|
||||
setUndoStack(us => [...us, action])
|
||||
setEditedTexts(prev => {
|
||||
const next = new Map(prev)
|
||||
next.set(action.cellId, action.newText)
|
||||
return next
|
||||
})
|
||||
return newStack
|
||||
})
|
||||
}, [])
|
||||
|
||||
const resetCell = useCallback((cellId: string) => {
|
||||
setEditedTexts(prev => {
|
||||
const next = new Map(prev)
|
||||
next.delete(cellId)
|
||||
return next
|
||||
})
|
||||
}, [])
|
||||
|
||||
// Keyboard shortcuts
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'z') {
|
||||
e.preventDefault()
|
||||
if (e.shiftKey) redo()
|
||||
else undo()
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', handler)
|
||||
return () => document.removeEventListener('keydown', handler)
|
||||
}, [undo, redo])
|
||||
|
||||
const getDisplayText = useCallback((cell: EditableCell): string => {
|
||||
return editedTexts.get(cell.cellId) ?? cell.text
|
||||
}, [editedTexts])
|
||||
|
||||
const isEdited = useCallback((cell: EditableCell): boolean => {
|
||||
const edited = editedTexts.get(cell.cellId)
|
||||
return edited !== undefined && edited !== cell.originalText
|
||||
}, [editedTexts])
|
||||
|
||||
const changedCount = useMemo(() => {
|
||||
let count = 0
|
||||
for (const cell of cells) {
|
||||
if (isEdited(cell)) count++
|
||||
}
|
||||
return count
|
||||
}, [cells, isEdited])
|
||||
|
||||
// Tab navigation
|
||||
const sortedCellIds = useMemo(() => {
|
||||
return [...cells]
|
||||
.sort((a, b) => a.rowIndex !== b.rowIndex ? a.rowIndex - b.rowIndex : a.colIndex - b.colIndex)
|
||||
.map(c => c.cellId)
|
||||
}, [cells])
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent, cellId: string) => {
|
||||
if (e.key === 'Tab') {
|
||||
e.preventDefault()
|
||||
const idx = sortedCellIds.indexOf(cellId)
|
||||
const nextIdx = e.shiftKey ? idx - 1 : idx + 1
|
||||
if (nextIdx >= 0 && nextIdx < sortedCellIds.length) {
|
||||
const nextId = sortedCellIds[nextIdx]
|
||||
const el = document.getElementById(`cell-${nextId}`)
|
||||
el?.focus()
|
||||
}
|
||||
}
|
||||
}, [sortedCellIds])
|
||||
|
||||
const saveReconstruction = useCallback(async () => {
|
||||
if (!sessionId) return
|
||||
setStatus('saving')
|
||||
try {
|
||||
const cellUpdates = Array.from(editedTexts.entries())
|
||||
.filter(([cellId, text]) => {
|
||||
const cell = cells.find(c => c.cellId === cellId)
|
||||
return cell && text !== cell.originalText
|
||||
})
|
||||
.map(([cellId, text]) => ({ cell_id: cellId, text }))
|
||||
|
||||
if (cellUpdates.length === 0) {
|
||||
setStatus('saved')
|
||||
return
|
||||
}
|
||||
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/reconstruction`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ cells: cellUpdates }),
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}))
|
||||
throw new Error(data.detail || `HTTP ${res.status}`)
|
||||
}
|
||||
|
||||
setStatus('saved')
|
||||
} catch (e: unknown) {
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
setStatus('error')
|
||||
}
|
||||
}, [sessionId, editedTexts, cells])
|
||||
|
||||
const dewarpedUrl = sessionId
|
||||
? `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
: ''
|
||||
|
||||
// Compute median cell height (in px) for consistent font sizing
|
||||
// Must be before early returns (Rules of Hooks)
|
||||
const medianCellHeightPx = useMemo(() => {
|
||||
const imgWVal = imageNaturalSize?.w || 1
|
||||
const imgHVal = imageNaturalSize?.h || 1
|
||||
const cH = reconWidth * (imgHVal / imgWVal)
|
||||
if (cells.length === 0 || cH === 0) return 40
|
||||
const heights = cells.map(c => cH * (c.bboxPct.h / 100)).sort((a, b) => a - b)
|
||||
const mid = Math.floor(heights.length / 2)
|
||||
return heights.length % 2 === 0 ? (heights[mid - 1] + heights[mid]) / 2 : heights[mid]
|
||||
}, [cells, reconWidth, imageNaturalSize])
|
||||
|
||||
if (!sessionId) {
|
||||
return <div className="text-center py-12 text-gray-400">Bitte zuerst eine Session auswaehlen.</div>
|
||||
}
|
||||
|
||||
if (status === 'loading') {
|
||||
return (
|
||||
<div className="flex items-center gap-3 justify-center py-12">
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-teal-500" />
|
||||
<span className="text-gray-500">Overlay-Daten werden geladen...</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (status === 'error') {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<div className="text-5xl mb-4">⚠️</div>
|
||||
<h3 className="text-lg font-medium text-red-600 dark:text-red-400 mb-2">Fehler</h3>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 max-w-lg mb-4">{error}</p>
|
||||
<div className="flex gap-3">
|
||||
<button onClick={() => { setError(''); loadSessionData() }}
|
||||
className="px-5 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors text-sm">
|
||||
Erneut versuchen
|
||||
</button>
|
||||
<button onClick={onNext}
|
||||
className="px-5 py-2 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors text-sm">
|
||||
Ueberspringen →
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (status === 'saved') {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<div className="text-5xl mb-4">✅</div>
|
||||
<h3 className="text-lg font-medium text-gray-700 dark:text-gray-300 mb-2">Overlay gespeichert</h3>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
|
||||
{changedCount > 0 ? `${changedCount} Zellen wurden aktualisiert.` : 'Keine Aenderungen vorgenommen.'}
|
||||
</p>
|
||||
<button onClick={onNext}
|
||||
className="px-6 py-2.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors font-medium">
|
||||
Fertig
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const imgW = imageNaturalSize?.w || 1
|
||||
const imgH = imageNaturalSize?.h || 1
|
||||
const containerH = reconWidth * (imgH / imgW)
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Toolbar */}
|
||||
<div className="flex items-center justify-between bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
Overlay-Rekonstruktion
|
||||
</h3>
|
||||
<span className="text-xs text-gray-400">
|
||||
{cells.length} Zellen · {changedCount} geaendert
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Undo/Redo */}
|
||||
<button
|
||||
onClick={undo}
|
||||
disabled={undoStack.length === 0}
|
||||
className="px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-30"
|
||||
title="Rueckgaengig (Ctrl+Z)"
|
||||
>
|
||||
↩
|
||||
</button>
|
||||
<button
|
||||
onClick={redo}
|
||||
disabled={redoStack.length === 0}
|
||||
className="px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-30"
|
||||
title="Wiederholen (Ctrl+Shift+Z)"
|
||||
>
|
||||
↪
|
||||
</button>
|
||||
|
||||
<div className="w-px h-5 bg-gray-300 dark:bg-gray-600 mx-1" />
|
||||
|
||||
{/* Font scale */}
|
||||
<label className="flex items-center gap-1 text-xs text-gray-600 dark:text-gray-400">
|
||||
Schrift
|
||||
<input
|
||||
type="range" min={30} max={120} value={Math.round(fontScale * 100)}
|
||||
onChange={e => setFontScale(Number(e.target.value) / 100)}
|
||||
className="w-20 h-1 accent-teal-600"
|
||||
/>
|
||||
<span className="w-8 text-right font-mono">{Math.round(fontScale * 100)}%</span>
|
||||
</label>
|
||||
<button
|
||||
onClick={() => setGlobalBold(b => !b)}
|
||||
className={`px-2 py-1 text-xs rounded border transition-colors font-bold ${
|
||||
globalBold
|
||||
? 'bg-teal-600 text-white border-teal-600'
|
||||
: 'bg-white dark:bg-gray-700 text-gray-600 dark:text-gray-400 border-gray-300 dark:border-gray-600'
|
||||
}`}
|
||||
>
|
||||
B
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setImageRotation(r => r === 0 ? 180 : 0)}
|
||||
className={`px-2 py-1 text-xs rounded border transition-colors ${
|
||||
imageRotation === 180
|
||||
? 'bg-teal-600 text-white border-teal-600'
|
||||
: 'bg-white dark:bg-gray-700 text-gray-600 dark:text-gray-400 border-gray-300 dark:border-gray-600'
|
||||
}`}
|
||||
title="Bild 180° drehen"
|
||||
>
|
||||
180°
|
||||
</button>
|
||||
|
||||
<div className="w-px h-5 bg-gray-300 dark:bg-gray-600 mx-1" />
|
||||
|
||||
{/* Positioning mode toggle */}
|
||||
<button
|
||||
onClick={() => setPositioningMode(m => m === 'slide' ? 'cluster' : 'slide')}
|
||||
className={`px-2 py-1 text-xs rounded border transition-colors ${
|
||||
positioningMode === 'slide'
|
||||
? 'bg-orange-500 text-white border-orange-500'
|
||||
: 'bg-white dark:bg-gray-700 text-gray-600 dark:text-gray-400 border-gray-300 dark:border-gray-600'
|
||||
}`}
|
||||
title={positioningMode === 'slide'
|
||||
? 'Slide-Modus: Woerter von links nach rechts schieben (klick fuer Cluster-Modus)'
|
||||
: 'Cluster-Modus: Woerter an Pixel-Cluster zuordnen (klick fuer Slide-Modus)'}
|
||||
>
|
||||
{positioningMode === 'slide' ? 'Slide' : 'Cluster'}
|
||||
</button>
|
||||
|
||||
<div className="w-px h-5 bg-gray-300 dark:bg-gray-600 mx-1" />
|
||||
|
||||
{/* Text color */}
|
||||
{(['red', 'blue', 'black'] as const).map(c => (
|
||||
<button
|
||||
key={c}
|
||||
onClick={() => setTextColor(c)}
|
||||
className={`w-5 h-5 rounded-full border-2 transition-colors ${
|
||||
textColor === c ? 'border-teal-500 ring-1 ring-teal-300' : 'border-gray-300 dark:border-gray-600'
|
||||
}`}
|
||||
style={{ backgroundColor: c === 'black' ? '#1a1a1a' : c }}
|
||||
title={`Textfarbe: ${c}`}
|
||||
/>
|
||||
))}
|
||||
|
||||
<div className="w-px h-5 bg-gray-300 dark:bg-gray-600 mx-1" />
|
||||
|
||||
{/* Text opacity */}
|
||||
<label className="flex items-center gap-1 text-xs text-gray-600 dark:text-gray-400">
|
||||
Text
|
||||
<input
|
||||
type="range" min={0} max={100} value={textOpacity}
|
||||
onChange={e => setTextOpacity(Number(e.target.value))}
|
||||
className="w-16 h-1 accent-teal-600"
|
||||
/>
|
||||
<span className="w-8 text-right font-mono">{textOpacity}%</span>
|
||||
</label>
|
||||
|
||||
<div className="w-px h-5 bg-gray-300 dark:bg-gray-600 mx-1" />
|
||||
|
||||
<button
|
||||
onClick={saveReconstruction}
|
||||
disabled={status === 'saving'}
|
||||
className="px-4 py-1.5 text-xs bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50 transition-colors font-medium"
|
||||
>
|
||||
Speichern
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* True overlay: text layer on top of original image */}
|
||||
<div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden bg-gray-50 dark:bg-gray-900">
|
||||
<div
|
||||
ref={reconRef}
|
||||
className="relative"
|
||||
style={{ aspectRatio: `${imgW} / ${imgH}` }}
|
||||
>
|
||||
{/* Background: original image */}
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={dewarpedUrl}
|
||||
alt="Original"
|
||||
className="absolute inset-0 w-full h-full object-contain"
|
||||
onLoad={(e) => {
|
||||
const img = e.target as HTMLImageElement
|
||||
setImageNaturalSize({ w: img.naturalWidth, h: img.naturalHeight })
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Text overlay layer */}
|
||||
<div
|
||||
className="absolute inset-0"
|
||||
style={{ opacity: textOpacity / 100 }}
|
||||
>
|
||||
{/* Row lines */}
|
||||
{rows.map((row, i) => (
|
||||
<div
|
||||
key={`row-${i}`}
|
||||
className="absolute left-0 right-0 border-t border-cyan-400/40"
|
||||
style={{ top: `${(row.y / imgH) * 100}%` }}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Pixel-positioned words / editable inputs */}
|
||||
{cells.map((cell) => {
|
||||
const displayText = getDisplayText(cell)
|
||||
const edited = isEdited(cell)
|
||||
const wordPos = cellWordPositions.get(cell.cellId)
|
||||
const bboxPct = cell.bboxPct
|
||||
const colorValue = textColor === 'black' ? '#1a1a1a' : textColor
|
||||
|
||||
// Pixel-analysed: render word-groups at detected positions
|
||||
if (wordPos && wordPos.length > 0) {
|
||||
return wordPos.map((wp, i) => {
|
||||
const autoFontPx = medianCellHeightPx * wp.fontRatio * fontScale
|
||||
const fs = Math.max(6, autoFontPx)
|
||||
|
||||
if (wordPos.length > 1) {
|
||||
return (
|
||||
<span
|
||||
key={`${cell.cellId}_wp_${i}`}
|
||||
className="absolute leading-none pointer-events-none select-none"
|
||||
style={{
|
||||
left: `${wp.xPct}%`,
|
||||
top: `${wp.yPct}%`,
|
||||
width: `${wp.wPct}%`,
|
||||
height: `${wp.hPct}%`,
|
||||
fontSize: `${fs}px`,
|
||||
fontWeight: globalBold ? 'bold' : 'normal',
|
||||
fontFamily: "'Liberation Sans', Arial, sans-serif",
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'visible',
|
||||
color: colorValue,
|
||||
}}
|
||||
>
|
||||
{wp.text}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={`${cell.cellId}_wp_${i}`} className="absolute group" style={{
|
||||
left: `${wp.xPct}%`,
|
||||
top: `${wp.yPct}%`,
|
||||
width: `${wp.wPct}%`,
|
||||
height: `${wp.hPct}%`,
|
||||
}}>
|
||||
<input
|
||||
id={`cell-${cell.cellId}`}
|
||||
type="text"
|
||||
value={displayText}
|
||||
onChange={(e) => handleTextChange(cell.cellId, e.target.value)}
|
||||
onKeyDown={(e) => handleKeyDown(e, cell.cellId)}
|
||||
className={`w-full h-full bg-transparent border-0 outline-none px-0 transition-colors ${
|
||||
edited ? 'bg-green-50/30' : ''
|
||||
}`}
|
||||
style={{
|
||||
fontSize: `${fs}px`,
|
||||
fontWeight: globalBold ? 'bold' : 'normal',
|
||||
fontFamily: "'Liberation Sans', Arial, sans-serif",
|
||||
lineHeight: '1',
|
||||
color: colorValue,
|
||||
}}
|
||||
title={`${cell.cellId} (${cell.colType})`}
|
||||
/>
|
||||
{edited && (
|
||||
<button
|
||||
onClick={() => resetCell(cell.cellId)}
|
||||
className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 text-white rounded-full text-[9px] leading-none opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
|
||||
title="Zuruecksetzen"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// Fallback: no pixel data — single input at cell bbox
|
||||
if (!cell.text) return null
|
||||
|
||||
const fontSize = Math.max(6, medianCellHeightPx * fontScale)
|
||||
return (
|
||||
<div key={cell.cellId} className="absolute group" style={{
|
||||
left: `${bboxPct.x}%`,
|
||||
top: `${bboxPct.y}%`,
|
||||
width: `${bboxPct.w}%`,
|
||||
height: `${bboxPct.h}%`,
|
||||
}}>
|
||||
<input
|
||||
id={`cell-${cell.cellId}`}
|
||||
type="text"
|
||||
value={displayText}
|
||||
onChange={(e) => handleTextChange(cell.cellId, e.target.value)}
|
||||
onKeyDown={(e) => handleKeyDown(e, cell.cellId)}
|
||||
className={`w-full h-full bg-transparent border-0 outline-none px-0 transition-colors ${
|
||||
edited ? 'bg-green-50/30' : ''
|
||||
}`}
|
||||
style={{
|
||||
fontSize: `${fontSize}px`,
|
||||
fontWeight: globalBold ? 'bold' : 'normal',
|
||||
fontFamily: "'Liberation Sans', Arial, sans-serif",
|
||||
lineHeight: '1',
|
||||
color: colorValue,
|
||||
}}
|
||||
title={`${cell.cellId} (${cell.colType})`}
|
||||
/>
|
||||
{edited && (
|
||||
<button
|
||||
onClick={() => resetCell(cell.cellId)}
|
||||
className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 text-white rounded-full text-[9px] leading-none opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
|
||||
title="Zuruecksetzen"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bottom action */}
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
onClick={() => {
|
||||
if (changedCount > 0) {
|
||||
saveReconstruction()
|
||||
} else {
|
||||
onNext()
|
||||
}
|
||||
}}
|
||||
className="px-6 py-2.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors font-medium text-sm"
|
||||
>
|
||||
{changedCount > 0 ? 'Speichern & Fertig' : 'Fertig'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
153
admin-lehrer/components/ocr-overlay/PaddleDirectStep.tsx
Normal file
153
admin-lehrer/components/ocr-overlay/PaddleDirectStep.tsx
Normal file
@@ -0,0 +1,153 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { OverlayReconstruction } from './OverlayReconstruction'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
type Phase = 'idle' | 'running' | 'overlay'
|
||||
|
||||
interface PaddleDirectStepProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
/** Backend endpoint suffix, default: 'paddle-direct' */
|
||||
endpoint?: string
|
||||
/** Title shown in idle state */
|
||||
title?: string
|
||||
/** Description shown in idle state */
|
||||
description?: string
|
||||
/** Icon shown in idle state */
|
||||
icon?: string
|
||||
/** Button label */
|
||||
buttonLabel?: string
|
||||
/** Running label */
|
||||
runningLabel?: string
|
||||
/** OCR engine key to check for auto-detect */
|
||||
engineKey?: string
|
||||
}
|
||||
|
||||
export function PaddleDirectStep({
|
||||
sessionId,
|
||||
onNext,
|
||||
endpoint = 'paddle-direct',
|
||||
title = 'PP-OCRv5 Direct',
|
||||
description = 'PP-OCRv5 (lokal via RapidOCR) erkennt alle Woerter direkt auf dem Originalbild — ohne Begradigung, Entzerrung oder Zuschnitt.',
|
||||
icon = '⚡',
|
||||
buttonLabel = 'PP-OCRv5 starten',
|
||||
runningLabel = 'PP-OCRv5 laeuft...',
|
||||
engineKey = 'paddle_direct',
|
||||
}: PaddleDirectStepProps) {
|
||||
const [phase, setPhase] = useState<Phase>('idle')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [stats, setStats] = useState<{ cells: number; rows: number; duration: number } | null>(null)
|
||||
|
||||
// Auto-detect: if session already has matching word_result → show overlay
|
||||
useEffect(() => {
|
||||
if (!sessionId) return
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}`)
|
||||
if (!res.ok || cancelled) return
|
||||
const data = await res.json()
|
||||
if (data.word_result?.ocr_engine === engineKey) {
|
||||
setPhase('overlay')
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
})()
|
||||
return () => { cancelled = true }
|
||||
}, [sessionId, engineKey])
|
||||
|
||||
const runOcr = useCallback(async () => {
|
||||
if (!sessionId) return
|
||||
setPhase('running')
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/${endpoint}`, {
|
||||
method: 'POST',
|
||||
})
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}))
|
||||
throw new Error(data.detail || `HTTP ${res.status}`)
|
||||
}
|
||||
const data = await res.json()
|
||||
setStats({
|
||||
cells: data.summary?.total_cells || 0,
|
||||
rows: data.grid_shape?.rows || 0,
|
||||
duration: data.duration_seconds || 0,
|
||||
})
|
||||
setPhase('overlay')
|
||||
} catch (e: unknown) {
|
||||
setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
|
||||
setPhase('idle')
|
||||
}
|
||||
}, [sessionId, endpoint])
|
||||
|
||||
if (!sessionId) {
|
||||
return (
|
||||
<div className="text-sm text-gray-400 py-8 text-center">
|
||||
Bitte zuerst ein Bild hochladen.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (phase === 'overlay') {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{stats && (
|
||||
<div className="flex items-center gap-4 text-xs text-gray-500 dark:text-gray-400">
|
||||
<span>{stats.cells} Woerter erkannt</span>
|
||||
<span>{stats.rows} Zeilen</span>
|
||||
<span>{stats.duration.toFixed(1)}s</span>
|
||||
</div>
|
||||
)}
|
||||
<OverlayReconstruction sessionId={sessionId} onNext={onNext} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-16 space-y-6">
|
||||
{phase === 'running' ? (
|
||||
<>
|
||||
<div className="w-10 h-10 border-4 border-teal-200 dark:border-teal-800 border-t-teal-600 dark:border-t-teal-400 rounded-full animate-spin" />
|
||||
<div className="text-center space-y-1">
|
||||
<p className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
{runningLabel}
|
||||
</p>
|
||||
<p className="text-xs text-gray-400">
|
||||
Bild wird analysiert (ca. 5-30s)
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-center space-y-2">
|
||||
<div className="text-4xl">{icon}</div>
|
||||
<h3 className="text-lg font-medium text-gray-700 dark:text-gray-300">
|
||||
{title}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 max-w-md">
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="text-sm text-red-500 bg-red-50 dark:bg-red-900/20 px-4 py-2 rounded-lg">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={runOcr}
|
||||
className="px-6 py-2.5 bg-teal-600 text-white text-sm font-medium rounded-lg hover:bg-teal-700 transition-colors"
|
||||
>
|
||||
{buttonLabel}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
253
admin-lehrer/components/ocr-overlay/usePixelWordPositions.ts
Normal file
253
admin-lehrer/components/ocr-overlay/usePixelWordPositions.ts
Normal file
@@ -0,0 +1,253 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { GridCell } from '@/app/(admin)/ai/ocr-overlay/types'
|
||||
|
||||
export interface WordPosition {
|
||||
xPct: number
|
||||
wPct: number
|
||||
yPct: number
|
||||
hPct: number
|
||||
text: string
|
||||
fontRatio: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyse dark-pixel clusters on an image to determine
|
||||
* the exact horizontal position & auto-font-size of word groups in each cell.
|
||||
*
|
||||
* When rotation=180, the image is rotated 180° before pixel analysis.
|
||||
* Cell coordinates are transformed to the rotated space for reading,
|
||||
* and cluster positions are mirrored back to the original coordinate system.
|
||||
*
|
||||
* Returns a Map<cell_id, WordPosition[]>.
|
||||
*/
|
||||
export function usePixelWordPositions(
|
||||
imageUrl: string,
|
||||
cells: GridCell[],
|
||||
active: boolean,
|
||||
rotation: 0 | 180 = 0,
|
||||
): Map<string, WordPosition[]> {
|
||||
const [cellWordPositions, setCellWordPositions] = useState<Map<string, WordPosition[]>>(new Map())
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || cells.length === 0 || !imageUrl) return
|
||||
|
||||
const img = new Image()
|
||||
img.crossOrigin = 'anonymous'
|
||||
img.onload = () => {
|
||||
const imgW = img.naturalWidth
|
||||
const imgH = img.naturalHeight
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = imgW
|
||||
canvas.height = imgH
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) return
|
||||
|
||||
if (rotation === 180) {
|
||||
ctx.translate(imgW, imgH)
|
||||
ctx.rotate(Math.PI)
|
||||
ctx.drawImage(img, 0, 0)
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0)
|
||||
} else {
|
||||
ctx.drawImage(img, 0, 0)
|
||||
}
|
||||
|
||||
const refFontSize = 40
|
||||
const fontFam = "'Liberation Sans', Arial, sans-serif"
|
||||
ctx.font = `${refFontSize}px ${fontFam}`
|
||||
|
||||
const positions = new Map<string, WordPosition[]>()
|
||||
|
||||
for (const cell of cells) {
|
||||
if (!cell.bbox_pct || !cell.text) continue
|
||||
|
||||
const rawGroups = cell.text.split(/\s{3,}/).map(s => s.trim()).filter(Boolean)
|
||||
|
||||
// Merge single-char symbol groups (OCR artifacts from box borders like "|", ">")
|
||||
// with their neighbour to avoid polluting the cluster-to-group matching
|
||||
const groups: string[] = []
|
||||
for (let gi = 0; gi < rawGroups.length; gi++) {
|
||||
const g = rawGroups[gi]
|
||||
const isArtifact = g.length <= 2 && !/[a-zA-Z0-9\u00C0-\u024F]/.test(g)
|
||||
if (isArtifact) {
|
||||
if (gi + 1 < rawGroups.length) {
|
||||
// merge with next group
|
||||
rawGroups[gi + 1] = g + ' ' + rawGroups[gi + 1]
|
||||
} else if (groups.length > 0) {
|
||||
// last group — merge with previous
|
||||
groups[groups.length - 1] += ' ' + g
|
||||
} else {
|
||||
groups.push(g)
|
||||
}
|
||||
} else {
|
||||
groups.push(g)
|
||||
}
|
||||
}
|
||||
|
||||
let cx: number, cy: number
|
||||
const cw = Math.round(cell.bbox_pct.w / 100 * imgW)
|
||||
const ch = Math.round(cell.bbox_pct.h / 100 * imgH)
|
||||
|
||||
if (rotation === 180) {
|
||||
cx = Math.round((100 - cell.bbox_pct.x - cell.bbox_pct.w) / 100 * imgW)
|
||||
cy = Math.round((100 - cell.bbox_pct.y - cell.bbox_pct.h) / 100 * imgH)
|
||||
} else {
|
||||
cx = Math.round(cell.bbox_pct.x / 100 * imgW)
|
||||
cy = Math.round(cell.bbox_pct.y / 100 * imgH)
|
||||
}
|
||||
if (cw <= 0 || ch <= 0) continue
|
||||
if (cx < 0) cx = 0
|
||||
if (cy < 0) cy = 0
|
||||
if (cx + cw > imgW || cy + ch > imgH) continue
|
||||
|
||||
const imageData = ctx.getImageData(cx, cy, cw, ch)
|
||||
|
||||
const proj = new Float32Array(cw)
|
||||
for (let y = 0; y < ch; y++) {
|
||||
for (let x = 0; x < cw; x++) {
|
||||
const idx = (y * cw + x) * 4
|
||||
const lum = 0.299 * imageData.data[idx] + 0.587 * imageData.data[idx + 1] + 0.114 * imageData.data[idx + 2]
|
||||
if (lum < 128) proj[x]++
|
||||
}
|
||||
}
|
||||
|
||||
const threshold = Math.max(1, ch * 0.03)
|
||||
const minGap = Math.max(5, Math.round(cw * 0.02))
|
||||
let clusters: { start: number; end: number }[] = []
|
||||
let inCluster = false
|
||||
let clStart = 0
|
||||
let gap = 0
|
||||
|
||||
for (let x = 0; x < cw; x++) {
|
||||
if (proj[x] >= threshold) {
|
||||
if (!inCluster) { clStart = x; inCluster = true }
|
||||
gap = 0
|
||||
} else if (inCluster) {
|
||||
gap++
|
||||
if (gap > minGap) {
|
||||
clusters.push({ start: clStart, end: x - gap })
|
||||
inCluster = false
|
||||
gap = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
if (inCluster) clusters.push({ start: clStart, end: cw - 1 - gap })
|
||||
|
||||
if (clusters.length === 0) continue
|
||||
|
||||
// Filter out very narrow clusters (likely box borders / vertical lines)
|
||||
const minClusterW = Math.max(3, Math.round(cw * 0.005))
|
||||
clusters = clusters.filter(c => (c.end - c.start + 1) > minClusterW)
|
||||
if (clusters.length === 0) continue
|
||||
|
||||
if (rotation === 180) {
|
||||
clusters = clusters.map(c => ({
|
||||
start: cw - 1 - c.end,
|
||||
end: cw - 1 - c.start,
|
||||
})).reverse()
|
||||
}
|
||||
|
||||
const wordPos: WordPosition[] = []
|
||||
|
||||
// Match groups to clusters using width-proportional assignment.
|
||||
// Each group is assigned to the cluster whose width best matches
|
||||
// the group's expected pixel width (text measurement).
|
||||
if (groups.length > 1 && clusters.length >= groups.length) {
|
||||
// Measure each group's expected width
|
||||
const groupWidths = groups.map(g => ctx.measureText(g).width)
|
||||
|
||||
// Greedy assignment: for each group (in order), find the best
|
||||
// unassigned cluster by width ratio consistency
|
||||
const totalMeasured = groupWidths.reduce((a, b) => a + b, 0)
|
||||
const totalClusterW = clusters.reduce((a, c) => a + (c.end - c.start + 1), 0)
|
||||
const refScale = totalClusterW / totalMeasured
|
||||
const used = new Set<number>()
|
||||
|
||||
const assignments: number[] = []
|
||||
for (let gi = 0; gi < groups.length; gi++) {
|
||||
const expectedW = groupWidths[gi] * refScale
|
||||
let bestIdx = -1
|
||||
let bestDiff = Infinity
|
||||
for (let ci = 0; ci < clusters.length; ci++) {
|
||||
if (used.has(ci)) continue
|
||||
const clW = clusters[ci].end - clusters[ci].start + 1
|
||||
const diff = Math.abs(clW - expectedW)
|
||||
if (diff < bestDiff) {
|
||||
bestDiff = diff
|
||||
bestIdx = ci
|
||||
}
|
||||
}
|
||||
used.add(bestIdx)
|
||||
assignments.push(bestIdx)
|
||||
}
|
||||
|
||||
// Sort assignments to maintain left-to-right order
|
||||
const sortedPairs = assignments
|
||||
.map((ci, gi) => ({ ci, gi }))
|
||||
.sort((a, b) => clusters[a.ci].start - clusters[b.ci].start)
|
||||
|
||||
for (const { ci, gi } of sortedPairs) {
|
||||
const cl = clusters[ci]
|
||||
const clusterW = cl.end - cl.start + 1
|
||||
const autoFontPx = refFontSize * (clusterW / groupWidths[gi])
|
||||
const fontRatio = Math.min(autoFontPx / ch, 1.0)
|
||||
wordPos.push({
|
||||
xPct: cell.bbox_pct.x + (cl.start / cw) * cell.bbox_pct.w,
|
||||
wPct: ((cl.end - cl.start + 1) / cw) * cell.bbox_pct.w,
|
||||
yPct: cell.bbox_pct.y,
|
||||
hPct: cell.bbox_pct.h,
|
||||
text: groups[gi],
|
||||
fontRatio,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Single group OR not enough clusters:
|
||||
// use the WIDEST cluster (not first-to-last span which pulls in
|
||||
// stray pixels from adjacent page areas like box borders)
|
||||
const widest = clusters.reduce((best, c) =>
|
||||
(c.end - c.start) > (best.end - best.start) ? c : best, clusters[0])
|
||||
const clusterW = widest.end - widest.start + 1
|
||||
const measured = ctx.measureText(cell.text.trim())
|
||||
const autoFontPx = refFontSize * (clusterW / measured.width)
|
||||
const fontRatio = Math.min(autoFontPx / ch, 1.0)
|
||||
wordPos.push({
|
||||
xPct: cell.bbox_pct.x + (widest.start / cw) * cell.bbox_pct.w,
|
||||
wPct: ((widest.end - widest.start + 1) / cw) * cell.bbox_pct.w,
|
||||
yPct: cell.bbox_pct.y,
|
||||
hPct: cell.bbox_pct.h,
|
||||
text: cell.text.trim(),
|
||||
fontRatio,
|
||||
})
|
||||
}
|
||||
|
||||
positions.set(cell.cell_id, wordPos)
|
||||
}
|
||||
|
||||
// Normalise: find the most common fontRatio (mode) and apply it to all
|
||||
const allRatios: number[] = []
|
||||
for (const wps of positions.values()) {
|
||||
for (const wp of wps) allRatios.push(wp.fontRatio)
|
||||
}
|
||||
if (allRatios.length > 0) {
|
||||
const buckets = new Map<number, number>()
|
||||
for (const r of allRatios) {
|
||||
const key = Math.round(r * 50) / 50
|
||||
buckets.set(key, (buckets.get(key) || 0) + 1)
|
||||
}
|
||||
let modeRatio = allRatios[0]
|
||||
let modeCount = 0
|
||||
for (const [ratio, count] of buckets) {
|
||||
if (count > modeCount) { modeRatio = ratio; modeCount = count }
|
||||
}
|
||||
for (const wps of positions.values()) {
|
||||
for (const wp of wps) wp.fontRatio = modeRatio
|
||||
}
|
||||
}
|
||||
|
||||
setCellWordPositions(positions)
|
||||
}
|
||||
img.src = imageUrl
|
||||
}, [active, cells, imageUrl, rotation])
|
||||
|
||||
return cellWordPositions
|
||||
}
|
||||
231
admin-lehrer/components/ocr-overlay/useSlideWordPositions.ts
Normal file
231
admin-lehrer/components/ocr-overlay/useSlideWordPositions.ts
Normal file
@@ -0,0 +1,231 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { GridCell } from '@/app/(admin)/ai/ocr-overlay/types'
|
||||
|
||||
export interface WordPosition {
|
||||
xPct: number
|
||||
wPct: number
|
||||
yPct: number
|
||||
hPct: number
|
||||
text: string
|
||||
fontRatio: number
|
||||
}
|
||||
|
||||
/**
|
||||
* "Slide from left" positioning using OCR word bounding boxes.
|
||||
*
|
||||
* TEXT comes from cell.text (cleaned, IPA-corrected).
|
||||
* POSITIONS come from word_boxes (exact OCR coordinates).
|
||||
*
|
||||
* Tokens from cell.text are matched 1:1 (in order) to word_boxes
|
||||
* sorted left-to-right. This guarantees:
|
||||
* - ALL words from cell.text appear (no dropping)
|
||||
* - Words preserve their reading order
|
||||
* - Each word lands on its correct black-text position
|
||||
* - No red words overlap each other
|
||||
*
|
||||
* If token count != box count, extra tokens get estimated positions
|
||||
* (spread across remaining space).
|
||||
*
|
||||
* Fallback: pixel-projection slide if no word_boxes available.
|
||||
*/
|
||||
export function useSlideWordPositions(
|
||||
imageUrl: string,
|
||||
cells: GridCell[],
|
||||
active: boolean,
|
||||
rotation: 0 | 180 = 0,
|
||||
): Map<string, WordPosition[]> {
|
||||
const [result, setResult] = useState<Map<string, WordPosition[]>>(new Map())
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || cells.length === 0 || !imageUrl) return
|
||||
|
||||
const img = new Image()
|
||||
img.crossOrigin = 'anonymous'
|
||||
img.onload = () => {
|
||||
const imgW = img.naturalWidth
|
||||
const imgH = img.naturalHeight
|
||||
|
||||
const hasWordBoxes = cells.some(c => c.word_boxes && c.word_boxes.length > 0)
|
||||
|
||||
if (hasWordBoxes) {
|
||||
// --- WORD-BOX PATH: use OCR positions directly ---
|
||||
// Each word_box already has exact coordinates from OCR.
|
||||
// Use them as-is — no fuzzy matching needed.
|
||||
const positions = new Map<string, WordPosition[]>()
|
||||
|
||||
for (const cell of cells) {
|
||||
if (!cell.bbox_pct || !cell.text) continue
|
||||
|
||||
const boxes = (cell.word_boxes || [])
|
||||
.filter(wb => wb.text.trim())
|
||||
.sort((a, b) => a.left - b.left)
|
||||
|
||||
if (boxes.length === 0) {
|
||||
// No word_boxes — spread tokens evenly across cell
|
||||
const tokens = cell.text.split(/\s+/).filter(Boolean)
|
||||
if (tokens.length === 0) continue
|
||||
const fallbackW = cell.bbox_pct.w / tokens.length
|
||||
const wordPos = tokens.map((t, i) => ({
|
||||
xPct: cell.bbox_pct.x + i * fallbackW,
|
||||
wPct: fallbackW,
|
||||
yPct: cell.bbox_pct.y,
|
||||
hPct: cell.bbox_pct.h,
|
||||
text: t,
|
||||
fontRatio: 1.0,
|
||||
}))
|
||||
positions.set(cell.cell_id, wordPos)
|
||||
continue
|
||||
}
|
||||
|
||||
// Use each word_box directly with its OCR coordinates
|
||||
const wordPos: WordPosition[] = boxes.map(box => ({
|
||||
xPct: (box.left / imgW) * 100,
|
||||
wPct: (box.width / imgW) * 100,
|
||||
yPct: (box.top / imgH) * 100,
|
||||
hPct: (box.height / imgH) * 100,
|
||||
text: box.text,
|
||||
fontRatio: 1.0,
|
||||
}))
|
||||
|
||||
if (wordPos.length > 0) {
|
||||
positions.set(cell.cell_id, wordPos)
|
||||
}
|
||||
}
|
||||
|
||||
setResult(positions)
|
||||
return
|
||||
}
|
||||
|
||||
// --- FALLBACK: pixel-projection slide (no word_boxes) ---
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = imgW
|
||||
canvas.height = imgH
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) return
|
||||
|
||||
if (rotation === 180) {
|
||||
ctx.translate(imgW, imgH)
|
||||
ctx.rotate(Math.PI)
|
||||
ctx.drawImage(img, 0, 0)
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0)
|
||||
} else {
|
||||
ctx.drawImage(img, 0, 0)
|
||||
}
|
||||
|
||||
const refFontSize = 40
|
||||
const fontFam = "'Liberation Sans', Arial, sans-serif"
|
||||
ctx.font = `${refFontSize}px ${fontFam}`
|
||||
|
||||
const cellHeights = cells
|
||||
.filter(c => c.bbox_pct && c.bbox_pct.h > 0)
|
||||
.map(c => Math.round(c.bbox_pct.h / 100 * imgH))
|
||||
.sort((a, b) => a - b)
|
||||
const medianCh = cellHeights.length > 0
|
||||
? cellHeights[Math.floor(cellHeights.length / 2)]
|
||||
: 30
|
||||
|
||||
const renderedFontImgPx = medianCh * 0.7
|
||||
const measureScale = renderedFontImgPx / refFontSize
|
||||
const spaceWidthPx = Math.max(2, Math.round(ctx.measureText(' ').width * measureScale))
|
||||
|
||||
const positions = new Map<string, WordPosition[]>()
|
||||
|
||||
for (const cell of cells) {
|
||||
if (!cell.bbox_pct || !cell.text) continue
|
||||
|
||||
let cx: number, cy: number
|
||||
const cw = Math.round(cell.bbox_pct.w / 100 * imgW)
|
||||
const ch = Math.round(cell.bbox_pct.h / 100 * imgH)
|
||||
|
||||
if (rotation === 180) {
|
||||
cx = Math.round((100 - cell.bbox_pct.x - cell.bbox_pct.w) / 100 * imgW)
|
||||
cy = Math.round((100 - cell.bbox_pct.y - cell.bbox_pct.h) / 100 * imgH)
|
||||
} else {
|
||||
cx = Math.round(cell.bbox_pct.x / 100 * imgW)
|
||||
cy = Math.round(cell.bbox_pct.y / 100 * imgH)
|
||||
}
|
||||
if (cw <= 0 || ch <= 0) continue
|
||||
if (cx < 0) cx = 0
|
||||
if (cy < 0) cy = 0
|
||||
if (cx + cw > imgW || cy + ch > imgH) continue
|
||||
|
||||
const imageData = ctx.getImageData(cx, cy, cw, ch)
|
||||
const proj = new Float32Array(cw)
|
||||
for (let y = 0; y < ch; y++) {
|
||||
for (let x = 0; x < cw; x++) {
|
||||
const idx = (y * cw + x) * 4
|
||||
const lum = 0.299 * imageData.data[idx] + 0.587 * imageData.data[idx + 1] + 0.114 * imageData.data[idx + 2]
|
||||
if (lum < 128) proj[x]++
|
||||
}
|
||||
}
|
||||
|
||||
const threshold = Math.max(1, ch * 0.03)
|
||||
const ink = new Uint8Array(cw)
|
||||
for (let x = 0; x < cw; x++) {
|
||||
ink[x] = proj[x] >= threshold ? 1 : 0
|
||||
}
|
||||
if (rotation === 180) {
|
||||
ink.reverse()
|
||||
}
|
||||
|
||||
const tokens = cell.text.split(/\s+/).filter(Boolean)
|
||||
if (tokens.length === 0) continue
|
||||
|
||||
const tokenWidthsPx = tokens.map(t =>
|
||||
Math.max(4, Math.round(ctx.measureText(t).width * measureScale))
|
||||
)
|
||||
|
||||
const wordPos: WordPosition[] = []
|
||||
let cursor = 0
|
||||
|
||||
for (let ti = 0; ti < tokens.length; ti++) {
|
||||
const tokenW = tokenWidthsPx[ti]
|
||||
const coverageNeeded = Math.max(1, Math.round(tokenW * 0.15))
|
||||
let bestX = cursor
|
||||
|
||||
const searchLimit = Math.max(cursor, cw - tokenW)
|
||||
|
||||
for (let x = cursor; x <= searchLimit; x++) {
|
||||
let inkCount = 0
|
||||
const spanEnd = Math.min(x + tokenW, cw)
|
||||
for (let dx = 0; dx < spanEnd - x; dx++) {
|
||||
inkCount += ink[x + dx]
|
||||
}
|
||||
if (inkCount >= coverageNeeded) {
|
||||
bestX = x
|
||||
break
|
||||
}
|
||||
if (x > cursor + cw * 0.3 && ti > 0) {
|
||||
bestX = cursor
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (bestX + tokenW > cw) {
|
||||
bestX = Math.max(0, cw - tokenW)
|
||||
}
|
||||
|
||||
wordPos.push({
|
||||
xPct: cell.bbox_pct.x + (bestX / cw) * cell.bbox_pct.w,
|
||||
wPct: (tokenW / cw) * cell.bbox_pct.w,
|
||||
yPct: cell.bbox_pct.y,
|
||||
hPct: cell.bbox_pct.h,
|
||||
text: tokens[ti],
|
||||
fontRatio: 1.0,
|
||||
})
|
||||
|
||||
cursor = bestX + tokenW + spaceWidthPx
|
||||
}
|
||||
|
||||
if (wordPos.length > 0) {
|
||||
positions.set(cell.cell_id, wordPos)
|
||||
}
|
||||
}
|
||||
|
||||
setResult(positions)
|
||||
}
|
||||
img.src = imageUrl
|
||||
}, [active, cells, imageUrl, rotation])
|
||||
|
||||
return result
|
||||
}
|
||||
67
admin-lehrer/components/ocr-pipeline/BoxSessionTabs.tsx
Normal file
67
admin-lehrer/components/ocr-pipeline/BoxSessionTabs.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
'use client'
|
||||
|
||||
import type { SubSession } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
interface BoxSessionTabsProps {
|
||||
parentSessionId: string
|
||||
subSessions: SubSession[]
|
||||
activeSessionId: string
|
||||
onSessionChange: (sessionId: string) => void
|
||||
}
|
||||
|
||||
const STATUS_ICONS: Record<string, string> = {
|
||||
pending: '\u23F3', // hourglass
|
||||
processing: '\uD83D\uDD04', // arrows
|
||||
completed: '\u2713', // checkmark
|
||||
}
|
||||
|
||||
function getStatusIcon(sub: SubSession): string {
|
||||
if (sub.status === 'completed' || (sub.current_step && sub.current_step >= 9)) return STATUS_ICONS.completed
|
||||
if (sub.current_step && sub.current_step > 1) return STATUS_ICONS.processing
|
||||
return STATUS_ICONS.pending
|
||||
}
|
||||
|
||||
/** Tabs for box sub-sessions (from column detection zone_type='box'). */
|
||||
export function BoxSessionTabs({ parentSessionId, subSessions, activeSessionId, onSessionChange }: BoxSessionTabsProps) {
|
||||
if (subSessions.length === 0) return null
|
||||
|
||||
const isParentActive = activeSessionId === parentSessionId
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 px-1 py-1.5 bg-gray-50 dark:bg-gray-800/50 rounded-xl border border-gray-200 dark:border-gray-700">
|
||||
<button
|
||||
onClick={() => onSessionChange(parentSessionId)}
|
||||
className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
|
||||
isParentActive
|
||||
? 'bg-white dark:bg-gray-700 text-teal-700 dark:text-teal-400 shadow-sm ring-1 ring-teal-300 dark:ring-teal-600'
|
||||
: 'text-gray-500 dark:text-gray-400 hover:bg-white/50 dark:hover:bg-gray-700/50'
|
||||
}`}
|
||||
>
|
||||
Hauptseite
|
||||
</button>
|
||||
|
||||
<div className="w-px h-5 bg-gray-200 dark:bg-gray-700" />
|
||||
|
||||
{subSessions.map((sub) => {
|
||||
const isActive = activeSessionId === sub.id
|
||||
const icon = getStatusIcon(sub)
|
||||
|
||||
return (
|
||||
<button
|
||||
key={sub.id}
|
||||
onClick={() => onSessionChange(sub.id)}
|
||||
className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
|
||||
isActive
|
||||
? 'bg-white dark:bg-gray-700 text-teal-700 dark:text-teal-400 shadow-sm ring-1 ring-teal-300 dark:ring-teal-600'
|
||||
: 'text-gray-500 dark:text-gray-400 hover:bg-white/50 dark:hover:bg-gray-700/50'
|
||||
}`}
|
||||
title={sub.name}
|
||||
>
|
||||
<span className="mr-1">{icon}</span>
|
||||
Box {sub.box_index + 1}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useMemo } from 'react'
|
||||
import type { ColumnResult, ColumnGroundTruth, PageRegion } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import type { ColumnResult, ColumnGroundTruth, PageRegion } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
interface ColumnControlsProps {
|
||||
columnResult: ColumnResult | null
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import type { DeskewResult, DeskewGroundTruth } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import type { DeskewResult, DeskewGroundTruth } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
interface DeskewControlsProps {
|
||||
deskewResult: DeskewResult | null
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { DewarpResult, DewarpDetection, DewarpGroundTruth } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import type { DeskewResult, DewarpResult, DewarpDetection, DewarpGroundTruth } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
interface DewarpControlsProps {
|
||||
dewarpResult: DewarpResult | null
|
||||
deskewResult?: DeskewResult | null
|
||||
showGrid: boolean
|
||||
onToggleGrid: () => void
|
||||
onManualDewarp: (shearDegrees: number) => void
|
||||
onCombinedAdjust?: (rotationDegrees: number, shearDegrees: number) => void
|
||||
onGroundTruth: (gt: DewarpGroundTruth) => void
|
||||
onNext: () => void
|
||||
isApplying: boolean
|
||||
@@ -19,9 +21,12 @@ const METHOD_LABELS: Record<string, string> = {
|
||||
hough_lines: 'C: Hough-Linien',
|
||||
text_lines: 'D: Textzeilenanalyse',
|
||||
manual: 'Manuell',
|
||||
manual_combined: 'Manuell (kombiniert)',
|
||||
none: 'Keine Korrektur',
|
||||
}
|
||||
|
||||
const SHEAR_METHOD_KEYS = ['vertical_edge', 'projection', 'hough_lines', 'text_lines'] as const
|
||||
|
||||
/** Colour for a confidence value (0-1). */
|
||||
function confColor(conf: number): string {
|
||||
if (conf >= 0.7) return 'text-green-600 dark:text-green-400'
|
||||
@@ -43,11 +48,67 @@ function ConfBar({ value }: { value: number }) {
|
||||
)
|
||||
}
|
||||
|
||||
/** A single slider row for fine-tuning. */
|
||||
function FineTuneSlider({
|
||||
label,
|
||||
value,
|
||||
onChange,
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
unit = '\u00B0',
|
||||
radioName,
|
||||
radioChecked,
|
||||
onRadioChange,
|
||||
}: {
|
||||
label: string
|
||||
value: number
|
||||
onChange: (v: number) => void
|
||||
min: number
|
||||
max: number
|
||||
step: number
|
||||
unit?: string
|
||||
radioName?: string
|
||||
radioChecked?: boolean
|
||||
onRadioChange?: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
{radioName !== undefined && (
|
||||
<input
|
||||
type="radio"
|
||||
name={radioName}
|
||||
checked={radioChecked}
|
||||
onChange={onRadioChange}
|
||||
className="w-3.5 h-3.5 accent-teal-500"
|
||||
/>
|
||||
)}
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400 w-36 shrink-0">{label}</span>
|
||||
<span className="text-xs text-gray-400 w-8 text-right">{min}{unit}</span>
|
||||
<input
|
||||
type="range"
|
||||
min={min * 100}
|
||||
max={max * 100}
|
||||
step={step * 100}
|
||||
value={Math.round(value * 100)}
|
||||
onChange={(e) => onChange(parseInt(e.target.value) / 100)}
|
||||
className="flex-1 h-1.5 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700 accent-teal-500"
|
||||
/>
|
||||
<span className="text-xs text-gray-400 w-8">+{max}{unit}</span>
|
||||
<span className="font-mono text-xs w-14 text-right tabular-nums">
|
||||
{value >= 0 ? '+' : ''}{value.toFixed(2)}{unit}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function DewarpControls({
|
||||
dewarpResult,
|
||||
deskewResult,
|
||||
showGrid,
|
||||
onToggleGrid,
|
||||
onManualDewarp,
|
||||
onCombinedAdjust,
|
||||
onGroundTruth,
|
||||
onNext,
|
||||
isApplying,
|
||||
@@ -57,6 +118,21 @@ export function DewarpControls({
|
||||
const [gtNotes, setGtNotes] = useState('')
|
||||
const [gtSaved, setGtSaved] = useState(false)
|
||||
const [showDetails, setShowDetails] = useState(false)
|
||||
const [showFineTune, setShowFineTune] = useState(false)
|
||||
|
||||
// Fine-tuning rotation sliders (3 passes)
|
||||
const [p1Iterative, setP1Iterative] = useState(0)
|
||||
const [p2Residual, setP2Residual] = useState(0)
|
||||
const [p3Textline, setP3Textline] = useState(0)
|
||||
|
||||
// Fine-tuning shear sliders (4 methods) + selected method
|
||||
const [shearValues, setShearValues] = useState<Record<string, number>>({
|
||||
vertical_edge: 0,
|
||||
projection: 0,
|
||||
hough_lines: 0,
|
||||
text_lines: 0,
|
||||
})
|
||||
const [selectedShearMethod, setSelectedShearMethod] = useState<string>('vertical_edge')
|
||||
|
||||
// Initialize slider to auto-detected value when result arrives
|
||||
useEffect(() => {
|
||||
@@ -65,6 +141,44 @@ export function DewarpControls({
|
||||
}
|
||||
}, [dewarpResult?.shear_degrees])
|
||||
|
||||
// Initialize fine-tuning sliders from deskew result
|
||||
useEffect(() => {
|
||||
if (deskewResult) {
|
||||
setP1Iterative(deskewResult.angle_iterative ?? 0)
|
||||
setP2Residual(deskewResult.angle_residual ?? 0)
|
||||
setP3Textline(deskewResult.angle_textline ?? 0)
|
||||
}
|
||||
}, [deskewResult])
|
||||
|
||||
// Initialize shear sliders from dewarp detections
|
||||
useEffect(() => {
|
||||
if (dewarpResult?.detections) {
|
||||
const newValues = { ...shearValues }
|
||||
let bestMethod = selectedShearMethod
|
||||
let bestConf = -1
|
||||
for (const d of dewarpResult.detections) {
|
||||
if (d.method in newValues) {
|
||||
newValues[d.method] = d.shear_degrees
|
||||
if (d.confidence > bestConf) {
|
||||
bestConf = d.confidence
|
||||
bestMethod = d.method
|
||||
}
|
||||
}
|
||||
}
|
||||
setShearValues(newValues)
|
||||
// Select the method that was actually used, or the highest confidence
|
||||
if (dewarpResult.method_used && dewarpResult.method_used in newValues) {
|
||||
setSelectedShearMethod(dewarpResult.method_used)
|
||||
} else {
|
||||
setSelectedShearMethod(bestMethod)
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [dewarpResult?.detections])
|
||||
|
||||
const rotationSum = p1Iterative + p2Residual + p3Textline
|
||||
const activeShear = shearValues[selectedShearMethod] ?? 0
|
||||
|
||||
const handleGroundTruth = (isCorrect: boolean) => {
|
||||
setGtFeedback(isCorrect ? 'correct' : 'incorrect')
|
||||
if (isCorrect) {
|
||||
@@ -82,8 +196,18 @@ export function DewarpControls({
|
||||
setGtSaved(true)
|
||||
}
|
||||
|
||||
const handleShearValueChange = (method: string, value: number) => {
|
||||
setShearValues((prev) => ({ ...prev, [method]: value }))
|
||||
}
|
||||
|
||||
const handleFineTunePreview = () => {
|
||||
if (onCombinedAdjust) {
|
||||
onCombinedAdjust(rotationSum, activeShear)
|
||||
}
|
||||
}
|
||||
|
||||
const wasRejected = dewarpResult && dewarpResult.method_used === 'none' && (dewarpResult.detections || []).length > 0
|
||||
const wasApplied = dewarpResult && dewarpResult.method_used !== 'none' && dewarpResult.method_used !== 'manual'
|
||||
const wasApplied = dewarpResult && dewarpResult.method_used !== 'none' && dewarpResult.method_used !== 'manual' && dewarpResult.method_used !== 'manual_combined'
|
||||
const detections = dewarpResult?.detections || []
|
||||
|
||||
return (
|
||||
@@ -106,9 +230,9 @@ export function DewarpControls({
|
||||
{wasRejected
|
||||
? 'Quality Gate: Korrektur verworfen (Projektion nicht verbessert)'
|
||||
: wasApplied
|
||||
? `Korrektur angewendet: ${dewarpResult.shear_degrees.toFixed(2)}°`
|
||||
: dewarpResult.method_used === 'manual'
|
||||
? `Manuelle Korrektur: ${dewarpResult.shear_degrees.toFixed(2)}°`
|
||||
? `Korrektur angewendet: ${dewarpResult.shear_degrees.toFixed(2)}\u00B0`
|
||||
: dewarpResult.method_used === 'manual' || dewarpResult.method_used === 'manual_combined'
|
||||
? `Manuelle Korrektur: ${dewarpResult.shear_degrees.toFixed(2)}\u00B0`
|
||||
: 'Keine Korrektur noetig'}
|
||||
</span>
|
||||
</div>
|
||||
@@ -117,7 +241,7 @@ export function DewarpControls({
|
||||
<div className="flex flex-wrap items-center gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-gray-500">Scherung:</span>{' '}
|
||||
<span className="font-mono font-medium">{dewarpResult.shear_degrees.toFixed(2)}°</span>
|
||||
<span className="font-mono font-medium">{dewarpResult.shear_degrees.toFixed(2)}\u00B0</span>
|
||||
</div>
|
||||
<div className="h-4 w-px bg-gray-300 dark:bg-gray-600" />
|
||||
<div>
|
||||
@@ -185,7 +309,7 @@ export function DewarpControls({
|
||||
{METHOD_LABELS[d.method] || d.method}
|
||||
</span>
|
||||
<span className="font-mono w-16 text-right">
|
||||
{d.shear_degrees.toFixed(2)}°
|
||||
{d.shear_degrees.toFixed(2)}\u00B0
|
||||
</span>
|
||||
<ConfBar value={d.confidence} />
|
||||
{!aboveThreshold && (
|
||||
@@ -210,7 +334,7 @@ export function DewarpControls({
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
|
||||
<div className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Scherwinkel (manuell)</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-xs text-gray-400 w-10 text-right">-2.0°</span>
|
||||
<span className="text-xs text-gray-400 w-10 text-right">-2.0\u00B0</span>
|
||||
<input
|
||||
type="range"
|
||||
min={-200}
|
||||
@@ -220,8 +344,8 @@ export function DewarpControls({
|
||||
onChange={(e) => setManualShear(parseInt(e.target.value) / 100)}
|
||||
className="flex-1 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700 accent-teal-500"
|
||||
/>
|
||||
<span className="text-xs text-gray-400 w-10">+2.0°</span>
|
||||
<span className="font-mono text-sm w-16 text-right">{manualShear.toFixed(2)}°</span>
|
||||
<span className="text-xs text-gray-400 w-10">+2.0\u00B0</span>
|
||||
<span className="font-mono text-sm w-16 text-right">{manualShear.toFixed(2)}\u00B0</span>
|
||||
<button
|
||||
onClick={() => onManualDewarp(manualShear)}
|
||||
disabled={isApplying}
|
||||
@@ -236,8 +360,128 @@ export function DewarpControls({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Fine-tuning panel */}
|
||||
{dewarpResult && onCombinedAdjust && (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
|
||||
<button
|
||||
onClick={() => setShowFineTune(v => !v)}
|
||||
className="w-full flex items-center justify-between p-4 text-left"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm">⚙️</span>
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">Feinabstimmung</span>
|
||||
<span className="text-xs text-gray-400">(7 Regler)</span>
|
||||
</div>
|
||||
<span className="text-gray-400 text-sm">{showFineTune ? '\u25B2' : '\u25BC'}</span>
|
||||
</button>
|
||||
|
||||
{showFineTune && (
|
||||
<div className="px-4 pb-4 space-y-5">
|
||||
{/* Rotation section */}
|
||||
<div>
|
||||
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2">
|
||||
Rotation (Begradigung)
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<FineTuneSlider
|
||||
label="P1 Iterative Projection"
|
||||
value={p1Iterative}
|
||||
onChange={setP1Iterative}
|
||||
min={-5}
|
||||
max={5}
|
||||
step={0.05}
|
||||
/>
|
||||
<FineTuneSlider
|
||||
label="P2 Word-Alignment"
|
||||
value={p2Residual}
|
||||
onChange={setP2Residual}
|
||||
min={-3}
|
||||
max={3}
|
||||
step={0.05}
|
||||
/>
|
||||
<FineTuneSlider
|
||||
label="P3 Textline-Regression"
|
||||
value={p3Textline}
|
||||
onChange={setP3Textline}
|
||||
min={-3}
|
||||
max={3}
|
||||
step={0.05}
|
||||
/>
|
||||
<div className="flex items-center gap-2 pt-1 border-t border-gray-100 dark:border-gray-700">
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400 w-36 shrink-0">Summe Rotation</span>
|
||||
<span className="font-mono text-sm font-medium text-teal-600 dark:text-teal-400">
|
||||
{rotationSum >= 0 ? '+' : ''}{rotationSum.toFixed(2)}\u00B0
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Shear section */}
|
||||
<div>
|
||||
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2">
|
||||
Scherung (Entzerrung) — einen Wert waehlen
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{SHEAR_METHOD_KEYS.map((method) => (
|
||||
<FineTuneSlider
|
||||
key={method}
|
||||
label={METHOD_LABELS[method] || method}
|
||||
value={shearValues[method]}
|
||||
onChange={(v) => handleShearValueChange(method, v)}
|
||||
min={-5}
|
||||
max={5}
|
||||
step={0.05}
|
||||
radioName="shear-method"
|
||||
radioChecked={selectedShearMethod === method}
|
||||
onRadioChange={() => setSelectedShearMethod(method)}
|
||||
/>
|
||||
))}
|
||||
<div className="flex items-center gap-2 pt-1 border-t border-gray-100 dark:border-gray-700">
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400 w-36 shrink-0">Gewaehlte Scherung</span>
|
||||
<span className="font-mono text-sm font-medium text-teal-600 dark:text-teal-400">
|
||||
{activeShear >= 0 ? '+' : ''}{activeShear.toFixed(2)}\u00B0
|
||||
</span>
|
||||
<span className="text-xs text-gray-400 ml-1">
|
||||
({METHOD_LABELS[selectedShearMethod]})
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Preview + Save */}
|
||||
<div className="flex items-center gap-3 pt-2">
|
||||
<button
|
||||
onClick={handleFineTunePreview}
|
||||
disabled={isApplying}
|
||||
className="px-4 py-2 text-sm bg-teal-600 text-white rounded-md hover:bg-teal-700 disabled:opacity-50 transition-colors"
|
||||
>
|
||||
{isApplying ? 'Wird angewendet...' : 'Vorschau'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
onGroundTruth({
|
||||
is_correct: false,
|
||||
corrected_shear: activeShear,
|
||||
notes: `Fine-tuned: rotation=${rotationSum.toFixed(3)}, shear=${activeShear.toFixed(3)} (${selectedShearMethod})`,
|
||||
})
|
||||
setGtSaved(true)
|
||||
}}
|
||||
disabled={gtSaved}
|
||||
className="px-4 py-2 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 transition-colors"
|
||||
>
|
||||
{gtSaved ? 'Gespeichert' : 'Als Ground Truth speichern'}
|
||||
</button>
|
||||
<span className="text-xs text-gray-400">
|
||||
Rotation: {rotationSum >= 0 ? '+' : ''}{rotationSum.toFixed(2)}\u00B0 + Scherung: {activeShear >= 0 ? '+' : ''}{activeShear.toFixed(2)}\u00B0
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Ground Truth */}
|
||||
{dewarpResult && (
|
||||
{dewarpResult && !showFineTune && (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
|
||||
<div className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
Spalten vertikal ausgerichtet?
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { GridCell } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import type { GridCell } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
@@ -101,7 +101,7 @@ export function FabricReconstructionCanvas({
|
||||
if (!canvasEl) return
|
||||
|
||||
// Load background image first to get dimensions
|
||||
const imgUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/dewarped`
|
||||
const imgUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
|
||||
const bgImg = await fabricModule.FabricImage.fromURL(imgUrl, { crossOrigin: 'anonymous' }) as FabricImage
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ export function ImageCompareView({
|
||||
<>
|
||||
<img
|
||||
src={rightUrl}
|
||||
alt="Begradigtes Bild"
|
||||
alt={rightLabel || 'Bearbeitetes Bild'}
|
||||
className="w-full h-full object-contain"
|
||||
onError={() => setRightError(true)}
|
||||
/>
|
||||
@@ -133,7 +133,7 @@ export function ImageCompareView({
|
||||
</>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full text-gray-400">
|
||||
{rightError ? 'Fehler beim Laden' : 'Begradigung laeuft...'}
|
||||
{rightError ? 'Fehler beim Laden' : `${rightLabel || 'Verarbeitung'} laeuft...`}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { ColumnTypeKey, PageRegion } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import type { ColumnTypeKey, PageRegion } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
const COLUMN_TYPES: { value: ColumnTypeKey; label: string }[] = [
|
||||
{ value: 'column_en', label: 'EN' },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { PipelineStep, DocumentTypeResult } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import { PipelineStep, DocumentTypeResult } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
const DOC_TYPE_LABELS: Record<string, string> = {
|
||||
vocab_table: 'Vokabeltabelle',
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import type { ColumnResult, ColumnGroundTruth, PageRegion } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import type { ColumnResult, ColumnGroundTruth, PageRegion, SubSession } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
import { ColumnControls } from './ColumnControls'
|
||||
import { ManualColumnEditor } from './ManualColumnEditor'
|
||||
import type { ColumnTypeKey } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import type { ColumnTypeKey } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
@@ -13,6 +13,7 @@ type ViewMode = 'normal' | 'ground-truth' | 'manual'
|
||||
interface StepColumnDetectionProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
onBoxSessionsCreated?: (subSessions: SubSession[]) => void
|
||||
}
|
||||
|
||||
/** Convert PageRegion[] to divider percentages + column types for ManualColumnEditor */
|
||||
@@ -34,7 +35,7 @@ function columnsToEditorState(
|
||||
return { dividers, columnTypes }
|
||||
}
|
||||
|
||||
export function StepColumnDetection({ sessionId, onNext }: StepColumnDetectionProps) {
|
||||
export function StepColumnDetection({ sessionId, onNext, onBoxSessionsCreated }: StepColumnDetectionProps) {
|
||||
const [columnResult, setColumnResult] = useState<ColumnResult | null>(null)
|
||||
const [detecting, setDetecting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -42,6 +43,9 @@ export function StepColumnDetection({ sessionId, onNext }: StepColumnDetectionPr
|
||||
const [applying, setApplying] = useState(false)
|
||||
const [imageDimensions, setImageDimensions] = useState<{ width: number; height: number } | null>(null)
|
||||
const [savedGtColumns, setSavedGtColumns] = useState<PageRegion[] | null>(null)
|
||||
const [creatingBoxSessions, setCreatingBoxSessions] = useState(false)
|
||||
const [existingSubSessions, setExistingSubSessions] = useState<SubSession[] | null>(null)
|
||||
const [isSubSession, setIsSubSession] = useState(false)
|
||||
|
||||
// Fetch session info (image dimensions) + check for cached column result
|
||||
useEffect(() => {
|
||||
@@ -55,10 +59,31 @@ export function StepColumnDetection({ sessionId, onNext }: StepColumnDetectionPr
|
||||
if (info.image_width && info.image_height) {
|
||||
setImageDimensions({ width: info.image_width, height: info.image_height })
|
||||
}
|
||||
const isSub = !!info.parent_session_id
|
||||
setIsSubSession(isSub)
|
||||
if (info.sub_sessions && info.sub_sessions.length > 0) {
|
||||
setExistingSubSessions(info.sub_sessions)
|
||||
onBoxSessionsCreated?.(info.sub_sessions)
|
||||
}
|
||||
if (info.column_result) {
|
||||
setColumnResult(info.column_result)
|
||||
// Sub-session with pseudo-column already set → auto-advance
|
||||
if (isSub) {
|
||||
onNext()
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
// Sub-session without columns → auto-detect (creates pseudo-column)
|
||||
if (isSub) {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/columns`, { method: 'POST' })
|
||||
if (res.ok) {
|
||||
const data: ColumnResult = await res.json()
|
||||
setColumnResult(data)
|
||||
onNext()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch session info:', e)
|
||||
@@ -178,6 +203,39 @@ export function StepColumnDetection({ sessionId, onNext }: StepColumnDetectionPr
|
||||
}
|
||||
}, [sessionId])
|
||||
|
||||
// Count box zones from column result
|
||||
const boxZones = columnResult?.zones?.filter(z => z.zone_type === 'box') || []
|
||||
const boxCount = boxZones.length
|
||||
|
||||
const createBoxSessions = useCallback(async () => {
|
||||
if (!sessionId) return
|
||||
setCreatingBoxSessions(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/create-box-sessions`, {
|
||||
method: 'POST',
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ detail: res.statusText }))
|
||||
throw new Error(err.detail || 'Box-Sessions konnten nicht erstellt werden')
|
||||
}
|
||||
const data = await res.json()
|
||||
const subs: SubSession[] = data.sub_sessions.map((s: { id: string; name?: string; box_index: number }) => ({
|
||||
id: s.id,
|
||||
name: s.name || `Box ${s.box_index + 1}`,
|
||||
box_index: s.box_index,
|
||||
current_step: 1,
|
||||
status: 'pending',
|
||||
}))
|
||||
setExistingSubSessions(subs)
|
||||
onBoxSessionsCreated?.(subs)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Fehler beim Erstellen der Box-Sessions')
|
||||
} finally {
|
||||
setCreatingBoxSessions(false)
|
||||
}
|
||||
}, [sessionId, onBoxSessionsCreated])
|
||||
|
||||
if (!sessionId) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-16 text-center">
|
||||
@@ -192,7 +250,7 @@ export function StepColumnDetection({ sessionId, onNext }: StepColumnDetectionPr
|
||||
)
|
||||
}
|
||||
|
||||
const dewarpedUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/dewarped`
|
||||
const dewarpedUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
const overlayUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/columns-overlay`
|
||||
|
||||
// Pre-compute editor state from saved GT or auto columns for GT mode
|
||||
@@ -317,6 +375,39 @@ export function StepColumnDetection({ sessionId, onNext }: StepColumnDetectionPr
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Box zone info */}
|
||||
{viewMode === 'normal' && boxCount > 0 && (
|
||||
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-700 rounded-xl p-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-2xl">📦</span>
|
||||
<div>
|
||||
<div className="text-sm font-medium text-amber-800 dark:text-amber-300">
|
||||
{boxCount} Box{boxCount > 1 ? 'en' : ''} erkannt
|
||||
</div>
|
||||
<div className="text-xs text-amber-600 dark:text-amber-400">
|
||||
Box-Bereiche werden separat verarbeitet
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{existingSubSessions && existingSubSessions.length > 0 ? (
|
||||
<div className="text-xs text-amber-700 dark:text-amber-300 font-medium">
|
||||
{existingSubSessions.length} Box-Session{existingSubSessions.length > 1 ? 's' : ''} vorhanden
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={createBoxSessions}
|
||||
disabled={creatingBoxSessions}
|
||||
className="px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors text-sm font-medium disabled:opacity-50 flex items-center gap-2"
|
||||
>
|
||||
{creatingBoxSessions && (
|
||||
<div className="animate-spin w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full" />
|
||||
)}
|
||||
Box-Sessions erstellen
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Controls */}
|
||||
{viewMode === 'normal' && (
|
||||
<ColumnControls
|
||||
|
||||
200
admin-lehrer/components/ocr-pipeline/StepCrop.tsx
Normal file
200
admin-lehrer/components/ocr-pipeline/StepCrop.tsx
Normal file
@@ -0,0 +1,200 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { CropResult } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
import { ImageCompareView } from './ImageCompareView'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface StepCropProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
export function StepCrop({ sessionId, onNext }: StepCropProps) {
|
||||
const [cropResult, setCropResult] = useState<CropResult | null>(null)
|
||||
const [cropping, setCropping] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [hasRun, setHasRun] = useState(false)
|
||||
|
||||
// Auto-trigger crop on mount
|
||||
useEffect(() => {
|
||||
if (!sessionId || hasRun) return
|
||||
setHasRun(true)
|
||||
|
||||
const runCrop = async () => {
|
||||
setCropping(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
// Check if session already has crop result
|
||||
const sessionRes = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}`)
|
||||
if (sessionRes.ok) {
|
||||
const sessionData = await sessionRes.json()
|
||||
if (sessionData.crop_result) {
|
||||
setCropResult(sessionData.crop_result)
|
||||
setCropping(false)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/crop`, {
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error('Zuschnitt fehlgeschlagen')
|
||||
}
|
||||
|
||||
const data = await res.json()
|
||||
setCropResult(data)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
|
||||
} finally {
|
||||
setCropping(false)
|
||||
}
|
||||
}
|
||||
|
||||
runCrop()
|
||||
}, [sessionId, hasRun])
|
||||
|
||||
const handleSkip = async () => {
|
||||
if (!sessionId) return
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/crop/skip`, {
|
||||
method: 'POST',
|
||||
})
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
setCropResult(data)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Skip crop failed:', e)
|
||||
}
|
||||
onNext()
|
||||
}
|
||||
|
||||
if (!sessionId) {
|
||||
return <div className="text-sm text-gray-400">Keine Session ausgewaehlt.</div>
|
||||
}
|
||||
|
||||
const dewarpedUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/dewarped`
|
||||
const croppedUrl = cropResult
|
||||
? `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
: null
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Loading indicator */}
|
||||
{cropping && (
|
||||
<div className="flex items-center gap-2 text-teal-600 dark:text-teal-400 text-sm">
|
||||
<div className="animate-spin w-4 h-4 border-2 border-teal-500 border-t-transparent rounded-full" />
|
||||
Scannerraender werden erkannt...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Image comparison */}
|
||||
<ImageCompareView
|
||||
originalUrl={dewarpedUrl}
|
||||
deskewedUrl={croppedUrl}
|
||||
showGrid={false}
|
||||
showBinarized={false}
|
||||
binarizedUrl={null}
|
||||
leftLabel="Entzerrt"
|
||||
rightLabel="Zugeschnitten"
|
||||
/>
|
||||
|
||||
{/* Crop result info */}
|
||||
{cropResult && (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
|
||||
<div className="flex flex-wrap items-center gap-3 text-sm">
|
||||
{(cropResult as Record<string, unknown>).multi_page ? (
|
||||
<>
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400 text-xs font-medium">
|
||||
Mehrseitig: {(cropResult as Record<string, unknown>).page_count as number} Seiten erkannt
|
||||
</span>
|
||||
{((cropResult as Record<string, unknown>).sub_sessions as Array<{id: string; name: string; page_index: number}> | undefined)?.map((sub) => (
|
||||
<span key={sub.id} className="text-gray-400 text-xs">
|
||||
Seite {sub.page_index + 1}
|
||||
</span>
|
||||
))}
|
||||
</>
|
||||
) : cropResult.crop_applied ? (
|
||||
<>
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-400 text-xs font-medium">
|
||||
Zugeschnitten
|
||||
</span>
|
||||
{cropResult.detected_format && (
|
||||
<>
|
||||
<div className="h-4 w-px bg-gray-300 dark:bg-gray-600" />
|
||||
<span className="text-gray-600 dark:text-gray-400">
|
||||
Format: <span className="font-medium">{cropResult.detected_format}</span>
|
||||
{cropResult.format_confidence != null && (
|
||||
<span className="text-gray-400 ml-1">
|
||||
({Math.round(cropResult.format_confidence * 100)}%)
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
{cropResult.original_size && cropResult.cropped_size && (
|
||||
<>
|
||||
<div className="h-4 w-px bg-gray-300 dark:bg-gray-600" />
|
||||
<span className="text-gray-400 text-xs">
|
||||
{cropResult.original_size.width}x{cropResult.original_size.height} → {cropResult.cropped_size.width}x{cropResult.cropped_size.height}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
{cropResult.border_fractions && (
|
||||
<>
|
||||
<div className="h-4 w-px bg-gray-300 dark:bg-gray-600" />
|
||||
<span className="text-gray-400 text-xs">
|
||||
Raender: O={pct(cropResult.border_fractions.top)} U={pct(cropResult.border_fractions.bottom)} L={pct(cropResult.border_fractions.left)} R={pct(cropResult.border_fractions.right)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-400 text-xs font-medium">
|
||||
Kein Zuschnitt noetig
|
||||
</span>
|
||||
)}
|
||||
{cropResult.duration_seconds != null && (
|
||||
<span className="text-gray-400 text-xs ml-auto">
|
||||
{cropResult.duration_seconds}s
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action buttons */}
|
||||
{cropResult && (
|
||||
<div className="flex justify-between">
|
||||
<button
|
||||
onClick={handleSkip}
|
||||
className="px-4 py-2 text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 transition-colors"
|
||||
>
|
||||
Ueberspringen
|
||||
</button>
|
||||
<button
|
||||
onClick={onNext}
|
||||
className="px-6 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 font-medium transition-colors"
|
||||
>
|
||||
Weiter →
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-lg text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function pct(v: number): string {
|
||||
return `${(v * 100).toFixed(1)}%`
|
||||
}
|
||||
@@ -1,36 +1,34 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import type { DeskewGroundTruth, DeskewResult, SessionInfo } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import type { DeskewGroundTruth, DeskewResult, SessionInfo } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
import { DeskewControls } from './DeskewControls'
|
||||
import { ImageCompareView } from './ImageCompareView'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface StepDeskewProps {
|
||||
sessionId?: string | null
|
||||
onNext: (sessionId: string) => void
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
export function StepDeskew({ sessionId: existingSessionId, onNext }: StepDeskewProps) {
|
||||
export function StepDeskew({ sessionId, onNext }: StepDeskewProps) {
|
||||
const [session, setSession] = useState<SessionInfo | null>(null)
|
||||
const [deskewResult, setDeskewResult] = useState<DeskewResult | null>(null)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const [deskewing, setDeskewing] = useState(false)
|
||||
const [applying, setApplying] = useState(false)
|
||||
const [showBinarized, setShowBinarized] = useState(false)
|
||||
const [showGrid, setShowGrid] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [dragOver, setDragOver] = useState(false)
|
||||
const [sessionName, setSessionName] = useState('')
|
||||
const [hasAutoRun, setHasAutoRun] = useState(false)
|
||||
|
||||
// Reload session data when navigating back from a later step
|
||||
// Load session and auto-trigger deskew
|
||||
useEffect(() => {
|
||||
if (!existingSessionId || session) return
|
||||
if (!sessionId || session) return
|
||||
|
||||
const loadSession = async () => {
|
||||
const loadAndDeskew = async () => {
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${existingSessionId}`)
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}`)
|
||||
if (!res.ok) return
|
||||
const data = await res.json()
|
||||
|
||||
@@ -39,83 +37,56 @@ export function StepDeskew({ sessionId: existingSessionId, onNext }: StepDeskewP
|
||||
filename: data.filename,
|
||||
image_width: data.image_width,
|
||||
image_height: data.image_height,
|
||||
original_image_url: `${KLAUSUR_API}${data.original_image_url}`,
|
||||
// Use oriented image as "before" view (deskew runs right after orientation)
|
||||
original_image_url: `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/oriented`,
|
||||
}
|
||||
setSession(sessionInfo)
|
||||
|
||||
// Reconstruct deskew result from session data
|
||||
// If deskew result already exists, use it
|
||||
if (data.deskew_result) {
|
||||
const dr: DeskewResult = {
|
||||
...data.deskew_result,
|
||||
deskewed_image_url: `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${existingSessionId}/image/deskewed`,
|
||||
binarized_image_url: `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${existingSessionId}/image/binarized`,
|
||||
deskewed_image_url: `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/deskewed`,
|
||||
binarized_image_url: `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/binarized`,
|
||||
}
|
||||
setDeskewResult(dr)
|
||||
return
|
||||
}
|
||||
|
||||
// Auto-trigger deskew if not already done
|
||||
if (!hasAutoRun) {
|
||||
setHasAutoRun(true)
|
||||
setDeskewing(true)
|
||||
const deskewRes = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/deskew`, {
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
if (!deskewRes.ok) {
|
||||
throw new Error('Begradigung fehlgeschlagen')
|
||||
}
|
||||
|
||||
const deskewData: DeskewResult = await deskewRes.json()
|
||||
deskewData.deskewed_image_url = `${KLAUSUR_API}${deskewData.deskewed_image_url}`
|
||||
deskewData.binarized_image_url = `${KLAUSUR_API}${deskewData.binarized_image_url}`
|
||||
setDeskewResult(deskewData)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to reload session:', e)
|
||||
setError(e instanceof Error ? e.message : 'Fehler beim Laden')
|
||||
} finally {
|
||||
setDeskewing(false)
|
||||
}
|
||||
}
|
||||
|
||||
loadSession()
|
||||
}, [existingSessionId, session])
|
||||
|
||||
const handleUpload = useCallback(async (file: File) => {
|
||||
setUploading(true)
|
||||
setError(null)
|
||||
setDeskewResult(null)
|
||||
|
||||
try {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
if (sessionName.trim()) {
|
||||
formData.append('name', sessionName.trim())
|
||||
}
|
||||
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ detail: res.statusText }))
|
||||
throw new Error(err.detail || 'Upload fehlgeschlagen')
|
||||
}
|
||||
|
||||
const data: SessionInfo = await res.json()
|
||||
// Prepend API prefix to relative URLs
|
||||
data.original_image_url = `${KLAUSUR_API}${data.original_image_url}`
|
||||
setSession(data)
|
||||
|
||||
// Auto-trigger deskew
|
||||
setDeskewing(true)
|
||||
const deskewRes = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${data.session_id}/deskew`, {
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
if (!deskewRes.ok) {
|
||||
throw new Error('Begradigung fehlgeschlagen')
|
||||
}
|
||||
|
||||
const deskewData: DeskewResult = await deskewRes.json()
|
||||
deskewData.deskewed_image_url = `${KLAUSUR_API}${deskewData.deskewed_image_url}`
|
||||
deskewData.binarized_image_url = `${KLAUSUR_API}${deskewData.binarized_image_url}`
|
||||
setDeskewResult(deskewData)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
|
||||
} finally {
|
||||
setUploading(false)
|
||||
setDeskewing(false)
|
||||
}
|
||||
}, [])
|
||||
loadAndDeskew()
|
||||
}, [sessionId, session, hasAutoRun])
|
||||
|
||||
const handleManualDeskew = useCallback(async (angle: number) => {
|
||||
if (!session) return
|
||||
if (!sessionId) return
|
||||
setApplying(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${session.session_id}/deskew/manual`, {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/deskew/manual`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ angle }),
|
||||
@@ -130,7 +101,6 @@ export function StepDeskew({ sessionId: existingSessionId, onNext }: StepDeskewP
|
||||
...prev,
|
||||
angle_applied: data.angle_applied,
|
||||
method_used: data.method_used,
|
||||
// Force reload by appending timestamp
|
||||
deskewed_image_url: `${KLAUSUR_API}${data.deskewed_image_url}?t=${Date.now()}`,
|
||||
}
|
||||
: null,
|
||||
@@ -140,12 +110,12 @@ export function StepDeskew({ sessionId: existingSessionId, onNext }: StepDeskewP
|
||||
} finally {
|
||||
setApplying(false)
|
||||
}
|
||||
}, [session])
|
||||
}, [sessionId])
|
||||
|
||||
const handleGroundTruth = useCallback(async (gt: DeskewGroundTruth) => {
|
||||
if (!session) return
|
||||
if (!sessionId) return
|
||||
try {
|
||||
await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${session.session_id}/ground-truth/deskew`, {
|
||||
await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/ground-truth/deskew`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(gt),
|
||||
@@ -153,89 +123,21 @@ export function StepDeskew({ sessionId: existingSessionId, onNext }: StepDeskewP
|
||||
} catch (e) {
|
||||
console.error('Ground truth save failed:', e)
|
||||
}
|
||||
}, [session])
|
||||
}, [sessionId])
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setDragOver(false)
|
||||
const file = e.dataTransfer.files[0]
|
||||
if (file) handleUpload(file)
|
||||
}, [handleUpload])
|
||||
|
||||
const handleFileInput = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) handleUpload(file)
|
||||
}, [handleUpload])
|
||||
|
||||
// Upload area (no session yet)
|
||||
if (!session) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Session name input */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-600 dark:text-gray-400 mb-1">
|
||||
Session-Name (optional)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={sessionName}
|
||||
onChange={(e) => setSessionName(e.target.value)}
|
||||
placeholder="z.B. Unit 3 Seite 42"
|
||||
className="w-full max-w-sm px-3 py-2 text-sm border rounded-lg dark:bg-gray-800 dark:border-gray-600 dark:text-gray-200 focus:outline-none focus:ring-2 focus:ring-teal-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
onDragOver={(e) => { e.preventDefault(); setDragOver(true) }}
|
||||
onDragLeave={() => setDragOver(false)}
|
||||
onDrop={handleDrop}
|
||||
className={`border-2 border-dashed rounded-xl p-12 text-center transition-colors ${
|
||||
dragOver
|
||||
? 'border-teal-400 bg-teal-50 dark:bg-teal-900/20'
|
||||
: 'border-gray-300 dark:border-gray-600 hover:border-teal-400'
|
||||
}`}
|
||||
>
|
||||
{uploading ? (
|
||||
<div className="text-gray-500">
|
||||
<div className="animate-spin inline-block w-8 h-8 border-2 border-teal-500 border-t-transparent rounded-full mb-3" />
|
||||
<p>Wird hochgeladen...</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-4xl mb-3">📄</div>
|
||||
<p className="text-gray-600 dark:text-gray-400 mb-2">
|
||||
PDF oder Bild hierher ziehen
|
||||
</p>
|
||||
<p className="text-sm text-gray-400 mb-4">oder</p>
|
||||
<label className="inline-block px-4 py-2 bg-teal-600 text-white rounded-lg cursor-pointer hover:bg-teal-700 transition-colors">
|
||||
Datei auswaehlen
|
||||
<input
|
||||
type="file"
|
||||
accept=".pdf,.png,.jpg,.jpeg,.tiff,.tif"
|
||||
onChange={handleFileInput}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-lg text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
if (!sessionId) {
|
||||
return <div className="text-sm text-gray-400">Keine Session ausgewaehlt.</div>
|
||||
}
|
||||
|
||||
// Session active: show comparison + controls
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Filename */}
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
Datei: <span className="font-medium text-gray-700 dark:text-gray-300">{session.filename}</span>
|
||||
{' '}({session.image_width} x {session.image_height} px)
|
||||
</div>
|
||||
{session && (
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
Datei: <span className="font-medium text-gray-700 dark:text-gray-300">{session.filename}</span>
|
||||
{' '}({session.image_width} x {session.image_height} px)
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Loading indicator */}
|
||||
{deskewing && (
|
||||
@@ -246,13 +148,17 @@ export function StepDeskew({ sessionId: existingSessionId, onNext }: StepDeskewP
|
||||
)}
|
||||
|
||||
{/* Image comparison */}
|
||||
<ImageCompareView
|
||||
originalUrl={session.original_image_url}
|
||||
deskewedUrl={deskewResult?.deskewed_image_url ?? null}
|
||||
showGrid={showGrid}
|
||||
showBinarized={showBinarized}
|
||||
binarizedUrl={deskewResult?.binarized_image_url ?? null}
|
||||
/>
|
||||
{session && (
|
||||
<ImageCompareView
|
||||
originalUrl={session.original_image_url}
|
||||
deskewedUrl={deskewResult?.deskewed_image_url ?? null}
|
||||
showGrid={showGrid}
|
||||
showBinarized={showBinarized}
|
||||
binarizedUrl={deskewResult?.binarized_image_url ?? null}
|
||||
leftLabel="Orientiert"
|
||||
rightLabel="Begradigt"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Controls */}
|
||||
<DeskewControls
|
||||
@@ -263,7 +169,7 @@ export function StepDeskew({ sessionId: existingSessionId, onNext }: StepDeskewP
|
||||
onToggleGrid={() => setShowGrid((v) => !v)}
|
||||
onManualDeskew={handleManualDeskew}
|
||||
onGroundTruth={handleGroundTruth}
|
||||
onNext={() => session && onNext(session.session_id)}
|
||||
onNext={onNext}
|
||||
isApplying={applying}
|
||||
/>
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import type { DewarpResult, DewarpGroundTruth } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import type { DeskewResult, DewarpResult, DewarpGroundTruth } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
import { DewarpControls } from './DewarpControls'
|
||||
import { ImageCompareView } from './ImageCompareView'
|
||||
|
||||
@@ -14,11 +14,31 @@ interface StepDewarpProps {
|
||||
|
||||
export function StepDewarp({ sessionId, onNext }: StepDewarpProps) {
|
||||
const [dewarpResult, setDewarpResult] = useState<DewarpResult | null>(null)
|
||||
const [deskewResult, setDeskewResult] = useState<DeskewResult | null>(null)
|
||||
const [dewarping, setDewarping] = useState(false)
|
||||
const [applying, setApplying] = useState(false)
|
||||
const [showGrid, setShowGrid] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
// Load session info to get deskew_result (for fine-tuning init values)
|
||||
useEffect(() => {
|
||||
if (!sessionId) return
|
||||
const loadSession = async () => {
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}`)
|
||||
if (res.ok) {
|
||||
const data = await res.json()
|
||||
if (data.deskew_result) {
|
||||
setDeskewResult(data.deskew_result)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load session info:', e)
|
||||
}
|
||||
}
|
||||
loadSession()
|
||||
}, [sessionId])
|
||||
|
||||
// Auto-trigger dewarp when component mounts with a sessionId
|
||||
useEffect(() => {
|
||||
if (!sessionId || dewarpResult) return
|
||||
@@ -78,6 +98,37 @@ export function StepDewarp({ sessionId, onNext }: StepDewarpProps) {
|
||||
}
|
||||
}, [sessionId])
|
||||
|
||||
const handleCombinedAdjust = useCallback(async (rotationDegrees: number, shearDegrees: number) => {
|
||||
if (!sessionId) return
|
||||
setApplying(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/adjust-combined`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ rotation_degrees: rotationDegrees, shear_degrees: shearDegrees }),
|
||||
})
|
||||
if (!res.ok) throw new Error('Kombinierte Anpassung fehlgeschlagen')
|
||||
|
||||
const data = await res.json()
|
||||
setDewarpResult((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
method_used: data.method_used,
|
||||
shear_degrees: data.shear_degrees,
|
||||
dewarped_image_url: `${KLAUSUR_API}${data.dewarped_image_url}?t=${Date.now()}`,
|
||||
}
|
||||
: null,
|
||||
)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Fehler')
|
||||
} finally {
|
||||
setApplying(false)
|
||||
}
|
||||
}, [sessionId])
|
||||
|
||||
const handleGroundTruth = useCallback(async (gt: DewarpGroundTruth) => {
|
||||
if (!sessionId) return
|
||||
try {
|
||||
@@ -133,9 +184,11 @@ export function StepDewarp({ sessionId, onNext }: StepDewarpProps) {
|
||||
{/* Controls */}
|
||||
<DewarpControls
|
||||
dewarpResult={dewarpResult}
|
||||
deskewResult={deskewResult}
|
||||
showGrid={showGrid}
|
||||
onToggleGrid={() => setShowGrid((v) => !v)}
|
||||
onManualDewarp={handleManualDewarp}
|
||||
onCombinedAdjust={handleCombinedAdjust}
|
||||
onGroundTruth={handleGroundTruth}
|
||||
onNext={onNext}
|
||||
isApplying={applying}
|
||||
|
||||
517
admin-lehrer/components/ocr-pipeline/StepGridReview.tsx
Normal file
517
admin-lehrer/components/ocr-pipeline/StepGridReview.tsx
Normal file
@@ -0,0 +1,517 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* StepGridReview — Last step of the Kombi Pipeline
|
||||
*
|
||||
* Split view: original scan on the left, GridEditor on the right.
|
||||
* Adds confidence stats, row-accept buttons, and integrates with
|
||||
* the GT marking flow in the parent page.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState, type MutableRefObject } from 'react'
|
||||
import { useGridEditor } from '@/components/grid-editor/useGridEditor'
|
||||
import type { GridZone, LayoutDividers } from '@/components/grid-editor/types'
|
||||
import { GridToolbar } from '@/components/grid-editor/GridToolbar'
|
||||
import { GridTable } from '@/components/grid-editor/GridTable'
|
||||
import { ImageLayoutEditor } from '@/components/grid-editor/ImageLayoutEditor'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface StepGridReviewProps {
|
||||
sessionId: string | null
|
||||
onNext?: () => void
|
||||
saveRef?: MutableRefObject<(() => Promise<void>) | null>
|
||||
}
|
||||
|
||||
export function StepGridReview({ sessionId, onNext, saveRef }: StepGridReviewProps) {
|
||||
const {
|
||||
grid,
|
||||
loading,
|
||||
saving,
|
||||
error,
|
||||
dirty,
|
||||
selectedCell,
|
||||
selectedCells,
|
||||
setSelectedCell,
|
||||
buildGrid,
|
||||
loadGrid,
|
||||
saveGrid,
|
||||
updateCellText,
|
||||
toggleColumnBold,
|
||||
toggleRowHeader,
|
||||
undo,
|
||||
redo,
|
||||
canUndo,
|
||||
canRedo,
|
||||
getAdjacentCell,
|
||||
deleteColumn,
|
||||
addColumn,
|
||||
deleteRow,
|
||||
addRow,
|
||||
commitUndoPoint,
|
||||
updateColumnDivider,
|
||||
updateLayoutHorizontals,
|
||||
splitColumnAt,
|
||||
toggleCellSelection,
|
||||
clearCellSelection,
|
||||
toggleSelectedBold,
|
||||
autoCorrectColumnPatterns,
|
||||
setCellColor,
|
||||
ipaMode,
|
||||
setIpaMode,
|
||||
syllableMode,
|
||||
setSyllableMode,
|
||||
ocrEnhance,
|
||||
setOcrEnhance,
|
||||
ocrMaxCols,
|
||||
setOcrMaxCols,
|
||||
ocrMinConf,
|
||||
setOcrMinConf,
|
||||
rerunOcr,
|
||||
} = useGridEditor(sessionId)
|
||||
|
||||
const [showImage, setShowImage] = useState(true)
|
||||
const [zoom, setZoom] = useState(100)
|
||||
const [acceptedRows, setAcceptedRows] = useState<Set<string>>(new Set())
|
||||
|
||||
// Expose save function to parent via ref (for GT marking auto-save)
|
||||
useEffect(() => {
|
||||
if (saveRef) {
|
||||
saveRef.current = async () => {
|
||||
if (dirty) await saveGrid()
|
||||
}
|
||||
return () => { saveRef.current = null }
|
||||
}
|
||||
}, [saveRef, dirty, saveGrid])
|
||||
|
||||
// Load grid on mount
|
||||
useEffect(() => {
|
||||
if (sessionId) loadGrid()
|
||||
}, [sessionId, loadGrid])
|
||||
|
||||
// Reset accepted rows when session changes
|
||||
useEffect(() => {
|
||||
setAcceptedRows(new Set())
|
||||
}, [sessionId])
|
||||
|
||||
// Keyboard shortcuts
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'z' && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
undo()
|
||||
} else if ((e.metaKey || e.ctrlKey) && e.key === 'z' && e.shiftKey) {
|
||||
e.preventDefault()
|
||||
redo()
|
||||
} else if ((e.metaKey || e.ctrlKey) && e.key === 's') {
|
||||
e.preventDefault()
|
||||
saveGrid()
|
||||
} else if ((e.metaKey || e.ctrlKey) && e.key === 'b') {
|
||||
e.preventDefault()
|
||||
if (selectedCells.size > 0) {
|
||||
toggleSelectedBold()
|
||||
}
|
||||
} else if (e.key === 'Escape') {
|
||||
clearCellSelection()
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', handler)
|
||||
return () => window.removeEventListener('keydown', handler)
|
||||
}, [undo, redo, saveGrid, selectedCells, toggleSelectedBold, clearCellSelection])
|
||||
|
||||
const handleNavigate = useCallback(
|
||||
(cellId: string, direction: 'up' | 'down' | 'left' | 'right') => {
|
||||
const target = getAdjacentCell(cellId, direction)
|
||||
if (target) {
|
||||
setSelectedCell(target)
|
||||
setTimeout(() => {
|
||||
const el = document.getElementById(`cell-${target}`)
|
||||
if (el) {
|
||||
el.focus()
|
||||
if (el instanceof HTMLInputElement) el.select()
|
||||
}
|
||||
}, 0)
|
||||
}
|
||||
},
|
||||
[getAdjacentCell, setSelectedCell],
|
||||
)
|
||||
|
||||
const acceptRow = (zoneIdx: number, rowIdx: number) => {
|
||||
setAcceptedRows((prev) => {
|
||||
const next = new Set(prev)
|
||||
const key = `${zoneIdx}-${rowIdx}`
|
||||
if (next.has(key)) next.delete(key)
|
||||
else next.add(key)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const acceptAllRows = () => {
|
||||
if (!grid) return
|
||||
const all = new Set<string>()
|
||||
for (const zone of grid.zones) {
|
||||
for (const row of zone.rows) {
|
||||
all.add(`${zone.zone_index}-${row.index}`)
|
||||
}
|
||||
}
|
||||
setAcceptedRows(all)
|
||||
}
|
||||
|
||||
// Confidence stats
|
||||
const allCells = grid?.zones?.flatMap((z) => z.cells) || []
|
||||
const lowConfCells = allCells.filter(
|
||||
(c) => c.confidence > 0 && c.confidence < 60,
|
||||
)
|
||||
const totalRows = grid?.zones?.reduce((sum, z) => sum + z.rows.length, 0) ?? 0
|
||||
|
||||
if (!sessionId) {
|
||||
return (
|
||||
<div className="text-center py-12 text-gray-400">
|
||||
Keine Session ausgewaehlt.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
<div className="flex items-center gap-3 text-gray-500 dark:text-gray-400">
|
||||
<svg className="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
|
||||
<circle
|
||||
className="opacity-25"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
/>
|
||||
<path
|
||||
className="opacity-75"
|
||||
fill="currentColor"
|
||||
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
|
||||
/>
|
||||
</svg>
|
||||
Grid wird geladen...
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
|
||||
<p className="text-sm text-red-700 dark:text-red-300">
|
||||
Fehler: {error}
|
||||
</p>
|
||||
<button
|
||||
onClick={buildGrid}
|
||||
className="mt-2 text-xs px-3 py-1.5 bg-red-600 text-white rounded hover:bg-red-700"
|
||||
>
|
||||
Erneut versuchen
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!grid || !grid.zones.length) {
|
||||
return (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-gray-400 mb-4">Kein Grid vorhanden.</p>
|
||||
<button
|
||||
onClick={buildGrid}
|
||||
className="px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 text-sm"
|
||||
>
|
||||
Grid aus OCR-Ergebnissen erstellen
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const imageUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Review Stats Bar */}
|
||||
<div className="flex items-center gap-4 text-xs flex-wrap">
|
||||
<span className="text-gray-500 dark:text-gray-400">
|
||||
{grid.summary.total_zones} Zone(n), {grid.summary.total_columns} Spalten,{' '}
|
||||
{grid.summary.total_rows} Zeilen, {grid.summary.total_cells} Zellen
|
||||
</span>
|
||||
{grid.dictionary_detection?.is_dictionary && (
|
||||
<span className="px-2 py-0.5 rounded-full bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border border-blue-200 dark:border-blue-800">
|
||||
Woerterbuch ({Math.round(grid.dictionary_detection.confidence * 100)}%)
|
||||
</span>
|
||||
)}
|
||||
{grid.page_number?.text && (
|
||||
<span className="px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 border border-gray-200 dark:border-gray-600">
|
||||
S. {grid.page_number.number ?? grid.page_number.text}
|
||||
</span>
|
||||
)}
|
||||
{lowConfCells.length > 0 && (
|
||||
<span className="px-2 py-0.5 rounded-full bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 border border-red-200 dark:border-red-800">
|
||||
{lowConfCells.length} niedrige Konfidenz
|
||||
</span>
|
||||
)}
|
||||
<span className="text-gray-400 dark:text-gray-500">
|
||||
{acceptedRows.size}/{totalRows} Zeilen akzeptiert
|
||||
</span>
|
||||
{acceptedRows.size < totalRows && (
|
||||
<button
|
||||
onClick={acceptAllRows}
|
||||
className="text-teal-600 dark:text-teal-400 hover:text-teal-700 dark:hover:text-teal-300"
|
||||
>
|
||||
Alle akzeptieren
|
||||
</button>
|
||||
)}
|
||||
{/* OCR Quality Steps (A/B Testing) */}
|
||||
<span className="text-gray-400 dark:text-gray-500">|</span>
|
||||
<label className="flex items-center gap-1 cursor-pointer" title="Step 3: CLAHE + Bilateral-Filter Enhancement">
|
||||
<input type="checkbox" checked={ocrEnhance} onChange={(e) => setOcrEnhance(e.target.checked)} className="rounded w-3 h-3" />
|
||||
<span className="text-gray-500 dark:text-gray-400">CLAHE</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-1" title="Step 2: Max Spaltenanzahl (0=unbegrenzt)">
|
||||
<span className="text-gray-500 dark:text-gray-400">MaxCol:</span>
|
||||
<select value={ocrMaxCols} onChange={(e) => setOcrMaxCols(Number(e.target.value))} className="px-1 py-0.5 text-xs rounded border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300">
|
||||
<option value={0}>off</option>
|
||||
<option value={2}>2</option>
|
||||
<option value={3}>3</option>
|
||||
<option value={4}>4</option>
|
||||
<option value={5}>5</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex items-center gap-1" title="Step 1: Min OCR Confidence (0=auto)">
|
||||
<span className="text-gray-500 dark:text-gray-400">MinConf:</span>
|
||||
<select value={ocrMinConf} onChange={(e) => setOcrMinConf(Number(e.target.value))} className="px-1 py-0.5 text-xs rounded border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300">
|
||||
<option value={0}>auto</option>
|
||||
<option value={20}>20</option>
|
||||
<option value={30}>30</option>
|
||||
<option value={40}>40</option>
|
||||
<option value={50}>50</option>
|
||||
<option value={60}>60</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
const n = autoCorrectColumnPatterns()
|
||||
if (n === 0) alert('Keine Muster-Korrekturen gefunden.')
|
||||
else alert(`${n} Zelle(n) korrigiert (Muster-Vervollstaendigung).`)
|
||||
}}
|
||||
className="px-2.5 py-1 rounded text-xs border border-purple-200 dark:border-purple-700 bg-purple-50 dark:bg-purple-900/20 text-purple-700 dark:text-purple-300 hover:bg-purple-100 dark:hover:bg-purple-900/40 transition-colors"
|
||||
title="Erkennt Muster wie p.70, p.71 und vervollstaendigt partielle Eintraege wie .65 zu p.65"
|
||||
>
|
||||
Auto-Korrektur
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowImage(!showImage)}
|
||||
className={`px-2.5 py-1 rounded text-xs border transition-colors ${
|
||||
showImage
|
||||
? 'bg-teal-50 dark:bg-teal-900/30 border-teal-200 dark:border-teal-700 text-teal-700 dark:text-teal-300'
|
||||
: 'bg-gray-50 dark:bg-gray-800 border-gray-200 dark:border-gray-700 text-gray-500 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
{showImage ? 'Bild ausblenden' : 'Bild einblenden'}
|
||||
</button>
|
||||
<span className="text-gray-400 dark:text-gray-500">
|
||||
{grid.duration_seconds.toFixed(1)}s
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Toolbar */}
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-2">
|
||||
<GridToolbar
|
||||
dirty={dirty}
|
||||
saving={saving}
|
||||
canUndo={canUndo}
|
||||
canRedo={canRedo}
|
||||
showOverlay={false}
|
||||
ipaMode={ipaMode}
|
||||
syllableMode={syllableMode}
|
||||
onSave={saveGrid}
|
||||
onUndo={undo}
|
||||
onRedo={redo}
|
||||
onRebuild={buildGrid}
|
||||
onToggleOverlay={() => setShowImage(!showImage)}
|
||||
onIpaModeChange={setIpaMode}
|
||||
onSyllableModeChange={setSyllableMode}
|
||||
/>
|
||||
<button
|
||||
onClick={rerunOcr}
|
||||
disabled={loading}
|
||||
className="ml-2 px-3 py-1.5 text-xs font-medium rounded border border-orange-300 dark:border-orange-700 bg-orange-50 dark:bg-orange-900/20 text-orange-700 dark:text-orange-300 hover:bg-orange-100 dark:hover:bg-orange-900/40 transition-colors disabled:opacity-50"
|
||||
title="OCR komplett neu ausfuehren mit aktuellen Quality-Step-Einstellungen (CLAHE, MinConf), dann Grid neu bauen"
|
||||
>
|
||||
{loading ? 'OCR laeuft...' : 'OCR neu + Grid'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Split View: Image left + Grid right */}
|
||||
<div
|
||||
className={showImage ? 'grid grid-cols-2 gap-3' : ''}
|
||||
style={{ minHeight: '55vh' }}
|
||||
>
|
||||
{/* Left: Original Image with Layout Editor */}
|
||||
{showImage && (
|
||||
<ImageLayoutEditor
|
||||
imageUrl={imageUrl}
|
||||
zones={grid.zones}
|
||||
imageWidth={grid.image_width}
|
||||
layoutDividers={grid.layout_dividers}
|
||||
zoom={zoom}
|
||||
onZoomChange={setZoom}
|
||||
onColumnDividerMove={updateColumnDivider}
|
||||
onHorizontalsChange={updateLayoutHorizontals}
|
||||
onCommitUndo={commitUndoPoint}
|
||||
onSplitColumnAt={splitColumnAt}
|
||||
onDeleteColumn={deleteColumn}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Right: Grid with row-accept buttons */}
|
||||
<div className="space-y-3">
|
||||
|
||||
{/* Zone tables with row-accept buttons */}
|
||||
{(() => {
|
||||
// Group consecutive zones with same vsplit_group
|
||||
const groups: GridZone[][] = []
|
||||
for (const zone of grid.zones) {
|
||||
const prev = groups[groups.length - 1]
|
||||
if (
|
||||
prev &&
|
||||
zone.vsplit_group != null &&
|
||||
prev[0].vsplit_group === zone.vsplit_group
|
||||
) {
|
||||
prev.push(zone)
|
||||
} else {
|
||||
groups.push([zone])
|
||||
}
|
||||
}
|
||||
return groups.map((group) => (
|
||||
<div key={group[0].vsplit_group ?? group[0].zone_index}>
|
||||
{/* Row-accept sidebar wraps each zone group */}
|
||||
<div className="flex gap-1">
|
||||
{/* Accept buttons column */}
|
||||
<div className="flex-shrink-0 pt-[52px]">
|
||||
{group[0].rows.map((row) => {
|
||||
const key = `${group[0].zone_index}-${row.index}`
|
||||
const isAccepted = acceptedRows.has(key)
|
||||
return (
|
||||
<button
|
||||
key={row.index}
|
||||
onClick={() =>
|
||||
acceptRow(group[0].zone_index, row.index)
|
||||
}
|
||||
className={`w-6 h-6 mb-px rounded flex items-center justify-center transition-colors ${
|
||||
isAccepted
|
||||
? 'bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400'
|
||||
: 'bg-gray-100 dark:bg-gray-800 text-gray-300 dark:text-gray-600 hover:bg-emerald-100 dark:hover:bg-emerald-900/30 hover:text-emerald-500'
|
||||
}`}
|
||||
title={
|
||||
isAccepted
|
||||
? 'Klick zum Entfernen'
|
||||
: 'Zeile als korrekt markieren'
|
||||
}
|
||||
>
|
||||
<svg
|
||||
className="w-3.5 h-3.5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2.5}
|
||||
d="M5 13l4 4L19 7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Grid table(s) */}
|
||||
<div
|
||||
className={`flex-1 min-w-0 ${group.length > 1 ? 'flex gap-2' : ''}`}
|
||||
>
|
||||
{group.map((zone) => (
|
||||
<div
|
||||
key={zone.zone_index}
|
||||
className={`${group.length > 1 ? 'flex-1 min-w-0' : ''} bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700`}
|
||||
>
|
||||
<GridTable
|
||||
zone={zone}
|
||||
layoutMetrics={grid.layout_metrics}
|
||||
selectedCell={selectedCell}
|
||||
selectedCells={selectedCells}
|
||||
onSelectCell={setSelectedCell}
|
||||
onToggleCellSelection={toggleCellSelection}
|
||||
onCellTextChange={updateCellText}
|
||||
onToggleColumnBold={toggleColumnBold}
|
||||
onToggleRowHeader={toggleRowHeader}
|
||||
onNavigate={handleNavigate}
|
||||
onDeleteColumn={deleteColumn}
|
||||
onAddColumn={addColumn}
|
||||
onDeleteRow={deleteRow}
|
||||
onAddRow={addRow}
|
||||
onSetCellColor={setCellColor}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Multi-select toolbar */}
|
||||
{selectedCells.size > 0 && (
|
||||
<div className="flex items-center gap-3 px-3 py-2 bg-teal-50 dark:bg-teal-900/20 border border-teal-200 dark:border-teal-800 rounded-lg text-xs">
|
||||
<span className="text-teal-700 dark:text-teal-300 font-medium">
|
||||
{selectedCells.size} Zellen markiert
|
||||
</span>
|
||||
<button
|
||||
onClick={toggleSelectedBold}
|
||||
className="px-2.5 py-1 bg-teal-600 text-white rounded hover:bg-teal-700 transition-colors font-medium"
|
||||
>
|
||||
B Fett umschalten
|
||||
</button>
|
||||
<button
|
||||
onClick={clearCellSelection}
|
||||
className="px-2 py-1 text-teal-600 dark:text-teal-400 hover:text-teal-800 dark:hover:text-teal-200 transition-colors"
|
||||
>
|
||||
Auswahl aufheben (Esc)
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tips + Next */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-[11px] text-gray-400 dark:text-gray-500 flex items-center gap-4">
|
||||
<span>Tab: naechste Zelle</span>
|
||||
<span>Pfeiltasten: Navigation</span>
|
||||
<span>Ctrl+Klick: Mehrfachauswahl</span>
|
||||
<span>Ctrl+B: Fett</span>
|
||||
<span>Rechtsklick: Farbe</span>
|
||||
<span>Ctrl+Z/Y: Undo/Redo</span>
|
||||
<span>Ctrl+S: Speichern</span>
|
||||
</div>
|
||||
{onNext && (
|
||||
<button
|
||||
onClick={async () => {
|
||||
if (dirty) await saveGrid()
|
||||
onNext()
|
||||
}}
|
||||
className="px-4 py-2 bg-teal-600 text-white text-sm rounded-lg hover:bg-teal-700 transition-colors"
|
||||
>
|
||||
Fertig
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,18 +1,639 @@
|
||||
'use client'
|
||||
|
||||
export function StepGroundTruth() {
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type {
|
||||
GridCell, ColumnMeta, ImageRegion, ImageStyle,
|
||||
} from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
import { IMAGE_STYLES as STYLES } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
const COL_TYPE_COLORS: Record<string, string> = {
|
||||
column_en: '#3b82f6',
|
||||
column_de: '#22c55e',
|
||||
column_example: '#f97316',
|
||||
column_text: '#a855f7',
|
||||
page_ref: '#06b6d4',
|
||||
column_marker: '#6b7280',
|
||||
}
|
||||
|
||||
interface StepGroundTruthProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
interface SessionData {
|
||||
cells: GridCell[]
|
||||
columnsUsed: ColumnMeta[]
|
||||
imageWidth: number
|
||||
imageHeight: number
|
||||
originalImageUrl: string
|
||||
}
|
||||
|
||||
export function StepGroundTruth({ sessionId, onNext }: StepGroundTruthProps) {
|
||||
const [status, setStatus] = useState<'loading' | 'ready' | 'saving' | 'saved' | 'error'>('loading')
|
||||
const [error, setError] = useState('')
|
||||
const [session, setSession] = useState<SessionData | null>(null)
|
||||
const [imageRegions, setImageRegions] = useState<(ImageRegion & { generating?: boolean })[]>([])
|
||||
const [detecting, setDetecting] = useState(false)
|
||||
const [zoom, setZoom] = useState(100)
|
||||
const [syncScroll, setSyncScroll] = useState(true)
|
||||
const [notes, setNotes] = useState('')
|
||||
const [score, setScore] = useState<number | null>(null)
|
||||
const [drawingRegion, setDrawingRegion] = useState(false)
|
||||
const [dragStart, setDragStart] = useState<{ x: number; y: number } | null>(null)
|
||||
const [dragEnd, setDragEnd] = useState<{ x: number; y: number } | null>(null)
|
||||
const [isGroundTruth, setIsGroundTruth] = useState(false)
|
||||
const [gtSaving, setGtSaving] = useState(false)
|
||||
const [gtMessage, setGtMessage] = useState('')
|
||||
|
||||
const leftPanelRef = useRef<HTMLDivElement>(null)
|
||||
const rightPanelRef = useRef<HTMLDivElement>(null)
|
||||
const reconRef = useRef<HTMLDivElement>(null)
|
||||
const [reconWidth, setReconWidth] = useState(0)
|
||||
|
||||
// Track reconstruction container width for font size calculation
|
||||
useEffect(() => {
|
||||
const el = reconRef.current
|
||||
if (!el) return
|
||||
const obs = new ResizeObserver(entries => {
|
||||
for (const entry of entries) setReconWidth(entry.contentRect.width)
|
||||
})
|
||||
obs.observe(el)
|
||||
return () => obs.disconnect()
|
||||
}, [session])
|
||||
|
||||
// Load session data
|
||||
useEffect(() => {
|
||||
if (!sessionId) return
|
||||
loadSessionData()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [sessionId])
|
||||
|
||||
const loadSessionData = async () => {
|
||||
if (!sessionId) return
|
||||
setStatus('loading')
|
||||
try {
|
||||
const resp = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}`)
|
||||
if (!resp.ok) throw new Error(`Failed to load session: ${resp.status}`)
|
||||
const data = await resp.json()
|
||||
|
||||
const wordResult = data.word_result || {}
|
||||
setSession({
|
||||
cells: wordResult.cells || [],
|
||||
columnsUsed: wordResult.columns_used || [],
|
||||
imageWidth: wordResult.image_width || data.image_width || 800,
|
||||
imageHeight: wordResult.image_height || data.image_height || 600,
|
||||
originalImageUrl: data.original_image_url
|
||||
? `${KLAUSUR_API}${data.original_image_url}`
|
||||
: `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/original`,
|
||||
})
|
||||
|
||||
// Check if session has ground truth reference
|
||||
const gt = data.ground_truth
|
||||
setIsGroundTruth(!!gt?.build_grid_reference)
|
||||
|
||||
// Load existing validation data
|
||||
const valResp = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/reconstruction/validation`)
|
||||
if (valResp.ok) {
|
||||
const valData = await valResp.json()
|
||||
const validation = valData.validation
|
||||
if (validation) {
|
||||
setImageRegions(validation.image_regions || [])
|
||||
setNotes(validation.notes || '')
|
||||
setScore(validation.score ?? null)
|
||||
}
|
||||
}
|
||||
|
||||
setStatus('ready')
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
setStatus('error')
|
||||
}
|
||||
}
|
||||
|
||||
// Sync scroll between panels
|
||||
const handleScroll = useCallback((source: 'left' | 'right') => {
|
||||
if (!syncScroll) return
|
||||
const from = source === 'left' ? leftPanelRef.current : rightPanelRef.current
|
||||
const to = source === 'left' ? rightPanelRef.current : leftPanelRef.current
|
||||
if (from && to) {
|
||||
to.scrollTop = from.scrollTop
|
||||
to.scrollLeft = from.scrollLeft
|
||||
}
|
||||
}, [syncScroll])
|
||||
|
||||
// Detect images via VLM
|
||||
const handleDetectImages = async () => {
|
||||
if (!sessionId) return
|
||||
setDetecting(true)
|
||||
try {
|
||||
const resp = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/reconstruction/detect-images`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
if (!resp.ok) throw new Error(`Detection failed: ${resp.status}`)
|
||||
const data = await resp.json()
|
||||
setImageRegions(data.regions || [])
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setDetecting(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Generate image for a region
|
||||
const handleGenerateImage = async (index: number) => {
|
||||
if (!sessionId) return
|
||||
const region = imageRegions[index]
|
||||
if (!region) return
|
||||
|
||||
setImageRegions(prev => prev.map((r, i) => i === index ? { ...r, generating: true } : r))
|
||||
|
||||
try {
|
||||
const resp = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/reconstruction/generate-image`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
region_index: index,
|
||||
prompt: region.prompt,
|
||||
style: region.style,
|
||||
}),
|
||||
}
|
||||
)
|
||||
if (!resp.ok) throw new Error(`Generation failed: ${resp.status}`)
|
||||
const data = await resp.json()
|
||||
|
||||
setImageRegions(prev => prev.map((r, i) =>
|
||||
i === index ? { ...r, image_b64: data.image_b64, generating: false } : r
|
||||
))
|
||||
} catch (e) {
|
||||
setImageRegions(prev => prev.map((r, i) => i === index ? { ...r, generating: false } : r))
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
}
|
||||
}
|
||||
|
||||
// Save validation
|
||||
const handleSave = async () => {
|
||||
if (!sessionId) {
|
||||
setError('Keine Session-ID vorhanden')
|
||||
return
|
||||
}
|
||||
setStatus('saving')
|
||||
setError('')
|
||||
try {
|
||||
const resp = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/reconstruction/validate`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ notes, score: score ?? 0 }),
|
||||
}
|
||||
)
|
||||
if (!resp.ok) {
|
||||
const body = await resp.text().catch(() => '')
|
||||
throw new Error(`Speichern fehlgeschlagen (${resp.status}): ${body}`)
|
||||
}
|
||||
setStatus('saved')
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
setStatus('ready')
|
||||
}
|
||||
}
|
||||
|
||||
// Mark/update ground truth reference
|
||||
const handleMarkGroundTruth = async () => {
|
||||
if (!sessionId) return
|
||||
setGtSaving(true)
|
||||
setGtMessage('')
|
||||
try {
|
||||
const resp = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/mark-ground-truth?pipeline=ocr-pipeline`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
if (!resp.ok) {
|
||||
const body = await resp.text().catch(() => '')
|
||||
throw new Error(`Ground Truth fehlgeschlagen (${resp.status}): ${body}`)
|
||||
}
|
||||
const data = await resp.json()
|
||||
setIsGroundTruth(true)
|
||||
setGtMessage(`Ground Truth gespeichert (${data.cells_saved} Zellen)`)
|
||||
setTimeout(() => setGtMessage(''), 5000)
|
||||
} catch (e) {
|
||||
setGtMessage(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setGtSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle manual region drawing on reconstruction
|
||||
const handleReconMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||
if (!drawingRegion) return
|
||||
const rect = e.currentTarget.getBoundingClientRect()
|
||||
const x = ((e.clientX - rect.left) / rect.width) * 100
|
||||
const y = ((e.clientY - rect.top) / rect.height) * 100
|
||||
setDragStart({ x, y })
|
||||
setDragEnd({ x, y })
|
||||
}
|
||||
|
||||
const handleReconMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||
if (!dragStart) return
|
||||
const rect = e.currentTarget.getBoundingClientRect()
|
||||
const x = ((e.clientX - rect.left) / rect.width) * 100
|
||||
const y = ((e.clientY - rect.top) / rect.height) * 100
|
||||
setDragEnd({ x, y })
|
||||
}
|
||||
|
||||
const handleReconMouseUp = () => {
|
||||
if (!dragStart || !dragEnd) return
|
||||
const x = Math.min(dragStart.x, dragEnd.x)
|
||||
const y = Math.min(dragStart.y, dragEnd.y)
|
||||
const w = Math.abs(dragEnd.x - dragStart.x)
|
||||
const h = Math.abs(dragEnd.y - dragStart.y)
|
||||
|
||||
if (w > 2 && h > 2) {
|
||||
setImageRegions(prev => [...prev, {
|
||||
bbox_pct: { x, y, w, h },
|
||||
prompt: '',
|
||||
description: 'Manually selected region',
|
||||
image_b64: null,
|
||||
style: 'educational' as ImageStyle,
|
||||
}])
|
||||
}
|
||||
|
||||
setDragStart(null)
|
||||
setDragEnd(null)
|
||||
setDrawingRegion(false)
|
||||
}
|
||||
|
||||
const handleRemoveRegion = (index: number) => {
|
||||
setImageRegions(prev => prev.filter((_, i) => i !== index))
|
||||
}
|
||||
|
||||
if (status === 'loading') {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-500 mr-3" />
|
||||
<span className="text-gray-500 dark:text-gray-400">Session wird geladen...</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (status === 'error' && !session) {
|
||||
return (
|
||||
<div className="text-center py-16">
|
||||
<p className="text-red-500">{error}</p>
|
||||
<button onClick={loadSessionData} className="mt-4 px-4 py-2 bg-teal-600 text-white rounded hover:bg-teal-700">
|
||||
Erneut laden
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!session) return null
|
||||
|
||||
const aspect = session.imageHeight / session.imageWidth
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-16 text-center">
|
||||
<div className="text-5xl mb-4">✅</div>
|
||||
<h3 className="text-lg font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
Schritt 7: Ground Truth Validierung
|
||||
</h3>
|
||||
<p className="text-gray-500 dark:text-gray-400 max-w-md">
|
||||
Gesamtpruefung der rekonstruierten Seite gegen das Original.
|
||||
Dieser Schritt wird in einer zukuenftigen Version implementiert.
|
||||
</p>
|
||||
<div className="mt-6 px-4 py-2 bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 rounded-full text-sm font-medium">
|
||||
Kommt bald
|
||||
<div className="space-y-4">
|
||||
{/* Header / Controls */}
|
||||
<div className="flex items-center justify-between flex-wrap gap-2">
|
||||
<h3 className="text-lg font-medium text-gray-800 dark:text-gray-200">
|
||||
Validierung — Original vs. Rekonstruktion
|
||||
</h3>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={handleDetectImages}
|
||||
disabled={detecting}
|
||||
className="px-3 py-1.5 text-sm bg-indigo-600 text-white rounded hover:bg-indigo-700 disabled:opacity-50"
|
||||
>
|
||||
{detecting ? 'Erkennung laeuft...' : 'Bilder erkennen'}
|
||||
</button>
|
||||
<label className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={syncScroll}
|
||||
onChange={e => setSyncScroll(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
Sync Scroll
|
||||
</label>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<button onClick={() => setZoom(z => Math.max(50, z - 25))} className="px-2 py-1 text-sm border rounded dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700">-</button>
|
||||
<span className="text-sm text-gray-600 dark:text-gray-400 w-12 text-center">{zoom}%</span>
|
||||
<button onClick={() => setZoom(z => Math.min(200, z + 25))} className="px-2 py-1 text-sm border rounded dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700">+</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-2 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 text-sm rounded">
|
||||
{error}
|
||||
<button onClick={() => setError('')} className="ml-2 underline">Schliessen</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Side-by-side panels */}
|
||||
<div className="grid grid-cols-2 gap-4" style={{ height: 'calc(100vh - 580px)', minHeight: 300 }}>
|
||||
{/* Left: Original */}
|
||||
<div className="border rounded-lg dark:border-gray-700 overflow-hidden flex flex-col">
|
||||
<div className="px-3 py-1.5 bg-gray-50 dark:bg-gray-800 text-sm font-medium text-gray-600 dark:text-gray-400 border-b dark:border-gray-700">
|
||||
Original
|
||||
</div>
|
||||
<div
|
||||
ref={leftPanelRef}
|
||||
className="flex-1 overflow-auto"
|
||||
onScroll={() => handleScroll('left')}
|
||||
>
|
||||
<div style={{ width: `${zoom}%`, minWidth: '100%' }}>
|
||||
<img
|
||||
src={session.originalImageUrl}
|
||||
alt="Original"
|
||||
className="w-full h-auto"
|
||||
draggable={false}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Reconstruction */}
|
||||
<div className="border rounded-lg dark:border-gray-700 overflow-hidden flex flex-col">
|
||||
<div className="px-3 py-1.5 bg-gray-50 dark:bg-gray-800 text-sm font-medium text-gray-600 dark:text-gray-400 border-b dark:border-gray-700 flex items-center justify-between">
|
||||
<span>Rekonstruktion</span>
|
||||
<button
|
||||
onClick={() => setDrawingRegion(!drawingRegion)}
|
||||
className={`text-xs px-2 py-0.5 rounded ${drawingRegion ? 'bg-indigo-600 text-white' : 'bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400'}`}
|
||||
>
|
||||
{drawingRegion ? 'Region zeichnen...' : '+ Region'}
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
ref={rightPanelRef}
|
||||
className="flex-1 overflow-auto"
|
||||
onScroll={() => handleScroll('right')}
|
||||
>
|
||||
<div style={{ width: `${zoom}%`, minWidth: '100%' }}>
|
||||
{/* Reconstruction container */}
|
||||
<div
|
||||
ref={reconRef}
|
||||
className="relative bg-white"
|
||||
style={{
|
||||
paddingBottom: `${aspect * 100}%`,
|
||||
cursor: drawingRegion ? 'crosshair' : 'default',
|
||||
}}
|
||||
onMouseDown={handleReconMouseDown}
|
||||
onMouseMove={handleReconMouseMove}
|
||||
onMouseUp={handleReconMouseUp}
|
||||
>
|
||||
{/* Row separator lines — derive from cells */}
|
||||
{(() => {
|
||||
const rowYs = new Set<number>()
|
||||
for (const cell of session.cells) {
|
||||
if (cell.col_index === 0 && cell.bbox_pct) {
|
||||
rowYs.add(cell.bbox_pct.y)
|
||||
}
|
||||
}
|
||||
return Array.from(rowYs).map((y, i) => (
|
||||
<div
|
||||
key={`row-${i}`}
|
||||
className="absolute left-0 right-0"
|
||||
style={{
|
||||
top: `${y}%`,
|
||||
height: '1px',
|
||||
backgroundColor: 'rgba(0,0,0,0.06)',
|
||||
}}
|
||||
/>
|
||||
))
|
||||
})()}
|
||||
|
||||
{/* Cell texts — black on white, font size derived from cell height */}
|
||||
{session.cells.map(cell => {
|
||||
if (!cell.bbox_pct || !cell.text) return null
|
||||
// Container height in px = reconWidth * aspect
|
||||
// Cell height in px = containerHeightPx * (bbox_pct.h / 100)
|
||||
// Font size ≈ 70% of cell height
|
||||
const containerH = reconWidth * aspect
|
||||
const cellHeightPx = containerH * (cell.bbox_pct.h / 100)
|
||||
const fontSize = Math.max(6, cellHeightPx * 0.7)
|
||||
return (
|
||||
<span
|
||||
key={cell.cell_id}
|
||||
className="absolute leading-none overflow-hidden whitespace-nowrap"
|
||||
style={{
|
||||
left: `${cell.bbox_pct.x}%`,
|
||||
top: `${cell.bbox_pct.y}%`,
|
||||
width: `${cell.bbox_pct.w}%`,
|
||||
height: `${cell.bbox_pct.h}%`,
|
||||
color: '#1a1a1a',
|
||||
fontSize: `${fontSize}px`,
|
||||
fontWeight: cell.is_bold ? 'bold' : 'normal',
|
||||
fontFamily: "'Liberation Sans', 'DejaVu Sans', Arial, sans-serif",
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
padding: '0 1px',
|
||||
}}
|
||||
title={`${cell.cell_id}: ${cell.text}`}
|
||||
>
|
||||
{cell.text}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Generated images at region positions */}
|
||||
{imageRegions.map((region, i) => (
|
||||
<div
|
||||
key={`region-${i}`}
|
||||
className="absolute border-2 border-dashed border-indigo-400"
|
||||
style={{
|
||||
left: `${region.bbox_pct.x}%`,
|
||||
top: `${region.bbox_pct.y}%`,
|
||||
width: `${region.bbox_pct.w}%`,
|
||||
height: `${region.bbox_pct.h}%`,
|
||||
}}
|
||||
>
|
||||
{region.image_b64 ? (
|
||||
<img src={region.image_b64} alt={region.description} className="w-full h-full object-cover" />
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center bg-indigo-50/50 text-indigo-400 text-[0.5em]">
|
||||
{region.generating ? '...' : `Bild ${i + 1}`}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Drawing rectangle */}
|
||||
{dragStart && dragEnd && (
|
||||
<div
|
||||
className="absolute border-2 border-dashed border-red-500 bg-red-100/20 pointer-events-none"
|
||||
style={{
|
||||
left: `${Math.min(dragStart.x, dragEnd.x)}%`,
|
||||
top: `${Math.min(dragStart.y, dragEnd.y)}%`,
|
||||
width: `${Math.abs(dragEnd.x - dragStart.x)}%`,
|
||||
height: `${Math.abs(dragEnd.y - dragStart.y)}%`,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Image regions panel */}
|
||||
{imageRegions.length > 0 && (
|
||||
<div className="border rounded-lg dark:border-gray-700 p-4">
|
||||
<h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
|
||||
Bildbereiche ({imageRegions.length} gefunden)
|
||||
</h4>
|
||||
<div className="space-y-3">
|
||||
{imageRegions.map((region, i) => (
|
||||
<div key={i} className="flex items-start gap-3 p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
|
||||
{/* Preview thumbnail */}
|
||||
<div className="w-16 h-16 flex-shrink-0 border rounded dark:border-gray-600 overflow-hidden bg-white">
|
||||
{region.image_b64 ? (
|
||||
<img src={region.image_b64} alt="" className="w-full h-full object-cover" />
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center text-gray-400 text-xs">
|
||||
{Math.round(region.bbox_pct.w)}x{Math.round(region.bbox_pct.h)}%
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Prompt + controls */}
|
||||
<div className="flex-1 min-w-0 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400 flex-shrink-0">
|
||||
Bereich {i + 1}:
|
||||
</span>
|
||||
<input
|
||||
type="text"
|
||||
value={region.prompt}
|
||||
onChange={e => {
|
||||
setImageRegions(prev => prev.map((r, j) =>
|
||||
j === i ? { ...r, prompt: e.target.value } : r
|
||||
))
|
||||
}}
|
||||
placeholder="Beschreibung / Prompt..."
|
||||
className="flex-1 text-sm px-2 py-1 border rounded dark:border-gray-600 dark:bg-gray-700 dark:text-white"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<select
|
||||
value={region.style}
|
||||
onChange={e => {
|
||||
setImageRegions(prev => prev.map((r, j) =>
|
||||
j === i ? { ...r, style: e.target.value as ImageStyle } : r
|
||||
))
|
||||
}}
|
||||
className="text-sm px-2 py-1 border rounded dark:border-gray-600 dark:bg-gray-700 dark:text-white"
|
||||
>
|
||||
{STYLES.map(s => (
|
||||
<option key={s.value} value={s.value}>{s.label}</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
onClick={() => handleGenerateImage(i)}
|
||||
disabled={!!region.generating || !region.prompt}
|
||||
className="px-3 py-1 text-sm bg-teal-600 text-white rounded hover:bg-teal-700 disabled:opacity-50"
|
||||
>
|
||||
{region.generating ? 'Generiere...' : 'Generieren'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleRemoveRegion(i)}
|
||||
className="px-2 py-1 text-sm text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded"
|
||||
>
|
||||
Entfernen
|
||||
</button>
|
||||
</div>
|
||||
{region.description && region.description !== region.prompt && (
|
||||
<p className="text-xs text-gray-400">{region.description}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Notes and score */}
|
||||
<div className="border rounded-lg dark:border-gray-700 p-4 space-y-3">
|
||||
<div className="flex items-center gap-4">
|
||||
<label className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
Bewertung (1-10):
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={10}
|
||||
value={score ?? ''}
|
||||
onChange={e => setScore(e.target.value ? parseInt(e.target.value) : null)}
|
||||
className="w-20 text-sm px-2 py-1 border rounded dark:border-gray-600 dark:bg-gray-700 dark:text-white"
|
||||
/>
|
||||
<div className="flex gap-1">
|
||||
{[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(v => (
|
||||
<button
|
||||
key={v}
|
||||
onClick={() => setScore(v)}
|
||||
className={`w-7 h-7 text-xs rounded ${score === v ? 'bg-teal-600 text-white' : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600'}`}
|
||||
>
|
||||
{v}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium text-gray-700 dark:text-gray-300 block mb-1">
|
||||
Notizen:
|
||||
</label>
|
||||
<textarea
|
||||
value={notes}
|
||||
onChange={e => setNotes(e.target.value)}
|
||||
rows={3}
|
||||
placeholder="Anmerkungen zur Qualitaet der Rekonstruktion..."
|
||||
className="w-full text-sm px-3 py-2 border rounded dark:border-gray-600 dark:bg-gray-700 dark:text-white"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions — sticky bottom bar */}
|
||||
<div className="sticky bottom-0 bg-white dark:bg-gray-900 border-t dark:border-gray-700 py-3 px-1 -mx-1 flex items-center justify-between">
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{status === 'saved' && <span className="text-green-600 dark:text-green-400">Validierung gespeichert</span>}
|
||||
{status === 'saving' && <span>Speichere...</span>}
|
||||
{gtMessage && (
|
||||
<span className={gtMessage.includes('fehlgeschlagen') ? 'text-red-500' : 'text-amber-600 dark:text-amber-400'}>
|
||||
{gtMessage}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={handleMarkGroundTruth}
|
||||
disabled={gtSaving || status === 'saving'}
|
||||
className="px-4 py-2 text-sm bg-amber-600 text-white rounded hover:bg-amber-700 disabled:opacity-50"
|
||||
>
|
||||
{gtSaving ? 'Speichere...' : isGroundTruth ? 'Ground Truth aktualisieren' : 'Als Ground Truth markieren'}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={status === 'saving'}
|
||||
className="px-4 py-2 text-sm bg-gray-600 text-white rounded hover:bg-gray-700 disabled:opacity-50"
|
||||
>
|
||||
Speichern
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
await handleSave()
|
||||
onNext()
|
||||
}}
|
||||
disabled={status === 'saving'}
|
||||
className="px-4 py-2 text-sm bg-teal-600 text-white rounded hover:bg-teal-700 disabled:opacity-50"
|
||||
>
|
||||
Abschliessen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { GridResult, WordEntry, ColumnMeta } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { GridCell, GridResult, WordEntry, ColumnMeta } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
import { usePixelWordPositions } from './usePixelWordPositions'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
@@ -36,6 +37,7 @@ const FIELD_LABELS: Record<string, string> = {
|
||||
example: 'Beispiel',
|
||||
source_page: 'Seite',
|
||||
marker: 'Marker',
|
||||
text: 'Text',
|
||||
}
|
||||
|
||||
/** Map column type to WordEntry field name */
|
||||
@@ -45,6 +47,7 @@ const COL_TYPE_TO_FIELD: Record<string, string> = {
|
||||
column_example: 'example',
|
||||
page_ref: 'source_page',
|
||||
column_marker: 'marker',
|
||||
column_text: 'text',
|
||||
}
|
||||
|
||||
/** Column type → color class */
|
||||
@@ -54,6 +57,7 @@ const COL_TYPE_COLOR: Record<string, string> = {
|
||||
column_example: 'text-orange-600 dark:text-orange-400',
|
||||
page_ref: 'text-cyan-600 dark:text-cyan-400',
|
||||
column_marker: 'text-gray-500 dark:text-gray-400',
|
||||
column_text: 'text-gray-700 dark:text-gray-300',
|
||||
}
|
||||
|
||||
type RowStatus = 'pending' | 'active' | 'reviewed' | 'corrected' | 'skipped'
|
||||
@@ -80,9 +84,35 @@ export function StepLlmReview({ sessionId, onNext }: StepLlmReviewProps) {
|
||||
// Image
|
||||
const [imageNaturalSize, setImageNaturalSize] = useState<{ w: number; h: number } | null>(null)
|
||||
|
||||
// Overlay view state
|
||||
const [viewMode, setViewMode] = useState<'table' | 'overlay'>('table')
|
||||
const [fontScale, setFontScale] = useState(0.7)
|
||||
const [leftPaddingPct, setLeftPaddingPct] = useState(0)
|
||||
const [globalBold, setGlobalBold] = useState(false)
|
||||
const [cells, setCells] = useState<GridCell[]>([])
|
||||
const reconRef = useRef<HTMLDivElement>(null)
|
||||
const [reconWidth, setReconWidth] = useState(0)
|
||||
|
||||
// Pixel-analysed word positions via shared hook
|
||||
const overlayImageUrl = sessionId
|
||||
? `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
: ''
|
||||
const cellWordPositions = usePixelWordPositions(overlayImageUrl, cells, viewMode === 'overlay')
|
||||
|
||||
const tableRef = useRef<HTMLDivElement>(null)
|
||||
const activeRowRef = useRef<HTMLTableRowElement>(null)
|
||||
|
||||
// Track reconstruction container width for font size calculation
|
||||
useEffect(() => {
|
||||
const el = reconRef.current
|
||||
if (!el) return
|
||||
const obs = new ResizeObserver(entries => {
|
||||
for (const entry of entries) setReconWidth(entry.contentRect.width)
|
||||
})
|
||||
obs.observe(el)
|
||||
return () => obs.disconnect()
|
||||
}, [viewMode])
|
||||
|
||||
// Load session data on mount
|
||||
useEffect(() => {
|
||||
if (!sessionId) return
|
||||
@@ -108,6 +138,7 @@ export function StepLlmReview({ sessionId, onNext }: StepLlmReviewProps) {
|
||||
const entries = wordResult.vocab_entries || wordResult.entries || []
|
||||
setVocabEntries(entries)
|
||||
setColumnsUsed(wordResult.columns_used || [])
|
||||
setCells(wordResult.cells || [])
|
||||
|
||||
// Check if LLM review was already run
|
||||
const llmReview = wordResult.llm_review
|
||||
@@ -320,9 +351,31 @@ export function StepLlmReview({ sessionId, onNext }: StepLlmReviewProps) {
|
||||
}
|
||||
|
||||
const dewarpedUrl = sessionId
|
||||
? `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/dewarped`
|
||||
? `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
: ''
|
||||
|
||||
// Snap all cells in the same column to consistent x/w positions
|
||||
// Uses the median x and width per col_index so columns align vertically
|
||||
const colPositions = useMemo(() => {
|
||||
const byCol = new Map<number, { xs: number[]; ws: number[] }>()
|
||||
for (const cell of cells) {
|
||||
if (!cell.bbox_pct) continue
|
||||
const entry = byCol.get(cell.col_index) || { xs: [], ws: [] }
|
||||
entry.xs.push(cell.bbox_pct.x)
|
||||
entry.ws.push(cell.bbox_pct.w)
|
||||
byCol.set(cell.col_index, entry)
|
||||
}
|
||||
const result = new Map<number, { x: number; w: number }>()
|
||||
for (const [colIdx, { xs, ws }] of byCol) {
|
||||
xs.sort((a, b) => a - b)
|
||||
ws.sort((a, b) => a - b)
|
||||
const medianX = xs[Math.floor(xs.length / 2)]
|
||||
const medianW = ws[Math.floor(ws.length / 2)]
|
||||
result.set(colIdx, { x: medianX, w: medianW })
|
||||
}
|
||||
return result
|
||||
}, [cells])
|
||||
|
||||
if (!sessionId) {
|
||||
return <div className="text-center py-12 text-gray-400">Bitte zuerst eine Session auswaehlen.</div>
|
||||
}
|
||||
@@ -380,6 +433,22 @@ export function StepLlmReview({ sessionId, onNext }: StepLlmReviewProps) {
|
||||
|
||||
const pct = progress ? Math.round((progress.current / progress.total) * 100) : 0
|
||||
|
||||
/** Handle inline edit of a cell in the overlay */
|
||||
const handleCellEdit = (cellId: string, rowIndex: number, newText: string | null) => {
|
||||
if (newText === null) return
|
||||
setCells(prev => prev.map(c => c.cell_id === cellId ? { ...c, text: newText } : c))
|
||||
// Also update vocabEntries if this cell maps to a known field
|
||||
const cell = cells.find(c => c.cell_id === cellId)
|
||||
if (cell) {
|
||||
const field = COL_TYPE_TO_FIELD[cell.col_type]
|
||||
if (field) {
|
||||
setVocabEntries(prev => prev.map((e, i) =>
|
||||
i === rowIndex ? { ...e, [field]: newText } : e
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Ready / Running / Done: 2-column layout ---
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -436,8 +505,66 @@ export function StepLlmReview({ sessionId, onNext }: StepLlmReviewProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 2-column layout: Image + Table */}
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{/* View mode toggle */}
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => setViewMode('table')}
|
||||
className={`px-3 py-1.5 text-xs rounded-l-lg border transition-colors ${
|
||||
viewMode === 'table'
|
||||
? 'bg-teal-600 text-white border-teal-600'
|
||||
: 'bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-400 border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
Tabelle
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setViewMode('overlay')}
|
||||
className={`px-3 py-1.5 text-xs rounded-r-lg border transition-colors ${
|
||||
viewMode === 'overlay'
|
||||
? 'bg-teal-600 text-white border-teal-600'
|
||||
: 'bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-400 border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
>
|
||||
Overlay
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Overlay toolbar */}
|
||||
{viewMode === 'overlay' && (
|
||||
<div className="flex items-center gap-4 flex-wrap bg-gray-50 dark:bg-gray-800/50 rounded-lg px-3 py-2">
|
||||
<label className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400">
|
||||
Schrift
|
||||
<input
|
||||
type="range" min={30} max={120} value={Math.round(fontScale * 100)}
|
||||
onChange={e => setFontScale(Number(e.target.value) / 100)}
|
||||
className="w-24 h-1 accent-teal-600"
|
||||
/>
|
||||
<span className="w-8 text-right font-mono">{Math.round(fontScale * 100)}%</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400">
|
||||
Einrueckung
|
||||
<input
|
||||
type="range" min={0} max={20} step={0.5} value={leftPaddingPct}
|
||||
onChange={e => setLeftPaddingPct(Number(e.target.value))}
|
||||
className="w-24 h-1 accent-teal-600"
|
||||
/>
|
||||
<span className="w-8 text-right font-mono">{leftPaddingPct}%</span>
|
||||
</label>
|
||||
<button
|
||||
onClick={() => setGlobalBold(b => !b)}
|
||||
className={`px-2 py-1 text-xs rounded border transition-colors font-bold ${
|
||||
globalBold
|
||||
? 'bg-teal-600 text-white border-teal-600'
|
||||
: 'bg-white dark:bg-gray-700 text-gray-600 dark:text-gray-400 border-gray-300 dark:border-gray-600'
|
||||
}`}
|
||||
>
|
||||
B
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 2-column layout: Image + Table/Overlay */}
|
||||
<div className={`grid gap-4 ${viewMode === 'overlay' ? 'grid-cols-2' : 'grid-cols-3'}`}>
|
||||
{/* Left: Dewarped Image with highlight overlay */}
|
||||
<div className="col-span-1">
|
||||
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
|
||||
@@ -469,93 +596,181 @@ export function StepLlmReview({ sessionId, onNext }: StepLlmReviewProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Full vocabulary table */}
|
||||
<div className="col-span-2" ref={tableRef}>
|
||||
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
|
||||
Vokabeltabelle ({vocabEntries.length} Eintraege)
|
||||
</div>
|
||||
<div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
|
||||
<div className="max-h-[70vh] overflow-y-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 z-10">
|
||||
<tr className="bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
|
||||
<th className="px-2 py-2 text-left text-gray-500 dark:text-gray-400 font-medium w-10">#</th>
|
||||
{columnsUsed.length > 0 ? (
|
||||
columnsUsed.map((col, i) => {
|
||||
const field = COL_TYPE_TO_FIELD[col.type]
|
||||
if (!field) return null
|
||||
return (
|
||||
<th key={i} className={`px-2 py-2 text-left font-medium ${COL_TYPE_COLOR[col.type] || 'text-gray-500 dark:text-gray-400'}`}>
|
||||
{FIELD_LABELS[field] || field}
|
||||
</th>
|
||||
)
|
||||
})
|
||||
) : (
|
||||
<>
|
||||
<th className="px-2 py-2 text-left text-gray-500 dark:text-gray-400 font-medium">EN</th>
|
||||
<th className="px-2 py-2 text-left text-gray-500 dark:text-gray-400 font-medium">DE</th>
|
||||
<th className="px-2 py-2 text-left text-gray-500 dark:text-gray-400 font-medium">Beispiel</th>
|
||||
</>
|
||||
)}
|
||||
<th className="px-2 py-2 text-center text-gray-500 dark:text-gray-400 font-medium w-16">Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{vocabEntries.map((entry, idx) => {
|
||||
const rowStatus = getRowStatus(idx)
|
||||
const rowChanges = correctedMap.get(idx)
|
||||
|
||||
const rowBg = {
|
||||
pending: '',
|
||||
active: 'bg-yellow-50 dark:bg-yellow-900/20',
|
||||
reviewed: '',
|
||||
corrected: 'bg-teal-50/50 dark:bg-teal-900/10',
|
||||
skipped: 'bg-gray-50 dark:bg-gray-800/50',
|
||||
}[rowStatus]
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={idx}
|
||||
ref={rowStatus === 'active' ? activeRowRef : undefined}
|
||||
className={`border-b border-gray-100 dark:border-gray-700/50 ${rowBg} ${
|
||||
rowStatus === 'active' ? 'ring-1 ring-yellow-400 ring-inset' : ''
|
||||
}`}
|
||||
>
|
||||
<td className="px-2 py-1.5 text-gray-400 font-mono text-xs">{idx}</td>
|
||||
{/* Right: Table or Overlay */}
|
||||
<div className={viewMode === 'table' ? 'col-span-2' : 'col-span-1'} ref={tableRef}>
|
||||
{viewMode === 'table' ? (
|
||||
<>
|
||||
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
|
||||
{columnsUsed.length === 1 && columnsUsed[0]?.type === 'column_text' ? 'Tabelle' : 'Vokabeltabelle'} ({vocabEntries.length} Eintraege)
|
||||
</div>
|
||||
<div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
|
||||
<div className="max-h-[70vh] overflow-y-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 z-10">
|
||||
<tr className="bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
|
||||
<th className="px-2 py-2 text-left text-gray-500 dark:text-gray-400 font-medium w-10">#</th>
|
||||
{columnsUsed.length > 0 ? (
|
||||
columnsUsed.map((col, i) => {
|
||||
const field = COL_TYPE_TO_FIELD[col.type]
|
||||
if (!field) return null
|
||||
const text = (entry as Record<string, unknown>)[field] as string || ''
|
||||
return (
|
||||
<td key={i} className="px-2 py-1.5 text-xs">
|
||||
<CellContent text={text} field={field} rowChanges={rowChanges} />
|
||||
</td>
|
||||
<th key={i} className={`px-2 py-2 text-left font-medium ${COL_TYPE_COLOR[col.type] || 'text-gray-500 dark:text-gray-400'}`}>
|
||||
{FIELD_LABELS[field] || field}
|
||||
</th>
|
||||
)
|
||||
})
|
||||
) : (
|
||||
<>
|
||||
<td className="px-2 py-1.5">
|
||||
<CellContent text={entry.english} field="english" rowChanges={rowChanges} />
|
||||
</td>
|
||||
<td className="px-2 py-1.5">
|
||||
<CellContent text={entry.german} field="german" rowChanges={rowChanges} />
|
||||
</td>
|
||||
<td className="px-2 py-1.5 text-xs">
|
||||
<CellContent text={entry.example} field="example" rowChanges={rowChanges} />
|
||||
</td>
|
||||
<th className="px-2 py-2 text-left text-gray-500 dark:text-gray-400 font-medium">EN</th>
|
||||
<th className="px-2 py-2 text-left text-gray-500 dark:text-gray-400 font-medium">DE</th>
|
||||
<th className="px-2 py-2 text-left text-gray-500 dark:text-gray-400 font-medium">Beispiel</th>
|
||||
</>
|
||||
)}
|
||||
<td className="px-2 py-1.5 text-center">
|
||||
<StatusIcon status={rowStatus} />
|
||||
</td>
|
||||
<th className="px-2 py-2 text-center text-gray-500 dark:text-gray-400 font-medium w-16">Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{vocabEntries.map((entry, idx) => {
|
||||
const rowStatus = getRowStatus(idx)
|
||||
const rowChanges = correctedMap.get(idx)
|
||||
|
||||
const rowBg = {
|
||||
pending: '',
|
||||
active: 'bg-yellow-50 dark:bg-yellow-900/20',
|
||||
reviewed: '',
|
||||
corrected: 'bg-teal-50/50 dark:bg-teal-900/10',
|
||||
skipped: 'bg-gray-50 dark:bg-gray-800/50',
|
||||
}[rowStatus]
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={idx}
|
||||
ref={rowStatus === 'active' ? activeRowRef : undefined}
|
||||
className={`border-b border-gray-100 dark:border-gray-700/50 ${rowBg} ${
|
||||
rowStatus === 'active' ? 'ring-1 ring-yellow-400 ring-inset' : ''
|
||||
}`}
|
||||
>
|
||||
<td className="px-2 py-1.5 text-gray-400 font-mono text-xs">{idx}</td>
|
||||
{columnsUsed.length > 0 ? (
|
||||
columnsUsed.map((col, i) => {
|
||||
const field = COL_TYPE_TO_FIELD[col.type]
|
||||
if (!field) return null
|
||||
const text = (entry as Record<string, unknown>)[field] as string || ''
|
||||
return (
|
||||
<td key={i} className="px-2 py-1.5 text-xs">
|
||||
<CellContent text={text} field={field} rowChanges={rowChanges} />
|
||||
</td>
|
||||
)
|
||||
})
|
||||
) : (
|
||||
<>
|
||||
<td className="px-2 py-1.5">
|
||||
<CellContent text={entry.english} field="english" rowChanges={rowChanges} />
|
||||
</td>
|
||||
<td className="px-2 py-1.5">
|
||||
<CellContent text={entry.german} field="german" rowChanges={rowChanges} />
|
||||
</td>
|
||||
<td className="px-2 py-1.5 text-xs">
|
||||
<CellContent text={entry.example} field="example" rowChanges={rowChanges} />
|
||||
</td>
|
||||
</>
|
||||
)}
|
||||
<td className="px-2 py-1.5 text-center">
|
||||
<StatusIcon status={rowStatus} />
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
|
||||
Text-Rekonstruktion ({cells.filter(c => c.text).length} Zellen)
|
||||
</div>
|
||||
<div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden bg-white dark:bg-white">
|
||||
<div
|
||||
ref={reconRef}
|
||||
className="relative"
|
||||
style={{
|
||||
aspectRatio: imageNaturalSize ? `${imageNaturalSize.w} / ${imageNaturalSize.h}` : '3 / 4',
|
||||
}}
|
||||
>
|
||||
{cells.map(cell => {
|
||||
if (!cell.bbox_pct || !cell.text) return null
|
||||
const col = colPositions.get(cell.col_index)
|
||||
const cellX = col?.x ?? cell.bbox_pct.x
|
||||
const cellW = col?.w ?? cell.bbox_pct.w
|
||||
const aspect = imageNaturalSize ? imageNaturalSize.h / imageNaturalSize.w : 4 / 3
|
||||
const containerH = reconWidth * aspect
|
||||
const cellHeightPx = containerH * (cell.bbox_pct.h / 100)
|
||||
|
||||
const wordPos = cellWordPositions.get(cell.cell_id)
|
||||
|
||||
// Pixel-analysed: render word-groups at detected positions
|
||||
if (wordPos) {
|
||||
return wordPos.map((wp, i) => {
|
||||
// Auto font-size from pixel analysis, scaled by user slider
|
||||
const autoFontPx = cellHeightPx * wp.fontRatio * fontScale
|
||||
const fs = Math.max(6, autoFontPx)
|
||||
return (
|
||||
<span
|
||||
key={`${cell.cell_id}_${i}`}
|
||||
className="absolute leading-none pointer-events-none select-none"
|
||||
style={{
|
||||
left: `${wp.xPct}%`,
|
||||
top: `${cell.bbox_pct.y}%`,
|
||||
width: `${wp.wPct}%`,
|
||||
height: `${cell.bbox_pct.h}%`,
|
||||
fontSize: `${fs}px`,
|
||||
fontWeight: globalBold ? 'bold' : (cell.is_bold ? 'bold' : 'normal'),
|
||||
fontFamily: "'Liberation Sans', Arial, sans-serif",
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'visible',
|
||||
color: '#1a1a1a',
|
||||
}}
|
||||
>
|
||||
{wp.text}
|
||||
</span>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// Fallback: no pixel data — single span for entire cell
|
||||
const fontSize = Math.max(6, cellHeightPx * fontScale)
|
||||
return (
|
||||
<span
|
||||
key={cell.cell_id}
|
||||
className="absolute leading-none pointer-events-none select-none"
|
||||
style={{
|
||||
left: `${cellX}%`,
|
||||
top: `${cell.bbox_pct.y}%`,
|
||||
width: `${cellW}%`,
|
||||
height: `${cell.bbox_pct.h}%`,
|
||||
fontSize: `${fontSize}px`,
|
||||
fontWeight: globalBold ? 'bold' : (cell.is_bold ? 'bold' : 'normal'),
|
||||
paddingLeft: `${leftPaddingPct}%`,
|
||||
fontFamily: "'Liberation Sans', Arial, sans-serif",
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
whiteSpace: 'pre',
|
||||
overflow: 'visible',
|
||||
color: '#1a1a1a',
|
||||
}}
|
||||
>
|
||||
{cell.text}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
326
admin-lehrer/components/ocr-pipeline/StepOrientation.tsx
Normal file
326
admin-lehrer/components/ocr-pipeline/StepOrientation.tsx
Normal file
@@ -0,0 +1,326 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import type { OrientationResult, SessionInfo } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
import { ImageCompareView } from './ImageCompareView'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface PageSplitResult {
|
||||
multi_page: boolean
|
||||
page_count?: number
|
||||
sub_sessions?: { id: string; name: string; page_index: number }[]
|
||||
used_original?: boolean
|
||||
duration_seconds?: number
|
||||
}
|
||||
|
||||
interface StepOrientationProps {
|
||||
sessionId?: string | null
|
||||
onNext: (sessionId: string) => void
|
||||
onSessionList?: () => void
|
||||
}
|
||||
|
||||
export function StepOrientation({ sessionId: existingSessionId, onNext, onSessionList }: StepOrientationProps) {
|
||||
const [session, setSession] = useState<SessionInfo | null>(null)
|
||||
const [orientationResult, setOrientationResult] = useState<OrientationResult | null>(null)
|
||||
const [pageSplitResult, setPageSplitResult] = useState<PageSplitResult | null>(null)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const [detecting, setDetecting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [dragOver, setDragOver] = useState(false)
|
||||
const [sessionName, setSessionName] = useState('')
|
||||
|
||||
// Reload session data when navigating back — auto-trigger orientation if missing
|
||||
useEffect(() => {
|
||||
if (!existingSessionId || session) return
|
||||
|
||||
const loadSession = async () => {
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${existingSessionId}`)
|
||||
if (!res.ok) return
|
||||
const data = await res.json()
|
||||
|
||||
const sessionInfo: SessionInfo = {
|
||||
session_id: data.session_id,
|
||||
filename: data.filename,
|
||||
image_width: data.image_width,
|
||||
image_height: data.image_height,
|
||||
original_image_url: `${KLAUSUR_API}${data.original_image_url}`,
|
||||
}
|
||||
setSession(sessionInfo)
|
||||
|
||||
if (data.orientation_result) {
|
||||
setOrientationResult(data.orientation_result)
|
||||
} else {
|
||||
// Session exists but orientation not yet run (e.g. page-split session)
|
||||
// Auto-trigger orientation detection
|
||||
setDetecting(true)
|
||||
try {
|
||||
const orientRes = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${existingSessionId}/orientation`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
if (orientRes.ok) {
|
||||
const orientData = await orientRes.json()
|
||||
setOrientationResult({
|
||||
orientation_degrees: orientData.orientation_degrees,
|
||||
corrected: orientData.corrected,
|
||||
duration_seconds: orientData.duration_seconds,
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Auto-orientation failed:', e)
|
||||
} finally {
|
||||
setDetecting(false)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to reload session:', e)
|
||||
}
|
||||
}
|
||||
|
||||
loadSession()
|
||||
}, [existingSessionId, session])
|
||||
|
||||
const handleUpload = useCallback(async (file: File) => {
|
||||
setUploading(true)
|
||||
setError(null)
|
||||
setOrientationResult(null)
|
||||
|
||||
try {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
if (sessionName.trim()) {
|
||||
formData.append('name', sessionName.trim())
|
||||
}
|
||||
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ detail: res.statusText }))
|
||||
throw new Error(err.detail || 'Upload fehlgeschlagen')
|
||||
}
|
||||
|
||||
const data: SessionInfo = await res.json()
|
||||
data.original_image_url = `${KLAUSUR_API}${data.original_image_url}`
|
||||
setSession(data)
|
||||
|
||||
// Auto-trigger orientation detection
|
||||
setDetecting(true)
|
||||
const orientRes = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${data.session_id}/orientation`, {
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
if (!orientRes.ok) {
|
||||
throw new Error('Orientierungserkennung fehlgeschlagen')
|
||||
}
|
||||
|
||||
const orientData = await orientRes.json()
|
||||
setOrientationResult({
|
||||
orientation_degrees: orientData.orientation_degrees,
|
||||
corrected: orientData.corrected,
|
||||
duration_seconds: orientData.duration_seconds,
|
||||
})
|
||||
|
||||
// Auto-trigger page-split detection (double-page book spreads)
|
||||
try {
|
||||
const splitRes = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${data.session_id}/page-split`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
if (splitRes.ok) {
|
||||
const splitData: PageSplitResult = await splitRes.json()
|
||||
setPageSplitResult(splitData)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Page-split detection failed:', e)
|
||||
// Not critical — continue as single page
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
|
||||
} finally {
|
||||
setUploading(false)
|
||||
setDetecting(false)
|
||||
}
|
||||
}, [sessionName])
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setDragOver(false)
|
||||
const file = e.dataTransfer.files[0]
|
||||
if (file) handleUpload(file)
|
||||
}, [handleUpload])
|
||||
|
||||
const handleFileInput = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) handleUpload(file)
|
||||
}, [handleUpload])
|
||||
|
||||
// Upload area (no session yet)
|
||||
if (!session) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Session name input */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-600 dark:text-gray-400 mb-1">
|
||||
Session-Name (optional)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={sessionName}
|
||||
onChange={(e) => setSessionName(e.target.value)}
|
||||
placeholder="z.B. Unit 3 Seite 42"
|
||||
className="w-full max-w-sm px-3 py-2 text-sm border rounded-lg dark:bg-gray-800 dark:border-gray-600 dark:text-gray-200 focus:outline-none focus:ring-2 focus:ring-teal-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
onDragOver={(e) => { e.preventDefault(); setDragOver(true) }}
|
||||
onDragLeave={() => setDragOver(false)}
|
||||
onDrop={handleDrop}
|
||||
className={`border-2 border-dashed rounded-xl p-12 text-center transition-colors ${
|
||||
dragOver
|
||||
? 'border-teal-400 bg-teal-50 dark:bg-teal-900/20'
|
||||
: 'border-gray-300 dark:border-gray-600 hover:border-teal-400'
|
||||
}`}
|
||||
>
|
||||
{uploading ? (
|
||||
<div className="text-gray-500">
|
||||
<div className="animate-spin inline-block w-8 h-8 border-2 border-teal-500 border-t-transparent rounded-full mb-3" />
|
||||
<p>Wird hochgeladen...</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-4xl mb-3">📄</div>
|
||||
<p className="text-gray-600 dark:text-gray-400 mb-2">
|
||||
PDF oder Bild hierher ziehen
|
||||
</p>
|
||||
<p className="text-sm text-gray-400 mb-4">oder</p>
|
||||
<label className="inline-block px-4 py-2 bg-teal-600 text-white rounded-lg cursor-pointer hover:bg-teal-700 transition-colors">
|
||||
Datei auswaehlen
|
||||
<input
|
||||
type="file"
|
||||
accept=".pdf,.png,.jpg,.jpeg,.tiff,.tif"
|
||||
onChange={handleFileInput}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-lg text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Session active: show orientation result
|
||||
const orientedUrl = orientationResult
|
||||
? `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${session.session_id}/image/oriented`
|
||||
: null
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Filename */}
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
Datei: <span className="font-medium text-gray-700 dark:text-gray-300">{session.filename}</span>
|
||||
{' '}({session.image_width} x {session.image_height} px)
|
||||
</div>
|
||||
|
||||
{/* Loading indicator */}
|
||||
{detecting && (
|
||||
<div className="flex items-center gap-2 text-teal-600 dark:text-teal-400 text-sm">
|
||||
<div className="animate-spin w-4 h-4 border-2 border-teal-500 border-t-transparent rounded-full" />
|
||||
Orientierung wird erkannt...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Image comparison */}
|
||||
<ImageCompareView
|
||||
originalUrl={session.original_image_url}
|
||||
deskewedUrl={orientedUrl}
|
||||
showGrid={false}
|
||||
showBinarized={false}
|
||||
binarizedUrl={null}
|
||||
leftLabel="Original"
|
||||
rightLabel="Orientiert"
|
||||
/>
|
||||
|
||||
{/* Orientation result badge */}
|
||||
{orientationResult && (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
|
||||
<div className="flex items-center gap-3 text-sm">
|
||||
{orientationResult.corrected ? (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-400 text-xs font-medium">
|
||||
🔄 {orientationResult.orientation_degrees}° korrigiert
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-400 text-xs font-medium">
|
||||
✓ 0° (keine Drehung noetig)
|
||||
</span>
|
||||
)}
|
||||
<span className="text-gray-400 text-xs">
|
||||
{orientationResult.duration_seconds}s
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Page-split result */}
|
||||
{pageSplitResult?.multi_page && (
|
||||
<div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-700 p-4">
|
||||
<div className="text-sm font-medium text-blue-700 dark:text-blue-300">
|
||||
Doppelseite erkannt — {pageSplitResult.page_count} unabhaengige Sessions erstellt
|
||||
</div>
|
||||
<p className="text-xs text-blue-600 dark:text-blue-400 mt-1">
|
||||
Jede Seite wird als eigene Session durch die Pipeline verarbeitet.
|
||||
{pageSplitResult.used_original && ' (Seitentrennung auf dem Originalbild, da die Orientierung die Doppelseite gedreht hat.)'}
|
||||
</p>
|
||||
<div className="flex gap-2 mt-2">
|
||||
{pageSplitResult.sub_sessions?.map((s) => (
|
||||
<span
|
||||
key={s.id}
|
||||
className="text-xs px-2 py-1 rounded-md bg-blue-100 dark:bg-blue-800/40 text-blue-700 dark:text-blue-300"
|
||||
>
|
||||
{s.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Next button */}
|
||||
{orientationResult && (
|
||||
<div className="flex justify-end">
|
||||
{pageSplitResult?.multi_page ? (
|
||||
<button
|
||||
onClick={() => onSessionList?.()}
|
||||
className="px-6 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 font-medium transition-colors"
|
||||
>
|
||||
Zur Session-Liste →
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => onNext(session.session_id)}
|
||||
className="px-6 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 font-medium transition-colors"
|
||||
>
|
||||
Weiter →
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-lg text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import dynamic from 'next/dynamic'
|
||||
import type { GridResult, GridCell, WordEntry } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import type { GridResult, GridCell, ColumnResult, RowResult, PageZone, PageRegion, RowItem, StructureResult, StructureBox, StructureGraphic } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
import { usePixelWordPositions } from './usePixelWordPositions'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
@@ -12,7 +13,7 @@ const FabricReconstructionCanvas = dynamic(
|
||||
{ ssr: false, loading: () => <div className="py-8 text-center text-sm text-gray-400">Editor wird geladen...</div> }
|
||||
)
|
||||
|
||||
type EditorMode = 'simple' | 'editor'
|
||||
type EditorMode = 'simple' | 'editor' | 'overlay'
|
||||
|
||||
interface StepReconstructionProps {
|
||||
sessionId: string | null
|
||||
@@ -46,11 +47,47 @@ export function StepReconstruction({ sessionId, onNext }: StepReconstructionProp
|
||||
const [undoStack, setUndoStack] = useState<UndoAction[]>([])
|
||||
const [redoStack, setRedoStack] = useState<UndoAction[]>([])
|
||||
|
||||
// (allCells removed — cells now contains all cells including empty ones)
|
||||
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const imageRef = useRef<HTMLImageElement>(null)
|
||||
|
||||
// Overlay mode state
|
||||
const [isParentWithBoxes, setIsParentWithBoxes] = useState(false)
|
||||
const [mergedGridCells, setMergedGridCells] = useState<GridCell[]>([])
|
||||
const [parentColumns, setParentColumns] = useState<PageRegion[]>([])
|
||||
const [parentRows, setParentRows] = useState<RowItem[]>([])
|
||||
const [parentZones, setParentZones] = useState<PageZone[]>([])
|
||||
const [imageNaturalSize, setImageNaturalSize] = useState<{ w: number; h: number } | null>(null)
|
||||
const [fontScale, setFontScale] = useState(0.7)
|
||||
const [globalBold, setGlobalBold] = useState(false)
|
||||
const [imageRotation, setImageRotation] = useState<0 | 180>(0)
|
||||
const [structureBoxes, setStructureBoxes] = useState<StructureBox[]>([])
|
||||
const [structureGraphics, setStructureGraphics] = useState<StructureGraphic[]>([])
|
||||
const [showStructure, setShowStructure] = useState(true)
|
||||
const reconRef = useRef<HTMLDivElement>(null)
|
||||
const [reconWidth, setReconWidth] = useState(0)
|
||||
|
||||
// Pixel-based word positions for overlay mode
|
||||
const overlayImageUrl = sessionId
|
||||
? `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
: ''
|
||||
const cellWordPositions = usePixelWordPositions(
|
||||
overlayImageUrl,
|
||||
mergedGridCells,
|
||||
editorMode === 'overlay',
|
||||
imageRotation,
|
||||
)
|
||||
|
||||
// Track reconstruction container width for font size calculation
|
||||
useEffect(() => {
|
||||
const el = reconRef.current
|
||||
if (!el) return
|
||||
const obs = new ResizeObserver(entries => {
|
||||
for (const entry of entries) setReconWidth(entry.contentRect.width)
|
||||
})
|
||||
obs.observe(el)
|
||||
return () => obs.disconnect()
|
||||
}, [editorMode])
|
||||
|
||||
// Load session data on mount
|
||||
useEffect(() => {
|
||||
if (!sessionId) return
|
||||
@@ -58,12 +95,15 @@ export function StepReconstruction({ sessionId, onNext }: StepReconstructionProp
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [sessionId])
|
||||
|
||||
// Track image natural height for font scaling
|
||||
// Track image natural dimensions for font scaling and structure layer
|
||||
const handleImageLoad = useCallback(() => {
|
||||
if (imageRef.current) {
|
||||
setImageNaturalH(imageRef.current.naturalHeight)
|
||||
if (!imageNaturalSize) {
|
||||
setImageNaturalSize({ w: imageRef.current.naturalWidth, h: imageRef.current.naturalHeight })
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
}, [imageNaturalSize])
|
||||
|
||||
const loadSessionData = async () => {
|
||||
if (!sessionId) return
|
||||
@@ -97,6 +137,108 @@ export function StepReconstruction({ sessionId, onNext }: StepReconstructionProp
|
||||
setEditedTexts(new Map())
|
||||
setUndoStack([])
|
||||
setRedoStack([])
|
||||
|
||||
// Load structure result (boxes, graphics, colors)
|
||||
const structureResult: StructureResult | undefined = data.structure_result
|
||||
if (structureResult) {
|
||||
setStructureBoxes(structureResult.boxes || [])
|
||||
setStructureGraphics(structureResult.graphics || [])
|
||||
}
|
||||
|
||||
// Check for parent with boxes (sub-sessions + zones)
|
||||
const columnResult: ColumnResult | undefined = data.column_result
|
||||
const rowResult: RowResult | undefined = data.row_result
|
||||
const subSessions: { id: string; box_index: number }[] = data.sub_sessions || []
|
||||
const zones: PageZone[] = columnResult?.zones || []
|
||||
const hasBoxes = subSessions.length > 0 && zones.some(z => z.zone_type === 'box')
|
||||
|
||||
setIsParentWithBoxes(hasBoxes)
|
||||
if (hasBoxes) setImageRotation(180) // Default: rotate for correct pixel matching
|
||||
|
||||
if (columnResult?.columns) setParentColumns(columnResult.columns)
|
||||
if (rowResult?.rows) setParentRows(rowResult.rows)
|
||||
if (zones.length > 0) setParentZones(zones)
|
||||
|
||||
// Store image dimensions
|
||||
if (wordResult.image_width && wordResult.image_height) {
|
||||
setImageNaturalSize({ w: wordResult.image_width, h: wordResult.image_height })
|
||||
}
|
||||
|
||||
if (hasBoxes) {
|
||||
// Default to overlay mode for parent sessions with boxes
|
||||
setEditorMode('overlay')
|
||||
|
||||
// Load sub-sessions and merge cells
|
||||
const imgW = wordResult.image_width || 1
|
||||
const imgH = wordResult.image_height || 1
|
||||
const allMergedCells: GridCell[] = [...rawGridCells]
|
||||
|
||||
for (const sub of subSessions) {
|
||||
try {
|
||||
const subRes = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sub.id}`)
|
||||
if (!subRes.ok) continue
|
||||
const subData = await subRes.json()
|
||||
const subWordResult: GridResult | undefined = subData.word_result
|
||||
if (!subWordResult?.cells) continue
|
||||
|
||||
// Find the box zone for this sub-session
|
||||
const boxZone = zones.find(z => z.zone_type === 'box')
|
||||
if (!boxZone?.box) continue
|
||||
|
||||
const box = boxZone.box
|
||||
// Box coordinates are in pixels, convert to pct
|
||||
const boxXPct = (box.x / imgW) * 100
|
||||
const boxYPct = (box.y / imgH) * 100
|
||||
const boxWPct = (box.width / imgW) * 100
|
||||
const boxHPct = (box.height / imgH) * 100
|
||||
|
||||
// Convert sub-session cell coordinates to parent coordinates
|
||||
for (const subCell of subWordResult.cells) {
|
||||
if (!subCell.bbox_pct) continue
|
||||
const parentCellX = boxXPct + (subCell.bbox_pct.x / 100) * boxWPct
|
||||
const parentCellY = boxYPct + (subCell.bbox_pct.y / 100) * boxHPct
|
||||
const parentCellW = (subCell.bbox_pct.w / 100) * boxWPct
|
||||
const parentCellH = (subCell.bbox_pct.h / 100) * boxHPct
|
||||
|
||||
allMergedCells.push({
|
||||
...subCell,
|
||||
cell_id: `sub_${sub.id}_${subCell.cell_id}`,
|
||||
bbox_pct: {
|
||||
x: parentCellX,
|
||||
y: parentCellY,
|
||||
w: parentCellW,
|
||||
h: parentCellH,
|
||||
},
|
||||
bbox_px: {
|
||||
x: Math.round(parentCellX / 100 * imgW),
|
||||
y: Math.round(parentCellY / 100 * imgH),
|
||||
w: Math.round(parentCellW / 100 * imgW),
|
||||
h: Math.round(parentCellH / 100 * imgH),
|
||||
},
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
// Skip failing sub-sessions
|
||||
}
|
||||
}
|
||||
|
||||
setMergedGridCells(allMergedCells)
|
||||
|
||||
// Also add merged cells as editable cells
|
||||
const mergedEditableCells: EditableCell[] = allMergedCells.map(c => ({
|
||||
cellId: c.cell_id,
|
||||
text: c.text,
|
||||
originalText: c.text,
|
||||
bboxPct: c.bbox_pct,
|
||||
colType: c.col_type,
|
||||
rowIndex: c.row_index,
|
||||
colIndex: c.col_index,
|
||||
}))
|
||||
setCells(mergedEditableCells)
|
||||
} else {
|
||||
setMergedGridCells(rawGridCells)
|
||||
}
|
||||
|
||||
setStatus('ready')
|
||||
} catch (e: unknown) {
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
@@ -276,7 +418,7 @@ export function StepReconstruction({ sessionId, onNext }: StepReconstructionProp
|
||||
}, [])
|
||||
|
||||
const dewarpedUrl = sessionId
|
||||
? `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/dewarped`
|
||||
? `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
: ''
|
||||
|
||||
const colTypeColor = (colType: string): string => {
|
||||
@@ -298,6 +440,20 @@ export function StepReconstruction({ sessionId, onNext }: StepReconstructionProp
|
||||
return Math.max(8, Math.min(18, px * (zoom / 100)))
|
||||
}, [imageNaturalH, zoom])
|
||||
|
||||
// Box zones in percent for clamping cell positions in overlay mode
|
||||
const boxZonesPct = useMemo(() =>
|
||||
parentZones
|
||||
.filter(z => z.zone_type === 'box' && z.box)
|
||||
.map(z => {
|
||||
const imgH = imageNaturalSize?.h || 1
|
||||
return {
|
||||
topPct: (z.box!.y / imgH) * 100,
|
||||
bottomPct: ((z.box!.y + z.box!.height) / imgH) * 100,
|
||||
}
|
||||
}),
|
||||
[parentZones, imageNaturalSize]
|
||||
)
|
||||
|
||||
if (!sessionId) {
|
||||
return <div className="text-center py-12 text-gray-400">Bitte zuerst eine Session auswaehlen.</div>
|
||||
}
|
||||
@@ -347,6 +503,305 @@ export function StepReconstruction({ sessionId, onNext }: StepReconstructionProp
|
||||
)
|
||||
}
|
||||
|
||||
// Clamp cell positions so they don't overlap with box zones
|
||||
const adjustCellForBoxZones = (
|
||||
bboxPct: { x: number; y: number; w: number; h: number },
|
||||
cellId: string,
|
||||
): { x: number; y: number; w: number; h: number } => {
|
||||
// Sub-session cells (inside box) → no adjustment
|
||||
if (cellId.startsWith('sub_')) return bboxPct
|
||||
if (boxZonesPct.length === 0) return bboxPct
|
||||
|
||||
const cellTop = bboxPct.y
|
||||
const cellBottom = bboxPct.y + bboxPct.h
|
||||
const boxMid = (boxZonesPct[0].topPct + boxZonesPct[0].bottomPct) / 2
|
||||
|
||||
for (const { topPct, bottomPct } of boxZonesPct) {
|
||||
// Check if cell overlaps with box zone at all
|
||||
if (cellBottom <= topPct || cellTop >= bottomPct) continue
|
||||
|
||||
// Cell starts ABOVE box midpoint → belongs above, clamp bottom to box top
|
||||
if (cellTop < boxMid) {
|
||||
return { ...bboxPct, h: Math.max(0.5, topPct - cellTop) }
|
||||
}
|
||||
// Cell starts AT or BELOW box midpoint → belongs below, push top to box bottom
|
||||
return { ...bboxPct, y: bottomPct, h: Math.max(0.5, cellBottom - bottomPct) }
|
||||
}
|
||||
return bboxPct
|
||||
}
|
||||
|
||||
// Structure layer: boxes and graphic elements as background
|
||||
const renderStructureLayer = (imgW: number, imgH: number) => {
|
||||
if (!showStructure) return null
|
||||
const hasElements = structureBoxes.length > 0 || structureGraphics.length > 0
|
||||
if (!hasElements) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Structure boxes */}
|
||||
{structureBoxes.map((box, i) => {
|
||||
const bgColor = box.bg_color_hex || '#6b7280'
|
||||
return (
|
||||
<div
|
||||
key={`sbox-${i}`}
|
||||
className="absolute pointer-events-none"
|
||||
style={{
|
||||
left: `${(box.x / imgW) * 100}%`,
|
||||
top: `${(box.y / imgH) * 100}%`,
|
||||
width: `${(box.w / imgW) * 100}%`,
|
||||
height: `${(box.h / imgH) * 100}%`,
|
||||
border: `${Math.max(1, box.border_thickness)}px solid ${bgColor}40`,
|
||||
backgroundColor: `${bgColor}0a`,
|
||||
borderRadius: '2px',
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Graphic elements */}
|
||||
{structureGraphics.map((g, i) => (
|
||||
<div
|
||||
key={`sgfx-${i}`}
|
||||
className="absolute pointer-events-none"
|
||||
style={{
|
||||
left: `${(g.x / imgW) * 100}%`,
|
||||
top: `${(g.y / imgH) * 100}%`,
|
||||
width: `${(g.w / imgW) * 100}%`,
|
||||
height: `${(g.h / imgH) * 100}%`,
|
||||
border: `1px dashed ${g.color_hex}60`,
|
||||
backgroundColor: `${g.color_hex}08`,
|
||||
borderRadius: '2px',
|
||||
}}
|
||||
>
|
||||
<span
|
||||
className="absolute text-[8px] leading-none opacity-50"
|
||||
style={{
|
||||
top: '1px',
|
||||
left: '2px',
|
||||
color: g.color_hex,
|
||||
}}
|
||||
>
|
||||
{g.shape === 'illustration' ? 'Illust' : 'Bild'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// Overlay rendering helper
|
||||
const renderOverlayMode = () => {
|
||||
const imgW = imageNaturalSize?.w || 1
|
||||
const imgH = imageNaturalSize?.h || 1
|
||||
const aspect = imgH / imgW
|
||||
const containerH = reconWidth * aspect
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{/* Left: Original image */}
|
||||
<div>
|
||||
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
|
||||
Originalbild
|
||||
</div>
|
||||
<div className="border rounded-lg overflow-hidden dark:border-gray-700 bg-gray-50 dark:bg-gray-900 sticky top-4">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={dewarpedUrl}
|
||||
alt="Original"
|
||||
className="w-full h-auto"
|
||||
onLoad={(e) => {
|
||||
const img = e.target as HTMLImageElement
|
||||
setImageNaturalSize({ w: img.naturalWidth, h: img.naturalHeight })
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Reconstructed table overlay */}
|
||||
<div>
|
||||
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
|
||||
Rekonstruktion ({cells.length} Zellen)
|
||||
</div>
|
||||
<div className="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden bg-white">
|
||||
<div
|
||||
ref={reconRef}
|
||||
className="relative"
|
||||
style={{
|
||||
aspectRatio: `${imgW} / ${imgH}`,
|
||||
}}
|
||||
>
|
||||
{/* Column lines */}
|
||||
{parentColumns
|
||||
.filter(c => !['header', 'footer'].includes(c.type))
|
||||
.map((col, i) => (
|
||||
<div
|
||||
key={`col-${i}`}
|
||||
className="absolute top-0 bottom-0 border-l border-gray-300/50"
|
||||
style={{ left: `${(col.x / imgW) * 100}%` }}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Row lines */}
|
||||
{parentRows.map((row, i) => (
|
||||
<div
|
||||
key={`row-${i}`}
|
||||
className="absolute left-0 right-0 border-t border-gray-300/50"
|
||||
style={{ top: `${(row.y / imgH) * 100}%` }}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Box zone highlight */}
|
||||
{parentZones
|
||||
.filter(z => z.zone_type === 'box' && z.box)
|
||||
.map((z, i) => {
|
||||
const box = z.box!
|
||||
return (
|
||||
<div
|
||||
key={`box-${i}`}
|
||||
className="absolute border-2 border-blue-400/30 bg-blue-50/10 pointer-events-none"
|
||||
style={{
|
||||
left: `${(box.x / imgW) * 100}%`,
|
||||
top: `${(box.y / imgH) * 100}%`,
|
||||
width: `${(box.width / imgW) * 100}%`,
|
||||
height: `${(box.height / imgH) * 100}%`,
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Structure elements (boxes, graphics) */}
|
||||
{renderStructureLayer(imgW, imgH)}
|
||||
|
||||
{/* Pixel-positioned words / editable inputs */}
|
||||
{cells.map((cell) => {
|
||||
const displayText = getDisplayText(cell)
|
||||
const edited = isEdited(cell)
|
||||
const wordPos = cellWordPositions.get(cell.cellId)
|
||||
const adjBbox = adjustCellForBoxZones(cell.bboxPct, cell.cellId)
|
||||
const cellHeightPx = containerH * (adjBbox.h / 100)
|
||||
|
||||
// Pixel-analysed: render word-groups at detected positions as inputs
|
||||
if (wordPos && wordPos.length > 0) {
|
||||
return wordPos.map((wp, i) => {
|
||||
const autoFontPx = cellHeightPx * wp.fontRatio * fontScale
|
||||
const fs = Math.max(6, autoFontPx)
|
||||
|
||||
// For multi-group cells, only the first group is the primary input
|
||||
// Show as span (read-only positioned) — editing happens at cell level
|
||||
if (wordPos.length > 1) {
|
||||
return (
|
||||
<span
|
||||
key={`${cell.cellId}_wp_${i}`}
|
||||
className="absolute leading-none pointer-events-none select-none"
|
||||
style={{
|
||||
left: `${wp.xPct}%`,
|
||||
top: `${adjBbox.y}%`,
|
||||
width: `${wp.wPct}%`,
|
||||
height: `${adjBbox.h}%`,
|
||||
fontSize: `${fs}px`,
|
||||
fontWeight: globalBold ? 'bold' : (cell.colType === 'column_en' ? 'bold' : 'normal'),
|
||||
fontFamily: "'Liberation Sans', Arial, sans-serif",
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'visible',
|
||||
color: '#1a1a1a',
|
||||
}}
|
||||
>
|
||||
{wp.text}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// Single group: render as editable input at pixel position
|
||||
return (
|
||||
<div key={`${cell.cellId}_wp_${i}`} className="absolute group" style={{
|
||||
left: `${wp.xPct}%`,
|
||||
top: `${adjBbox.y}%`,
|
||||
width: `${wp.wPct}%`,
|
||||
height: `${adjBbox.h}%`,
|
||||
}}>
|
||||
<input
|
||||
id={`cell-${cell.cellId}`}
|
||||
type="text"
|
||||
value={displayText}
|
||||
onChange={(e) => handleTextChange(cell.cellId, e.target.value)}
|
||||
onKeyDown={(e) => handleKeyDown(e, cell.cellId)}
|
||||
className={`w-full h-full bg-transparent border-0 outline-none px-0 transition-colors ${
|
||||
edited ? 'bg-green-50/30' : ''
|
||||
}`}
|
||||
style={{
|
||||
fontSize: `${fs}px`,
|
||||
fontWeight: globalBold ? 'bold' : (cell.colType === 'column_en' ? 'bold' : 'normal'),
|
||||
fontFamily: "'Liberation Sans', Arial, sans-serif",
|
||||
lineHeight: '1',
|
||||
color: '#1a1a1a',
|
||||
}}
|
||||
title={`${cell.cellId} (${cell.colType})`}
|
||||
/>
|
||||
{edited && (
|
||||
<button
|
||||
onClick={() => resetCell(cell.cellId)}
|
||||
className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 text-white rounded-full text-[9px] leading-none opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
|
||||
title="Zuruecksetzen"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// Multi-group cell with pixel positions: already handled above
|
||||
// Fallback: no pixel data — single input at cell bbox
|
||||
if (!cell.text) return null
|
||||
|
||||
const fontSize = Math.max(6, cellHeightPx * fontScale)
|
||||
return (
|
||||
<div key={cell.cellId} className="absolute group" style={{
|
||||
left: `${adjBbox.x}%`,
|
||||
top: `${adjBbox.y}%`,
|
||||
width: `${adjBbox.w}%`,
|
||||
height: `${adjBbox.h}%`,
|
||||
}}>
|
||||
<input
|
||||
id={`cell-${cell.cellId}`}
|
||||
type="text"
|
||||
value={displayText}
|
||||
onChange={(e) => handleTextChange(cell.cellId, e.target.value)}
|
||||
onKeyDown={(e) => handleKeyDown(e, cell.cellId)}
|
||||
className={`w-full h-full bg-transparent border-0 outline-none px-0 transition-colors ${
|
||||
edited ? 'bg-green-50/30' : ''
|
||||
}`}
|
||||
style={{
|
||||
fontSize: `${fontSize}px`,
|
||||
fontWeight: globalBold ? 'bold' : 'normal',
|
||||
fontFamily: "'Liberation Sans', Arial, sans-serif",
|
||||
lineHeight: '1',
|
||||
color: '#1a1a1a',
|
||||
}}
|
||||
title={`${cell.cellId} (${cell.colType})`}
|
||||
/>
|
||||
{edited && (
|
||||
<button
|
||||
onClick={() => resetCell(cell.cellId)}
|
||||
className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 text-white rounded-full text-[9px] leading-none opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
|
||||
title="Zuruecksetzen"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Toolbar */}
|
||||
@@ -367,6 +822,18 @@ export function StepReconstruction({ sessionId, onNext }: StepReconstructionProp
|
||||
>
|
||||
Einfach
|
||||
</button>
|
||||
{isParentWithBoxes && (
|
||||
<button
|
||||
onClick={() => setEditorMode('overlay')}
|
||||
className={`px-2 py-0.5 transition-colors ${
|
||||
editorMode === 'overlay'
|
||||
? 'bg-teal-600 text-white'
|
||||
: 'hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-600 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
Overlay
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => setEditorMode('editor')}
|
||||
className={`px-2 py-0.5 transition-colors ${
|
||||
@@ -406,43 +873,113 @@ export function StepReconstruction({ sessionId, onNext }: StepReconstructionProp
|
||||
|
||||
<div className="w-px h-5 bg-gray-300 dark:bg-gray-600 mx-1" />
|
||||
|
||||
{/* Empty field toggle */}
|
||||
<button
|
||||
onClick={() => setShowEmptyHighlight(v => !v)}
|
||||
className={`px-2 py-1 text-xs border rounded transition-colors ${
|
||||
showEmptyHighlight
|
||||
? 'border-red-300 bg-red-50 text-red-600 dark:border-red-700 dark:bg-red-900/30 dark:text-red-400'
|
||||
: 'border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
title="Leere Pflichtfelder markieren"
|
||||
>
|
||||
Leer
|
||||
</button>
|
||||
{/* Overlay-specific toolbar */}
|
||||
{editorMode === 'overlay' && (
|
||||
<>
|
||||
<label className="flex items-center gap-1 text-xs text-gray-600 dark:text-gray-400">
|
||||
Schrift
|
||||
<input
|
||||
type="range" min={30} max={120} value={Math.round(fontScale * 100)}
|
||||
onChange={e => setFontScale(Number(e.target.value) / 100)}
|
||||
className="w-20 h-1 accent-teal-600"
|
||||
/>
|
||||
<span className="w-8 text-right font-mono">{Math.round(fontScale * 100)}%</span>
|
||||
</label>
|
||||
<button
|
||||
onClick={() => setGlobalBold(b => !b)}
|
||||
className={`px-2 py-1 text-xs rounded border transition-colors font-bold ${
|
||||
globalBold
|
||||
? 'bg-teal-600 text-white border-teal-600'
|
||||
: 'bg-white dark:bg-gray-700 text-gray-600 dark:text-gray-400 border-gray-300 dark:border-gray-600'
|
||||
}`}
|
||||
>
|
||||
B
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setImageRotation(r => r === 0 ? 180 : 0)}
|
||||
className={`px-2 py-1 text-xs rounded border transition-colors ${
|
||||
imageRotation === 180
|
||||
? 'bg-teal-600 text-white border-teal-600'
|
||||
: 'bg-white dark:bg-gray-700 text-gray-600 dark:text-gray-400 border-gray-300 dark:border-gray-600'
|
||||
}`}
|
||||
title="Bild 180° drehen"
|
||||
>
|
||||
180°
|
||||
</button>
|
||||
{(structureBoxes.length > 0 || structureGraphics.length > 0) && (
|
||||
<button
|
||||
onClick={() => setShowStructure(v => !v)}
|
||||
className={`px-2 py-1 text-xs border rounded transition-colors ${
|
||||
showStructure
|
||||
? 'border-violet-300 bg-violet-50 text-violet-600 dark:border-violet-700 dark:bg-violet-900/30 dark:text-violet-400'
|
||||
: 'border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
title="Strukturelemente anzeigen"
|
||||
>
|
||||
Struktur
|
||||
</button>
|
||||
)}
|
||||
<div className="w-px h-5 bg-gray-300 dark:bg-gray-600 mx-1" />
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="w-px h-5 bg-gray-300 dark:bg-gray-600 mx-1" />
|
||||
{/* Non-overlay controls */}
|
||||
{editorMode !== 'overlay' && (
|
||||
<>
|
||||
{/* Empty field toggle */}
|
||||
<button
|
||||
onClick={() => setShowEmptyHighlight(v => !v)}
|
||||
className={`px-2 py-1 text-xs border rounded transition-colors ${
|
||||
showEmptyHighlight
|
||||
? 'border-red-300 bg-red-50 text-red-600 dark:border-red-700 dark:bg-red-900/30 dark:text-red-400'
|
||||
: 'border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
title="Leere Pflichtfelder markieren"
|
||||
>
|
||||
Leer
|
||||
</button>
|
||||
|
||||
{/* Zoom controls */}
|
||||
<button
|
||||
onClick={() => setZoom(z => Math.max(50, z - 25))}
|
||||
className="px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700"
|
||||
>
|
||||
−
|
||||
</button>
|
||||
<span className="text-xs text-gray-500 w-10 text-center">{zoom}%</span>
|
||||
<button
|
||||
onClick={() => setZoom(z => Math.min(200, z + 25))}
|
||||
className="px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setZoom(100)}
|
||||
className="px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700"
|
||||
>
|
||||
Fit
|
||||
</button>
|
||||
{/* Structure toggle */}
|
||||
{(structureBoxes.length > 0 || structureGraphics.length > 0) && (
|
||||
<button
|
||||
onClick={() => setShowStructure(v => !v)}
|
||||
className={`px-2 py-1 text-xs border rounded transition-colors ${
|
||||
showStructure
|
||||
? 'border-violet-300 bg-violet-50 text-violet-600 dark:border-violet-700 dark:bg-violet-900/30 dark:text-violet-400'
|
||||
: 'border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
title="Strukturelemente anzeigen"
|
||||
>
|
||||
Struktur
|
||||
</button>
|
||||
)}
|
||||
|
||||
<div className="w-px h-5 bg-gray-300 dark:bg-gray-600 mx-1" />
|
||||
<div className="w-px h-5 bg-gray-300 dark:bg-gray-600 mx-1" />
|
||||
|
||||
{/* Zoom controls */}
|
||||
<button
|
||||
onClick={() => setZoom(z => Math.max(50, z - 25))}
|
||||
className="px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700"
|
||||
>
|
||||
−
|
||||
</button>
|
||||
<span className="text-xs text-gray-500 w-10 text-center">{zoom}%</span>
|
||||
<button
|
||||
onClick={() => setZoom(z => Math.min(200, z + 25))}
|
||||
className="px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setZoom(100)}
|
||||
className="px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-50 dark:hover:bg-gray-700"
|
||||
>
|
||||
Fit
|
||||
</button>
|
||||
|
||||
<div className="w-px h-5 bg-gray-300 dark:bg-gray-600 mx-1" />
|
||||
</>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={saveReconstruction}
|
||||
@@ -454,8 +991,10 @@ export function StepReconstruction({ sessionId, onNext }: StepReconstructionProp
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Reconstruction canvas — Simple or Editor mode */}
|
||||
{editorMode === 'editor' && sessionId ? (
|
||||
{/* Reconstruction canvas */}
|
||||
{editorMode === 'overlay' ? (
|
||||
renderOverlayMode()
|
||||
) : editorMode === 'editor' && sessionId ? (
|
||||
<FabricReconstructionCanvas
|
||||
sessionId={sessionId}
|
||||
cells={gridCells}
|
||||
@@ -479,6 +1018,9 @@ export function StepReconstruction({ sessionId, onNext }: StepReconstructionProp
|
||||
onLoad={handleImageLoad}
|
||||
/>
|
||||
|
||||
{/* Structure elements (boxes, graphics) */}
|
||||
{imageNaturalSize && renderStructureLayer(imageNaturalSize.w, imageNaturalSize.h)}
|
||||
|
||||
{/* Empty field markers */}
|
||||
{showEmptyHighlight && cells
|
||||
.filter(c => emptyCellIds.has(c.cellId))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import type { RowResult, RowGroundTruth } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import type { RowResult, RowGroundTruth } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
@@ -95,7 +95,7 @@ export function StepRowDetection({ sessionId, onNext }: StepRowDetectionProps) {
|
||||
}
|
||||
|
||||
const overlayUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/rows-overlay`
|
||||
const dewarpedUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/dewarped`
|
||||
const dewarpedUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
|
||||
const rowTypeColors: Record<string, string> = {
|
||||
header: 'bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300',
|
||||
|
||||
777
admin-lehrer/components/ocr-pipeline/StepStructureDetection.tsx
Normal file
777
admin-lehrer/components/ocr-pipeline/StepStructureDetection.tsx
Normal file
@@ -0,0 +1,777 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { ExcludeRegion, StructureResult } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
interface StepStructureDetectionProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
}
|
||||
|
||||
const COLOR_HEX: Record<string, string> = {
|
||||
red: '#dc2626',
|
||||
orange: '#ea580c',
|
||||
yellow: '#ca8a04',
|
||||
green: '#16a34a',
|
||||
blue: '#2563eb',
|
||||
purple: '#9333ea',
|
||||
}
|
||||
|
||||
type DetectionMethod = 'auto' | 'opencv' | 'ppdoclayout'
|
||||
|
||||
/** Color map for PP-DocLayout region classes */
|
||||
const DOCLAYOUT_CLASS_COLORS: Record<string, string> = {
|
||||
table: '#2563eb',
|
||||
figure: '#16a34a',
|
||||
title: '#ea580c',
|
||||
text: '#6b7280',
|
||||
list: '#9333ea',
|
||||
header: '#0ea5e9',
|
||||
footer: '#64748b',
|
||||
equation: '#dc2626',
|
||||
}
|
||||
|
||||
const DOCLAYOUT_DEFAULT_COLOR = '#a3a3a3'
|
||||
|
||||
function getDocLayoutColor(className: string): string {
|
||||
return DOCLAYOUT_CLASS_COLORS[className.toLowerCase()] || DOCLAYOUT_DEFAULT_COLOR
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a mouse event on the image container to image-pixel coordinates.
|
||||
* The image uses object-contain inside an A4-ratio container, so we need
|
||||
* to account for letterboxing.
|
||||
*/
|
||||
function mouseToImageCoords(
|
||||
e: React.MouseEvent,
|
||||
containerEl: HTMLElement,
|
||||
imgWidth: number,
|
||||
imgHeight: number,
|
||||
): { x: number; y: number } | null {
|
||||
const rect = containerEl.getBoundingClientRect()
|
||||
const containerW = rect.width
|
||||
const containerH = rect.height
|
||||
|
||||
// object-contain: image is scaled to fit, centered
|
||||
const scaleX = containerW / imgWidth
|
||||
const scaleY = containerH / imgHeight
|
||||
const scale = Math.min(scaleX, scaleY)
|
||||
|
||||
const renderedW = imgWidth * scale
|
||||
const renderedH = imgHeight * scale
|
||||
const offsetX = (containerW - renderedW) / 2
|
||||
const offsetY = (containerH - renderedH) / 2
|
||||
|
||||
const relX = e.clientX - rect.left - offsetX
|
||||
const relY = e.clientY - rect.top - offsetY
|
||||
|
||||
if (relX < 0 || relY < 0 || relX > renderedW || relY > renderedH) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
x: Math.round(relX / scale),
|
||||
y: Math.round(relY / scale),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert image-pixel coordinates to container-relative percentages
|
||||
* for overlay positioning.
|
||||
*/
|
||||
function imageToOverlayPct(
|
||||
region: { x: number; y: number; w: number; h: number },
|
||||
containerW: number,
|
||||
containerH: number,
|
||||
imgWidth: number,
|
||||
imgHeight: number,
|
||||
): { left: string; top: string; width: string; height: string } {
|
||||
const scaleX = containerW / imgWidth
|
||||
const scaleY = containerH / imgHeight
|
||||
const scale = Math.min(scaleX, scaleY)
|
||||
|
||||
const renderedW = imgWidth * scale
|
||||
const renderedH = imgHeight * scale
|
||||
const offsetX = (containerW - renderedW) / 2
|
||||
const offsetY = (containerH - renderedH) / 2
|
||||
|
||||
const left = offsetX + region.x * scale
|
||||
const top = offsetY + region.y * scale
|
||||
const width = region.w * scale
|
||||
const height = region.h * scale
|
||||
|
||||
return {
|
||||
left: `${(left / containerW) * 100}%`,
|
||||
top: `${(top / containerH) * 100}%`,
|
||||
width: `${(width / containerW) * 100}%`,
|
||||
height: `${(height / containerH) * 100}%`,
|
||||
}
|
||||
}
|
||||
|
||||
export function StepStructureDetection({ sessionId, onNext }: StepStructureDetectionProps) {
|
||||
const [result, setResult] = useState<StructureResult | null>(null)
|
||||
const [detecting, setDetecting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [hasRun, setHasRun] = useState(false)
|
||||
const [overlayTs, setOverlayTs] = useState(0)
|
||||
const [detectionMethod, setDetectionMethod] = useState<DetectionMethod>('auto')
|
||||
|
||||
// Exclude region drawing state
|
||||
const [excludeRegions, setExcludeRegions] = useState<ExcludeRegion[]>([])
|
||||
const [drawing, setDrawing] = useState(false)
|
||||
const [drawStart, setDrawStart] = useState<{ x: number; y: number } | null>(null)
|
||||
const [drawCurrent, setDrawCurrent] = useState<{ x: number; y: number } | null>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [drawMode, setDrawMode] = useState(false)
|
||||
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const overlayContainerRef = useRef<HTMLDivElement>(null)
|
||||
const [containerSize, setContainerSize] = useState({ w: 0, h: 0 })
|
||||
const [overlayContainerSize, setOverlayContainerSize] = useState({ w: 0, h: 0 })
|
||||
|
||||
// Track container size for overlay positioning
|
||||
useEffect(() => {
|
||||
const el = containerRef.current
|
||||
if (!el) return
|
||||
const obs = new ResizeObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
setContainerSize({ w: entry.contentRect.width, h: entry.contentRect.height })
|
||||
}
|
||||
})
|
||||
obs.observe(el)
|
||||
return () => obs.disconnect()
|
||||
}, [])
|
||||
|
||||
// Track overlay container size for PP-DocLayout region overlays
|
||||
useEffect(() => {
|
||||
const el = overlayContainerRef.current
|
||||
if (!el) return
|
||||
const obs = new ResizeObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
setOverlayContainerSize({ w: entry.contentRect.width, h: entry.contentRect.height })
|
||||
}
|
||||
})
|
||||
obs.observe(el)
|
||||
return () => obs.disconnect()
|
||||
}, [])
|
||||
|
||||
// Auto-trigger detection on mount
|
||||
useEffect(() => {
|
||||
if (!sessionId || hasRun) return
|
||||
setHasRun(true)
|
||||
|
||||
const runDetection = async () => {
|
||||
setDetecting(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const params = detectionMethod !== 'auto' ? `?method=${detectionMethod}` : ''
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/detect-structure${params}`, {
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error('Strukturerkennung fehlgeschlagen')
|
||||
}
|
||||
|
||||
const data = await res.json()
|
||||
setResult(data)
|
||||
setExcludeRegions(data.exclude_regions || [])
|
||||
setOverlayTs(Date.now())
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
|
||||
} finally {
|
||||
setDetecting(false)
|
||||
}
|
||||
}
|
||||
|
||||
runDetection()
|
||||
}, [sessionId, hasRun])
|
||||
|
||||
const handleRerun = async () => {
|
||||
if (!sessionId) return
|
||||
setDetecting(true)
|
||||
setError(null)
|
||||
try {
|
||||
const params = detectionMethod !== 'auto' ? `?method=${detectionMethod}` : ''
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/detect-structure${params}`, {
|
||||
method: 'POST',
|
||||
})
|
||||
if (!res.ok) throw new Error('Erneute Erkennung fehlgeschlagen')
|
||||
const data = await res.json()
|
||||
setResult(data)
|
||||
setExcludeRegions(data.exclude_regions || [])
|
||||
setOverlayTs(Date.now())
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
|
||||
} finally {
|
||||
setDetecting(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Save exclude regions to backend
|
||||
const saveExcludeRegions = useCallback(async (regions: ExcludeRegion[]) => {
|
||||
if (!sessionId) return
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/exclude-regions`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ regions }),
|
||||
})
|
||||
if (!res.ok) throw new Error('Speichern fehlgeschlagen')
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Speichern fehlgeschlagen')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}, [sessionId])
|
||||
|
||||
// Mouse handlers for drawing exclude rectangles
|
||||
const handleMouseDown = useCallback((e: React.MouseEvent) => {
|
||||
if (!drawMode || !containerRef.current || !result) return
|
||||
const coords = mouseToImageCoords(e, containerRef.current, result.image_width, result.image_height)
|
||||
if (coords) {
|
||||
setDrawing(true)
|
||||
setDrawStart(coords)
|
||||
setDrawCurrent(coords)
|
||||
}
|
||||
}, [drawMode, result])
|
||||
|
||||
const handleMouseMove = useCallback((e: React.MouseEvent) => {
|
||||
if (!drawing || !containerRef.current || !result) return
|
||||
const coords = mouseToImageCoords(e, containerRef.current, result.image_width, result.image_height)
|
||||
if (coords) {
|
||||
setDrawCurrent(coords)
|
||||
}
|
||||
}, [drawing, result])
|
||||
|
||||
const handleMouseUp = useCallback(() => {
|
||||
if (!drawing || !drawStart || !drawCurrent) {
|
||||
setDrawing(false)
|
||||
return
|
||||
}
|
||||
|
||||
const x = Math.min(drawStart.x, drawCurrent.x)
|
||||
const y = Math.min(drawStart.y, drawCurrent.y)
|
||||
const w = Math.abs(drawCurrent.x - drawStart.x)
|
||||
const h = Math.abs(drawCurrent.y - drawStart.y)
|
||||
|
||||
// Minimum size to avoid accidental clicks
|
||||
if (w > 10 && h > 10) {
|
||||
const newRegion: ExcludeRegion = { x, y, w, h, label: `Bereich ${excludeRegions.length + 1}` }
|
||||
const updated = [...excludeRegions, newRegion]
|
||||
setExcludeRegions(updated)
|
||||
saveExcludeRegions(updated)
|
||||
}
|
||||
|
||||
setDrawing(false)
|
||||
setDrawStart(null)
|
||||
setDrawCurrent(null)
|
||||
}, [drawing, drawStart, drawCurrent, excludeRegions, saveExcludeRegions])
|
||||
|
||||
const handleDeleteRegion = useCallback(async (index: number) => {
|
||||
if (!sessionId) return
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await fetch(`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/exclude-regions/${index}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
if (!res.ok) throw new Error('Loeschen fehlgeschlagen')
|
||||
const updated = excludeRegions.filter((_, i) => i !== index)
|
||||
setExcludeRegions(updated)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Loeschen fehlgeschlagen')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}, [sessionId, excludeRegions])
|
||||
|
||||
if (!sessionId) {
|
||||
return <div className="text-sm text-gray-400">Keine Session ausgewaehlt.</div>
|
||||
}
|
||||
|
||||
const croppedUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
const overlayUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/structure-overlay${overlayTs ? `?t=${overlayTs}` : ''}`
|
||||
|
||||
// Current drag rectangle in image coords
|
||||
const dragRect = drawing && drawStart && drawCurrent
|
||||
? {
|
||||
x: Math.min(drawStart.x, drawCurrent.x),
|
||||
y: Math.min(drawStart.y, drawCurrent.y),
|
||||
w: Math.abs(drawCurrent.x - drawStart.x),
|
||||
h: Math.abs(drawCurrent.y - drawStart.y),
|
||||
}
|
||||
: null
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Loading indicator */}
|
||||
{detecting && (
|
||||
<div className="flex items-center gap-2 text-teal-600 dark:text-teal-400 text-sm">
|
||||
<div className="animate-spin w-4 h-4 border-2 border-teal-500 border-t-transparent rounded-full" />
|
||||
Dokumentstruktur wird analysiert...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Detection method toggle */}
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-medium text-gray-500 dark:text-gray-400">Methode:</span>
|
||||
{(['auto', 'opencv', 'ppdoclayout'] as DetectionMethod[]).map((method) => (
|
||||
<button
|
||||
key={method}
|
||||
onClick={() => setDetectionMethod(method)}
|
||||
className={`px-3 py-1.5 text-xs rounded-md font-medium transition-colors ${
|
||||
detectionMethod === method
|
||||
? 'bg-teal-600 text-white'
|
||||
: 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
{method === 'auto' ? 'Auto' : method === 'opencv' ? 'OpenCV' : 'PP-DocLayout'}
|
||||
</button>
|
||||
))}
|
||||
<span className="text-[10px] text-gray-400 dark:text-gray-500 ml-1">
|
||||
{detectionMethod === 'auto'
|
||||
? 'PP-DocLayout wenn verfuegbar, sonst OpenCV'
|
||||
: detectionMethod === 'ppdoclayout'
|
||||
? 'ONNX-basierte Layouterkennung mit Klassifikation'
|
||||
: 'Klassische OpenCV-Konturerkennung'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Draw mode toggle */}
|
||||
{result && (
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => setDrawMode(!drawMode)}
|
||||
className={`px-4 py-2 text-sm rounded-lg font-medium transition-colors ${
|
||||
drawMode
|
||||
? 'bg-red-600 text-white hover:bg-red-700'
|
||||
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
{drawMode ? 'Zeichnen beenden' : 'Ausschlussbereich zeichnen'}
|
||||
</button>
|
||||
{drawMode && (
|
||||
<span className="text-xs text-red-600 dark:text-red-400">
|
||||
Rechteck auf dem Bild zeichnen um Bereiche von der OCR-Erkennung auszuschliessen
|
||||
</span>
|
||||
)}
|
||||
{saving && (
|
||||
<span className="text-xs text-gray-400">Speichern...</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Two-column image comparison */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
{/* Left: Original document with exclude region drawing */}
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Original {excludeRegions.length > 0 && `(${excludeRegions.length} Ausschlussbereich${excludeRegions.length !== 1 ? 'e' : ''})`}
|
||||
</div>
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={`relative bg-gray-100 dark:bg-gray-800 rounded-lg overflow-hidden ${
|
||||
drawMode ? 'cursor-crosshair' : ''
|
||||
}`}
|
||||
style={{ aspectRatio: '210/297' }}
|
||||
onMouseDown={handleMouseDown}
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseUp={handleMouseUp}
|
||||
onMouseLeave={() => {
|
||||
if (drawing) {
|
||||
handleMouseUp()
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={croppedUrl}
|
||||
alt="Originaldokument"
|
||||
className="w-full h-full object-contain pointer-events-none"
|
||||
draggable={false}
|
||||
onError={(e) => {
|
||||
(e.target as HTMLImageElement).style.display = 'none'
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Saved exclude regions overlay */}
|
||||
{result && containerSize.w > 0 && excludeRegions.map((region, i) => {
|
||||
const pos = imageToOverlayPct(region, containerSize.w, containerSize.h, result.image_width, result.image_height)
|
||||
return (
|
||||
<div
|
||||
key={i}
|
||||
className="absolute border-2 border-red-500 bg-red-500/20 group"
|
||||
style={pos}
|
||||
>
|
||||
<div className="absolute -top-5 left-0 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<span className="text-[10px] bg-red-600 text-white px-1 rounded whitespace-nowrap">
|
||||
{region.label || `Bereich ${i + 1}`}
|
||||
</span>
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); handleDeleteRegion(i) }}
|
||||
className="w-4 h-4 bg-red-600 text-white rounded-full text-[10px] flex items-center justify-center hover:bg-red-700"
|
||||
>
|
||||
x
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Current drag rectangle */}
|
||||
{dragRect && result && containerSize.w > 0 && (() => {
|
||||
const pos = imageToOverlayPct(dragRect, containerSize.w, containerSize.h, result.image_width, result.image_height)
|
||||
return (
|
||||
<div
|
||||
className="absolute border-2 border-red-500 border-dashed bg-red-500/15"
|
||||
style={pos}
|
||||
/>
|
||||
)
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Structure overlay */}
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Erkannte Struktur
|
||||
{result?.detection_method && (
|
||||
<span className="ml-2 text-[10px] font-normal normal-case">
|
||||
({result.detection_method === 'ppdoclayout' ? 'PP-DocLayout' : 'OpenCV'})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
ref={overlayContainerRef}
|
||||
className="relative bg-gray-100 dark:bg-gray-800 rounded-lg overflow-hidden"
|
||||
style={{ aspectRatio: '210/297' }}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={overlayUrl}
|
||||
alt="Strukturerkennung"
|
||||
className="w-full h-full object-contain"
|
||||
onError={(e) => {
|
||||
(e.target as HTMLImageElement).style.display = 'none'
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* PP-DocLayout region overlays with class colors and labels */}
|
||||
{result?.layout_regions && overlayContainerSize.w > 0 && result.layout_regions.map((region, i) => {
|
||||
const pos = imageToOverlayPct(region, overlayContainerSize.w, overlayContainerSize.h, result.image_width, result.image_height)
|
||||
const color = getDocLayoutColor(region.class_name)
|
||||
return (
|
||||
<div
|
||||
key={`layout-${i}`}
|
||||
className="absolute border-2 pointer-events-none"
|
||||
style={{
|
||||
...pos,
|
||||
borderColor: color,
|
||||
backgroundColor: `${color}18`,
|
||||
}}
|
||||
>
|
||||
<span
|
||||
className="absolute -top-4 left-0 px-1 py-px text-[9px] font-medium text-white rounded-sm whitespace-nowrap leading-tight"
|
||||
style={{ backgroundColor: color }}
|
||||
>
|
||||
{region.class_name} {Math.round(region.confidence * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* PP-DocLayout legend */}
|
||||
{result?.layout_regions && result.layout_regions.length > 0 && (() => {
|
||||
const usedClasses = [...new Set(result.layout_regions!.map((r) => r.class_name.toLowerCase()))]
|
||||
return (
|
||||
<div className="flex flex-wrap gap-x-3 gap-y-1 px-1">
|
||||
{usedClasses.sort().map((cls) => (
|
||||
<span key={cls} className="inline-flex items-center gap-1 text-[10px] text-gray-500 dark:text-gray-400">
|
||||
<span
|
||||
className="w-2.5 h-2.5 rounded-sm border"
|
||||
style={{
|
||||
backgroundColor: `${getDocLayoutColor(cls)}30`,
|
||||
borderColor: getDocLayoutColor(cls),
|
||||
}}
|
||||
/>
|
||||
{cls}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Exclude regions list */}
|
||||
{excludeRegions.length > 0 && (
|
||||
<div className="bg-red-50 dark:bg-red-900/10 rounded-lg border border-red-200 dark:border-red-800 p-3">
|
||||
<h4 className="text-xs font-medium text-red-700 dark:text-red-400 mb-2">
|
||||
Ausschlussbereiche ({excludeRegions.length}) — Woerter in diesen Bereichen werden nicht erkannt
|
||||
</h4>
|
||||
<div className="space-y-1">
|
||||
{excludeRegions.map((region, i) => (
|
||||
<div key={i} className="flex items-center gap-3 text-xs">
|
||||
<span className="w-3 h-3 rounded-sm flex-shrink-0 bg-red-500/30 border border-red-500" />
|
||||
<span className="text-red-700 dark:text-red-400 font-medium">
|
||||
{region.label || `Bereich ${i + 1}`}
|
||||
</span>
|
||||
<span className="font-mono text-red-600/70 dark:text-red-400/70">
|
||||
{region.w}x{region.h}px @ ({region.x}, {region.y})
|
||||
</span>
|
||||
<button
|
||||
onClick={() => handleDeleteRegion(i)}
|
||||
className="ml-auto text-red-500 hover:text-red-700 dark:hover:text-red-300"
|
||||
>
|
||||
Entfernen
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Result info */}
|
||||
{result && (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4 space-y-3">
|
||||
{/* Summary badges */}
|
||||
<div className="flex flex-wrap items-center gap-3 text-sm">
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-teal-50 dark:bg-teal-900/20 text-teal-700 dark:text-teal-400 text-xs font-medium">
|
||||
{result.zones.length} Zone(n)
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-400 text-xs font-medium">
|
||||
{result.boxes.length} Box(en)
|
||||
</span>
|
||||
{result.layout_regions && result.layout_regions.length > 0 && (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-indigo-50 dark:bg-indigo-900/20 text-indigo-700 dark:text-indigo-400 text-xs font-medium">
|
||||
{result.layout_regions.length} Layout-Region(en)
|
||||
</span>
|
||||
)}
|
||||
{result.graphics && result.graphics.length > 0 && (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-purple-50 dark:bg-purple-900/20 text-purple-700 dark:text-purple-400 text-xs font-medium">
|
||||
{result.graphics.length} Grafik(en)
|
||||
</span>
|
||||
)}
|
||||
{result.has_words && (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-400 text-xs font-medium">
|
||||
{result.word_count} Woerter
|
||||
</span>
|
||||
)}
|
||||
{excludeRegions.length > 0 && (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-400 text-xs font-medium">
|
||||
{excludeRegions.length} Ausschluss
|
||||
</span>
|
||||
)}
|
||||
{(result.border_ghosts_removed ?? 0) > 0 && (
|
||||
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-400 text-xs font-medium">
|
||||
{result.border_ghosts_removed} Rahmenlinien entfernt
|
||||
</span>
|
||||
)}
|
||||
<span className="text-gray-400 text-xs ml-auto">
|
||||
{result.detection_method && (
|
||||
<span className="mr-1.5">
|
||||
{result.detection_method === 'ppdoclayout' ? 'PP-DocLayout' : 'OpenCV'} |
|
||||
</span>
|
||||
)}
|
||||
{result.image_width}x{result.image_height}px | {result.duration_seconds}s
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Boxes detail */}
|
||||
{result.boxes.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">Erkannte Boxen</h4>
|
||||
<div className="space-y-1.5">
|
||||
{result.boxes.map((box, i) => (
|
||||
<div key={i} className="flex items-center gap-3 text-xs">
|
||||
<span
|
||||
className="w-3 h-3 rounded-sm flex-shrink-0 border border-gray-300 dark:border-gray-600"
|
||||
style={{ backgroundColor: box.bg_color_hex || '#6b7280' }}
|
||||
/>
|
||||
<span className="text-gray-600 dark:text-gray-400">
|
||||
Box {i + 1}:
|
||||
</span>
|
||||
<span className="font-mono text-gray-500">
|
||||
{box.w}x{box.h}px @ ({box.x}, {box.y})
|
||||
</span>
|
||||
{box.bg_color_name && box.bg_color_name !== 'unknown' && box.bg_color_name !== 'white' && (
|
||||
<span className="px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-700 text-gray-500">
|
||||
{box.bg_color_name}
|
||||
</span>
|
||||
)}
|
||||
{box.border_thickness > 0 && (
|
||||
<span className="text-gray-400">
|
||||
Rahmen: {box.border_thickness}px
|
||||
</span>
|
||||
)}
|
||||
<span className="text-gray-400">
|
||||
{Math.round(box.confidence * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* PP-DocLayout regions detail */}
|
||||
{result.layout_regions && result.layout_regions.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">
|
||||
PP-DocLayout Regionen ({result.layout_regions.length})
|
||||
</h4>
|
||||
<div className="space-y-1.5">
|
||||
{result.layout_regions.map((region, i) => {
|
||||
const color = getDocLayoutColor(region.class_name)
|
||||
return (
|
||||
<div key={i} className="flex items-center gap-3 text-xs">
|
||||
<span
|
||||
className="w-3 h-3 rounded-sm flex-shrink-0 border"
|
||||
style={{ backgroundColor: `${color}40`, borderColor: color }}
|
||||
/>
|
||||
<span className="text-gray-600 dark:text-gray-400 font-medium min-w-[60px]">
|
||||
{region.class_name}
|
||||
</span>
|
||||
<span className="font-mono text-gray-500">
|
||||
{region.w}x{region.h}px @ ({region.x}, {region.y})
|
||||
</span>
|
||||
<span className="text-gray-400">
|
||||
{Math.round(region.confidence * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Zones detail */}
|
||||
<div>
|
||||
<h4 className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">Seitenzonen</h4>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{result.zones.map((zone) => (
|
||||
<span
|
||||
key={zone.index}
|
||||
className={`inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] font-medium ${
|
||||
zone.zone_type === 'box'
|
||||
? 'bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-300 border border-amber-200 dark:border-amber-800'
|
||||
: 'bg-gray-50 dark:bg-gray-800 text-gray-500 dark:text-gray-400 border border-gray-200 dark:border-gray-700'
|
||||
}`}
|
||||
>
|
||||
{zone.zone_type === 'box' ? 'Box' : 'Inhalt'} {zone.index}
|
||||
<span className="text-[10px] font-normal opacity-70">
|
||||
({zone.w}x{zone.h})
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Graphics / visual elements */}
|
||||
{result.graphics && result.graphics.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">
|
||||
Graphische Elemente ({result.graphics.length})
|
||||
</h4>
|
||||
{/* Summary by shape */}
|
||||
{(() => {
|
||||
const shapeCounts: Record<string, number> = {}
|
||||
for (const g of result.graphics) {
|
||||
shapeCounts[g.shape] = (shapeCounts[g.shape] || 0) + 1
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2 mb-2">
|
||||
{Object.entries(shapeCounts)
|
||||
.sort(([, a], [, b]) => b - a)
|
||||
.map(([shape, count]) => (
|
||||
<span
|
||||
key={shape}
|
||||
className="inline-flex items-center gap-1 px-2 py-1 rounded text-[11px] bg-purple-50 dark:bg-purple-900/20 text-purple-700 dark:text-purple-300 border border-purple-200 dark:border-purple-800"
|
||||
>
|
||||
{shape === 'arrow' ? '→' : shape === 'circle' ? '●' : shape === 'line' ? '─' : shape === 'exclamation' ? '❗' : shape === 'dot' ? '•' : shape === 'illustration' ? '🖼' : '◆'}
|
||||
{' '}{shape} <span className="font-semibold">x{count}</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
{/* Individual graphics list */}
|
||||
<div className="space-y-1.5 max-h-40 overflow-y-auto">
|
||||
{result.graphics.map((g, i) => (
|
||||
<div key={i} className="flex items-center gap-3 text-xs">
|
||||
<span
|
||||
className="w-3 h-3 rounded-full flex-shrink-0 border border-gray-300 dark:border-gray-600"
|
||||
style={{ backgroundColor: g.color_hex || '#6b7280' }}
|
||||
/>
|
||||
<span className="text-gray-600 dark:text-gray-400 font-medium min-w-[60px]">
|
||||
{g.shape}
|
||||
</span>
|
||||
<span className="font-mono text-gray-500">
|
||||
{g.w}x{g.h}px @ ({g.x}, {g.y})
|
||||
</span>
|
||||
<span className="text-gray-400">
|
||||
{g.color_name}
|
||||
</span>
|
||||
<span className="text-gray-400">
|
||||
{Math.round(g.confidence * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Color regions */}
|
||||
{Object.keys(result.color_pixel_counts).length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">Erkannte Farben</h4>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{Object.entries(result.color_pixel_counts)
|
||||
.sort(([, a], [, b]) => b - a)
|
||||
.map(([name, count]) => (
|
||||
<span key={name} className="inline-flex items-center gap-1.5 px-2 py-1 rounded text-[11px] bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700">
|
||||
<span
|
||||
className="w-2.5 h-2.5 rounded-full"
|
||||
style={{ backgroundColor: COLOR_HEX[name] || '#6b7280' }}
|
||||
/>
|
||||
<span className="text-gray-600 dark:text-gray-400">{name}</span>
|
||||
<span className="text-gray-400 text-[10px]">{count.toLocaleString()}px</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action buttons */}
|
||||
{result && (
|
||||
<div className="flex justify-between">
|
||||
<button
|
||||
onClick={handleRerun}
|
||||
disabled={detecting}
|
||||
className="px-4 py-2 text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 transition-colors disabled:opacity-50"
|
||||
>
|
||||
Erneut erkennen
|
||||
</button>
|
||||
<button
|
||||
onClick={onNext}
|
||||
className="px-6 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 font-medium transition-colors"
|
||||
>
|
||||
Weiter →
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-lg text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { GridResult, GridCell, WordEntry, WordGroundTruth } from '@/app/(admin)/ai/ocr-pipeline/types'
|
||||
import type { GridResult, GridCell, WordEntry, WordGroundTruth } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
const KLAUSUR_API = '/klausur-api'
|
||||
|
||||
@@ -44,9 +44,11 @@ interface StepWordRecognitionProps {
|
||||
sessionId: string | null
|
||||
onNext: () => void
|
||||
goToStep: (step: number) => void
|
||||
/** Skip _heal_row_gaps in cell grid (better overlay positioning) */
|
||||
skipHealGaps?: boolean
|
||||
}
|
||||
|
||||
export function StepWordRecognition({ sessionId, onNext, goToStep }: StepWordRecognitionProps) {
|
||||
export function StepWordRecognition({ sessionId, onNext, goToStep, skipHealGaps = false }: StepWordRecognitionProps) {
|
||||
const [gridResult, setGridResult] = useState<GridResult | null>(null)
|
||||
const [detecting, setDetecting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -58,9 +60,10 @@ export function StepWordRecognition({ sessionId, onNext, goToStep }: StepWordRec
|
||||
const [editedEntries, setEditedEntries] = useState<WordEntry[]>([])
|
||||
const [editedCells, setEditedCells] = useState<GridCell[]>([])
|
||||
const [mode, setMode] = useState<'overview' | 'labeling'>('overview')
|
||||
const [ocrEngine, setOcrEngine] = useState<'auto' | 'tesseract' | 'rapid'>('auto')
|
||||
const [ocrEngine, setOcrEngine] = useState<'auto' | 'tesseract' | 'rapid' | 'paddle'>('auto')
|
||||
const [usedEngine, setUsedEngine] = useState<string>('')
|
||||
const [pronunciation, setPronunciation] = useState<'british' | 'american'>('british')
|
||||
const [gridMethod, setGridMethod] = useState<'v2' | 'words_first'>('v2')
|
||||
|
||||
// Streaming progress state
|
||||
const [streamProgress, setStreamProgress] = useState<{ current: number; total: number } | null>(null)
|
||||
@@ -105,12 +108,16 @@ export function StepWordRecognition({ sessionId, onNext, goToStep }: StepWordRec
|
||||
setGridResult(null)
|
||||
|
||||
try {
|
||||
// PP-OCRv5 forces words_first on the backend, so align frontend accordingly
|
||||
const effectiveGridMethod = eng === 'paddle' ? 'words_first' : gridMethod
|
||||
const useStream = effectiveGridMethod === 'v2'
|
||||
|
||||
// Retry once if initial request fails (e.g. after container restart,
|
||||
// session cache may not be warm yet when navigating via wizard)
|
||||
let res: Response | null = null
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
res = await fetch(
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/words?stream=true&engine=${eng}&pronunciation=${pronunciation}`,
|
||||
`${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/words?stream=${useStream ? 'true' : 'false'}&engine=${eng}&pronunciation=${pronunciation}${skipHealGaps ? '&skip_heal_gaps=true' : ''}&grid_method=${effectiveGridMethod}`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
if (res.ok) break
|
||||
@@ -126,6 +133,13 @@ export function StepWordRecognition({ sessionId, onNext, goToStep }: StepWordRec
|
||||
throw new Error(err.detail || 'Worterkennung fehlgeschlagen')
|
||||
}
|
||||
|
||||
// words_first / pp-ocrv5 returns plain JSON (no streaming)
|
||||
if (!useStream) {
|
||||
const data = await res.json() as GridResult
|
||||
applyGridResult(data)
|
||||
return
|
||||
}
|
||||
|
||||
const reader = res.body!.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
@@ -218,7 +232,7 @@ export function StepWordRecognition({ sessionId, onNext, goToStep }: StepWordRec
|
||||
setDetecting(false)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [sessionId, ocrEngine, pronunciation])
|
||||
}, [sessionId, ocrEngine, pronunciation, gridMethod])
|
||||
|
||||
const handleGroundTruth = useCallback(async (isCorrect: boolean) => {
|
||||
if (!sessionId) return
|
||||
@@ -334,7 +348,7 @@ export function StepWordRecognition({ sessionId, onNext, goToStep }: StepWordRec
|
||||
}
|
||||
|
||||
const overlayUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/words-overlay`
|
||||
const dewarpedUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/dewarped`
|
||||
const dewarpedUrl = `${KLAUSUR_API}/api/v1/ocr-pipeline/sessions/${sessionId}/image/cropped`
|
||||
|
||||
const confColor = (conf: number) => {
|
||||
if (conf >= 70) return 'text-green-600 dark:text-green-400'
|
||||
@@ -787,15 +801,26 @@ export function StepWordRecognition({ sessionId, onNext, goToStep }: StepWordRec
|
||||
{gridResult && (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4 space-y-3">
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
{/* Grid method selector */}
|
||||
<select
|
||||
value={gridMethod}
|
||||
onChange={(e) => setGridMethod(e.target.value as 'v2' | 'words_first')}
|
||||
className="px-2 py-1.5 text-xs border rounded-lg dark:bg-gray-700 dark:border-gray-600"
|
||||
>
|
||||
<option value="v2">Standard (v2)</option>
|
||||
<option value="words_first">Words-First</option>
|
||||
</select>
|
||||
|
||||
{/* OCR Engine selector */}
|
||||
<select
|
||||
value={ocrEngine}
|
||||
onChange={(e) => setOcrEngine(e.target.value as 'auto' | 'tesseract' | 'rapid')}
|
||||
onChange={(e) => setOcrEngine(e.target.value as 'auto' | 'tesseract' | 'rapid' | 'paddle')}
|
||||
className="px-2 py-1.5 text-xs border rounded-lg dark:bg-gray-700 dark:border-gray-600"
|
||||
>
|
||||
<option value="auto">Auto (RapidOCR wenn verfuegbar)</option>
|
||||
<option value="rapid">RapidOCR (ONNX)</option>
|
||||
<option value="tesseract">Tesseract</option>
|
||||
<option value="paddle">PP-OCRv5 (lokal)</option>
|
||||
</select>
|
||||
|
||||
{/* Pronunciation selector (only for vocab) */}
|
||||
@@ -821,11 +846,11 @@ export function StepWordRecognition({ sessionId, onNext, goToStep }: StepWordRec
|
||||
{/* Show which engine was used */}
|
||||
{usedEngine && (
|
||||
<span className={`px-2 py-0.5 rounded text-[10px] uppercase font-semibold ${
|
||||
usedEngine === 'rapid'
|
||||
usedEngine === 'rapid' || usedEngine === 'paddle'
|
||||
? 'bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300'
|
||||
: 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400'
|
||||
}`}>
|
||||
{usedEngine}
|
||||
{usedEngine === 'paddle' ? 'pp-ocrv5' : usedEngine}
|
||||
</span>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
/**
|
||||
* Tests for usePixelWordPositions hook.
|
||||
*
|
||||
* The hook performs pixel-based word positioning using an offscreen canvas.
|
||||
* Since Canvas/getImageData is not available in jsdom, we test the pure
|
||||
* computation logic by extracting and testing the algorithms directly.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Extract pure computation functions from the hook for testing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface Cluster {
|
||||
start: number
|
||||
end: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Cluster detection: find runs of dark pixels above a threshold.
|
||||
* Replicates the cluster detection logic in usePixelWordPositions.
|
||||
*/
|
||||
function findClusters(proj: number[], ch: number, cw: number): Cluster[] {
|
||||
const threshold = Math.max(1, ch * 0.03)
|
||||
const minGap = Math.max(5, Math.round(cw * 0.02))
|
||||
const clusters: Cluster[] = []
|
||||
let inCluster = false
|
||||
let clStart = 0
|
||||
let gap = 0
|
||||
|
||||
for (let x = 0; x < cw; x++) {
|
||||
if (proj[x] >= threshold) {
|
||||
if (!inCluster) { clStart = x; inCluster = true }
|
||||
gap = 0
|
||||
} else if (inCluster) {
|
||||
gap++
|
||||
if (gap > minGap) {
|
||||
clusters.push({ start: clStart, end: x - gap })
|
||||
inCluster = false
|
||||
gap = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
if (inCluster) clusters.push({ start: clStart, end: cw - 1 - gap })
|
||||
|
||||
return clusters
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirror clusters for 180° rotation.
|
||||
* Replicates the rotation logic in usePixelWordPositions.
|
||||
*/
|
||||
function mirrorClusters(clusters: Cluster[], cw: number): Cluster[] {
|
||||
return clusters.map(c => ({
|
||||
start: cw - 1 - c.end,
|
||||
end: cw - 1 - c.start,
|
||||
})).reverse()
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute fontRatio from cluster width, measured text width, and cell height.
|
||||
* Replicates the font ratio calculation.
|
||||
*/
|
||||
function computeFontRatio(
|
||||
clusterW: number,
|
||||
measuredWidth: number,
|
||||
refFontSize: number,
|
||||
ch: number,
|
||||
): number {
|
||||
const autoFontPx = refFontSize * (clusterW / measuredWidth)
|
||||
return Math.min(autoFontPx / ch, 1.0)
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode normalization: find the most common fontRatio (bucketed to 0.02).
|
||||
* Replicates the mode normalization in usePixelWordPositions.
|
||||
*/
|
||||
function normalizeFontRatios(ratios: number[]): number {
|
||||
if (ratios.length === 0) return 0
|
||||
const buckets = new Map<number, number>()
|
||||
for (const r of ratios) {
|
||||
const key = Math.round(r * 50) / 50
|
||||
buckets.set(key, (buckets.get(key) || 0) + 1)
|
||||
}
|
||||
let modeRatio = ratios[0]
|
||||
let modeCount = 0
|
||||
for (const [ratio, count] of buckets) {
|
||||
if (count > modeCount) { modeRatio = ratio; modeCount = count }
|
||||
}
|
||||
return modeRatio
|
||||
}
|
||||
|
||||
/**
|
||||
* Coordinate transform for 180° rotation.
|
||||
*/
|
||||
function transformCellCoords180(
|
||||
x: number, y: number, w: number, h: number,
|
||||
imgW: number, imgH: number,
|
||||
): { cx: number; cy: number } {
|
||||
return {
|
||||
cx: Math.round((100 - x - w) / 100 * imgW),
|
||||
cy: Math.round((100 - y - h) / 100 * imgH),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('findClusters', () => {
|
||||
it('should find a single cluster', () => {
|
||||
// Simulate a projection with dark pixels from x=10 to x=50
|
||||
const proj = new Array(100).fill(0)
|
||||
for (let x = 10; x <= 50; x++) proj[x] = 10
|
||||
|
||||
const clusters = findClusters(proj, 100, 100)
|
||||
expect(clusters.length).toBe(1)
|
||||
expect(clusters[0].start).toBe(10)
|
||||
expect(clusters[0].end).toBe(50)
|
||||
})
|
||||
|
||||
it('should find multiple clusters separated by gaps', () => {
|
||||
const proj = new Array(200).fill(0)
|
||||
// Two word groups with a gap between
|
||||
for (let x = 10; x <= 40; x++) proj[x] = 10
|
||||
for (let x = 80; x <= 120; x++) proj[x] = 10
|
||||
|
||||
const clusters = findClusters(proj, 100, 200)
|
||||
expect(clusters.length).toBe(2)
|
||||
expect(clusters[0].start).toBe(10)
|
||||
expect(clusters[1].start).toBe(80)
|
||||
})
|
||||
|
||||
it('should merge clusters with small gaps', () => {
|
||||
// Gap smaller than minGap should not split clusters
|
||||
const proj = new Array(100).fill(0)
|
||||
for (let x = 10; x <= 30; x++) proj[x] = 10
|
||||
// Small gap (3px) — minGap = max(5, 100*0.02) = 5
|
||||
for (let x = 34; x <= 50; x++) proj[x] = 10
|
||||
|
||||
const clusters = findClusters(proj, 100, 100)
|
||||
expect(clusters.length).toBe(1) // merged into one cluster
|
||||
})
|
||||
|
||||
it('should return empty for all-white projection', () => {
|
||||
const proj = new Array(100).fill(0)
|
||||
const clusters = findClusters(proj, 100, 100)
|
||||
expect(clusters.length).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('mirrorClusters', () => {
|
||||
it('should mirror clusters for 180° rotation', () => {
|
||||
const clusters: Cluster[] = [
|
||||
{ start: 10, end: 50 },
|
||||
{ start: 80, end: 120 },
|
||||
]
|
||||
const cw = 200
|
||||
|
||||
const mirrored = mirrorClusters(clusters, cw)
|
||||
|
||||
// Cluster at (10,50) → (cw-1-50, cw-1-10) = (149, 189)
|
||||
// Cluster at (80,120) → (cw-1-120, cw-1-80) = (79, 119)
|
||||
// After reverse: [(79,119), (149,189)]
|
||||
expect(mirrored.length).toBe(2)
|
||||
expect(mirrored[0]).toEqual({ start: 79, end: 119 })
|
||||
expect(mirrored[1]).toEqual({ start: 149, end: 189 })
|
||||
})
|
||||
|
||||
it('should maintain left-to-right order after mirroring', () => {
|
||||
const clusters: Cluster[] = [
|
||||
{ start: 5, end: 30 },
|
||||
{ start: 50, end: 80 },
|
||||
{ start: 100, end: 130 },
|
||||
]
|
||||
|
||||
const mirrored = mirrorClusters(clusters, 200)
|
||||
|
||||
// After mirroring and reversing, order should be left-to-right
|
||||
for (let i = 1; i < mirrored.length; i++) {
|
||||
expect(mirrored[i].start).toBeGreaterThan(mirrored[i - 1].start)
|
||||
}
|
||||
})
|
||||
|
||||
it('should handle single cluster', () => {
|
||||
const clusters: Cluster[] = [{ start: 20, end: 80 }]
|
||||
const mirrored = mirrorClusters(clusters, 200)
|
||||
|
||||
expect(mirrored.length).toBe(1)
|
||||
expect(mirrored[0]).toEqual({ start: 119, end: 179 })
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('computeFontRatio', () => {
|
||||
it('should compute ratio based on cluster vs measured width', () => {
|
||||
// Cluster is 100px wide, measured text at 40px font is 200px → autoFont = 20px
|
||||
// Cell height = 30px → ratio = 20/30 = 0.667
|
||||
const ratio = computeFontRatio(100, 200, 40, 30)
|
||||
expect(ratio).toBeCloseTo(0.667, 2)
|
||||
})
|
||||
|
||||
it('should cap ratio at 1.0', () => {
|
||||
// Very large cluster relative to measured text
|
||||
const ratio = computeFontRatio(400, 100, 40, 30)
|
||||
expect(ratio).toBe(1.0)
|
||||
})
|
||||
|
||||
it('should handle small cluster width', () => {
|
||||
const ratio = computeFontRatio(10, 200, 40, 30)
|
||||
expect(ratio).toBeCloseTo(0.067, 2)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('normalizeFontRatios', () => {
|
||||
it('should return the most common ratio', () => {
|
||||
const ratios = [0.5, 0.5, 0.5, 0.3, 0.3, 0.7]
|
||||
const mode = normalizeFontRatios(ratios)
|
||||
expect(mode).toBe(0.5)
|
||||
})
|
||||
|
||||
it('should bucket ratios to nearest 0.02', () => {
|
||||
// 0.51 and 0.49 both round to 0.50 (nearest 0.02)
|
||||
const ratios = [0.51, 0.49, 0.50, 0.30]
|
||||
const mode = normalizeFontRatios(ratios)
|
||||
expect(mode).toBe(0.50)
|
||||
})
|
||||
|
||||
it('should handle empty array', () => {
|
||||
expect(normalizeFontRatios([])).toBe(0)
|
||||
})
|
||||
|
||||
it('should handle single ratio', () => {
|
||||
expect(normalizeFontRatios([0.65])).toBe(0.66) // rounded to nearest 0.02
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('transformCellCoords180', () => {
|
||||
it('should transform cell coordinates for 180° rotation', () => {
|
||||
// Cell at x=10%, y=20%, w=30%, h=5% on a 1000x2000 image
|
||||
const { cx, cy } = transformCellCoords180(10, 20, 30, 5, 1000, 2000)
|
||||
|
||||
// Expected: cx = (100 - 10 - 30) / 100 * 1000 = 600
|
||||
// cy = (100 - 20 - 5) / 100 * 2000 = 1500
|
||||
expect(cx).toBe(600)
|
||||
expect(cy).toBe(1500)
|
||||
})
|
||||
|
||||
it('should handle cell at origin', () => {
|
||||
const { cx, cy } = transformCellCoords180(0, 0, 50, 50, 1000, 1000)
|
||||
|
||||
// Expected: cx = (100 - 0 - 50) / 100 * 1000 = 500
|
||||
// cy = (100 - 0 - 50) / 100 * 1000 = 500
|
||||
expect(cx).toBe(500)
|
||||
expect(cy).toBe(500)
|
||||
})
|
||||
|
||||
it('should handle cell at bottom-right', () => {
|
||||
const { cx, cy } = transformCellCoords180(80, 90, 20, 10, 1000, 2000)
|
||||
|
||||
// Expected: cx = (100 - 80 - 20) / 100 * 1000 = 0
|
||||
// cy = (100 - 90 - 10) / 100 * 2000 = 0
|
||||
expect(cx).toBe(0)
|
||||
expect(cy).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('sub-session coordinate conversion', () => {
|
||||
/**
|
||||
* Test the coordinate conversion from sub-session (box-relative)
|
||||
* to parent (page-absolute) coordinates.
|
||||
* Replicates the logic in StepReconstruction loadSessionData.
|
||||
*/
|
||||
it('should convert sub-session cell coords to parent space', () => {
|
||||
const imgW = 1746
|
||||
const imgH = 2487
|
||||
|
||||
// Box zone in pixels
|
||||
const box = { x: 50, y: 1145, width: 1100, height: 270 }
|
||||
|
||||
// Box in percent
|
||||
const boxXPct = (box.x / imgW) * 100
|
||||
const boxYPct = (box.y / imgH) * 100
|
||||
const boxWPct = (box.width / imgW) * 100
|
||||
const boxHPct = (box.height / imgH) * 100
|
||||
|
||||
// Sub-session cell at (10%, 20%, 80%, 15%) relative to box
|
||||
const subCell = { x: 10, y: 20, w: 80, h: 15 }
|
||||
|
||||
const parentX = boxXPct + (subCell.x / 100) * boxWPct
|
||||
const parentY = boxYPct + (subCell.y / 100) * boxHPct
|
||||
const parentW = (subCell.w / 100) * boxWPct
|
||||
const parentH = (subCell.h / 100) * boxHPct
|
||||
|
||||
// Box start in percent: x ≈ 2.86%, y ≈ 46.04%
|
||||
expect(parentX).toBeCloseTo(boxXPct + 0.1 * boxWPct, 2)
|
||||
expect(parentY).toBeCloseTo(boxYPct + 0.2 * boxHPct, 2)
|
||||
expect(parentW).toBeCloseTo(0.8 * boxWPct, 2)
|
||||
expect(parentH).toBeCloseTo(0.15 * boxHPct, 2)
|
||||
|
||||
// All values should be within 0-100%
|
||||
expect(parentX).toBeGreaterThan(0)
|
||||
expect(parentY).toBeGreaterThan(0)
|
||||
expect(parentX + parentW).toBeLessThan(100)
|
||||
expect(parentY + parentH).toBeLessThan(100)
|
||||
})
|
||||
|
||||
it('should place sub-cell at box origin when sub coords are 0,0', () => {
|
||||
const imgW = 1000
|
||||
const imgH = 2000
|
||||
const box = { x: 100, y: 500, width: 800, height: 200 }
|
||||
|
||||
const boxXPct = (box.x / imgW) * 100 // 10%
|
||||
const boxYPct = (box.y / imgH) * 100 // 25%
|
||||
|
||||
const parentX = boxXPct + (0 / 100) * ((box.width / imgW) * 100)
|
||||
const parentY = boxYPct + (0 / 100) * ((box.height / imgH) * 100)
|
||||
|
||||
expect(parentX).toBeCloseTo(10, 1)
|
||||
expect(parentY).toBeCloseTo(25, 1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Tests for useSlideWordPositions hook.
|
||||
*
|
||||
* The hook computes word positions from OCR word_boxes or pixel projection.
|
||||
* Since Canvas/Image are not available in jsdom, we test the pure computation
|
||||
* logic by extracting and verifying the WordPosition interface contract.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// WordPosition interface (mirrored from useSlideWordPositions.ts)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface WordPosition {
|
||||
xPct: number
|
||||
wPct: number
|
||||
yPct: number
|
||||
hPct: number
|
||||
text: string
|
||||
fontRatio: number
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pure computation functions extracted from the hook for testing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Word-box path: compute WordPosition from an OCR word_box.
|
||||
* Replicates the word_boxes.map() logic in useSlideWordPositions.
|
||||
*/
|
||||
function wordBoxToPosition(
|
||||
box: { text: string; left: number; top: number; width: number; height: number },
|
||||
imgW: number,
|
||||
imgH: number,
|
||||
): WordPosition {
|
||||
return {
|
||||
xPct: (box.left / imgW) * 100,
|
||||
wPct: (box.width / imgW) * 100,
|
||||
yPct: (box.top / imgH) * 100,
|
||||
hPct: (box.height / imgH) * 100,
|
||||
text: box.text,
|
||||
fontRatio: 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback path (no word_boxes): spread tokens evenly across cell bbox.
|
||||
* Replicates the fallback logic in useSlideWordPositions.
|
||||
*/
|
||||
function fallbackPositions(
|
||||
tokens: string[],
|
||||
bboxPct: { x: number; y: number; w: number; h: number },
|
||||
): WordPosition[] {
|
||||
const fallbackW = bboxPct.w / tokens.length
|
||||
return tokens.map((t, i) => ({
|
||||
xPct: bboxPct.x + i * fallbackW,
|
||||
wPct: fallbackW,
|
||||
yPct: bboxPct.y,
|
||||
hPct: bboxPct.h,
|
||||
text: t,
|
||||
fontRatio: 1.0,
|
||||
}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('wordBoxToPosition (word-box path)', () => {
|
||||
it('should compute percentage positions from pixel coordinates', () => {
|
||||
const box = { text: 'hello', left: 100, top: 200, width: 80, height: 20 }
|
||||
const wp = wordBoxToPosition(box, 1000, 2000)
|
||||
|
||||
expect(wp.xPct).toBeCloseTo(10, 1) // 100/1000 * 100
|
||||
expect(wp.wPct).toBeCloseTo(8, 1) // 80/1000 * 100
|
||||
expect(wp.yPct).toBeCloseTo(10, 1) // 200/2000 * 100
|
||||
expect(wp.hPct).toBeCloseTo(1, 1) // 20/2000 * 100
|
||||
expect(wp.text).toBe('hello')
|
||||
expect(wp.fontRatio).toBe(1.0)
|
||||
})
|
||||
|
||||
it('should produce different yPct for words on different lines', () => {
|
||||
const imgW = 1000, imgH = 2000
|
||||
const word1 = wordBoxToPosition({ text: 'line1', left: 50, top: 100, width: 60, height: 20 }, imgW, imgH)
|
||||
const word2 = wordBoxToPosition({ text: 'line2', left: 50, top: 130, width: 60, height: 20 }, imgW, imgH)
|
||||
|
||||
expect(word1.yPct).not.toEqual(word2.yPct)
|
||||
expect(word2.yPct).toBeGreaterThan(word1.yPct)
|
||||
})
|
||||
|
||||
it('should handle word at origin', () => {
|
||||
const wp = wordBoxToPosition({ text: 'a', left: 0, top: 0, width: 50, height: 25 }, 500, 500)
|
||||
expect(wp.xPct).toBe(0)
|
||||
expect(wp.yPct).toBe(0)
|
||||
expect(wp.wPct).toBeCloseTo(10, 1)
|
||||
expect(wp.hPct).toBeCloseTo(5, 1)
|
||||
})
|
||||
|
||||
it('should handle word at bottom-right corner', () => {
|
||||
const wp = wordBoxToPosition({ text: 'z', left: 900, top: 1900, width: 100, height: 100 }, 1000, 2000)
|
||||
expect(wp.xPct).toBe(90)
|
||||
expect(wp.yPct).toBe(95)
|
||||
expect(wp.wPct).toBe(10)
|
||||
expect(wp.hPct).toBe(5)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('fallbackPositions (no word_boxes)', () => {
|
||||
it('should spread tokens evenly across cell width', () => {
|
||||
const bbox = { x: 10, y: 20, w: 60, h: 5 }
|
||||
const positions = fallbackPositions(['apple', 'Apfel'], bbox)
|
||||
|
||||
expect(positions.length).toBe(2)
|
||||
expect(positions[0].xPct).toBeCloseTo(10, 1)
|
||||
expect(positions[1].xPct).toBeCloseTo(40, 1) // 10 + 30
|
||||
expect(positions[0].wPct).toBeCloseTo(30, 1)
|
||||
expect(positions[1].wPct).toBeCloseTo(30, 1)
|
||||
})
|
||||
|
||||
it('should use cell bbox for Y position (all words same Y)', () => {
|
||||
const bbox = { x: 5, y: 30, w: 80, h: 4 }
|
||||
const positions = fallbackPositions(['a', 'b', 'c'], bbox)
|
||||
|
||||
for (const wp of positions) {
|
||||
expect(wp.yPct).toBe(30)
|
||||
expect(wp.hPct).toBe(4)
|
||||
}
|
||||
})
|
||||
|
||||
it('should handle single token', () => {
|
||||
const bbox = { x: 15, y: 25, w: 50, h: 6 }
|
||||
const positions = fallbackPositions(['word'], bbox)
|
||||
|
||||
expect(positions.length).toBe(1)
|
||||
expect(positions[0].xPct).toBe(15)
|
||||
expect(positions[0].wPct).toBe(50)
|
||||
expect(positions[0].yPct).toBe(25)
|
||||
expect(positions[0].hPct).toBe(6)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('WordPosition yPct/hPct contract', () => {
|
||||
it('word-box path: yPct comes from box.top, not cell bbox', () => {
|
||||
// This is the key fix: multi-line cells should NOT stack words at cell center
|
||||
const cellBbox = { x: 10, y: 20, w: 60, h: 10 } // cell spans y=20% to y=30%
|
||||
const imgW = 1000, imgH = 1000
|
||||
|
||||
// Two words on different lines within the same cell
|
||||
const word1 = wordBoxToPosition({ text: 'line1', left: 100, top: 200, width: 80, height: 20 }, imgW, imgH)
|
||||
const word2 = wordBoxToPosition({ text: 'line2', left: 100, top: 260, width: 80, height: 20 }, imgW, imgH)
|
||||
|
||||
// word1 should be at y=20%, word2 at y=26% — NOT both at cellBbox.y (20%)
|
||||
expect(word1.yPct).toBeCloseTo(20, 1)
|
||||
expect(word2.yPct).toBeCloseTo(26, 1)
|
||||
expect(word1.yPct).not.toEqual(word2.yPct)
|
||||
|
||||
// Both should have individual heights from their box, not cell height
|
||||
expect(word1.hPct).toBeCloseTo(2, 1)
|
||||
expect(word2.hPct).toBeCloseTo(2, 1)
|
||||
// Cell height would be 10% — word height is 2%, confirming per-word sizing
|
||||
expect(word1.hPct).toBeLessThan(cellBbox.h)
|
||||
})
|
||||
|
||||
it('fallback path: yPct equals cell bbox.y (no per-word data)', () => {
|
||||
const bbox = { x: 10, y: 45, w: 30, h: 8 }
|
||||
const positions = fallbackPositions(['a', 'b'], bbox)
|
||||
|
||||
// Without word_boxes, all words use cell bbox Y — expected behavior
|
||||
expect(positions[0].yPct).toBe(bbox.y)
|
||||
expect(positions[1].yPct).toBe(bbox.y)
|
||||
expect(positions[0].hPct).toBe(bbox.h)
|
||||
expect(positions[1].hPct).toBe(bbox.h)
|
||||
})
|
||||
})
|
||||
198
admin-lehrer/components/ocr-pipeline/usePixelWordPositions.ts
Normal file
198
admin-lehrer/components/ocr-pipeline/usePixelWordPositions.ts
Normal file
@@ -0,0 +1,198 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { GridCell } from '@/app/(admin)/ai/ocr-kombi/types'
|
||||
|
||||
export interface WordPosition {
|
||||
xPct: number
|
||||
wPct: number
|
||||
text: string
|
||||
fontRatio: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared hook: analyse dark-pixel clusters on an image to determine
|
||||
* the exact horizontal position & auto-font-size of word groups in each cell.
|
||||
*
|
||||
* When rotation=180, the image is rotated 180° before pixel analysis.
|
||||
* Cell coordinates are transformed to the rotated space for reading,
|
||||
* and cluster positions are mirrored back to the original coordinate system.
|
||||
*
|
||||
* Returns a Map<cell_id, WordPosition[]>.
|
||||
*/
|
||||
export function usePixelWordPositions(
|
||||
imageUrl: string,
|
||||
cells: GridCell[],
|
||||
active: boolean,
|
||||
rotation: 0 | 180 = 0,
|
||||
): Map<string, WordPosition[]> {
|
||||
const [cellWordPositions, setCellWordPositions] = useState<Map<string, WordPosition[]>>(new Map())
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || cells.length === 0 || !imageUrl) return
|
||||
|
||||
const img = new Image()
|
||||
img.crossOrigin = 'anonymous'
|
||||
img.onload = () => {
|
||||
const imgW = img.naturalWidth
|
||||
const imgH = img.naturalHeight
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = imgW
|
||||
canvas.height = imgH
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) return
|
||||
|
||||
if (rotation === 180) {
|
||||
// Draw image rotated 180°
|
||||
ctx.translate(imgW, imgH)
|
||||
ctx.rotate(Math.PI)
|
||||
ctx.drawImage(img, 0, 0)
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0) // reset transform for measureText
|
||||
} else {
|
||||
ctx.drawImage(img, 0, 0)
|
||||
}
|
||||
|
||||
const refFontSize = 40
|
||||
const fontFam = "'Liberation Sans', Arial, sans-serif"
|
||||
ctx.font = `${refFontSize}px ${fontFam}`
|
||||
|
||||
const positions = new Map<string, WordPosition[]>()
|
||||
|
||||
for (const cell of cells) {
|
||||
if (!cell.bbox_pct || !cell.text) continue
|
||||
|
||||
// Split by 3+ whitespace into word-groups
|
||||
const groups = cell.text.split(/\s{3,}/).map(s => s.trim()).filter(Boolean)
|
||||
|
||||
// Cell pixel region — when rotated 180°, transform coordinates
|
||||
let cx: number, cy: number
|
||||
const cw = Math.round(cell.bbox_pct.w / 100 * imgW)
|
||||
const ch = Math.round(cell.bbox_pct.h / 100 * imgH)
|
||||
|
||||
if (rotation === 180) {
|
||||
// In rotated image: (x,y) maps to (W-x-w, H-y-h)
|
||||
cx = Math.round((100 - cell.bbox_pct.x - cell.bbox_pct.w) / 100 * imgW)
|
||||
cy = Math.round((100 - cell.bbox_pct.y - cell.bbox_pct.h) / 100 * imgH)
|
||||
} else {
|
||||
cx = Math.round(cell.bbox_pct.x / 100 * imgW)
|
||||
cy = Math.round(cell.bbox_pct.y / 100 * imgH)
|
||||
}
|
||||
if (cw <= 0 || ch <= 0) continue
|
||||
// Clamp to image bounds
|
||||
if (cx < 0) cx = 0
|
||||
if (cy < 0) cy = 0
|
||||
if (cx + cw > imgW || cy + ch > imgH) continue
|
||||
|
||||
const imageData = ctx.getImageData(cx, cy, cw, ch)
|
||||
|
||||
// Vertical projection: count dark pixels per column
|
||||
const proj = new Float32Array(cw)
|
||||
for (let y = 0; y < ch; y++) {
|
||||
for (let x = 0; x < cw; x++) {
|
||||
const idx = (y * cw + x) * 4
|
||||
const lum = 0.299 * imageData.data[idx] + 0.587 * imageData.data[idx + 1] + 0.114 * imageData.data[idx + 2]
|
||||
if (lum < 128) proj[x]++
|
||||
}
|
||||
}
|
||||
|
||||
// Find dark-pixel clusters (word groups on the image)
|
||||
const threshold = Math.max(1, ch * 0.03)
|
||||
const minGap = Math.max(5, Math.round(cw * 0.02))
|
||||
let clusters: { start: number; end: number }[] = []
|
||||
let inCluster = false
|
||||
let clStart = 0
|
||||
let gap = 0
|
||||
|
||||
for (let x = 0; x < cw; x++) {
|
||||
if (proj[x] >= threshold) {
|
||||
if (!inCluster) { clStart = x; inCluster = true }
|
||||
gap = 0
|
||||
} else if (inCluster) {
|
||||
gap++
|
||||
if (gap > minGap) {
|
||||
clusters.push({ start: clStart, end: x - gap })
|
||||
inCluster = false
|
||||
gap = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
if (inCluster) clusters.push({ start: clStart, end: cw - 1 - gap })
|
||||
|
||||
if (clusters.length === 0) continue
|
||||
|
||||
// When rotated 180°, mirror clusters back to original coordinate system
|
||||
// A cluster at (start, end) in rotated space = (cw-1-end, cw-1-start) in original
|
||||
if (rotation === 180) {
|
||||
clusters = clusters.map(c => ({
|
||||
start: cw - 1 - c.end,
|
||||
end: cw - 1 - c.start,
|
||||
})).reverse() // reverse to restore left-to-right order in original space
|
||||
}
|
||||
|
||||
const wordPos: WordPosition[] = []
|
||||
|
||||
if (groups.length <= 1) {
|
||||
// Single group: position at first cluster, merge all clusters for width
|
||||
const firstCl = clusters[0]
|
||||
const lastCl = clusters[clusters.length - 1]
|
||||
const clusterW = lastCl.end - firstCl.start + 1
|
||||
const measured = ctx.measureText(cell.text.trim())
|
||||
const autoFontPx = refFontSize * (clusterW / measured.width)
|
||||
const fontRatio = Math.min(autoFontPx / ch, 1.0)
|
||||
wordPos.push({
|
||||
xPct: cell.bbox_pct.x + (firstCl.start / cw) * cell.bbox_pct.w,
|
||||
wPct: ((lastCl.end - firstCl.start + 1) / cw) * cell.bbox_pct.w,
|
||||
text: cell.text.trim(),
|
||||
fontRatio,
|
||||
})
|
||||
} else if (clusters.length >= groups.length) {
|
||||
// Multiple groups: match to clusters left-to-right
|
||||
for (let i = 0; i < groups.length; i++) {
|
||||
const cl = clusters[i]
|
||||
const clusterW = cl.end - cl.start + 1
|
||||
const measured = ctx.measureText(groups[i])
|
||||
const autoFontPx = refFontSize * (clusterW / measured.width)
|
||||
const fontRatio = Math.min(autoFontPx / ch, 1.0)
|
||||
wordPos.push({
|
||||
xPct: cell.bbox_pct.x + (cl.start / cw) * cell.bbox_pct.w,
|
||||
wPct: ((cl.end - cl.start + 1) / cw) * cell.bbox_pct.w,
|
||||
text: groups[i],
|
||||
fontRatio,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
continue // fewer clusters than groups — skip
|
||||
}
|
||||
|
||||
positions.set(cell.cell_id, wordPos)
|
||||
}
|
||||
|
||||
// Normalise: find the most common fontRatio (mode) and apply it to all
|
||||
const allRatios: number[] = []
|
||||
for (const wps of positions.values()) {
|
||||
for (const wp of wps) allRatios.push(wp.fontRatio)
|
||||
}
|
||||
if (allRatios.length > 0) {
|
||||
// Bucket ratios to 2 decimal places, find mode
|
||||
const buckets = new Map<number, number>()
|
||||
for (const r of allRatios) {
|
||||
const key = Math.round(r * 50) / 50 // round to nearest 0.02
|
||||
buckets.set(key, (buckets.get(key) || 0) + 1)
|
||||
}
|
||||
let modeRatio = allRatios[0]
|
||||
let modeCount = 0
|
||||
for (const [ratio, count] of buckets) {
|
||||
if (count > modeCount) { modeRatio = ratio; modeCount = count }
|
||||
}
|
||||
// Apply mode to all word positions
|
||||
for (const wps of positions.values()) {
|
||||
for (const wp of wps) wp.fontRatio = modeRatio
|
||||
}
|
||||
}
|
||||
|
||||
setCellWordPositions(positions)
|
||||
}
|
||||
img.src = imageUrl
|
||||
}, [active, cells, imageUrl, rotation])
|
||||
|
||||
return cellWordPositions
|
||||
}
|
||||
@@ -234,28 +234,6 @@ export const MODULE_REGISTRY: BackendModule[] = [
|
||||
},
|
||||
priority: 'high'
|
||||
},
|
||||
{
|
||||
id: 'llm-compare',
|
||||
name: 'LLM Vergleich',
|
||||
description: 'Vergleich verschiedener KI-Modelle und Provider',
|
||||
category: 'ai',
|
||||
backend: {
|
||||
service: 'python-backend',
|
||||
port: 8000,
|
||||
basePath: '/api/llm',
|
||||
endpoints: [
|
||||
{ path: '/providers', method: 'GET', description: 'Verfuegbare Provider' },
|
||||
{ path: '/compare', method: 'POST', description: 'Modelle vergleichen' },
|
||||
{ path: '/benchmark', method: 'POST', description: 'Benchmark ausfuehren' },
|
||||
]
|
||||
},
|
||||
frontend: {
|
||||
adminV2Page: '/ai/llm-compare',
|
||||
oldAdminPage: '/admin/llm-compare',
|
||||
status: 'connected'
|
||||
},
|
||||
priority: 'medium'
|
||||
},
|
||||
{
|
||||
id: 'magic-help',
|
||||
name: 'Magic Help (TrOCR)',
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* All DSGVO and Compliance modules are now consolidated under the SDK.
|
||||
*/
|
||||
|
||||
export type CategoryId = 'compliance-sdk' | 'ai' | 'education' | 'website' | 'sdk-docs'
|
||||
export type CategoryId = 'communication' | 'ai' | 'education' | 'website' | 'sdk-docs'
|
||||
|
||||
export interface NavModule {
|
||||
id: string
|
||||
@@ -31,23 +31,31 @@ export interface NavCategory {
|
||||
|
||||
export const navigation: NavCategory[] = [
|
||||
// =========================================================================
|
||||
// Compliance SDK - Alle Datenschutz-, Compliance- und SDK-Module
|
||||
// Kommunikation — Video, Voice, Alerts
|
||||
// =========================================================================
|
||||
{
|
||||
id: 'compliance-sdk',
|
||||
name: 'Compliance SDK',
|
||||
icon: 'shield',
|
||||
color: '#8b5cf6', // Violet-500
|
||||
colorClass: 'compliance-sdk',
|
||||
description: 'DSGVO, Audit, GRC & SDK-Werkzeuge',
|
||||
id: 'communication',
|
||||
name: 'Kommunikation',
|
||||
icon: 'mail',
|
||||
color: '#f59e0b', // Amber-500
|
||||
colorClass: 'communication',
|
||||
description: 'Video & Chat, Voice Service, E-Mail, Alerts',
|
||||
modules: [
|
||||
{
|
||||
id: 'catalog-manager',
|
||||
name: 'Katalogverwaltung',
|
||||
href: '/dashboard/catalog-manager',
|
||||
description: 'SDK-Kataloge & Auswahltabellen',
|
||||
purpose: 'Zentrale Verwaltung aller Dropdown- und Auswahltabellen im SDK. Systemkataloge (Risiken, Massnahmen, Vorlagen) anzeigen und benutzerdefinierte Eintraege ergaenzen, bearbeiten und loeschen.',
|
||||
audience: ['DSB', 'Compliance Officer', 'Administratoren'],
|
||||
id: 'mail',
|
||||
name: 'Unified Inbox',
|
||||
href: '/communication/mail',
|
||||
description: 'E-Mail-Konten & KI-Analyse',
|
||||
purpose: 'E-Mail-Konten verwalten und KI-Kategorisierung nutzen. IMAP/SMTP Konfiguration, Vorlagen und Audit-Log.',
|
||||
audience: ['Support', 'Admins'],
|
||||
},
|
||||
{
|
||||
id: 'alerts',
|
||||
name: 'Alerts Monitoring',
|
||||
href: '/communication/alerts',
|
||||
description: 'Google Alerts & Feed-Ueberwachung',
|
||||
purpose: 'Google Alerts und RSS-Feeds fuer relevante Neuigkeiten ueberwachen. Topics, Regeln, Relevanz-Profil und Digest-Generierung.',
|
||||
audience: ['Marketing', 'Admins'],
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -109,31 +117,12 @@ export const navigation: NavCategory[] = [
|
||||
// KI-Werkzeuge: Standalone-Tools fuer Entwicklung & QA
|
||||
// -----------------------------------------------------------------------
|
||||
{
|
||||
id: 'llm-compare',
|
||||
name: 'LLM Vergleich',
|
||||
href: '/ai/llm-compare',
|
||||
description: 'KI-Provider Vergleich',
|
||||
purpose: 'Vergleichen Sie verschiedene LLM-Anbieter (Ollama, OpenAI, Anthropic) hinsichtlich Qualitaet, Geschwindigkeit und Kosten. Standalone-Werkzeug fuer Modell-Evaluation.',
|
||||
audience: ['Entwickler', 'Data Scientists'],
|
||||
oldAdminPath: '/admin/llm-compare',
|
||||
subgroup: 'KI-Werkzeuge',
|
||||
},
|
||||
{
|
||||
id: 'ocr-compare',
|
||||
name: 'OCR Vergleich',
|
||||
href: '/ai/ocr-compare',
|
||||
description: 'OCR-Methoden & Vokabel-Extraktion',
|
||||
purpose: 'Vergleichen Sie verschiedene OCR-Methoden (lokales LLM, Vision LLM, PaddleOCR, Tesseract, Anthropic) fuer Vokabel-Extraktion. Grid-Overlay, Block-Review und LLM-Vergleich.',
|
||||
audience: ['Entwickler', 'Data Scientists', 'Lehrer'],
|
||||
subgroup: 'KI-Werkzeuge',
|
||||
},
|
||||
{
|
||||
id: 'ocr-pipeline',
|
||||
name: 'OCR Pipeline',
|
||||
href: '/ai/ocr-pipeline',
|
||||
description: 'Schrittweise Seitenrekonstruktion',
|
||||
purpose: 'Schrittweise Seitenrekonstruktion: Scan begradigen, Spalten erkennen, Woerter lokalisieren und die Seite Wort fuer Wort nachbauen. 6-Schritt-Pipeline mit Ground Truth Validierung.',
|
||||
audience: ['Entwickler', 'Data Scientists'],
|
||||
id: 'ocr-kombi',
|
||||
name: 'OCR Kombi',
|
||||
href: '/ai/ocr-kombi',
|
||||
description: 'Modulare 11-Schritt-Pipeline',
|
||||
purpose: 'Modulare OCR-Pipeline mit Dual-Engine (PP-OCRv5 + Tesseract), Strukturerkennung, Grid-Aufbau und Review. Multi-Page-Dokument-Unterstuetzung.',
|
||||
audience: ['Entwickler'],
|
||||
subgroup: 'KI-Werkzeuge',
|
||||
},
|
||||
{
|
||||
@@ -146,19 +135,27 @@ export const navigation: NavCategory[] = [
|
||||
oldAdminPath: '/admin/quality',
|
||||
subgroup: 'KI-Werkzeuge',
|
||||
},
|
||||
{
|
||||
id: 'gpu',
|
||||
name: 'GPU Infrastruktur',
|
||||
href: '/ai/gpu',
|
||||
description: 'vast.ai GPU Management',
|
||||
purpose: 'Verwalten Sie GPU-Instanzen auf vast.ai fuer ML-Training und Inferenz.',
|
||||
audience: ['DevOps', 'Entwickler'],
|
||||
oldAdminPath: '/admin/gpu',
|
||||
subgroup: 'KI-Werkzeuge',
|
||||
},
|
||||
// -----------------------------------------------------------------------
|
||||
// KI-Anwendungen: Endnutzer-orientierte KI-Module
|
||||
// -----------------------------------------------------------------------
|
||||
{
|
||||
id: 'ocr-regression',
|
||||
name: 'OCR Regression',
|
||||
href: '/ai/ocr-regression',
|
||||
description: 'Regressions-Tests & Ground Truth',
|
||||
purpose: 'Regressions-Tests fuer die OCR-Pipeline ausfuehren. Zeigt Pass/Fail pro Ground-Truth Session, Diff-Details und Verlauf vergangener Laeufe.',
|
||||
audience: ['Entwickler', 'QA'],
|
||||
subgroup: 'KI-Werkzeuge',
|
||||
},
|
||||
{
|
||||
id: 'ocr-ground-truth',
|
||||
name: 'Ground Truth Review',
|
||||
href: '/ai/ocr-ground-truth',
|
||||
description: 'Ground Truth pruefen & markieren',
|
||||
purpose: 'Effiziente Massenpruefung von OCR-Sessions. Split-View mit Confidence-Highlighting, Quick-Accept und Batch-Markierung als Ground Truth.',
|
||||
audience: ['Entwickler', 'QA'],
|
||||
subgroup: 'KI-Werkzeuge',
|
||||
},
|
||||
{
|
||||
id: 'agents',
|
||||
name: 'Agent Management',
|
||||
|
||||
@@ -23,7 +23,7 @@ export const roles: Role[] = [
|
||||
name: 'Entwickler',
|
||||
description: 'Voller Zugriff auf alle Bereiche',
|
||||
icon: 'code',
|
||||
visibleCategories: ['compliance-sdk', 'ai', 'education', 'website'],
|
||||
visibleCategories: ['communication', 'ai', 'education', 'website'],
|
||||
color: 'bg-primary-100 border-primary-300 text-primary-700',
|
||||
},
|
||||
{
|
||||
@@ -31,7 +31,7 @@ export const roles: Role[] = [
|
||||
name: 'Manager',
|
||||
description: 'Executive Uebersicht',
|
||||
icon: 'chart',
|
||||
visibleCategories: ['compliance-sdk', 'website'],
|
||||
visibleCategories: ['communication', 'website'],
|
||||
color: 'bg-blue-100 border-blue-300 text-blue-700',
|
||||
},
|
||||
{
|
||||
@@ -39,7 +39,7 @@ export const roles: Role[] = [
|
||||
name: 'Auditor',
|
||||
description: 'Compliance Pruefung',
|
||||
icon: 'clipboard',
|
||||
visibleCategories: ['compliance-sdk'],
|
||||
visibleCategories: ['communication'],
|
||||
color: 'bg-amber-100 border-amber-300 text-amber-700',
|
||||
},
|
||||
{
|
||||
@@ -47,7 +47,7 @@ export const roles: Role[] = [
|
||||
name: 'DSB',
|
||||
description: 'Datenschutzbeauftragter',
|
||||
icon: 'shield',
|
||||
visibleCategories: ['compliance-sdk'],
|
||||
visibleCategories: ['communication'],
|
||||
color: 'bg-purple-100 border-purple-300 text-purple-700',
|
||||
},
|
||||
]
|
||||
|
||||
1697
admin-lehrer/package-lock.json
generated
1697
admin-lehrer/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -18,7 +18,8 @@
|
||||
"test:all": "vitest run && playwright test --project=chromium"
|
||||
},
|
||||
"dependencies": {
|
||||
"bpmn-js": "^18.0.1",
|
||||
"@fortune-sheet/react": "^1.0.4",
|
||||
"fabric": "^6.0.0",
|
||||
"jspdf": "^4.1.0",
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.468.0",
|
||||
@@ -27,7 +28,6 @@
|
||||
"react-dom": "^18.3.1",
|
||||
"reactflow": "^11.11.4",
|
||||
"recharts": "^2.15.0",
|
||||
"fabric": "^6.0.0",
|
||||
"uuid": "^13.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -119,13 +119,6 @@ export const AI_PIPELINE_MODULES: AIModuleLink[] = [
|
||||
* Kein direkter Datenfluss zur Pipeline.
|
||||
*/
|
||||
export const AI_TOOLS_MODULES: AIModuleLink[] = [
|
||||
{
|
||||
id: 'llm-compare',
|
||||
name: 'LLM Vergleich',
|
||||
href: '/ai/llm-compare',
|
||||
description: 'KI-Provider Vergleich & Evaluation',
|
||||
icon: '⚖️',
|
||||
},
|
||||
{
|
||||
id: 'test-quality',
|
||||
name: 'Test Quality (BQAS)',
|
||||
@@ -212,27 +205,7 @@ export const AI_MODULE_RELATIONS: Record<string, AIModuleLink[]> = {
|
||||
},
|
||||
],
|
||||
// KI-Werkzeuge Relations (Standalone-Tools)
|
||||
'llm-compare': [
|
||||
{
|
||||
id: 'test-quality',
|
||||
name: 'Test Quality (BQAS)',
|
||||
href: '/ai/test-quality',
|
||||
description: 'Golden Suite & Synthetic Tests',
|
||||
},
|
||||
{
|
||||
id: 'agents',
|
||||
name: 'Agent Management',
|
||||
href: '/ai/agents',
|
||||
description: 'Multi-Agent System',
|
||||
},
|
||||
],
|
||||
'test-quality': [
|
||||
{
|
||||
id: 'llm-compare',
|
||||
name: 'LLM Vergleich',
|
||||
href: '/ai/llm-compare',
|
||||
description: 'KI-Provider vergleichen',
|
||||
},
|
||||
{
|
||||
id: 'klausur-korrektur',
|
||||
name: 'Klausur-Korrektur',
|
||||
|
||||
@@ -1,10 +1 @@
|
||||
"""
|
||||
Infrastructure management module.
|
||||
|
||||
Provides control plane for external GPU resources (vast.ai).
|
||||
"""
|
||||
|
||||
from .vast_client import VastAIClient
|
||||
from .vast_power import router as vast_router
|
||||
|
||||
__all__ = ["VastAIClient", "vast_router"]
|
||||
# Infrastructure module (vast.ai GPU management removed — see git history)
|
||||
|
||||
@@ -1,419 +0,0 @@
|
||||
"""
|
||||
Vast.ai REST API Client.
|
||||
|
||||
Verwendet die offizielle vast.ai API statt CLI fuer mehr Stabilitaet.
|
||||
API Dokumentation: https://docs.vast.ai/api
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from enum import Enum
|
||||
from typing import Optional, Dict, Any, List
|
||||
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class InstanceStatus(Enum):
|
||||
"""Vast.ai Instance Status."""
|
||||
RUNNING = "running"
|
||||
STOPPED = "stopped"
|
||||
EXITED = "exited"
|
||||
LOADING = "loading"
|
||||
SCHEDULING = "scheduling"
|
||||
CREATING = "creating"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
@dataclass
|
||||
class AccountInfo:
|
||||
"""Informationen ueber den vast.ai Account."""
|
||||
credit: float # Aktuelles Guthaben in USD
|
||||
balance: float # Balance (meist 0)
|
||||
total_spend: float # Gesamtausgaben
|
||||
username: str
|
||||
email: str
|
||||
has_billing: bool
|
||||
|
||||
@classmethod
|
||||
def from_api_response(cls, data: Dict[str, Any]) -> "AccountInfo":
|
||||
"""Erstellt AccountInfo aus API Response."""
|
||||
return cls(
|
||||
credit=data.get("credit", 0.0),
|
||||
balance=data.get("balance", 0.0),
|
||||
total_spend=abs(data.get("total_spend", 0.0)), # API gibt negativ zurück
|
||||
username=data.get("username", ""),
|
||||
email=data.get("email", ""),
|
||||
has_billing=data.get("has_billing", False),
|
||||
)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Serialisiert zu Dictionary."""
|
||||
return {
|
||||
"credit": self.credit,
|
||||
"balance": self.balance,
|
||||
"total_spend": self.total_spend,
|
||||
"username": self.username,
|
||||
"email": self.email,
|
||||
"has_billing": self.has_billing,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class InstanceInfo:
|
||||
"""Informationen ueber eine vast.ai Instanz."""
|
||||
id: int
|
||||
status: InstanceStatus
|
||||
machine_id: Optional[int] = None
|
||||
gpu_name: Optional[str] = None
|
||||
num_gpus: int = 1
|
||||
gpu_ram: Optional[float] = None # GB
|
||||
cpu_ram: Optional[float] = None # GB
|
||||
disk_space: Optional[float] = None # GB
|
||||
dph_total: Optional[float] = None # $/hour
|
||||
public_ipaddr: Optional[str] = None
|
||||
ports: Dict[str, Any] = field(default_factory=dict)
|
||||
label: Optional[str] = None
|
||||
image_uuid: Optional[str] = None
|
||||
started_at: Optional[datetime] = None
|
||||
|
||||
@classmethod
|
||||
def from_api_response(cls, data: Dict[str, Any]) -> "InstanceInfo":
|
||||
"""Erstellt InstanceInfo aus API Response."""
|
||||
status_map = {
|
||||
"running": InstanceStatus.RUNNING,
|
||||
"exited": InstanceStatus.EXITED,
|
||||
"loading": InstanceStatus.LOADING,
|
||||
"scheduling": InstanceStatus.SCHEDULING,
|
||||
"creating": InstanceStatus.CREATING,
|
||||
}
|
||||
|
||||
actual_status = data.get("actual_status", "unknown")
|
||||
status = status_map.get(actual_status, InstanceStatus.UNKNOWN)
|
||||
|
||||
# Parse ports mapping
|
||||
ports = {}
|
||||
if "ports" in data and data["ports"]:
|
||||
ports = data["ports"]
|
||||
|
||||
# Parse started_at
|
||||
started_at = None
|
||||
if "start_date" in data and data["start_date"]:
|
||||
try:
|
||||
started_at = datetime.fromtimestamp(data["start_date"], tz=timezone.utc)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
return cls(
|
||||
id=data.get("id", 0),
|
||||
status=status,
|
||||
machine_id=data.get("machine_id"),
|
||||
gpu_name=data.get("gpu_name"),
|
||||
num_gpus=data.get("num_gpus", 1),
|
||||
gpu_ram=data.get("gpu_ram"),
|
||||
cpu_ram=data.get("cpu_ram"),
|
||||
disk_space=data.get("disk_space"),
|
||||
dph_total=data.get("dph_total"),
|
||||
public_ipaddr=data.get("public_ipaddr"),
|
||||
ports=ports,
|
||||
label=data.get("label"),
|
||||
image_uuid=data.get("image_uuid"),
|
||||
started_at=started_at,
|
||||
)
|
||||
|
||||
def get_endpoint_url(self, internal_port: int = 8001) -> Optional[str]:
|
||||
"""Berechnet die externe URL fuer einen internen Port."""
|
||||
if not self.public_ipaddr:
|
||||
return None
|
||||
|
||||
# vast.ai mapped interne Ports auf externe Ports
|
||||
# Format: {"8001/tcp": [{"HostIp": "0.0.0.0", "HostPort": "12345"}]}
|
||||
port_key = f"{internal_port}/tcp"
|
||||
if port_key in self.ports:
|
||||
port_info = self.ports[port_key]
|
||||
if isinstance(port_info, list) and port_info:
|
||||
host_port = port_info[0].get("HostPort")
|
||||
if host_port:
|
||||
return f"http://{self.public_ipaddr}:{host_port}"
|
||||
|
||||
# Fallback: Direkter Port
|
||||
return f"http://{self.public_ipaddr}:{internal_port}"
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Serialisiert zu Dictionary."""
|
||||
return {
|
||||
"id": self.id,
|
||||
"status": self.status.value,
|
||||
"machine_id": self.machine_id,
|
||||
"gpu_name": self.gpu_name,
|
||||
"num_gpus": self.num_gpus,
|
||||
"gpu_ram": self.gpu_ram,
|
||||
"cpu_ram": self.cpu_ram,
|
||||
"disk_space": self.disk_space,
|
||||
"dph_total": self.dph_total,
|
||||
"public_ipaddr": self.public_ipaddr,
|
||||
"ports": self.ports,
|
||||
"label": self.label,
|
||||
"started_at": self.started_at.isoformat() if self.started_at else None,
|
||||
}
|
||||
|
||||
|
||||
class VastAIClient:
|
||||
"""
|
||||
Async Client fuer vast.ai REST API.
|
||||
|
||||
Verwendet die offizielle API unter https://console.vast.ai/api/v0/
|
||||
"""
|
||||
|
||||
BASE_URL = "https://console.vast.ai/api/v0"
|
||||
|
||||
def __init__(self, api_key: str, timeout: float = 30.0):
|
||||
self.api_key = api_key
|
||||
self.timeout = timeout
|
||||
self._client: Optional[httpx.AsyncClient] = None
|
||||
|
||||
async def _get_client(self) -> httpx.AsyncClient:
|
||||
"""Lazy Client-Erstellung."""
|
||||
if self._client is None or self._client.is_closed:
|
||||
self._client = httpx.AsyncClient(
|
||||
timeout=self.timeout,
|
||||
headers={
|
||||
"Accept": "application/json",
|
||||
},
|
||||
)
|
||||
return self._client
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Schliesst den HTTP Client."""
|
||||
if self._client and not self._client.is_closed:
|
||||
await self._client.aclose()
|
||||
self._client = None
|
||||
|
||||
def _build_url(self, endpoint: str) -> str:
|
||||
"""Baut vollstaendige URL mit API Key."""
|
||||
sep = "&" if "?" in endpoint else "?"
|
||||
return f"{self.BASE_URL}{endpoint}{sep}api_key={self.api_key}"
|
||||
|
||||
async def list_instances(self) -> List[InstanceInfo]:
|
||||
"""Listet alle Instanzen auf."""
|
||||
client = await self._get_client()
|
||||
url = self._build_url("/instances/")
|
||||
|
||||
try:
|
||||
response = await client.get(url)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
instances = []
|
||||
if "instances" in data:
|
||||
for inst_data in data["instances"]:
|
||||
instances.append(InstanceInfo.from_api_response(inst_data))
|
||||
|
||||
return instances
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"vast.ai API error listing instances: {e}")
|
||||
raise
|
||||
|
||||
async def get_instance(self, instance_id: int) -> Optional[InstanceInfo]:
|
||||
"""Holt Details einer spezifischen Instanz."""
|
||||
client = await self._get_client()
|
||||
url = self._build_url(f"/instances/{instance_id}/")
|
||||
|
||||
try:
|
||||
response = await client.get(url)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
if "instances" in data:
|
||||
instances = data["instances"]
|
||||
# API gibt bei einzelner Instanz ein dict zurück, bei Liste eine Liste
|
||||
if isinstance(instances, list) and instances:
|
||||
return InstanceInfo.from_api_response(instances[0])
|
||||
elif isinstance(instances, dict):
|
||||
# Füge ID hinzu falls nicht vorhanden
|
||||
if "id" not in instances:
|
||||
instances["id"] = instance_id
|
||||
return InstanceInfo.from_api_response(instances)
|
||||
elif isinstance(data, dict) and "id" in data:
|
||||
return InstanceInfo.from_api_response(data)
|
||||
|
||||
return None
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 404:
|
||||
return None
|
||||
logger.error(f"vast.ai API error getting instance {instance_id}: {e}")
|
||||
raise
|
||||
|
||||
async def start_instance(self, instance_id: int) -> bool:
|
||||
"""Startet eine gestoppte Instanz."""
|
||||
client = await self._get_client()
|
||||
url = self._build_url(f"/instances/{instance_id}/")
|
||||
|
||||
try:
|
||||
response = await client.put(
|
||||
url,
|
||||
json={"state": "running"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
logger.info(f"vast.ai instance {instance_id} start requested")
|
||||
return True
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"vast.ai API error starting instance {instance_id}: {e}")
|
||||
return False
|
||||
|
||||
async def stop_instance(self, instance_id: int) -> bool:
|
||||
"""Stoppt eine laufende Instanz (haelt Disk)."""
|
||||
client = await self._get_client()
|
||||
url = self._build_url(f"/instances/{instance_id}/")
|
||||
|
||||
try:
|
||||
response = await client.put(
|
||||
url,
|
||||
json={"state": "stopped"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
logger.info(f"vast.ai instance {instance_id} stop requested")
|
||||
return True
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"vast.ai API error stopping instance {instance_id}: {e}")
|
||||
return False
|
||||
|
||||
async def destroy_instance(self, instance_id: int) -> bool:
|
||||
"""Loescht eine Instanz komplett (Disk weg!)."""
|
||||
client = await self._get_client()
|
||||
url = self._build_url(f"/instances/{instance_id}/")
|
||||
|
||||
try:
|
||||
response = await client.delete(url)
|
||||
response.raise_for_status()
|
||||
logger.info(f"vast.ai instance {instance_id} destroyed")
|
||||
return True
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"vast.ai API error destroying instance {instance_id}: {e}")
|
||||
return False
|
||||
|
||||
async def set_label(self, instance_id: int, label: str) -> bool:
|
||||
"""Setzt ein Label fuer eine Instanz."""
|
||||
client = await self._get_client()
|
||||
url = self._build_url(f"/instances/{instance_id}/")
|
||||
|
||||
try:
|
||||
response = await client.put(
|
||||
url,
|
||||
json={"label": label},
|
||||
)
|
||||
response.raise_for_status()
|
||||
return True
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"vast.ai API error setting label on instance {instance_id}: {e}")
|
||||
return False
|
||||
|
||||
async def wait_for_status(
|
||||
self,
|
||||
instance_id: int,
|
||||
target_status: InstanceStatus,
|
||||
timeout_seconds: int = 300,
|
||||
poll_interval: float = 5.0,
|
||||
) -> Optional[InstanceInfo]:
|
||||
"""
|
||||
Wartet bis eine Instanz einen bestimmten Status erreicht.
|
||||
|
||||
Returns:
|
||||
InstanceInfo wenn Status erreicht, None bei Timeout.
|
||||
"""
|
||||
deadline = asyncio.get_event_loop().time() + timeout_seconds
|
||||
|
||||
while asyncio.get_event_loop().time() < deadline:
|
||||
instance = await self.get_instance(instance_id)
|
||||
|
||||
if instance and instance.status == target_status:
|
||||
return instance
|
||||
|
||||
if instance:
|
||||
logger.debug(
|
||||
f"vast.ai instance {instance_id} status: {instance.status.value}, "
|
||||
f"waiting for {target_status.value}"
|
||||
)
|
||||
|
||||
await asyncio.sleep(poll_interval)
|
||||
|
||||
logger.warning(
|
||||
f"Timeout waiting for instance {instance_id} to reach {target_status.value}"
|
||||
)
|
||||
return None
|
||||
|
||||
async def wait_for_health(
|
||||
self,
|
||||
instance: InstanceInfo,
|
||||
health_path: str = "/health",
|
||||
internal_port: int = 8001,
|
||||
timeout_seconds: int = 600,
|
||||
poll_interval: float = 5.0,
|
||||
) -> bool:
|
||||
"""
|
||||
Wartet bis der Health-Endpoint erreichbar ist.
|
||||
|
||||
Returns:
|
||||
True wenn Health OK, False bei Timeout.
|
||||
"""
|
||||
endpoint = instance.get_endpoint_url(internal_port)
|
||||
if not endpoint:
|
||||
logger.error("No endpoint URL available for health check")
|
||||
return False
|
||||
|
||||
health_url = f"{endpoint.rstrip('/')}{health_path}"
|
||||
logger.info(f"Waiting for health at {health_url}")
|
||||
|
||||
deadline = asyncio.get_event_loop().time() + timeout_seconds
|
||||
health_client = httpx.AsyncClient(timeout=5.0)
|
||||
|
||||
try:
|
||||
while asyncio.get_event_loop().time() < deadline:
|
||||
try:
|
||||
response = await health_client.get(health_url)
|
||||
if 200 <= response.status_code < 300:
|
||||
logger.info(f"Health check passed: {health_url}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.debug(f"Health check failed: {e}")
|
||||
|
||||
await asyncio.sleep(poll_interval)
|
||||
|
||||
logger.warning(f"Health check timeout: {health_url}")
|
||||
return False
|
||||
|
||||
finally:
|
||||
await health_client.aclose()
|
||||
|
||||
async def get_account_info(self) -> Optional[AccountInfo]:
|
||||
"""
|
||||
Holt Account-Informationen inkl. Credit/Budget.
|
||||
|
||||
Returns:
|
||||
AccountInfo oder None bei Fehler.
|
||||
"""
|
||||
client = await self._get_client()
|
||||
url = self._build_url("/users/current/")
|
||||
|
||||
try:
|
||||
response = await client.get(url)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
return AccountInfo.from_api_response(data)
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.error(f"vast.ai API error getting account info: {e}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting vast.ai account info: {e}")
|
||||
return None
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user