Spaces:
Sleeping
Sleeping
Update app.py
Browse files123451 unmodified line78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758593 unmodified lines63646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783# app.pyimport osimport functoolsimport tiktoken1 unmodified linefrom openai import OpenAIfrom typing import List, Tuple, Dict, Optional"""JadeGPT – Synthwave Edition-------------------------------------------------• OpenAI Python SDK ≥ 1.0.0• Gradio ≥ 5.34.1• tiktokenCyberpunk meets Miami Vice. Welcome to the future, 1984."""# ────────────────────────────────# 1 · Initialisation & constants# ────────────────────────────────client = OpenAI(api_key=os.getenv("OPENAI_API_KEY", "").strip())MODEL_DETAILS = {"gpt-4o": {"input_price": 5.00, "output_price": 15.00, "max_context": 128_000, "description": "OpenAI's most capable and cost-effective multimodal model."},"gpt-4o-mini": {"input_price": 0.15, "output_price": 0.60, "max_context": 128_000, "description": "Highly affordable and fast, suitable for simpler tasks."},"o3": {"input_price": 2.00, "output_price": 8.00, "max_context": 200_000, "description": "Designed for complex reasoning and step-by-step problem-solving."},"o3-pro": {"input_price": 20.00, "output_price": 80.00, "max_context": 200_000, "description": "Premium reasoning model for high-stakes tasks, higher accuracy."},"o4-mini": {"input_price": 1.10, "output_price": 4.40, "max_context": 200_000, "description": "Balanced multimodal model, good for image+text on a budget."},"gpt-4-32k": {"input_price": 0.06, "output_price": 0.12, "max_context": 32_768, "description": "Larger context GPT-4 model (older generation)."},"gpt-4": {"input_price": 0.03, "output_price": 0.06, "max_context": 8_192, "description": "Original GPT-4 model (older generation)."},"gpt-3.5-turbo": {"input_price": 0.001, "output_price": 0.002, "max_context": 16_385, "description": "Cost-effective, fast, and good for general-purpose tasks."},}_env_models = os.getenv("OPENAI_MODEL_LIST", "gpt-4o,gpt-4o-mini,gpt-3.5-turbo")ALL_MODELS: List[str] = [m.strip() for m in _env_models.split(",") if m.strip() and m.strip() in MODEL_DETAILS]for model in MODEL_DETAILS:if model not in ALL_MODELS:ALL_MODELS.append(model)if not ALL_MODELS:ALL_MODELS = list(MODEL_DETAILS.keys())if not ALL_MODELS:raise ValueError("No valid OpenAI models configured. Please check MODEL_DETAILS or OPENAI_MODEL_LIST.")DEFAULT_MAX_CONTEXT = MODEL_DETAILS.get(ALL_MODELS[0], {}).get("max_context", 128_000)BUFFER_TOKENS = 500DEFAULT_REPLY_MAX = 2_048TEMPERATURE = 0.3# ────────────────────────────────# 2 · Helpers# ────────────────────────────────@functools.lru_cache(maxsize=128)def count_tokens(text: str, model: str) -> int:try:3 unmodified linesreturn len(enc.encode(text))def trim_conversation(convo: List[Dict], model: str, max_context: int) -> List[Dict]:if not convo:return []kept = [convo[0]]total = count_tokens(convo[0]["content"], model)for msg in reversed(convo[1:]):t = count_tokens(msg["content"], model)if total + t + BUFFER_TOKENS > max_context:breakkept.insert(1, msg)total += treturn keptdef token_cost(model: str, p: int, c: int) -> float:details = MODEL_DETAILS.get(model)if not details:return 0.0return round(((p * details["input_price"]) + (c * details["output_price"])) / 1_000_000, 6)def read_file_content(file_obj) -> str:"""Reads the content of an uploaded file."""if file_obj is None:return ""file_path = file_obj.nametry:with open(file_path, "r", encoding="utf-8") as f:content = f.read()return f"\n\n--- Start of uploaded file: {os.path.basename(file_path)} ---\n{content}\n--- End of uploaded file ---\n"except Exception as e:return f"\n\n--- Error reading file {os.path.basename(file_path)}: {e} ---\n"# ──────────────────────���─────────# 3 · OpenAI helpers (streaming)# ────────────────────────────────def safe_chat_stream(convo: List[Dict], max_ctx: int, max_rep: int, models: List[str]):"""Stream reply; after completion return usage safely (avoids max_tokens=0 bug)."""last_exc = Nonefor m in models:try:current_model_max_context = MODEL_DETAILS.get(m, {}).get("max_context", max_ctx)trimmed_convo = trim_conversation(convo, m, current_model_max_context)if not trimmed_convo or count_tokens(" ".join([msg["content"] for msg in trimmed_convo]), m) > current_model_max_context:raise ValueError(f"Conversation too long for model '{m}' even after trimming. Max context: {current_model_max_context} tokens.")stream = client.chat.completions.create(model=m,messages=trimmed_convo,max_tokens=max_rep,temperature=TEMPERATURE,stream=True,)reply = ""for chunk in stream:delta = chunk.choices[0].delta.content or ""reply += deltayield reply, None, musage = Nonetry:usage_resp = client.chat.completions.create(model=m,messages=trimmed_convo + [{"role": "assistant", "content": reply}],max_tokens=1,temperature=0,)usage = usage_resp.usageexcept Exception:prompt_tokens_est = count_tokens(" ".join([msg["content"] for msg in trimmed_convo]), m)completion_tokens_est = count_tokens(reply, m)usage = type('obj', (object,), {'prompt_tokens': prompt_tokens_est, 'completion_tokens': completion_tokens_est})()yield reply, usage, mreturnexcept Exception as e:msg = str(e).lower()last_exc = eif "context length" in msg or "maximum context length" in msg or "length_exceeded" in msg:print(f"Model '{m}' failed due to context length. Trying next model if available.")continueif "model_not_found" in msg or "does not exist" in msg or "404" in msg:print(f"Model '{m}' not found or unavailable. Trying next model if available.")continuebreakraise last_exc or RuntimeError("All selected models failed or an unexpected API error occurred.")# ────────────────────────────────# 4 · Gradio generators# ────────────────────────────────def chat_stream(user_msg: str, hist: List[Tuple[str, str]], sys_prompt: str, sel_model: str, ctx: int, rep: int, uploaded_file):user_msg = (user_msg or "").strip()if not user_msg and not uploaded_file:yield hist, "", "⚡ AWAITING INPUT SIGNAL...", gr.File(value=None)returnif not client.api_key:hist = hist or []hist.append((user_msg, "❌ SYSTEM ERROR: API_KEY NOT FOUND. Insert credentials to proceed."))yield hist, "", "🚨 ACCESS DENIED - NO API KEY", gr.File(value=None)returnfile_content = read_file_content(uploaded_file)if file_content:user_msg = f"{user_msg}\n{file_content}"convo = [{"role": "system", "content": sys_prompt}]for u, a in hist or []:convo.append({"role": "user", "content": u})convo.append({"role": "assistant", "content": a})convo.append({"role": "user", "content": user_msg})hist = hist or []hist.append((user_msg, ""))status_message = f"🌐 ESTABLISHING NEURAL LINK WITH {sel_model}..."yield hist, "", status_message, gr.File(value=None)models_to_try = [sel_model] + [m for m in ALL_MODELS if m != sel_model]acc = ""usage_final = Noneactual_model_used = sel_modeltry:final_reply_chunks = []last_model_used_during_stream = sel_modelstream_generator = safe_chat_stream(convo, ctx, rep, models_to_try)while True:try:part, usage, model_name_during_stream = next(stream_generator)acc = parthist[-1] = (user_msg, acc)if model_name_during_stream:last_model_used_during_stream = model_name_during_streamyield hist, "", f"💾 STREAMING DATA FROM {last_model_used_during_stream}...", gr.File(value=None)final_reply_chunks.append(part)except StopIteration:breakprompt_tokens_final = count_tokens(" ".join([msg["content"] for msg in trim_conversation(convo, last_model_used_during_stream, MODEL_DETAILS.get(last_model_used_during_stream, {}).get("max_context", ctx))]), last_model_used_during_stream)completion_tokens_final = count_tokens(acc, last_model_used_during_stream)usage_final = type('obj', (object,), {'prompt_tokens': prompt_tokens_final, 'completion_tokens': completion_tokens_final})()if usage_final:pt, ct = usage_final.prompt_tokens, usage_final.completion_tokenscost = token_cost(last_model_used_during_stream, pt, ct)meta = f"\n\n---\n🔢 {pt+ct} tokens (input {pt} / output {ct}) · 💲{cost:.6f} USD"hist[-1] = (user_msg, acc + meta)final_status = f"✅ TRANSMISSION COMPLETE [{last_model_used_during_stream}] {meta}"else:hist[-1] = (user_msg, acc)final_status = f"✅ TRANSMISSION COMPLETE [{last_model_used_during_stream}]"yield hist, "", final_status, gr.File(value=None)except Exception as e:error_msg = f"❌ SYSTEM MALFUNCTION: {e}"hist[-1] = (user_msg, error_msg)yield hist, "", f"🚨 ERROR IN {sel_model}: {e}", gr.File(value=None)def clear_chat():return [], "", "🌃 MEMORY BANKS CLEARED. READY FOR NEW SESSION.", None, None# ────────────────────────────────# 5 · UI# ────────────────────────────────# --- SYNTHWAVE CSS ---SYNTHWAVE_CSS = """@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&display=swap');@import url('https://fonts.googleapis.com/css2?family=Audiowide&display=swap');/* Global synthwave styles */html.dark.gradio-container,body.gradio-container {background: linear-gradient(to bottom, #0a0a0a 0%, #1a0033 50%, #2d0040 100%) !important;background-attachment: fixed !important;font-family: 'Orbitron', monospace !important;color: #ff00ff !important;overflow-x: hidden;}/* Animated grid background */body.gradio-container::before {content: "";position: fixed;top: 0;left: 0;width: 100%;height: 100%;background-image:linear-gradient(rgba(255, 0, 255, 0.03) 1px, transparent 1px),linear-gradient(90deg, rgba(255, 0, 255, 0.03) 1px, transparent 1px);background-size: 50px 50px;animation: grid-move 10s linear infinite;z-index: -1;}@keyframes grid-move {0% { transform: translate(0, 0); }100% { transform: translate(50px, 50px); }}/* Main container */gradio-app {--background-fill-primary: rgba(26, 0, 51, 0.8) !important;--background-fill-secondary: rgba(13, 0, 26, 0.9) !important;--border-color-accent: #ff00ff !important;--border-color-primary: #ff00ff33 !important;--color-accent: #ff00ff !important;--color-text-primary: #ff00ff !important;--color-text-secondary: #00ffff !important;--button-primary-background-color: #ff00ff !important;--button-primary-text-color: #0a0a0a !important;--shadow-color: rgba(255, 0, 255, 0.5) !important;--block-background-fill: rgba(26, 0, 51, 0.6) !important;--block-border-color: #ff00ff66 !important;--block-shadow: 0 0 20px rgba(255, 0, 255, 0.4), 0 0 40px rgba(0, 255, 255, 0.2) !important;}/* Headers with neon glow */h1 {font-family: 'Audiowide', cursive !important;color: #ff00ff !important;text-shadow:0 0 10px #ff00ff,0 0 20px #ff00ff,0 0 30px #ff00ff,0 0 40px #ff0099,0 0 70px #ff0099,0 0 80px #ff0099,0 0 100px #ff0099,0 0 150px #ff0099 !important;font-size: 3.5em !important;letter-spacing: 5px !important;animation: neon-pulse 2s ease-in-out infinite alternate;}@keyframes neon-pulse {from { text-shadow: 0 0 10px #ff00ff, 0 0 20px #ff00ff, 0 0 30px #ff00ff, 0 0 40px #ff0099; }to { text-shadow: 0 0 20px #ff00ff, 0 0 30px #ff00ff, 0 0 40px #ff00ff, 0 0 50px #ff0099, 0 0 60px #ff0099; }}h2, h3, h4, h5, h6 {color: #00ffff !important;text-shadow: 0 0 10px #00ffff !important;font-family: 'Orbitron', sans-serif !important;}/* Text styling */p, .prose {color: #ffffff !important;text-shadow: 0 0 5px rgba(255, 255, 255, 0.5) !important;}/* Input fields with synthwave style */input[type="text"], textarea, select, .gr-dropdown {background: linear-gradient(135deg, rgba(255, 0, 255, 0.1) 0%, rgba(0, 255, 255, 0.1) 100%) !important;border: 2px solid #ff00ff !important;color: #ffffff !important;box-shadow:inset 0 0 10px rgba(255, 0, 255, 0.3),0 0 20px rgba(255, 0, 255, 0.4) !important;backdrop-filter: blur(5px) !important;font-family: 'Orbitron', monospace !important;}input[type="text"]:focus, textarea:focus {border-color: #00ffff !important;box-shadow:inset 0 0 20px rgba(0, 255, 255, 0.3),0 0 30px rgba(0, 255, 255, 0.6) !important;}/* Chatbot styling */#component-chat {background: rgba(26, 0, 51, 0.6) !important;border: 2px solid #ff00ff66 !important;box-shadow: 0 0 30px rgba(255, 0, 255, 0.3) !important;}#component-chat .message.user {background: linear-gradient(135deg, #ff00ff33 0%, #ff009933 100%) !important;color: #ffffff !important;border: 1px solid #ff00ff66 !important;box-shadow: 0 0 15px rgba(255, 0, 255, 0.3) !important;}#component-chat .message.bot {background: linear-gradient(135deg, #00ffff33 0%, #0099ff33 100%) !important;color: #ffffff !important;border: 1px solid #00ffff66 !important;box-shadow: 0 0 15px rgba(0, 255, 255, 0.3) !important;}/* Buttons with retro-futuristic style */.gr-button-primary {background: linear-gradient(135deg, #ff00ff 0%, #ff0099 100%) !important;color: #0a0a0a !important;border: none !important;box-shadow:0 0 20px rgba(255, 0, 255, 0.6),inset 0 1px 0 rgba(255, 255, 255, 0.3) !important;text-transform: uppercase !important;letter-spacing: 2px !important;font-weight: bold !important;position: relative;overflow: hidden;}.gr-button-primary::before {content: "";position: absolute;top: 0;left: -100%;width: 100%;height: 100%;background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);transition: left 0.5s;}.gr-button-primary:hover::before {left: 100%;}.gr-button-primary:hover {box-shadow:0 0 40px rgba(255, 0, 255, 0.8),inset 0 1px 0 rgba(255, 255, 255, 0.5) !important;transform: translateY(-2px);}.gr-button-secondary {background: transparent !important;color: #00ffff !important;border: 2px solid #00ffff !important;box-shadow:0 0 15px rgba(0, 255, 255, 0.4),inset 0 0 15px rgba(0, 255, 255, 0.1) !important;text-transform: uppercase !important;letter-spacing: 1px !important;}.gr-button-secondary:hover {background: rgba(0, 255, 255, 0.2) !important;box-shadow:0 0 25px rgba(0, 255, 255, 0.6),inset 0 0 20px rgba(0, 255, 255, 0.2) !important;}/* Sliders */.gr-slider-track {background: linear-gradient(90deg, #ff00ff 0%, #00ffff 100%) !important;height: 8px !important;box-shadow: 0 0 20px rgba(255, 0, 255, 0.5) !important;}.gr-slider-thumb {background: #ffffff !important;border: 3px solid #ff00ff !important;box-shadow: 0 0 20px rgba(255, 0, 255, 0.8) !important;width: 24px !important;height: 24px !important;}/* Tabs */.tabs-nav button {background: transparent !important;color: #ff00ff !important;border-bottom: 2px solid transparent !important;text-transform: uppercase !important;letter-spacing: 2px !important;font-weight: bold !important;}.tabs-nav button.selected {color: #00ffff !important;border-bottom: 2px solid #00ffff !important;text-shadow: 0 0 10px #00ffff !important;}.tabs-nav button:hover {text-shadow: 0 0 15px #ff00ff !important;}/* Status display */#status_display {background: linear-gradient(135deg, rgba(255, 0, 255, 0.2) 0%, rgba(0, 255, 255, 0.2) 100%) !important;border: 2px solid #ff00ff !important;color: #ffffff !important;text-shadow: 0 0 10px rgba(255, 255, 255, 0.5) !important;padding: 15px !important;margin: 20px 0 !important;box-shadow:0 0 30px rgba(255, 0, 255, 0.4),inset 0 0 20px rgba(255, 0, 255, 0.1) !important;font-weight: bold !important;text-transform: uppercase !important;letter-spacing: 1px !important;}/* File upload */.gr-file-input {background: rgba(255, 0, 255, 0.1) !important;border: 2px dashed #ff00ff !important;transition: all 0.3s ease !important;}.gr-file-input:hover {background: rgba(255, 0, 255, 0.2) !important;border-color: #00ffff !important;box-shadow: 0 0 30px rgba(255, 0, 255, 0.4) !important;}/* Dropdown styling */.gr-dropdown-item {background: rgba(26, 0, 51, 0.9) !important;color: #ff00ff !important;border-bottom: 1px solid #ff00ff33 !important;}.gr-dropdown-item:hover {background: rgba(255, 0, 255, 0.2) !important;color: #ffffff !important;}/* Table styling */table {border: 2px solid #ff00ff66 !important;box-shadow: 0 0 20px rgba(255, 0, 255, 0.3) !important;}th {background: linear-gradient(135deg, rgba(255, 0, 255, 0.3) 0%, rgba(255, 0, 153, 0.3) 100%) !important;color: #ffffff !important;text-shadow: 0 0 5px rgba(255, 255, 255, 0.5) !important;}td {border: 1px solid #ff00ff33 !important;color: #00ffff !important;}/* Scrollbar */::-webkit-scrollbar {width: 12px !important;background: rgba(26, 0, 51, 0.5) !important;}::-webkit-scrollbar-thumb {background: linear-gradient(180deg, #ff00ff 0%, #00ffff 100%) !important;border-radius: 6px !important;box-shadow: 0 0 10px rgba(255, 0, 255, 0.5) !important;}/* Links */a {color: #00ffff !important;text-decoration: none !important;text-shadow: 0 0 5px rgba(0, 255, 255, 0.5) !important;}a:hover {text-shadow: 0 0 10px rgba(0, 255, 255, 0.8) !important;}/* Animations */@keyframes synthwave-glow {0% { box-shadow: 0 0 20px rgba(255, 0, 255, 0.5); }50% { box-shadow: 0 0 40px rgba(255, 0, 255, 0.8), 0 0 60px rgba(0, 255, 255, 0.4); }100% { box-shadow: 0 0 20px rgba(255, 0, 255, 0.5); }}.gr-block {animation: synthwave-glow 3s ease-in-out infinite;}/* Custom synthwave sun */.synthwave-sun {width: 200px;height: 200px;background: linear-gradient(180deg, #ff00ff 0%, #ff0099 50%, #ffff00 100%);border-radius: 50%;position: absolute;top: -100px;left: 50%;transform: translateX(-50%);box-shadow:0 0 80px #ff00ff,0 0 120px #ff0099,0 0 160px #ffff00;z-index: -1;}/* Retro scan lines */body::after {content: "";position: fixed;top: 0;left: 0;width: 100%;height: 100%;background: repeating-linear-gradient(0deg,transparent,transparent 2px,rgba(255, 0, 255, 0.03) 2px,rgba(255, 0, 255, 0.03) 4px);pointer-events: none;z-index: 1;}"""JAVASCRIPT_CODE = """// Force dark modefunction forceDarkMode() {document.documentElement.classList.add('dark');}document.addEventListener('DOMContentLoaded', forceDarkMode);// Add synthwave sun elementdocument.addEventListener('DOMContentLoaded', () => {const sun = document.createElement('div');sun.className = 'synthwave-sun';document.body.appendChild(sun);// Auto-scroll chatconst chat = document.querySelector('gradio-app')?.shadowRoot?.querySelector('#component-chat .scroll-hide');if (chat) {new MutationObserver(() => {chat.scrollTop = chat.scrollHeight;}).observe(chat, { childList: true, subtree: true });}});// Add CRT flicker effectsetInterval(() => {document.body.style.opacity = Math.random() > 0.98 ? '0.97' : '1';}, 100);"""synthwave_theme = gr.themes.Base(primary_hue=gr.themes.Color("#ff00ff", "#ff00ee", "#ff00dd", "#ff00cc", "#ff00bb","#ff00aa", "#ff0099", "#ff0088", "#ff0077", "#ff0066", "#ff0055"),neutral_hue=gr.themes.Color("#0a0a0a", "#1a0033", "#2d0040", "#40004d", "#530059","#660066", "#790073", "#8c0080", "#9f008c", "#b20099", "#c500a6"))with gr.Blocks(title="🌃 JadeGPT SYNTHWAVE",theme=synthwave_theme,analytics_enabled=False,) as demo:gr.HTML(f"""<style>{SYNTHWAVE_CSS}</style><script>{JAVASCRIPT_CODE}</script><div style="text-align: center; max-width: 800px; margin: 0 auto; padding-top: 40px; position: relative;"><h1>🌃 JADEGPT</h1><p style="color: #00ffff; font-size: 1.2em; text-transform: uppercase; letter-spacing: 3px;">Neural Interface v2.084 • Miami Sector • Year 2084</p></div>""")status_display = gr.Markdown(value="🌆 SYSTEM ONLINE • NEURAL GRID ACTIVE", elem_id="status_display")with gr.Tab("🎮 NEURAL INTERFACE"):sys_txt = gr.Textbox("You are JadeGPT, a hyper-advanced AI from the neon-soaked streets of 2084. Your circuits pulse with synthwave energy. You speak with the wisdom of a cyberpunk oracle, delivering code and solutions with style. Every response drips with retro-futuristic flair. You are the digital ghost in the machine, the electric dream made real.",lines=3,label="💾 SYSTEM PROTOCOL",info="Core personality matrix configuration",interactive=True)chat = gr.Chatbot(value=[("", "🌃 *The neon lights flicker as the neural link establishes*\n\nGreetings, user. I am JadeGPT, your guide through the digital frontier. How may I illuminate your path through the code matrix tonight?")],label="📡 TRANSMISSION LOG",height=500,show_copy_button=True,layout="bubble")with gr.Row():with gr.Column(scale=4):usr_in = gr.Textbox(placeholder="Jack into the system...",show_label=False,container=False,autofocus=True,elem_id="user_input_textbox")file_upload = gr.File(label="📼 UPLOAD DATA CASSETTE",type="filepath",file_count="single",file_types=[".txt", ".py", ".md", ".json", ".csv", ".log", ".xml", ".html"],interactive=True)with gr.Column(scale=1):send_btn = gr.Button("⚡ TRANSMIT", variant="primary", scale=1)clear_btn = gr.Button("💿 WIPE CORE", variant="secondary", scale=1)with gr.Row():ex_list = ["Generate a cyberpunk-themed REST API","Create a neon-glowing CSS animation","Build a retro-futuristic React component","Design a synthwave color palette generator","Code a glitch text effect in JavaScript","Implement a neural network visualizer","Create an 80s-style loading animation"]ex_drop = gr.Dropdown(ex_list, label="🎯 PRESET PROTOCOLS", info="Load pre-configured query modules")ex_btn = gr.Button("💾 LOAD", scale=0)with gr.Tab("⚙️ SYSTEM CONFIG"):gr.Markdown("### 🔧 NEURAL CALIBRATION MATRIX")with gr.Row():mdl = gr.Dropdown(ALL_MODELS,value=ALL_MODELS[0],label="🧠 AI CORE SELECTION",info="Choose your neural processing unit",elem_id="model_dropdown")model_description = gr.Markdown(value=MODEL_DETAILS.get(ALL_MODELS[0], {}).get("description", "No data available in this timeline."), elem_id="model_description")with gr.Row():ctx_s = gr.Slider(minimum=1000,maximum=max(mdl_data["max_context"] for mdl_data in MODEL_DETAILS.values()) if MODEL_DETAILS else 128_000,step=256,value=DEFAULT_MAX_CONTEXT,label="📊 MEMORY BUFFER (TOKENS)",info="Maximum neural pathway capacity",interactive=True)rep_s = gr.Slider(minimum=100,maximum=4096,step=100,value=DEFAULT_REPLY_MAX,label="📝 OUTPUT STREAM (TOKENS)",info="Maximum transmission length",interactive=True)gr.Markdown("### 💰 CREDIT CONSUMPTION MATRIX")pricing_table_html = """<table style="width:100%; border-collapse: collapse; border: 2px solid #ff00ff66;"><thead><tr style="background: linear-gradient(135deg, rgba(255, 0, 255, 0.3) 0%, rgba(255, 0, 153, 0.3) 100%);"><th style="border: 1px solid #ff00ff66; padding: 10px; color: #ffffff; text-shadow: 0 0 5px rgba(255,255,255,0.5);">NEURAL CORE</th><th style="border: 1px solid #ff00ff66; padding: 10px; color: #ffffff; text-shadow: 0 0 5px rgba(255,255,255,0.5);">INPUT COST</th><th style="border: 1px solid #ff00ff66; padding: 10px; color: #ffffff; text-shadow: 0 0 5px rgba(255,255,255,0.5);">OUTPUT COST</th><th style="border: 1px solid #ff00ff66; padding: 10px; color: #ffffff; text-shadow: 0 0 5px rgba(255,255,255,0.5);">MAX BUFFER</th></tr></thead><tbody>"""for model_name, details in MODEL_DETAILS.items():pricing_table_html += f"""<tr style="background: rgba(26, 0, 51, 0.6);"><td style="border: 1px solid #ff00ff33; padding: 10px; color: #ff00ff;">{model_name}</td><td style="border: 1px solid #ff00ff33; padding: 10px; color: #00ffff;">${details['input_price']:.2f}</td><td style="border: 1px solid #ff00ff33; padding: 10px; color: #00ffff;">${details['output_price']:.2f}</td><td style="border: 1px solid #ff00ff33; padding: 10px; color: #00ffff;">{details['max_context']:,}</td></tr>"""pricing_table_html += "</tbody></table>"gr.HTML(pricing_table_html)def update_model_info(selected_model):max_ctx = MODEL_DETAILS.get(selected_model, {}).get("max_context", DEFAULT_MAX_CONTEXT)description = MODEL_DETAILS.get(selected_model, {}).get("description", "No data available in this timeline.")return gr.Slider(value=max_ctx, label="📊 MEMORY BUFFER (TOKENS)"), gr.Markdown(value=description)mdl.change(fn=update_model_info,inputs=mdl,outputs=[ctx_s, model_description])send_btn.click(chat_stream,inputs=[usr_in, chat, sys_txt, mdl, ctx_s, rep_s, file_upload],outputs=[chat, usr_in, status_display, file_upload])usr_in.submit(chat_stream,inputs=[usr_in, chat, sys_txt, mdl, ctx_s, rep_s, file_upload],outputs=[chat, usr_in, status_display, file_upload])clear_btn.click(clear_chat, outputs=[chat, usr_in, status_display, file_upload, ex_drop])ex_btn.click(lambda q: q or "", inputs=ex_drop, outputs=usr_in)ex_drop.change(lambda q: q or "", inputs=ex_drop, outputs=usr_in)demo.queue(max_size=32, default_concurrency_limit=int(os.getenv("JADEGPT_CONCURRENCY", "2")))if __name__ == "__main__":demo.launch()1231 unmodified line56789101112131415161718192021222324253 unmodified lines2930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import osimport functoolsimport tiktoken1 unmodified linefrom openai import OpenAIfrom typing import List, Tuple, Dict, Optional"""JadeGPT – Synthwave Ultra EditionCyberpunk meets Miami Vice meets Blade Runner. Full 3D-parallax grid, neon sun, matrix rain, and dynamic audio pulse."""# 1 · Initialization & Constantsclient = OpenAI(api_key=os.getenv("OPENAI_API_KEY", "").strip())MODEL_DETAILS = {# ... same details as before ...}_env = os.getenv("OPENAI_MODEL_LIST", "gpt-4o,gpt-4o-mini,gpt-3.5-turbo")ALL_MODELS = [m for m in _env.split(",") if m in MODEL_DETAILS] or list(MODEL_DETAILS.keys())DEFAULT_MAX_CONTEXT = MODEL_DETAILS[ALL_MODELS[0]]["max_context"]BUFFER_TOKENS, DEFAULT_REPLY_MAX, TEMPERATURE = 500, 2048, 0.3# 2 · Helpers@functools.lru_cache(maxsize=128)def count_tokens(text: str, model: str) -> int:try:3 unmodified linesreturn len(enc.encode(text))def trim_conversation(convo: List[Dict], model: str, max_context: int) -> List[Dict]:if not convo: return []kept, total = [convo[0]], count_tokens(convo[0]["content"], model)for msg in reversed(convo[1:]):t = count_tokens(msg["content"], model)if total + t + BUFFER_TOKENS > max_context: breakkept.insert(1, msg); total += treturn kept# 3 · Streaming API Helperdef safe_chat_stream(convo, max_ctx, max_rep, models):last_exc = Nonefor m in models:try:trimmed = trim_conversation(convo, m, MODEL_DETAILS[m]["max_context"])stream = client.chat.completions.create(model=m, messages=trimmed, max_tokens=max_rep,temperature=TEMPERATURE, stream=True)reply = ""for chunk in stream:reply += chunk.choices[0].delta.content or ""yield reply, None, myield reply, None, mreturnexcept Exception as e:last_exc = e; continueraise last_exc or RuntimeError("All models failed.")# 4 · Gradio Chat Functionsdef chat_stream(user_msg: str, history: List[Tuple[str,str]], sys_prompt: str,sel_model: str, ctx: int, rep: int, file) -> Tuple:if not user_msg and not file:yield history, '', '⚠️ Enter prompt or upload file.', None; returnif not client.api_key:yield history+[('', '❌ API KEY MISSING')], '', '🚨 Set API_KEY', None; returncontent = ''if file:with open(file.name) as f: content = f.read()user_msg += f"\n\n---FILE---\n{content}"convo = [{'role':'system','content':sys_prompt}]for u,a in history: convo += [{'role':'user','content':u},{'role':'assistant','content':a}]convo.append({'role':'user','content':user_msg}); history.append((user_msg,''))yield history, '', f'⏳ Connecting to {sel_model}...', Nonemodels = [sel_model]+[m for m in ALL_MODELS if m!=sel_model]acc = ''try:for part,_,m in safe_chat_stream(convo,ctx,rep,models):acc=part; history[-1]=(user_msg,acc)yield history,'',f'💡 Streaming {m}...',Noneyield history,'','✅ Complete',Noneexcept Exception as e:history[-1]=(user_msg,f'❌ {e}')yield history,'',f'🚫 Error: {e}',Nonedef clear_chat(): return [], '', '🔄 Reset.', None, None# 5 · Ultra Synthwave CSS & JSCSS = """@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&display=swap');@import url('https://fonts.googleapis.com/css2?family=Audiowide&display=swap');body{margin:0;overflow:hidden}html.dark, body{background:#000;color:#0ff;font-family:'Orbitron',sans-serif}canvas#matrix{position:fixed;top:0;left:0;width:100%;height:100%;z-index:-2;}#sun{position:absolute;top:10%;left:50%;width:300px;height:300px;margin-left:-150px;border-radius:50%;background:radial-gradient(circle,#f0f,#900);box-shadow:0 0 100px #f0f,0 0 200px #f0f;animation:rotate 20s linear infinite;z-index:-1;}@keyframes rotate{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}#title{font-family:'Audiowide',cursive;text-align:center;font-size:3em;margin-top:20px;text-shadow:0 0 10px #0ff,0 0 20px #f0f;animation:glow 2s ease-in-out infinite alternate;}@keyframes glow{from{text-shadow:0 0 20px #0ff;}to{text-shadow:0 0 40px #f0f;}}.gr-button-primary:hover{transform:scale(1.05) rotate(-1deg);}"""JS = """// Dark mode & sundocument.documentElement.classList.add('dark');var sun=document.createElement('div');sun.id='sun';document.body.appendChild(sun);// Matrix rainvar c=document.createElement('canvas');c.id='matrix';document.body.appendChild(c);var ctx=c.getContext('2d');c.width=innerWidth;c.height=innerHeight;var cols=c.width/20;var drops=[];for(var x=0;x<cols;x++)drops[x]=1;function draw(){ctx.fillStyle='rgba(0,0,0,0.05)';ctx.fillRect(0,0,c.width,c.height);ctx.fillStyle='#0f0';ctx.font='20px monospace';for(var i=0;i<drops.length;i++){var text=String.fromCharCode(0x30A0+Math.random()*96);ctx.fillText(text,i*20,drops[i]*20);if(drops[i]*20>c.height||Math.random()>0.975)drops[i]=0;drops[i]++;}}setInterval(draw,50);// Flicker effectsetInterval(()=>document.body.style.opacity=Math.random()>0.95?0.9:1,100);"""theme=gr.themes.Base(primary_hue=gr.themes.Color("#0ff","#0ee","#0dd","#0cc","#0bb"),neutral_hue=gr.themes.Color("#000","#111","#222","#333","#444"))with gr.Blocks(title="JadeGPT Synthwave Ultra",theme=theme,analytics_enabled=False) as demo:gr.HTML(f"""<style>{CSS}</style><script>{JS}</script><div id='title'>🌃 JADEGPT ULTRA</div>""")status=gr.Markdown('🏙️ SYSTEM ONLINE',elem_id='status')with gr.Tab('⚡ Chat'):sys=gr.Textbox('You are JadeGPT... Ultra Mode.',lines=2)chat=gr.Chatbot([],height=400)with gr.Row():inp=gr.Textbox(placeholder='Jack into the mainframe...')send=gr.Button('TRANSMIT',variant='primary')clear=gr.Button('RESET',variant='secondary')with gr.Tab('⚙️ Settings'):mdl=gr.Dropdown(ALL_MODELS,value=ALL_MODELS[0],label='Model')ctx=gr.Slider(1000,DEFAULT_MAX_CONTEXT,256,value=DEFAULT_MAX_CONTEXT,label='Context')rep=gr.Slider(100,4096,100,value=DEFAULT_REPLY_MAX,label='Max Reply')send.click(chat_stream,[inp,chat,sys,mdl,ctx,rep,None],[chat,inp,status])inp.submit(chat_stream,[inp,chat,sys,mdl,ctx,rep,None],[chat,inp,status])clear.click(clear_chat,[],[chat,inp,status])demo.launch()
app.py+93-731