Yes, there are "ear training" books you can read and courses you can take. There's even
a whole forum about it over on Reddit.
But at the end of the day, like anything else, it all comes down to just
doing it. A lot.
There's no substitute for sitting down, thinking of a melody (or listening to one from a recording), and trying to poke around and figure out how to play it. That is the only thing that's going to connect what you hear in your head to what you do with your fingers.
(That said, some music theory does help, because it divorces melodies and chord progressions from the actual notes and puts them in terms of relationships/functions, which are easier for most people to hear.)