MusicLounge1 / test_api.py
Productive Pod
c1.
a24acdc
Raw History Blame Contribute Delete
6.05 kB
"""
Test script for Hindi Karaoke Generator API
Demonstrates all endpoints and features
"""
import requests
import time
import json
# Configuration
BASE_URL = "http://localhost:7860" # Change to your HuggingFace Space URL
AUDIO_URL = "https://example.com/your-song.mp3" # Replace with actual audio URL
def test_health():
"""Test health endpoint"""
print("\n=== Testing Health Endpoint ===")
response = requests.get(f"{BASE_URL}/health")
print(f"Status: {response.status_code}")
print(f"Response: {json.dumps(response.json(), indent=2)}")
return response.ok
def test_version():
"""Test version endpoint"""
print("\n=== Testing Version Endpoint ===")
response = requests.get(f"{BASE_URL}/version")
print(f"Status: {response.status_code}")
print(f"Response: {json.dumps(response.json(), indent=2)}")
return response.ok
def test_generate_with_whisper():
"""Test karaoke generation with Whisper transcription"""
print("\n=== Testing Generate with Whisper ===")
payload = {
"audio_url": AUDIO_URL,
"start_time": "00:00:00",
"duration": 30,
"font_color": "&HFFFFFF&",
"lyrics_mode": "both",
"max_font_size": 58,
"min_font_size": 38
}
print(f"Request: {json.dumps(payload, indent=2)}")
response = requests.post(f"{BASE_URL}/generate", json=payload)
print(f"Status: {response.status_code}")
if response.ok:
data = response.json()
print(f"Response: {json.dumps(data, indent=2)}")
return data.get("job_id")
else:
print(f"Error: {response.text}")
return None
def test_generate_with_lrc():
"""Test karaoke generation with LRC lyrics"""
print("\n=== Testing Generate with LRC ===")
lrc_content = """[00:00.50]यह एक नमूना गीत है
[00:03.20]Yeh ek namoona geet hai
[00:06.00]संगीत के साथ गाना
[00:08.80]Sangeet ke saath gaana
[00:11.50]हर शब्द को समझना
[00:14.30]Har shabd ko samajhna
[00:17.00]यही है असली मज़ा
[00:19.80]Yahi hai asli maza
[00:22.50]करोके का आनंद लो
[00:25.30]Karaoke ka anand lo"""
payload = {
"audio_url": AUDIO_URL,
"start_time": "00:00:00",
"duration": 30,
"font_color": "&H00FFFF&", # Cyan color
"lyrics_mode": "both",
"lrc_content": lrc_content
}
print(f"Request with LRC content ({len(lrc_content)} chars)")
response = requests.post(f"{BASE_URL}/generate", json=payload)
print(f"Status: {response.status_code}")
if response.ok:
data = response.json()
print(f"Response: {json.dumps(data, indent=2)}")
return data.get("job_id")
else:
print(f"Error: {response.text}")
return None
def test_job_status(job_id):
"""Test job status endpoint"""
print(f"\n=== Testing Job Status for {job_id} ===")
max_attempts = 60 # 5 minutes max
attempt = 0
while attempt < max_attempts:
response = requests.get(f"{BASE_URL}/status/{job_id}")
if response.ok:
data = response.json()
status = data.get("status")
progress = data.get("progress", 0)
print(f"Attempt {attempt + 1}: Status={status}, Progress={progress}%")
if status == "completed":
print("✅ Job completed successfully!")
return True
elif status == "failed":
print(f"❌ Job failed: {data.get('error')}")
return False
time.sleep(5) # Wait 5 seconds before next check
attempt += 1
else:
print(f"Error checking status: {response.text}")
return False
print("⏱️ Timeout waiting for job completion")
return False
def test_download(job_id):
"""Test download endpoint"""
print(f"\n=== Testing Download for {job_id} ===")
response = requests.get(f"{BASE_URL}/download/{job_id}", stream=True)
if response.ok:
# Get filename from Content-Disposition header
content_disposition = response.headers.get('Content-Disposition', '')
filename = content_disposition.split('filename=')[-1].strip('"') if 'filename=' in content_disposition else f"{job_id}.mp4"
# Save file
output_path = f"test_output_{filename}"
with open(output_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"✅ Video downloaded: {output_path}")
print(f"File size: {len(open(output_path, 'rb').read()) / 1024 / 1024:.2f} MB")
return True
else:
print(f"❌ Download failed: {response.text}")
return False
def main():
"""Run all tests"""
print("=" * 60)
print("Hindi Karaoke Generator API Test Suite")
print("=" * 60)
# Test basic endpoints
if not test_health():
print("❌ Health check failed!")
return
if not test_version():
print("❌ Version check failed!")
return
# Choose test mode
print("\n" + "=" * 60)
print("Select test mode:")
print("1. Generate with Whisper (auto transcription)")
print("2. Generate with LRC (manual lyrics)")
print("3. Both")
choice = input("Enter choice (1/2/3): ").strip()
job_ids = []
if choice in ["1", "3"]:
job_id = test_generate_with_whisper()
if job_id:
job_ids.append(job_id)
if choice in ["2", "3"]:
job_id = test_generate_with_lrc()
if job_id:
job_ids.append(job_id)
# Monitor and download
for job_id in job_ids:
if test_job_status(job_id):
test_download(job_id)
print("\n" + "=" * 60)
print("Test suite completed!")
print("=" * 60)
if __name__ == "__main__":
main()