flash-l2sca 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flash_l2sca/__init__.py +78 -0
- flash_l2sca/cli.py +103 -0
- flash_l2sca/engine.py +371 -0
- flash_l2sca/head_rules.py +246 -0
- flash_l2sca/rules_lu2010.py +309 -0
- flash_l2sca/schema.py +358 -0
- flash_l2sca/scorer.py +112 -0
- flash_l2sca/tree_ops.py +254 -0
- flash_l2sca-0.1.0.dist-info/METADATA +238 -0
- flash_l2sca-0.1.0.dist-info/RECORD +14 -0
- flash_l2sca-0.1.0.dist-info/WHEEL +5 -0
- flash_l2sca-0.1.0.dist-info/entry_points.txt +2 -0
- flash_l2sca-0.1.0.dist-info/licenses/LICENSE +21 -0
- flash_l2sca-0.1.0.dist-info/top_level.txt +1 -0
flash_l2sca/__init__.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""`flash_l2sca`: Zero-Java, GPU/MPS-batched Syntactic Complexity Analyzer (Lu, 2010)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .engine import FlashL2SCA, analyze_bracketed_trees, resolve_device
|
|
6
|
+
from .rules_lu2010 import SUBCOUNT_KEYS, count_tree_structures, explain_tree_matches, rollup_counts
|
|
7
|
+
from .schema import (
|
|
8
|
+
AnalysisResult,
|
|
9
|
+
COUNT_DESCRIPTIONS,
|
|
10
|
+
COUNT_GLOSSARY,
|
|
11
|
+
COUNTS,
|
|
12
|
+
DENOMINATORS,
|
|
13
|
+
INDEX_DESCRIPTIONS,
|
|
14
|
+
INDEX_GLOSSARY,
|
|
15
|
+
INDICES,
|
|
16
|
+
NUMERATORS,
|
|
17
|
+
SYNTAX_GROUPS,
|
|
18
|
+
compute_indices,
|
|
19
|
+
describe_measure,
|
|
20
|
+
)
|
|
21
|
+
from .scorer import StructuredSyntaxScorer
|
|
22
|
+
from .tree_ops import RichNode, parse_bracketed_tree, wrap_stanza_tree
|
|
23
|
+
|
|
24
|
+
__version__ = "0.1.0"
|
|
25
|
+
|
|
26
|
+
_DEFAULT_ANALYZER: FlashL2SCA | None = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _get_default_analyzer() -> FlashL2SCA:
|
|
30
|
+
global _DEFAULT_ANALYZER
|
|
31
|
+
if _DEFAULT_ANALYZER is None:
|
|
32
|
+
_DEFAULT_ANALYZER = FlashL2SCA(auto_download=True)
|
|
33
|
+
return _DEFAULT_ANALYZER
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def analyze_text(text: str, *, include_trees: bool = False) -> dict:
|
|
37
|
+
"""Convenience one-liner to analyze a single English text."""
|
|
38
|
+
return _get_default_analyzer().analyze_text(text, include_trees=include_trees).to_dict(
|
|
39
|
+
include_trees=include_trees
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def analyze_batch(texts: list[str], *, include_trees: bool = False) -> list[dict]:
|
|
44
|
+
"""Convenience one-liner to batch-analyze multiple English texts."""
|
|
45
|
+
return [
|
|
46
|
+
r.to_dict(include_trees=include_trees)
|
|
47
|
+
for r in _get_default_analyzer().analyze_batch(texts, include_trees=include_trees)
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
__all__ = [
|
|
52
|
+
"__version__",
|
|
53
|
+
"AnalysisResult",
|
|
54
|
+
"COUNTS",
|
|
55
|
+
"COUNT_DESCRIPTIONS",
|
|
56
|
+
"COUNT_GLOSSARY",
|
|
57
|
+
"DENOMINATORS",
|
|
58
|
+
"FlashL2SCA",
|
|
59
|
+
"INDEX_DESCRIPTIONS",
|
|
60
|
+
"INDEX_GLOSSARY",
|
|
61
|
+
"INDICES",
|
|
62
|
+
"NUMERATORS",
|
|
63
|
+
"RichNode",
|
|
64
|
+
"SYNTAX_GROUPS",
|
|
65
|
+
"SUBCOUNT_KEYS",
|
|
66
|
+
"StructuredSyntaxScorer",
|
|
67
|
+
"analyze_batch",
|
|
68
|
+
"analyze_bracketed_trees",
|
|
69
|
+
"analyze_text",
|
|
70
|
+
"compute_indices",
|
|
71
|
+
"count_tree_structures",
|
|
72
|
+
"describe_measure",
|
|
73
|
+
"explain_tree_matches",
|
|
74
|
+
"parse_bracketed_tree",
|
|
75
|
+
"resolve_device",
|
|
76
|
+
"rollup_counts",
|
|
77
|
+
"wrap_stanza_tree",
|
|
78
|
+
]
|
flash_l2sca/cli.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Command-line interface for `flash-l2sca`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import csv
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from .engine import FlashL2SCA
|
|
12
|
+
from .schema import COUNTS, INDICES
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
16
|
+
parser = argparse.ArgumentParser(
|
|
17
|
+
prog="flash-l2sca",
|
|
18
|
+
description="Zero-Java, GPU/MPS-batched Syntactic Complexity Analyzer (Lu, 2010).",
|
|
19
|
+
)
|
|
20
|
+
parser.add_argument(
|
|
21
|
+
"inputs",
|
|
22
|
+
nargs="*",
|
|
23
|
+
help="Input `.txt` / `.jsonl` file paths, or omit to use `--text`.",
|
|
24
|
+
)
|
|
25
|
+
parser.add_argument("--text", "-t", type=str, help="Analyze an inline text string directly.")
|
|
26
|
+
parser.add_argument("--output", "-o", type=str, help="Optional output file path (CSV or JSON).")
|
|
27
|
+
parser.add_argument(
|
|
28
|
+
"--format",
|
|
29
|
+
choices=("json", "csv"),
|
|
30
|
+
default="json",
|
|
31
|
+
help="Output format (default: json).",
|
|
32
|
+
)
|
|
33
|
+
parser.add_argument("--device", type=str, default=None, help="Device (`mps`, `cuda`, or `cpu`).")
|
|
34
|
+
parser.add_argument(
|
|
35
|
+
"--batch-size",
|
|
36
|
+
type=int,
|
|
37
|
+
default=None,
|
|
38
|
+
help="Constituency parser batch size in sentences (default: per-device tuned value).",
|
|
39
|
+
)
|
|
40
|
+
parser.add_argument("--trees", action="store_true", help="Include bracketed constituency trees in JSON.")
|
|
41
|
+
return parser
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def main(argv: list[str] | None = None) -> int:
|
|
45
|
+
args = build_parser().parse_args(argv)
|
|
46
|
+
|
|
47
|
+
records: list[tuple[str, str]] = []
|
|
48
|
+
if args.text:
|
|
49
|
+
records.append(("inline", args.text))
|
|
50
|
+
|
|
51
|
+
for raw_path in args.inputs:
|
|
52
|
+
p = Path(raw_path)
|
|
53
|
+
if p.suffix.lower() == ".jsonl":
|
|
54
|
+
for idx, line in enumerate(p.read_text(encoding="utf-8").splitlines()):
|
|
55
|
+
if not line.strip():
|
|
56
|
+
continue
|
|
57
|
+
obj = json.loads(line)
|
|
58
|
+
doc_id = str(obj.get("id", f"{p.stem}:{idx}"))
|
|
59
|
+
records.append((doc_id, str(obj["text"])))
|
|
60
|
+
else:
|
|
61
|
+
records.append((p.name, p.read_text(encoding="utf-8")))
|
|
62
|
+
|
|
63
|
+
if not records:
|
|
64
|
+
build_parser().print_help(sys.stderr)
|
|
65
|
+
return 1
|
|
66
|
+
|
|
67
|
+
analyzer = FlashL2SCA(device=args.device, batch_size=args.batch_size, auto_download=True)
|
|
68
|
+
results = analyzer.analyze_batch([text for _, text in records], include_trees=args.trees)
|
|
69
|
+
|
|
70
|
+
if args.format == "csv":
|
|
71
|
+
fieldnames = ["Filename", *COUNTS, *INDICES]
|
|
72
|
+
out_stream = open(args.output, "w", newline="", encoding="utf-8") if args.output else sys.stdout
|
|
73
|
+
try:
|
|
74
|
+
writer = csv.DictWriter(out_stream, fieldnames=fieldnames)
|
|
75
|
+
writer.writeheader()
|
|
76
|
+
for (doc_id, _), res in zip(records, results):
|
|
77
|
+
row: dict[str, object] = {"Filename": doc_id}
|
|
78
|
+
if res.status == "ok" and res.counts and res.indices:
|
|
79
|
+
for k in COUNTS:
|
|
80
|
+
row[k] = res.counts[k]
|
|
81
|
+
for k in INDICES:
|
|
82
|
+
val = res.indices[k]
|
|
83
|
+
row[k] = f"{val:.4f}" if val is not None else ""
|
|
84
|
+
writer.writerow(row)
|
|
85
|
+
finally:
|
|
86
|
+
if args.output:
|
|
87
|
+
out_stream.close()
|
|
88
|
+
else:
|
|
89
|
+
payload = [
|
|
90
|
+
{"id": doc_id, **res.to_dict(include_trees=args.trees)}
|
|
91
|
+
for (doc_id, _), res in zip(records, results)
|
|
92
|
+
]
|
|
93
|
+
rendered = json.dumps(payload[0] if len(payload) == 1 and args.text else payload, indent=2)
|
|
94
|
+
if args.output:
|
|
95
|
+
Path(args.output).write_text(rendered + "\n", encoding="utf-8")
|
|
96
|
+
else:
|
|
97
|
+
print(rendered)
|
|
98
|
+
|
|
99
|
+
return 0
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
if __name__ == "__main__":
|
|
103
|
+
raise SystemExit(main())
|
flash_l2sca/engine.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"""GPU/MPS-resident Stanza constituency batching engine for Lu (2010) L2SCA."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Sequence
|
|
8
|
+
|
|
9
|
+
import stanza
|
|
10
|
+
from stanza.models.common.doc import Document
|
|
11
|
+
import torch
|
|
12
|
+
|
|
13
|
+
from .rules_lu2010 import SUBCOUNT_KEYS, count_tree_structures, rollup_counts
|
|
14
|
+
from .schema import AnalysisResult, COUNTS, compute_indices
|
|
15
|
+
from .tree_ops import parse_bracketed_tree, wrap_stanza_tree
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def resolve_device(device: str | None = None) -> str:
|
|
19
|
+
"""Select the fastest available accelerator (`mps` -> `cuda` -> `cpu`)."""
|
|
20
|
+
if device is not None:
|
|
21
|
+
return device
|
|
22
|
+
if torch.backends.mps.is_available():
|
|
23
|
+
return "mps"
|
|
24
|
+
if torch.cuda.is_available():
|
|
25
|
+
return "cuda"
|
|
26
|
+
return "cpu"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# Measured defaults (see benchmarks/): both sizes count *sentences*. Stanza additionally caps each POS
|
|
30
|
+
# batch by a token limit, so a large POS batch size is safe against out-of-memory on long sentences.
|
|
31
|
+
# Across Apple Silicon (MPS) and NVIDIA GPUs (T4, L4), `batch_size=128` hits the throughput plateau
|
|
32
|
+
# while keeping memory ~2x lower than `256` (friendly to 8 GB laptops and shared GPUs).
|
|
33
|
+
DEFAULT_POS_BATCH_SIZE = 1000
|
|
34
|
+
DEFAULT_CONSTITUENCY_BATCH_SIZE: dict[str, int] = {"mps": 128, "cuda": 128, "cpu": 64}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def resolve_model_dir(model_dir: str | Path | None = None) -> str | None:
|
|
38
|
+
"""Resolve Stanza model directory, preferring explicit path, env var, or local cache."""
|
|
39
|
+
if model_dir is not None:
|
|
40
|
+
return str(Path(model_dir).expanduser().resolve())
|
|
41
|
+
env_dir = os.environ.get("STANZA_RESOURCES_DIR")
|
|
42
|
+
if env_dir:
|
|
43
|
+
return str(Path(env_dir).expanduser().resolve())
|
|
44
|
+
# Check repository-local `.stanza_resources` if running from a source checkout
|
|
45
|
+
repo_cache = Path(__file__).resolve().parents[2] / ".stanza_resources"
|
|
46
|
+
if (repo_cache / "resources.json").is_file():
|
|
47
|
+
return str(repo_cache)
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def analyze_bracketed_trees(
|
|
52
|
+
bracketed_trees: Sequence[str],
|
|
53
|
+
*,
|
|
54
|
+
sentence_ct_floor: bool = False,
|
|
55
|
+
include_subcounts: bool = False,
|
|
56
|
+
include_trees: bool = False,
|
|
57
|
+
) -> AnalysisResult:
|
|
58
|
+
"""Compute all 9 counts and 14 indices directly from Penn Treebank bracketed tree strings."""
|
|
59
|
+
if not bracketed_trees:
|
|
60
|
+
return AnalysisResult(status="missing", reason="empty_trees")
|
|
61
|
+
|
|
62
|
+
doc_sub = {k: 0 for k in SUBCOUNT_KEYS}
|
|
63
|
+
kept_trees: list[str] = []
|
|
64
|
+
|
|
65
|
+
for tree_str in bracketed_trees:
|
|
66
|
+
s = tree_str.strip()
|
|
67
|
+
if not s:
|
|
68
|
+
continue
|
|
69
|
+
root = parse_bracketed_tree(s)
|
|
70
|
+
sub = count_tree_structures(root)
|
|
71
|
+
if sentence_ct_floor:
|
|
72
|
+
if sub["C1"] + sub["C2"] < 1:
|
|
73
|
+
sub["C1"] = 1 - sub["C2"]
|
|
74
|
+
if sub["T1"] + sub["T2"] < 1:
|
|
75
|
+
sub["T1"] = 1 - sub["T2"]
|
|
76
|
+
for k in SUBCOUNT_KEYS:
|
|
77
|
+
doc_sub[k] += sub[k]
|
|
78
|
+
if include_trees:
|
|
79
|
+
kept_trees.append(s)
|
|
80
|
+
|
|
81
|
+
counts = rollup_counts(doc_sub)
|
|
82
|
+
if counts["S"] == 0:
|
|
83
|
+
return AnalysisResult(status="missing", reason="no_valid_sentences")
|
|
84
|
+
|
|
85
|
+
indices, missing_reasons = compute_indices(counts)
|
|
86
|
+
return AnalysisResult(
|
|
87
|
+
status="ok",
|
|
88
|
+
counts=counts,
|
|
89
|
+
indices=indices,
|
|
90
|
+
missing_reasons=missing_reasons,
|
|
91
|
+
subcounts=doc_sub if include_subcounts else None,
|
|
92
|
+
trees=kept_trees if include_trees else None,
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class FlashL2SCA:
|
|
97
|
+
"""In-memory GPU/MPS-batched Syntactic Complexity Analyzer following Lu (2010).
|
|
98
|
+
|
|
99
|
+
Key systems optimizations over legacy Java L2SCA and CLI wrappers:
|
|
100
|
+
1. Zero Java / zero subprocess / zero temporary files.
|
|
101
|
+
2. Single resident Stanza neural constituency pipeline (`mps` / `cuda` / `cpu`).
|
|
102
|
+
3. Cross-document sentence flattening + length-sorted micro-batching to minimize
|
|
103
|
+
padding waste and maximize GPU/MPS throughput across hundreds of documents.
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
def __init__(
|
|
107
|
+
self,
|
|
108
|
+
device: str | None = None,
|
|
109
|
+
batch_size: int | None = None,
|
|
110
|
+
model_dir: str | Path | None = None,
|
|
111
|
+
auto_download: bool = False,
|
|
112
|
+
max_chunk_sentences: int = 512,
|
|
113
|
+
pos_batch_size: int | None = None,
|
|
114
|
+
) -> None:
|
|
115
|
+
"""Create a resident pipeline.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
batch_size: Constituency-parser batch size in sentences. `None` picks a per-device default.
|
|
119
|
+
pos_batch_size: POS-tagger batch size in sentences. `None` uses `DEFAULT_POS_BATCH_SIZE`.
|
|
120
|
+
"""
|
|
121
|
+
os.environ.setdefault("PYTORCH_ENABLE_MPS_FALLBACK", "1")
|
|
122
|
+
self.device = resolve_device(device)
|
|
123
|
+
if batch_size is None:
|
|
124
|
+
batch_size = DEFAULT_CONSTITUENCY_BATCH_SIZE.get(self.device, 64)
|
|
125
|
+
if pos_batch_size is None:
|
|
126
|
+
pos_batch_size = DEFAULT_POS_BATCH_SIZE
|
|
127
|
+
self.batch_size = batch_size
|
|
128
|
+
self.pos_batch_size = pos_batch_size
|
|
129
|
+
self.max_chunk_sentences = max(batch_size, max_chunk_sentences)
|
|
130
|
+
self.model_dir = resolve_model_dir(model_dir)
|
|
131
|
+
|
|
132
|
+
pipeline_kwargs: dict[str, Any] = {
|
|
133
|
+
"lang": "en",
|
|
134
|
+
"processors": "tokenize,mwt,pos,constituency",
|
|
135
|
+
"device": self.device,
|
|
136
|
+
"pos_batch_size": pos_batch_size,
|
|
137
|
+
"constituency_batch_size": batch_size,
|
|
138
|
+
"verbose": False,
|
|
139
|
+
}
|
|
140
|
+
if self.model_dir is not None:
|
|
141
|
+
pipeline_kwargs["dir"] = self.model_dir
|
|
142
|
+
if not auto_download and self.model_dir is not None:
|
|
143
|
+
pipeline_kwargs["download_method"] = None
|
|
144
|
+
|
|
145
|
+
self.pipeline = stanza.Pipeline(**pipeline_kwargs)
|
|
146
|
+
self._cpu_tok_pipeline: stanza.Pipeline | None = None
|
|
147
|
+
self._no_ssplit_tokenizer: stanza.Pipeline | None = None
|
|
148
|
+
|
|
149
|
+
def set_batch_sizes(self, batch_size: int | None = None, pos_batch_size: int | None = None) -> None:
|
|
150
|
+
"""Change batch sizes on the already-loaded models (used by benchmark sweeps)."""
|
|
151
|
+
if batch_size is not None:
|
|
152
|
+
self.batch_size = batch_size
|
|
153
|
+
self.max_chunk_sentences = max(batch_size, self.max_chunk_sentences)
|
|
154
|
+
self.pipeline.processors["constituency"]._batch_size = batch_size
|
|
155
|
+
if pos_batch_size is not None:
|
|
156
|
+
self.pos_batch_size = pos_batch_size
|
|
157
|
+
self.pipeline.processors["pos"].config["batch_size"] = pos_batch_size
|
|
158
|
+
|
|
159
|
+
def _get_cpu_tok_pipeline(self) -> stanza.Pipeline:
|
|
160
|
+
"""Lightweight 1.1 MB CPU tokenizer using `bulk_process` to avoid GPU kernel launch overhead on char-level tokenization."""
|
|
161
|
+
if self._cpu_tok_pipeline is None:
|
|
162
|
+
kwargs: dict[str, Any] = {
|
|
163
|
+
"lang": "en",
|
|
164
|
+
"processors": "tokenize,mwt",
|
|
165
|
+
"device": "cpu",
|
|
166
|
+
"verbose": False,
|
|
167
|
+
}
|
|
168
|
+
if self.model_dir is not None:
|
|
169
|
+
kwargs["dir"] = self.model_dir
|
|
170
|
+
kwargs["download_method"] = None
|
|
171
|
+
self._cpu_tok_pipeline = stanza.Pipeline(**kwargs)
|
|
172
|
+
return self._cpu_tok_pipeline
|
|
173
|
+
|
|
174
|
+
def _get_no_ssplit_tokenizer(self) -> stanza.Pipeline:
|
|
175
|
+
"""Lazy lightweight CPU tokenizer (`tokenize_no_ssplit=True`) for pre-segmented sentences."""
|
|
176
|
+
if self._no_ssplit_tokenizer is None:
|
|
177
|
+
kwargs: dict[str, Any] = {
|
|
178
|
+
"lang": "en",
|
|
179
|
+
"processors": "tokenize,mwt",
|
|
180
|
+
"tokenize_no_ssplit": True,
|
|
181
|
+
"device": "cpu",
|
|
182
|
+
"verbose": False,
|
|
183
|
+
}
|
|
184
|
+
if self.model_dir is not None:
|
|
185
|
+
kwargs["dir"] = self.model_dir
|
|
186
|
+
kwargs["download_method"] = None
|
|
187
|
+
self._no_ssplit_tokenizer = stanza.Pipeline(**kwargs)
|
|
188
|
+
return self._no_ssplit_tokenizer
|
|
189
|
+
|
|
190
|
+
def _score_tokenized_docs(
|
|
191
|
+
self,
|
|
192
|
+
tok_docs: list[Document | None],
|
|
193
|
+
*,
|
|
194
|
+
drop_punct_only_sentences: bool = True,
|
|
195
|
+
sentence_ct_floor: bool = False,
|
|
196
|
+
include_subcounts: bool = False,
|
|
197
|
+
include_trees: bool = False,
|
|
198
|
+
) -> list[AnalysisResult]:
|
|
199
|
+
"""Sort all sentences across documents by word length, run batched GPU/MPS
|
|
200
|
+
POS + Constituency parsing, and re-aggregate per document.
|
|
201
|
+
"""
|
|
202
|
+
flat: list[tuple[int, int, Any]] = []
|
|
203
|
+
for doc_idx, doc in enumerate(tok_docs):
|
|
204
|
+
if doc is None or not doc.sentences:
|
|
205
|
+
continue
|
|
206
|
+
for sent_idx, sent in enumerate(doc.sentences):
|
|
207
|
+
if sent.words:
|
|
208
|
+
flat.append((doc_idx, sent_idx, sent))
|
|
209
|
+
|
|
210
|
+
parsed_by_doc: list[list[tuple[int, Any]]] = [[] for _ in tok_docs]
|
|
211
|
+
|
|
212
|
+
if flat:
|
|
213
|
+
# Sort globally by token length to minimize padding bubbles inside POS & Constituency batches
|
|
214
|
+
flat_sorted = sorted(flat, key=lambda item: len(item[2].words))
|
|
215
|
+
|
|
216
|
+
with torch.inference_mode():
|
|
217
|
+
for start in range(0, len(flat_sorted), self.max_chunk_sentences):
|
|
218
|
+
chunk = flat_sorted[start : start + self.max_chunk_sentences]
|
|
219
|
+
mega_doc = Document([])
|
|
220
|
+
mega_doc.sentences = [item[2] for item in chunk]
|
|
221
|
+
mega_doc.num_tokens = sum(len(s.tokens) for s in mega_doc.sentences)
|
|
222
|
+
mega_doc.num_words = sum(len(s.words) for s in mega_doc.sentences)
|
|
223
|
+
|
|
224
|
+
mega_doc = self.pipeline(mega_doc, processors=["pos", "constituency"])
|
|
225
|
+
for (doc_idx, sent_idx, _), parsed_sent in zip(chunk, mega_doc.sentences):
|
|
226
|
+
parsed_by_doc[doc_idx].append((sent_idx, parsed_sent))
|
|
227
|
+
|
|
228
|
+
results: list[AnalysisResult] = []
|
|
229
|
+
for doc_idx, tok_doc in enumerate(tok_docs):
|
|
230
|
+
if tok_doc is None:
|
|
231
|
+
results.append(AnalysisResult(status="missing", reason="empty_text"))
|
|
232
|
+
continue
|
|
233
|
+
|
|
234
|
+
sent_pairs = sorted(parsed_by_doc[doc_idx], key=lambda p: p[0])
|
|
235
|
+
doc_sub = {k: 0 for k in SUBCOUNT_KEYS}
|
|
236
|
+
kept_trees: list[str] = []
|
|
237
|
+
|
|
238
|
+
for _, sent in sent_pairs:
|
|
239
|
+
if (
|
|
240
|
+
drop_punct_only_sentences
|
|
241
|
+
and len(sent.words) == 1
|
|
242
|
+
and sent.words[0].upos == "PUNCT"
|
|
243
|
+
):
|
|
244
|
+
continue
|
|
245
|
+
rich_root = wrap_stanza_tree(sent.constituency)
|
|
246
|
+
sub = count_tree_structures(rich_root)
|
|
247
|
+
if sentence_ct_floor:
|
|
248
|
+
if sub["C1"] + sub["C2"] < 1:
|
|
249
|
+
sub["C1"] = 1 - sub["C2"]
|
|
250
|
+
if sub["T1"] + sub["T2"] < 1:
|
|
251
|
+
sub["T1"] = 1 - sub["T2"]
|
|
252
|
+
for k in SUBCOUNT_KEYS:
|
|
253
|
+
doc_sub[k] += sub[k]
|
|
254
|
+
if include_trees:
|
|
255
|
+
kept_trees.append(str(sent.constituency))
|
|
256
|
+
|
|
257
|
+
counts = rollup_counts(doc_sub)
|
|
258
|
+
if counts["S"] == 0 or counts["W"] == 0:
|
|
259
|
+
results.append(AnalysisResult(status="missing", reason="no_analyzable_words"))
|
|
260
|
+
continue
|
|
261
|
+
|
|
262
|
+
indices, missing_reasons = compute_indices(counts)
|
|
263
|
+
results.append(
|
|
264
|
+
AnalysisResult(
|
|
265
|
+
status="ok",
|
|
266
|
+
counts=counts,
|
|
267
|
+
indices=indices,
|
|
268
|
+
missing_reasons=missing_reasons,
|
|
269
|
+
subcounts=doc_sub if include_subcounts else None,
|
|
270
|
+
trees=kept_trees if include_trees else None,
|
|
271
|
+
)
|
|
272
|
+
)
|
|
273
|
+
return results
|
|
274
|
+
|
|
275
|
+
def analyze_batch(
|
|
276
|
+
self,
|
|
277
|
+
texts: Sequence[str],
|
|
278
|
+
*,
|
|
279
|
+
sentence_ct_floor: bool = False,
|
|
280
|
+
include_subcounts: bool = False,
|
|
281
|
+
include_trees: bool = False,
|
|
282
|
+
) -> list[AnalysisResult]:
|
|
283
|
+
"""Batch-analyze raw English documents using hybrid CPU `bulk_process` tokenization
|
|
284
|
+
followed by length-sorted GPU/MPS `pos + constituency` parsing.
|
|
285
|
+
"""
|
|
286
|
+
tok_docs: list[Document | None] = [None] * len(texts)
|
|
287
|
+
non_empty_indices: list[int] = []
|
|
288
|
+
non_empty_texts: list[str] = []
|
|
289
|
+
for idx, text in enumerate(texts):
|
|
290
|
+
if text and text.strip():
|
|
291
|
+
non_empty_indices.append(idx)
|
|
292
|
+
non_empty_texts.append(text)
|
|
293
|
+
|
|
294
|
+
if non_empty_texts:
|
|
295
|
+
with torch.inference_mode():
|
|
296
|
+
if len(non_empty_texts) > 1 or self.device != "cpu":
|
|
297
|
+
parsed_toks = self._get_cpu_tok_pipeline().bulk_process(non_empty_texts)
|
|
298
|
+
else:
|
|
299
|
+
parsed_toks = [self.pipeline(non_empty_texts[0], processors=["tokenize", "mwt"])]
|
|
300
|
+
for idx, doc in zip(non_empty_indices, parsed_toks):
|
|
301
|
+
tok_docs[idx] = doc
|
|
302
|
+
|
|
303
|
+
return self._score_tokenized_docs(
|
|
304
|
+
tok_docs,
|
|
305
|
+
drop_punct_only_sentences=True,
|
|
306
|
+
sentence_ct_floor=sentence_ct_floor,
|
|
307
|
+
include_subcounts=include_subcounts,
|
|
308
|
+
include_trees=include_trees,
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
def analyze_text(
|
|
312
|
+
self,
|
|
313
|
+
text: str,
|
|
314
|
+
*,
|
|
315
|
+
sentence_ct_floor: bool = False,
|
|
316
|
+
include_subcounts: bool = False,
|
|
317
|
+
include_trees: bool = False,
|
|
318
|
+
) -> AnalysisResult:
|
|
319
|
+
"""Analyze a single English text string."""
|
|
320
|
+
return self.analyze_batch(
|
|
321
|
+
[text],
|
|
322
|
+
sentence_ct_floor=sentence_ct_floor,
|
|
323
|
+
include_subcounts=include_subcounts,
|
|
324
|
+
include_trees=include_trees,
|
|
325
|
+
)[0]
|
|
326
|
+
|
|
327
|
+
def analyze_sentences_batch(
|
|
328
|
+
self,
|
|
329
|
+
sentences_per_doc: Sequence[Sequence[str]],
|
|
330
|
+
*,
|
|
331
|
+
drop_punct_only_sentences: bool = False,
|
|
332
|
+
sentence_ct_floor: bool = False,
|
|
333
|
+
include_subcounts: bool = False,
|
|
334
|
+
include_trees: bool = False,
|
|
335
|
+
) -> list[AnalysisResult]:
|
|
336
|
+
"""Batch-analyze pre-segmented documents (e.g., from external `pysbd` segmentation),
|
|
337
|
+
strictly preserving caller-supplied sentence boundaries (`\n\n` under `tokenize_no_ssplit`).
|
|
338
|
+
"""
|
|
339
|
+
tok_pipe = self._get_no_ssplit_tokenizer()
|
|
340
|
+
tok_docs: list[Document | None] = [None] * len(sentences_per_doc)
|
|
341
|
+
non_empty_indices: list[int] = []
|
|
342
|
+
joined_texts: list[str] = []
|
|
343
|
+
for idx, sents in enumerate(sentences_per_doc):
|
|
344
|
+
cleaned = [s.strip() for s in sents if s and s.strip()]
|
|
345
|
+
if cleaned:
|
|
346
|
+
non_empty_indices.append(idx)
|
|
347
|
+
joined_texts.append("\n\n".join(cleaned))
|
|
348
|
+
|
|
349
|
+
if joined_texts:
|
|
350
|
+
with torch.inference_mode():
|
|
351
|
+
parsed_toks = tok_pipe.bulk_process(joined_texts) if len(joined_texts) > 1 else [tok_pipe(joined_texts[0])]
|
|
352
|
+
for idx, doc in zip(non_empty_indices, parsed_toks):
|
|
353
|
+
tok_docs[idx] = doc
|
|
354
|
+
|
|
355
|
+
return self._score_tokenized_docs(
|
|
356
|
+
tok_docs,
|
|
357
|
+
drop_punct_only_sentences=drop_punct_only_sentences,
|
|
358
|
+
sentence_ct_floor=sentence_ct_floor,
|
|
359
|
+
include_subcounts=include_subcounts,
|
|
360
|
+
include_trees=include_trees,
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
def score_batch_ct(
|
|
364
|
+
self,
|
|
365
|
+
texts: Sequence[str],
|
|
366
|
+
*,
|
|
367
|
+
sentence_ct_floor: bool = False,
|
|
368
|
+
) -> list[float | None]:
|
|
369
|
+
"""Ultra-concise helper returning `C/T` (Clauses per T-unit) for each text in `texts`."""
|
|
370
|
+
results = self.analyze_batch(texts, sentence_ct_floor=sentence_ct_floor)
|
|
371
|
+
return [r.indices["C/T"] if (r.status == "ok" and r.indices is not None) else None for r in results]
|