Skip to content

Instantly share code, notes, and snippets.

@luisdamed
Last active April 10, 2023 14:54
Show Gist options
  • Save luisdamed/db8615e3746607b556ccc8195e92ee87 to your computer and use it in GitHub Desktop.
Save luisdamed/db8615e3746607b556ccc8195e92ee87 to your computer and use it in GitHub Desktop.
Python script to get the maximum dimensions of a gcode file for 3D printing. Works for gcode created from PrusaSlicer, with verbose enabled
# %% Import libraries
import os
import tkinter as tk
from tkinter import filedialog
import re
class App(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.master = master
self.create_widgets()
def create_widgets(self):
self.label = tk.Label(self.master, text="Select GCODE file to analyze")
self.label.pack()
self.file_list = tk.Listbox(self.master, selectmode=tk.MULTIPLE)
self.file_list.pack()
self.select_button = tk.Button(self.master, text="Select files", command=self.select_files)
self.select_button.pack()
self.analyze_button = tk.Button(self.master, text="Analyze dimensions", command=self.analyze_dimensions)
self.analyze_button.pack()
def select_files(self):
filetypes = [('GCODE files', '*.gco;*.gcode;*.txt')]
files = filedialog.askopenfilenames(filetypes=filetypes)
for file in files:
self.file_list.insert(tk.END, file)
def get_max_size( self, lines):
x_coords = []
y_coords = []
z_coords = []
n_widths = 0
avg_width = 0
for line in lines:
if ((line.endswith('perimeter\n')
or
line.endswith('layer Z\n'))
and
line.startswith('G1')):
try:
x_coords.append(float(
''.join(re.findall('X' + '(\d*.\d*)', line))
))
y_coords.append(float(
''.join(re.findall('Y' + '(\d*.\d*)', line))
))
except:
z_coords.append(float(
''.join(re.findall('Z' + '(\d*.\d*)', line))
))
if line.startswith(';WIDTH:'):
n_widths += 1
value = float(
''.join(re.findall(';WIDTH:(\d*.\d*)', line))
)
avg_width += (value - avg_width)/n_widths
x_max = max(x_coords) - min(x_coords) + avg_width
y_max = max(y_coords) - min(y_coords) + avg_width
z_coords.sort()
z_max = z_coords[-1]
return f'Max. X dimension is {x_max:.1f} mm\n'\
f'Max. Y dimension is {y_max:.1f} mm\n'\
f'Max. Z dimension is {z_max:.1f} mm\n'\
def analyze_dimensions(self):
for file in self.file_list.get(0, tk.END):
input_file = os.path.abspath(file)
filename = os.path.splitext(os.path.basename(file))[0]
with open(input_file) as f:
lines = f.readlines()
print(f'File: {filename}:')
print(self.get_max_size(lines))
self.file_list.delete(tk.ANCHOR)
if __name__ == '__main__':
root = tk.Tk()
app = App(root)
app.pack()
root.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment