Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines34567897 unmodified lines17181920212220 unmodified lines434445464748495051525354555657585960616263646566676869707172737475767720 unmodified lines98991001011021031041055 unmodified lines1111121131141151161171181191201211221231241251261271281291301311322 unmodified linesfrom pathlib import Pathimport gradio as grROOT = Path(__file__).resolve().parent # /home/user/appDATA = ROOT / "dataset.jsonl"LOG = ROOT / "train.log"OUT = ROOT / "trained_model"7 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()20 unmodified lineswith open(LOG, "a", encoding="utf-8") as lf:code = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT).wait()if code == 0 and ZIP.exists():info = f"✅ Training complete. Saved: {OUT.name} | Zip: {ZIP.name}"return info, gr.update(value=str(ZIP), visible=True), ls_workspace(), read_logs()else:info = f"❌ Training failed (exit {code}). See logs."return info, gr.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.update(value=str(ZIP), visible=ZIP.exists()), ls_workspace()# ---------------- Test tab ----------------def list_models():out = []for p in ROOT.iterdir():if p.is_dir() and (p / "config.json").exists() and ((p / "tokenizer.json").exists() or (p / "tokenizer_config.json").exists()):out.append(str(p))if OUT.exists() and str(OUT) not in out:out.insert(0, str(OUT))return sorted(out)def 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:20 unmodified linesreturn 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():ds = gr.File(label="📥 Upload JSONL", file_types=[".jsonl", ".jsonl.gz", ".json"])5 unmodified linesdownload_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")out = gr.Textbox(label="AI Response", lines=20)refresh_btn.click(list_models, outputs=model_list)zip_in.change(import_zip, inputs=zip_in, outputs=[import_status, model_list])go.click(generate, inputs=[model_list, prompt], outputs=out)app.launch()2 unmodified lines34567897 unmodified lines171819202122232425262728293031323320 unmodified lines545556575859606162636465666768697071727374757677787980818220 unmodified lines1031041051061071081091101111121131141151161171181191201211225 unmodified lines1281291301311321331341351361371381391401411421431441452 unmodified linesfrom pathlib import Pathimport gradio as grROOT = Path(_file_).resolve().parentDATA = ROOT / "dataset.jsonl"LOG = ROOT / "train.log"OUT = ROOT / "trained_model"7 unmodified linesrows.append(f"{'[DIR]' if p.is_dir() else ' '}\t{size:>10}\t{p.name}")return "\n".join(rows) or "(empty)"def list_models():out = []for p in ROOT.iterdir():if p.is_dir() and (p / "config.json").exists() and ((p / "tokenizer.json").exists() or (p / "tokenizer_config.json").exists()):out.append(str(p))if OUT.exists() and str(OUT) not in out:out.insert(0, str(OUT))return sorted(out)def upload_dataset(file):if not file:return "❌ No file selected.", ls_workspace()20 unmodified lineswith open(LOG, "a", encoding="utf-8") as lf:code = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT).wait()# build model-list update payloadmodels = list_models()model_update = gr.update(choices=models, value=str(OUT) if OUT.exists() else None)if code == 0 and ZIP.exists():info = f"✅ Training complete. Saved: {OUT.name} | Zip: {ZIP.name}"return info, gr.update(value=str(ZIP), visible=True), ls_workspace(), read_logs(), model_updateelse:info = f"❌ Training failed (exit {code}). See logs."return info, gr.update(visible=False), ls_workspace(), read_logs(), model_updatedef read_logs():return LOG.read_text(encoding="utf-8")[-20000:] if LOG.exists() else "⏳ Waiting…"def refresh_download():# also refresh model dropdownmodels = list_models()return gr.update(value=str(ZIP), visible=ZIP.exists()), ls_workspace(), gr.update(choices=models)def import_zip(zfile):if not zfile:return "❌ No zip selected.", list_models()dest = ROOT / "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:20 unmodified linesreturn f"❌ Error: {e}"with gr.Blocks(title="Python AI — Train & Test") as app:gr.Markdown("## 🧠 Python AI — Train & Test (auto-add to Test tab)")# --- Test tab UI FIRST so we can reference components ---with gr.Tab("Test"):gr.Markdown("### Pick a model or upload a .zip")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")out = gr.Textbox(label="AI Response", lines=20)# --- Train tab UI ---with gr.Tab("Train"):with gr.Row():ds = gr.File(label="📥 Upload JSONL", file_types=[".jsonl", ".jsonl.gz", ".json"])5 unmodified linesdownload_file = gr.File(label="📦 trained_model.zip", visible=ZIP.exists())refresh_dl_btn = gr.Button("Refresh Download")# --- wiring ---ds.change(upload_dataset, inputs=ds, outputs=[up_status, ws])start.click(start_training,outputs=[status, download_file, ws, logs, model_list] # <-- update Test dropdown automatically)refresh_dl_btn.click(refresh_download,outputs=[download_file, ws, model_list] # <-- also updates Test dropdown)refresh_btn.click(lambda: gr.update(choices=list_models()), outputs=model_list)zip_in.change(import_zip, inputs=zip_in, outputs=[import_status, model_list])go.click(generate, inputs=[model_list, prompt], outputs=out)app.launch()
app.py+48-35