Unfortunately, you can't always do it automatically. In Classical Latin, a and ā are distinct vowels just as much as a and i are, and they have to be learned as part of the word. Without context and human-level understanding, there's no way to know whether "levis" is meant to be lēvis "smooth" or lĕvis "light", for example, of if "senatus" is senātus "senate" or senātūs "senates/of the senate".
On the plus side—morphemes being distinguished solely by macrons aren't too common, and I can only think of a handful off the top of my head. If you have a way of breaking the words down into their morphemes (like Perseus's word study tool), you can then look up the morphemes in a database to figure out their vowel lengths, asking the user to clarify if there's ambiguity ("from context, does this word mean ali- 'other' or āli- 'garlic'?").
For making such a database, stems can be extracted from Lewis and Short's famous dictionary, which marks long vowels in headwords when possible. There are few enough noun endings that they can be listed out by hand, and verb endings are more predictable than they seem.
I wish you luck with this project! I for one would appreciate an automatic macron-adder to check my scansion when writing metered poetry.