Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415162 unmodified lines1920212223242526272829303132333435363738394041421 unmodified line44454647484950515253545556575859606162636465666768697071727374757677787980818283848586878 unmodified lines9697989910010110210310410510610710810911011111210 unmodified lines1231241251261271281291301311 unmodified line133134135136137138139140141142143144145146147148149150151152153import os, shutil, subprocess, zipfile, timefrom pathlib import Pathimport gradio as grROOT = Path(__file__).resolve().parent # /home/user/appDATA = ROOT / "dataset.jsonl"LOG = ROOT / "train.log"OUT = ROOT / "trained_model"ZIP = ROOT / "trained_model.zip"DONE = ROOT / "TRAIN_DONE" # <- completion flagERRF = ROOT / "TRAIN_ERROR" # <- error flag# ---------- helpers ----------def ls_workspace() -> str:rows = []for p in sorted(ROOT.iterdir(), key=lambda x: (x.is_file(), x.name.lower())):2 unmodified linesrows.append(f"{'[DIR]' if p.is_dir() else ' '}\t{size:>10}\t{p.name}")return "\n".join(rows) or "(empty)"def _reset_artifacts():for path in [OUT, ZIP, DONE, ERRF, LOG]:if path.is_dir():shutil.rmtree(path, ignore_errors=True)else:path.unlink(missing_ok=True)def _zip_if_ready() -> bool:"""Zip OUT → ZIP once DONE exists."""if DONE.exists() and OUT.exists():if ZIP.exists():ZIP.unlink()with zipfile.ZipFile(ZIP, "w", compression=zipfile.ZIP_DEFLATED) as z:for p in OUT.rglob("*"):z.write(p, arcname=p.relative_to(OUT))return ZIP.exists()# ---------- train tab callbacks ----------def upload_dataset(file):if not file:return "❌ No file selected.", ls_workspace()1 unmodified linereturn f"✅ Uploaded → {DATA.name}", ls_workspace()def start_training():if not DATA.exists():return "❌ Upload a JSONL first.", ls_workspace()_reset_artifacts()LOG.write_text("🔥 Training started in background…\n", encoding="utf-8")cmd = ["python", "train.py","--dataset", str(DATA),"--output", str(OUT),"--model_name", "Salesforce/codegen-350M-multi","--epochs", "1","--batch_size", "2","--block_size", "256","--learning_rate", "5e-5","--subset", "0",]with open(LOG, "a", encoding="utf-8") as lf:subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT)return "🚀 Training launched. Use Refresh buttons.", ls_workspace()def read_logs():return LOG.read_text(encoding="utf-8")[-20000:] if LOG.exists() else "⏳ Waiting…"def refresh_status_and_download():if ERRF.exists():status = f"❌ Error:\n{ERRF.read_text(encoding='utf-8')[-1200:]}"elif DONE.exists():status = "✅ Training complete."else:status = "⏳ Training…"_zip_if_ready()files = [str(ZIP)] if ZIP.exists() else []return status, gr.Files.update(value=files, visible=bool(files)), ls_workspace()# ---------- test tab ----------def list_models():out = []for p in ROOT.iterdir():8 unmodified linesdef import_zip(zfile):if not zfile:return "❌ No zip selected.", list_models()dest = ROOT / f"imported_{int(time.time())}"dest.mkdir(parents=True, exist_ok=True)with zipfile.ZipFile(zfile.name, "r") as z:z.extractall(dest)return f"✅ Imported to {dest.name}", list_models()def generate(model_path, prompt):if not model_path:return "❌ Select a model."if not prompt or not prompt.strip():return "❌ Enter a prompt."try:from transformers import AutoTokenizer, AutoModelForCausalLM, pipelinetok = AutoTokenizer.from_pretrained(model_path, use_fast=True)10 unmodified linesexcept Exception as e:return f"❌ Error: {e}"# ---------- UI ----------with gr.Blocks(title="Python AI — Train & Test") as app:gr.Markdown("## 🧠 Python AI — Train & Test\nBackground training with DONE flag → reliable zip.\n")with gr.Tab("Train"):with gr.Row():1 unmodified linews = gr.Textbox(label="Workspace", lines=16, value=ls_workspace())up_status = gr.Textbox(label="Upload Status", interactive=False)start = gr.Button("🚀 Start Training", variant="primary")logs = gr.Textbox(label="📜 Logs (click Refresh)", lines=18)refresh_logs_btn = gr.Button("Refresh Logs")status = gr.Textbox(label="Status", interactive=False)downloads = gr.Files(label="📦 Downloads (zips)", value=[], interactive=False)refresh_dl_btn = gr.Button("Refresh Status & Download")ds.change(upload_dataset, inputs=ds, outputs=[up_status, ws])start.click(start_training, outputs=[status, ws])refresh_logs_btn.click(read_logs, outputs=logs)refresh_dl_btn.click(refresh_status_and_download, outputs=[status, downloads, ws])with gr.Tab("Test"):refresh_btn = gr.Button("↻ Refresh Model List")model_list = gr.Dropdown(choices=list_models(), label="Available AIs", interactive=True)zip_in = gr.File(label="Or upload model .zip", file_types=[".zip"])import_status = gr.Textbox(label="Import Status", interactive=False)prompt = gr.Textbox(label="Prompt", lines=8, placeholder="### Instruction:\nPython: write a function ...\n### Response:\n")go = gr.Button("Generate")12345678910111213142 unmodified lines1718192021221 unmodified line24252627282930313233343536373839404142434445464748495051525354555657585960616263648 unmodified lines7374757677787980818283848586878810 unmodified lines991001011021031041051061 unmodified line108109110111112113114115116117118119120121122123124125126127# app.pyimport os, shutil, subprocess, zipfilefrom pathlib import Pathimport gradio as grROOT = Path(_file_).resolve().parent # /home/user/appDATA = ROOT / "dataset.jsonl"LOG = ROOT / "train.log"OUT = ROOT / "trained_model"ZIP = ROOT / "trained_model.zip"def ls_workspace() -> str:rows = []for p in sorted(ROOT.iterdir(), key=lambda x: (x.is_file(), x.name.lower())):2 unmodified linesrows.append(f"{'[DIR]' if p.is_dir() else ' '}\t{size:>10}\t{p.name}")return "\n".join(rows) or "(empty)"def upload_dataset(file):if not file:return "❌ No file selected.", ls_workspace()1 unmodified linereturn f"✅ Uploaded → {DATA.name}", ls_workspace()def start_training():# clean previous artifactsif OUT.exists(): shutil.rmtree(OUT, ignore_errors=True)if ZIP.exists(): ZIP.unlink(missing_ok=True)LOG.write_text("🔥 Training started…\n", encoding="utf-8")cmd = ["python", str(ROOT / "train.py"),"--dataset", str(DATA),"--output", str(OUT),"--zip_path", str(ZIP),"--model_name", "Salesforce/codegen-350M-multi","--epochs", "1","--batch_size", "2","--block_size", "256","--learning_rate", "5e-5",]# run training (blocking) and capture logswith open(LOG, "a", encoding="utf-8") as lf:code = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT).wait()# after process exits, show resultif code == 0 and ZIP.exists():info = f"✅ Training complete. Saved: {OUT.name} | Zip: {ZIP.name}"return info, gr.File.update(value=str(ZIP), visible=True), ls_workspace(), read_logs()else:info = f"❌ Training failed (exit {code}). See logs."return info, gr.File.update(visible=False), ls_workspace(), read_logs()def read_logs():return LOG.read_text(encoding="utf-8")[-20000:] if LOG.exists() else "⏳ Waiting…"def refresh_download():return gr.File.update(value=str(ZIP), visible=ZIP.exists()), ls_workspace()# ---------------- Test tab ----------------def list_models():out = []for p in ROOT.iterdir():8 unmodified linesdef import_zip(zfile):if not zfile:return "❌ No zip selected.", list_models()dest = ROOT / f"imported_model"if dest.exists(): shutil.rmtree(dest, ignore_errors=True)dest.mkdir(parents=True, exist_ok=True)with zipfile.ZipFile(zfile.name, "r") as z:z.extractall(dest)return f"✅ Imported to {dest.name}", list_models()def generate(model_path, prompt):if not model_path: return "❌ Select a model."if not prompt or not prompt.strip(): return "❌ Enter a prompt."try:from transformers import AutoTokenizer, AutoModelForCausalLM, pipelinetok = AutoTokenizer.from_pretrained(model_path, use_fast=True)10 unmodified linesexcept Exception as e:return f"❌ Error: {e}"with gr.Blocks(title="Python AI — Train & Test") as app:gr.Markdown("## 🧠 Python AI — Train & Test (simple + reliable)\nTrainer zips the model itself. UI just shows the zip.\n")with gr.Tab("Train"):with gr.Row():1 unmodified linews = gr.Textbox(label="Workspace", lines=16, value=ls_workspace())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="📦 trained_model.zip", visible=ZIP.exists())refresh_dl_btn = gr.Button("Refresh Download")ds.change(upload_dataset, inputs=ds, outputs=[up_status, ws])start.click(start_training, outputs=[status, download_file, ws, logs])refresh_dl_btn.click(refresh_download, outputs=[download_file, ws])with gr.Tab("Test"):gr.Markdown("### Choose a model folder or upload a .zip, then prompt it")refresh_btn = gr.Button("↻ Refresh Model List")model_list = gr.Dropdown(choices=list_models(), label="Available AIs", interactive=True)zip_in = gr.File(label="Or upload a model .zip", file_types=[".zip"])import_status = gr.Textbox(label="Import Status", interactive=False)prompt = gr.Textbox(label="Prompt", lines=8, placeholder="### Instruction:\nPython: write a function ...\n### Response:\n")go = gr.Button("Generate")
app.py+33-59