serializers: allow str | bytes | None

This commit is contained in:
Aleix Conchillo Flaqué
2024-06-21 08:20:25 -07:00
parent e195941aa5
commit 25ef0cb87b
4 changed files with 7 additions and 5 deletions

View File

@@ -12,9 +12,9 @@ from pipecat.frames.frames import Frame
class FrameSerializer(ABC): class FrameSerializer(ABC):
@abstractmethod @abstractmethod
def serialize(self, frame: Frame) -> bytes: def serialize(self, frame: Frame) -> str | bytes | None:
pass pass
@abstractmethod @abstractmethod
def deserialize(self, data: bytes) -> Frame | None: def deserialize(self, data: str | bytes) -> Frame | None:
pass pass

View File

@@ -26,7 +26,7 @@ class ProtobufFrameSerializer(FrameSerializer):
def __init__(self): def __init__(self):
pass pass
def serialize(self, frame: Frame) -> bytes: def serialize(self, frame: Frame) -> str | bytes | None:
proto_frame = frame_protos.Frame() proto_frame = frame_protos.Frame()
if type(frame) not in self.SERIALIZABLE_TYPES: if type(frame) not in self.SERIALIZABLE_TYPES:
raise ValueError( raise ValueError(
@@ -41,7 +41,7 @@ class ProtobufFrameSerializer(FrameSerializer):
result = proto_frame.SerializeToString() result = proto_frame.SerializeToString()
return result return result
def deserialize(self, data: bytes) -> Frame | None: def deserialize(self, data: str | bytes) -> Frame | None:
"""Returns a Frame object from a Frame protobuf. Used to convert frames """Returns a Frame object from a Frame protobuf. Used to convert frames
passed over the wire as protobufs to Frame objects used in pipelines passed over the wire as protobufs to Frame objects used in pipelines
and frame processors. and frame processors.

View File

@@ -33,6 +33,7 @@ def calculate_audio_volume(audio: bytes, sample_rate: int) -> float:
def exp_smoothing(value: float, prev_value: float, factor: float) -> float: def exp_smoothing(value: float, prev_value: float, factor: float) -> float:
return prev_value + factor * (value - prev_value) return prev_value + factor * (value - prev_value)
def ulaw_8000_to_pcm_16000(ulaw_8000_bytes): def ulaw_8000_to_pcm_16000(ulaw_8000_bytes):
# Convert μ-law to PCM # Convert μ-law to PCM
pcm_8000_bytes = audioop.ulaw2lin(ulaw_8000_bytes, 2) pcm_8000_bytes = audioop.ulaw2lin(ulaw_8000_bytes, 2)
@@ -42,6 +43,7 @@ def ulaw_8000_to_pcm_16000(ulaw_8000_bytes):
return pcm_16000_bytes return pcm_16000_bytes
def pcm_16000_to_ulaw_8000(pcm_16000_bytes): def pcm_16000_to_ulaw_8000(pcm_16000_bytes):
# Resample from 16000 Hz to 8000 Hz # Resample from 16000 Hz to 8000 Hz
pcm_8000_bytes = audioop.ratecv(pcm_16000_bytes, 2, 1, 16000, 8000, None)[0] pcm_8000_bytes = audioop.ratecv(pcm_16000_bytes, 2, 1, 16000, 8000, None)[0]