import json, os, re, requests, time

with open('test/all_voices.json', 'r', encoding='utf-8') as f:
    raw = f.read()
m = re.search(r'"(\[.*\])"', raw, re.DOTALL)
data = json.loads(m.group(1).replace(r'\"', '"').replace(r'\\\\', '\\'))

print(f'共 {len(data)} 个音色')
os.makedirs('voices', exist_ok=True)

dl = skip = fail = 0
for i, v in enumerate(data):
    url, voice = v['url'], v['voice']
    if not url or not voice:
        skip += 1; continue
    fpath = f'voices/{voice}.mp3'
    if os.path.exists(fpath):
        skip += 1; continue
    try:
        r = requests.get(url, timeout=30)
        if r.status_code == 200 and len(r.content) > 100:
            open(fpath, 'wb').write(r.content); dl += 1
        else: fail += 1
    except: fail += 1
    if (i+1) % 30 == 0:
        print(f'  进度: {i+1}/{len(data)} (下载{dl} 跳过{skip} 失败{fail})')
    time.sleep(0.15)

print(f'\n完成! 下载{dl} 跳过{skip} 失败{fail}')
# 列表
files = sorted(os.listdir('voices'))
print(f'voices/ 共 {len(files)} 个文件:')
for f in files[:20]:
    print(f'  {f}')
if len(files) > 20:
    print(f'  ... 等 {len(files)} 个')
