81 lines
5.1 KiB
Python
81 lines
5.1 KiB
Python
import asyncio
|
|
import json
|
|
import subprocess
|
|
import tempfile
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
import websockets
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
CHROME = '/home/gorios-spark-2/.cache/ms-playwright/chromium_headless_shell-1243/chrome-headless-shell-linux-arm64/chrome-headless-shell'
|
|
|
|
|
|
async def main():
|
|
with tempfile.TemporaryDirectory(prefix='lan-voice-browser-') as profile:
|
|
process = subprocess.Popen([CHROME, '--headless', '--no-sandbox', '--ignore-certificate-errors', '--autoplay-policy=no-user-gesture-required', '--remote-debugging-address=127.0.0.1', '--remote-debugging-port=0', '--user-data-dir=' + profile, 'https://192.168.31.61:5011'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
try:
|
|
portfile = Path(profile) / 'DevToolsActivePort'
|
|
for _ in range(100):
|
|
if portfile.exists(): break
|
|
await asyncio.sleep(0.05)
|
|
port = portfile.read_text().splitlines()[0]
|
|
async with httpx.AsyncClient(trust_env=False) as client:
|
|
pages = (await client.get(f'http://127.0.0.1:{port}/json')).json()
|
|
target = next(p for p in pages if p['type'] == 'page')
|
|
async with websockets.connect(target['webSocketDebuggerUrl'], proxy=None) as ws:
|
|
counter = 0
|
|
async def cdp(method, params):
|
|
nonlocal counter
|
|
counter += 1; current = counter
|
|
await ws.send(json.dumps({'id': current, 'method': method, 'params': params}))
|
|
while True:
|
|
message = json.loads(await ws.recv())
|
|
if message.get('id') == current: return message
|
|
await asyncio.sleep(0.5)
|
|
result = await cdp('Runtime.evaluate', {'expression': '''(async()=>{
|
|
const {Resampler}=await import('/static/audio-core.js');
|
|
const {runPlaybackTests}=await import('/static/playback-test.js');
|
|
const playbackTests=runPlaybackTests();
|
|
const checks=[];
|
|
for(const rate of [44100,48000]){
|
|
const signal=Float32Array.from({length:rate*2},(_,i)=>Math.sin(i*.01));
|
|
const all=new Resampler(rate,16000).push(signal);
|
|
const r=new Resampler(rate,16000);let pieces=[];
|
|
for(let i=0;i<signal.length;i+=128)pieces.push(...r.push(signal.slice(i,i+128)));
|
|
if(all.length!==pieces.length||all.some((x,i)=>Math.abs(x-pieces[i])>1e-7))throw Error('resample drift');
|
|
checks.push({rate,outputSamples:pieces.length,chunkInvariant:true});
|
|
}
|
|
const context=new AudioContext();await context.resume();
|
|
await context.audioWorklet.addModule('/static/capture-worklet.js');
|
|
await context.audioWorklet.addModule('/static/play-worklet.js');
|
|
const node=new AudioWorkletNode(context,'playback');node.connect(context.destination);
|
|
const events=[];node.port.onmessage=e=>events.push(e.data);
|
|
node.port.postMessage({type:'clear',turn:1});
|
|
node.port.postMessage({type:'pcm',turn:1,pcm:new Float32Array(6000).fill(.1)});
|
|
node.port.postMessage({type:'end',turn:1});
|
|
await new Promise(r=>setTimeout(r,200));node.port.postMessage({type:'clear',turn:2});
|
|
await new Promise(r=>setTimeout(r,50));await context.close();
|
|
let microphone;
|
|
try{const stream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:true,noiseSuppression:true,autoGainControl:true}});microphone={available:true,settings:stream.getAudioTracks()[0].getSettings()};stream.getTracks().forEach(t=>t.stop());}catch(e){microphone={available:false,error:e.name};}
|
|
return {secureContext:isSecureContext,title:document.title,checks,playbackTests,workletEvents:events,microphone,opusDisabled:document.querySelector('#codec option:nth-child(2)').disabled};
|
|
})()''', 'awaitPromise': True, 'returnByValue': True})
|
|
if 'exceptionDetails' in result.get('result', {}): raise RuntimeError(result)
|
|
await cdp('Page.captureScreenshot', {'format':'png'})
|
|
for width,name in [(1100,'desktop'),(390,'mobile')]:
|
|
await cdp('Emulation.setDeviceMetricsOverride', {'width':width,'height':900,'deviceScaleFactor':1,'mobile':width<500})
|
|
shot=await cdp('Page.captureScreenshot', {'format':'png'})
|
|
import base64
|
|
(ROOT / ('tmp/home-'+name+'.png')).write_bytes(base64.b64decode(shot['result']['data']))
|
|
data = result['result']['result']['value']
|
|
print(json.dumps(data, ensure_ascii=False))
|
|
(ROOT / 'tmp/browser_validation.json').write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n')
|
|
finally:
|
|
process.terminate()
|
|
try: process.wait(timeout=5)
|
|
except subprocess.TimeoutExpired: process.kill(); process.wait()
|
|
|
|
|
|
if __name__ == '__main__': asyncio.run(main())
|