Spaces:
Sleeping
Sleeping
| import os | |
| import shutil | |
| import subprocess | |
| import gradio as gr | |
| # Use /tmp in Spaces, or ./data locally if you set LOCAL_TRAIN=1 | |
| LOCAL = os.environ.get("LOCAL_TRAIN", "").lower() in ("1","true") | |
| DATA_DIR = os.path.join(os.getcwd(), "data") if LOCAL else "/tmp/data" | |
| os.makedirs(DATA_DIR, exist_ok=True) | |
| def prepare_dataset(files): | |
| # wipe and copy uploaded files | |
| for f in os.listdir(DATA_DIR): | |
| os.remove(os.path.join(DATA_DIR, f)) | |
| for file in files: | |
| dst = os.path.join(DATA_DIR, os.path.basename(file.name)) | |
| shutil.copyfile(file.name, dst) | |
| return f"β {len(files)} files uploaded to {DATA_DIR}" | |
| def start_training(base_model, trigger_word, steps, r, alpha): | |
| # pass args via environment to train.py | |
| env = os.environ.copy() | |
| env.update({ | |
| "BASE_MODEL": base_model, | |
| "TRIGGER_WORD": trigger_word, | |
| "NUM_STEPS": str(steps), | |
| "LORA_R": str(r), | |
| "LORA_ALPHA": str(alpha), | |
| "LOCAL_TRAIN": os.environ.get("LOCAL_TRAIN","") | |
| }) | |
| # run training and capture all output | |
| proc = subprocess.run( | |
| ["python3","train.py"], | |
| capture_output=True, text=True, env=env | |
| ) | |
| return proc.stdout + ("\n" + proc.stderr if proc.stderr else "") | |
| model_choices = [ | |
| "HiDream-ai/HiDream-I1-Dev", | |
| "runwayml/stable-diffusion-v1-5", | |
| "stabilityai/stable-diffusion-2-1" | |
| ] | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# ποΈ HiDream LoRA Trainer") | |
| gr.Markdown(f"Running in **{'local' if LOCAL else 'Spaces'}** mode; data dir: `{DATA_DIR}`") | |
| with gr.Row(): | |
| uploader = gr.File(file_types=["image",".txt"], file_count="multiple", label="Upload images + texts") | |
| up_btn = gr.Button("π Upload") | |
| up_status = gr.Textbox(label="Upload status") | |
| mdl = gr.Dropdown(model_choices, value=model_choices[0], label="Base model") | |
| tw = gr.Textbox(label="Trigger word", placeholder="e.g. rami-style") | |
| st = gr.Slider(10,500,value=100,step=10,label="Training steps") | |
| r_v = gr.Slider(4,128,value=16,step=4,label="LoRA rank (r)") | |
| a_v = gr.Slider(4,128,value=16,step=4,label="LoRA alpha") | |
| tr_btn = gr.Button("π Train") | |
| log_tb = gr.Textbox(label="Training log", lines=20) | |
| up_btn.click(prepare_dataset, inputs=uploader, outputs=up_status) | |
| tr_btn.click(start_training, inputs=[mdl,tw,st,r_v,a_v], outputs=log_tb) | |
| demo.launch(server_name="0.0.0.0", server_port=7860) | |