File size: 4,064 Bytes
e412140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Step 2: metadata.tsv → FLAC-to-WAV conversion + metadata_kimi_train.jsonl

WARNING: This script converts all .flac files to .wav IN-PLACE and deletes the .flac.
         WAV files are approximately 2-3x larger than FLAC.
         Purpose: produce training data in Kimi-Audio conversation format.

Output: metadata_kimi_train.jsonl  (same directory as this script)
        Each pair produces two entries:
          1. EN→ZH: user gives EN audio, assistant responds with ZH audio + ZH text
          2. ZH→EN: user gives ZH audio, assistant responds with EN audio + EN text
"""

import csv
import json
import os
import soundfile as sf
from tqdm import tqdm

BASE_DIR     = os.path.dirname(__file__)
INPUT_TSV    = os.path.join(BASE_DIR, "metadata.tsv")
OUTPUT_JSONL = os.path.join(BASE_DIR, "metadata_kimi_train.jsonl")


def flac_to_wav(flac_path: str) -> str:
    """Convert a .flac file to .wav in-place (deletes .flac). Returns .wav path."""
    wav_path = flac_path[:-5] + ".wav"
    data, sr = sf.read(flac_path)
    sf.write(wav_path, data, sr)
    os.remove(flac_path)
    return wav_path


def flac_rel_to_wav_rel(p: str) -> str:
    return p[:-5] + ".wav" if p.endswith(".flac") else p


def main():
    with open(INPUT_TSV, "r", encoding="utf-8") as f:
        rows = list(csv.DictReader(f, delimiter="\t"))
    print(f"Loaded {len(rows)} pairs from {INPUT_TSV}")
    print("Converting FLAC → WAV (in-place) and writing metadata_kimi_train.jsonl ...")

    ok = skip = fail = 0
    out_f = open(OUTPUT_JSONL, "w", encoding="utf-8")

    for row in tqdm(rows, unit="pairs"):
        zh_flac = os.path.join(BASE_DIR, row["zh_path"])
        en_flac = os.path.join(BASE_DIR, row["en_path"])
        zh_text = row["zh_text"]
        en_text = row["en_text"]

        # Convert FLAC → WAV for both files
        converted = {}
        for key, flac_abs in [("zh", zh_flac), ("en", en_flac)]:
            wav_abs = flac_abs[:-5] + ".wav"
            if os.path.exists(wav_abs):
                converted[key] = wav_abs
            elif os.path.exists(flac_abs):
                try:
                    converted[key] = flac_to_wav(flac_abs)
                except Exception as e:
                    print(f"\n  FAILED converting {flac_abs}: {e}")
                    fail += 1
                    break
            else:
                print(f"\n  MISSING: {flac_abs}")
                fail += 1
                break
        else:
            # Both converted successfully — write two conversation entries
            en_rel = flac_rel_to_wav_rel(row["en_path"])
            zh_rel = flac_rel_to_wav_rel(row["zh_path"])

            # EN → ZH
            out_f.write(json.dumps({
                "task_type": "s-s",
                "conversation": [
                    {"role": "user",      "message_type": "text",       "content": "Translate the given English speech into Chinese while preserving its expressiveness."},
                    {"role": "user",      "message_type": "audio",      "content": en_rel},
                    {"role": "assistant", "message_type": "audio-text", "content": [zh_rel, zh_text]},
                ]
            }, ensure_ascii=False) + "\n")

            # ZH → EN
            out_f.write(json.dumps({
                "task_type": "s-s",
                "conversation": [
                    {"role": "user",      "message_type": "text",       "content": "Translate the given Chinese speech into English while preserving its expressiveness."},
                    {"role": "user",      "message_type": "audio",      "content": zh_rel},
                    {"role": "assistant", "message_type": "audio-text", "content": [en_rel, en_text]},
                ]
            }, ensure_ascii=False) + "\n")

            ok += 1
            continue

        skip += 1

    out_f.close()
    print(f"\nDone: {ok} pairs converted, {skip} skipped/missing, {fail} errors")
    print(f"Output: {OUTPUT_JSONL}  ({ok * 2} total conversation entries)")


if __name__ == "__main__":
    main()