File size: 13,180 Bytes
ad409f8
ba8ab66
 
469a0ee
861e752
 
 
38666bb
 
 
0d7c97f
e21aedb
e8bc8c8
 
 
30964df
e8bc8c8
 
 
 
 
 
861e752
 
 
 
 
 
 
 
 
 
 
 
 
469a0ee
173a07e
 
 
469a0ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad409f8
469a0ee
 
 
 
 
 
909ea6c
469a0ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e82ec2
 
 
 
 
 
 
469a0ee
 
 
2276970
173a07e
2276970
 
 
469a0ee
 
 
173a07e
469a0ee
2276970
173a07e
469a0ee
 
 
2276970
173a07e
469a0ee
ad409f8
e756713
469a0ee
 
 
e756713
469a0ee
 
2276970
 
 
 
e756713
a5c72e9
e756713
469a0ee
 
 
 
 
 
 
 
 
 
 
173a07e
469a0ee
55b7d2a
173a07e
55b7d2a
 
 
 
 
9e82ec2
469a0ee
 
55b7d2a
469a0ee
55b7d2a
 
 
 
9e82ec2
84fe81b
38666bb
1045a67
a0d0957
68423f1
26754d2
 
b2c1cde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26754d2
a0d0957
00a41d3
0d7c97f
5d766de
2b652f9
7454a9e
469a0ee
173a07e
469a0ee
 
 
 
 
3804a35
469a0ee
 
 
 
 
173a07e
02b6b0e
34bbd0c
ebedd7c
17a35e0
ebedd7c
34bbd0c
ff37b57
ebedd7c
4af8cfd
0b9bb4d
23b1060
 
0b9bb4d
aedb120
aeae83d
e8bc8c8
7ee8f33
e8bc8c8
 
37504e2
7ee8f33
 
 
37504e2
 
 
e8bc8c8
861e752
 
3b0d93f
861e752
 
 
173a07e
db316be
173a07e
 
 
 
 
 
84fe81b
 
db316be
 
f72d3c8
7ee8f33
 
 
 
f72d3c8
627f309
f72d3c8
e3c3297
b93a136
 
 
 
f4f2274
b93a136
 
6b3346f
b93a136
 
 
6bb58a6
b93a136
1afdc29
469a0ee
 
32c2d30
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
import gradio as gr
import requests
import os
import speech_recognition as sr
import mimetypes
from PIL import Image
import pytesseract
import base64
import gradio as gr



def export_chat(history):
    from datetime import datetime
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    file_path = f"chat_history_{timestamp}.txt"
    with open(file_path, "w", encoding="utf-8") as f:
        for user_msg, bot_msg in history:
            f.write(f"User: {user_msg}\n")
            f.write(f"Bot: {bot_msg}\n\n")
    return file_path

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

def search_google(query):
    url = "https://google.serper.dev/search"
    headers = {"X-API-KEY": SERPER_API_KEY}
    data = {"q": query}
    try:
        res = requests.post(url, json=data, headers=headers)
        res.raise_for_status()
        results = res.json()
        snippets = []
        if "organic" in results:
            for r in results["organic"][:3]:
                snippets.append(f"- {r['title']}: {r['snippet']}")
        return "\n".join(snippets) if snippets else "No real-time info found."
    except requests.exceptions.RequestException as e:
        return f"Search failed: {e}"

def needs_search(text):
    trigger_words = ["today", "news", "latest", "who won", "trending", "current", "happening"]
    return any(word in text.lower() for word in trigger_words)

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. You should respond only in 15 words unless user is serious. 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 point wise. 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, 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 needs_search(message) 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()))

        # 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=gr.themes.Soft(), 
        css="""
        @import url('https://fonts.googleapis.com/css2?family=Michroma&display=swap');
        body {
            background-color: #e6ccff !important;
            font-family: 'Michroma', sans-serif !important;
            color: #b266ff !important;
            font-size: 12px !important;
            letter-spacing: 1.5px !important;
        }
        .gr-box {
            background-color: #f2e6ff !important;
            border: none !important;
        }
        textarea, input, .gr-textbox, .gr-dropdown, button, .gr-button {
            background-color: #f9f0ff !important;
            color: #b266ff !important;
            font-family: 'Michroma', sans-serif !important;
            border: 1px solid #cc99ff !important;
            font-size: 12px !important;
            letter-spacing: 1.5px !important;
        }
        .gr-chatbot {
            background-color: #e6ccff !important;
        }
        .message, label, h1, h2, h3, h4, h5, h6, p, span {
            font-family: 'Michroma', sans-serif !important;
            font-size: 12px !important;
            color: #b266ff !important;
            letter-spacing: 1.5px !important;
        }
        """
    ) as demo:

    
        chatbot = gr.Chatbot(type='messages')
        state = gr.State([]) 

        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
            )

        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.Column(scale=0, min_width=150):
                audio_input = gr.Audio(sources=["microphone"], type="filepath", visible=False)
                audio_btn = gr.Button("🎤")
            with gr.Column(scale=0, min_width=150):
                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)

        def handle_export(history):
            file_path = export_chat(history)
            return gr.update(value=file_path, visible=True)


            
        def respond(message, history, role, 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, None)
            return messages_for_gradio, updated_history
    
        def transcribe_and_respond(audio_file, history, role):
            message = transcribe_audio(audio_file)
            messages_for_gradio, updated_history = chat_with_ai(message, history, role, None)
            return message, messages_for_gradio, updated_history

        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(respond, [msg, state, role, audio_input, file_input], [chatbot, state])
        audio_input.stop_recording(transcribe_and_respond, [audio_input, state, role], [msg, chatbot, state])
        export_button.click(
            fn=handle_export,
            inputs=[state],
            outputs=[download_output],
            show_progress=True
        )
        
                
        gr.HTML("""
<link href="https://fonts.googleapis.com/css2?family=Tilt+Neon&display=swap" rel="stylesheet">
<style>
#neon-text {
  color: #b266ff; /* Light purple */
  font-size: 20px;
  font-family: 'Tilt Neon', sans-serif;
  text-align: center;
  letter-spacing: 10px; 
  font-weight: 300; /* Slim weight */
}
</style>
<div id="neon-text">NEON</div>
""")
    
    return demo

create_chatbot().launch()