2024-04-07 08:36:13 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2024-04-06 18:25:28 +00:00
|
|
|
import re
|
2024-04-07 08:36:13 +00:00
|
|
|
from typing import Iterable, AsyncIterator
|
2024-04-06 18:25:28 +00:00
|
|
|
|
2024-04-07 08:36:13 +00:00
|
|
|
def filter_json(text: str) -> str:
|
2024-04-06 18:25:28 +00:00
|
|
|
"""
|
|
|
|
Parses JSON code block from a string.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
text (str): A string containing a JSON code block.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
dict: A dictionary parsed from the JSON code block.
|
|
|
|
"""
|
|
|
|
match = re.search(r"```(json|)\n(?P<code>[\S\s]+?)\n```", text)
|
|
|
|
if match:
|
|
|
|
return match.group("code")
|
2024-04-06 19:05:04 +00:00
|
|
|
return text
|
|
|
|
|
2024-04-07 08:36:13 +00:00
|
|
|
def find_stop(stop, content: str, chunk: str = None):
|
2024-04-06 19:05:04 +00:00
|
|
|
first = -1
|
|
|
|
word = None
|
|
|
|
if stop is not None:
|
|
|
|
for word in list(stop):
|
|
|
|
first = content.find(word)
|
|
|
|
if first != -1:
|
|
|
|
content = content[:first]
|
|
|
|
break
|
2024-04-07 08:36:13 +00:00
|
|
|
if chunk is not None and first != -1:
|
2024-04-06 19:05:04 +00:00
|
|
|
first = chunk.find(word)
|
|
|
|
if first != -1:
|
|
|
|
chunk = chunk[:first]
|
|
|
|
else:
|
|
|
|
first = 0
|
|
|
|
return first, content, chunk
|
2024-04-07 08:36:13 +00:00
|
|
|
|
|
|
|
def filter_none(**kwargs) -> dict:
|
|
|
|
return {
|
|
|
|
key: value
|
|
|
|
for key, value in kwargs.items()
|
|
|
|
if value is not None
|
|
|
|
}
|
|
|
|
|
|
|
|
async def cast_iter_async(iter: Iterable) -> AsyncIterator:
|
|
|
|
for chunk in iter:
|
|
|
|
yield chunk
|