Spaces:
Sleeping
Sleeping
Update app.py
Browse files1223456789101112131314151516171819202122222324252620 unmodified lines47484949505152532 unmodified lines565758585960616263646566676869707172737422 unmodified lines979899100929394959697989910010110210310410510610710810911011111211311411511611711811912012147 unmodified lines1691701711571721731741755 unmodified lines18118218316918418518618728 unmodified lines2162172182042052192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502072512522532542552562132572582592152162602612622182632642652202662672682692702712242252722732742272752762292772782792802332342812822832842852862872882892362902912922932402942952422962972982992463003013023032493043053063073081 unmodified line3103113123133143153163172593183193203213223233243253263273283293306 unmodified lines337338339275340341342343278344345346347348349350351352353354355356357358359360361362363291364365366# app.pyimport os, shutil, subprocess, zipfile, traceback, time, ioimport 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 helpers --------# ----------------- Logging -----------------def append_log(msg: str): msg = msg.rstrip() 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 --------# ----------------- Workspace & Models -----------------def ls_workspace() -> str: rows = [] for p in sorted(ROOT.iterdir(), key=lambda x: (x.is_file(), x.name.lower())):20 unmodified lines val = prefer if (prefer and prefer in models) else (models[0] if models else None) return gr.update(choices=models, value=val)
# -------- dataset upload --------# ----------------- Dataset Upload -----------------def upload_dataset(file): if not file: return "β No file selected.", ls_workspace()2 unmodified lines return f"β
Uploaded β {DATA.name}", ls_workspace() return "β Unexpected item; please upload a .jsonl file.", ls_workspace()
# -------- training (LIVE LOGS) --------# ----------------- 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 exist if 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())) return
run_id = (run_name or "").strip() or datetime.now().strftime("run_%Y%m%d_%H%M%S") out_dir = RUNS / run_id zip_path = RUNS / f"{run_id}.zip"22 unmodified lines append_log("βΆ " + " ".join(cmd))
# start subprocess with live stdout try: proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, universal_newlines=True, encoding="utf-8", errors="replace", ) 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())) return
live_log = io.StringIO() status_msg = f"π Training run '{run_id}' in progressβ¦"
# stream loop while True: line = proc.stdout.readline()47 unmodified lines dropdown_update_safe(models) )
# -------- import a zip as a model folder --------# ----------------- Import a Zip as Model Folder -----------------def import_zip(zfile): if not zfile: return "β No zip selected.", list_models()5 unmodified lines z.extractall(dest) return f"β
Imported to {dest.name}", list_models()
# -------- generation: cached pipeline --------# ----------------- Generation (cached pipeline) -----------------_GEN_CACHE = {"path": None, "pipe": None}
def get_generation_pipeline(model_path: str):28 unmodified lines append_log("β
Pipeline loaded.") return pipe
def generate(model_path, prompt): from pathlib import Path# ----------------- 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 string if isinstance(model_path, list): model_path = model_path[0] if model_path else None if 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 feedback yield "β³ Loading modelβ¦" append_log("βΆ Generate clicked")
# Coerce Dropdown value (can be list) # Coerce if isinstance(model_path, list): model_path = model_path[0] if model_path else None
# validate if not model_path: return "β Select a model from the dropdown first." msg = "β Select a model from the dropdown first." append_log(msg); yield msg; return if not isinstance(model_path, str): # fix minor bug: _name_ not name return f"β Invalid model path type: {type(model_path)._name_}" msg = f"β Invalid model path type: {type(model_path)._name_}" append_log(msg); yield msg; return if not Path(model_path).exists(): return f"β Model folder not found: {model_path}" msg = f"β Model folder not found: {model_path}" append_log(msg); yield msg; return if not prompt or not prompt.strip(): return "β Enter a prompt." msg = "β Enter a prompt." append_log(msg); yield msg; return
try: pipe = get_generation_pipeline(model_path) yield "β Generatingβ¦ (this may take a bit on CPU)" append_log(f"π Generating for prompt ({len(prompt)} chars)β¦") out = pipe( append_log(f"π Generatingβ¦ prompt_len={len(prompt)}") result = pipe( prompt.strip(), max_new_tokens=120, max_new_tokens=80, # quicker to show something do_sample=True, temperature=0.4, temperature=0.3, top_p=0.9, repetition_penalty=1.15, no_repeat_ngram_size=4, truncation=True )[0]["generated_text"] 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." return append_log("β
Generation OK.") return out yield text except 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)) yield "β Error during generation:\n" + "".join(traceback.format_exception_only(type(e), e))
# -------- UI --------# ----------------- 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) # ---------- 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") refresh_btn = gr.Button("β» Refresh Model List") ping_btn = gr.Button("π Ping UI") # quick sanity check model_list = gr.Dropdown( choices=list_models(), label="Available AIs",1 unmodified line allow_custom_value=True, # keeps UI quiet when empty multiselect=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")
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 lines download_file = gr.File(label="π¦ Latest trained zip", visible=False) refresh_dl_btn = gr.Button("Refresh Download")
# wiring # ---------- Wiring ---------- # Upload + workspace ds.change(upload_dataset, inputs=ds, outputs=[up_status, ws])
# STREAMED training: function yields updates # Train (live streaming) start.click( start_training_live, inputs=[run_name], outputs=[status, download_file, ws, logs, model_list] )
# Download refresh refresh_dl_btn.click( refresh_download, outputs=[download_file, ws, model_list] )
# Test tab helpers refresh_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 output go.click(generate, inputs=[model_list, prompt], outputs=out) go.click(generate_stream, inputs=[model_list, prompt], outputs=out)
app.queue(default_concurrency_limit=1).launch()app.py+113-40