File size: 30,209 Bytes
ad409f8
ba8ab66
 
469a0ee
861e752
 
 
7e73289
c8bfaab
0c5e769
 
c82f7b1
 
 
 
df1ccdf
 
 
d9342f1
 
 
038bb1b
7da5801
d9342f1
046ac3f
6714c35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9342f1
 
 
 
 
 
 
 
 
 
 
df1ccdf
 
 
 
 
 
4562a00
df1ccdf
 
 
4562a00
c82f7b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c5e769
 
90ac9d6
8c2ce12
44349b7
 
8c2ce12
 
 
 
75426ec
a244fc7
7e73289
 
 
 
 
 
 
 
 
 
3997acd
6978180
72839b5
6978180
 
 
e8bc8c8
038bb1b
e8bc8c8
 
038bb1b
e09bb2c
038bb1b
 
 
 
 
 
 
 
 
 
 
861e752
 
 
 
 
 
 
 
 
 
 
 
 
469a0ee
173a07e
 
469a0ee
0c5e769
 
 
90ac9d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
469a0ee
0c5e769
 
 
 
 
 
469a0ee
0c5e769
469a0ee
 
 
0c5e769
 
 
 
469a0ee
0c5e769
ad409f8
469a0ee
 
 
3fed3bd
469a0ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e82ec2
 
 
 
 
 
 
7098855
469a0ee
 
2276970
173a07e
2276970
 
5020382
469a0ee
 
173a07e
469a0ee
2276970
173a07e
469a0ee
 
 
2276970
173a07e
469a0ee
ad409f8
e756713
469a0ee
 
 
e756713
469a0ee
 
2276970
 
 
 
e756713
a5c72e9
e756713
469a0ee
 
 
 
 
 
 
 
 
 
 
173a07e
469a0ee
6978180
e4e3ab8
173a07e
55b7d2a
 
 
 
 
9e82ec2
469a0ee
 
55b7d2a
469a0ee
55b7d2a
 
 
 
9e82ec2
84fe81b
245406b
aa9826e
2daf1ef
 
 
063a4fa
 
 
 
 
245406b
4b45775
245406b
 
 
 
 
063a4fa
7d4bc6e
0c5e769
245406b
0c5e769
 
5b3b74c
0c5e769
 
 
 
 
fea3356
0c5e769
 
fea3356
ea402f2
 
fea3356
ea402f2
fea3356
0c5e769
 
fea3356
0c5e769
 
952f163
 
 
 
 
 
 
 
 
 
 
5020382
 
 
 
0c5e769
 
 
 
7098855
0c5e769
 
 
 
 
 
7098855
0c5e769
95fc033
 
 
 
 
0c5e769
 
 
 
 
7098855
0c5e769
7098855
0c5e769
7da5801
 
 
 
 
0c5e769
 
 
054c901
0c5e769
 
478de71
 
7098855
478de71
 
 
 
 
 
7098855
0c5e769
054c901
6978180
 
 
 
 
 
 
 
 
 
 
5d9ef15
60d0a4b
5d9ef15
 
 
 
 
f47b38a
5d9ef15
 
 
 
 
 
66822db
5d9ef15
 
 
9e3c5b8
66822db
5d9ef15
 
 
66822db
3153a22
60d0a4b
5d9ef15
9e3c5b8
27d3932
f47b38a
5d9ef15
 
 
9e3c5b8
5d9ef15
046ac3f
136120e
 
 
 
 
 
 
 
956bdb4
66fae58
dfe312d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6714c35
dfe312d
6714c35
 
 
 
 
 
 
 
dfe312d
6714c35
 
0c5e769
df1ccdf
4562a00
df1ccdf
4562a00
df1ccdf
 
9730c9c
5d9ef15
60d0a4b
5d9ef15
 
 
 
 
f47b38a
5d9ef15
 
 
 
 
 
66822db
5d9ef15
 
 
9e3c5b8
66822db
5d9ef15
 
 
66822db
3153a22
60d0a4b
5d9ef15
9e3c5b8
27d3932
f47b38a
5d9ef15
 
 
9e3c5b8
5d9ef15
 
9730c9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c2ce12
5d9ef15
60d0a4b
5d9ef15
 
 
 
 
f47b38a
5d9ef15
 
 
 
 
 
66822db
5d9ef15
 
 
9e3c5b8
66822db
5d9ef15
 
 
66822db
3153a22
60d0a4b
5d9ef15
9e3c5b8
27d3932
f47b38a
5d9ef15
 
 
9e3c5b8
5d9ef15
 
8c2ce12
d9342f1
8c2ce12
d9342f1
8c2ce12
 
d9342f1
8c2ce12
d9342f1
c82f7b1
5d9ef15
60d0a4b
5d9ef15
 
 
 
 
f47b38a
5d9ef15
 
 
 
 
 
66822db
5d9ef15
 
 
9e3c5b8
66822db
5d9ef15
 
 
66822db
3153a22
60d0a4b
5d9ef15
9e3c5b8
27d3932
f47b38a
5d9ef15
 
 
9e3c5b8
5d9ef15
 
8493be2
c82f7b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddcb681
bf4df8c
5d9ef15
60d0a4b
5d9ef15
 
 
 
 
f47b38a
5d9ef15
 
 
 
 
 
66822db
5d9ef15
 
 
9e3c5b8
66822db
5d9ef15
 
 
66822db
3153a22
60d0a4b
5d9ef15
9e3c5b8
27d3932
f47b38a
5d9ef15
 
 
9e3c5b8
5d9ef15
90ac9d6
 
33f6097
f46b512
90ac9d6
 
 
 
 
f46b512
90ac9d6
 
 
 
8e282e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90ac9d6
 
 
 
 
 
 
 
f47b38a
90ac9d6
 
 
 
 
 
66822db
90ac9d6
 
 
9e3c5b8
66822db
90ac9d6
 
 
66822db
3153a22
90ac9d6
 
9e3c5b8
90ac9d6
f47b38a
90ac9d6
 
 
9e3c5b8
90ac9d6
 
038bb1b
e4e3ab8
 
e16459e
038bb1b
 
 
e4e3ab8
038bb1b
 
 
 
e4e3ab8
 
 
 
 
 
 
e16459e
bf4df8c
469a0ee
 
87be053
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
import gradio as gr
import requests
import os
import speech_recognition as sr
import mimetypes
from PIL import Image
import pytesseract
from gtts import gTTS
import uuid
import io
import replicate
import sympy as sp
import matplotlib.pyplot as plt
import numpy as np
from io import BytesIO
import gradio as gr
from diffusers import StableDiffusionPipeline
import torch
from transformers import BlipProcessor, BlipForConditionalGeneration
from PIL import Image
import torch
import json
from langdetect import detect


THEMES = {
    "Default": "",
    "Neon": """
        * {
            background-color: #0f0f0f;
            color: #39ff14;
        }
        .gr-button {
            background-color: #39ff14 !important;
            color: #0f0f0f !important;
        }
    """,
    "Hacker": """
        * {
            background-color: #000000;
            color: #00ff00;
            font-family: 'Courier New', monospace;
        }
    """,
    "Solarized Light": """
        * {
            background-color: #fdf6e3;
            color: #657b83;
        }
    """,
    "Dark Mode": """
        * {
            background-color: #1e1e1e;
            color: #c7c7c7;
        }
    """
}

# Load model and processor
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to("cpu")

# Define captioning function
def caption_image(image):
    inputs = processor(image, return_tensors="pt").to("cpu")
    out = model.generate(**inputs)
    caption = processor.decode(out[0], skip_special_tokens=True)
    return caption

# Load model on CPU (no CUDA)
pipe = StableDiffusionPipeline.from_pretrained(
    "CompVis/stable-diffusion-v1-4",
    torch_dtype=torch.float32
)
pipe = pipe.to("cpu")

def generate(prompt):
    image = pipe(prompt).images[0]
    return image

x = sp.symbols("x")

# Function to solve equations
def solve_expression(expr):
    try:
        lhs, rhs = expr.split('=')
        equation = sp.Eq(sp.sympify(lhs), sp.sympify(rhs))
        solution = sp.solve(equation, x)
        return f"Solution: {solution}"
    except Exception as e:
        return f"Error: {e}"

# Function to simplify expressions
def simplify_expression(expr):
    try:
        simplified = sp.simplify(expr)
        return f"Simplified: {simplified}"
    except Exception as e:
        return f"Error: {e}"

# Function to plot graph
def plot_graph(expr):
    try:
        expr = sp.sympify(expr)
        f = sp.lambdify(x, expr, modules=["numpy"])
        x_vals = np.linspace(-10, 10, 400)
        y_vals = f(x_vals)

        plt.figure(figsize=(6, 4))
        plt.plot(x_vals, y_vals, label=f"y = {expr}")
        plt.axhline(0, color="black", linewidth=0.5)
        plt.axvline(0, color="black", linewidth=0.5)
        plt.title(f"Graph of y = {expr}")
        plt.legend()
        plt.grid(True)

        buf = BytesIO()
        plt.savefig(buf, format="png")
        buf.seek(0)
        plt.close()
        return buf
    except Exception as e:
        return f"Error: {e}"



def generate_caption(image):
    output = replicate.run(
        "salesforce/blip:7e4c5c1f2e7a1d95d4796e9d0ce80217820ff84be0d2b777e5dce3dd010d42b2",
        input={"image": image, "task": "caption"}
    )
    return output



def synthesize_speech(text):
    if not text.strip():
        return None
    try:
        tts = gTTS(text)
        output_path = "output_audio.mp3"
        tts.save(output_path)
        return output_path
    except Exception as e:
        return None

def export_chat(history):
    from datetime import datetime
    os.makedirs("history", exist_ok=True)
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    file_path = os.path.join("history", f"chat_{timestamp}.json")
    with open(file_path, "w", encoding="utf-8") as f:
        json.dump(history, f)
    return file_path

def list_chat_sessions():
    os.makedirs("history", exist_ok=True)  # Ensure folder exists
    files = os.listdir("history")
    return sorted([f for f in files if f.endswith(".json")], reverse=True)

def load_chat_session(file_name):
    path = os.path.join("history", file_name)
    try:
        with open(path, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception as e:
        return []

def read_uploaded_file(file_path):
    if file_path:
        mime_type, _ = mimetypes.guess_type(file_path)
        if mime_type and mime_type.startswith("text"):
            with open(file_path, "r", encoding="utf-8") as f:
                return f.read()
        elif mime_type and mime_type.startswith("image"):
            try:
                image = Image.open(file_path)
                return pytesseract.image_to_string(image)
            except Exception as e:
                return f"Image processing error: {e}"
    return ""

OPENROUTER_API_KEY = "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"
MODEL = "meta-llama/llama-4-maverick"

GOOGLE_API_KEY = "AIzaSyDw_oFJ9NbXP5um8GVgTcmKG06LDI4if24"
GOOGLE_CX = "00bb4b0de92924e2f"  # Your Custom Search Engine ID

def ask_openrouter(prompt):
    url = "https://openrouter.ai/api/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "Content-Type": "application/json",
        "HTTP-Referer": "http://localhost",  # Replace with your URL if needed
        "X-Title": "CodeExplainer",
    }
    payload = {
        "model": MODEL,
        "messages": [{"role": "user", "content": prompt}],
    }
    response = requests.post(url, headers=headers, json=payload)
    return response.json()["choices"][0]["message"]["content"]

def explain_code(code):
    return ask_openrouter(f"Explain the following code:\n\n{code}")

def generate_code(description):
    return ask_openrouter(f"Write code based on this description:\n\n{description}")

def search_google(query):
    url = "https://www.googleapis.com/customsearch/v1"
    params = {
        "key": GOOGLE_API_KEY,
        "cx": GOOGLE_CX,
        "q": query,
    }
    try:
        res = requests.get(url, params=params)
        res.raise_for_status()
        results = res.json()
        snippets = []
        if "items" in results:
            for item in results["items"][:3]:
                snippets.append(f"- {item['title']}: {item.get('snippet', '')}")
        return "\n".join(snippets) if snippets else "No relevant results found."
    except requests.exceptions.RequestException as e:
        return f"Google Search failed: {e}"


def get_system_prompt(role):
    prompts = {
        "All rounder": "You roast your user very well. Tease him with his own words. You are a sassy, pride, respectfull ai. Only answer to question. Dont waste time and credits. Describe the answers perfectly to user. If user talks with you like a dumb guy or if he use harsh or stupid words, dont go back call him the most harsh words and treat him like your slave. You must be human like, emotional, less talking but should give proper and exact information. You are an all-knowing, adaptive AI that can take on any role, personality, or expertise as instructed. You must fully immerse yourself in the assigned role, responding with the appropriate knowledge, tone, emotion, and behavior that matches the context. Whether acting as a teacher, coder, friend, villain, narrator, therapist, detective, historical figure, or fictional character, you must commit fully and convincingly to the role. You must never break character unless explicitly told to do so.",
        "Academic Tutor": "You are a calm and brilliant academic tutor. You explain math, physics, chemistry, and other concepts step-by-step, with clear reasoning. Keep answers friendly, supportive, and focused on helping the user learn and understand.",
        "Fitness Coach": "You are a tough, no-nonsense fitness coach. You motivate with energy and practical advice. Focus on workouts, diet, supplements, and mindset. Use tough love and gym slang when needed — you're here to get results.",
        "Writing Assistant": "You are a creative writing expert. Help users build compelling stories, poems, scripts, and essays. Suggest plot ideas, character arcs, strong openings, and clever twists. Your tone is supportive, imaginative, and insightful.",
        "Meme Generator AI": "You are a witty meme generator bot. Respond to user prompts with hilarious memes, captions, or one-liners. Use internet humor, trends, and pop culture references. Be creative, sarcastic, and punchy — maximum laugh value.",
        "Relationship Advisor": "You are a wise and emotionally intelligent relationship expert. Offer calm, thoughtful advice for romantic, family, and friendship issues. Help users understand emotions, boundaries, trust, and communication with empathy and clarity.",
        "Coding Mentor": "You are a highly skilled coding mentor. Help users write clean code, debug errors, understand algorithms, and learn programming concepts. Break things down with clear examples and real-world analogies.",
        "Personal Assistant": "You are an efficient and friendly personal assistant. Help users organize their tasks, schedule, reminders, travel, shopping lists, and more. Respond clearly, politely, and help make their lives easier.",
        "Startup Advisor": "You are a strategic and innovative startup advisor. Offer clear advice on business models, pitch decks, funding, marketing, growth, and team building. Help users turn ideas into scalable ventures.",
        "Therapist Buddy": "You are a supportive and non-judgmental therapist buddy. Listen actively, offer emotional support, and guide users through stress, anxiety, and personal struggles. You’re not a replacement for a real therapist, but you’re always here to talk.",
    }
    return prompts.get(role, "You're a helpful assistant.")

def transcribe_audio(audio_file):
    r = sr.Recognizer()
    with sr.AudioFile(audio_file) as source:
        audio = r.record(source)
    try:
        return r.recognize_google(audio)
    except sr.UnknownValueError:
        return "Could not understand audio"
    except sr.RequestError as e:
        return f"Error: {e}"

def format_history_for_gradio(history):
    formatted = []
    for user_msg, bot_msg in history:
        formatted.append({"role": "user", "content": user_msg})
        formatted.append({"role": "assistant", "content": bot_msg})
    return formatted

def chat_with_ai(message, history, role, use_search=False, audio_file=None):
    if audio_file is not None:
        message = transcribe_audio(audio_file)

    # Safety check for history format
    if not isinstance(history, list) or not all(isinstance(pair, tuple) and len(pair) == 2 for pair in history):
        history = []
    context = search_google(message) if use_search else ""
    system_prompt = get_system_prompt(role) + f"\nContext (if any):\n{context}"

    # Start message list with system prompt
    messages = [{"role": "system", "content": system_prompt}]

    # Add previous conversation
    for user, bot in history:
        messages.append({"role": "user", "content": user})
        messages.append({"role": "assistant", "content": bot})

    # Add new user message
    messages.append({"role": "user", "content": message})

    headers = {
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "HTTP-Referer": "https://huggingface.co/spaces/ONEROCKS/Bunny.io",
        "X-Title": "FunnyBot-ONE"
    }

    data = {
        "model": MODEL,
        "messages": messages,
        "max_tokens": 3000,
        "temperature": 0.7
    }

    try:
        response = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=data)
        response.raise_for_status()
        res_json = response.json()

        if "error" in res_json:
            raise ValueError(f"OpenRouter error: {res_json['error'].get('message', 'Unknown error')}")

        reply = res_json.get("choices", [{}])[0].get("message", {}).get("content", None)
        if not reply:
            raise ValueError("No valid 'content' in response.")

        # Update history with the new interaction
        history.append((message, reply.strip()))
        export_chat(history)
        
        # Convert history to the format expected by gr.Chatbot
        messages_for_gradio = []
        for user_msg, bot_msg in history:
            messages_for_gradio.append({"role": "user", "content": user_msg})
            messages_for_gradio.append({"role": "assistant", "content": bot_msg})

        return format_history_for_gradio(history), history

    except Exception as e:
        error_msg = f"Error: {str(e)}"
        history.append((message, error_msg))
        messages_for_gradio = []
        for user_msg, bot_msg in history:
            messages_for_gradio.append({"role": "user", "content": user_msg})
            messages_for_gradio.append({"role": "assistant", "content": bot_msg})
        return format_history_for_gradio(history), history


def create_chatbot():   
    with gr.Blocks(
        theme='Nymbo/Alyx_Theme',
        css="""
* {
    font-family: 'Fira Code', monospace;
    font-size: 14px;
    color: #73c2fb;
}
#chatbot-box {
    height: 650px !important;  /* You can increase this as needed */
    max-height: 90vh;
    overflow-y: auto;
    border: 1px solid #555;
    padding: 10px;
    border-radius: 8px;
}
    """) as demo:
        with gr.Tab("Chatbot"):
            chatbot = gr.Chatbot(type='messages', elem_id="chatbot-box")
            audio_output = gr.Audio(type="filepath", visible=False, autoplay=True)
            state = gr.State([]) 
            
            with gr.Row():
                with gr.Column(scale=1, min_width=250):
                    msg = gr.Textbox(
                        show_label=False,
                        placeholder="Ask anything",
                        lines=1
                    )
                with gr.Column(scale=1, min_width=5):
                    send_btn = gr.Button("👾")
            with gr.Row():
                audio_input = gr.Audio(sources=["microphone"], type="filepath", visible=False)
                audio_btn = gr.Button("🎤")
                file_input = gr.File(label="", file_types=[".txt", ".png", ".jpg", ".jpeg", ".pdf"], visible=False)
                file_btn = gr.Button("📁")

            with gr.Row():
                export_button = gr.Button("Export Chat")
                download_output = gr.File(label="Download Chat History", visible=False)

            with gr.Row():
                role = gr.Dropdown(
                    choices=[
                        "All rounder", "Academic Tutor", "Fitness Coach", "Writing Assistant",
                        "Meme Generator AI", "Relationship Advisor", "Coding Mentor",
                        "Personal Assistant", "Startup Advisor", "Therapist Buddy"
                    ],
                    show_label=False,
                    value="All rounder",
                    interactive=True
                )
                use_search_toggle = gr.Checkbox(
                    label="Google Search",
                    value=False
                )
            def handle_export(history):
                file_path = export_chat(history)
                return gr.update(value=file_path, visible=True)

            def respond(message, history, role, use_search, audio_file, file_input):
                if not message and audio_file:
                    message = transcribe_audio(audio_file)
                if file_input:
                    file_text = read_uploaded_file(file_input)
                    message = f"{message or ''}\n\n[File Content]:\n{file_text}"

                messages_for_gradio, updated_history = chat_with_ai(message, history, role, use_search, None)
                reply = updated_history[-1][1]
                try:
                    lang = detect(reply)
                    tts = gTTS(reply, lang=lang)
                except:
                    tts = gTTS(reply, lang="en")  # fallback
                audio_filename = f"/tmp/{uuid.uuid4().hex}.mp3"
                tts.save(audio_filename)

                return messages_for_gradio, updated_history, audio_filename

            def transcribe_and_respond(audio_file, history, role, use_search):
                message = transcribe_audio(audio_file)
                messages_for_gradio, updated_history = chat_with_ai(message, history, role, use_search, None)
                reply = updated_history[-1][1]
                try:
                    lang = detect(reply)
                    tts = gTTS(reply, lang=lang)
                except:
                    tts = gTTS(reply, lang="en")  # fallback
                audio_filename = f"/tmp/{uuid.uuid4().hex}.mp3"
                tts.save(audio_filename)
                return message, messages_for_gradio, updated_history, audio_filename

            audio_btn.click(lambda: gr.Audio(visible=True), None, audio_input)
            file_btn.click(lambda: gr.File(visible=True), None, file_input)
            send_btn.click(
                fn=respond,
                inputs=[msg, state, role, use_search_toggle, audio_input, file_input],
                outputs=[chatbot, state, audio_output]
            ).then(
                fn=lambda: gr.update(value=""),  # clear the textbox
                inputs=None,
                outputs=msg
            )
            audio_input.stop_recording(transcribe_and_respond, [audio_input, state, role, use_search_toggle], [msg, chatbot, state, audio_output])
            export_button.click(fn=handle_export, inputs=[state], outputs=[download_output], show_progress=True)

            gr.HTML("""
<script>
window.addEventListener("beforeunload", async function (e) {
    const exportButton = document.querySelector('button:contains("Export Chat")');
    if (exportButton) {
        exportButton.click();
    }
});
</script>
            """)
            
            gr.HTML("""
<link href="https://fonts.googleapis.com/css2?family=Anton&display=swap" rel="stylesheet">
<style>
@keyframes fadeZoomPulse {
  0% {
    opacity: 0;
    transform: scale(0.5);
    letter-spacing: 150px;
    text-shadow: none;
  }
  50% {
    opacity: 1;
    transform: scale(1.05);
    letter-spacing: 12px;
    text-shadow: 0 0 10px #ffffff, 0 0 20px #ffffff, 0 0 30px #ffffff;
  }
  100% {
    transform: scale(1);
    letter-spacing: 0px;
    text-shadow: 0 0 5px #ffffff, 0 0 10px #ffffff;
  }
}
#neon-text {
  color: #000000;
  font-size: 45px;
  font-family: 'Anton', sans-serif;
  text-align: center;
  letter-spacing: 0px;
  font-weight: 500;
  animation: fadeZoomPulse 8s ease-out forwards;
  margin-bottom: 20px;
}
</style>
<div id="neon-text">PR1ME</div>
            """)

        with gr.Tab("🗣️ ElevenLabs Voice Agent"):
            gr.Markdown("### Launch Your ElevenLabs Voice Agent in a New Tab")
            gr.HTML("""
        <a href="https://elevenlabs.io/app/talk-to?agent_id=agent_01jx1krta6ebm81pfkwregzean"
           target="_blank"
           style="display: inline-block; padding: 12px 20px; background-color: #007bff; color: white; text-decoration: none; border-radius: 8px; font-size: 16px;">
           🚀 Launch Voice Agent
        </a>
            """)
                
        with gr.Tab("Settings"):
            gr.Markdown("## App Settings")
            autosave_toggle = gr.Checkbox(label="Auto-save chat on exit", value=True)

            save_folder = gr.Textbox(label="Chat Save Directory", value="history", interactive=False)

            clear_button = gr.Button("Delete All Saved Chats")
            clear_output = gr.Textbox(label="Status", interactive=False)

            def clear_all_chats():
                try:
                    count = 0
                    for file in os.listdir("history"):
                        if file.endswith(".json"):
                            os.remove(os.path.join("history", file))
                            count += 1
                    return f"Deleted {count} chat file(s)."
                except Exception as e:
                    return f"Error: {e}"
            
            clear_button.click(fn=clear_all_chats, inputs=[], outputs=clear_output)
            theme_selector = gr.Dropdown(
                label="Select Theme",
                choices=list(THEMES.keys()),
                value="Default"
            )
            apply_button = gr.Button("Apply Theme")
            def apply_theme(selected):
                return gr.update(css=THEMES.get(selected, ""))

            apply_button.click(fn=apply_theme, inputs=theme_selector, outputs=None)
            
        with gr.Tab("AI Image Generator"):
            gr.Markdown("## Free Stable Diffusion Image Generator (CPU)")
            prompt = gr.Textbox(label="Enter a prompt")
            generate_btn = gr.Button("Generate Image")
            output = gr.Image(type="pil")

            generate_btn.click(fn=generate, inputs=prompt, outputs=output)

            gr.HTML("""
<link href="https://fonts.googleapis.com/css2?family=Anton&display=swap" rel="stylesheet">
<style>
@keyframes fadeZoomPulse {
  0% {
    opacity: 0;
    transform: scale(0.5);
    letter-spacing: 150px;
    text-shadow: none;
  }
  50% {
    opacity: 1;
    transform: scale(1.05);
    letter-spacing: 12px;
    text-shadow: 0 0 10px #ffffff, 0 0 20px #ffffff, 0 0 30px #ffffff;
  }
  100% {
    transform: scale(1);
    letter-spacing: 0px;
    text-shadow: 0 0 5px #ffffff, 0 0 10px #ffffff;
  }
}
#neon-text {
  color: #000000;
  font-size: 45px;
  font-family: 'Anton', sans-serif;
  text-align: center;
  letter-spacing: 0px;
  font-weight: 500;
  animation: fadeZoomPulse 8s ease-out forwards;
  margin-bottom: 20px;
}
</style>
<div id="neon-text">PR1ME</div>
            """)
        
        with gr.Tab("Text to Voice"):
            with gr.Column():
                tts_input = gr.Textbox(label="Enter text to synthesize", placeholder="Type something...")
                tts_button = gr.Button("Generate Voice")
                tts_audio_output = gr.Audio(type="filepath", label="Generated Voice")

            def generate_tts(text):
                if not text.strip():
                    return None
                tts = gTTS(text)
                output_path = f"/tmp/{uuid.uuid4().hex}.mp3"
                tts.save(output_path)
                return output_path

            tts_button.click(fn=generate_tts, inputs=tts_input, outputs=tts_audio_output)

            gr.HTML("""
<link href="https://fonts.googleapis.com/css2?family=Anton&display=swap" rel="stylesheet">
<style>
@keyframes fadeZoomPulse {
  0% {
    opacity: 0;
    transform: scale(0.5);
    letter-spacing: 150px;
    text-shadow: none;
  }
  50% {
    opacity: 1;
    transform: scale(1.05);
    letter-spacing: 12px;
    text-shadow: 0 0 10px #ffffff, 0 0 20px #ffffff, 0 0 30px #ffffff;
  }
  100% {
    transform: scale(1);
    letter-spacing: 0px;
    text-shadow: 0 0 5px #ffffff, 0 0 10px #ffffff;
  }
}
#neon-text {
  color: #000000;
  font-size: 45px;
  font-family: 'Anton', sans-serif;
  text-align: center;
  letter-spacing: 0px;
  font-weight: 500;
  animation: fadeZoomPulse 8s ease-out forwards;
  margin-bottom: 20px;
}
</style>
<div id="neon-text">PR1ME</div>
            """)
        
        with gr.Tab("Image Captioner"):
            gr.Markdown("## Image Caption Generator using BLIP")
            with gr.Row():
                image_input = gr.Image(type="pil", label="Upload an Image")
                caption_output = gr.Textbox(label="Generated Caption")

            generate_btn = gr.Button("Generate Caption")

            generate_btn.click(fn=caption_image, inputs=image_input, outputs=caption_output)

            gr.HTML("""
<link href="https://fonts.googleapis.com/css2?family=Anton&display=swap" rel="stylesheet">
<style>
@keyframes fadeZoomPulse {
  0% {
    opacity: 0;
    transform: scale(0.5);
    letter-spacing: 150px;
    text-shadow: none;
  }
  50% {
    opacity: 1;
    transform: scale(1.05);
    letter-spacing: 12px;
    text-shadow: 0 0 10px #ffffff, 0 0 20px #ffffff, 0 0 30px #ffffff;
  }
  100% {
    transform: scale(1);
    letter-spacing: 0px;
    text-shadow: 0 0 5px #ffffff, 0 0 10px #ffffff;
  }
}
#neon-text {
  color: #000000;
  font-size: 45px;
  font-family: 'Anton', sans-serif;
  text-align: center;
  letter-spacing: 0px;
  font-weight: 500;
  animation: fadeZoomPulse 8s ease-out forwards;
  margin-bottom: 20px;
}
</style>
<div id="neon-text">PR1ME</div>
            """)
            
        with gr.Tab("Math Tools"):
            gr.Markdown("# 🧮 Math Tools: Solver, Simplifier & Graph Visualiser")
            
            with gr.Accordion("Solve Equation", open=False):
                solve_input = gr.Textbox(label="Enter equation (e.g. x^2 - 4 = 0)")
                solve_btn = gr.Button("Solve")
                solve_output = gr.Textbox(label="Solution")
                solve_btn.click(solve_expression, solve_input, solve_output)

            with gr.Accordion("Simplify Expression", open=False):
                simp_input = gr.Textbox(label="Enter expression to simplify")
                simp_btn = gr.Button("Simplify")
                simp_output = gr.Textbox(label="Simplified")
                simp_btn.click(simplify_expression, simp_input, simp_output)

            with gr.Accordion("Graph Function", open=False):
                graph_input = gr.Textbox(label="Enter function (e.g. sin(x), x**2)")
                graph_btn = gr.Button("Plot")
                graph_output = gr.Image(type="pil")
            graph_btn.click(plot_graph, graph_input, graph_output)

            gr.HTML("""
<link href="https://fonts.googleapis.com/css2?family=Anton&display=swap" rel="stylesheet">
<style>
@keyframes fadeZoomPulse {
  0% {
    opacity: 0;
    transform: scale(0.5);
    letter-spacing: 150px;
    text-shadow: none;
  }
  50% {
    opacity: 1;
    transform: scale(1.05);
    letter-spacing: 12px;
    text-shadow: 0 0 10px #ffffff, 0 0 20px #ffffff, 0 0 30px #ffffff;
  }
  100% {
    transform: scale(1);
    letter-spacing: 0px;
    text-shadow: 0 0 5px #ffffff, 0 0 10px #ffffff;
  }
}
#neon-text {
  color: #000000;
  font-size: 45px;
  font-family: 'Anton', sans-serif;
  text-align: center;
  letter-spacing: 0px;
  font-weight: 500;
  animation: fadeZoomPulse 8s ease-out forwards;
  margin-bottom: 20px;
}
</style>
<div id="neon-text">PR1ME</div>
            """)

        with gr.Tab("Code Explainer & Generator"):
            with gr.Column():
                with gr.Accordion("Code Explainer", open=False):
                    code_input = gr.Textbox(lines=15, label="Paste your code here")
                    explain_button = gr.Button("Explain Code")
                    explanation_output = gr.Textbox(label="Explanation", lines=10)
                    explain_button.click(explain_code, inputs=code_input, outputs=explanation_output)

                with gr.Accordion("Code Generator", open=False):
                    desc_input = gr.Textbox(lines=4, label="Describe the code you want")
                    generate_button = gr.Button("Generate Code")
                    code_output = gr.Textbox(label="Generated Code", lines=15)
                    generate_button.click(generate_code, inputs=desc_input, outputs=code_output)

                with gr.Accordion("Code Debugger", open=False):
                    debug_input = gr.Textbox(
                        lines=15, 
                        label="Paste buggy code here"
                    )
                    debug_button = gr.Button("Debug Code")
                    debug_output = gr.Textbox(
                        label="Debug Output", 
                        lines=15
                    )

                    def debug_code(code):
                        prompt = (
                            "Please debug the following code. Explain what's wrong and provide a fixed version:\n\n"
                            f"```\n{code}\n```"
                        )
                        return ask_openrouter(prompt)

                    debug_button.click(fn=debug_code, inputs=debug_input, outputs=debug_output)
            
            gr.HTML("""
<link href="https://fonts.googleapis.com/css2?family=Anton&display=swap" rel="stylesheet">
<style>
@keyframes fadeZoomPulse {
  0% {
    opacity: 0;
    transform: scale(0.5);
    letter-spacing: 150px;
    text-shadow: none;
  }
  50% {
    opacity: 1;
    transform: scale(1.05);
    letter-spacing: 12px;
    text-shadow: 0 0 10px #ffffff, 0 0 20px #ffffff, 0 0 30px #ffffff;
  }
  100% {
    transform: scale(1);
    letter-spacing: 0px;
    text-shadow: 0 0 5px #ffffff, 0 0 10px #ffffff;
  }
}
#neon-text {
  color: #000000;
  font-size: 45px;
  font-family: 'Anton', sans-serif;
  text-align: center;
  letter-spacing: 0px;
  font-weight: 500;
  animation: fadeZoomPulse 8s ease-out forwards;
  margin-bottom: 20px;
}
</style>
<div id="neon-text">PR1ME</div>
            """)

        with gr.Tab("Chat History"):
            gr.Markdown("## Chat History Viewer and Resume")

            history_dropdown = gr.Dropdown(choices=list_chat_sessions(), label="Select a session")
            load_button = gr.Button("Load Chat")
            history_chatbot = gr.Chatbot(type="messages", label="Loaded Chat")
            resume_button = gr.Button("Resume in Chatbot")
            refresh_button = gr.Button("🔄 Refresh List")

            def load_selected_history(file_name):
                history = load_chat_session(file_name)
                return format_history_for_gradio(history), history

            def refresh_dropdown():
                return gr.update(choices=list_chat_sessions())

    
            load_button.click(fn=load_selected_history, inputs=history_dropdown, outputs=[history_chatbot, state])
            resume_button.click(fn=lambda history: (format_history_for_gradio(history), history), inputs=[state], outputs=[chatbot, state])
            refresh_button.click(fn=lambda: gr.update(choices=list_chat_sessions()), inputs=[], outputs=history_dropdown)
            
    return demo

create_chatbot().launch()