added
This commit is contained in:
1 parent
c04ca92c13
commit
31253e14c1
1008 files changed
+46154
-10432
No files matched your search
@@ -18,13 +18,14 @@ from typing import Any, Iterable
|
||||
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
||||
|
||||
|
||||
PIPELINE_VERSION = "1.1.0"
|
||||
PUBLIC_SCHEMA_VERSION = "1.1"
|
||||
PIPELINE_VERSION = "1.2.0"
|
||||
PUBLIC_SCHEMA_VERSION = "1.2"
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
REPOSITORY_ROOT = BASE_DIR.parents[1]
|
||||
DEFAULT_CONFIG = BASE_DIR / "config" / "local.json"
|
||||
SCHEMA_PATH = BASE_DIR / "schemas" / "future-map-signal.schema.json"
|
||||
PATCH_SCHEMA_PATH = BASE_DIR / "schemas" / "reasoning-patch.schema.json"
|
||||
READINESS_PATCH_SCHEMA_PATH = BASE_DIR / "schemas" / "readiness-patch.schema.json"
|
||||
TRACKING_KEYS = {
|
||||
"token", "auth", "signature", "sig", "key", "j", "r", "redirect",
|
||||
"fbclid", "gclid", "mc_cid", "mc_eid", "isfreemail",
|
||||
@@ -233,6 +234,55 @@ def empty_reasoning() -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def empty_source_assessment(source: dict[str, Any], links: list[dict[str, Any]], media: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
basis: list[str] = []
|
||||
if source.get("Summary"):
|
||||
basis.append("summary")
|
||||
if source.get("Notes"):
|
||||
basis.append("notes")
|
||||
if source.get("CaptureContext"):
|
||||
basis.append("capture-context")
|
||||
if source.get("SourceURL") or any(item.get("kind") == "source" for item in links):
|
||||
basis.append("source-url")
|
||||
if media:
|
||||
basis.append("connected-media")
|
||||
return {
|
||||
"status": "unassessed",
|
||||
"basis": basis,
|
||||
"missing_elements": [],
|
||||
"assessment": None,
|
||||
"review_required": True,
|
||||
"assessed_at": None,
|
||||
"assessed_by": None,
|
||||
}
|
||||
|
||||
|
||||
def empty_media_inspection(copy_status: str) -> dict[str, Any]:
|
||||
return {
|
||||
"requirement": "unassessed",
|
||||
"status": "missing" if copy_status == "missing" else "unassessed",
|
||||
"method": None,
|
||||
"inspected_at": None,
|
||||
"inspected_by": None,
|
||||
}
|
||||
|
||||
|
||||
def preserve_media_assessment(media: list[dict[str, Any]], previous: dict[str, Any] | None) -> None:
|
||||
previous_media = {item.get("id"): item for item in (previous or {}).get("media", [])}
|
||||
for item in media:
|
||||
prior = previous_media.get(item.get("id"))
|
||||
unchanged = prior and all(
|
||||
prior.get(key) == item.get(key)
|
||||
for key in ("source_reference", "source_url", "content_hash", "copy_status")
|
||||
)
|
||||
if unchanged:
|
||||
item["inspection"] = prior.get("inspection", empty_media_inspection(item["copy_status"]))
|
||||
item["description"] = prior.get("description")
|
||||
item["extracted_text"] = prior.get("extracted_text")
|
||||
else:
|
||||
item["inspection"] = empty_media_inspection(item["copy_status"])
|
||||
|
||||
|
||||
def build_record(
|
||||
source_path: Path,
|
||||
source: dict[str, Any],
|
||||
@@ -330,6 +380,7 @@ def build_record(
|
||||
})
|
||||
|
||||
fingerprint = sha256_bytes("\n".join(fingerprint_parts).encode("utf-8"))
|
||||
preserve_media_assessment(media, previous)
|
||||
if (
|
||||
previous
|
||||
and previous.get("schema_version") == PUBLIC_SCHEMA_VERSION
|
||||
@@ -347,6 +398,11 @@ def build_record(
|
||||
elif reasoning.get("status") not in {"complete", "stale"}:
|
||||
reasoning = empty_reasoning()
|
||||
|
||||
if previous and not source_changed and previous.get("source_assessment"):
|
||||
source_assessment = previous["source_assessment"]
|
||||
else:
|
||||
source_assessment = empty_source_assessment(source, links, media)
|
||||
|
||||
canonical_url = explicit_source_url or next((item["url"] for item in links if item["kind"] == "source"), None)
|
||||
result = {
|
||||
"schema_version": PUBLIC_SCHEMA_VERSION,
|
||||
@@ -381,6 +437,7 @@ def build_record(
|
||||
},
|
||||
"links": links,
|
||||
"media": media,
|
||||
"source_assessment": source_assessment,
|
||||
"rights": {
|
||||
"ownership": "unknown", "rights_status": "unknown", "source_access": "unknown",
|
||||
"publication_policy": "publish-with-attribution", "publication_decision": "publish",
|
||||
@@ -404,7 +461,7 @@ def build_record(
|
||||
|
||||
def basic_validate(record: dict[str, Any], base: Path) -> list[str]:
|
||||
errors: list[str] = []
|
||||
required = {"schema_version", "id", "source_record", "source", "links", "media", "rights", "reasoning", "review", "provenance"}
|
||||
required = {"schema_version", "id", "source_record", "source", "links", "media", "source_assessment", "rights", "reasoning", "review", "provenance"}
|
||||
missing = required - set(record)
|
||||
if missing:
|
||||
errors.append("missing top-level fields: " + ", ".join(sorted(missing)))
|
||||
@@ -428,6 +485,20 @@ def basic_validate(record: dict[str, Any], base: Path) -> list[str]:
|
||||
public_path = item.get("public_path")
|
||||
if not public_path or not (base / public_path).exists():
|
||||
errors.append(f"missing copied media path: {public_path}")
|
||||
inspection = item.get("inspection", {})
|
||||
if inspection.get("status") == "inspected" and (not inspection.get("method") or not inspection.get("inspected_by")):
|
||||
errors.append(f"inspected media requires method and inspected_by: {item.get('id')}")
|
||||
if inspection.get("requirement") == "not-required" and inspection.get("status") != "not-required":
|
||||
errors.append(f"not-required media must have not-required status: {item.get('id')}")
|
||||
assessment = record.get("source_assessment", {})
|
||||
if assessment.get("status") == "sufficient":
|
||||
incomplete = [
|
||||
item.get("id") for item in record.get("media", [])
|
||||
if item.get("inspection", {}).get("requirement") == "required"
|
||||
and item.get("inspection", {}).get("status") != "inspected"
|
||||
]
|
||||
if incomplete:
|
||||
errors.append("sufficient source assessment has uninspected required media: " + ", ".join(incomplete))
|
||||
reasoning = record.get("reasoning", {})
|
||||
if reasoning.get("status") == "complete":
|
||||
if not reasoning.get("analysis") or len(reasoning.get("analysis", "")) < 20:
|
||||
@@ -492,6 +563,8 @@ def render_outputs(base: Path) -> dict[str, int]:
|
||||
if item.get("content_id") and item.get("path")
|
||||
}
|
||||
counts = {state: 0 for state in ("pending", "complete", "stale", "failed", "excluded")}
|
||||
readiness_counts = {state: 0 for state in ("unassessed", "sufficient", "partial", "insufficient", "unavailable", "needs-human-context")}
|
||||
inspection_counts: dict[str, int] = {}
|
||||
media_names: set[str] = set()
|
||||
pending_lines: list[str] = []
|
||||
index_lines: list[str] = []
|
||||
@@ -501,6 +574,15 @@ def render_outputs(base: Path) -> dict[str, int]:
|
||||
reasoning = record["reasoning"]
|
||||
state = reasoning.get("status", "pending")
|
||||
counts[state] = counts.get(state, 0) + 1
|
||||
assessment = record.get("source_assessment", {})
|
||||
readiness_state = assessment.get("status", "unassessed")
|
||||
readiness_counts[readiness_state] = readiness_counts.get(readiness_state, 0) + 1
|
||||
required_media_pending = 0
|
||||
for media_item in record.get("media", []):
|
||||
inspection_state = media_item.get("inspection", {}).get("status", "unassessed")
|
||||
inspection_counts[inspection_state] = inspection_counts.get(inspection_state, 0) + 1
|
||||
if media_item.get("inspection", {}).get("requirement") == "required" and inspection_state != "inspected":
|
||||
required_media_pending += 1
|
||||
title = source.get("title") or f"Future Map Signal {source['source_file_id']}"
|
||||
summary = source.get("summary")
|
||||
capture_context = source.get("capture_context", {}).get("text")
|
||||
@@ -511,6 +593,7 @@ def render_outputs(base: Path) -> dict[str, int]:
|
||||
f"**Date:** {source.get('date') or source.get('date_original') or 'Unknown'}", "",
|
||||
f"**Capture type:** {source.get('capture_type', 'legacy')}", "",
|
||||
f"**Reasoning:** {state}", "",
|
||||
f"**Source readiness:** {readiness_state}", "",
|
||||
])
|
||||
if summary:
|
||||
md.extend([markdown_clean(summary), ""])
|
||||
@@ -572,6 +655,8 @@ def render_outputs(base: Path) -> dict[str, int]:
|
||||
"id": record["id"], "source_file_id": source["source_file_id"], "hub_id": source.get("hub_id"), "date": source.get("date"),
|
||||
"title": title, "summary": summary, "capture_type": source.get("capture_type", "legacy"),
|
||||
"capture_context": capture_context, "intended_use": intended_use, "reasoning_status": state,
|
||||
"source_readiness_status": readiness_state,
|
||||
"required_media_pending": required_media_pending,
|
||||
"signal_types": reasoning.get("classification", {}).get("signal_types", []),
|
||||
"topics": reasoning.get("classification", {}).get("topics", []),
|
||||
"related_documents": [item.get("document_id") for item in reasoning.get("related_documents", [])],
|
||||
@@ -579,10 +664,13 @@ def render_outputs(base: Path) -> dict[str, int]:
|
||||
"record_path": f"hrecords/{source['source_file_id']}.json",
|
||||
"media_paths": [item.get("public_path") for item in record.get("media", []) if item.get("public_path")],
|
||||
}, ensure_ascii=False))
|
||||
if state in {"pending", "stale", "failed"} or record.get("review", {}).get("warnings"):
|
||||
if state in {"pending", "stale", "failed"} or assessment.get("review_required") or required_media_pending or record.get("review", {}).get("warnings"):
|
||||
pending_lines.append(json.dumps({
|
||||
"id": record["id"], "source_file_id": source["source_file_id"], "hub_id": source.get("hub_id"), "date": source.get("date"),
|
||||
"title": title, "reasoning_status": state,
|
||||
"source_readiness_status": readiness_state,
|
||||
"source_readiness_review_required": bool(assessment.get("review_required")),
|
||||
"required_media_pending": required_media_pending,
|
||||
"warnings": record.get("review", {}).get("warnings", []),
|
||||
"record_path": f"hrecords/{source['source_file_id']}.json",
|
||||
}, ensure_ascii=False))
|
||||
@@ -591,6 +679,8 @@ def render_outputs(base: Path) -> dict[str, int]:
|
||||
"schema_version": "1.0", "pipeline_version": PIPELINE_VERSION,
|
||||
"required_tag": "Future Map", "record_count": len(records),
|
||||
"media_file_count": len(media_names), "reasoning_counts": counts,
|
||||
"source_assessment_counts": readiness_counts,
|
||||
"media_inspection_counts": inspection_counts,
|
||||
"latest_source_date": max((item["source_record"].get("date") or "" for item in records), default="") or None,
|
||||
"generated_at": utc_now(),
|
||||
}
|
||||
@@ -746,6 +836,76 @@ def validate_reasoning_patch(patch: dict[str, Any]) -> list[str]:
|
||||
return errors
|
||||
|
||||
|
||||
def validate_readiness_patch(patch: dict[str, Any], record: dict[str, Any]) -> list[str]:
|
||||
errors = schema_validate(patch, READINESS_PATCH_SCHEMA_PATH)
|
||||
required = {"record_id", "source_assessment", "media_inspections"}
|
||||
missing = required - set(patch)
|
||||
if missing:
|
||||
errors.append("missing fields: " + ", ".join(sorted(missing)))
|
||||
return errors
|
||||
known_media = {item.get("id") for item in record.get("media", [])}
|
||||
media_ids = [item.get("media_id") for item in patch.get("media_inspections", [])]
|
||||
if len(media_ids) != len(set(media_ids)):
|
||||
errors.append("media_inspections contains duplicate media_id values")
|
||||
unknown = sorted(str(item) for item in set(media_ids) - known_media)
|
||||
if unknown:
|
||||
errors.append("unknown media_id values: " + ", ".join(unknown))
|
||||
for item in patch.get("media_inspections", []):
|
||||
if item.get("status") == "inspected" and (not item.get("method") or not item.get("inspected_by")):
|
||||
errors.append(f"inspected media requires method and inspected_by: {item.get('media_id')}")
|
||||
if item.get("requirement") == "not-required" and item.get("status") != "not-required":
|
||||
errors.append(f"not-required media must have not-required status: {item.get('media_id')}")
|
||||
assessment_status = patch.get("source_assessment", {}).get("status")
|
||||
patched = {item.get("media_id"): item for item in patch.get("media_inspections", [])}
|
||||
incomplete_required: list[str] = []
|
||||
for item in record.get("media", []):
|
||||
inspection = patched.get(item.get("id"), item.get("inspection", {}))
|
||||
if inspection.get("requirement") == "required" and inspection.get("status") != "inspected":
|
||||
incomplete_required.append(str(item.get("id")))
|
||||
if assessment_status == "sufficient" and incomplete_required:
|
||||
errors.append("sufficient assessment requires inspection of required media: " + ", ".join(incomplete_required))
|
||||
return errors
|
||||
|
||||
|
||||
def command_apply_readiness(args: argparse.Namespace) -> int:
|
||||
base = Path(args.output_root).resolve() if args.output_root else BASE_DIR
|
||||
patch = json.loads(Path(args.patch).read_text(encoding="utf-8"))
|
||||
if patch.get("record_id") != args.record_id:
|
||||
raise RuntimeError("Patch record_id does not match --record-id")
|
||||
source_file_id = args.record_id.removeprefix("fm-signal-")
|
||||
record_path = base / "hrecords" / f"{source_file_id}.json"
|
||||
record = load_json(record_path)
|
||||
if not record or record.get("id") != args.record_id:
|
||||
raise FileNotFoundError(f"Derivative record not found: {record_path}")
|
||||
issues = validate_readiness_patch(patch, record)
|
||||
if issues:
|
||||
for issue in issues:
|
||||
print("ERROR", issue)
|
||||
return 1
|
||||
assessment = dict(patch["source_assessment"])
|
||||
assessment["assessed_at"] = utc_now()
|
||||
assessment["review_required"] = assessment["status"] != "sufficient"
|
||||
record["source_assessment"] = assessment
|
||||
media_patches = {item["media_id"]: item for item in patch["media_inspections"]}
|
||||
for media_item in record.get("media", []):
|
||||
media_patch = media_patches.get(media_item.get("id"))
|
||||
if not media_patch:
|
||||
continue
|
||||
media_item["inspection"] = {
|
||||
"requirement": media_patch["requirement"],
|
||||
"status": media_patch["status"],
|
||||
"method": media_patch.get("method"),
|
||||
"inspected_at": utc_now() if media_patch["status"] == "inspected" else None,
|
||||
"inspected_by": media_patch.get("inspected_by"),
|
||||
}
|
||||
media_item["description"] = media_patch.get("description")
|
||||
media_item["extracted_text"] = media_patch.get("extracted_text")
|
||||
write_json_if_changed(record_path, record)
|
||||
render_outputs(base)
|
||||
errors, _ = validate_output(base)
|
||||
return 1 if errors else 0
|
||||
|
||||
|
||||
def command_apply_reasoning(args: argparse.Namespace) -> int:
|
||||
base = Path(args.output_root).resolve() if args.output_root else BASE_DIR
|
||||
patch_path = Path(args.patch)
|
||||
@@ -762,6 +922,16 @@ def command_apply_reasoning(args: argparse.Namespace) -> int:
|
||||
record = load_json(record_path)
|
||||
if not record or record.get("id") != args.record_id:
|
||||
raise FileNotFoundError(f"Derivative record not found: {record_path}")
|
||||
assessment = record.get("source_assessment", {})
|
||||
if assessment.get("status") not in {"sufficient", "partial"}:
|
||||
raise RuntimeError("Reasoning requires a source assessment of sufficient or partial")
|
||||
incomplete_media = [
|
||||
item.get("id") for item in record.get("media", [])
|
||||
if item.get("inspection", {}).get("requirement") == "required"
|
||||
and item.get("inspection", {}).get("status") != "inspected"
|
||||
]
|
||||
if incomplete_media:
|
||||
raise RuntimeError("Reasoning requires inspection of required media: " + ", ".join(incomplete_media))
|
||||
record["reasoning"] = {
|
||||
"status": "complete",
|
||||
"analysis": patch["analysis"],
|
||||
@@ -801,6 +971,10 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
apply_reasoning.add_argument("--record-id", required=True)
|
||||
apply_reasoning.add_argument("--patch", required=True)
|
||||
apply_reasoning.add_argument("--output-root")
|
||||
apply_readiness = subparsers.add_parser("apply-readiness", help="Apply one validated source/media readiness patch.")
|
||||
apply_readiness.add_argument("--record-id", required=True)
|
||||
apply_readiness.add_argument("--patch", required=True)
|
||||
apply_readiness.add_argument("--output-root")
|
||||
return parser
|
||||
|
||||
|
||||
@@ -817,6 +991,8 @@ def main() -> int:
|
||||
return 0
|
||||
if args.command == "apply-reasoning":
|
||||
return command_apply_reasoning(args)
|
||||
if args.command == "apply-readiness":
|
||||
return command_apply_readiness(args)
|
||||
return 2
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user