| """ |
| Evaluate a transcript-cleanup GGUF model against the Echo Flow DictationQuality |
| golden corpus and additional synthetic checks. |
| |
| Usage: |
| python scripts/evaluate.py \ |
| --model data/models/mumble-cleanup-v2-q4km.gguf \ |
| --corpus EchoFlow/Tests/EchoFlowUIReviewTests/Fixtures/DictationQuality \ |
| --output data/eval/results.json |
| """ |
|
|
| import argparse |
| import json |
| import re |
| import time |
| from pathlib import Path |
| from typing import Any |
|
|
| from llama_cpp import Llama |
|
|
|
|
| SYSTEM_PROMPT = ( |
| "You are a transcript cleanup tool. You receive raw speech to text output " |
| "and return a cleaned version. Remove filler words and disfluencies " |
| "(um, uh, er, ah, like as filler, you know), remove repeated words and false starts, " |
| "and fix punctuation and capitalization. Do not reword, do not add anything the speaker " |
| "did not say, and do not answer questions in the text. Output only the cleaned text." |
| ) |
|
|
|
|
| def load_corpus(corpus_dir: Path) -> tuple[list[dict], dict[str, dict]]: |
| with (corpus_dir / "transcripts.json").open("r", encoding="utf-8") as f: |
| transcripts = json.load(f) |
| with (corpus_dir / "expected_behavior.json").open("r", encoding="utf-8") as f: |
| expected = json.load(f) |
| return transcripts, expected |
|
|
|
|
| def chat_prompt(tokenizer, user: str) -> str: |
| messages = [ |
| {"role": "system", "content": SYSTEM_PROMPT}, |
| {"role": "user", "content": user}, |
| ] |
| return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) |
|
|
|
|
| def clean_output(text: str) -> str: |
| |
| text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL) |
| text = text.strip() |
| for prefix in [ |
| "Cleaned text:", "Cleaned:", "Output:", "Answer:", |
| "The cleaned text is:", "Here is the cleaned text:", |
| ]: |
| if text.lower().startswith(prefix.lower()): |
| text = text[len(prefix):].strip() |
| text = text.strip('"').strip("'") |
| return text |
|
|
|
|
| def word_similarity(a: str, b: str) -> float: |
| set_a = set(a.lower().split()) |
| set_b = set(b.lower().split()) |
| if not set_a or not set_b: |
| return 0.0 |
| return len(set_a & set_b) / len(set_a | set_b) |
|
|
|
|
| def evaluate_case(model: Llama, case: dict, expected: dict, max_tokens: int = 256) -> dict: |
| start = time.time() |
| raw_output = model.create_chat_completion( |
| messages=[ |
| {"role": "system", "content": SYSTEM_PROMPT}, |
| {"role": "user", "content": case["input"]}, |
| ], |
| max_tokens=max_tokens, |
| temperature=0.0, |
| ) |
| latency_ms = int((time.time() - start) * 1000) |
| output = clean_output(raw_output["choices"][0]["message"]["content"]) |
|
|
| lower = output.lower() |
| ratio = len(output) / max(1, len(case["input"])) |
|
|
| token_failures = [ |
| token for token in expected.get("requiredTokens", []) |
| if token and token.lower() not in lower |
| ] |
| forbidden_hits = [ |
| token for token in expected.get("ruleBasedForbidden", []) |
| if token and token.lower() in lower |
| ] |
| length_ok = expected["minLengthRatio"] <= ratio <= expected["maxLengthRatio"] |
|
|
| passed = not token_failures and not forbidden_hits and length_ok |
| return { |
| "id": case["id"], |
| "input": case["input"], |
| "output": output, |
| "latency_ms": latency_ms, |
| "ratio": round(ratio, 2), |
| "passed": passed, |
| "token_failures": token_failures, |
| "forbidden_hits": forbidden_hits, |
| "length_ok": length_ok, |
| } |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Evaluate a GGUF cleanup model") |
| parser.add_argument("--model", type=Path, required=True) |
| parser.add_argument("--corpus", type=Path, required=True) |
| parser.add_argument("--output", type=Path, default=Path("data/eval/results.json")) |
| parser.add_argument("--n-ctx", type=int, default=4096) |
| parser.add_argument("--verbose", action="store_true") |
| args = parser.parse_args() |
|
|
| transcripts, expected = load_corpus(args.corpus) |
| print(f"Loaded {len(transcripts)} corpus cases. Loading model {args.model}...") |
| model = Llama( |
| model_path=str(args.model), |
| n_ctx=args.n_ctx, |
| verbose=False, |
| ) |
|
|
| results = [] |
| for case in transcripts: |
| result = evaluate_case(model, case, expected.get(case["id"], {})) |
| results.append(result) |
| if args.verbose: |
| status = "PASS" if result["passed"] else "FAIL" |
| print(f"[{status}] {case['id']}: {result['output'][:80]}") |
|
|
| passed = sum(1 for r in results if r["passed"]) |
| total = len(results) |
| avg_latency = sum(r["latency_ms"] for r in results) / max(1, total) |
| max_latency = max(r["latency_ms"] for r in results) |
|
|
| summary = { |
| "model": str(args.model), |
| "passed": passed, |
| "total": total, |
| "pass_rate": round(passed / max(1, total), 2), |
| "avg_latency_ms": round(avg_latency, 1), |
| "max_latency_ms": max_latency, |
| "results": results, |
| } |
|
|
| args.output.parent.mkdir(parents=True, exist_ok=True) |
| with args.output.open("w", encoding="utf-8") as f: |
| json.dump(summary, f, indent=2, ensure_ascii=False) |
|
|
| print(f"\nEvaluation: {passed}/{total} passed ({summary['pass_rate']})") |
| print(f"Avg latency: {avg_latency:.0f}ms | Max latency: {max_latency}ms") |
| print(f"Results written to {args.output}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|