File size: 1,316 Bytes
c202fc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""Text helpers shared by the voice-study scripts.

Copied verbatim from the stimulus-generation code, which is not part of the
release.
"""

from __future__ import annotations

import re

HIST_SPLIT = re.compile(r"role: (user|model)\\n response: ")  # literal \n, as in the survey JS


def normalize(text: str) -> list[str]:
    text = text.lower()
    text = re.sub(r"[^a-z0-9' ]+", " ", text)
    return text.split()


def wer(ref: list[str], hyp: list[str]) -> float:
    """Standard word error rate via edit distance."""
    d = list(range(len(hyp) + 1))
    for i, r in enumerate(ref, 1):
        prev, d[0] = d[0], i
        for j, h in enumerate(hyp, 1):
            cur = min(d[j] + 1, d[j - 1] + 1, prev + (r != h))
            prev, d[j] = d[j], cur
    return d[-1] / max(1, len(ref))


def parse_history(prev_hist: str) -> list[tuple[str, str]]:
    """-> [(role, text), ...] in order; identical logic to the survey page."""
    parts = [p for p in HIST_SPLIT.split(prev_hist)]
    turns, i = [], 0
    # split() yields [pre, role, text, role, text, ...]; pre is empty or noise
    while i + 1 < len(parts):
        if parts[i] in ("user", "model") and parts[i + 1].strip():
            turns.append((parts[i], parts[i + 1].strip()))
            i += 2
        else:
            i += 1
    return turns