43 lines
1.2 KiB
Python
43 lines
1.2 KiB
Python
import spacy
|
|
|
|
# Helper for logging
|
|
import uuid
|
|
from helpers.logger import get_logger
|
|
|
|
# Initiate logger
|
|
logger = get_logger(__name__)
|
|
|
|
intent_handlers = []
|
|
nlp = spacy.load("en_core_web_sm")
|
|
|
|
def intent(keyword_groups):
|
|
def decorator(func):
|
|
func._intent_pattern = keyword_groups # Mark function with pattern
|
|
return func
|
|
return decorator
|
|
|
|
def match_intent(text):
|
|
doc = nlp(text.lower())
|
|
#tokens = [token.lemma_ for token in doc if not token.is_stop and not token.is_punct]
|
|
tokens = [token.lemma_ for token in doc if not token.is_punct]
|
|
print(f"Tokens: {tokens}") # DEBUG
|
|
|
|
for handler in intent_handlers:
|
|
pattern = handler["pattern"]
|
|
if all(any(kw in tokens for kw in group) for group in pattern):
|
|
print(f"Matched intent: {handler['func'].__name__}") # DEBUG
|
|
return handler["func"], doc
|
|
print("No intent matched") # DEBUG
|
|
return None, doc
|
|
|
|
|
|
def list_intents():
|
|
return [
|
|
{
|
|
"pattern": handler["pattern"],
|
|
"func_name": handler["func"].__name__,
|
|
"cog": handler["func"].__self__.__class__.__name__ if hasattr(handler["func"], "__self__") else None,
|
|
}
|
|
for handler in intent_handlers
|
|
]
|
|
|