Spaces:
Sleeping
Sleeping
Improve UI and add overlapping interlock
Browse filesFiles changed (4)
- README.md+3-2
- app.py+502-115
- tests/test_app_scaling.py+39
- tests/test_nozzle_spacing.py+63
42 unmodified lines43444546474821 unmodified lines70717273747576777842 unmodified lines- Shows an interactive selected-shape 3D viewer for rotating each model- Shows model extents, face count, vertex count, and watertight status- Scales loaded STLs from editable target X/Y/Z dimensions in the Shape Settings table; new rows default to the STL's original dimensions, **Reset Dimensions** restores them, and **Keep Proportions** updates the other target sides from the edited side- Lets you choose layer height and XY pixel size- Produces one `.tif` image per slice- Encodes material as black (`0`) and empty space as white (`255`) in each TIFF slice21 unmodified lines- Alignment is centered image placement, not bottom-left anchoring.- If image-size differences are odd, centering may produce a one-pixel shift due to integer rounding.### Single Shape Multi-NozzleThe **Single Shape Multi-Nozzle** tab can split one generated shape stack into a grid of print-ready stacks. Choose a source shape that already has TIFF slices, set the number of columns and rows, choose the starting nozzle and valve numbers, then click **Split Selected Shape into Grid Pieces**.- Each slice is split into columns along X and rows along Y; leftover pixels are assigned to earlier columns/rows so no pixels are dropped.- The selected shape is replaced in Shape Settings by one generated record per grid cell, named by row and column.42 unmodified lines4344454647484921 unmodified lines71727374757677787942 unmodified lines- Shows an interactive selected-shape 3D viewer for rotating each model- Shows model extents, face count, vertex count, and watertight status- Scales loaded STLs from editable target X/Y/Z dimensions in the Shape Settings table; new rows default to the STL's original dimensions, **Reset Dimensions** restores them, and **Keep Proportions** updates the other target sides from the edited side- Keeps optional shape, TIFF, reference-stack, and nozzle-spacing previews in closed accordions to reduce clutter- Lets you choose layer height and XY pixel size- Produces one `.tif` image per slice- Encodes material as black (`0`) and empty space as white (`255`) in each TIFF slice21 unmodified lines- Alignment is centered image placement, not bottom-left anchoring.- If image-size differences are odd, centering may produce a one-pixel shift due to integer rounding.### Multi-Nozzle SplitThe **Multi-Nozzle Split** accordion on the **STL to TIFF Slicer** tab can split one generated shape stack into a grid of print-ready stacks. Choose a source shape that already has TIFF slices, set the number of columns and rows, choose the starting nozzle and valve numbers, then click **Split Selected Shape into Grid Pieces**.- Each slice is split into columns along X and rows along Y; leftover pixels are assigned to earlier columns/rows so no pixels are dropped.- The selected shape is replaced in Shape Settings by one generated record per grid cell, named by row and column.
37 unmodified lines383940414243449 unmodified lines54555657585939 unmodified lines991001011021031041349 unmodified lines145414551456145714581459194 unmodified lines1654165516561657165816591660166116621663166413 unmodified lines16781679168016811682168317 unmodified lines170117021703170417051706170717086 unmodified lines1715171617171718171917201721172217231724172517261727172817291730173117321733145 unmodified lines18791880188118821883188418851886188718881889189018917 unmodified lines1899190019011902190319041905189 unmodified lines20952096209720982099210021 unmodified lines21222123212421252126212726 unmodified lines2154215521562157215821592160363 unmodified lines25242525252625272528252930 unmodified lines25602561256225632564256544 unmodified lines261026112612261326142615132 unmodified lines274827492750275127522753275427552756275727582759276027612762276327642765276664 unmodified lines2831283228332834283528362 unmodified lines28392840284128422843284428452846284728482849285028512852285327 unmodified lines2881288228832884288528866 unmodified lines28932894289528962897289828992900290129022903290429052906290761 unmodified lines29692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304321 unmodified lines306530663067306830693070307130723073307430753076307730783079308030813082179 unmodified lines32623263326432653266326714 unmodified lines3282328332843285328632877 unmodified lines3295329632973298329933003301330231 unmodified lines33343335333633373338333933401 unmodified line334233433344334533463347334837 unmodified linesslice_stl_to_tiffs,)from tiff_to_gcode import (RASTER_PATTERN_CHOICES,RASTER_PATTERN_SAME_DIRECTION,generate_snake_path_gcode,)9 unmodified linesSCALE_MODE_UNIFORM_FACTOR = "Keep Proportions"TARGET_DIMENSION_KEYS = ("target_x", "target_y", "target_z")FRONT_CAMERA = (90, 80, None)APP_CSS = """.gradio-container {font-size: 90%;39 unmodified linesopacity: 1 !important;}#load-sample-stls-button,#load-sample-stls-button button,#visualize-nozzle-spacing-button,1349 unmodified linesreturn offsets, spacingsdef _same_spacing_from_individual(use_individual_spacing: bool | None) -> bool:return not bool(use_individual_spacing)194 unmodified linesreturn spansdef split_tiff_stack_grid(state: ViewerState,base_name: str = "split_shape",columns: float = 2,rows: float = 1,progress: gr.Progress = gr.Progress(),) -> list[dict[str, Any]]:tiff_paths = [Path(path) for path in state.get("tiff_paths", [])]13 unmodified linesoutput_dir = Path(tempfile.mkdtemp(prefix=f"{safe_name}_split_"))x_spans = _partition_length(width, column_count)y_spans = _partition_length(height, row_count)pieces: list[dict[str, Any]] = []for row_index, (y_start, y_end) in enumerate(y_spans, start=1):for col_index, (x_start, x_end) in enumerate(x_spans, start=1):17 unmodified linesif layer.size != (width, height):raise ValueError("All TIFF slices must have the same dimensions to split the stack.")for piece in pieces:piece_image = layer.crop((piece["x_start"], piece["y_start"], piece["x_end"], piece["y_end"]))piece_path = piece["tiff_dir"] / f"slice_{index:04d}.tif"piece_image.save(piece_path, compression="tiff_deflate")piece["tiff_paths"].append(piece_path)6 unmodified linesbase_x_min = float(state.get("x_min", 0.0) or 0.0)base_y_min = float(state.get("y_min", 0.0) or 0.0)for piece in pieces:piece_width = piece["x_end"] - piece["x_start"]piece_height = piece["y_end"] - piece["y_start"]zip_path = output_dir / f"{safe_name}_r{piece['row']:02d}_c{piece['col']:02d}_tiff_slices.zip"_zip_tiff_paths(piece["tiff_paths"], zip_path)piece_state: ViewerState = {"tiff_paths": [str(path) for path in piece["tiff_paths"]],"z_values": z_values[: len(piece["tiff_paths"])],"pixel_size": pixel_size,"x_min": base_x_min + (piece["x_start"] * pixel_size),"y_min": base_y_min + ((height - piece["y_end"]) * pixel_size),"image_width": piece_width,"image_height": piece_height,"zip_path": str(zip_path),}piece["state"] = piece_statepiece["zip_path"] = zip_path145 unmodified linesreturn 0def _records_from_files(files: Any, previous_records: list[dict] | None = None) -> list[dict]:previous_by_path = {record.get("stl_path"): record for record in (previous_records or [])}records: list[dict] = []for index, path in enumerate(_uploaded_file_paths(files), start=1):previous = previous_by_path.get(path, {})name = previous.get("name") or Path(path).stem or f"Shape {index}"default_x, default_y, default_z = _default_target_extents_for_stl(path)records.append({"idx": index,"name": name,7 unmodified lines"last_scaled_axis": previous.get("last_scaled_axis", "target_x"),"pressure": previous.get("pressure", 25.0),"valve": previous.get("valve", 4),"nozzle": previous.get("nozzle", index),"port": previous.get("port", 1),"color": previous.get("color", _default_color(index)),"contour_tracing": previous.get("contour_tracing", False),189 unmodified lines)def _dropdown_update(records: list[dict], selected: str | None = None) -> dict[str, Any]:choices = [_shape_choice(record) for record in records]value = selected if selected in choices else (choices[0] if choices else None)21 unmodified linesreturn mergeddef sync_uploaded_shapes(files: Any,records: list[dict] | None,26 unmodified lines) -> tuple:records = _apply_shape_settings(records or [], settings_table)paths = [str(SAMPLE_STL_DIR / filename) for filename in SAMPLE_STL_FILENAMES if (SAMPLE_STL_DIR / filename).exists()]merged_paths = _merge_file_paths(files, paths)return (gr.update(value=merged_paths),*sync_uploaded_shapes(merged_paths, records, None, existing_spacing, use_individual_spacing),363 unmodified linesuse_individual_spacing: bool | None,columns: float,rows: float,starting_nozzle: float,starting_valve: float,progress: gr.Progress = gr.Progress(),30 unmodified linesbase_name=str(source.get("name") or f"shape_{source.get('idx', pos + 1)}"),columns=columns,rows=rows,progress=progress,)except Exception as exc:44 unmodified linesf"({max(1, _coerce_int(columns, 2))} columns x {max(1, _coerce_int(rows, 1))} rows). \n"f"Nozzles {first_nozzle}-{first_nozzle + len(pieces) - 1}; valves {first_valve}-{first_valve + len(pieces) - 1}.")return (next_records,_shape_settings_rows(next_records),132 unmodified linesreturn pairs[0][0], pairs[0][1], pairs[1][0], pairs[1][1], extradef render_dynamic_nozzle_spacing(records: list[dict] | None, use_individual_spacing: bool, spacing_table: Any) -> tuple[Any, str]:parts, _messages = _parts_from_records(records)if not parts:return None, "No shape G-code available. Generate G-code first."gap12x, gap12y, gap23x, gap23y, extra = _spacing_args_from_table(spacing_table, use_individual_spacing)offsets, spacings = _resolve_nozzle_layout(parts,_same_spacing_from_individual(use_individual_spacing),gap12x,gap12y,gap23x,gap23y,*extra,)return build_nozzle_spacing_figure(parts, offsets, spacings), _format_nozzle_spacing_status(parts, offsets, spacings)64 unmodified linestravel_opacity: float,filament_width: float,travel_width: float,use_individual_spacing: bool,spacing_table: Any,tube: bool = True,2 unmodified linesparts, messages = _parts_from_records(records)if not parts:return None, "No shape G-code available. Generate G-code on the TIFF Slices to GCode tab first."gap12x, gap12y, gap23x, gap23y, extra = _spacing_args_from_table(spacing_table, use_individual_spacing)offsets, spacings = _resolve_nozzle_layout(parts,_same_spacing_from_individual(use_individual_spacing),gap12x,gap12y,gap23x,gap23y,*extra,)figure = build_parallel_figure(parts,27 unmodified linesrecords: list[dict] | None,settings_table: Any,travel_opacity: float,use_individual_spacing: bool,spacing_table: Any,duration: float,6 unmodified linesparts, _messages = _parts_from_records(records)if not parts:return Nonegap12x, gap12y, gap23x, gap23y, extra = _spacing_args_from_table(spacing_table, use_individual_spacing)offsets, _spacings = _resolve_nozzle_layout(parts,_same_spacing_from_individual(use_individual_spacing),gap12x,gap12y,gap23x,gap23y,*extra,)def report(frame: int, total: int) -> None:61 unmodified linespixel_size = gr.Number(label="Pixel Size/Fill Width (mm)", value=0.8, minimum=0.0001, step=0.01)generate_button = gr.Button("Generate TIFF Stacks", variant="primary")with gr.Row():selected_shape = gr.Dropdown(label="Preview Shape", choices=[], value=None, allow_custom_value=False)refresh_preview_button = gr.Button("Regenerate Preview", variant="secondary", size="sm")with gr.Row():with gr.Column(scale=2, min_width=420):model_viewer = gr.Model3D(label="Selected 3D Viewer",display_mode="solid",clear_color=(0.94, 0.95, 0.97, 1.0),camera_position=FRONT_CAMERA,height=360,)with gr.Column(scale=1, min_width=300):model_details = gr.Markdown("No model loaded.")with gr.Row():with gr.Column(scale=2, min_width=420):slice_preview = gr.Image(label="Selected Slice Preview", type="pil", image_mode="RGB", height=320)with gr.Column(scale=1, min_width=300):slice_label = gr.Markdown("No slice stack loaded yet.")with gr.Row():prev_button = gr.Button("Prev", scale=1, min_width=90, size="sm")next_button = gr.Button("Next", scale=1, min_width=90, size="sm")slice_slider = gr.Slider(label="Slice Index", minimum=0, maximum=0, value=0, step=1, interactive=False)tiff_downloads = gr.File(label="Download TIFF ZIPs", file_count="multiple", interactive=False)slicer_status = gr.Markdown("")gr.Markdown("---")gr.Markdown("### Reference TIFF Stack")with gr.Row():with gr.Column(scale=1, min_width=200):ref_generate_button = gr.Button("Generate Reference TIFF Stack", variant="primary")with gr.Column(scale=3, min_width=250):ref_slice_label = gr.Markdown("No reference stack generated yet.")ref_slice_preview = gr.Image(label="Reference Slice Preview", type="pil", image_mode="RGB", height=270)with gr.Row():ref_prev_button = gr.Button("Prev", scale=1, min_width=90, size="sm")ref_next_button = gr.Button("Next", scale=1, min_width=90, size="sm")ref_slice_slider = gr.Slider(label="Slice Index", minimum=0, maximum=0, value=0, step=1, interactive=False)with gr.Tab("Single Shape Multi-Nozzle"):gr.Markdown("""# Single Shape Multi-NozzleSplit one generated TIFF stack into a row/column grid, then print each piece with a different nozzle.""")with gr.Row():split_source = gr.Dropdown(label="Source Shape", choices=[], value=None, allow_custom_value=False)split_refresh_sources = gr.Button("Refresh Source Shapes", variant="secondary", size="sm")with gr.Row():split_columns = gr.Number(label="Columns (X)", value=2, minimum=1, step=1)split_rows = gr.Number(label="Rows (Y)", value=1, minimum=1, step=1)split_start_nozzle = gr.Number(label="Starting Nozzle", value=1, minimum=1, step=1)split_start_valve = gr.Number(label="Starting Valve", value=4, minimum=1, step=1)split_button = gr.Button("Split Selected Shape into Grid Pieces", variant="primary")split_status = gr.Markdown("Generate a TIFF stack, then split it for multi-nozzle printing.")split_downloads = gr.File(label="Download Split TIFF ZIPs", file_count="multiple", interactive=False)with gr.Row():with gr.Column(scale=1, min_width=260):split_piece_source = gr.Dropdown(label="Preview Generated Piece", choices=[], value=None, allow_custom_value=False)with gr.Row():split_piece_prev = gr.Button("Prev", scale=1, min_width=90, size="sm")split_piece_next = gr.Button("Next", scale=1, min_width=90, size="sm")split_piece_slider = gr.Slider(label="Piece Slice Index", minimum=0, maximum=0, value=0, step=1, interactive=False)split_piece_label = gr.Markdown("No split stack generated yet.")with gr.Column(scale=2, min_width=420):split_piece_preview = gr.Image(label="Generated Piece Preview", type="pil", image_mode="RGB", height=330)with gr.Tab("TIFF Slices to GCode"):gr.Markdown(21 unmodified linesrefresh_gcode_text_button = gr.Button("Refresh G-Code Preview", variant="secondary", size="sm")gcode_text = gr.Code(label="Selected G-Code", language=None, lines=18, max_lines=18, interactive=False, elem_classes=["gcode-view"])with gr.Group():gr.Markdown("### Nozzle Spacing")nozzle_use_individual_spacing = gr.Checkbox(label="Advanced Settings", value=False)nozzle_spacing_table = gr.Dataframe(headers=NOZZLE_SPACING_HEADERS,value=[["Same spacing", "All neighboring nozzles", 5.0, 0.0]],row_count=(1, "fixed"),column_count=(len(NOZZLE_SPACING_HEADERS), "fixed"),interactive=True,label="Nozzle Spacing",elem_id="nozzle-spacing-table",)nozzle_preview_button = gr.Button("Visualize Nozzle Spacing", variant="secondary", elem_id="visualize-nozzle-spacing-button")with gr.Row():with gr.Column(scale=3, min_width=420):179 unmodified linesnozzle_use_individual_spacing,split_columns,split_rows,split_start_nozzle,split_start_valve,],14 unmodified linessplit_piece_preview,split_status,],)split_piece_source.change(fn=preview_selected_split_piece, inputs=[split_piece_states, split_piece_source], outputs=[split_piece_slider, split_piece_label, split_piece_preview], queue=False)split_piece_slider.release(fn=jump_to_selected_split_piece, inputs=[split_piece_states, split_piece_source, split_piece_slider], outputs=[split_piece_label, split_piece_preview], queue=False)7 unmodified lines)gcode_text_source.change(fn=load_selected_gcode_text, inputs=[shape_records, gcode_text_source], outputs=[gcode_text])refresh_gcode_text_button.click(fn=load_selected_gcode_text, inputs=[shape_records, gcode_text_source], outputs=[gcode_text])nozzle_use_individual_spacing.change(fn=update_nozzle_spacing_table_mode, inputs=[shape_records, nozzle_spacing_table, nozzle_use_individual_spacing], outputs=[nozzle_spacing_table], queue=False)nozzle_preview_button.click(fn=render_dynamic_nozzle_spacing, inputs=[shape_records, nozzle_use_individual_spacing, nozzle_spacing_table], outputs=[nozzle_spacing_plot, nozzle_spacing_status])gcode_source.change(fn=None,31 unmodified lineslayer_height.change(fn=sync_width_sliders, inputs=[layer_height], outputs=[print_width_slider, travel_width_slider], queue=False)parallel_render_inputs = [shape_records, shape_settings, pp_travel_opacity, pp_filament_width, pp_travel_width, nozzle_use_individual_spacing, nozzle_spacing_table]parallel_outputs = [parallel_plot, parallel_status, parallel_mode, parallel_anim_controls, pp_width_row, pp_export_group]parallel_line_button.click(fn=render_dynamic_parallel_lines, inputs=parallel_render_inputs, outputs=parallel_outputs)parallel_render_button.click(fn=render_dynamic_parallel_tubes, inputs=parallel_render_inputs, outputs=parallel_outputs)1 unmodified linepp_travel_width.release(fn=rerender_dynamic_parallel_current_mode, inputs=[parallel_mode] + parallel_render_inputs, outputs=[parallel_plot, parallel_status])pp_export_button.click(fn=export_dynamic_parallel_gif,inputs=[shape_records, shape_settings, pp_gif_travel_opacity, nozzle_use_individual_spacing, nozzle_spacing_table, pp_gif_duration, pp_gif_fps, pp_elev, pp_azim],outputs=[pp_gif_file],)37 unmodified lines383940414243449 unmodified lines5455565758596061626364656667686970717239 unmodified lines1121131141151161171181191201211221231241251261271281291349 unmodified lines1479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596194 unmodified lines1791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182513 unmodified lines183918401841184218431844184517 unmodified lines18631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618876 unmodified lines18941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919145 unmodified lines206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920907 unmodified lines2098209921002101210221032104189 unmodified lines22942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238621 unmodified lines240824092410241124122413241424152416241724182419242026 unmodified lines2447244824492450245124522453363 unmodified lines281728182819282028212822282330 unmodified lines285428552856285728582859286044 unmodified lines29052906290729082909291029112912132 unmodified lines304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307264 unmodified lines313731383139314031413142314331443145314631472 unmodified lines31503151315231533154315531563157315831593160316131623163316427 unmodified lines319231933194319531963197319831993200320132026 unmodified lines32093210321132123213321432153216321732183219322032213222322361 unmodified lines3285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335521 unmodified lines33773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411179 unmodified lines359135923593359435953596359714 unmodified lines36123613361436153616361736183619362036217 unmodified lines36293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366131 unmodified lines369336943695369636973698369937003701370237033704370537063707370837093710371137121 unmodified line371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537 unmodified linesslice_stl_to_tiffs,)from tiff_to_gcode import (RASTER_PATTERN_CHOICES,RASTER_PATTERN_SAME_DIRECTION,generate_snake_path_gcode,)9 unmodified linesSCALE_MODE_UNIFORM_FACTOR = "Keep Proportions"TARGET_DIMENSION_KEYS = ("target_x", "target_y", "target_z")FRONT_CAMERA = (90, 80, None)NOZZLE_LAYOUT_GRID = "Grid Layout"NOZZLE_LAYOUT_PAIR_TABLE = "Custom Spacing"NOZZLE_LAYOUT_PRESETS = ["Custom","One row","One column","2 x 1","1 x 2","2 x 2","3 x 3","2 x 5","5 x 2",]APP_CSS = """.gradio-container {font-size: 90%;39 unmodified linesopacity: 1 !important;}.settings-accordion summary,.settings-accordion button[aria-expanded],.settings-accordion .label-wrap span {font-size: 1.05rem !important;font-weight: 700 !important;}.settings-accordion summary {padding-top: 0.55rem !important;padding-bottom: 0.55rem !important;}#load-sample-stls-button,#load-sample-stls-button button,#visualize-nozzle-spacing-button,1349 unmodified linesreturn offsets, spacingsdef _group_parts_by_nozzle(parts: list[dict]) -> dict[int, list[dict]]:grouped: dict[int, list[dict]] = {}for part in parts:grouped.setdefault(_record_nozzle_number(part, int(part.get("idx", 1) or 1)), []).append(part)return groupeddef _nozzle_group_bounds(grouped: dict[int, list[dict]], nozzle: int) -> tuple[tuple[float, float, float], tuple[float, float, float]]:mins: list[tuple[float, float, float]] = []maxs: list[tuple[float, float, float]] = []for part in grouped[nozzle]:part_min, part_max = part["parsed"]["bounds"]mins.append(part_min)maxs.append(part_max)return (tuple(min(values) for values in zip(*mins)),tuple(max(values) for values in zip(*maxs)),)def _resolve_nozzle_grid_layout(parts: list[dict],columns: Any,rows: Any,column_spacing: Any,row_spacing: Any,) -> tuple[dict[int, tuple[float, float]], list[dict]]:offsets: dict[int, tuple[float, float]] = {}spacings: list[dict] = []if not parts:return offsets, spacingsgrouped = _group_parts_by_nozzle(parts)ordered_nozzles = sorted(grouped)column_count = max(1, _coerce_int(columns, 1))requested_rows = max(1, _coerce_int(rows, 1))row_count = max(requested_rows, math.ceil(len(ordered_nozzles) / column_count))try:x_gap = float(column_spacing)except (TypeError, ValueError):x_gap = 0.0try:y_gap = float(row_spacing)except (TypeError, ValueError):y_gap = 0.0placements = {nozzle: (index % column_count, index // column_count)for index, nozzle in enumerate(ordered_nozzles)}column_widths = [0.0 for _ in range(column_count)]row_heights = [0.0 for _ in range(row_count)]bounds_by_nozzle: dict[int, tuple[tuple[float, float, float], tuple[float, float, float]]] = {}for nozzle, (column, row) in placements.items():bounds = _nozzle_group_bounds(grouped, nozzle)bounds_by_nozzle[nozzle] = bounds(xmin, ymin, _), (xmax, ymax, _) = boundscolumn_widths[column] = max(column_widths[column], xmax - xmin)row_heights[row] = max(row_heights[row], ymax - ymin)column_positions: list[float] = []x_pos = 0.0for width in column_widths:column_positions.append(x_pos)x_pos += width + x_gaprow_positions: list[float] = []y_pos = 0.0for height in row_heights:row_positions.append(y_pos)y_pos += height + y_gapfor nozzle, (column, row) in placements.items():(xmin, ymin, _), _ = bounds_by_nozzle[nozzle]offsets[nozzle] = (column_positions[column] - xmin, row_positions[row] - ymin)for first, second in zip(ordered_nozzles, ordered_nozzles[1:]):first_x, first_y = offsets[first]second_x, second_y = offsets[second]spacings.append({"from": first,"to": second,"dx": second_x - first_x,"dy": second_y - first_y,})return offsets, spacingsdef _resolve_layout_from_spacing_controls(parts: list[dict],layout_mode: str | None,columns: Any,rows: Any,column_spacing: Any,row_spacing: Any,use_individual_spacing: bool,spacing_table: Any,) -> tuple[dict[int, tuple[float, float]], list[dict]]:if layout_mode != NOZZLE_LAYOUT_PAIR_TABLE:return _resolve_nozzle_grid_layout(parts, columns, rows, column_spacing, row_spacing)gap12x, gap12y, gap23x, gap23y, extra = _spacing_args_from_table(spacing_table, use_individual_spacing)return _resolve_nozzle_layout(parts,_same_spacing_from_individual(use_individual_spacing),gap12x,gap12y,gap23x,gap23y,*extra,)def _same_spacing_from_individual(use_individual_spacing: bool | None) -> bool:return not bool(use_individual_spacing)194 unmodified linesreturn spansdef _layer_split_spans(length: int, count: int, layer_index: int, overlap_pixels: int) -> list[tuple[int, int]]:base_spans = _partition_length(length, count)if overlap_pixels <= 0 or count <= 1:return base_spansboundaries = [base_spans[0][0], *[end for _start, end in base_spans]]adjusted = list(boundaries)for boundary_index in range(1, len(boundaries) - 1):direction = 1 if (layer_index + boundary_index) % 2 == 1 else -1lower = adjusted[boundary_index - 1] + 1upper = boundaries[boundary_index + 1] - 1adjusted[boundary_index] = max(lower, min(upper, boundaries[boundary_index] + direction * overlap_pixels))return [(adjusted[index], adjusted[index + 1]) for index in range(count)]def _overlap_canvas_span(start: int, end: int, length: int, position: int, count: int, overlap_pixels: int) -> tuple[int, int]:if overlap_pixels <= 0:return start, endcanvas_start = max(0, start - overlap_pixels) if position > 1 else startcanvas_end = min(length, end + overlap_pixels) if position < count else endreturn canvas_start, canvas_enddef split_tiff_stack_grid(state: ViewerState,base_name: str = "split_shape",columns: float = 2,rows: float = 1,overlapping_layers: bool | None = False,progress: gr.Progress = gr.Progress(),) -> list[dict[str, Any]]:tiff_paths = [Path(path) for path in state.get("tiff_paths", [])]13 unmodified linesoutput_dir = Path(tempfile.mkdtemp(prefix=f"{safe_name}_split_"))x_spans = _partition_length(width, column_count)y_spans = _partition_length(height, row_count)overlap_pixels = 1 if overlapping_layers else 0pieces: list[dict[str, Any]] = []for row_index, (y_start, y_end) in enumerate(y_spans, start=1):for col_index, (x_start, x_end) in enumerate(x_spans, start=1):17 unmodified linesif layer.size != (width, height):raise ValueError("All TIFF slices must have the same dimensions to split the stack.")layer_x_spans = _layer_split_spans(width, column_count, index, overlap_pixels)layer_y_spans = _layer_split_spans(height, row_count, index, overlap_pixels)for piece in pieces:canvas_x_start, canvas_x_end = _overlap_canvas_span(piece["x_start"], piece["x_end"], width, piece["col"], column_count, overlap_pixels)canvas_y_start, canvas_y_end = _overlap_canvas_span(piece["y_start"], piece["y_end"], height, piece["row"], row_count, overlap_pixels)x_start, x_end = layer_x_spans[piece["col"] - 1]y_start, y_end = layer_y_spans[piece["row"] - 1]if overlapping_layers:piece_image = Image.new("L", (canvas_x_end - canvas_x_start, canvas_y_end - canvas_y_start), 255)piece_image.paste(layer.crop((x_start, y_start, x_end, y_end)),(x_start - canvas_x_start, y_start - canvas_y_start),)else:piece_image = layer.crop((x_start, y_start, x_end, y_end))piece_path = piece["tiff_dir"] / f"slice_{index:04d}.tif"piece_image.save(piece_path, compression="tiff_deflate")piece["tiff_paths"].append(piece_path)6 unmodified linesbase_x_min = float(state.get("x_min", 0.0) or 0.0)base_y_min = float(state.get("y_min", 0.0) or 0.0)for piece in pieces:canvas_x_start, canvas_x_end = _overlap_canvas_span(piece["x_start"], piece["x_end"], width, piece["col"], column_count, overlap_pixels)canvas_y_start, canvas_y_end = _overlap_canvas_span(piece["y_start"], piece["y_end"], height, piece["row"], row_count, overlap_pixels)piece_width = canvas_x_end - canvas_x_start if overlapping_layers else piece["x_end"] - piece["x_start"]piece_height = canvas_y_end - canvas_y_start if overlapping_layers else piece["y_end"] - piece["y_start"]zip_path = output_dir / f"{safe_name}_r{piece['row']:02d}_c{piece['col']:02d}_tiff_slices.zip"_zip_tiff_paths(piece["tiff_paths"], zip_path)piece_state: ViewerState = {"tiff_paths": [str(path) for path in piece["tiff_paths"]],"z_values": z_values[: len(piece["tiff_paths"])],"pixel_size": pixel_size,"x_min": base_x_min + ((canvas_x_start if overlapping_layers else piece["x_start"]) * pixel_size),"y_min": base_y_min + ((height - (canvas_y_end if overlapping_layers else piece["y_end"])) * pixel_size),"image_width": piece_width,"image_height": piece_height,"zip_path": str(zip_path),"overlapping_layers": bool(overlapping_layers),}piece["state"] = piece_statepiece["zip_path"] = zip_path145 unmodified linesreturn 0def _next_unused_nozzle(used_nozzles: set[int]) -> int:nozzle = 1while nozzle in used_nozzles:nozzle += 1return nozzledef _records_from_files(files: Any, previous_records: list[dict] | None = None) -> list[dict]:previous_by_path: dict[str | None, list[dict]] = {}for record in previous_records or []:previous_by_path.setdefault(record.get("stl_path"), []).append(record)used_nozzles: set[int] = set()records: list[dict] = []for index, path in enumerate(_uploaded_file_paths(files), start=1):previous_queue = previous_by_path.get(path) or []previous = previous_queue.pop(0) if previous_queue else {}name = previous.get("name") or Path(path).stem or f"Shape {index}"default_x, default_y, default_z = _default_target_extents_for_stl(path)nozzle = _record_nozzle_number(previous, index) if previous else _next_unused_nozzle(used_nozzles)used_nozzles.add(nozzle)records.append({"idx": index,"name": name,7 unmodified lines"last_scaled_axis": previous.get("last_scaled_axis", "target_x"),"pressure": previous.get("pressure", 25.0),"valve": previous.get("valve", 4),"nozzle": nozzle,"port": previous.get("port", 1),"color": previous.get("color", _default_color(index)),"contour_tracing": previous.get("contour_tracing", False),189 unmodified lines)def _grid_spacing_rows(records: list[dict],columns: Any,rows: Any,column_spacing: Any,row_spacing: Any,) -> tuple[list[list[Any]], int, int]:ordered_nozzles = _ordered_nozzle_numbers(records)column_count = max(1, _coerce_int(columns, 2))row_count = max(1, _coerce_int(rows, 1))try:x_spacing = float(column_spacing)except (TypeError, ValueError):x_spacing = 5.0try:y_spacing = float(row_spacing)except (TypeError, ValueError):y_spacing = 5.0spacing_rows: list[list[Any]] = []for index, (first, second) in enumerate(zip(ordered_nozzles, ordered_nozzles[1:])):current_col = index % column_countnext_col = (index + 1) % column_countif next_col > current_col:gap_x = x_spacinggap_y = 0.0else:gap_x = -x_spacing * (column_count - 1)gap_y = y_spacingspacing_rows.append([_nozzle_spacing_label(first, records),_nozzle_spacing_label(second, records),gap_x,gap_y,])return spacing_rows, column_count, row_countdef apply_nozzle_grid_spacing(records: list[dict] | None,columns: Any,rows: Any,column_spacing: Any,row_spacing: Any,) -> tuple[dict[str, Any], dict[str, Any], str]:records = records or []spacing_rows, column_count, row_count = _grid_spacing_rows(records, columns, rows, column_spacing, row_spacing)nozzle_count = len(_ordered_nozzle_numbers(records))capacity = column_count * row_countstatus = f"Applied {column_count} x {row_count} grid spacing to {max(nozzle_count - 1, 0)} nozzle pair(s)."if nozzle_count > capacity:status += f" {nozzle_count} nozzles exceed {capacity} grid slots, so spacing continues row by row."return (gr.update(value=True),gr.update(headers=ADVANCED_NOZZLE_SPACING_HEADERS,value=spacing_rows,row_count=(len(spacing_rows), "fixed"),column_count=(len(ADVANCED_NOZZLE_SPACING_HEADERS), "fixed"),label="Advanced Nozzle Spacing",),status,)def update_nozzle_grid_preset(preset: str | None,records: list[dict] | None,columns: Any,rows: Any,) -> tuple[dict[str, Any], dict[str, Any]]:nozzle_count = max(1, len(_ordered_nozzle_numbers(records or [])))if preset == "One row":return gr.update(value=nozzle_count), gr.update(value=1)if preset == "One column":return gr.update(value=1), gr.update(value=nozzle_count)if preset and " x " in preset:left, right = preset.split(" x ", 1)return gr.update(value=max(1, _coerce_int(left, 1))), gr.update(value=max(1, _coerce_int(right, 1)))return gr.update(value=max(1, _coerce_int(columns, 1))), gr.update(value=max(1, _coerce_int(rows, 1)))def update_nozzle_spacing_mode(layout_mode: str | None) -> tuple[dict[str, Any], dict[str, Any]]:custom_selected = layout_mode == NOZZLE_LAYOUT_PAIR_TABLEreturn gr.update(visible=not custom_selected), gr.update(visible=custom_selected)def _dropdown_update(records: list[dict], selected: str | None = None) -> dict[str, Any]:choices = [_shape_choice(record) for record in records]value = selected if selected in choices else (choices[0] if choices else None)21 unmodified linesreturn mergeddef _append_file_paths(*file_groups: Any) -> list[str]:paths: list[str] = []for group in file_groups:paths.extend(_uploaded_file_paths(group))return pathsdef sync_uploaded_shapes(files: Any,records: list[dict] | None,26 unmodified lines) -> tuple:records = _apply_shape_settings(records or [], settings_table)paths = [str(SAMPLE_STL_DIR / filename) for filename in SAMPLE_STL_FILENAMES if (SAMPLE_STL_DIR / filename).exists()]merged_paths = _append_file_paths(files, paths)return (gr.update(value=merged_paths),*sync_uploaded_shapes(merged_paths, records, None, existing_spacing, use_individual_spacing),363 unmodified linesuse_individual_spacing: bool | None,columns: float,rows: float,overlapping_layers: bool,starting_nozzle: float,starting_valve: float,progress: gr.Progress = gr.Progress(),30 unmodified linesbase_name=str(source.get("name") or f"shape_{source.get('idx', pos + 1)}"),columns=columns,rows=rows,overlapping_layers=overlapping_layers,progress=progress,)except Exception as exc:44 unmodified linesf"({max(1, _coerce_int(columns, 2))} columns x {max(1, _coerce_int(rows, 1))} rows). \n"f"Nozzles {first_nozzle}-{first_nozzle + len(pieces) - 1}; valves {first_valve}-{first_valve + len(pieces) - 1}.")if overlapping_layers:status += " \nOverlapping Layers is enabled: split boundaries alternate by 1 pixel per layer with small blank margins for alignment."return (next_records,_shape_settings_rows(next_records),132 unmodified linesreturn pairs[0][0], pairs[0][1], pairs[1][0], pairs[1][1], extradef render_dynamic_nozzle_spacing(records: list[dict] | None,layout_mode: str | None,columns: Any,rows: Any,column_spacing: Any,row_spacing: Any,use_individual_spacing: bool,spacing_table: Any,) -> tuple[Any, str]:parts, _messages = _parts_from_records(records)if not parts:return None, "No shape G-code available. Generate G-code first."offsets, spacings = _resolve_layout_from_spacing_controls(parts,layout_mode,columns,rows,column_spacing,row_spacing,use_individual_spacing,spacing_table,)return build_nozzle_spacing_figure(parts, offsets, spacings), _format_nozzle_spacing_status(parts, offsets, spacings)64 unmodified linestravel_opacity: float,filament_width: float,travel_width: float,layout_mode: str | None,columns: Any,rows: Any,column_spacing: Any,row_spacing: Any,use_individual_spacing: bool,spacing_table: Any,tube: bool = True,2 unmodified linesparts, messages = _parts_from_records(records)if not parts:return None, "No shape G-code available. Generate G-code on the TIFF Slices to GCode tab first."offsets, spacings = _resolve_layout_from_spacing_controls(parts,layout_mode,columns,rows,column_spacing,row_spacing,use_individual_spacing,spacing_table,)figure = build_parallel_figure(parts,27 unmodified linesrecords: list[dict] | None,settings_table: Any,travel_opacity: float,layout_mode: str | None,columns: Any,rows: Any,column_spacing: Any,row_spacing: Any,use_individual_spacing: bool,spacing_table: Any,duration: float,6 unmodified linesparts, _messages = _parts_from_records(records)if not parts:return Noneoffsets, _spacings = _resolve_layout_from_spacing_controls(parts,layout_mode,columns,rows,column_spacing,row_spacing,use_individual_spacing,spacing_table,)def report(frame: int, total: int) -> None:61 unmodified linespixel_size = gr.Number(label="Pixel Size/Fill Width (mm)", value=0.8, minimum=0.0001, step=0.01)generate_button = gr.Button("Generate TIFF Stacks", variant="primary")with gr.Accordion("Multi-Nozzle Split", open=False, elem_classes=["settings-accordion"]):with gr.Row():split_source = gr.Dropdown(label="Source Shape", choices=[], value=None, allow_custom_value=False)split_refresh_sources = gr.Button("Refresh Source Shapes", variant="secondary", size="sm")with gr.Row():split_columns = gr.Number(label="Columns (X)", value=2, minimum=1, step=1)split_rows = gr.Number(label="Rows (Y)", value=1, minimum=1, step=1)split_start_nozzle = gr.Number(label="Starting Nozzle", value=1, minimum=1, step=1)split_start_valve = gr.Number(label="Starting Valve", value=4, minimum=1, step=1)split_overlapping_layers = gr.Checkbox(label="Overlapping Layers", value=False)split_button = gr.Button("Split Selected Shape into Grid Pieces", variant="primary")split_status = gr.Markdown("Generate a TIFF stack, then split it for multi-nozzle printing.")split_downloads = gr.File(label="Download Split TIFF ZIPs", file_count="multiple", interactive=False)with gr.Row():with gr.Column(scale=1, min_width=260):split_piece_source = gr.Dropdown(label="Preview Generated Piece", choices=[], value=None, allow_custom_value=False)with gr.Row():split_piece_prev = gr.Button("Prev", scale=1, min_width=90, size="sm")split_piece_next = gr.Button("Next", scale=1, min_width=90, size="sm")split_piece_slider = gr.Slider(label="Piece Slice Index", minimum=0, maximum=0, value=0, step=1, interactive=False)split_piece_label = gr.Markdown("No split stack generated yet.")with gr.Column(scale=2, min_width=420):split_piece_preview = gr.Image(label="Generated Piece Preview", type="pil", image_mode="RGB", height=330)with gr.Accordion("Selected Shape Preview", open=False, elem_classes=["settings-accordion"]):with gr.Row():selected_shape = gr.Dropdown(label="Preview Shape", choices=[], value=None, allow_custom_value=False)refresh_preview_button = gr.Button("Regenerate Preview", variant="secondary", size="sm")with gr.Row():with gr.Column(scale=2, min_width=420):model_viewer = gr.Model3D(label="Selected 3D Viewer",display_mode="solid",clear_color=(0.94, 0.95, 0.97, 1.0),camera_position=FRONT_CAMERA,height=360,)with gr.Column(scale=1, min_width=300):model_details = gr.Markdown("No model loaded.")with gr.Row():with gr.Column(scale=2, min_width=420):slice_preview = gr.Image(label="Selected Slice Preview", type="pil", image_mode="RGB", height=320)with gr.Column(scale=1, min_width=300):slice_label = gr.Markdown("No slice stack loaded yet.")with gr.Row():prev_button = gr.Button("Prev", scale=1, min_width=90, size="sm")next_button = gr.Button("Next", scale=1, min_width=90, size="sm")slice_slider = gr.Slider(label="Slice Index", minimum=0, maximum=0, value=0, step=1, interactive=False)tiff_downloads = gr.File(label="Download TIFF ZIPs", file_count="multiple", interactive=False)slicer_status = gr.Markdown("")with gr.Accordion("Reference TIFF Stack Preview", open=False, elem_classes=["settings-accordion"]):with gr.Row():with gr.Column(scale=1, min_width=200):ref_generate_button = gr.Button("Generate Reference TIFF Stack", variant="primary")with gr.Column(scale=3, min_width=250):ref_slice_label = gr.Markdown("No reference stack generated yet.")ref_slice_preview = gr.Image(label="Reference Slice Preview", type="pil", image_mode="RGB", height=270)with gr.Row():ref_prev_button = gr.Button("Prev", scale=1, min_width=90, size="sm")ref_next_button = gr.Button("Next", scale=1, min_width=90, size="sm")ref_slice_slider = gr.Slider(label="Slice Index", minimum=0, maximum=0, value=0, step=1, interactive=False)with gr.Tab("TIFF Slices to GCode"):gr.Markdown(21 unmodified linesrefresh_gcode_text_button = gr.Button("Refresh G-Code Preview", variant="secondary", size="sm")gcode_text = gr.Code(label="Selected G-Code", language=None, lines=18, max_lines=18, interactive=False, elem_classes=["gcode-view"])with gr.Accordion("Nozzle Spacing", open=False, elem_classes=["settings-accordion"]):nozzle_layout_mode = gr.Radio(label="Spacing Mode",choices=[NOZZLE_LAYOUT_GRID, NOZZLE_LAYOUT_PAIR_TABLE],value=NOZZLE_LAYOUT_GRID,)with gr.Group(visible=True) as nozzle_grid_group:with gr.Row():nozzle_grid_preset = gr.Dropdown(label="Common Layout",choices=NOZZLE_LAYOUT_PRESETS,value="Custom",allow_custom_value=False,)nozzle_grid_columns = gr.Number(label="Grid Columns", value=2, minimum=1, step=1)nozzle_grid_rows = gr.Number(label="Grid Rows", value=2, minimum=1, step=1)nozzle_grid_column_spacing = gr.Number(label="Column Gap (X, mm)", value=0.0, step=0.1)nozzle_grid_row_spacing = gr.Number(label="Row Gap (Y, mm)", value=0.0, step=0.1)with gr.Group(visible=False) as nozzle_custom_group:nozzle_use_individual_spacing = gr.Checkbox(label="Use Different Values for Each Nozzle Connection", value=False)nozzle_spacing_table = gr.Dataframe(headers=NOZZLE_SPACING_HEADERS,value=[["Same spacing", "All neighboring nozzles", 5.0, 0.0]],row_count=(1, "fixed"),column_count=(len(NOZZLE_SPACING_HEADERS), "fixed"),interactive=True,label="Custom Spacing",elem_id="nozzle-spacing-table",)nozzle_preview_button = gr.Button("Visualize Nozzle Spacing", variant="secondary", elem_id="visualize-nozzle-spacing-button")with gr.Row():with gr.Column(scale=3, min_width=420):179 unmodified linesnozzle_use_individual_spacing,split_columns,split_rows,split_overlapping_layers,split_start_nozzle,split_start_valve,],14 unmodified linessplit_piece_preview,split_status,],).then(fn=generate_dynamic_reference_stack,inputs=[shape_records],outputs=[ref_state, ref_slice_slider, ref_slice_label, ref_slice_preview],)split_piece_source.change(fn=preview_selected_split_piece, inputs=[split_piece_states, split_piece_source], outputs=[split_piece_slider, split_piece_label, split_piece_preview], queue=False)split_piece_slider.release(fn=jump_to_selected_split_piece, inputs=[split_piece_states, split_piece_source, split_piece_slider], outputs=[split_piece_label, split_piece_preview], queue=False)7 unmodified lines)gcode_text_source.change(fn=load_selected_gcode_text, inputs=[shape_records, gcode_text_source], outputs=[gcode_text])refresh_gcode_text_button.click(fn=load_selected_gcode_text, inputs=[shape_records, gcode_text_source], outputs=[gcode_text])nozzle_layout_mode.change(fn=update_nozzle_spacing_mode,inputs=[nozzle_layout_mode],outputs=[nozzle_grid_group, nozzle_custom_group],queue=False,)nozzle_grid_preset.change(fn=update_nozzle_grid_preset,inputs=[nozzle_grid_preset, shape_records, nozzle_grid_columns, nozzle_grid_rows],outputs=[nozzle_grid_columns, nozzle_grid_rows],queue=False,)nozzle_use_individual_spacing.change(fn=update_nozzle_spacing_table_mode, inputs=[shape_records, nozzle_spacing_table, nozzle_use_individual_spacing], outputs=[nozzle_spacing_table], queue=False)nozzle_preview_button.click(fn=render_dynamic_nozzle_spacing,inputs=[shape_records,nozzle_layout_mode,nozzle_grid_columns,nozzle_grid_rows,nozzle_grid_column_spacing,nozzle_grid_row_spacing,nozzle_use_individual_spacing,nozzle_spacing_table,],outputs=[nozzle_spacing_plot, nozzle_spacing_status],)gcode_source.change(fn=None,31 unmodified lineslayer_height.change(fn=sync_width_sliders, inputs=[layer_height], outputs=[print_width_slider, travel_width_slider], queue=False)parallel_render_inputs = [shape_records,shape_settings,pp_travel_opacity,pp_filament_width,pp_travel_width,nozzle_layout_mode,nozzle_grid_columns,nozzle_grid_rows,nozzle_grid_column_spacing,nozzle_grid_row_spacing,nozzle_use_individual_spacing,nozzle_spacing_table,]parallel_outputs = [parallel_plot, parallel_status, parallel_mode, parallel_anim_controls, pp_width_row, pp_export_group]parallel_line_button.click(fn=render_dynamic_parallel_lines, inputs=parallel_render_inputs, outputs=parallel_outputs)parallel_render_button.click(fn=render_dynamic_parallel_tubes, inputs=parallel_render_inputs, outputs=parallel_outputs)1 unmodified linepp_travel_width.release(fn=rerender_dynamic_parallel_current_mode, inputs=[parallel_mode] + parallel_render_inputs, outputs=[parallel_plot, parallel_status])pp_export_button.click(fn=export_dynamic_parallel_gif,inputs=[shape_records,shape_settings,pp_gif_travel_opacity,nozzle_layout_mode,nozzle_grid_columns,nozzle_grid_rows,nozzle_grid_column_spacing,nozzle_grid_row_spacing,nozzle_use_individual_spacing,nozzle_spacing_table,pp_gif_duration,pp_gif_fps,pp_elev,pp_azim,],outputs=[pp_gif_file],)
137 unmodified lines138139140137 unmodified linesfor piece, expected_pixels in zip(pieces, expected):with Image.open(piece["state"]["tiff_paths"][0]) as image:np.testing.assert_array_equal(np.asarray(image), expected_pixels)137 unmodified lines138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179137 unmodified linesfor piece, expected_pixels in zip(pieces, expected):with Image.open(piece["state"]["tiff_paths"][0]) as image:np.testing.assert_array_equal(np.asarray(image), expected_pixels)def test_split_tiff_stack_grid_overlapping_layers_keep_small_alignment_margin(tmp_path) -> None:layer0 = np.zeros((2, 6), dtype=np.uint8)layer1 = np.zeros((2, 6), dtype=np.uint8)layer0_path = tmp_path / "slice_0000.tif"layer1_path = tmp_path / "slice_0001.tif"Image.fromarray(layer0, mode="L").save(layer0_path)Image.fromarray(layer1, mode="L").save(layer1_path)state = {"tiff_paths": [str(layer0_path), str(layer1_path)],"z_values": [0.0, 1.0],"pixel_size": 0.5,"x_min": 10.0,"y_min": -2.0,"image_width": 6,"image_height": 2,}left, right = split_tiff_stack_grid(state, "overlap-part", columns=2, rows=1, overlapping_layers=True)assert left["state"]["image_width"] == 4assert right["state"]["image_width"] == 4assert left["state"]["x_min"] == 10.0assert right["state"]["x_min"] == 11.0with Image.open(left["state"]["tiff_paths"][0]) as left_layer0:expected = np.zeros((2, 4), dtype=np.uint8)np.testing.assert_array_equal(np.asarray(left_layer0), expected)with Image.open(right["state"]["tiff_paths"][0]) as right_layer0:expected = np.full((2, 4), 255, dtype=np.uint8)expected[:, 2:] = 0np.testing.assert_array_equal(np.asarray(right_layer0), expected)with Image.open(left["state"]["tiff_paths"][1]) as left_layer1:expected = np.full((2, 4), 255, dtype=np.uint8)expected[:, :2] = 0np.testing.assert_array_equal(np.asarray(left_layer1), expected)with Image.open(right["state"]["tiff_paths"][1]) as right_layer1:expected = np.zeros((2, 4), dtype=np.uint8)np.testing.assert_array_equal(np.asarray(right_layer1), expected)
9 unmodified lines10111213141516171819225 unmodified lines24524624724824925042 unmodified lines2932942952962972989 unmodified lines_apply_shape_settings,delete_shape_from_settings,_format_nozzle_spacing_status,_shape_settings_rows,_spacing_args_from_table,_spacing_table_update,normalize_shape_dimensions_for_mode,_resolve_nozzle_layout,)225 unmodified linesassert updated[0]["contour_tracing"] is Truedef test_simple_spacing_table_uses_one_shared_spacing_row() -> None:records = [{"idx": 1, "name": "first"},42 unmodified linesassert update["value"] == [["Nozzle 1: Shape 1, Shape 2", "Nozzle 2: Shape 3", 9.0, 2.5]]def test_delete_shape_reindexes_without_losing_shape_data() -> None:class Event:index = (1, len(SHAPE_SETTINGS_HEADERS) - 1)9 unmodified lines10111213141516171819202122225 unmodified lines24824925025125225325425525625725825926026126226326426526626726826927027127227342 unmodified lines3163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603619 unmodified lines_apply_shape_settings,delete_shape_from_settings,_format_nozzle_spacing_status,_grid_spacing_rows,_records_from_files,_shape_settings_rows,_spacing_args_from_table,_spacing_table_update,normalize_shape_dimensions_for_mode,_resolve_nozzle_grid_layout,_resolve_nozzle_layout,)225 unmodified linesassert updated[0]["contour_tracing"] is Truedef test_repeated_sample_path_gets_next_unused_nozzle() -> None:records = _records_from_files(["sample.stl", "sample.stl"],previous_records=[{"idx": 1, "name": "sample", "stl_path": "sample.stl", "nozzle": 1}],)assert [record["nozzle"] for record in records] == [1, 2]def test_sample_reload_appends_next_nozzle_set() -> None:sample_paths = ["sample_a.stl", "sample_b.stl", "sample_c.stl"]first_load = _records_from_files(sample_paths)first_resync = _records_from_files(sample_paths, first_load)second_load = _records_from_files([*sample_paths, *sample_paths], first_load)assert [record["nozzle"] for record in first_load] == [1, 2, 3]assert [record["nozzle"] for record in first_resync] == [1, 2, 3]assert [record["nozzle"] for record in second_load] == [1, 2, 3, 4, 5, 6]def test_simple_spacing_table_uses_one_shared_spacing_row() -> None:records = [{"idx": 1, "name": "first"},42 unmodified linesassert update["value"] == [["Nozzle 1: Shape 1, Shape 2", "Nozzle 2: Shape 3", 9.0, 2.5]]def test_grid_spacing_rows_follow_row_major_pattern() -> None:records = [{"idx": 1, "name": "first", "nozzle": 1},{"idx": 2, "name": "second", "nozzle": 2},{"idx": 3, "name": "third", "nozzle": 3},{"idx": 4, "name": "fourth", "nozzle": 4},]rows, column_count, row_count = _grid_spacing_rows(records, columns=2, rows=2, column_spacing=10.0, row_spacing=3.0)assert column_count == 2assert row_count == 2assert rows == [["Nozzle 1: Shape 1", "Nozzle 2: Shape 2", 10.0, 0.0],["Nozzle 2: Shape 2", "Nozzle 3: Shape 3", -10.0, 3.0],["Nozzle 3: Shape 3", "Nozzle 4: Shape 4", 10.0, 0.0],]def test_nozzle_grid_layout_places_nozzles_by_rows_and_columns() -> None:parts = [_part(1, ((0.0, 0.0, 0.0), (10.0, 20.0, 1.0))),_part(2, ((0.0, 0.0, 0.0), (10.0, 20.0, 1.0))),_part(3, ((0.0, 0.0, 0.0), (10.0, 20.0, 1.0))),_part(4, ((0.0, 0.0, 0.0), (10.0, 20.0, 1.0))),]offsets, spacings = _resolve_nozzle_grid_layout(parts, columns=2, rows=2, column_spacing=2.0, row_spacing=3.0)np.testing.assert_allclose(offsets[1], (0.0, 0.0))np.testing.assert_allclose(offsets[2], (12.0, 0.0))np.testing.assert_allclose(offsets[3], (0.0, 23.0))np.testing.assert_allclose(offsets[4], (12.0, 23.0))assert spacings == [{"from": 1, "to": 2, "dx": 12.0, "dy": 0.0},{"from": 2, "to": 3, "dx": -12.0, "dy": 23.0},{"from": 3, "to": 4, "dx": 12.0, "dy": 0.0},]def test_delete_shape_reindexes_without_losing_shape_data() -> None:class Event:index = (1, len(SHAPE_SETTINGS_HEADERS) - 1)
README.md+3-2
app.py+502-115
tests/test_app_scaling.py+39
tests/test_nozzle_spacing.py+63