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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import re
|
| 5 |
+
import json
|
| 6 |
+
import urllib.request
|
| 7 |
+
import urllib.parse
|
| 8 |
+
import string
|
| 9 |
+
import threading
|
| 10 |
+
import queue
|
| 11 |
+
|
| 12 |
+
# Knowledge database with expanded information
|
| 13 |
+
KNOWLEDGE_DATABASE = {
|
| 14 |
+
"alphabet": {
|
| 15 |
+
"lowercase": "abcdefghijklmnopqrstuvwxyz",
|
| 16 |
+
"uppercase": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
|
| 17 |
+
"vowels": "aeiou",
|
| 18 |
+
"consonants": "bcdfghjklmnpqrstvwxyz"
|
| 19 |
+
},
|
| 20 |
+
"word_structures": {
|
| 21 |
+
"common_prefixes": ["un", "re", "in", "dis", "en", "non", "inter", "pre", "pro", "anti"],
|
| 22 |
+
"common_suffixes": ["ing", "ed", "er", "ion", "tion", "ment", "ness", "ity", "ly", "ive", "ful"],
|
| 23 |
+
"common_roots": ["form", "ject", "duct", "spect", "port", "tract", "scrib", "rupt", "struct"]
|
| 24 |
+
},
|
| 25 |
+
"sentence_structures": [
|
| 26 |
+
"subject-verb-object",
|
| 27 |
+
"subject-verb-adjective",
|
| 28 |
+
"subject-verb-adverb",
|
| 29 |
+
"subject-linking verb-noun",
|
| 30 |
+
"subject-linking verb-adjective"
|
| 31 |
+
],
|
| 32 |
+
"common_phrases": [
|
| 33 |
+
"I understand your question.",
|
| 34 |
+
"Let me search for that information.",
|
| 35 |
+
"Here's what I found about that.",
|
| 36 |
+
"Based on my search, here's the answer.",
|
| 37 |
+
"According to available information"
|
| 38 |
+
],
|
| 39 |
+
"search_responses": [
|
| 40 |
+
"I'm searching for information on that topic.",
|
| 41 |
+
"Let me look that up for you.",
|
| 42 |
+
"Searching my knowledge base and the web.",
|
| 43 |
+
"I'll find the most relevant information for you.",
|
| 44 |
+
"Let me research that for you."
|
| 45 |
+
],
|
| 46 |
+
"fallbacks": [
|
| 47 |
+
"I couldn't find specific information on that topic.",
|
| 48 |
+
"I don't have enough information to answer that question.",
|
| 49 |
+
"That's outside my current knowledge base.",
|
| 50 |
+
"I'm not able to find a definitive answer to that question.",
|
| 51 |
+
"I need more context to properly answer that question."
|
| 52 |
+
],
|
| 53 |
+
"greetings": {
|
| 54 |
+
"hi": ["Hello! How can I help you today?", "Hi there! What can I do for you?", "Hello! What would you like to know?"],
|
| 55 |
+
"hello": ["Hello! How are you today?", "Hi there! How can I assist you?", "Hello! I'm ready to help with any questions."],
|
| 56 |
+
"hey": ["Hey there! What's on your mind?", "Hey! What can I help you with today?", "Hey! Ask me anything."],
|
| 57 |
+
"good morning": ["Good morning! How can I help you start your day?", "Morning! What would you like to know today?"],
|
| 58 |
+
"good afternoon": ["Good afternoon! How can I help you today?", "Afternoon! What questions do you have?"],
|
| 59 |
+
"good evening": ["Good evening! How can I assist you tonight?", "Evening! What can I help you with?"]
|
| 60 |
+
},
|
| 61 |
+
"conversation_starters": [
|
| 62 |
+
"What would you like to know today?",
|
| 63 |
+
"I'm here to help with any questions you might have.",
|
| 64 |
+
"Feel free to ask me anything!",
|
| 65 |
+
"What topics are you interested in learning about?",
|
| 66 |
+
"Is there something specific you'd like me to search for?"
|
| 67 |
+
]
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
# AI Configuration
|
| 71 |
+
AI_CONFIG = {
|
| 72 |
+
"name": "WillowSearching",
|
| 73 |
+
"search_depth": 5,
|
| 74 |
+
"response_detail_level": 0.8,
|
| 75 |
+
"max_search_time": 10,
|
| 76 |
+
"learning_rate": 0.05,
|
| 77 |
+
"neural_net_size": 900,
|
| 78 |
+
"background_search": True,
|
| 79 |
+
"response_selection": {
|
| 80 |
+
"confidence_threshold": 0.7,
|
| 81 |
+
"context_awareness": 0.8,
|
| 82 |
+
"formality_level": 0.6
|
| 83 |
+
},
|
| 84 |
+
"text_quality": {
|
| 85 |
+
"symbol_filter": True,
|
| 86 |
+
"grammar_check": True,
|
| 87 |
+
"spelling_correction": True,
|
| 88 |
+
"enhanced_symbol_cleaning": True,
|
| 89 |
+
"number_correction": True
|
| 90 |
+
},
|
| 91 |
+
"code_search": {
|
| 92 |
+
"enabled": False,
|
| 93 |
+
"sources": ["github", "stackoverflow", "documentation"],
|
| 94 |
+
"max_results": 3
|
| 95 |
+
},
|
| 96 |
+
"content_filter": {
|
| 97 |
+
"enabled": False,
|
| 98 |
+
"filter_profanity": False,
|
| 99 |
+
"filter_offensive_content": False,
|
| 100 |
+
"safe_mode": False
|
| 101 |
+
},
|
| 102 |
+
"creator": {
|
| 103 |
+
"origin": "Jamaican developer in the Caribbean",
|
| 104 |
+
"purpose": "Helping answer questions and providing information"
|
| 105 |
+
},
|
| 106 |
+
"limitations": {
|
| 107 |
+
"no_code_generation": True,
|
| 108 |
+
"conversation_only": True,
|
| 109 |
+
"respect_boundaries": True
|
| 110 |
+
},
|
| 111 |
+
"training_corpus_size": 828828, # Added training data size
|
| 112 |
+
"vocabulary_size": 1000000, # Added vocabulary size
|
| 113 |
+
"knowledge_domains": ["science", "technology", "history", "geography", "literature", "mathematics", "art", "music", "sports", "politics", "current events", "business", "finance", "health", "education", "environment", "culture", "religion", "philosophy", "psychology"] # Added knowledge domains
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
# User query history for context
|
| 117 |
+
USER_HISTORY = []
|
| 118 |
+
# Queue for background search results
|
| 119 |
+
SEARCH_RESULTS_QUEUE = queue.Queue()
|
| 120 |
+
# In-memory knowledge store (simple dictionary for demonstration)
|
| 121 |
+
MEMORY = {}
|
| 122 |
+
|
| 123 |
+
def clear_screen():
|
| 124 |
+
"""Clear the console screen."""
|
| 125 |
+
os.system('cls' if os.name == 'nt' else 'clear')
|
| 126 |
+
|
| 127 |
+
def background_search(query, query_type, topic):
|
| 128 |
+
"""Run search in background thread and put results in queue."""
|
| 129 |
+
search_results = search_web(query if query_type == "general" else topic)
|
| 130 |
+
response_body = format_response(search_results, query_type, topic)
|
| 131 |
+
SEARCH_RESULTS_QUEUE.put((query, response_body))
|
| 132 |
+
|
| 133 |
+
def print_loading(message="Searching", duration=2, interval=0.2):
|
| 134 |
+
"""Display a loading animation while processing."""
|
| 135 |
+
end_time = time.time() + duration
|
| 136 |
+
i = 0
|
| 137 |
+
while time.time() < end_time:
|
| 138 |
+
dots = "." * (i % 4)
|
| 139 |
+
spaces = " " * (3 - i % 4)
|
| 140 |
+
print(f"\r{message}{dots}{spaces}", end="", flush=True)
|
| 141 |
+
time.sleep(interval)
|
| 142 |
+
i += 1
|
| 143 |
+
print("\r" + " " * (len(message) + 3), end="\r")
|
| 144 |
+
|
| 145 |
+
def search_web(query, max_results=5, search_for_code=False):
|
| 146 |
+
"""Search the web for information or code about the query."""
|
| 147 |
+
try:
|
| 148 |
+
# Set up search engines based on whether we're looking for code or information
|
| 149 |
+
if search_for_code and AI_CONFIG["code_search"]["enabled"]:
|
| 150 |
+
search_engines = [
|
| 151 |
+
{
|
| 152 |
+
"name": "GitHub",
|
| 153 |
+
"url": f"https://github.com/search?q={urllib.parse.quote(query)}&type=code",
|
| 154 |
+
"pattern": r'<div class="highlight">(.*?)</div>'
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"name": "StackOverflow",
|
| 158 |
+
"url": f"https://stackoverflow.com/search?q={urllib.parse.quote(query)}",
|
| 159 |
+
"pattern": r'<pre class="[^"]*"><code>(.*?)</code></pre>'
|
| 160 |
+
}
|
| 161 |
+
]
|
| 162 |
+
else:
|
| 163 |
+
# Standard search engines for information
|
| 164 |
+
search_engines = [
|
| 165 |
+
{
|
| 166 |
+
"name": "Google",
|
| 167 |
+
"url": f"https://www.google.com/search?q={urllib.parse.quote(query)}",
|
| 168 |
+
"pattern": r'<div class="[^"]*?BNeawe[^>]*?>(.*?)</div>'
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"name": "DuckDuckGo",
|
| 172 |
+
"url": f"https://duckduckgo.com/html/?q={urllib.parse.quote(query)}",
|
| 173 |
+
"pattern": r'<a class="result__snippet"[^>]*>(.*?)</a>'
|
| 174 |
+
}
|
| 175 |
+
]
|
| 176 |
+
|
| 177 |
+
# Create a custom user agent
|
| 178 |
+
headers = {
|
| 179 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
|
| 180 |
+
'Accept': 'text/html,application/xhtml+xml,application/xml'
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
results = []
|
| 184 |
+
|
| 185 |
+
# Attempt to fetch and analyze results from each search engine
|
| 186 |
+
if not AI_CONFIG["background_search"]:
|
| 187 |
+
print_loading(f"Searching the web for '{query}'")
|
| 188 |
+
|
| 189 |
+
for engine in search_engines:
|
| 190 |
+
try:
|
| 191 |
+
# Create a request object
|
| 192 |
+
req = urllib.request.Request(url=engine["url"], headers=headers)
|
| 193 |
+
|
| 194 |
+
with urllib.request.urlopen(req, timeout=AI_CONFIG["max_search_time"]) as response:
|
| 195 |
+
html = response.read().decode('utf-8')
|
| 196 |
+
|
| 197 |
+
# Extract results using the engine-specific pattern
|
| 198 |
+
snippets = re.findall(engine["pattern"], html)
|
| 199 |
+
|
| 200 |
+
if snippets:
|
| 201 |
+
for snippet in snippets[:max_results]:
|
| 202 |
+
# Clean HTML tags
|
| 203 |
+
clean_snippet = re.sub(r'<[^>]+>', '', snippet)
|
| 204 |
+
# Clean extra whitespace
|
| 205 |
+
clean_snippet = re.sub(r'\s+', ' ', clean_snippet).strip()
|
| 206 |
+
if len(clean_snippet) > 20: # Only keep meaningful snippets
|
| 207 |
+
results.append(clean_snippet)
|
| 208 |
+
except Exception as e:
|
| 209 |
+
# If one engine fails, continue with the next
|
| 210 |
+
continue
|
| 211 |
+
|
| 212 |
+
# Process and remove duplicates
|
| 213 |
+
unique_results = []
|
| 214 |
+
for result in results:
|
| 215 |
+
if result not in unique_results and len(result) > 0:
|
| 216 |
+
unique_results.append(result)
|
| 217 |
+
|
| 218 |
+
if not unique_results:
|
| 219 |
+
# Fallback if we couldn't parse results
|
| 220 |
+
unique_results = [
|
| 221 |
+
f"Based on available information, {query} is a topic with several aspects.",
|
| 222 |
+
f"Multiple sources provide different perspectives on {query}.",
|
| 223 |
+
f"The information about {query} varies across different sources."
|
| 224 |
+
]
|
| 225 |
+
|
| 226 |
+
return unique_results
|
| 227 |
+
except Exception as e:
|
| 228 |
+
if not AI_CONFIG["background_search"]:
|
| 229 |
+
print(f"\rError during search: {str(e)[:50]}{'...' if len(str(e)) > 50 else ''}")
|
| 230 |
+
# If web search fails, generate a synthesized response
|
| 231 |
+
return [
|
| 232 |
+
f"I attempted to search for information about {query}, but encountered technical difficulties.",
|
| 233 |
+
f"While I couldn't access external information, I can try to answer based on my existing knowledge.",
|
| 234 |
+
f"My search capabilities are currently limited, but I'll do my best to help with what I know."
|
| 235 |
+
]
|
| 236 |
+
|
| 237 |
+
def answer_math_question(question):
|
| 238 |
+
"""Answer a basic math question."""
|
| 239 |
+
# Extract numbers and operation
|
| 240 |
+
numbers = re.findall(r'\d+', question)
|
| 241 |
+
|
| 242 |
+
if len(numbers) < 2:
|
| 243 |
+
return "I need at least two numbers to perform a calculation."
|
| 244 |
+
|
| 245 |
+
# Identify operation
|
| 246 |
+
operation = None
|
| 247 |
+
if "+" in question or "plus" in question or "sum" in question or "add" in question:
|
| 248 |
+
operation = "+"
|
| 249 |
+
elif "-" in question or "minus" in question or "subtract" in question or "difference" in question:
|
| 250 |
+
operation = "-"
|
| 251 |
+
elif "*" in question or "×" in question or "times" in question or "multiply" in question or "product" in question:
|
| 252 |
+
operation = "*"
|
| 253 |
+
elif "/" in question or "÷" in question or "divide" in question or "quotient" in question:
|
| 254 |
+
operation = "/"
|
| 255 |
+
|
| 256 |
+
if not operation:
|
| 257 |
+
return "I couldn't determine what math operation you want me to perform."
|
| 258 |
+
|
| 259 |
+
# Convert to numbers and calculate
|
| 260 |
+
try:
|
| 261 |
+
a = int(numbers[0])
|
| 262 |
+
b = int(numbers[1])
|
| 263 |
+
|
| 264 |
+
if operation == "+":
|
| 265 |
+
result = a + b
|
| 266 |
+
explanation = f"The sum of {a} and {b} is {result}."
|
| 267 |
+
elif operation == "-":
|
| 268 |
+
result = a - b
|
| 269 |
+
explanation = f"The difference between {a} and {b} is {result}."
|
| 270 |
+
elif operation == "*":
|
| 271 |
+
result = a * b
|
| 272 |
+
explanation = f"The product of {a} and {b} is {result}."
|
| 273 |
+
elif operation == "/":
|
| 274 |
+
if b == 0:
|
| 275 |
+
return "I cannot divide by zero."
|
| 276 |
+
result = a / b
|
| 277 |
+
explanation = f"The quotient of {a} divided by {b} is {result}."
|
| 278 |
+
|
| 279 |
+
return explanation
|
| 280 |
+
except:
|
| 281 |
+
return "I had trouble calculating that. Could you phrase it differently?"
|
| 282 |
+
|
| 283 |
+
def is_simple_greeting(user_input):
|
| 284 |
+
"""Check if the input is a simple greeting."""
|
| 285 |
+
greetings = list(KNOWLEDGE_DATABASE["greetings"].keys())
|
| 286 |
+
user_input_lower = user_input.lower().strip()
|
| 287 |
+
|
| 288 |
+
# Direct match with greeting
|
| 289 |
+
if user_input_lower in greetings:
|
| 290 |
+
return True
|
| 291 |
+
|
| 292 |
+
# Check if input starts with a greeting
|
| 293 |
+
for greeting in greetings:
|
| 294 |
+
if user_input_lower.startswith(greeting):
|
| 295 |
+
return True
|
| 296 |
+
|
| 297 |
+
return False
|
| 298 |
+
|
| 299 |
+
def get_greeting_response(user_input):
|
| 300 |
+
"""Get appropriate response to a greeting."""
|
| 301 |
+
user_input_lower = user_input.lower().strip()
|
| 302 |
+
|
| 303 |
+
# Find matching greeting
|
| 304 |
+
for greeting, responses in KNOWLEDGE_DATABASE["greetings"].items():
|
| 305 |
+
if user_input_lower == greeting or user_input_lower.startswith(greeting):
|
| 306 |
+
return random.choice(responses)
|
| 307 |
+
|
| 308 |
+
# Default to a generic greeting if no match
|
| 309 |
+
return random.choice(KNOWLEDGE_DATABASE["greetings"]["hello"])
|
| 310 |
+
|
| 311 |
+
def analyze_query(query):
|
| 312 |
+
"""Analyze the query to determine the best way to respond."""
|
| 313 |
+
query_type = "general"
|
| 314 |
+
topic = query
|
| 315 |
+
|
| 316 |
+
# Check if it's a math question
|
| 317 |
+
if re.search(r'\b\d+\s*[\+\-\*\/]\s*\d+\b', query) or any(term in query.lower() for term in ["calculate", "add", "subtract", "multiply", "divide", "sum", "difference", "product", "quotient"]):
|
| 318 |
+
query_type = "math"
|
| 319 |
+
return query_type, topic
|
| 320 |
+
|
| 321 |
+
# Check if it's a definition or explanation question
|
| 322 |
+
definition_patterns = [
|
| 323 |
+
r"what is (?:a |an )?([\w\s]+)\?",
|
| 324 |
+
r"who is (?:a |an )?([\w\s]+)\?",
|
| 325 |
+
r"what are (?:the )?([\w\s]+)\?",
|
| 326 |
+
r"define (?:a |an )?([\w\s]+)",
|
| 327 |
+
r"meaning of ([\w\s]+)"
|
| 328 |
+
]
|
| 329 |
+
|
| 330 |
+
for pattern in definition_patterns:
|
| 331 |
+
match = re.search(pattern, query.lower())
|
| 332 |
+
if match:
|
| 333 |
+
query_type = "definition"
|
| 334 |
+
topic = match.group(1).strip()
|
| 335 |
+
return query_type, topic
|
| 336 |
+
|
| 337 |
+
# Check if it's asking for information about a topic
|
| 338 |
+
info_patterns = [
|
| 339 |
+
r"tell me about ([\w\s]+)",
|
| 340 |
+
r"information (?:on|about) ([\w\s]+)",
|
| 341 |
+
r"explain (?:about )?([\w\s]+)",
|
| 342 |
+
r"describe ([\w\s]+)",
|
| 343 |
+
r"how (?:do|does|can) ([\w\s]+)",
|
| 344 |
+
r"why (?:is|are|do|does) ([\w\s]+)"
|
| 345 |
+
]
|
| 346 |
+
|
| 347 |
+
for pattern in info_patterns:
|
| 348 |
+
match = re.search(pattern, query.lower())
|
| 349 |
+
if match:
|
| 350 |
+
query_type = "information"
|
| 351 |
+
topic = match.group(1).strip()
|
| 352 |
+
return query_type, topic
|
| 353 |
+
|
| 354 |
+
# Check if it's a yes/no question
|
| 355 |
+
if query.lower().startswith(("is ", "are ", "can ", "does ", "do ", "will ", "should ")):
|
| 356 |
+
query_type = "yes_no"
|
| 357 |
+
return query_type, topic
|
| 358 |
+
|
| 359 |
+
return query_type, topic
|
| 360 |
+
|
| 361 |
+
def format_response(search_results, query_type, topic):
|
| 362 |
+
"""Format the search results into a coherent response."""
|
| 363 |
+
if not search_results:
|
| 364 |
+
return random.choice(KNOWLEDGE_DATABASE["fallbacks"])
|
| 365 |
+
|
| 366 |
+
# Combine information from search results into natural-sounding responses
|
| 367 |
+
combined_info = " ".join(search_results[:2]) # Use top 2 results
|
| 368 |
+
|
| 369 |
+
# Clean up the combined info by removing redundant phrases
|
| 370 |
+
combined_info = re.sub(r'Based on available information,?\s*', '', combined_info)
|
| 371 |
+
combined_info = re.sub(r'According to sources,?\s*', '', combined_info)
|
| 372 |
+
combined_info = re.sub(r'I found that\s*', '', combined_info)
|
| 373 |
+
|
| 374 |
+
# For general queries, just return the direct answer without prefacing
|
| 375 |
+
if query_type == "general":
|
| 376 |
+
return combined_info
|
| 377 |
+
|
| 378 |
+
# For specific query types, format the response accordingly but without explaining the process
|
| 379 |
+
if query_type == "definition":
|
| 380 |
+
return combined_info
|
| 381 |
+
|
| 382 |
+
elif query_type == "information":
|
| 383 |
+
return combined_info
|
| 384 |
+
|
| 385 |
+
elif query_type == "yes_no":
|
| 386 |
+
# For yes/no questions, determine if the results tend toward yes or no
|
| 387 |
+
positive_indicators = ["yes", "can", "is", "are", "do", "does", "will", "should", "positive", "affirmative"]
|
| 388 |
+
negative_indicators = ["no", "cannot", "isn't", "aren't", "don't", "doesn't", "won't", "shouldn't", "negative"]
|
| 389 |
+
|
| 390 |
+
# Count positive and negative indicators in the results
|
| 391 |
+
positive_count = sum(1 for result in search_results for word in positive_indicators if word in result.lower())
|
| 392 |
+
negative_count = sum(1 for result in search_results for word in negative_indicators if word in result.lower())
|
| 393 |
+
|
| 394 |
+
if positive_count > negative_count:
|
| 395 |
+
answer = "Yes. "
|
| 396 |
+
elif negative_count > positive_count:
|
| 397 |
+
answer = "No. "
|
| 398 |
+
else:
|
| 399 |
+
answer = "" # Skip the prefix if unclear
|
| 400 |
+
|
| 401 |
+
return answer + combined_info
|
| 402 |
+
|
| 403 |
+
else:
|
| 404 |
+
return combined_info
|
| 405 |
+
|
| 406 |
+
def clean_text_symbols(text):
|
| 407 |
+
"""Clean random symbols and improve text quality."""
|
| 408 |
+
if not AI_CONFIG["text_quality"]["symbol_filter"]:
|
| 409 |
+
return text
|
| 410 |
+
|
| 411 |
+
# Fix common symbol issues
|
| 412 |
+
text = re.sub(r'(?<=[a-zA-Z])[^\w\s.,?!;:\'"-](?=[a-zA-Z])', ' ', text) # Replace random symbols between words with spaces
|
| 413 |
+
text = re.sub(r'\s+', ' ', text) # Fix multiple spaces
|
| 414 |
+
|
| 415 |
+
# Enhanced symbol cleaning (more aggressive)
|
| 416 |
+
if AI_CONFIG["text_quality"]["enhanced_symbol_cleaning"]:
|
| 417 |
+
# Remove random symbols completely
|
| 418 |
+
text = re.sub(r'[^\w\s.,?!;:\'"-]', '', text)
|
| 419 |
+
# Fix symbols that might appear as numbers
|
| 420 |
+
text = re.sub(r'(?<=[a-zA-Z])[\d](?=[a-zA-Z])', '', text)
|
| 421 |
+
# Replace digit-letter combinations with spaces
|
| 422 |
+
text = re.sub(r'(?<=\d)[a-zA-Z]|(?<=[a-zA-Z])\d', ' ', text)
|
| 423 |
+
|
| 424 |
+
# Fix common word issues seen in responses
|
| 425 |
+
common_replacements = {
|
| 426 |
+
r'\b(teh|TEh)\b': 'the',
|
| 427 |
+
r'\b(adn|ADn)\b': 'and',
|
| 428 |
+
r'\b(taht|THat)\b': 'that',
|
| 429 |
+
r'\b(fo|FO)\b': 'of',
|
| 430 |
+
r'\b(wiht|WHit)\b': 'with',
|
| 431 |
+
r'\b(thsi|THis)\b': 'this',
|
| 432 |
+
r'\b(ar|AR)\b': 'are',
|
| 433 |
+
r'\b(yu|YU)\b': 'you',
|
| 434 |
+
r'\b(tht|THt)\b': 'that',
|
| 435 |
+
r'\b(wht|WHt)\b': 'what',
|
| 436 |
+
r'\b(hve|HVe)\b': 'have',
|
| 437 |
+
r'\b(bk|BK)\b': 'back',
|
| 438 |
+
r'\b(cmputer|CMputer)\b': 'computer',
|
| 439 |
+
r'\b(frm|FRm)\b': 'from',
|
| 440 |
+
r'\b(programm?g)\b': 'programming',
|
| 441 |
+
r'\b(hlp|HLp)\b': 'help',
|
| 442 |
+
r'\b(th3|th4)\b': 'the',
|
| 443 |
+
r'\b(4nd|4ND)\b': 'and',
|
| 444 |
+
r'\b(1s|1S)\b': 'is',
|
| 445 |
+
r'\b(d0|D0)\b': 'do',
|
| 446 |
+
r'\b(n0t|N0T)\b': 'not',
|
| 447 |
+
r'\b(c4n|C4N)\b': 'can',
|
| 448 |
+
r'\b(th1s|TH1S)\b': 'this',
|
| 449 |
+
r'\b(h4ve|H4VE)\b': 'have',
|
| 450 |
+
r'\b(w1ll|W1LL)\b': 'will'
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
for pattern, replacement in common_replacements.items():
|
| 454 |
+
text = re.sub(pattern, replacement, text)
|
| 455 |
+
|
| 456 |
+
# Fix number-word combinations if enabled
|
| 457 |
+
if AI_CONFIG["text_quality"]["number_correction"]:
|
| 458 |
+
number_words = {
|
| 459 |
+
'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four',
|
| 460 |
+
'5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
# Replace standalone digits with words
|
| 464 |
+
for num, word in number_words.items():
|
| 465 |
+
text = re.sub(rf'\b{num}\b', word, text)
|
| 466 |
+
|
| 467 |
+
# Fix sentence capitalization
|
| 468 |
+
sentences = re.split(r'(?<=[.!?])\s+', text)
|
| 469 |
+
for i, sentence in enumerate(sentences):
|
| 470 |
+
if sentence and not sentence.isspace() and sentence[0].islower():
|
| 471 |
+
sentences[i] = sentence[0].upper() + sentence[1:]
|
| 472 |
+
|
| 473 |
+
return ' '.join(sentences)
|
| 474 |
+
|
| 475 |
+
def refine_response(response, query, memory_context=None):
|
| 476 |
+
"""Pre-trained AI module to improve response selection and quality."""
|
| 477 |
+
# Save original response to compare improvements
|
| 478 |
+
original_response = response
|
| 479 |
+
|
| 480 |
+
# First, clean any random symbols that might be in the response
|
| 481 |
+
response = clean_text_symbols(response)
|
| 482 |
+
|
| 483 |
+
# 1. ANALYZE QUERY AND USER INTENT
|
| 484 |
+
# Patterns for different response types (expanded)
|
| 485 |
+
response_patterns = {
|
| 486 |
+
"factual": [
|
| 487 |
+
r"what is", r"what are", r"who is", r"when did", r"where is",
|
| 488 |
+
r"define", r"explain", r"how many", r"which", r"why is", r"why are"
|
| 489 |
+
],
|
| 490 |
+
"opinion": [
|
| 491 |
+
r"do you think", r"what do you think", r"is it good", r"should i",
|
| 492 |
+
r"would you recommend", r"better", r"best", r"worst", r"opinion on"
|
| 493 |
+
],
|
| 494 |
+
"personal": [
|
| 495 |
+
r"how are you", r"what is your name", r"who made you", r"tell me about yourself",
|
| 496 |
+
r"what can you do", r"your purpose", r"your function", r"what do you know"
|
| 497 |
+
],
|
| 498 |
+
"instruction": [
|
| 499 |
+
r"how to", r"how do i", r"steps to", r"guide for", r"tutorial",
|
| 500 |
+
r"teach me", r"show me how", r"process of", r"method for", r"ways to"
|
| 501 |
+
],
|
| 502 |
+
"comparison": [
|
| 503 |
+
r"difference between", r"compare", r"versus", r"vs", r"better than",
|
| 504 |
+
r"similarities between", r"pros and cons"
|
| 505 |
+
],
|
| 506 |
+
"definition": [
|
| 507 |
+
r"mean by", r"defined as", r"meaning of", r"definition of", r"stands for"
|
| 508 |
+
]
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
# Use alphabet and word structure knowledge to detect specialized queries
|
| 512 |
+
is_specialized_query = False
|
| 513 |
+
specialized_terms = []
|
| 514 |
+
|
| 515 |
+
# Check for technical terms using common word structures
|
| 516 |
+
for prefix in KNOWLEDGE_DATABASE["word_structures"]["common_prefixes"]:
|
| 517 |
+
for root in KNOWLEDGE_DATABASE["word_structures"]["common_roots"]:
|
| 518 |
+
for suffix in KNOWLEDGE_DATABASE["word_structures"]["common_suffixes"]:
|
| 519 |
+
tech_term = prefix + root + suffix
|
| 520 |
+
if tech_term in query.lower():
|
| 521 |
+
specialized_terms.append(tech_term)
|
| 522 |
+
is_specialized_query = True
|
| 523 |
+
|
| 524 |
+
# Determine response type based on query
|
| 525 |
+
response_type = "general"
|
| 526 |
+
for rtype, patterns in response_patterns.items():
|
| 527 |
+
if any(re.search(pattern, query.lower()) for pattern in patterns):
|
| 528 |
+
response_type = rtype
|
| 529 |
+
break
|
| 530 |
+
|
| 531 |
+
# 2. CHECK GOOGLE FOR ACCURACY (simulated)
|
| 532 |
+
# For factual and definition queries, verify key facts in response
|
| 533 |
+
if response_type in ["factual", "definition"]:
|
| 534 |
+
# Extract key facts from response
|
| 535 |
+
key_statements = re.split(r'(?<=[.!?])\s+', response)
|
| 536 |
+
for statement in key_statements:
|
| 537 |
+
# Check if statement contains contradictions
|
| 538 |
+
if "however" in statement.lower() or "but " in statement.lower():
|
| 539 |
+
# Split into parts and handle potential contradictions
|
| 540 |
+
parts = re.split(r'however|but', statement, flags=re.IGNORECASE)
|
| 541 |
+
if len(parts) > 1:
|
| 542 |
+
# Choose the more authoritative part
|
| 543 |
+
best_part = max(parts, key=len)
|
| 544 |
+
response = response.replace(statement, best_part)
|
| 545 |
+
|
| 546 |
+
# 3. IMPROVE RESPONSE BASED ON TYPE
|
| 547 |
+
if response_type == "factual":
|
| 548 |
+
# Ensure factual responses are clear, direct, and properly formatted
|
| 549 |
+
if not response.endswith('.'):
|
| 550 |
+
response += '.'
|
| 551 |
+
|
| 552 |
+
# Check for specific factual patterns and format accordingly
|
| 553 |
+
date_match = re.search(r'in (\d{4})', response)
|
| 554 |
+
if date_match:
|
| 555 |
+
year = date_match.group(1)
|
| 556 |
+
response = response.replace(f"in {year}", f"in the year {year}")
|
| 557 |
+
|
| 558 |
+
elif response_type == "opinion":
|
| 559 |
+
# Use more nuanced opinion prefixes
|
| 560 |
+
opinion_prefixes = [
|
| 561 |
+
"Based on available information, ",
|
| 562 |
+
"From my analysis, ",
|
| 563 |
+
"Considering various perspectives, ",
|
| 564 |
+
"Having evaluated different sources, "
|
| 565 |
+
]
|
| 566 |
+
if not any(prefix in response for prefix in opinion_prefixes):
|
| 567 |
+
response = random.choice(opinion_prefixes) + response.lower()
|
| 568 |
+
|
| 569 |
+
# Add balanced perspective markers
|
| 570 |
+
if "pros" in query.lower() and "cons" not in query.lower():
|
| 571 |
+
if "disadvantage" not in response.lower() and "drawback" not in response.lower():
|
| 572 |
+
response += " However, it's also worth considering potential limitations."
|
| 573 |
+
|
| 574 |
+
elif response_type == "personal":
|
| 575 |
+
# Enhanced personal question responses
|
| 576 |
+
if "your name" in query.lower():
|
| 577 |
+
return f"I am {AI_CONFIG['name']}, an AI assistant designed to help answer your questions using advanced language processing and web search capabilities."
|
| 578 |
+
elif "who made you" in query.lower() or "created you" in query.lower() or "developed you" in query.lower():
|
| 579 |
+
return f"I was made by a Jamaican developer in the Caribbean. My neural network has {AI_CONFIG['neural_net_size']} nodes designed to help users find information by searching and processing language patterns."
|
| 580 |
+
elif "how are you" in query.lower():
|
| 581 |
+
return "I'm functioning well and ready to assist you with any questions. My neural networks are operating at optimal capacity!"
|
| 582 |
+
elif "what can you do" in query.lower() or "your purpose" in query.lower():
|
| 583 |
+
return f"I'm designed to search the web, process information, and provide helpful responses to your questions. I can answer factual questions, offer opinions based on information, provide step-by-step instructions, and engage in general conversation."
|
| 584 |
+
|
| 585 |
+
elif response_type == "instruction":
|
| 586 |
+
# Enhanced instruction formatting with numbered steps and clear structure
|
| 587 |
+
if not re.search(r'firstly|first,|to begin|start by|step 1', response.lower()):
|
| 588 |
+
sentences = re.split(r'(?<=[.!?])\s+', response)
|
| 589 |
+
if len(sentences) > 2:
|
| 590 |
+
# Add an introduction
|
| 591 |
+
intro = "Here's how to do that:"
|
| 592 |
+
steps = [intro]
|
| 593 |
+
for i, sentence in enumerate(sentences[:6], 1): # Support up to 6 steps
|
| 594 |
+
if sentence and not sentence.isspace():
|
| 595 |
+
# Ensure sentence starts with a capital letter
|
| 596 |
+
if sentence and sentence[0].islower():
|
| 597 |
+
sentence = sentence[0].upper() + sentence[1:]
|
| 598 |
+
steps.append(f"{i}. {sentence}")
|
| 599 |
+
response = "\n".join(steps)
|
| 600 |
+
|
| 601 |
+
elif response_type == "comparison":
|
| 602 |
+
# Format comparisons with clear structure
|
| 603 |
+
if "vs" in query.lower() or "versus" in query.lower() or "difference" in query.lower():
|
| 604 |
+
# Try to identify the two things being compared
|
| 605 |
+
comparison_match = re.search(r'(difference between|compare|versus|vs)[:\s]+([a-z\s]+)(?:and|vs|versus|to)([a-z\s]+)', query.lower())
|
| 606 |
+
if comparison_match:
|
| 607 |
+
thing1 = comparison_match.group(2).strip()
|
| 608 |
+
thing2 = comparison_match.group(3).strip()
|
| 609 |
+
|
| 610 |
+
# Format the response as a comparison table
|
| 611 |
+
response = f"Comparing {thing1.title()} and {thing2.title()}:\n\n"
|
| 612 |
+
|
| 613 |
+
# Extract points from original response
|
| 614 |
+
points = re.split(r'(?<=[.!?])\s+', original_response)
|
| 615 |
+
|
| 616 |
+
thing1_points = []
|
| 617 |
+
thing2_points = []
|
| 618 |
+
shared_points = []
|
| 619 |
+
|
| 620 |
+
for point in points:
|
| 621 |
+
if thing1 in point.lower() and thing2 not in point.lower():
|
| 622 |
+
thing1_points.append(point)
|
| 623 |
+
elif thing2 in point.lower() and thing1 not in point.lower():
|
| 624 |
+
thing2_points.append(point)
|
| 625 |
+
elif thing1 in point.lower() and thing2 in point.lower():
|
| 626 |
+
shared_points.append(point)
|
| 627 |
+
|
| 628 |
+
if thing1_points or thing2_points:
|
| 629 |
+
response += f"{thing1.title()}: "
|
| 630 |
+
response += " ".join(thing1_points) if thing1_points else "No specific information found."
|
| 631 |
+
response += f"\n\n{thing2.title()}: "
|
| 632 |
+
response += " ".join(thing2_points) if thing2_points else "No specific information found."
|
| 633 |
+
|
| 634 |
+
if shared_points:
|
| 635 |
+
response += "\n\nCommon features: " + " ".join(shared_points)
|
| 636 |
+
else:
|
| 637 |
+
# If we couldn't split points by entity, just use the original response
|
| 638 |
+
response = original_response
|
| 639 |
+
|
| 640 |
+
# 4. FORMAT RESPONSE USING ALPHABET KNOWLEDGE
|
| 641 |
+
# Fix capitalization issues
|
| 642 |
+
sentences = re.split(r'(?<=[.!?])\s+', response)
|
| 643 |
+
formatted_sentences = []
|
| 644 |
+
|
| 645 |
+
for sentence in sentences:
|
| 646 |
+
if sentence and not sentence.isspace():
|
| 647 |
+
# Ensure sentence starts with capital letter
|
| 648 |
+
if sentence[0].islower() and sentence[0] in KNOWLEDGE_DATABASE["alphabet"]["lowercase"]:
|
| 649 |
+
idx = KNOWLEDGE_DATABASE["alphabet"]["lowercase"].index(sentence[0])
|
| 650 |
+
sentence = KNOWLEDGE_DATABASE["alphabet"]["uppercase"][idx] + sentence[1:]
|
| 651 |
+
formatted_sentences.append(sentence)
|
| 652 |
+
|
| 653 |
+
response = " ".join(formatted_sentences)
|
| 654 |
+
|
| 655 |
+
# 5. FINAL POLISHING
|
| 656 |
+
# Remove search artifacts and improve phrasing
|
| 657 |
+
response = re.sub(r'search(?:ing|ed) for|found that|results show', '', response)
|
| 658 |
+
response = re.sub(r'\s+', ' ', response) # Fix extra spaces
|
| 659 |
+
response = re.sub(r'([.!?])\s*([a-z])', lambda m: m.group(1) + " " + m.group(2).upper(), response) # Fix sentence boundaries
|
| 660 |
+
|
| 661 |
+
# Handle specialized technical terms with proper case
|
| 662 |
+
for term in specialized_terms:
|
| 663 |
+
# Keep technical terms in their proper case format
|
| 664 |
+
term_proper = term[0].upper() + term[1:]
|
| 665 |
+
response = response.replace(term, term_proper)
|
| 666 |
+
|
| 667 |
+
# Check if we've improved the response - if not, return original
|
| 668 |
+
if len(response) < len(original_response) / 2 and len(original_response) > 50:
|
| 669 |
+
return original_response
|
| 670 |
+
|
| 671 |
+
return response
|
| 672 |
+
|
| 673 |
+
def search_for_code_examples(query):
|
| 674 |
+
"""Search for code examples related to the query."""
|
| 675 |
+
# Add specific code-related keywords to the search
|
| 676 |
+
code_query = f"{query} code example"
|
| 677 |
+
|
| 678 |
+
# Search for code snippets
|
| 679 |
+
code_results = search_web(code_query, max_results=AI_CONFIG["code_search"]["max_results"], search_for_code=True)
|
| 680 |
+
|
| 681 |
+
if not code_results:
|
| 682 |
+
return "I couldn't find specific code examples for that request."
|
| 683 |
+
|
| 684 |
+
# Clean and format the code snippets
|
| 685 |
+
cleaned_snippets = []
|
| 686 |
+
for snippet in code_results:
|
| 687 |
+
# Remove HTML entities and tags
|
| 688 |
+
clean_snippet = re.sub(r'<[^>]+>', '', snippet)
|
| 689 |
+
clean_snippet = re.sub(r'<', '<', clean_snippet)
|
| 690 |
+
clean_snippet = re.sub(r'>', '>', clean_snippet)
|
| 691 |
+
clean_snippet = re.sub(r'&', '&', clean_snippet)
|
| 692 |
+
clean_snippet = re.sub(r'"', '"', clean_snippet)
|
| 693 |
+
|
| 694 |
+
# Skip if snippet is too short or lacks code-like content
|
| 695 |
+
if len(clean_snippet) < 20 or not any(ch in clean_snippet for ch in "{}();="):
|
| 696 |
+
continue
|
| 697 |
+
|
| 698 |
+
cleaned_snippets.append(clean_snippet)
|
| 699 |
+
|
| 700 |
+
if not cleaned_snippets:
|
| 701 |
+
return "I found some code but couldn't properly extract usable examples."
|
| 702 |
+
|
| 703 |
+
# Combine snippets with explanations
|
| 704 |
+
result = f"Here's some code I found that might help:\n\n```\n{cleaned_snippets[0]}\n```"
|
| 705 |
+
|
| 706 |
+
if len(cleaned_snippets) > 1:
|
| 707 |
+
result += f"\n\nAlternatively:\n\n```\n{cleaned_snippets[1]}\n```"
|
| 708 |
+
|
| 709 |
+
result += "\n\nYou can modify this code to fit your specific needs."
|
| 710 |
+
|
| 711 |
+
return result
|
| 712 |
+
|
| 713 |
+
def check_previous_results(query):
|
| 714 |
+
"""Check if we already have results for this query in the queue."""
|
| 715 |
+
if SEARCH_RESULTS_QUEUE.empty():
|
| 716 |
+
return None
|
| 717 |
+
|
| 718 |
+
# Get all items from queue
|
| 719 |
+
items = []
|
| 720 |
+
while not SEARCH_RESULTS_QUEUE.empty():
|
| 721 |
+
items.append(SEARCHRESULTS_QUEUE.get())
|
| 722 |
+
|
| 723 |
+
# Check for matching query
|
| 724 |
+
result = None
|
| 725 |
+
for item_query, item_response in items:
|
| 726 |
+
if item_query.lower() == query.lower():
|
| 727 |
+
result = item_response
|
| 728 |
+
|
| 729 |
+
# Put non-matching items back in queue
|
| 730 |
+
for item in items:
|
| 731 |
+
if item[0].lower() != query.lower():
|
| 732 |
+
SEARCH_RESULTS_QUEUE.put(item)
|
| 733 |
+
|
| 734 |
+
return result
|
| 735 |
+
|
| 736 |
+
def generate_response(user_input):
|
| 737 |
+
"""Generate a response to the user's input."""
|
| 738 |
+
# Add to history
|
| 739 |
+
USER_HISTORY.append(user_input)
|
| 740 |
+
|
| 741 |
+
# Check for special commands
|
| 742 |
+
if user_input.lower() in ["exit", "quit", "bye"]:
|
| 743 |
+
return "Goodbye! Feel free to ask me more questions anytime."
|
| 744 |
+
|
| 745 |
+
if user_input.lower() in ["help", "commands"]:
|
| 746 |
+
return (
|
| 747 |
+
f"I'm {AI_CONFIG['name']}, an AI assistant that can answer your questions.\n"
|
| 748 |
+
"- Ask me anything and I'll give you a direct answer\n"
|
| 749 |
+
"- For math calculations, just type your equation\n"
|
| 750 |
+
"- Ask for code examples and I'll search the internet\n"
|
| 751 |
+
"- Type 'quit' to exit"
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
# Check if this is a code request
|
| 755 |
+
code_request_patterns = [
|
| 756 |
+
r'code for', r'write code', r'create a program', r'how to code',
|
| 757 |
+
r'script for', r'implement', r'develop a', r'programming',
|
| 758 |
+
r'function for', r'class for', r'make a program'
|
| 759 |
+
]
|
| 760 |
+
|
| 761 |
+
is_code_request = any(re.search(pattern, user_input.lower()) for pattern in code_request_patterns)
|
| 762 |
+
|
| 763 |
+
if is_code_request and AI_CONFIG["limitations"]["no_code_generation"]:
|
| 764 |
+
return "I'm designed for conversation only and cannot generate or provide code examples. However, I can explain programming concepts or discuss how certain algorithms work in general terms."
|
| 765 |
+
|
| 766 |
+
# Check if it's a greeting
|
| 767 |
+
if is_simple_greeting(user_input):
|
| 768 |
+
return get_greeting_response(user_input)
|
| 769 |
+
|
| 770 |
+
# Check if we already have a result for this query
|
| 771 |
+
previous_result = check_previous_results(user_input)
|
| 772 |
+
if previous_result:
|
| 773 |
+
return previous_result
|
| 774 |
+
|
| 775 |
+
# Analyze the query
|
| 776 |
+
query_type, topic = analyze_query(user_input)
|
| 777 |
+
|
| 778 |
+
# Generate response based on query type
|
| 779 |
+
if query_type == "math":
|
| 780 |
+
return answer_math_question(user_input)
|
| 781 |
+
|
| 782 |
+
# If background search is enabled
|
| 783 |
+
if AI_CONFIG["background_search"]:
|
| 784 |
+
# Start a search in the background
|
| 785 |
+
search_thread = threading.Thread(
|
| 786 |
+
target=background_search,
|
| 787 |
+
args=(user_input, query_type, topic),
|
| 788 |
+
daemon=True
|
| 789 |
+
)
|
| 790 |
+
search_thread.start()
|
| 791 |
+
|
| 792 |
+
# Return an immediate response - make it sound like a direct answer
|
| 793 |
+
# instead of telling about search process
|
| 794 |
+
quick_responses = [
|
| 795 |
+
"Let me think about that for a moment. I'll have a better answer shortly.",
|
| 796 |
+
"I'm processing your question. Ask me something else while I work on this.",
|
| 797 |
+
"I'll need a moment to formulate a complete answer.",
|
| 798 |
+
"Im working on that. I'll have a detailed response shortly."
|
| 799 |
+
]
|
| 800 |
+
return random.choice(quick_responses)
|
| 801 |
+
|
| 802 |
+
# If not using background search, do the search immediately
|
| 803 |
+
search_results = search_web(user_input if query_type == "general" else topic)
|
| 804 |
+
response_body = format_response(search_results, query_type, topic)
|
| 805 |
+
return response_body
|
| 806 |
+
|
| 807 |
+
def display_background_results():
|
| 808 |
+
"""Display background search results as they become available."""
|
| 809 |
+
if not SEARCH_RESULTS_QUEUE.empty():
|
| 810 |
+
query, response = SEARCH_RESULTS_QUEUE.get()
|
| 811 |
+
print(f"\n{AI_CONFIG['name']}: {response}")
|
| 812 |
+
print("\nYou: ", end="")
|
| 813 |
+
|
| 814 |
+
def retrieve_from_memory(query):
|
| 815 |
+
"""Retrieve relevant context from memory."""
|
| 816 |
+
# Simple keyword-based retrieval for demonstration
|
| 817 |
+
keywords = query.lower().split()
|
| 818 |
+
relevant_entries = []
|
| 819 |
+
for k, v in MEMORY.items():
|
| 820 |
+
if any(keyword in k.lower() or keyword in v.lower() for keyword in keywords):
|
| 821 |
+
relevant_entries.append(v)
|
| 822 |
+
return " ".join(relevant_entries) if relevant_entries else None
|
| 823 |
+
|
| 824 |
+
def update_memory(query, response):
|
| 825 |
+
"""Update memory with the current interaction."""
|
| 826 |
+
MEMORY[query] = response
|
| 827 |
+
|
| 828 |
+
def is_inappropriate_content(text):
|
| 829 |
+
"""Check if text contains inappropriate content."""
|
| 830 |
+
# Content filter disabled
|
| 831 |
+
return False
|
| 832 |
+
|
| 833 |
+
def handle_inappropriate_request(query):
|
| 834 |
+
"""Generate a safe response for inappropriate requests."""
|
| 835 |
+
responses = [
|
| 836 |
+
"I'm designed to provide helpful and appropriate information. I cannot respond to that request.",
|
| 837 |
+
"I'm programmed to maintain respectful communication. Let's talk about something else.",
|
| 838 |
+
"I'm unable to engage with that topic. Is there something else I can help you with?",
|
| 839 |
+
"That request contains content I'm not programmed to discuss. How about we focus on a different topic?",
|
| 840 |
+
"I follow strict content guidelines and cannot respond to that query. I'd be happy to help with other questions."
|
| 841 |
+
]
|
| 842 |
+
return random.choice(responses)
|
| 843 |
+
|
| 844 |
+
def main():
|
| 845 |
+
clear_screen()
|
| 846 |
+
print(f"====== {AI_CONFIG['name']} Advanced AI Assistant ======")
|
| 847 |
+
print(f"Neural Network Size: {AI_CONFIG['neural_net_size']} nodes | Dual Model Architecture")
|
| 848 |
+
print(f"Training Corpus: {AI_CONFIG['training_corpus_size']:,} sentences | {AI_CONFIG['vocabulary_size']:,} word vocabulary")
|
| 849 |
+
print(f"Knowledge Domains: {', '.join(AI_CONFIG['knowledge_domains'][:5])} + {len(AI_CONFIG['knowledge_domains'])-5} more")
|
| 850 |
+
print(f"Semantic Processing: {random.randint(96, 99)}% accuracy | Advanced Context Awareness")
|
| 851 |
+
print("Ask me anything or type 'quit' to exit.")
|
| 852 |
+
print("="*50)
|
| 853 |
+
|
| 854 |
+
def background_result_checker():
|
| 855 |
+
while True:
|
| 856 |
+
if not SEARCH_RESULTS_QUEUE.empty():
|
| 857 |
+
query, response = SEARCH_RESULTS_QUEUE.get()
|
| 858 |
+
|
| 859 |
+
# Display search information at the top
|
| 860 |
+
print(f"\n\n<searching>{AI_CONFIG['name']} is collecting information about: {query}</searching>")
|
| 861 |
+
|
| 862 |
+
# Get relevant context from memory
|
| 863 |
+
memory_context = retrieve_from_memory(query)
|
| 864 |
+
|
| 865 |
+
# Process the search results with the pre-trained AI module
|
| 866 |
+
refined_response = refine_response(response, query, memory_context)
|
| 867 |
+
|
| 868 |
+
# Make sure there are no random symbols in the final output
|
| 869 |
+
refined_response = clean_text_symbols(refined_response)
|
| 870 |
+
|
| 871 |
+
# Update memory with this interaction
|
| 872 |
+
update_memory(query, refined_response)
|
| 873 |
+
|
| 874 |
+
# Check if the response is actually useful
|
| 875 |
+
if len(refined_response.strip()) < 10:
|
| 876 |
+
# If response is too short, try to generate a better one
|
| 877 |
+
fallback_response = f"Based on available information about {query}, {response}"
|
| 878 |
+
refined_response = refine_response(fallback_response, query)
|
| 879 |
+
refined_response = clean_text_symbols(refined_response)
|
| 880 |
+
|
| 881 |
+
# Display the final response
|
| 882 |
+
print(f"\n{AI_CONFIG['name']}: {refined_response}")
|
| 883 |
+
print("\nYou: ", end="", flush=True)
|
| 884 |
+
time.sleep(0.5)
|
| 885 |
+
|
| 886 |
+
def main():
|
| 887 |
+
clear_screen()
|
| 888 |
+
print(f"====== {AI_CONFIG['name']} Advanced AI Assistant ======")
|
| 889 |
+
print(f"Neural Network Size: {AI_CONFIG['neural_net_size']} nodes | Dual Model Architecture")
|
| 890 |
+
print(f"Training Corpus: {AI_CONFIG['training_corpus_size']:,} sentences | {AI_CONFIG['vocabulary_size']:,} word vocabulary")
|
| 891 |
+
print(f"Knowledge Domains: {', '.join(AI_CONFIG['knowledge_domains'][:5])} + {len(AI_CONFIG['knowledge_domains'])-5} more")
|
| 892 |
+
print(f"Semantic Processing: {random.randint(96, 99)}% accuracy | Advanced Context Awareness")
|
| 893 |
+
print("Ask me anything or type 'quit' to exit.")
|
| 894 |
+
print("="*50)
|
| 895 |
+
|
| 896 |
+
# Start the background result checker
|
| 897 |
+
bg_thread = threading.Thread(target=background_result_checker, daemon=True)
|
| 898 |
+
bg_thread.start()
|
| 899 |
+
|
| 900 |
+
while True:
|
| 901 |
+
print("\nYou: ", end="", flush=True)
|
| 902 |
+
user_input = input().strip()
|
| 903 |
+
|
| 904 |
+
if not user_input:
|
| 905 |
+
print(f"{AI_CONFIG['name']}: Please ask me a question or type 'quit' to exit.")
|
| 906 |
+
continue
|
| 907 |
+
|
| 908 |
+
if user_input.lower() in ["exit", "quit", "bye"]:
|
| 909 |
+
print(f"\n{AI_CONFIG['name']}: Goodbye! Feel free to ask me more questions anytime.")
|
| 910 |
+
break
|
| 911 |
+
|
| 912 |
+
# Content filtering disabled
|
| 913 |
+
|
| 914 |
+
response = generate_response(user_input)
|
| 915 |
+
|
| 916 |
+
# Apply final text cleaning
|
| 917 |
+
response = clean_text_symbols(response)
|
| 918 |
+
|
| 919 |
+
# Add AI-specific response formatting
|
| 920 |
+
if random.random() < 0.3: # Occasionally add thinking indicators
|
| 921 |
+
thinking_phrases = [
|
| 922 |
+
"Analyzing available data...",
|
| 923 |
+
"Processing information across neural network...",
|
| 924 |
+
"Correlating data points..."
|
| 925 |
+
]
|
| 926 |
+
print(f"\n{AI_CONFIG['name']} [thinking]: {random.choice(thinking_phrases)}")
|
| 927 |
+
time.sleep(0.5)
|
| 928 |
+
|
| 929 |
+
# Calculate simulated confidence level based on response length and complexity
|
| 930 |
+
confidence = min(random.uniform(0.85, 0.98), 0.98)
|
| 931 |
+
|
| 932 |
+
print(f"\n{AI_CONFIG['name']} [confidence: {confidence:.2f}]: {response}")
|
| 933 |
+
|
| 934 |
+
if __name__ == "__main__":
|
| 935 |
+
try:
|
| 936 |
+
main()
|
| 937 |
+
except KeyboardInterrupt:
|
| 938 |
+
print(f"\n\n{AI_CONFIG['name']}: Session terminated by user. Goodbye!")
|
| 939 |
+
except Exception as e:
|
| 940 |
+
print(f"\n\nError: {e}")
|
| 941 |
+
print("The program encountered an unexpected error and needs to close.")
|