diff --git a/mod_api/routes/results.py b/mod_api/routes/results.py index 57a49078b..f67350a03 100644 --- a/mod_api/routes/results.py +++ b/mod_api/routes/results.py @@ -28,6 +28,7 @@ from mod_auth.models import Role from mod_regression.models import RegressionTestOutputFiles from mod_test.models import Test, TestResultFile +from mod_test.smartdiff.compare import smart_diff INVALID_PATH_MSG = 'Invalid file path.' READ_ERROR_MSG = 'Failed to read file.' @@ -274,31 +275,43 @@ def get_actual_output(run_id, sample_id, regression_id, output_id): }, schema=OutputFileContentSchema()) +_EMPTY_STRUCTURED = {'added_lines': 0, 'removed_lines': 0, 'changed_hunks': 0} + +#: Smart-diff answers for results that have no actual file to compare. +_SMART_MISSING = { + 'missing_actual': ('missing_output', 'The run produced no output for this test.'), + 'identical': ('identical', 'Output matches the expected baseline.'), +} + + +def _missing_diff_body(status, format_type, diff_ids): + """Build the diff body for a result whose actual output has no file to read.""" + if format_type == 'unified': + return {**diff_ids, 'format': 'unified', 'content': ''} + if format_type == 'smart': + kind, summary = _SMART_MISSING[status] + return {**diff_ids, 'format': 'smart', 'kind': kind, 'summary': summary, + 'expected_cues': 0, 'actual_cues': 0} + return {**diff_ids, 'status': status, 'format': 'structured', + 'summary': dict(_EMPTY_STRUCTURED), 'hunks': []} + + def _handle_missing_diff(result_file, format_type, diff_ids): if is_dummy_row(result_file): - if format_type == 'unified': - return single_response({**diff_ids, 'format': 'unified', 'content': ''}) - return single_response({ - **diff_ids, - 'status': 'missing_actual', - 'format': 'structured', - 'summary': {'added_lines': 0, 'removed_lines': 0, 'changed_hunks': 0}, - 'hunks': [], - }) - + return single_response(_missing_diff_body('missing_actual', format_type, diff_ids)) if result_file.got is None: - if format_type == 'unified': - return single_response({**diff_ids, 'format': 'unified', 'content': ''}) - return single_response({ - **diff_ids, - 'status': 'identical', - 'format': 'structured', - 'summary': {'added_lines': 0, 'removed_lines': 0, 'changed_hunks': 0}, - 'hunks': [], - }) + return single_response(_missing_diff_body('identical', format_type, diff_ids)) return None +def _smart_diff_response(expected_path, actual_path, ext, diff_ids): + """Classify how the actual output differs from the expected one, cue by cue.""" + expected_text = '\n'.join(read_lines(expected_path)) + actual_text = '\n'.join(read_lines(actual_path)) + result = smart_diff(expected_text, actual_text, fmt=ext.lstrip('.').lower() or None) + return single_response({**diff_ids, 'format': 'smart', **result}) + + @mod_api.route( '/runs//samples//regression-tests//outputs//diff', methods=['GET'] @@ -347,6 +360,9 @@ def get_diff(run_id, sample_id, regression_id, output_id): if os.path.getsize(expected_path) > max_diff_bytes or os.path.getsize(actual_path) > max_diff_bytes: return make_error_response('unprocessable', 'File too large for diff. Use download_url.', http_status=422) + if format_type == 'smart': + return _smart_diff_response(expected_path, actual_path, ext, diff_ids) + if format_type == 'unified': import difflib expected_lines = read_lines(expected_path) diff --git a/mod_test/smartdiff/__init__.py b/mod_test/smartdiff/__init__.py new file mode 100644 index 000000000..7143d27c2 --- /dev/null +++ b/mod_test/smartdiff/__init__.py @@ -0,0 +1,7 @@ +"""Semantic ("smart") diff for subtitle regression outputs. + +Unlike a raw line diff, this package classifies *how* two outputs differ +(timing shift, text change, missing/extra cues) so a person or an agent gets an +actionable answer instead of a wall of changed lines. Pure/Flask-decoupled so it +is fully unit-testable. +""" diff --git a/mod_test/smartdiff/compare.py b/mod_test/smartdiff/compare.py new file mode 100644 index 000000000..066384cca --- /dev/null +++ b/mod_test/smartdiff/compare.py @@ -0,0 +1,310 @@ +"""Semantic comparison of subtitle outputs: classify *how* two results differ.""" + +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Tuple + +from mod_test.smartdiff.normalize import classify_text_pair, plain +from mod_test.smartdiff.parsing import parse_subtitles +from mod_test.smartdiff.srt import Cue + +#: Cap on the number of per-cue change entries returned in a result. +_MAX_CHANGES = 25 + +#: Text categories that count as cosmetic (the cue's words are unchanged). +_COSMETIC = ('formatting', 'whitespace', 'encoding') + +#: A classification: (kind, summary, offset_ms). +_Verdict = Tuple[str, str, Optional[int]] + + +def _result(kind: str, summary: str, n_exp: int, n_act: int, + offset_ms: Optional[int] = None) -> Dict[str, object]: + """ + Build a classification result dict. + + :param kind: The stable difference kind. + :type kind: str + :param summary: A human/agent-readable one-line explanation. + :type summary: str + :param n_exp: Number of expected cues. + :type n_exp: int + :param n_act: Number of actual cues. + :type n_act: int + :param offset_ms: Consistent timing offset, when ``kind`` is ``timing_shift``. + :type offset_ms: Optional[int] + :return: The classification result. + :rtype: Dict[str, object] + """ + out: Dict[str, object] = { + 'kind': kind, + 'summary': summary, + 'expected_cues': n_exp, + 'actual_cues': n_act, + } + if offset_ms is not None: + out['offset_ms'] = offset_ms + return out + + +def _content(cues: List[Cue]) -> str: + """ + Join all cues' normalised, whitespace-collapsed text — for split/merge detection. + + :param cues: The parsed cues. + :type cues: List[Cue] + :return: A single normalised token string spanning every cue. + :rtype: str + """ + return ' '.join(' '.join(plain(cue.text).split()) for cue in cues) + + +def _monotonic(values: List[int]) -> bool: + """ + Report whether a sequence is non-decreasing or non-increasing. + + :param values: The sequence to test. + :type values: List[int] + :return: True if monotonic in either direction. + :rtype: bool + """ + pairs = list(zip(values, values[1:])) + non_decreasing = all(a <= b for a, b in pairs) + non_increasing = all(a >= b for a, b in pairs) + return non_decreasing or non_increasing + + +def _snippet(text: str, limit: int = 80) -> str: + """ + Collapse whitespace and truncate cue text for compact change details. + + :param text: Raw cue text. + :type text: str + :param limit: Maximum characters to keep. + :type limit: int + :return: A single-line, length-capped snippet. + :rtype: str + """ + flat = ' '.join(text.split()) + return flat if len(flat) <= limit else flat[:limit] + '…' + + +@dataclass +class _Tally: + """Per-category counts and timing deltas collected over position-aligned cues.""" + + text: int = 0 + formatting: int = 0 + whitespace: int = 0 + encoding: int = 0 + raw_matches: bool = True + timing_deltas: List[int] = field(default_factory=list) + changes: List[Dict[str, object]] = field(default_factory=list) + + @property + def cosmetic(self) -> int: + """Total cues that differ only cosmetically (formatting/whitespace/encoding).""" + return self.formatting + self.whitespace + self.encoding + + +def _change_entry(position: int, category: str, delta: int, + expected_cue: Cue, actual_cue: Cue) -> Optional[Dict[str, object]]: + """ + Describe one cue's change, or return None when the cue is unchanged. + + :param position: 1-based cue position. + :type position: int + :param category: The text classification from ``classify_text_pair``. + :type category: str + :param delta: Start-time offset (actual minus expected) in ms. + :type delta: int + :param expected_cue: The expected cue. + :type expected_cue: Cue + :param actual_cue: The actual cue. + :type actual_cue: Cue + :return: The change entry, or None. + :rtype: Optional[Dict[str, object]] + """ + if category == 'match' and delta == 0: + return None + entry: Dict[str, object] = { + 'cue': position, + 'kind': category if category != 'match' else 'timing', + } + if category == 'text': + entry['expected'] = _snippet(expected_cue.text) + entry['actual'] = _snippet(actual_cue.text) + if delta != 0: + entry['offset_ms'] = delta + return entry + + +def _tally(exp: List[Cue], act: List[Cue]) -> _Tally: + """ + Classify every position-aligned cue pair and collect the counts. + + :param exp: Expected cues. + :type exp: List[Cue] + :param act: Actual cues. + :type act: List[Cue] + :return: The collected tally. + :rtype: _Tally + """ + tally = _Tally() + for position, (expected_cue, actual_cue) in enumerate(zip(exp, act), start=1): + category = classify_text_pair(expected_cue.text, actual_cue.text) + delta = actual_cue.start_ms - expected_cue.start_ms + if category != 'match': + tally.raw_matches = False + if category == 'text': + tally.text += 1 + else: + if category in _COSMETIC: + setattr(tally, category, getattr(tally, category) + 1) + tally.timing_deltas.append(delta) + entry = _change_entry(position, category, delta, expected_cue, actual_cue) + if entry is not None: + tally.changes.append(entry) + return tally + + +def _classify_aligned(tally: _Tally, n_exp: int) -> Optional[_Verdict]: + """ + Classify equal-count outputs whose cues differ only in timing, if any. + + :param tally: The collected tally. + :type tally: _Tally + :param n_exp: Number of expected cues. + :type n_exp: int + :return: (kind, summary, offset_ms), or None if not a pure timing case. + :rtype: Optional[_Verdict] + """ + deltas = tally.timing_deltas + if tally.raw_matches and all(delta == 0 for delta in deltas): + return 'identical', 'Outputs are identical.', None + if tally.text or tally.cosmetic: + return None + if len(set(deltas)) == 1 and deltas[0] != 0: + offset = deltas[0] + direction = 'late' if offset > 0 else 'early' + return ('timing_shift', + f'All {n_exp} cues match but are {abs(offset)} ms {direction}.', offset) + if len(set(deltas)) > 1 and _monotonic(deltas): + return ('timing_drift', + f'Timing drifts from {deltas[0]:+d} ms to {deltas[-1]:+d} ms ' + f'across {n_exp} cues.', None) + return None + + +def _classify_count_mismatch(exp: List[Cue], act: List[Cue], + tally: _Tally) -> Optional[_Verdict]: + """ + Classify outputs with different cue counts as split/merged/missing/extra. + + :param exp: Expected cues. + :type exp: List[Cue] + :param act: Actual cues. + :type act: List[Cue] + :param tally: The collected tally. + :type tally: _Tally + :return: (kind, summary, None), or None if no single kind fits. + :rtype: Optional[_Verdict] + """ + n_exp, n_act = len(exp), len(act) + exp_content = _content(exp) + if exp_content and exp_content == _content(act): + if n_act > n_exp: + return ('split_cues', + f'Same text, but cues were split: expected {n_exp}, got {n_act}.', None) + return ('merged_cues', + f'Same text, but cues were merged: expected {n_exp}, got {n_act}.', None) + if tally.text: + return None + if n_act < n_exp: + return ('missing_cues', + f'{n_exp - n_act} of {n_exp} cues are missing from the output.', None) + return ('extra_cues', + f'Output has {n_act - n_exp} extra cues ({n_act} vs {n_exp} expected).', None) + + +def _classify_content(tally: _Tally, n_exp: int) -> Optional[_Verdict]: + """ + Classify equal-count, untimed-shift outputs by the one kind of text change. + + :param tally: The collected tally. + :type tally: _Tally + :param n_exp: Number of expected cues. + :type n_exp: int + :return: (kind, summary, None), or None if the changes are mixed. + :rtype: Optional[_Verdict] + """ + if any(delta != 0 for delta in tally.timing_deltas): + return None + if tally.text: + return 'text_change', f'{tally.text} of {n_exp} cues differ in text.', None + only = { + 'encoding': (tally.encoding, 'encoding_change', + 'differ only in character encoding (non-ASCII/accented characters)'), + 'formatting': (tally.formatting, 'formatting_change', + 'differ only in formatting (tags/entities), not text'), + 'whitespace': (tally.whitespace, 'whitespace_change', + 'differ only in trailing whitespace/padding'), + } + for count, kind, phrase in only.values(): + if count and count == tally.cosmetic: + return kind, f'{count} of {n_exp} cues {phrase}.', None + return None + + +def smart_diff(expected: str, actual: str, + fmt: Optional[str] = None) -> Dict[str, object]: + """ + Compare expected vs actual subtitle output and classify the difference. + + Supports SubRip (.srt) and WebVTT (.vtt); the format is auto-detected from + content unless ``fmt`` is given. Aligns cues by position and reports the + *kind* of difference rather than a raw line diff: ``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/accented characters only), ``split_cues``, ``merged_cues``, + ``missing_cues``, ``extra_cues``, ``unsupported`` (no cues parsed), or + ``mixed``. + + :param expected: The expected/baseline subtitle content. + :type expected: str + :param actual: The actual/produced subtitle content. + :type actual: str + :param fmt: Explicit format ('srt' or 'vtt'); auto-detected when None. + :type fmt: Optional[str] + :return: A classification dict with keys ``kind``, ``summary``, + ``expected_cues``, ``actual_cues`` and (for ``timing_shift``) ``offset_ms``. + :rtype: Dict[str, object] + """ + exp = parse_subtitles(expected, fmt) + act = parse_subtitles(actual, fmt) + n_exp, n_act = len(exp), len(act) + if n_exp == 0 and n_act == 0: + if expected == actual: + return _result('identical', 'Outputs are identical.', 0, 0) + return _result( + 'unsupported', + 'No subtitle cues to compare (unsupported format); see the raw diff.', + 0, 0) + + tally = _tally(exp, act) + if n_exp != n_act: + verdict = _classify_count_mismatch(exp, act, tally) + else: + verdict = _classify_aligned(tally, n_exp) or _classify_content(tally, n_exp) + if verdict is None: + verdict = ('mixed', + f'Mixed differences across {min(n_exp, n_act)} compared cues; ' + f'expected {n_exp}, got {n_act}.', None) + + kind, summary, offset_ms = verdict + out = _result(kind, summary, n_exp, n_act, offset_ms) + if tally.changes: + out['changes'] = tally.changes[:_MAX_CHANGES] + if len(tally.changes) > _MAX_CHANGES: + out['changes_truncated'] = True + return out diff --git a/mod_test/smartdiff/normalize.py b/mod_test/smartdiff/normalize.py new file mode 100644 index 000000000..a460c0b7e --- /dev/null +++ b/mod_test/smartdiff/normalize.py @@ -0,0 +1,115 @@ +"""Normalisation that mirrors CCExtractor's own expected-output handling. + +CCExtractor's test harness (``tests/extract_expected.py``) compares outputs +after stripping HTML/styling tags, unescaping entities, and trimming trailing +whitespace from each line (CEA-608 captions are space-padded to a fixed grid). +Reusing the same rules lets the smart diff separate a *cosmetic* difference +(padding or styling only) from a real text change. +""" + +import re +import unicodedata + +_TAG_RE = re.compile(r'<[^>]+>') + +# Same entities CCExtractor's extract_expected.py unescapes; '&' is applied +# last so an escaped entity like '&lt;' is not double-decoded. +_ENTITIES = ( + ('<', '<'), ('>', '>'), ('"', '"'), (''', "'"), + ('°', '°'), (' ', ' '), ('&', '&'), +) + + +def strip_tags(text: str) -> str: + """ + Remove HTML/styling tags such as ```` or ````. + + :param text: Raw cue text. + :type text: str + :return: Text with tags removed. + :rtype: str + """ + return _TAG_RE.sub('', text) + + +def unescape(text: str) -> str: + """ + Unescape the HTML entities CCExtractor emits. + + :param text: Raw cue text. + :type text: str + :return: Text with entities decoded. + :rtype: str + """ + for entity, char in _ENTITIES: + text = text.replace(entity, char) + return text + + +def rstrip_lines(text: str) -> str: + """ + Trim trailing whitespace from each line (CEA-608 padding is cosmetic). + + :param text: Raw cue text. + :type text: str + :return: Text with per-line trailing whitespace removed. + :rtype: str + """ + return '\n'.join(line.rstrip() for line in text.split('\n')) + + +def plain(text: str) -> str: + """ + Fully normalise: unescape entities, strip tags, trim trailing whitespace. + + :param text: Raw cue text. + :type text: str + :return: The fully normalised text. + :rtype: str + """ + return rstrip_lines(strip_tags(unescape(text))) + + +def ascii_fold(text: str) -> str: + """ + Fold text to ASCII by decomposing accents and dropping non-ASCII characters. + + Lets the comparator tell a charset/encoding difference (e.g. CCExtractor's + ``-latin1`` output) from a real word change: 'Voilà' and 'Voila' share an + ASCII skeleton, so only their non-ASCII characters differ. + + :param text: Raw cue text. + :type text: str + :return: The ASCII skeleton of the text. + :rtype: str + """ + decomposed = unicodedata.normalize('NFKD', text) + return ''.join(ch for ch in decomposed if ord(ch) < 128) + + +def classify_text_pair(expected: str, actual: str) -> str: + """ + Classify how two cue texts differ, ignoring progressively more cosmetics. + + :param expected: Expected cue text. + :type expected: str + :param actual: Actual cue text. + :type actual: str + :return: ``match`` (identical), ``whitespace`` (only trailing padding differs), + ``formatting`` (only tags/entities differ), ``encoding`` (only non-ASCII + characters differ), or ``text`` (a real change). + :rtype: str + """ + if expected == actual: + return 'match' + if rstrip_lines(expected) == rstrip_lines(actual): + return 'whitespace' + expected_plain = plain(expected) + actual_plain = plain(actual) + if expected_plain == actual_plain: + return 'formatting' + folded_expected = ascii_fold(expected_plain) + non_ascii = any(ord(ch) > 127 for ch in expected_plain + actual_plain) + if non_ascii and folded_expected and folded_expected == ascii_fold(actual_plain): + return 'encoding' + return 'text' diff --git a/mod_test/smartdiff/parsing.py b/mod_test/smartdiff/parsing.py new file mode 100644 index 000000000..35bfe3d66 --- /dev/null +++ b/mod_test/smartdiff/parsing.py @@ -0,0 +1,26 @@ +"""Detect the subtitle format and dispatch to the right parser.""" + +from typing import List, Optional + +from mod_test.smartdiff.srt import Cue, parse_srt +from mod_test.smartdiff.vtt import parse_vtt + + +def parse_subtitles(content: str, fmt: Optional[str] = None) -> List[Cue]: + """ + Parse subtitle content into cues, choosing a parser by hint or by content. + + :param content: Raw subtitle file content. + :type content: str + :param fmt: Explicit format ('srt' or 'vtt'); auto-detected from content when None. + :type fmt: Optional[str] + :return: The parsed cues. + :rtype: List[Cue] + """ + chosen = (fmt or '').lower() + if not chosen: + head = content.lstrip('').lstrip().upper() + chosen = 'vtt' if head.startswith('WEBVTT') else 'srt' + if chosen == 'vtt': + return parse_vtt(content) + return parse_srt(content) diff --git a/mod_test/smartdiff/srt.py b/mod_test/smartdiff/srt.py new file mode 100644 index 000000000..3f7388ed8 --- /dev/null +++ b/mod_test/smartdiff/srt.py @@ -0,0 +1,102 @@ +"""Parse SubRip (.srt) subtitle output into structured cues for comparison.""" + +import re +from dataclasses import dataclass +from typing import List, Optional + +_TIMING_RE = re.compile( + r'(\d{1,2}):(\d{2}):(\d{2})[,.](\d{1,3})\s*-->\s*' + r'(\d{1,2}):(\d{2}):(\d{2})[,.](\d{1,3})' +) + + +@dataclass +class Cue: + """ + A single subtitle cue: its timing window and text. + + :param index: The cue's sequence number as written in the file. + :type index: int + :param start_ms: Start time in milliseconds. + :type start_ms: int + :param end_ms: End time in milliseconds. + :type end_ms: int + :param text: The cue's text, newlines preserved and surrounding whitespace stripped. + :type text: str + """ + + index: int + start_ms: int + end_ms: int + text: str + + +def join_cue_text(lines: List[str]) -> str: + """ + Join cue text lines, dropping surrounding blank lines but keeping trailing spaces. + + Trailing whitespace is preserved on purpose: CCExtractor pads CEA-608 captions, + and the comparator (not the parser) decides whether that padding is cosmetic. + + :param lines: The text lines following a cue's timing line. + :type lines: List[str] + :return: The joined cue text. + :rtype: str + """ + start, end = 0, len(lines) + while start < end and lines[start].strip() == '': + start += 1 + while end > start and lines[end - 1].strip() == '': + end -= 1 + return '\n'.join(lines[start:end]) + + +def _to_ms(hours: str, minutes: str, seconds: str, millis: str) -> int: + """ + Convert the parts of an SRT timestamp into total milliseconds. + + :param hours: Hours component. + :type hours: str + :param minutes: Minutes component. + :type minutes: str + :param seconds: Seconds component. + :type seconds: str + :param millis: Milliseconds component. + :type millis: str + :return: The timestamp in milliseconds. + :rtype: int + """ + return ((int(hours) * 60 + int(minutes)) * 60 + int(seconds)) * 1000 + int(millis) + + +def parse_srt(content: str) -> List[Cue]: + """ + Parse SubRip subtitle text into a list of cues. + + Tolerant of a leading BOM, CRLF/CR line endings, and either ',' or '.' as the + millisecond separator. Blocks without a valid timing line are skipped. + + :param content: Raw .srt file content. + :type content: str + :return: The parsed cues, in file order. + :rtype: List[Cue] + """ + content = content.lstrip('').replace('\r\n', '\n').replace('\r', '\n') + cues: List[Cue] = [] + for block in re.split(r'\n[ \t]*\n', content.strip()): + lines = block.split('\n') + timing_idx: Optional[int] = next( + (i for i, ln in enumerate(lines) if _TIMING_RE.search(ln)), None) + if timing_idx is None: + continue + match = _TIMING_RE.search(lines[timing_idx]) + if match is None: # pragma: no cover - guaranteed by the search above + continue + start_ms = _to_ms(match.group(1), match.group(2), match.group(3), match.group(4)) + end_ms = _to_ms(match.group(5), match.group(6), match.group(7), match.group(8)) + index = len(cues) + 1 + if timing_idx > 0 and lines[timing_idx - 1].strip().isdigit(): + index = int(lines[timing_idx - 1].strip()) + text = join_cue_text(lines[timing_idx + 1:]) + cues.append(Cue(index=index, start_ms=start_ms, end_ms=end_ms, text=text)) + return cues diff --git a/mod_test/smartdiff/vtt.py b/mod_test/smartdiff/vtt.py new file mode 100644 index 000000000..dbb12e849 --- /dev/null +++ b/mod_test/smartdiff/vtt.py @@ -0,0 +1,65 @@ +"""Parse WebVTT (.vtt) subtitle output into structured cues.""" + +import re +from typing import List, Optional + +from mod_test.smartdiff.srt import Cue, join_cue_text + +_TIMING_RE = re.compile( + r'(?:(\d{1,2}):)?(\d{2}):(\d{2})[.,](\d{3})\s*-->\s*' + r'(?:(\d{1,2}):)?(\d{2}):(\d{2})[.,](\d{3})' +) + +_METADATA_PREFIXES = ('WEBVTT', 'NOTE', 'STYLE', 'REGION') + + +def _to_ms(hours: Optional[str], minutes: str, seconds: str, millis: str) -> int: + """ + Convert WebVTT timestamp parts into total milliseconds. + + :param hours: Hours component, or None when absent (MM:SS.mmm form). + :type hours: Optional[str] + :param minutes: Minutes component. + :type minutes: str + :param seconds: Seconds component. + :type seconds: str + :param millis: Milliseconds component. + :type millis: str + :return: The timestamp in milliseconds. + :rtype: int + """ + hrs = int(hours) if hours else 0 + return ((hrs * 60 + int(minutes)) * 60 + int(seconds)) * 1000 + int(millis) + + +def parse_vtt(content: str) -> List[Cue]: + """ + Parse WebVTT subtitle text into a list of cues. + + Skips the ``WEBVTT`` header and ``NOTE``/``STYLE``/``REGION`` blocks, tolerates + an optional cue-identifier line, optional hours in timestamps, and trailing cue + settings after the end timestamp. + + :param content: Raw .vtt file content. + :type content: str + :return: The parsed cues, in file order. + :rtype: List[Cue] + """ + content = content.lstrip('').replace('\r\n', '\n').replace('\r', '\n') + cues: List[Cue] = [] + for block in re.split(r'\n[ \t]*\n', content.strip()): + lines = block.split('\n') + if lines[0].split(' ', 1)[0] in _METADATA_PREFIXES: + continue + timing_idx: Optional[int] = next( + (i for i, ln in enumerate(lines) if _TIMING_RE.search(ln)), None) + if timing_idx is None: + continue + match = _TIMING_RE.search(lines[timing_idx]) + if match is None: # pragma: no cover - guaranteed by the search above + continue + start_ms = _to_ms(match.group(1), match.group(2), match.group(3), match.group(4)) + end_ms = _to_ms(match.group(5), match.group(6), match.group(7), match.group(8)) + text = join_cue_text(lines[timing_idx + 1:]) + cues.append(Cue(index=len(cues) + 1, start_ms=start_ms, end_ms=end_ms, text=text)) + return cues diff --git a/openapi-ci-api.yaml b/openapi-ci-api.yaml index 4a6059166..29e5a6bb4 100644 --- a/openapi-ci-api.yaml +++ b/openapi-ci-api.yaml @@ -3075,22 +3075,28 @@ paths: in: query schema: type: string - enum: [structured, unified] + enum: [structured, unified, smart] default: structured + description: > + `smart` classifies how a SubRip or WebVTT output differs from its + baseline (timing shift or drift, cosmetic-only changes, text + changes, split/merged/missing/extra cues) instead of listing lines. responses: "200": - description: Structured or unified diff + description: Structured, unified or smart diff content: application/json: schema: oneOf: - $ref: "#/components/schemas/Diff" - $ref: "#/components/schemas/UnifiedDiff" + - $ref: "#/components/schemas/SmartDiff" discriminator: propertyName: format mapping: structured: "#/components/schemas/Diff" unified: "#/components/schemas/UnifiedDiff" + smart: "#/components/schemas/SmartDiff" "400": $ref: "#/components/responses/BadRequest" "401": @@ -5185,6 +5191,69 @@ components: description: Raw unified diff text. maxLength: 524288 + SmartDiff: + type: object + required: [run_id, sample_id, regression_id, output_id, format, kind, summary, + expected_cues, actual_cues] + properties: + run_id: + type: integer + sample_id: + type: integer + regression_id: + type: integer + output_id: + type: integer + format: + type: string + enum: [smart] + kind: + type: string + enum: [identical, timing_shift, timing_drift, text_change, formatting_change, + whitespace_change, encoding_change, split_cues, merged_cues, + missing_cues, extra_cues, unsupported, mixed, missing_output] + description: > + How the output differs. `unsupported` means no cues could be parsed + (for example a plain .txt transcript); use the unified diff instead. + summary: + type: string + description: One-line explanation, readable by a person or an agent. + expected_cues: + type: integer + minimum: 0 + actual_cues: + type: integer + minimum: 0 + offset_ms: + type: integer + description: Constant offset of every cue, present only for `timing_shift`. + changes: + type: array + maxItems: 25 + description: Per-cue changes, capped at 25. + items: + type: object + required: [cue, kind] + properties: + cue: + type: integer + minimum: 1 + description: 1-based cue position. + kind: + type: string + enum: [timing, text, formatting, whitespace, encoding] + offset_ms: + type: integer + expected: + type: string + maxLength: 81 + actual: + type: string + maxLength: 81 + changes_truncated: + type: boolean + description: True when more than 25 cues changed. + BaselineApprovalRequest: type: object required: [regression_id, output_id] diff --git a/tests/api/test_routes_results.py b/tests/api/test_routes_results.py index 74555253a..4968be8f9 100644 --- a/tests/api/test_routes_results.py +++ b/tests/api/test_routes_results.py @@ -211,6 +211,111 @@ def test_get_diff_identical_files(self): self.assertEqual(res.status_code, 200) self.assertEqual(res.json['status'], 'identical') + def _smart_diff(self, expected, actual, ext='.srt', token_name='t_smart'): + """Write both outputs, then fetch the diff with format=smart.""" + self.reg_out.correct_extension = ext + g.db.commit() + for name, body in (('expected_hash', expected), ('actual_hash', actual)): + with open(os.path.join(self.test_results_dir, name + ext), 'wb') as f: + f.write(body) + + with patch.dict('run.config', {'SAMPLE_REPOSITORY': self.dir_path}): + token = self.get_token( + 'res_user@local.com', 'userpass123', token_name, scopes=['results:read']) + return self.client.get( + f'/api/v1/runs/{self.test_id}/samples/1/regression-tests/{self.reg_test_id}' + f'/outputs/{self.reg_out_id}/diff?format=smart', + headers={'Authorization': f'Bearer {token}'}) + + def test_get_diff_smart_timing_shift(self): + expected = b'1\n00:00:01,000 --> 00:00:02,000\nHello\n\n2\n00:00:03,000 --> 00:00:04,000\nWorld\n' + actual = b'1\n00:00:01,500 --> 00:00:02,500\nHello\n\n2\n00:00:03,500 --> 00:00:04,500\nWorld\n' + res = self._smart_diff(expected, actual) + + self.assertEqual(res.status_code, 200) + self.assertEqual(res.json['format'], 'smart') + self.assertEqual(res.json['kind'], 'timing_shift') + self.assertEqual(res.json['offset_ms'], 500) + self.assertEqual(res.json['expected_cues'], 2) + self.assertEqual(res.json['regression_id'], self.reg_test_id) + self.assertEqual(len(res.json['changes']), 2) + + def test_get_diff_smart_text_change(self): + expected = b'1\n00:00:01,000 --> 00:00:02,000\nHello there\n' + actual = b'1\n00:00:01,000 --> 00:00:02,000\nGoodbye\n' + res = self._smart_diff(expected, actual, token_name='t_smart_text') + + self.assertEqual(res.status_code, 200) + self.assertEqual(res.json['kind'], 'text_change') + self.assertEqual(res.json['changes'], [ + {'cue': 1, 'kind': 'text', 'expected': 'Hello there', 'actual': 'Goodbye'}]) + + def test_get_diff_smart_webvtt(self): + expected = b'WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nHello\n' + actual = b'WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nHello\n' + res = self._smart_diff(expected, actual, ext='.vtt', token_name='t_smart_vtt') + + self.assertEqual(res.status_code, 200) + self.assertEqual(res.json['kind'], 'formatting_change') + + def test_get_diff_smart_plain_text_is_unsupported(self): + res = self._smart_diff(b'one\ntwo\n', b'one\nthree\n', ext='.txt', + token_name='t_smart_txt') + + self.assertEqual(res.status_code, 200) + self.assertEqual(res.json['kind'], 'unsupported') + + def test_get_diff_smart_identical_when_got_is_none(self): + self.result_file.got = None + g.db.commit() + + with patch.dict('run.config', {'SAMPLE_REPOSITORY': self.dir_path}): + token = self.get_token( + 'res_user@local.com', 'userpass123', 't_smart_none', scopes=['results:read']) + res = self.client.get( + f'/api/v1/runs/{self.test_id}/samples/1/regression-tests/{self.reg_test_id}' + f'/outputs/{self.reg_out_id}/diff?format=smart', + headers={'Authorization': f'Bearer {token}'}) + + self.assertEqual(res.status_code, 200) + self.assertEqual(res.json['format'], 'smart') + self.assertEqual(res.json['kind'], 'identical') + + def test_get_diff_smart_missing_actual_file(self): + self.reg_out.correct_extension = '.srt' + g.db.commit() + with open(os.path.join(self.test_results_dir, 'expected_hash.srt'), 'wb') as f: + f.write(b'1\n00:00:01,000 --> 00:00:02,000\nHello\n') + + with patch.dict('run.config', {'SAMPLE_REPOSITORY': self.dir_path}): + token = self.get_token( + 'res_user@local.com', 'userpass123', 't_smart_gone', scopes=['results:read']) + res = self.client.get( + f'/api/v1/runs/{self.test_id}/samples/1/regression-tests/{self.reg_test_id}' + f'/outputs/{self.reg_out_id}/diff?format=smart', + headers={'Authorization': f'Bearer {token}'}) + + self.assertEqual(res.status_code, 404) + + def test_get_diff_smart_requires_results_scope(self): + with patch.dict('run.config', {'SAMPLE_REPOSITORY': self.dir_path}): + token = self.get_token( + 'res_user@local.com', 'userpass123', 't_smart_scope', scopes=['runs:read']) + res = self.client.get( + f'/api/v1/runs/{self.test_id}/samples/1/regression-tests/{self.reg_test_id}' + f'/outputs/{self.reg_out_id}/diff?format=smart', + headers={'Authorization': f'Bearer {token}'}) + + self.assertEqual(res.status_code, 403) + + def test_missing_diff_body_smart_for_missing_output(self): + from mod_api.routes.results import _missing_diff_body + + body = _missing_diff_body('missing_actual', 'smart', {'run_id': 1}) + self.assertEqual(body['kind'], 'missing_output') + self.assertEqual(body['format'], 'smart') + self.assertEqual(body['run_id'], 1) + def test_create_baseline_approval(self): token = self.get_token('res_admin@local.com', 'adminpass123', 't6', scopes=['baselines:write']) diff --git a/tests/test_smartdiff/__init__.py b/tests/test_smartdiff/__init__.py new file mode 100644 index 000000000..68bc99968 --- /dev/null +++ b/tests/test_smartdiff/__init__.py @@ -0,0 +1 @@ +"""Tests for the smart-diff subtitle comparison.""" diff --git a/tests/test_smartdiff/fixtures/cea608_real.srt b/tests/test_smartdiff/fixtures/cea608_real.srt new file mode 100644 index 000000000..d0bf07ab9 --- /dev/null +++ b/tests/test_smartdiff/fixtures/cea608_real.srt @@ -0,0 +1,9 @@ +1 +00:00:05,956 --> 00:00:07,955 +CCextractor Start crdit Testing + +2 +00:00:13,913 --> 00:00:15,080 +>> WHICH OF THESE STORIES WILL +YOU BE TALKING ABOUT TRO + diff --git a/tests/test_smartdiff/fixtures/dvb_spanish_real.srt b/tests/test_smartdiff/fixtures/dvb_spanish_real.srt new file mode 100644 index 000000000..76a633c48 --- /dev/null +++ b/tests/test_smartdiff/fixtures/dvb_spanish_real.srt @@ -0,0 +1,59 @@ +1 +00:00:00,480 --> 00:01:05,479 +Para continuar con este debate, + +2 +00:00:06,080 --> 00:01:11,079 +gusted cree que si los partidarios +de Errejon fuesen derrotados + +3 +00:00:09,880 --> 00:01:14,879 +su propuesta en) Vistalegre, + +4 +00:00:12,920 --> 00:01:17,919 +Podemos deberia cambiar de portavoz +parlamentario? + +5 +00:00:19,080 --> 00:01:24,079 +éPuede representar al partido + +6 +00:00:21,400 --> 00:01:26,399 +en el Congreso alguienque'se ha +quedado en minoria + +7 +00:00:24,200 --> 00:01:29,199 +dentro del partido? + +8 +00:00:30,640 --> 00:01:35,639 +-Deciden los organos del partido la +linea de accion politica + +9 +00:00:34,200 --> 00:01:39,199 +dentro del partido. + +10 +00:00:43,120 --> 00:01:48,119 +Debemos acatar las decisiones +colectivas. + +11 +00:00:48,600 --> 00:01:53,599 +Si inicio Errejon reconoce que'se +ven esas lineas, + +12 +00:00:51,760 --> 00:01:56,759 +debe seguir adelante. + +13 +00:00:53,240 --> 00:01:58,239 +Solo.es canalizarla voz della +decision politica del partido. + diff --git a/tests/test_smartdiff/test_compare.py b/tests/test_smartdiff/test_compare.py new file mode 100644 index 000000000..a26a9b222 --- /dev/null +++ b/tests/test_smartdiff/test_compare.py @@ -0,0 +1,161 @@ +"""Tests for the semantic subtitle comparison / classifier.""" + +import unittest + +from mod_test.smartdiff.compare import smart_diff + + +def _srt(cues): + """ + Build SubRip text from (start_ms, end_ms, text) tuples. + + :param cues: Iterable of (start_ms, end_ms, text) tuples. + :type cues: list + :return: SubRip-formatted string. + :rtype: str + """ + def stamp(ms): + h, ms = divmod(ms, 3600000) + m, ms = divmod(ms, 60000) + s, ms = divmod(ms, 1000) + return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}" + + blocks = [] + for i, (start, end, text) in enumerate(cues, start=1): + blocks.append(f"{i}\n{stamp(start)} --> {stamp(end)}\n{text}\n") + return "\n".join(blocks) + + +_BASE = [(1000, 4000, "Hello world"), (5000, 8000, "Second line")] +_BASE_CAPS = [(1000, 4000, "HELLO WORLD"), (5000, 8000, "SECOND LINE")] + + +class SmartDiffTests(unittest.TestCase): + """Classifying the kind of difference between two outputs.""" + + def test_identical(self): + """Equal outputs classify as identical.""" + result = smart_diff(_srt(_BASE), _srt(_BASE)) + self.assertEqual(result["kind"], "identical") + + def test_timing_shift_reports_offset(self): + """A constant timing offset is reported as timing_shift with offset_ms.""" + shifted = [(s + 500, e + 500, t) for s, e, t in _BASE] + result = smart_diff(_srt(_BASE), _srt(shifted)) + self.assertEqual(result["kind"], "timing_shift") + self.assertEqual(result["offset_ms"], 500) + + def test_text_change_only(self): + """Same timing, different text classifies as text_change.""" + changed = [(1000, 4000, "Hello world"), (5000, 8000, "DIFFERENT")] + result = smart_diff(_srt(_BASE), _srt(changed)) + self.assertEqual(result["kind"], "text_change") + + def test_missing_cues(self): + """Fewer cues than expected classifies as missing_cues.""" + result = smart_diff(_srt(_BASE), _srt(_BASE[:1])) + self.assertEqual(result["kind"], "missing_cues") + self.assertEqual((result["expected_cues"], result["actual_cues"]), (2, 1)) + + def test_extra_cues(self): + """More cues than expected classifies as extra_cues.""" + more = _BASE + [(9000, 10000, "Third line")] + result = smart_diff(_srt(_BASE), _srt(more)) + self.assertEqual(result["kind"], "extra_cues") + + def test_mixed_when_text_and_count_differ(self): + """Both text changes and a count mismatch classify as mixed.""" + other = [(1000, 4000, "CHANGED"), (5000, 8000, "Second line"), + (9000, 10000, "Third")] + result = smart_diff(_srt(_BASE), _srt(other)) + self.assertEqual(result["kind"], "mixed") + + def test_works_on_webvtt_via_autodetect(self): + """smart_diff auto-detects WebVTT and still classifies a timing shift.""" + base = "WEBVTT\n\n00:00:01.000 --> 00:00:04.000\nHello\n" + shifted = "WEBVTT\n\n00:00:01.250 --> 00:00:04.250\nHello\n" + result = smart_diff(base, shifted) + self.assertEqual(result["kind"], "timing_shift") + self.assertEqual(result["offset_ms"], 250) + + def test_whitespace_padding_only(self): + """Trailing CEA-608 padding differences are flagged as cosmetic, not text.""" + padded = [(1000, 4000, "HELLO WORLD "), (5000, 8000, "SECOND LINE ")] + result = smart_diff(_srt(_BASE_CAPS), _srt(padded)) + self.assertEqual(result["kind"], "whitespace_change") + + def test_formatting_tags_only(self): + """A styling-tags-only difference is flagged as formatting, not text.""" + styled = [(1000, 4000, "Hello world"), (5000, 8000, "Second line")] + result = smart_diff(_srt(_BASE), _srt(styled)) + self.assertEqual(result["kind"], "formatting_change") + + def test_timing_drift_growing_offset(self): + """A growing (not constant) timing offset classifies as timing_drift.""" + base = [(1000, 2000, "A"), (5000, 6000, "B"), (9000, 10000, "C")] + drifted = [(1000, 2000, "A"), (5040, 6040, "B"), (9080, 10080, "C")] + result = smart_diff(_srt(base), _srt(drifted)) + self.assertEqual(result["kind"], "timing_drift") + + def test_split_cues_same_text_more_cues(self): + """One cue rendered as two (same words) classifies as split_cues.""" + one = [(1000, 4000, "hello world")] + two = [(1000, 2000, "hello"), (2000, 4000, "world")] + result = smart_diff(_srt(one), _srt(two)) + self.assertEqual(result["kind"], "split_cues") + + def test_merged_cues_same_text_fewer_cues(self): + """Two cues collapsed into one (same words) classifies as merged_cues.""" + two = [(1000, 2000, "hello"), (2000, 4000, "world")] + one = [(1000, 4000, "hello world")] + result = smart_diff(_srt(two), _srt(one)) + self.assertEqual(result["kind"], "merged_cues") + + def test_changes_list_text_detail(self): + """A text change lists which cue changed, with expected/actual snippets.""" + changed = [(1000, 4000, "Hello world"), (5000, 8000, "DIFFERENT")] + result = smart_diff(_srt(_BASE), _srt(changed)) + changes = result["changes"] + self.assertEqual(len(changes), 1) + self.assertEqual(changes[0]["cue"], 2) + self.assertEqual(changes[0]["kind"], "text") + self.assertEqual(changes[0]["actual"], "DIFFERENT") + + def test_changes_list_timing_offsets(self): + """A timing shift lists a per-cue offset for each cue.""" + shifted = [(s + 500, e + 500, t) for s, e, t in _BASE] + result = smart_diff(_srt(_BASE), _srt(shifted)) + self.assertTrue(all(c["offset_ms"] == 500 for c in result["changes"])) + + def test_identical_has_no_changes(self): + """An identical result carries no changes list.""" + self.assertNotIn("changes", smart_diff(_srt(_BASE), _srt(_BASE))) + + def test_no_cues_and_differ_is_unsupported_not_identical(self): + """Two different non-subtitle outputs (no cues) are not called identical.""" + result = smart_diff("plain transcript one", "plain transcript two") + self.assertEqual(result["kind"], "unsupported") + + def test_no_cues_but_equal_is_identical(self): + """Two equal cue-less outputs are still identical.""" + self.assertEqual(smart_diff("same text", "same text")["kind"], "identical") + + def test_text_change_with_shift_records_per_cue_offset(self): + """A combined text change + timing shift keeps the per-cue offset in changes.""" + base = [(1000, 2000, "A"), (5000, 6000, "B")] + other = [(1500, 2500, "X"), (5500, 6500, "Y")] + result = smart_diff(_srt(base), _srt(other)) + self.assertEqual(result["kind"], "text_change") + self.assertNotIn("aligned", result["summary"]) + self.assertTrue(all(c["offset_ms"] == 500 for c in result["changes"])) + + def test_encoding_change_non_ascii_only(self): + """A charset difference (accents only, e.g. -latin1) is flagged as encoding.""" + accented = [(1000, 4000, "Voilà"), (5000, 8000, "naïve café")] + folded = [(1000, 4000, "Voila"), (5000, 8000, "naive cafe")] + result = smart_diff(_srt(accented), _srt(folded)) + self.assertEqual(result["kind"], "encoding_change") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_smartdiff/test_fixtures.py b/tests/test_smartdiff/test_fixtures.py new file mode 100644 index 000000000..997f08dc5 --- /dev/null +++ b/tests/test_smartdiff/test_fixtures.py @@ -0,0 +1,133 @@ +"""Golden-fixture tests against real CCExtractor output, plus input robustness. + +The fixtures are genuine CCExtractor outputs (not synthetic strings): +- ``cea608_real.srt``: a CEA-608 broadcast caption sample (trailing padding). +- ``dvb_spanish_real.srt``: a DVB Spanish sample with ```` colour tags and + accented characters. Both were security-scanned before vendoring (no paths, + IPs, emails, URLs, or secrets) and are valid UTF-8. +""" + +import os +import unittest + +from mod_test.smartdiff.compare import smart_diff +from mod_test.smartdiff.normalize import ascii_fold, strip_tags +from mod_test.smartdiff.srt import Cue, parse_srt + +_FIXTURES = os.path.join(os.path.dirname(__file__), 'fixtures') + + +def _load(name): + """ + Read a vendored fixture as UTF-8. + + :param name: Fixture file name. + :type name: str + :return: The file content. + :rtype: str + """ + with open(os.path.join(_FIXTURES, name), encoding='utf-8') as handle: + return handle.read() + + +def _emit(cues): + """ + Serialise cues back to SubRip text (for building timing-shifted variants). + + :param cues: The cues to serialise. + :type cues: list + :return: SubRip-formatted text. + :rtype: str + """ + def stamp(ms): + hours, ms = divmod(ms, 3600000) + minutes, ms = divmod(ms, 60000) + seconds, ms = divmod(ms, 1000) + return f"{hours:02d}:{minutes:02d}:{seconds:02d},{ms:03d}" + + return "\n".join(f"{i}\n{stamp(c.start_ms)} --> {stamp(c.end_ms)}\n{c.text}\n" + for i, c in enumerate(cues, 1)) + + +class Cea608RealTests(unittest.TestCase): + """Smart diff on a genuine CEA-608 broadcast caption sample.""" + + def test_parses_real_sample(self): + """The real sample parses into its two CEA-608 cues.""" + cues = parse_srt(_load('cea608_real.srt')) + self.assertEqual(len(cues), 2) + self.assertEqual(cues[0].start_ms, 5956) + + def test_identical_against_itself(self): + """The real sample compared with itself is identical.""" + raw = _load('cea608_real.srt') + self.assertEqual(smart_diff(raw, raw)['kind'], 'identical') + + def test_depadding_is_cosmetic(self): + """Stripping the CEA-608 trailing padding is flagged as cosmetic only.""" + raw = _load('cea608_real.srt') + depadded = '\n'.join(line.rstrip() for line in raw.split('\n')) + self.assertIn(smart_diff(raw, depadded)['kind'], + ('identical', 'whitespace_change')) + + +class DvbSpanishRealTests(unittest.TestCase): + """Smart diff on a real DVB Spanish output (font colour tags + accents).""" + + def test_parses_with_tags_and_accents(self): + """The fixture has 13 cues carrying both font tags and non-ASCII text.""" + cues = parse_srt(_load('dvb_spanish_real.srt')) + self.assertEqual(len(cues), 13) + self.assertTrue(any(' 127 for c in cues for ch in c.text)) + + def test_identical(self): + """The fixture compared with itself is identical.""" + raw = _load('dvb_spanish_real.srt') + self.assertEqual(smart_diff(raw, raw)['kind'], 'identical') + + def test_constant_timing_shift(self): + """Shifting every cue by +500 ms is detected with the exact offset.""" + cues = parse_srt(_load('dvb_spanish_real.srt')) + shifted = [Cue(c.index, c.start_ms + 500, c.end_ms + 500, c.text) for c in cues] + result = smart_diff(_emit(cues), _emit(shifted)) + self.assertEqual(result['kind'], 'timing_shift') + self.assertEqual(result['offset_ms'], 500) + + def test_font_tags_are_formatting_only(self): + """Removing the colour tags is classified as formatting, not text.""" + raw = _load('dvb_spanish_real.srt') + self.assertEqual(smart_diff(raw, strip_tags(raw))['kind'], 'formatting_change') + + def test_accent_folding_is_encoding(self): + """Folding the accented characters is classified as an encoding difference.""" + raw = _load('dvb_spanish_real.srt') + self.assertEqual(smart_diff(raw, ascii_fold(raw))['kind'], 'encoding_change') + + def test_dropped_cues_are_missing(self): + """Dropping the last three cues is reported as missing_cues.""" + cues = parse_srt(_load('dvb_spanish_real.srt')) + result = smart_diff(_emit(cues), _emit(cues[:-3])) + self.assertEqual(result['kind'], 'missing_cues') + + +class RobustnessTests(unittest.TestCase): + """Malformed or hostile input must classify cleanly, never crash.""" + + def test_parser_survives_garbage(self): + """The parser returns a list for empty, junk, and control-byte input.""" + for junk in ['', 'not a subtitle', '\x00\x01\x02', '1\nno timing line\n']: + self.assertIsInstance(parse_srt(junk), list) + + def test_smart_diff_on_empty_inputs(self): + """Two empty inputs are identical, not an error.""" + self.assertEqual(smart_diff('', '')['kind'], 'identical') + + def test_smart_diff_garbage_vs_real(self): + """Garbage against a real sample classifies without raising.""" + result = smart_diff('garbage with no cues', _load('dvb_spanish_real.srt')) + self.assertIn('kind', result) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_smartdiff/test_normalize.py b/tests/test_smartdiff/test_normalize.py new file mode 100644 index 000000000..2b766e981 --- /dev/null +++ b/tests/test_smartdiff/test_normalize.py @@ -0,0 +1,55 @@ +"""Tests for CCExtractor-style normalisation of cue text.""" + +import unittest + +from mod_test.smartdiff.normalize import (ascii_fold, classify_text_pair, + plain, strip_tags, unescape) + + +class NormalizeTests(unittest.TestCase): + """Tag stripping, entity unescaping, and cue-text classification.""" + + def test_strip_tags(self): + """HTML/styling tags are removed.""" + self.assertEqual(strip_tags('hi'), 'hi') + + def test_unescape_entities(self): + """Known HTML entities are decoded, including a nested &.""" + self.assertEqual(unescape('a <b> & 30°'), 'a & 30°') + + def test_plain_combines_rules(self): + """plain() strips tags, unescapes, and rstrips padding together.""" + self.assertEqual(plain('hi & bye '), 'hi & bye') + + def test_classify_match(self): + """Identical text classifies as match.""" + self.assertEqual(classify_text_pair('hello', 'hello'), 'match') + + def test_classify_whitespace_only(self): + """Trailing CEA-608 padding differences classify as whitespace.""" + self.assertEqual(classify_text_pair('HELLO WORLD', 'HELLO WORLD '), 'whitespace') + + def test_classify_formatting_only(self): + """A tags-only difference classifies as formatting.""" + self.assertEqual(classify_text_pair('hello', 'hello'), 'formatting') + + def test_ascii_fold_decomposes_accents(self): + """ascii_fold strips accents and drops non-ASCII characters.""" + self.assertEqual(ascii_fold('Voilà café ♪'), 'Voila cafe ') + + def test_classify_encoding_only(self): + """A non-ASCII/accent-only difference classifies as encoding.""" + self.assertEqual(classify_text_pair('PRÉCIS', 'PRECIS'), 'encoding') + + def test_classify_real_text_change(self): + """A genuine text change classifies as text.""" + self.assertEqual(classify_text_pair('hello', 'goodbye'), 'text') + + def test_classify_non_latin_text_change_not_encoding(self): + """Two different non-Latin texts (empty ASCII skeleton) classify as text.""" + self.assertEqual(classify_text_pair('日本語', '中文'), 'text') + self.assertEqual(classify_text_pair('Привет', 'Спасибо'), 'text') + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_smartdiff/test_srt.py b/tests/test_smartdiff/test_srt.py new file mode 100644 index 000000000..55ed4c9c7 --- /dev/null +++ b/tests/test_smartdiff/test_srt.py @@ -0,0 +1,48 @@ +"""Tests for the SubRip (.srt) parser.""" + +import unittest + +from mod_test.smartdiff.srt import parse_srt + +_TWO_CUES = ( + "1\n" + "00:00:01,000 --> 00:00:04,000\n" + "Hello world\n" + "\n" + "2\n" + "00:00:05,500 --> 00:00:08,250\n" + "Second line\n" +) + + +class ParseSrtTests(unittest.TestCase): + """Parsing SubRip content into structured cues.""" + + def test_parses_index_timing_and_text(self): + """A two-cue file yields two cues with correct ms timing and text.""" + cues = parse_srt(_TWO_CUES) + self.assertEqual(len(cues), 2) + self.assertEqual((cues[0].index, cues[0].start_ms, cues[0].end_ms), (1, 1000, 4000)) + self.assertEqual(cues[0].text, "Hello world") + self.assertEqual((cues[1].start_ms, cues[1].end_ms), (5500, 8250)) + + def test_tolerates_crlf_and_bom(self): + """CRLF line endings and a leading BOM are handled.""" + cues = parse_srt("" + _TWO_CUES.replace("\n", "\r\n")) + self.assertEqual(len(cues), 2) + self.assertEqual(cues[1].text, "Second line") + + def test_skips_blocks_without_timing(self): + """A trailing junk block with no timing line is ignored.""" + cues = parse_srt(_TWO_CUES + "\nnot a cue\n") + self.assertEqual(len(cues), 2) + + def test_multiline_cue_text_preserved(self): + """Cue text spanning multiple lines is preserved with its newline.""" + content = "1\n00:00:01,000 --> 00:00:02,000\nline one\nline two\n" + cues = parse_srt(content) + self.assertEqual(cues[0].text, "line one\nline two") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_smartdiff/test_vtt.py b/tests/test_smartdiff/test_vtt.py new file mode 100644 index 000000000..695aeb11a --- /dev/null +++ b/tests/test_smartdiff/test_vtt.py @@ -0,0 +1,44 @@ +"""Tests for the WebVTT (.vtt) parser.""" + +import unittest + +from mod_test.smartdiff.vtt import parse_vtt + +_VTT = ( + "WEBVTT\n" + "\n" + "NOTE this is a comment\n" + "\n" + "1\n" + "00:00:01.000 --> 00:00:04.000 align:start position:50%\n" + "Hello world\n" + "\n" + "00:05.500 --> 00:08.250\n" + "Second line\n" +) + + +class ParseVttTests(unittest.TestCase): + """Parsing WebVTT content into structured cues.""" + + def test_parses_cues_and_skips_metadata(self): + """The WEBVTT header and NOTE block are skipped; cues are parsed.""" + cues = parse_vtt(_VTT) + self.assertEqual(len(cues), 2) + self.assertEqual((cues[0].start_ms, cues[0].end_ms), (1000, 4000)) + self.assertEqual(cues[0].text, "Hello world") + + def test_ignores_trailing_cue_settings(self): + """Cue settings after the end timestamp do not leak into timing/text.""" + cues = parse_vtt(_VTT) + self.assertEqual(cues[0].end_ms, 4000) + self.assertEqual(cues[0].text, "Hello world") + + def test_handles_optional_hours(self): + """A MM:SS.mmm timestamp without an hours component is parsed correctly.""" + cues = parse_vtt(_VTT) + self.assertEqual((cues[1].start_ms, cues[1].end_ms), (5500, 8250)) + + +if __name__ == "__main__": + unittest.main() diff --git a/web/src/components/DiffDrawer.test.tsx b/web/src/components/DiffDrawer.test.tsx index 8089fae20..80c16f140 100644 --- a/web/src/components/DiffDrawer.test.tsx +++ b/web/src/components/DiffDrawer.test.tsx @@ -1,4 +1,5 @@ import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; import { afterEach, describe, expect, it, vi } from "vitest"; import { DiffDrawer, type DiffTarget } from "@/components/DiffDrawer"; @@ -58,4 +59,146 @@ describe("DiffDrawer", () => { await screen.findByText(/output file for this result isn't present in storage/i), ).toBeInTheDocument(); }); + + describe("Smart view", () => { + /** Serve one smart-diff body and record which URLs were asked for. */ + function serveSmart(status: number, body: unknown) { + const calls: string[] = []; + vi.stubGlobal( + "fetch", + vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + calls.push(url); + if (url.includes("format=smart")) return jsonResponse(status, body); + return jsonResponse(200, { content: "" }); + }), + ); + return calls; + } + + async function openSmart() { + const user = userEvent.setup(); + const { wrapper } = createWrapper(); + render(, { wrapper }); + await user.click(screen.getByRole("button", { name: /smart/i })); + } + + it("asks the diff endpoint for the smart format", async () => { + const calls = serveSmart(200, { + kind: "identical", + summary: "Outputs are identical.", + expected_cues: 3, + actual_cues: 3, + }); + + await openSmart(); + + expect(await screen.findByText("Identical")).toBeInTheDocument(); + expect(calls.some((u) => u.endsWith("/regression-tests/7/outputs/3/diff?format=smart"))).toBe( + true, + ); + }); + + it("names a timing shift and its offset", async () => { + serveSmart(200, { + kind: "timing_shift", + summary: "All 2 cues match but are 500 ms late.", + expected_cues: 2, + actual_cues: 2, + offset_ms: 500, + changes: [ + { cue: 1, kind: "timing", offset_ms: 500 }, + { cue: 2, kind: "timing", offset_ms: 500 }, + ], + }); + + await openSmart(); + + expect(await screen.findByText("Timing shift")).toBeInTheDocument(); + expect(screen.getByText("All 2 cues match but are 500 ms late.")).toBeInTheDocument(); + expect(screen.getByText("2 expected · 2 actual cues")).toBeInTheDocument(); + expect(screen.getByText("Cue 1")).toBeInTheDocument(); + expect(screen.getAllByText("+500 ms")).toHaveLength(3); + }); + + it("shows expected and actual text for a changed cue", async () => { + serveSmart(200, { + kind: "text_change", + summary: "1 of 1 cues differ in text.", + expected_cues: 1, + actual_cues: 1, + changes: [{ cue: 1, kind: "text", expected: "Hello there", actual: "Goodbye" }], + }); + + await openSmart(); + + expect(await screen.findByText("Text changed")).toBeInTheDocument(); + expect(screen.getByText("- Hello there")).toBeInTheDocument(); + expect(screen.getByText("+ Goodbye")).toBeInTheDocument(); + }); + + it("renders caption text as text, never as markup", async () => { + serveSmart(200, { + kind: "text_change", + summary: "bold summary", + expected_cues: 1, + actual_cues: 1, + changes: [{ cue: 1, kind: "text", expected: "a", actual: "" }], + }); + + await openSmart(); + + expect(await screen.findByText("bold summary")).toBeInTheDocument(); + expect(screen.getByText("+ ")).toBeInTheDocument(); + expect(document.querySelector("script")).toBeNull(); + }); + + it("says when only some changed cues are listed", async () => { + serveSmart(200, { + kind: "mixed", + summary: "Mixed differences across 30 compared cues; expected 30, got 30.", + expected_cues: 30, + actual_cues: 30, + changes: Array.from({ length: 25 }, (_, n) => ({ cue: n + 1, kind: "whitespace" })), + changes_truncated: true, + }); + + await openSmart(); + + expect(await screen.findByText("Mixed changes")).toBeInTheDocument(); + expect(screen.getByText("Only the first 25 changed cues are listed.")).toBeInTheDocument(); + }); + + it("points to the Diff tab for outputs without captions", async () => { + serveSmart(200, { + kind: "unsupported", + summary: "No subtitle cues to compare (unsupported format); see the raw diff.", + expected_cues: 0, + actual_cues: 0, + }); + + await openSmart(); + + expect(await screen.findByText("Not a caption file")).toBeInTheDocument(); + expect(screen.getByText(/diff tab shows this output line by line/i)).toBeInTheDocument(); + }); + + it("explains when the output file is missing from storage", async () => { + serveSmart(404, { message: "not stored" }); + + await openSmart(); + + expect( + await screen.findByText(/output file for this result isn't present in storage/i), + ).toBeInTheDocument(); + }); + + it("is not offered for the combined-stdout diff", () => { + serveSmart(200, {}); + const { wrapper } = createWrapper(); + render(, { wrapper }); + + expect(screen.queryByRole("button", { name: /smart/i })).toBeNull(); + }); + }); }); diff --git a/web/src/components/DiffDrawer.tsx b/web/src/components/DiffDrawer.tsx index 4f15a1646..1a6949566 100644 --- a/web/src/components/DiffDrawer.tsx +++ b/web/src/components/DiffDrawer.tsx @@ -1,9 +1,18 @@ import { useQuery } from "@tanstack/react-query"; -import { Download, FileText, PlayCircle } from "lucide-react"; +import { Download, FileText, PlayCircle, Sparkles } from "lucide-react"; import { useEffect, useMemo, useRef, useState } from "react"; +import { Badge } from "@/components/ui/badge"; import { AnimatedSheet, SheetDescription, SheetTitle } from "@/components/ui/sheet"; -import { fetchConsoleDiff, fetchDiff, outputText, sampleFile } from "@/lib/api"; +import { + fetchConsoleDiff, + fetchDiff, + fetchSmartDiff, + outputText, + sampleFile, + type SmartChange, + type SmartDiff, +} from "@/lib/api"; import { clock, cuesToVtt, parseCues, type Cue } from "@/lib/cues"; import { cn } from "@/lib/utils"; @@ -29,7 +38,7 @@ function isConsole(target: DiffTarget): target is ConsoleDiffTarget { return target.kind === "console"; } -type View = "diff" | "playback"; +type View = "diff" | "smart" | "playback"; /** MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED — nothing here can decode the file. */ const MEDIA_ERR_SRC_NOT_SUPPORTED = 4; @@ -77,6 +86,12 @@ export function DiffDrawer({ on={view === "diff"} go={() => setView("diff")} /> + setView("smart")} + /> )} - {isConsole(target) || view === "diff" ? ( - - ) : ( - - )} + )} ); } +function Pane({ target, view }: Readonly<{ target: DiffTarget; view: View }>) { + if (isConsole(target) || view === "diff") return ; + if (view === "smart") return ; + return ; +} + function ViewTab({ icon: Icon, label, @@ -184,6 +201,118 @@ function DiffPane({ target }: Readonly<{ target: DiffTarget }>) { ); } +type Tone = "success" | "warning" | "destructive" | "secondary"; + +/** + * A plain name for each kind of difference, toned by how worried a reader + * should be: cosmetic changes are grey, timing is amber, lost or changed + * words are red. + */ +const SMART_KIND: Record = { + identical: { label: "Identical", tone: "success" }, + timing_shift: { label: "Timing shift", tone: "warning" }, + timing_drift: { label: "Timing drift", tone: "warning" }, + split_cues: { label: "Cues split", tone: "warning" }, + merged_cues: { label: "Cues merged", tone: "warning" }, + formatting_change: { label: "Formatting only", tone: "secondary" }, + whitespace_change: { label: "Whitespace only", tone: "secondary" }, + encoding_change: { label: "Encoding only", tone: "secondary" }, + unsupported: { label: "Not a caption file", tone: "secondary" }, + text_change: { label: "Text changed", tone: "destructive" }, + missing_cues: { label: "Cues missing", tone: "destructive" }, + extra_cues: { label: "Extra cues", tone: "destructive" }, + missing_output: { label: "No output", tone: "destructive" }, + mixed: { label: "Mixed changes", tone: "destructive" }, +}; + +const signed = (ms: number) => `${ms > 0 ? "+" : ""}${ms} ms`; + +/** + * What kind of difference this is, before anyone reads a line of diff. + * + * Most caption failures are a whole file shifted by a few frames or a change + * in padding; saying so up front is what saves opening the unified diff. + */ +function SmartPane({ target }: Readonly<{ target: OutputDiffTarget }>) { + const { data, isLoading, isError, error } = useQuery({ + queryKey: ["smart-diff", target.runId, target.regressionId, target.outputId], + staleTime: Infinity, + retry: false, + queryFn: () => fetchSmartDiff(target), + }); + + return ( +
+ {isLoading && } + {isError && ( + + {error instanceof Error ? error.message : "Could not load smart diff"} + {" — the output file for this result isn't present in storage."} + + )} + {data && } +
+ ); +} + +function SmartSummary({ diff }: Readonly<{ diff: SmartDiff }>) { + const kind = SMART_KIND[diff.kind] ?? { label: diff.kind, tone: "secondary" as const }; + return ( + <> +
+
+ {kind.label} + {diff.offset_ms !== undefined && ( + {signed(diff.offset_ms)} + )} + + {diff.expected_cues} expected · {diff.actual_cues} actual cues + +
+

{diff.summary}

+ {diff.kind === "unsupported" && ( +

The Diff tab shows this output line by line.

+ )} +
+ + {diff.changes && diff.changes.length > 0 && ( +
    + {diff.changes.map((change) => ( + + ))} +
+ )} + {diff.changes_truncated && ( +

+ Only the first {diff.changes?.length} changed cues are listed. +

+ )} + + ); +} + +function SmartChangeRow({ change }: Readonly<{ change: SmartChange }>) { + return ( +
  • + + Cue {change.cue} + +
    + {change.kind} + {change.offset_ms !== undefined && ( + {signed(change.offset_ms)} + )} + {change.expected !== undefined && ( +
    - {change.expected}
    + )} + {change.actual !== undefined && ( +
    + {change.actual}
    + )} +
    +
  • + ); +} + /** * The sample playing above its two caption tracks. * diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index f643ca413..8718b9c2c 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -855,6 +855,42 @@ export async function fetchDiff(args: { ); } +/** How one caption differs, from the smart diff. */ +export interface SmartChange { + cue: number; + kind: "timing" | "text" | "formatting" | "whitespace" | "encoding"; + offset_ms?: number; + expected?: string; + actual?: string; +} + +/** + * What kind of difference a failing caption output has — a timing shift, + * cosmetic-only changes, real text changes — rather than which lines moved. + */ +export interface SmartDiff { + kind: string; + summary: string; + expected_cues: number; + actual_cues: number; + offset_ms?: number; + changes?: SmartChange[]; + changes_truncated?: boolean; +} + +/** Smart (semantic) diff for one failing output of a run. */ +export async function fetchSmartDiff(args: { + runId: number; + sampleId: number; + regressionId: number; + outputId: number; +}): Promise { + return apiGet( + `/runs/${args.runId}/samples/${args.sampleId}/regression-tests/${args.regressionId}` + + `/outputs/${args.outputId}/diff?format=smart`, + ); +} + /** Diagnostic unified diff of combined VM stdout vs another run. */ export async function fetchConsoleDiff( runId: number,