File size: 5,677 Bytes
e2908eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#!/usr/bin/env python3
"""Build a one-row-per-song Acidwave CSV using the agent's transcribe_audio().

Run without --audio-dir to create the catalog manifest. With --audio-dir, run
inside the webarena-pro Python environment with OPENAI_API_KEY set. Completed
rows are retained across runs so an interrupted transcription can be resumed.
"""

from __future__ import annotations

import argparse
import csv
import os
import sys
from datetime import datetime, timezone
from pathlib import Path

from transcribe_songs import load_catalog


ACIDWAVE_DIR = Path(__file__).resolve().parents[1]
AGENT_TRANSCRIBER = "webarena_pro.benchmark.audio.transcribe_audio"
TRANSCRIPT_SOURCE = f"{AGENT_TRANSCRIBER} (whisper-1 API default)"
FIELDS = [
    "catalog_index",
    "song_title",
    "artist",
    "album",
    "genre",
    "genre_source",
    "audio_file",
    "audio_url",
    "transcript",
    "transcript_source",
    "status",
    "error",
    "transcribed_at_utc",
]


def write_rows(path: Path, rows: list[dict[str, str]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + ".tmp")
    with temporary.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=FIELDS)
        writer.writeheader()
        writer.writerows(rows)
        handle.flush()
        os.fsync(handle.fileno())
    os.replace(temporary, path)


def read_rows(path: Path) -> dict[str, dict[str, str]]:
    if not path.exists():
        return {}
    with path.open(encoding="utf-8", newline="") as handle:
        rows = list(csv.DictReader(handle))
    files = [row["audio_file"] for row in rows]
    if len(files) != len(set(files)):
        raise ValueError(f"Duplicate audio_file in existing CSV: {path}")
    return {row["audio_file"]: row for row in rows}


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--seed-sql", type=Path, default=ACIDWAVE_DIR / "database" / "seed.sql"
    )
    parser.add_argument(
        "--output", type=Path, default=ACIDWAVE_DIR / "data" / "acidwave_agent_transcripts.csv"
    )
    parser.add_argument(
        "--audio-dir", type=Path, help="Directory containing the catalog MP3 files"
    )
    args = parser.parse_args()

    catalog = load_catalog(args.seed_sql)
    files = [song["audio_file"] for song in catalog]
    if len(files) != len(set(files)):
        raise ValueError("The seed catalog has duplicate audio filenames")
    existing = read_rows(args.output)
    rows: list[dict[str, str]] = []
    for song in catalog:
        old = existing.get(song["audio_file"], {})
        verified_old = (
            old.get("status") == "completed"
            and old.get("transcript_source") == TRANSCRIPT_SOURCE
            and bool(old.get("transcript", "").strip())
        )
        rows.append(
            {
                "catalog_index": song["catalog_index"],
                "song_title": song["song_title"],
                "artist": song["artist"],
                "album": song["album"],
                "genre": song["genre"],
                "genre_source": "Acidwave database/seed.sql songs.genre",
                "audio_file": song["audio_file"],
                "audio_url": f"/audio/{song['audio_file']}",
                "transcript": old["transcript"] if verified_old else "",
                "transcript_source": TRANSCRIPT_SOURCE if verified_old else "",
                "status": "completed" if verified_old else "awaiting_audio",
                "error": "",
                "transcribed_at_utc": old.get("transcribed_at_utc", "") if verified_old else "",
            }
        )

    write_rows(args.output, rows)
    if args.audio_dir is None:
        print(f"Wrote {len(rows)} catalog rows to {args.output}; no audio directory supplied.")
        return 0

    pending = [row for row in rows if row["status"] != "completed"]
    for row in pending:
        if not (args.audio_dir / row["audio_file"]).is_file():
            row["status"] = "missing_audio"
            row["error"] = f"Audio file not found: {args.audio_dir / row['audio_file']}"
    write_rows(args.output, rows)
    available = [row for row in pending if row["status"] != "missing_audio"]
    if not available:
        print(f"No audio to transcribe; {len(rows)} catalog rows in {args.output}.")
        return 1 if pending else 0
    if not os.environ.get("OPENAI_API_KEY"):
        print("OPENAI_API_KEY is required by the agent's default whisper-1 transcriber.", file=sys.stderr)
        return 2

    from webarena_pro.benchmark.audio import transcribe_audio

    for position, row in enumerate(available, start=1):
        audio_path = args.audio_dir / row["audio_file"]
        print(f"[{position}/{len(available)}] {row['song_title']} ({row['audio_file']})", flush=True)
        try:
            # This is the same call made by the agent's full-file transcribe() action.
            transcript = transcribe_audio(audio_path.read_bytes())
            row["transcript"] = transcript
            row["transcript_source"] = TRANSCRIPT_SOURCE
            row["status"] = "completed" if transcript else "empty_result"
            row["error"] = "" if transcript else "Agent transcriber returned no text"
            row["transcribed_at_utc"] = datetime.now(timezone.utc).isoformat()
        except Exception as exc:
            row["status"] = "error"
            row["error"] = f"{type(exc).__name__}: {exc}"
        finally:
            write_rows(args.output, rows)

    return 0 if all(row["status"] == "completed" for row in rows) else 1


if __name__ == "__main__":
    raise SystemExit(main())