Spaces:
Running on Zero
Running on Zero
Download studio.py from himanshu5trpth/checkjson: direct link, hf CLI and curl.
- Browser
- Download file 17.2 kB
-
https://huggingface.co/spaces/himanshu5trpth/checkjson/resolve/main/studio.py
- Command line
-
hf download hf://spaces/himanshu5trpth/checkjson/studio.py
-
curl -L -o studio.py https://huggingface.co/spaces/himanshu5trpth/checkjson/resolve/main/studio.py
17.2 kB
| """The HF2 interface. The original repair and live API handlers are shared.""" | |
| import base64 | |
| import json | |
| from html import escape | |
| import gradio as gr | |
| from ..generators import PRESETS | |
| from ..presets import MODELS, WEB_EXAMPLE_NAMES, WEB_EXAMPLES | |
| from .app import STATIC, _trace_of, make_functions | |
| from .benchmark import benchmark_panel | |
| from .pipeline import STAGES, char_diff | |
| LABELS = dict(box for _, boxes in STAGES for box in boxes) | |
| OUTCOMES = {"pass": "Passed", "fail": "Issue found", "repaired": "Repaired", | |
| "filled": "Filled", "hole": "Needs review", "no_call": "No call", | |
| "skipped": "Skipped"} | |
| CSS = (STATIC / "studio.css").read_text(encoding="utf-8") | |
| # The page is light only. Gradio adds the class "dark" for a dark system theme or ?__theme=dark. | |
| LIGHT_ONLY = """<meta name="color-scheme" content="light"> | |
| <style>html, body {color-scheme: light; background: #f2f5fa !important}</style> | |
| <script> | |
| (() => { | |
| const light = () => document.querySelectorAll(".dark").forEach(e => e.classList.remove("dark")); | |
| if (window.self !== window.top) document.documentElement.classList.add("embedded"); | |
| new MutationObserver(light).observe(document.documentElement, {subtree: true, attributes: true, attributeFilter: ["class"]}); | |
| document.addEventListener("DOMContentLoaded", light); | |
| light(); | |
| })(); | |
| </script>""" | |
| # Phones only: nothing is wider than the screen. This goes in the page head, because Gradio rewrites the | |
| # selectors inside a media query of its css option. | |
| PHONE = """<style> | |
| @media (max-width: 720px) { | |
| .gradio-container, .gradio-container :is(.main, .wrap, .contain, .tabs, .tabitem, .tab-wrapper, .tab-container, .column:not(.studio-card)) {min-width: 0 !important; max-width: 100% !important} | |
| .gradio-container, .gradio-container .main {width: 100% !important} | |
| } | |
| </style>""" | |
| # The colours of preview.html: teal instead of Gradio's orange, on a light blue-grey page. | |
| TEAL = gr.themes.Color(c50="#eefaf6", c100="#d7f4eb", c200="#b0e8d8", c300="#75bfb1", c400="#2f9d8a", c500="#007f6f", | |
| c600="#007666", c700="#006356", c800="#075347", c900="#06443a", c950="#032a24", name="studio") | |
| THEME = gr.themes.Default(primary_hue=TEAL).set( | |
| body_background_fill="#f2f5fa", body_text_color="#16243a", body_text_color_subdued="#47596f", | |
| border_color_primary="#d9e1eb", color_accent="#007666", link_text_color="#007666", loader_color="#007666", | |
| button_primary_background_fill="#007666", button_primary_background_fill_hover="#006356", | |
| button_primary_border_color="#007666", button_primary_text_color="#ffffff", | |
| button_secondary_background_fill="#ffffff", button_secondary_background_fill_hover="#e7edf4", | |
| button_secondary_border_color="#cdd8e4", input_border_color_focus="#007666") | |
| CAPSULES = "<style>" + (STATIC / "gradio6.css").read_text(encoding="utf-8") + "</style>" | |
| # No "Settings" link in the footer: its panel holds the theme switch. | |
| LAUNCH = {"css": CSS, "head": LIGHT_ONLY + PHONE + CAPSULES, "theme": THEME, "footer_links": ["api", "gradio"], "favicon_path": str(STATIC / "icon.png")} | |
| def timeline(result): | |
| trace = _trace_of(result) | |
| if not trace or not trace["steps"]: | |
| return '<p class="studio-empty">Run a repair to see its steps.</p>' | |
| cards = [] | |
| previous_payload = None | |
| for index, step in enumerate(trace["steps"]): | |
| outcome = step["outcome"] | |
| label = LABELS.get(step["box"], step["box"]) | |
| before, after = step.get("text_before"), step.get("text_after") | |
| if step.get("payload_after") is not None: | |
| payload = json.dumps(step["payload_after"], ensure_ascii=False, indent=2) | |
| if after is None: | |
| before, after = previous_payload, payload | |
| previous_payload = payload | |
| detail = "" | |
| if after is not None and after != before: | |
| content = char_diff(before, after) if before and len(before) + len(after) < 8000 else escape(after) | |
| detail = f'<details><summary>Inspect JSON</summary><pre>{content}</pre></details>' | |
| model = ' · Model' if step["model_used"] else '' | |
| cards.append( | |
| f'<li class="studio-step" style="--delay:{min(index, 12) * 110}ms">' | |
| f'<span class="studio-number">{index + 1:02}</span>' | |
| f'<div><strong>{escape(label)}</strong><p>{escape(step["message"] or "")}</p>{detail}</div>' | |
| f'<span class="studio-state {escape(outcome)}">{escape(OUTCOMES.get(outcome, outcome))}{model}</span></li>' | |
| ) | |
| return '<ol class="studio-flow" aria-label="Repair timeline">' + "".join(cards) + '</ol>' | |
| def result_view(): | |
| with gr.Column(elem_classes=["studio-card"]): | |
| gr.Markdown("### Result") | |
| summary = gr.Textbox(label="Outcome", show_label=False, interactive=False) | |
| flow = gr.HTML(timeline(None)) | |
| with gr.Accordion("Full trace and result", open=False): | |
| steps = gr.Textbox(label="Steps", interactive=False) | |
| result = gr.Code(label="Result JSON", language="json", interactive=False) | |
| return summary, flow, steps, result | |
| def attach_trace(event, result, flow): | |
| event.then(timeline, result, flow, api_visibility="private", queue=False) | |
| def api_fields(public): | |
| providers = [name for name in PRESETS if not (public and name == "ollama")] | |
| with gr.Row(): | |
| provider = gr.Dropdown([*providers, "custom"], value="openrouter", label="Provider") | |
| model = gr.Textbox(value=MODELS["openrouter"], label="Model") | |
| with gr.Row(): | |
| url = gr.Textbox(value=PRESETS["openrouter"], label="Base URL") | |
| key = gr.Textbox(label="API key", type="password") | |
| gr.Markdown("Use a model with tool calling. Your key is sent with this request to the selected endpoint.") | |
| button = gr.Button("Test API and repair", variant="primary") | |
| provider.change(lambda name: (PRESETS.get(name, ""), MODELS.get(name, "")), | |
| provider, [url, model], api_visibility="private", queue=False) | |
| return button, url, model, key | |
| def wire_api(fields, live, tools, question, reply, view, *, standalone=False): | |
| button, url, model, key = fields | |
| summary, flow, steps, result = view | |
| event = button.click(live, [url, model, key, tools, question], [summary, reply, steps, result], | |
| # Only the two public events may be called "repair" and "live". Clients and the website use them. | |
| api_name="live" if standalone else "panel_live", | |
| api_visibility="public" if standalone else "private") | |
| attach_trace(event, result, flow) | |
| def example_panel(repair, live, public, *, sample): | |
| request_value, tools_value, candidate_value = WEB_EXAMPLES[0] | |
| with gr.Row(elem_classes=["studio-workspace"]): | |
| with gr.Column(elem_classes=["studio-card"]): | |
| if sample: | |
| choice = gr.Dropdown([(name, i) for i, name in enumerate(WEB_EXAMPLE_NAMES)], | |
| value=0, label="Example") | |
| request = gr.Textbox(value=request_value if sample else "", label="Request", interactive=not sample) | |
| with gr.Accordion("Tool schema", open=not sample): | |
| tools = gr.Code(value=tools_value if sample else "", label="Tools JSON", | |
| language="json", interactive=not sample, max_lines=12) | |
| with gr.Tabs(elem_classes=["studio-compact-tabs"]): | |
| with gr.Tab("Repair call"): | |
| candidate = gr.Textbox(value=candidate_value if sample else "", label="Candidate call", | |
| lines=5, interactive=not sample) | |
| button = gr.Button("Repair call", variant="primary") | |
| with gr.Tab("Test your API"): | |
| api = api_fields(public) | |
| reply = gr.Textbox(label="Generated candidate", interactive=False, lines=3) | |
| if sample: | |
| choice.change(lambda i: WEB_EXAMPLES[i], choice, [request, tools, candidate], | |
| api_visibility="private", queue=False) | |
| summary, flow, steps, result = result_view() | |
| event = button.click(repair, [request, tools, candidate], [summary, steps, result], | |
| api_name="sample_repair" if sample else "repair", | |
| api_visibility="private" if sample else "public") | |
| attach_trace(event, result, flow) | |
| wire_api(api, live, tools, request, reply, (summary, flow, steps, result)) | |
| HOME = """<section class="studio-hero"> | |
| <h1>Fix broken tool calls.</h1> | |
| <p class="studio-lead">Repair the JSON before your app uses it. See exactly what changed.</p> | |
| <div class="studio-story" aria-label="The model sends a string, CheckJSON wraps it in a list, and the repaired call passes schema validation."> | |
| <div class="studio-story-card"><small>Model output</small><code>"domain": "lock"</code><span class="studio-problem">Expected a list</span></div> | |
| <span class="studio-arrow" aria-hidden="true">→</span> | |
| <div class="studio-story-card"><img src="__ASSET__checkjson-icon.png" alt=""><small>CheckJSON</small><code>"domain": <mark>[</mark>"lock"<mark>]</mark></code><span>Wraps the value in a list</span></div> | |
| <span class="studio-arrow" aria-hidden="true">→</span> | |
| <div class="studio-story-card"><small>Repaired call</small><code>"domain": ["lock"]</code><span class="studio-success">✓ Passes schema validation</span></div> | |
| </div></section> | |
| <section class="studio-chapter"><div><h2>The right tool.<br>A broken call.</h2><p>A small formatting error can stop the whole request.</p></div><figure><img src="__ASSET__paper-intro.png" alt="Smart Lock example showing the original model call and the repaired output"><figcaption>Smart Lock repair from the paper</figcaption></figure></section> | |
| <section class="studio-chapter studio-chapter-reverse"><div><h2>See what changed.</h2><p>Follow the checks and edits from the original call to the result.</p></div><figure><img src="__ASSET__figure2-overview.png" alt="CheckJSON pipeline from tool-call validation through repair and output"><figcaption>CheckJSON repair pipeline</figcaption></figure></section> | |
| <section class="studio-chapter studio-closing"><div><h2>Try a repair.</h2><p>Start with Smart Lock in the Demo tab.</p></div><div class="studio-score"><strong>46.50% → 99.36%</strong><span>Schema-valid calls on 157 RestGPT queries</span></div></section>""" | |
| METHOD = """<section class="studio-info studio-method"><h2>How it works</h2> | |
| <p>CheckJSON sits between the model response and the tool. It reads the user request, the tool definition, and the candidate call. It returns a repaired call and a trace your application can inspect.</p> | |
| <h3>Start with a real call</h3><figure><img src="__ASSET__paper-intro.png" alt="A model generates a malformed Home Assistant call. CheckJSON fixes the quotes and converts the domain string into a list."><figcaption><strong>Figure 1. A repair in context.</strong> The model identifies the Smart Lock, but single quotes break JSON parsing and the tool expects <code>domain</code> to be a list. CheckJSON fixes both issues while keeping the tool name and the other arguments.</figcaption></figure> | |
| <p class="stage-note">The request gives context about the device. The tool definition tells CheckJSON what a valid argument looks like. In this example, the source already says “Entry” and “lock,” so neither value needs to be invented. The repair changes the quote style and wraps the existing domain value in brackets.</p> | |
| <h3>Follow the pipeline</h3><figure><img src="__ASSET__figure2-overview.png" alt="CheckJSON pipeline showing detection, rule-based and model-assisted repair, safeguards, and output."><figcaption><strong>Figure 2. The repair pipeline.</strong> Follow the call from validation through the relevant repair steps to the final output.</figcaption></figure> | |
| <ol> | |
| <li><strong>Parse first, then validate.</strong> Parsing checks whether the response is legal JSON. Schema validation checks whether the named tool exists and whether its arguments meet the declared types and requirements. A call can parse successfully and still fail validation.</li> | |
| <li><strong>Repair syntax before argument structure.</strong> When parsing fails, lexical rules address supported problems such as quotes, punctuation, and brackets. Once the call can be read, schema-aware rules can fix supported mismatches in names and argument types. In the Smart Lock case, fixing the quotes exposes the remaining string-versus-list error.</li> | |
| <li><strong>Use the optional corrector for gaps.</strong> If rules leave a hole and a corrector is configured, it can propose a value from the request or help resolve whether a call is needed. Rules-only mode leaves a hole unresolved when it cannot be repaired. Proposed repairs are checked before returning.</li> | |
| <li><strong>Inspect what came back.</strong> A valid call can pass through unchanged. A repaired call comes back with a trace of the checks and edits. The output can also indicate an unresolved hole or that a tool call is unnecessary. Schema validation establishes the shape of the call. Your application still checks intent and permission before execution.</li> | |
| </ol><p class="stage-note">In Demo, replay Smart Lock to compare the two failed checks with the two edits. Expand <strong>Inspect JSON</strong> on a repair step to see the change.</p></section>""" | |
| INSTALL = """<section class="studio-info studio-install"><h2>Install CheckJSON</h2><p>Install the prerelease and run a built-in example locally.</p><pre><code>python -m pip install --pre checkjson-repair | |
| checkjson example | |
| ckjn tui</code></pre><p><a href="https://himanshu5trpth.github.io/checkjson-interactive/#home">Project website</a> · <a href="https://pypi.org/project/checkjson-repair/">CheckJSON on PyPI</a></p></section>""" | |
| def embed_assets(markup, *names): | |
| assets = STATIC.parents[2] / "assets" | |
| for name in names: | |
| encoded = base64.b64encode((assets / name).read_bytes()).decode("ascii") | |
| markup = markup.replace("__ASSET__" + name, "data:image/png;base64," + encoded) | |
| return markup | |
| def benchmark_results(): | |
| readme = (STATIC.parents[2] / "README.md").read_text(encoding="utf-8") | |
| return ("## Benchmark results" + | |
| readme.split("## Benchmark results", 1)[1].split("## Call it from Python", 1)[0]) | |
| def build_studio(engine=None, public=True): | |
| repair, live = make_functions(engine, public) | |
| with gr.Blocks(title="CheckJSON Studios @ HuggingFace", analytics_enabled=False) as page: | |
| gr.HTML(embed_assets('<h1 class="studio-brand-title"><img class="studio-brand-icon" src="__ASSET__checkjson-icon.png" alt=""> <span aria-label="CheckJSON Studios">C<span class="studio-brand-smallcaps">HECK</span><span class="studio-brand-json">JSON</span> Studios</span> <span class="studio-brand-host">@ <span role="img" aria-label="Hugging Face">🤗</span></span></h1>', "checkjson-icon.png"), elem_id="studio-header") | |
| with gr.Tabs(elem_classes=["studio-pages"]): | |
| with gr.Tab("Home"): | |
| gr.HTML(embed_assets(HOME, "checkjson-icon.png", "paper-intro.png", "figure2-overview.png")) | |
| with gr.Tab("Demo"): | |
| with gr.Tabs(elem_classes=["studio-modes"]): | |
| with gr.Tab("Try an example"): | |
| example_panel(repair, live, public, sample=True) | |
| data = STATIC.parents[2] / "data" / "benchmark.json.gz" | |
| if data.is_file(): | |
| with gr.Tab("Benchmark calls"): | |
| benchmark_panel(data, repair, result_view, timeline, attach_trace) | |
| with gr.Tab("Bring your own"): | |
| example_panel(repair, live, public, sample=False) | |
| with gr.Tab("Test your API"): | |
| with gr.Row(elem_classes=["studio-workspace"]): | |
| with gr.Column(elem_classes=["studio-card"]): | |
| request_value, tools_value, _ = WEB_EXAMPLES[0] | |
| request = gr.Textbox(value=request_value, label="Request") | |
| with gr.Accordion("Tool schema", open=False): | |
| tools = gr.Code(value=tools_value, label="Tools JSON", language="json", max_lines=12) | |
| api = api_fields(public) | |
| reply = gr.Textbox(label="Generated candidate", interactive=False, lines=3) | |
| view = result_view() | |
| wire_api(api, live, tools, request, reply, view, standalone=True) | |
| with gr.Tab("How it works"): | |
| gr.HTML(embed_assets(METHOD, "paper-intro.png", "figure2-overview.png")) | |
| with gr.Tab("Results"): | |
| gr.Markdown(benchmark_results(), elem_classes=["studio-info", "studio-results"]) | |
| with gr.Tab("Install"): | |
| gr.HTML(INSTALL) | |
| return page | |