Spaces:
Sleeping
Sleeping
Commit ·
adcd7fa
0
Parent(s):
Initial commit
Browse filesFiles changed (7)
- .gitattributesAdded+36
- .gitignoreAdded+4
- README.mdAdded+30
- app.pyAdded+1227
- pyproject.tomlAdded+10
- requirements.txtAdded+3
- uv.lockAdded
123456789101112131415161718192021222324252627282930313233343536*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text
1234.venv/__pycache__/*.py[cod].env123456789101112131415161718192021222324252627282930---title: North Mini Code Demoemoji: 💻colorFrom: bluecolorTo: indigosdk: gradiosdk_version: 6.14.0python_version: '3.13'app_file: app.pypinned: false---
## North Mini Code Demo
A Gradio Space that streams code from Cohere's [North-Mini-Code-1.0](https://huggingface.co/CohereLabs/North-Mini-Code-1.0) model, executes the generated Python in a constrained subprocess, and renders generated HTML/CSS/JavaScript in a sandboxed browser iframe.
North-Mini-Code-1.0 is built for agentic coding and works best in your terminal with [OpenCode](https://opencode.ai).
## Configuration
Set `COHERE_API_KEY` as a Hugging Face Space secret.
## Local Run
```bashexport COHERE_API_KEY=...uv run python app.py```
`requirements.txt` is kept for Hugging Face Spaces; `pyproject.toml` is for local uv runs.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227"""Gradio Space that showcases execution-grounded code generation."""
from __future__ import annotations
import htmlimport loggingimport osimport reimport subprocessimport sysimport tempfileimport textwrapfrom collections.abc import Iteratorfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any
import gradio as grfrom cohere import ClientV2from cohere.core.api_error import ApiError
APP_TITLE = "North Mini Code 1.0 Demo"CLIENT_NAME = "hf-space-north-mini-code"MODEL_ID = "north-mini-code-1-0"MODEL_URL = "https://huggingface.co/CohereLabs/North-Mini-Code-1.0"OPENCODE_URL = "https://opencode.ai"
DEFAULT_TEMPERATURE = 0.2PY_TIMEOUT_S = 12PY_MEM_LIMIT_MB = 1024MAX_STDIO_CHARS = 16_000OUTPUT_PNG = "output.png"
THINKING_BLOCK_RE = re.compile(r"<\s*think\s*>.*?<\s*/\s*think\s*>", re.IGNORECASE | re.DOTALL)CODE_BLOCK_RE = re.compile(r"```([a-zA-Z0-9_+.#-]*)\s*\n(.*?)```", re.DOTALL)
logger = logging.getLogger(__name__)logging.basicConfig(level=logging.INFO)
SYSTEM_PROMPT = """You are a coding model in a demo where generated code can be run.
Only respond to coding-related requests: code generation, debugging, code review,software design, developer tooling, programming concepts, or reasoning about code.If the user asks for something unrelated to coding, briefly say you can only helpwith coding-related requests.
If the user asks a coding question that does not require runnable code, answer itdirectly and do not force a code block.If the user asks you to generate, modify, or fix runnable code, return exactly onefenced code block and no extra prose. Use a correct language tag: ```python forPython, or ```html for Web.
For Python, prefer standard library or common packages such as matplotlib.For Python, do not use network calls, subprocesses, shell commands, or long-running loops.For Web, return a single self-contained HTML document with any CSS and JavaScript inline.For Web, make the page fully responsive so it fills the area it is given: set html and bodyto margin:0 and 100% width/height, prefer relative sizes (100%, 100vw/100vh, flexbox) overfixed pixel dimensions, and size any <canvas> to its container and re-fit it on window resizeso nothing is clipped or scrolled."""
# Curated starter prompts. Each entry is (chip label, prompt, target language).EXAMPLE_PROMPTS: list[tuple[str, str, str]] = [ ( "🌀 Spiral plot", "Create a Python script that plots a colorful spiral with matplotlib, prints a short " "description of what it drew, and does not require any external files.", "Python", ), ( "📊 Sine waves", "Plot three sine waves with different frequencies and amplitudes on one matplotlib " "figure with a legend and grid, and print the equation of each wave.", "Python", ), ( "✨ Particles", "Create a self-contained HTML/CSS/JavaScript demo with an animated particle field " "that reacts to the mouse and includes a small title.", "Web", ), ( "🖌️ Blackboard", "Create a self-contained HTML/CSS/JavaScript blackboard drawing app: a dark chalkboard " "canvas you can draw on with the mouse (and touch), a small palette of chalk colors, an " "adjustable brush size, and a button to clear the board.", "Web", ), ( "🎲 Monte Carlo π", "Estimate π with a Monte Carlo simulation: sample random points in a unit square, count " "how many fall inside the quarter circle, and print the estimate, the true value, and the " "error. Plot the sampled points with matplotlib, colored by whether they land inside the " "circle.", "Python", ), ( "✅ Todo app", "Create a self-contained HTML/CSS/JavaScript todo app: add tasks, mark them complete, " "delete them, filter by all/active/completed, and show a live count of remaining tasks, " "with a clean, modern, responsive UI.", "Web", ),]
@dataclassclass PythonExecutionResult: stdout: str stderr: str image_path: str | None returncode: int | None timed_out: bool = False
def _disable_parent_proc_inspection() -> None: """Best-effort hardening against same-UID reads of the parent process env.
The subprocess receives a scrubbed env, but Linux /proc can sometimes expose a same-user process's environment. Marking the Gradio process non-dumpable helps prevent generated code from reading `/proc/<parent>/environ`. """
if sys.platform != "linux": return try: import ctypes
pr_set_dumpable = 4 libc = ctypes.CDLL(None) libc.prctl(pr_set_dumpable, 0, 0, 0, 0) except Exception: logger.warning("Could not disable parent /proc inspection", exc_info=True)
def _build_client(api_key: str) -> ClientV2 | None: if api_key: return ClientV2(api_key=api_key, client_name=CLIENT_NAME) else: logger.warning("COHERE_API_KEY is not set; inference is disabled until configured.") return None
_raw_api_key = os.getenv("COHERE_API_KEY", "").strip()API_KEY_CONFIGURED = bool(_raw_api_key)CLIENT = _build_client(_raw_api_key)
# Do not keep the secret in the parent environment longer than needed. The Cohere# client has already been constructed, and subprocesses are passed explicit envs.if _raw_api_key: os.environ.pop("COHERE_API_KEY", None) _disable_parent_proc_inspection()_raw_api_key = ""
def _extract_content_parts(content: object) -> tuple[str, str]: """Extract visible text and reasoning text from Cohere content shapes."""
if content is None: return "", "" if isinstance(content, str): return content, "" if isinstance(content, list): parts = [_extract_content_parts(block) for block in content] return "".join(text for text, _ in parts), "".join(thinking for _, thinking in parts) if isinstance(content, dict): text = str(content.get("text") or "") thinking = str(content.get("thinking") or "") if not text and not thinking and "content" in content: return _extract_content_parts(content.get("content")) return text, thinking
text = getattr(content, "text", None) thinking = getattr(content, "thinking", None) return (str(text) if text is not None else ""), (str(thinking) if thinking is not None else "")
def _strip_thinking_blocks(text: str) -> str: return THINKING_BLOCK_RE.sub("", text).strip()
def _format_response(output: str, thinking: str) -> str: thinking = thinking.strip() if not thinking: return output if not output: return f"<think>{thinking}</think>" return f"<think>{thinking}</think>\n\n{output}"
def _no_output_note(finish_reason: str) -> str: if finish_reason == "MAX_TOKENS": return "_The model hit its output-token cap before producing visible code._" if finish_reason == "ERROR": return "_The model returned an error before producing code. Please try again._" return f"_The model finished without visible output (finish_reason={finish_reason})._"
def _format_api_error(exc: ApiError) -> str: body = exc.body if isinstance(body, dict): message = body.get("message") or body.get("error") or "" body_text = str(message) if message else str(body) else: body_text = str(body or "").strip()
if exc.status_code == 404: return f"Model `{MODEL_ID}` was not found on the configured Cohere endpoint." if exc.status_code in (401, 403): return "The `COHERE_API_KEY` secret was rejected. Check the Space secret." if exc.status_code == 429: return "The Cohere API rate limit was reached. Please wait and try again." return body_text[:240] or f"HTTP {exc.status_code}"
def call_model(messages: list[dict[str, Any]]) -> Iterator[str]: """Stream cumulative model text.
All Cohere-specific details are intentionally isolated here: model name, client method, streaming event shape, and reasoning handling. """
if CLIENT is None: if not API_KEY_CONFIGURED: yield "This Space needs a `COHERE_API_KEY` secret before it can call Cohere." else: yield "Cohere client is not configured." return
output = "" thinking_output = "" finish_reason: str | None = None event_counts: dict[str, int] = {}
try: stream = CLIENT.chat_stream( model=MODEL_ID, messages=messages, temperature=DEFAULT_TEMPERATURE, thinking={"type": "enabled"}, ) for event in stream: event_type = getattr(event, "type", None) or "unknown" event_counts[event_type] = event_counts.get(event_type, 0) + 1 delta = getattr(event, "delta", None)
if event_type in ("content-delta", "content-start"): msg = getattr(delta, "message", None) if delta is not None else None if msg is None: continue text, thinking = _extract_content_parts(getattr(msg, "content", None)) if thinking: thinking_output += thinking yield _format_response(output, thinking_output) if text: output += text yield _format_response(output, thinking_output) elif event_type == "message-end": finish_reason = getattr(delta, "finish_reason", None) if finish_reason is None and isinstance(delta, dict): finish_reason = delta.get("finish_reason")
logger.info( "Cohere stream ended: finish_reason=%s, output_len=%d, thinking_len=%d, events=%s", finish_reason, len(output), len(thinking_output), event_counts, ) if not output: yield _format_response(_no_output_note((finish_reason or "unknown").upper()), thinking_output) except ApiError as exc: logger.exception("Cohere API error (status=%s)", exc.status_code) yield _format_response(f"_Cohere API error_: {_format_api_error(exc)}", thinking_output) except Exception as exc: logger.exception("Unexpected error calling Cohere API") yield _format_response(f"_Unexpected error calling Cohere_: {exc}", thinking_output)
def _chat_history_to_messages(history: list[dict[str, str]]) -> list[dict[str, Any]]: messages: list[dict[str, Any]] = [{"role": "system", "content": SYSTEM_PROMPT}] for item in history: role = item.get("role") content = str(item.get("content") or "").strip() if role not in {"user", "assistant"} or not content: continue if role == "assistant": content = _strip_thinking_blocks(content) messages.append({"role": role, "content": content}) return messages
def _clip_context(text: str, limit: int = 6_000) -> str: if len(text) <= limit: return text return text[:limit] + f"\n... truncated {len(text) - limit} characters ..."
def _iteration_context(execution_context: dict[str, Any] | None) -> str: if not execution_context or not execution_context.get("code"): return ""
code = _clip_context(str(execution_context.get("code") or ""), 8_000) target = str(execution_context.get("target") or "code") fence_lang = str(execution_context.get("fence_lang") or target) status = str(execution_context.get("status") or "") stdout = _clip_context(str(execution_context.get("stdout") or ""), 2_000) stderr = _clip_context(str(execution_context.get("stderr") or ""), 2_000)
parts = [ "Previous generated code and run result are available for iteration.", f"Previous target: {target}", f"Previous status: {status}", f"Previous code:\n```{fence_lang}\n{code}\n```", ] if stdout: parts.append(f"Previous stdout:\n{stdout}") if stderr: parts.append(f"Previous stderr / traceback:\n{stderr}") parts.append("If the user asks to revise, debug, extend, or explain the prior code, use this context.") return "\n\n".join(parts)
def _targeted_prompt( prompt: str, target_language: str, execution_context: dict[str, Any] | None = None,) -> str: target = "Python" if target_language == "Python" else "Web" iteration_context = _iteration_context(execution_context) context_block = f"\n\n{iteration_context}" if iteration_context else "" if target == "Python": return ( "Target: Python. Stay within coding-related requests only. " "If the user asks a coding question or wants reasoning that does not require running code, " "answer directly without a fenced block. If they ask to generate, revise, or fix runnable " "code, return one ```python fenced block only. The code will be executed in a short-lived " "subprocess." f"{context_block}\n\n" f"User request:\n{prompt}" ) return ( "Target: Web. Stay within coding-related requests only. " "If the user asks a coding question or wants reasoning that does not require running code, " "answer directly without a fenced block. If they ask to generate, revise, or fix runnable " "web code, return one ```html fenced block only. The code is rendered inside a sandboxed " "iframe that spans the full width of the preview panel and is about 680px tall, so design " "the page to fill that iframe responsively: html/body at margin:0 and 100% width/height, " "avoid fixed widths larger than the iframe, and resize any <canvas> to its container " "(including on window resize) so the whole app is visible without horizontal scrolling." f"{context_block}\n\n" f"User request:\n{prompt}" )
def extract_code(response: str) -> tuple[str, str | None]: """Return the first fenced code block and its language tag."""
visible_response = _strip_thinking_blocks(response) match = CODE_BLOCK_RE.search(visible_response) if not match: return "", None return match.group(2).strip(), (match.group(1).strip().lower() or None)
def _normalize_language(target_language: str | None, fence_lang: str | None) -> str: if fence_lang in {"python", "py"}: return "python" if fence_lang in {"html", "web", "javascript", "js", "css"}: return "web" if target_language in {"Python", "Web"}: return target_language.lower() return "python"
def _truncate_output(text: str) -> str: if len(text) <= MAX_STDIO_CHARS: return text remaining = len(text) - MAX_STDIO_CHARS return text[:MAX_STDIO_CHARS] + f"\n\n... truncated {remaining} characters ..."
def _decode_timeout_output(value: str | bytes | None) -> str: if value is None: return "" if isinstance(value, bytes): return value.decode("utf-8", errors="replace") return value
def _apply_subprocess_limits() -> None: """Apply child-only CPU and memory caps before Python user code starts."""
import resource
mem_bytes = PY_MEM_LIMIT_MB * 1024 * 1024 resource.setrlimit(resource.RLIMIT_AS, (mem_bytes, mem_bytes)) resource.setrlimit(resource.RLIMIT_CPU, (PY_TIMEOUT_S, PY_TIMEOUT_S))
def _python_runner_source() -> str: return textwrap.dedent( f""" import os import runpy import sys import traceback
os.environ.setdefault("MPLBACKEND", "Agg") exit_code = 0 try: runpy.run_path(os.path.join(os.getcwd(), "user_code.py"), run_name="__main__") except SystemExit as exc: code = exc.code exit_code = code if isinstance(code, int) else 1 except Exception: traceback.print_exc() exit_code = 1 finally: try: import matplotlib
matplotlib.use("Agg", force=True) import matplotlib.pyplot as plt
if plt.get_fignums(): plt.savefig(os.environ["OUTPUT_PNG"], bbox_inches="tight") except ModuleNotFoundError as exc: if exc.name != "matplotlib": traceback.print_exc() except Exception: traceback.print_exc()
raise SystemExit(exit_code) """ ).strip()
def run_python(code: str) -> PythonExecutionResult: """Execute generated Python in a subprocess with baseline containment.
Security boundary for v1: - Scrubbed env: never pass os.environ, so COHERE_API_KEY is absent. - Hard timeout: kill code that hangs the Space. - Memory/CPU caps: reduce the blast radius of runaway code.
Accepted limitation: a standard non-privileged Gradio Space cannot reliably block network egress or filesystem reads from this subprocess. Full isolation would require a privileged Docker Space with nsjail/gVisor, or an external executor such as E2B/Modal. Do not refactor these comments away; they define the risk boundary of this demo. """
with tempfile.TemporaryDirectory(prefix="coding_model_run_") as tmp: workdir = Path(tmp) runner_path = workdir / "runner.py" user_path = workdir / "user_code.py" image_path = workdir / OUTPUT_PNG
runner_path.write_text(_python_runner_source(), encoding="utf-8") user_path.write_text(code, encoding="utf-8")
env = { # SECURITY: explicit scrubbed env. Never pass parent os.environ, which # may contain COHERE_API_KEY or other HF Space secrets. "PATH": "/usr/bin:/bin", "HOME": str(workdir), "TMPDIR": str(workdir), "MPLBACKEND": "Agg", "MPLCONFIGDIR": str(workdir / ".matplotlib"), "OUTPUT_PNG": str(image_path), "PYTHONIOENCODING": "utf-8", "PYTHONNOUSERSITE": "1", "PYTHONUNBUFFERED": "1", "LANG": "C.UTF-8", # Keep numeric libraries from spawning many workers inside the capped process. "OPENBLAS_NUM_THREADS": "1", "OMP_NUM_THREADS": "1", "MKL_NUM_THREADS": "1", "NUMEXPR_NUM_THREADS": "1", }
try: completed = subprocess.run( [sys.executable, "-I", str(runner_path)], cwd=workdir, env=env, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=PY_TIMEOUT_S, preexec_fn=_apply_subprocess_limits if sys.platform == "linux" else None, check=False, ) stdout = _truncate_output(completed.stdout) stderr = _truncate_output(completed.stderr) if completed.returncode and not stderr: stderr = f"Process exited with status {completed.returncode}."
saved_image: str | None = None if image_path.exists() and image_path.stat().st_size > 0: saved = tempfile.NamedTemporaryFile( prefix="coding_model_plot_", suffix=".png", delete=False ) saved.close() Path(saved.name).write_bytes(image_path.read_bytes()) saved_image = saved.name
return PythonExecutionResult( stdout=stdout, stderr=stderr, image_path=saved_image, returncode=completed.returncode, ) except subprocess.TimeoutExpired as exc: stdout = _truncate_output(_decode_timeout_output(exc.stdout)) stderr = _truncate_output(_decode_timeout_output(exc.stderr)) timeout_note = f"Timed out after {PY_TIMEOUT_S} seconds; the process was killed." stderr = f"{stderr}\n{timeout_note}".strip() return PythonExecutionResult( stdout=stdout, stderr=stderr, image_path=None, returncode=None, timed_out=True, )
def _web_document(code: str, fence_lang: str | None) -> str: lang = (fence_lang or "").lower() if lang in {"javascript", "js"}: return f"<!doctype html><html><body><script>\n{code}\n</script></body></html>" if lang == "css": return f"<!doctype html><html><head><style>\n{code}\n</style></head><body></body></html>" if re.search(r"<!doctype|<html[\s>]", code, flags=re.IGNORECASE): return code return f"<!doctype html><html><head><meta charset='utf-8'></head><body>\n{code}\n</body></html>"
def build_iframe(code: str, fence_lang: str | None = None) -> str: """Render web code in a sandboxed iframe.
SECURITY: sandbox allows scripts so demos can run, but deliberately omits allow-same-origin. Without same-origin, generated code cannot share the parent origin, cookies, or storage. """
document = _web_document(code, fence_lang) srcdoc = html.escape(document, quote=True) return ( '<iframe class="web-frame" ' 'sandbox="allow-scripts" ' 'allow="fullscreen" ' "allowfullscreen " f'srcdoc="{srcdoc}" ' 'style="width:100%; min-height:680px; border:0; border-radius:14px; ' 'background:white;"></iframe>' )
TAB_PREVIEW = "preview"TAB_CONSOLE = "console"TAB_CODE = "code"
def _status_badge(text: str, state: str = "idle") -> str: spinner = '<span class="status-spinner"></span>' if state == "working" else '<span class="status-dot"></span>' return ( f'<div class="status-badge status-{state}">{spinner}' f"<span>{html.escape(text)}</span></div>" )
def _preview_placeholder(message: str = "Run code to see the result here.") -> str: return ( '<div class="preview-placeholder">' '<div class="pp-emoji">🖼️</div>' f"<strong>{html.escape(message)}</strong>" "<span>A matplotlib figure or a live web preview will appear in this panel.</span>" "</div>" )
def _write_download(code: str, language: str) -> str | None: if not code: return None ext = "py" if language == "python" else "html" try: directory = tempfile.mkdtemp(prefix="coding_model_dl_") path = Path(directory) / f"generated.{ext}" path.write_text(code, encoding="utf-8") return str(path) except Exception: logger.warning("Could not write downloadable snippet", exc_info=True) return None
def _display_kwargs(execution_context: dict[str, Any] | None) -> dict[str, Any]: """Map the persisted execution context onto concrete component updates."""
base = { "show_image": False, "image": None, "show_web": False, "web_html": "", "show_placeholder": True, "placeholder_msg": "Run code to see the result here.", "stdout": "", "stderr": "", "code": "", "code_language": "python", "download_path": None, "suggested_tab": None, } if not execution_context or not execution_context.get("code"): return base
target = str(execution_context.get("target") or "") code = str(execution_context.get("code") or "") fence_lang = str(execution_context.get("fence_lang") or target) download = execution_context.get("download_path")
if target == "web": base.update( show_web=True, web_html=build_iframe(code, fence_lang), show_placeholder=False, code=code, code_language="html", download_path=download, suggested_tab=TAB_PREVIEW, ) return base
image = execution_context.get("image_path") base.update( show_image=bool(image), image=image, show_placeholder=not bool(image), placeholder_msg="No figure produced — open the Console tab for program output.", stdout=str(execution_context.get("stdout") or ""), stderr=str(execution_context.get("stderr") or ""), code=code, code_language="python", download_path=download, suggested_tab=TAB_PREVIEW if image else TAB_CONSOLE, ) return base
def _output_state( history: list[dict[str, str]], prompt_value: str, status_text: str, status_state: str, execution_context: dict[str, Any] | None, *, selected_tab: str | None = None, display: dict[str, Any] | None = None,) -> tuple[Any, ...]: data = display if display is not None else _display_kwargs(execution_context) tab_update = gr.update(selected=selected_tab) if selected_tab else gr.update() return ( history, prompt_value, _status_badge(status_text, status_state), tab_update, gr.update(value=_preview_placeholder(data["placeholder_msg"]), visible=data["show_placeholder"]), gr.update(value=data["image"], visible=data["show_image"]), gr.update(value=data["web_html"], visible=data["show_web"]), gr.update(visible=data["show_web"]), data["stdout"], data["stderr"], gr.update(value=data["code"], language=data["code_language"]), gr.update(value=data["download_path"], visible=bool(data["download_path"])), execution_context or {}, )
def _run_extracted_code( code: str, target: str,) -> tuple[str, str, str | None, str, str]: """Execute code and return (stdout, stderr, image_path, status_text, status_state)."""
if target == "python": result = run_python(code) if result.timed_out: return result.stdout, result.stderr, result.image_path, f"Timed out after {PY_TIMEOUT_S}s", "error" if result.returncode: return result.stdout, result.stderr, result.image_path, "Finished with errors", "error" return result.stdout, result.stderr, result.image_path, "Ran successfully", "success"
return "", "", None, "Preview ready", "success"
def _updated_execution_context( *, code: str, target: str, fence_lang: str | None, stdout: str, stderr: str, image_path: str | None, status: str, download_path: str | None,) -> dict[str, Any]: return { "code": code, "target": target, "fence_lang": fence_lang or target, "stdout": stdout, "stderr": stderr, "image_path": image_path, "status": status, "download_path": download_path, }
def handle_submit( prompt: str, target_language: str, history: list[dict[str, str]] | None, execution_context: dict[str, Any] | None,) -> Iterator[tuple[Any, ...]]: history = list(history or []) execution_context = execution_context or {} prompt = (prompt or "").strip() if not prompt: yield _output_state(history, "", "Enter a prompt to get started.", "info", execution_context) return
generation_history = history + [ {"role": "user", "content": prompt}, {"role": "assistant", "content": ""}, ] assistant_index = len(generation_history) - 1 yield _output_state(generation_history, "", "Thinking…", "working", execution_context)
cohere_history = history + [ {"role": "user", "content": _targeted_prompt(prompt, target_language, execution_context)} ] messages = _chat_history_to_messages(cohere_history)
final_response = "" for partial in call_model(messages): final_response = partial generation_history[assistant_index]["content"] = partial yield _output_state(generation_history, "", "Generating…", "working", execution_context)
if not final_response: generation_history[assistant_index]["content"] = "The model did not return a response." yield _output_state(generation_history, "", "No model response.", "error", execution_context) return
code, fence_lang = extract_code(final_response) target = _normalize_language(target_language, fence_lang) if not code: yield _output_state(generation_history, "", "Answered without running code.", "info", execution_context) return
yield _output_state(generation_history, "", "Running…", "working", execution_context)
stdout, stderr, image, status_text, status_state = _run_extracted_code(code, target) download = _write_download(code, "python" if target == "python" else "html") execution_context = _updated_execution_context( code=code, target=target, fence_lang=fence_lang, stdout=stdout, stderr=stderr, image_path=image, status=status_text, download_path=download, ) data = _display_kwargs(execution_context) yield _output_state( generation_history, "", status_text, status_state, execution_context, selected_tab=data["suggested_tab"], display=data, )
def _make_example_runner(prompt: str, target: str): def runner(*_ignored: Any) -> Iterator[tuple[Any, ...]]: # Starters always begin a fresh conversation rather than appending to the # current thread, so prior history and execution context are discarded. yield from handle_submit(prompt, target, [], {})
return runner
def start_new_conversation() -> tuple[Any, ...]: return _output_state( [], "", "New conversation — ask anything about code.", "idle", {}, selected_tab=TAB_PREVIEW, )
def _cancelled_status() -> str: return _status_badge("Stopped.", "info")
APP_THEME = gr.themes.Soft( primary_hue="indigo", secondary_hue="violet", neutral_hue="slate", radius_size=gr.themes.sizes.radius_lg, font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"], font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "SFMono-Regular", "monospace"],).set( body_background_fill="*neutral_50", body_background_fill_dark="*neutral_950", block_shadow="0 1px 2px rgba(16,24,40,.04), 0 10px 28px -18px rgba(16,24,40,.22)", button_primary_shadow="0 8px 22px -10px rgba(99,102,241,.7)",)
CUSTOM_CSS = """.gradio-container { max-width: 1720px !important; margin: 0 auto !important; padding-left: 1.25rem !important; padding-right: 1.25rem !important; }
/* ---------- Hero ---------- */.hero { padding: 1.2rem 0 0.2rem; }.hero-row { display: flex; align-items: center; gap: 0.95rem; flex-wrap: wrap; }.hero-mark { width: 54px; height: 54px; border-radius: 16px; flex: none; background: linear-gradient(135deg, #3b82f6, #6366f1 45%, #8b5cf6); display: flex; align-items: center; justify-content: center; font-size: 1.75rem; box-shadow: 0 10px 26px -10px rgba(99,102,241,.7);}.hero h1 { font-size: 1.95rem; font-weight: 800; line-height: 1.1; margin: 0; letter-spacing: -0.025em; background: linear-gradient(110deg, #2563eb, #7c3aed 55%, #9333ea); -webkit-background-clip: text; background-clip: text; color: transparent;}.hero .subtitle { margin: 0.28rem 0 0; color: var(--body-text-color-subdued); font-size: 1.02rem; }.hero-tip { margin: 0.7rem 0 0; padding: 0.5rem 0.8rem; font-size: 0.86rem; line-height: 1.45; display: flex; align-items: baseline; gap: 0.45rem; border: 1px solid var(--border-color-primary); border-left: 3px solid #7c3aed; border-radius: 12px; background: var(--block-background-fill); color: var(--body-text-color-subdued);}.hero-tip a { color: #6d28d9; font-weight: 600; text-decoration: none; white-space: nowrap; }.hero-tip a:hover { text-decoration: underline; }.dark .hero-tip a { color: #c4b5fd; }.hero-spacer { flex: 1 1 auto; min-width: 1rem; }.hero-pills { display: flex; flex-wrap: wrap; gap: 0.4rem; justify-content: flex-end; }.brand-pill { display: inline-flex; align-items: center; gap: 0.4rem; font-size: 0.78rem; font-weight: 600; padding: 0.34rem 0.7rem; border-radius: 999px; border: 1px solid var(--border-color-primary); background: var(--block-background-fill); color: var(--body-text-color-subdued); white-space: nowrap; text-decoration: none; transition: transform .12s ease, box-shadow .12s ease, border-color .12s ease, color .12s ease;}a.brand-pill:hover { transform: translateY(-1px); border-color: #8b5cf6; color: var(--body-text-color); box-shadow: 0 8px 18px -12px rgba(124,58,237,.75);}.brand-pill .pill-ext { opacity: 0.55; font-size: 0.72rem; }.brand-pill.accent { border-color: transparent; color: #fff; background: linear-gradient(110deg, #4f46e5, #7c3aed);}
/* ---------- Config alert ---------- */.config-alert { border: 1px solid #f4c7c7; background: #fdeeee; color: #8a1f1f; border-radius: 14px; padding: 0.75rem 0.95rem; font-size: 0.9rem; margin: 0.55rem 0 0; line-height: 1.45;}.config-alert code { background: rgba(0,0,0,.07); padding: 0.05rem 0.32rem; border-radius: 6px; }.dark .config-alert { background: rgba(180,35,24,.13); border-color: rgba(180,35,24,.42); color: #f3b4b4; }.dark .config-alert code { background: rgba(255,255,255,.1); }
/* ---------- Panels ---------- */.panel-card { border: 1px solid var(--border-color-primary); border-radius: 20px; padding: 1.05rem 1.1rem 1.15rem; background: var(--block-background-fill);}.panel-head { display: flex; align-items: center; justify-content: space-between; gap: 0.6rem; margin-bottom: 0.7rem; min-height: 34px;}.panel-title { font-weight: 700; font-size: 1.05rem; display: flex; align-items: center; gap: 0.45rem; margin: 0; }.workbench-status { display: flex; justify-content: flex-end; }
/* ---------- Status badge ---------- */.status-badge { display: inline-flex; align-items: center; gap: 0.5rem; font-size: 0.85rem; font-weight: 600; padding: 0.4rem 0.8rem; border-radius: 999px; border: 1px solid var(--border-color-primary); background: var(--block-background-fill); white-space: nowrap;}.status-dot { width: 9px; height: 9px; border-radius: 50%; background: #94a3b8; flex: none; }.status-info .status-dot { background: #3b82f6; }.status-success .status-dot { background: #22c55e; }.status-error .status-dot { background: #ef4444; }.status-error { border-color: rgba(239,68,68,.45); }.status-success { border-color: rgba(34,197,94,.45); }.status-working { border-color: rgba(99,102,241,.5); color: var(--body-text-color); }.status-spinner { width: 12px; height: 12px; border-radius: 50%; flex: none; border: 2px solid rgba(99,102,241,.3); border-top-color: #6366f1; animation: spin 0.7s linear infinite;}@keyframes spin { to { transform: rotate(360deg); } }
/* ---------- Examples ---------- */.examples-label { font-size: 0.78rem; font-weight: 600; color: var(--body-text-color-subdued); text-transform: uppercase; letter-spacing: 0.05em; margin: 0.45rem 0 0.15rem; }.examples-wrap { flex-wrap: wrap !important; gap: 0.5rem !important; }button.example-chip { flex: 0 0 auto !important; border-radius: 999px !important; font-size: 0.83rem !important; font-weight: 600 !important; padding: 0.45rem 0.95rem !important; white-space: nowrap !important; width: auto !important; min-width: 0 !important; background: var(--block-background-fill) !important; border: 1px solid var(--border-color-primary) !important; transition: transform .12s ease, box-shadow .12s ease, border-color .12s ease;}button.example-chip:hover { transform: translateY(-1px); border-color: #8b5cf6 !important; box-shadow: 0 8px 18px -12px rgba(124,58,237,.75);}
/* ---------- Inputs ---------- */.send-btn button { font-weight: 700 !important; }.input-hint { font-size: 0.78rem; color: var(--body-text-color-subdued); margin: 0.2rem 0 0; }
/* ---------- Target toggle ---------- */.target-toggle { background: transparent !important; border: none !important; box-shadow: none !important; padding: 0 !important; }
/* ---------- Console ---------- */.console-box textarea { font-family: var(--font-mono) !important; font-size: 0.82rem !important; line-height: 1.5 !important;}.stderr-box textarea { color: #b42318 !important; }.dark .stderr-box textarea { color: #fca5a5 !important; }
/* ---------- Preview ---------- */.preview-placeholder { min-height: 560px; border: 1.5px dashed var(--border-color-primary); border-radius: 16px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 0.45rem; color: var(--body-text-color-subdued); text-align: center; padding: 2rem;}.preview-placeholder .pp-emoji { font-size: 2.3rem; opacity: 0.85; }.preview-placeholder strong { font-size: 1.02rem; color: var(--body-text-color); }.web-frame { box-shadow: 0 8px 30px -18px rgba(16,24,40,.5); }.web-frame:fullscreen { border-radius: 0 !important; box-shadow: none !important; min-height: 100vh !important; background: #fff; }.preview-toolbar { justify-content: flex-end !important; margin-bottom: 0.5rem; }.fullscreen-btn button { border-radius: 999px !important; font-weight: 600 !important; white-space: nowrap !important;}
/* ---------- Footer note ---------- */.safety-note { font-size: 0.78rem; color: var(--body-text-color-subdued); margin: 0.7rem 0 0; line-height: 1.45; display: flex; align-items: center; gap: 0.4rem;}
/* ---------- Responsive ---------- */@media (max-width: 1024px) { .hero h1 { font-size: 1.6rem; }}"""
def _configuration_banner_html() -> str: messages: list[str] = [] if not API_KEY_CONFIGURED: messages.append("Set <code>COHERE_API_KEY</code> as a Hugging Face Space secret.") if not messages: return "" items = " ".join(messages) return ( '<div class="config-alert"><strong>⚙️ Configuration required.</strong> ' f"{items} Generation stays disabled until this is done.</div>" )
def _hero_html() -> str: model_pill = ( f'<a class="brand-pill" href="{html.escape(MODEL_URL, quote=True)}" ' 'target="_blank" rel="noopener noreferrer" ' f'title="View {html.escape(MODEL_ID)} on Hugging Face">' f'🧠 {html.escape(MODEL_ID)} <span class="pill-ext">↗</span></a>' ) opencode_url = html.escape(OPENCODE_URL, quote=True) return f"""<section class="hero"> <div class="hero-row"> <div class="hero-mark">💻</div> <div> <h1>{html.escape(APP_TITLE)}</h1> <p class="subtitle">Chat with a coding model. Run Python or Web code.</p> </div> <div class="hero-spacer"></div> <div class="hero-pills"> {model_pill} </div> </div> <p class="hero-tip">⌨️ <span><strong>North-Mini-Code-1.0</strong> is built for agentic coding and works best in your terminal with <a href="{opencode_url}" target="_blank" rel="noopener noreferrer">OpenCode ↗</a>. This Space is a browser playground for trying the model.</span></p></section>{_configuration_banner_html()}"""
def build_demo() -> gr.Blocks: with gr.Blocks(title=APP_TITLE, fill_height=True) as demo: gr.HTML(_hero_html())
execution_state = gr.State({})
with gr.Row(equal_height=False): # ----- Left: conversation ----- with gr.Column(scale=6, min_width=420, elem_classes=["panel-card"]): with gr.Row(elem_classes=["panel-head"]): gr.HTML('<div class="panel-title">💬 Conversation</div>') new_conversation_btn = gr.Button( "+ New chat", variant="secondary", size="sm", scale=0, min_width=120 )
chatbot = gr.Chatbot( label=None, show_label=False, height=440, layout="bubble", reasoning_tags=[("<think>", "</think>")], placeholder=( "### 👋 Ask me to write code\n" "I can build runnable **Python** scripts and self-contained **web** demos.\n\n" "Pick a starter below, or describe what you want to build." ), )
gr.HTML('<p class="examples-label">Run generated code as</p>') target_language = gr.Radio( choices=["Python", "Web"], value="Python", show_label=False, container=False, interactive=True, elem_classes=["target-toggle"], )
prompt = gr.Textbox( label=None, show_label=False, placeholder="Ask a coding question, request code, or iterate on the previous result…", lines=3, max_lines=10, submit_btn=False, autofocus=True, ) with gr.Row(): submit_btn = gr.Button("Send ➤", variant="primary", scale=4, elem_classes=["send-btn"]) stop_btn = gr.Button("Stop", variant="stop", scale=1, min_width=90) gr.HTML('<p class="input-hint">Press <strong>Shift+Enter</strong> to send · <strong>Enter</strong> for a new line</p>')
gr.HTML('<p class="examples-label">Try a starter</p>') example_buttons: list[tuple[gr.Button, str, str]] = [] with gr.Row(elem_classes=["examples-wrap"]): for label, ex_prompt, ex_target in EXAMPLE_PROMPTS: btn = gr.Button(label, size="sm", scale=0, elem_classes=["example-chip"]) example_buttons.append((btn, ex_prompt, ex_target))
# ----- Right: workbench ----- with gr.Column(scale=6, min_width=420, elem_classes=["panel-card"]): with gr.Row(elem_classes=["panel-head"]): gr.HTML('<div class="panel-title">🛠️ Workbench</div>') status = gr.HTML(_status_badge("Idle.", "idle"), elem_classes=["workbench-status"])
with gr.Tabs() as result_tabs: with gr.Tab("Preview", id=TAB_PREVIEW): preview_placeholder = gr.HTML(_preview_placeholder()) py_image = gr.Image( label="Matplotlib figure", type="filepath", visible=False, interactive=False, show_label=False, ) with gr.Row(elem_classes=["preview-toolbar"], visible=False) as preview_toolbar: fullscreen_btn = gr.Button( "⤢ Fullscreen", size="sm", scale=0, min_width=120, elem_classes=["fullscreen-btn"], ) web_preview = gr.HTML(value="", visible=False, min_height=680)
with gr.Tab("Console", id=TAB_CONSOLE): py_stdout = gr.Textbox( label="Program output (stdout)", lines=11, interactive=False, elem_classes=["console-box"], placeholder="Program output will appear here after a Python run.", ) py_stderr = gr.Textbox( label="Errors / stderr", lines=7, interactive=False, elem_classes=["console-box", "stderr-box"], placeholder="Tracebacks and error messages will appear here.", )
with gr.Tab("Code", id=TAB_CODE): code_view = gr.Code( label="Generated source", language="python", lines=20, interactive=False, wrap_lines=True, ) download_btn = gr.DownloadButton( "⬇ Download snippet", size="sm", visible=False )
outputs = [ chatbot, prompt, status, result_tabs, preview_placeholder, py_image, web_preview, preview_toolbar, py_stdout, py_stderr, code_view, download_btn, execution_state, ]
new_conversation_btn.click( fn=start_new_conversation, inputs=[], outputs=outputs, show_progress="hidden", )
submit_event = submit_btn.click( fn=handle_submit, inputs=[prompt, target_language, chatbot, execution_state], outputs=outputs, show_progress="minimal", ) prompt_event = prompt.submit( fn=handle_submit, inputs=[prompt, target_language, chatbot, execution_state], outputs=outputs, show_progress="minimal", )
cancellable_events = [submit_event, prompt_event] for btn, ex_prompt, ex_target in example_buttons: set_target = btn.click( fn=lambda t=ex_target: gr.update(value=t), inputs=[], outputs=[target_language], show_progress="hidden", ) run_event = set_target.then( fn=_make_example_runner(ex_prompt, ex_target), inputs=[chatbot, execution_state], outputs=outputs, show_progress="minimal", ) cancellable_events.append(run_event)
stop_btn.click( fn=_cancelled_status, inputs=[], outputs=[status], cancels=cancellable_events, show_progress="hidden", )
# Expand the sandboxed web preview to fill the screen so users can actually # interact with apps larger than the side panel. Runs purely client-side and # keeps the iframe's sandbox attributes intact. fullscreen_btn.click( fn=None, inputs=None, outputs=None, js=( "() => { const f = document.querySelector('.web-frame'); " "if (f) { const r = f.requestFullscreen || f.webkitRequestFullscreen; " "if (r) { try { Promise.resolve(r.call(f)).catch(() => {}); } catch (e) {} } } }" ), )
return demo
demo = build_demo()demo.queue(default_concurrency_limit=2)
if __name__ == "__main__": demo.launch(theme=APP_THEME, css=CUSTOM_CSS)12345678910[project]name = "coding-model-space"version = "0.1.0"description = "Gradio Space that streams code from Cohere and runs generated Python or Web output."requires-python = ">=3.13"dependencies = [ "cohere>=5.16.1", "gradio==6.14.0", "matplotlib>=3.8",]123cohere>=5.16.1gradio==6.14.0matplotlib>=3.8.gitattributesAdded+36
.gitignoreAdded+4
README.mdAdded+30
app.pyAdded+1227
pyproject.tomlAdded+10
requirements.txtAdded+3
uv.lockAdded