Just doing plain OCR doesn't really work because the notes in the margin and the footnotes get mingled with the text, which results in gibberish.
But, when sent to Google Vision API, each page results in a json file that has an object for each word and the four coordinates of its bounding box.
That json file is pretty big (around 1.5 Mo when pretty printed, or 500 k with no indents or line breaks) but it can then be fed to Gemini, taking advantage of its large context window.
Gemini is pretty good at identifying each section of the page (headers, main text, margin comments, footnotes) but it takes a looong time to respond (2-5 minutes per page).
So another approach is to ask Gemini to write a python script to analyze the json result and group sections depending of the coordinates of each word, and then run that script against the json output by the OCR phase.
But it's quite difficult to have a script that works for any page; comments in the margin are always in the margin so that's pretty easy, but footnotes can start at any height of the page (some pages contain only footnotes running from previous pages) and Gemini likes to be pretty specific, giving hard 'y' coordinates for where footnotes should start, which obviously only works for the one page it's working on.
I'm iterating and making some progress but I feel like I miss a big breakthrough and it all should be simpler than it currently is. Information about OCR is pretty scarce online. Any pointer is welcome!