mirror of
https://github.com/MarkParker5/STARK.git
synced 2024-11-24 08:12:13 +02:00
add context(subpatterns), repeat function
This commit is contained in:
parent
3951ede3cb
commit
92242c184d
@ -38,6 +38,7 @@ class Command(ABC):
|
||||
_patterns = {
|
||||
'word': '([A-Za-zА-ЯЁа-яё0-9])+',
|
||||
'quest' : '(кто|что|как|какой|какая|какое|где|зачем|почему|сколько|чей|куда|когда)',
|
||||
'repeat': '* ((повтор*)|(еще раз)|(еще*раз)*) *',
|
||||
}
|
||||
_regex = {
|
||||
# stars *
|
||||
@ -52,10 +53,11 @@ class Command(ABC):
|
||||
# one or more of the list, without order {a|b|c}
|
||||
'\{((?:.*\|?)*?.*?)\}': r'(?:\1)+?',
|
||||
}
|
||||
def __init__(this, name, keywords = {}, patterns = []): # initialisation of new command
|
||||
def __init__(this, name, keywords = {}, patterns = [], subPatterns = []): # initialisation of new command
|
||||
this._name = name
|
||||
this._keywords = keywords
|
||||
this._patterns = patterns
|
||||
this._subPatterns = subPatterns
|
||||
Command.append(this)
|
||||
|
||||
def __str__(this):
|
||||
@ -87,6 +89,15 @@ class Command(ABC):
|
||||
this.removeKeyword(string)
|
||||
this.addKeyword(weight, string)
|
||||
|
||||
def checkContext(this, string):
|
||||
for pattern in this.getSubPatterns():
|
||||
if match := re.search(re.compile(Command.compilePattern(pattern)), string):
|
||||
return {
|
||||
'cmd': this,
|
||||
'params': {**match.groupdict(), 'string':string},
|
||||
}
|
||||
raise Exception("Not Found")
|
||||
|
||||
# setters
|
||||
def setStart(this, function): # define start (required)
|
||||
this.start = function
|
||||
@ -104,6 +115,9 @@ class Command(ABC):
|
||||
def getPatterns(this):
|
||||
return this._patterns
|
||||
|
||||
def getSubPatterns(this):
|
||||
return this._subPatterns
|
||||
|
||||
# abstract
|
||||
@abstractmethod
|
||||
def start(this, params): # main method
|
||||
@ -135,6 +149,13 @@ class Command(ABC):
|
||||
for obj in Command.getList():
|
||||
if obj.getName() == name: return obj
|
||||
|
||||
@staticmethod
|
||||
def isRepeat(string):
|
||||
print(Command.getPatternsDict()['repeat'])
|
||||
print(Command.compilePattern(Command.getPatternsDict()['repeat']))
|
||||
if re.search(re.compile(Command.compilePattern(Command.getPatternsDict()['repeat'])), string): return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def ratio(string, word):
|
||||
return ( fuzz.WRatio(string, word) + fuzz.ratio(string, word) ) / 2
|
||||
@ -193,7 +214,7 @@ class Command(ABC):
|
||||
if match := re.search(re.compile(Command.compilePattern(pattern)), string):
|
||||
return {
|
||||
'cmd': obj,
|
||||
'params': match.groupdict(),
|
||||
'params': {**match.groupdict(), 'string':string,},
|
||||
}
|
||||
# return QA-system if command not found
|
||||
return {
|
||||
|
@ -11,7 +11,9 @@
|
||||
# (int)weight1 : ['word3', 'word4'],
|
||||
# (int)weight2 : ['word5', 'word6', 'word7', 'word8', 'word9'],
|
||||
# }
|
||||
# 3. new_command = SmallTalk(Name, kw)
|
||||
# patterns = ['* который * час *', '* скольк* * (врем|час)* *']
|
||||
# subpatterns = [...] #like patterns
|
||||
# 3. new_command = SmallTalk(Name, kw, patterns, subpatterns)
|
||||
# 4. new_command.setStart(method)
|
||||
# 5. new_command.setConfirm(confirm_method) # optional, not required
|
||||
|
||||
@ -112,8 +114,9 @@ keywords = {
|
||||
5: ['текущее', 'сейчас', 'время'],
|
||||
1: ['сколько']
|
||||
}
|
||||
patterns = ['* который * час *', '* скольк* * (врем|час)* *']
|
||||
ctime = SmallTalk('Current Time', keywords, patterns)
|
||||
patterns = ['* который * час *', '* скольк* * (врем|час)* *']
|
||||
subpatterns = ['а сейчас']
|
||||
ctime = SmallTalk('Current Time', keywords, patterns, subpatterns)
|
||||
ctime.setStart(method)
|
||||
################################################################################
|
||||
# Only for tests
|
||||
|
34
main.py
34
main.py
@ -3,6 +3,7 @@ import Text2Speech
|
||||
import SmallTalk
|
||||
from Command import Command
|
||||
import config
|
||||
import QA
|
||||
|
||||
listener = SpeechRecognition.SpeechToText()
|
||||
voice = Text2Speech.Engine()
|
||||
@ -12,14 +13,17 @@ online = False
|
||||
voids = 0
|
||||
listener.listen_noise()
|
||||
|
||||
def reply(responce):
|
||||
if responce['text']:
|
||||
print('Archie: '+responce['text'])
|
||||
if responce['voice']:
|
||||
voice.generate(responce['voice']).speak()
|
||||
|
||||
def check_threads():
|
||||
for thread in threads:
|
||||
if thread['finish_event'].is_set():
|
||||
responce = thread['thread'].join()
|
||||
if responce['text']:
|
||||
print(' — '+responce['text'])
|
||||
if responce['voice']:
|
||||
voice.generate(responce['voice']).speak()
|
||||
reply(responce)
|
||||
thread['finish_event'].clear()
|
||||
del thread
|
||||
|
||||
@ -30,21 +34,25 @@ while True: # main loop
|
||||
text = speech['text']
|
||||
if speech['status'] == 'ok':
|
||||
print(text)
|
||||
if online := set(config.names) & set(text.split(' ')):
|
||||
voids = 0
|
||||
cmd, params = Command.reg_find(text).values()
|
||||
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)
|
||||
if responce['type'] == 'background': # add background thread to list
|
||||
threads.append(responce['thread'])
|
||||
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']:
|
||||
print('Archie: '+responce['text'])
|
||||
if responce['voice']:
|
||||
voice.generate(responce['voice']).speak()
|
||||
else:
|
||||
if speech['status'] == 'error': print('Отсутсвует подключение к интернету');
|
||||
elif online and speech['status'] == 'void': voids += 1;
|
||||
|
Loading…
Reference in New Issue
Block a user