Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242520 unmodified lines464748495051522 unmodified lines55565758596061626364656622 unmodified lines899091929394959697989910010110210310410510647 unmodified lines1541551561571581591605 unmodified lines16616716816917017117228 unmodified lines2012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512521 unmodified line2542552562572582592602612622632642656 unmodified lines272273274275276277278279280281282283284285286287288289290291292293# 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"RUNS.mkdir(exist_ok=True)# -------- logging helpers --------def append_log(msg: str):msg = msg.rstrip()with open(LOG, "a", encoding="utf-8") as lf:lf.write(msg + "\n")def read_logs():return LOG.read_text(encoding="utf-8")[-20000:] if LOG.exists() else "β³ Waitingβ¦"# -------- workspace + models --------def ls_workspace() -> str:rows = []for p in sorted(ROOT.iterdir(), key=lambda x: (x.is_file(), x.name.lower())):20 unmodified linesval = prefer if (prefer and prefer in models) else (models[0] if models else None)return gr.update(choices=models, value=val)# -------- dataset upload --------def upload_dataset(file):if not file:return "β No file selected.", ls_workspace()2 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"22 unmodified linesappend_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()47 unmodified linesdropdown_update_safe(models))# -------- import a zip as a model folder --------def import_zip(zfile):if not zfile:return "β No zip selected.", list_models()5 unmodified linesz.extractall(dest)return f"β Imported to {dest.name}", list_models()# -------- generation: cached pipeline --------_GEN_CACHE = {"path": None, "pipe": None}def get_generation_pipeline(model_path: str):28 unmodified linesappend_log("β Pipeline loaded.")return pipedef generate(model_path, prompt):from pathlib import Path# Coerce Dropdown value (can be list)if isinstance(model_path, list):model_path = model_path[0] if model_path else None# validateif 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}"if not prompt or not prompt.strip():return "β Enter a prompt."try:pipe = get_generation_pipeline(model_path)append_log(f"π Generating for prompt ({len(prompt)} chars)β¦")out = pipe(prompt.strip(),max_new_tokens=120,do_sample=True,temperature=0.4,top_p=0.9,repetition_penalty=1.15,no_repeat_ngram_size=4,truncation=True)[0]["generated_text"]append_log("β Generation OK.")return outexcept Exception as e:tb = traceback.format_exc()append_log("β Generation error:\n" + tb)return "β Error during generation:\n" + "".join(traceback.format_exception_only(type(e), e))# -------- 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"):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",1 unmodified lineallow_custom_value=True, # keeps UI quiet when emptymultiselect=False # force single selection)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)with gr.Tab("Train"):with gr.Row():ds = gr.File(label="π₯ Upload JSONL", file_types=[".jsonl"])6 unmodified linesdownload_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])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.queue(default_concurrency_limit=1).launch()123456789101112131415161718192021222324252620 unmodified lines474849505152532 unmodified lines5657585960616263646566676869707172737422 unmodified lines97989910010110210310410510610710810911011111211311411511611711811912012147 unmodified lines1691701711721731741755 unmodified lines18118218318418518618728 unmodified lines2162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073081 unmodified line3103113123133143153163173183193203213223233243253263273283293306 unmodified lines337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366# app.pyimport os, shutil, subprocess, zipfile, traceback, iofrom pathlib import Pathfrom datetime import datetimeimport gradio as gr# ----------------- Paths -----------------ROOT = Path(__file__).resolve().parentDATA = ROOT / "dataset.jsonl"LOG = ROOT / "train.log"RUNS = ROOT / "runs"RUNS.mkdir(exist_ok=True)# ----------------- Logging -----------------def append_log(msg: str):msg = (msg or "").rstrip("\n")with open(LOG, "a", encoding="utf-8") as lf:lf.write(msg + "\n")def read_logs():return LOG.read_text(encoding="utf-8")[-20000:] if LOG.exists() else "β³ Waitingβ¦"# ----------------- Workspace & Models -----------------def ls_workspace() -> str:rows = []for p in sorted(ROOT.iterdir(), key=lambda x: (x.is_file(), x.name.lower())):20 unmodified linesval = prefer if (prefer and prefer in models) else (models[0] if models else None)return gr.update(choices=models, value=val)# ----------------- Dataset Upload -----------------def upload_dataset(file):if not file:return "β No file selected.", ls_workspace()2 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]"""# Quick guard: dataset must existif not DATA.exists():msg = "β dataset.jsonl not found. Upload a JSONL dataset first."append_log(msg)yield (msg, gr.update(value=None, visible=False), ls_workspace(), read_logs(), dropdown_update_safe(list_models()))returnrun_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"22 unmodified linesappend_log("βΆ " + " ".join(cmd))# start subprocess with live stdouttry:proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,bufsize=1,universal_newlines=True,encoding="utf-8",errors="replace",)except Exception as e:err = "β Failed to start train.py: " + "".join(traceback.format_exception_only(type(e), e))append_log(err)yield (err, gr.update(value=None, visible=False), ls_workspace(), read_logs(), dropdown_update_safe(list_models()))returnlive_log = io.StringIO()status_msg = f"π Training run '{run_id}' in progressβ¦"# stream loopwhile True:line = proc.stdout.readline()47 unmodified linesdropdown_update_safe(models))# ----------------- Import a Zip as Model Folder -----------------def import_zip(zfile):if not zfile:return "β No zip selected.", list_models()5 unmodified linesz.extractall(dest)return f"β Imported to {dest.name}", list_models()# ----------------- Generation (cached pipeline) -----------------_GEN_CACHE = {"path": None, "pipe": None}def get_generation_pipeline(model_path: str):28 unmodified linesappend_log("β Pipeline loaded.")return pipe# ----------------- Test Tab Helpers -----------------def ping():append_log("π Ping pressed (UI wiring OK)")return "β UI is connected and responding."def load_selected_model(model_path):# Dropdown may pass a list; coerce to stringif isinstance(model_path, list):model_path = model_path[0] if model_path else Noneif not model_path:return "β Select a model first."if not isinstance(model_path, str):return f"β Invalid model path type: {type(model_path)._name_}"p = Path(model_path)if not p.exists() or not p.is_dir():return f"β Model folder not found: {model_path}"try:append_log(f"π¦ Load request β {model_path}")_ = get_generation_pipeline(model_path)append_log(f"β Loaded pipeline: {model_path}")return f"β Loaded: {model_path}"except Exception as e:tb = traceback.format_exc()append_log("β Load error:\n" + tb)return "β Error while loading model:\n" + "".join(traceback.format_exception_only(type(e), e))def generate_stream(model_path, prompt):"""Stream intermediate status to prove the button is working, then final text."""# immediate feedbackyield "β³ Loading modelβ¦"append_log("βΆ Generate clicked")# Coerceif isinstance(model_path, list):model_path = model_path[0] if model_path else None# validateif not model_path:msg = "β Select a model from the dropdown first."append_log(msg); yield msg; returnif not isinstance(model_path, str):msg = f"β Invalid model path type: {type(model_path)._name_}"append_log(msg); yield msg; returnif not Path(model_path).exists():msg = f"β Model folder not found: {model_path}"append_log(msg); yield msg; returnif not prompt or not prompt.strip():msg = "β Enter a prompt."append_log(msg); yield msg; returntry:pipe = get_generation_pipeline(model_path)yield "β Generatingβ¦ (this may take a bit on CPU)"append_log(f"π Generatingβ¦ prompt_len={len(prompt)}")result = pipe(prompt.strip(),max_new_tokens=80, # quicker to show somethingdo_sample=True,temperature=0.3,top_p=0.9,repetition_penalty=1.15,no_repeat_ngram_size=4,truncation=True,return_full_text=True,)text = result[0].get("generated_text", "")if not text:append_log("β Empty generated_text")yield "β Model returned empty text. Try lowering temperature or adding more context."returnappend_log("β Generation OK.")yield textexcept Exception as e:tb = traceback.format_exc()append_log("β Generation error:\n" + tb)yield "β Error during generation:\n" + "".join(traceback.format_exception_only(type(e), e))# ----------------- 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 Tab ----------with gr.Tab("Test"):gr.Markdown("### Choose a model folder or upload a .zip, then prompt it")with gr.Row():refresh_btn = gr.Button("β» Refresh Model List")ping_btn = gr.Button("π Ping UI") # quick sanity checkmodel_list = gr.Dropdown(choices=list_models(),label="Available AIs",1 unmodified lineallow_custom_value=True, # keeps UI quiet when emptymultiselect=False # force single selection)load_btn = gr.Button("π¦ Load Model")load_status = gr.Textbox(label="Model Status", interactive=False)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 ----------with gr.Tab("Train"):with gr.Row():ds = gr.File(label="π₯ Upload JSONL", file_types=[".jsonl"])6 unmodified linesdownload_file = gr.File(label="π¦ Latest trained zip", visible=False)refresh_dl_btn = gr.Button("Refresh Download")# ---------- Wiring ----------# Upload + workspaceds.change(upload_dataset, inputs=ds, outputs=[up_status, ws])# Train (live streaming)start.click(start_training_live,inputs=[run_name],outputs=[status, download_file, ws, logs, model_list])# Download refreshrefresh_dl_btn.click(refresh_download,outputs=[download_file, ws, model_list])# Test tab helpersrefresh_btn.click(lambda: dropdown_update_safe(list_models()), outputs=model_list)ping_btn.click(ping, outputs=out)load_btn.click(load_selected_model, inputs=[model_list], outputs=[load_status])zip_in.change(import_zip, inputs=zip_in, outputs=[import_status, model_list])# Streamed generation outputgo.click(generate_stream, inputs=[model_list, prompt], outputs=out)app.queue(default_concurrency_limit=1).launch()
app.py+113-40