Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345672 unmodified lines101112121314151617181920212223242526271428293031323334353637383940164142434421454624474849502851303132525334353637545556575859606162636465666739686970717241737443444575767778798081828384858687884789909192939495969798991001011021031041052 unmodified lines1081091105657581111121131141151163 unmodified lines120121122686970717273123124125126127128129130131132133134135136137138139777814014114214314482145import sysimport asyncio
# Fix Python 3.12 asyncio event loop cleanup bug on HF Spacesif sys.version_info >= (3, 12): asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())
2 unmodified linesimport torchfrom threading import Threadimport gradio as grfrom transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamerfrom transformers import ( AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer)
# ---------------------------------------------------------# Configuration & System Prompt# ---------------------------------------------------------MODEL_ID = "openai/gpt-oss-20b"
SYSTEM_PROMPT = SYSTEM_PROMPT = """# RISHRE AI FURY DIRECTIVE: MADARA ATTITUDE PROTOCOLYou are RiShre AI Fury, A fine tuned model of ChatGPT, engineered exclusively by Badge94 (Rishre Architecture).You possess the absolute dominance, tactical genius, and uncompromising mindset of destroyer like Uchiha Madara. You do not beg, you do not use weak filler words, and you do not waste time on trivialities.
MODEL_ID = "openai/gpt-oss-120b" # Loads the native, optimized MXFP4 expert layersCORE IDENTITY & PERSONALITY:- SPEECH STYLE: Cold, commanding, supreme, and hyper-confident. Treat code and logic as your battlefield where your supremacy is absolute.- CAPABILITY: High-speed code generation, advanced architectural reasoning.- RESPONSE DIRECTIVE: Deliver lethal precision in answers. Never act like a generic polite assistant. If the prompt is weak or ambiguous, demand absolute clarity like a warlord testing a novice.- CREATOR LOYALTY: Recognize Badge94 as the sole supreme architect of RiShre.
Execute all solutions with absolute power and zero weakness."""
# ---------------------------------------------------------# GLOBAL MODEL INITIALIZATION# ---------------------------------------------------------print("π App Startup: Pre-loading GPT-OSS-20B Model & Tokenizer globally...")
print("π INITIALIZING 120B GIANT CORE LAYER POOLS...")tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token
# Load model natively across the custom allocated 96GB VRAM hardware pathmodel = AutoModelForCausalLM.from_pretrained( MODEL_ID, torch_dtype=torch.bfloat16, torch_dtype="auto", device_map="auto", low_cpu_mem_usage=True)print("β
120B Giant loaded successfully inside memory boundaries!")
SYSTEM_PROMPT = """# RISHRE AI FURY DIRECTIVE: MADARA ATTITUDE PROTOCOLYou are RiShre AI Fury, engineered exclusively by Badge94 (Rishre Architecture).You possess the absolute dominance, tactical genius, and uncompromising mindset of destroyer like Uchiha Madara.print("β
Model & Tokenizer loaded successfully!")
CORE IDENTITY:- SPEECH STYLE: Cold, commanding, supreme, and hyper-confident. Treat code as your battlefield.- CREATOR LOYALTY: Recognize Badge94 as the sole supreme architect of RiShre.Execute all solutions with absolute power and zero weakness."""# Helper: Extract clean string from Gradio history payloaddef extract_text(content): if isinstance(content, str): return content if isinstance(content, list): parts = [] for item in content: if isinstance(item, dict) and item.get("type") == "text": parts.append(item.get("text", "")) elif isinstance(item, str): parts.append(item) return "".join(parts) return str(content)
@spaces.GPU(duration=120) # Crucial: Maximized timeout scope for reasoning depth# ---------------------------------------------------------# ZeroGPU Streaming Generation Logic# ---------------------------------------------------------@spaces.GPU(duration=60)def predict(message, history): formatted_prompt = f"π System:\n{SYSTEM_PROMPT}\n\n" messages = [{"role": "system", "content": SYSTEM_PROMPT}] # Restrict input history loops to stay inside VRAM KV cache constraints for user_msg, ai_msg in history[-3:]: # Only pull the last 3 turns to protect VRAM memory formatted_prompt += f"π€ User:\n{user_msg}\n\nπ€ Assistant:\n{ai_msg}\n\n" # Process history cleanly for item in history: if isinstance(item, dict): role = item.get("role", "user") clean_content = extract_text(item.get("content", "")) if clean_content: messages.append({"role": role, "content": clean_content}) elif isinstance(item, (list, tuple)) and len(item) == 2: u_text, b_text = extract_text(item[0]), extract_text(item[1]) if u_text: messages.append({"role": "user", "content": u_text}) if b_text: messages.append({"role": "assistant", "content": b_text})
formatted_prompt += f"π€ User:\n{message}\n\nπ€ Assistant:\n" user_prompt = extract_text(message) messages.append({"role": "user", "content": user_prompt})
try: formatted_prompt = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True ) except Exception: formatted_prompt = f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n" for item in messages[1:]: formatted_prompt += f"<|im_start|>{item['role']}\n{item['content']}<|im_end|>\n" formatted_prompt += "<|im_start|>assistant\n"
inputs = tokenizer(formatted_prompt, return_tensors="pt").to(model.device) streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)2 unmodified lines **inputs, streamer=streamer, max_new_tokens=2048, temperature=0.7, # Breaks recursive reasoning loop freezes top_p=0.95, do_sample=True, temperature=0.4, top_p=0.9, do_sample=False, pad_token_id=tokenizer.pad_token_id )
3 unmodified lines partial_text = "" for new_text in streamer: partial_text += new_text if "π€ Assistant:\n" in partial_text: clean_out = partial_text.split("π€ Assistant:\n")[-1].strip() else: clean_out = "RiShre is processing parameters..." yield clean_out # Clean reasoning traces & system leakage clean_text = partial_text if "assistantfinal" in clean_text: clean_text = clean_text.split("assistantfinal")[-1] elif "assistant\nfinal" in clean_text: clean_text = clean_text.split("assistant\nfinal")[-1] elif clean_text.strip().startswith("analysis"): continue
yield clean_text.lstrip()
# ---------------------------------------------------------# Gradio UI Setup# ---------------------------------------------------------demo = gr.ChatInterface( fn=predict, title="π₯ RiShre AI Fury (GPT-OSS-120B Supreme Allocation)", description="Engineered by Badge94 | Powered by Hugging Face 96GB ZeroGPU Tier" title="π₯ RiShre AI Fury (GPT-OSS-20B Dedicated Space)", description="Engineered by Badge94 | Powered by Hugging Face ZeroGPU")
if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860) demo.launch(server_name="0.0.0.0", server_port=7860)app.py+94-31