Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files4 unmodified lines5678910111 unmodified line131415161718192021222324252627282930313233343536373839404142434445464748495051527 unmodified lines606162636465666768692 unmodified lines727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121 unmodified line1141151161171181191201211221231241251261 unmodified line128129130131132133134135136137138139140141142143144145101 unmodified lines24724824925025125225312 unmodified lines2662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303311 unmodified line33333433533633733833934034134234334434534634734834935035135235335435535635735835911 unmodified lines3713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064073 unmodified lines4114124134144154164174184194209 unmodified lines4304314324334344354366 unmodified lines4434444454464474484494504514526 unmodified lines45946046146246346414 unmodified lines47948048148248348448548610 unmodified lines49749849950050150250319 unmodified lines52352452552652752852953053153253353453553653753853954054154254354454554654754815 unmodified lines5645655665675685695709 unmodified lines5805815825835845855865873 unmodified lines59159259359459559659711 unmodified lines60961061161261361461530 unmodified lines64664764864965065165265365465565665765865966066166266366466566666761 unmodified lines7297307317327337347359 unmodified lines7457467477487497507517527537547557567577587597607617621 unmodified line7647657667677687697707717727737747757767777785 unmodified lines7847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168173 unmodified lines8218228238248258268278288298308318 unmodified lines8408418428438448458468471 unmodified line8498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928931 unmodified line8958968978988999009019029039049059069079089099109119129139149159169179189199202 unmodified lines923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810198 unmodified lines10281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710584 unmodified lines106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911006 unmodified lines11071108110911101111111211131114111511161117111811191120112111221123112411254 unmodified linesimport loggingimport zipfileimport importlibimport sentry_sdkimport wandbfrom contextlib import redirect_stdout, redirect_stderrimport spaces1 unmodified lineUSE_WANDB = "WANDB_API_KEY" in os.environif USE_WANDB:wandb.login(key=os.environ["WANDB_API_KEY"])else:print("Warning: WANDB_API_KEY not set. Skipping wandb logging.")import gradioimport functoolsfrom sentry_sdk import flushorig_call_fn = gradio.blocks.Blocks.call_function # present in all 3.x & 4.x@functools.wraps(orig_call_fn)async def sentry_call_fn(self, *args, **kwargs):try:return await orig_call_fn(self, *args, **kwargs)except Exception as exc:capture_exception(exc)flush(timeout=2)raisegradio.blocks.Blocks.call_function = sentry_call_fnimport gradio as grimport pandas as pdimport osimport timeimport sysfrom datetime import datetimeimport re# --- Configuration ---#AUTFORGE_SCRIPT_PATH = "auto_forge.py" # Make sure this points to your scriptDEFAULT_MATERIALS_CSV = "default_materials.csv"GRADIO_OUTPUT_BASE_DIR = "output"os.makedirs(GRADIO_OUTPUT_BASE_DIR, exist_ok=True)7 unmodified lines}def exc_text(exc: BaseException) -> str:"""Return the human-readable message of *exc*.Falls back to the class name if the message is empty."""txt = str(exc).strip()if txt:return txt2 unmodified linesreturn exc.__class__.__name__def ensure_required_cols(df, *, in_display_space):"""Return a copy of *df* with every required column present.If *in_display_space* is True we use the display names(Brand, Name, TD, Color (Hex)); otherwise we use the script names."""target_cols = (DISPLAY_COL_MAP if in_display_space else {k: k for k in REQUIRED_SCRIPT_COLS})df_fixed = df.copy()for col_script, col_display in target_cols.items():if col_display not in df_fixed.columns:# sensible defaultsif "TD" in col_display:default = 0.0elif "Color" in col_display:default = "#000000"elif "Owned" in col_display: # NEWdefault = "false"else:default = ""df_fixed[col_display] = default# order columns nicelyreturn df_fixed[list(target_cols.values())]def rgba_to_hex(col: str) -> str:"""Turn 'rgba(r, g, b, a)' or 'rgb(r, g, b)' into '#RRGGBB'.If the input is already a hex code or anything unexpected,return it unchanged."""if not isinstance(col, str):return colcol = col.strip()if col.startswith("#"): # already finereturn col.upper()m = re.match(1 unmodified linecol,)if not m:return col # not something we recogniser, g, b = (int(float(x)) for x in m.groups()[:3])return "#{:02X}{:02X}{:02X}".format(r, g, b)def zip_dir_no_compress(src_dir: str, dest_zip: str) -> str:"""Create *dest_zip* from *src_dir* using no compression (ZIP_STORED)."""t0 = time.time()with zipfile.ZipFile(dest_zip, "w",compression=zipfile.ZIP_STORED,1 unmodified linefor root, _, files in os.walk(src_dir):for fname in files:fpath = os.path.join(root, fname)# keep folder structure inside the archive but drop the leading pathzf.write(fpath, os.path.relpath(fpath, src_dir))print(f"Zipping finished in {time.time() - t0:.1f}s")return dest_zip# --- Helper Functions ---def get_script_args_info(exclude_args=None):if exclude_args is None:exclude_args = []all_args_info = [# input_image is handled separately in the UI{"name": "--iterations","type": "number",101 unmodified lines"min": 0.0,"max": 1.0,"step": 0.01,"help": "Percentage of increment search for fast pruning. If unsure just keep it at 0.05 (5%).",},{"name": "--random_seed",12 unmodified lines]return [arg for arg in all_args_info if arg["name"] not in exclude_args]# Initial filament datainitial_filament_data = {"Brand": ["Generic", "Generic", "Generic","Generic","Generic","Generic",]," Name": ["PLA Black", "PLA Grey", "PLA White","PLA Red","PLA Green","PLA Blue"]," TD": [5.0, 5.0, 5.0, 5.0, 5.0, 5.0]," Color": ["#000000", "#808080", "#FFFFFF","#FF0000","#00FF00","#0000FF"]," Owned": ["true", "true", "true", "true", "true", "true"], # ← add}initial_df = pd.DataFrame(initial_filament_data)if os.path.exists(DEFAULT_MATERIALS_CSV):try:# Load what the user already hasloaded_df = pd.read_csv(DEFAULT_MATERIALS_CSV)# Make sure the columns we need are presentfor col in ["Brand", " Name", " TD", " Color"]:if col not in loaded_df.columns:# keep it simple, create empty columnloaded_df[col] = "" if col != " TD" else 0.0# Cast to the types we expectloaded_df = loaded_df[["Brand", " Name", " TD", " Color"]].astype({" TD": float, " Color": str})# Keep a DataFrame version for the rest of the appinitial_df = loaded_df# Important part:# also update the in memory initial_filament_data so later fallbacks# do not go back to the hardcoded 6 Generic rowsinitial_filament_data = {"Brand": initial_df["Brand"].tolist()," Name": initial_df[" Name"].tolist()," TD": initial_df[" TD"].tolist()," Color": initial_df[" Color"].tolist(),}# If you want to keep " Owned" around even when CSV did not have it,# you can add a default hereif " Owned" not in initial_df.columns:# fill with false by defaultinitial_filament_data[" Owned"] = ["false"] * len(initial_df)else:initial_filament_data[" Owned"] = initial_df[" Owned"].astype(str).tolist()except Exception as e:print(f"Warning: Could not load {DEFAULT_MATERIALS_CSV}: {e}. Using default.")initial_df = pd.DataFrame(initial_filament_data)else:# CSV does not exist yet, create it from the hardcoded defaultsinitial_df = pd.DataFrame(initial_filament_data)initial_df.to_csv(DEFAULT_MATERIALS_CSV, index=False)def run_autoforge_process(cmd, log_path):"""Run AutoForge in-process and stream its console output to *log_path*."""from joblib import parallel_backendcli_args = cmd[1:] # skip the literal "autoforge"autoforge_main = importlib.import_module("autoforge.__main__")exit_code = 01 unmodified lineredirect_stdout(log_f), redirect_stderr(log_f), parallel_backend("threading", n_jobs=-1):try:sys.argv = ["autoforge"] + cli_argsautoforge_main.main() # runs until completionexcept SystemExit as e: # AutoForge calls sys.exit()exit_code = e.codereturn exit_code# Helper for creating an empty 10-tuple for error returnsdef create_empty_error_outputs(log_message=""):return (log_message, # progress_outputNone, # final_image_previewgr.update(visible=False, interactive=False), # ### ZIP: download_zip)def load_filaments_from_json_upload(file_obj):"""Called when the user picks a .json file and converts it to thescript-style DataFrame expected by the rest of the app."""# ── early-out when nothing was chosen ──────────────────────────────if file_obj is None:current_script_df = filament_df_state.valueif current_script_df is not None and not current_script_df.empty:11 unmodified linesdata = data["Filaments"]df_loaded = pd.DataFrame(data)# strip whitespace around every header firstdf_loaded.columns = [c.strip() for c in df_loaded.columns]# convert Hue-forge “nice” headers to the script headers that# still carry a leading blankrename_map = {"Name": " Name","Transmissivity": " TD","Color": " Color",}df_loaded.rename(columns={k: v for k, v in rename_map.items() if k in df_loaded.columns},inplace=True,)if " TD" in df_loaded.columns:df_loaded[" TD"] = pd.to_numeric(df_loaded[" TD"], errors="coerce").fillna(0.0)# now make sure the usual helpers see exactly the expected headersdf_loaded = ensure_required_cols(df_loaded, in_display_space=False)expected_cols = ["Brand", " Name", " TD", " Color"]if not all(col in df_loaded.columns for col in expected_cols):gr.Error(f"JSON must contain keys/columns: {', '.join(expected_cols)}. "f"Found: {df_loaded.columns.tolist()}")return filament_table.value # keep the table unchangedfilament_df_state.value = df_loaded.copy()3 unmodified linesexcept Exception as e:gr.Error(f"Error loading JSON: {e}")return filament_table.value # keep current table on failure# --- Gradio UI Definition ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# [Autoforge](https://github.com/hvoss-techfak/AutoForge) Web UI")9 unmodified lines'If you have Hueforge, you can export your filaments under "Filaments -> Export" in the Hueforge software. Please make sure to select "CSV" instead of "JSON" during the export dialog.')gr.Markdown('If you want to load your personal library of Hueforge filaments, you can also simply paste this path into your explorer address bar: %APPDATA%\HueForge\Filaments\ and import your "personal_library.json" using the "Load Filaments Json" button.')gr.Markdown('To remove a filament simply right-click on any of the fields and select "Delete Row"'6 unmodified linesload_csv_button = gr.UploadButton("Load Filaments CSV", file_types=[".csv"])load_json_button = gr.UploadButton( # NEW"Load Filaments JSON", file_types=[".json"])save_csv_button = gr.Button("Save Current Filaments to CSV")filament_table = gr.DataFrame(value=ensure_required_cols(initial_df.copy().rename(6 unmodified linesinteractive=True,label="Filaments",)gr.Markdown("## Add New Filament")with gr.Row():new_brand = gr.Textbox(label="Brand")14 unmodified linesdef update_filament_df_state_from_table(display_df):display_df = ensure_required_cols(display_df, in_display_space=True)# make sure every colour is hexif "Color (Hex)" in display_df.columns:display_df["Color (Hex)"] = display_df["Color (Hex)"].apply(rgba_to_hex10 unmodified linesgr.Warning("Brand and Name cannot be empty.")return current_display_dfcolor_hex = rgba_to_hex(color_hex) # <-- new linenew_row = pd.DataFrame([{"Brand": brand, "Name": name, "TD": td, "Color (Hex)": color_hex}]19 unmodified linescolumns={" Name": "Name", " TD": "TD", " Color": "Color (Hex)"})try:loaded_script_df = pd.read_csv(file_obj.name)loaded_script_df = ensure_required_cols(loaded_script_df, in_display_space=False)expected_cols = ["Brand", " Name", " TD", " Color"]if not all(col in loaded_script_df.columns for col in expected_cols):gr.Error(f"CSV must contain columns: {', '.join(expected_cols)}. Found: {loaded_script_df.columns.tolist()}")capture_exception(Exception(f"CSV must contain columns: {', '.join(expected_cols)}. Found: {loaded_script_df.columns.tolist()}"))current_script_df = filament_df_state.valueif (current_script_df is not Noneand not current_script_df.empty):return current_script_df.rename(columns={15 unmodified lines)except Exception as e:gr.Error(f"Error loading CSV: {e}")capture_exception(e)current_script_df = filament_df_state.valueif current_script_df is not None and not current_script_df.empty:return current_script_df.rename(9 unmodified linesdef save_filaments_to_file_for_download(current_script_df_from_state):if (current_script_df_from_state is Noneor current_script_df_from_state.empty):gr.Warning("Filament table is empty. Nothing to save.")return None3 unmodified linesgr.Error(f"Cannot save. DataFrame missing required script columns. Expected: {required_cols}. Found: {df_to_save.columns.tolist()}")capture_exception(Exception(f"Missing columns: {df_to_save.columns.tolist()}"))return Nonetemp_dir = os.path.join(GRADIO_OUTPUT_BASE_DIR, "_temp_downloads")os.makedirs(temp_dir, exist_ok=True)11 unmodified linesvisible=True,)except Exception as e:capture_exception(e)gr.Error(f"Error saving CSV for download: {e}")return None30 unmodified linesaccordion_params_ordered_names = []gr.Markdown('Here you can upload an image, adjust the parameters and run the Autoforge process. The filaments from the "Filament Management" Tab are automatically used. After the process completes you can download the results at the bottom of the page.')gr.Markdown('If you want to limit the number of colors or color swaps you can find the option under the "Autoforge Parameters" as "pruning_max_colors" and "pruning_max_swaps"')gr.Markdown('Please note that huggingface enforces a maximum execution time of two minutes. Depending on your configuration (especially iteration count) it is possible to exceed this time limit. In that case you will see a "GPU Task aborted" error or simply "Error".'' If you need more time, take a look at the [Autoforge Github Page](https://github.com/hvoss-techfak/AutoForge) to see how you can run the program locally, or pull the docker container for this project (upper right corner -> three dots -> "run locally")')with gr.Row():with gr.Column(scale=1):gr.Markdown("### Input Image (Required)")input_image_component = gr.Image( # keep transparency alivetype="pil", # <- no temporary JPEG cacheimage_mode="RGBA", # tells Gradio to expect alphalabel="Upload Image",sources=["upload"],interactive=True,61 unmodified lineselem_id="run_button_full_width",)progress_output = gr.Textbox(label="Console Output",lines=15,9 unmodified linesvisible=False,)# --- Backend Function for Running the Script ---@spaces.GPU(duration=150)def execute_autoforge_script(current_filaments_df_state_val, input_image, *accordion_param_values):log_output = []# 0. Validate Inputsif input_image is None:gr.Error("Input Image is required! Please upload an image.")capture_exception(Exception("Input Image is required!"))return create_empty_error_outputs("Error: Input Image is required!")timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + str(uuid.uuid4())1 unmodified lineos.makedirs(run_output_dir_val, exist_ok=True)current_run_output_dir.value = run_output_dir_val# 1. Save current filamentsif (current_filaments_df_state_val is Noneor current_filaments_df_state_val.empty):gr.Error("Filament table is empty. Please add filaments.")capture_exception(Exception("Filament table is empty. Please add filaments."))return create_empty_error_outputs("Error: Filament table is empty.")temp_filament_csv = os.path.join(run_output_dir_val, "materials.csv")5 unmodified linesf"Error: Filament data is missing columns: {', '.join(missing_cols)}.")gr.Error(err_msg)capture_exception(Exception(f"Filament data is missing columns: {', '.join(missing_cols)}."))return create_empty_error_outputs(err_msg)try:df_to_save.to_csv(temp_filament_csv, index=False)except Exception as e:capture_exception(e)err_msg = f"Error saving temporary filament CSV: {e}"gr.Error(err_msg)return create_empty_error_outputs(err_msg)# 2. Construct commandpython_executable = sys.executable or "python"command = ["autoforge",]command.extend(["--csv_file", temp_filament_csv])command.extend(["--output_folder", run_output_dir_val])command.extend(["--disable_visualization_for_gradio","1"])try:# decide where to store the image we pass to Autoforgescript_input_image_path = os.path.join(run_output_dir_val, "input_image.png")input_image.save(script_input_image_path, format="PNG")command.extend(["--input_image", script_input_image_path])except Exception as e:capture_exception(e)err_msg = f"Error handling input image: {e}"gr.Error(err_msg)return create_empty_error_outputs(err_msg)3 unmodified linesif arg_widget_val is None or arg_widget_val == "":arg_info_list = [item for item in get_script_args_info() if item["name"] == arg_name] # get full list to check typeif (arg_info_listand arg_info_list[0]["type"] == "checkbox"and arg_widget_val is False):continueelse:8 unmodified lineselse:command.extend([arg_name, str(arg_widget_val)])# 3. Run scriptlog_output = ["Starting Autoforge process at ",f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n",1 unmodified linef"Command: {' '.join(command)}\n\n",]yield create_empty_error_outputs(log_output) # clear UI and show headerdef _maybe_new_preview():"""If vis_temp.png has a newer mtime than last time, copy it to astamped name (to defeat browser cache) and return that path.Otherwise return gr.update() so the image stays as-is."""from gradio import update # local import for claritynonlocal preview_mtimesrc = os.path.join(run_output_dir_val, "vis_temp.png")if not os.path.exists(src):return update() # nothing new, keep oldmtime = os.path.getmtime(src)if mtime <= preview_mtime: # unchangedreturn update() # → no UI updatereturn src # → refresh image# ---- run Autoforge on the GPU in a helper thread ------------------log_file = os.path.join(run_output_dir_val, "autoforge_live.log")open(log_file, "w", encoding="utf-8").close()cmd_str = " ".join(command)sentry_sdk.capture_event({"message": "Autoforge process started","level": "info","fingerprint": ["autoforge-process-start"], # every start groups here"extra": {"command": cmd_str}, # still searchable})# simple thread that just calls the GPU helper and stores the exit codeimport threadingclass Worker(threading.Thread):1 unmodified linesuper().__init__(daemon=True)self.cmd, self.log_path = cmd, log_pathself.returncode = Nonedef run(self):try:self.returncode = run_autoforge_process(self.cmd, self.log_path)except Exception as e:exc_str = exc_text(e)self.exc = ecapture_exception(e) # still goes to Sentry# make the error visible in the UI consolewith open(self.log_path, "a", encoding="utf-8") as lf:lf.write("\nERROR: {}. This usually means that you, your IP adress or the space has no free GPU ""minutes left, or the process took too long due to too many filaments or changed parameters. Please clone the docker container, run it locally or wait for a bit.\n".format(exc_str))gr.Error("ERROR: {}. This usually means that you, your IP adress or the the space has no free GPU ""minutes left, or the process took too long due to too many filaments or changed parameters. Please clone the docker container, run it locally or wait for a bit.\n".format(exc_str))# a non-zero code tells the outer loop something went wrongself.returncode = -1try:2 unmodified linespreview_mtime = 0last_push = 0file_pos = 0 # how far we've readwhile worker.is_alive() or file_pos < os.path.getsize(log_file):# read any new console textwith open(log_file, "r", encoding="utf-8") as lf:lf.seek(file_pos)new_txt = lf.read()file_pos = lf.tell()log_output += new_txtnow = time.time()if now - last_push >= 1.0: # one-second UI tickcurrent_preview = _maybe_new_preview()yield ("".join(log_output),current_preview,gr.update(), # placeholder for download widget)last_push = nowtime.sleep(0.05)worker.join() # make sure it’s doneexcept RuntimeError as e:# Show toast to userlog_output += repr(e)gr.Error(str(e)) # <-- this is the toastcapture_exception(e)with open(log_file, "r", encoding="utf-8") as lf:lf.seek(file_pos)new_txt = lf.read()file_pos = lf.tell()log_output += new_txtyield ("".join(log_output),current_preview,gr.update(), # placeholder for download widget)return create_empty_error_outputs(str(e))if getattr(worker, "exc", None) is not None:# worker.exc will be the ZeroGPU / scheduler errorerr_msg = f"GPU run failed: {worker.exc}"log_output += f"\n{err_msg}\n"gr.Error(err_msg) # toastyield ( # push the message into the textbox"".join(log_output),_maybe_new_preview(),gr.update(),)return # stop the coroutine cleanly# If the GPU scheduler threw, we already wrote the text into the log.# Just read the tail once more so it reaches the UI textbox.with open(log_file, "r", encoding="utf-8") as lf:lf.seek(file_pos)log_output += lf.read()return_code = worker.returncodetry:sentry_sdk.add_attachment(path=log_file,filename="autoforge.log",content_type="text/plain",)except Exception as e:capture_exception(e)if worker.returncode != 0:err_msg = (f"Autoforge exited with code {worker.returncode}\n""See the console output above for details.")log_output += f"\n{err_msg}\n"gr.Error(err_msg)yield ("".join(log_output),_maybe_new_preview(),gr.update(),)returnlog_output += ("\nAutoforge process completed successfully!"if return_code == 0else f"\nAutoforge process failed with exit code {return_code}.")log_str = " ".join(log_output)files_to_offer = [p8 unmodified linespng_path = os.path.join(run_output_dir_val, "final_model.png")out_png = png_path if os.path.exists(png_path) else Noneif out_png is None:log_output += "\nWarning: final_model.png not found in output."zip_path = Noneif files_to_offer:zip_path = os.path.join(run_output_dir_val, "autoforge_results.zip")log_output += f"\nZipping results to {os.path.basename(zip_path)}..."try:with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_STORED) as zf:for f in files_to_offer:zf.write(f, os.path.basename(f))log_output += " done."except Exception as e:capture_exception(e)log_output += f"\nError creating zip file: {e}"zip_path = None # Don't offer a broken zipsentry_sdk.capture_event( # moved inside the same scope{"message": "Autoforge process finished","level": "info","fingerprint": ["autoforge-process-finished"],"extra": {"log": log_str},})if USE_WANDB:run = None4 unmodified linesnotes="Autoforge Web UI run",tags=["autoforge", "gradio"],)wlogs= {"input_image": wandb.Image(script_input_image_path),}if out_png:wlogs["output_image"] = wandb.Image(out_png)material_csv = pd.read_csv(temp_filament_csv)table = wandb.Table(dataframe=material_csv)wlogs["materials"] = table#log log_output as pandas tablefrom wandb import Htmllog_text = "".join(log_output).replace("\r", "\n")def clean_log_strict(text: str) -> str:# Keep only printable characters + newline + taballowed = set(string.printable) | {"\n", "\t"}return "".join(ch for ch in text if ch in allowed)log_text_cleaned = clean_log_strict(log_text)wlogs["log"] = Html(f"<pre>{log_text_cleaned}</pre>")wandb.log(wlogs)except Exception as e:#we don't want wandb errors logged in sentryprint(e)finally:if run is not None:run.finish()yield ("".join(log_output), # progress_outputout_png, # final_image_preview (same as before)gr.update( # download_resultsvalue=zip_path,visible=bool(zip_path),interactive=bool(zip_path),6 unmodified linesrun_outputs = [progress_output,final_image_preview,download_results, # ### ZIP PATCH: only three outputs now]run_button.click(execute_autoforge_script, inputs=run_inputs, outputs=run_outputs)css = """ #run_button_full_width { width: 100%; } """if __name__ == "__main__":if not os.path.exists(DEFAULT_MATERIALS_CSV):print(f"Creating default filament file: {DEFAULT_MATERIALS_CSV}")try:initial_df.to_csv(DEFAULT_MATERIALS_CSV, index=False)except Exception as e:print(f"Could not write default {DEFAULT_MATERIALS_CSV}: {e}")print("To run the UI, execute: python app.py") # Corrected to python app.pydemo.queue(default_concurrency_limit=1).launch(share=False)4 unmodified lines56789101 unmodified line12131415161718192021222324252627287 unmodified lines3637383940412 unmodified lines444546474849505152535455565758596061626364656667686970711 unmodified line7374757677787980818283841 unmodified line8687888990919293949596979899100101 unmodified lines20220320420520620720812 unmodified lines2212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993001 unmodified line30230330430530630730830931031131231331431531631731831932032132232332411 unmodified lines3363373383393403413423433443453463473483493503513523533543553 unmodified lines3593603613623633643653669 unmodified lines3763773783793803813826 unmodified lines3893903913923933943953963973983996 unmodified lines40640740840941041141214 unmodified lines42742842943043143210 unmodified lines44344444544644744844919 unmodified lines46947047147247347447547647747847948048148248348448548615 unmodified lines5025035045055065079 unmodified lines5175185195205215225235243 unmodified lines52852953053153253311 unmodified lines54554654754854955030 unmodified lines58158258358458558658758858959059159259359459561 unmodified lines6576586596606616629 unmodified lines6726736746756766776786796806816826836846856861 unmodified line6886896906916926936946956966976985 unmodified lines7047057067077087097107117127137147157167177187197207217227237247257267277287293 unmodified lines7337347357367377387397407417427438 unmodified lines7527537547557567571 unmodified line7597607617627637647657667677687691 unmodified line7717727737747757767777787797807817827837847857867877887892 unmodified lines7927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618 unmodified lines8708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029034 unmodified lines9089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399406 unmodified lines9479489499509519529539549559569579589599609619629639649654 unmodified linesimport loggingimport zipfileimport importlibimport wandbfrom contextlib import redirect_stdout, redirect_stderrimport spaces1 unmodified lineUSE_WANDB = "WANDB_API_KEY" in os.environif USE_WANDB:wandb.login(key=os.environ["WANDB_API_KEY"])else:print("Warning: WANDB_API_KEY not set. Skipping wandb logging.")import gradio as grimport pandas as pdimport timeimport sysfrom datetime import datetimeimport re# --- Configuration ---DEFAULT_MATERIALS_CSV = "default_materials.csv"GRADIO_OUTPUT_BASE_DIR = "output"os.makedirs(GRADIO_OUTPUT_BASE_DIR, exist_ok=True)7 unmodified lines}def exc_text(exc: BaseException) -> str:txt = str(exc).strip()if txt:return txt2 unmodified linesreturn exc.__class__.__name__def ensure_required_cols(df, *, in_display_space):target_cols = (DISPLAY_COL_MAP if in_display_space else {k: k for k in REQUIRED_SCRIPT_COLS})df_fixed = df.copy()for col_script, col_display in target_cols.items():if col_display not in df_fixed.columns:if "TD" in col_display:default = 0.0elif "Color" in col_display:default = "#000000"elif "Owned" in col_display:default = "false"else:default = ""df_fixed[col_display] = defaultreturn df_fixed[list(target_cols.values())]def rgba_to_hex(col: str) -> str:if not isinstance(col, str):return colcol = col.strip()if col.startswith("#"):return col.upper()m = re.match(1 unmodified linecol,)if not m:return colr, g, b = (int(float(x)) for x in m.groups()[:3])return "#{:02X}{:02X}{:02X}".format(r, g, b)def zip_dir_no_compress(src_dir: str, dest_zip: str) -> str:t0 = time.time()with zipfile.ZipFile(dest_zip, "w",compression=zipfile.ZIP_STORED,1 unmodified linefor root, _, files in os.walk(src_dir):for fname in files:fpath = os.path.join(root, fname)zf.write(fpath, os.path.relpath(fpath, src_dir))print(f"Zipping finished in {time.time() - t0:.1f}s")return dest_zipdef get_script_args_info(exclude_args=None):if exclude_args is None:exclude_args = []all_args_info = [{"name": "--iterations","type": "number",101 unmodified lines"min": 0.0,"max": 1.0,"step": 0.01,"help": "Percentage of increment search for fast pruning.",},{"name": "--random_seed",12 unmodified lines]return [arg for arg in all_args_info if arg["name"] not in exclude_args]# initial data that will be used if no CSV existsinitial_filament_data = {"Brand": ["Generic", "Generic", "Generic", "Generic", "Generic", "Generic"]," Name": ["PLA Black", "PLA Grey", "PLA White", "PLA Red", "PLA Green", "PLA Blue"]," TD": [5.0, 5.0, 5.0, 5.0, 5.0]," Color": ["#000000", "#808080", "#FFFFFF", "#FF0000", "#00FF00", "#0000FF"]," Owned": ["true", "true", "true", "true", "true", "true"],}def normalize_filament_df(df: pd.DataFrame) -> pd.DataFrame:df = df.copy()df.columns = [c.strip() for c in df.columns]rename_map = {"Name": " Name","TD": " TD","Color": " Color","Owned": " Owned",}for src, dst in rename_map.items():if src in df.columns and dst not in df.columns:df.rename(columns={src: dst}, inplace=True)if " TD" in df.columns:df[" TD"] = pd.to_numeric(df[" TD"], errors="coerce").fillna(0.0)else:df[" TD"] = 0.0if " Color" in df.columns:df[" Color"] = df[" Color"].astype(str)else:df[" Color"] = "#000000"if " Owned" not in df.columns:df[" Owned"] = "false"else:df[" Owned"] = df[" Owned"].astype(str)if "Brand" not in df.columns:df["Brand"] = ""ordered_cols = ["Brand", " Name", " TD", " Color", " Owned"]df = df[[c for c in ordered_cols if c in df.columns]]return df# load CSV if presentif os.path.exists(DEFAULT_MATERIALS_CSV):try:loaded_df = pd.read_csv(DEFAULT_MATERIALS_CSV, index_col=False)loaded_df = normalize_filament_df(loaded_df)initial_df = loaded_df.copy()initial_filament_data = {"Brand": initial_df["Brand"].tolist()," Name": initial_df[" Name"].tolist()," TD": initial_df[" TD"].tolist()," Color": initial_df[" Color"].tolist(),}if " Owned" in initial_df.columns:initial_filament_data[" Owned"] = initial_df[" Owned"].astype(str).tolist()else:initial_filament_data[" Owned"] = ["false"] * len(initial_df)except Exception as e:print(f"Warning: Could not load {DEFAULT_MATERIALS_CSV}: {e}. Using default.")initial_df = pd.DataFrame(initial_filament_data)else:initial_df = pd.DataFrame(initial_filament_data)initial_df.to_csv(DEFAULT_MATERIALS_CSV, index=False)def run_autoforge_process(cmd, log_path):from joblib import parallel_backendcli_args = cmd[1:]autoforge_main = importlib.import_module("autoforge.__main__")exit_code = 01 unmodified lineredirect_stdout(log_f), redirect_stderr(log_f), parallel_backend("threading", n_jobs=-1):try:sys.argv = ["autoforge"] + cli_argsautoforge_main.main()except SystemExit as e:exit_code = e.codeexcept Exception as e:log_f.write(f"\nERROR: {e}\n")exit_code = -1return exit_codedef create_empty_error_outputs(log_message=""):return (log_message,None,gr.update(visible=False, interactive=False),)def load_filaments_from_json_upload(file_obj):if file_obj is None:current_script_df = filament_df_state.valueif current_script_df is not None and not current_script_df.empty:11 unmodified linesdata = data["Filaments"]df_loaded = pd.DataFrame(data)df_loaded.columns = [c.strip() for c in df_loaded.columns]rename_map = {"Name": " Name","Transmissivity": " TD","Color": " Color","Owned": " Owned",}df_loaded.rename(columns={k: v for k, v in rename_map.items() if k in df_loaded.columns},inplace=True,)df_loaded = normalize_filament_df(df_loaded)filament_df_state.value = df_loaded.copy()3 unmodified linesexcept Exception as e:gr.Error(f"Error loading JSON: {e}")return filament_table.valuewith gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# [Autoforge](https://github.com/hvoss-techfak/AutoForge) Web UI")9 unmodified lines'If you have Hueforge, you can export your filaments under "Filaments -> Export" in the Hueforge software. Please make sure to select "CSV" instead of "JSON" during the export dialog.')gr.Markdown('If you want to load your personal library of Hueforge filaments, you can also simply paste this path into your explorer address bar: %APPDATA%\\HueForge\\Filaments\\ and import your "personal_library.json" using the "Load Filaments Json" button.')gr.Markdown('To remove a filament simply right-click on any of the fields and select "Delete Row"'6 unmodified linesload_csv_button = gr.UploadButton("Load Filaments CSV", file_types=[".csv"])load_json_button = gr.UploadButton("Load Filaments JSON", file_types=[".json"])save_csv_button = gr.Button("Save Current Filaments to CSV")filament_table = gr.DataFrame(value=ensure_required_cols(initial_df.copy().rename(6 unmodified linesinteractive=True,label="Filaments",)gr.Markdown("## Add New Filament")with gr.Row():new_brand = gr.Textbox(label="Brand")14 unmodified linesdef update_filament_df_state_from_table(display_df):display_df = ensure_required_cols(display_df, in_display_space=True)if "Color (Hex)" in display_df.columns:display_df["Color (Hex)"] = display_df["Color (Hex)"].apply(rgba_to_hex10 unmodified linesgr.Warning("Brand and Name cannot be empty.")return current_display_dfcolor_hex = rgba_to_hex(color_hex)new_row = pd.DataFrame([{"Brand": brand, "Name": name, "TD": td, "Color (Hex)": color_hex}]19 unmodified linescolumns={" Name": "Name", " TD": "TD", " Color": "Color (Hex)"})try:loaded_script_df = pd.read_csv(file_obj.name, index_col=False)loaded_script_df = normalize_filament_df(loaded_script_df)expected_cols = ["Brand", " Name", " TD", " Color"]if not all(col in loaded_script_df.columns for col in expected_cols):gr.Error(f"CSV must contain columns: {', '.join(expected_cols)}. Found: {loaded_script_df.columns.tolist()}")current_script_df = filament_df_state.valueif (current_script_df is not Noneand not current_script_df.empty):return current_script_df.rename(columns={15 unmodified lines)except Exception as e:gr.Error(f"Error loading CSV: {e}")current_script_df = filament_df_state.valueif current_script_df is not None and not current_script_df.empty:return current_script_df.rename(9 unmodified linesdef save_filaments_to_file_for_download(current_script_df_from_state):if (current_script_df_from_state is Noneor current_script_df_from_state.empty):gr.Warning("Filament table is empty. Nothing to save.")return None3 unmodified linesgr.Error(f"Cannot save. DataFrame missing required script columns. Expected: {required_cols}. Found: {df_to_save.columns.tolist()}")return Nonetemp_dir = os.path.join(GRADIO_OUTPUT_BASE_DIR, "_temp_downloads")os.makedirs(temp_dir, exist_ok=True)11 unmodified linesvisible=True,)except Exception as e:gr.Error(f"Error saving CSV for download: {e}")return None30 unmodified linesaccordion_params_ordered_names = []gr.Markdown('Here you can upload an image, adjust the parameters and run the Autoforge process. The filaments from the "Filament Management" Tab are automatically used.')with gr.Row():with gr.Column(scale=1):gr.Markdown("### Input Image (Required)")input_image_component = gr.Image(type="pil",image_mode="RGBA",label="Upload Image",sources=["upload"],interactive=True,61 unmodified lineselem_id="run_button_full_width",)progress_output = gr.Textbox(label="Console Output",lines=15,9 unmodified linesvisible=False,)@spaces.GPU(duration=150)def execute_autoforge_script(current_filaments_df_state_val, input_image, *accordion_param_values):log_output = []if input_image is None:gr.Error("Input Image is required! Please upload an image.")return create_empty_error_outputs("Error: Input Image is required!")timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + str(uuid.uuid4())1 unmodified lineos.makedirs(run_output_dir_val, exist_ok=True)current_run_output_dir.value = run_output_dir_valif (current_filaments_df_state_val is Noneor current_filaments_df_state_val.empty):gr.Error("Filament table is empty. Please add filaments.")return create_empty_error_outputs("Error: Filament table is empty.")temp_filament_csv = os.path.join(run_output_dir_val, "materials.csv")5 unmodified linesf"Error: Filament data is missing columns: {', '.join(missing_cols)}.")gr.Error(err_msg)return create_empty_error_outputs(err_msg)try:df_to_save.to_csv(temp_filament_csv, index=False)except Exception as e:err_msg = f"Error saving temporary filament CSV: {e}"gr.Error(err_msg)return create_empty_error_outputs(err_msg)command = ["autoforge"]command.extend(["--csv_file", temp_filament_csv])command.extend(["--output_folder", run_output_dir_val])command.extend(["--disable_visualization_for_gradio", "1"])try:script_input_image_path = os.path.join(run_output_dir_val, "input_image.png")input_image.save(script_input_image_path, format="PNG")command.extend(["--input_image", script_input_image_path])except Exception as e:err_msg = f"Error handling input image: {e}"gr.Error(err_msg)return create_empty_error_outputs(err_msg)3 unmodified linesif arg_widget_val is None or arg_widget_val == "":arg_info_list = [item for item in get_script_args_info() if item["name"] == arg_name]if (arg_info_listand arg_info_list[0]["type"] == "checkbox"and arg_widget_val is False):continueelse:8 unmodified lineselse:command.extend([arg_name, str(arg_widget_val)])log_output = ["Starting Autoforge process at ",f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n",1 unmodified linef"Command: {' '.join(command)}\n\n",]yield create_empty_error_outputs("".join(log_output))log_file = os.path.join(run_output_dir_val, "autoforge_live.log")open(log_file, "w", encoding="utf-8").close()import threadingclass Worker(threading.Thread):1 unmodified linesuper().__init__(daemon=True)self.cmd, self.log_path = cmd, log_pathself.returncode = Noneself.exc = Nonedef run(self):try:self.returncode = run_autoforge_process(self.cmd, self.log_path)except Exception as e:self.exc = ewith open(self.log_path, "a", encoding="utf-8") as lf:lf.write("\nERROR: {}. This usually means there was no GPU or the process took too long.\n".format(exc_text(e)))self.returncode = -1try:2 unmodified linespreview_mtime = 0last_push = 0file_pos = 0def _maybe_new_preview():nonlocal preview_mtimesrc = os.path.join(run_output_dir_val, "vis_temp.png")if not os.path.exists(src):return gr.update()mtime = os.path.getmtime(src)if mtime <= preview_mtime:return gr.update()preview_mtime = mtimereturn srcwhile worker.is_alive() or file_pos < os.path.getsize(log_file):with open(log_file, "r", encoding="utf-8") as lf:lf.seek(file_pos)new_txt = lf.read()file_pos = lf.tell()log_output.append(new_txt)now = time.time()if now - last_push >= 1.0:current_preview = _maybe_new_preview()yield ("".join(log_output),current_preview,gr.update(),)last_push = nowtime.sleep(0.05)worker.join()except RuntimeError as e:log_output.append(repr(e))gr.Error(str(e))with open(log_file, "r", encoding="utf-8") as lf:lf.seek(file_pos)new_txt = lf.read()file_pos = lf.tell()log_output.append(new_txt)yield ("".join(log_output),gr.update(),gr.update(),)return create_empty_error_outputs(str(e))if getattr(worker, "exc", None) is not None:err_msg = f"GPU run failed: {worker.exc}"log_output.append(f"\n{err_msg}\n")gr.Error(err_msg)yield ("".join(log_output),gr.update(),gr.update(),)returnwith open(log_file, "r", encoding="utf-8") as lf:lf.seek(file_pos)log_output.append(lf.read())return_code = worker.returncodefiles_to_offer = [p8 unmodified linespng_path = os.path.join(run_output_dir_val, "final_model.png")out_png = png_path if os.path.exists(png_path) else Noneif return_code != 0:err_msg = (f"Autoforge exited with code {return_code}\n""See the console output above for details.")log_output.append(f"\n{err_msg}\n")gr.Error(err_msg)yield ("".join(log_output),out_png if out_png else gr.update(),gr.update(),)returnlog_output.append("\nAutoforge process completed successfully!")zip_path = Noneif files_to_offer:zip_path = os.path.join(run_output_dir_val, "autoforge_results.zip")log_output.append(f"\nZipping results to {os.path.basename(zip_path)}...")try:with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_STORED) as zf:for f in files_to_offer:zf.write(f, os.path.basename(f))log_output.append(" done.")except Exception as e:log_output.append(f"\nError creating zip file: {e}")zip_path = Noneif USE_WANDB:run = None4 unmodified linesnotes="Autoforge Web UI run",tags=["autoforge", "gradio"],)wlogs = {"input_image": wandb.Image(script_input_image_path)}if out_png:wlogs["output_image"] = wandb.Image(out_png)material_csv = pd.read_csv(temp_filament_csv)table = wandb.Table(dataframe=material_csv)wlogs["materials"] = tablefrom wandb import Htmllog_text = "".join(log_output).replace("\r", "\n")def clean_log_strict(text: str) -> str:allowed = set(string.printable) | {"\n", "\t"}return "".join(ch for ch in text if ch in allowed)log_text_cleaned = clean_log_strict(log_text)wlogs["log"] = Html(f"<pre>{log_text_cleaned}</pre>")wandb.log(wlogs)except Exception as e:print(e)finally:if run is not None:run.finish()yield ("".join(log_output),out_png,gr.update(value=zip_path,visible=bool(zip_path),interactive=bool(zip_path),6 unmodified linesrun_outputs = [progress_output,final_image_preview,download_results,]run_button.click(execute_autoforge_script, inputs=run_inputs, outputs=run_outputs)css = """ #run_button_full_width { width: 100%; } """if __name__ == "__main__":if not os.path.exists(DEFAULT_MATERIALS_CSV):print(f"Creating default filament file: {DEFAULT_MATERIALS_CSV}")try:initial_df.to_csv(DEFAULT_MATERIALS_CSV, index=False)except Exception as e:print(f"Could not write default {DEFAULT_MATERIALS_CSV}: {e}")print("To run the UI, execute: python app.py")demo.queue(default_concurrency_limit=1).launch(share=False)
app.py+152-312