zino36 commited on
Commit
7d39621
Β·
verified Β·
1 Parent(s): 1735090

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +203 -0
app.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, subprocess, json, pathlib, time
2
+ import gradio as gr
3
+
4
+ # ---------- CONSTANTS ----------
5
+ RUN_ROOT = "/home/user/app/runs" # where all runs are stored (visible in App Files)
6
+ LAST_PTR = pathlib.Path(RUN_ROOT) / "LAST" # file that stores path to the most recent run
7
+ os.makedirs(RUN_ROOT, exist_ok=True)
8
+
9
+ # env helpers (with correct names)
10
+ DEFAULT_REPO_ID = os.environ.get("REPO_ID", "")
11
+ PUSH_DEFAULT = os.environ.get("PUSH_TO_HUB", "true").lower() in {"1","true","yes"}
12
+ HF_TOKEN = os.environ.get("HF_TOKEN")
13
+
14
+ # Optional: login with a Space secret named HF_TOKEN
15
+ if HF_TOKEN:
16
+ try:
17
+ from huggingface_hub import login
18
+ login(token=HF_TOKEN)
19
+ except Exception as e:
20
+ print("HF login failed:", e)
21
+
22
+ # ---------- LOG HELPERS ----------
23
+ def _run(cmd: str, logfile: str):
24
+ os.makedirs(os.path.dirname(logfile), exist_ok=True)
25
+ with open(logfile, "a", buffering=1) as f:
26
+ f.write("\n---- CMD ----\n" + cmd + "\n--------------\n")
27
+ p = subprocess.Popen(cmd, shell=True,
28
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
29
+ text=True, bufsize=1)
30
+ lines = []
31
+ for line in p.stdout:
32
+ f.write(line)
33
+ lines.append(line)
34
+ p.wait()
35
+ return p.returncode, "".join(lines[-200:])
36
+
37
+ def tail_file(path: str, n=200):
38
+ if not os.path.exists(path):
39
+ return "(no log yet)"
40
+ with open(path, "r", errors="ignore") as f:
41
+ lines = f.readlines()
42
+ return "".join(lines[-n:])
43
+
44
+ # ---------- RUN DIR HELPERS ----------
45
+ def new_run_dir():
46
+ d = pathlib.Path(RUN_ROOT) / f"pusht_{int(time.time())}"
47
+ d.mkdir(parents=True, exist_ok=True)
48
+ LAST_PTR.write_text(str(d))
49
+ return str(d)
50
+
51
+ def current_run_dir(user_override: str | None):
52
+ if user_override and user_override.strip():
53
+ return user_override.strip()
54
+ if LAST_PTR.exists():
55
+ return LAST_PTR.read_text().strip()
56
+ return "" # none yet
57
+
58
+ def has_checkpoint(run_dir: str):
59
+ return os.path.isdir(os.path.join(run_dir, "checkpoints", "last"))
60
+
61
+ def train_log_path(run_dir: str):
62
+ return os.path.join(run_dir, "logs", "train.log")
63
+
64
+ def eval_log_path(run_dir: str):
65
+ return os.path.join(run_dir, "logs", "eval.log")
66
+
67
+ # ---------- ACTIONS ----------
68
+ def start_training(steps, batch_size, push_to_hub, repo_id):
69
+ run_dir = new_run_dir()
70
+ log = train_log_path(run_dir)
71
+
72
+ push_flags = (f"--policy.push_to_hub=true --policy.repo_id='{repo_id.strip()}'"
73
+ if push_to_hub and repo_id.strip() else
74
+ "--policy.push_to_hub=false")
75
+
76
+ cmd = (
77
+ "lerobot-train "
78
+ f"--output_dir='{run_dir}' "
79
+ "--policy.type=diffusion "
80
+ "--dataset.repo_id=lerobot/pusht "
81
+ "--env.type=pusht "
82
+ f"--batch_size={batch_size} "
83
+ f"--steps={steps} "
84
+ "--eval_freq=500 "
85
+ "--save_freq=500 "
86
+ f"{push_flags}"
87
+ )
88
+ rc, tail = _run(cmd, log)
89
+ msg = f"Started fresh run at: {run_dir}\nTrain exited rc={rc}\n\n=== train.log tail ===\n{tail}"
90
+ return msg, run_dir, tail_file(log)
91
+
92
+ def resume_training(extra_steps, push_to_hub, repo_id, run_dir_text):
93
+ run_dir = current_run_dir(run_dir_text)
94
+ if not run_dir:
95
+ return "No run found yet. Start a fresh training first.", "", "(no log)"
96
+ log = train_log_path(run_dir)
97
+
98
+ if not has_checkpoint(run_dir):
99
+ return f"No checkpoint in {run_dir}/checkpoints/last/ yet β€” let the run save once (>= first 500 steps).", run_dir, tail_file(log)
100
+
101
+ push_flags = (f"--policy.push_to_hub=true --policy.repo_id='{repo_id.strip()}'"
102
+ if push_to_hub and repo_id.strip() else
103
+ "--policy.push_to_hub=false")
104
+
105
+ cmd = (
106
+ "lerobot-train "
107
+ f"--output_dir='{run_dir}' "
108
+ "--resume=true "
109
+ f"--steps={extra_steps} "
110
+ "--eval_freq=500 "
111
+ "--save_freq=500 "
112
+ f"{push_flags}"
113
+ )
114
+ rc, tail = _run(cmd, log)
115
+ msg = f"Resumed run at: {run_dir}\nResume exited rc={rc}\n\n=== train.log tail ===\n{tail}"
116
+ return msg, run_dir, tail_file(log)
117
+
118
+ def eval_latest(run_dir_text):
119
+ run_dir = current_run_dir(run_dir_text)
120
+ if not run_dir:
121
+ return "No run found yet. Start a fresh training first.", "", "(no log)", "(no metrics)"
122
+ elog = eval_log_path(run_dir)
123
+
124
+ if not has_checkpoint(run_dir):
125
+ return f"No checkpoint in {run_dir}/checkpoints/last/ to evaluate.", run_dir, tail_file(elog), "(no metrics)"
126
+
127
+ ckpt = os.path.join(run_dir, "checkpoints", "last", "pretrained_model")
128
+ eval_out_dir = os.path.join(run_dir, "eval_latest")
129
+ os.makedirs(eval_out_dir, exist_ok=True)
130
+
131
+ cmd = (
132
+ "lerobot-eval "
133
+ f"--policy.path='{ckpt}' "
134
+ "--env.type=pusht "
135
+ "--eval.n_episodes=100 "
136
+ "--eval.batch_size=50 "
137
+ f"--output_dir='{eval_out_dir}'"
138
+ )
139
+ rc, tail = _run(cmd, elog)
140
+ metrics_txt = "(metrics.json not found)"
141
+ p = pathlib.Path(eval_out_dir) / "metrics.json"
142
+ if p.exists():
143
+ try:
144
+ m = json.loads(p.read_text())
145
+ metrics_txt = f"Success rate: {m.get('success_rate')}\nAvg max overlap: {m.get('avg_max_overlap')}"
146
+ except Exception:
147
+ metrics_txt = "(could not parse metrics.json)"
148
+ msg = f"Evaluated run at: {run_dir}\nEval exited rc={rc}\n\n=== eval.log tail ===\n{tail}"
149
+ return msg, run_dir, tail_file(elog), metrics_txt
150
+
151
+ def list_runs():
152
+ root = pathlib.Path(RUN_ROOT)
153
+ if not root.exists():
154
+ return "(no runs)"
155
+ rows = []
156
+ for d in sorted(root.glob("pusht_*")):
157
+ size = subprocess.check_output(["bash","-lc", f"du -sh {d} | cut -f1"], text=True).strip()
158
+ ck = "βœ“" if has_checkpoint(str(d)) else "β€”"
159
+ rows.append(f"{d.name}\t{size}\tcheckpoint:{ck}")
160
+ return "name\tsize\tcheckpoint\n" + "\n".join(rows) if rows else "(no runs)"
161
+
162
+ # ---------- UI ----------
163
+ with gr.Blocks(title="LeRobot PushT Trainer (Space)") as demo:
164
+ gr.Markdown("# πŸ€– LeRobot PushT Trainer\nTrain / Resume / Evaluate. Files persist under `/home/user/app/runs/` (see App Files).")
165
+
166
+ with gr.Row():
167
+ repo_id = gr.Textbox(label="Hugging Face Model Repo (optional)", value=DEFAULT_REPO_ID, placeholder="username/repo-name")
168
+ push_to_hub = gr.Checkbox(label="Push checkpoints to Hub", value=PUSH_DEFAULT)
169
+
170
+ with gr.Row():
171
+ steps = gr.Slider(200, 20000, value=2000, step=100, label="Training steps (fresh run)")
172
+ batch = gr.Slider(4, 64, value=16, step=2, label="Batch size")
173
+
174
+ start_btn = gr.Button("πŸš€ Start Fresh Training")
175
+ start_out = gr.Textbox(label="Start Output")
176
+ run_dir_view = gr.Textbox(label="Current run directory (auto-filled after start)")
177
+ train_log = gr.Textbox(label="train.log (tail)", lines=20)
178
+
179
+ gr.Markdown("### Resume / Evaluate a Specific Run")
180
+ run_dir_text = gr.Textbox(label="Run directory (leave blank to use the latest)")
181
+ with gr.Row():
182
+ extra_steps = gr.Slider(200, 20000, value=2000, step=100, label="Steps to add on resume")
183
+ resume_btn = gr.Button("▢️ Resume from Last Checkpoint")
184
+ resume_out = gr.Textbox(label="Resume Output")
185
+ resume_log = gr.Textbox(label="train.log (tail)", lines=20)
186
+
187
+ gr.Markdown("### Evaluate Latest Checkpoint of Selected Run")
188
+ eval_btn = gr.Button("πŸ“ˆ Evaluate Latest")
189
+ eval_out = gr.Textbox(label="Eval Output")
190
+ eval_log = gr.Textbox(label="eval.log (tail)", lines=20)
191
+ metrics_box = gr.Textbox(label="Parsed metrics (if metrics.json exists)")
192
+
193
+ gr.Markdown("### Runs on disk")
194
+ list_btn = gr.Button("πŸ“‚ List runs folder")
195
+ list_out = gr.Textbox(label="runs/ listing", lines=12)
196
+
197
+ start_btn.click(start_training, inputs=[steps, batch, push_to_hub, repo_id], outputs=[start_out, run_dir_view, train_log])
198
+ resume_btn.click(resume_training, inputs=[extra_steps, push_to_hub, repo_id, run_dir_text], outputs=[resume_out, run_dir_view, resume_log])
199
+ eval_btn.click(eval_latest, inputs=[run_dir_text], outputs=[eval_out, run_dir_view, eval_log, metrics_box])
200
+ list_btn.click(list_runs, outputs=list_out)
201
+
202
+ if __name__ == "__main__":
203
+ demo.launch()