-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponseai.py
More file actions
60 lines (47 loc) · 2.05 KB
/
Copy pathresponseai.py
File metadata and controls
60 lines (47 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import json
import random
from pathlib import Path
from typing import List, Dict
_INTENTS_PATH = Path(__file__).with_name("intents.json")
def _load_intents() -> List[Dict]:
if _INTENTS_PATH.exists():
try:
with open(_INTENTS_PATH, "r", encoding="utf-8") as f:
data = json.load(f)
# Expecting a dict with "intents" or a list of intents
if isinstance(data, dict) and "intents" in data:
return data["intents"]
if isinstance(data, list):
return data
except Exception:
pass
# fallback sample intents
return [
{"tag": "greeting", "patterns": ["Hi", "Hello", "Hey"], "responses": ["Hello!", "Hi there!"]},
{"tag": "goodbye", "patterns": ["Bye", "See you", "Goodbye"], "responses": ["Goodbye!", "See you later!"]},
{"tag": "capital", "patterns": ["What is the capital of France?", "capital of France"], "responses": ["The capital of France is Paris."]}
]
_INTENTS = _load_intents()
def generate_response(text: str) -> str:
text_lower = text.lower()
# simple keyword / pattern matching first
for intent in _INTENTS:
for pattern in intent.get("patterns", []):
if pattern.lower() in text_lower or all(word in text_lower for word in pattern.lower().split()):
return random.choice(intent.get("responses", ["Sorry, I don't know that."]))
# fallback: match by token overlap
best = None
best_score = 0
tokens = set(text_lower.split())
for intent in _INTENTS:
score = 0
for pattern in intent.get("patterns", []):
score += len(tokens.intersection(set(pattern.lower().split())))
if score > best_score:
best_score = score
best = intent
if best and best_score > 0:
return random.choice(best.get("responses", ["Sorry, I don't know that."]))
return "Sorry, I don't know the answer to that yet."
if __name__ == "__main__":
print(generate_response("What is the capital of France?"))