xiaozhi-esp32-server/main/xiaozhi-server/core/utils/tts.py
lapy c5ff101e66 feat(xiaozhi-server): western provider set, English defaults, runtime, and plugins
- Defaults and config aligned with English-first product surface

- Adds/removes ASR/TTS paths; drops China-only provider implementations and bundled SenseVoice assets

- Westernizes prompts, plugin/tool copy, connection and handler behavior on upstream fixes

- Powermem max_tokens and OpenAI no-thinking guard preserved on downstream path
2026-04-25 17:05:08 +01:00

175 lines
6.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import re
import sys
import importlib
from config.logger import setup_logging
from core.utils.textUtils import check_emoji
logger = setup_logging()
punctuation_set = {
",",
",", # Comma
"。",
".", # Period
"!",
"!", # Exclamation mark
"“",
"”",
'"', # Quotation mark
":",
":", # Colon
"-",
"-", # Full-width dash
"、", # Ideographic comma
"[",
"]", # Square brackets
"【",
"】", # Full-width square brackets
"~", # Tilde
}
def create_instance(class_name, *args, **kwargs):
# Create TTS instance
if os.path.exists(os.path.join('core', 'providers', 'tts', f'{class_name}.py')):
lib_name = f'core.providers.tts.{class_name}'
if lib_name not in sys.modules:
sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
return sys.modules[lib_name].TTSProvider(*args, **kwargs)
raise ValueError(f"Unsupported TTS type: {class_name}, please check if the type configuration is set correctly")
class MarkdownCleaner:
"""
Encapsulate Markdown cleaning logic: directly use MarkdownCleaner.clean_markdown(text)
"""
# Formula characters
NORMAL_FORMULA_CHARS = re.compile(r'[a-zA-Z\\^_{}\+\-\(\)\[\]=]')
@staticmethod
def _replace_inline_dollar(m: re.Match) -> str:
"""
As long as complete "$...$" is captured:
- If internal has typical formula characters => remove both sides $
- Otherwise (pure numbers/currency etc.) => keep "$...$"
"""
content = m.group(1)
if MarkdownCleaner.NORMAL_FORMULA_CHARS.search(content):
return content
else:
return m.group(0)
@staticmethod
def _replace_table_block(match: re.Match) -> str:
"""
When a complete table block is matched, call this function.
"""
block_text = match.group('table_block')
lines = block_text.strip('\n').split('\n')
parsed_table = []
for line in lines:
line_stripped = line.strip()
if re.match(r'^\|\s*[-:]+\s*(\|\s*[-:]+\s*)+\|?$', line_stripped):
continue
columns = [col.strip() for col in line_stripped.split('|') if col.strip() != '']
if columns:
parsed_table.append(columns)
if not parsed_table:
return ""
headers = parsed_table[0]
data_rows = parsed_table[1:] if len(parsed_table) > 1 else []
lines_for_tts = []
if len(parsed_table) == 1:
# Only one row
only_line_str = ", ".join(parsed_table[0])
lines_for_tts.append(f"Single row table: {only_line_str}")
else:
lines_for_tts.append(f"Table headers are: {', '.join(headers)}")
for i, row in enumerate(data_rows, start=1):
row_str_list = []
for col_index, cell_val in enumerate(row):
if col_index < len(headers):
row_str_list.append(f"{headers[col_index]} = {cell_val}")
else:
row_str_list.append(cell_val)
lines_for_tts.append(f"Row {i}: {', '.join(row_str_list)}")
return "\n".join(lines_for_tts) + "\n"
# Pre-compile all regular expressions (sorted by execution frequency)
# Static methods replace_xxx must be defined first so they can be correctly referenced in the list.
REGEXES = [
(re.compile(r'```.*?```', re.DOTALL), ''), # Code blocks
(re.compile(r'^#+\s*', re.MULTILINE), ''), # Headers
(re.compile(r'(\*\*|__)(.*?)\1'), r'\2'), # Bold
(re.compile(r'(\*|_)(?=\S)(.*?)(?<=\S)\1'), r'\2'), # Italic
(re.compile(r'!\[.*?\]\(.*?\)'), ''), # Images
(re.compile(r'\[(.*?)\]\(.*?\)'), r'\1'), # Links
(re.compile(r'^\s*>+\s*', re.MULTILINE), ''), # Quotes
(
re.compile(r'(?P<table_block>(?:^[^\n]*\|[^\n]*\n)+)', re.MULTILINE),
_replace_table_block
),
(re.compile(r'^\s*[*+-]\s*', re.MULTILINE), '- '), # Lists
(re.compile(r'\$\$.*?\$\$', re.DOTALL), ''), # Block-level formulas
(
re.compile(r'(?<![A-Za-z0-9])\$([^\n$]+)\$(?![A-Za-z0-9])'),
_replace_inline_dollar
),
(re.compile(r'\n{2,}'), '\n'), # Extra blank lines
]
@staticmethod
def clean_markdown(text: str) -> str:
"""
Main entry method: apply all regex replacements in sequence to remove or
normalize Markdown content.
"""
# Return early when the text is already plain ASCII text plus punctuation.
if text and all((c.isascii() or c.isspace() or c in punctuation_set) for c in text):
# Preserve original spacing and return immediately.
return text
for regex, replacement in MarkdownCleaner.REGEXES:
text = regex.sub(replacement, text)
# Strip emoji before returning the final text.
text = check_emoji(text)
# Preserve spacing for plain ASCII text plus punctuation.
if text and all((c.isascii() or c.isspace() or c in punctuation_set) for c in text):
return text
return text.strip()
def convert_percentage_to_range(percentage, min_val, max_val, base_val=None):
"""
Convert a percentage in the `-100..100` range into a target numeric range.
Args:
percentage: Percentage value from -100 to 100.
min_val: Minimum of the target range.
max_val: Maximum of the target range.
base_val: Optional baseline value. Defaults to the midpoint.
Returns:
Converted numeric value.
"""
percentage, min_val, max_val = float(percentage), float(min_val), float(max_val)
base_val = float(base_val) if base_val is not None else (min_val + max_val) / 2
if percentage < 0:
# Negative percentages interpolate from base_val toward min_val.
result = base_val + (base_val - min_val) * (percentage / 100)
else:
# Positive percentages interpolate from base_val toward max_val.
result = base_val + (max_val - base_val) * (percentage / 100)
# Clamp the result to the valid range.
return max(min_val, min(max_val, result))