Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,107 +3,156 @@ import os
|
|
| 3 |
import json
|
| 4 |
import re
|
| 5 |
import random
|
|
|
|
| 6 |
from difflib import get_close_matches
|
| 7 |
from huggingface_hub import InferenceClient
|
| 8 |
-
from
|
| 9 |
import gradio as gr
|
| 10 |
|
| 11 |
-
# ===
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
except:
|
| 19 |
-
pass
|
| 20 |
-
|
| 21 |
-
KEYWORDS = {
|
| 22 |
-
"привет": ["привет", "здравствуй", "хай"],
|
| 23 |
-
"как дела": ["дела", "как ты", "настроение"],
|
| 24 |
-
"имя": ["имя", "кто ты", "зовут"],
|
| 25 |
-
"пока": ["пока", "выход", "до свидания", "стоп"]
|
| 26 |
-
}
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
def get_fallback_response(user_input):
|
| 32 |
-
if not HAS_PATTERNS:
|
| 33 |
-
return None
|
| 34 |
-
clean = preprocess(user_input)
|
| 35 |
-
if not clean:
|
| 36 |
-
return None
|
| 37 |
-
if any(w in clean for w in ["пока", "выход", "стоп"]):
|
| 38 |
-
return random.choice(PATTERNS["пока"])
|
| 39 |
-
knowledge = PATTERNS.get("knowledge", {})
|
| 40 |
-
if clean in knowledge:
|
| 41 |
-
return knowledge[clean]
|
| 42 |
-
matches = get_close_matches(clean, knowledge.keys(), n=1, cutoff=0.6)
|
| 43 |
-
if matches:
|
| 44 |
-
return knowledge[matches[0]]
|
| 45 |
-
for intent, words in KEYWORDS.items():
|
| 46 |
-
for token in clean.split():
|
| 47 |
-
if get_close_matches(token, words, n=1, cutoff=0.6):
|
| 48 |
-
return random.choice(PATTERNS[intent])
|
| 49 |
-
return None
|
| 50 |
|
| 51 |
-
# ===
|
| 52 |
-
def
|
| 53 |
try:
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
def
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
return "Введите запрос."
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
messages = [{"role": "user", "content": prompt}]
|
| 82 |
response = ""
|
| 83 |
try:
|
| 84 |
for chunk in client.chat_completion(
|
| 85 |
messages,
|
| 86 |
model=MODEL_ID,
|
| 87 |
-
max_tokens=
|
| 88 |
-
stream=True,
|
| 89 |
temperature=0.6,
|
| 90 |
-
top_p=0.92
|
|
|
|
| 91 |
):
|
| 92 |
token = chunk.choices[0].delta.content or ""
|
| 93 |
response += token
|
| 94 |
-
|
| 95 |
except Exception as e:
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
# === Gradio ===
|
| 99 |
chatbot = gr.ChatInterface(
|
| 100 |
respond,
|
| 101 |
-
title="
|
| 102 |
-
description="
|
| 103 |
examples=[
|
| 104 |
["Привет!", None],
|
|
|
|
| 105 |
["перевод: How are you?", None],
|
| 106 |
-
["Что такое
|
| 107 |
],
|
| 108 |
theme="soft"
|
| 109 |
)
|
|
|
|
| 3 |
import json
|
| 4 |
import re
|
| 5 |
import random
|
| 6 |
+
import requests
|
| 7 |
from difflib import get_close_matches
|
| 8 |
from huggingface_hub import InferenceClient
|
| 9 |
+
from bs4 import BeautifulSoup
|
| 10 |
import gradio as gr
|
| 11 |
|
| 12 |
+
# === Настройки: разрешённые домены (без защиты) ===
|
| 13 |
+
ALLOWED_DOMAINS = [
|
| 14 |
+
"uncomos.github.io",
|
| 15 |
+
"runget.dev",
|
| 16 |
+
"dualgaming.centre",
|
| 17 |
+
"example-knowledge-base.com"
|
| 18 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
+
SEARCH_URLS = [
|
| 21 |
+
f"https://{domain}" for domain in ALLOWED_DOMAINS
|
| 22 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
# === patterns.json ===
|
| 25 |
+
def load_json(path, default):
|
| 26 |
try:
|
| 27 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 28 |
+
return json.load(f)
|
| 29 |
+
except:
|
| 30 |
+
return default
|
| 31 |
|
| 32 |
+
PATTERNS = load_json("patterns.json", {
|
| 33 |
+
"привет": ["Привет!"],
|
| 34 |
+
"пока": ["До свидания!"],
|
| 35 |
+
"default": ["Не знаю."],
|
| 36 |
+
"knowledge": {}
|
| 37 |
+
})
|
| 38 |
|
| 39 |
+
def save_patterns():
|
| 40 |
+
with open("patterns.json", "w", encoding="utf-8") as f:
|
| 41 |
+
json.dump(PATTERNS, f, ensure_ascii=False, indent=2)
|
|
|
|
| 42 |
|
| 43 |
+
def preprocess(text):
|
| 44 |
+
return re.sub(r'[^а-яёa-z\s]', ' ', text.lower()).strip()
|
| 45 |
|
| 46 |
+
# === Скрапинг текста с сайта ===
|
| 47 |
+
def scrape_text_from_url(url, timeout=8):
|
| 48 |
+
try:
|
| 49 |
+
headers = {"User-Agent": "Newton-MAX-bot/1.0 (+https://hf.space)"}
|
| 50 |
+
resp = requests.get(url, headers=headers, timeout=timeout)
|
| 51 |
+
if resp.status_code == 200:
|
| 52 |
+
soup = BeautifulSoup(resp.text, "html.parser")
|
| 53 |
+
for tag in soup(["script", "style", "nav", "footer", "header"]):
|
| 54 |
+
tag.decompose()
|
| 55 |
+
text = soup.get_text(separator=" ", strip=True)
|
| 56 |
+
return " ".join(text.split())[:2000] # ограничение
|
| 57 |
+
except Exception:
|
| 58 |
+
pass
|
| 59 |
+
return None
|
| 60 |
|
| 61 |
+
def search_web(query):
|
| 62 |
+
query_clean = preprocess(query)
|
| 63 |
+
for base_url in SEARCH_URLS:
|
| 64 |
+
# Пробуем основную страницу
|
| 65 |
+
text = scrape_text_from_url(base_url)
|
| 66 |
+
if text and (query_clean in preprocess(text) or len(query_clean) < 10):
|
| 67 |
+
return text
|
| 68 |
+
# Можно добавить логику поиска по /search?q=..., но это редко работает
|
| 69 |
+
return None
|
| 70 |
|
| 71 |
+
# === TinyLlama через Inference API ===
|
| 72 |
+
MODEL_ID = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
| 73 |
+
client = InferenceClient()
|
| 74 |
+
|
| 75 |
+
def generate(prompt, max_tokens=256):
|
| 76 |
messages = [{"role": "user", "content": prompt}]
|
| 77 |
response = ""
|
| 78 |
try:
|
| 79 |
for chunk in client.chat_completion(
|
| 80 |
messages,
|
| 81 |
model=MODEL_ID,
|
| 82 |
+
max_tokens=max_tokens,
|
|
|
|
| 83 |
temperature=0.6,
|
| 84 |
+
top_p=0.92,
|
| 85 |
+
stream=True
|
| 86 |
):
|
| 87 |
token = chunk.choices[0].delta.content or ""
|
| 88 |
response += token
|
| 89 |
+
return response.strip()
|
| 90 |
except Exception as e:
|
| 91 |
+
return f"⚠️ Ошибка: {str(e)[:100]}"
|
| 92 |
+
|
| 93 |
+
# === Основная логика ===
|
| 94 |
+
def respond(message, history):
|
| 95 |
+
user_input = message.strip()
|
| 96 |
+
if not user_input:
|
| 97 |
+
return "Введите запрос."
|
| 98 |
+
|
| 99 |
+
# Обучение
|
| 100 |
+
if user_input.lower().startswith("запиши в базу данных:"):
|
| 101 |
+
rest = user_input[20:].strip()
|
| 102 |
+
if "?" not in rest:
|
| 103 |
+
return "❌ Формат: `запиши в базу данных: Вопрос? Ответ.`"
|
| 104 |
+
question, answer = rest.split("?", 1)
|
| 105 |
+
question = question.strip() + "?"
|
| 106 |
+
answer = answer.strip()
|
| 107 |
+
if question and answer:
|
| 108 |
+
PATTERNS["knowledge"][question.lower()] = answer
|
| 109 |
+
save_patterns()
|
| 110 |
+
return f"✅ Записал: {question} → {answer}"
|
| 111 |
+
return "❌ Неполный формат."
|
| 112 |
+
|
| 113 |
+
# Перевод
|
| 114 |
+
if user_input.lower().startswith("перевод:"):
|
| 115 |
+
text = user_input[8:].strip()
|
| 116 |
+
if not text:
|
| 117 |
+
return "🔤 Пример: `перевод: Hello`"
|
| 118 |
+
if any(c in text for c in "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"):
|
| 119 |
+
prompt = f"Translate to English: {text}"
|
| 120 |
+
else:
|
| 121 |
+
prompt = f"Переведи на русский: {text}"
|
| 122 |
+
return generate(prompt, max_tokens=128)
|
| 123 |
+
|
| 124 |
+
# === СКРАПИНГ С САЙТОВ ===
|
| 125 |
+
context = search_web(user_input)
|
| 126 |
+
if context:
|
| 127 |
+
prompt = (
|
| 128 |
+
f"ИНФОРМАЦИЯ С САЙТА:\n{context}\n\n"
|
| 129 |
+
f"ВОПРОС: {user_input}\n"
|
| 130 |
+
f"Дай краткий ответ на русском, основываясь ТОЛЬКО на приведённой информации."
|
| 131 |
+
)
|
| 132 |
+
return generate(prompt, max_tokens=256)
|
| 133 |
+
|
| 134 |
+
# Fallback через patterns.json
|
| 135 |
+
clean = preprocess(user_input)
|
| 136 |
+
knowledge = PATTERNS.get("knowledge", {})
|
| 137 |
+
if clean in knowledge:
|
| 138 |
+
return knowledge[clean]
|
| 139 |
+
matches = get_close_matches(clean, knowledge.keys(), n=1, cutoff=0.6)
|
| 140 |
+
if matches:
|
| 141 |
+
return knowledge[matches[0]]
|
| 142 |
+
|
| 143 |
+
# Обычный режим
|
| 144 |
+
return generate(f"Ответь кратко на русском: {user_input}", max_tokens=256)
|
| 145 |
|
| 146 |
# === Gradio ===
|
| 147 |
chatbot = gr.ChatInterface(
|
| 148 |
respond,
|
| 149 |
+
title="Newton MAX {BETA1}",
|
| 150 |
+
description="Мощный ИИ Newton MAX",
|
| 151 |
examples=[
|
| 152 |
["Привет!", None],
|
| 153 |
+
["что такое Runget?", None],
|
| 154 |
["перевод: How are you?", None],
|
| 155 |
+
["запиши в базу данных: Что такое Runget? Лёгкая ОС с ИИ.", None]
|
| 156 |
],
|
| 157 |
theme="soft"
|
| 158 |
)
|