File size: 17,153 Bytes
672e00d | 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 | """Parse Old Bailey Online XML (v7.2, figshare 10.15131/shef.data.4775434.v2) into one row per trial, with typed
persons, offences, verdicts, punishments and the defendant→offence→verdict→punishment joins; one row per session; one
row per Ordinary's Account. Verbatim TEI is kept in an `xml` column.
Usage: python parse_obo.py <xml_root> <out_dir> [--limit N] [--stats]
Conventions (see dataset card):
- persons.type is null when the source assigns no role (part-1 names tagged by GATE without a role).
- name = the person's own surface text (nested <persName> excluded); given/surname/gender/age/occupation/place/aliases
come from <interp> children and persNameOccupation / persNamePlace / nameAlias joins (first value wins for interps —
no repeated interp types were found in the corpus sample).
- <lb/> inside text: joined without a space (hyphenation-style breaks are the majority) unless the break sits between a
word character and an upper-case letter, where a space is inserted.
- punishments: attached via defendantPunishment joins file-wide (part-1 sentences sit in a separate punishmentSummary
div; a few joins point across trial divs — kept as the source has them, and the punishment row records the trial div
it was found in). An in-trial punishment with no join anywhere is kept with defendant_ids = [].
- charges: criminalCharge joins; target ids that resolve to nothing in the trial are kept in `unresolved_ids`.
- sessions.summary_items: every <rs> outside a trialAccount div (offence/verdict/punishment/alias/occupation/crimeDate) with its
category, text, containing div and joined ids — the 1670s–80s sessions record outcomes in supplementaryMaterial, not trials.
"""
import re, sys, json, collections
from pathlib import Path
from lxml import etree
import polars as pl
ROOT = Path(sys.argv[1]); OUT = Path(sys.argv[2]); OUT.mkdir(parents=True, exist_ok=True)
LIMIT = int(sys.argv[sys.argv.index("--limit") + 1]) if "--limit" in sys.argv else None
STATS = "--stats" in sys.argv
STRICT = etree.XMLParser(huge_tree=True)
LENIENT = etree.XMLParser(recover=True, huge_tree=True)
WS = re.compile(r"\s+")
ENC_RE = re.compile(rb'^<\?xml[^>]*encoding\s*=\s*["\']([A-Za-z0-9._-]+)["\']')
stats = collections.Counter(); warnings = []
def read_xml(path):
"""Return (root, verbatim_text). Decode with the declared encoding; parse strictly, fall back to recovery + warn."""
raw = path.read_bytes()
m = ENC_RE.match(raw[:200]); enc = m.group(1).decode() if m else "utf-8"
if raw.startswith(b"\xef\xbb\xbf"): enc = "utf-8-sig"
elif raw.startswith((b"\xff\xfe", b"\xfe\xff")): enc = "utf-16"
try: text = raw.decode(enc) # verbatim column must be lossless: no errors="replace"
except (UnicodeDecodeError, LookupError) as e:
raise SystemExit(f"{path.name}: cannot decode with declared encoding {enc!r}: {e}")
try: root = etree.fromstring(raw, STRICT)
except etree.XMLSyntaxError as e:
root = etree.fromstring(raw, LENIENT); warnings.append(f"{path.name}: recovered parse ({str(e)[:80]})"); stats["recovered_parse"] += 1
return root, text
def norm(s): return WS.sub(" ", s or "").strip()
def _collect(el, parts, skip_tag=None):
if el.tag == "lb": parts.append("\x00")
elif el.text: parts.append(el.text)
for c in el:
if not (skip_tag is not None and c.tag == skip_tag): _collect(c, parts, skip_tag)
if c.tail: parts.append(c.tail)
def text_of(el, skip_tag=None):
parts = []; _collect(el, parts, skip_tag)
s = "".join(parts)
s = re.sub(r"(\w)\x00(?=[A-Z])", r"\1 ", s).replace("\x00", "")
return norm(s)
def interps(el):
d = {}
for i in el.findall("interp"): d.setdefault(i.get("type"), i.get("value"))
return d
def parse_person(p):
d = interps(p)
has_nested = p.find(".//persName") is not None
name = text_of(p, skip_tag="persName")
if (has_nested or not name) and (d.get("given") or d.get("surname")): name = norm(f"{d.get('given') or ''} {d.get('surname') or ''}")
if not name: name = text_of(p)
return {"id": p.get("id"), "type": (p.get("type").replace("Name", "") if p.get("type") else None),
"name": name, "given": d.get("given"), "surname": d.get("surname"), "gender": d.get("gender"), "age": d.get("age"),
"occupation": d.get("occupation"), "place": None, "aliases": []}
def parse_rs(rs):
d = interps(rs)
return {**d, "id": rs.get("id"), "text": text_of(rs)}
trials, oas, sessions = [], [], []
def index_file(root):
"""File-level indexes: rs by id, persons by id (enriched from joins), places, joins by member id."""
all_rs = {rs.get("id"): (rs, parse_rs(rs)) for rs in root.iter("rs") if rs.get("id")}
all_place = {x.get("id"): text_of(x) for x in root.iter("placeName") if x.get("id")}
pers_el = [p for p in root.iter("persName")]
all_pers = {p.get("id"): parse_person(p) for p in pers_el if p.get("id")}
joins = collections.defaultdict(list); by_member = collections.defaultdict(list)
for j in root.iter("join"):
res, targets = j.get("result"), j.get("targets", "").split()
stats[f"join:{res}"] += 1; joins[res].append(targets)
for t in targets: by_member[t].append((res, targets))
for pid, per in all_pers.items(): # enrich persons from joins, once, file-wide
for res, targets in by_member.get(pid, []):
others = [t for t in targets if t != pid]
if res == "persNameOccupation" and per["occupation"] is None:
for t in others:
if t in all_rs: per["occupation"] = all_rs[t][1]["text"]
elif res == "persNamePlace" and per["place"] is None:
for t in others:
if t in all_place: per["place"] = all_place[t]
elif res == "nameAlias":
for t in others:
if t in all_rs and all_rs[t][1]["text"] not in per["aliases"]: per["aliases"].append(all_rs[t][1]["text"])
return all_rs, all_place, all_pers, pers_el, joins, by_member
def parse_session(path):
root, raw_text = read_xml(path)
if root is None: stats["unparseable"] += 1; return
session_id = path.stem
all_rs, all_place, all_pers, pers_el, joins, by_member = index_file(root)
rs_div = {}
for rs in root.iter("rs"):
if rs.get("id"):
anc = next(rs.iterancestors("div1"), None); rs_div[rs.get("id")] = anc.get("id") if anc is not None else None
body = root.find(".//body")
div_types = collections.Counter(d.get("type") for d in root.iter("div1"))
summary_items = [] # rs elements outside trialAccount divs (supplementaryMaterial / punishmentSummary / no div): early sessions record outcomes here
for rs in root.iter("rs"):
anc = next(rs.iterancestors("div1"), None)
if rs.get("id") and (anc is None or anc.get("type") != "trialAccount"):
d = all_rs[rs.get("id")][1]
linked = sorted({t for res, targets in by_member.get(rs.get("id"), []) for t in targets if t != rs.get("id")})
cat = d.get("offenceCategory") or d.get("verdictCategory") or d.get("punishmentCategory")
sub = d.get("offenceSubcategory") or d.get("verdictSubcategory") or d.get("punishmentSubcategory")
summary_items.append({"id": rs.get("id"), "type": rs.get("type"), "category": cat, "subcategory": sub, "text": d["text"],
"found_in": anc.get("id") if anc is not None else None, "linked_ids": linked})
stats[f"summary_item:{rs.get('type')}"] += 1
sessions.append({"summary_items": summary_items, "session_id": session_id, "date": session_id[:8], "part": 1 if session_id[:8] <= "18341024" else 2,
"text": text_of(body) if body is not None else text_of(root), "xml": raw_text, "n_trials": div_types.get("trialAccount", 0),
"div_types": json.dumps(dict(div_types)), "persons": [all_pers[p.get("id")] if p.get("id") else parse_person(p) for p in pers_el],
"places": [text_of(x) for x in root.iter("placeName")], "obo_url": f"https://www.oldbaileyonline.org/browse.jsp?name={session_id}"})
for div in root.iter("div1"):
stats[f"div1:{div.get('type')}"] += 1
if div.get("type") != "trialAccount": continue
tid = div.get("id"); di = interps(div)
persons = [all_pers[p.get("id")] if p.get("id") else parse_person(p) for p in div.iter("persName")]
def_ids = [p["id"] for p in persons if p["type"] == "defendant" and p["id"]] # source order
def_set = set(def_ids)
offences = [parse_rs(rs) for rs in div.iter("rs") if rs.get("type") == "offenceDescription"]
verdicts = [parse_rs(rs) for rs in div.iter("rs") if rs.get("type") == "verdictDescription"]
off_ids = {o["id"] for o in offences}; ver_ids = {v["id"] for v in verdicts}
for o in offences:
o["victim_ids"] = []; o["crime_date"] = None; o["place"] = None
for res, targets in by_member.get(o["id"], []):
others = [t for t in targets if t != o["id"]]
if res == "offenceVictim": o["victim_ids"] += others
elif res == "offencePlace":
for t in others:
if t in all_place: o["place"] = all_place[t]
elif res == "offenceCrimeDate":
for t in others:
if t in all_rs: o["crime_date"] = all_rs[t][1]["text"]
charges = []
for targets in joins.get("criminalCharge", []):
if not any(t in def_set for t in targets): continue
unresolved = [t for t in targets if t not in def_set and t not in off_ids and t not in ver_ids]
if unresolved: stats["charge_unresolved_targets"] += 1
charges.append({"defendant_ids": [t for t in targets if t in def_set], "offence_ids": [t for t in targets if t in off_ids],
"verdict_ids": [t for t in targets if t in ver_ids], "unresolved_ids": unresolved})
pun_rows = {}
for d_id in def_ids: # deterministic: defendant source order
for res, targets in by_member.get(d_id, []):
if res != "defendantPunishment": continue
for t in targets:
if t in all_rs and all_rs[t][0].get("type") == "punishmentDescription":
row = pun_rows.setdefault(t, {**all_rs[t][1], "defendant_ids": [], "found_in": rs_div.get(t)})
if d_id not in row["defendant_ids"]: row["defendant_ids"].append(d_id)
if rs_div.get(t) not in (None, tid): stats["punishment_cross_trial"] += 1
for rs in div.iter("rs"): # every punishment whose text lives in this trial, with whatever defendants the joins name (possibly another trial's)
pid = rs.get("id")
if rs.get("type") == "punishmentDescription" and pid and pid not in pun_rows:
joined = [t for res, targets in by_member.get(pid, []) if res == "defendantPunishment" for t in targets if t != pid and t in all_pers]
pun_rows[pid] = {**parse_rs(rs), "defendant_ids": joined, "found_in": tid}
if not joined: stats["punishment_unjoined"] += 1
elif not any(j in def_set for j in joined): stats["punishment_text_here_defendant_elsewhere"] += 1
trials.append({
"trial_id": tid, "session_id": session_id, "date": di.get("date") or session_id[:8], "part": 1 if session_id[:8] <= "18341024" else 2,
"text": text_of(div), "xml": etree.tostring(div, encoding="unicode"), "n_defendants": len(def_ids), "persons": persons,
"offences": [{"id": o["id"], "category": o.get("offenceCategory"), "subcategory": o.get("offenceSubcategory"), "text": o["text"],
"crime_date": o["crime_date"], "place": o["place"], "victim_ids": o["victim_ids"]} for o in offences],
"verdicts": [{"id": v["id"], "category": v.get("verdictCategory"), "subcategory": v.get("verdictSubcategory"), "text": v["text"]} for v in verdicts],
"punishments": [{"id": p["id"], "category": p.get("punishmentCategory"), "subcategory": p.get("punishmentSubcategory"), "text": p["text"],
"defendant_ids": p["defendant_ids"], "found_in": p["found_in"]} for p in pun_rows.values()],
"charges": charges, "places": [text_of(x) for x in div.iter("placeName")],
"obo_url": f"https://www.oldbaileyonline.org/browse.jsp?div={tid}"})
stats["trials"] += 1
def parse_oa(path):
root, raw_text = read_xml(path)
if root is None: stats["unparseable_oa"] += 1; return
_, _, all_pers, pers_el, _, _ = index_file(root)
div = root.find(".//div0"); di = interps(div) if div is not None else {}
body = root.find(".//body")
oas.append({"oa_id": path.stem, "date": di.get("date") or path.stem[2:10], "text": text_of(body) if body is not None else text_of(root), "xml": raw_text,
"persons": [all_pers[p.get("id")] if p.get("id") else parse_person(p) for p in pers_el],
"places": [text_of(x) for x in root.iter("placeName")], "obo_url": f"https://www.oldbaileyonline.org/browse.jsp?name={path.stem}"})
stats["oa"] += 1
files = sorted((ROOT / "sessionsPapers").glob("*.xml"))
if LIMIT: files = files[::max(1, len(files) // LIMIT)][:LIMIT]
for i, f in enumerate(files):
parse_session(f)
if i % 200 == 0: print(f"{i}/{len(files)} {f.name} trials so far {stats['trials']}", flush=True)
oa_files = sorted((ROOT / "ordinarysAccounts").glob("*.xml"))
if LIMIT: oa_files = oa_files[:max(2, LIMIT // 5)]
for f in oa_files: parse_oa(f)
used = set()
for t in trials: # source quirk: a few supplementary items share an id (e.g. s16980504-1) — suffix collision-safely and report
base = t["trial_id"]
if base in used:
k = 2
while f"{base}-dup{k}" in used: k += 1
t["trial_id"] = f"{base}-dup{k}"; stats["dup_trial_id"] += 1; warnings.append(f"duplicate trial id {base} -> {t['trial_id']}")
used.add(t["trial_id"])
PERSON = pl.Struct({"id": pl.Utf8, "type": pl.Utf8, "name": pl.Utf8, "given": pl.Utf8, "surname": pl.Utf8, "gender": pl.Utf8, "age": pl.Utf8,
"occupation": pl.Utf8, "place": pl.Utf8, "aliases": pl.List(pl.Utf8)})
SCHEMA = {
"trial_id": pl.Utf8, "session_id": pl.Utf8, "date": pl.Utf8, "part": pl.Int8, "text": pl.Utf8, "xml": pl.Utf8, "n_defendants": pl.Int32,
"persons": pl.List(PERSON),
"offences": pl.List(pl.Struct({"id": pl.Utf8, "category": pl.Utf8, "subcategory": pl.Utf8, "text": pl.Utf8, "crime_date": pl.Utf8, "place": pl.Utf8, "victim_ids": pl.List(pl.Utf8)})),
"verdicts": pl.List(pl.Struct({"id": pl.Utf8, "category": pl.Utf8, "subcategory": pl.Utf8, "text": pl.Utf8})),
"punishments": pl.List(pl.Struct({"id": pl.Utf8, "category": pl.Utf8, "subcategory": pl.Utf8, "text": pl.Utf8, "defendant_ids": pl.List(pl.Utf8), "found_in": pl.Utf8})),
"charges": pl.List(pl.Struct({"defendant_ids": pl.List(pl.Utf8), "offence_ids": pl.List(pl.Utf8), "verdict_ids": pl.List(pl.Utf8), "unresolved_ids": pl.List(pl.Utf8)})),
"places": pl.List(pl.Utf8), "obo_url": pl.Utf8,
}
df = pl.from_dicts(trials, schema=SCHEMA); assert df["trial_id"].n_unique() == df.height
df.write_parquet(OUT / "trials.parquet", compression="zstd")
oa = pl.from_dicts(oas, schema={"oa_id": pl.Utf8, "date": pl.Utf8, "text": pl.Utf8, "xml": pl.Utf8, "persons": pl.List(PERSON), "places": pl.List(pl.Utf8), "obo_url": pl.Utf8})
oa.write_parquet(OUT / "ordinarys_accounts.parquet", compression="zstd")
ses = pl.from_dicts(sessions, schema={"session_id": pl.Utf8, "date": pl.Utf8, "part": pl.Int8, "text": pl.Utf8, "xml": pl.Utf8, "n_trials": pl.Int32, "div_types": pl.Utf8,
"persons": pl.List(PERSON), "places": pl.List(pl.Utf8),
"summary_items": pl.List(pl.Struct({"id": pl.Utf8, "type": pl.Utf8, "category": pl.Utf8, "subcategory": pl.Utf8, "text": pl.Utf8, "found_in": pl.Utf8, "linked_ids": pl.List(pl.Utf8)})),
"obo_url": pl.Utf8})
ses.write_parquet(OUT / "sessions.parquet", compression="zstd")
print("\nwrote", df.shape, "trials;", ses.shape, "sessions;", oa.shape, "OA")
(OUT / "parse_warnings.txt").write_text("\n".join(warnings))
if warnings: print(f"{len(warnings)} parse warnings -> {OUT / 'parse_warnings.txt'}")
if STATS:
for k, v in sorted(stats.items()): print(f" {k:32s} {v}")
g = df.filter(pl.col("verdicts").list.eval(pl.element().struct.field("category") == "guilty").list.any())
print("guilty trials:", g.height, "| guilty with 0 punishments:", g.filter(pl.col("punishments").list.len() == 0).height)
print("trials with 0 offences:", df.filter(pl.col("offences").list.len() == 0).height, "| 0 charges:", df.filter(pl.col("charges").list.len() == 0).height,
"| punishments with no defendant:", df.explode("punishments").filter(pl.col("punishments").struct.field("defendant_ids").list.len() == 0).height)
|