spacy-project / scripts /convert.py
wjbmattingly's picture
init
5472d34
"""Convert entity annotation from spaCy v2 TRAIN_DATA format to spaCy v3 .spacy format."""
import srsly
import typer
import warnings
from pathlib import Path
import spacy
from spacy.tokens import DocBin
def convert(lang: str, input_paths: list[Path], output_dir: Path, spans_key: str = "sc"):
nlp = spacy.blank(lang)
nlp.add_pipe("sentencizer")
# Ensure output directory exists
output_dir.mkdir(parents=True, exist_ok=True)
# Process each input file
for input_path in input_paths:
print(input_path)
doc_bin = DocBin()
for annotation in srsly.read_jsonl(input_path):
text = annotation["text"]
doc = nlp.make_doc(text)
spans = []
for item in annotation["spans"]:
start = item["start"]
end = item["end"]
label = item["label"]
span = doc.char_span(start, end, label=label)
if span is None:
msg = f"Skipping entity [{start}, {end}, {label}] in the following text because the character span '{doc.text[start:end]}' does not align with token boundaries."
warnings.warn(msg)
else:
spans.append(span)
doc.spans[spans_key] = spans
doc_bin.add(doc)
# Write to output file in the specified directory
output_file = output_dir / f"{input_path.stem}.spacy"
doc_bin.to_disk(output_file)
if __name__ == "__main__":
typer.run(convert)