---
title: "Taxonomic Trait Extraction from Pakistani Flora: A Case Study"
author: "Taxaudit Maintainer"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Taxonomic Trait Extraction from Pakistani Flora: A Case Study}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

## Introduction

This vignette demonstrates an end-to-end reproducible workflow using the `taxaudit` package to extract morphological traits from the *Flora of Pakistan* corpus, map them to standard plant ontologies, and evaluate model performance with held-out validation splits.

## 1. Load the Gold-Standard Corpus

First, we load our expert-annotated benchmark corpus containing treatment text, exact character spans, and Plant Ontology IDs (`PO:0025034`):

```{r}
library(taxaudit)

corpus <- ta_load_corpus()
head(corpus)
```

## 2. Run Trait Extraction with Evidence Spans

Next, we run our upgraded extraction pipeline on the corpus treatments to automatically recover trait values and their precise text coordinates:

```{r}
# Extract traits from the first treatment
sample_text <- corpus$text[1]
extracted_results <- ta_extract_traits(sample_text)
print(extracted_results)
```

## 3. Inter-Annotator Agreement Audit

To prove annotation reliability, we simulate a second independent annotator and measure span-level agreement:

```{r}
annotator_1 <- data.frame(
  trait = extracted_results$trait,
  span_start = extracted_results$span_start,
  span_end = extracted_results$span_end,
  stringsAsFactors = FALSE
)

# Simulated second annotator with slightly shifted span bounds
annotator_2 <- data.frame(
  trait = extracted_results$trait,
  span_start = extracted_results$span_start + 2,
  span_end = extracted_results$span_end + 1,
  stringsAsFactors = FALSE
)

agreement <- ta_audit_agreement(annotator_1, annotator_2)
print(agreement)
```

## 4. Held-Out Evaluation Strategy

Finally, we ensure robust generalization by splitting our dataset using taxon-held-out cross-validation:

```{r}
eval_split <- ta_split_evaluation(corpus, holdout_type = "taxon", target_holdout = "Cedrus deodara")
cat("Training set size:", nrow(eval_split$train), "\n")
cat("Test set size (held-out taxon):", nrow(eval_split$test), "\n")
```
