I would write a custom Dataset deriving from DatasetFolder as the parent class.
In the __init__ method, use your custom method to calculate the class_to_idx mapping, then apply other methods, if desired, as e.g. datasets.folder.make_dataset.
This would probably be the easiest and cleanest approach.
Let me know, if you get stuck somewhere.