Neon / app.py
ONEROCKS's picture
Update app.py
0d7c97f verified
Raw History Blame Contribute Delete
13.2 kB
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()