Datasets:
Tasks:
Text Retrieval
Formats:
parquet
Size:
10K - 100K
Tags:
political-science
public-policy
evidence-retrieval
scientific-literature
source-provenance
tacitus
License:
Download tools/study_search.py from Giuliocc/doxa-study-evidence: direct link, hf CLI and curl.
- Browser
- Download file 7.82 kB
-
https://huggingface.co/datasets/Giuliocc/doxa-study-evidence/resolve/main/tools/study_search.py
- Command line
-
hf download hf://datasets/Giuliocc/doxa-study-evidence/tools/study_search.py
-
curl -L -o study_search.py https://huggingface.co/datasets/Giuliocc/doxa-study-evidence/resolve/main/tools/study_search.py
7.82 kB
| """Search the licensed study corpus and return inspectable original anchors. | |
| Lexical retrieval requires only pyarrow. Dense/hybrid optionally use a fixed | |
| Hugging Face MiniLM encoder locally. Scores are ranks, never bias probabilities | |
| or support labels. No hosted inference, API key or paid computation is used. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from hashlib import sha256 | |
| import json | |
| import os | |
| from pathlib import Path | |
| import pyarrow.parquet as pq | |
| from retrieval_benchmark import BM25, ranks | |
| def anchor(row): | |
| return {"document_id": row["document_id"], "paragraph_id": row["id"], | |
| "text": row["text"], "source_text_start": row["source_text_start"], | |
| "source_text_end": row["source_text_end"], "offset_unit": "unicode_code_points", | |
| "source_xml_sha256": row["source_xml_sha256"], "source_xpath": row["source_xpath"], | |
| "paragraph_index": row["paragraph_index"], "source_section": row["source_section"], | |
| "section_title": row["section_title"], "section_path": row["section_path"], | |
| "url": row["document_url"], "license": row["license"], "page": None} | |
| def search(data, query, method="lexical", limit=8, document_id=None, model_path=None, cache=None): | |
| rows = pq.read_table(data).to_pylist() | |
| if document_id: | |
| rows = [x for x in rows if x["document_id"] == document_id or document_id.casefold() in x["document_url"].casefold()] | |
| if not rows: | |
| raise ValueError("No admitted paragraphs match the requested paper") | |
| lexical = BM25(rows).scores(query) | |
| order = ranks(lexical) | |
| dense_scores = None | |
| window_mapping = window_scores = window_starts = window_ends = None | |
| if method != "lexical": | |
| os.environ.setdefault("OMP_NUM_THREADS", "1") | |
| os.environ.setdefault("MKL_NUM_THREADS", "1") | |
| os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") | |
| import numpy as np | |
| import torch | |
| from transformers import AutoModel, AutoTokenizer | |
| torch.set_num_threads(1) | |
| model_name = model_path or "sentence-transformers/all-MiniLM-L6-v2" | |
| revision = "1110a243fdf4706b3f48f1d95db1a4f5529b4d41" if not model_path else None | |
| tokenizer = AutoTokenizer.from_pretrained(model_name, revision=revision) | |
| model = AutoModel.from_pretrained(model_name, revision=revision, attn_implementation="eager").eval() | |
| def encode(texts): | |
| # Every paragraph is tokenized into overlapping windows. Ranking | |
| # therefore sees the end of a long paragraph rather than silently | |
| # using only the first 256 tokens. | |
| encoded = tokenizer(texts, return_tensors="pt", padding=True, truncation=True, max_length=256, | |
| stride=32, return_overflowing_tokens=True, return_offsets_mapping=True) | |
| mapping = encoded.pop("overflow_to_sample_mapping").numpy() | |
| offsets = encoded.pop("offset_mapping").numpy() | |
| starts = np.array([min((a for a, z in row if z > a), default=0) for row in offsets]) | |
| ends = np.array([max((z for a, z in row if z > a), default=0) for row in offsets]) | |
| embeddings = [] | |
| with torch.inference_mode(): | |
| for start in range(0, len(mapping), 16): | |
| batch = {name: value[start:start + 16] for name, value in encoded.items()} | |
| hidden = model(**batch).last_hidden_state | |
| mask = batch["attention_mask"].unsqueeze(-1) | |
| embeddings.append(torch.nn.functional.normalize((hidden * mask).sum(1) / mask.sum(1).clamp(min=1), dim=1).numpy()) | |
| return np.concatenate(embeddings), mapping, starts, ends | |
| destination = Path(cache) if cache else Path.home() / ".cache/doxa-study-evidence" | |
| destination.mkdir(parents=True, exist_ok=True) | |
| fingerprint = sha256(("all-token-windows-256-stride32-v1:" + str(model_name) + str(revision) + "\n" + "\n".join(x["id"] + ":" + x["text_sha256"] for x in rows)).encode()).hexdigest() | |
| path = destination / (fingerprint + ".npz") | |
| if path.exists(): | |
| loaded = np.load(path) | |
| vectors, window_mapping, window_starts, window_ends = (loaded[name] for name in ("vectors", "mapping", "starts", "ends")) | |
| else: | |
| vectors, window_mapping, window_starts, window_ends = encode([x["text"] for x in rows]) | |
| np.savez(path, vectors=vectors, mapping=window_mapping, starts=window_starts, ends=window_ends) | |
| query_vectors, _, _, _ = encode([query]) | |
| window_scores = (vectors @ query_vectors.T).max(axis=1) | |
| dense_scores = np.full(len(rows), -np.inf) | |
| np.maximum.at(dense_scores, window_mapping, window_scores) | |
| dense_order = ranks(dense_scores) | |
| if method == "dense": | |
| order = dense_order | |
| else: | |
| scores = [0.] * len(rows) | |
| for sequence in (order, dense_order): | |
| for rank, index in enumerate(sequence, 1): | |
| scores[index] += 1 / (60 + rank) | |
| order = ranks(scores) | |
| result = [] | |
| for rank, index in enumerate(order[:limit], 1): | |
| row = rows[index] | |
| dense_match = None | |
| if window_mapping is not None: | |
| windows = np.flatnonzero(window_mapping == index) | |
| best = windows[np.argmax(window_scores[windows])] | |
| start, end = int(window_starts[best]), int(window_ends[best]) | |
| dense_match = {"text": row["text"][start:end], "paragraph_start": start, "paragraph_end": end, | |
| "source_text_start": row["source_text_start"] + start, "source_text_end": row["source_text_start"] + end} | |
| result.append({"rank": rank, "title": row["title"], "semantic_role_candidate": row["semantic_role"], | |
| "status": "retrieved_context_requires_review", "reference_judgment": None, | |
| "lexical_score": lexical[index], "dense_cosine": float(dense_scores[index]) if dense_scores is not None else None, | |
| "evidence": anchor(row), "dense_matching_span": dense_match, | |
| "adjacent_context": [row[name] for name in ("context_before", "context_after") if row.get(name) is not None]}) | |
| return {"query": query, "method": method, "searched_paragraphs": len(rows), "results": result, | |
| "supported_claim": None, "political_bias_score": None, | |
| "scope": "candidate retrieval only; inspect Methods/Results/limitations and adjudicate sufficiency separately", | |
| "neighbor_scope": "nearest admitted original-source contexts; inspect originally_adjacent and source/XML gaps before treating as uninterrupted context", | |
| "dense_input_budget": "all paragraphs processed in 256-token windows, stride32; maximum window similarity per paragraph; full original evidence retained" if method != "lexical" else None, | |
| "dense_window_count": len(window_mapping) if window_mapping is not None else None, | |
| "spent_usd": 0} | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser() | |
| here = Path(__file__).resolve().parent | |
| default_stage = here.parent if here.name == "tools" else here / "stage" | |
| parser.add_argument("--data", type=Path, default=default_stage / "data/paragraphs/corpus.parquet") | |
| parser.add_argument("--query", required=True) | |
| parser.add_argument("--method", choices=("lexical", "dense", "hybrid"), default="lexical") | |
| parser.add_argument("--limit", type=int, default=8) | |
| parser.add_argument("--paper") | |
| parser.add_argument("--model-path") | |
| parser.add_argument("--cache", type=Path) | |
| args = parser.parse_args() | |
| print(json.dumps(search(args.data, args.query, args.method, args.limit, args.paper, args.model_path, args.cache), ensure_ascii=False, indent=2)) | |