-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_wav_integration.py
More file actions
223 lines (176 loc) · 7.1 KB
/
Copy pathtest_wav_integration.py
File metadata and controls
223 lines (176 loc) · 7.1 KB
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#!/usr/bin/env python3
"""
Integration test for WAV conversion feature.
Requires valid SUNO_API_KEY and API credits.
Usage:
python3 test_wav_integration.py
"""
import asyncio
import os
import sys
from suno_client import SunoClient, SunoAPIError
async def test_wav_conversion_workflow():
"""Test complete workflow: generate music -> convert to WAV -> check status."""
# Check API key
api_key = os.getenv("SUNO_API_KEY")
if not api_key:
print("ERROR: SUNO_API_KEY not found in environment")
print("Set it with: export SUNO_API_KEY='your-key-here'")
return False
print("=" * 70)
print("WAV Conversion Integration Test")
print("=" * 70)
print()
print("This test will:")
print("1. Check API credits")
print("2. Generate a short test track")
print("3. Convert the track to WAV format")
print("4. Check conversion status")
print()
print("WARNING: This will consume API credits!")
print()
# Ask for confirmation
response = input("Continue with integration test? (y/N): ").strip().lower()
if response != 'y':
print("Test cancelled.")
return False
client = SunoClient()
try:
# Step 1: Check credits
print("\n" + "-" * 70)
print("Step 1: Checking API Credits")
print("-" * 70)
try:
credits_result = await client.get_credits()
credits = credits_result.get('data', 0)
print(f"✓ Remaining credits: {credits}")
if isinstance(credits, (int, float)) and credits < 5:
print("WARNING: Low credits. Test may fail.")
except SunoAPIError as e:
print(f"✗ Failed to get credits: {e}")
return False
# Step 2: Generate music
print("\n" + "-" * 70)
print("Step 2: Generating Test Track")
print("-" * 70)
print("Generating short test track (this may take 30-60 seconds)...")
try:
music_result = await client.generate_music(
prompt="Short upbeat test jingle",
make_instrumental=True,
model_version="V5",
wait_audio=True
)
if not music_result.get('data') or not isinstance(music_result['data'], list):
print(f"✗ Unexpected response format: {music_result}")
return False
track = music_result['data'][0]
track_id = track.get('id')
track_title = track.get('title', 'Unknown')
if not track_id:
print(f"✗ No track ID in response: {music_result}")
return False
print(f"✓ Generated track: {track_title}")
print(f" Track ID: {track_id}")
print(f" Status: {track.get('status', 'Unknown')}")
if track.get('audio_url'):
print(f" Audio URL: {track['audio_url']}")
except SunoAPIError as e:
print(f"✗ Failed to generate music: {e}")
return False
# Step 3: Convert to WAV
print("\n" + "-" * 70)
print("Step 3: Converting to WAV")
print("-" * 70)
print(f"Converting track {track_id} to WAV format...")
try:
wav_result = await client.convert_to_wav(
audio_id=track_id,
callback_url="https://example.com/webhook"
)
if not wav_result.get('data') or not isinstance(wav_result['data'], dict):
print(f"✗ Unexpected response format: {wav_result}")
return False
task_id = wav_result['data'].get('taskId')
if not task_id:
print(f"✗ No task ID in response: {wav_result}")
return False
print(f"✓ Conversion started")
print(f" Task ID: {task_id}")
except SunoAPIError as e:
print(f"✗ Failed to start conversion: {e}")
return False
# Step 4: Check conversion status
print("\n" + "-" * 70)
print("Step 4: Checking Conversion Status")
print("-" * 70)
print("Polling for conversion completion (max 60 seconds)...")
max_attempts = 20
poll_interval = 3
for attempt in range(1, max_attempts + 1):
try:
status_result = await client.get_wav_conversion_status(task_id)
if not status_result.get('data'):
print(f" Attempt {attempt}: No data in response")
await asyncio.sleep(poll_interval)
continue
status_data = status_result['data']
current_status = status_data.get('status', 'UNKNOWN')
print(f" Attempt {attempt}/{max_attempts}: {current_status}")
if current_status == 'COMPLETED':
response_data = status_data.get('response', {})
wav_data = response_data.get('wavData', {})
wav_url = wav_data.get('wavUrl')
print(f"\n✓ Conversion completed!")
print(f" Task ID: {status_data.get('taskId')}")
print(f" Audio ID: {wav_data.get('audioId')}")
print(f" WAV URL: {wav_url}")
print(f" Created: {wav_data.get('createTime', 'Unknown')}")
return True
elif current_status == 'FAILED':
print(f"\n✗ Conversion failed!")
print(f" Response: {status_result}")
return False
# Still processing, wait before next check
if attempt < max_attempts:
await asyncio.sleep(poll_interval)
except SunoAPIError as e:
print(f" Attempt {attempt}: Error checking status: {e}")
if attempt < max_attempts:
await asyncio.sleep(poll_interval)
print(f"\n⚠ Timeout after {max_attempts * poll_interval} seconds")
print("The conversion may still be processing. Check status later with:")
print(f" Task ID: {task_id}")
return False
except Exception as e:
print(f"\n✗ Unexpected error: {e}")
import traceback
traceback.print_exc()
return False
finally:
await client.close()
def main():
"""Run the integration test."""
try:
result = asyncio.run(test_wav_conversion_workflow())
print("\n" + "=" * 70)
if result:
print("✓ WAV CONVERSION INTEGRATION TEST PASSED")
print("=" * 70)
print("\nThe WAV conversion feature is working correctly with the Suno API!")
return 0
else:
print("✗ WAV CONVERSION INTEGRATION TEST FAILED")
print("=" * 70)
print("\nCheck the error messages above for details.")
return 1
except KeyboardInterrupt:
print("\n\nTest interrupted by user.")
return 1
except Exception as e:
print(f"\n\n✗ Test failed with error: {e}")
import traceback
traceback.print_exc()
return 1
if __name__ == "__main__":
exit(main())