Download src/cdi/export.py from AnthropicallyHuggingFaces/chat-directed-ingestion: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/spaces/AnthropicallyHuggingFaces/chat-directed-ingestion/resolve/main/src/cdi/export.py
- Command line
-
hf download hf://spaces/AnthropicallyHuggingFaces/chat-directed-ingestion/src/cdi/export.py
-
curl -L -o export.py https://huggingface.co/spaces/AnthropicallyHuggingFaces/chat-directed-ingestion/resolve/main/src/cdi/export.py
11.4 kB
| """Exports: sitemap.xml, backlinks.json, chunks.jsonl, and a SQL load file for a remote pgvector.""" | |
| from __future__ import annotations | |
| import json | |
| from datetime import timezone | |
| from pathlib import Path | |
| from xml.sax.saxutils import escape | |
| import psycopg | |
| class LocalOnlyExportError(ValueError): | |
| """The requested staging bundle includes a local-only source.""" | |
| def export_all(conn: psycopg.Connection, out: Path, source_keys: list[str] | None = None) -> dict[str, str]: | |
| """Export the requested document rows. None is unfiltered; [] selects nothing.""" | |
| out.mkdir(parents=True, exist_ok=True) | |
| where = "where d.source_key = any(%s)" if source_keys is not None else "" | |
| params = (source_keys,) if source_keys is not None else () | |
| docs = conn.execute( | |
| f"select id, source_key, title, metadata, updated_at, content_sha256 " | |
| f"from rag_documents d {where} order by source_key", | |
| params, | |
| ).fetchall() | |
| # sitemap: only http(s) sources; lastmod = when our captured content last changed. | |
| lines = ['<?xml version="1.0" encoding="UTF-8"?>', | |
| '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'] | |
| for d in docs: | |
| if d["source_key"].startswith(("http://", "https://")): | |
| lm = d["updated_at"].astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") | |
| lines.append(f" <url><loc>{escape(d['source_key'])}</loc><lastmod>{lm}</lastmod></url>") | |
| lines.append("</urlset>") | |
| (out / "sitemap.xml").write_text("\n".join(lines) + "\n", encoding="utf-8") | |
| known = {d["source_key"] for d in docs} | |
| backlinks: dict[str, dict] = {d["source_key"]: {"title": d["title"], "outlinks": [], "backlinks": []} | |
| for d in docs} | |
| for d in docs: | |
| for link in d["metadata"].get("links", []): | |
| backlinks[d["source_key"]]["outlinks"].append({"url": link, "ingested": link in known}) | |
| if link in known and link != d["source_key"]: | |
| backlinks[link]["backlinks"].append(d["source_key"]) | |
| (out / "backlinks.json").write_text(json.dumps(backlinks, indent=2, sort_keys=True), encoding="utf-8") | |
| with (out / "chunks.jsonl").open("w", encoding="utf-8") as fh: | |
| for c in conn.execute(f"""select d.source_key, c.ordinal, c.heading_path, c.char_start, c.char_end, | |
| c.content_sha256, c.content, c.metadata | |
| from rag_chunks c join rag_documents d on d.id=c.document_id | |
| {where} | |
| order by d.source_key, c.ordinal""", params): | |
| fh.write(json.dumps(c, default=str, ensure_ascii=False) + "\n") | |
| return {k: str(out / k) for k in ("sitemap.xml", "backlinks.json", "chunks.jsonl")} | |
| def _lit(v) -> str: | |
| """Safe SQL literal via dollar quoting with a tag absent from the value.""" | |
| if v is None: | |
| return "null" | |
| if isinstance(v, (int, float)): | |
| return repr(v) | |
| s = v if isinstance(v, str) else json.dumps(v, ensure_ascii=False, sort_keys=True) | |
| tag = "q" | |
| # Include the opening '$' of the closing tag in the collision check. | |
| while f"${tag}$" in s + "$": | |
| tag += "q" | |
| return f"${tag}${s}${tag}$" | |
| def staging_sql(conn: psycopg.Connection, source_keys: list[str] | None = None) -> list[str]: | |
| return [";\n".join(stmts) + ";" for stmts in staging_statements(conn, source_keys)] | |
| def staging_statements(conn: psycopg.Connection, source_keys: list[str] | None = None) -> list[list[str]]: | |
| """Insert sources or fill missing vectors on the same revision, never replacing a revision. | |
| Every statement checks and locks the revision it writes. Parts can be retried but must | |
| be applied in order, stopping on error. A conflicting revision needs a separate fork. | |
| """ | |
| scope = "and d.source_key = any(%s)" if source_keys is not None else "" | |
| params = (source_keys,) if source_keys is not None else () | |
| # Check all selected sources, including duplicates. A staging bundle also includes | |
| # sitemap/backlink files for rows not eligible for SQL. Match the legacy pilot origin too. | |
| blocked = conn.execute( | |
| "select 1 from rag_documents d where (d.metadata->>'staging_policy' = 'local_only' " | |
| f"or starts_with(d.source_key, 'https://aiguru.one/')) {scope} limit 1", | |
| params, | |
| ).fetchone() | |
| if blocked is not None: | |
| raise LocalOnlyExportError( | |
| "Staging export includes local-only content. Select other sources or use a metadata-only catalog." | |
| ) | |
| blocks: list[list[str]] = [] | |
| for d in conn.execute( | |
| f"select * from rag_documents d where d.extraction_status <> 'rejected' {scope} order by source_key", params, | |
| ).fetchall(): | |
| cv = (d["metadata"] or {}).get("chunker_version") | |
| revision = (f"d.source_key = {_lit(d['source_key'])} and d.content_sha256 = {_lit(d['content_sha256'])} " | |
| f"and d.metadata->>'chunker_version' is not distinct from {_lit(cv)}") | |
| lock = f"""perform 1 from public.rag_documents d where {revision} for no key update; | |
| if not found then | |
| raise exception 'CDI source revision conflict: load the original part first or use a separate revision fork'; | |
| end if;""" | |
| status = "validated" if d["extraction_status"] == "indexed" else d["extraction_status"] | |
| stmts = [_do(f"""insert into public.rag_documents | |
| (source_key, source_filename, source_type, title, canonical_markdown, content_sha256, metadata, extraction_status) | |
| values ({_lit(d['source_key'])}, {_lit(d['source_filename'])}, {_lit(d['source_type'])}, {_lit(d['title'])}, | |
| {_lit(d['canonical_markdown'])}, {_lit(d['content_sha256'])}, {_lit(d['metadata'])}::jsonb, {_lit(status)}) | |
| on conflict (source_key) do nothing; | |
| {lock}""")] | |
| chunks = conn.execute("""select ordinal, heading_path, content, content_sha256, token_estimate, char_start, | |
| char_end, metadata, embedding::text e1, embedding_model, embedding_created_at, | |
| embedding_edge::text e2, embedding_edge_model, embedding_edge_created_at | |
| from rag_chunks where document_id=%s order by ordinal""", (d["id"],)).fetchall() | |
| for c in chunks: | |
| ts1 = c["embedding_created_at"] | |
| ts2 = c["embedding_edge_created_at"] | |
| stmts.append(_do(f"""{lock} | |
| if exists ( | |
| select 1 from public.rag_chunks c join public.rag_documents d on d.id = c.document_id | |
| where {revision} and c.content_sha256 = {_lit(c['content_sha256'])} and c.ordinal <> {c['ordinal']} | |
| ) then | |
| raise exception 'CDI chunk layout conflict: existing chunks cannot be re-ordered by a staging load'; | |
| end if; | |
| insert into public.rag_chunks (document_id, ordinal, heading_path, content, content_sha256, token_estimate, | |
| char_start, char_end, metadata, embedding, embedding_model, embedding_created_at, embedding_edge, embedding_edge_model, embedding_edge_created_at) | |
| select d.id, {c['ordinal']}, {_lit(c['heading_path'])}, {_lit(c['content'])}, {_lit(c['content_sha256'])}, {_lit(c['token_estimate'])}, | |
| {_lit(c['char_start'])}, {_lit(c['char_end'])}, {_lit(c['metadata'])}::jsonb, | |
| {_lit(c['e1'])}::vector, {_lit(c['embedding_model'])}, {_lit(ts1.isoformat() if ts1 else None)}::timestamptz, | |
| {_lit(c['e2'])}::vector, {_lit(c['embedding_edge_model'])}, {_lit(ts2.isoformat() if ts2 else None)}::timestamptz | |
| from public.rag_documents d where {revision} | |
| on conflict (document_id, content_sha256) do update set | |
| embedding = coalesce(public.rag_chunks.embedding, excluded.embedding), | |
| embedding_model = case when public.rag_chunks.embedding is null and excluded.embedding is not null | |
| then excluded.embedding_model else public.rag_chunks.embedding_model end, | |
| embedding_created_at = case when public.rag_chunks.embedding is null and excluded.embedding is not null | |
| then excluded.embedding_created_at else public.rag_chunks.embedding_created_at end, | |
| embedding_edge = coalesce(public.rag_chunks.embedding_edge, excluded.embedding_edge), | |
| embedding_edge_model = case when public.rag_chunks.embedding_edge is null and excluded.embedding_edge is not null | |
| then excluded.embedding_edge_model else public.rag_chunks.embedding_edge_model end, | |
| embedding_edge_created_at = case when public.rag_chunks.embedding_edge is null and excluded.embedding_edge is not null | |
| then excluded.embedding_edge_created_at else public.rag_chunks.embedding_edge_created_at end, | |
| updated_at = now() | |
| where (public.rag_chunks.embedding is null and excluded.embedding is not null) | |
| or (public.rag_chunks.embedding_edge is null and excluded.embedding_edge is not null);""")) | |
| if status == "validated" and d["extraction_status"] == "indexed" and chunks: | |
| stmts.append(_do(f"""{lock} | |
| update public.rag_documents d set extraction_status = 'indexed', updated_at = now() | |
| where {revision} and d.extraction_status = 'validated' | |
| and (select count(*) = {len(chunks)} | |
| and count(c.embedding) >= {sum(c['e1'] is not None for c in chunks)} | |
| and count(c.embedding_edge) >= {sum(c['e2'] is not None for c in chunks)} | |
| from public.rag_chunks c where c.document_id = d.id);""")) | |
| blocks.append(stmts) | |
| return blocks | |
| def _do(body: str) -> str: | |
| """Keep a revision check and its SQL writes in one PostgreSQL statement.""" | |
| return "do " + _lit("begin\n" + body + "\nend;") | |
| def backfill_sql(rows: list[dict], keys: list[str], batch_size: int = 16) -> list[str]: | |
| """Vector backfill for chunks that already exist remotely (rows: id, content, content_sha256). | |
| Embeds the stored text as-is (no re-chunking). Each UPDATE is guarded by the content hash and | |
| by ``<column> is null`` so it never overwrites a vector or attaches one to changed text.""" | |
| from . import embed as E | |
| from .chunk import sha256 | |
| stmts = [] | |
| for key in keys: | |
| c = E.CONTRACTS[key] | |
| todo = [r for r in rows if sha256(r["content"]) == r["content_sha256"]] | |
| vecs = E.embed_passages(key, [r["content"] for r in todo], batch_size) | |
| for r, v in zip(todo, vecs): | |
| stmts.append( | |
| f"update public.rag_chunks set {c.column} = {_lit(E.to_pgvector(v))}::vector, " | |
| f"{c.model_column} = {_lit(c.model)}, {c.column}_created_at = now() " | |
| f"where id = {_lit(str(r['id']))}::uuid and content_sha256 = {_lit(r['content_sha256'])} " | |
| f"and {c.column} is null") | |
| return stmts | |
| def contracts_sql() -> str: | |
| from . import embed as E | |
| vals = ",\n".join( | |
| f"({_lit(c.key)}, {_lit(c.model)}, {_lit(c.weights)}, {c.dim}, {_lit(c.column)}, {_lit(c.query_prefix)}, " | |
| f"{_lit(c.passage_prefix)}, {str(c.normalized).lower()}, {_lit(c.distance)}, {_lit(c.runtime)}, 'staging')" | |
| for c in E.CONTRACTS.values()) | |
| return ("insert into public.rag_encoder_contracts (key, model, model_revision, dim, column_name, query_prefix, " | |
| "passage_prefix, normalized, distance, runtime, status) values\n" + vals + | |
| "\non conflict (key) do update set model = excluded.model, model_revision = excluded.model_revision, " | |
| "dim = excluded.dim, query_prefix = excluded.query_prefix, passage_prefix = excluded.passage_prefix, " | |
| "runtime = excluded.runtime;") | |