[docs]defstringify_value(val:Any)->str:"""Stringify a value. Args: val: The value to stringify. Returns: str: The stringified value. """ifisinstance(val,str):returnvalifisinstance(val,dict):return"\n"+stringify_dict(val)ifisinstance(val,list):return"\n".join(stringify_value(v)forvinval)returnstr(val)
[docs]defstringify_dict(data:dict)->str:"""Stringify a dictionary. Args: data: The dictionary to stringify. Returns: str: The stringified dictionary. """text=""forkey,valueindata.items():text+=key+": "+stringify_value(value)+"\n"returntext
[docs]defcomma_list(items:list[Any])->str:"""Convert a list to a comma-separated string. Args: items: The list to convert. Returns: str: The comma-separated string. """return", ".join(str(item)foriteminitems)
[docs]defsanitize_for_postgres(text:str,replacement:str="")->str:r"""Sanitize text by removing NUL bytes that are incompatible with PostgreSQL. PostgreSQL text fields cannot contain NUL (0x00) bytes, which can cause psycopg.DataError when inserting documents. This function removes or replaces such characters to ensure compatibility. Args: text: The text to sanitize. replacement: String to replace NUL bytes with. Defaults to empty string. Returns: str: The sanitized text with NUL bytes removed or replaced. Example: >>> sanitize_for_postgres("Hello\\x00world") 'Helloworld' >>> sanitize_for_postgres("Hello\\x00world", " ") 'Hello world' """returntext.replace("\x00",replacement)