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