Upload folder using huggingface_hub
Browse filesFiles changed (2)
- app.py+191-285
- requirements.txt+1-6
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304import gradio as grimport torchimport requestsimport jsonimport timeimport threadingfrom transformers import AutoModelForCausalLM, AutoTokenizerfrom peft import PeftModel# โโ Config โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโBASE_MODEL = "Qwen/Qwen2.5-0.5B"PEFT_REPO = "coderofpears/gimkit-copilot"SB_URL = "https://unztspukhwdzrllavnef.supabase.co"SB_ANON = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InVuenRzcHVraHdkenJsbGF2bmVmIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzM2MDMzNTAsImV4cCI6MjA4OTE3OTM1MH0.eUWx9O9uX-BqI7oUikVvSAwljgt4Gw3Fl6hb-Xz_YWo"ALL_TOOLS = ["gkc_create_build","gkc_undo_last_build","gkc_get_map_devices","gkc_look_around","gkc_capture_screenshot","gkc_remove_elements","gkc_vc_checkpoint","gkc_list_devices","gkc_search_terrain","gkc_search_props","gkc_get_device_info","gkc_skill_search","gkc_web_search","gkc_wiki_search",]TOOL_DESCRIPTIONS = {"gkc_create_build": "Place devices/wires on the map","gkc_undo_last_build": "Undo the last build","gkc_get_map_devices": "List all devices currently on the map","gkc_look_around": "Screenshot the area around the player","gkc_capture_screenshot":"Take a screenshot of a specific area","gkc_remove_elements": "Remove devices, tiles, or wires","gkc_vc_checkpoint": "Save a version-control checkpoint","gkc_list_devices": "Search available device types","gkc_search_terrain": "Search available terrain types","gkc_search_props": "Search available prop types","gkc_get_device_info": "Get options/schema for a device type","gkc_skill_search": "Search Gimkit Creative skills/docs","gkc_web_search": "Search the web","gkc_wiki_search": "Search the GKC wiki",}# โโ Load model once at startup โโโโโโโโโโโโโโโโโโ๏ฟฝ๏ฟฝ๏ฟฝโโโโโโโโโโโโโโโโโโโโโโโโโโโโโprint("Loading modelโฆ")tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, trust_remote_code=True)if tokenizer.pad_token is None:tokenizer.pad_token = tokenizer.eos_token_base = AutoModelForCausalLM.from_pretrained(BASE_MODEL,torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,device_map="auto" if torch.cuda.is_available() else None,trust_remote_code=True,)model = PeftModel.from_pretrained(_base, PEFT_REPO)model.eval()print("Model ready.")DEVICE = next(model.parameters()).device# โโ Supabase helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdef base_h():return {"Content-Type":"application/json","apikey":SB_ANON}def auth_h(token):return {**base_h(),"Authorization":"Bearer "+token}def sb_sign_in(email, password):r = requests.post(SB_URL+"/auth/v1/token?grant_type=password",headers=base_h(),json={"email":email,"password":password},timeout=10,)d = r.json()if not r.ok:raise Exception(d.get("error_description") or d.get("message") or r.text)return d["access_token"], d["user"]["email"]def queue_tool(token, name, args, timeout=30):"""Insert a pending tool_call row and wait for the plugin to execute it."""r = requests.post(SB_URL+"/rest/v1/tool_calls",headers={**auth_h(token),"Prefer":"return=representation"},json={"name":name,"args":args,"status":"pending"},timeout=10,)r.raise_for_status()row_id = r.json()[0]["id"]deadline = time.time() + timeoutwhile time.time() < deadline:time.sleep(1.2)pr = requests.get(SB_URL+f"/rest/v1/tool_calls?id=eq.{row_id}&select=status,result",headers=auth_h(token), timeout=10,)pr.raise_for_status()rows = pr.json()if rows and rows[0]["status"] in ("complete","error"):return rows[0]["result"], rows[0]["status"]return {"error":"Timed out โ is the plugin open and connected?"}, "error"# โโ Model inference โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโSYSTEM = ("You are Gimkit Copilot, an AI assistant for building Gimkit Creative maps. ""You can call tools by responding with JSON like: "'{"tool":"<tool_name>","args":{...}} '"Otherwise reply normally. Available tools: "+", ".join(ALL_TOOLS))def run_model(history, user_msg):"""Run one forward pass. Returns the raw model string."""prompt = SYSTEM + "\n\n"for u, a in history:prompt += f"User: {u}\nAssistant: {a}\n"prompt += f"User: {user_msg}\nAssistant:"inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024).to(DEVICE)with torch.no_grad():out = model.generate(**inputs,max_new_tokens=256,do_sample=True,temperature=0.7,top_p=0.9,pad_token_id=tokenizer.eos_token_id,eos_token_id=tokenizer.eos_token_id,)new_tokens = out[0][inputs["input_ids"].shape[1]:]return tokenizer.decode(new_tokens, skip_special_tokens=True).strip()def try_parse_tool_call(text):"""Return (tool_name, args) if the model output is a tool call JSON, else None."""text = text.strip()# find first { ... }start = text.find("{")end = text.rfind("}") + 1if start == -1 or end == 0:return Nonetry:obj = json.loads(text[start:end])if "tool" in obj and obj["tool"] in ALL_TOOLS:return obj["tool"], obj.get("args", {})except Exception:passreturn None# โโ Chat handler โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdef respond(message, history, token):if not token:history.append((message, "โ Please sign in first (use the Sign In tab)."))return history# 1. Run the fine-tuned modelmodel_out = run_model(history, message)# 2. Check if the model wants to call a tooltool_call = try_parse_tool_call(model_out)if tool_call:tool_name, args = tool_callhistory.append((message, f"๐ง Calling `{tool_name}`โฆ"))result, status = queue_tool(token, tool_name, args)icon = "โ " if status == "complete" else "โ"result_text = json.dumps(result, indent=2) if isinstance(result, dict) else str(result)# Feed result back into model for a final natural-language replyfollowup = run_model(history + [(message, model_out)],f"Tool result for {tool_name}: {result_text}. Summarise what happened.")history[-1] = (message, f"๐ง Called `{tool_name}`\n\n{icon} {result_text}\n\n{followup}")else:history.append((message, model_out))return history# โโ UI โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโCSS = """@import url('https://fonts.googleapis.com/css2?family=Space+Mono:ital,wght@0,400;0,700;1,400&family=DM+Sans:wght@300;400;500;600&display=swap');:root{--bg:#070b07;--surface:#0c120c;--border:#162016;--green:#4CAF50;--green-dim:#1a3a1a;--green-glow:rgba(76,175,80,.15);--text:#cce0cc;--muted:#4a664a;--accent:#a3e635;--warn:#f59e0b;}body,.gradio-container{background:var(--bg)!important;font-family:'DM Sans',sans-serif;color:var(--text);}.gr-box,.gr-panel{background:var(--surface)!important;border-color:var(--border)!important;}#title{font-family:'Space Mono',monospace;color:var(--green);font-size:26px;font-weight:700;letter-spacing:-1px;padding:24px 0 4px;text-align:center;}#subtitle{color:var(--muted);font-size:13px;text-align:center;margin-bottom:28px;font-family:'Space Mono',monospace;}.gr-button.primary{background:var(--green-dim)!important;border:1px solid var(--green)!important;color:var(--green)!important;font-family:'Space Mono',monospace!important;font-weight:700!important;}.gr-button.primary:hover{background:#223a22!important;}.gr-button.secondary{background:#0a100a!important;border:1px solid var(--border)!important;color:var(--muted)!important;font-family:'Space Mono',monospace!important;}.gr-textbox textarea,.gr-textbox input{background:#050a05!important;border:1px solid var(--border)!important;color:var(--accent)!important;font-family:'Space Mono',monospace!important;font-size:12px!important;}.gr-textbox textarea:focus,.gr-textbox input:focus{border-color:var(--green)!important;box-shadow:0 0 0 2px var(--green-glow)!important;}#chatbot{background:var(--bg)!important;border-color:var(--border)!important;}#chatbot .message.user{background:#0d1a0d!important;border:1px solid var(--border)!important;color:var(--text)!important;}#chatbot .message.bot{background:var(--surface)!important;border:1px solid var(--border)!important;color:var(--text)!important;}.status-dot{display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:6px;}.connected{background:#4CAF50;box-shadow:0 0 6px #4CAF50;}.disconnected{background:#333;}"""with gr.Blocks(css=CSS, title="Gimkit Copilot") as demo:token_state = gr.State("")gr.HTML('<div id="title">โ Gimkit Copilot</div>')gr.HTML('<div id="subtitle">Fine-tuned Qwen2.5 ยท GimkitCopilot MCP</div>')with gr.Tabs():# โโ Sign In tab โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโwith gr.Tab("๐ Sign In"):gr.Markdown("Sign in with your **GimkitCopilot account** ""(same credentials as the Gimloader plugin). \n""The Gimloader plugin must be **open and connected** in Gimkit Creative ""for map tools to work.")with gr.Row():email_in = gr.Textbox(label="Email", placeholder="you@example.com")pass_in = gr.Textbox(label="Password", placeholder="โขโขโขโขโขโขโขโข", type="password")signin_btn = gr.Button("Sign In โ", variant="primary")auth_status = gr.HTML("")def do_signin(email, password):try:tok, user_email = sb_sign_in(email.strip(), password)return (tok,f'''<div style="color:#4CAF50;font-family:Space Mono,monospace;font-size:12px;padding:8px 0">โ Signed in as {user_email}</div>''')except Exception as e:return ("",f'''<div style="color:#ef4444;font-family:Space Mono,monospace;font-size:12px;padding:8px 0">โ {e}</div>''')signin_btn.click(do_signin, inputs=[email_in, pass_in], outputs=[token_state, auth_status])# โโ Chat tab โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโwith gr.Tab("๐ฌ Chat"):chatbot = gr.Chatbot(elem_id="chatbot",height=480,show_label=False,bubble_full_width=False,)with gr.Row():msg_box = gr.Textbox(placeholder="Ask me to build something, inspect your map, search the wikiโฆ",show_label=False,lines=2,scale=8,)send_btn = gr.Button("Send", variant="primary", scale=1)clear_btn = gr.Button("Clear chat", variant="secondary", size="sm")def submit(message, history, token):if not message.strip():return history, ""new_history = respond(message, history, token)return new_history, ""send_btn.click(submit, inputs=[msg_box, chatbot, token_state], outputs=[chatbot, msg_box])msg_box.submit(submit, inputs=[msg_box, chatbot, token_state], outputs=[chatbot, msg_box])clear_btn.click(lambda: [], outputs=[chatbot])# โโ Tools tab โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโwith gr.Tab("๐ง Tools"):gr.Markdown("### Available MCP Tools")rows = "".join(f'''<tr><td style="font-family:monospace;color:#a3e635;padding:5px 12px;font-size:12px">{n}</td><td style="color:#6a8a6a;font-size:12px;padding:5px 12px">{TOOL_DESCRIPTIONS.get(n,"")}</td></tr>'''for n in ALL_TOOLS)gr.HTML(f'''<table style="width:100%;border-collapse:collapse;background:#0c120c;border-radius:8px;overflow:hidden"><tr style="background:#0d1a0d"><th style="text-align:left;padding:8px 12px;color:#4CAF50;font-size:11px;font-family:Space Mono,monospace">TOOL</th><th style="text-align:left;padding:8px 12px;color:#4CAF50;font-size:11px;font-family:Space Mono,monospace">DESCRIPTION</th></tr>{rows}</table>''')gr.Markdown("\n> **Note:** Tools that interact with the map (gkc_create_build, etc.) ""require the **GimkitCopilot Gimloader plugin** to be running in your browser.")demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210import gradio as grimport requestsimport jsonimport timeSB_URL = "https://unztspukhwdzrllavnef.supabase.co"SB_ANON = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InVuenRzcHVraHdkenJsbGF2bmVmIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzM2MDMzNTAsImV4cCI6MjA4OTE3OTM1MH0.eUWx9O9uX-BqI7oUikVvSAwljgt4Gw3Fl6hb-Xz_YWo"ALL_TOOLS = ["gkc_create_build","gkc_undo_last_build","gkc_get_map_devices","gkc_look_around","gkc_capture_screenshot","gkc_remove_elements","gkc_vc_checkpoint","gkc_list_devices","gkc_search_terrain","gkc_search_props","gkc_get_device_info","gkc_skill_search","gkc_web_search","gkc_wiki_search",]def base_headers():return {"Content-Type": "application/json", "apikey": SB_ANON}def auth_headers(token):return {**base_headers(), "Authorization": "Bearer " + token}# โโ Auth โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdef sign_in(email, password):if not email.strip() or not password.strip():return None, "โ Enter email and password."try:r = requests.post(SB_URL + "/auth/v1/token?grant_type=password",headers=base_headers(),json={"email": email, "password": password},timeout=10,)d = r.json()if not r.ok:return None, "โ " + (d.get("error_description") or d.get("message") or r.text)return d["access_token"], f"โ Signed in as {d['user']['email']}"except Exception as e:return None, f"โ {e}"def sign_up(email, password):if not email.strip() or not password.strip():return None, "โ Enter email and password."if len(password) < 6:return None, "โ Password must be at least 6 characters."try:r = requests.post(SB_URL + "/auth/v1/signup",headers=base_headers(),json={"email": email, "password": password},timeout=10,)d = r.json()if not r.ok:return None, "โ " + (d.get("error_description") or d.get("message") or r.text)if not d.get("access_token"):return None, "๐ง Check your email to confirm, then sign in."return d["access_token"], f"โ Account created & signed in as {d['user']['email']}"except Exception as e:return None, f"โ {e}"# โโ Tool call (insert row โ poll for result) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdef call_tool(token, tool_name, args_raw, timeout_s=30):if not token:return "โ Not signed in."try:args = json.loads(args_raw) if args_raw.strip() else {}except json.JSONDecodeError as e:return f"โ Invalid JSON in arguments: {e}"# Insert a pending tool_call rowtry:r = requests.post(SB_URL + "/rest/v1/tool_calls",headers={**auth_headers(token), "Prefer": "return=representation"},json={"name": tool_name, "args": args, "status": "pending"},timeout=10,)r.raise_for_status()row = r.json()[0]row_id = row["id"]except Exception as e:return f"โ Failed to queue tool call: {e}"# Poll until the Gimloader plugin executes it and writes back the resultdeadline = time.time() + timeout_swhile time.time() < deadline:time.sleep(1.2)try:pr = requests.get(SB_URL + f"/rest/v1/tool_calls?id=eq.{row_id}&select=status,result",headers=auth_headers(token),timeout=10,)pr.raise_for_status()rows = pr.json()if not rows:continuerow = rows[0]if row["status"] in ("complete", "error"):result = row["result"]prefix = "โ " if row["status"] == "complete" else "โ "return prefix + json.dumps(result, indent=2)except Exception as e:return f"โ Poll error: {e}"return f"โฑ๏ธ Timed out after {timeout_s}s โ is the Gimloader plugin open and connected in Gimkit?"# โโ Gradio UI โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ_token_state = gr.State(None)with gr.Blocks(title="Gimkit Copilot") as demo:gr.Markdown("# ๐ฎ Gimkit Copilot\nControl your Gimkit Creative map from here.")token_state = gr.State(None)with gr.Tab("Sign In"):gr.Markdown("Sign in or create a free account to get your MCP token.")email_box = gr.Textbox(label="Email", placeholder="you@example.com")pass_box = gr.Textbox(label="Password", placeholder="โขโขโขโขโขโขโขโข", type="password")auth_msg = gr.Textbox(label="Status", interactive=False)with gr.Row():signin_btn = gr.Button("Sign In", variant="primary")signup_btn = gr.Button("Create Account", variant="secondary")def do_signin(email, password, _tok):tok, msg = sign_in(email, password)return tok if tok else _tok, msgdef do_signup(email, password, _tok):tok, msg = sign_up(email, password)return tok if tok else _tok, msgsignin_btn.click(do_signin, inputs=[email_box, pass_box, token_state], outputs=[token_state, auth_msg])signup_btn.click(do_signup, inputs=[email_box, pass_box, token_state], outputs=[token_state, auth_msg])with gr.Tab("Call a Tool"):gr.Markdown("**Requires:** Gimkit Creative open in browser with the GimkitCopilot plugin ""running and showing **โ Connected**.")tool_dd = gr.Dropdown(choices=ALL_TOOLS, value=ALL_TOOLS[0], label="Tool")args_box = gr.Textbox(label='Arguments (JSON)',placeholder='{"devices": [{"type": "textBillboard", "x": 0, "y": 0, "options": {"text": "Hello"}}]}',lines=5,)timeout_sl = gr.Slider(minimum=10, maximum=120, value=30, step=5, label="Timeout (seconds)")call_btn = gr.Button("โถ Run Tool", variant="primary")call_out = gr.Textbox(label="Result", lines=12, interactive=False)call_btn.click(call_tool,inputs=[token_state, tool_dd, args_box, timeout_sl],outputs=call_out,)with gr.Tab("MCP Token"):gr.Markdown("Copy this token into **Claude Desktop**, **Claude Code**, **Cursor**, etc. ""to let your AI client control Gimkit directly.\n\n""**MCP URL:** `https://unztspukhwdzrllavnef.supabase.co/functions/v1/mcp`")tok_box = gr.Textbox(label="Your Bearer Token", interactive=False, type="password")show_btn = gr.Button("๐ Show / Refresh Token")def show_token(tok):if not tok:return "โ Sign in first."return tokshow_btn.click(show_token, inputs=[token_state], outputs=tok_box)gr.Markdown("""### Quick Setup**Claude Desktop** โ add to `claude_desktop_config.json`:```json{"mcpServers": {"gimkit-copilot": {"url": "https://unztspukhwdzrllavnef.supabase.co/functions/v1/mcp","headers": { "Authorization": "Bearer <YOUR-TOKEN>" }}}}```**Claude Code** โ run in terminal:```claude mcp add gimkit-copilot https://unztspukhwdzrllavnef.supabase.co/functions/v1/mcp --header "Authorization: Bearer <YOUR-TOKEN>"```""")demo.launch()
1234567gradio>=4.0torchtransformerspeftacceleraterequestssentencepiece12gradiorequests
app.py+191-285
requirements.txt+1-6