From dde9313cd8fced2b736136fb0ff356baae9ef8d5 Mon Sep 17 00:00:00 2001 From: movchan74 Date: Wed, 8 Nov 2023 12:53:44 +0000 Subject: [PATCH] Fixed pydantic serializartion issue. Whisper is running now. --- aana/api/responses.py | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/aana/api/responses.py b/aana/api/responses.py index e16d8274..e50353ef 100644 --- a/aana/api/responses.py +++ b/aana/api/responses.py @@ -1,6 +1,33 @@ from typing import Any, Optional from fastapi.responses import JSONResponse import orjson +from pydantic import BaseModel + + +def orjson_default(obj: Any) -> Any: + """ + Default function for orjson.dumps to handle pydantic models. + + If orjson does not know how to serialize an object, it calls the default function. + + If we see that the object is a pydantic model, + we call the dict method to get the dictionary representation of the model that orjson can serialize. + + If the object is not a pydantic model, we raise a TypeError. + + Args: + obj (Any): The object to serialize. + + Returns: + Any: The serialized object. + + Raises: + TypeError: If the object is not a pydantic model. + """ + + if isinstance(obj, BaseModel): + return obj.dict() + raise TypeError class AanaJSONResponse(JSONResponse): @@ -23,4 +50,4 @@ def render(self, content: Any) -> bytes: """ Override the render method to use orjson.dumps instead of json.dumps. """ - return orjson.dumps(content, option=self.option) + return orjson.dumps(content, option=self.option, default=orjson_default)