Source code for alter_ego.utils
import html
import re
from typing import Any, Optional, Union, List
[docs]
def from_file(file_name: str) -> str:
"""
Read file content as a stripped string.
:param str file_name: The name of the file to read.
:return: The content of the file as a stripped string.
:rtype: str
"""
with open(file_name) as f:
return f.read().strip()
[docs]
def exclusive_response(
s: str,
tokens: List[str],
*,
case_insensitive: bool = True,
) -> Optional[str]:
"""
Validates that a string contains only one of a list of tokens.
:param str s: The string to search in.
:param List[str] tokens: List of allowable tokens.
:param bool case_insensitive: If True, the function will be case insensitive.
:return: The first matching token found, or None.
:rtype: Optional[str]
"""
which = None
s2 = s.lower() if case_insensitive else s
for needle in tokens:
needle2 = needle.lower() if case_insensitive else needle
if which is None:
if needle2 in s2:
which = needle
else:
if needle2 in s2:
raise RuntimeError(f"Response contains '{which}' and '{needle}'.")
return which
[docs]
def homogenize(s: str) -> str:
# TODO: doc
s = s.replace("\r", "\n")
s = "\n".join(r.strip() for r in s.split("\n"))
while " " in s or "\n\n\n" in s:
s = s.replace(" ", " ").replace("\n\n\n", "\n\n")
return s.strip()
[docs]
def to_html(s: str) -> str:
"""
Escapes special characters and converts newlines to HTML format.
:param str s: The string to convert.
:return: The converted string in HTML format.
:rtype: str
"""
s = html.escape(s)
s = s.replace("\n", "<br>")
return s