# How to ungroup all Shader Node Groups for a given file?

I have a sizeable asset library (Chocofur Lifetime Bundle) that I need to make compatible with a PBR baking addon that I use (SimpleBake). My problem is that in order for the addon to work, the shader nodes cannot be inside node groups (and they have to be either Principled BSDF or Mix Shader Nodes but that's another problem for later).

I'm just getting into scripting and after searching this website and others for a while, I couldn't find a solution to ungroup all shader node groups within a file. I tried the following approach :

import bpy

D = bpy.data

# Loop through objects
for ob in D.objects:
# Set context to Node Editor to make bpy.ops.node.group_ungroup() usable
bpy.context.area.type = "NODE_EDITOR"
# Loop through material slots
for sl in ob.material_slots:
# Get material_slots index as an integer (feels hacky)
sl_id = int(sl.path_from_id()[-2])
# Set the slot to active
ob.active_material_index = sl_id
# Loop through nodes and ungroup
for n in sl.material.node_tree.nodes:
if n.type == 'GROUP':
n.select = 1
bpy.ops.node.group_ungroup()
# Set active material slot to [0]
ob.active_material_index = 0
# Set context to Text Editor
bpy.context.area.type = "TEXT_EDITOR"


This script works for the first material slot, but won't work for the others, and I have a hard time understanding why, so any suggestion would be greatly appreciated.

Thanks!