Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,12 @@ All notable changes to SkillEvaluator are documented in this file.
match. That reason in `skillspector_evidence.reasons` carries
`line_source: "parser_diagnostic"`. Because the suggestion text changes, the `finding_id` of each such AE1
finding changes once with this release.
- The text-analyzer reference skill counts a sentence end only when `.`, `!` or
`?` is followed by whitespace or the end of the text, so file names, decimals
and version numbers stay in one sentence. Closing quotes, Markdown emphasis
and citation or footnote markers such as `[1]` or `[^1]` after the terminator
still end it. `--file` on a directory or an unreadable path prints `Error:`
on stderr and exits 1 instead of a traceback.
- Restore a temporary-cleanup exemption for a narrow, NUL-delimited
find-to-xargs pipeline under a literal temporary root: these pipelines now
score Security `1.0` instead of a destructive-command finding. Unknown
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,18 @@ The script prints a structured report with:

## Limitations

- Sentence detection uses simple period/question/exclamation splitting;
may be inaccurate for abbreviations (e.g., "U.S.A.").
- Sentence detection counts a run of `.`, `!` or `?` only when it is
followed by whitespace or the end of the text. Closing quotes or brackets,
Markdown `*` / `_` emphasis and numeric citations or footnotes such as `[1]`
or `[^1]` may sit between the terminator and that whitespace. Abbreviations
followed by a space (e.g., "Dr. Smith") still split.
- Non-UTF-8 files will be read with errors replaced.

## Troubleshooting

| Problem | Fix |
|---------|-----|
| `FileNotFoundError` | Check the `--file` path exists |
| `Error: file not found: <path>` | Check the `--file` path exists |
| `Error: not a file: <path>` | Pass a regular file, not a directory |
| `Error: cannot read file: <path> (...)` | Check that the file is readable |
| Empty output | Ensure `--text` or `--file` is provided |
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@
from collections import Counter
from pathlib import Path

# A run of .!? ends a sentence only when it is followed by whitespace or the
# end of the text. Closing quotes or brackets, Markdown emphasis markers and
# numeric citation or footnote markers directly after the terminator still
# count (He said "go." Then / (see above.) Next / **done.** Next / 1993.[1] The
# / Done.[^1] Next). Periods inside tokens such as input.txt, 3.14, or v1.2.3
# are not sentence ends. The lookbehind starts a match only at the first
# terminator of a run, so long runs split in linear time.
_SENTENCE_END = re.compile("(?<![.!?])[.!?]+(?:[\"')\\]}\u201d\u2019\u00bb\u203a*_]|\\[\\^?\\d+\\])*(?:\\s+|$)")


def analyze(text: str) -> dict:
lines = text.splitlines()
Expand All @@ -19,8 +28,7 @@ def analyze(text: str) -> dict:
word_count = len(words)
line_count = len(lines)

sentences = [s.strip() for s in re.split(r"[.!?]+", text) if s.strip()]
sentence_count = len(sentences)
sentence_count = len([part for part in _SENTENCE_END.split(text) if part.strip()])
Comment thread
chrisknvidia marked this conversation as resolved.
Resolved

avg_word_len = round(sum(len(w) for w in words) / max(word_count, 1), 2)

Expand Down Expand Up @@ -65,10 +73,27 @@ def main():

if args.file:
path = Path(args.file)
if not path.exists():
# The read decides: Path.exists() and is_dir() report False for a
# path they cannot stat on Python 3.14, which hid permission errors.
try:
text = path.read_text(encoding="utf-8", errors="replace")
except (FileNotFoundError, NotADirectoryError):
print(f"Error: file not found: {args.file}", file=sys.stderr)
sys.exit(1)
text = path.read_text(encoding="utf-8", errors="replace")
except IsADirectoryError:
print(f"Error: not a file: {args.file}", file=sys.stderr)
sys.exit(1)
except OSError as exc:
Comment thread
rng1995 marked this conversation as resolved.
Resolved
# Windows refuses to open a directory with PermissionError.
try:
is_dir = path.is_dir()
except OSError:
is_dir = False
if is_dir:
print(f"Error: not a file: {args.file}", file=sys.stderr)
else:
print(f"Error: cannot read file: {args.file} ({exc.strerror})", file=sys.stderr)
sys.exit(1)
else:
text = args.text

Expand Down
118 changes: 118 additions & 0 deletions tests/test_reference_text_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,15 @@
from __future__ import annotations

import importlib.util
import os
import subprocess
import sys
import time
from pathlib import Path
from types import ModuleType

import pytest

ANALYZE_TEXT = (
Path(__file__).resolve().parents[1]
/ "src/skillevaluator/tier3/reference_skills/text-analyzer/scripts/analyze_text.py"
Expand Down Expand Up @@ -54,3 +60,115 @@ def test_starter_eval_text_statistics_are_unchanged() -> None:
{"word": "fox", "count": 3},
{"word": "dog", "count": 2},
]


@pytest.mark.parametrize(
("text", "sentence_count"),
[
("Open input.txt and report the totals.", 1),
("Pi is 3.14. Done!", 2),
("Ship v1.2.3 today.", 1),
("See https://example.com/index.html for details.", 1),
("Write to user@example.com.", 1),
('He said "go." Then left.', 2),
("She said \u201cGo now.\u201d Then left.", 2),
("She said \u2018Go now.\u2019 Then left.", 2),
("He wrote \u00abfin.\u00bb Then left.", 2),
("(see above.) Next", 2),
Comment thread
rng1995 marked this conversation as resolved.
Resolved
("It was founded in 1993.[1] The company grew.", 2),
("Done.[1][2] Next.", 2),
("Done.[^1] Next.", 2),
("Done.[^1][^2] Next.", 2),
("This is **done.** Next one.", 2),
("_She left._ Then he came.", 2),
("Wait... what?", 2),
("Really?! Yes.", 2),
("hello world", 1),
("", 0),
(" \n ", 0),
("First.\nSecond.", 2),
(
"The quick brown fox jumps over the lazy dog. The dog barked at the fox. The fox ran away quickly.",
3,
),
],
)
def test_sentence_count_ends_only_before_whitespace_or_end(text: str, sentence_count: int) -> None:
assert _load_analyzer().analyze(text)["sentence_count"] == sentence_count


def test_sentence_count_is_linear_on_long_terminator_runs() -> None:
analyzer = _load_analyzer()
started = time.perf_counter()
result = analyzer.analyze("." * 50_000 + "x")
elapsed = time.perf_counter() - started

assert result["sentence_count"] == 1
assert elapsed < 2.0


def _run_analyzer(*args: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[sys.executable, str(ANALYZE_TEXT), *args],
check=False,
capture_output=True,
text=True,
)


def test_file_argument_reports_a_missing_file(tmp_path: Path) -> None:
path = tmp_path / "missing.txt"
result = _run_analyzer("--file", str(path))

assert result.returncode == 1
assert result.stdout == ""
assert result.stderr == f"Error: file not found: {path}\n"


def test_file_argument_rejects_a_directory(tmp_path: Path) -> None:
result = _run_analyzer("--file", str(tmp_path))

assert result.returncode == 1
assert result.stdout == ""
assert result.stderr == f"Error: not a file: {tmp_path}\n"
assert "Traceback" not in result.stderr


@pytest.mark.skipif(os.name == "nt", reason="permission bits do not apply on Windows")
@pytest.mark.skipif(
hasattr(os, "geteuid") and os.geteuid() == 0, reason="permission bits do not apply when running as root"
)
def test_file_argument_rejects_an_unreadable_file(tmp_path: Path) -> None:
path = tmp_path / "secret.txt"
path.write_text("hello", encoding="utf-8")
path.chmod(0)
try:
result = _run_analyzer("--file", str(path))
finally:
path.chmod(0o644)

assert result.returncode == 1
assert result.stdout == ""
assert result.stderr == f"Error: cannot read file: {path} (Permission denied)\n"
assert "Traceback" not in result.stderr


@pytest.mark.skipif(os.name == "nt", reason="permission bits do not apply on Windows")
@pytest.mark.skipif(
hasattr(os, "geteuid") and os.geteuid() == 0, reason="permission bits do not apply when running as root"
)
def test_file_argument_rejects_a_file_under_an_unreadable_directory(tmp_path: Path) -> None:
directory = tmp_path / "locked"
directory.mkdir()
path = directory / "secret.txt"
path.write_text("hello", encoding="utf-8")
directory.chmod(0o000)
try:
result = _run_analyzer("--file", str(path))
finally:
directory.chmod(0o755)

assert result.returncode == 1
assert result.stdout == ""
assert result.stderr == f"Error: cannot read file: {path} (Permission denied)\n"
assert "Traceback" not in result.stderr