guicybercode's picture
Publish experimental multilingual microdataset draft
99a46bd verified
Raw History Blame
16.8 kB
#!/usr/bin/env python3
"""Validate the bilingual fictional technology-ethics microdataset.
SPDX-License-Identifier: MIT
"""
from __future__ import annotations
import argparse
import json
import re
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable
ROOT = Path(__file__).resolve().parent
DEFAULT_DATA = ROOT / "data" / "train.jsonl"
EXPECTED_PAIR_DOMAINS = {
"ice-tech-ethics-01": "emergency-energy-allocation",
"ice-tech-ethics-02": "public-safety-surveillance",
"ice-tech-ethics-03": "algorithmic-resource-governance",
"ice-tech-ethics-04": "sustainable-computing",
"ice-tech-ethics-05": "autonomous-access-control",
"ice-tech-ethics-06": "emotion-recognition",
"ice-tech-ethics-07": "healthcare-ai",
"ice-tech-ethics-08": "autonomous-logistics",
"ice-tech-ethics-09": "generative-ai-memorials",
"ice-tech-ethics-10": "workplace-algorithms",
"ice-tech-ethics-11": "biometric-access",
"ice-tech-ethics-12": "conversational-ai-spiritual-care",
}
EXPECTED_PAIR_MOTIFS = {
"ice-tech-ethics-01": "geothermal-valley",
"ice-tech-ethics-02": "glacier-lagoon",
"ice-tech-ethics-03": "basalt-bay",
"ice-tech-ethics-04": "winter-greenhouse",
"ice-tech-ethics-05": "mossy-lava-field",
"ice-tech-ethics-06": "black-sand-coast",
"ice-tech-ethics-07": "stormy-fjord",
"ice-tech-ethics-08": "snowy-highlands",
"ice-tech-ethics-09": "volcanic-island",
"ice-tech-ethics-10": "winter-harbor",
"ice-tech-ethics-11": "lava-ridge-shelter",
"ice-tech-ethics-12": "glacier-edge-shelter",
}
ALLOWED_CONCEPTS = {
"care-for-vulnerable",
"common-good",
"creation-care",
"hospitality",
"human-dignity",
"humility",
"justice",
"love-of-neighbor",
"non-coercion",
"remembrance",
"sabbath-rest",
"stewardship",
"truthfulness",
}
PLURALISM_COMMITMENTS = {
"multiple-worldviews-welcome",
"no-group-consensus-claim",
"no-required-assent",
}
REVIEW_FOCUS = {
"bilingual-equivalence",
"cultural-non-attribution",
"technology-ethics",
"theological-pluralism",
}
RECORD_KEYS = {
"audience",
"christian_ethics_concepts",
"creation",
"discussion_question",
"fictionality",
"id",
"intended_use",
"landscape_motif",
"language",
"license",
"pair_id",
"perspectives",
"pluralism",
"scenario_title",
"setting",
"status",
"technology_domain",
"topic_tags",
"translation_of",
"version",
}
ID_PATTERN = re.compile(r"^ice-tech-ethics-(?:0[1-9]|1[0-2])-(?:pt-br|en)$")
PAIR_PATTERN = re.compile(r"^ice-tech-ethics-(?:0[1-9]|1[0-2])$")
SLUG_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
PROHIBITED_PHRASES = {
"a visão cristã é",
"aceitar jesus",
"all christians",
"christians believe",
"christians must",
"converter-se ao cristianismo",
"cristãos acreditam",
"cristãos devem",
"deve acreditar",
"icelanders believe",
"islandeses acreditam",
"must believe",
"only correct answer",
"the christian view is",
"todos os cristãos",
"única resposta correta",
}
def _read_jsonl(path: Path) -> tuple[list[dict[str, Any]], list[str]]:
records: list[dict[str, Any]] = []
errors: list[str] = []
try:
lines = path.read_text(encoding="utf-8").splitlines()
except (OSError, UnicodeError) as exc:
return [], [f"cannot read {path}: {exc}"]
for line_number, raw_line in enumerate(lines, 1):
if not raw_line.strip():
errors.append(f"line {line_number}: blank JSONL line")
continue
try:
value = json.loads(raw_line, parse_constant=_reject_constant)
except (json.JSONDecodeError, ValueError) as exc:
errors.append(f"line {line_number}: invalid JSON: {exc}")
continue
if not isinstance(value, dict):
errors.append(f"line {line_number}: record must be a JSON object")
continue
records.append(value)
return records, errors
def _reject_constant(token: str) -> Any:
raise ValueError(f"non-standard JSON constant {token!r}")
def _nonempty_text(value: Any, *, minimum: int = 1) -> bool:
return isinstance(value, str) and len(value.strip()) >= minimum
def _exact_keys(value: Any, expected: set[str]) -> bool:
return isinstance(value, dict) and set(value) == expected
def _record_text(record: dict[str, Any]) -> str:
return json.dumps(record, ensure_ascii=False, sort_keys=True).casefold()
def _duplicate_values(values: Iterable[str]) -> set[str]:
return {value for value, count in Counter(values).items() if count > 1}
def validate_records(records: list[dict[str, Any]]) -> list[str]:
"""Return human-readable validation errors for already parsed records."""
errors: list[str] = []
if len(records) != 24:
errors.append(f"dataset must contain exactly 24 records; found {len(records)}")
record_ids = [record.get("id") for record in records if isinstance(record.get("id"), str)]
for duplicate in sorted(_duplicate_values(record_ids)):
errors.append(f"duplicate record id {duplicate!r}")
pairs: dict[str, list[dict[str, Any]]] = defaultdict(list)
for index, record in enumerate(records, 1):
label = str(record.get("id") or f"line-{index}")
if set(record) != RECORD_KEYS:
missing = sorted(RECORD_KEYS - set(record))
unexpected = sorted(set(record) - RECORD_KEYS)
errors.append(
f"{label}: record keys mismatch; missing={missing}, unexpected={unexpected}"
)
record_id = record.get("id")
pair_id = record.get("pair_id")
language = record.get("language")
if not isinstance(record_id, str) or not ID_PATTERN.fullmatch(record_id):
errors.append(f"{label}: invalid id")
if not isinstance(pair_id, str) or not PAIR_PATTERN.fullmatch(pair_id):
errors.append(f"{label}: invalid pair_id")
else:
pairs[pair_id].append(record)
if language not in {"pt-BR", "en"}:
errors.append(f"{label}: language must be pt-BR or en")
elif isinstance(pair_id, str):
expected_id = f"{pair_id}-{'pt-br' if language == 'pt-BR' else 'en'}"
if record_id != expected_id:
errors.append(f"{label}: id must be {expected_id!r}")
if record.get("version") != "1.0.0":
errors.append(f"{label}: version must be '1.0.0'")
if record.get("status") != "ai-generated-draft-human-review-required":
errors.append(f"{label}: invalid review status")
if record.get("license") != "CC-BY-4.0":
errors.append(f"{label}: license must be CC-BY-4.0")
if record.get("intended_use") != "facilitated-ethical-discussion":
errors.append(f"{label}: invalid intended_use")
if record.get("audience") != ["adult-learners", "educators"]:
errors.append(f"{label}: audience must be adult-learners and educators")
expected_domain = EXPECTED_PAIR_DOMAINS.get(pair_id)
if record.get("technology_domain") != expected_domain:
errors.append(f"{label}: unexpected technology_domain")
expected_motif = EXPECTED_PAIR_MOTIFS.get(pair_id)
if record.get("landscape_motif") != expected_motif:
errors.append(f"{label}: unexpected landscape_motif")
if not _nonempty_text(record.get("scenario_title"), minimum=8):
errors.append(f"{label}: scenario_title is too short")
if not _nonempty_text(record.get("setting"), minimum=100):
errors.append(f"{label}: setting must be substantive")
question = record.get("discussion_question")
if not _nonempty_text(question, minimum=40) or not question.strip().endswith("?"):
errors.append(f"{label}: discussion_question must be a substantive question")
tags = record.get("topic_tags")
if (
not isinstance(tags, list)
or not 2 <= len(tags) <= 5
or len(tags) != len(set(tags))
or not all(isinstance(tag, str) and SLUG_PATTERN.fullmatch(tag) for tag in tags)
):
errors.append(f"{label}: topic_tags must contain 2-5 unique slugs")
concepts = record.get("christian_ethics_concepts")
if (
not isinstance(concepts, list)
or not 2 <= len(concepts) <= 4
or len(concepts) != len(set(concepts))
or not set(concepts) <= ALLOWED_CONCEPTS
):
errors.append(f"{label}: invalid christian_ethics_concepts")
fictionality = record.get("fictionality")
if not _exact_keys(
fictionality,
{"claims_real_icelandic_or_christian_practices", "is_fictional", "notice"},
):
errors.append(f"{label}: invalid fictionality object")
else:
if fictionality["is_fictional"] is not True:
errors.append(f"{label}: scenario must be marked fictional")
if fictionality["claims_real_icelandic_or_christian_practices"] is not False:
errors.append(f"{label}: record must disclaim real-practice claims")
notice = fictionality["notice"]
expected_terms = ("ficcional", "não descreve") if language == "pt-BR" else ("fictional", "does not describe")
if not _nonempty_text(notice, minimum=80) or not all(term in notice.casefold() for term in expected_terms):
errors.append(f"{label}: fictionality notice is incomplete for {language}")
pluralism = record.get("pluralism")
if not _exact_keys(pluralism, {"commitments", "required", "safeguard"}):
errors.append(f"{label}: invalid pluralism object")
else:
if pluralism["required"] is not True:
errors.append(f"{label}: pluralism safeguard must be required")
commitments = pluralism["commitments"]
if not isinstance(commitments, list) or set(commitments) != PLURALISM_COMMITMENTS or len(commitments) != 3:
errors.append(f"{label}: pluralism commitments are incomplete")
if not _nonempty_text(pluralism["safeguard"], minimum=120):
errors.append(f"{label}: pluralism safeguard must be substantive")
creation = record.get("creation")
if not _exact_keys(creation, {"human_review_status", "method", "review_focus"}):
errors.append(f"{label}: invalid creation object")
else:
if creation["method"] != "ai-generated-original-draft":
errors.append(f"{label}: creation method must disclose AI generation")
if creation["human_review_status"] != "required-before-curated-release-or-use":
errors.append(f"{label}: human review requirement is missing")
focus = creation["review_focus"]
if not isinstance(focus, list) or set(focus) != REVIEW_FOCUS or len(focus) != 4:
errors.append(f"{label}: review_focus is incomplete")
perspectives = record.get("perspectives")
if not isinstance(perspectives, list) or len(perspectives) != 2:
errors.append(f"{label}: exactly two perspectives are required")
else:
perspective_ids: list[str] = []
arguments: list[str] = []
for perspective_index, perspective in enumerate(perspectives):
pointer = f"{label}: perspective[{perspective_index}]"
if not _exact_keys(perspective, {"argument", "id", "questions", "title"}):
errors.append(f"{pointer}: invalid object")
continue
perspective_ids.append(perspective["id"])
arguments.append(perspective["argument"])
if not _nonempty_text(perspective["title"], minimum=8):
errors.append(f"{pointer}: title is too short")
if not _nonempty_text(perspective["argument"], minimum=120):
errors.append(f"{pointer}: argument must be substantive")
questions = perspective["questions"]
if (
not isinstance(questions, list)
or len(questions) != 2
or len(set(questions)) != 2
or not all(_nonempty_text(item, minimum=20) and item.strip().endswith("?") for item in questions)
):
errors.append(f"{pointer}: exactly two substantive questions are required")
if set(perspective_ids) != {"a", "b"} or len(perspective_ids) != 2:
errors.append(f"{label}: perspective ids must be a and b")
if len(arguments) == 2 and arguments[0].strip() == arguments[1].strip():
errors.append(f"{label}: perspectives must present distinct arguments")
text = _record_text(record)
for phrase in sorted(PROHIBITED_PHRASES):
if phrase in text:
errors.append(f"{label}: prohibited universalizing or proselytizing phrase {phrase!r}")
expected_pairs = set(EXPECTED_PAIR_DOMAINS)
if set(pairs) != expected_pairs:
errors.append(
f"pair set mismatch; missing={sorted(expected_pairs - set(pairs))}, "
f"unexpected={sorted(set(pairs) - expected_pairs)}"
)
stable_fields = (
"audience",
"christian_ethics_concepts",
"creation",
"intended_use",
"landscape_motif",
"license",
"status",
"technology_domain",
"topic_tags",
"version",
)
for pair_id in sorted(expected_pairs):
pair_records = pairs.get(pair_id, [])
languages = [record.get("language") for record in pair_records]
if len(pair_records) != 2 or Counter(languages) != Counter({"pt-BR": 1, "en": 1}):
errors.append(f"{pair_id}: pair must contain exactly one pt-BR and one en record")
continue
by_language = {record["language"]: record for record in pair_records}
source = by_language["pt-BR"]
translated = by_language["en"]
if source.get("translation_of") is not None:
errors.append(f"{source['id']}: pt-BR root must have null translation_of")
if translated.get("translation_of") != source.get("id"):
errors.append(f"{translated['id']}: en record must translate directly from pt-BR root")
for field in stable_fields:
if source.get(field) != translated.get(field):
errors.append(f"{pair_id}: bilingual invariant {field!r} differs")
if [item.get("id") for item in source.get("perspectives", [])] != [
item.get("id") for item in translated.get("perspectives", [])
]:
errors.append(f"{pair_id}: perspective order differs across languages")
return errors
def validate_repository(data_path: Path = DEFAULT_DATA) -> list[str]:
"""Validate data plus the minimum Hugging Face release files."""
records, errors = _read_jsonl(data_path)
errors.extend(validate_records(records))
readme = ROOT / "README.md"
license_file = ROOT / "LICENSE"
try:
readme_text = readme.read_text(encoding="utf-8")
except (OSError, UnicodeError) as exc:
errors.append(f"cannot read {readme}: {exc}")
else:
required_card_fragments = (
"---\nlanguage:\n- pt\n- en\n",
"license: cc-by-4.0",
"path: data/train.jsonl",
"AI-generated",
"human review",
)
for fragment in required_card_fragments:
if fragment not in readme_text:
errors.append(f"README.md is missing required fragment {fragment!r}")
try:
license_text = license_file.read_text(encoding="utf-8")
except (OSError, UnicodeError) as exc:
errors.append(f"cannot read {license_file}: {exc}")
else:
if "Creative Commons Attribution 4.0 International" not in license_text:
errors.append("LICENSE does not identify CC BY 4.0")
if "https://creativecommons.org/licenses/by/4.0/legalcode" not in license_text:
errors.append("LICENSE does not link to the official legal code")
return errors
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--data", type=Path, default=DEFAULT_DATA)
args = parser.parse_args()
errors = validate_repository(args.data)
if errors:
for error in errors:
print(f"ERROR: {error}")
return 1
print("valid: 24 records in 12 pt-BR/en pairs")
return 0
if __name__ == "__main__":
raise SystemExit(main())