flash-l2sca 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 flash-l2sca Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,238 @@
1
+ Metadata-Version: 2.4
2
+ Name: flash-l2sca
3
+ Version: 0.1.0
4
+ Summary: Zero-Java, GPU/MPS-batched Python implementation of Lu (2010)'s L2 Syntactic Complexity Analyzer powered by Stanford Stanza.
5
+ Author: flash-l2sca Contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/unyuchen/flash-l2sca
8
+ Project-URL: Repository, https://github.com/unyuchen/flash-l2sca
9
+ Project-URL: Issues, https://github.com/unyuchen/flash-l2sca/issues
10
+ Keywords: nlp,syntactic-complexity,l2sca,stanza,pytorch,constituency-parsing,corpus-linguistics,llm-evaluation
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Classifier: Topic :: Text Processing :: Linguistic
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: torch>=2.0.0
23
+ Requires-Dist: stanza>=1.8.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
26
+ Requires-Dist: neosca>=0.1.0; extra == "dev"
27
+ Requires-Dist: scipy>=1.11.0; extra == "dev"
28
+ Requires-Dist: matplotlib>=3.8.0; extra == "dev"
29
+ Provides-Extra: demo
30
+ Requires-Dist: gradio>=4.0.0; extra == "demo"
31
+ Dynamic: license-file
32
+
33
+ # flash-l2sca
34
+
35
+ **Zero-Java, GPU/MPS-Batched Python Implementation of Lu (2010)'s Syntactic Complexity Analyzer Powered by Stanford Stanza**
36
+
37
+ [![License: MIT](https://img.shields.io/badge/License-MIT-emerald.svg)](https://github.com/unyuchen/flash-l2sca/blob/main/LICENSE)
38
+ [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-blue.svg)](https://github.com/unyuchen/flash-l2sca/blob/main/pyproject.toml)
39
+ [![Backend: PyTorch + Stanza](https://img.shields.io/badge/Backend-PyTorch%20%2B%20Stanza-orange.svg)](https://stanfordnlp.github.io/stanza/)
40
+
41
+ `flash-l2sca` is a lightweight (~500-line), clean-room **MIT-licensed** Python micro-kernel that computes all **9 foundational structural counts** and **14 syntactic complexity indices** defined in **Xiaofei Lu's (2010) L2 Syntactic Complexity Analyzer (L2SCA)**—without Java, `JPype`, subprocess spawning, or temporary disk files.
42
+
43
+ Designed for **in-memory batch evaluation** in LLM style analysis, RLHF / preference reward loops, and large-scale corpus linguistics, `flash-l2sca` keeps a single neural constituency pipeline resident on the accelerator (~390 MB of model weights; ~0.65–1.13 GB peak on CUDA during 200-document batches) and processes **200 multi-sentence passages in 3.95 s on an NVIDIA A100-80GB, 4.00 s on an NVIDIA L4, 4.61 s on an Apple M5 laptop, and 4.75 s on a free Colab Tesla T4 (184×–519× faster than per-document subprocess invocation)**.
44
+
45
+ ![From 41 Minutes to 4 Seconds: 200-Document Parsing Throughput](https://raw.githubusercontent.com/unyuchen/flash-l2sca/main/benchmarks/results/fig1_ablation_speedup.png)
46
+
47
+ ---
48
+
49
+ ## Key Features
50
+
51
+ - **100% Zero-Java & Minimal Dependencies**: Depends *only* on `torch` and `stanza`. No JVM installation, no legacy `.jar` classpaths, and no desktop GUI dependencies (`PyQt5` / `PyInstaller`) that break headless Linux servers.
52
+ - **Exact Lu (2010) Tree-Pattern Parity (`r = 1.0000`, `MAE = 0`)**: Translates all 12 original Penn Treebank Tregex sub-patterns and **Collins (1999)** head-percolation rules (`<#`) into composable $O(N)$ Python tree predicates—verified with **0 discrepancies across 164 sentences (840 index pairs)** on identical Stanza constituency trees.
53
+ - **Hybrid CPU-GPU Length-Bucketed Batching**: Pairs fast CPU `bulk_process` tokenization (`1.1 MB` weights) with cross-document sentence flattening and word-length-sorted GPU/MPS micro-batching (`pos_batch_size=1000`, `batch_size=128` across GPU/MPS accelerators) to eliminate padding waste without changing any output tree.
54
+ - **Modest Accelerator Footprint**: ~390 MB of resident model weights, with a ~1.1 GB CUDA peak on 200-document batches (about 8% of a free 15 GB Colab T4 and 5% of a 22 GB L4), so it can stay co-resident alongside an LLM or reward model.
55
+ - **Pre-Segmented Sentence Lock**: Supports both raw prose strings and pre-segmented sentence lists (`analyze_sentences_batch`) when strict external sentence boundary preservation (e.g., `pysbd`) is required.
56
+
57
+ ![Why Sentence Length != Syntactic Complexity: 2D Genre Fingerprint](https://raw.githubusercontent.com/unyuchen/flash-l2sca/main/benchmarks/results/fig2_accuracy_and_fingerprint.png)
58
+
59
+ ---
60
+
61
+ ## Installation
62
+
63
+ ```bash
64
+ pip install flash-l2sca
65
+ ```
66
+
67
+ Or install from source in editable mode (with optional benchmark & Gradio demo extras):
68
+
69
+ ```bash
70
+ git clone https://github.com/unyuchen/flash-l2sca.git
71
+ cd flash-l2sca
72
+ pip install -e ".[dev,demo]"
73
+ ```
74
+
75
+ *(On first run, `FlashL2SCA(auto_download=True)` automatically downloads Stanza's English `tokenize`, `pos`, and `constituency` models if not already cached.)*
76
+
77
+ ---
78
+
79
+ ## Quickstart
80
+
81
+ ### 1. In-Memory Batch Scoring (Python API)
82
+
83
+ ```python
84
+ from flash_l2sca import FlashL2SCA
85
+
86
+ # Automatically selects CUDA -> Apple Metal (MPS) -> CPU
87
+ sca = FlashL2SCA(auto_download=True) # per-device tuned batch sizes
88
+
89
+ texts = [
90
+ "I went home, and I slept.", # Coordinated independent clauses -> T=2, C=2, C/T=1.0
91
+ "I went home because I was tired.", # Subordinate dependent clause -> T=1, C=2, C/T=2.0
92
+ ]
93
+
94
+ results = sca.analyze_batch(texts)
95
+ for res in results:
96
+ print("Counts :", res.counts)
97
+ print("C/T :", res.indices["C/T"], "| MLT:", res.indices["MLT"], "| CN/T:", res.indices["CN/T"])
98
+ ```
99
+
100
+ For fast inner-loop reward or feature scoring of **Clauses per T-unit (`C/T`)**:
101
+
102
+ ```python
103
+ ct_scores = sca.score_batch_ct(texts) # -> [1.0, 2.0]
104
+ ```
105
+
106
+ ### 2. Preserving External Sentence Segmentation
107
+
108
+ If your preprocessing pipeline already strips Markdown and segments sentences (e.g., via `pysbd`):
109
+
110
+ ```python
111
+ docs_sentences = [
112
+ ["I went home.", "I slept because I was tired."],
113
+ ["Syntactic complexity relies on phrase-structure representations."],
114
+ ]
115
+ results = sca.analyze_sentences_batch(docs_sentences)
116
+ ```
117
+
118
+ ### 3. Command-Line Interface (`flash-l2sca`)
119
+
120
+ ```bash
121
+ # Single string -> JSON
122
+ flash-l2sca --text "Although it rained heavily, the students arrived on time."
123
+
124
+ # Batch JSONL / TXT files -> CSV table
125
+ flash-l2sca benchmarks/data/public_eval_corpus.jsonl --format csv -o scores.csv
126
+ ```
127
+
128
+ ### 4. Interactive Web App (Gradio / Hugging Face Spaces)
129
+
130
+ ```bash
131
+ python app.py
132
+ ```
133
+
134
+ ---
135
+
136
+ ## Supported Counts & Indices (Lu, 2010)
137
+
138
+ ### 9 Foundational Structural Counts (`COUNTS`)
139
+
140
+ | Code | Structure | Operationalization over Penn Treebank Trees |
141
+ | :--- | :--- | :--- |
142
+ | **`W`** | Words | Non-punctuation preterminal POS tokens (`^[A-Z]+\$?$`, excluding hyphens/dashes/parens) |
143
+ | **`S`** | Sentences | Root sentence trees (`ROOT !> __`) |
144
+ | **`VP`** | Verb Phrases | Clause-parented verb phrases (`VP > S\|SINV\|SQ`) + copula/modal inverted questions (`VP2`) |
145
+ | **`C`** | Clauses | Finite clauses (`S\|SINV\|SQ` headed by or dominating finite `MD/VBD/VBP/VBZ` VPs, imperatives, or root fragments) |
146
+ | **`T`** | T-units | Root main clauses + unembedded coordinated independent clauses (`!>> SBAR\|VP`), plus clause-free root `FRAG`s |
147
+ | **`DC`** | Dependent Clauses | Finite clauses directly dominated by a subordinate `SBAR` (`SBAR < C1`) |
148
+ | **`CT`** | Complex T-units | T-units dominating at least one dependent clause (`T1 << DC`) |
149
+ | **`CP`** | Coordinate Phrases | Phrases directly dominating a coordinating conjunction (`ADJP\|ADVP\|NP\|VP < CC`) |
150
+ | **`CN`** | Complex Nominals | Sum of modified/appositive top-level `NP`s (`CN1`), nominal `SBAR`s (`CN2`), and gerund/infinitival subjects (`CN3`) |
151
+
152
+ ### 14 Syntactic Complexity Indices (`INDICES`, 5 Dimensions)
153
+
154
+ | Dimension (`SYNTAX_GROUPS`) | Index | Name | Formula | Zero Denominator |
155
+ | :--- | :--- | :--- | :---: | :---: |
156
+ | **1. Length of Production Unit** (`unit_length`) | `MLS` | Mean Length of Sentence | `W / S` | `None` |
157
+ | | `MLT` | Mean Length of T-unit | `W / T` | `None` |
158
+ | | `MLC` | Mean Length of Clause | `W / C` | `None` |
159
+ | **2. Sentence Complexity & Overall** (`sentence_structure`) | `C/S` | Clauses per Sentence | `C / S` | `None` |
160
+ | | `T/S` | T-units per Sentence | `T / S` | `None` |
161
+ | | `C/T` | Clauses per T-unit | `C / T` | `None` |
162
+ | | `VP/T` | Verb Phrases per T-unit | `VP / T` | `None` |
163
+ | **3. Subordination** (`subordination`) | `DC/C` | Dependent Clauses per Clause | `DC / C` | `None` |
164
+ | | `DC/T` | Dependent Clauses per T-unit | `DC / T` | `None` |
165
+ | | `CT/T` | Complex T-units per T-unit | `CT / T` | `None` |
166
+ | **4. Coordination** (`coordination`) | `CP/T` | Coordinate Phrases per T-unit | `CP / T` | `None` |
167
+ | | `CP/C` | Coordinate Phrases per Clause | `CP / C` | `None` |
168
+ | **5. Phrasal Sophistication** (`complex_nominals`) | `CN/T` | Complex Nominals per T-unit | `CN / T` | `None` |
169
+ | | `CN/C` | Complex Nominals per Clause | `CN / C` | `None` |
170
+
171
+ ---
172
+
173
+ ## Benchmarks: Accuracy Alignment & Cross-Platform Speed
174
+
175
+ All benchmark scripts and the 60-passage multi-genre evaluation corpus (`benchmarks/data/public_eval_corpus.jsonl`) are included in [`benchmarks/`](https://github.com/unyuchen/flash-l2sca/tree/main/benchmarks), along with a **self-contained 1-click Google Colab notebook** ([`benchmarks/colab_t4_a100_benchmark.ipynb`](https://github.com/unyuchen/flash-l2sca/blob/main/benchmarks/colab_t4_a100_benchmark.ipynb)).
176
+
177
+ ### 1. Tree-Level Structural Parity
178
+ Evaluated across **60 multi-genre passages (164 sentences, 2,428 words, 840 index pairs)** covering simple narratives, coordinated compound prose, deep subordination, dense academic nominalizations, LLM explanations, and inversions/fragments:
179
+ - **Sub-pattern count discrepancies** (`W, S, VP1, VP2, C1, C2, T1, T2, DC, CT, CP, CN1, CN2, CN3`): **`0 / 164` sentences (`0` errors)**.
180
+ - **All 14 Lu (2010) indices**: **Pearson $r = 1.0000$**, **Spearman $\rho = 1.0000$**, **$\text{MAE} = 0.000000$**.
181
+
182
+ ### 2. Cross-Platform 4-Tier Throughput (`N = 200` Documents)
183
+
184
+ | Execution Tier | Apple M5 (Local MPS) | NVIDIA Tesla T4 (Colab Free) | NVIDIA L4 (Colab) | NVIDIA A100-80GB* (Colab Pro) |
185
+ | :--- | :---: | :---: | :---: | :---: |
186
+ | **Tier 1: Subprocess Cold-Start** | 849.31 s · `0.24/s` (1.0×) | 2,468.32 s · `0.08/s` (1.0×) | 1,852.82 s · `0.11/s` (1.0×) | 1,827.33 s · `0.11/s` (1.0×) |
187
+ | **Tier 2: CPU Resident (Single)** | 86.26 s · `2.32/s` (9.8×) | 449.82 s · `0.45/s` (5.5×) | 100.48 s · `1.99/s` (18.4×) | 109.02 s · `1.83/s` (16.8×) |
188
+ | **Tier 3: GPU/MPS Resident (Single)** | 83.97 s · `2.38/s` (10.1×) | 43.64 s · `4.58/s` (56.6×) | 31.35 s · `6.38/s` (59.1×) | 31.45 s · `6.36/s` (58.1×) |
189
+ | **Tier 4: Hybrid + Batch-128 (Ours)** | **4.61 s · `43.37/s` (184.2×)** | **4.75 s · `42.07/s` (519.2×)** | **4.00 s · `50.02/s` (463.4×)** | **3.95 s · `50.63/s` (462.6×)** |
190
+ | **Accelerator Memory** | 379 MB tensors · 2,313 MB pool | 1,132 MB peak *(7.6% of 14.6 GB)* | 1,132 MB peak *(5.0% of 22.0 GB)* | 645 MB* *(recorded @ `bs=64`, 0.8%)* |
191
+
192
+ > **Reading the table**: M5, T4, and L4 use the unified default (`pos_batch_size=1000`, `batch_size=128`); `*A100-80GB` `N=200` latency (`3.95 s`, `50.63 docs/s`) is the directly measured `batch_size=128` sweep entry (`pos_batch_size=128`, with `645 MB` peak VRAM recorded on the preceding `bs=64` pass). Memory metrics differ by backend (CUDA: peak allocated tensors; Apple MPS: driver-allocated pool). Run-to-run variation on shared Colab GPUs is several percent.
193
+
194
+ > **Methodological Note (Tree-Query Equivalence vs. Parser Generation)**:
195
+ > Given identical Penn Treebank constituency trees, `flash-l2sca` produces mathematically identical counts to Stanford Tregex. End-to-end on raw text, `flash-l2sca` parses sentences with **Stanford Stanza's modern neural constituency parser** (`ptb3-revised_charlm`; Qi et al., 2020) rather than the 2003 Java PCFG parser (Klein & Manning, 2003) bundled in legacy L2SCA. Because neural parsing resolves long-range phrase attachments more accurately, researchers should keep a **single parser implementation fixed across all experimental conditions** within a study rather than mixing legacy Java PCFG scores with Stanza neural scores.
196
+
197
+ ---
198
+
199
+ ## Academic Attribution & Positioning
200
+
201
+ To ensure accurate scholarly attribution, please note the distinct roles of prior foundational works:
202
+
203
+ | Work | Authors & Venue | Role & Relationship to `flash-l2sca` |
204
+ | :--- | :--- | :--- |
205
+ | **L2SCA Framework** | **Xiaofei Lu (2010)**, Penn State (*IJCL*) | Defined the 9 structural counts, 14 syntactic complexity indices, and original Penn Treebank Tregex specifications implemented here. |
206
+ | **Head Percolation & Tregex** | **Collins (1999)**; **Levy & Andrew (2006)** | Defined Penn Treebank phrase head-finding priorities (`<#`) and tree-relation operators, re-implemented here in clean-room native Python. |
207
+ | **Stanford Stanza** | **Qi et al. (2020)**, Stanford NLP (*ACL Demo*) | Provides the modern PyTorch neural tokenization, POS, and constituency parsing models driving `flash-l2sca`. |
208
+ | **NeoSCA** | **Long Tan** (`tanloong/neosca`) | Community cross-platform desktop/CLI fork of L2SCA & LCA (`GPLv3`). Whereas `neosca` on PyPI (`0.0.55`) requires `JPype1`/JVM and newer GitHub builds target `PyQt5` desktop applications, `flash-l2sca` is an **MIT-licensed**, headless, GPU-batched micro-kernel built for ML/NLP pipelines. |
209
+
210
+ ---
211
+
212
+ ## Citation
213
+
214
+ If you use `flash-l2sca` in academic research, **please cite both Xiaofei Lu's (2010) original L2SCA paper and Qi et al.'s (2020) Stanza paper**, alongside this software package:
215
+
216
+ ```bibtex
217
+ @article{lu2010automatic,
218
+ title={Automatic analysis of syntactic complexity in second language writing},
219
+ author={Lu, Xiaofei},
220
+ journal={International Journal of Corpus Linguistics},
221
+ volume={15},
222
+ number={4},
223
+ pages={474--496},
224
+ year={2010}
225
+ }
226
+
227
+ @inproceedings{qi2020stanza,
228
+ title={Stanza: A Python Natural Language Processing Toolkit for Many Human Languages},
229
+ author={Qi, Peng and Zhang, Yuhao and Zhang, Yuhui and Bolton, Jason and Manning, Christopher D.},
230
+ booktitle={Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics: System Demonstrations},
231
+ pages={101--108},
232
+ year={2020}
233
+ }
234
+ ```
235
+
236
+ ## License
237
+
238
+ Released under the [MIT License](https://github.com/unyuchen/flash-l2sca/blob/main/LICENSE).
@@ -0,0 +1,206 @@
1
+ # flash-l2sca
2
+
3
+ **Zero-Java, GPU/MPS-Batched Python Implementation of Lu (2010)'s Syntactic Complexity Analyzer Powered by Stanford Stanza**
4
+
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-emerald.svg)](https://github.com/unyuchen/flash-l2sca/blob/main/LICENSE)
6
+ [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-blue.svg)](https://github.com/unyuchen/flash-l2sca/blob/main/pyproject.toml)
7
+ [![Backend: PyTorch + Stanza](https://img.shields.io/badge/Backend-PyTorch%20%2B%20Stanza-orange.svg)](https://stanfordnlp.github.io/stanza/)
8
+
9
+ `flash-l2sca` is a lightweight (~500-line), clean-room **MIT-licensed** Python micro-kernel that computes all **9 foundational structural counts** and **14 syntactic complexity indices** defined in **Xiaofei Lu's (2010) L2 Syntactic Complexity Analyzer (L2SCA)**—without Java, `JPype`, subprocess spawning, or temporary disk files.
10
+
11
+ Designed for **in-memory batch evaluation** in LLM style analysis, RLHF / preference reward loops, and large-scale corpus linguistics, `flash-l2sca` keeps a single neural constituency pipeline resident on the accelerator (~390 MB of model weights; ~0.65–1.13 GB peak on CUDA during 200-document batches) and processes **200 multi-sentence passages in 3.95 s on an NVIDIA A100-80GB, 4.00 s on an NVIDIA L4, 4.61 s on an Apple M5 laptop, and 4.75 s on a free Colab Tesla T4 (184×–519× faster than per-document subprocess invocation)**.
12
+
13
+ ![From 41 Minutes to 4 Seconds: 200-Document Parsing Throughput](https://raw.githubusercontent.com/unyuchen/flash-l2sca/main/benchmarks/results/fig1_ablation_speedup.png)
14
+
15
+ ---
16
+
17
+ ## Key Features
18
+
19
+ - **100% Zero-Java & Minimal Dependencies**: Depends *only* on `torch` and `stanza`. No JVM installation, no legacy `.jar` classpaths, and no desktop GUI dependencies (`PyQt5` / `PyInstaller`) that break headless Linux servers.
20
+ - **Exact Lu (2010) Tree-Pattern Parity (`r = 1.0000`, `MAE = 0`)**: Translates all 12 original Penn Treebank Tregex sub-patterns and **Collins (1999)** head-percolation rules (`<#`) into composable $O(N)$ Python tree predicates—verified with **0 discrepancies across 164 sentences (840 index pairs)** on identical Stanza constituency trees.
21
+ - **Hybrid CPU-GPU Length-Bucketed Batching**: Pairs fast CPU `bulk_process` tokenization (`1.1 MB` weights) with cross-document sentence flattening and word-length-sorted GPU/MPS micro-batching (`pos_batch_size=1000`, `batch_size=128` across GPU/MPS accelerators) to eliminate padding waste without changing any output tree.
22
+ - **Modest Accelerator Footprint**: ~390 MB of resident model weights, with a ~1.1 GB CUDA peak on 200-document batches (about 8% of a free 15 GB Colab T4 and 5% of a 22 GB L4), so it can stay co-resident alongside an LLM or reward model.
23
+ - **Pre-Segmented Sentence Lock**: Supports both raw prose strings and pre-segmented sentence lists (`analyze_sentences_batch`) when strict external sentence boundary preservation (e.g., `pysbd`) is required.
24
+
25
+ ![Why Sentence Length != Syntactic Complexity: 2D Genre Fingerprint](https://raw.githubusercontent.com/unyuchen/flash-l2sca/main/benchmarks/results/fig2_accuracy_and_fingerprint.png)
26
+
27
+ ---
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ pip install flash-l2sca
33
+ ```
34
+
35
+ Or install from source in editable mode (with optional benchmark & Gradio demo extras):
36
+
37
+ ```bash
38
+ git clone https://github.com/unyuchen/flash-l2sca.git
39
+ cd flash-l2sca
40
+ pip install -e ".[dev,demo]"
41
+ ```
42
+
43
+ *(On first run, `FlashL2SCA(auto_download=True)` automatically downloads Stanza's English `tokenize`, `pos`, and `constituency` models if not already cached.)*
44
+
45
+ ---
46
+
47
+ ## Quickstart
48
+
49
+ ### 1. In-Memory Batch Scoring (Python API)
50
+
51
+ ```python
52
+ from flash_l2sca import FlashL2SCA
53
+
54
+ # Automatically selects CUDA -> Apple Metal (MPS) -> CPU
55
+ sca = FlashL2SCA(auto_download=True) # per-device tuned batch sizes
56
+
57
+ texts = [
58
+ "I went home, and I slept.", # Coordinated independent clauses -> T=2, C=2, C/T=1.0
59
+ "I went home because I was tired.", # Subordinate dependent clause -> T=1, C=2, C/T=2.0
60
+ ]
61
+
62
+ results = sca.analyze_batch(texts)
63
+ for res in results:
64
+ print("Counts :", res.counts)
65
+ print("C/T :", res.indices["C/T"], "| MLT:", res.indices["MLT"], "| CN/T:", res.indices["CN/T"])
66
+ ```
67
+
68
+ For fast inner-loop reward or feature scoring of **Clauses per T-unit (`C/T`)**:
69
+
70
+ ```python
71
+ ct_scores = sca.score_batch_ct(texts) # -> [1.0, 2.0]
72
+ ```
73
+
74
+ ### 2. Preserving External Sentence Segmentation
75
+
76
+ If your preprocessing pipeline already strips Markdown and segments sentences (e.g., via `pysbd`):
77
+
78
+ ```python
79
+ docs_sentences = [
80
+ ["I went home.", "I slept because I was tired."],
81
+ ["Syntactic complexity relies on phrase-structure representations."],
82
+ ]
83
+ results = sca.analyze_sentences_batch(docs_sentences)
84
+ ```
85
+
86
+ ### 3. Command-Line Interface (`flash-l2sca`)
87
+
88
+ ```bash
89
+ # Single string -> JSON
90
+ flash-l2sca --text "Although it rained heavily, the students arrived on time."
91
+
92
+ # Batch JSONL / TXT files -> CSV table
93
+ flash-l2sca benchmarks/data/public_eval_corpus.jsonl --format csv -o scores.csv
94
+ ```
95
+
96
+ ### 4. Interactive Web App (Gradio / Hugging Face Spaces)
97
+
98
+ ```bash
99
+ python app.py
100
+ ```
101
+
102
+ ---
103
+
104
+ ## Supported Counts & Indices (Lu, 2010)
105
+
106
+ ### 9 Foundational Structural Counts (`COUNTS`)
107
+
108
+ | Code | Structure | Operationalization over Penn Treebank Trees |
109
+ | :--- | :--- | :--- |
110
+ | **`W`** | Words | Non-punctuation preterminal POS tokens (`^[A-Z]+\$?$`, excluding hyphens/dashes/parens) |
111
+ | **`S`** | Sentences | Root sentence trees (`ROOT !> __`) |
112
+ | **`VP`** | Verb Phrases | Clause-parented verb phrases (`VP > S\|SINV\|SQ`) + copula/modal inverted questions (`VP2`) |
113
+ | **`C`** | Clauses | Finite clauses (`S\|SINV\|SQ` headed by or dominating finite `MD/VBD/VBP/VBZ` VPs, imperatives, or root fragments) |
114
+ | **`T`** | T-units | Root main clauses + unembedded coordinated independent clauses (`!>> SBAR\|VP`), plus clause-free root `FRAG`s |
115
+ | **`DC`** | Dependent Clauses | Finite clauses directly dominated by a subordinate `SBAR` (`SBAR < C1`) |
116
+ | **`CT`** | Complex T-units | T-units dominating at least one dependent clause (`T1 << DC`) |
117
+ | **`CP`** | Coordinate Phrases | Phrases directly dominating a coordinating conjunction (`ADJP\|ADVP\|NP\|VP < CC`) |
118
+ | **`CN`** | Complex Nominals | Sum of modified/appositive top-level `NP`s (`CN1`), nominal `SBAR`s (`CN2`), and gerund/infinitival subjects (`CN3`) |
119
+
120
+ ### 14 Syntactic Complexity Indices (`INDICES`, 5 Dimensions)
121
+
122
+ | Dimension (`SYNTAX_GROUPS`) | Index | Name | Formula | Zero Denominator |
123
+ | :--- | :--- | :--- | :---: | :---: |
124
+ | **1. Length of Production Unit** (`unit_length`) | `MLS` | Mean Length of Sentence | `W / S` | `None` |
125
+ | | `MLT` | Mean Length of T-unit | `W / T` | `None` |
126
+ | | `MLC` | Mean Length of Clause | `W / C` | `None` |
127
+ | **2. Sentence Complexity & Overall** (`sentence_structure`) | `C/S` | Clauses per Sentence | `C / S` | `None` |
128
+ | | `T/S` | T-units per Sentence | `T / S` | `None` |
129
+ | | `C/T` | Clauses per T-unit | `C / T` | `None` |
130
+ | | `VP/T` | Verb Phrases per T-unit | `VP / T` | `None` |
131
+ | **3. Subordination** (`subordination`) | `DC/C` | Dependent Clauses per Clause | `DC / C` | `None` |
132
+ | | `DC/T` | Dependent Clauses per T-unit | `DC / T` | `None` |
133
+ | | `CT/T` | Complex T-units per T-unit | `CT / T` | `None` |
134
+ | **4. Coordination** (`coordination`) | `CP/T` | Coordinate Phrases per T-unit | `CP / T` | `None` |
135
+ | | `CP/C` | Coordinate Phrases per Clause | `CP / C` | `None` |
136
+ | **5. Phrasal Sophistication** (`complex_nominals`) | `CN/T` | Complex Nominals per T-unit | `CN / T` | `None` |
137
+ | | `CN/C` | Complex Nominals per Clause | `CN / C` | `None` |
138
+
139
+ ---
140
+
141
+ ## Benchmarks: Accuracy Alignment & Cross-Platform Speed
142
+
143
+ All benchmark scripts and the 60-passage multi-genre evaluation corpus (`benchmarks/data/public_eval_corpus.jsonl`) are included in [`benchmarks/`](https://github.com/unyuchen/flash-l2sca/tree/main/benchmarks), along with a **self-contained 1-click Google Colab notebook** ([`benchmarks/colab_t4_a100_benchmark.ipynb`](https://github.com/unyuchen/flash-l2sca/blob/main/benchmarks/colab_t4_a100_benchmark.ipynb)).
144
+
145
+ ### 1. Tree-Level Structural Parity
146
+ Evaluated across **60 multi-genre passages (164 sentences, 2,428 words, 840 index pairs)** covering simple narratives, coordinated compound prose, deep subordination, dense academic nominalizations, LLM explanations, and inversions/fragments:
147
+ - **Sub-pattern count discrepancies** (`W, S, VP1, VP2, C1, C2, T1, T2, DC, CT, CP, CN1, CN2, CN3`): **`0 / 164` sentences (`0` errors)**.
148
+ - **All 14 Lu (2010) indices**: **Pearson $r = 1.0000$**, **Spearman $\rho = 1.0000$**, **$\text{MAE} = 0.000000$**.
149
+
150
+ ### 2. Cross-Platform 4-Tier Throughput (`N = 200` Documents)
151
+
152
+ | Execution Tier | Apple M5 (Local MPS) | NVIDIA Tesla T4 (Colab Free) | NVIDIA L4 (Colab) | NVIDIA A100-80GB* (Colab Pro) |
153
+ | :--- | :---: | :---: | :---: | :---: |
154
+ | **Tier 1: Subprocess Cold-Start** | 849.31 s · `0.24/s` (1.0×) | 2,468.32 s · `0.08/s` (1.0×) | 1,852.82 s · `0.11/s` (1.0×) | 1,827.33 s · `0.11/s` (1.0×) |
155
+ | **Tier 2: CPU Resident (Single)** | 86.26 s · `2.32/s` (9.8×) | 449.82 s · `0.45/s` (5.5×) | 100.48 s · `1.99/s` (18.4×) | 109.02 s · `1.83/s` (16.8×) |
156
+ | **Tier 3: GPU/MPS Resident (Single)** | 83.97 s · `2.38/s` (10.1×) | 43.64 s · `4.58/s` (56.6×) | 31.35 s · `6.38/s` (59.1×) | 31.45 s · `6.36/s` (58.1×) |
157
+ | **Tier 4: Hybrid + Batch-128 (Ours)** | **4.61 s · `43.37/s` (184.2×)** | **4.75 s · `42.07/s` (519.2×)** | **4.00 s · `50.02/s` (463.4×)** | **3.95 s · `50.63/s` (462.6×)** |
158
+ | **Accelerator Memory** | 379 MB tensors · 2,313 MB pool | 1,132 MB peak *(7.6% of 14.6 GB)* | 1,132 MB peak *(5.0% of 22.0 GB)* | 645 MB* *(recorded @ `bs=64`, 0.8%)* |
159
+
160
+ > **Reading the table**: M5, T4, and L4 use the unified default (`pos_batch_size=1000`, `batch_size=128`); `*A100-80GB` `N=200` latency (`3.95 s`, `50.63 docs/s`) is the directly measured `batch_size=128` sweep entry (`pos_batch_size=128`, with `645 MB` peak VRAM recorded on the preceding `bs=64` pass). Memory metrics differ by backend (CUDA: peak allocated tensors; Apple MPS: driver-allocated pool). Run-to-run variation on shared Colab GPUs is several percent.
161
+
162
+ > **Methodological Note (Tree-Query Equivalence vs. Parser Generation)**:
163
+ > Given identical Penn Treebank constituency trees, `flash-l2sca` produces mathematically identical counts to Stanford Tregex. End-to-end on raw text, `flash-l2sca` parses sentences with **Stanford Stanza's modern neural constituency parser** (`ptb3-revised_charlm`; Qi et al., 2020) rather than the 2003 Java PCFG parser (Klein & Manning, 2003) bundled in legacy L2SCA. Because neural parsing resolves long-range phrase attachments more accurately, researchers should keep a **single parser implementation fixed across all experimental conditions** within a study rather than mixing legacy Java PCFG scores with Stanza neural scores.
164
+
165
+ ---
166
+
167
+ ## Academic Attribution & Positioning
168
+
169
+ To ensure accurate scholarly attribution, please note the distinct roles of prior foundational works:
170
+
171
+ | Work | Authors & Venue | Role & Relationship to `flash-l2sca` |
172
+ | :--- | :--- | :--- |
173
+ | **L2SCA Framework** | **Xiaofei Lu (2010)**, Penn State (*IJCL*) | Defined the 9 structural counts, 14 syntactic complexity indices, and original Penn Treebank Tregex specifications implemented here. |
174
+ | **Head Percolation & Tregex** | **Collins (1999)**; **Levy & Andrew (2006)** | Defined Penn Treebank phrase head-finding priorities (`<#`) and tree-relation operators, re-implemented here in clean-room native Python. |
175
+ | **Stanford Stanza** | **Qi et al. (2020)**, Stanford NLP (*ACL Demo*) | Provides the modern PyTorch neural tokenization, POS, and constituency parsing models driving `flash-l2sca`. |
176
+ | **NeoSCA** | **Long Tan** (`tanloong/neosca`) | Community cross-platform desktop/CLI fork of L2SCA & LCA (`GPLv3`). Whereas `neosca` on PyPI (`0.0.55`) requires `JPype1`/JVM and newer GitHub builds target `PyQt5` desktop applications, `flash-l2sca` is an **MIT-licensed**, headless, GPU-batched micro-kernel built for ML/NLP pipelines. |
177
+
178
+ ---
179
+
180
+ ## Citation
181
+
182
+ If you use `flash-l2sca` in academic research, **please cite both Xiaofei Lu's (2010) original L2SCA paper and Qi et al.'s (2020) Stanza paper**, alongside this software package:
183
+
184
+ ```bibtex
185
+ @article{lu2010automatic,
186
+ title={Automatic analysis of syntactic complexity in second language writing},
187
+ author={Lu, Xiaofei},
188
+ journal={International Journal of Corpus Linguistics},
189
+ volume={15},
190
+ number={4},
191
+ pages={474--496},
192
+ year={2010}
193
+ }
194
+
195
+ @inproceedings{qi2020stanza,
196
+ title={Stanza: A Python Natural Language Processing Toolkit for Many Human Languages},
197
+ author={Qi, Peng and Zhang, Yuhao and Zhang, Yuhui and Bolton, Jason and Manning, Christopher D.},
198
+ booktitle={Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics: System Demonstrations},
199
+ pages={101--108},
200
+ year={2020}
201
+ }
202
+ ```
203
+
204
+ ## License
205
+
206
+ Released under the [MIT License](https://github.com/unyuchen/flash-l2sca/blob/main/LICENSE).
@@ -0,0 +1,65 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "flash-l2sca"
7
+ version = "0.1.0"
8
+ description = "Zero-Java, GPU/MPS-batched Python implementation of Lu (2010)'s L2 Syntactic Complexity Analyzer powered by Stanford Stanza."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [
14
+ { name = "flash-l2sca Contributors" },
15
+ ]
16
+ keywords = [
17
+ "nlp",
18
+ "syntactic-complexity",
19
+ "l2sca",
20
+ "stanza",
21
+ "pytorch",
22
+ "constituency-parsing",
23
+ "corpus-linguistics",
24
+ "llm-evaluation",
25
+ ]
26
+ classifiers = [
27
+ "Development Status :: 4 - Beta",
28
+ "Intended Audience :: Science/Research",
29
+ "Programming Language :: Python :: 3",
30
+ "Programming Language :: Python :: 3.10",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
34
+ "Topic :: Text Processing :: Linguistic",
35
+ ]
36
+ dependencies = [
37
+ "torch>=2.0.0",
38
+ "stanza>=1.8.0",
39
+ ]
40
+
41
+ [project.optional-dependencies]
42
+ dev = [
43
+ "pytest>=8.0.0",
44
+ "neosca>=0.1.0",
45
+ "scipy>=1.11.0",
46
+ "matplotlib>=3.8.0",
47
+ ]
48
+ demo = [
49
+ "gradio>=4.0.0",
50
+ ]
51
+
52
+ [project.urls]
53
+ Homepage = "https://github.com/unyuchen/flash-l2sca"
54
+ Repository = "https://github.com/unyuchen/flash-l2sca"
55
+ Issues = "https://github.com/unyuchen/flash-l2sca/issues"
56
+
57
+ [project.scripts]
58
+ flash-l2sca = "flash_l2sca.cli:main"
59
+
60
+ [tool.setuptools.packages.find]
61
+ where = ["src"]
62
+
63
+ [tool.pytest.ini_options]
64
+ testpaths = ["tests"]
65
+ addopts = "-q"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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
+ ]