Python: convert collections to empty-parents with hierarchy (problem with location of instanced collection)
I could get it to work like I need it.
I had to select the above parent-collection and found some example code to implement and now it works.
I use the STEP-importer Plugin STEPper from ambi to import CAD-data and I need the correct hierarchy in the exported GLB-File and collections are exported without hierarchy.
I try to animate and show assembly groups with babylon.js.
Here is the working code:
import bpy

print()
print()
print(&quot;---------START------------&quot;)
bpy.ops.object.select_all(action='DESELECT')

def traverse_tree(t):
    yield t
    for child in t.children:
        yield from traverse_tree(child)


def parent_lookup(coll):
    parent_lookup = {}
    for coll in traverse_tree(coll):
        for c in coll.children.keys():
            parent_lookup.setdefault(c, coll.name)
    return parent_lookup


#Recursivly transverse layer_collection for a particular name
def recurLayerCollection(layerColl, collName):
    found = None
    if (layerColl.name == collName):
        return layerColl
        
    for layer in layerColl.children:
        found = recurLayerCollection(layer, collName)
        if found:
           return found

C = bpy.context
coll_all = bpy.context.scene.collection
liste =[]
counter = 0

for c in traverse_tree(coll_all):
    liste.append(c.name)


liste.remove('Collection')
liste.remove('Master Collection')
#liste.pop(0)
#iste.pop(0)
liste.reverse()


for entity in liste:
    counter = counter +1
    print(&quot;Verarbeite: &quot; + entity)
    
    source_collection = bpy.data.collections[entity]
    instance_obj = bpy.data.objects.new(name=entity, object_data=None)
    instance_obj.instance_collection = source_collection
    instance_obj.instance_type = 'COLLECTION'
#   print(instance_obj)

    # Get all collections of the scene and their parents in a dict
    coll_scene = C.scene.collection
    coll_parents = parent_lookup(coll_scene)

    # Get active collection reference
    active_coll = source_collection
#    print (coll_parents.get(active_coll.name))
    
    # Set parent collection as active
    layer_collection = bpy.context.view_layer.layer_collection
    layerColl = recurLayerCollection(layer_collection, coll_parents.get(active_coll.name))
    bpy.context.view_layer.active_layer_collection = layerColl
#    print(layerColl)
    
    # create / link instances
    parent_collection = bpy.context.view_layer.active_layer_collection
    parent_collection.collection.objects.link(instance_obj)
    
    # convert instances to real objects (with hierarchy)    
    bpy.data.objects[entity].select_set(True)
    bpy.ops.object.duplicates_make_real(use_base_parent=True, use_hierarchy=True)
    
    # delete original collection
    bpy.data.collections.remove(source_collection) #delete collection
   
    
print(counter,  &quot; Collections verarbeitet&quot;)
print(&quot;------ ENDE--------&quot;)