Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import osimport timeimport zipfileimport gradio as grimport subprocessimport threading# PathsOUTPUT_DIR = "train_output"ZIP_FILE = "python_ai_trained_model.zip"LOG_FILE = "train_log.txt"# Zip functiondef zip_trained_model():with zipfile.ZipFile(ZIP_FILE, 'w', zipfile.ZIP_DEFLATED) as zipf:for root, _, files in os.walk(OUTPUT_DIR):for file in files:filepath = os.path.join(root, file)arcname = os.path.relpath(filepath, OUTPUT_DIR)zipf.write(filepath, arcname)# Tail logs functiondef tail_logs(n=20):if not os.path.exists(LOG_FILE):return ""with open(LOG_FILE, 'r') as f:return ''.join(f.readlines()[-n:])# Background training runnerdef run_training(status_box, time_box, download_file, model_size_box, log_box):start_time = time.time()status_box.value = "π Training started..."time_box.value = "Training in progress..."log_box.value = ""# Create log filewith open(LOG_FILE, "w") as log:log.write("π Launching train.py...\n")# Start trainingwith open(LOG_FILE, "a") as log:process = subprocess.Popen(["python", "train.py"], stdout=log, stderr=subprocess.STDOUT)while process.poll() is None:log_box.update(value=tail_logs())time.sleep(5)# Check exit statusif process.returncode != 0:status_box.value = f"β Training failed with exit code {process.returncode}"log_box.value = tail_logs()return# Training successelapsed = round(time.time() - start_time, 2)time_box.value = f"β Completed in {elapsed // 60:.0f} min {elapsed % 60:.0f} sec"status_box.value = "π Compressing model..."# Zip itzip_trained_model()size_mb = round(os.path.getsize(ZIP_FILE) / (1024 * 1024), 2)model_size_box.value = f"π¦ Model Size: {size_mb} MB"download_file.value = ZIP_FILEdownload_file.visible = Truestatus_box.value = "β Training complete. Download below."# Button triggerdef start_training(status_box, time_box, download_file, model_size_box, log_box):thread = threading.Thread(target=run_training, args=(status_box, time_box, download_file, model_size_box, log_box))thread.start()return "Training process started."# Gradio UIwith gr.Blocks() as demo:gr.Markdown("## π§ Python AI Trainer (StarCoder 7B)")gr.Markdown("Train your Python AI with 1 click. Watch logs. Download model when done.")with gr.Row():train_btn = gr.Button("π Start Training")status_box = gr.Textbox(label="Status", value="Ready", interactive=False)with gr.Row():time_box = gr.Textbox(label="Training Time", interactive=False)model_size_box = gr.Textbox(label="Final Model Size", interactive=False)log_box = gr.Textbox(label="Live Training Logs", lines=20, interactive=False, value="")download_file = gr.File(label="π₯ Download Trained Model (.zip)", visible=False)train_btn.click(fn=start_training,inputs=[status_box, time_box, download_file, model_size_box, log_box],outputs=[status_box])demo.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283import osimport shutilimport subprocessimport gradio as grfrom transformers import pipelineuploaded_file_path = "dataset.jsonl"log_path = "train.log"model_dir = "trained_model"zip_file = "trained_model.zip"# Try loading the generator model once at the top (for better performance)try:generator = pipeline("text-generation", model=model_dir, tokenizer="distilgpt2")except:generator = Nonedef upload_file(file):if file is None:return "No file uploaded."shutil.copy(file.name, uploaded_file_path)return "β File uploaded successfully."def start_training():with open(log_path, "w") as log_file:process = subprocess.Popen(["python", "train.py", "--dataset", uploaded_file_path],stdout=log_file,stderr=subprocess.STDOUT)process.wait()if os.path.exists(model_dir):shutil.make_archive("trained_model", "zip", model_dir)return "β Training complete!", zip_fileelse:return "β Training failed.", Nonedef read_logs():if os.path.exists(log_path):with open(log_path, "r") as f:return f.read()return "Waiting for logs..."def generate_response(prompt):try:if generator is None:return "β Model not loaded. Please train or upload a valid model."result = generator(prompt,max_length=256,do_sample=True,temperature=0.7,truncation=True # β Fix warning and enforce consistent length)[0]["generated_text"]return resultexcept Exception as e:return f"β Error: {e}"# === UI ===with gr.Blocks() as app:with gr.Tab("π§ Train AI"):gr.Markdown("## π₯ Upload your dataset and π― train a Godot AI")file_input = gr.File(label="Upload JSONL Dataset")upload_btn = gr.Button("Upload")status_box = gr.Textbox(label="Upload Status")start_btn = gr.Button("π Start Training")log_output = gr.Textbox(label="π Training Logs", lines=15)download_btn = gr.File(label="π₯ Download Trained Model", visible=False)upload_btn.click(fn=upload_file, inputs=file_input, outputs=status_box)start_btn.click(fn=start_training, outputs=[status_box, download_btn])start_btn.click(fn=read_logs, outputs=log_output)with gr.Tab("π Test AI"):gr.Markdown("## π‘ Try your trained Godot AI below")prompt_input = gr.Textbox(label="Enter Prompt")test_btn = gr.Button("π Test AI")response_output = gr.Textbox(label="AI Response", lines=10)test_btn.click(fn=generate_response, inputs=prompt_input, outputs=response_output)app.launch()
app.py+81-94