Spaces:
Build error
Build error
| # app.py — работает в Gradio 2.0 и выше | |
| import gradio as gr | |
| import json | |
| import random | |
| import re | |
| from difflib import get_close_matches | |
| import os | |
| # === Загрузка базы знаний === | |
| PATTERNS = {} | |
| try: | |
| with open("patterns.json", "r", encoding="utf-8") as f: | |
| PATTERNS = json.load(f) | |
| except Exception as e: | |
| PATTERNS = {"default": [f"⚠️ Ошибка загрузки: {e}"]} | |
| # === Логика обработки === | |
| KEYWORDS = { | |
| "привет": ["привет", "здравствуй", "хай", "прив"], | |
| "как дела": ["дела", "как ты", "настроение"], | |
| "имя": ["имя", "кто ты", "зовут"], | |
| "школа": ["школа", "урок", "задача", "математика"], | |
| "пока": ["пока", "выход", "до свидания"], | |
| "knowledge": ["что такое", "как приготовить", "расскажи про"] | |
| } | |
| def preprocess(text): | |
| return re.sub(r'[^а-яё\s]', ' ', text.lower()).strip() | |
| def find_response(user_input): | |
| clean = preprocess(user_input) | |
| if not clean: | |
| return "Пожалуйста, напиши что-нибудь!" | |
| if any(w in clean for w in ["пока", "выход", "стоп"]): | |
| return "До свидания! Возвращайся скорее! 😊" | |
| knowledge = PATTERNS.get("knowledge", {}) | |
| if clean in knowledge: | |
| return knowledge[clean] | |
| matches = get_close_matches(clean, knowledge.keys(), n=1, cutoff=0.6) | |
| if matches: | |
| return knowledge[matches[0]] | |
| all_keywords = [] | |
| keyword_to_intent = {} | |
| for intent, words in KEYWORDS.items(): | |
| if intent == "knowledge": continue | |
| for word in words: | |
| all_keywords.append(word) | |
| keyword_to_intent[word] = intent | |
| for token in clean.split(): | |
| matches = get_close_matches(token, all_keywords, n=1, cutoff=0.6) | |
| if matches: | |
| return random.choice(PATTERNS[keyword_to_intent[matches[0]]]) | |
| return random.choice(PATTERNS["default"]) | |
| io = gr.Interface( | |
| fn=find_response, | |
| inputs=gr.inputs.Textbox( | |
| placeholder="Например: «что такое любовь?» или «превет!»", | |
| label="Твой запрос" | |
| ), | |
| outputs=gr.outputs.Textbox(label="Ответ Newton Micro"), | |
| title="🧠 Newton Micro — сверхлёгкий ИИ", | |
| description="Мини-ИИ на чистом Python. Поддерживает опечатки, рецепты, определения.", | |
| examples=[ | |
| ["Превет!"], | |
| ["Что такое дружба?"], | |
| ["Как приготовить яичницу?"], | |
| ["выхад"] | |
| ], | |
| allow_flagging="never" | |
| ) | |
| # Запуск | |
| if __name__ == "__main__": | |
| io.launch() |