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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import random
|
| 3 |
+
import re
|
| 4 |
+
from bs4 import BeautifulSoup
|
| 5 |
+
import requests
|
| 6 |
+
import wikipedia
|
| 7 |
+
greets = [
|
| 8 |
+
'Добрый день!',
|
| 9 |
+
'Здравствуй',
|
| 10 |
+
'Привет, как могу помочь?',
|
| 11 |
+
'Здравствуйте',
|
| 12 |
+
'Приветики',
|
| 13 |
+
'Привет, как дела!',
|
| 14 |
+
'Привет, Привет и ещё раз Привет!'
|
| 15 |
+
]
|
| 16 |
+
searches = [
|
| 17 |
+
'Ищу в интернете...',
|
| 18 |
+
'Идёт поиск...',
|
| 19 |
+
'Скоро отвечу...',
|
| 20 |
+
'Секунду...',
|
| 21 |
+
'Одну секунду...',
|
| 22 |
+
'Сейчас найду...',
|
| 23 |
+
'Ищу информацию...',
|
| 24 |
+
'Источники не врут, нужно изучить информацию...',
|
| 25 |
+
'Я сейчас...',
|
| 26 |
+
'Подождите минутку...'
|
| 27 |
+
]
|
| 28 |
+
defaults = [
|
| 29 |
+
'Не понял, повторите',
|
| 30 |
+
'Я не расслышал, можете повторить',
|
| 31 |
+
'Я вас не понял, скажите снова',
|
| 32 |
+
'Вы говорите тихо, скажите пожалуйста погромче.',
|
| 33 |
+
'Я вас не смог понять, можете повторить?'
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
class NeuralNet:
|
| 37 |
+
def __init__(self, input_size, hidden_size, output_size):
|
| 38 |
+
self.Wxh = np.random.randn(hidden_size, input_size) * 0.01
|
| 39 |
+
self.Whh = np.random.randn(hidden_size, hidden_size) * 0.01
|
| 40 |
+
self.Why = np.random.randn(output_size, hidden_size) * 0.01
|
| 41 |
+
self.bh = np.zeros((hidden_size, 1))
|
| 42 |
+
self.by = np.zeros((output_size, 1))
|
| 43 |
+
|
| 44 |
+
def forward(self, inputs, h_prev):
|
| 45 |
+
h = np.tanh(np.dot(self.Wxh, inputs) + np.dot(self.Whh, h_prev) + self.bh)
|
| 46 |
+
y = np.dot(self.Why, h) + self.by
|
| 47 |
+
return y, h
|
| 48 |
+
|
| 49 |
+
def train(self, X, Y, learning_rate=0.01, epochs=1000):
|
| 50 |
+
for epoch in range(epochs):
|
| 51 |
+
loss = 0
|
| 52 |
+
h_prev = np.zeros((self.Whh.shape[0], 1))
|
| 53 |
+
|
| 54 |
+
for i in range(len(X)):
|
| 55 |
+
x = np.array(X[i]).reshape(-1, 1)
|
| 56 |
+
y_true = np.array(Y[i]).reshape(-1, 1)
|
| 57 |
+
|
| 58 |
+
# Forward pass
|
| 59 |
+
y_pred, h_prev = self.forward(x, h_prev)
|
| 60 |
+
|
| 61 |
+
# Compute loss
|
| 62 |
+
loss += np.sum((y_pred - y_true) ** 2)
|
| 63 |
+
|
| 64 |
+
# Backward pass
|
| 65 |
+
dy = y_pred - y_true
|
| 66 |
+
dWhy = np.dot(dy, h_prev.T)
|
| 67 |
+
dby = dy
|
| 68 |
+
|
| 69 |
+
dh = np.dot(self.Why.T, dy)
|
| 70 |
+
dh_raw = (1 - h_prev ** 2) * dh
|
| 71 |
+
|
| 72 |
+
dWxh = np.dot(dh_raw, x.T)
|
| 73 |
+
dWhh = np.dot(dh_raw, h_prev.T)
|
| 74 |
+
dbh = dh_raw
|
| 75 |
+
|
| 76 |
+
# Update weights
|
| 77 |
+
self.Wxh -= learning_rate * dWxh
|
| 78 |
+
self.Whh -= learning_rate * dWhh
|
| 79 |
+
self.Why -= learning_rate * dWhy
|
| 80 |
+
self.bh -= learning_rate * dbh
|
| 81 |
+
self.by -= learning_rate * dby
|
| 82 |
+
|
| 83 |
+
if epoch % 100 == 0:
|
| 84 |
+
print(f'Epoch {epoch}, Loss: {loss}')
|
| 85 |
+
|
| 86 |
+
class MaestroAssistant:
|
| 87 |
+
def __init__(self):
|
| 88 |
+
self.wake_word = "эй маэстро"
|
| 89 |
+
self.vocab = {}
|
| 90 |
+
self.intents = {
|
| 91 |
+
'greet': ['привет', 'здравствуй', 'добрый день'],
|
| 92 |
+
'search': ['найди', 'поищи', 'что такое', 'кто такой'],
|
| 93 |
+
'joke': ['расскажи шутку', 'пошути', 'анекдот'],
|
| 94 |
+
'time': ['который час', 'сколько времени', 'время']
|
| 95 |
+
}
|
| 96 |
+
self.responses = {
|
| 97 |
+
'greet': greets,
|
| 98 |
+
'search': searches,
|
| 99 |
+
'joke': 'Я не умею шутить, но могу найти сайт с шутками!',
|
| 100 |
+
'default': defaults
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
self.init_vocab()
|
| 105 |
+
input_size = len(self.vocab)
|
| 106 |
+
hidden_size = 64
|
| 107 |
+
output_size = len(self.intents)
|
| 108 |
+
self.nn = NeuralNet(input_size, hidden_size, output_size)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
self.train()
|
| 112 |
+
|
| 113 |
+
def init_vocab(self):
|
| 114 |
+
|
| 115 |
+
words = set()
|
| 116 |
+
for intent in self.intents.values():
|
| 117 |
+
for phrase in intent:
|
| 118 |
+
words.update(phrase.split())
|
| 119 |
+
self.vocab = {word: i for i, word in enumerate(words)}
|
| 120 |
+
|
| 121 |
+
def text_to_vector(self, text):
|
| 122 |
+
|
| 123 |
+
vector = np.zeros(len(self.vocab))
|
| 124 |
+
for word in text.split():
|
| 125 |
+
if word in self.vocab:
|
| 126 |
+
vector[self.vocab[word]] += 1
|
| 127 |
+
return vector
|
| 128 |
+
|
| 129 |
+
def train(self):
|
| 130 |
+
|
| 131 |
+
X = []
|
| 132 |
+
y = []
|
| 133 |
+
for i, (intent, phrases) in enumerate(self.intents.items()):
|
| 134 |
+
for phrase in phrases:
|
| 135 |
+
X.append(self.text_to_vector(phrase))
|
| 136 |
+
y_vec = np.zeros(len(self.intents))
|
| 137 |
+
y_vec[i] = 1
|
| 138 |
+
y.append(y_vec)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
X = np.array(X)
|
| 142 |
+
y = np.array(y)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
self.nn.train(X, y, epochs=1000, learning_rate=0.01)
|
| 146 |
+
|
| 147 |
+
def predict_intent(self, text):
|
| 148 |
+
|
| 149 |
+
vector = self.text_to_vector(text)
|
| 150 |
+
output, _ = self.nn.forward(vector.reshape(-1, 1), np.zeros((self.nn.Whh.shape[0], 1)))
|
| 151 |
+
intent_idx = np.argmax(output)
|
| 152 |
+
return list(self.intents.keys())[intent_idx]
|
| 153 |
+
|
| 154 |
+
def handle_command(self, command):
|
| 155 |
+
|
| 156 |
+
if not command.startswith(self.wake_word):
|
| 157 |
+
return None
|
| 158 |
+
|
| 159 |
+
command = command[len(self.wake_word):].strip()
|
| 160 |
+
intent = self.predict_intent(command)
|
| 161 |
+
|
| 162 |
+
if intent == 'greet':
|
| 163 |
+
return random.choice(self.responses['greet'])
|
| 164 |
+
elif intent == 'joke':
|
| 165 |
+
return random.choice(self.responses['joke'])
|
| 166 |
+
elif intent == 'search':
|
| 167 |
+
query = re.sub(r'(найди|поищи|что такое|кто такой)', '', command).strip()
|
| 168 |
+
return self.search(query)
|
| 169 |
+
else:
|
| 170 |
+
return random.choice(self.responses['default'])
|
| 171 |
+
|
| 172 |
+
def search(self, query):
|
| 173 |
+
|
| 174 |
+
try:
|
| 175 |
+
wikipedia.set_lang('ru')
|
| 176 |
+
result = wikipedia.summary(query, sentences=2)
|
| 177 |
+
return f"Вот что я нашел в Википедии: {result}"
|
| 178 |
+
except:
|
| 179 |
+
pass
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
try:
|
| 183 |
+
url = f"https://www.google.com/search?q={query}"
|
| 184 |
+
headers = {'User-Agent': 'Mozilla/5.0'}
|
| 185 |
+
response = requests.get(url, headers=headers)
|
| 186 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
result = soup.find('div', class_='BNeawe').text
|
| 190 |
+
return f"Вот что я нашел: {result[:200]}..."
|
| 191 |
+
except Exception as e:
|
| 192 |
+
return f"Не удалось найти информацию: {str(e)}"
|