File size: 17,230 Bytes
f734d80
 
7c19df4
 
 
 
 
 
 
 
 
f734d80
 
 
 
 
 
 
 
 
 
 
 
7c19df4
f734d80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c19df4
f734d80
7c19df4
 
 
f734d80
7c19df4
f734d80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c19df4
f734d80
 
 
 
 
 
 
7c19df4
 
 
 
 
 
f734d80
 
 
7c19df4
f734d80
 
 
 
 
7c19df4
 
 
 
 
 
 
 
 
f734d80
 
 
 
 
 
 
 
 
 
 
 
 
7c19df4
 
 
 
 
 
f734d80
 
 
7c19df4
f734d80
 
 
 
7c19df4
f734d80
 
7c19df4
 
 
f734d80
 
 
 
 
 
 
 
 
7c19df4
 
 
 
f734d80
7c19df4
f734d80
7c19df4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734d80
7c19df4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734d80
 
7c19df4
f734d80
7c19df4
f734d80
7c19df4
 
 
f734d80
7c19df4
 
 
 
 
 
f734d80
7c19df4
 
f734d80
7c19df4
 
 
 
 
 
 
 
 
 
f734d80
7c19df4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734d80
7c19df4
 
 
 
f734d80
7c19df4
 
 
 
 
f734d80
7c19df4
 
 
 
f734d80
7c19df4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734d80
7c19df4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734d80
7c19df4
 
 
f734d80
7c19df4
f734d80
7c19df4
 
 
 
 
 
f734d80
7c19df4
 
 
 
 
 
 
f734d80
7c19df4
 
 
 
 
 
 
f734d80
7c19df4
 
 
f734d80
 
7c19df4
 
 
 
f734d80
7c19df4
f734d80
7c19df4
f734d80
 
7c19df4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
"""
RoboGen β€” HaptalAI Synthetic Robotics Dataset Generator
Gradio 5.9.1 / Python 3.11

Step flow:
  1  Robot selection (card-style radio)
  2  Task dropdown
  3  Parameter sliders + failure checkboxes
  4  Generate button
  5  Quality results dashboard
  6  Email gate + zip download
"""

from __future__ import annotations

import os
import sys
import io
import zipfile
import tempfile
import traceback
from typing import Optional, Dict, List

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import gradio as gr
import pandas as pd

from generator import (
    generate_dataset,
    score_dataset,
    annotate_quality_scores,
    TASKS_BY_ROBOT,
    ROBOT_CONFIG,
    FAILURE_TYPES,
)
from readme_gen import generate_readme
from airtable import log_email

# ── CSS ───────────────────────────────────────────────────────────────────────

_here = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(_here, "style.css")) as _f:
    CSS = _f.read()

# ── Constants ─────────────────────────────────────────────────────────────────

TASK_LABELS = {
    "pick_and_place":    "Pick and Place",
    "push_object":       "Push Object",
    "grasp_and_lift":    "Grasp and Lift",
    "stacking":          "Stacking",
    "drawer_open_close": "Drawer Open / Close",
}

FAILURE_LABELS = {
    "grasp_slip":        "Grasp Slip",
    "velocity_spike":    "Velocity Spike",
    "torque_saturation": "Torque Saturation",
}

DEFAULTS = {
    "SO-100": {"n_eps": 50, "success": 70, "fmin": 1.0, "fmax": 10.0},
    "SO-101": {"n_eps": 50, "success": 70, "fmin": 1.0, "fmax": 10.0},
    "Koch":   {"n_eps": 30, "success": 75, "fmin": 0.5, "fmax":  8.0},
}

# ── HTML helpers ──────────────────────────────────────────────────────────────

def _results_html(result: Dict, robot: str, task: str) -> str:
    score    = result["overall_score"]
    band     = result["band"]
    n_pass   = result["n_passed"]
    n_flag   = result["n_flagged"]
    n_eps    = result["n_episodes"]
    mismatch = result["mean_mismatch"]
    fb       = result["failure_breakdown"]
    scorer   = result["scorer_used"]
    band_cls = band.lower()
    band_desc = {
        "Clean":   "Trajectories are smooth and anomaly-free. Ready for policy training.",
        "Review":  "Some anomalies detected. Review flagged episodes before training.",
        "Flagged": "High anomaly rate. Best used for failure analysis and augmentation.",
    }.get(band, "")
    total = sum(fb.values()) or 1
    bars  = "".join(
        f'<div class="rg-failure-bar">'
        f'<span class="rg-failure-label">{FAILURE_LABELS.get(k,k)}</span>'
        f'<div class="rg-bar-track"><div class="rg-bar-fill" style="width:{v/total*100:.0f}%"></div></div>'
        f'<span class="rg-bar-count">{v}</span></div>'
        for k, v in sorted(fb.items(), key=lambda x: -x[1])
    )
    task_label = TASK_LABELS.get(task, task)
    return f"""
<div class="rg-results">
  <div class="rg-score-row">
    <div class="rg-score-circle {band_cls}">
      <span class="rg-score-value">{score:.0f}</span>
      <span class="rg-score-denom">/ 100</span>
    </div>
    <div class="rg-score-info">
      <div class="rg-band-badge {band_cls}">{band}</div>
      <div class="rg-band-desc">{band_desc}</div>
    </div>
  </div>
  <div class="rg-stat-grid">
    <div class="rg-stat"><div class="rg-stat-value">{n_eps}</div><div class="rg-stat-label">Total Episodes</div></div>
    <div class="rg-stat"><div class="rg-stat-value" style="color:var(--green)">{n_pass}</div><div class="rg-stat-label">Passed</div></div>
    <div class="rg-stat"><div class="rg-stat-value" style="color:var(--red)">{n_flag}</div><div class="rg-stat-label">Flagged</div></div>
    <div class="rg-stat"><div class="rg-stat-value">{mismatch:.3f}</div><div class="rg-stat-label">Mean Mismatch</div></div>
    <div class="rg-stat"><div class="rg-stat-value">{robot}</div><div class="rg-stat-label">Robot</div></div>
    <div class="rg-stat"><div class="rg-stat-value" style="font-size:0.9rem">{task_label}</div><div class="rg-stat-label">Task</div></div>
  </div>
  <div class="rg-failure-section">
    <div class="rg-failure-title">Failure Type Breakdown</div>
    {bars or "No failure episodes in dataset."}
  </div>
  <div class="rg-scorer-note">
    Scored by HaptalAI misalignment benchmark &middot; scorer: <code>{scorer}</code>
  </div>
</div>"""


def _build_zip(df, result, robot, task, n_eps, success, fmin, fmax, failures) -> str:
    df_out = annotate_quality_scores(df, result)
    readme = generate_readme(
        robot=robot, task=task, n_episodes=n_eps,
        success_rate=success / 100, force_min=fmin, force_max=fmax,
        failures=failures,
        score=result["overall_score"], band=result["band"],
        n_passed=result["n_passed"], n_flagged=result["n_flagged"],
        mean_mismatch=result["mean_mismatch"],
        failure_breakdown=result["failure_breakdown"],
        scorer_used=result["scorer_used"],
    )
    tag = f"{robot.replace('-','')}_{task}"
    fd, path = tempfile.mkstemp(suffix=".zip", prefix=f"robogen_{tag}_")
    os.close(fd)
    with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
        buf = io.BytesIO()
        df_out.to_parquet(buf, index=False)
        zf.writestr(f"robogen_{tag}.parquet", buf.getvalue())
        zf.writestr("README.md", readme.encode("utf-8"))
    return path


# ── Event handlers (module level β€” Gradio 5 requirement) ─────────────────────

def on_robot_select(robot: str):
    if not robot:
        return (
            gr.update(visible=False),
            gr.update(choices=[], value=None),
            gr.update(visible=False),
            gr.update(visible=False),
            "",
        )
    tasks_raw  = TASKS_BY_ROBOT[robot]
    tasks_disp = [(TASK_LABELS.get(t, t), t) for t in tasks_raw]
    return (
        gr.update(visible=True),
        gr.update(choices=tasks_disp, value=tasks_raw[0]),
        gr.update(visible=False),
        gr.update(visible=False),
        robot,
    )


def on_task_select(task: str, robot: str):
    if not task or not robot:
        return gr.update(visible=False), gr.update(visible=False), 50, 70, 1.0, 10.0
    d  = DEFAULTS.get(robot, DEFAULTS["SO-100"])
    fr = ROBOT_CONFIG[robot]["force_range"]
    return (
        gr.update(visible=True),
        gr.update(visible=True),
        d["n_eps"],
        d["success"],
        fr[0],
        fr[1],
    )


def on_generate(robot, task, n_eps, success_pct, fmin, fmax, failures):
    if not robot or not task:
        return (
            "Please complete steps 1 and 2 first.",
            gr.update(visible=False), "",
            gr.update(visible=False),
            None, None,
        )
    if not failures:
        failures = list(FAILURE_TYPES)
    try:
        df = generate_dataset(
            robot=robot, task=task,
            n_episodes=int(n_eps),
            success_rate=float(success_pct) / 100,
            force_min=float(fmin), force_max=float(fmax),
            enabled_failures=list(failures),
            seed=None,
        )
        result  = score_dataset(df)
        panel   = _results_html(result, robot, task)
        status  = (
            f"Generated {len(df):,} rows across {result['n_episodes']} episodes β€” "
            f"score **{result['overall_score']:.1f}/100** ({result['band']})"
        )
        return (
            status,
            gr.update(visible=True), panel,
            gr.update(visible=True),
            df, result,
        )
    except Exception:
        return (
            f"Generation failed:\n```\n{traceback.format_exc()}\n```",
            gr.update(visible=False), "",
            gr.update(visible=False),
            None, None,
        )


def on_email_submit(email, robot, task, n_eps, success_pct, fmin, fmax, failures, df, result):
    if not email or "@" not in email:
        return "Please enter a valid email address.", gr.update(visible=False)
    if df is None or result is None:
        return "Generate a dataset first (Step 4).", gr.update(visible=False)
    try:
        ok, msg = log_email(
            email=email.strip(), robot=robot, task=task,
            n_episodes=int(n_eps),
            quality_score=result["overall_score"],
            band=result["band"],
        )
        if not ok:
            print(f"[RoboGen] Airtable: {msg}")
    except Exception as exc:
        print(f"[RoboGen] Airtable exception: {exc}")
    try:
        path = _build_zip(
            df=df, result=result, robot=robot, task=task,
            n_eps=int(n_eps), success=float(success_pct),
            fmin=float(fmin), fmax=float(fmax),
            failures=list(failures),
        )
        return "Email confirmed. Your download is ready below.", gr.update(visible=True, value=path)
    except Exception:
        return (
            f"Download preparation failed:\n```\n{traceback.format_exc()}\n```",
            gr.update(visible=False),
        )


# ── Build UI ──────────────────────────────────────────────────────────────────

with gr.Blocks(css=CSS, title="RoboGen") as demo:

    robot_state  = gr.State("")
    df_state     = gr.State(None)
    result_state = gr.State(None)

    gr.HTML("""
    <div class="rg-header">
      <div class="rg-logo">RoboGen</div>
      <div class="rg-tagline">Synthetic robotics datasets, physics-accurate &amp; quality-scored</div>
      <div class="rg-badge">LeRobot-format &nbsp;&middot;&nbsp; SO-100 / SO-101 / Koch &nbsp;&middot;&nbsp; HaptalAI</div>
    </div>""")

    # ── Step 1 ────────────────────────────────────────────────────────────────
    with gr.Group(elem_classes=["step-card"]):
        gr.HTML("""
        <div class="step-header">
          <span class="step-num">1</span>
          <span class="step-title">Select Robot</span>
        </div>""")
        robot_select = gr.Radio(
            choices=["SO-100", "Koch", "SO-101"],
            value=None,
            label="",
            elem_classes=["robot-radio"],
        )

    # ── Step 2 ────────────────────────────────────────────────────────────────
    with gr.Group(visible=False, elem_classes=["step-card"]) as step2_grp:
        gr.HTML("""
        <div class="step-header">
          <span class="step-num">2</span>
          <span class="step-title">Select Task</span>
        </div>""")
        task_select = gr.Dropdown(choices=[], value=None, label="Task", interactive=True)

    # ── Step 3 ────────────────────────────────────────────────────────────────
    with gr.Group(visible=False, elem_classes=["step-card"]) as step3_grp:
        gr.HTML("""
        <div class="step-header">
          <span class="step-num">3</span>
          <span class="step-title">Configure Parameters</span>
        </div>""")
        with gr.Row():
            n_episodes_slider = gr.Slider(
                minimum=10, maximum=500, value=50, step=5,
                label="Number of Episodes",
                info="Total episodes in the dataset (10–500)",
            )
            success_slider = gr.Slider(
                minimum=0, maximum=100, value=70, step=5,
                label="Success Rate (%)",
                info="Fraction of episodes with successful trajectories",
            )
        with gr.Row():
            force_min_slider = gr.Slider(
                minimum=0.1, maximum=10.0, value=1.0, step=0.1,
                label="Min Contact Force (N)",
                info="Lower bound of spring-damper contact force during grasping",
            )
            force_max_slider = gr.Slider(
                minimum=1.0, maximum=20.0, value=10.0, step=0.5,
                label="Max Contact Force (N)",
                info="Upper bound of contact force β€” higher = firmer grip",
            )
        gr.HTML("""
        <div style="margin:4px 0 8px;font-size:0.82rem;color:#8892a4;">
          <b>Failure types to include</b> &nbsp;
          <span style="font-style:italic;">
            Grasp Slip β€” gripper opens mid-episode &nbsp;|&nbsp;
            Velocity Spike β€” servo glitch (z&gt;6.5) &nbsp;|&nbsp;
            Torque Saturation β€” joint hits angular limit
          </span>
        </div>""")
        failure_check = gr.CheckboxGroup(
            choices=["grasp_slip", "velocity_spike", "torque_saturation"],
            value=["grasp_slip", "velocity_spike", "torque_saturation"],
            label="",
            elem_classes=["checkbox-group"],
        )

    # ── Step 4 ────────────────────────────────────────────────────────────────
    with gr.Group(visible=False, elem_classes=["step-card"]) as step4_grp:
        gr.HTML("""
        <div class="step-header">
          <span class="step-num">4</span>
          <span class="step-title">Generate Dataset</span>
        </div>""")
        generate_btn = gr.Button("Generate Dataset", elem_classes=["btn-generate"], size="lg")
        gen_status   = gr.Markdown("", elem_classes=["status-msg"])

    # ── Step 5 ────────────────────────────────────────────────────────────────
    with gr.Group(visible=False, elem_classes=["step-card"]) as step5_grp:
        gr.HTML("""
        <div class="step-header">
          <span class="step-num">5</span>
          <span class="step-title">Quality Results</span>
        </div>""")
        results_html = gr.HTML("")

    # ── Step 6 ────────────────────────────────────────────────────────────────
    with gr.Group(visible=False, elem_classes=["step-card"]) as step6_grp:
        gr.HTML("""
        <div class="step-header">
          <span class="step-num">6</span>
          <span class="step-title">Download Dataset</span>
        </div>
        <div class="email-gate-note">
          Enter your email to unlock the download. You'll receive occasional
          updates on new robot configs and dataset improvements.
        </div>""")
        with gr.Row():
            email_input = gr.Textbox(
                placeholder="you@example.com", label="Email",
                scale=4, max_lines=1,
            )
            email_btn = gr.Button("Confirm", elem_classes=["btn-primary"], scale=1)
        email_status = gr.Markdown("")
        download_file = gr.File(label="Download robogen_dataset.zip", visible=False)

    # ── Wire events ───────────────────────────────────────────────────────────

    robot_select.change(
        fn=on_robot_select,
        inputs=[robot_select],
        outputs=[step2_grp, task_select, step3_grp, step4_grp, robot_state],
        api_name=False,
    )

    task_select.change(
        fn=on_task_select,
        inputs=[task_select, robot_state],
        outputs=[step3_grp, step4_grp, n_episodes_slider, success_slider,
                 force_min_slider, force_max_slider],
        api_name=False,
    )

    generate_btn.click(
        fn=on_generate,
        inputs=[robot_state, task_select, n_episodes_slider, success_slider,
                force_min_slider, force_max_slider, failure_check],
        outputs=[gen_status, step5_grp, results_html, step6_grp, df_state, result_state],
        api_name=False,
    )

    email_btn.click(
        fn=on_email_submit,
        inputs=[email_input, robot_state, task_select,
                n_episodes_slider, success_slider,
                force_min_slider, force_max_slider,
                failure_check, df_state, result_state],
        outputs=[email_status, download_file],
        api_name=False,
    )

# ── Launch ────────────────────────────────────────────────────────────────────

demo.queue()

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))