The script works in many cases, for sure. The difficulty in using the "plot" from a general perspective is that you don't know where the minimum and maximum are; they may not occur for the same k, and although your example shows what seems to be a 1D system, it becomes very complicated in 3D.
In your simple case one could of course extract the "HOMO" and "LUMO" bands (i.e. the lowest conduction band and highest valence band) and take the difference in all points and take the smallest value, but this assumes a direct band gap.
A more general approach (for 1D) would instead be to search (over k) these two bands for the minimum/maximum. There are many generic numerical approaches for finding a minimum and maximum of a curve; all you need to do is identify the band index of the two bands of interest and implement such a minimization function, where the "kernel" is the energy of the band as function of k (the free parameter to optimize).