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(""" """) gr.HTML("""