mirror of
https://github.com/MarkParker5/STARK.git
synced 2024-11-24 08:12:13 +02:00
New way to launch archie, telegram bot, bat for fast install used packages (except pyAudio)
This commit is contained in:
parent
5159471db4
commit
171217f808
3
.gitignore
vendored
3
.gitignore
vendored
@ -1,6 +1,7 @@
|
||||
__pycache__
|
||||
audio/*
|
||||
audio
|
||||
tts-gc-key.json
|
||||
test.py
|
||||
sandbox.py
|
||||
logs.txt
|
||||
config
|
||||
|
78
QA/QA.py
Normal file
78
QA/QA.py
Normal file
@ -0,0 +1,78 @@
|
||||
from bs4 import BeautifulSoup as BS
|
||||
from Command import Command
|
||||
import wikipedia as wiki
|
||||
import requests
|
||||
import random
|
||||
import json
|
||||
import re
|
||||
|
||||
class QA(Command):
|
||||
def confirm(this, string): return True
|
||||
|
||||
def googleDictionary(this, word):
|
||||
responce = requests.get(f'https://api.dictionaryapi.dev/api/v2/entries/ru/{word}')
|
||||
if responce.status_code == 200:
|
||||
responce = json.loads(responce.content)
|
||||
text = ''
|
||||
r = responce[0]
|
||||
definition = r['meanings'][0]['definitions'][0]
|
||||
short = r['word'].lower().capitalize() + ' (' + ( r['meanings'][0]['partOfSpeech'].capitalize() if r['meanings'][0]['partOfSpeech'] != 'undefined' else 'Разговорный' ) + ') — ' + definition['definition'].lower().capitalize() + ( '. Синонимы: ' + ', '.join(definition['synonyms']) if definition['synonyms'] else '')
|
||||
short = short.replace(word[0].lower()+'.', word.lower())
|
||||
short = short.replace(word[0].upper()+'.', word.capitalize())
|
||||
short = short.replace('-н.', '-нибудь')
|
||||
short = short.replace('потр.', 'потребляется')
|
||||
short = short.replace('знач.', 'значении')
|
||||
|
||||
for r in responce:
|
||||
text += '\n' + r['word'].lower().capitalize() + ' (' + (r['meanings'][0]['partOfSpeech'].capitalize() if r['meanings'][0]['partOfSpeech'] != 'undefined' else 'Разговорный') + ')\n'
|
||||
for definition in r['meanings'][0]['definitions']:
|
||||
text += '\t— ' + definition['definition'].lower().capitalize()
|
||||
if example := definition.get('example'):
|
||||
text += '\n\tНапример: ' + example
|
||||
if synonyms := definition['synonyms']:
|
||||
text += '\n\tСинонимы: ' + ', '.join(synonyms) + '.'
|
||||
if antonyms := definition['antonyms']:
|
||||
text += '\n\tАнтонимы: ' + ', '.join(antonyms) + '.'
|
||||
text += '\n\n'
|
||||
|
||||
return {
|
||||
'text': text,
|
||||
'short': short,
|
||||
}
|
||||
return {}
|
||||
|
||||
def wikipedia(this, word):
|
||||
wiki.set_lang("ru")
|
||||
article = wiki.summary(word, sentences=5)
|
||||
try: return article[:article.find('\n\n')][:600]
|
||||
except: return ''
|
||||
|
||||
def googleSearch(this, word):
|
||||
responce = requests.get(f'https://www.google.ru/search?&q={word}&lr=lang_ru&lang=ru')
|
||||
page = BS(responce.content, 'html.parser')
|
||||
info = page.select('div.BNeawe>div>div.BNeawe')
|
||||
return info[0].get_text() if info else ''
|
||||
|
||||
def start(this, params):
|
||||
query = params['string']
|
||||
if 'вики' in query:
|
||||
query = query.replace('википедия', '').replace('вики', '').strip()
|
||||
try: search = this.googleSearch(query)
|
||||
except: search = ''
|
||||
try: wiki = this.wikipedia(query) if not 'Википедия' in search else ''
|
||||
except: wiki = ''
|
||||
try: gdict = this.googleDictionary(query)
|
||||
except: gdict = []
|
||||
voice = search or (gdict['short'] if gdict else '') or wiki
|
||||
text = (f'Google Search:\n\t{search}' if search else '') + (f'\n\nWikipedia:\n\t{wiki}' if wiki else '') + ('\n\nDictionary:'+gdict['text'] if gdict else '')
|
||||
else:
|
||||
try: search = this.googleSearch(query)
|
||||
except: search = ''
|
||||
voice = text = search or random.choice(['Не совсем понимаю, о чём вы.', 'Вот эта последняя фраза мне не ясна.', 'А вот это не совсем понятно.', 'Можете сказать то же самое другими словами?', 'Вот сейчас я совсем вас не понимаю.', 'Попробуйте выразить свою мысль по-другому',])
|
||||
return {
|
||||
'type': 'simple',
|
||||
'text': text,
|
||||
'voice': voice,
|
||||
}
|
||||
|
||||
Command.QA = QA('QA', {}, [])
|
1
QA/__init__.py
Normal file
1
QA/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
from .QA import *
|
@ -51,7 +51,6 @@ def method(params):
|
||||
|
||||
hours = now.hour%12 or 12
|
||||
minutes = now.minute
|
||||
print(now, hours, minutes)
|
||||
get_str = ['десять', 'один', 'два', 'три', 'четыре', 'пять', 'шесть', 'семь', 'восемь', 'девять']
|
||||
|
||||
if hours%20 == 1:
|
||||
|
@ -25,6 +25,14 @@ class SpeechToText:
|
||||
responce = {'text': None, 'status': 'error'}
|
||||
return responce
|
||||
|
||||
def recognize(this, speech):
|
||||
with sr.AudioFile(speech.getPath()) as source:
|
||||
audio = r.record(source)
|
||||
try:
|
||||
return r.recognize_google(audio)
|
||||
except:
|
||||
return ''
|
||||
|
||||
def listen_noise(this):
|
||||
with this.m as source:
|
||||
this.r.adjust_for_ambient_noise(source)
|
||||
|
@ -25,6 +25,12 @@ class Speech:
|
||||
sleep(0.1)
|
||||
if(not this._standart): os.remove(this._path)
|
||||
|
||||
def getBytes(this):
|
||||
return open(this._path, 'rb')
|
||||
|
||||
def getPath(this):
|
||||
return this._path
|
||||
|
||||
@staticmethod
|
||||
def append(obj):
|
||||
Speech._list.append(obj)
|
||||
|
7
config.example.py
Normal file
7
config.example.py
Normal file
@ -0,0 +1,7 @@
|
||||
telebot = '12345678:token'
|
||||
goole_tts_json_key = 'google-cloud-text-to-speech-private-key.json'
|
||||
|
||||
language_code = 'ru-RU'
|
||||
device_index = 1
|
||||
|
||||
names = ['арчи', 'archie']
|
@ -1,4 +1,7 @@
|
||||
google_tts_json_key= "tts-gc-key.json"
|
||||
language_code = "ru-RU"
|
||||
telebot = '1324863832:AAEcBXMcCXxrH-PnscUo6c2VkrCkqxJHiPs'
|
||||
goole_tts_json_key = 'tts-gc-key.json'
|
||||
|
||||
language_code = 'ru-RU'
|
||||
device_index = 1
|
||||
|
||||
names = ['арчи', 'archie']
|
||||
|
10
install.bat
Normal file
10
install.bat
Normal file
@ -0,0 +1,10 @@
|
||||
python -m pip install --upgrade pip
|
||||
start pip install fuzzywuzzy
|
||||
start pip install bs4
|
||||
start pip install wikipedia
|
||||
start pip install speech_recognition
|
||||
start pip install pygame
|
||||
start pip install pyTelegramBotAPI
|
||||
start pip install pyAudio
|
||||
start pip install google-cloud-texttospeech
|
||||
start pip install python-Levenshtein
|
69
main.py
69
main.py
@ -1,60 +1,13 @@
|
||||
import SpeechRecognition
|
||||
import Text2Speech
|
||||
import SmallTalk
|
||||
from Command import Command
|
||||
import config
|
||||
import QA
|
||||
import os
|
||||
|
||||
listener = SpeechRecognition.SpeechToText()
|
||||
voice = Text2Speech.Engine()
|
||||
threads = []
|
||||
memory = []
|
||||
online = True
|
||||
voids = 0
|
||||
listener.listen_noise()
|
||||
modules = {
|
||||
'Voice Assistant': 'voice_assistant',
|
||||
'Telegram bot': 'telegram_bot',
|
||||
}
|
||||
|
||||
def reply(responce):
|
||||
if responce['text']: # print answer
|
||||
print('Archie: '+responce['text'])
|
||||
if responce['voice']: # say answer
|
||||
voice.generate(responce['voice']).speak()
|
||||
if responce['type'] == 'background': # add background thread to list
|
||||
threads.append(responce['thread'])
|
||||
|
||||
def check_threads():
|
||||
for thread in threads:
|
||||
if thread['finish_event'].is_set():
|
||||
responce = thread['thread'].join()
|
||||
reply(responce)
|
||||
thread['finish_event'].clear()
|
||||
del thread
|
||||
|
||||
while True: # main loop
|
||||
check_threads()
|
||||
print('\nYou: ', end='')
|
||||
speech = listener.listen()
|
||||
text = speech['text']
|
||||
if speech['status'] == 'ok':
|
||||
print(text)
|
||||
voids = 0
|
||||
if name := list(set(config.names) & set(text.split(' '))):
|
||||
online = True
|
||||
text = text.replace(name[0], '').strip()
|
||||
if online:
|
||||
if Command.isRepeat(text):
|
||||
reply(memory[0]['responce']);
|
||||
continue
|
||||
try: cmd, params = memory[0]['cmd'].checkContext(text).values(); params = {**memory[0]['params'], **params}
|
||||
except: cmd, params = Command.reg_find(text).values()
|
||||
responce = cmd.start(params)
|
||||
reply(responce)
|
||||
memory.insert(0, {
|
||||
'text': text,
|
||||
'cmd': cmd,
|
||||
'responce': responce
|
||||
})
|
||||
else:
|
||||
if speech['status'] == 'error': print('Отсутсвует подключение к интернету');
|
||||
elif online and speech['status'] == 'void': voids += 1;
|
||||
if online and voids >= 3: online = False; voids = 0
|
||||
if not online: listener.listen_noise()
|
||||
for name, module in modules.items():
|
||||
try:
|
||||
print(f'launching the {name}')
|
||||
os.system(f'start python {module}.py')
|
||||
except:
|
||||
print(f'[error]\t{name} launch failed')
|
||||
|
59
telegram_bot.py
Normal file
59
telegram_bot.py
Normal file
@ -0,0 +1,59 @@
|
||||
from Command import Command
|
||||
import SpeechRecognition
|
||||
import Text2Speech
|
||||
import SmallTalk
|
||||
import telebot
|
||||
import config
|
||||
import QA
|
||||
|
||||
threads = []
|
||||
online = True
|
||||
voids = 0
|
||||
memory = []
|
||||
voice = Text2Speech.Engine()
|
||||
listener= SpeechRecognition.SpeechToText()
|
||||
bot = telebot.TeleBot(config.telebot)
|
||||
|
||||
def reply(id, responce):
|
||||
if responce['text']:
|
||||
bot.send_message(id, responce['text'])
|
||||
if responce['voice']:
|
||||
bot.send_voice(id, voice.generate(responce['voice']).getBytes() )
|
||||
|
||||
def check_threads(threads):
|
||||
for thread in threads:
|
||||
if thread['finish_event'].is_set():
|
||||
responce = thread['thread'].join()
|
||||
reply(thread['id'], responce)
|
||||
thread['finish_event'].clear()
|
||||
del thread
|
||||
|
||||
def main(id, text):
|
||||
text = text.lower()
|
||||
if Command.isRepeat(text):
|
||||
reply(memory[0]['responce']);
|
||||
return
|
||||
try: cmd, params = memory[0]['cmd'].checkContext(text).values(); params = {**memory[0]['params'], **params}
|
||||
except: cmd, params = Command.reg_find(text).values()
|
||||
responce = cmd.start(params)
|
||||
reply(id, responce)
|
||||
if responce['type'] == 'background': # add background thread to list
|
||||
responce['thread']['id'] = id
|
||||
threads.append(responce['thread'])
|
||||
memory.insert(0, {
|
||||
'cmd': cmd,
|
||||
'params': params,
|
||||
'responce': responce,
|
||||
})
|
||||
|
||||
@bot.message_handler(content_types = ['text'])
|
||||
def execute(msg):
|
||||
main(msg.chat.id, msg.text)
|
||||
|
||||
|
||||
while True:
|
||||
#try:
|
||||
print("Start polling...")
|
||||
bot.polling(callback = check_threads, args = (threads,) )
|
||||
#except:
|
||||
print("Polling failed")
|
60
voice_assistant.py
Normal file
60
voice_assistant.py
Normal file
@ -0,0 +1,60 @@
|
||||
import SpeechRecognition
|
||||
import Text2Speech
|
||||
import SmallTalk
|
||||
from Command import Command
|
||||
import config
|
||||
import QA
|
||||
|
||||
listener = SpeechRecognition.SpeechToText()
|
||||
voice = Text2Speech.Engine()
|
||||
threads = []
|
||||
memory = []
|
||||
online = True
|
||||
voids = 0
|
||||
listener.listen_noise()
|
||||
|
||||
def reply(responce):
|
||||
if responce['text']: # print answer
|
||||
print('Archie: '+responce['text'])
|
||||
if responce['voice']: # say answer
|
||||
voice.generate(responce['voice']).speak()
|
||||
if responce['type'] == 'background': # add background thread to list
|
||||
threads.append(responce['thread'])
|
||||
|
||||
def check_threads():
|
||||
for thread in threads:
|
||||
if thread['finish_event'].is_set():
|
||||
responce = thread['thread'].join()
|
||||
reply(responce)
|
||||
thread['finish_event'].clear()
|
||||
del thread
|
||||
|
||||
while True: # main loop
|
||||
check_threads()
|
||||
print('\nYou: ', end='')
|
||||
speech = listener.listen()
|
||||
text = speech['text']
|
||||
if speech['status'] == 'ok':
|
||||
print(text)
|
||||
voids = 0
|
||||
if name := list(set(config.names) & set(text.split(' '))):
|
||||
online = True
|
||||
text = text.replace(name[0], '').strip()
|
||||
if online:
|
||||
if Command.isRepeat(text):
|
||||
reply(memory[0]['responce']);
|
||||
continue
|
||||
try: cmd, params = memory[0]['cmd'].checkContext(text).values(); params = {**memory[0]['params'], **params}
|
||||
except: cmd, params = Command.reg_find(text).values()
|
||||
responce = cmd.start(params)
|
||||
reply(responce)
|
||||
memory.insert(0, {
|
||||
'text': text,
|
||||
'cmd': cmd,
|
||||
'responce': responce
|
||||
})
|
||||
else:
|
||||
if speech['status'] == 'error': print('Отсутсвует подключение к интернету');
|
||||
elif online and speech['status'] == 'void': voids += 1;
|
||||
if online and voids >= 3: online = False; voids = 0
|
||||
if not online: listener.listen_noise()
|
Loading…
Reference in New Issue
Block a user