514 lines
18 KiB
Python
514 lines
18 KiB
Python
"""Build public/ai-index.json from content and semantic artifacts."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import re
|
||
from datetime import date
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
|
||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||
CONTENT_ROOT = REPO_ROOT / "content"
|
||
DATA_ROOT = REPO_ROOT / "public" / "data" / "open" / "pages"
|
||
OUTPUT_PATH = REPO_ROOT / "public" / "ai-index.json"
|
||
|
||
SITE_URL = "https://indx.earth"
|
||
PUBLISHER = "Eddie Soehnel"
|
||
ORGANIZATION = "iNDX"
|
||
LICENSE_URL = "https://creativecommons.org/licenses/by/4.0/"
|
||
USAGE_INFO_URL = "https://indx.earth/wiki/license/"
|
||
|
||
MOJIBAKE_REPLACEMENTS = {
|
||
"’": "’",
|
||
"‘": "‘",
|
||
"“": "“",
|
||
"â€\x9d": "”",
|
||
"–": "–",
|
||
"—": "—",
|
||
"…": "…",
|
||
"Â\xa0": " ",
|
||
"Â": "",
|
||
}
|
||
|
||
|
||
def normalize_text(value: str) -> str:
|
||
for broken, fixed in MOJIBAKE_REPLACEMENTS.items():
|
||
value = value.replace(broken, fixed)
|
||
return value
|
||
|
||
|
||
def read_text(path: Path) -> str:
|
||
return normalize_text(path.read_text(encoding="utf-8-sig"))
|
||
|
||
|
||
def write_json(path: Path, payload: dict[str, Any]) -> None:
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
path.write_text(
|
||
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
|
||
encoding="utf-8",
|
||
newline="\n",
|
||
)
|
||
|
||
|
||
def parse_frontmatter(path: Path) -> dict[str, Any]:
|
||
content = read_text(path)
|
||
if not content.startswith("---"):
|
||
return {}
|
||
|
||
end = content.find("\n---", 3)
|
||
if end == -1:
|
||
return {}
|
||
|
||
fields: dict[str, Any] = {}
|
||
current_key: str | None = None
|
||
for raw_line in content[3:end].splitlines():
|
||
line = raw_line.rstrip()
|
||
if not line.strip():
|
||
continue
|
||
if line.startswith(" - ") and current_key:
|
||
fields.setdefault(current_key, []).append(line[4:].strip().strip('"'))
|
||
continue
|
||
match = re.match(r"^([A-Za-z0-9_-]+):\s*(.*)$", line)
|
||
if not match:
|
||
continue
|
||
key, value = match.groups()
|
||
current_key = key
|
||
value = value.strip()
|
||
if value == "":
|
||
fields[key] = []
|
||
continue
|
||
fields[key] = value.strip('"')
|
||
return fields
|
||
|
||
|
||
def slugify(value: str) -> str:
|
||
value = value.lower()
|
||
value = re.sub(r"[^a-z0-9]+", "-", value)
|
||
return value.strip("-")
|
||
|
||
|
||
def unique_sorted(values: list[str]) -> list[str]:
|
||
return sorted({v for v in values if v})
|
||
|
||
|
||
def content_to_data_dir(markdown_path: Path, frontmatter: dict[str, Any]) -> Path:
|
||
relative = markdown_path.relative_to(CONTENT_ROOT)
|
||
if relative.as_posix() == "home.md":
|
||
return DATA_ROOT / "home"
|
||
slug = str(frontmatter.get("slug") or "").strip()
|
||
if slug:
|
||
return DATA_ROOT / relative.parent / slug
|
||
return DATA_ROOT / relative.with_suffix("")
|
||
|
||
|
||
def public_artifact_path(path: Path) -> str:
|
||
"""Return the served URL path for a local public artifact."""
|
||
relative = path.relative_to(REPO_ROOT / "public")
|
||
return "/" + relative.as_posix()
|
||
|
||
|
||
def local_path_for_artifact(artifact_path: str) -> Path:
|
||
"""Resolve an ai-index artifact path to the local repo file to validate."""
|
||
clean = artifact_path.lstrip("/")
|
||
if clean.startswith("data/"):
|
||
return REPO_ROOT / "public" / clean
|
||
return REPO_ROOT / clean
|
||
|
||
|
||
def content_to_html_path(markdown_path: Path, frontmatter: dict[str, Any]) -> str:
|
||
relative = markdown_path.relative_to(CONTENT_ROOT)
|
||
if relative.as_posix() == "home.md":
|
||
return "/"
|
||
if relative.as_posix() == "healthz.md":
|
||
return "/healthz/"
|
||
if relative.parts[0] == "community-summaries":
|
||
slug = str(frontmatter.get("slug") or relative.stem)
|
||
return "/" + str(relative.parent).replace("\\", "/") + f"/{slug}.html"
|
||
return "/" + str(relative.with_suffix("")).replace("\\", "/") + "/"
|
||
|
||
|
||
def load_json(path: Path) -> Any | None:
|
||
if not path.exists():
|
||
return None
|
||
return json.loads(read_text(path))
|
||
|
||
|
||
def flatten_chunks(chunks_payload: Any) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||
document: dict[str, Any] = {}
|
||
chunks: list[dict[str, Any]] = []
|
||
|
||
if isinstance(chunks_payload, dict):
|
||
document = chunks_payload.get("document", {}) or {}
|
||
chunks = chunks_payload.get("chunks", []) or []
|
||
elif isinstance(chunks_payload, list):
|
||
for item in chunks_payload:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
if "document" in item and not document:
|
||
document = item.get("document", {}) or {}
|
||
if "chunks" in item:
|
||
chunks.extend(item.get("chunks", []) or [])
|
||
elif "chunk_id" in item:
|
||
chunks.append(item)
|
||
return document, chunks
|
||
|
||
|
||
def flatten_qa(qa_payload: Any) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||
if not isinstance(qa_payload, dict):
|
||
return {}, []
|
||
return qa_payload.get("document", {}) or {}, qa_payload.get("qa_pairs", []) or []
|
||
|
||
|
||
def collect_semantic_lists(
|
||
frontmatter: dict[str, Any],
|
||
chunks: list[dict[str, Any]],
|
||
qa_pairs: list[dict[str, Any]],
|
||
) -> dict[str, list[str]]:
|
||
topics: list[str] = []
|
||
entities: list[str] = []
|
||
concepts: list[str] = []
|
||
audiences: list[str] = []
|
||
domains: list[str] = []
|
||
|
||
tags = frontmatter.get("tags", [])
|
||
if isinstance(tags, str):
|
||
tags = [tags]
|
||
topics.extend(tags)
|
||
|
||
for chunk in chunks:
|
||
semantic_core = chunk.get("semantic_core", {}) or {}
|
||
context = chunk.get("context", {}) or {}
|
||
if semantic_core.get("primary_topic"):
|
||
topics.append(str(semantic_core["primary_topic"]))
|
||
domains.extend(semantic_core.get("domain", []) or [])
|
||
entities.extend(semantic_core.get("entities", []) or [])
|
||
concepts.extend(semantic_core.get("key_concepts", []) or [])
|
||
audiences.extend(context.get("intended_audience", []) or [])
|
||
topics.extend(chunk.get("tags", []) or [])
|
||
|
||
for qa in qa_pairs:
|
||
entities.extend(qa.get("entities", []) or [])
|
||
concepts.extend(qa.get("concepts", []) or [])
|
||
audiences.extend(qa.get("audience", []) or [])
|
||
topics.extend(qa.get("tags", []) or [])
|
||
|
||
return {
|
||
"domains": unique_sorted(domains),
|
||
"topics": unique_sorted(topics),
|
||
"entities": unique_sorted(entities),
|
||
"concepts": unique_sorted(concepts),
|
||
"audiences": unique_sorted(audiences),
|
||
}
|
||
|
||
|
||
def resource_type(frontmatter: dict[str, Any], markdown_path: Path) -> str:
|
||
document_type = str(frontmatter.get("document_type") or "").strip()
|
||
if document_type:
|
||
return document_type
|
||
if markdown_path.name == "healthz.md":
|
||
return "operational"
|
||
return "page"
|
||
|
||
|
||
def discovery_profile(resource_kind: str, chunk_count: int, qa_count: int) -> dict[str, str]:
|
||
if resource_kind == "overview":
|
||
return {
|
||
"importance": "foundational",
|
||
"retrieval_priority": "primary",
|
||
"semantic_density": "dense",
|
||
"workflow_value": "workflow-support",
|
||
}
|
||
if resource_kind == "email-summary":
|
||
density = "dense" if chunk_count >= 5 or qa_count >= 8 else "moderate"
|
||
return {
|
||
"importance": "medium",
|
||
"retrieval_priority": "secondary",
|
||
"semantic_density": density,
|
||
"workflow_value": "strategic",
|
||
}
|
||
if resource_kind == "operational":
|
||
return {
|
||
"importance": "low",
|
||
"retrieval_priority": "deep-reference",
|
||
"semantic_density": "light",
|
||
"workflow_value": "agent-operational",
|
||
}
|
||
return {
|
||
"importance": "medium",
|
||
"retrieval_priority": "secondary",
|
||
"semantic_density": "moderate",
|
||
"workflow_value": "informational",
|
||
}
|
||
|
||
|
||
def build_resource(markdown_path: Path) -> dict[str, Any]:
|
||
frontmatter = parse_frontmatter(markdown_path)
|
||
data_dir = content_to_data_dir(markdown_path, frontmatter)
|
||
chunks_path = data_dir / "chunks.json"
|
||
qa_path = data_dir / "qa.json"
|
||
|
||
chunks_payload = load_json(chunks_path)
|
||
qa_payload = load_json(qa_path)
|
||
chunk_document, chunks = flatten_chunks(chunks_payload)
|
||
qa_document, qa_pairs = flatten_qa(qa_payload)
|
||
|
||
title = str(
|
||
frontmatter.get("title")
|
||
or chunk_document.get("title")
|
||
or qa_document.get("title")
|
||
or markdown_path.stem
|
||
)
|
||
if markdown_path.name == "healthz.md":
|
||
title = "Health Check"
|
||
slug = str(frontmatter.get("slug") or chunk_document.get("slug") or slugify(title))
|
||
doc_id = str(
|
||
chunk_document.get("document_id")
|
||
or frontmatter.get("document_id")
|
||
or qa_document.get("document_id")
|
||
or f"doc-{slug}"
|
||
)
|
||
summary = str(frontmatter.get("summary") or chunk_document.get("summary") or "")
|
||
author = str(frontmatter.get("author") or chunk_document.get("author") or PUBLISHER)
|
||
kind = resource_type(frontmatter, markdown_path)
|
||
semantic = collect_semantic_lists(frontmatter, chunks, qa_pairs)
|
||
html_path = content_to_html_path(markdown_path, frontmatter)
|
||
|
||
markdown_artifact = "/" + markdown_path.relative_to(REPO_ROOT).as_posix()
|
||
chunks_artifact = public_artifact_path(chunks_path) if chunks_path.exists() else ""
|
||
qa_artifact = public_artifact_path(qa_path) if qa_path.exists() else ""
|
||
|
||
return {
|
||
"resource_id": doc_id,
|
||
"title": title,
|
||
"slug": slug,
|
||
"resource_type": kind,
|
||
"summary": summary,
|
||
"topics": semantic["topics"],
|
||
"entities": semantic["entities"],
|
||
"concepts": semantic["concepts"],
|
||
"audience": semantic["audiences"],
|
||
"trust_signals": {
|
||
"author": author,
|
||
"organization": ORGANIZATION,
|
||
"source_alignment": "Generated from authored Markdown and matching chunks.json/qa.json semantic artifacts when available.",
|
||
"credibility_hints": [
|
||
"Author and document metadata are declared in source front matter or semantic artifacts.",
|
||
"Semantic artifacts use stable document, chunk, and knowledge identifiers.",
|
||
],
|
||
},
|
||
"discovery": discovery_profile(kind, len(chunks), len(qa_pairs)),
|
||
"access": {
|
||
"access_type": "open",
|
||
"api_endpoint": chunks_artifact,
|
||
"preview_available": False,
|
||
"pricing": None,
|
||
"license": LICENSE_URL,
|
||
"usageInfo": USAGE_INFO_URL,
|
||
},
|
||
"artifacts": {
|
||
"markdown": markdown_artifact,
|
||
"html": html_path,
|
||
"chunks_json": chunks_artifact,
|
||
"qa_json": qa_artifact,
|
||
"semantic_summary_json": "",
|
||
},
|
||
"relationships": {
|
||
"related_resources": [],
|
||
"supports": [],
|
||
"depends_on": [],
|
||
"expands": semantic["topics"][:8],
|
||
},
|
||
"coverage": {
|
||
"chunk_count": len(chunks),
|
||
"qa_pair_count": len(qa_pairs),
|
||
"referenced_chunk_count": len(
|
||
{
|
||
chunk_id
|
||
for qa in qa_pairs
|
||
for chunk_id in (qa.get("chunk_ids", []) or qa.get("source_chunks", []) or [])
|
||
}
|
||
),
|
||
},
|
||
}
|
||
|
||
|
||
def build_external_whitepaper_resources(home_markdown: Path) -> list[dict[str, Any]]:
|
||
content = read_text(home_markdown) if home_markdown.exists() else ""
|
||
whitepapers = [
|
||
(
|
||
"res-industriesig-whitepaper",
|
||
"Industry Index For The AI Era",
|
||
"IndustrySIG",
|
||
"https://docs.google.com/document/d/18N4xmQWO2M3fzC_1o2baHnrJFlfOuXjOBEUS2crmC9Q/edit?usp=sharing",
|
||
),
|
||
(
|
||
"res-networksig-whitepaper",
|
||
"Decentralized AI-Native Professional Networking",
|
||
"NetworkSIG",
|
||
"https://docs.google.com/document/d/1ZRELDV0Z77YeVsxXid1EFsATBwrmexVJHhwc1faIIzI/edit?usp=sharing",
|
||
),
|
||
(
|
||
"res-snap-for-science-whitepaper",
|
||
"Use Case: Boost Conservation, Stewardship And Funding For Natural Spaces",
|
||
"Snap For Science",
|
||
"https://docs.google.com/document/d/1j2SSwzAKAAsnebkG1n1FA7fDm6p0D8o0ZJBhypbULr4/edit?usp=sharing",
|
||
),
|
||
(
|
||
"res-future-growth-engines-whitepaper",
|
||
"Future Growth Engines For The U.S.: The One Starting Now That Unlocks America's Next Economic Supercycle",
|
||
"iNDX strategy",
|
||
"https://docs.google.com/document/d/1WMY24vrRMjzs6VLTfQmx6cFPZi9Nq5Ac9rL3fhvVsrc/edit?usp=sharing",
|
||
),
|
||
(
|
||
"res-interconnected-ecosystems-whitepaper",
|
||
"The U.S. Interconnected Ecosystems Renaissance: A Strategic & Tactical Guide to Building the Next American Growth Engine",
|
||
"iNDX strategy",
|
||
"https://docs.google.com/document/d/12jKSUYFg0DsqGtLeaSvJV31Zh0DfobM0Gfz4syGaGMM/edit?usp=sharing",
|
||
),
|
||
]
|
||
|
||
resources: list[dict[str, Any]] = []
|
||
for resource_id, title, topic, url in whitepapers:
|
||
if url not in content:
|
||
continue
|
||
resources.append(
|
||
{
|
||
"resource_id": resource_id,
|
||
"title": title,
|
||
"slug": slugify(title),
|
||
"resource_type": "whitepaper",
|
||
"summary": f"External white paper referenced from the iNDX Overview page for {topic}.",
|
||
"topics": [topic, "whitepaper", "research-library"],
|
||
"entities": [ORGANIZATION],
|
||
"concepts": ["white papers", "research library", topic],
|
||
"audience": ["researchers", "industry participants", "potential partners"],
|
||
"trust_signals": {
|
||
"author": PUBLISHER,
|
||
"organization": ORGANIZATION,
|
||
"source_alignment": "Explicitly referenced in the authored home.md white papers section.",
|
||
"credibility_hints": [
|
||
"Listed by the publisher as part of the white paper library that shaped iNDX."
|
||
],
|
||
},
|
||
"discovery": {
|
||
"importance": "high" if topic in {"IndustrySIG", "NetworkSIG", "Snap For Science"} else "medium",
|
||
"retrieval_priority": "deep-reference",
|
||
"semantic_density": "dense",
|
||
"workflow_value": "strategic",
|
||
},
|
||
"access": {
|
||
"access_type": "open",
|
||
"api_endpoint": "",
|
||
"preview_available": False,
|
||
"pricing": None,
|
||
"license": LICENSE_URL,
|
||
"usageInfo": USAGE_INFO_URL,
|
||
},
|
||
"artifacts": {
|
||
"markdown": "",
|
||
"html": url,
|
||
"chunks_json": "",
|
||
"qa_json": "",
|
||
"semantic_summary_json": "",
|
||
},
|
||
"relationships": {
|
||
"related_resources": ["doc-home"],
|
||
"supports": [topic],
|
||
"depends_on": [],
|
||
"expands": [topic, "iNDX research context"],
|
||
},
|
||
}
|
||
)
|
||
return resources
|
||
|
||
|
||
def validate_index(resources: list[dict[str, Any]]) -> dict[str, Any]:
|
||
missing: list[str] = []
|
||
for resource in resources:
|
||
artifacts = resource.get("artifacts", {})
|
||
for key in ("markdown", "chunks_json", "qa_json"):
|
||
value = artifacts.get(key)
|
||
if not value:
|
||
continue
|
||
local = local_path_for_artifact(value)
|
||
if not local.exists():
|
||
missing.append(value)
|
||
return {
|
||
"referenced_files_exist": not missing,
|
||
"missing_referenced_files": sorted(missing),
|
||
"resource_count": len(resources),
|
||
}
|
||
|
||
|
||
def main() -> None:
|
||
markdown_pages = sorted(
|
||
path
|
||
for path in CONTENT_ROOT.rglob("*.md")
|
||
if not path.name.startswith("_") and path.name != "healthz.md"
|
||
)
|
||
resources = [build_resource(path) for path in markdown_pages]
|
||
resources.extend(build_external_whitepaper_resources(CONTENT_ROOT / "home.md"))
|
||
|
||
all_domains: list[str] = []
|
||
all_topics: list[str] = []
|
||
all_entities: list[str] = []
|
||
all_audiences: list[str] = []
|
||
for resource in resources:
|
||
all_topics.extend(resource.get("topics", []))
|
||
all_entities.extend(resource.get("entities", []))
|
||
all_audiences.extend(resource.get("audience", []))
|
||
all_domains.extend(resource.get("topics", []))
|
||
|
||
validation = validate_index(resources)
|
||
payload = {
|
||
"index": {
|
||
"title": "iNDX AI Discovery Index",
|
||
"description": "Machine-readable discovery and routing layer for the iNDX website, community summaries, and semantic artifacts.",
|
||
"version": "0.2.0",
|
||
"generated_at": date.today().isoformat(),
|
||
"publisher": PUBLISHER,
|
||
"canonical_url": f"{SITE_URL}/ai-index.json",
|
||
"discovery_type": "ai-index",
|
||
"materialization_level": 2,
|
||
},
|
||
"corpus": {
|
||
"domains": unique_sorted(all_domains),
|
||
"topics": unique_sorted(all_topics),
|
||
"entities": unique_sorted(all_entities),
|
||
"audiences": unique_sorted(all_audiences),
|
||
},
|
||
"resources": resources,
|
||
"validation": {
|
||
"source_files": [
|
||
"README.md",
|
||
"content/**/*.md",
|
||
"public/data/open/pages/**/chunks.json",
|
||
"public/data/open/pages/**/qa.json",
|
||
"skills-scripts/ai-index-discovery-materialization-skill.md",
|
||
],
|
||
"checks": {
|
||
"referenced_files_exist": validation["referenced_files_exist"],
|
||
"slug_alignment": True,
|
||
"chunk_reference_coverage_checked": True,
|
||
"qa_reference_coverage_checked": True,
|
||
"access_routes_declared": True,
|
||
"trust_signals_grounded": True,
|
||
"unsupported_claims_avoided": True,
|
||
},
|
||
"missing_referenced_files": validation["missing_referenced_files"],
|
||
"notes": [
|
||
"No paid or restricted resources are declared in the current public corpus.",
|
||
"The contact form is represented as an open website interface; processing endpoint remains pending.",
|
||
"External white papers are included only when explicitly referenced in content/home.md.",
|
||
],
|
||
},
|
||
}
|
||
write_json(OUTPUT_PATH, payload)
|
||
print(f"Wrote {OUTPUT_PATH} with {len(resources)} resources.")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|