LOPs - PY - extract point instancer

from pxr import Usd, UsdGeom, Gf, Vt, Sdf

# Get the current LOP node and stage
node = hou.pwd()
stage = node.editableStage()

# Get the PointInstancer prim path from parameter
prim_path = node.evalParm("instancer_primpath")
instancer_prim = stage.GetPrimAtPath(prim_path)

if not instancer_prim or not instancer_prim.IsValid():
raise RuntimeError(f"Invalid prim at path: {prim_path}")

instancer = UsdGeom.PointInstancer(instancer_prim)

# Extract array data from the PointInstancer
positions = instancer.GetPositionsAttr().Get() or Vt.Vec3fArray()
raw_orientations = instancer.GetOrientationsAttr().Get() or Vt.QuathArray()
scales = instancer.GetScalesAttr().Get() or Vt.Vec3fArray()
proto_indices = instancer.GetProtoIndicesAttr().Get() or Vt.IntArray()

# Convert orientations from QuathArray to QuatfArray
orientations = Vt.QuatfArray([
Gf.Quatf(o.GetReal(), Gf.Vec3f(o.GetImaginary())) for o in raw_orientations
])

# Create a new Points prim under "/"
clean_name = prim_path.strip("/").replace("/", "_")
new_path = f"/{clean_name}_extracted_points"
points_prim = UsdGeom.Points.Define(stage, new_path)

# Set 'points' (position) attribute
points_prim.CreatePointsAttr(positions)

# Create and set 'orientations' primvar (Quatf array)
orient_primvar = points_prim.CreatePrimvar(
"orientations", Sdf.ValueTypeNames.QuatfArray, UsdGeom.Tokens.vertex
)
orient_primvar.Set(orientations)

# Create and set 'scales' primvar (Vec3f array)
scale_primvar = points_prim.CreatePrimvar(
"scales", Sdf.ValueTypeNames.Float3Array, UsdGeom.Tokens.vertex
)
scale_primvar.Set(scales)

# Create and set 'protoIndices' primvar (int array)
proto_index_primvar = points_prim.CreatePrimvar(
"protoIndices", Sdf.ValueTypeNames.IntArray, UsdGeom.Tokens.vertex
)
proto_index_primvar.Set(proto_indices)