Reconstructing spectral functions via automatic differentiation