Analyse FDM G-code files without a printer: filament, layers, time and cost, from the command line or from Python.
When you run a few printers for batch production, the questions before a job are always the same:
how much filament does this plate use, how long does each layer take, what does one part cost, and
what changed between two slicings of the same model. The slicer knows some of this, but only inside
its GUI, only for its own files and without a cost model. gcode-insight reads the G-code itself, so
it works on files from Bambu Studio, OrcaSlicer, PrusaSlicer or anything Marlin-flavoured, in scripts
and in CI, with no printer and no slicer installed.
- Streaming parser for
G0/G1moves,G2/G3arcs (I/JandRforms),G90/G91,M82/M83,G92,G28,G4,G20/G21, tool changes,M104/M109/M140/M190temperatures andM106/M107fan commands. Files are read line by line; memory use does not grow with file size. - Slicer metadata from header/footer comments: slicer name and version, estimated time, filament used, layer height, nozzle diameter, filament type/density/diameter/colour and the printer model the file was sliced for. Understands the Bambu Studio, OrcaSlicer, PrusaSlicer/SuperSlicer and Cura comment styles and returns empty fields when they are absent.
- Geometry and statistics: layers (from
;LAYER_CHANGE/; CHANGE_LAYER/;LAYER:nmarkers, or from Z changes when there are none), per-layer filament, extrusion path, travel path and time, bounding box of extruded moves, retraction count, filament length -> volume -> mass, per-tool usage. - Time estimate from a documented trapezoidal motion model with per-axis speed and acceleration limits, compared against the slicer's own estimate when the file has one.
- Cost model: filament price, machine hourly rate, electricity, failure allowance, markup, fixed setup cost, and batch totals for N copies.
- Output as a terminal summary, JSON (
--json, written to a file with--out FILE), or a single self-contained HTML report with inline SVG charts (no scripts, no external assets). - Reads plain
.gcodeand Bambu/Orca.gcode.3mfarchives (--plate N). - No runtime dependencies outside the Python standard library.
Requires Python 3.10 or newer. The package is not on PyPI; install from GitHub:
pip install git+https://github.com/projectbin07-stack/gcode-insight.gitor from a clone:
git clone https://github.com/projectbin07-stack/gcode-insight.git
cd gcode-insight
pip install .The outputs below are real, produced from the fixtures in tests/fixtures/. Those fixtures are small
synthetic files written for this project; the slicer time figures inside them are placeholders, so
the "Model vs slicer" line here demonstrates the feature and says nothing about accuracy.
$ gcode-insight analyze tests/fixtures/bambu_cube.gcode
G-code analysis: bambu_cube.gcode
File
Slicer BambuStudio 01.10.01.50
Sliced for Bambu Lab P1S
Lines 350
Layers 5 (detected from slicer markers)
Layer height 0.2 mm
Nozzle 0.4 mm
Bounding box 119.79 x 136.79 x 0.80 mm (X 18.00..137.79, Y 1.00..137.79, Z 0.20..1.00)
Nozzle temp (max) 245 C
Bed temp (max) 55 C
Fan (max) P1: 100%, P2: 70%
Filament
Filament length 72.62 mm (0.073 m)
Volume 0.175 cm^3
Mass 0.22 g
T0 PLA #FFFFFF 47.16 mm, 0.14 g (density 1.24 g/cm^3)
T1 PETG #161616 25.46 mm, 0.08 g (density 1.27 g/cm^3)
Slicer says 72.62 mm
Slicer mass 0.22 g
Motion
Extrusion path 1596.4 mm
Travel path 270.0 mm
Retractions 17
Tool changes 1
Time (trapezoidal model; excludes heating, homing, levelling, filament changes)
Model estimate 22.4s
Slicer (model printing time) 27.0s
Model vs slicer -5 s (-17.2%)
Layers
layer Z filament mm extrude mm travel mm time
1 0.20 10.73 307.3 129.0 6.9s
2 0.40 10.73 307.3 28.5 2.9s
3 0.60 14.73 307.3 31.5 4.0s
4 0.80 10.73 307.3 30.3 3.1s
5 1.00 10.73 307.3 32.5 3.2sThe bounding box includes the nozzle load line at the front of the bed, because it is an extruding
move. Add --json for machine-readable output or --html report.html for the report.
To save the JSON for another tool (for example printfarm-planner), use --out rather than a shell
redirect. Windows PowerShell 5.1's > re-encodes the output as UTF-16, or as UTF-8 with a byte-order
mark when Out-File is set to utf8, and strict JSON readers reject both. --out always writes
UTF-8 without a BOM:
gcode-insight analyze part.gcode --json --out part.jsonThe JSON carries "schema_version": 4. Version 2 (0.2.0) added metadata.filament_colour,
metadata.printer_model and tools[].colour. Version 3 (0.3.0) added
metadata.estimated_time_source, the comment the slicer's total came from. Version 4 (0.4.0)
added the timeline fields described under Timeline. 0.1.0
output has no schema_version and lacks those fields. Every version only added fields; nothing
was removed or renamed.
For Cura files the slicer's figure is read from ;PRINT.TIME: (Griffin flavour, Ultimaker
printers) or ;TIME: (Marlin and other flavours). It is shown next to the model estimate and
labelled with its source, for example Slicer (Cura ;PRINT.TIME) 1m 35s.
$ gcode-insight cost tests/fixtures/bambu_cube.gcode --filament-price 22 --machine-rate 1.5 \
--power 110 --kwh-price 0.30 --failure-rate 5 --margin 40 --copies 20 --setup-cost 2 --currency '$'
Cost estimate: bambu_cube.gcode
Basis (one copy)
Filament mass 0.22 g
Print time 6m 33s (slicer estimate)
Per copy
Filament $0.00
Machine time $0.16
Electricity $0.00
Failure allowance $0.01
Setup share $0.10
Unit cost $0.28
Suggested price $0.39
Batch of 20
Filament mass 4.4 g
Machine time 2h 11m 00s
Batch cost $5.62
Batch price $7.87The formulas:
filament = mass_g / 1000 * filament_price
machine = hours * machine_rate
electricity = power_watts / 1000 * hours * kwh_price
run_cost = filament + machine + electricity
failure = run_cost * f / (1 - f) f = failure rate
unit_cost = run_cost + failure + setup_cost / copies
unit_price = unit_cost * (1 + margin)
--margin is a markup on cost, not a share of the selling price. --failure-rate and --margin
are given in percent. Batch figures assume N separate runs of the same file. By default the cost
uses the slicer's total time estimate when the file has one (--time-source auto), because that
includes the start-up sequence; --time-source model uses this tool's motion estimate instead.
$ gcode-insight compare tests/fixtures/orca_cube.gcode tests/fixtures/prusa_cube.gcode
A: orca_cube.gcode B: prusa_cube.gcode B - A
Slicer OrcaSlicer PrusaSlicer
Layers 5 6 +1
Filament 58.5 mm 70.2 mm +11.7 mm (+20.0%)
Mass 0.15 g 0.21 g +0.07 g (+46.5%)
Model time 29.2s 58.1s +29 s (+98.9%)
Extrusion path 1564.0 mm 1876.8 mm +312.8 mm (+20.0%)
Travel path 259.1 mm 303.9 mm +44.8 mm (+17.3%)
Retractions 15 18 +3
Max Z 1.00 mm 1.20 mm +0.20 mm (+20.0%)from gcode_insight import AnalysisOptions, CostInputs, analyze_file, compute_cost
analysis = analyze_file("plate_1.gcode", AnalysisOptions(material="PETG"))
print(analysis.layer_count, analysis.filament_mm, analysis.mass_g, analysis.estimated_time_s)
for layer in analysis.layers:
print(layer.index, layer.z, layer.filament_mm, layer.time_s)
cost = compute_cost(
analysis.mass_g,
analysis.estimated_time_s,
CostInputs(filament_price_per_kg=22.0, machine_rate_per_hour=1.5, copies=20),
)
print(cost.unit_cost, cost.batch_price)The shared registry of Bambu Lab printers and base materials is part of the public API:
from gcode_insight import load_registry
p1s = load_registry().printer("P1S")
print(p1s.build_volume_mm, p1s.ams_max_slots, p1s.connection.slicer_model_id.value)
# (256.0, 256.0, 256.0) 16 C12Each printer has its manufacturer sources, and since 0.4.0 (registry schema 2) connection
facts such as the camera port, each marked as official or community-sourced. Facts no source
settles are None. See docs/registry.md for the API and the data.
Each layer (and the start-up section) carries start_s and end_s, the model time from the
start of the file at which it begins and ends. They are the running sum of time_s, starting
with the start-up section at 0, so the last layer ends at estimated_time_s. Each layer also
splits its filament by tool in filament_mm_by_tool, and tool_change_events lists every tool
change with the layer it happened in and its time. From the synthetic two-filament fixture
tests/fixtures/bambu_cube.gcode (values rounded here; the JSON has full precision):
layer start_s end_s filament_mm_by_tool
0 0.00 2.16 {"0": 14.97} (start-up: purge line)
1 2.16 9.08 {"0": 10.73}
2 9.08 12.02 {"0": 10.73}
3 12.02 16.01 {"0": 10.73, "1": 4.00}
4 16.01 19.13 {"1": 10.73}
5 19.13 22.36 {"1": 10.73}
tool_change_events: [{"from_tool": 0, "to_tool": 1, "layer": 3, "time_s": 15.14, "line": 221}]
estimated_time_s: 22.36
analysis = analyze_file("plate_1.gcode.3mf")
for layer in analysis.layers:
print(layer.index, layer.start_s, layer.end_s, layer.filament_mm_by_tool)
for change in analysis.tool_change_events:
print(
f"T{change.from_tool} -> T{change.to_tool} in layer {change.layer} at {change.time_s:.0f} s"
)The times are this tool's motion model, so they inherit its limits (see "Accuracy limits"
below); scale them by a measured factor per printer if you need wall-clock times. Filament is
attributed to the tool that was active when it was pushed, including purge and flush moves,
because that filament really leaves the spool. A tool change commanded just before the first
move of a new layer counts towards the layer that is still open (without slicer layer markers,
a layer opens at its first extruding move). from_tool of the first change is 0, because the
analyser starts with tool 0 selected.
$ gcode-insight --help
usage: gcode-insight [-h] [--version] COMMAND ...
Analyse FDM G-code files without a printer: filament, time, layers, cost.
positional arguments:
COMMAND
analyze print statistics for one file
cost estimate cost and price
compare compare two files
options:
-h, --help show this help message and exit
--version show program's version number and exit$ gcode-insight analyze --help
usage: gcode-insight analyze [-h] [--json] [--html OUT] [--all-layers]
[-o FILE] [--filament-diameter MM]
[--material NAME] [--density G_CM3] [--plate N]
[--accel MM_S2] [--travel-accel MM_S2]
[--max-feedrate X Y Z E] [--max-accel X Y Z E]
[--jerk MM_S] [--ignore-gcode-limits]
file
Analyse one G-code file.
positional arguments:
file G-code file (.gcode or .gcode.3mf)
options:
-h, --help show this help message and exit
--json print JSON instead of text
--html OUT also write an HTML report
--all-layers list every layer in the text summary
-o, --out FILE write the output (text or --json) to FILE as UTF-8
without a BOM instead of printing it; use this rather
than '>' in PowerShell
filament:
--filament-diameter MM
filament diameter (default: slicer metadata, else
1.75)
--material NAME material for the density table: PLA, PETG, ABS, ASA,
TPU
--density G_CM3 filament density in g/cm^3 (overrides --material and
metadata)
--plate N plate number inside a .gcode.3mf archive (default:
lowest)
time model:
--accel MM_S2 acceleration for extruding moves (default 3000)
--travel-accel MM_S2 acceleration for travel moves (default 3000)
--max-feedrate X Y Z E
maximum speed per axis in mm/s (default 500 500 20 80)
--max-accel X Y Z E maximum acceleration per axis in mm/s^2 (default 10000
10000 500 5000)
--jerk MM_S junction speed step (default 8)
--ignore-gcode-limits
do not apply M201/M203/M204/M220 from the file; use
only the values abovecost takes the same filament and time-model options plus --filament-price (required),
--machine-rate, --power, --kwh-price, --failure-rate, --margin, --setup-cost, --copies,
--time-source {auto,model,slicer}, --currency, --json, --html and --out. compare A B takes
the filament and time-model options, --json and --out. Exit status is 0 on success and 2 on a usage or input
error.
reader.py lines from .gcode or a plate inside .gcode.3mf
|
parser.py text line -> Command(code, params, flags, comment)
|
analysis.py Analyzer: modal state machine (position, E mode, tool, limits)
| |- metadata.py comments -> SlicerMetadata
| |- timing.py Planner: look-ahead trapezoid timing per move
| `- materials.py length -> volume -> mass
v
Analysis totals + one LayerStats per layer
|
|- report.py terminal text / compare table
|- html_report.py self-contained HTML with inline SVG
`- cost.py CostInputs -> CostBreakdown
cli.py argparse front end for the above
Some decisions worth knowing about:
- Filament accounting. The extruder is tracked as one E axis with a high-water mark. Only material pushed beyond the furthest point reached so far counts as used, so a retract/unretract pair adds nothing and a final retraction does not reduce the total. Filament is attributed to the tool that was active when it was pushed.
- Mass. Density is taken, in order, from
--density,--material, the slicer'sfilament_density, the slicer'sfilament_typelooked up in the built-in table (PLA 1.24, PETG 1.27, ABS 1.04, ASA 1.07, TPU 1.21 g/cm^3), and finally PLA with a warning. Trade names resolve to their base polymer through the aliases in the shared printer and material registry (PLA Silk,Silk PLA,PETG HF,PLA-CF), then by leading letters. The densities are generic values, not datasheet figures. The registry is vendored into printfarm-planner, print-forge and stl-doctor; see docs/registry.md. - Layers. If the file contains slicer layer markers they define the layers, and everything before the first marker (start G-code, purge line) is reported separately as start-up. Otherwise a new layer starts at each extruding move whose Z differs from the current layer's Z; non-extruding Z-hops do not start layers.
- Relative/absolute E follows Marlin 2:
G90/G91also switch the extruder untilM82orM83is seen, after which the extruder mode is fixed by those commands only.
Each move is a block with a path length, a nominal speed and an acceleration.
- Nominal speed is the commanded feedrate (
F, scaled byM220), reduced so that no axis exceeds its maximum speed. - Acceleration is the print acceleration for extruding moves and the travel acceleration otherwise, reduced so that no axis exceeds its maximum acceleration. Extruder-only moves use the E limits.
- Speed over a block is a trapezoid: accelerate, cruise, decelerate (a triangle if the block is too short to reach nominal speed).
- Junctions use one "junction speed step"
jerk(default 8 mm/s): the junction speed is the slower of the two nominal speeds, lowered tojerk / |u2 - u1|if the change in the velocity vector would exceedjerk(u1,u2are the unit directions). Collinear moves pass at full speed, a right angle atjerk / 1.41, a reversal atjerk / 2. Extruder-only moves start and end at rest. - A backward and a forward pass over a sliding window of at least 64 blocks keep entry and exit speeds reachable.
- Arcs are single blocks with the true arc length, tangent directions at both ends and a
centripetal limit
v <= sqrt(a * r). M201,M203,M204(S/P/T) andM220in the file update the limits as they are encountered;--ignore-gcode-limitsdisables that.G4dwell time is added as written.
This model has not been validated against real print durations, and no accuracy figure is claimed. Expect it to differ from a stopwatch and from your slicer, in particular because:
- Heating, homing, bed levelling, calibration, filament loading and AMS/MMU filament changes take real time and are not in the G-code as moves. They are not estimated. On short prints they dominate.
- Real firmware differs: Bambu printers run proprietary motion control; Klipper uses square-corner-velocity junctions and input shaping; Marlin may use junction deviation and S-curve acceleration. Corner speeds here follow the single simple rule described above.
- Pressure/linear advance, firmware-side speed or flow overrides, and limits set outside the file
(EEPROM, printer config, Klipper
SET_VELOCITY_LIMIT) are invisible to the model. - The default machine profile is a generic set of numbers, not a measured profile of any printer.
Files from Bambu Studio and PrusaSlicer usually carry
M201/M203/M204lines, which helps; plain files rely entirely on the defaults or on the limits you pass.
For costing, the slicer's own estimate is used by default when present for these reasons. The model is most useful for relative questions (which layers are slow, how two slicings compare) and for files that carry no slicer estimate at all.
pip install -e ".[dev]"
ruff check .
ruff format --check .
mypy
pytest --covThe tests check numerical results against hand-derived values (for example a 20 mm extrusion at a
known E value, and a 100 mm move whose trapezoid time is 2.05 s) and run the full pipeline on four
fixtures in the Bambu Studio, OrcaSlicer, PrusaSlicer and plain Marlin styles. The fixtures are
generated by tests/fixtures/generate_fixtures.py, which keeps its own independent tally of what it
wrote (expected.json); a test fails if the committed fixtures drift from the generator. CI runs the
same commands on Ubuntu and Windows with Python 3.10 and 3.13.
tests/fixtures/real/ adds four real OrcaSlicer 2.4.2 files for the P1S, A1 and A1 mini (one of
them two-colour), sliced from print-forge models by the Real slicer fixtures workflow, which
re-slices them whenever that folder changes and fails if the G-code differs. Their provenance,
licence and what the analyser reports on them are in
tests/fixtures/real/README.md.
- Tested on synthetic fixtures and on four small real OrcaSlicer files (P1S, A1, A1 mini; no
Bambu Studio, PrusaSlicer or Cura output yet). It has not been checked against real print
times or weighed parts. On the real files the motion model differs from the slicer's own
"model printing time" by -48% to +28% (table in
tests/fixtures/real/README.md). - The time estimate has the limits described above.
- Volumetric extrusion (
M200), per-tool offsets, mixing extruders andM221flow overrides are not handled.G2/G3arcs are supported in the XY plane only (G17);G18/G19andG5splines are ignored. - The extruder is modelled as a single shared E axis. Multi-extruder machines whose tools retract by different amounts around a tool change can be off by that difference per change.
Tnumbers of 100 and above are ignored as firmware-internal selectors (Bambu usesT255,T1000, ...).M203is read as mm/s (Marlin). RepRapFirmware's mm/min convention is not detected. KlipperSET_VELOCITY_LIMITand other macros are passed over.- Without layer markers, a purge line at its own Z height is counted as a layer, and spiral-vase prints (continuously rising Z) produce one "layer" per move.
- The bounding box covers every extruding move, including purge/prime lines. Arc extents are sampled every 2 degrees.
- Filled materials (CF/GF) use the density of their base polymer unless the file or
--densitysays otherwise. - Bambu Studio's start-up G-code contains many proprietary commands; unknown commands are skipped, so anything they do (and the time they take) is not reflected.
- Validate against measured print times and weighed parts from P1S / A1 / A1 mini jobs and publish the comparison.
- Named machine profiles, and reading limits from Klipper
SET_VELOCITY_LIMIT. - Per-feature breakdown (walls, infill, support) from
;TYPE:/; FEATURE:comments. - Fixed allowances for heat-up and filament changes in the time and cost models.
- CSV export of per-layer data and a multi-file batch report.
See CONTRIBUTING.md. Security reports: SECURITY.md.
MIT, see LICENSE. Copyright 2026 Navaneeth KG.
