Skip to main content

text2rel

TestTestTest

PyPI version Python versions PyPI status PyPI downloads Source

pip install text2rel

Kinship ties extraction

This is the package implementation of the code for the kinship ties and relational information from large text corpora, such as genealogies, biographies, and historical dictionaries.

Important information:

  • For example package usage, see test_workflow.ipynb
  • For information about individual functions before the package implementation and release, see examples folder.

Expected input files

Each document should normally have these three files together in the same folder under documents_root:

0_GenelogiesAndBiographies/
├── Example genealogy/
│   ├── Example genealogy_mod.htm       # source HTML used for the inventory
│   ├── Example genealogy_mod.pdf       # PDF with a readable OCR text layer
│   └── Example genealogy_Original.pdf  # original PDF without OCR
└── Biographies/
    └── Example biography/
        ├── Example biography_mod.htm
        ├── Example biography_mod.pdf
        └── Example biography_Original.pdf

The filenames must share the same base name. The package uses the HTML for inventory creation, prefers *_mod.pdf for page matching, and falls back to *_Original.pdf, which can be OCRed with Tesseract when necessary.

Current release:

Current release includes inventory creation, setting text bounds, assigning font usage and selecting appropriate text chunks from the files (including restriction to "MainText" fonts and JumPJumP insertion).

Files structure:

  1. cleaner.py

Contains the HTMLCleaner class and thus the main logic.

  1. utils.py

Contains helper functions (like JumPJumP insertion)

  1. io.py

Contains the file processing logic, such as loading and saving the JSON inventory.

  1. page_matching.py

Adds one-based PDF start_page and end_page values to chunk metadata using exact and fuzzy text matching. Missing PDFs are skipped with null page values and explicit filename guidance.

Add PDF page numbers

If you already created an HTMLCleaner, use cleaner.add_pdf_pages(). If you only have an inventory JSON file, use add_pages_to_inventory_file() directly.

summary = cleaner.add_pdf_pages(
    documents_root="../0_GenelogiesAndBiographies",
    output_path="exact_html_inventory_new_ids_cleaned_pages.json",
)

The default fuzzy threshold is 0.80. The matcher prefers *_mod.pdf, falls back to _Original.pdf when needed, and can use Tesseract for image-only originals when Tesseract is installed.

Human Labeler Allocation

By default, upload_labelers_data_to_labelbox() leaves ontology setup to the user in the Labelbox UI. For newly created projects, optionally pass existing ontology IDs or separate JSON file paths:

# Reuse existing Labelbox ontologies:
upload_labelers_data_to_labelbox(
    tasks_dir, upload_labelers=labelers, epoch=1,
    ontology_ids={"Relns": "kinship_id", "Events": "events_id"},
)

# Or create ontologies from JSON and attach them to the new projects:
upload_labelers_data_to_labelbox(
    tasks_dir, upload_labelers=labelers, epoch=1,
    relations_ontology_path="kinship_ontology.json",
    events_ontology_path="events_ontology.json",
)

JSON files may be Labelbox ontology exports or normalized objects with tools and classifications. Relationships in exports are included; archived features and old schema IDs are omitted. Each JSON creates one Text ontology per call that creates projects of that type, reused across those projects. Its ID is printed for reuse in later calls. An ID and JSON path may be combined for different types, but not for the same type. Existing projects are still skipped.

When text chunks are allocated to labelers, each generated TXT filename indicates its task type:

  • Task_0 contains chunks shared across all labelers.
  • Task_1 through Task_9 contain labeler-specific, unshared chunks.

New section 4 assessment workflow

The reusable assessment follows sections 4.2.2.1 and 4.2.2.2 of 240426 Information extraction system 260801.ipynb. Install the optional plot dependencies, load the processed human and AI tables, and then create the assessment tables before drawing anything:

pip install -e ".[plots]"
from text2rel import (
    ReliabilityAssessment,
    build_sweep_report,
    plot_sweep_report,
    plot_threshold_curves,
)

assessment = ReliabilityAssessment("inventory.json")
assessment.load_relations_data(relations_csv="human_relations.csv")
assessment.load_chatgpt_relations("machine_relations.csv")

# one_to_one is the package's stricter default for headline metrics.
relation_results = assessment.assess_llm_against_humans(data="relations")
plot_threshold_curves(relation_results["threshold_metrics"], direction="one_to_one")

# directional_best reproduces the notebook's two reusable-candidate views.
diagnostics = assessment.assess_llm_against_humans(
    data="relations", matching_mode="directional_best"
)
fn_report = build_sweep_report(
    diagnostics["human_to_llm_best_pairs"], data="relations"
)
plot_sweep_report(fn_report)

assess_llm_against_humans() returns the selected pairs, threshold metrics, false-negative and false-positive review tables, structural exclusions, and configuration metadata. Plot functions only render these returned tables; they do not change matching or scores. See the separate New section 4 assessment plots and tables section at the end of test_workflow.ipynb for relations and events, notebook-style titles, confidence/length diagnostics, and review summaries.

Quick model comparison

Put human_relations.csv and human_events.csv in user_data/inputs, next to user_data/outputs. Add AI pairs named, for example, llm_relations_modelA.csv and llm_events_modelA.csv. Add more pairs with different suffixes to overlay runs in different colours; filenames label them.

from text2rel import plot_model_comparison
plot_model_comparison("user_data/inputs")

This shows one canvas with Relations and Events precision/recall/F1 panels, using the bundled taxonomy, greedy one-to-one matching, pooled authors, and a 0.80 reference line. CSVs must use matching chunk IDs. As in the existing assessment, chunks without human fact rows are excluded. Pass taxonomy_path=None for already prepared CSVs, a custom taxonomy file path to use another taxonomy, or save_path="comparison.png" to save the graph. The helper returns (figure, axes) and leaves input CSVs unchanged. See DEMOS/text2rel_quick_comparison.ipynb for the short demo.

Submit and resume model comparisons

Start with html_inventory_cleaned.json and either or both human_relations.csv and human_events.csv in user_data/input_data_model_comparison, then run:

from text2rel import run_model_comparison
run_model_comparison("user_data/input_data_model_comparison", tasks=[
    ["gpt-4.1-mini", "../full_prompt_files/default_prompts.txt"],
])

Each task is a model name and a JSON-formatted prompt .txt path. Only types present in both the human reference and that prompt are submitted. Every new task processes all chunks in the cleaned inventory for those types. When API access is needed, a hidden prompt asks for your key once per call; alternatively pass api_key=. The key is not saved. Redrawing downloaded results needs no key.

Run the same call later: it checks progress, downloads completed batches, converts them, applies the taxonomy and overlays the saved runs. Add another task to submit only that new model/prompt combination. Editing prompt contents or source data creates a new run; changing only the human reference or taxonomy reuses the AI output. Prior runs for the same source data remain visible.

Keep comparison_results/: its comparison_runs.json registry records job IDs, progress, downloads, CSVs and audits, and resumes after a kernel restart. Completed runs plot while pending runs show their progress. Failed jobs are not automatically resubmitted; recovered incomplete results are explicitly marked. With everything downloaded, tasks=[] redraws saved runs without an API key.

Optional gt_paths=["path/to/human_events.csv"] selects explicit reference files; inventory_path= overrides the inventory location. taxonomy_path=None skips taxonomy for already prepared inputs; a custom taxonomy path also works. The returned dictionary contains the summary table, registry path and plot. See DEMOS/text2rel_model_comparison.ipynb for the short resumable demo.

Convert downloaded OpenAI batches to CSV

Use the submitted cleaned inventory (or the exact submitted subset) to restore chunk IDs. The function accepts a JSONL path or download_batch_results() output:

CSV saving is automatic: omitted or None output_csv writes llm_relations.csv or llm_events.csv in the current working directory. Pass a path to choose another destination. Reruns overwrite the destination; both DataFrames are still returned.

from text2rel import process_batch_results

relations, relation_audit = process_batch_results(
    "batch_output_relations.jsonl", submitted_inventory,
    extraction_type="relations", output_csv="llm_relations.csv",
)
events, event_audit = process_batch_results(
    "batch_output_events.jsonl", submitted_inventory,
    extraction_type="events", output_csv="llm_events.csv",
)
assessment.load_llm_relations("llm_relations.csv")
assessment.load_llm_events("llm_events.csv")

Taxonomy can be applied to the returned tables before assessment. These are the ungrouped load_llm_* schemas, not historical load_chatgpt_* grouped CSVs. Recovery is the default: valid facts are saved and failures remain in the audit. Pass strict=True to process_batch_results() to raise on errors or missing responses before writing the CSV. Recovery keeps valid facts from a response even when another fact is malformed. The audit marks that response partial (or error if no valid facts remain), with the rejected facts and their zero-based indices in detail. Missing values are never guessed. The demo saves incomplete results as llm_relations_partial.csv or llm_events_partial.csv, saves the audit, and continues to the other batch. Review or correct these results before using them for assessment; the demo blocks complete-named inputs whose audit still contains failures. Keep the audit, which also records successful empty extractions. Custom schemas must retain s/r/t or S/V; extra fields are preserved. For historical req_N IDs, pass an explicit mapping from each request ID to its original chunk metadata (including chunk_id).

Download Labelbox annotations to human CSVs

Use download_labelbox_results(project_ids, allocation, tasks_dir, output_dir) with project_ids={"relations": ["project_id"], "events": ["project_id"]}. It reuses the Done-only exporter and saves human_relations.csv, human_events.csv, and coverage CSVs. Each returned dictionary value is a (facts, coverage) pair. Supply api_key and optionally author_map.

Keep the original allocation JSON and uploaded TXT files unchanged: offsets in the TXT locate each annotation; allocation row IDs recover original chunk IDs. For manual JSON/JSONL exports use process_labelbox_results(exports, allocation, tasks_dir, "relations", output_csv) (or "events"). Ambiguous mappings raise before saving that CSV. Coverage records empty completed annotations separately; the current assessment does not automatically score these empty chunks. Downloads include only Done tasks and do not establish that every assigned task has been completed.

Labelbox event construction modes

labelbox_events_to_dataframe(..., construction_mode="graph") is the default. It follows section 2.4.3.2 of the 260801 notebook: connected annotations are rebuilt around one Verb, safe reversed arrows are corrected, and incomplete or ambiguous structures remain auditable. Use construction_mode="legacy_simple" only when explicitly reproducing the package's earlier permissive conversion. Relation conversion uses its audited endpoint joins separately.

Metadata

Release files for text2rel 1.0.15

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for text2rel 1.0.15
File Size Uploaded Provenance Actions
text2rel-1.0.15.tar.gz 176.8 kB With provenance Details for text2rel-1.0.15.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for text2rel 1.0.15
File Interpreter ABI Platform Actions
text2rel-1.0.15-py3-none-any.whl Python 3 none any Details for text2rel-1.0.15-py3-none-any.whl

Total release size: 361.8 kB

Release files / text2rel-1.0.15.tar.gz

Download URL text2rel-1.0.15.tar.gz
Size 176.8 kB
Tags Source
SHA-256 checksum
How to use checksums
6d5a75ae55c3cc5a35eab3db3f6cfddcbbacaaece3252f5726caa9ccaad715a8
BLAKE2b-256 checksum
How to use checksums
e9ba61888aa6d769fc07047db571fee6f421a9716a12cf77b9623201c6692547
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Release files / text2rel-1.0.15-py3-none-any.whl

Download URL text2rel-1.0.15-py3-none-any.whl
Size 184.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
19be3105fc9c91e3880058150a7d64e8666bce98c5b6335ae26d708c02c660ee
BLAKE2b-256 checksum
How to use checksums
299cf9991f6158b5a628bc04fc8504c4742be6c9858dfe9342f97141ab255651
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Security for text2rel 1.0.15

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for text2rel-1.0.15.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page