Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678920 unmodified lines3031323334353637383940414243447 unmodified lines525354555657585960615 unmodified lines676869707172737475767 unmodified lines8485868788899034 unmodified lines12512612712812913013113213313413523 unmodified lines159160161162163164165import os, shutil, subprocess, zipfilefrom pathlib import Pathimport gradio as grROOT = Path(__file__).resolve().parentDATA = ROOT / "dataset.jsonl" # single-file mode targetLOG = ROOT / "train.log"OUT = ROOT / "trained_model"ZIP = ROOT / "trained_model.zip"20 unmodified linesout.insert(0, str(OUT))return sorted(out)# ---------- train tab ----------def upload_dataset(file):"""If user uploads a file -> copy to dataset.jsonlIf user uploads a folder -> we DO NOT move it, they’ll pass folder path via a textbox if needed."""if not file:return "❌ No file selected.", ls_workspace()# If it's a file object, copy to DATAif hasattr(file, "name") and os.path.isfile(file.name):shutil.copy(file.name, DATA)return f"✅ Uploaded → {DATA.name}", ls_workspace()7 unmodified linesZIP.unlink(missing_ok=True)LOG.write_text("🔥 Training started…\n", encoding="utf-8")# Run trainer (blocking) and capture output in train.logcmd = ["python", str(ROOT / "train.py"),"--dataset", str(DATA), # For folder-mode, replace DATA with folder path in train.py if you extend UI"--output", str(OUT),"--zip_path", str(ZIP),"--model_name", "Salesforce/codegen-350M-multi",5 unmodified lineswith open(LOG, "a", encoding="utf-8") as lf:code = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT).wait()# Refresh model list & set selection only if it’s presentmodels = list_models()selected = str(OUT) if OUT.exists() and str(OUT) in models else Nonemodel_update = gr.update(choices=models, value=selected)if code == 0 and ZIP.exists():info = f"✅ Training complete. Saved: {OUT.name} | Zip: {ZIP.name}"7 unmodified linesdef refresh_download():models = list_models()return gr.update(value=(str(ZIP) if ZIP.exists() else None), visible=ZIP.exists()), ls_workspace(), gr.update(choices=models)# ---------- test tab ----------def import_zip(zfile):34 unmodified lineswith gr.Blocks(title="Python AI — Train & Test") as app:gr.Markdown("## 🧠 Python AI — Train & Test\nTrainer saves & zips. UI only shows existing artifacts.\n")# Test tab (declared first so we can update its dropdown from Train tab)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")23 unmodified linesoutputs=[download_file, ws, model_list])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)1234567891020 unmodified lines3132333435363738394041424344457 unmodified lines5354555657585960615 unmodified lines6768697071727374757 unmodified lines838485868788899091929334 unmodified lines12812913013113213313413513613713813914014114214323 unmodified lines167168169170171172173# app.pyimport os, shutil, subprocess, zipfilefrom pathlib import Pathimport gradio as grROOT = Path(__file__).resolve().parentDATA = ROOT / "dataset.jsonl"LOG = ROOT / "train.log"OUT = ROOT / "trained_model"ZIP = ROOT / "trained_model.zip"20 unmodified linesout.insert(0, str(OUT))return sorted(out)def dropdown_update_safe(models, prefer=None):"""Return a gr.update that always uses a value present in choices (or None)."""val = prefer if (prefer and prefer in models) else (models[0] if models else None)return gr.update(choices=models, value=val)# ---------- train tab ----------def upload_dataset(file):if not file:return "❌ No file selected.", ls_workspace()if hasattr(file, "name") and os.path.isfile(file.name):shutil.copy(file.name, DATA)return f"✅ Uploaded → {DATA.name}", ls_workspace()7 unmodified linesZIP.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",5 unmodified lineswith open(LOG, "a", encoding="utf-8") as lf:code = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT).wait()models = list_models()prefer = str(OUT) if OUT.exists() else Nonemodel_update = dropdown_update_safe(models, prefer=prefer)if code == 0 and ZIP.exists():info = f"✅ Training complete. Saved: {OUT.name} | Zip: {ZIP.name}"7 unmodified linesdef refresh_download():models = list_models()return (gr.update(value=(str(ZIP) if ZIP.exists() else None), visible=ZIP.exists()),ls_workspace(),dropdown_update_safe(models))# ---------- test tab ----------def import_zip(zfile):34 unmodified lineswith gr.Blocks(title="Python AI — Train & Test") as app:gr.Markdown("## 🧠 Python AI — Train & Test\nTrainer saves & zips. UI only shows existing artifacts.\n")# Test first (so Train can update it)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,allow_custom_value=True # <-- stops warnings when choices are empty)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")23 unmodified linesoutputs=[download_file, ws, model_list])refresh_btn.click(lambda: dropdown_update_safe(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.py+23-15