Download app.py from ONEROCKS/PRIME: direct link, hf CLI and curl.
- Browser
- Download file 30.2 kB
-
https://huggingface.co/spaces/ONEROCKS/PRIME/resolve/main/app.py
- Command line
-
hf download hf://spaces/ONEROCKS/PRIME/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ONEROCKS/PRIME/resolve/main/app.py
30.2 kB
| 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() |