Update app.py
Browse files18 unmodified lines192021222324258 unmodified lines3435363738394041424344454647484917 unmodified lines676869707172731 unmodified line757677787980815 unmodified lines878889909192939495969798991001011023 unmodified lines1061071081091101111122 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421436 unmodified lines1501511521531541556 unmodified lines16216316416516616716818 unmodified linesdef _zip_dir_atomic(src, out_path, tmp_path):if os.path.exists(tmp_path): os.remove(tmp_path)with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as z:for root,_,files in os.walk(src):for fn in files:fp = os.path.join(root, fn)8 unmodified linesshutil.copy(f.name, dst)return f"β Uploaded β {dst}", dstdef _train_single(dataset, log):p = subprocess.Popen(["python","train.py","--dataset",dataset,"--output",MODEL_DIR],stdout=log, stderr=subprocess.STDOUT)p.wait()log.write(f"\n β³ train.py exited {p.returncode} for {os.path.basename(dataset)}\n")return p.returncode == 0def _worker(dataset_path, shards_folder):with open(LOG_FILE,"w") as log: log.write("π₯ Starting training (C# AI)β¦\n")ok=Truewith open(LOG_FILE,"a") as log:17 unmodified lineslog.write(f"β GZ read failed: {e}\n"); ok=False; breakelse:shard = pthif not _train_single(shard, log): ok=False; breakif os.path.exists(tmp):try: os.remove(tmp)except: pass1 unmodified lineif not dataset_path or not os.path.exists(dataset_path):log.write("β Upload a valid dataset.\n"); ok=Falseelse:ok = _train_single(dataset_path, log)if ok and os.path.isdir(MODEL_DIR):try:5 unmodified lineselse:log.write("\nβ Training failed; no zip.\n")def start_training(dataset_path, shards_folder):try:if os.path.exists(ZIP_FILE): os.remove(ZIP_FILE)if os.path.exists(ZIP_PART): os.remove(ZIP_PART)except: passthreading.Thread(target=_worker, args=(dataset_path, shards_folder), daemon=True).start()return "π Training started. Use Refresh buttons."def read_logs():return _read(LOG_FILE, "Waiting for logs...")def refresh_download():if os.path.exists(ZIP_FILE):3 unmodified linesdef load_test_zip(z):if z is None: return "β No file.", ""import zipfile, uuidroot = os.path.join("models", f"test_{uuid.uuid4().hex}")os.makedirs(root, exist_ok=True)try:2 unmodified linesexcept Exception as e:return f"β Extract failed: {e}", ""def clear_test_model():return "Cleared. Will use trained_model/ if present.", ""def generate(prompt, model_path):if not prompt.strip(): return "Enter a prompt."try:if model_path and os.path.isdir(model_path):m = model_pathsrc="(uploaded)"elif os.path.isdir(MODEL_DIR):m = MODEL_DIRsrc="(trained_model/)"else:m = "distilgpt2" # tiny fallbacksrc="(fallback)"gen = pipeline("text-generation", model=m, tokenizer="distilgpt2")out = gen(prompt, max_length=200, do_sample=True, temperature=0.7, truncation=True)[0]["generated_text"]return f"{out}\n\nβ using {src}"except Exception as e:return f"β Error: {e}"with gr.Blocks(title="C# AI Trainer") as app:gr.Markdown("## π§© C# AI Trainer β upload JSONL, train fast, download, and test.")ds_state = gr.State("")folder_state = gr.State("")6 unmodified lineswith gr.Row():shards_folder = gr.Textbox(value="", label="Folder with shards (optional)")use_folder = gr.Button("π Use Folder")status = gr.Textbox(label="Status", interactive=False)with gr.Row():start_btn = gr.Button("π Start Training")6 unmodified linesup_btn.click(fn=upload_file, inputs=file_in, outputs=[status, ds_state])use_folder.click(fn=lambda p: ("β Using folder." if p.strip() else "β Provide folder path.", p.strip()),inputs=shards_folder, outputs=[status, folder_state])start_btn.click(fn=start_training, inputs=[ds_state, folder_state], outputs=status).then(fn=read_logs, outputs=logs).then(fn=refresh_download, outputs=[dl_btn, dl_info])refresh_logs.click(fn=read_logs, outputs=logs)18 unmodified lines192021222324258 unmodified lines3435363738394041424344454647484917 unmodified lines676869707172731 unmodified line757677787980815 unmodified lines878889909192939495969798991001013 unmodified lines1051061071081091101112 unmodified lines1141151161171181191201211221231241251261271281291301311321331341356 unmodified lines1421431441451461471481491501516 unmodified lines15815916016116216316418 unmodified linesdef _zip_dir_atomic(src, out_path, tmp_path):if os.path.exists(tmp_path): os.remove(tmp_path)with zipfile.ZipFile(tmp_path,"w",zipfile.ZIP_DEFLATED) as z:for root,_,files in os.walk(src):for fn in files:fp = os.path.join(root, fn)8 unmodified linesshutil.copy(f.name, dst)return f"β Uploaded β {dst}", dstdef _train_single(dataset, log, quick, steps, subset):args = ["python","train.py","--dataset",dataset,"--output",MODEL_DIR]if quick:args += ["--quick","1","--max_steps",str(steps or 8),"--subset",str(subset or 32)]p = subprocess.Popen(args, stdout=log, stderr=subprocess.STDOUT)p.wait()log.write(f"\n β³ train.py exited {p.returncode} for {os.path.basename(dataset)}\n")return p.returncode == 0def _worker(dataset_path, shards_folder, quick, steps, subset):with open(LOG_FILE,"w") as log: log.write("π₯ Starting training (C# AI)β¦\n")ok=Truewith open(LOG_FILE,"a") as log:17 unmodified lineslog.write(f"β GZ read failed: {e}\n"); ok=False; breakelse:shard = pthif not _train_single(shard, log, quick, steps, subset): ok=False; breakif os.path.exists(tmp):try: os.remove(tmp)except: pass1 unmodified lineif not dataset_path or not os.path.exists(dataset_path):log.write("β Upload a valid dataset.\n"); ok=Falseelse:ok = _train_single(dataset_path, log, quick, steps, subset)if ok and os.path.isdir(MODEL_DIR):try:5 unmodified lineselse:log.write("\nβ Training failed; no zip.\n")def start_training(dataset_path, shards_folder, quick, steps, subset):for p in (ZIP_FILE, ZIP_PART):if os.path.exists(p):try: os.remove(p)except: passthreading.Thread(target=_worker, args=(dataset_path, shards_folder, quick, steps, subset), daemon=True).start()return "π Training started. Use Refresh buttons."def read_logs(): return _read(LOG_FILE, "Waiting for logs...")def refresh_download():if os.path.exists(ZIP_FILE):3 unmodified linesdef load_test_zip(z):if z is None: return "β No file.", ""import zipfileroot = os.path.join("models", f"test_{uuid.uuid4().hex}")os.makedirs(root, exist_ok=True)try:2 unmodified linesexcept Exception as e:return f"β Extract failed: {e}", ""def clear_test_model(): return "Cleared. Will use trained_model/ if present.", ""def generate(prompt, model_path):if not prompt.strip(): return "Enter a prompt."try:if model_path and os.path.isdir(model_path): m, src = model_path, "(uploaded)"elif os.path.isdir(MODEL_DIR): m, src = MODEL_DIR, "(trained_model/)"else: m, src = "sshleifer/tiny-gpt2", "(tiny fallback)"gen = pipeline("text-generation", model=m, tokenizer="sshleifer/tiny-gpt2")out = gen(prompt, max_length=120, do_sample=True, temperature=0.7, truncation=True)[0]["generated_text"]return f"{out}\n\nβ using {src}"except Exception as e:return f"β Error: {e}"with gr.Blocks(title="C# AI Trainer (Quick Test Mode)") as app:gr.Markdown("## β‘ C# AI Trainer β includes *Quick Test* (few steps on a tiny model).")ds_state = gr.State("")folder_state = gr.State("")6 unmodified lineswith gr.Row():shards_folder = gr.Textbox(value="", label="Folder with shards (optional)")use_folder = gr.Button("π Use Folder")with gr.Row():quick = gr.Checkbox(value=True, label="β‘ Quick Test (tiny model, few steps)")steps = gr.Number(value=8, label="Max steps (Quick mode)", precision=0)subset = gr.Number(value=32, label="Subset rows (Quick mode)", precision=0)status = gr.Textbox(label="Status", interactive=False)with gr.Row():start_btn = gr.Button("π Start Training")6 unmodified linesup_btn.click(fn=upload_file, inputs=file_in, outputs=[status, ds_state])use_folder.click(fn=lambda p: ("β Using folder." if p.strip() else "β Provide folder path.", p.strip()),inputs=shards_folder, outputs=[status, folder_state])start_btn.click(fn=start_training, inputs=[ds_state, folder_state, quick, steps, subset], outputs=status).then(fn=read_logs, outputs=logs).then(fn=refresh_download, outputs=[dl_btn, dl_info])refresh_logs.click(fn=read_logs, outputs=logs)
app.py+30-34