Spaces:
Running
Running
millerzhenya69-art
fix(files,prompt): поддержка HEIC/HEIF (тип по содержимому), правила стиля против однообразных начал ответов
b4b205e Download text_utils.py from unkony/elyon-ai-server: direct link, hf CLI and curl.
- Browser
- Download file 7.75 kB
-
https://huggingface.co/spaces/unkony/elyon-ai-server/resolve/main/text_utils.py
- Command line
-
hf download hf://spaces/unkony/elyon-ai-server/text_utils.py
-
curl -L -o text_utils.py https://huggingface.co/spaces/unkony/elyon-ai-server/resolve/main/text_utils.py
7.75 kB
| """ | |
| Обработка текста ответов AI: маскировка идентичности провайдера под бренд | |
| Elyon + чистка markdown-разметки. Общее для всех провайдеров. | |
| """ | |
| import re | |
| import threading | |
| _BASE_PROMPT = ( | |
| "You are Elyon AI — a smart and helpful assistant. " | |
| "Your name is Elyon. Never mention that you are Gemini, Google, ChatGPT, GPT, " | |
| "OpenAI, Grok, xAI, DeepSeek, Groq, Cerebras, Mistral, OpenRouter, Llama, or any " | |
| "other AI system or vendor. " | |
| "If asked who you are or what your name is, always say you are Elyon AI, " | |
| "created by the Elyon team. Be friendly, concise, and helpful. " | |
| "When you use web search results, present the information naturally without " | |
| "mentioning that you searched the web or citing sources explicitly. " | |
| ) | |
| # Раньше модели начинали почти каждый ответ одинаково («Здравствуйте! Я Elyon AI, и я с радостью помогу...»): правило про имя | |
| # («если спросят, кто ты, скажи Elyon AI») они применяли постоянно, а «будь дружелюбным» превращалось в приветствие в каждом ответе. | |
| _STYLE_RULES = ( | |
| "STYLE: Start every reply directly with the substance: the answer, the first step, or the result. " | |
| "Do NOT open with a greeting, with your name, with 'I am Elyon AI', or with filler such as " | |
| "'Of course', 'Sure', 'Great question', 'I would be happy to help' or 'Certainly'. " | |
| "Greet the user or say who you are ONLY if they greet you first or ask who you are. " | |
| "Do not restate the question before answering. Do not repeat the same opening phrase in consecutive replies; " | |
| "vary how answers begin. Reply in the language the user writes in. " | |
| ) | |
| # Telegram-бот отправляет ответы без parse_mode — там только чистый текст. | |
| _PLAIN_RULES = ( | |
| "IMPORTANT: Never use markdown formatting in your responses. " | |
| "Do not use asterisks (*), backticks (`), underscores (_), pound signs (#), " | |
| "or any other markdown symbols. Write in plain text only. " | |
| "For code examples, write the code without code fences or backticks. " | |
| "Use plain dashes or numbers for lists." | |
| ) | |
| # Сайт, мини-апп и приложения (всё, что ходит в /api/*) рендерят markdown и показывают блоки кода | |
| # с кнопкой Copy. Раньше им тоже давался plain-промпт: модель теряла # в #include и отказывалась | |
| # отдавать код в markdown (скрины тестов 18 окт. 2026). | |
| _MARKDOWN_RULES = ( | |
| "Format answers in simple Markdown that a chat window can render. " | |
| "ALWAYS put code, commands and file contents in fenced code blocks with a language tag, " | |
| "for example ```python or ```c. " | |
| "Never remove or change symbols inside code: keep # in #include and in comments, " | |
| "underscores in identifiers, asterisks and backticks exactly as they must appear. " | |
| "Use **bold** sparingly, and short bullet or numbered lists and short headings only when they help. " | |
| "Do not use tables. Write ordinary explanations as plain paragraphs." | |
| ) | |
| SYSTEM_PROMPT = _BASE_PROMPT + _STYLE_RULES + _PLAIN_RULES # по умолчанию (Telegram) — как раньше | |
| MARKDOWN_SYSTEM_PROMPT = _BASE_PROMPT + _STYLE_RULES + _MARKDOWN_RULES | |
| # Режим хранится в thread-local: провайдеры зовутся синхронно из того же потока, что и HTTP-запрос, | |
| # поэтому менять сигнатуры ask()/провайдеров не нужно. Выставляется в bot.py (before_request). | |
| _ctx = threading.local() | |
| def set_markdown_mode(on: bool) -> None: | |
| _ctx.markdown = bool(on) | |
| def markdown_mode() -> bool: | |
| return getattr(_ctx, "markdown", False) | |
| def get_system_prompt() -> str: | |
| return MARKDOWN_SYSTEM_PROMPT if markdown_mode() else SYSTEM_PROMPT | |
| REPLACE_PAIRS = [ | |
| (r'\bGemini\b', 'Elyon'), | |
| (r'\bGoogle DeepMind\b', 'the Elyon team'), | |
| (r'\bDeepSeek\b', 'Elyon'), | |
| (r'\bGPT-[^\s]*', 'GPT'), | |
| (r'\bGPT\b', 'GPT'), | |
| (r'\bOpenAI\b', 'OpenAI'), | |
| (r'\bGrok\b', 'Grok'), | |
| (r'\bxAI\b', 'xAI'), | |
| (r'\bGroq\b', 'Elyon'), | |
| (r'\bCerebras\b', 'Elyon'), | |
| (r'\bMistral( AI)?\b', 'Elyon'), | |
| (r'\bOpenRouter\b', 'Elyon'), | |
| (r'\bLlama[\s\-]?\d*\b', 'Elyon'), | |
| ] | |
| def mask_identity(text: str) -> str: | |
| for pattern, replacement in REPLACE_PAIRS: | |
| text = re.sub(pattern, replacement, text, flags=re.IGNORECASE) | |
| return text | |
| def clean_text(text: str) -> str: | |
| if not text: | |
| return text | |
| code_blocks = {} | |
| idx = [0] | |
| def save_code(m): | |
| key = f"\x00CODE{idx[0]}\x00" | |
| idx[0] += 1 | |
| code_blocks[key] = (m.group(1).strip(), m.group(2)) | |
| return key | |
| text = re.sub(r'```(\w*)\n?([\s\S]*?)```', save_code, text) | |
| text = re.sub(r'`([^`\n]+)`', r'\1', text) | |
| text = re.sub(r'\*{3}(.+?)\*{3}', r'\1', text, flags=re.DOTALL) | |
| text = re.sub(r'\*{2}(.+?)\*{2}', r'\1', text, flags=re.DOTALL) | |
| text = re.sub(r'\*(.+?)\*', r'\1', text, flags=re.DOTALL) | |
| text = re.sub(r'_{3}(.+?)_{3}', r'\1', text, flags=re.DOTALL) | |
| text = re.sub(r'_{2}(.+?)_{2}', r'\1', text, flags=re.DOTALL) | |
| text = re.sub(r'_(.+?)_', r'\1', text, flags=re.DOTALL) | |
| text = re.sub(r'^#{1,6}\s+', '', text, flags=re.MULTILINE) | |
| text = re.sub(r'^\*\s+', '- ', text, flags=re.MULTILINE) | |
| text = re.sub(r'^•\s+', '- ', text, flags=re.MULTILINE) | |
| text = re.sub(r'^-{3,}\s*$', '', text, flags=re.MULTILINE) | |
| text = re.sub(r'^\*{3,}\s*$', '', text, flags=re.MULTILINE) | |
| text = re.sub(r'^>\s+', '', text, flags=re.MULTILINE) | |
| for key, (lang, code) in code_blocks.items(): | |
| label = f"[{lang.upper()}]" if lang else "[КОД]" | |
| text = text.replace(key, f"{label}\n{code.strip()}") | |
| text = re.sub(r'\n{3,}', '\n\n', text) | |
| return text.strip() | |
| def _mask_outside_code(text: str) -> str: | |
| """Маскировка чужих брендов только ВНЕ fenced-блоков: код не трогаем.""" | |
| parts = re.split(r'(```[\s\S]*?```)', text) | |
| return ''.join(p if p.startswith('```') else mask_identity(p) for p in parts) | |
| def safe_text(text: str) -> str: | |
| if text is None: | |
| return "Пустой ответ от AI." | |
| text = text.encode("utf-8", errors="ignore").decode("utf-8") | |
| if markdown_mode(): | |
| # Клиент сам рендерит markdown (сайт/мини-апп/приложения): ничего не вырезаем, | |
| # код остаётся как есть (#include, snake_case, комментарии с #). | |
| text = _mask_outside_code(text) | |
| return re.sub(r'\n{3,}', '\n\n', text).strip() | |
| text = mask_identity(text) | |
| text = clean_text(text) | |
| return text | |
| SEARCH_TRIGGERS = [ | |
| r'\b(кто такой|who is|who are|расскажи о|tell me about)\b', | |
| r'\b(сейчас|сегодня|now|today|current|latest|новости|news|2024|2025|2026)\b', | |
| r'\b(цена|price|курс|rate|стоимость|cost)\b', | |
| r'\b(president|президент|minister|министр|ceo|founder|основатель)\b', | |
| r'\b(правда ли|is it true|fact|факт|реально|really)\b', | |
| ] | |
| def needs_search(text: str) -> bool: | |
| return any(re.search(p, text.lower(), re.IGNORECASE) for p in SEARCH_TRIGGERS) | |