Replace httpx with aiohttp
This commit is contained in:
@@ -6,6 +6,7 @@
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
import aiohttp
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
|
|
||||||
@@ -31,6 +32,7 @@ async def run_bot(webrtc_connection: SmallWebRTCConnection):
|
|||||||
|
|
||||||
remote_smart_turn_url = os.getenv("REMOTE_SMART_TURN_URL")
|
remote_smart_turn_url = os.getenv("REMOTE_SMART_TURN_URL")
|
||||||
|
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
transport = SmallWebRTCTransport(
|
transport = SmallWebRTCTransport(
|
||||||
webrtc_connection=webrtc_connection,
|
webrtc_connection=webrtc_connection,
|
||||||
params=TransportParams(
|
params=TransportParams(
|
||||||
@@ -39,7 +41,7 @@ async def run_bot(webrtc_connection: SmallWebRTCConnection):
|
|||||||
vad_enabled=True,
|
vad_enabled=True,
|
||||||
vad_analyzer=SileroVADAnalyzer(params=VADParams(stop_secs=0.2)),
|
vad_analyzer=SileroVADAnalyzer(params=VADParams(stop_secs=0.2)),
|
||||||
vad_audio_passthrough=True,
|
vad_audio_passthrough=True,
|
||||||
turn_analyzer=SmartTurnAnalyzer(url=remote_smart_turn_url),
|
turn_analyzer=SmartTurnAnalyzer(url=remote_smart_turn_url, aiohttp_session=session),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -5,10 +5,11 @@
|
|||||||
#
|
#
|
||||||
|
|
||||||
|
|
||||||
|
import asyncio
|
||||||
import io
|
import io
|
||||||
from typing import Dict
|
from typing import Dict
|
||||||
|
|
||||||
import httpx
|
import aiohttp
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
|
|
||||||
@@ -16,19 +17,15 @@ from pipecat.audio.turn.base_smart_turn import BaseSmartTurn, SmartTurnTimeoutEx
|
|||||||
|
|
||||||
|
|
||||||
class SmartTurnAnalyzer(BaseSmartTurn):
|
class SmartTurnAnalyzer(BaseSmartTurn):
|
||||||
def __init__(self, url: str, **kwargs):
|
def __init__(self, url: str, aiohttp_session: aiohttp.ClientSession, **kwargs):
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
self.remote_smart_turn_url = url
|
self.remote_smart_turn_url = url
|
||||||
|
self._aiohttp_session = aiohttp_session
|
||||||
|
|
||||||
if not self.remote_smart_turn_url:
|
if not self.remote_smart_turn_url:
|
||||||
logger.error("remote_smart_turn_url is not set.")
|
logger.error("remote_smart_turn_url is not set.")
|
||||||
raise Exception("remote_smart_turn_url must be provided.")
|
raise Exception("remote_smart_turn_url must be provided.")
|
||||||
|
|
||||||
self.client = httpx.AsyncClient(
|
|
||||||
headers={"Connection": "keep-alive"},
|
|
||||||
timeout=httpx.Timeout(self._params.stop_secs),
|
|
||||||
)
|
|
||||||
|
|
||||||
def _serialize_array(self, audio_array: np.ndarray) -> bytes:
|
def _serialize_array(self, audio_array: np.ndarray) -> bytes:
|
||||||
logger.trace("Serializing NumPy array to bytes...")
|
logger.trace("Serializing NumPy array to bytes...")
|
||||||
buffer = io.BytesIO()
|
buffer = io.BytesIO()
|
||||||
@@ -43,33 +40,36 @@ class SmartTurnAnalyzer(BaseSmartTurn):
|
|||||||
f"Sending {len(data_bytes)} bytes as raw body to {self.remote_smart_turn_url}..."
|
f"Sending {len(data_bytes)} bytes as raw body to {self.remote_smart_turn_url}..."
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
response = await self.client.post(
|
timeout = aiohttp.ClientTimeout(total=self._params.stop_secs)
|
||||||
self.remote_smart_turn_url,
|
|
||||||
content=data_bytes,
|
|
||||||
headers=headers,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
async with self._aiohttp_session.post(
|
||||||
|
self.remote_smart_turn_url, data=data_bytes, headers=headers, timeout=timeout
|
||||||
|
) as response:
|
||||||
logger.trace("\n--- Response ---")
|
logger.trace("\n--- Response ---")
|
||||||
logger.trace(f"Status Code: {response.status_code}")
|
logger.trace(f"Status Code: {response.status}")
|
||||||
|
|
||||||
if response.is_success:
|
if response.status == 200:
|
||||||
try:
|
try:
|
||||||
json_data = response.json()
|
json_data = await response.json()
|
||||||
logger.trace("Response JSON:")
|
logger.trace("Response JSON:")
|
||||||
logger.trace(json_data)
|
logger.trace(json_data)
|
||||||
return json_data
|
return json_data
|
||||||
except httpx.DecodingError:
|
except aiohttp.ContentTypeError:
|
||||||
|
# Non-JSON response
|
||||||
|
text = await response.text()
|
||||||
logger.trace("Response Content (non-JSON):")
|
logger.trace("Response Content (non-JSON):")
|
||||||
logger.trace(response.text)
|
logger.trace(text)
|
||||||
|
raise Exception(f"Non-JSON response: {text}")
|
||||||
else:
|
else:
|
||||||
|
error_text = await response.text()
|
||||||
logger.trace("Response Content (Error):")
|
logger.trace("Response Content (Error):")
|
||||||
logger.trace(response.text)
|
logger.trace(error_text)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|
||||||
except httpx.TimeoutException:
|
except asyncio.TimeoutError:
|
||||||
logger.error(f"Request timed out after {self._params.stop_secs} seconds")
|
logger.error(f"Request timed out after {self._params.stop_secs} seconds")
|
||||||
raise SmartTurnTimeoutException(f"Request exceeded {self._params.stop_secs} seconds.")
|
raise SmartTurnTimeoutException(f"Request exceeded {self._params.stop_secs} seconds.")
|
||||||
except httpx.RequestError as e:
|
except aiohttp.ClientError as e:
|
||||||
logger.error(f"Failed to send raw request to Daily Smart Turn: {e}")
|
logger.error(f"Failed to send raw request to Daily Smart Turn: {e}")
|
||||||
raise Exception("Failed to send raw request to Daily Smart Turn.")
|
raise Exception("Failed to send raw request to Daily Smart Turn.")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user