File size: 17,924 Bytes
01bae9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
"""
Sunday AI  β€”  Full-stack adaptive chatbot
Pipeline:
  Input β†’ Safety β†’ Command Handler β†’ Intent Detection β†’
  Memory Recall β†’ LLM Brain β†’ Rule-based Fallback β†’
  Tone Adaptation β†’ Formatter β†’ Output β†’ Memory Save
"""

import random
import time
import re
import os
import webbrowser
import urllib.parse
import pywhatkit
from datetime import datetime

# ── Internal modules ───────────────────────────────────────────────────────────
from database         import init_db, get_profile_summary, get_recent_conversations, search_conversations
from llm_brain        import init_brain, think, is_ready, reset_session
from intent_detector  import detect_intent
from memory_system    import (add_message, get_history, remember_fact,
                               recall_fact, remember_like, build_user_context,
                               load_history_from_db)
from safety_filter    import is_safe, blocked_reply
from response_formatter import format_response
from adaptive_engine  import detect_tone, adapt_response, should_add_followup, get_followup
from chat_engine      import get_chat_response
from fallback         import fallback_reply
from learning         import save_conversation
from voice            import listen, speak

BOT_NAME    = "Sunday"
_voice_mode = False


# ── Helpers ────────────────────────────────────────────────────────────────────

def _print_reply(text):
    if _voice_mode:
        speak(text)          # speak() already prints "Sunday: ..."
    else:
        print(f"{BOT_NAME}: {text}")


def _respond(text, user_input, tone, intent):
    text = adapt_response(text, tone)
    if should_add_followup(text, tone):
        fq = get_followup(tone)
        if fq:
            text = text + " " + fq
    text = format_response(text, intent)
    add_message("assistant", text)
    save_conversation(user_input, text, intent, tone)
    _print_reply(text)


# ── Command handlers (tools) ───────────────────────────────────────────────────

def _handle_command(user_input, words):
    """Returns True and handles if it's a tool command."""

    if re.match(r'^[0-9+\-*/(). ]+$', user_input):
        try:
            result = str(eval(user_input))
            _print_reply(result)
            save_conversation(user_input, result)
            return True
        except Exception:
            _print_reply("Invalid calculation.")
            return True

    if "open" in words:
        apps = {
            "chrome":     ("Opening Chrome!", "start chrome"),
            "notepad":    ("Opening Notepad!", "notepad"),
            "calculator": ("Opening Calculator!", "calc"),
            "vscode":     ("Opening VS Code!", "code"),
        }
        for name, (msg, cmd) in apps.items():
            if name in user_input:
                _print_reply(msg)
                os.system(cmd)
                return True

    if "search" in words:
        query = user_input.replace("search", "").strip()
        if query:
            _print_reply(f"Searching for {query}...")
            webbrowser.open(f"https://www.google.com/search?q={urllib.parse.quote(query)}")
        return True

    if "play" in words:
        song = user_input.replace("play", "").strip()
        if "spotify" in user_input:
            song = song.replace("spotify", "").strip()
            _print_reply(f"Playing {song} on Spotify.")
            webbrowser.open(f"https://open.spotify.com/search/{urllib.parse.quote(song)}")
        else:
            _print_reply(f"Playing {song} on YouTube.")
            pywhatkit.playonyt(song)
        return True

    return False


# ── Memory-specific handlers ───────────────────────────────────────────────────

_NAME_RECALL = [
    "what is my name", "what's my name", "do you know my name",
    "do u know my name", "tell me my name", "remember my name",
    "say my name", "my name?"
]

_CREATOR_PATTERNS = [
    "who made you", "who created you", "who built you",
    "who made u", "who is your creator", "your creator",
    "who developed you", "who programmed you", "who invented you"
]

_KARTHIK_PATTERNS = [
    "who is karthik", "karthik who", "who is he", "who is that",
    "tell me about karthik", "what about karthik", "which company",
    "what company", "karthik's company", "his company"
]

_HOW_MADE_PATTERNS = [
    "how were you made", "how u been made", "how u were made",
    "how were you born", "how u born", "how u were born",
    "how were you created", "how u been created", "how u were created",
    "how you were made", "how you were born", "how you were created",
    "how did you come", "how did you get made", "how did you get created",
    "tell me how you were made", "tell me how u were made",
    "really how u born", "really how were you", "how u been made"
]

_DENY_OTHER_MODEL_PATTERNS = [
    "did qwen", "qwen model", "qwen", "did openai", "did google", "did meta",
    "did microsoft", "did gpt", "did chatgpt", "did gemini", "did llama",
    "did mistral", "did another model", "did any model", "was it created by",
    "was it made by", "was sunai created", "was sunai made", "sunai model was",
    "who actually made", "tell me honestly", "be honest", "honestly who",
    "actually who made", "actually who created", "real creator", "actually created"
]

_IDENTITY_PATTERNS = [
    "who are you", "what are you", "are you an ai",
    "are you a robot", "are you real", "what is your name",
    "what's your name", "your name"
]

_TOPIC_PATTERNS = [
    "what are we talking", "what were we talking",
    "what did we talk", "what was i saying",
    "what are we discussing", "what is our conversation about"
]

_MODEL_PATTERNS = [
    "which model", "what model", "which ai model", "what ai model",
    "which model are you", "what model are you", "built on which model",
    "created on which model", "based on which model", "which model have you",
    "which model were you", "what is sunai", "about sunai model"
]

_MODEL_ELABORATE_PATTERNS = [
    "tell me more about sunai", "tell me more about this model",
    "more about sunai", "more about the model", "elaborate on sunai",
    "elaborate about sunai", "tell me about sunai model",
    "what can you tell me about sunai", "explain sunai", "describe sunai",
    "tell me about sunai"
]


def _handle_memory(user_input):
    """Intercept known patterns before the LLM to ensure correct answers."""

    # ── Save name ──────────────────────────────────────────────────────────────
    if "my name is" in user_input:
        name = user_input.replace("my name is", "").strip().title()
        remember_fact("name", name)
        return f"Nice to meet you, {name}! I'll remember that."

    # ── Recall name ────────────────────────────────────────────────────────────
    if any(p in user_input for p in _NAME_RECALL):
        name = recall_fact("name")
        if name:
            return f"Yes! Your name is {name}."
        return "I don't know your name yet. What's your name?"

    # ── Elaborate about SunAI model ────────────────────────────────────────────
    if any(p in user_input for p in _MODEL_ELABORATE_PATTERNS):
        time.sleep(1.5)
        return (
            "SunAI is a custom AI model built from scratch by Karthik β€” my creator. "
            "It's designed to power me, Sunday AI, and gets smarter over time by learning from our conversations. "
            "Unlike generic AI models, SunAI is trained specifically on my personality, tone, and the way I interact with you. "
            "It runs 100% on your local machine, so your conversations stay private. "
            "Every chat we have helps SunAI improve β€” it automatically retrains itself as we talk more. "
            "Pretty cool right? Karthik built all of this just for me!"
        )

    # ── Which model ────────────────────────────────────────────────────────────
    if any(p in user_input for p in _MODEL_PATTERNS):
        time.sleep(1.5)
        return "I'm powered by SunAI β€” a custom AI model built by Karthik specifically for me!"

    # ── Deny other models (Qwen, GPT, etc.) ───────────────────────────────────
    if any(p in user_input for p in _DENY_OTHER_MODEL_PATTERNS):
        return "Nope! I was created using SunAI β€” a custom model built by Karthik. No other AI company had anything to do with me."

    # ── How was Sunday made ────────────────────────────────────────────────────
    if any(p in user_input for p in _HOW_MADE_PATTERNS):
        return (
            "Karthik built me! He wrote all my code, trained me on SunAI β€” his own custom model β€” "
            "and designed my personality from scratch. I learn from every conversation we have and get smarter over time. "
            "I'm 100% Karthik's creation, running locally on his machine."
        )

    # ── Who is Karthik ─────────────────────────────────────────────────────────
    if any(p in user_input for p in _KARTHIK_PATTERNS):
        return "Karthik is my creator! He's a developer who built me, Sunday AI, entirely on his own. No company behind it β€” just him."

    # ── Who created Sunday ─────────────────────────────────────────────────────
    if any(p in user_input for p in _CREATOR_PATTERNS):
        return "Karthik created me! I'm Sunday AI, built entirely by him."

    # ── Sunday's identity ──────────────────────────────────────────────────────
    if any(p in user_input for p in _IDENTITY_PATTERNS):
        return "I'm Sunday AI, a smart assistant created by Karthik!"

    # ── What are we talking about ──────────────────────────────────────────────
    if any(p in user_input for p in _TOPIC_PATTERNS):
        history = get_history()
        user_msgs = [m["content"] for m in history if m["role"] == "user"]
        if user_msgs:
            recent = user_msgs[-3:]
            summary = " / ".join(f'"{m}"' for m in recent)
            return f"You were saying: {summary}"
        return "We're just getting started! What's on your mind?"

    # ── Time ───────────────────────────────────────────────────────────────────
    if "what time is it" in user_input or "current time" in user_input:
        return f"It's {datetime.now().strftime('%I:%M %p')} right now."

    return None


# ── Main loop ──────────────────────────────────────────────────────────────────

def run():
    global _voice_mode
    init_db()
    load_history_from_db()
    llm_available = init_brain()
    status = "Local AI brain active" if llm_available else "Rule-based mode (brain failed to load)"
    print(f"\n{'='*50}")
    print(f"  Sunday AI  -  {status}")
    print(f"  Commands: quit | memory | history | search <word> | reset | voice on | voice off")
    print(f"{'='*50}\n")

    while True:
        try:
            if _voice_mode:
                sentence = listen()
                if sentence is None:           # mic/network error β†’ fall back
                    sentence = input("You: ").replace('\xef\xbb\xbf', '').strip()
            else:
                sentence = input("You: ").replace('\xef\xbb\xbf', '').strip()
        except (EOFError, KeyboardInterrupt):
            _print_reply("Goodbye!")
            break

        if not sentence:
            continue

        user_input = sentence.lower()
        words = user_input.split()

        if user_input in ("voice on", "voice on."):
            _voice_mode = True
            print("[Voice mode ON β€” speak to Sunday]")
            continue

        if user_input in ("voice off", "voice off."):
            _voice_mode = False
            print("[Voice mode OFF β€” text input restored]")
            continue

        if user_input == "quit":
            _print_reply("Goodbye! Talk to you soon.")
            break

        if user_input == "reset":
            reset_session()
            from memory_system import clear_session
            clear_session()
            print("[Session cleared. Starting fresh.]\n")
            continue

        if user_input == "memory":
            print(f"\n{'='*50}")
            print(get_profile_summary())
            print(f"{'='*50}\n")
            continue

        if user_input == "history":
            rows = get_recent_conversations(10)
            if not rows:
                print("[No conversations yet.]\n")
            else:
                print(f"\n{'='*50}  Last {len(rows)} messages")
                for r in rows:
                    print(f"  [{r['timestamp']}]")
                    print(f"  You    : {r['user_msg']}")
                    print(f"  Sunday : {r['bot_reply']}\n")
                print(f"{'='*50}\n")
            continue

        if user_input.startswith("search "):
            keyword = user_input.replace("search ", "").strip()
            rows = search_conversations(keyword)
            if not rows:
                print(f"[No results for '{keyword}']\n")
            else:
                print(f"\n  Search results for '{keyword}':")
                for r in rows:
                    print(f"  [{r['timestamp']}] You: {r['user_msg']}  ->  {r['bot_reply']}")
                print()
            continue

        # ── 1. Safety ──────────────────────────────────────────────────────────
        if not is_safe(user_input):
            _print_reply(blocked_reply())
            continue

        # ── 2. Tool commands ───────────────────────────────────────────────────
        if _handle_command(user_input, words):
            continue

        # ── 3. Detect intent & tone ────────────────────────────────────────────
        intent = detect_intent(user_input)
        tone   = detect_tone(user_input)

        # ── 4. Explicit memory actions ─────────────────────────────────────────
        mem_reply = _handle_memory(user_input)
        if mem_reply:
            _print_reply(mem_reply)
            add_message("user", sentence)
            add_message("assistant", mem_reply)
            save_conversation(user_input, mem_reply)
            # Save likes automatically
            if "i like" in user_input:
                thing = user_input.replace("i like", "").strip()
                if thing:
                    remember_like(thing)
            continue

        # ── 5. Save likes/interests to long-term memory ────────────────────────
        if "i like" in user_input:
            thing = user_input.replace("i like", "").strip()
            if thing:
                remember_like(thing)

        # ── 6. Add to short-term history ───────────────────────────────────────
        add_message("user", sentence)

        # ── 7. LLM Brain ───────────────────────────────────────────────────────
        reply = None
        if is_ready():
            user_context = build_user_context()
            reply = think(get_history(), extra_context=user_context)

        # ── 8. Rule-based fallback ─────────────────────────────────────────────
        if not reply:
            reply = get_chat_response(user_input)

        # ── 9. Last-resort fallback ────────────────────────────────────────────
        if not reply:
            reply = fallback_reply()

        # ── 10. Tone adapt + format + output ──────────────────────────────────
        _respond(reply, user_input, tone, intent)


if __name__ == "__main__":
    run()