Spaces:
Sleeping
Sleeping
Update app.py
Browse files12344 unmodified lines910111213141516171819202122232425262728293031323334353637383940412 unmodified lines4445464748495051525354555612 unmodified lines6970717273747 unmodified lines828384858687888990919293943 unmodified lines98991001011021031045 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461472 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711721731741751761771781 unmodified line18018118218318418518617 unmodified lines204205206207208209210import os, shutil, subprocess, zipfilefrom pathlib import Pathfrom datetime import datetimeimport gradio as gr4 unmodified linesRUNS = ROOT / "runs"RUNS.mkdir(exist_ok=True)# ---------- helpers ----------def ls_workspace() -> str:rows = []for p in sorted(ROOT.iterdir(), key=lambda x: (x.is_file(), x.name.lower())):try: size = p.stat().st_sizeexcept Exception: size = 0rows.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 base in [ROOT, RUNS]:if not base.exists():continuefor p in base.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))# ensure uniqueness & sortedreturn sorted(set(out))def dropdown_update_safe(models, prefer=None):val = prefer if (prefer and prefer in models) else (models[0] if models else None)return gr.update(choices=models, value=val)# ---------- training ----------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()def start_training(run_name):# Unique run folder and ziprun_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"# Clean previous artifacts only for this runif out_dir.exists():shutil.rmtree(out_dir, ignore_errors=True)if zip_path.exists():12 unmodified lines"--block_size", "256","--learning_rate", "5e-5",]with open(LOG, "a", encoding="utf-8") as lf:code = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT).wait()7 unmodified linesinfo = f"β Training failed (exit {code}). Check logs below."dl_update = gr.update(value=None, visible=False)return info, dl_update, ls_workspace(), read_logs(), model_updatedef read_logs():return LOG.read_text(encoding="utf-8")[-20000:] if LOG.exists() else "β³ Waitingβ¦"def refresh_download():# We donβt know which run user wants; show the newest zip if anyzips = sorted(RUNS.glob("*.zip"), key=lambda p: p.stat().st_mtime, reverse=True)latest = zips[0] if zips else Nonemodels = list_models()3 unmodified linesdropdown_update_safe(models))# ---------- testing ----------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()def generate(model_path, prompt):# 1) Validate inputsif not model_path:return "β Select a model from the dropdown first."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:from transformers import AutoTokenizer, AutoModelForCausalLM, pipelineimport torchtok = AutoTokenizer.from_pretrained(model_path, use_fast=True)# ensure pad tokenif tok.pad_token_id is None:if tok.eos_token_id is not None:tok.pad_token = tok.eos_tokenelse:tok.add_special_tokens({"pad_token": "[PAD]"})model = AutoModelForCausalLM.from_pretrained(model_path)# align embeddings if we added tokensif getattr(model, "config", None) and getattr(model.config, "vocab_size", None) and len(tok) > model.config.vocab_size:model.resize_token_embeddings(len(tok))pipe = pipeline("text-generation",model=model,tokenizer=tok,device_map="auto" if torch.cuda.is_available() else None,)out = pipe(prompt.strip(),max_new_tokens=120,2 unmodified linestop_p=0.9,repetition_penalty=1.15,no_repeat_ngram_size=4,eos_token_id=tok.eos_token_id,pad_token_id=tok.pad_token_id,truncation=True)[0]["generated_text"]return outexcept Exception as e:import tracebackreturn "β 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 run folders β’ Safe download β’ Reliable generation\n")# ---- Test tab first so Train can target its dropdownwith gr.Tab("Test"):gr.Markdown("### Pick 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 # no warnings when empty)zip_in = gr.File(label="Or upload a model .zip", file_types=[".zip"])import_status = gr.Textbox(label="Import Status", interactive=False)1 unmodified linego = gr.Button("Generate")out = gr.Textbox(label="AI Response", lines=20)# ---- Train tabwith gr.Tab("Train"):with gr.Row():ds = gr.File(label="π₯ Upload JSONL", file_types=[".jsonl"])17 unmodified linesrefresh_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)123454 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748495051522 unmodified lines5556575859606162636465666712 unmodified lines808182838485867 unmodified lines9495969798991001011021033 unmodified lines1071081091101111121135 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781792 unmodified lines1821831841851861871881891901911921931941951961971981992002012022032042052062072082092101 unmodified line21221321421521621717 unmodified lines235236237238239240# app.pyimport os, shutil, subprocess, zipfile, tracebackfrom pathlib import Pathfrom datetime import datetimeimport gradio as gr4 unmodified linesRUNS = 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())):try:size = p.stat().st_sizeexcept Exception:size = 0rows.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 base in [ROOT, RUNS]:if not base.exists():continuefor p in base.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))return sorted(set(out))def dropdown_update_safe(models, prefer=None):val = 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 --------def start_training(run_name):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"# clean only this runif out_dir.exists():shutil.rmtree(out_dir, ignore_errors=True)if zip_path.exists():12 unmodified lines"--block_size", "256","--learning_rate", "5e-5",]append_log("βΆ " + " ".join(cmd))with open(LOG, "a", encoding="utf-8") as lf:code = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT).wait()7 unmodified linesinfo = f"β Training failed (exit {code}). Check logs below."dl_update = gr.update(value=None, visible=False)append_log(info)return info, dl_update, ls_workspace(), read_logs(), model_updatedef refresh_download():zips = sorted(RUNS.glob("*.zip"), key=lambda p: p.stat().st_mtime, reverse=True)latest = zips[0] if zips else Nonemodels = list_models()3 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):from transformers import AutoTokenizer, AutoModelForCausalLM, pipelineimport torchif _GEN_CACHE["path"] == model_path and _GEN_CACHE["pipe"] is not None:return _GEN_CACHE["pipe"]append_log(f"π§© Loading pipeline from: {model_path}")tok = AutoTokenizer.from_pretrained(model_path, use_fast=True)if tok.pad_token_id is None:if tok.eos_token_id is not None:tok.pad_token = tok.eos_tokenappend_log("βΉ No pad_token; using eos_token as pad_token.")else:tok.add_special_tokens({"pad_token": "[PAD]"})append_log("βΉ Added [PAD] token to tokenizer.")model = AutoModelForCausalLM.from_pretrained(model_path)if getattr(model, "config", None) and getattr(model.config, "vocab_size", None) and len(tok) > model.config.vocab_size:model.resize_token_embeddings(len(tok))append_log(f"βΉ Resized embeddings to {len(tok)}.")pipe = pipeline("text-generation",model=model,tokenizer=tok,device_map="auto" if torch.cuda.is_available() else None,)_GEN_CACHE["path"] = model_path_GEN_CACHE["pipe"] = pipeappend_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):return 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,2 unmodified linestop_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\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",interactive=True,allow_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)1 unmodified linego = 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"])17 unmodified linesrefresh_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.py+78-48