Repository navigation
Expand file tree
/
Copy pathseo_pages.py
More file actions
1678 lines (1539 loc) · 71.4 KB
/
Copy pathseo_pages.py
File metadata and controls
1678 lines (1539 loc) · 71.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""SEO-optimized HTML pages for individual court decisions.
Serves lightweight HTML pages with:
- Schema.org LegalCase markup
- Open Graph tags
- Regeste, metadata, statute references
- Links to PDF/source
- Canonical URLs
Mounted at /entscheid/{decision_id} on the Starlette app.
"""
from __future__ import annotations
import html
import logging
import os
import re
import sqlite3
import urllib.parse
from pathlib import Path
import decision_ref
import appeal_refs
import ecthr_docket
logger = logging.getLogger("swiss-caselaw-mcp")
DATA_DIR = Path(os.environ.get("SWISS_CASELAW_DIR", str(Path.home() / ".swiss-caselaw")))
BASE_URL = os.environ.get("SWISS_CASELAW_BASE_URL", "https://mcp.opencaselaw.ch")
# ── Text reflow ───────────────────────────────────────────────────────
#
# Source corpus text is hard-wrapped at PDF column width (60–80 chars)
# and additionally wraps inline citations like "BGE 129 III 209" or
# "Art. 27 ZGB" onto their own lines. Rendering those `\n`s with
# CSS `white-space: pre-wrap` produces the jagged "citation dangling
# mid-sentence" look the user reported.
#
# Fix: split on blank lines into logical paragraphs, then within each
# paragraph collapse single newlines + whitespace runs into single
# spaces. List items (1. / a) / – ) keep their hard break so dispositiv
# orders and enumerations stay legible.
#
# This mirrors the helpers in exports.py (used by DOCX / PDF) so HTML,
# DOCX and PDF outputs all flow identically.
_LIST_MARKER_RE = re.compile(r"^([0-9]+[.)]|[a-z][.)]|[-*\u2013\u2022])\s")
# Punctuation-spacing fixes for text that has been re-joined from
# PDF-extracted lines (citation-broken inline text). Applied AFTER
# newline-as-space collapse so we tighten artefacts like "( art." and
# "L' art" without disturbing intentional whitespace inside the prose.
#
# Conservative: only the patterns that are *always* wrong in legal
# DE/FR/IT typography. Skipped intentionally:
# * `:` — French typography uses a thin space before, hard to
# distinguish from the join artefact without a NBSP signal.
# * `.` — risk of breaking abbreviations like "Bd. " or "S. ".
_PUNCT_OPEN_PAREN_RE = re.compile(r"\(\s+")
_PUNCT_CLOSE_PAREN_RE = re.compile(r"\s+\)")
_PUNCT_BEFORE_SEMI_COMMA_RE = re.compile(r"\s+([;,])")
# Apostrophe elision (FR / IT): "L' art" → "L'art". Allow-list of
# known elision prefixes — keeps the rule from gluing English closing
# quotes (e.g. `She said 'Hello' and waved` would otherwise become
# `Hello'and waved`). Longer alternatives ordered first so the regex
# matches greedily.
_PUNCT_ELISION_RE = re.compile(
r"\b("
r"jusqu|lorsqu|puisqu|presqu|quoiqu" # FR compound w/ qu'
r"|dell|nell|sull|dall|all" # IT compound w/ ll'
r"|gli" # IT
r"|qu|ch" # FR / IT digraph
r"|[ldnscmtjv]" # FR / IT mono-letter
r")(['\u2019])\s+([a-zA-Z\u00C0-\u017F])",
re.IGNORECASE,
)
def _tighten_punctuation_spacing(text: str) -> str:
if not text:
return text
text = _PUNCT_OPEN_PAREN_RE.sub("(", text)
text = _PUNCT_CLOSE_PAREN_RE.sub(")", text)
text = _PUNCT_BEFORE_SEMI_COMMA_RE.sub(r"\1", text)
text = _PUNCT_ELISION_RE.sub(r"\1\2\3", text)
return text
def _flow_paragraph(text: str) -> str:
"""Collapse a chunk of corpus text into a single re-flowable
paragraph: newlines + runs of whitespace become single spaces."""
if not text:
return ""
text = text.replace("\r\n", "\n").replace("\r", "\n")
text = re.sub(r"\s*\n\s*", " ", text)
text = re.sub(r" {2,}", " ", text)
text = _tighten_punctuation_spacing(text)
return text.strip()
def _split_paragraphs(text: str) -> list[str]:
"""Split text into logical paragraphs.
* Blank lines (``\\n\\s*\\n``) → paragraph boundary.
* Within a paragraph, lines that begin with a list marker stay as
their own paragraph (preserves dispositiv-style enumerations).
* Other single newlines collapse into spaces (joins PDF column
wraps and dangling citations).
HUDOC fallback: ECHR decisions ingested via HUDOC have many
single-newlines but ZERO blank-line breaks (their source HTML's
block boundaries collapse to ``\\n`` under BeautifulSoup's
``separator='\\n'``, never doubled). When we detect that pattern
— many ``\\n`` and no ``\\n\\n`` — we treat each ``\\n`` as a
paragraph boundary so the rendered page isn't one giant wall of
text. This kicks in only when the heuristic strongly applies, so
courts whose source HAS proper blank-line paragraph structure are
unaffected.
"""
if not text:
return []
text = text.replace("\r\n", "\n").replace("\r", "\n")
# HUDOC fallback: many single newlines, no blank lines → each line
# IS a paragraph. Threshold of 30 protects against short single-
# paragraph regestes / dispositivs.
#
# 2026-05-09 hardening: also gate on line-length distribution.
# PDF-extracted BGE Erwägungen (e.g. bge_BGE_133_III_121 E. 3.1)
# have 30+ newlines and 0 blank breaks too, but the newlines split
# mid-sentence around legal citations like "art. 394 ss CO" — those
# short citation-only lines should INLINE into the surrounding
# prose, not become standalone paragraphs. Real HUDOC paragraphs
# are legal-prose lines that average well over 30 characters; a
# majority-of-short-lines pattern indicates citation-broken inline
# text, in which case we fall through to the regular path that
# collapses single newlines into spaces.
n_newlines = text.count("\n")
n_blank_breaks = len(re.findall(r"\n\s*\n", text))
if n_newlines >= 30 and n_blank_breaks == 0:
lines = [ln.strip() for ln in text.split("\n") if ln.strip()]
short_ratio = (
sum(1 for ln in lines if len(ln) < 30) / len(lines)
if lines else 0.0
)
if lines and short_ratio < 0.30:
return [_tighten_punctuation_spacing(ln) for ln in lines]
# else: fall through — the regular newline-as-space collapse
# below produces correctly-flowed prose.
paragraphs: list[str] = []
for block in re.split(r"\n\s*\n+", text.strip()):
if not block.strip():
continue
items: list[str] = []
for raw_line in block.split("\n"):
line = raw_line.strip()
if not line:
continue
if not items:
items.append(line)
continue
if _LIST_MARKER_RE.match(line):
items.append(line)
else:
items[-1] = re.sub(r" {2,}", " ", items[-1].rstrip() + " " + line)
paragraphs.extend(_tighten_punctuation_spacing(p) for p in items)
return paragraphs
_REGESTE_SPLIT_RE = re.compile(r"(?=\b(?:Regeste|Regesto)\b)", re.IGNORECASE)
def _split_regeste(regeste: str) -> list[str]:
"""Split a multilingual regeste into per-language paragraphs.
Falls back to a single flowed paragraph when no language headers
are detectable (most cantonal decisions)."""
if not regeste or not regeste.strip():
return []
parts = [p for p in _REGESTE_SPLIT_RE.split(regeste) if p and p.strip()]
if len(parts) <= 1:
return [_flow_paragraph(regeste)]
return [_flow_paragraph(p) for p in parts if _flow_paragraph(p)]
def _paragraphs_html(text: str, *, classname: str | None = None) -> str:
"""Render `text` as a sequence of <p> elements after reflow.
Returns the empty string for empty input."""
paras = _split_paragraphs(text)
if not paras:
return ""
cls = f' class="{classname}"' if classname else ""
return "\n".join(f"<p{cls}>{_esc(p)}</p>" for p in paras)
# Court display names (subset — full list in mcp_server.py)
_COURT_NAMES = {
"bger": "Bundesgericht", "bge": "Bundesgericht (BGE)",
"bge_historical": "Bundesgericht (historisch)",
"ecthr_chamber": "EGMR (Kammer)",
"ecthr_grand_chamber": "EGMR (Grosse Kammer)",
"ecthr_committee": "EGMR (Ausschuss)",
"untb_ccpr": "UNO-Menschenrechtsausschuss (CCPR)",
"untb_cat": "UNO-Ausschuss gegen Folter (CAT)",
"untb_cerd": "UNO-Ausschuss gegen Rassendiskriminierung (CERD)",
"untb_cedaw": "UNO-Frauenrechtsausschuss (CEDAW)",
"untb_crc": "UNO-Kinderrechtsausschuss (CRC)",
"untb_crpd": "UNO-Behindertenrechtsausschuss (CRPD)",
"untb_cescr": "UNO-Sozialrechtsausschuss (CESCR)",
"untb_ced": "UNO-Ausschuss gegen das Verschwindenlassen (CED)",
"unwgad": "UNO-Arbeitsgruppe über willkürliche Inhaftierung (WGAD)",
"cjeu": "Gerichtshof der Europäischen Union (EuGH)",
"icj": "Internationaler Gerichtshof (IGH)",
"bvger": "Bundesverwaltungsgericht", "bstger": "Bundesstrafgericht",
"bpatger": "Bundespatentgericht",
"ag_gerichte": "Aargau", "ai_gerichte": "Appenzell I.Rh.",
"ar_gerichte": "Appenzell A.Rh.", "be_verwaltungsgericht": "Bern VerwG",
"be_zivilstraf": "Bern OG", "bl_gerichte": "Basel-Landschaft",
"bs_appellationsgericht": "Basel-Stadt", "fr_gerichte": "Freiburg",
"ge_gerichte": "Genf", "gl_gerichte": "Glarus", "gr_gerichte": "Graubünden",
"ju_gerichte": "Jura", "lu_gerichte": "Luzern", "ne_gerichte": "Neuenburg",
"nw_gerichte": "Nidwalden", "ow_gerichte": "Obwalden",
"sg_gerichte": "St. Gallen", "sh_gerichte": "Schaffhausen",
"so_gerichte": "Solothurn", "sz_gerichte": "Schwyz",
"tg_gerichte": "Thurgau", "ti_gerichte": "Ticino",
"ur_gerichte": "Uri", "vd_gerichte": "Waadt", "vd_findinfo": "Waadt",
"vs_gerichte": "Wallis", "zg_obergericht": "Zug OG",
"zh_obergericht": "Zürich OG", "zh_verwaltungsgericht": "Zürich VerwG",
"zh_sozialversicherungsgericht": "Zürich SozVersG",
"zh_handelsgericht": "Handelsgericht Zürich",
"zh_kassationsgericht": "Kassationsgericht Zürich",
"zh_steuerrekursgericht": "Steuerrekursgericht Zürich",
"zh_baurekursgericht": "Baurekursgericht Zürich",
# The Arbeitsgericht / Mietgericht of the Bezirksgericht Zürich; the other
# districts' divisions are a chamber of their district court.
"zh_arbeitsgericht": "Arbeitsgericht Zürich",
"zh_mietgericht": "Mietgericht Zürich",
"zh_bezirksgericht_zuerich": "Bezirksgericht Zürich",
"zh_bezirksgericht_winterthur": "Bezirksgericht Winterthur",
"zh_bezirksgericht_uster": "Bezirksgericht Uster",
"zh_bezirksgericht_pfaeffikon": "Bezirksgericht Pfäffikon",
"zh_bezirksgericht_meilen": "Bezirksgericht Meilen",
"zh_bezirksgericht_horgen": "Bezirksgericht Horgen",
"zh_bezirksgericht_hinwil": "Bezirksgericht Hinwil",
"zh_bezirksgericht_dietikon": "Bezirksgericht Dietikon",
"zh_bezirksgericht_dielsdorf": "Bezirksgericht Dielsdorf",
"zh_bezirksgericht_buelach": "Bezirksgericht Bülach",
"zh_bezirksgericht_andelfingen": "Bezirksgericht Andelfingen",
"zh_bezirksgericht_affoltern": "Bezirksgericht Affoltern",
}
def _appeal_html(row) -> str:
"""The court's appeal note for the page header: its own wording, with the
dockets it names linked where the corpus holds exactly that decision."""
text = appeal_refs.appeal_info_of(row)
if not text:
return ""
refs: list[dict] = []
try:
conn = _get_db()
try:
refs = appeal_refs.resolve(conn, text, row["court"], row["decision_id"])
finally:
conn.close()
except Exception as e: # a missing link must never cost the page
logger.debug("appeal references not resolved for %s: %s", row["decision_id"], e)
out = _esc(" · ".join(ln for ln in text.splitlines() if ln.strip()))
for ref in refs:
docket = _esc(ref["docket"])
href = _esc(f"{BASE_URL}/entscheid/{urllib.parse.quote(ref['decision_id'])}")
out = out.replace(docket, f'<a href="{href}">{docket}</a>', 1)
return out
def _court_display_name(court_code: str) -> str:
"""Court name for a decision page. A code without an entry keeps its
canton prefix in capitals ("ZH Arbeitsgericht", never "Zh Arbeitsgericht")."""
if court_code in _COURT_NAMES:
return _COURT_NAMES[court_code]
prefix, _, rest = court_code.partition("_")
if len(prefix) == 2 and rest:
return f"{prefix.upper()} {rest.replace('_', ' ').title()}"
return court_code.replace("_", " ").title()
def _get_db():
db_path = DATA_DIR / "decisions.db"
conn = sqlite3.connect(f"file:{db_path}?mode=ro&immutable=1", uri=True)
conn.row_factory = sqlite3.Row
return conn
def _get_structure_db():
"""Open the decision-structure sidecar DB if available, else None."""
db_path = Path(os.environ.get(
"SWISS_CASELAW_STRUCTURE_DB", str(DATA_DIR / "decision_structure.db")
))
if not db_path.exists():
return None
try:
conn = sqlite3.connect(f"file:{db_path}?mode=ro&immutable=1", uri=True)
conn.row_factory = sqlite3.Row
return conn
except sqlite3.Error:
return None
_E_NUMBER_LEVEL_RE = re.compile(r"^(\d*)([A-Za-z]*)$")
def _e_number_sort_key(e_number: str) -> tuple:
"""Sort '1.10' after '1.9' (numeric, not lexicographic) and keep
lettered Erwägungen in document order: '2' < '2a' < '2a/aa' <
'2a/bb' < '2b', and 'aa' < 'ab' < 'bb'.
Every level is a (number, letters) pair, so keys always compare.
The old int-or-str mix raised TypeError as soon as the structure
sidecar started carrying lettered numbers ('2a', '2aa', '3c/aa';
2026-09-06 incident). Levels split on '.' and on '/' (the extractor
writes a double-letter run under a letter as '3c/aa')."""
out = []
for level in re.split(r"[./]", str(e_number or "")):
m = _E_NUMBER_LEVEL_RE.match(level)
if level and m:
out.append((int(m.group(1)) if m.group(1) else 0, m.group(2).lower()))
else:
out.append((0, level.lower()))
return tuple(out)
def _fetch_structure(decision_id: str) -> dict | None:
"""Return {'row': structure_row, 'paragraphs': [..]} or None."""
sconn = _get_structure_db()
if sconn is None:
return None
try:
row = sconn.execute(
"SELECT * FROM structure WHERE decision_id = ?", (decision_id,)
).fetchone()
if not row:
return None
paragraphs = sconn.execute(
"SELECT e_number, depth, parent, text FROM erwaegungen_paragraph "
"WHERE decision_id = ? ORDER BY depth, e_number",
(decision_id,),
).fetchall()
paragraphs = sorted(
[dict(p) for p in paragraphs],
key=lambda p: _e_number_sort_key(p["e_number"]),
)
return {"row": dict(row), "paragraphs": paragraphs}
finally:
sconn.close()
_REFERENCE_DB_PATH = DATA_DIR / "reference_graph.db"
_STATUTE_RE = re.compile(r"^ART\.([^.]+)(?:\.ABS\.([^.]+))?\.(.+)$")
def _get_reference_db():
"""Open reference_graph.db read-only. Returns None if unavailable
(the page falls back to the no-citations layout in that case)."""
if not _REFERENCE_DB_PATH.exists():
return None
try:
return sqlite3.connect(
f"file:{_REFERENCE_DB_PATH}?mode=ro&immutable=1",
uri=True, timeout=30,
)
except Exception:
return None
def _decision_id_variants(did: str) -> list[str]:
"""BGE-style ids appear with and without the leading court prefix in the
citation graph; try both so the join hits regardless of the storage form."""
variants = {did}
if did.startswith("bge_"):
variants.add(did[4:]) # "bge_BGE_..." → "BGE_..."
if did.startswith("BGE_"):
variants.add("bge_" + did)
return list(variants)
def _parse_statute_id(sid: str) -> tuple[str, str, str] | None:
"""Parse 'ART.20.ABS.2.OR' → ('OR', '20', 'Art. 20 Abs. 2 OR').
Returns None if the shape is unrecognised."""
if not sid:
return None
m = _STATUTE_RE.match(sid)
if not m:
return None
art, para, abbr = m.group(1), m.group(2), m.group(3)
label = f"Art. {art}"
if para:
label += f" Abs. {para}"
label += f" {abbr}"
return (abbr, art, label)
def _fetch_citations(decision_id: str, *, limit: int = 10) -> dict:
"""Pull the citation-graph context for a decision: outbound case
citations, inbound case citations, statute references."""
out: list[tuple[str, str, int]] = []
inb: list[tuple[str, int]] = []
statutes: list[tuple[str, str, str, int]] = []
conn = _get_reference_db()
if conn is None:
return {"out": out, "in": inb, "statutes": statutes}
try:
ids = _decision_id_variants(decision_id)
ph = ",".join("?" * len(ids))
for row in conn.execute(
f"SELECT target_decision_id, MIN(target_ref) ref, COUNT(*) c "
f"FROM citation_targets "
f"WHERE source_decision_id IN ({ph}) AND target_decision_id IS NOT NULL "
f"GROUP BY target_decision_id ORDER BY c DESC LIMIT ?",
(*ids, limit),
).fetchall():
out.append((row[0], row[1] or row[0], row[2]))
for row in conn.execute(
f"SELECT source_decision_id, COUNT(*) c "
f"FROM citation_targets "
f"WHERE target_decision_id IN ({ph}) "
f"GROUP BY source_decision_id ORDER BY c DESC LIMIT ?",
(*ids, limit),
).fetchall():
inb.append((row[0], row[1]))
for row in conn.execute(
f"SELECT statute_id, mention_count FROM decision_statutes "
f"WHERE decision_id IN ({ph}) "
f"ORDER BY mention_count DESC LIMIT ?",
(*ids, limit),
).fetchall():
parsed = _parse_statute_id(row[0])
if parsed:
statutes.append((parsed[0], parsed[1], parsed[2], row[1]))
except sqlite3.OperationalError:
pass
finally:
conn.close()
return {"out": out, "in": inb, "statutes": statutes}
def _esc(text: str | None) -> str:
return html.escape(text or "", quote=True)
def _short_court_label(court_code: str) -> str:
"""Compact court display name for citation lists. Falls back to the
underscore-stripped code when not in _COURT_NAMES."""
if not court_code:
return ""
if court_code in _COURT_NAMES:
return _COURT_NAMES[court_code]
return court_code.replace("_", " ").upper()
_COURT_SHORT = {
"bger": "BGer", "bvger": "BVGer", "bstger": "BStGer", "bpatger": "BPatGer",
"bge": "BGE", "bge_historical": "BGE", "bge_egmr": "EGMR",
"ch_bundesrat": "BR", "mkg": "MKG", "hudoc_ch": "EGMR",
"ecthr_chamber": "EGMR", "ecthr_grand_chamber": "EGMR (GK)",
"ecthr_committee": "EGMR",
"untb_ccpr": "CCPR",
"untb_cat": "CAT",
"untb_cerd": "CERD",
"untb_cedaw": "CEDAW",
"untb_crc": "CRC",
"untb_crpd": "CRPD",
"untb_cescr": "CESCR",
"untb_ced": "CED",
"unwgad": "WGAD",
"cjeu": "EuGH",
"icj": "IGH",
"finma": "FINMA", "finma_versicherungsrecht": "FINMA-VR", "weko": "WEKO",
"edoeb": "EDÖB", "ubi": "UBI", "elcom": "ElCom", "postcom": "PostCom",
"comcom": "ComCom", "emark": "EMARK",
}
def _short_decision_label(did: str) -> str:
"""Render a decision_id as a short, human-readable citation.
Examples:
bge_BGE_143_III_480 → 'BGE 143 III 480'
BGE_143_III_480 → 'BGE 143 III 480'
bger_4A_140_2023 → 'BGer 4A_140/2023'
zh_obergericht_NP190024 → 'ZH Obergericht NP190024'
"""
if not did:
return ""
# BGE forms first (highest precision)
if did.startswith("bge_BGE_"):
rest = did[len("bge_BGE_"):]
return "BGE " + rest.replace("_", " ")
if did.startswith("BGE_"):
return "BGE " + did[4:].replace("_", " ")
# Schweizer Sportgericht: the docket is the tribunal's own citation form
# ("SSG 2025/E/60", "TSS 2025/E/64"); no court label in front of it.
if did.startswith("ta_sst_"):
return did[len("ta_sst_"):].replace("_", "/")
# Try the longest court-prefix match.
for prefix in sorted(_COURT_SHORT, key=len, reverse=True):
if did.startswith(prefix + "_"):
docket = did[len(prefix) + 1:]
# bger 4A_140_2023 → 4A_140/2023 (slash before the 4-digit year)
if "_" in docket and docket.rsplit("_", 1)[-1].isdigit() and len(docket.rsplit("_", 1)[-1]) == 4:
head, year = docket.rsplit("_", 1)
docket = head + "/" + year
return f"{_COURT_SHORT[prefix]} {docket}"
# Cantonal pattern: "{canton}_{court_word}_{rest}" → "{CANTON} {Court} {rest}"
parts = did.split("_", 2)
if len(parts) == 3 and len(parts[0]) == 2 and parts[0].isalpha():
canton = parts[0].upper()
court_word = parts[1].replace("gerichte", "Gerichte").title()
return f"{canton} {court_word} {parts[2]}"
return did.replace("_", " ")
def _render_citation_section(citations: dict, language: str) -> str:
"""Bottom-of-page citation context: outbound, inbound, statutes.
All three lists are optional — only the populated columns render."""
out, inb, statutes = citations["out"], citations["in"], citations["statutes"]
if not (out or inb or statutes):
return ""
labels = {
"de": ("Verweise & Kontext", "Zitiert (Out)", "Zitiert von (In)", "Gesetzesartikel", "Vorinstanzen / verwandte Entscheide"),
"fr": ("Références & contexte", "Cite", "Cité par", "Articles de loi", "Décisions liées"),
"it": ("Riferimenti & contesto", "Cita", "Citato da", "Articoli di legge", "Decisioni correlate"),
}
lab = labels.get(language, labels["de"])
parts = ['<aside class="citations" id="citations">']
parts.append(f'<h2>{_esc(lab[0])}</h2>')
parts.append('<div class="citations-grid">')
if out:
parts.append(f'<div class="cit-col"><h3>{_esc(lab[1])} <span class="count">({len(out)})</span></h3><ul>')
for did, ref, cnt in out:
label = ref if ref else _short_decision_label(did)
parts.append(
f'<li><a href="/entscheid/{_esc(did)}">{_esc(label)}</a>'
+ (f' <span class="muted">×{cnt}</span>' if cnt > 1 else '')
+ '</li>'
)
parts.append('</ul></div>')
if inb:
parts.append(f'<div class="cit-col"><h3>{_esc(lab[2])} <span class="count">({len(inb)})</span></h3><ul>')
for did, cnt in inb:
parts.append(
f'<li><a href="/entscheid/{_esc(did)}">{_esc(_short_decision_label(did))}</a>'
+ (f' <span class="muted">×{cnt}</span>' if cnt > 1 else '')
+ '</li>'
)
parts.append('</ul></div>')
if statutes:
parts.append(f'<div class="cit-col"><h3>{_esc(lab[3])}</h3><ul>')
seen_labels = set()
for abbr, art, label, cnt in statutes:
if label in seen_labels:
continue
seen_labels.add(label)
parts.append(
f'<li><a href="/laws/?law={_esc(abbr)}&art={_esc(art)}">{_esc(label)}</a>'
+ (f' <span class="muted">×{cnt}</span>' if cnt > 1 else '')
+ '</li>'
)
parts.append('</ul></div>')
parts.append('</div></aside>')
return "\n".join(parts)
def _truncate(text: str | None, max_len: int) -> str:
if not text:
return ""
text = text.strip()
if len(text) <= max_len:
return text
return text[:max_len].rsplit(" ", 1)[0] + "..."
def render_decision_page(
decision_id: str,
*,
highlight: str | None = None,
e_focus: str | None = None,
resolve_reference=None,
) -> tuple[str, int, str | None]:
"""Render an HTML page for a single decision.
Returns ``(html, status_code, redirect_location)``. ``redirect_location``
is non-None only for the 301 redirect cases below; the caller must
send it as the ``Location`` header instead of ``html`` when present.
``resolve_reference``: optional ``callable(str) -> decision_id | None``
for a path that is a written reference rather than an id ("BGE 73 II 6",
"4C.230/2006"). The server passes mcp_server._resolve_reference_unique,
the resolution behind the ``cite`` tool with every tie refused, so this
module needs no second copy of the docket grammar. It must return an id
only when exactly one decision carries the reference.
Optional ``highlight``: a verbatim substring that, if found in the
Erwägung whose ``e_number`` matches ``e_focus``, is wrapped in
``<mark>…</mark>`` so the lawyer landing on the page sees the exact
sentence that triggered the citation. Used by the
find_relevant_erwaegung MCP tool's display_url so chat → browser
handoff lands on the highlighted span, not just the right anchor.
"""
conn = _get_db()
try:
row = conn.execute(
"SELECT * FROM decisions WHERE decision_id = ?", (decision_id,)
).fetchone()
if row:
return _render_decision(row, highlight=highlight, e_focus=e_focus), 200, None
# An id the row carried before a re-key (decision_id_aliases, e.g. the
# BS Gerichte case-number ids of before 2026-09-17): exact, one target,
# so indexed links and bookmarks 301 to the same decision. Joined on
# decisions and guarded against a DB without the table.
try:
prev = conn.execute(
"SELECT a.decision_id FROM decision_id_aliases a "
"JOIN decisions d ON d.decision_id = a.decision_id "
"WHERE a.previous_id = ?",
(decision_id,),
).fetchone()
except sqlite3.OperationalError:
prev = None
if prev:
location = "/entscheid/" + urllib.parse.quote(str(prev[0]), safe="")
return "", 301, location
# A BGE is stored under the direct scraper's id ("bge_140 III 244")
# and, while the entscheidsuche feed is served, "bge_BGE_140_III_244"
# as well. Links minted with either form (cite(), cli:ch, indexed
# pages) 301 to the one that exists (#40). Exact (volume, division,
# page) candidates only.
for cand in decision_ref.bge_id_candidates(decision_id):
hit = conn.execute(
"SELECT decision_id FROM decisions WHERE decision_id = ?", (cand,)
).fetchone()
if hit:
location = "/entscheid/" + urllib.parse.quote(str(hit[0]), safe="")
return "", 301, location
# P1.4: no LIKE %...% substring fallback here any more — that let
# /entscheid/1 resolve to an unrelated decision with HTTP 200 via
# nondeterministic substring matching. An EXACT docket_number match
# is safe to redirect on ONLY if it is unique; zero or multiple
# matches both 404 (the caller decoded the path segment already, so
# docket_number values containing '/' or spaces compare correctly
# here).
docket_matches = conn.execute(
"SELECT decision_id FROM decisions WHERE docket_number = ? LIMIT 2",
(decision_id,),
).fetchall()
if len(docket_matches) == 1:
canonical_id = docket_matches[0]["decision_id"]
location = "/entscheid/" + urllib.parse.quote(str(canonical_id), safe="")
return "", 301, location
# Every other spelling of a reference (BGE/ATF/DTF labels, the federal
# docket separators, joined dockets): the cite tool's resolution,
# unique matches only. Also asked when the exact docket above is
# shared by several rows, which may be one decision stored twice; a
# docket shared by different decisions stays a 404 there too.
if resolve_reference is not None:
try:
resolved_id = resolve_reference(decision_id)
except Exception: # noqa: BLE001 — a resolver fault is a 404, not a 500
logger.exception("reference resolution failed for %r", decision_id)
resolved_id = None
if resolved_id and resolved_id != decision_id:
location = "/entscheid/" + urllib.parse.quote(str(resolved_id), safe="")
return "", 301, location
return _render_404(decision_id), 404, None
finally:
conn.close()
def _apply_highlight(escaped_text: str, highlight: str) -> str:
"""Wrap the first verbatim occurrence of ``highlight`` in ``escaped_text``
with ``<mark>…</mark>``. Both inputs are HTML-escaped already; the wrapper
tags are injected raw. Case-sensitive on the raw substring (lawyers cite
verbatim quotes), but normalises whitespace runs so PDF column wrapping
in the corpus doesn't defeat the match.
"""
if not highlight or not escaped_text:
return escaped_text
needle = _esc(highlight.strip())
if not needle:
return escaped_text
# Whitespace-tolerant match: replace runs of whitespace in BOTH the
# haystack and needle with a single space for matching, but rewrite
# the original positions in the haystack — so we don't lose layout.
norm_re = re.compile(r"\s+")
flat_hay = norm_re.sub(" ", escaped_text)
flat_needle = norm_re.sub(" ", needle)
idx = flat_hay.find(flat_needle)
if idx < 0:
return escaped_text
# Re-find the same position in the un-flattened haystack by walking
# both strings in lockstep.
j = 0 # cursor in escaped_text
flat_cursor = 0
start = end = -1
while j < len(escaped_text):
ch = escaped_text[j]
flat_ch = " " if ch.isspace() else ch
# advance the flat cursor only when we emit a non-collapsed char
if not (ch.isspace() and j > 0 and escaped_text[j - 1].isspace()):
if flat_cursor == idx and start < 0:
start = j
flat_cursor += 1
if flat_cursor == idx + len(flat_needle):
end = j + 1
break
j += 1
if start < 0 or end < 0:
return escaped_text
return escaped_text[:start] + "<mark>" + escaped_text[start:end] + "</mark>" + escaped_text[end:]
def _render_decision(
row: sqlite3.Row,
*,
highlight: str | None = None,
e_focus: str | None = None,
) -> str:
did = row["decision_id"]
court = row["court"] or ""
court_name = _court_display_name(court)
appeal_html = _appeal_html(row)
# The division that decided (e.g. the Arbeitsgericht of a Bezirksgericht).
chamber = (row["chamber"] if "chamber" in row.keys() else None) or ""
chamber = chamber.strip() if chamber.strip() not in ("", "-") else ""
canton = row["canton"] or ""
# ECtHR dockets carry a _yyyymmdd key suffix that must never reach a page
# title, an og:title or the Schema.org LegalCase name.
docket = ecthr_docket.display_docket(row["court"], row["docket_number"]) or did
date = row["decision_date"] or ""
language = row["language"] or "de"
title = row["title"] or ""
regeste = row["regeste"] or ""
full_text = row["full_text"] or ""
source_url = row["source_url"] or ""
pdf_url = row["pdf_url"] or ""
# Clean regeste for meta description
clean_regeste = re.sub(r"<[^>]+>", " ", regeste) # strip HTML tags
clean_regeste = re.sub(r"^Regeste\s*\n?\s*", "", clean_regeste) # strip "Regeste" prefix
clean_regeste = re.sub(r"^Regesto\s*\n?\s*", "", clean_regeste)
meta_desc = _truncate(re.sub(r"\s+", " ", clean_regeste).strip(), 160)
# Page title
if title:
page_title = f"{docket}, {_truncate(title, 60)} | OpenCaseLaw"
else:
page_title = f"{docket}, {court_name} | OpenCaseLaw"
canonical = f"{BASE_URL}/entscheid/{did}"
# Mint both identifiers for the Schema.org LegalCase block:
# - cli:ch (Swiss-native, primary): captures cantonal sovereignty,
# trilingualism, pinpoint and version as first-class axes.
# - ECLI (European projection): deterministic many-to-one
# projection used for cross-border interop. See cli_ch.py.
try:
from cli_ch import mint_cli_ch
cli_ch_uri = mint_cli_ch(
decision_id=did,
court=court,
docket_number=docket,
)
except Exception:
cli_ch_uri = None
try:
from ecli import mint_ecli
ecli_uri = mint_ecli(
decision_id=did,
court=court,
docket_number=docket,
decision_date=date,
language=language,
)
except Exception:
ecli_uri = None
# Schema.org LegalCase — enriched 2026-05-21 with identifier (ECLI),
# citation (case-citation graph), and legislationCited (statute graph).
# These three fields are what turns a Schema.org LegalCase from "page
# title + date" into a machine-readable legal record. The arrays are
# capped (100 / 100) so the per-decision payload stays well under
# 100 KB even for the most citation-heavy BGE.
schema_json = {
"@context": "https://schema.org",
"@type": "LegalCase",
"name": docket,
"description": _truncate(regeste, 300),
"datePublished": date,
"inLanguage": language,
"court": {
"@type": "GovernmentOrganization",
"name": court_name,
"address": {
"@type": "PostalAddress",
"addressCountry": "CH",
},
},
"url": canonical,
"isPartOf": {
"@type": "Dataset",
"name": "Swiss Case Law Open Dataset",
"url": "https://opencaselaw.ch",
},
}
identifiers = []
if cli_ch_uri:
identifiers.append({
"@type": "PropertyValue",
"propertyID": "cli:ch",
"value": cli_ch_uri,
})
if ecli_uri:
identifiers.append({
"@type": "PropertyValue",
"propertyID": "ECLI",
"value": ecli_uri,
})
if identifiers:
schema_json["identifier"] = identifiers if len(identifiers) > 1 else identifiers[0]
if source_url:
schema_json["sameAs"] = source_url
# Enrich with outbound case + statute citations from the reference
# graph. _fetch_citations returns {"out": [(target_id, ref, count)],
# "in": [...], "statutes": [(law_code, article, version, count)]}.
# We cap at 100 each so the per-decision payload stays under 100 KB
# even on citation-heavy BGEs.
try:
_citations = _fetch_citations(did)
except Exception:
_citations = None
if _citations:
out_cases = _citations.get("out") or []
if out_cases:
schema_json["citation"] = [
{
"@type": "LegalCase",
"name": (ref or target_id),
"url": f"{BASE_URL}/entscheid/{target_id}",
}
for (target_id, ref, _count) in out_cases[:100]
if target_id
]
cited_statutes = _citations.get("statutes") or []
if cited_statutes:
schema_json["legislationCited"] = [
{
"@type": "Legislation",
"name": f"Art. {article} {law_code}".strip(),
}
for (law_code, article, _version, _count) in cited_statutes[:100]
if law_code and article
]
import json
schema_str = json.dumps(schema_json, ensure_ascii=False)
# Language labels
lang_labels = {"de": "Deutsch", "fr": "Français", "it": "Italiano", "rm": "Rumantsch"}
lang_label = lang_labels.get(language, language)
# Regeste paragraphs — multilingual headers split per-language, then
# each language is reflowed (collapses PDF column line-wraps).
regeste_html = ""
if regeste:
for para in _split_regeste(regeste):
regeste_html += f"<p>{_esc(para)}</p>\n"
# Structured fields (Sachverhalt / Erwägungen / Dispositiv) from sidecar DB
structure = _fetch_structure(did)
structured_html = ""
if structure and structure["row"]:
srow = structure["row"]
sachverhalt = srow.get("sachverhalt") or ""
dispositiv = srow.get("dispositiv") or ""
paragraphs = structure["paragraphs"]
try:
import json as _json
disp_orders = _json.loads(srow["dispositiv_orders"]) if srow.get("dispositiv_orders") else []
except Exception:
disp_orders = []
parts = ['<section class="structured">']
if sachverhalt:
parts.append('<details><summary><strong>Sachverhalt</strong></summary>')
parts.append(f'<div class="section-body">{_paragraphs_html(sachverhalt)}</div></details>')
if paragraphs:
parts.append('<details open><summary><strong>Erwägungen</strong> '
f'<span class="count">({len(paragraphs)} Absätze)</span></summary>')
parts.append('<div class="erwaegungen">')
# If we received a ?highlight=… query, render a banner above
# the Erwägungen section so the lawyer sees WHY the page was
# opened with a highlight (came from chat / Word add-in).
if highlight and e_focus:
parts.append(
f'<div class="match-banner" role="status">'
f'<span class="match-banner-icon" aria-hidden="true">★</span> '
f'Treffer in <a href="#e-{_esc(e_focus.replace(".", "-"))}">'
f'E. {_esc(e_focus)}</a> — markierter Satz unten hervorgehoben.'
f'</div>'
)
for p in paragraphs:
indent_px = (p["depth"] - 1) * 16
e_label = f"E. {p['e_number']}"
anchor = f"e-{p['e_number'].replace('.', '-')}"
# Each Erwägung is paragraph-flowed; the E-number anchor
# sits inline with the first paragraph for compact scanning.
e_paras = _split_paragraphs(p["text"])
if not e_paras:
continue
# Apply the ?highlight= substring only to the focused
# Erwägung — never elsewhere — so the same string showing up
# in another paragraph (boilerplate, repeated tests) doesn't
# also get marked.
is_focus = bool(e_focus and p["e_number"] == e_focus)
first_esc = _esc(e_paras[0])
if is_focus and highlight:
first_esc = _apply_highlight(first_esc, highlight)
first_html = (
f'<a class="e-num" href="#{anchor}">{_esc(e_label)}</a> '
f'{first_esc}'
)
rest_paras = []
for par in e_paras[1:]:
par_esc = _esc(par)
if is_focus and highlight:
par_esc = _apply_highlight(par_esc, highlight)
rest_paras.append(f'<p>{par_esc}</p>')
rest_html = "".join(rest_paras)
focus_class = " erw-focus" if is_focus and highlight else ""
parts.append(
f'<div class="erw{focus_class}" id="{anchor}" style="margin-left:{indent_px}px">'
f'<p class="e-text">{first_html}</p>{rest_html}</div>'
)
parts.append('</div></details>')
if dispositiv:
parts.append('<details open><summary><strong>Dispositiv</strong></summary>')
if disp_orders:
parts.append('<ol class="dispositiv-orders">')
for order in disp_orders:
parts.append(f'<li>{_esc(order)}</li>')
parts.append('</ol>')
else:
parts.append(f'<div class="section-body">{_paragraphs_html(dispositiv)}</div>')
parts.append('</details>')
parts.append('</section>')
structured_html = "\n".join(parts)
# Full decision text — collapsed by default when structured view is available
text_excerpt = ""
if full_text:
is_open = "" if structure else " open"
text_excerpt = f"""
<details{is_open}>
<summary>Volltext (verifizierbarer Originaltext)</summary>
<div class="fulltext">{_paragraphs_html(full_text)}</div>
</details>"""
# Citation graph context — outbound + inbound + statute references.
citations = _fetch_citations(did)
citations_html = _render_citation_section(citations, language)
# Localised section labels
breadcrumb_labels = {"de": "Startseite", "fr": "Accueil", "it": "Home"}
sources_labels = {"de": "Quelle", "fr": "Source", "it": "Fonte"}
pdf_labels = {"de": "Original-PDF", "fr": "PDF original", "it": "PDF originale"}
export_labels = {"de": "Export", "fr": "Export", "it": "Esporta"}
home_label = breadcrumb_labels.get(language, "Home")
source_label = sources_labels.get(language, "Source")
pdf_label = pdf_labels.get(language, "Original PDF")
appeal_label = {"de": "Weiterzug / Verweise", "fr": "Recours / renvois",
"it": "Ricorso / rinvii"}.get(language, "Appeal / references")
export_label = export_labels.get(language, "Export")
return f"""<!DOCTYPE html>