You've already forked STARK
mirror of
https://github.com/MarkParker5/STARK.git
synced 2025-07-12 22:50:22 +02:00
Create main loop (main.py), background threads, config.py
This commit is contained in:
4
.gitignore
vendored
4
.gitignore
vendored
@ -1,4 +1,6 @@
|
|||||||
__pycache__
|
__pycache__
|
||||||
audio/*
|
audio/*
|
||||||
Text2Speech/tts-gc-key.json
|
tts-gc-key.json
|
||||||
test.py
|
test.py
|
||||||
|
sandbox.py
|
||||||
|
logs.txt
|
||||||
|
38
Command.py
38
Command.py
@ -16,6 +16,20 @@
|
|||||||
|
|
||||||
from abc import ABC, abstractmethod # for abstract class and methods
|
from abc import ABC, abstractmethod # for abstract class and methods
|
||||||
from fuzzywuzzy import fuzz
|
from fuzzywuzzy import fuzz
|
||||||
|
from threading import Thread, Event
|
||||||
|
|
||||||
|
class RThread(Thread):
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self._return = None
|
||||||
|
|
||||||
|
def run(self):
|
||||||
|
if self._target is not None:
|
||||||
|
self._return = self._target(*self._args, **self._kwargs)
|
||||||
|
|
||||||
|
def join(self, *args, **kwargs):
|
||||||
|
super().join(*args, **kwargs)
|
||||||
|
return self._return
|
||||||
|
|
||||||
class Command(ABC):
|
class Command(ABC):
|
||||||
_list = [] # list of all commands
|
_list = [] # list of all commands
|
||||||
@ -69,11 +83,11 @@ class Command(ABC):
|
|||||||
|
|
||||||
# abstract
|
# abstract
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def start(this, string): # main method
|
def start(this, string): # main method
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def confirm(this): # optional method
|
def confirm(this): # optional method
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# static
|
# static
|
||||||
@ -103,9 +117,27 @@ class Command(ABC):
|
|||||||
top = max( chances.values() ) / sum( chances.values() ) * 100
|
top = max( chances.values() ) / sum( chances.values() ) * 100
|
||||||
else:
|
else:
|
||||||
return list[0]
|
return list[0]
|
||||||
if( max( chances.values() ) < 1000 or top < 80): return list[0]
|
|
||||||
print(chances)
|
print(chances)
|
||||||
print(top)
|
print(top)
|
||||||
|
#if( max( chances.values() ) < 800 or top < 80): return list[0]
|
||||||
for i, chance in chances.items():
|
for i, chance in chances.items():
|
||||||
if chance == max( chances.values() ):
|
if chance == max( chances.values() ):
|
||||||
return list[i]
|
return list[i]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def background(answer = ''):
|
||||||
|
def decorator(cmd):
|
||||||
|
def wrapper(text):
|
||||||
|
finish_event = Event()
|
||||||
|
thread = RThread(target=cmd, args=(text, finish_event))
|
||||||
|
thread.start()
|
||||||
|
return {
|
||||||
|
'type': 'background',
|
||||||
|
'text': answer,
|
||||||
|
'thread': {
|
||||||
|
'thread': thread,
|
||||||
|
'finish_event': finish_event,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return wrapper
|
||||||
|
return decorator
|
||||||
|
@ -20,15 +20,20 @@
|
|||||||
from .SmallTalk import *
|
from .SmallTalk import *
|
||||||
import datetime, time
|
import datetime, time
|
||||||
import math
|
import math
|
||||||
|
from Command import Command
|
||||||
|
import time
|
||||||
################################################################################
|
################################################################################
|
||||||
def method():
|
def method(text):
|
||||||
return 'Я не понимаю'
|
return {
|
||||||
|
'type': 'simple',
|
||||||
|
'text': 'Я не понимаю',
|
||||||
|
}
|
||||||
|
|
||||||
keywords = {}
|
keywords = {}
|
||||||
void = SmallTalk('Undefined', keywords)
|
void = SmallTalk('Undefined', keywords)
|
||||||
void.setStart(method)
|
void.setStart(method)
|
||||||
################################################################################
|
################################################################################
|
||||||
def method():
|
def method(text):
|
||||||
now = datetime.datetime.now()
|
now = datetime.datetime.now()
|
||||||
hours = now.hour%12 if now.hour else 12
|
hours = now.hour%12 if now.hour else 12
|
||||||
minutes = now.minute
|
minutes = now.minute
|
||||||
@ -92,7 +97,10 @@ def method():
|
|||||||
return ' '.join(result)
|
return ' '.join(result)
|
||||||
answer = f'Сейчас {get_str_num(hours, 0)} {str_hour}'
|
answer = f'Сейчас {get_str_num(hours, 0)} {str_hour}'
|
||||||
if(minutes): answer += f', {get_str_num(minutes, 1)} {str_minute}'
|
if(minutes): answer += f', {get_str_num(minutes, 1)} {str_minute}'
|
||||||
return answer
|
return {
|
||||||
|
'type': 'simple',
|
||||||
|
'text': answer
|
||||||
|
}
|
||||||
|
|
||||||
keywords = {
|
keywords = {
|
||||||
10: ['который час', 'сколько времени'],
|
10: ['который час', 'сколько времени'],
|
||||||
@ -102,3 +110,20 @@ keywords = {
|
|||||||
ctime = SmallTalk('Current Time', keywords)
|
ctime = SmallTalk('Current Time', keywords)
|
||||||
ctime.setStart(method)
|
ctime.setStart(method)
|
||||||
################################################################################
|
################################################################################
|
||||||
|
# Only for tests
|
||||||
|
@Command.background('Запускаю фоновый процесс')
|
||||||
|
def method(text, finish_event):
|
||||||
|
time.sleep(10)
|
||||||
|
finish_event.set()
|
||||||
|
return {
|
||||||
|
'text': 'Фоновый процесс завершен',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
keywords = {
|
||||||
|
10: ['тестирование', 'проверка', 'потоков', 'фоновых'],
|
||||||
|
5: ['процессов',]
|
||||||
|
}
|
||||||
|
test = SmallTalk('Test threads', keywords)
|
||||||
|
test.setStart(method)
|
||||||
|
################################################################################
|
||||||
|
@ -3,7 +3,7 @@ import os
|
|||||||
from pygame import mixer
|
from pygame import mixer
|
||||||
import time
|
import time
|
||||||
import mmap
|
import mmap
|
||||||
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "Text2Speech/archie-test-key.json"
|
import config
|
||||||
|
|
||||||
class Speech:
|
class Speech:
|
||||||
_list = []
|
_list = []
|
||||||
@ -35,14 +35,15 @@ class Speech:
|
|||||||
return Speech._list
|
return Speech._list
|
||||||
|
|
||||||
class Engine:
|
class Engine:
|
||||||
def __init__(this, name = 'ru-RU-Wavenet-B'):
|
def __init__(this, name = 'ru-RU-Wavenet-B', language_code = config.language_code):
|
||||||
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "Text2Speech/tts-gc-key.json"
|
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = config.goole_tts_json_key
|
||||||
this._name = name
|
|
||||||
this._client = texttospeech.TextToSpeechClient()
|
this._client = texttospeech.TextToSpeechClient()
|
||||||
this._audio_config = texttospeech.AudioConfig( audio_encoding = texttospeech.AudioEncoding.MP3 )
|
this._audio_config = texttospeech.AudioConfig( audio_encoding = texttospeech.AudioEncoding.MP3 )
|
||||||
|
this._language_code= language_code
|
||||||
|
this._name = name
|
||||||
this._voice = texttospeech.VoiceSelectionParams(
|
this._voice = texttospeech.VoiceSelectionParams(
|
||||||
language_code = 'ru-RU',
|
language_code = this._language_code,
|
||||||
name = name,
|
name = this._name,
|
||||||
ssml_gender = texttospeech.SsmlVoiceGender.FEMALE)
|
ssml_gender = texttospeech.SsmlVoiceGender.FEMALE)
|
||||||
|
|
||||||
def generate(this, text, standart = False):
|
def generate(this, text, standart = False):
|
||||||
|
2
config.py
Normal file
2
config.py
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
goole_tts_json_key = "tts-gc-key.json"
|
||||||
|
language_code = "ru-RU"
|
40
main.py
Normal file
40
main.py
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
import SpeechRecognition
|
||||||
|
import Text2Speech
|
||||||
|
import SmallTalk
|
||||||
|
from Command import Command
|
||||||
|
|
||||||
|
listener = SpeechRecognition.SpeechToText()
|
||||||
|
voice = Text2Speech.Engine()
|
||||||
|
threads = []
|
||||||
|
memory = []
|
||||||
|
listener.listen_noise()
|
||||||
|
|
||||||
|
def check_threads():
|
||||||
|
for thread in threads:
|
||||||
|
if thread['finish_event'].is_set():
|
||||||
|
responce = thread['thread'].join()
|
||||||
|
if responce['text']:
|
||||||
|
voice.generate(responce['text']).speak()
|
||||||
|
thread['finish_event'].clear()
|
||||||
|
del thread
|
||||||
|
|
||||||
|
while True: # main loop
|
||||||
|
check_threads()
|
||||||
|
print('Listening...')
|
||||||
|
speech = listener.listen()
|
||||||
|
text = speech['text']
|
||||||
|
print('You: ')
|
||||||
|
if text:
|
||||||
|
cmd = Command.find(text)
|
||||||
|
responce = cmd.start(text)
|
||||||
|
memory.insert(0, {
|
||||||
|
'text': text,
|
||||||
|
'cmd': cmd,
|
||||||
|
'responce': responce
|
||||||
|
})
|
||||||
|
if responce['type'] == 'background': # add background thread to list
|
||||||
|
threads.append(responce['thread'])
|
||||||
|
if responce['text']:
|
||||||
|
voice.generate(responce['text']).speak()
|
||||||
|
else:
|
||||||
|
print(speech['status'])
|
Reference in New Issue
Block a user