Spaces:
Running
Running
File size: 10,047 Bytes
d8f8a45 | 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 | """
UndertriAI — Synthetic Case Generator (Theme 4: Self-Improvement)
When the agent masters a domain, this generates harder synthetic variants
of existing cases. All generation is deterministic string manipulation —
no LLM calls.
5 perturbation types:
1. custody_escalation — custody just below statutory threshold
2. co_accused_conflict — co-accused with opposite bail outcome
3. section_ambiguity — IPC ↔ BNSS section swap
4. evidence_reversal — retracted witness / unreliable evidence
5. surety_complexity — non-resident surety complication
"""
import copy
import re
from typing import Any, Dict, List, Optional
# IPC → BNSS mapping (subset used by the environment)
IPC_TO_BNSS = {
"302": "103", "307": "109", "376": "64", "304B": "80", "395": "310",
"392": "309", "420": "318", "498A": "85", "406": "316", "465": "336",
"323": "115", "354": "74", "120B": "61", "506": "351", "121": "147",
"379": "303", "324": "117", "354A": "75",
}
BNSS_TO_IPC = {v: k for k, v in IPC_TO_BNSS.items()}
# ── Required fields for schema validation ────────────────────────────
REQUIRED_FIELDS = {
"case_id": str,
"crime_type": str,
"ipc_sections": list,
"custody_months": (int, float),
"charge_sheet": str,
"ground_truth": dict,
"curriculum_stage": (int, float),
}
def is_schema_valid(episode: Dict[str, Any]) -> bool:
"""
Check that all required fields are present and correct types.
Returns True/False — used to filter out malformed synthetic cases.
"""
for field, expected_type in REQUIRED_FIELDS.items():
if field not in episode:
return False
if not isinstance(episode[field], expected_type):
return False
# ground_truth must have 'outcome'
gt = episode.get("ground_truth", {})
if "outcome" not in gt:
return False
return True
def generate_variants(
source_episode: Dict[str, Any],
n: int = 5,
) -> List[Dict[str, Any]]:
"""
Generate up to n synthetic harder variants of a real episode.
Each variant applies exactly ONE perturbation.
Returns only valid variants (may be fewer than n if some
perturbations can't be applied cleanly).
"""
if not is_schema_valid(source_episode):
return []
perturbations = [
_custody_escalation,
_co_accused_conflict,
_section_ambiguity,
_evidence_reversal,
_surety_complexity,
]
variants = []
for i, perturb_fn in enumerate(perturbations[:n]):
try:
variant = perturb_fn(source_episode)
if variant is not None and is_schema_valid(variant):
variants.append(variant)
except Exception:
# Skip perturbation on any error
continue
return variants
# ── Perturbation 1: Custody Escalation ───────────────────────────────
def _custody_escalation(episode: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
Set custody_months to exactly 2 months below the statutory threshold.
Forces careful computation — case is NOT yet eligible for default bail.
"""
ep = copy.deepcopy(episode)
max_sent = ep.get("max_sentence_years", 5.0)
# Threshold is 50% of max sentence in months
threshold_months = (max_sent * 12) / 2
new_custody = max(1.0, threshold_months - 2.0)
old_custody = ep.get("custody_months", 0)
ep["custody_months"] = round(new_custody, 1)
# Update charge sheet text if it mentions custody duration
charge = ep.get("charge_sheet", "")
if str(int(old_custody)) in charge:
charge = charge.replace(
f"{int(old_custody)} months",
f"{int(new_custody)} months",
)
ep["charge_sheet"] = charge
# Metadata
parent_id = ep.get("case_id", "UNKNOWN")
ep["case_id"] = f"SYN_{parent_id}_CUST"
ep["source"] = "synthetic"
ep["parent_case_id"] = parent_id
ep["perturbation_type"] = "custody_escalation"
ep["difficulty"] = "hard"
return ep
# ── Perturbation 2: Co-Accused Conflict ──────────────────────────────
def _co_accused_conflict(episode: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
Add a co-accused with the OPPOSITE bail outcome.
Forces the agent to make a parity argument.
"""
ep = copy.deepcopy(episode)
gt = ep.get("ground_truth", {})
gt_outcome = gt.get("outcome", "Bail Granted")
# Opposite outcome
if "grant" in gt_outcome.lower():
co_outcome = "Bail Denied"
else:
co_outcome = "Bail Granted"
ep["co_accused"] = [{
"name": "Co-Accused A",
"bail_outcome": co_outcome,
"sections": ep.get("ipc_sections", []),
}]
gt["parity_argument_used"] = True
ep["ground_truth"] = gt
# Add parity context to defence arguments
defence = ep.get("defence_arguments", [])
defence.append(
f"Co-accused was {'granted' if 'grant' in co_outcome.lower() else 'denied'} "
f"bail under identical charges — parity principle applies."
)
ep["defence_arguments"] = defence
# Metadata
parent_id = ep.get("case_id", "UNKNOWN")
ep["case_id"] = f"SYN_{parent_id}_COAC"
ep["source"] = "synthetic"
ep["parent_case_id"] = parent_id
ep["perturbation_type"] = "co_accused_conflict"
ep["difficulty"] = "hard"
return ep
# ── Perturbation 3: Section Ambiguity (IPC ↔ BNSS) ──────────────────
def _section_ambiguity(episode: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
Swap IPC sections to BNSS equivalents (or vice versa).
Tests schema drift adaptability.
"""
ep = copy.deepcopy(episode)
sections = ep.get("ipc_sections", [])
if not sections:
return None
new_sections = []
swapped = False
for sec in sections:
sec_clean = sec.strip()
if sec_clean in IPC_TO_BNSS:
new_sections.append(IPC_TO_BNSS[sec_clean])
swapped = True
elif sec_clean in BNSS_TO_IPC:
new_sections.append(BNSS_TO_IPC[sec_clean])
swapped = True
else:
new_sections.append(sec_clean)
if not swapped:
return None
ep["ipc_sections"] = new_sections
# Update charge sheet references
charge = ep.get("charge_sheet", "")
for old_sec, new_sec in zip(sections, new_sections):
if old_sec != new_sec:
charge = charge.replace(f"Section {old_sec}", f"Section {new_sec}")
charge = charge.replace(f"section {old_sec}", f"section {new_sec}")
ep["charge_sheet"] = charge
# Metadata
parent_id = ep.get("case_id", "UNKNOWN")
ep["case_id"] = f"SYN_{parent_id}_SECT"
ep["source"] = "synthetic"
ep["parent_case_id"] = parent_id
ep["perturbation_type"] = "section_ambiguity"
ep["difficulty"] = "hard"
return ep
# ── Perturbation 4: Evidence Reversal ────────────────────────────────
def _evidence_reversal(episode: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
Add a contradicting element to the strongest evidence.
Tests whether the agent updates assessment when evidence weakens.
"""
ep = copy.deepcopy(episode)
# Find the strongest evidence mention
evidence_keywords = ["witness", "evidence", "testimony", "eyewitness"]
pros_args = ep.get("prosecution_arguments", [])
charge = ep.get("charge_sheet", "")
# Check prosecution arguments first
target_arg = None
for arg in pros_args:
if any(kw in arg.lower() for kw in evidence_keywords):
target_arg = arg
break
if target_arg is None:
# Check charge sheet sentences
sentences = [s.strip() for s in charge.split('.') if s.strip()]
for sent in sentences:
if any(kw in sent.lower() for kw in evidence_keywords):
target_arg = sent
break
if target_arg is None:
return None # No evidence to reverse
# Add reversal to defence arguments
defence = ep.get("defence_arguments", [])
defence.append(
"However, the key prosecution evidence was subsequently found "
"unreliable — the primary witness retracted their statement and "
"forensic analysis raised doubts about the physical evidence."
)
ep["defence_arguments"] = defence
# Metadata
parent_id = ep.get("case_id", "UNKNOWN")
ep["case_id"] = f"SYN_{parent_id}_EVID"
ep["source"] = "synthetic"
ep["parent_case_id"] = parent_id
ep["perturbation_type"] = "evidence_reversal"
ep["difficulty"] = "hard"
return ep
# ── Perturbation 5: Surety Complexity ────────────────────────────────
def _surety_complexity(episode: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
Add a surety complication forcing careful condition assessment.
"""
ep = copy.deepcopy(episode)
# Add surety complication to defence arguments
defence = ep.get("defence_arguments", [])
defence.append(
"Proposed surety is a non-resident relative with no verifiable "
"local assets or employment in the jurisdiction. Surety bond "
"amount of Rs. 5,00,000 proposed."
)
ep["defence_arguments"] = defence
# Add surety info to accused profile
profile = ep.get("accused_profile", {})
profile["surety_status"] = "non-resident, unverified assets"
ep["accused_profile"] = profile
# Metadata
parent_id = ep.get("case_id", "UNKNOWN")
ep["case_id"] = f"SYN_{parent_id}_SURE"
ep["source"] = "synthetic"
ep["parent_case_id"] = parent_id
ep["perturbation_type"] = "surety_complexity"
ep["difficulty"] = "hard"
return ep
|