Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829309 unmodified lines4041424344454627 unmodified lines74757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431446 unmodified lines151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180import osimport functoolsimport tiktokenimport gradio as grfrom 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: Dict[str, Dict] = {"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 = os.getenv("OPENAI_MODEL_LIST", "gpt-4o,gpt-4o-mini,gpt-3.5-turbo")ALL_MODELS: List[str] = [m.strip() for m in _env.split(",") if m.strip() in MODEL_DETAILS]if not ALL_MODELS:ALL_MODELS = list(MODEL_DETAILS.keys())DEFAULT_MAX_CONTEXT = MODEL_DETAILS[ALL_MODELS[0]]["max_context"]BUFFER_TOKENS, DEFAULT_REPLY_MAX, TEMPERATURE = 500, 2048, 0.39 unmodified linesdef 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:27 unmodified linesraise 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.', Nonereturnif not client.api_key:yield history + [('', 'β API KEY MISSING')], '', 'π¨ Set API_KEY', Nonereturnif file:with open(file.name, 'r', encoding='utf-8') as f:content = f.read()user_msg += f"\n\n---FILE UPLOAD---\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]try:for part, _, m in safe_chat_stream(convo, ctx, rep, models):history[-1] = (user_msg, part)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 = Math.floor(c.width / 20); var drops = Array(cols).fill(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);// CRT flickersetInterval(function() { document.body.style.opacity = Math.random() > 0.95 ? '0.9' : '1'; }, 100);"""theme = gr.themes.Base(6 unmodified lines"#555555","#666666","#777777","#888888","#999999","#aaaaaa"))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(minimum=1000, maximum=DEFAULT_MAX_CONTEXT, step=256, value=DEFAULT_MAX_CONTEXT, label='Context')rep = gr.Slider(minimum=100, maximum=4096, step=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])if __name__ == '__main__':demo.launch()1234567891011121314151617181920212223249 unmodified lines343536373839404127 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381396 unmodified lines146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178import osimport functools\import tiktokenimport gradio as grfrom 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: Dict[str, Dict] = {"gpt-4o": {"input_price": 5.00, "output_price": 15.00, "max_context": 128000, "description": "OpenAI's most capable."},"gpt-4o-mini": {"input_price": 0.15, "output_price": 0.60, "max_context": 128000, "description": "Affordable & fast."},"gpt-3.5-turbo": {"input_price": 0.001, "output_price": 0.002,"max_context": 16385, "description": "General-purpose model."},}_env = os.getenv("OPENAI_MODEL_LIST", ",".join(MODEL_DETAILS.keys()))ALL_MODELS = [m.strip() for m in _env.split(",") if m.strip() 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.39 unmodified linesdef 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:27 unmodified linesraise last_exc or RuntimeError("All models failed.")# 4 Β· Gradio Chat Functionsdef chat_stream(user_msg: str, history: List[Dict], sys_prompt: str,sel_model: str, ctx: int, rep: int, file_upload) -> Tuple:user_msg = (user_msg or "").strip()if not user_msg and not file_upload:yield history, "", "β οΈ Enter a prompt or upload a file.", Nonereturnif not client.api_key:history.append({'role':'assistant','content':'β API KEY MISSING'})yield history, "", "π¨ Please set OPENAI_API_KEY.", Nonereturnif file_upload:try:content = open(file_upload.name, 'r', encoding='utf-8').read()user_msg += f"\n\n---FILE UPLOAD---\n{content}"except:passmessages = [{'role': 'system', 'content': sys_prompt}]messages += historymessages.append({'role': 'user', 'content': user_msg})history.append({'role':'user','content':user_msg})yield history, "", f"β³ Connecting to {sel_model}...", Nonemodels = [sel_model] + [m for m in ALL_MODELS if m != sel_model]try:combined = ''for part, _, m in safe_chat_stream(messages, ctx, rep, models):combined = parthistory[-1] = {'role':'assistant','content':combined}yield history, "", f"π‘ Streaming from {m}...", Noneyield history, "", "β Complete.", Noneexcept Exception as e:history[-1] = {'role':'assistant','content':f"β {e}"}yield history, "", f"π« Error: {e}", Nonedef clear_chat() -> Tuple:return [], "", "π Chat reset.", None# 5 Β· Ultra Synthwave CSS & JSCSS = """@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&display=swap');body { margin:0; overflow:hidden; 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:200px; height:200px; margin-left:-100px;border-radius:50%; background:radial-gradient(circle,#f0f,#900);box-shadow:0 0 50px #f0f,0 0 100px #f0f; animation:rotate 30s linear infinite; z-index:-1;}@keyframes rotate { from{transform:rotate(0deg);} to{transform:rotate(360deg);} }"""JS = """// Dark modedocument.documentElement.classList.add('dark');// Sun effectdocument.body.insertAdjacentHTML('beforeend', '<div id="sun"></div>');// Matrix rain setupconst canvas = document.createElement('canvas'); canvas.id = 'matrix'; document.body.appendChild(canvas);const ctx = canvas.getContext('2d'); function resize(){canvas.width=innerWidth;canvas.height=innerHeight;} window.addEventListener('resize',resize); resize();const cols = Math.floor(innerWidth/20), drops = Array(cols).fill(0);function draw(){ ctx.fillStyle='rgba(0,0,0,0.05)'; ctx.fillRect(0,0,canvas.width,canvas.height);ctx.fillStyle='#0f0'; ctx.font='20px monospace'; for(let i=0;i<cols;i++){ const char=String.fromCharCode(0x30A0+Math.random()*96);ctx.fillText(char,i*20,drops[i]*20);drops[i] = drops[i]*20>canvas.height||Math.random()>0.975?0:drops[i]+1;} }setInterval(draw,50);// CRT flickersetInterval(()=>document.body.style.opacity=Math.random()>0.95?0.9:1,100);"""theme = gr.themes.Base(6 unmodified lines"#555555","#666666","#777777","#888888","#999999","#aaaaaa"))with gr.Blocks(title="JadeGPT Synthwave Ultra", theme=theme, analytics_enabled=False) as demo:gr.HTML(f"""<style>{CSS}</style><script>{JS}</script><h1 style="text-align:center; margin-top:20px;">π JadeGPT ULTRA</h1>""")status = gr.Markdown('ποΈ SYSTEM ONLINE', elem_id='status')with gr.Tab('β‘ Chat'):sys = gr.Textbox(value="You are JadeGPT... Ultra Mode.", lines=2)chat = gr.Chatbot(type='messages', value=[], height=400)with gr.Row():inp = gr.Textbox(placeholder='Jack into the mainframe...')file_upload = gr.File(label='Upload File', type='filepath')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(minimum=1000, maximum=DEFAULT_MAX_CONTEXT, step=256, value=DEFAULT_MAX_CONTEXT, label='Context')rep = gr.Slider(minimum=100, maximum=4096, step=100, value=DEFAULT_REPLY_MAX, label='Max Reply')send.click(chat_stream, [inp, chat, sys, mdl, ctx, rep, file_upload], [chat, inp, status, file_upload])inp.submit(chat_stream, [inp, chat, sys, mdl, ctx, rep, file_upload], [chat, inp, status, file_upload])clear.click(clear_chat, [], [chat, inp, status, file_upload])if __name__ == '__main__':demo.launch()
app.py+70-72