Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891044 unmodified lines55565758596061624 unmodified lines676869707172737 unmodified lines8182838485868788899091929394959697989910010163 unmodified lines16516616716816917022 unmodified lines19319419519619719819918 unmodified lines218219220221222223224225226227228229230231232233234235236# app.pyimport os, shutil, subprocess, zipfile, tracebackfrom pathlib import Pathfrom datetime import datetimeimport gradio as grROOT = Path(__file__).resolve().parentDATA = ROOT / "dataset.jsonl"LOG = ROOT / "train.log"RUNS = ROOT / "runs"44 unmodified linesreturn f"✅ Uploaded → {DATA.name}", ls_workspace()return "⚠ Unexpected item; please upload a .jsonl file.", ls_workspace()# -------- training --------def start_training(run_name):run_id = (run_name or "").strip() or datetime.now().strftime("run_%Y%m%d_%H%M%S")out_dir = RUNS / run_idzip_path = RUNS / f"{run_id}.zip"4 unmodified linesif zip_path.exists():zip_path.unlink()LOG.write_text(f"🔥 Training started…\nRun: {run_id}\n", encoding="utf-8")cmd = ["python", str(ROOT / "train.py"),7 unmodified lines"--learning_rate", "5e-5",]append_log("▶ " + " ".join(cmd))with open(LOG, "a", encoding="utf-8") as lf:code = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT).wait()models = list_models()model_update = dropdown_update_safe(models, prefer=str(out_dir) if out_dir.exists() else None)if code == 0 and zip_path.exists():info = f"✅ Training complete. Saved: {out_dir.name} | Zip: {zip_path.name}"dl_update = gr.update(value=str(zip_path), visible=True)else:info = f"❌ Training failed (exit {code}). Check logs below."dl_update = gr.update(value=None, visible=False)append_log(info)return info, dl_update, ls_workspace(), read_logs(), model_updatedef refresh_download():zips = sorted(RUNS.glob("*.zip"), key=lambda p: p.stat().st_mtime, reverse=True)63 unmodified linesif not model_path:return "❌ Select a model from the dropdown first."if not isinstance(model_path, str):return f"❌ Invalid model path type: {type(model_path)._name_}"if not Path(model_path).exists():return f"❌ Model folder not found: {model_path}"22 unmodified lines# -------- UI --------with gr.Blocks(title="Python AI — Train & Test") as app:gr.Markdown("## 🧠 Python AI — Train & Test\n• Unique runs • Safe download • Cached generation\n")# Test first (so Train can update its dropdown)with gr.Tab("Test"):18 unmodified linesws = gr.Textbox(label="Workspace", lines=16, value=ls_workspace())run_name = gr.Textbox(label="Run name (optional)", placeholder="e.g., python_small_v1")up_status = gr.Textbox(label="Upload Status", interactive=False)start = gr.Button("🚀 Start Training", variant="primary")logs = gr.Textbox(label="📜 Training Logs", lines=18, value=read_logs())status = gr.Textbox(label="Status", interactive=False)download_file = gr.File(label="📦 Latest trained zip", visible=False)refresh_dl_btn = gr.Button("Refresh Download")# wiringds.change(upload_dataset, inputs=ds, outputs=[up_status, ws])start.click(start_training,inputs=[run_name],outputs=[status, download_file, ws, logs, model_list])refresh_dl_btn.click(refresh_download,outputs=[download_file, ws, model_list]1234567891044 unmodified lines5556575859606162636465664 unmodified lines7172737475767778797 unmodified lines8788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714863 unmodified lines21221321421521621721822 unmodified lines24124224324424524624718 unmodified lines266267268269270271272273274275276277278279280281282283284285286287# app.pyimport os, shutil, subprocess, zipfile, traceback, time, iofrom pathlib import Pathfrom datetime import datetimeimport gradio as grROOT = Path(_file_).resolve().parentDATA = ROOT / "dataset.jsonl"LOG = ROOT / "train.log"RUNS = ROOT / "runs"44 unmodified linesreturn f"✅ Uploaded → {DATA.name}", ls_workspace()return "⚠ Unexpected item; please upload a .jsonl file.", ls_workspace()# -------- training (LIVE LOGS) --------def start_training_live(run_name):"""Streams training logs to the UI while the subprocess runs.Yields tuples for outputs: [status, download_file, workspace, logs, model_dropdown]"""run_id = (run_name or "").strip() or datetime.now().strftime("run_%Y%m%d_%H%M%S")out_dir = RUNS / run_idzip_path = RUNS / f"{run_id}.zip"4 unmodified linesif zip_path.exists():zip_path.unlink()# init logLOG.write_text(f"🔥 Training started…\nRun: {run_id}\n", encoding="utf-8")append_log(f"Workspace:\n{ls_workspace()}")cmd = ["python", str(ROOT / "train.py"),7 unmodified lines"--learning_rate", "5e-5",]append_log("▶ " + " ".join(cmd))# start subprocess with live stdoutproc = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,bufsize=1,universal_newlines=True,encoding="utf-8",errors="replace",)live_log = io.StringIO()status_msg = f"🚀 Training run '{run_id}' in progress…"# stream loopwhile True:line = proc.stdout.readline()if line == "" and proc.poll() is not None:breakif line:append_log(line.rstrip("\n"))live_log.write(line)# Trim to last ~20k chars for UItext = live_log.getvalue()[-20000:]# yield with download hidden (until zip exists)yield (status_msg,gr.update(value=None, visible=False),ls_workspace(),text,dropdown_update_safe(list_models(), prefer=None),)# if zip appears during training (e.g., early save), surface itif zip_path.exists():yield ("📦 Model zip created during run.",gr.update(value=str(zip_path), visible=True),ls_workspace(),text,dropdown_update_safe(list_models(), prefer=None),)code = proc.wait()models = list_models()model_update = dropdown_update_safe(models, prefer=str(out_dir) if out_dir.exists() else None)final_logs = read_logs()if code == 0 and zip_path.exists():info = f"✅ Training complete. Saved: {out_dir.name} | Zip: {zip_path.name}"append_log(info)yield (info, gr.update(value=str(zip_path), visible=True), ls_workspace(), final_logs, model_update)else:info = f"❌ Training failed (exit {code}). Check logs below."append_log(info)yield (info, gr.update(value=None, visible=False), ls_workspace(), final_logs, model_update)def refresh_download():zips = sorted(RUNS.glob("*.zip"), key=lambda p: p.stat().st_mtime, reverse=True)63 unmodified linesif not model_path:return "❌ Select a model from the dropdown first."if not isinstance(model_path, str):# fix minor bug: _name_ not namereturn f"❌ Invalid model path type: {type(model_path)._name_}"if not Path(model_path).exists():return f"❌ Model folder not found: {model_path}"22 unmodified lines# -------- UI --------with gr.Blocks(title="Python AI — Train & Test") as app:gr.Markdown("## 🧠 Python AI — Train & Test\n• Unique runs • Safe download • Cached generation • Live logs\n")# Test first (so Train can update its dropdown)with gr.Tab("Test"):18 unmodified linesws = gr.Textbox(label="Workspace", lines=16, value=ls_workspace())run_name = gr.Textbox(label="Run name (optional)", placeholder="e.g., python_small_v1")up_status = gr.Textbox(label="Upload Status", interactive=False)start = gr.Button("🚀 Start Training (Live Logs)", variant="primary")logs = gr.Textbox(label="📜 Training Logs (live)", lines=18, value=read_logs())status = gr.Textbox(label="Status", interactive=False)download_file = gr.File(label="📦 Latest trained zip", visible=False)refresh_dl_btn = gr.Button("Refresh Download")# wiringds.change(upload_dataset, inputs=ds, outputs=[up_status, ws])# STREAMED training: function yields updatesstart.click(start_training_live,inputs=[run_name],outputs=[status, download_file, ws, logs, model_list])refresh_dl_btn.click(refresh_download,outputs=[download_file, ws, model_list]
app.py+66-15