import requests, json

r = requests.post(
    'https://dashscope.aliyuncs.com/api/v1/services/audio/tts/SpeechSynthesizer',
    headers={'Authorization': 'Bearer sk-c25679401ba24c749f53be86b0c9a7a6', 'Content-Type': 'application/json', 'X-DashScope-SSE': 'enable'},
    json={'model': 'cosyvoice-v3-flash', 'input': {'text': '春天来了万物复苏阳光温暖', 'voice': 'longanyang', 'format': 'mp3', 'sample_rate': 24000}},
    stream=True
)

chunks = []
for line in r.iter_lines(decode_unicode=True):
    if line and line.startswith('data:'):
        try:
            d = json.loads(line[5:].strip())
            data = d.get('output',{}).get('audio',{}).get('data','')
            if data:
                chunks.append(data)
        except: pass

import base64
audio = b''.join(base64.b64decode(c) for c in chunks)
print(f'HTTP {r.status_code}, chunks: {len(chunks)}, total: {len(audio)} bytes')
with open('test-results/sse_test.mp3', 'wb') as f:
    f.write(audio)
print('saved to test-results/sse_test.mp3')
