File size: 1,529 Bytes
5472d34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""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)