service_voice_smoke.py 2.27 KB
#!/usr/bin/env /usr/local/miniconda3/bin/python
from __future__ import annotations

import json
import subprocess
import time
from pathlib import Path
from urllib.request import Request, urlopen

BASE = 'http://127.0.0.1:8000'


def post_multipart(url: str, file_path: Path):
    boundary = '----acrboundary'
    data = file_path.read_bytes()
    body = (
        f'--{boundary}\r\n'
        f'Content-Disposition: form-data; name="file"; filename="{file_path.name}"\r\n'
        f'Content-Type: audio/mpeg\r\n\r\n'
    ).encode('utf-8') + data + f'\r\n--{boundary}--\r\n'.encode('utf-8')
    req = Request(url + '?top_n=1&max_chunks=1&include_context=true&corpus=workspace_music20', data=body, method='POST')
    req.add_header('Content-Type', f'multipart/form-data; boundary={boundary}')
    with urlopen(req, timeout=60) as resp:
        return json.loads(resp.read().decode('utf-8'))


def main():
    cmd = ['/usr/local/miniconda3/bin/python', '-m', 'uvicorn', 'src.service.app:app', '--host', '127.0.0.1', '--port', '8000']
    proc = subprocess.Popen(cmd, cwd='/root/vprecog/acr-engine', stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    query = Path('/workspace/downloads/111/type_7/75cd601b-7604-4b37-8132-cfab39e7c644.mp3')
    try:
        for _ in range(20):
            time.sleep(0.5)
            try:
                result = post_multipart(BASE + '/recognize/voice', query)
                top = result.get('candidates', [{}])[0] if result.get('candidates') else {}
                print(json.dumps({
                    'status': 'ok',
                    'corpus': result.get('corpus'),
                    'chunk_count': result.get('chunk_count'),
                    'top_song_id': top.get('song_id'),
                    'has_context': bool(top.get('context_clip')),
                    'reference_audio_path': top.get('reference_audio_path'),
                }, ensure_ascii=False, indent=2))
                return
            except Exception:
                continue
        raise SystemExit('service voice smoke failed: service not ready or endpoint failed')
    finally:
        proc.terminate()
        try:
            proc.wait(timeout=5)
        except subprocess.TimeoutExpired:
            proc.kill()
            proc.wait(timeout=5)


if __name__ == '__main__':
    main()