Skip to content

feat: smart (semantic) diff for subtitle regression outputs - #1142

Open
gaurav02081 wants to merge 12 commits into
CCExtractor:masterfrom
gaurav02081:feat/smart-diff
Open

gaurav02081 wants to merge 12 commits into
CCExtractor:masterfrom
gaurav02081:feat/smart-diff

Conversation

@gaurav02081

@gaurav02081 gaurav02081 commented Jun 30, 2026 •

Copy link
Copy Markdown

What this is

A semantic diff for caption outputs. Instead of a raw line diff, it says how two outputs differ, so whoever is looking at a failure (a person or an agent) gets a verdict instead of a wall of changed lines.

For example, instead of "53 lines differ" it says "All 13 cues match but are 500 ms late."

Kinds

identical, timing_shift (constant offset), timing_drift (growing offset), text_change, formatting_change (tags/entities only), whitespace_change (CEA-608 padding only), encoding_change (non-ASCII/accents only), split_cues, merged_cues, missing_cues, extra_cues, unsupported (no cues parsed, e.g. a .txt transcript), mixed, and missing_output when the run produced nothing. Each result also has a per-cue changes list (which cue, what changed, expected/actual text, timing offset), capped at 25.

Grounded in CCExtractor's own behaviour

  • Uses the same normalization as tests/extract_expected.py (strip styling tags, unescape entities, trim CEA-608 trailing padding), so cosmetic differences are kept apart from real text changes.
  • Handles the -latin1 charset case (accent folding gives encoding_change).
  • Checked against real CCExtractor output (CEA-608 English, DVB Spanish with <font> tags and accents), kept as golden fixtures.

Where it lives

  • mod_test/smartdiff/: the core, with no Flask dependency (SRT and WebVTT parsers, format detection, normalization, classifier).
  • API: the existing diff endpoint takes ?format=smart:
    GET /api/v1/runs/{id}/samples/{sid}/regression-tests/{rid}/outputs/{oid}/diff?format=smart
    It reuses the endpoint's scope check (results:read), path safety and 10 MiB limit. Documented in openapi-ci-api.yaml as SmartDiff.
  • Web console: a Smart tab in the diff drawer, next to Diff and Playback.

Changed since the first version

  • Rebased onto current master.
  • The frontend moved to the web console, so the feature moved with it. The classic-page route (/test/diff/.../smart), its button on test/by_id.html and TestResultFile.generate_smart_diff() are gone; nothing outside mod_api and web/ is touched.
  • The two SonarQube findings: smart_diff() is split into small helpers (it was over the cognitive-complexity limit), and the old popup's unescaped innerHTML is gone (React escapes the new view).

Tests

  • tests/test_smartdiff/: parsers, classifier, normalization, real golden fixtures, malformed input.
  • tests/api/test_routes_results.py: 8 tests for format=smart (timing shift, text change, WebVTT, plain text, matched output, missing file, missing scope).
  • web/src/components/DiffDrawer.test.tsx: 8 tests for the Smart tab, including that caption text is never rendered as markup.
  • Full suite: 884 backend tests and 40 web tests pass; lint, mypy, tsc -b and build:app are clean.

Follow-up (not in this PR)

sp run diff --format smart in sp_cli, using the same endpoint.

@sonarqubecloud

Copy link
Copy Markdown

@sonarqubecloud

Copy link
Copy Markdown

@gaurav02081

Copy link
Copy Markdown
Author

@canihavesomecoffee Hi could you take a look at this PR? It just hasn't had eyes on it yet. Also, the SP CLI is live. Once this feature is merged I will wire it into that as well.

@canihavesomecoffee

Copy link
Copy Markdown
Member

Please fix the two new sonarqube issues first.

gaurav-dev02 and others added 12 commits November 24, 2026 00:02
Add a Flask-decoupled smart-diff module that classifies *how* two subtitle
outputs differ instead of producing a raw line diff:
- srt.py: parse SubRip content into structured cues (BOM/CRLF tolerant).
- compare.py: align cues and classify as identical, timing_shift (with a
  consistent offset_ms), text_change, missing_cues, extra_cues, or mixed,
  with an agent-actionable one-line summary.

Includes unit tests for the parser and every classification branch.
- vtt.py: parse WebVTT into cues (skips WEBVTT/NOTE/STYLE/REGION blocks,
  handles optional hours and trailing cue settings).
- parsing.py: parse_subtitles() picks the parser by explicit hint or by
  auto-detecting the format from content.
- compare.smart_diff() now takes an optional fmt and works across SRT/VTT.

Adds parser tests for WebVTT and a cross-format auto-detect compare test.
…inds

Mirror CCExtractor's own expected-output handling (tests/extract_expected.py):
strip HTML/styling tags, unescape entities, and trim per-line trailing
whitespace. This lets the comparator separate cosmetic differences from real
text changes, adding two classifications:
- formatting_change: cues differ only in tags/entities, not text.
- whitespace_change: cues differ only in CEA-608 trailing padding.

Parsers now preserve raw cue text (only surrounding blank lines are dropped)
so the comparator, not the parser, decides what is cosmetic. Verified against
a real CCExtractor CEA-608 sample.
- timing_drift: detect a growing (non-constant) offset across cues, the
  signature of a progressive sync bug, distinct from a constant timing_shift.
- split_cues / merged_cues: when cue count changes but the text content is
  unchanged, report re-segmentation instead of missing/extra cues.
- Vendor a real CCExtractor CEA-608 sample (tests/.../fixtures/cea608_real.srt)
  and add golden-fixture tests so the diff is exercised on true output:
  identical, constant shift, and cosmetic de-padding.
Add ascii_fold() and an 'encoding' text category so the comparator can tell a
charset difference (e.g. CCExtractor's -latin1 output: 'Voilà' vs 'Voila')
from a real word change. Surfaced as a new 'encoding_change' classification.
…s tests

- Vendor dvb_spanish_real.srt: a genuine CCExtractor DVB Spanish output with
  <font> colour tags and accented text. Security-scanned before vendoring
  (no paths/IPs/emails/URLs/secrets) and verified valid UTF-8.
- Strict fixture tests assert exact kinds and values on real output:
  identical, timing_shift (offset 500), formatting_change (font tags),
  encoding_change (accent folding), missing_cues.
- Robustness tests: malformed/empty/control-byte/garbage input must classify
  cleanly and never raise.

Note: the available "Chinese" DVB samples were failed OCR (no real CJK, and
invalid UTF-8), so they were deliberately not vendored.
… the UI

- TestResultFile.generate_smart_diff(): reads the expected/actual output files
  (reusing the encoding-tolerant read_lines) and returns a semantic
  classification via smart_diff.
- New JSON endpoint GET /diff/<test>/<regression>/<output>/smart, reusable by
  the web UI, the CLI, and agents. Returns 'unavailable' gracefully if the
  output files are not on disk.
- Result page: a "Smart" link next to each "Fail" diff link opens a small
  popup with the difference kind + summary (additive, opt-in).

Includes a unit test of the model glue against real on-disk files.
…offset)

smart_diff now returns a capped 'changes' list alongside the verdict: each
changed cue with its kind, a per-cue timing offset, and (for text changes)
expected/actual snippets. This gives an agent the structured detail to act on
without scraping the raw HTML diff. The web "Smart" popup lists these changes
(HTML-escaped). Result shape stays backward compatible (additive).
In the result cell, place the Smart link below the Fail link separated by a
thin horizontal rule, instead of inline, so the two diff actions read clearly.
- compare: zero-cue outputs (non-srt/vtt formats) no longer report 'identical'
  when they differ — return a new 'unsupported' kind so a real failure isn't
  masked; equal cue-less outputs still report 'identical'.
- normalize: require a non-empty ASCII skeleton for 'encoding', so two
  different non-Latin texts (CJK/Cyrillic) classify as 'text', not 'encoding'.
- controllers: smart_diff_view also catches UnicodeDecodeError (outputs with
  bytes invalid in both utf-8 and cp1252) and returns 'unavailable' instead of
  a 500.
- compare: drop the misleading "(timing aligned)" from the text_change summary
  (per-cue offsets are still in `changes`); compute _content(exp) once.
Address the two SonarQube findings on CCExtractor#1142:

- smart_diff() exceeded the cognitive-complexity limit. Tally the cue
  pairs once, then classify in three small helpers (timing-only,
  count mismatch, single kind of text change). Behaviour is unchanged;
  the existing smartdiff tests cover every kind.
- The Smart popup put resp.kind and resp.summary into innerHTML
  unescaped. Escape them the same way the change list already is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sole

The frontend moved to the web console, so the smart diff moves with it
instead of living on the classic test page.

- GET .../outputs/{oid}/diff?format=smart returns the classification
  (kind, summary, cue counts, per-cue changes), reusing the endpoint's
  scope check, path safety and size limit. Missing output and matched
  output answer without reading files, as the other formats do.
- The console's DiffDrawer gets a Smart tab next to Diff and Playback.
- Drop the classic /test/diff/.../smart route, its button on the test
  page and TestResultFile.generate_smart_diff, which only that route used.
- Document format=smart and the SmartDiff schema in the OpenAPI spec.

Tests: 8 API tests for format=smart, 8 Vitest tests for the Smart view
(including that caption text is never rendered as markup).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sonarqubecloud

Copy link
Copy Markdown

@gaurav02081

gaurav02081 commented Nov 23, 2026 •

Copy link
Copy Markdown
Author

Hi @canihavesomecoffee , sorry this sat for so long. Since the frontend has moved to the new console, I moved smart diff there too: it's now ?format=smart on the API diff endpoint plus a Smart tab in the diff drawer, and the classic-page version is gone. I also fixed the two SonarQube issues (split up smart_diff(), and the unescaped popup no longer exists). Rebased on master, tests added on both sides. Description is updated with the details. Could you take another look when you get a chance?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants