File size: 260,239 Bytes
62787e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
from __future__ import annotations

import base64
import io
import contextlib
import difflib
import html
import importlib.util
import inspect
import io
import json
import os
import math
import re
import shlex
import shutil
import subprocess
import sys
import time
import warnings
from functools import lru_cache
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Any, Callable, Dict, List, Optional, Tuple

import requests

try:
    from dotenv import load_dotenv
except Exception:
    load_dotenv = None


ROOT = Path(__file__).resolve().parent
ProgressHandler = Optional[Callable[[str], None]]
_DEEPSEEK_OCR_MODEL = None
_DEEPSEEK_OCR_PROCESSOR = None
_DEEPSEEK_OCR_MODEL_ID = None
_DEEPSEEK_OCR_LOAD_ERROR = None
_GENERIC_OCR_BACKENDS: Dict[str, Any] = {}


_QIANFAN_OCR_DEFAULT_MODEL_ID = "baidu/Qianfan-OCR"
_GLM_OCR_DEFAULT_MODEL_ID = "zai-org/GLM-OCR"
_PADDLEOCR_VL_DEFAULT_MODEL_ID = "PaddlePaddle/PaddleOCR-VL-1.5"
_GOT_OCR_DEFAULT_MODEL_ID = "stepfun-ai/GOT-OCR2_0"
_MONKEYOCR_DEFAULT_MODEL_ID = "echo840/MonkeyOCR-pro-3B"
_QWEN_OCR_DEFAULT_MODEL_ID = "Qwen/Qwen3.6-35B-A3B"
_GEMMA4_VLLM_DEFAULT_MODEL_ID = "google/gemma-4-26B-A4B-it"
_GEMMA4_LLAMA_CPP_DEFAULT_MODEL_ID = "gemma4-26b-llamacpp"


if load_dotenv is not None:
    load_dotenv(ROOT / "sec_parser" / ".env")
    load_dotenv(ROOT / ".env")


class TableOCRContentError(RuntimeError):
    def __init__(
        self,
        message: str,
        *,
        response_payload: Optional[Dict[str, Any]] = None,
        details: Optional[Dict[str, Any]] = None,
    ):
        super().__init__(message)
        self.response_payload = response_payload or {}
        self.details = details or {}


class TableOCRTranscriptionText(str):
    def __new__(
        cls,
        text: str,
        *,
        effective_model_id: Optional[str] = None,
        thinking_latency_s: Optional[float] = None,
        total_latency_s: Optional[float] = None,
        first_content_latency_s: Optional[float] = None,
        reasoning_tokens: Optional[int] = None,
        completion_tokens: Optional[int] = None,
    ):
        obj = super().__new__(cls, text)
        obj.effective_model_id = normalize_text(effective_model_id or "")
        obj.thinking_latency_s = (
            max(0.0, float(thinking_latency_s))
            if isinstance(thinking_latency_s, (int, float))
            else None
        )
        obj.total_latency_s = (
            max(0.0, float(total_latency_s))
            if isinstance(total_latency_s, (int, float))
            else None
        )
        obj.first_content_latency_s = (
            max(0.0, float(first_content_latency_s))
            if isinstance(first_content_latency_s, (int, float))
            else None
        )
        obj.reasoning_tokens = (
            max(0, int(reasoning_tokens))
            if isinstance(reasoning_tokens, (int, float))
            else None
        )
        obj.completion_tokens = (
            max(0, int(completion_tokens))
            if isinstance(completion_tokens, (int, float))
            else None
        )
        return obj


def emit_progress(message: str, *, progress_handler: ProgressHandler = None) -> None:
    if progress_handler is not None:
        progress_handler(message)
        return
    print(message, flush=True)


def default_table_image_transcription_prompt() -> str:
    return (
        "Transcribe the table in the image into a minimal HTML fragment.\n"
        "Return only plain HTML using <table>, <tr>, <th>, <td>, <br>, and inline formatting tags such as <strong>/<b>, <em>/<i>, <u>, <sup>, and <sub> when needed.\n"
        "Do not use markdown fences, commentary, CSS, or JavaScript.\n"
        "Assume every visible textual element inside the image crop belongs to the table and must be transcribed.\n"
        "Include all visible titles, units, stub labels, grouped headers, footnotes, side labels, and notes, even when they sit above, below, or beside the main grid.\n"
        "Do not omit text just because it looks visually separate from the numeric body; if it is visible in the crop, capture it in the output table.\n"
        "Preserve merged-cell structure faithfully. Use colspan and rowspan when they are needed to represent the visible table layout.\n"
        "Do not duplicate merged-cell text across multiple cells unless the image itself repeats that text.\n"
        "Preserve visible text formatting exactly when present, including bold, italics, underline, superscripts, and subscripts.\n"
        "Ignore purely visual table styling such as thick borders, ruling lines, shading, and decorative emphasis; transcribe only the table's textual content and structure.\n"
        "Preserve row order, column order, signs, punctuation, decimals, and capitalization exactly."
    )


def strip_code_fences(text: str) -> str:
    text = (text or "").strip()
    text = re.sub(r"^```(?:html)?\s*", "", text, flags=re.IGNORECASE)
    text = re.sub(r"\s*```$", "", text)
    return text.strip()


def normalize_text(text: str) -> str:
    return str(text or "").strip()


_HTML_TABLE_RE = re.compile(r"<table\b", re.IGNORECASE)
_HTML_TABLE_FRAGMENT_RE = re.compile(r"<table\b[\s\S]*?</table>", re.IGNORECASE)
_GEMMA4_THOUGHT_BLOCK_RE = re.compile(
    r"<\|channel\>thought\s*[\s\S]*?<channel\|>",
    re.IGNORECASE,
)
_GEMMA4_THINK_BLOCK_RE = re.compile(r"<think>[\s\S]*?</think>", re.IGNORECASE)
_GEMMA4_CHANNEL_MARKER_RE = re.compile(
    r"<\|channel\>[A-Za-z0-9_-]*\s*|<channel\|>",
    re.IGNORECASE,
)
_LATEX_INLINE_TEXT_RE = re.compile(
    r"\\(?:[A-Za-z]+|[()[\]{}%&_#$,])"
    r"|(?<!\\)\$\$?.+?(?<!\\)\$\$?"
    r"|(?:[A-Za-z0-9])(?:\^|_)\{",
    re.DOTALL,
)
_LATEX_TABULAR_RE = re.compile(
    r"\\begin\s*\{tabular\}\s*\{(?P<spec>[^{}]*)\}(?P<body>[\s\S]*?)\\end\s*\{tabular\}",
    re.IGNORECASE,
)
_LATEX_BEGIN_ENV_RE = re.compile(r"\\begin\s*\{(?P<name>[^{}]+)\}", re.IGNORECASE)
_LATEX_RULE_COMMAND_RE = re.compile(
    r"\\(?:hline|toprule|midrule|bottomrule)\b"
    r"|\\(?:c|x)?cline(?:\[[^\]]+\])?\{[^{}]*\}"
    r"|\\cmidrule(?:\([^)]+\))?\{[^{}]*\}",
    re.IGNORECASE,
)
_LATEX_TABLE_ENVIRONMENT_ARG_COUNTS: Dict[str, int] = {
    "array": 1,
    "longtable": 1,
    "longtabu": 2,
    "nicetabular": 1,
    "tabu": 1,
    "tabular": 1,
    "tabular*": 2,
    "tabularx": 2,
    "tabulary": 2,
    "tblr": 1,
    "xltabular": 2,
}
_LATEX_INLINE_SYMBOLS: Dict[str, str] = {
    "alpha": "&alpha;",
    "beta": "&beta;",
    "gamma": "&gamma;",
    "delta": "&delta;",
    "epsilon": "&epsilon;",
    "theta": "&theta;",
    "lambda": "&lambda;",
    "mu": "&mu;",
    "pi": "&pi;",
    "sigma": "&sigma;",
    "tau": "&tau;",
    "phi": "&phi;",
    "omega": "&omega;",
    "Gamma": "&Gamma;",
    "Delta": "&Delta;",
    "Theta": "&Theta;",
    "Lambda": "&Lambda;",
    "Pi": "&Pi;",
    "Sigma": "&Sigma;",
    "Phi": "&Phi;",
    "Omega": "&Omega;",
    "cdot": "&middot;",
    "times": "&times;",
    "div": "&divide;",
    "leq": "&le;",
    "geq": "&ge;",
    "neq": "&ne;",
    "approx": "&asymp;",
    "sim": "~",
    "pm": "&plusmn;",
    "mp": "&#8723;",
    "to": "&rarr;",
    "rightarrow": "&rarr;",
    "leftarrow": "&larr;",
    "leftrightarrow": "&harr;",
    "infty": "&infin;",
    "degree": "&deg;",
    "circ": "&deg;",
    "ldots": "...",
    "dots": "...",
    "cdots": "...",
    "vdots": "...",
    "ddots": "...",
}
_LATEX_INLINE_UNWRAP_COMMANDS = {
    "bar",
    "boxed",
    "fbox",
    "hphantom",
    "mathbb",
    "mathcal",
    "mathfrak",
    "mathrm",
    "mathsf",
    "mathtt",
    "mbox",
    "operatorname",
    "overline",
    "phantom",
    "rlap",
    "smash",
    "text",
    "textnormal",
    "textrm",
    "textsf",
    "texttt",
    "tilde",
    "vec",
    "vphantom",
    "widehat",
    "widetilde",
}
_LATEX_INLINE_BOLD_COMMANDS = {"bf", "bfseries", "bm", "boldsymbol", "mathbf", "textbf"}
_LATEX_INLINE_ITALIC_COMMANDS = {"emph", "it", "itshape", "mathit", "textit"}
_LATEX_INLINE_UNDERLINE_COMMANDS = {"dashuline", "uline", "underline", "uwave"}
_LATEX_LAYOUT_COMMAND_RE = re.compile(
    r"\\(?:addlinespace(?:\[[^\]]*\])?|arraybackslash|centering|footnotesize|Huge|huge|LARGE|Large|large|"
    r"morecmidrulespace|newline|normalcolor|normalfont|normalsize|par|qquad|quad|raggedleft|raggedright|"
    r"scriptsize|small|tabularnewline|tiny)\b",
    re.IGNORECASE,
)
_LATEX_HEADER_FOOTER_MARKER_RE = re.compile(
    r"\\(?:endfirsthead|endhead|endfoot|endlastfoot)\b",
    re.IGNORECASE,
)
_LATEX_TABLENOTES_ENV_RE = re.compile(
    r"\\begin\s*\{tablenotes\}(?P<body>[\s\S]*?)\\end\s*\{tablenotes\}",
    re.IGNORECASE,
)


def _consume_latex_braced_group(text: str, start_index: int) -> tuple[Optional[str], int]:
    if start_index >= len(text) or text[start_index] != "{":
        return None, start_index
    depth = 0
    index = start_index
    while index < len(text):
        char = text[index]
        if char == "\\":
            index += 2
            continue
        if char == "{":
            depth += 1
        elif char == "}":
            depth -= 1
            if depth == 0:
                return text[start_index + 1 : index], index + 1
        index += 1
    return None, start_index


def _consume_latex_optional_bracket_group(text: str, start_index: int) -> int:
    _, next_index = _consume_latex_bracket_group(text, start_index)
    return next_index


def _consume_latex_bracket_group(text: str, start_index: int) -> tuple[Optional[str], int]:
    if start_index >= len(text) or text[start_index] != "[":
        return None, start_index
    depth = 0
    index = start_index
    while index < len(text):
        char = text[index]
        if char == "\\":
            index += 2
            continue
        if char == "[":
            depth += 1
        elif char == "]":
            depth -= 1
            if depth == 0:
                return text[start_index + 1 : index], index + 1
        index += 1
    return None, start_index


def _consume_latex_command(
    text: str,
    command: str,
    *,
    required_arg_count: int,
    optional_arg_count: int = 0,
    allow_star: bool = False,
) -> tuple[Optional[Dict[str, Any]], int]:
    index = 0
    while index < len(text) and text[index].isspace():
        index += 1
    prefix = f"\\{command}"
    if not text.startswith(prefix, index):
        return None, 0
    index += len(prefix)

    starred = False
    if allow_star and index < len(text) and text[index] == "*":
        starred = True
        index += 1

    optional_args: List[str] = []
    for _ in range(optional_arg_count):
        while index < len(text) and text[index].isspace():
            index += 1
        optional_arg, next_index = _consume_latex_bracket_group(text, index)
        if optional_arg is None:
            break
        optional_args.append(optional_arg)
        index = next_index

    args: List[str] = []
    for _ in range(required_arg_count):
        while index < len(text) and text[index].isspace():
            index += 1
        arg, next_index = _consume_latex_braced_group(text, index)
        if arg is None:
            return None, 0
        args.append(arg)
        index = next_index

    return {
        "args": args,
        "optional_args": optional_args,
        "starred": starred,
    }, index


def _consume_latex_command_args(text: str, command: str, arg_count: int) -> tuple[Optional[List[str]], int]:
    payload, end_index = _consume_latex_command(
        text,
        command,
        required_arg_count=arg_count,
    )
    if payload is None:
        return None, 0
    return list(payload["args"]), end_index


def _split_latex_top_level(text: str, *, separator: str) -> List[str]:
    parts: List[str] = []
    current: List[str] = []
    brace_depth = 0
    index = 0
    while index < len(text):
        char = text[index]
        if char == "\\":
            if separator == "\\\\" and text.startswith("\\\\", index) and brace_depth == 0:
                parts.append("".join(current))
                current = []
                index += 2
                while index < len(text) and text[index].isspace():
                    index += 1
                next_index = _consume_latex_optional_bracket_group(text, index)
                if next_index != index:
                    index = next_index
                continue
            if index + 1 < len(text):
                current.append(text[index : index + 2])
                index += 2
                continue
        if char == "{":
            brace_depth += 1
        elif char == "}" and brace_depth > 0:
            brace_depth -= 1
        elif separator == "&" and char == "&" and brace_depth == 0:
            parts.append("".join(current))
            current = []
            index += 1
            continue
        current.append(char)
        index += 1
    parts.append("".join(current))
    return parts


def _replace_latex_command_occurrences(
    text: str,
    command: str,
    *,
    required_arg_count: int,
    optional_arg_count: int = 0,
    allow_star: bool = False,
    replacement: Any = "",
    predicate: Optional[Callable[[Dict[str, Any]], bool]] = None,
) -> str:
    if not text:
        return text
    star_pattern = r"(?:\*)?" if allow_star else ""
    pattern = re.compile(
        rf"\\{re.escape(command)}{star_pattern}(?![A-Za-z])",
        re.IGNORECASE,
    )
    chunks: List[str] = []
    index = 0
    for match in pattern.finditer(text):
        if match.start() < index:
            continue
        parsed, consumed = _consume_latex_command(
            text[match.start() :],
            command,
            required_arg_count=required_arg_count,
            optional_arg_count=optional_arg_count,
            allow_star=allow_star,
        )
        if parsed is None:
            continue
        if predicate is not None and not predicate(parsed):
            continue
        chunks.append(text[index : match.start()])
        if callable(replacement):
            replacement_text = replacement(parsed)
            if replacement_text:
                chunks.append(str(replacement_text))
        elif replacement:
            chunks.append(str(replacement))
        index = match.start() + consumed
    if not chunks:
        return text
    chunks.append(text[index:])
    return "".join(chunks)


def _find_matching_latex_end(
    text: str,
    *,
    env_name: str,
    start_index: int,
) -> tuple[Optional[int], Optional[int]]:
    pattern = re.compile(
        rf"\\(?P<kind>begin|end)\s*\{{{re.escape(env_name)}\}}",
        re.IGNORECASE,
    )
    depth = 1
    for match in pattern.finditer(text, start_index):
        if normalize_text(match.group("kind")).lower() == "begin":
            depth += 1
            continue
        depth -= 1
        if depth == 0:
            return match.start(), match.end()
    return None, None


def _extract_latex_table_candidates(text: str) -> List[Dict[str, Any]]:
    candidates: List[Dict[str, Any]] = []
    for begin_match in _LATEX_BEGIN_ENV_RE.finditer(text):
        env_name = normalize_text(begin_match.group("name"))
        arg_count = _LATEX_TABLE_ENVIRONMENT_ARG_COUNTS.get(env_name.lower())
        if arg_count is None:
            continue
        index = begin_match.end()
        valid = True
        for _ in range(arg_count):
            while index < len(text) and text[index].isspace():
                index += 1
            while True:
                optional_arg, next_index = _consume_latex_bracket_group(text, index)
                if optional_arg is None:
                    break
                index = next_index
                while index < len(text) and text[index].isspace():
                    index += 1
            _, next_index = _consume_latex_braced_group(text, index)
            if next_index == index:
                valid = False
                break
            index = next_index
        if not valid:
            continue
        body_end_start, body_end_end = _find_matching_latex_end(
            text,
            env_name=env_name,
            start_index=index,
        )
        if body_end_start is None or body_end_end is None:
            continue
        candidates.append(
            {
                "env_name": env_name,
                "body": text[index:body_end_start],
                "source": text[begin_match.start() : body_end_end],
                "start": begin_match.start(),
                "end": body_end_end,
            }
        )
    return candidates


def _read_latex_inline_argument(text: str, start_index: int) -> tuple[str, int]:
    index = start_index
    while index < len(text) and text[index].isspace():
        index += 1
    if index >= len(text):
        return "", index
    if text[index] == "{":
        group, next_index = _consume_latex_braced_group(text, index)
        if group is None:
            return "", index
        return _latex_inline_to_html(group), next_index
    if text[index] == "\\" and index + 1 < len(text):
        return _latex_inline_to_html(text[index : index + 2]), index + 2
    return html.escape(text[index]), index + 1


def _read_latex_inline_arguments(
    text: str,
    start_index: int,
    *,
    count: int,
) -> tuple[List[str], int]:
    values: List[str] = []
    index = start_index
    for _ in range(count):
        value_html, next_index = _read_latex_inline_argument(text, index)
        values.append(value_html)
        index = next_index
    return values, index


def _latex_inline_to_html(text: str) -> str:
    def parse_segment(start_index: int, *, stop_at_closing_brace: bool = False) -> tuple[str, int]:
        parts: List[str] = []
        index = start_index
        while index < len(text):
            char = text[index]
            if stop_at_closing_brace and char == "}":
                return "".join(parts), index + 1
            if char == "$":
                delimiter_len = 2 if text.startswith("$$", index) else 1
                search_index = index + delimiter_len
                matched = False
                while search_index < len(text):
                    matching_index = text.find("$" * delimiter_len, search_index)
                    if matching_index < 0:
                        break
                    if delimiter_len == 1 and matching_index > 0 and text[matching_index - 1] == "\\":
                        search_index = matching_index + 1
                        continue
                    payload = text[index + delimiter_len : matching_index]
                    if _LATEX_INLINE_TEXT_RE.search(payload or ""):
                        parts.append(_latex_inline_to_html(payload))
                        index = matching_index + delimiter_len
                        matched = True
                    break
                if matched:
                    continue
                parts.append(html.escape(char))
                index += 1
                continue
            if char == "{":
                inner, index = parse_segment(index + 1, stop_at_closing_brace=True)
                parts.append(inner)
                continue
            if char in {"^", "_"}:
                tag_name = "sup" if char == "^" else "sub"
                payload_html, index = _read_latex_inline_argument(text, index + 1)
                parts.append(f"<{tag_name}>{payload_html}</{tag_name}>")
                continue
            if char == "~":
                parts.append(" ")
                index += 1
                continue
            if char == "\\":
                if text.startswith("\\\\", index):
                    parts.append("<br>")
                    index += 2
                    continue
                index += 1
                if index >= len(text):
                    break
                escaped_char = text[index]
                if escaped_char in "{}%&$_#":
                    parts.append(html.escape(escaped_char))
                    index += 1
                    continue
                if escaped_char in "()[],":
                    index += 1
                    continue
                match = re.match(r"[A-Za-z]+", text[index:])
                if not match:
                    parts.append(html.escape("\\" + escaped_char))
                    index += 1
                    continue
                command = match.group(0)
                index += len(command)
                if command in _LATEX_INLINE_UNWRAP_COMMANDS:
                    payload_html, index = _read_latex_inline_argument(text, index)
                    parts.append(payload_html)
                    continue
                if command in _LATEX_INLINE_BOLD_COMMANDS:
                    payload_html, index = _read_latex_inline_argument(text, index)
                    parts.append(f"<strong>{payload_html}</strong>")
                    continue
                if command in _LATEX_INLINE_ITALIC_COMMANDS:
                    payload_html, index = _read_latex_inline_argument(text, index)
                    parts.append(f"<em>{payload_html}</em>")
                    continue
                if command in _LATEX_INLINE_UNDERLINE_COMMANDS:
                    payload_html, index = _read_latex_inline_argument(text, index)
                    parts.append(f"<u>{payload_html}</u>")
                    continue
                if command in {"frac", "dfrac", "tfrac"}:
                    fraction_parts, index = _read_latex_inline_arguments(text, index, count=2)
                    numerator_html, denominator_html = fraction_parts
                    parts.append(f"{numerator_html}/{denominator_html}")
                    continue
                if command in {"textcolor", "colorbox"}:
                    _, index = _read_latex_inline_argument(text, index)
                    payload_html, index = _read_latex_inline_argument(text, index)
                    parts.append(payload_html)
                    continue
                if command == "fcolorbox":
                    _, index = _read_latex_inline_argument(text, index)
                    _, index = _read_latex_inline_argument(text, index)
                    payload_html, index = _read_latex_inline_argument(text, index)
                    parts.append(payload_html)
                    continue
                if command in {"makecell", "shortstack"}:
                    while True:
                        optional_arg, next_index = _consume_latex_bracket_group(text, index)
                        if optional_arg is None:
                            break
                        index = next_index
                    payload_html, index = _read_latex_inline_argument(text, index)
                    parts.append(payload_html)
                    continue
                if command in {"multicolumn", "multirow", "parbox", "rotatebox", "scalebox"}:
                    payload_html = ""
                    if command == "multicolumn":
                        _, index = _read_latex_inline_argument(text, index)
                        _, index = _read_latex_inline_argument(text, index)
                        payload_html, index = _read_latex_inline_argument(text, index)
                    elif command == "multirow":
                        while True:
                            optional_arg, next_index = _consume_latex_bracket_group(text, index)
                            if optional_arg is None:
                                break
                            index = next_index
                        _, index = _read_latex_inline_argument(text, index)
                        _, index = _read_latex_inline_argument(text, index)
                        payload_html, index = _read_latex_inline_argument(text, index)
                    else:
                        _, index = _read_latex_inline_argument(text, index)
                        payload_html, index = _read_latex_inline_argument(text, index)
                    parts.append(payload_html)
                    continue
                if command == "resizebox":
                    _, index = _read_latex_inline_argument(text, index)
                    _, index = _read_latex_inline_argument(text, index)
                    payload_html, index = _read_latex_inline_argument(text, index)
                    parts.append(payload_html)
                    continue
                if command == "raisebox":
                    _, index = _read_latex_inline_argument(text, index)
                    while True:
                        optional_arg, next_index = _consume_latex_bracket_group(text, index)
                        if optional_arg is None:
                            break
                        index = next_index
                    payload_html, index = _read_latex_inline_argument(text, index)
                    parts.append(payload_html)
                    continue
                if command in {"footnote", "tablefootnote"}:
                    payload_html, index = _read_latex_inline_argument(text, index)
                    if payload_html:
                        parts.append(f"<br>{payload_html}")
                    continue
                if command == "tnote":
                    payload_html, index = _read_latex_inline_argument(text, index)
                    parts.append(f"<sup>{payload_html}</sup>")
                    continue
                if command in _LATEX_INLINE_SYMBOLS:
                    parts.append(_LATEX_INLINE_SYMBOLS[command])
                    continue
                if command in {"left", "right"}:
                    continue
                if command in {"label", "nonumber"}:
                    continue
                payload_html, next_index = _read_latex_inline_argument(text, index)
                if next_index != index:
                    parts.append(payload_html)
                    index = next_index
                continue
            if char == "}":
                if stop_at_closing_brace:
                    return "".join(parts), index + 1
                index += 1
                continue
            parts.append(html.escape(char))
            index += 1
        return "".join(parts), index

    rendered, _ = parse_segment(0)
    rendered = re.sub(r"\s*<br>\s*", "<br>", rendered)
    rendered = re.sub(r"[ \t\r\f\v]+", " ", rendered)
    return rendered.strip()


def normalize_inline_latex_in_html_fragment(html_fragment: str) -> str:
    cleaned = strip_code_fences(str(html_fragment or ""))
    if not cleaned or not _HTML_TABLE_RE.search(cleaned):
        return cleaned

    try:
        from bs4 import BeautifulSoup, NavigableString, Tag
    except ImportError:
        return cleaned

    soup = BeautifulSoup(cleaned, "html.parser")
    for text_node in list(soup.find_all(string=True)):
        parent = text_node.parent
        if not isinstance(text_node, NavigableString) or not isinstance(parent, Tag):
            continue
        if parent.name in {"script", "style"}:
            continue

        original = str(text_node)
        if not _LATEX_INLINE_TEXT_RE.search(original):
            continue

        rendered = _latex_inline_to_html(original)
        if not rendered or rendered == html.escape(original):
            continue

        fragment_soup = BeautifulSoup(f"<body>{rendered}</body>", "html.parser")
        body = getattr(fragment_soup, "body", None)
        replacement_nodes = list(body.contents if body is not None else fragment_soup.contents)
        if not replacement_nodes:
            continue
        for node in replacement_nodes:
            text_node.insert_before(node)
        text_node.extract()

    return str(soup)


def _parse_latex_cell(cell_text: str) -> Dict[str, Any]:
    cell = normalize_text(cell_text)
    colspan = 1
    rowspan = 1

    while cell:
        matched = False
        multicolumn_payload, multicolumn_end = _consume_latex_command(
            cell,
            "multicolumn",
            required_arg_count=3,
        )
        if multicolumn_payload is not None:
            multicolumn_args = list(multicolumn_payload["args"])
            try:
                colspan = max(1, int(normalize_text(multicolumn_args[0])))
            except ValueError:
                colspan = 1
            cell = (multicolumn_args[2] + cell[multicolumn_end:]).strip()
            matched = True
        multirow_payload, multirow_end = _consume_latex_command(
            cell,
            "multirow",
            required_arg_count=3,
            optional_arg_count=1,
        )
        if multirow_payload is not None:
            multirow_args = list(multirow_payload["args"])
            try:
                rowspan = max(1, int(normalize_text(multirow_args[0]).lstrip("*")))
            except ValueError:
                rowspan = 1
            cell = (multirow_args[2] + cell[multirow_end:]).strip()
            matched = True
        block_payload, block_end = _consume_latex_command(
            cell,
            "Block",
            required_arg_count=2,
            optional_arg_count=1,
        )
        if block_payload is not None:
            block_args = list(block_payload["args"])
            block_spec = normalize_text(block_args[0])
            span_match = re.match(r"(?P<rows>\d+)\s*[-x,]\s*(?P<cols>\d+)", block_spec)
            if span_match is not None:
                rowspan = max(rowspan, int(span_match.group("rows")))
                colspan = max(colspan, int(span_match.group("cols")))
            elif block_spec.isdigit():
                rowspan = max(rowspan, int(block_spec))
            cell = (block_args[1] + cell[block_end:]).strip()
            matched = True
        setcell_payload, setcell_end = _consume_latex_command(
            cell,
            "SetCell",
            required_arg_count=1,
            optional_arg_count=1,
        )
        if setcell_payload is not None:
            option_text = ",".join(
                piece
                for piece in [*setcell_payload["optional_args"], *setcell_payload["args"]]
                if normalize_text(piece)
            )
            row_match = re.search(r"(?:^|[,; ]+)r\s*=\s*(\d+)", option_text, re.IGNORECASE)
            col_match = re.search(r"(?:^|[,; ]+)c\s*=\s*(\d+)", option_text, re.IGNORECASE)
            if row_match is not None:
                rowspan = max(rowspan, int(row_match.group(1)))
            if col_match is not None:
                colspan = max(colspan, int(col_match.group(1)))
            cell = cell[setcell_end:].strip()
            matched = True
        if not matched:
            break

    return {
        "html": _latex_inline_to_html(cell),
        "colspan": colspan,
        "rowspan": rowspan,
    }


def _extract_latex_caption_html(text: str) -> str:
    best_caption = ""
    if not text:
        return best_caption

    for match in re.finditer(r"\\captionof(?:\*)?(?![A-Za-z])", text, re.IGNORECASE):
        payload, _ = _consume_latex_command(
            text[match.start() :],
            "captionof",
            required_arg_count=2,
            optional_arg_count=1,
            allow_star=True,
        )
        if payload is None:
            continue
        target_name = normalize_text(payload["args"][0]).lower()
        if "table" not in target_name:
            continue
        caption_html = _latex_inline_to_html(payload["args"][1])
        if len(caption_html) > len(best_caption):
            best_caption = caption_html

    for match in re.finditer(r"\\caption(?:\*)?(?![A-Za-z])", text, re.IGNORECASE):
        payload, _ = _consume_latex_command(
            text[match.start() :],
            "caption",
            required_arg_count=1,
            optional_arg_count=1,
            allow_star=True,
        )
        if payload is None:
            continue
        caption_html = _latex_inline_to_html(payload["args"][0])
        if len(caption_html) > len(best_caption):
            best_caption = caption_html
    return best_caption


def _extract_latex_tablenotes_html(text: str) -> str:
    note_fragments: List[str] = []
    for match in _LATEX_TABLENOTES_ENV_RE.finditer(text):
        body = normalize_text(match.group("body"))
        if not body:
            continue
        item_parts = re.split(r"\\item(?:\s*\[[^\]]*\])?", body)
        rendered_items = [
            _latex_inline_to_html(piece)
            for piece in item_parts
            if normalize_text(piece)
        ]
        if rendered_items:
            note_fragments.extend(rendered_items)
            continue
        fallback_html = _latex_inline_to_html(body)
        if fallback_html:
            note_fragments.append(fallback_html)
    return "<br>".join(fragment for fragment in note_fragments if normalize_text(fragment))


def _clean_latex_tabular_body(body: str) -> str:
    cleaned = body.replace("\r", "\n").replace("\\tabularnewline", "\\\\")
    cleaned = _LATEX_TABLENOTES_ENV_RE.sub("", cleaned)
    cleaned = _replace_latex_command_occurrences(
        cleaned,
        "captionof",
        required_arg_count=2,
        optional_arg_count=1,
        allow_star=True,
        replacement=r"\\",
        predicate=lambda payload: "table" in normalize_text(payload["args"][0]).lower(),
    )
    cleaned = _replace_latex_command_occurrences(
        cleaned,
        "caption",
        required_arg_count=1,
        optional_arg_count=1,
        allow_star=True,
        replacement=r"\\",
    )
    cleaned = _replace_latex_command_occurrences(
        cleaned,
        "label",
        required_arg_count=1,
        replacement="",
    )
    cleaned = _replace_latex_command_occurrences(
        cleaned,
        "endfirsthead",
        required_arg_count=0,
        replacement=r"\\",
    )
    cleaned = _replace_latex_command_occurrences(
        cleaned,
        "endhead",
        required_arg_count=0,
        replacement=r"\\",
    )
    cleaned = _replace_latex_command_occurrences(
        cleaned,
        "endfoot",
        required_arg_count=0,
        replacement=r"\\",
    )
    cleaned = _replace_latex_command_occurrences(
        cleaned,
        "endlastfoot",
        required_arg_count=0,
        replacement=r"\\",
    )
    cleaned = _LATEX_RULE_COMMAND_RE.sub("", cleaned)
    cleaned = _LATEX_LAYOUT_COMMAND_RE.sub(" ", cleaned)
    cleaned = _LATEX_HEADER_FOOTER_MARKER_RE.sub(lambda _match: r"\\", cleaned)
    return cleaned


def _parse_latex_tabular_body(body: str) -> List[List[Dict[str, Any]]]:
    cleaned = _clean_latex_tabular_body(body)
    rows: List[List[Dict[str, Any]]] = []
    for raw_row in _split_latex_top_level(cleaned, separator="\\\\"):
        row_text = normalize_text(raw_row)
        if not row_text:
            continue
        row_cells = [
            _parse_latex_cell(raw_cell)
            for raw_cell in _split_latex_top_level(row_text, separator="&")
        ]
        row_cells = [
            cell
            for cell in row_cells
            if cell["html"] or cell["colspan"] > 1 or cell["rowspan"] > 1
        ]
        if row_cells:
            rows.append(row_cells)
    return rows


def _latex_table_score(
    rows: List[List[Dict[str, Any]]],
    *,
    caption_html: str = "",
    notes_html: str = "",
) -> float:
    if not rows:
        return 0.0
    max_width = max(sum(int(cell["colspan"]) for cell in row) for row in rows)
    alpha_count = sum(
        1
        for row in rows
        for cell in row
        for char in html.unescape(str(cell["html"]))
        if char.isalpha()
    )
    caption_bonus = len(html.unescape(caption_html or ""))
    notes_bonus = len(html.unescape(notes_html or ""))
    return float(len(rows) * max_width * 4 + alpha_count + caption_bonus + (notes_bonus * 0.5))


def _render_latex_table_html(
    rows: List[List[Dict[str, Any]]],
    *,
    caption_html: str = "",
    notes_html: str = "",
) -> str:
    max_width = max((sum(int(cell["colspan"]) for cell in row) for row in rows), default=1)
    colspan_attr = f' colspan="{max_width}"' if max_width > 1 else ""
    parts: List[str] = ["<table>"]
    if caption_html:
        parts.append(f"<tr><td{colspan_attr}>{caption_html}</td></tr>")
    for row in rows:
        parts.append("<tr>")
        for cell in row:
            attrs = ""
            if int(cell["colspan"]) > 1:
                attrs += f' colspan="{int(cell["colspan"])}"'
            if int(cell["rowspan"]) > 1:
                attrs += f' rowspan="{int(cell["rowspan"])}"'
            parts.append(f"<td{attrs}>{cell['html']}</td>")
        parts.append("</tr>")
    if notes_html:
        parts.append(f"<tr><td{colspan_attr}>{notes_html}</td></tr>")
    parts.append("</table>")
    return "".join(parts)


def _looks_like_latex_table_markup(text: str) -> bool:
    if not text:
        return False
    if re.search(r"\\begin\s*\{(?:array|longtable|longtabu|nicetabular|tabu|tabular\*?|tabularx|tabulary|tblr|xltabular)\}", text, re.IGNORECASE):
        return True
    return bool(
        re.search(
            r"\\(?:caption(?:of)?|cmidrule|multicolumn|multirow|toprule|midrule|bottomrule)\b",
            text,
            re.IGNORECASE,
        )
    )


def _latex_table_renderer_command_template() -> Optional[str]:
    configured = normalize_text(os.getenv("LATEX_TABLE_RENDER_COMMAND", ""))
    if configured:
        return configured
    if shutil.which("latexmlc"):
        return "latexmlc --quiet --nocomments --format=html5 --dest={output_path} {input_path}"
    if shutil.which("pandoc"):
        return "pandoc --from=latex --to=html {input_path}"
    return None


def _latex_table_renderer_timeout_s() -> int:
    return _env_int("LATEX_TABLE_RENDER_TIMEOUT_S", 20)


def _wrap_latex_table_fragment_for_renderer(text: str) -> str:
    cleaned = strip_code_fences(text)
    if not cleaned:
        return cleaned
    if re.search(r"\\documentclass\b", cleaned, re.IGNORECASE):
        return cleaned
    package_names = [
        "array",
        "booktabs",
        "graphicx",
        "longtable",
        "makecell",
        "multirow",
        "nicematrix",
        "tabularray",
        "tabularx",
        "tabulary",
        "threeparttable",
        "ulem",
        "xcolor",
    ]
    preamble = "\n".join(f"\\usepackage{{{package_name}}}" for package_name in package_names)
    return (
        "\\documentclass{article}\n"
        f"{preamble}\n"
        "\\begin{document}\n"
        f"{cleaned}\n"
        "\\end{document}\n"
    )


def _extract_best_html_table_fragment(rendered_html: str) -> Optional[str]:
    candidates = _HTML_TABLE_FRAGMENT_RE.findall(rendered_html or "")
    if not candidates:
        return None

    def candidate_score(fragment: str) -> int:
        visible_text = re.sub(r"<[^>]+>", " ", fragment)
        return len(normalize_text(html.unescape(visible_text)))

    best_fragment = max(candidates, key=candidate_score)
    return normalize_text(best_fragment) or None


def _maybe_render_latex_tabular_with_external_renderer(text: str) -> Optional[str]:
    cleaned = strip_code_fences(text)
    if not cleaned or _HTML_TABLE_RE.search(cleaned) or not _looks_like_latex_table_markup(cleaned):
        return None

    command_template = _latex_table_renderer_command_template()
    if not command_template:
        return None

    with TemporaryDirectory(prefix="latex_table_renderer_") as tmpdir:
        tmpdir_path = Path(tmpdir)
        input_path = tmpdir_path / "table.tex"
        output_path = tmpdir_path / "table.html"
        input_path.write_text(_wrap_latex_table_fragment_for_renderer(cleaned), encoding="utf-8")
        try:
            completed = subprocess.run(
                command_template.format(
                    input_path=shlex.quote(str(input_path)),
                    output_path=shlex.quote(str(output_path)),
                ),
                shell=True,
                capture_output=True,
                text=True,
                timeout=_latex_table_renderer_timeout_s(),
            )
        except (OSError, subprocess.SubprocessError):
            return None
        if completed.returncode != 0:
            return None

        rendered_html = ""
        if output_path.exists():
            rendered_html = output_path.read_text(encoding="utf-8", errors="replace")
        if not rendered_html:
            rendered_html = completed.stdout or ""
        return _extract_best_html_table_fragment(rendered_html)


def maybe_convert_latex_tabular_to_html(text: str) -> Optional[str]:
    cleaned = strip_code_fences(text)
    if not cleaned or _HTML_TABLE_RE.search(cleaned):
        return None
    if not _looks_like_latex_table_markup(cleaned):
        return None

    rendered_html = _maybe_render_latex_tabular_with_external_renderer(cleaned)
    if rendered_html:
        return rendered_html

    best_rendered_html: Optional[str] = None
    best_score = 0.0
    for candidate in _extract_latex_table_candidates(cleaned):
        rows = _parse_latex_tabular_body(candidate["body"])
        if not rows:
            continue
        source_text = str(candidate["source"])
        context_start = max(0, int(candidate["start"]) - 600)
        context_end = min(len(cleaned), int(candidate["end"]) + 600)
        context_text = cleaned[context_start:context_end]
        caption_html = _extract_latex_caption_html(source_text) or _extract_latex_caption_html(context_text)
        notes_html = _extract_latex_tablenotes_html(source_text) or _extract_latex_tablenotes_html(context_text)
        score = _latex_table_score(rows, caption_html=caption_html, notes_html=notes_html)
        if score > best_score:
            best_rendered_html = _render_latex_table_html(
                rows,
                caption_html=caption_html,
                notes_html=notes_html,
            )
            best_score = score

    if not best_rendered_html:
        return None

    return best_rendered_html


def _env_int(name: str, default: int) -> int:
    raw_value = os.getenv(name, "").strip()
    if not raw_value:
        return default
    try:
        return max(1, int(raw_value))
    except ValueError:
        return default


def _env_float(
    name: str,
    default: float,
    *,
    min_value: Optional[float] = None,
    max_value: Optional[float] = None,
) -> float:
    raw_value = os.getenv(name, "").strip()
    if not raw_value:
        value = float(default)
    else:
        try:
            value = float(raw_value)
        except ValueError:
            value = float(default)
    if min_value is not None:
        value = max(float(min_value), value)
    if max_value is not None:
        value = min(float(max_value), value)
    return value


def _env_flag(name: str, default: str = "0") -> bool:
    return os.getenv(name, default).strip().lower() in {"1", "true", "yes", "on"}


def _env_nonnegative_int(name: str, default: int) -> int:
    raw_value = os.getenv(name, "").strip()
    if not raw_value:
        return default
    try:
        return max(0, int(raw_value))
    except ValueError:
        return default


def _table_ocr_normalized_max_image_pixels() -> int:
    fallback = _env_nonnegative_int("TABLE_OCR_MAX_IMAGE_PIXELS", 2_000_000)
    return _env_nonnegative_int("TABLE_OCR_NORMALIZED_MAX_IMAGE_PIXELS", fallback)


def _table_ocr_allow_backend_image_resize() -> bool:
    return _env_flag("TABLE_OCR_ALLOW_BACKEND_IMAGE_RESIZE", "0")


def load_module_from_path(module_name: str, path: Path):
    spec = importlib.util.spec_from_file_location(module_name, path)
    if spec is None or spec.loader is None:
        raise RuntimeError(f"Unable to load module from {path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


@lru_cache(maxsize=1)
def load_sec_parser_module():
    sec_parser_dir = ROOT / "sec_parser"
    if not sec_parser_dir.exists():
        raise RuntimeError(f"Expected sec_parser directory at {sec_parser_dir}")
    dir_str = str(sec_parser_dir)
    if dir_str not in sys.path:
        sys.path.insert(0, dir_str)
    import sec_parser as sec_parser_mod

    return sec_parser_mod


class TableOCRRemoteResponseError(RuntimeError):
    def __init__(
        self,
        message: str,
        *,
        response_payload: Optional[Dict[str, Any]] = None,
        details: Optional[Dict[str, Any]] = None,
    ):
        super().__init__(message)
        self.response_payload = response_payload or {}
        self.details = details or {}


class TableOCROpenRouterResponseError(TableOCRRemoteResponseError):
    pass


class TableOCRRemoteChatClient:
    provider_label = "Remote OCR"
    response_error_cls = TableOCRRemoteResponseError
    api_key_env_name = ""
    model_id_env_name = ""
    base_url_env_name = ""
    reasoning_level_env_name = ""
    default_base_url = ""
    require_api_key = True

    def __init__(
        self,
        *,
        api_key: Optional[str] = None,
        model_id: Optional[str] = None,
        base_url: Optional[str] = None,
        reasoning_level: Optional[str] = None,
        timeout_s: int = 180,
    ):
        api_key_value = api_key
        if api_key_value is None and self.api_key_env_name:
            api_key_value = os.getenv(self.api_key_env_name, "")
        self.api_key = normalize_text(api_key_value or "")

        model_id_value = model_id
        if model_id_value is None and self.model_id_env_name:
            model_id_value = os.getenv(self.model_id_env_name, "")
        self.model_id = normalize_text(model_id_value or "")

        base_url_value = base_url
        if base_url_value is None and self.base_url_env_name:
            base_url_value = os.getenv(self.base_url_env_name, self.default_base_url)
        self.base_url = normalize_text(base_url_value or self.default_base_url).rstrip("/")

        reasoning_level_value = reasoning_level
        if reasoning_level_value is None and self.reasoning_level_env_name:
            reasoning_level_value = os.getenv(self.reasoning_level_env_name, "")
        self.reasoning_level = normalize_text(reasoning_level_value or "")
        self.timeout_s = timeout_s

        if self.require_api_key and not self.api_key:
            raise RuntimeError(f"Missing {self.api_key_env_name} for {self.provider_label} OCR transcription.")
        if not self.model_id:
            raise RuntimeError(f"Missing {self.provider_label} OCR model id.")
        if not self.base_url:
            raise RuntimeError(f"Missing {self.provider_label} OCR base URL.")

        self.session = requests.Session()
        self.headers = self._build_headers()

    def _build_headers(self) -> Dict[str, str]:
        headers = {
            "Content-Type": "application/json",
        }
        if self.api_key:
            headers["Authorization"] = f"Bearer {self.api_key}"
        return headers

    def _augment_request_body(self, body: Dict[str, Any], *, include_reasoning: bool) -> None:
        del body, include_reasoning

    def _raise_request_error(
        self,
        message: str,
        *,
        response_payload: Optional[Dict[str, Any]] = None,
        details: Optional[Dict[str, Any]] = None,
    ) -> None:
        raise self.response_error_cls(
            message,
            response_payload=response_payload,
            details=details,
        )

    def chat_completion(
        self,
        *,
        messages: List[Dict[str, Any]],
        max_tokens: int = 4096,
        temperature: float = 0.0,
        progress_label: str = "",
        progress_handler: ProgressHandler = None,
    ) -> Dict[str, Any]:
        url = f"{self.base_url}/chat/completions"
        body: Dict[str, Any] = {
            "model": self.model_id,
            "messages": messages,
            "max_tokens": max_tokens,
            "temperature": temperature,
        }
        self._augment_request_body(body, include_reasoning=False)

        if progress_label:
            emit_progress(
                f"{progress_label} | model {self.model_id}",
                progress_handler=progress_handler,
            )
        try:
            response = self.session.post(
                url,
                headers=self.headers,
                json=body,
                timeout=self.timeout_s,
            )
        except requests.RequestException as exc:
            self._raise_request_error(
                f"{self.provider_label} request failed: {exc}",
                details={
                    "status_code": None,
                    "model_id": self.model_id,
                },
            )
        if response.status_code >= 400:
            response_payload: Optional[Dict[str, Any]] = None
            try:
                decoded_payload = response.json()
                if isinstance(decoded_payload, dict):
                    response_payload = decoded_payload
            except ValueError:
                response_payload = None
            self._raise_request_error(
                f"{self.provider_label} HTTP {response.status_code}: {response.text[:1500]}",
                response_payload=response_payload,
                details={
                    "status_code": response.status_code,
                    "model_id": self.model_id,
                },
            )
        if progress_label:
            emit_progress(
                f"{progress_label} | response received",
                progress_handler=progress_handler,
            )
        return response.json()

    def chat_completion_streaming(
        self,
        *,
        messages: List[Dict[str, Any]],
        max_tokens: int = 4096,
        temperature: float = 0.0,
        progress_label: str = "",
        progress_handler: ProgressHandler = None,
        include_reasoning: bool = False,
    ) -> Dict[str, Any]:
        url = f"{self.base_url}/chat/completions"
        body: Dict[str, Any] = {
            "model": self.model_id,
            "messages": messages,
            "max_tokens": max_tokens,
            "temperature": temperature,
            "stream": True,
            "stream_options": {"include_usage": True},
        }
        self._augment_request_body(body, include_reasoning=include_reasoning)

        if progress_label:
            emit_progress(
                f"{progress_label} | model {self.model_id}",
                progress_handler=progress_handler,
            )
        started_at = time.perf_counter()
        try:
            response = self.session.post(
                url,
                headers=self.headers,
                json=body,
                timeout=self.timeout_s,
                stream=True,
            )
        except requests.RequestException as exc:
            self._raise_request_error(
                f"{self.provider_label} request failed: {exc}",
                details={
                    "status_code": None,
                    "model_id": self.model_id,
                },
            )
        if response.status_code >= 400:
            response_payload: Optional[Dict[str, Any]] = None
            response_text = ""
            try:
                response_payload = response.json()
                response_text = json.dumps(response_payload, ensure_ascii=False)
            except ValueError:
                try:
                    response_text = response.text
                except Exception:
                    response_text = ""
            finally:
                response.close()
            self._raise_request_error(
                f"{self.provider_label} HTTP {response.status_code}: {response_text[:1500]}",
                response_payload=response_payload,
                details={
                    "status_code": response.status_code,
                    "model_id": self.model_id,
                },
            )
        if progress_label:
            emit_progress(
                f"{progress_label} | response received",
                progress_handler=progress_handler,
            )
        content_parts: List[str] = []
        refusal_parts: List[str] = []
        tool_calls: List[Any] = []
        provider_payload: Any = None
        usage_payload: Dict[str, Any] = {}
        finish_reason = ""
        message_role = ""
        first_content_latency_s: Optional[float] = None
        first_reasoning_latency_s: Optional[float] = None
        last_reasoning_latency_s: Optional[float] = None
        saw_reasoning = False

        def process_event_payload(event_payload: Dict[str, Any]) -> None:
            nonlocal provider_payload, usage_payload, finish_reason, message_role
            nonlocal first_content_latency_s, first_reasoning_latency_s, last_reasoning_latency_s, saw_reasoning
            if provider_payload is None and event_payload.get("provider") is not None:
                provider_payload = event_payload.get("provider")
            event_usage = event_payload.get("usage")
            if isinstance(event_usage, dict):
                usage_payload = event_usage
            choices = event_payload.get("choices")
            first_choice = choices[0] if isinstance(choices, list) and choices else {}
            if not isinstance(first_choice, dict):
                return
            finish_reason = normalize_text(first_choice.get("finish_reason", "")) or finish_reason
            delta = first_choice.get("delta")
            if not isinstance(delta, dict):
                delta = {}
            if not message_role:
                message_role = normalize_text(delta.get("role", "")) or message_role
            delta_tool_calls = delta.get("tool_calls")
            if isinstance(delta_tool_calls, list):
                tool_calls.extend(delta_tool_calls)
            delta_refusal = delta.get("refusal")
            if isinstance(delta_refusal, str) and delta_refusal.strip():
                refusal_parts.append(delta_refusal)
            reasoning_payload = (
                delta.get("reasoning_details")
                or delta.get("reasoning")
                or delta.get("reasoning_content")
                or first_choice.get("reasoning_details")
                or first_choice.get("reasoning")
                or first_choice.get("reasoning_content")
            )
            if reasoning_payload:
                saw_reasoning = True
                reasoning_latency_s = time.perf_counter() - started_at
                if first_reasoning_latency_s is None:
                    first_reasoning_latency_s = reasoning_latency_s
                last_reasoning_latency_s = reasoning_latency_s
            content_piece = extract_text_from_openrouter_content(delta.get("content"))
            if content_piece is None:
                message_payload = first_choice.get("message")
                if isinstance(message_payload, dict):
                    content_piece = extract_text_from_openrouter_content(message_payload.get("content"))
            if content_piece is not None:
                if first_content_latency_s is None:
                    first_content_latency_s = time.perf_counter() - started_at
                content_parts.append(content_piece)

        current_event_lines: List[str] = []
        with contextlib.closing(response):
            for raw_line in response.iter_lines(decode_unicode=True):
                if raw_line is None:
                    continue
                line = raw_line if isinstance(raw_line, str) else raw_line.decode("utf-8", errors="replace")
                if line.startswith(":"):
                    continue
                if line == "":
                    if current_event_lines:
                        payload_text = "\n".join(current_event_lines).strip()
                        current_event_lines = []
                        if payload_text and payload_text != "[DONE]":
                            try:
                                decoded_payload = json.loads(payload_text)
                            except json.JSONDecodeError:
                                decoded_payload = None
                            if isinstance(decoded_payload, dict):
                                process_event_payload(decoded_payload)
                    continue
                if line.startswith("data:"):
                    current_event_lines.append(line[len("data:") :].lstrip())
            if current_event_lines:
                payload_text = "\n".join(current_event_lines).strip()
                if payload_text and payload_text != "[DONE]":
                    try:
                        decoded_payload = json.loads(payload_text)
                    except json.JSONDecodeError:
                        decoded_payload = None
                    if isinstance(decoded_payload, dict):
                        process_event_payload(decoded_payload)

        content_text = "".join(content_parts) if content_parts else None
        total_latency_s = time.perf_counter() - started_at

        return {
            "choices": [
                {
                    "message": {
                        "role": message_role or "assistant",
                        "content": content_text,
                        "tool_calls": tool_calls,
                        "refusal": "".join(refusal_parts) if refusal_parts else None,
                    },
                    "finish_reason": finish_reason or None,
                }
            ],
            "provider": provider_payload,
            "usage": usage_payload or None,
            "_stream_timing": {
                "first_content_latency_s": first_content_latency_s,
                "first_reasoning_latency_s": first_reasoning_latency_s,
                "last_reasoning_latency_s": last_reasoning_latency_s,
                "thinking_latency_s": (
                    last_reasoning_latency_s
                    if (saw_reasoning and last_reasoning_latency_s is not None and content_text is not None)
                    else None
                ),
                "total_latency_s": max(0.0, float(total_latency_s)),
                "saw_reasoning": bool(saw_reasoning),
            },
        }


class TableOCROpenRouterClient(TableOCRRemoteChatClient):
    provider_label = "OpenRouter"
    response_error_cls = TableOCROpenRouterResponseError
    api_key_env_name = "OPENROUTER_API_KEY"
    model_id_env_name = "OPENROUTER_MODEL_ID"
    base_url_env_name = "OPENROUTER_BASE_URL"
    reasoning_level_env_name = "OPENROUTER_REASONING_LEVEL"
    default_base_url = "https://openrouter.ai/api/v1"

    def _build_headers(self) -> Dict[str, str]:
        headers = super()._build_headers()
        headers["HTTP-Referer"] = "http://localhost"
        headers["X-Title"] = "OCR-Bench"
        return headers

    def _augment_request_body(self, body: Dict[str, Any], *, include_reasoning: bool) -> None:
        if self.reasoning_level:
            body["reasoning"] = {
                "effort": self.reasoning_level,
                "exclude": (not include_reasoning),
            }


class TableOCRQwenClient(TableOCRRemoteChatClient):
    provider_label = "Qwen OCR"
    api_key_env_name = "QWEN_OCR_API_KEY"
    model_id_env_name = "QWEN_OCR_MODEL_ID"
    base_url_env_name = "QWEN_OCR_BASE_URL"
    default_base_url = "http://127.0.0.1:8000/v1"
    require_api_key = False

    def _augment_request_body(self, body: Dict[str, Any], *, include_reasoning: bool) -> None:
        if include_reasoning or _env_flag("QWEN_OCR_PRESERVE_THINKING", "1"):
            body["chat_template_kwargs"] = {
                "preserve_thinking": True,
            }


class TableOCRGemma4VLLMClient(TableOCRRemoteChatClient):
    provider_label = "Gemma 4 vLLM"
    api_key_env_name = "GEMMA4_VLLM_API_KEY"
    model_id_env_name = "GEMMA4_VLLM_MODEL_ID"
    base_url_env_name = "GEMMA4_VLLM_BASE_URL"
    default_base_url = "http://127.0.0.1:8000/v1"
    require_api_key = False

    def _augment_request_body(self, body: Dict[str, Any], *, include_reasoning: bool) -> None:
        del include_reasoning
        if _env_flag("GEMMA4_VLLM_ENABLE_THINKING", "1"):
            body["chat_template_kwargs"] = {
                "enable_thinking": True,
            }


class TableOCRGemma4LlamaCppClient(TableOCRRemoteChatClient):
    provider_label = "Gemma 4 llama.cpp"
    api_key_env_name = "GEMMA4_LLAMA_CPP_API_KEY"
    model_id_env_name = "GEMMA4_LLAMA_CPP_MODEL_ID"
    base_url_env_name = "GEMMA4_LLAMA_CPP_BASE_URL"
    default_base_url = "http://127.0.0.1:8080/v1"
    require_api_key = False


def extract_text_from_openrouter_content(content: Any) -> Optional[str]:
    if isinstance(content, str):
        normalized = normalize_text(content)
        return content if normalized else None
    if not isinstance(content, list):
        return None

    parts: List[str] = []
    for item in content:
        if isinstance(item, str):
            parts.append(item)
            continue
        if not isinstance(item, dict):
            continue
        for key in ("text", "content", "value"):
            value = item.get(key)
            if isinstance(value, str) and value.strip():
                parts.append(value)
                break

    joined = "\n".join(part for part in parts if normalize_text(part))
    return joined or None


def estimate_openrouter_thinking_latency_s(
    total_latency_s: float,
    *,
    reasoning_tokens: Optional[int],
    completion_tokens: Optional[int],
) -> Optional[float]:
    if not isinstance(total_latency_s, (int, float)) or total_latency_s < 0:
        return None
    if not isinstance(reasoning_tokens, int) or reasoning_tokens <= 0:
        return None
    if not isinstance(completion_tokens, int) or completion_tokens <= 0:
        return None
    ratio = max(0.0, min(1.0, float(reasoning_tokens) / float(completion_tokens)))
    return float(total_latency_s) * ratio


def summarize_openrouter_chat_response(response: Dict[str, Any]) -> Dict[str, Any]:
    choices = response.get("choices")
    first_choice = choices[0] if isinstance(choices, list) and choices else {}
    if not isinstance(first_choice, dict):
        first_choice = {}

    message = first_choice.get("message")
    if not isinstance(message, dict):
        message = {}

    provider = response.get("provider")
    if isinstance(provider, dict):
        provider_summary = (
            provider.get("name")
            or provider.get("provider_name")
            or normalize_text(json.dumps(provider, ensure_ascii=False))
        )
    else:
        provider_summary = normalize_text(provider)

    tool_calls = message.get("tool_calls")
    tool_call_count = len(tool_calls) if isinstance(tool_calls, list) else 0
    content = message.get("content")
    refusal = message.get("refusal")
    finish_reason = normalize_text(first_choice.get("finish_reason", ""))
    usage = response.get("usage")
    usage_payload = usage if isinstance(usage, dict) else {}
    completion_tokens_raw = usage_payload.get("completion_tokens")
    if not isinstance(completion_tokens_raw, (int, float)):
        completion_tokens_raw = usage_payload.get("output_tokens")
    completion_tokens = int(completion_tokens_raw) if isinstance(completion_tokens_raw, (int, float)) else None
    completion_details = usage_payload.get("completion_tokens_details")
    if not isinstance(completion_details, dict):
        completion_details = {}
    reasoning_tokens_raw = completion_details.get("reasoning_tokens")
    reasoning_tokens = int(reasoning_tokens_raw) if isinstance(reasoning_tokens_raw, (int, float)) else None
    stream_timing = response.get("_stream_timing")
    if not isinstance(stream_timing, dict):
        stream_timing = {}
    thinking_latency_s = stream_timing.get("thinking_latency_s")
    if not isinstance(thinking_latency_s, (int, float)):
        thinking_latency_s = None
    total_latency_s = stream_timing.get("total_latency_s")
    if not isinstance(total_latency_s, (int, float)):
        total_latency_s = None
    first_content_latency_s = stream_timing.get("first_content_latency_s")
    if not isinstance(first_content_latency_s, (int, float)):
        first_content_latency_s = None

    return {
        "content": content,
        "content_type": type(content).__name__,
        "finish_reason": finish_reason or None,
        "provider": provider_summary or None,
        "tool_call_count": tool_call_count,
        "tool_calls": tool_calls if isinstance(tool_calls, list) else [],
        "refusal": refusal,
        "message_role": normalize_text(message.get("role", "")) or None,
        "completion_tokens": completion_tokens,
        "reasoning_tokens": reasoning_tokens,
        "thinking_latency_s": (max(0.0, float(thinking_latency_s)) if thinking_latency_s is not None else None),
        "total_latency_s": (max(0.0, float(total_latency_s)) if total_latency_s is not None else None),
        "first_content_latency_s": (max(0.0, float(first_content_latency_s)) if first_content_latency_s is not None else None),
    }


def openrouter_ocr_model_ids() -> set[str]:
    return {
        value.strip()
        for value in [
            os.getenv("OPENROUTER_MODEL_ID", ""),
            os.getenv("TESTMODEL", ""),
        ]
        if value and value.strip()
    }


def default_openrouter_retry_model_ids(model_id: str) -> List[str]:
    normalized = normalize_text(model_id)
    if normalized.endswith(":free"):
        paid_slug = normalized[: -len(":free")]
        return [paid_slug] if paid_slug else []
    return []


def default_openrouter_ocr_max_attempts() -> int:
    return _env_int("OPENROUTER_OCR_MAX_ATTEMPTS", 3)


def build_openrouter_retry_chain(model_id: str) -> List[str]:
    chain: List[str] = []
    for candidate in [normalize_text(model_id), *default_openrouter_retry_model_ids(model_id)]:
        if candidate and candidate not in chain:
            chain.append(candidate)
    return chain


def build_openrouter_attempt_plan(model_id: str, *, max_attempts: int) -> List[str]:
    retry_chain = build_openrouter_retry_chain(model_id)
    if not retry_chain:
        return []
    attempt_limit = max(1, int(max_attempts))
    plan: List[str] = []
    for candidate in retry_chain:
        if len(plan) >= attempt_limit:
            break
        plan.append(candidate)
    while len(plan) < attempt_limit:
        plan.append(retry_chain[-1])
    return plan


def default_firered_model_id() -> str:
    return normalize_text(os.getenv("FIRERED_MODEL_ID", "FireRedTeam/FireRed-OCR")) or "FireRedTeam/FireRed-OCR"


def default_qianfan_ocr_model_id() -> str:
    return normalize_text(os.getenv("QIANFAN_OCR_MODEL_ID", _QIANFAN_OCR_DEFAULT_MODEL_ID)) or _QIANFAN_OCR_DEFAULT_MODEL_ID


def default_glm_ocr_model_id() -> str:
    return normalize_text(os.getenv("GLM_OCR_MODEL_ID", _GLM_OCR_DEFAULT_MODEL_ID)) or _GLM_OCR_DEFAULT_MODEL_ID


def default_paddleocr_vl_model_id() -> str:
    return normalize_text(os.getenv("PADDLEOCR_VL_MODEL_ID", _PADDLEOCR_VL_DEFAULT_MODEL_ID)) or _PADDLEOCR_VL_DEFAULT_MODEL_ID


def default_got_ocr_model_id() -> str:
    return normalize_text(os.getenv("GOT_OCR_MODEL_ID", _GOT_OCR_DEFAULT_MODEL_ID)) or _GOT_OCR_DEFAULT_MODEL_ID


def default_monkeyocr_model_id() -> str:
    return normalize_text(os.getenv("MONKEYOCR_MODEL_ID", _MONKEYOCR_DEFAULT_MODEL_ID)) or _MONKEYOCR_DEFAULT_MODEL_ID


def default_qwen_ocr_model_id() -> str:
    return normalize_text(os.getenv("QWEN_OCR_MODEL_ID", _QWEN_OCR_DEFAULT_MODEL_ID)) or _QWEN_OCR_DEFAULT_MODEL_ID


def default_gemma4_hf_model_id() -> str:
    return (
        normalize_text(os.getenv("GEMMA4_HF_MODEL_ID", _GEMMA4_VLLM_DEFAULT_MODEL_ID))
        or _GEMMA4_VLLM_DEFAULT_MODEL_ID
    )


def default_gemma4_vllm_model_id() -> str:
    return (
        normalize_text(os.getenv("GEMMA4_VLLM_MODEL_ID", _GEMMA4_VLLM_DEFAULT_MODEL_ID))
        or _GEMMA4_VLLM_DEFAULT_MODEL_ID
    )


def default_gemma4_llamacpp_model_id() -> str:
    return (
        normalize_text(os.getenv("GEMMA4_LLAMA_CPP_MODEL_ID", _GEMMA4_LLAMA_CPP_DEFAULT_MODEL_ID))
        or _GEMMA4_LLAMA_CPP_DEFAULT_MODEL_ID
    )


def resolve_firered_model_id(model_id: Optional[str]) -> str:
    normalized = normalize_text(model_id or "")
    if not normalized:
        return default_firered_model_id()
    if normalized.lower() in {"firered", "firered-local", "local-firered"}:
        return default_firered_model_id()
    return normalized


def resolve_qianfan_model_id(model_id: Optional[str]) -> str:
    normalized = normalize_text(model_id or "")
    if not normalized:
        return default_qianfan_ocr_model_id()
    if normalized.lower() in {"qianfan", "qianfan-ocr"}:
        return default_qianfan_ocr_model_id()
    return normalized


def resolve_glm_ocr_model_id(model_id: Optional[str]) -> str:
    normalized = normalize_text(model_id or "")
    if not normalized:
        return default_glm_ocr_model_id()
    if normalized.lower() in {"glm-ocr", "glmocr"}:
        return default_glm_ocr_model_id()
    return normalized


def resolve_paddleocr_vl_model_id(model_id: Optional[str]) -> str:
    normalized = normalize_text(model_id or "")
    if not normalized:
        return default_paddleocr_vl_model_id()
    if normalized.lower() in {"paddleocr-vl", "paddleocr-vl-1.5", "paddleocr_vl"}:
        return default_paddleocr_vl_model_id()
    return normalized


def resolve_got_ocr_model_id(model_id: Optional[str]) -> str:
    normalized = normalize_text(model_id or "")
    if not normalized:
        return default_got_ocr_model_id()
    if normalized.lower() in {"got-ocr", "got-ocr2", "got-ocr2_0", "got_ocr", "gotocr", "gotocr2"}:
        return default_got_ocr_model_id()
    return normalized


def resolve_monkeyocr_model_id(model_id: Optional[str]) -> str:
    normalized = normalize_text(model_id or "")
    if not normalized:
        return default_monkeyocr_model_id()
    if normalized.lower() in {"monkeyocr", "monkeyocr-pro-3b", "monkeyocr_pro_3b"}:
        return default_monkeyocr_model_id()
    return normalized


def resolve_qwen_ocr_model_id(model_id: Optional[str]) -> str:
    normalized = normalize_text(model_id or "")
    if not normalized:
        return default_qwen_ocr_model_id()
    if normalized.lower() in {
        "qwen_ocr",
        "qwen-ocr",
        "qwenocr",
        "qwen3.5-35b-a3b",
        "qwen3.5-35b-a3b-fp8",
        "qwen3.6-35b-a3b",
        "qwen3.6-35b-a3b-fp8",
    }:
        return default_qwen_ocr_model_id()
    return normalized


def resolve_gemma4_vllm_model_id(model_id: Optional[str]) -> str:
    normalized = normalize_text(model_id or "")
    if not normalized:
        return default_gemma4_vllm_model_id()
    if normalized.lower().replace("_", "-") in {
        "gemma4-vllm",
        "gemma-4-vllm",
        "gemma4-26b-vllm",
        "gemma-4-26b-vllm",
        "gemma4-26b-a4b",
        "gemma-4-26b-a4b",
        "gemma4-26b-a4b-it",
        "gemma-4-26b-a4b-it",
    }:
        return default_gemma4_vllm_model_id()
    return normalized


def resolve_gemma4_hf_model_id(model_id: Optional[str]) -> str:
    normalized = normalize_text(model_id or "")
    if not normalized:
        return default_gemma4_hf_model_id()
    if normalized.lower().replace("_", "-") in {
        "gemma4",
        "gemma-4",
        "gemma4-hf",
        "gemma-4-hf",
        "gemma4-local",
        "gemma-4-local",
        "gemma4-huggingface",
        "gemma-4-huggingface",
        "gemma4-transformers",
        "gemma-4-transformers",
    }:
        return default_gemma4_hf_model_id()
    return normalized


def resolve_gemma4_llamacpp_model_id(model_id: Optional[str]) -> str:
    normalized = normalize_text(model_id or "")
    if not normalized:
        return default_gemma4_llamacpp_model_id()
    if normalized.lower().replace("_", "-") in {
        "gemma4",
        "gemma-4",
        "gemma4-26b",
        "gemma-4-26b",
        "gemma4-26b-it",
        "gemma-4-26b-it",
        "gemma4-llamacpp",
        "gemma-4-llamacpp",
        "gemma4-26b-llamacpp",
        "gemma-4-26b-llamacpp",
        "gemma4-26b-llama-cpp",
        "gemma-4-26b-llama-cpp",
        "gemma4-llama-cpp",
        "gemma-4-llama-cpp",
        "llamacpp-gemma4-26b",
        "llama-cpp-gemma4-26b",
        "llamacpp-gemma4",
        "llama-cpp-gemma4",
    }:
        return default_gemma4_llamacpp_model_id()
    return normalized


def _resolve_monkeyocr_entrypoint(repo_path: Path) -> Path:
    for candidate in (
        repo_path / "parse.py",
        repo_path / "infer.py",
        repo_path / "inference.py",
        repo_path / "run.py",
        repo_path / "demo.py",
        repo_path / "app.py",
    ):
        if candidate.exists():
            return candidate
    raise RuntimeError(
        "MonkeyOCR backend needs either MONKEYOCR_RUN_COMMAND or one of parse.py/infer.py/inference.py/run.py/demo.py/app.py in MONKEYOCR_REPO_DIR."
    )


def _extract_monkeyocr_text_payload(payload: Any, *, _depth: int = 0) -> Optional[str]:
    if _depth > 8:
        return None
    if isinstance(payload, str):
        normalized = normalize_text(payload)
        return payload if normalized else None
    if isinstance(payload, dict):
        preferred_keys = (
            "html",
            "markdown",
            "md",
            "table_html",
            "table_markdown",
            "output_html",
            "output_markdown",
            "prediction",
            "pred",
            "result",
            "response",
            "text",
            "content",
            "output",
            "ocr",
            "table",
            "data",
        )
        for key in preferred_keys:
            extracted = _extract_monkeyocr_text_payload(payload.get(key), _depth=_depth + 1)
            if extracted:
                return extracted
        for value in payload.values():
            extracted = _extract_monkeyocr_text_payload(value, _depth=_depth + 1)
            if extracted:
                return extracted
        return None
    if isinstance(payload, list):
        candidates = [
            extracted
            for extracted in (
                _extract_monkeyocr_text_payload(item, _depth=_depth + 1)
                for item in payload
            )
            if extracted
        ]
        if not candidates:
            return None
        return max(candidates, key=lambda item: len(normalize_text(re.sub(r"<[^>]+>", " ", item))))
    return None


def _coerce_monkeyocr_output_text(raw_text: str) -> str:
    text = str(raw_text or "")
    normalized = normalize_text(text)
    if not normalized:
        return ""
    if normalized.startswith("{") or normalized.startswith("["):
        try:
            payload = json.loads(normalized)
        except Exception:
            return text
        extracted = _extract_monkeyocr_text_payload(payload)
        if extracted:
            return extracted
    return text


def _read_monkeyocr_output_artifact(path: Path) -> str:
    suffix = path.suffix.lower()
    text = path.read_text(encoding="utf-8", errors="replace")
    if suffix == ".json":
        try:
            payload = json.loads(text)
        except Exception:
            return _coerce_monkeyocr_output_text(text)
        extracted = _extract_monkeyocr_text_payload(payload)
        return extracted or ""
    return _coerce_monkeyocr_output_text(text)


def firered_mps_retry_pixel_limits() -> List[int]:
    raw_value = normalize_text(os.getenv("FIRERED_MPS_RETRY_MAX_IMAGE_PIXELS", "1500000,1000000"))
    limits: List[int] = []
    seen: set[int] = set()
    for piece in raw_value.split(","):
        try:
            value = max(0, int(piece.strip()))
        except ValueError:
            continue
        if value <= 0 or value in seen:
            continue
        limits.append(value)
        seen.add(value)
    return limits


def default_deepseek_ocr_model_id() -> str:
    return normalize_text(os.getenv("DEEPSEEK_OCR_MODEL_ID", "deepseek-ai/DeepSeek-OCR-2")) or "deepseek-ai/DeepSeek-OCR-2"


def default_mistral_ocr_model_id() -> str:
    return normalize_text(os.getenv("MISTRAL_OCR_MODEL_ID", "mistral-ocr-latest")) or "mistral-ocr-latest"


def default_pdf_page_ocr_model_id() -> str:
    candidates = [
        normalize_text(os.getenv("PDF_PAGE_OCR_MODEL_ID", "")),
        normalize_text(os.getenv("MISTRAL_OCR_MODEL_ID", "")),
        default_mistral_ocr_model_id(),
    ]
    for candidate in candidates:
        if candidate:
            return candidate
    return default_mistral_ocr_model_id()


def _mistral_ocr_table_format() -> str:
    value = normalize_text(os.getenv("MISTRAL_OCR_TABLE_FORMAT", "html")).lower()
    if value in {"markdown", "html"}:
        return value
    return "html"


def _deepseek_ocr_local_dir() -> Optional[str]:
    value = normalize_text(os.getenv("DEEPSEEK_OCR_MODEL_LOCAL_DIR", ""))
    return value or None


def _deepseek_ocr_cache_dir() -> Optional[str]:
    value = normalize_text(os.getenv("DEEPSEEK_OCR_MODEL_CACHE_DIR", ""))
    return value or None


def _deepseek_ocr_revision() -> Optional[str]:
    value = normalize_text(os.getenv("DEEPSEEK_OCR_MODEL_REVISION", ""))
    return value or None


def _deepseek_ocr_local_files_only() -> bool:
    return _env_flag("DEEPSEEK_OCR_LOCAL_FILES_ONLY")


def _deepseek_ocr_trust_remote_code() -> bool:
    return _env_flag("DEEPSEEK_OCR_TRUST_REMOTE_CODE", "1")


def _deepseek_ocr_device() -> str:
    return normalize_text(os.getenv("DEEPSEEK_OCR_DEVICE", "auto")).lower() or "auto"


def _deepseek_ocr_device_map() -> str:
    return normalize_text(os.getenv("DEEPSEEK_OCR_DEVICE_MAP", "auto")) or "auto"


def _deepseek_ocr_max_new_tokens() -> int:
    return _env_int("DEEPSEEK_OCR_MAX_NEW_TOKENS", 4096)


def _deepseek_ocr_max_image_pixels() -> int:
    return _env_int("DEEPSEEK_OCR_MAX_IMAGE_PIXELS", 0)


def _backend_env_name(prefix: str, suffix: str) -> str:
    return f"{prefix.upper()}_{suffix.upper()}"


def _backend_model_local_dir(prefix: str) -> Optional[str]:
    value = normalize_text(os.getenv(_backend_env_name(prefix, "MODEL_LOCAL_DIR"), ""))
    return value or None


def _backend_model_cache_dir(prefix: str) -> Optional[str]:
    value = normalize_text(os.getenv(_backend_env_name(prefix, "MODEL_CACHE_DIR"), ""))
    return value or None


def _backend_model_revision(prefix: str) -> Optional[str]:
    value = normalize_text(os.getenv(_backend_env_name(prefix, "MODEL_REVISION"), ""))
    return value or None


def _backend_local_files_only(prefix: str) -> bool:
    return _env_flag(_backend_env_name(prefix, "LOCAL_FILES_ONLY"))


def _backend_trust_remote_code(prefix: str, default: Optional[str] = None) -> bool:
    if default is None:
        # PaddleOCR-VL now has native Transformers support, so remote code should be
        # opt-in there to avoid loading stale/incompatible model-side Python.
        default = "0" if str(prefix or "").upper() == "PADDLEOCR_VL" else "1"
    return _env_flag(_backend_env_name(prefix, "TRUST_REMOTE_CODE"), default)


def _backend_device(prefix: str) -> str:
    return normalize_text(os.getenv(_backend_env_name(prefix, "DEVICE"), "auto")).lower() or "auto"


def _backend_device_map(prefix: str) -> str:
    return normalize_text(os.getenv(_backend_env_name(prefix, "DEVICE_MAP"), "auto")) or "auto"


def _backend_max_new_tokens(prefix: str, default: int = 4096) -> int:
    return _env_int(_backend_env_name(prefix, "MAX_NEW_TOKENS"), default)


def _backend_max_image_pixels(prefix: str, default: int = 0) -> int:
    return _env_int(_backend_env_name(prefix, "MAX_IMAGE_PIXELS"), default)


def _backend_attn_implementation(prefix: str) -> Optional[str]:
    value = normalize_text(os.getenv(_backend_env_name(prefix, "ATTN_IMPLEMENTATION"), ""))
    return value or None


def _select_generic_ocr_runtime(torch, requested: str):
    normalized = normalize_text(requested or "auto").lower() or "auto"
    mps_available = bool(getattr(torch.backends, "mps", None)) and torch.backends.mps.is_available()
    if normalized not in {"auto", "cuda", "mps", "cpu"}:
        raise RuntimeError(
            f"Unsupported OCR device '{requested}'. Expected one of: auto, cuda, mps, cpu."
        )
    if normalized in {"auto", "cuda"} and torch.cuda.is_available():
        return "cuda", torch.bfloat16, True
    if normalized == "cuda":
        raise RuntimeError("CUDA was requested for OCR, but CUDA is not available.")
    if normalized in {"auto", "mps"} and mps_available:
        return "mps", torch.float16, False
    if normalized == "mps":
        raise RuntimeError("MPS was requested for OCR, but MPS is not available.")
    return "cpu", torch.float32, False


def _resolve_generic_model_source(model_id: str, *, env_prefix: str) -> str:
    local_dir = _backend_model_local_dir(env_prefix)
    if not local_dir:
        return model_id
    local_path = Path(local_dir).expanduser()
    if str(local_path).startswith("/content") and not Path("/content").exists():
        raise RuntimeError(
            f"{_backend_env_name(env_prefix, 'MODEL_LOCAL_DIR')} points to '{local_dir}', which looks like a Colab path, "
            "but this process is running outside Colab."
        )
    if not local_path.exists():
        raise RuntimeError(f"{_backend_env_name(env_prefix, 'MODEL_LOCAL_DIR')}='{local_dir}' does not exist.")
    if not local_path.is_dir():
        raise RuntimeError(f"{_backend_env_name(env_prefix, 'MODEL_LOCAL_DIR')}='{local_dir}' is not a directory.")
    return str(local_path)


def _prepare_backend_image(image, *, env_prefix: str, runtime_device: str):
    del runtime_device
    if not _table_ocr_allow_backend_image_resize():
        return image
    max_pixels = _backend_max_image_pixels(env_prefix, 0)
    width, height = image.size
    total_pixels = width * height
    if max_pixels <= 0 or total_pixels <= max_pixels:
        return image
    scale = math.sqrt(float(max_pixels) / float(total_pixels))
    new_width = max(28, int(width * scale))
    new_height = max(28, int(height * scale))
    emit_progress(
        f"Resizing {env_prefix} OCR image from {width}x{height} to {new_width}x{new_height} "
        f"to stay within {max_pixels:,} pixels."
    )
    return image.resize((new_width, new_height))


def _ensure_transformers_dynamic_cache_compatibility() -> None:
    try:
        from transformers.cache_utils import Cache, DynamicCache
    except ImportError:
        return

    def get_seq_length_compat(cache_obj: Any, layer_idx: int = 0) -> int:
        get_seq_length = getattr(cache_obj, "get_seq_length", None)
        if callable(get_seq_length):
            try:
                return int(get_seq_length(layer_idx))
            except TypeError:
                try:
                    return int(get_seq_length())
                except Exception:
                    return 0
            except Exception:
                return 0
        return 0

    def get_max_length_compat(cache_obj: Any, layer_idx: int = 0) -> Optional[int]:
        get_max_cache_shape = getattr(cache_obj, "get_max_cache_shape", None)
        if not callable(get_max_cache_shape):
            return None
        try:
            max_length = get_max_cache_shape(layer_idx)
        except TypeError:
            try:
                max_length = get_max_cache_shape()
            except Exception:
                return None
        except Exception:
            return None
        if not isinstance(max_length, (int, float)):
            return None
        resolved = int(max_length)
        return None if resolved < 0 else resolved

    def install_cache_compatibility_shims(cache_cls: Any) -> None:
        if hasattr(cache_cls, "seen_tokens"):
            seen_tokens_missing = False
        else:
            seen_tokens_missing = True

        if seen_tokens_missing:
            def get_seen_tokens(self) -> int:
                override = getattr(self, "_codex_seen_tokens_override", None)
                if override is not None:
                    try:
                        return int(override)
                    except Exception:
                        return 0
                return get_seq_length_compat(self)

            def set_seen_tokens(self, value: Any) -> None:
                try:
                    self._codex_seen_tokens_override = int(value)
                except Exception:
                    self._codex_seen_tokens_override = value

            setattr(cache_cls, "seen_tokens", property(get_seen_tokens, set_seen_tokens))

        if not hasattr(cache_cls, "get_max_length"):
            def get_max_length(self, layer_idx: int = 0) -> Optional[int]:
                return get_max_length_compat(self, layer_idx=layer_idx)

            setattr(cache_cls, "get_max_length", get_max_length)

        if not hasattr(cache_cls, "get_usable_length"):
            def get_usable_length(self, new_seq_length: int, layer_idx: int = 0) -> int:
                previous_seq_length = get_seq_length_compat(self, layer_idx=layer_idx)
                max_length = get_max_length_compat(self, layer_idx=layer_idx)
                if max_length is not None and previous_seq_length + int(new_seq_length) > max_length:
                    return max(0, max_length - int(new_seq_length))
                return previous_seq_length

            setattr(cache_cls, "get_usable_length", get_usable_length)

    install_cache_compatibility_shims(Cache)
    install_cache_compatibility_shims(DynamicCache)


def _maybe_to_model_device(batch: Any, model_device: Any):
    try:
        return batch.to(model_device)
    except Exception:
        return batch


def _get_batch_item(batch: Any, key: str):
    if isinstance(batch, dict):
        return batch.get(key)
    return getattr(batch, key, None)


def _decode_generated_text(processor: Any, generated_ids: Any, input_ids: Any = None) -> str:
    trimmed_ids = generated_ids
    if input_ids is not None:
        try:
            trimmed_ids = generated_ids[:, input_ids.shape[1] :]
        except Exception:
            trimmed_ids = generated_ids
    decode_targets = [
        processor,
        getattr(processor, "tokenizer", None),
    ]
    for target in decode_targets:
        if target is None or not hasattr(target, "batch_decode"):
            continue
        try:
            decoded = target.batch_decode(
                trimmed_ids,
                skip_special_tokens=True,
                clean_up_tokenization_spaces=False,
            )
            if isinstance(decoded, list) and decoded:
                return decoded[0]
        except Exception:
            continue
    raise RuntimeError("Could not decode OCR model output with the loaded processor/tokenizer.")


def _build_generic_messages(prompt_text: str, page_image) -> List[Dict[str, Any]]:
    return [
        {
            "role": "user",
            "content": [
                {"type": "image", "image": page_image},
                {"type": "text", "text": prompt_text},
            ],
        }
    ]


def _build_transformers_multimodal_inputs(processor: Any, page_image, prompt_text: str):
    messages = _build_generic_messages(prompt_text, page_image)
    if hasattr(processor, "apply_chat_template"):
        try:
            chat_text = processor.apply_chat_template(
                messages,
                tokenize=False,
                add_generation_prompt=True,
            )
            try:
                return processor(text=[chat_text], images=[page_image], return_tensors="pt")
            except Exception:
                return processor(text=chat_text, images=page_image, return_tensors="pt")
        except Exception:
            pass
    attempts = [
        {"text": [prompt_text], "images": [page_image], "return_tensors": "pt"},
        {"text": prompt_text, "images": page_image, "return_tensors": "pt"},
        {"text": [prompt_text], "image": [page_image], "return_tensors": "pt"},
        {"text": prompt_text, "image": page_image, "return_tensors": "pt"},
    ]
    last_exc: Optional[Exception] = None
    for kwargs in attempts:
        try:
            return processor(**kwargs)
        except Exception as exc:
            last_exc = exc
    raise RuntimeError(f"Could not build multimodal OCR inputs: {last_exc}")


def _normalize_chat_result(result: Any) -> str:
    if isinstance(result, str):
        return result
    if isinstance(result, tuple):
        for item in result:
            if isinstance(item, str) and normalize_text(item):
                return item
    if isinstance(result, dict):
        for key in ("text", "response", "content", "answer", "output", "transcription"):
            value = result.get(key)
            if isinstance(value, str) and normalize_text(value):
                return value
    raise RuntimeError(f"OCR chat backend returned unsupported result type: {type(result).__name__}")


def _build_generation_config_dict(prefix: str) -> Dict[str, Any]:
    return {
        "max_new_tokens": _backend_max_new_tokens(prefix, 4096),
        "do_sample": False,
    }


@contextlib.contextmanager
def _known_model_load_warnings_context(*, env_prefix: str):
    if env_prefix != "GOT_OCR":
        yield
        return
    with warnings.catch_warnings():
        warnings.filterwarnings(
            "ignore",
            message=r".*invalid escape sequence '\\l'.*",
            category=SyntaxWarning,
        )
        yield


def _call_from_pretrained_with_dtype_fallback(loader: Any, model_source: str, **kwargs: Any):
    try:
        return loader(model_source, **kwargs)
    except TypeError as exc:
        if "unexpected keyword argument 'dtype'" not in str(exc) or "dtype" not in kwargs:
            raise
        fallback_kwargs = dict(kwargs)
        fallback_kwargs["torch_dtype"] = fallback_kwargs.pop("dtype")
        return loader(model_source, **fallback_kwargs)


def _build_got_ocr_prompt_and_stop_text() -> tuple[str, str]:
    stop_text = "<|im_end|>"
    system_prompt = (
        "<|im_start|>system\n"
        "        You should follow the instructions carefully and explain your answers in detail."
    )
    image_prompt = "<img>" + ("<imgpad>" * 256) + "</img>\nOCR with format: "
    prompt = (
        system_prompt
        + stop_text
        + "<|im_start|>user\n"
        + image_prompt
        + stop_text
        + "<|im_start|>assistant\n"
    )
    return prompt, stop_text


def _build_got_ocr_image_tensor(page_image):
    try:
        import torchvision.transforms as T
        from torchvision.transforms.functional import InterpolationMode
    except ImportError as exc:
        raise RuntimeError("GOT_OCR local backend requires torchvision for image preprocessing.") from exc

    transform = T.Compose(
        [
            T.Lambda(lambda img: img.convert("RGB") if img.mode != "RGB" else img),
            T.Resize((1024, 1024), interpolation=InterpolationMode.BICUBIC),
            T.ToTensor(),
            T.Normalize(
                mean=(0.48145466, 0.4578275, 0.40821073),
                std=(0.26862954, 0.26130258, 0.27577711),
            ),
        ]
    )
    return transform(page_image).unsqueeze(0)


def _run_got_ocr_generate_backend(
    model_obj: Any,
    tokenizer_like: Any,
    page_image,
    *,
    model_device: Any,
) -> str:
    prompt, stop_text = _build_got_ocr_prompt_and_stop_text()
    try:
        tokenized_inputs = tokenizer_like([prompt], return_tensors="pt")
    except Exception:
        tokenized_inputs = tokenizer_like(prompt, return_tensors="pt")

    input_ids = _get_batch_item(tokenized_inputs, "input_ids")
    if input_ids is None:
        raise RuntimeError("GOT_OCR tokenizer did not return input_ids for the native OCR prompt.")
    attention_mask = _get_batch_item(tokenized_inputs, "attention_mask")

    try:
        input_ids = input_ids.to(model_device)
    except Exception:
        pass
    if attention_mask is None:
        try:
            import torch

            attention_mask = torch.ones_like(input_ids)
        except Exception:
            attention_mask = None
    elif hasattr(attention_mask, "to"):
        try:
            attention_mask = attention_mask.to(model_device)
        except Exception:
            pass

    image_tensor = _build_got_ocr_image_tensor(page_image)
    image_dtype = getattr(model_obj, "dtype", None)
    try:
        image_tensor = image_tensor.to(device=model_device, dtype=image_dtype)
    except Exception:
        try:
            image_tensor = image_tensor.to(model_device)
        except Exception:
            pass

    generate_kwargs: Dict[str, Any] = {
        "input_ids": input_ids,
        "images": [image_tensor],
        "do_sample": False,
        "num_beams": 1,
        "no_repeat_ngram_size": 20,
        "max_new_tokens": _backend_max_new_tokens("GOT_OCR", 4096),
        # GOT's remote-code chat() helper can hit cache/attention shape mismatches.
        "use_cache": False,
    }
    if attention_mask is not None:
        generate_kwargs["attention_mask"] = attention_mask
    eos_token_id = getattr(tokenizer_like, "eos_token_id", None)
    pad_token_id = getattr(tokenizer_like, "pad_token_id", None)
    if pad_token_id is None:
        pad_token_id = eos_token_id
    if pad_token_id is not None:
        generate_kwargs["pad_token_id"] = pad_token_id
    if eos_token_id is not None:
        generate_kwargs["eos_token_id"] = eos_token_id

    with __import__("torch").inference_mode():
        generated_ids = model_obj.generate(**generate_kwargs)

    decoded_output = _decode_generated_text(tokenizer_like, generated_ids, input_ids=input_ids)
    if stop_text and stop_text in decoded_output:
        decoded_output = decoded_output.split(stop_text, 1)[0]
    return decoded_output.strip()


def _run_got_ocr_backend(
    model_obj: Any,
    tokenizer_like: Any,
    page_image,
    *,
    model_device: Any,
) -> str:
    errors: List[str] = []
    try:
        emit_progress("Trying GOT_OCR OCR via direct generate(..., attention_mask=..., use_cache=False)")
        return _run_got_ocr_generate_backend(
            model_obj,
            tokenizer_like,
            page_image,
            model_device=model_device,
        )
    except Exception as exc:
        errors.append(f"direct generate(..., attention_mask=..., use_cache=False): {exc}")

    try:
        return _run_chat_style_backend(
            model_obj,
            tokenizer_like,
            page_image,
            default_table_image_transcription_prompt(),
            env_prefix="GOT_OCR",
            model_device=model_device,
        )
    except Exception as exc:
        errors.append(f"legacy chat(...): {exc}")

    raise RuntimeError("GOT_OCR backend exhausted: " + " ; ".join(errors))


def _run_generate_style_backend(
    model_obj: Any,
    processor: Any,
    page_image,
    prompt_text: str,
    *,
    model_device: Any,
    env_prefix: str,
) -> str:
    batch = _build_transformers_multimodal_inputs(processor, page_image, prompt_text)
    batch = _maybe_to_model_device(batch, model_device)
    input_ids = _get_batch_item(batch, "input_ids")
    generate_fn = getattr(model_obj, "generate", None)
    if not callable(generate_fn):
        raise RuntimeError(f"{env_prefix} OCR model does not expose a callable generate() method.")
    with __import__("torch").inference_mode():
        generated_ids = generate_fn(
            **batch,
            max_new_tokens=_backend_max_new_tokens(env_prefix, 4096),
            do_sample=False,
        )
    return _decode_generated_text(processor, generated_ids, input_ids=input_ids)


def _build_image_processor_inputs(processor: Any, page_image):
    attempts = [
        {"images": [page_image], "return_tensors": "pt"},
        {"images": page_image, "return_tensors": "pt"},
        {"image": [page_image], "return_tensors": "pt"},
        {"image": page_image, "return_tensors": "pt"},
    ]
    for kwargs in attempts:
        try:
            outputs = processor(**kwargs)
        except Exception:
            continue
        pixel_values = _get_batch_item(outputs, "pixel_values")
        if pixel_values is not None:
            return pixel_values
    return None


def _build_qianfan_pixel_values(page_image, *, image_size: int = 448, max_num: int = 12):
    try:
        import torch
        import torchvision.transforms as T
        from torchvision.transforms.functional import InterpolationMode
    except ImportError as exc:
        raise RuntimeError(
            "QIANFAN_OCR local backend requires torch and torchvision."
        ) from exc

    imagenet_mean = (0.485, 0.456, 0.406)
    imagenet_std = (0.229, 0.224, 0.225)
    transform = T.Compose(
        [
            T.Lambda(lambda img: img.convert("RGB") if img.mode != "RGB" else img),
            T.Resize((image_size, image_size), interpolation=InterpolationMode.BICUBIC),
            T.ToTensor(),
            T.Normalize(mean=imagenet_mean, std=imagenet_std),
        ]
    )

    orig_width, orig_height = page_image.size
    aspect_ratio = orig_width / max(1, orig_height)
    target_ratios = sorted(
        {
            (i, j)
            for n in range(1, max_num + 1)
            for i in range(1, n + 1)
            for j in range(1, n + 1)
            if 1 <= i * j <= max_num
        },
        key=lambda ratio: ratio[0] * ratio[1],
    )
    best_ratio = (1, 1)
    best_ratio_diff = float("inf")
    area = orig_width * orig_height
    for ratio in target_ratios:
        target_aspect_ratio = ratio[0] / ratio[1]
        ratio_diff = abs(aspect_ratio - target_aspect_ratio)
        if ratio_diff < best_ratio_diff:
            best_ratio_diff = ratio_diff
            best_ratio = ratio
        elif ratio_diff == best_ratio_diff:
            if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
                best_ratio = ratio

    target_width = image_size * best_ratio[0]
    target_height = image_size * best_ratio[1]
    resized_img = page_image.resize((target_width, target_height))
    processed_images = []
    blocks = best_ratio[0] * best_ratio[1]
    for block_index in range(blocks):
        box = (
            (block_index % best_ratio[0]) * image_size,
            (block_index // best_ratio[0]) * image_size,
            ((block_index % best_ratio[0]) + 1) * image_size,
            ((block_index // best_ratio[0]) + 1) * image_size,
        )
        processed_images.append(resized_img.crop(box))
    if len(processed_images) != 1:
        processed_images.append(page_image.resize((image_size, image_size)))
    return torch.stack([transform(image) for image in processed_images])


def _run_chat_style_backend(
    model_obj: Any,
    tokenizer_like: Any,
    page_image,
    prompt_text: str,
    *,
    env_prefix: str,
    model_device: Any,
) -> str:
    chat_fn = getattr(model_obj, "chat", None)
    if not callable(chat_fn):
        raise RuntimeError(f"{env_prefix} OCR model does not expose a callable chat() method.")
    signature = inspect.signature(chat_fn)
    param_names = set(signature.parameters)
    generation_config = _build_generation_config_dict(env_prefix)

    pixel_values = None
    processor = getattr(model_obj, "processor", None)
    if processor is not None:
        pixel_values = _build_image_processor_inputs(processor, page_image)
    if pixel_values is None and tokenizer_like is not None and not _processor_is_tokenizer_like(tokenizer_like):
        pixel_values = _build_image_processor_inputs(tokenizer_like, page_image)
    if pixel_values is not None:
        try:
            pixel_values = pixel_values.to(model_device)
        except Exception:
            pass

    with TemporaryDirectory(prefix=f"{env_prefix.lower()}_ocr_") as tmpdir:
        image_path = Path(tmpdir) / "page.png"
        page_image.convert("RGB").save(image_path)
        attempts: List[tuple[str, Dict[str, Any]]] = []
        if {"tokenizer", "pixel_values", "question"}.issubset(param_names) and pixel_values is not None:
            attempts.append(
                (
                    "chat(tokenizer=..., pixel_values=..., question=...)",
                    {
                        "tokenizer": tokenizer_like,
                        "pixel_values": pixel_values,
                        "question": prompt_text,
                        "generation_config": generation_config,
                    },
                )
            )
        if {"tokenizer", "image_file", "ocr_type"}.issubset(param_names):
            kwargs = {
                "tokenizer": tokenizer_like,
                "image_file": str(image_path),
                "ocr_type": "format",
            }
            if "question" in param_names:
                kwargs["question"] = prompt_text
            if "query" in param_names:
                kwargs["query"] = prompt_text
            if "generation_config" in param_names:
                kwargs["generation_config"] = generation_config
            attempts.append(("chat(tokenizer=..., image_file=..., ocr_type='format')", kwargs))
        if {"tokenizer", "image_file", "question"}.issubset(param_names):
            attempts.append(
                (
                    "chat(tokenizer=..., image_file=..., question=...)",
                    {
                        "tokenizer": tokenizer_like,
                        "image_file": str(image_path),
                        "question": prompt_text,
                        "generation_config": generation_config,
                    },
                )
            )
        if {"tokenizer", "image", "query"}.issubset(param_names):
            attempts.append(
                (
                    "chat(tokenizer=..., image=..., query=...)",
                    {
                        "tokenizer": tokenizer_like,
                        "image": page_image,
                        "query": prompt_text,
                        "generation_config": generation_config,
                    },
                )
            )
        if {"tokenizer", "msgs"}.issubset(param_names):
            attempts.append(
                (
                    "chat(tokenizer=..., msgs=...)",
                    {
                        "tokenizer": tokenizer_like,
                        "msgs": [{"role": "user", "content": prompt_text}],
                        "image": page_image,
                    },
                )
            )

        errors: List[str] = []
        for label, kwargs in attempts:
            filtered_kwargs = {key: value for key, value in kwargs.items() if key in param_names and value is not None}
            try:
                emit_progress(f"Trying {env_prefix} OCR via {label}")
                return _normalize_chat_result(chat_fn(**filtered_kwargs))
            except Exception as exc:
                errors.append(f"{label}: {exc}")

    raise RuntimeError(f"{env_prefix} OCR chat fallback exhausted: {' ; '.join(errors)}")


def _build_transformers_model_kwargs(
    *,
    env_prefix: str,
    model_source: str,
    dtype: Any,
    runtime_device: str,
    use_device_map: bool,
) -> Dict[str, Any]:
    kwargs: Dict[str, Any] = {
        "trust_remote_code": _backend_trust_remote_code(env_prefix),
        "local_files_only": _backend_local_files_only(env_prefix),
    }
    cache_dir = _backend_model_cache_dir(env_prefix)
    if cache_dir:
        kwargs["cache_dir"] = cache_dir
    revision = _backend_model_revision(env_prefix)
    if revision:
        kwargs["revision"] = revision
    attn_implementation = _backend_attn_implementation(env_prefix)
    if attn_implementation:
        kwargs["attn_implementation"] = attn_implementation
    if runtime_device == "cuda":
        kwargs["dtype"] = dtype
        if use_device_map:
            kwargs["device_map"] = _backend_device_map(env_prefix)
    elif runtime_device == "cpu":
        kwargs["dtype"] = dtype
    return kwargs


def _load_first_available_processor(model_source: str, *, env_prefix: str, prefer_tokenizer: bool = False):
    try:
        from transformers import AutoProcessor, AutoTokenizer
    except ImportError as exc:
        raise RuntimeError(
            f"{env_prefix} OCR requires transformers. Install a recent transformers build first."
        ) from exc

    common_kwargs: Dict[str, Any] = {
        "trust_remote_code": _backend_trust_remote_code(env_prefix),
        "local_files_only": _backend_local_files_only(env_prefix),
    }
    cache_dir = _backend_model_cache_dir(env_prefix)
    if cache_dir:
        common_kwargs["cache_dir"] = cache_dir
    revision = _backend_model_revision(env_prefix)
    if revision:
        common_kwargs["revision"] = revision

    constructors = [AutoProcessor, AutoTokenizer]
    if prefer_tokenizer:
        constructors = [AutoTokenizer, AutoProcessor]
    failures: List[str] = []
    for constructor in constructors:
        constructor_kwargs = dict(common_kwargs)
        if constructor.__name__ == "AutoTokenizer":
            constructor_kwargs.setdefault("use_fast", False)
        try:
            with _known_model_load_warnings_context(env_prefix=env_prefix):
                return constructor.from_pretrained(model_source, **constructor_kwargs)
        except Exception as exc:
            failures.append(f"{constructor.__name__}: {exc}")
    raise RuntimeError(
        f"Could not load processor/tokenizer for {model_source}: " + " | ".join(failures)
    )


def _load_first_available_model(model_source: str, *, env_prefix: str):
    try:
        import torch
        from transformers import AutoModel, AutoModelForCausalLM
    except ImportError as exc:
        raise RuntimeError(
            f"{env_prefix} OCR requires transformers and torch."
        ) from exc

    try:
        from transformers import AutoModelForImageTextToText
    except ImportError:
        AutoModelForImageTextToText = None
    try:
        from transformers import AutoModelForVision2Seq
    except ImportError:
        AutoModelForVision2Seq = None

    runtime_device, dtype, use_device_map = _select_generic_ocr_runtime(torch, _backend_device(env_prefix))
    common_kwargs = _build_transformers_model_kwargs(
        env_prefix=env_prefix,
        model_source=model_source,
        dtype=dtype,
        runtime_device=runtime_device,
        use_device_map=use_device_map,
    )
    constructors = [
        constructor
        for constructor in (
            AutoModelForImageTextToText,
            AutoModelForVision2Seq,
            AutoModelForCausalLM,
            AutoModel,
        )
        if constructor is not None
    ]
    last_exc: Optional[Exception] = None
    for constructor in constructors:
        try:
            with _known_model_load_warnings_context(env_prefix=env_prefix):
                model_obj = _call_from_pretrained_with_dtype_fallback(
                    constructor.from_pretrained,
                    model_source,
                    **common_kwargs,
                )
            if runtime_device in {"cpu", "mps"}:
                model_obj = model_obj.to(runtime_device)
            return model_obj, runtime_device
        except Exception as exc:
            last_exc = exc
    raise RuntimeError(f"Could not load model for {model_source}: {last_exc}")


def _get_generic_ocr_backend(
    model_id: str,
    *,
    env_prefix: str,
    prefer_tokenizer: bool = False,
):
    cache_key = (env_prefix, model_id)
    cached = _GENERIC_OCR_BACKENDS.get(cache_key)
    if cached is not None:
        return cached
    model_source = _resolve_generic_model_source(model_id, env_prefix=env_prefix)
    processor = _load_first_available_processor(
        model_source,
        env_prefix=env_prefix,
        prefer_tokenizer=prefer_tokenizer,
    )
    model_obj, runtime_device = _load_first_available_model(
        model_source,
        env_prefix=env_prefix,
    )
    cached = (model_obj, processor, runtime_device)
    _GENERIC_OCR_BACKENDS[cache_key] = cached
    return cached


def _run_monkeyocr_command(
    page_image,
    prompt_text: str,
    *,
    model_id: str,
    progress_handler: ProgressHandler = None,
) -> str:
    repo_dir = normalize_text(os.getenv("MONKEYOCR_REPO_DIR", ""))
    if not repo_dir:
        raise RuntimeError(
            "MonkeyOCR local backend requires MONKEYOCR_REPO_DIR to point at a local MonkeyOCR checkout."
        )
    repo_path = Path(repo_dir).expanduser()
    if not repo_path.exists():
        raise RuntimeError(f"MONKEYOCR_REPO_DIR='{repo_dir}' does not exist.")
    runner_template = normalize_text(os.getenv("MONKEYOCR_RUN_COMMAND", ""))
    if not runner_template:
        default_entrypoint = _resolve_monkeyocr_entrypoint(repo_path)
        runner_template = (
            "{python_bin} {entrypoint} {image_path} -o {output_dir}"
        )
    python_bin = normalize_text(os.getenv("MONKEYOCR_PYTHON", sys.executable)) or sys.executable
    timeout_s = _env_int("MONKEYOCR_TIMEOUT_S", 900)
    output_glob = normalize_text(os.getenv("MONKEYOCR_OUTPUT_GLOB", ""))
    emit_progress(
        f"MonkeyOCR local wrapper | repo {repo_path} | model {model_id}",
        progress_handler=progress_handler,
    )
    with TemporaryDirectory(prefix="monkeyocr_") as tmpdir:
        tmpdir_path = Path(tmpdir)
        image_path = Path(tmpdir) / "page.png"
        page_image.convert("RGB").save(image_path)
        prompt_path = tmpdir_path / "prompt.txt"
        prompt_path.write_text(str(prompt_text or ""), encoding="utf-8")
        entrypoint = _resolve_monkeyocr_entrypoint(repo_path)
        formatted_command = runner_template.format(
            python_bin=shlex.quote(python_bin),
            entrypoint=shlex.quote(str(entrypoint)),
            image_path=shlex.quote(str(image_path)),
            output_dir=shlex.quote(tmpdir),
            prompt=shlex.quote(prompt_text),
            prompt_path=shlex.quote(str(prompt_path)),
            model_id=shlex.quote(model_id),
            repo_dir=shlex.quote(str(repo_path)),
        )
        child_env = os.environ.copy()
        child_env["MONKEYOCR_IMAGE_PATH"] = str(image_path)
        child_env["MONKEYOCR_OUTPUT_DIR_ACTIVE"] = str(tmpdir_path)
        child_env["MONKEYOCR_PROMPT"] = str(prompt_text or "")
        child_env["MONKEYOCR_PROMPT_FILE"] = str(prompt_path)
        child_env["MONKEYOCR_MODEL_ID_ACTIVE"] = str(model_id)
        try:
            completed = subprocess.run(
                formatted_command,
                cwd=str(repo_path),
                shell=True,
                capture_output=True,
                text=True,
                env=child_env,
                timeout=timeout_s,
            )
        except subprocess.TimeoutExpired as exc:
            raise RuntimeError(
                f"MonkeyOCR command timed out after {timeout_s}s: {formatted_command}"
            ) from exc
        if completed.returncode != 0:
            raise RuntimeError(
                "MonkeyOCR command failed: "
                f"{normalize_text(completed.stderr) or normalize_text(completed.stdout) or completed.returncode}"
            )
        for candidate in (
            "result.md",
            "result.html",
            "result.json",
            "output.md",
            "output.html",
            "output.json",
            "pred.md",
            "pred.html",
            "pred.json",
            "response.json",
            "response.md",
            "response.html",
            "table.html",
            "table.md",
            "table.json",
            "ocr_result.json",
            "ocr_result.md",
            "ocr_result.html",
            "result.txt",
            "output.txt",
        ):
            candidate_path = tmpdir_path / candidate
            if candidate_path.exists():
                extracted = _read_monkeyocr_output_artifact(candidate_path)
                if normalize_text(extracted):
                    return extracted
        if output_glob:
            for pattern in [piece.strip() for piece in output_glob.split(",") if piece.strip()]:
                for candidate_path in sorted(tmpdir_path.glob(pattern)):
                    if candidate_path.is_file():
                        if candidate_path.name in {"prompt.txt", image_path.name}:
                            continue
                        extracted = _read_monkeyocr_output_artifact(candidate_path)
                        if normalize_text(extracted):
                            return extracted
        for candidate_path in (
            sorted(tmpdir_path.glob("**/*.html"))
            + sorted(tmpdir_path.glob("**/*.md"))
            + sorted(tmpdir_path.glob("**/*.json"))
            + sorted(tmpdir_path.glob("**/*.txt"))
        ):
            if candidate_path.is_file():
                if candidate_path.name in {"prompt.txt", image_path.name}:
                    continue
                extracted = _read_monkeyocr_output_artifact(candidate_path)
                if normalize_text(extracted):
                    return extracted
        stdout_text = _coerce_monkeyocr_output_text(completed.stdout)
        if stdout_text:
            return stdout_text
    raise RuntimeError(
        "MonkeyOCR command completed but did not produce a readable OCR output file. "
        "Set MONKEYOCR_RUN_COMMAND if your checkout uses a nonstandard entrypoint, output path, or task flags."
    )


def is_firered_model_id(model_id: str) -> bool:
    normalized = normalize_text(model_id).lower()
    if not normalized:
        return False
    configured = default_firered_model_id().lower()
    return normalized == configured or "firered" in normalized


def is_deepseek_model_id(model_id: str) -> bool:
    normalized = normalize_text(model_id).lower()
    if not normalized:
        return False
    configured = default_deepseek_ocr_model_id().lower()
    return (
        normalized == configured
        or normalized.startswith("deepseek-ai/")
        or "deepseek-ocr" in normalized
    )


def is_mistral_model_id(model_id: str) -> bool:
    normalized = normalize_text(model_id).lower()
    if not normalized:
        return False
    configured = default_mistral_ocr_model_id().lower()
    return (
        normalized == configured
        or normalized.startswith("mistral-ocr")
        or normalized.startswith("ocr-")
        or ("mistral" in normalized and "ocr" in normalized)
    )


def is_qianfan_model_id(model_id: str) -> bool:
    normalized = normalize_text(model_id).lower()
    if not normalized:
        return False
    configured = default_qianfan_ocr_model_id().lower()
    return (
        normalized == configured
        or normalized.startswith("baidu/qianfan")
        or normalized in {"qianfan", "qianfan-ocr"}
        or "qianfan-ocr" in normalized
    )


def is_glm_ocr_model_id(model_id: str) -> bool:
    normalized = normalize_text(model_id).lower()
    if not normalized:
        return False
    configured = default_glm_ocr_model_id().lower()
    return (
        normalized == configured
        or normalized.startswith("zai-org/glm-ocr")
        or normalized in {"glm-ocr", "glmocr"}
        or normalized.endswith("/glm-ocr")
    )


def is_paddleocr_vl_model_id(model_id: str) -> bool:
    normalized = normalize_text(model_id).lower()
    if not normalized:
        return False
    configured = default_paddleocr_vl_model_id().lower()
    return (
        normalized == configured
        or normalized.startswith("paddlepaddle/paddleocr-vl")
        or normalized in {"paddleocr-vl", "paddleocr-vl-1.5", "paddleocr_vl"}
        or "paddleocr-vl" in normalized
    )


def is_got_ocr_model_id(model_id: str) -> bool:
    normalized = normalize_text(model_id).lower()
    if not normalized:
        return False
    configured = default_got_ocr_model_id().lower()
    return (
        normalized == configured
        or normalized.startswith("stepfun-ai/got-ocr")
        or normalized in {"got-ocr", "got-ocr2", "got-ocr2_0", "gotocr", "gotocr2"}
        or "got-ocr" in normalized
        or "got_ocr" in normalized
    )


def is_monkeyocr_model_id(model_id: str) -> bool:
    normalized = normalize_text(model_id).lower()
    if not normalized:
        return False
    configured = default_monkeyocr_model_id().lower()
    return (
        normalized == configured
        or normalized.startswith("echo840/monkeyocr")
        or normalized in {"monkeyocr", "monkeyocr-pro-3b", "monkeyocr_pro_3b"}
        or "monkeyocr" in normalized
    )


def is_qwen_ocr_model_id(model_id: str) -> bool:
    normalized = normalize_text(model_id).lower()
    if not normalized:
        return False
    configured = default_qwen_ocr_model_id().lower()
    return (
        normalized == configured
        or normalized.startswith("qwen/qwen3.5-35b-a3b")
        or normalized.startswith("qwen/qwen3.6-35b-a3b")
        or normalized in {
            "qwen_ocr",
            "qwen-ocr",
            "qwenocr",
            "qwen3.5-35b-a3b",
            "qwen3.5-35b-a3b-fp8",
            "qwen3.6-35b-a3b",
            "qwen3.6-35b-a3b-fp8",
        }
        or "qwen3.5-35b-a3b" in normalized
        or "qwen3.6-35b-a3b" in normalized
    )


def is_gemma4_vllm_model_id(model_id: str) -> bool:
    normalized = normalize_text(model_id).lower().replace("_", "-")
    if not normalized:
        return False
    configured = default_gemma4_vllm_model_id().lower().replace("_", "-")
    if normalized == configured:
        return True
    if "llamacpp" in normalized or "llama-cpp" in normalized or "llama.cpp" in normalized or "gguf" in normalized:
        return False
    return (
        normalized.startswith("google/gemma-4-")
        or normalized.startswith("gemma-4-")
        or normalized.startswith("gemma4-")
        or normalized in {"gemma4-vllm", "gemma-4-vllm"}
    )


def is_gemma4_hf_model_id(model_id: str) -> bool:
    normalized = normalize_text(model_id).lower().replace("_", "-")
    if not normalized:
        return False
    if "vllm" in normalized or "llamacpp" in normalized or "llama-cpp" in normalized or "llama.cpp" in normalized or "gguf" in normalized:
        return False
    configured = default_gemma4_hf_model_id().lower().replace("_", "-")
    if normalized == configured:
        return True
    return (
        normalized in {
            "gemma4",
            "gemma-4",
            "gemma4-hf",
            "gemma-4-hf",
            "gemma4-local",
            "gemma-4-local",
            "gemma4-huggingface",
            "gemma-4-huggingface",
            "gemma4-transformers",
            "gemma-4-transformers",
        }
        or normalized.startswith("google/gemma-4-")
        or normalized.startswith("gemma-4-")
        or normalized.startswith("gemma4-")
    )


def is_gemma4_llamacpp_model_id(model_id: str) -> bool:
    normalized = normalize_text(model_id).lower().replace("_", "-")
    if not normalized:
        return False
    configured = default_gemma4_llamacpp_model_id().lower().replace("_", "-")
    if normalized == configured:
        return True
    if normalized in {
        "gemma4",
        "gemma-4",
        "gemma4-26b",
        "gemma-4-26b",
        "gemma4-26b-it",
        "gemma-4-26b-it",
        "gemma4-llamacpp",
        "gemma-4-llamacpp",
        "gemma4-26b-llamacpp",
        "gemma-4-26b-llamacpp",
        "gemma4-26b-llama-cpp",
        "gemma-4-26b-llama-cpp",
        "gemma4-llama-cpp",
        "gemma-4-llama-cpp",
        "llamacpp-gemma4-26b",
        "llama-cpp-gemma4-26b",
        "llamacpp-gemma4",
        "llama-cpp-gemma4",
    }:
        return True
    return ("gemma4" in normalized or "gemma-4" in normalized) and (
        "llamacpp" in normalized
        or "llama-cpp" in normalized
        or "llama.cpp" in normalized
        or "gguf" in normalized
    )


def resolve_table_ocr_backend(model_id: str) -> str:
    normalized = normalize_text(model_id)
    if is_firered_model_id(normalized):
        return "firered"
    if is_deepseek_model_id(normalized):
        return "deepseek"
    if is_mistral_model_id(normalized):
        return "mistral"
    if is_qianfan_model_id(normalized):
        return "qianfan"
    if is_glm_ocr_model_id(normalized):
        return "glm_ocr"
    if is_paddleocr_vl_model_id(normalized):
        return "paddleocr_vl"
    if is_got_ocr_model_id(normalized):
        return "got_ocr"
    if is_monkeyocr_model_id(normalized):
        return "monkeyocr"
    if is_qwen_ocr_model_id(normalized):
        return "qwen_ocr"
    if is_gemma4_hf_model_id(normalized):
        return "gemma4_hf"
    if is_gemma4_vllm_model_id(normalized):
        return "gemma4_vllm"
    if is_gemma4_llamacpp_model_id(normalized):
        return "gemma4_llamacpp"
    if normalized in openrouter_ocr_model_ids():
        return "openrouter"
    return "openrouter"


def should_use_openrouter_ocr(model_id: str) -> bool:
    return resolve_table_ocr_backend(model_id) == "openrouter"


def _resolve_deepseek_ocr_model_source(model_id: str) -> str:
    local_dir = _deepseek_ocr_local_dir()
    if not local_dir:
        return model_id

    local_path = Path(local_dir).expanduser()
    if str(local_path).startswith("/content") and not Path("/content").exists():
        raise RuntimeError(
            f"DEEPSEEK_OCR_MODEL_LOCAL_DIR points to '{local_dir}', which looks like a Colab path, "
            "but this Python process is running outside Colab."
        )
    if not local_path.exists():
        raise RuntimeError(
            f"DEEPSEEK_OCR_MODEL_LOCAL_DIR='{local_dir}' does not exist."
        )
    if not local_path.is_dir():
        raise RuntimeError(f"DEEPSEEK_OCR_MODEL_LOCAL_DIR='{local_dir}' is not a directory.")
    if not (local_path / "config.json").exists():
        raise RuntimeError(
            f"DEEPSEEK_OCR_MODEL_LOCAL_DIR='{local_dir}' does not look like a downloaded model directory "
            "(missing config.json)."
        )
    return str(local_path)


def _select_deepseek_ocr_runtime(torch):
    requested = _deepseek_ocr_device()
    mps_available = bool(getattr(torch.backends, "mps", None)) and torch.backends.mps.is_available()

    if requested not in {"auto", "cuda", "mps", "cpu"}:
        raise RuntimeError(
            f"Unsupported DEEPSEEK_OCR_DEVICE='{requested}'. Expected one of: auto, cuda, mps, cpu."
        )

    if requested in {"auto", "cuda"} and torch.cuda.is_available():
        return "cuda", torch.bfloat16, True
    if requested == "cuda":
        raise RuntimeError("DEEPSEEK_OCR_DEVICE='cuda' was requested, but CUDA is not available.")

    if requested in {"auto", "mps"} and mps_available:
        return "mps", torch.float16, False
    if requested == "mps":
        raise RuntimeError("DEEPSEEK_OCR_DEVICE='mps' was requested, but MPS is not available.")

    return "cpu", torch.float32, False


def _prepare_deepseek_ocr_image(image, runtime_device: str):
    if not _table_ocr_allow_backend_image_resize():
        return image
    max_pixels = _deepseek_ocr_max_image_pixels()
    width, height = image.size
    total_pixels = width * height
    if max_pixels <= 0 or total_pixels <= max_pixels:
        return image

    scale = math.sqrt(max_pixels / total_pixels)
    new_width = max(28, int(width * scale))
    new_height = max(28, int(height * scale))
    emit_progress(
        f"Resizing DeepSeek OCR image for {runtime_device} from {width}x{height} to "
        f"{new_width}x{new_height} to stay within {max_pixels:,} pixels."
    )
    return image.resize((new_width, new_height))


def _build_deepseek_prompt_text(processor, prompt_text: str) -> str:
    image_token = getattr(processor, "image_token", None)
    if image_token is None:
        image_token = getattr(getattr(processor, "tokenizer", None), "image_token", None)
    if image_token:
        return f"{image_token}\n{prompt_text}"
    return prompt_text


def _build_deepseek_infer_prompt(prompt_text: str) -> str:
    normalized = str(prompt_text or "").strip()
    if not normalized:
        normalized = default_table_image_transcription_prompt()
    return normalized


def _build_deepseek_infer_prompt_candidates(prompt_text: str) -> List[tuple[str, str]]:
    normalized = _build_deepseek_infer_prompt(prompt_text)
    default_prompt = normalize_text(default_table_image_transcription_prompt())
    candidates: List[tuple[str, str]] = []
    seen: set[str] = set()

    def add_candidate(label: str, candidate_prompt: str) -> None:
        candidate_text = normalize_text(candidate_prompt)
        if not candidate_text or candidate_text in seen:
            return
        seen.add(candidate_text)
        candidates.append((label, candidate_text))

    # DeepSeek-OCR-2's infer() helper only returns text in eval_mode when the
    # prompt includes the literal <image> token.
    if normalize_text(normalized) == default_prompt:
        add_candidate("grounding markdown prompt", "<image>\n<|grounding|>Convert the document to markdown. ")
        add_candidate("free OCR prompt", "<image>\nFree OCR. ")
        add_candidate("plain markdown prompt", "<image>\nConvert the document to markdown. ")
        add_candidate("caller HTML prompt with image token", f"<image>\n{normalized}")
    else:
        add_candidate("caller prompt with image token", f"<image>\n{normalized}")
        add_candidate("grounding markdown prompt", "<image>\n<|grounding|>Convert the document to markdown. ")
        add_candidate("free OCR prompt", "<image>\nFree OCR. ")

    return candidates


def _require_nonempty_ocr_text_output(
    text: str,
    *,
    backend_label: str,
    details: Optional[Dict[str, Any]] = None,
) -> str:
    cleaned = strip_code_fences(text)
    if cleaned and _HTML_TABLE_RE.search(cleaned):
        cleaned = normalize_inline_latex_in_html_fragment(cleaned)
    elif cleaned:
        latex_html = maybe_convert_latex_tabular_to_html(cleaned)
        if latex_html:
            cleaned = latex_html
    if cleaned:
        return cleaned
    raise TableOCRContentError(
        f"OCR backend returned empty text content via {backend_label}",
        details=details or {"backend": backend_label},
    )


def _resize_image_to_max_pixels(img, max_pixels: int):
    if max_pixels <= 0:
        return img
    width, height = img.size
    total_pixels = width * height
    if total_pixels <= max_pixels:
        return img
    scale = math.sqrt(float(max_pixels) / float(total_pixels))
    new_width = max(28, int(width * scale))
    new_height = max(28, int(height * scale))
    return img.resize((new_width, new_height))


def _is_firered_buffer_error(exc: Exception) -> bool:
    message = normalize_text(str(exc)).lower()
    return (
        "invalid buffer size" in message
        or "out of memory" in message
        or ("mps" in message and "buffer" in message)
    )


def _build_deepseek_inputs(processor, page_image, prompt_text: str):
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "image", "image": page_image},
                {"type": "text", "text": prompt_text},
            ],
        }
    ]

    if hasattr(processor, "apply_chat_template"):
        try:
            chat_text = processor.apply_chat_template(
                messages,
                tokenize=False,
                add_generation_prompt=True,
            )
            return processor(text=[chat_text], images=[page_image], return_tensors="pt")
        except Exception:
            pass

    fallback_prompt = _build_deepseek_prompt_text(processor, prompt_text)
    try:
        return processor(text=[fallback_prompt], images=[page_image], return_tensors="pt")
    except Exception:
        return processor(text=fallback_prompt, images=page_image, return_tensors="pt")


def _normalize_deepseek_chat_output(result: Any) -> str:
    if isinstance(result, str):
        return result
    if isinstance(result, tuple) and result:
        first = result[0]
        if isinstance(first, str):
            return first
    if isinstance(result, dict):
        for key in ("text", "response", "content", "answer", "output"):
            value = result.get(key)
            if isinstance(value, str):
                return value
    raise RuntimeError(f"DeepSeek chat fallback returned an unsupported result type: {type(result).__name__}")


def _processor_is_tokenizer_like(processor: Any) -> bool:
    class_name = type(processor).__name__.lower()
    if "tokenizer" in class_name:
        return True
    try:
        from transformers import PreTrainedTokenizerBase

        return isinstance(processor, PreTrainedTokenizerBase)
    except Exception:
        return False


def _model_supports_image_aware_fallback(model_obj: Any) -> bool:
    if callable(getattr(model_obj, "chat", None)):
        return True

    for attr_name in ("generate", "forward"):
        method = getattr(model_obj, attr_name, None)
        if not callable(method):
            continue
        try:
            param_names = set(inspect.signature(method).parameters)
        except Exception:
            continue
        if {"images", "image"} & param_names:
            return True
        if {"pixel_values", "image_tensors", "input_images"} & param_names:
            return True
    return False


def _decode_deepseek_generated_output(processor: Any, generated_ids: Any, input_ids: Any = None) -> str:
    trimmed_ids = generated_ids
    if input_ids is not None:
        try:
            trimmed_ids = generated_ids[:, input_ids.shape[1] :]
        except Exception:
            trimmed_ids = generated_ids

    if hasattr(processor, "batch_decode"):
        return processor.batch_decode(
            trimmed_ids,
            skip_special_tokens=True,
            clean_up_tokenization_spaces=False,
        )[0]
    if hasattr(processor, "tokenizer") and hasattr(processor.tokenizer, "batch_decode"):
        return processor.tokenizer.batch_decode(
            trimmed_ids,
            skip_special_tokens=True,
            clean_up_tokenization_spaces=False,
        )[0]
    raise RuntimeError("DeepSeek fallback could not find a decode path on the loaded processor/tokenizer.")


def _maybe_build_pixel_values(model_obj: Any, page_image, model_device: Any):
    candidates = []
    image_processor = getattr(model_obj, "image_processor", None)
    if image_processor is not None:
        candidates.append(image_processor)
    vision_tower = getattr(model_obj, "vision_tower", None)
    if vision_tower is not None:
        nested_processor = getattr(vision_tower, "image_processor", None)
        if nested_processor is not None:
            candidates.append(nested_processor)

    for candidate in candidates:
        try:
            if hasattr(candidate, "preprocess"):
                outputs = candidate.preprocess(page_image, return_tensors="pt")
            elif callable(candidate):
                outputs = candidate(page_image, return_tensors="pt")
            else:
                continue
            if isinstance(outputs, dict):
                pixel_values = outputs.get("pixel_values")
            else:
                pixel_values = getattr(outputs, "pixel_values", None)
            if pixel_values is None:
                continue
            return pixel_values.to(model_device)
        except Exception:
            continue
    return None


def _run_deepseek_generate_fallback(model_obj, processor, page_image, prompt_text: str, model_device: Any) -> str:
    generate_fn = getattr(model_obj, "generate", None)
    if not callable(generate_fn):
        raise RuntimeError("DeepSeek-OCR-2 did not expose a callable `generate` fallback.")

    prompt_with_image = _build_deepseek_prompt_text(processor, prompt_text)
    prompt_for_tokenizer = prompt_with_image
    if hasattr(processor, "apply_chat_template"):
        try:
            prompt_for_tokenizer = processor.apply_chat_template(
                [
                    {
                        "role": "user",
                        "content": [
                            {"type": "image", "image": page_image},
                            {"type": "text", "text": prompt_text},
                        ],
                    }
                ],
                tokenize=False,
                add_generation_prompt=True,
            )
        except Exception:
            prompt_for_tokenizer = prompt_with_image
    try:
        text_inputs = processor(text=[prompt_for_tokenizer], return_tensors="pt")
    except Exception:
        try:
            text_inputs = processor([prompt_for_tokenizer], return_tensors="pt")
        except Exception:
            text_inputs = processor(prompt_for_tokenizer, return_tensors="pt")

    text_inputs = text_inputs.to(model_device)
    input_ids = getattr(text_inputs, "input_ids", None)
    if input_ids is None and isinstance(text_inputs, dict):
        input_ids = text_inputs.get("input_ids")

    candidate_image_kwargs: List[tuple[str, Dict[str, Any]]] = [
        ("generate(..., images=[[PIL]])", {"images": [[page_image]]}),
        ("generate(..., images=[PIL])", {"images": [page_image]}),
        ("generate(..., images=PIL)", {"images": page_image}),
        ("generate(..., image=PIL)", {"image": page_image}),
        ("generate(..., input_images=[PIL])", {"input_images": [page_image]}),
    ]

    pixel_values = _maybe_build_pixel_values(model_obj, page_image, model_device)
    if pixel_values is not None:
        candidate_image_kwargs.append(("generate(..., pixel_values=tensor)", {"pixel_values": pixel_values}))

    errors: List[str] = []
    for label, extra_kwargs in candidate_image_kwargs:
        try:
            emit_progress(f"Trying DeepSeek generate fallback via {label}")
            generated_ids = generate_fn(
                **text_inputs,
                **extra_kwargs,
                max_new_tokens=_deepseek_ocr_max_new_tokens(),
                do_sample=False,
            )
            return _decode_deepseek_generated_output(processor, generated_ids, input_ids=input_ids)
        except Exception as exc:
            errors.append(f"{label}: {exc}")

    prepare_inputs_embeds_fn = getattr(model_obj, "prepare_inputs_embeds", None)
    language_model = getattr(model_obj, "language", None)
    language_generate_fn = getattr(language_model, "generate", None) if language_model is not None else None
    attention_mask = getattr(text_inputs, "attention_mask", None)
    if attention_mask is None and isinstance(text_inputs, dict):
        attention_mask = text_inputs.get("attention_mask")
    if callable(prepare_inputs_embeds_fn):
        embed_attempts: List[tuple[str, Dict[str, Any]]] = [
            ("prepare_inputs_embeds(..., images=[[PIL]])", {"images": [[page_image]]}),
            ("prepare_inputs_embeds(..., images=[PIL])", {"images": [page_image]}),
        ]
        for label, extra_kwargs in embed_attempts:
            try:
                emit_progress(f"Trying DeepSeek embedding fallback via {label}")
                inputs_embeds = prepare_inputs_embeds_fn(
                    input_ids=input_ids,
                    **extra_kwargs,
                )
                if callable(language_generate_fn):
                    generated_ids = language_generate_fn(
                        inputs_embeds=inputs_embeds,
                        attention_mask=attention_mask,
                        max_new_tokens=_deepseek_ocr_max_new_tokens(),
                        do_sample=False,
                    )
                else:
                    generated_ids = generate_fn(
                        inputs_embeds=inputs_embeds,
                        attention_mask=attention_mask,
                        max_new_tokens=_deepseek_ocr_max_new_tokens(),
                        do_sample=False,
                    )
                return _decode_deepseek_generated_output(processor, generated_ids, input_ids=None)
            except Exception as exc:
                errors.append(f"{label}: {exc}")

    raise RuntimeError(" ; ".join(errors))


def _run_deepseek_infer_fallback(
    model_obj,
    processor,
    page_image,
    prompt_text: str,
    runtime_device: str,
) -> str:
    infer_fn = getattr(model_obj, "infer", None)
    if not callable(infer_fn):
        raise RuntimeError("DeepSeek-OCR-2 did not expose a callable `infer` helper.")
    if runtime_device != "cuda":
        raise RuntimeError(
            f"DeepSeek-OCR-2 remote-code infer helper currently requires CUDA, but runtime device is {runtime_device}."
        )

    signature = inspect.signature(infer_fn)
    param_names = set(signature.parameters)

    with TemporaryDirectory(prefix="deepseek_ocr_") as tmpdir:
        image_path = Path(tmpdir) / "page.png"
        result_mmd_path = Path(tmpdir) / "result.mmd"
        page_image.convert("RGB").save(image_path)

        infer_kwargs_base: Dict[str, Any] = {
            "tokenizer": processor,
            "image_file": str(image_path),
            "output_path": tmpdir,
            "eval_mode": True,
        }
        if "save_results" in param_names:
            infer_kwargs_base["save_results"] = False
        if "test_compress" in param_names:
            infer_kwargs_base["test_compress"] = False
        if "crop_mode" in param_names:
            infer_kwargs_base["crop_mode"] = True
        if "base_size" in param_names:
            infer_kwargs_base["base_size"] = 1024
        if "image_size" in param_names:
            infer_kwargs_base["image_size"] = 768

        errors: List[str] = []
        emit_progress("Trying DeepSeek remote-code infer(...) fallback")
        for attempt_label, infer_prompt in _build_deepseek_infer_prompt_candidates(prompt_text):
            emit_progress(f"Trying DeepSeek infer prompt variant: {attempt_label}")

            try:
                infer_kwargs = dict(infer_kwargs_base)
                infer_kwargs["prompt"] = infer_prompt
                infer_kwargs["eval_mode"] = True
                result = infer_fn(**{key: value for key, value in infer_kwargs.items() if key in param_names})
                normalized_result = ""
                if result is not None:
                    normalized_result = strip_code_fences(_normalize_deepseek_chat_output(result))
                if normalized_result:
                    return normalized_result
            except Exception as exc:
                errors.append(f"{attempt_label} eval_mode=True: {exc}")
                continue

            if "save_results" not in param_names:
                errors.append(f"{attempt_label} eval_mode=True: empty text output")
                continue

            try:
                if result_mmd_path.exists():
                    result_mmd_path.unlink()
                infer_kwargs = dict(infer_kwargs_base)
                infer_kwargs["prompt"] = infer_prompt
                infer_kwargs["eval_mode"] = False
                infer_kwargs["save_results"] = True
                with contextlib.redirect_stdout(io.StringIO()):
                    result = infer_fn(**{key: value for key, value in infer_kwargs.items() if key in param_names})
                normalized_result = ""
                if result is not None:
                    normalized_result = strip_code_fences(_normalize_deepseek_chat_output(result))
                if not normalized_result and result_mmd_path.exists():
                    normalized_result = strip_code_fences(result_mmd_path.read_text(encoding="utf-8"))
                if normalized_result:
                    return normalized_result
                errors.append(f"{attempt_label} save_results=True: empty text output")
            except Exception as exc:
                errors.append(f"{attempt_label} save_results=True: {exc}")

    raise RuntimeError(" ; ".join(errors))


def _deepseek_ocr_version_guidance_message() -> str:
    return (
        "DeepSeek-OCR-2 remote code expects the Hugging Face stack from the model card, "
        "especially `transformers==4.46.3` and `tokenizers==0.20.3`. "
        "In Colab, reinstall those versions, restart the runtime, and reload the model."
    )


def _run_deepseek_chat_fallback(model_obj, processor, page_image, prompt_text: str) -> str:
    chat_fn = getattr(model_obj, "chat", None)
    if not callable(chat_fn):
        raise RuntimeError(
            "DeepSeek-OCR-2 loaded a tokenizer-like processor instead of a multimodal processor, "
            "and the model does not expose a callable `chat` fallback."
        )

    signature = inspect.signature(chat_fn)
    param_names = set(signature.parameters)
    max_new_tokens = _deepseek_ocr_max_new_tokens()

    call_attempts: List[tuple[str, Dict[str, Any]]] = []
    if {"image", "msgs", "tokenizer"}.issubset(param_names):
        kwargs: Dict[str, Any] = {
            "image": page_image,
            "msgs": [{"role": "user", "content": prompt_text}],
            "tokenizer": processor,
        }
        if "sampling" in param_names:
            kwargs["sampling"] = False
        if "do_sample" in param_names:
            kwargs["do_sample"] = False
        if "temperature" in param_names:
            kwargs["temperature"] = 0.0
        if "max_new_tokens" in param_names:
            kwargs["max_new_tokens"] = max_new_tokens
        if "ocr_type" in param_names:
            kwargs["ocr_type"] = "format"
        call_attempts.append(("chat(image=..., msgs=..., tokenizer=...)", kwargs))

    if {"tokenizer", "query", "image"}.issubset(param_names):
        kwargs = {
            "tokenizer": processor,
            "query": prompt_text,
            "image": page_image,
        }
        if "max_new_tokens" in param_names:
            kwargs["max_new_tokens"] = max_new_tokens
        if "temperature" in param_names:
            kwargs["temperature"] = 0.0
        call_attempts.append(("chat(tokenizer=..., query=..., image=...)", kwargs))

    if {"tokenizer", "prompt", "image"}.issubset(param_names):
        kwargs = {
            "tokenizer": processor,
            "prompt": prompt_text,
            "image": page_image,
        }
        if "max_new_tokens" in param_names:
            kwargs["max_new_tokens"] = max_new_tokens
        if "temperature" in param_names:
            kwargs["temperature"] = 0.0
        call_attempts.append(("chat(tokenizer=..., prompt=..., image=...)", kwargs))

    if {"tokenizer", "text", "image"}.issubset(param_names):
        kwargs = {
            "tokenizer": processor,
            "text": prompt_text,
            "image": page_image,
        }
        if "max_new_tokens" in param_names:
            kwargs["max_new_tokens"] = max_new_tokens
        if "temperature" in param_names:
            kwargs["temperature"] = 0.0
        call_attempts.append(("chat(tokenizer=..., text=..., image=...)", kwargs))

    if not call_attempts:
        raise RuntimeError(
            "DeepSeek-OCR-2 exposed a `chat` method, but this backend does not yet recognize its signature: "
            f"{signature}"
        )

    errors: List[str] = []
    for label, kwargs in call_attempts:
        try:
            emit_progress(f"Trying DeepSeek chat fallback via {label}")
            return _normalize_deepseek_chat_output(chat_fn(**kwargs))
        except Exception as exc:
            errors.append(f"{label}: {exc}")

    raise RuntimeError(" ; ".join(errors))


def _patch_missing_llama_flash_attention2() -> None:
    try:
        import transformers.models.llama.modeling_llama as llama_modeling
    except Exception:
        return

    if hasattr(llama_modeling, "LlamaFlashAttention2"):
        return

    replacement = getattr(llama_modeling, "LlamaSdpaAttention", None)
    if replacement is None:
        replacement = getattr(llama_modeling, "LlamaAttention", None)
    if replacement is None:
        return

    setattr(llama_modeling, "LlamaFlashAttention2", replacement)
    emit_progress(
        "Applied compatibility shim: aliased transformers.models.llama.modeling_llama."
        "LlamaFlashAttention2 to an available Llama attention implementation."
    )


def _get_deepseek_table_backend(model_id: str):
    global _DEEPSEEK_OCR_MODEL, _DEEPSEEK_OCR_PROCESSOR, _DEEPSEEK_OCR_MODEL_ID, _DEEPSEEK_OCR_LOAD_ERROR

    if (
        _DEEPSEEK_OCR_MODEL is not None
        and _DEEPSEEK_OCR_PROCESSOR is not None
        and _DEEPSEEK_OCR_MODEL_ID == model_id
    ):
        return _DEEPSEEK_OCR_MODEL, _DEEPSEEK_OCR_PROCESSOR

    try:
        import torch
    except ImportError as exc:
        raise RuntimeError("PyTorch is required for DeepSeek OCR transcription. Install `torch` first.") from exc
    try:
        import torchvision  # noqa: F401
    except ImportError as exc:
        raise RuntimeError(
            "DeepSeek OCR transcription requires `torchvision`. Install `torchvision` and restart Python."
        ) from exc

    try:
        from transformers import AutoConfig, AutoModelForCausalLM, AutoProcessor
    except ImportError as exc:
        raise RuntimeError(
            "DeepSeek OCR transcription requires a recent Hugging Face stack. "
            "Install or upgrade `accelerate` and `safetensors`, then install the latest "
            "`transformers` build (for example `pip install -U git+https://github.com/huggingface/transformers`)."
        ) from exc

    _patch_missing_llama_flash_attention2()

    try:
        from transformers import AutoModel
    except ImportError:
        AutoModel = None

    try:
        from transformers import AutoModelForImageTextToText
    except ImportError:
        AutoModelForImageTextToText = None

    try:
        from transformers import AutoModelForVision2Seq
    except ImportError:
        AutoModelForVision2Seq = None

    try:
        from transformers.models.deepseek_vl import DeepseekVLForConditionalGeneration
    except ImportError:
        DeepseekVLForConditionalGeneration = None

    try:
        from transformers.models.deepseek_vl_hybrid import DeepseekVLHybridForConditionalGeneration
    except ImportError:
        DeepseekVLHybridForConditionalGeneration = None

    runtime_device, dtype, use_device_map = _select_deepseek_ocr_runtime(torch)
    try:
        model_source = _resolve_deepseek_ocr_model_source(model_id)
        common_kwargs: Dict[str, Any] = {
            "trust_remote_code": _deepseek_ocr_trust_remote_code(),
        }
        cache_dir = _deepseek_ocr_cache_dir()
        revision = _deepseek_ocr_revision()
        if cache_dir:
            common_kwargs["cache_dir"] = cache_dir
        if revision and not _deepseek_ocr_local_dir():
            common_kwargs["revision"] = revision
        if _deepseek_ocr_local_files_only():
            common_kwargs["local_files_only"] = True

        with _known_model_load_warnings_context(env_prefix="DEEPSEEK_OCR"):
            config = AutoConfig.from_pretrained(model_source, **common_kwargs)
            processor = AutoProcessor.from_pretrained(model_source, **common_kwargs)
        processor_is_tokenizer_like = _processor_is_tokenizer_like(processor)
        model_type = normalize_text(getattr(config, "model_type", ""))

        load_kwargs = dict(common_kwargs)
        load_kwargs["dtype"] = dtype
        if use_device_map:
            load_kwargs["device_map"] = _deepseek_ocr_device_map()
        else:
            load_kwargs["low_cpu_mem_usage"] = True

        loader_candidates = []
        if model_type == "deepseek_vl_hybrid" and DeepseekVLHybridForConditionalGeneration is not None:
            loader_candidates.append(
                ("DeepseekVLHybridForConditionalGeneration", DeepseekVLHybridForConditionalGeneration.from_pretrained)
            )
        elif model_type == "deepseek_vl" and DeepseekVLForConditionalGeneration is not None:
            loader_candidates.append(
                ("DeepseekVLForConditionalGeneration", DeepseekVLForConditionalGeneration.from_pretrained)
            )
        if AutoModelForImageTextToText is not None:
            loader_candidates.append(("AutoModelForImageTextToText", AutoModelForImageTextToText.from_pretrained))
        if AutoModelForVision2Seq is not None:
            loader_candidates.append(("AutoModelForVision2Seq", AutoModelForVision2Seq.from_pretrained))
        if AutoModel is not None:
            loader_candidates.append(("AutoModel", AutoModel.from_pretrained))
        loader_candidates.append(("AutoModelForCausalLM", AutoModelForCausalLM.from_pretrained))

        if _deepseek_ocr_local_dir():
            emit_progress(f"Loading DeepSeek OCR model from local dir '{model_source}' on {runtime_device}...")
        elif cache_dir:
            emit_progress(
                f"Loading DeepSeek OCR model '{model_source}' using cache '{cache_dir}' on {runtime_device}..."
            )
        else:
            emit_progress(f"Loading DeepSeek OCR model '{model_source}' on {runtime_device}...")

        model_errors: List[str] = []
        model_obj = None
        for loader_name, loader in loader_candidates:
            try:
                with _known_model_load_warnings_context(env_prefix="DEEPSEEK_OCR"):
                    candidate_model = _call_from_pretrained_with_dtype_fallback(
                        loader,
                        model_source,
                        **load_kwargs,
                    )
                if processor_is_tokenizer_like and not _model_supports_image_aware_fallback(candidate_model):
                    model_errors.append(
                        f"{loader_name}: loaded successfully but does not expose an image-aware fallback "
                        "(`chat`, `generate(images=...)`, or `forward(images=...)`) while the processor is tokenizer-like"
                    )
                    continue
                model_obj = candidate_model
                break
            except Exception as exc:
                model_errors.append(f"{loader_name}: {exc}")

        if model_obj is None:
            raise RuntimeError(" ; ".join(model_errors))

        if not use_device_map:
            model_obj = model_obj.to(runtime_device)

        if getattr(model_obj, "generation_config", None) is not None:
            model_obj.generation_config.temperature = None
            model_obj.generation_config.top_p = None
            model_obj.generation_config.top_k = None
        model_obj.eval()

        _DEEPSEEK_OCR_MODEL = model_obj
        _DEEPSEEK_OCR_PROCESSOR = processor
        _DEEPSEEK_OCR_MODEL_ID = model_id
        _DEEPSEEK_OCR_LOAD_ERROR = None
        emit_progress("Loaded DeepSeek OCR model.")
        return _DEEPSEEK_OCR_MODEL, _DEEPSEEK_OCR_PROCESSOR
    except Exception as exc:
        if "LlamaFlashAttention2" in str(exc):
            exc = RuntimeError(
                "DeepSeek-OCR-2 remote code is not compatible with the currently installed Transformers stack. "
                f"{_deepseek_ocr_version_guidance_message()}"
            )
        _DEEPSEEK_OCR_LOAD_ERROR = (model_id, str(exc))
        raise


def transcribe_table_image_with_openrouter(
    image_data_uri: str,
    *,
    model_id: str,
    prompt: Optional[str] = None,
    reasoning_level: Optional[str] = None,
    max_tokens: int = 32000,
    max_attempts: Optional[int] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    attempt_plan = build_openrouter_attempt_plan(
        model_id,
        max_attempts=max_attempts or default_openrouter_ocr_max_attempts(),
    )
    prompt_text = prompt or default_table_image_transcription_prompt()
    last_response_error: Optional[RuntimeError] = None

    for attempt_index, candidate_model in enumerate(attempt_plan, start=1):
        progress_label = f"[ocr {candidate_model}]"
        client = TableOCROpenRouterClient(
            model_id=candidate_model,
            reasoning_level=reasoning_level or os.getenv("OPENROUTER_REASONING_LEVEL", "low"),
        )
        try:
            request_started_at = time.perf_counter()
            response = client.chat_completion(
                messages=[
                    {
                        "role": "user",
                        "content": [
                            {"type": "text", "text": prompt_text},
                            {"type": "image_url", "image_url": {"url": image_data_uri}},
                        ],
                    }
                ],
                max_tokens=max_tokens,
                temperature=0.0,
                progress_label=f"{progress_label} | request {attempt_index}/{len(attempt_plan)}",
                progress_handler=progress_handler,
            )
            request_latency_s = time.perf_counter() - request_started_at
        except TableOCROpenRouterResponseError as exc:
            last_response_error = exc
            if attempt_index < len(attempt_plan):
                next_model = attempt_plan[attempt_index]
                if next_model != candidate_model:
                    emit_progress(
                        f"[ocr {model_id}] | retrying with fallback model {next_model} after error: {exc}",
                        progress_handler=progress_handler,
                    )
                else:
                    emit_progress(
                        f"[ocr {model_id}] | retrying attempt {attempt_index + 1}/{len(attempt_plan)} "
                        f"with model {candidate_model} after error: {exc}",
                        progress_handler=progress_handler,
                    )
                continue
            raise

        summary = summarize_openrouter_chat_response(response)
        summary["total_latency_s"] = max(0.0, float(request_latency_s))
        text_content = extract_text_from_openrouter_content(summary["content"])
        if text_content is None:
            summary["thinking_latency_s"] = None
            summary["first_content_latency_s"] = None
        else:
            summary["thinking_latency_s"] = estimate_openrouter_thinking_latency_s(
                request_latency_s,
                reasoning_tokens=summary["reasoning_tokens"],
                completion_tokens=summary["completion_tokens"],
            )
        emit_progress(
            f"{progress_label} | finish_reason={summary['finish_reason'] or 'unknown'} | "
            f"provider={summary['provider'] or 'unknown'} | "
            f"tool_calls={summary['tool_call_count']} | "
            f"content_type={summary['content_type']}",
            progress_handler=progress_handler,
        )
        if summary["thinking_latency_s"] is not None:
            reasoning_tokens_label = (
                str(summary["reasoning_tokens"])
                if isinstance(summary["reasoning_tokens"], int)
                else "unknown"
            )
            completion_tokens_label = (
                str(summary["completion_tokens"])
                if isinstance(summary["completion_tokens"], int)
                else "unknown"
            )
            emit_progress(
                f"{progress_label} | total latency={summary['total_latency_s']:.2f}s"
                f" | estimated thinking latency={summary['thinking_latency_s']:.2f}s"
                f" | reasoning_tokens={reasoning_tokens_label}"
                f" | completion_tokens={completion_tokens_label}",
                progress_handler=progress_handler,
            )

        if text_content is None:
            detail_bits = [
                f"finish_reason={summary['finish_reason'] or 'unknown'}",
                f"provider={summary['provider'] or 'unknown'}",
                f"tool_calls={summary['tool_call_count']}",
                f"content_type={summary['content_type']}",
            ]
            if summary["refusal"]:
                detail_bits.append(f"refusal={normalize_text(summary['refusal'])[:200]}")
            exc = TableOCRContentError(
                f"OCR response did not contain text content ({', '.join(detail_bits)})",
                response_payload=response,
                details=summary,
            )
            last_response_error = exc
            if attempt_index < len(attempt_plan):
                next_model = attempt_plan[attempt_index]
                if next_model != candidate_model:
                    emit_progress(
                        f"[ocr {model_id}] | retrying with fallback model {next_model} after content error: {exc}",
                        progress_handler=progress_handler,
                    )
                else:
                    emit_progress(
                        f"[ocr {model_id}] | retrying attempt {attempt_index + 1}/{len(attempt_plan)} "
                        f"with model {candidate_model} after content error: {exc}",
                        progress_handler=progress_handler,
                    )
                continue
            raise exc
        return TableOCRTranscriptionText(
            strip_code_fences(text_content),
            effective_model_id=candidate_model,
            thinking_latency_s=summary["thinking_latency_s"],
            total_latency_s=summary["total_latency_s"],
            first_content_latency_s=summary["first_content_latency_s"],
            reasoning_tokens=summary["reasoning_tokens"],
            completion_tokens=summary["completion_tokens"],
        )

    if last_response_error is not None:
        raise last_response_error
    raise RuntimeError("OpenRouter OCR transcription failed without producing a result.")


def transcribe_table_image_with_qwen_ocr(
    image_data_uri: str,
    *,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    max_tokens: int = 32000,
    progress_handler: ProgressHandler = None,
) -> str:
    resolved_model = resolve_qwen_ocr_model_id(model_id)
    prompt_text = prompt or default_table_image_transcription_prompt()
    progress_label = f"[qwen_ocr {resolved_model}]"
    client = TableOCRQwenClient(model_id=resolved_model)
    configured_max_tokens = normalize_text(os.getenv("QWEN_OCR_MAX_TOKENS", ""))
    if configured_max_tokens:
        try:
            max_tokens = max(1, int(configured_max_tokens))
        except ValueError:
            pass
    request_started_at = time.perf_counter()
    response = client.chat_completion_streaming(
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": prompt_text},
                    {"type": "image_url", "image_url": {"url": image_data_uri}},
                ],
            }
        ],
        max_tokens=max_tokens,
        temperature=0.0,
        progress_label=progress_label,
        progress_handler=progress_handler,
        include_reasoning=True,
    )
    request_latency_s = time.perf_counter() - request_started_at

    summary = summarize_openrouter_chat_response(response)
    if summary["total_latency_s"] is None:
        summary["total_latency_s"] = max(0.0, float(request_latency_s))
    text_content = extract_text_from_openrouter_content(summary["content"])
    if text_content is None:
        raise TableOCRContentError(
            "Qwen OCR response did not contain text content.",
            response_payload=response,
            details=summary,
        )

    emit_progress(
        f"{progress_label} | finish_reason={summary['finish_reason'] or 'unknown'} | "
        f"provider={summary['provider'] or 'unknown'} | "
        f"total latency={summary['total_latency_s']:.2f}s"
        + (
            f" | thinking latency={summary['thinking_latency_s']:.2f}s"
            if isinstance(summary["thinking_latency_s"], (int, float))
            else ""
        ),
        progress_handler=progress_handler,
    )
    return TableOCRTranscriptionText(
        strip_code_fences(text_content),
        effective_model_id=resolved_model,
        thinking_latency_s=summary["thinking_latency_s"],
        total_latency_s=summary["total_latency_s"],
        first_content_latency_s=summary["first_content_latency_s"],
        reasoning_tokens=summary["reasoning_tokens"],
        completion_tokens=summary["completion_tokens"],
    )


def gemma4_vllm_launch_hint() -> str:
    return (
        "Start local vLLM for Gemma 4 with thinking and the full OCR vision budget, for example: "
        "vllm serve google/gemma-4-26B-A4B-it --host 0.0.0.0 --port 8000 "
        "--dtype bfloat16 --max-model-len 32768 --gpu-memory-utilization 0.90 "
        "--limit-mm-per-prompt '{\"image\":1}' "
        "--mm-processor-kwargs '{\"max_soft_tokens\":1120}' "
        "--hf-overrides '{\"vision_config\":{\"default_output_length\":1120},\"vision_soft_tokens_per_image\":1120}' "
        "--reasoning-parser gemma4 --default-chat-template-kwargs '{\"enable_thinking\":true}'"
    )


def gemma4_hf_load_hint() -> str:
    return (
        "Use Gemma 4 locally through plain Hugging Face Transformers, for example after installing "
        "`transformers torch torchvision accelerate` with model `google/gemma-4-26B-A4B-it`."
    )


def _gemma4_hf_max_new_tokens() -> int:
    return _env_int("GEMMA4_HF_MAX_NEW_TOKENS", 8192)


def _gemma4_hf_device_map() -> str:
    return normalize_text(os.getenv("GEMMA4_HF_DEVICE_MAP", "auto")) or "auto"


def _decode_image_data_uri_for_gemma4_hf(image_data_uri: str) -> tuple[bytes, str]:
    import base64

    normalized = normalize_text(image_data_uri)
    if not normalized.startswith("data:") or "," not in normalized:
        raise RuntimeError("Gemma 4 HF backend expected a data URI image payload.")
    header, payload = normalized.split(",", 1)
    media_type = header[5:].split(";", 1)[0].strip().lower()
    suffix = {
        "image/png": ".png",
        "image/jpeg": ".jpg",
        "image/jpg": ".jpg",
        "image/webp": ".webp",
        "image/gif": ".gif",
        "image/bmp": ".bmp",
    }.get(media_type, ".png")
    try:
        return base64.b64decode(payload), suffix
    except Exception as exc:
        raise RuntimeError("Gemma 4 HF backend could not decode the image data URI.") from exc


def _load_gemma4_hf_backend(model_id: str) -> tuple[Any, Any]:
    cache = getattr(_load_gemma4_hf_backend, "_cache", None)
    if isinstance(cache, dict) and cache.get("model_id") == model_id:
        return cache["processor"], cache["model"]

    try:
        import transformers
        from transformers import AutoProcessor
    except Exception as exc:
        raise RuntimeError(f"Gemma 4 HF backend could not import Transformers. {gemma4_hf_load_hint()}") from exc

    auto_model_cls = getattr(transformers, "AutoModelForMultimodalLM", None)
    if auto_model_cls is None:
        auto_model_cls = getattr(transformers, "AutoModelForImageTextToText", None)
    if auto_model_cls is None:
        raise RuntimeError(
            "Installed Transformers does not expose `AutoModelForMultimodalLM` or `AutoModelForImageTextToText`. "
            f"{gemma4_hf_load_hint()}"
        )

    processor = AutoProcessor.from_pretrained(model_id)
    try:
        model = auto_model_cls.from_pretrained(
            model_id,
            device_map=_gemma4_hf_device_map(),
            torch_dtype="auto",
        )
    except TypeError:
        model = auto_model_cls.from_pretrained(
            model_id,
            device_map=_gemma4_hf_device_map(),
            dtype="auto",
        )
    model.eval()
    _load_gemma4_hf_backend._cache = {
        "model_id": model_id,
        "processor": processor,
        "model": model,
    }
    return processor, model


def _gemma4_hf_input_device(model: Any) -> Any:
    import torch

    model_device = getattr(model, "device", None)
    if isinstance(model_device, torch.device) and model_device.type != "meta":
        return model_device
    if torch.cuda.is_available():
        return torch.device("cuda")
    return torch.device("cpu")


def _extract_gemma4_hf_text_value(value: Any) -> Optional[str]:
    if isinstance(value, str):
        return value if normalize_text(value) else None
    if isinstance(value, dict):
        for key in ("content", "text", "response", "output", "answer", "final", "generated_text"):
            extracted = _extract_gemma4_hf_text_value(value.get(key))
            if extracted:
                return extracted
        for nested_value in value.values():
            extracted = _extract_gemma4_hf_text_value(nested_value)
            if extracted:
                return extracted
        return None
    if isinstance(value, list):
        for item in value:
            extracted = _extract_gemma4_hf_text_value(item)
            if extracted:
                return extracted
    return None


def _extract_gemma4_hf_response_text(processor: Any, generated_text: str) -> str:
    parse_response = getattr(processor, "parse_response", None)
    if callable(parse_response):
        try:
            parsed = parse_response(generated_text)
        except Exception:
            parsed = None
        parsed_text = _extract_gemma4_hf_text_value(parsed)
        if parsed_text:
            cleaned_text, _ = _strip_gemma4_unparsed_thinking(parsed_text)
            if normalize_text(cleaned_text):
                return cleaned_text
    cleaned_text, _ = _strip_gemma4_unparsed_thinking(generated_text)
    return cleaned_text


def transcribe_table_image_with_gemma4_hf(
    image_data_uri: str,
    *,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    from pathlib import Path
    import tempfile
    import time
    import torch

    resolved_model = resolve_gemma4_hf_model_id(model_id)
    prompt_text = prompt or default_table_image_transcription_prompt()
    progress_label = f"[gemma4_hf {resolved_model}]"

    emit_progress(
        f"{progress_label} | local transformers multimodal | thinking=off",
        progress_handler=progress_handler,
    )

    try:
        processor, model = _load_gemma4_hf_backend(resolved_model)
    except Exception as exc:
        raise RuntimeError(f"{exc}\n{gemma4_hf_load_hint()}") from exc

    started_at = time.perf_counter()
    try:
        image_bytes, image_suffix = _decode_image_data_uri_for_gemma4_hf(image_data_uri)
        with tempfile.TemporaryDirectory(prefix="gemma4_hf_ocr_") as tmp_dir:
            image_path = Path(tmp_dir) / f"table{image_suffix}"
            image_path.write_bytes(image_bytes)
            messages = [
                {
                    "role": "user",
                    "content": [
                        {"type": "image", "path": str(image_path)},
                        {"type": "text", "text": prompt_text},
                    ],
                }
            ]
            inputs = processor.apply_chat_template(
                messages,
                tokenize=True,
                return_dict=True,
                return_tensors="pt",
                add_generation_prompt=True,
            ).to(_gemma4_hf_input_device(model))
            input_len = inputs["input_ids"].shape[-1]
            with torch.inference_mode():
                outputs = model.generate(
                    **inputs,
                    max_new_tokens=_gemma4_hf_max_new_tokens(),
                    do_sample=False,
                )
            generated_text = processor.decode(outputs[0][input_len:], skip_special_tokens=False)
    except Exception as exc:
        raise RuntimeError(f"Gemma 4 HF OCR call failed: {exc}\n{gemma4_hf_load_hint()}") from exc

    total_latency_s = time.perf_counter() - started_at
    text_content = _extract_gemma4_hf_response_text(processor, generated_text)
    if not normalize_text(text_content):
        raise TableOCRContentError(
            "Gemma 4 Hugging Face response did not contain text content.",
            details={
                "model_id": resolved_model,
                "generated_text_preview": generated_text[-4000:],
            },
        )

    emit_progress(
        f"{progress_label} | local transformers response | total latency={total_latency_s:.2f}s | content_chars={len(text_content)}",
        progress_handler=progress_handler,
    )
    return TableOCRTranscriptionText(
        strip_code_fences(text_content),
        effective_model_id=resolved_model,
        total_latency_s=total_latency_s,
    )


def _gemma4_vllm_max_tokens() -> int:
    return _env_int("GEMMA4_VLLM_MAX_TOKENS", 32000)


def _gemma4_vllm_temperature() -> float:
    return _env_float("GEMMA4_VLLM_TEMPERATURE", 0.0, min_value=0.0, max_value=2.0)


def _gemma4_vllm_enable_thinking() -> bool:
    return _env_flag("GEMMA4_VLLM_ENABLE_THINKING", "1")


def _gemma4_vllm_require_thinking_latency() -> bool:
    return _env_flag("GEMMA4_VLLM_REQUIRE_THINKING_LATENCY", "1")


def _strip_gemma4_unparsed_thinking(text: str) -> tuple[str, bool]:
    rendered = str(text or "")
    had_thought_block = bool(_GEMMA4_THOUGHT_BLOCK_RE.search(rendered) or _GEMMA4_THINK_BLOCK_RE.search(rendered))
    rendered = _GEMMA4_THOUGHT_BLOCK_RE.sub("", rendered)
    rendered = _GEMMA4_THINK_BLOCK_RE.sub("", rendered)
    if had_thought_block:
        rendered = _GEMMA4_CHANNEL_MARKER_RE.sub("", rendered)
    return rendered.strip(), had_thought_block


def transcribe_table_image_with_gemma4_vllm(
    image_data_uri: str,
    *,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    resolved_model = resolve_gemma4_vllm_model_id(model_id)
    prompt_text = prompt or default_table_image_transcription_prompt()
    progress_label = f"[gemma4_vllm {resolved_model}]"
    client = TableOCRGemma4VLLMClient(model_id=resolved_model)

    emit_progress(
        f"{progress_label} | local vLLM streaming | thinking=on | expects --reasoning-parser gemma4",
        progress_handler=progress_handler,
    )
    try:
        response = client.chat_completion_streaming(
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "image_url", "image_url": {"url": image_data_uri}},
                        {"type": "text", "text": prompt_text},
                    ],
                }
            ],
            max_tokens=_gemma4_vllm_max_tokens(),
            temperature=_gemma4_vllm_temperature(),
            progress_label=progress_label,
            progress_handler=progress_handler,
            include_reasoning=True,
        )
    except TableOCRRemoteResponseError as exc:
        raise RuntimeError(f"{exc}\n{gemma4_vllm_launch_hint()}") from exc

    summary = summarize_openrouter_chat_response(response)
    text_content = extract_text_from_openrouter_content(summary["content"])
    if text_content is None:
        raise TableOCRContentError(
            "Gemma 4 vLLM response did not contain text content.",
            response_payload=response,
            details=summary,
        )
    text_content, stripped_unparsed_thinking = _strip_gemma4_unparsed_thinking(text_content)
    if not normalize_text(text_content):
        raise TableOCRContentError(
            "Gemma 4 vLLM response contained only unparsed thinking content.",
            response_payload=response,
            details=summary,
        )
    if (
        _gemma4_vllm_enable_thinking()
        and _gemma4_vllm_require_thinking_latency()
        and not isinstance(summary["thinking_latency_s"], (int, float))
    ):
        raise TableOCRContentError(
            "Gemma 4 vLLM thinking latency was unavailable. Restart vLLM with "
            "`--reasoning-parser gemma4 --default-chat-template-kwargs '{\"enable_thinking\":true}'` "
            "so reasoning is streamed separately from OCR content. "
            "Set GEMMA4_VLLM_REQUIRE_THINKING_LATENCY=0 only if you intentionally want to score without it.",
            response_payload=response,
            details={
                **summary,
                "stripped_unparsed_thinking": bool(stripped_unparsed_thinking),
                "launch_hint": gemma4_vllm_launch_hint(),
            },
        )
    if normalize_text(summary["finish_reason"]).lower() == "length":
        raise TableOCRContentError(
            "Gemma 4 vLLM hit finish_reason=length before producing a complete OCR answer. "
            "This usually means thinking was not parsed out or GEMMA4_VLLM_MAX_TOKENS is too low.",
            response_payload=response,
            details={
                **summary,
                "stripped_unparsed_thinking": bool(stripped_unparsed_thinking),
            },
        )

    emit_progress(
        f"{progress_label} | finish_reason={summary['finish_reason'] or 'unknown'} | "
        f"total latency={summary['total_latency_s']:.2f}s | content_chars={len(text_content)}"
        + (
            f" | thinking latency={summary['thinking_latency_s']:.2f}s"
            if isinstance(summary["thinking_latency_s"], (int, float))
            else " | thinking latency=unavailable; confirm vLLM was started with --reasoning-parser gemma4"
        ),
        progress_handler=progress_handler,
    )
    return TableOCRTranscriptionText(
        strip_code_fences(text_content),
        effective_model_id=resolved_model,
        thinking_latency_s=summary["thinking_latency_s"],
        total_latency_s=summary["total_latency_s"],
        first_content_latency_s=summary["first_content_latency_s"],
        reasoning_tokens=summary["reasoning_tokens"],
        completion_tokens=summary["completion_tokens"],
    )


def gemma4_llamacpp_launch_hint() -> str:
    return (
        "Start llama.cpp with Gemma 4 vision budget enabled, for example: "
        "llama-server --model /models/Gemma4/gemma-4-26B-it-Q8_0.gguf "
        "--mmproj /models/Gemma4/mmproj-F32.gguf --jinja "
        "--chat-template-file /models/Gemma4/google-gemma-4-26B-it-interleaved.jinja "
        "--image-min-tokens 560 --image-max-tokens 2240 "
        "--batch-size 4096 --ubatch-size 4096"
    )


def _gemma4_llamacpp_max_tokens() -> int:
    return _env_int("GEMMA4_LLAMA_CPP_MAX_TOKENS", 32000)


def _gemma4_llamacpp_temperature() -> float:
    return _env_float("GEMMA4_LLAMA_CPP_TEMPERATURE", 0.0, min_value=0.0, max_value=2.0)


def transcribe_table_image_with_gemma4_llamacpp(
    image_data_uri: str,
    *,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    resolved_model = resolve_gemma4_llamacpp_model_id(model_id)
    prompt_text = prompt or default_table_image_transcription_prompt()
    progress_label = f"[gemma4_llamacpp {resolved_model}]"
    client = TableOCRGemma4LlamaCppClient(model_id=resolved_model)

    emit_progress(
        f"{progress_label} | expects llama-server with --image-min-tokens 560 "
        "--image-max-tokens 2240 --batch-size 4096 --ubatch-size 4096",
        progress_handler=progress_handler,
    )
    normalized_max_pixels = _table_ocr_normalized_max_image_pixels()
    if 0 < normalized_max_pixels < 2_600_000:
        emit_progress(
            f"{progress_label} | shared image cap is {normalized_max_pixels:,} pixels; "
            "raise TABLE_OCR_NORMALIZED_MAX_IMAGE_PIXELS for full high-budget Gemma 4 vision tests",
            progress_handler=progress_handler,
        )
    request_started_at = time.perf_counter()
    try:
        response = client.chat_completion(
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": prompt_text},
                        {"type": "image_url", "image_url": {"url": image_data_uri}},
                    ],
                }
            ],
            max_tokens=_gemma4_llamacpp_max_tokens(),
            temperature=_gemma4_llamacpp_temperature(),
            progress_label=progress_label,
            progress_handler=progress_handler,
        )
    except TableOCRRemoteResponseError as exc:
        raise RuntimeError(f"{exc}\n{gemma4_llamacpp_launch_hint()}") from exc
    request_latency_s = time.perf_counter() - request_started_at

    summary = summarize_openrouter_chat_response(response)
    summary["total_latency_s"] = max(0.0, float(request_latency_s))
    text_content = extract_text_from_openrouter_content(summary["content"])
    if text_content is None:
        raise TableOCRContentError(
            "Gemma 4 llama.cpp response did not contain text content.",
            response_payload=response,
            details=summary,
        )

    emit_progress(
        f"{progress_label} | finish_reason={summary['finish_reason'] or 'unknown'} | "
        f"total latency={summary['total_latency_s']:.2f}s | content_chars={len(text_content)}",
        progress_handler=progress_handler,
    )
    return TableOCRTranscriptionText(
        strip_code_fences(text_content),
        effective_model_id=resolved_model,
        total_latency_s=summary["total_latency_s"],
        first_content_latency_s=summary["first_content_latency_s"],
        reasoning_tokens=summary["reasoning_tokens"],
        completion_tokens=summary["completion_tokens"],
    )


def transcribe_table_image_with_deepseek(
    image_data_uri: str,
    *,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    del progress_handler
    sec_parser = load_sec_parser_module()
    resolved_model = normalize_text(model_id or default_deepseek_ocr_model_id())
    if not resolved_model:
        raise RuntimeError(
            "Missing DeepSeek OCR model id. Pass a Hugging Face model id or set DEEPSEEK_OCR_MODEL_ID."
        )
    try:
        import torch
    except ImportError as exc:
        raise RuntimeError("PyTorch is required for DeepSeek OCR transcription.") from exc

    model_obj, processor = _get_deepseek_table_backend(resolved_model)
    model_device = sec_parser._model_input_device(model_obj)
    runtime_device = model_device.type
    page_image = _prepare_deepseek_ocr_image(
        sec_parser._decode_data_uri_to_pil_image(image_data_uri),
        runtime_device,
    )
    prompt_text = prompt or default_table_image_transcription_prompt()
    infer_exc: Optional[Exception] = None
    if callable(getattr(model_obj, "infer", None)):
        try:
            return _require_nonempty_ocr_text_output(
                _run_deepseek_infer_fallback(
                    model_obj,
                    processor,
                    page_image,
                    prompt_text,
                    runtime_device,
                ),
                backend_label="DeepSeek infer(...) fallback",
            )
        except Exception as exc:
            infer_exc = exc
            infer_message = str(infer_exc)
            if "position_embeddings" in infer_message or "LlamaAttention.forward()" in infer_message:
                raise RuntimeError(_deepseek_ocr_version_guidance_message()) from infer_exc
            emit_progress(f"DeepSeek infer fallback failed: {infer_exc}")
    try:
        inputs = _build_deepseek_inputs(
            processor,
            page_image,
            prompt_text,
        )
    except TypeError as exc:
        if "unexpected keyword argument 'images'" not in str(exc):
            raise
        generate_exc: Optional[Exception] = None
        try:
            return _require_nonempty_ocr_text_output(
                _run_deepseek_generate_fallback(model_obj, processor, page_image, prompt_text, model_device),
                backend_label="DeepSeek generate() fallback",
                details={"infer_failure": str(infer_exc) if infer_exc else None},
            )
        except Exception as exc2:
            generate_exc = exc2
            emit_progress(f"DeepSeek generate fallback failed: {generate_exc}")
        try:
            return _require_nonempty_ocr_text_output(
                _run_deepseek_chat_fallback(model_obj, processor, page_image, prompt_text),
                backend_label="DeepSeek chat() fallback",
                details={
                    "infer_failure": str(infer_exc) if infer_exc else None,
                    "generate_failure": str(generate_exc) if generate_exc else None,
                },
            )
        except Exception as chat_exc:
            raise RuntimeError(
                "DeepSeek OCR fallback exhausted. "
                f"model={type(model_obj).__name__}, processor={type(processor).__name__}; "
                f"infer fallback failed: {infer_exc}; "
                f"generate fallback failed: {generate_exc}; "
                f"chat fallback failed: {chat_exc}"
            ) from chat_exc
    inputs = inputs.to(model_device)

    with torch.inference_mode():
        generated_ids = model_obj.generate(
            **inputs,
            max_new_tokens=_deepseek_ocr_max_new_tokens(),
            do_sample=False,
        )

    input_ids = getattr(inputs, "input_ids", None)
    if input_ids is None and isinstance(inputs, dict):
        input_ids = inputs.get("input_ids")
    raw_output = _decode_deepseek_generated_output(processor, generated_ids, input_ids=input_ids)
    return _require_nonempty_ocr_text_output(
        raw_output,
        backend_label="DeepSeek direct generate()",
        details={"infer_failure": str(infer_exc) if infer_exc else None},
    )


def _decode_image_data_uri_bytes(image_data_uri: str) -> bytes:
    try:
        header, encoded = image_data_uri.split(",", 1)
    except ValueError as exc:
        raise RuntimeError("Expected a valid data URI for Mistral OCR image transcription.") from exc
    if ";base64" not in header:
        raise RuntimeError("Expected a base64-encoded data URI for Mistral OCR image transcription.")
    try:
        return base64.b64decode(encoded)
    except Exception as exc:
        raise RuntimeError("Could not decode the Mistral OCR image data URI.") from exc


def _decode_table_ocr_image_data_uri_bytes(image_data_uri: str) -> bytes:
    try:
        header, encoded = image_data_uri.split(",", 1)
    except ValueError as exc:
        raise RuntimeError("Expected a valid data URI for table OCR image transcription.") from exc
    if ";base64" not in header:
        raise RuntimeError("Expected a base64-encoded data URI for table OCR image transcription.")
    try:
        return base64.b64decode(encoded)
    except Exception as exc:
        raise RuntimeError("Could not decode the table OCR image data URI.") from exc


def _normalize_table_ocr_image_data_uri(
    image_data_uri: str,
    *,
    progress_handler: ProgressHandler = None,
) -> str:
    max_pixels = _table_ocr_normalized_max_image_pixels()
    if max_pixels <= 0:
        return image_data_uri

    image_bytes = _decode_table_ocr_image_data_uri_bytes(image_data_uri)
    try:
        from PIL import Image

        with Image.open(io.BytesIO(image_bytes)) as opened_image:
            opened_image.load()
            original_image = opened_image.convert("RGB")
    except ImportError as exc:
        raise RuntimeError("Pillow is required to normalize table OCR image resolution.") from exc
    except Exception as exc:
        raise RuntimeError("Could not read the table OCR image for resolution normalization.") from exc

    original_width, original_height = original_image.size
    normalized_image = _resize_image_to_max_pixels(original_image, max_pixels)
    normalized_width, normalized_height = normalized_image.size
    if (normalized_width, normalized_height) == (original_width, original_height):
        return image_data_uri

    output = io.BytesIO()
    normalized_image.save(output, format="PNG")
    emit_progress(
        f"Normalized table OCR image from {original_width}x{original_height} "
        f"to {normalized_width}x{normalized_height} with max {max_pixels:,} pixels.",
        progress_handler=progress_handler,
    )
    encoded = base64.b64encode(output.getvalue()).decode("ascii")
    return f"data:image/png;base64,{encoded}"


def _data_uri_file_suffix(image_data_uri: str) -> str:
    header = image_data_uri.split(",", 1)[0].lower()
    if "image/jpeg" in header or "image/jpg" in header:
        return ".jpg"
    if "image/webp" in header:
        return ".webp"
    return ".png"


def _inline_mistral_table_placeholders(page_obj: Dict[str, Any], text_content: str) -> str:
    rendered = str(text_content or "")
    tables = page_obj.get("tables")
    if not isinstance(tables, list) or not tables:
        return rendered

    inlined_count = 0
    fallback_contents: List[str] = []
    for table in tables:
        if not isinstance(table, dict):
            continue
        table_id = normalize_text(table.get("id"))
        table_content = normalize_text(table.get("content"))
        if not table_content:
            continue
        if table_id:
            placeholder = f"[{table_id}]({table_id})"
            if placeholder in rendered:
                rendered = rendered.replace(placeholder, table_content)
                inlined_count += 1
                continue
        fallback_contents.append(table_content)

    # Some OCR responses may return only placeholders or very short markdown.
    # If we failed to inline but do have table payloads, return the table contents directly.
    if inlined_count == 0 and fallback_contents:
        return "\n\n".join(fallback_contents)

    return rendered


def _build_mistral_ocr_payload(
    *,
    model: str,
    signed_url: str,
    table_format: str,
    prompt_text: str,
) -> Dict[str, Any]:
    payload: Dict[str, Any] = {
        "model": model,
        "document": {
            "type": "document_url",
            "document_url": signed_url,
        },
        "table_format": table_format,
    }
    normalized_prompt = normalize_text(prompt_text)
    if normalized_prompt:
        # Mistral OCR does not expose a direct prompt field for the page markdown/tables
        # output. The supported guided path is document_annotation_prompt + format.
        # The API currently requires a json_schema-backed document_annotation_format.
        payload["document_annotation_format"] = {
            "type": "json_schema",
            "json_schema": {
                "name": "ocr_table_transcription",
                "strict": True,
                "schema": {
                    "type": "object",
                    "properties": {
                        "transcription": {"type": "string"},
                    },
                    "required": ["transcription"],
                    "additionalProperties": False,
                },
            },
        }
        payload["document_annotation_prompt"] = normalized_prompt
    return payload


def _extract_mistral_prompted_text(response_payload: Dict[str, Any]) -> str:
    def unwrap_annotation_text(value: Any) -> str:
        if not isinstance(value, str):
            return ""
        normalized = normalize_text(value)
        if not normalized:
            return ""
        stripped = normalized.strip()
        if stripped.startswith("{") and stripped.endswith("}"):
            try:
                payload = json.loads(stripped)
            except Exception:
                return normalized
            if isinstance(payload, dict):
                for key in ("transcription", "text", "content", "value", "html"):
                    nested = payload.get(key)
                    if isinstance(nested, str) and normalize_text(nested):
                        return normalize_text(nested)
        return normalized

    annotation = response_payload.get("document_annotation")
    if isinstance(annotation, str):
        return unwrap_annotation_text(annotation)
    if isinstance(annotation, dict):
        transcription = annotation.get("transcription")
        if isinstance(transcription, str) and normalize_text(transcription):
            return unwrap_annotation_text(transcription)
        for key in ("text", "content", "value"):
            value = annotation.get(key)
            if isinstance(value, str) and normalize_text(value):
                return unwrap_annotation_text(value)
    return ""


def transcribe_table_image_with_mistral(
    image_data_uri: str,
    *,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    resolved_model = normalize_text(model_id or default_mistral_ocr_model_id())
    if not resolved_model:
        raise RuntimeError(
            "Missing Mistral OCR model id. Pass a model id or set MISTRAL_OCR_MODEL_ID."
        )

    api_key = normalize_text(os.getenv("MISTRAL_API_KEY", ""))
    if not api_key:
        raise RuntimeError("Missing MISTRAL_API_KEY for Mistral OCR transcription.")

    sec_parser = load_sec_parser_module()
    progress_label = f"[ocr {resolved_model}]"
    image_bytes = _decode_image_data_uri_bytes(image_data_uri)
    table_format = _mistral_ocr_table_format()
    prompt_text = normalize_text(prompt or default_table_image_transcription_prompt())

    emit_progress(
        f"{progress_label} | upload image to Mistral OCR",
        progress_handler=progress_handler,
    )
    client = sec_parser.Mistral(api_key=api_key)
    upload = client.files.upload(
        file={
            "file_name": f"ocr_table{_data_uri_file_suffix(image_data_uri)}",
            "content": image_bytes,
        },
        purpose="ocr",
    )
    if not upload or not getattr(upload, "id", None):
        raise RuntimeError("Mistral OCR image upload failed to return a valid file id.")

    signed_url = sec_parser.get_signed_url_with_retry(client, file_id=upload.id)
    payload = _build_mistral_ocr_payload(
        model=resolved_model,
        signed_url=signed_url,
        table_format=table_format,
        prompt_text=prompt_text,
    )

    emit_progress(
        f"{progress_label} | request 1/1 | table_format={table_format}",
        progress_handler=progress_handler,
    )
    response = requests.post(
        sec_parser.OCR_API_URL,
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        },
        json=payload,
        timeout=600,
    )
    if response.status_code >= 400:
        raise RuntimeError(f"Mistral OCR HTTP {response.status_code}: {response.text[:1500]}")
    response_payload = response.json()
    emit_progress(
        f"{progress_label} | response received",
        progress_handler=progress_handler,
    )

    prompted_text_content = _extract_mistral_prompted_text(response_payload)
    if prompted_text_content:
        emit_progress(
            f"{progress_label} | using prompted document_annotation | content_chars={len(prompted_text_content)}",
            progress_handler=progress_handler,
        )
        return strip_code_fences(prompted_text_content)

    pages = response_payload.get("pages")
    if not isinstance(pages, list) or not pages:
        raise TableOCRContentError(
            "Mistral OCR response did not include any pages.",
            response_payload=response_payload,
            details={
                "top_level_keys": sorted(str(key) for key in response_payload.keys()),
            },
        )

    first_page = pages[0]
    if not isinstance(first_page, dict):
        raise TableOCRContentError(
            f"Mistral OCR first page was {type(first_page).__name__}, expected an object.",
            response_payload=response_payload,
            details={"page_type": type(first_page).__name__},
        )

    raw_text_content = normalize_text(sec_parser._pick_text(first_page))
    text_content = normalize_text(_inline_mistral_table_placeholders(first_page, raw_text_content))
    if not text_content:
        raise TableOCRContentError(
            "Mistral OCR response did not contain markdown/text content for the first page.",
            response_payload=response_payload,
            details={
                "page_keys": sorted(str(key) for key in first_page.keys()),
                "page_count": len(pages),
                "table_format": table_format,
            },
        )

    emit_progress(
        f"{progress_label} | pages={len(pages)} | content_chars={len(text_content)}",
        progress_handler=progress_handler,
    )
    return strip_code_fences(text_content)


def transcribe_table_image_with_firered(
    image_data_uri: str,
    *,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    sec_parser = load_sec_parser_module()
    model_name = resolve_firered_model_id(model_id)
    if not model_name:
        raise RuntimeError("Missing OCR model id for FireRed transcription.")
    progress_label = f"[ocr {model_name}]"

    try:
        import torch
    except ImportError as exc:
        raise RuntimeError("PyTorch is required for OCR transcription.") from exc

    emit_progress(
        f"{progress_label} | local FireRed load",
        progress_handler=progress_handler,
    )
    model_obj, processor = sec_parser._get_firered_table_backend(model_name)
    runtime_device = sec_parser._model_input_device(model_obj).type
    original_image = sec_parser._decode_data_uri_to_pil_image(image_data_uri)
    if _table_ocr_allow_backend_image_resize():
        base_page_image = sec_parser._prepare_firered_image(original_image, runtime_device)
    else:
        base_page_image = original_image.convert("RGB")

    prompt_text = prompt or default_table_image_transcription_prompt()
    candidate_images = [("initial", base_page_image)]
    if runtime_device == "mps" and _table_ocr_allow_backend_image_resize():
        base_pixels = base_page_image.size[0] * base_page_image.size[1]
        seen_sizes = {base_page_image.size}
        for retry_limit in firered_mps_retry_pixel_limits():
            if retry_limit >= base_pixels:
                continue
            retry_image = _resize_image_to_max_pixels(original_image, retry_limit)
            if retry_image.size in seen_sizes:
                continue
            candidate_images.append((f"retry_max_pixels={retry_limit}", retry_image))
            seen_sizes.add(retry_image.size)

    last_exc: Optional[Exception] = None
    for attempt_index, (attempt_label, page_image) in enumerate(candidate_images, start=1):
        if attempt_index > 1:
            emit_progress(
                f"{progress_label} | retry local FireRed with {attempt_label} after buffer error: {last_exc}",
                progress_handler=progress_handler,
            )

        messages = [
            {
                "role": "user",
                "content": [
                    {"type": "image", "image": page_image},
                    {"type": "text", "text": prompt_text},
                ],
            }
        ]

        chat_text = processor.apply_chat_template(
            messages,
            tokenize=False,
            add_generation_prompt=True,
        )

        inputs = processor(
            text=[chat_text],
            images=[page_image],
            return_tensors="pt",
        )
        inputs = inputs.to(sec_parser._model_input_device(model_obj))

        emit_progress(
            f"{progress_label} | local FireRed generate | device={runtime_device} | attempt={attempt_index}/{len(candidate_images)} | image={page_image.size[0]}x{page_image.size[1]}",
            progress_handler=progress_handler,
        )
        try:
            with torch.inference_mode():
                generated_ids = model_obj.generate(
                    **inputs,
                    max_new_tokens=sec_parser.Config.FIRERED_MAX_NEW_TOKENS,
                    do_sample=False,
                )
        except Exception as exc:
            last_exc = exc
            if runtime_device == "mps" and attempt_index < len(candidate_images) and _is_firered_buffer_error(exc):
                continue
            raise

        trimmed = generated_ids[:, inputs.input_ids.shape[1] :]
        raw_output = processor.batch_decode(
            trimmed,
            skip_special_tokens=True,
            clean_up_tokenization_spaces=False,
        )[0]
        cleaned_output = _require_nonempty_ocr_text_output(
            raw_output,
            backend_label="FireRed local generate()",
            details={"model_id": model_name, "device": runtime_device},
        )
        emit_progress(
            f"{progress_label} | local FireRed response | content_chars={len(cleaned_output)}",
            progress_handler=progress_handler,
        )
        return TableOCRTranscriptionText(
            cleaned_output,
            effective_model_id=model_name,
        )

    if last_exc is not None:
        raise last_exc
    raise RuntimeError("FireRed OCR exhausted local retries without producing output.")


def transcribe_table_image_with_qianfan(
    image_data_uri: str,
    *,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    del progress_handler
    resolved_model = resolve_qianfan_model_id(model_id)
    sec_parser = load_sec_parser_module()
    model_obj, processor, runtime_device = _get_generic_ocr_backend(
        resolved_model,
        env_prefix="QIANFAN_OCR",
    )
    model_device = sec_parser._model_input_device(model_obj)
    page_image = _prepare_backend_image(
        sec_parser._decode_data_uri_to_pil_image(image_data_uri),
        env_prefix="QIANFAN_OCR",
        runtime_device=runtime_device,
    )
    prompt_text = prompt or default_table_image_transcription_prompt()
    tokenizer_like = processor
    pixel_values = _build_qianfan_pixel_values(page_image)
    try:
        pixel_values = pixel_values.to(device=model_device, dtype=getattr(model_obj, "dtype", None))
    except Exception:
        try:
            pixel_values = pixel_values.to(model_device)
        except Exception:
            pass
    with __import__("torch").inference_mode():
        raw_output = model_obj.chat(
            tokenizer_like,
            pixel_values=pixel_values,
            question=prompt_text,
            generation_config={"max_new_tokens": _backend_max_new_tokens("QIANFAN_OCR", 4096)},
        )
    return _require_nonempty_ocr_text_output(
        raw_output,
        backend_label="Qianfan OCR local chat()",
        details={"model_id": resolved_model, "device": runtime_device},
    )


def transcribe_table_image_with_glm_ocr(
    image_data_uri: str,
    *,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    del progress_handler
    resolved_model = resolve_glm_ocr_model_id(model_id)
    sec_parser = load_sec_parser_module()
    model_obj, processor, runtime_device = _get_generic_ocr_backend(
        resolved_model,
        env_prefix="GLM_OCR",
    )
    model_device = sec_parser._model_input_device(model_obj)
    page_image = _prepare_backend_image(
        sec_parser._decode_data_uri_to_pil_image(image_data_uri),
        env_prefix="GLM_OCR",
        runtime_device=runtime_device,
    )
    prompt_text = prompt or "Table Recognition:"
    raw_output = _run_generate_style_backend(
        model_obj,
        processor,
        page_image,
        prompt_text,
        env_prefix="GLM_OCR",
        model_device=model_device,
    )
    return _require_nonempty_ocr_text_output(
        raw_output,
        backend_label="GLM-OCR local generate()",
        details={"model_id": resolved_model, "device": runtime_device},
    )


def transcribe_table_image_with_paddleocr_vl(
    image_data_uri: str,
    *,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    del progress_handler
    resolved_model = resolve_paddleocr_vl_model_id(model_id)
    sec_parser = load_sec_parser_module()
    model_obj, processor, runtime_device = _get_generic_ocr_backend(
        resolved_model,
        env_prefix="PADDLEOCR_VL",
    )
    model_device = sec_parser._model_input_device(model_obj)
    page_image = _prepare_backend_image(
        sec_parser._decode_data_uri_to_pil_image(image_data_uri),
        env_prefix="PADDLEOCR_VL",
        runtime_device=runtime_device,
    )
    prompt_text = prompt or default_table_image_transcription_prompt()
    raw_output = _run_generate_style_backend(
        model_obj,
        processor,
        page_image,
        prompt_text,
        env_prefix="PADDLEOCR_VL",
        model_device=model_device,
    )
    return _require_nonempty_ocr_text_output(
        raw_output,
        backend_label="PaddleOCR-VL local generate()",
        details={"model_id": resolved_model, "device": runtime_device},
    )


def transcribe_table_image_with_got_ocr(
    image_data_uri: str,
    *,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    del progress_handler
    # GOT-OCR's exposed local interface only supports its native formatted OCR prompt.
    del prompt
    _ensure_transformers_dynamic_cache_compatibility()
    resolved_model = resolve_got_ocr_model_id(model_id)
    sec_parser = load_sec_parser_module()
    model_obj, processor, runtime_device = _get_generic_ocr_backend(
        resolved_model,
        env_prefix="GOT_OCR",
        prefer_tokenizer=True,
    )
    model_device = sec_parser._model_input_device(model_obj)
    page_image = _prepare_backend_image(
        sec_parser._decode_data_uri_to_pil_image(image_data_uri),
        env_prefix="GOT_OCR",
        runtime_device=runtime_device,
    )
    raw_output = _run_got_ocr_backend(
        model_obj,
        processor,
        page_image,
        model_device=model_device,
    )
    return _require_nonempty_ocr_text_output(
        raw_output,
        backend_label="GOT-OCR local backend",
        details={"model_id": resolved_model, "device": runtime_device},
    )


def transcribe_table_image_with_monkeyocr(
    image_data_uri: str,
    *,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    resolved_model = resolve_monkeyocr_model_id(model_id)
    sec_parser = load_sec_parser_module()
    page_image = sec_parser._decode_data_uri_to_pil_image(image_data_uri)
    prompt_text = prompt or default_table_image_transcription_prompt()
    raw_output = _run_monkeyocr_command(
        page_image,
        prompt_text,
        model_id=resolved_model,
        progress_handler=progress_handler,
    )
    return _require_nonempty_ocr_text_output(
        raw_output,
        backend_label="MonkeyOCR local wrapper",
        details={"model_id": resolved_model},
    )


def _pdf_fastpath_raster_fallback_model_id(explicit_model_id: Optional[str] = None) -> str:
    candidates = [
        normalize_text(explicit_model_id or ""),
        normalize_text(os.getenv("PDF_FASTPATH_RASTER_OCR_MODEL_ID", "")),
        normalize_text(os.getenv("OPENROUTER_MODEL_ID", "")),
        normalize_text(os.getenv("DEEPSEEK_OCR_MODEL_ID", "")),
        normalize_text(os.getenv("FIRERED_MODEL_ID", "")),
        normalize_text(os.getenv("GEMMA4_LLAMA_CPP_MODEL_ID", "")),
    ]
    for candidate in candidates:
        if candidate and candidate.lower() != "pdf_native_fastpath":
            return candidate
    raise RuntimeError(
        "Raster PDF fast-path fallback needs an OCR model id. Pass ocr_model_id=... "
        "or set PDF_FASTPATH_RASTER_OCR_MODEL_ID / OPENROUTER_MODEL_ID."
    )


def _pdf_fastpath_raster_render_zoom() -> float:
    raw_value = normalize_text(os.getenv("PDF_FASTPATH_RASTER_RENDER_ZOOM", "2.0"))
    try:
        return max(1.0, float(raw_value))
    except ValueError:
        return 2.0


def _pdf_fastpath_raster_padding_pt() -> float:
    raw_value = normalize_text(os.getenv("PDF_FASTPATH_RASTER_PADDING_PT", "6.0"))
    try:
        return max(0.0, float(raw_value))
    except ValueError:
        return 6.0


def _pdf_fastpath_raster_max_tables() -> int:
    return _env_int("PDF_FASTPATH_RASTER_MAX_TABLES", 3)


def _pdf_fastpath_page_render_zoom() -> float:
    raw_value = normalize_text(os.getenv("PDF_FASTPATH_PAGE_RENDER_ZOOM", "2.0"))
    try:
        return max(1.0, float(raw_value))
    except ValueError:
        return 2.0


def _render_pdf_page_data_uri(
    page: Any,
    *,
    zoom: float,
) -> str:
    try:
        import fitz
    except ImportError as exc:
        raise RuntimeError("PyMuPDF is required for PDF page rendering.") from exc

    pix = page.get_pixmap(matrix=fitz.Matrix(float(zoom), float(zoom)), alpha=False)
    return f"data:image/png;base64,{base64.b64encode(pix.tobytes('png')).decode('utf-8')}"


def _render_pdf_table_region_data_uri(
    page: Any,
    *,
    bbox: List[float] | tuple[float, float, float, float],
    zoom: float,
    padding_pt: float,
) -> str:
    try:
        import fitz
    except ImportError as exc:
        raise RuntimeError("PyMuPDF is required for PDF fast-path raster fallback rendering.") from exc

    page_rect = page.rect
    left = max(float(page_rect.x0), float(bbox[0]) - padding_pt)
    top = max(float(page_rect.y0), float(bbox[1]) - padding_pt)
    right = min(float(page_rect.x1), float(bbox[2]) + padding_pt)
    bottom = min(float(page_rect.y1), float(bbox[3]) + padding_pt)
    clip_rect = fitz.Rect(left, top, right, bottom)
    pix = page.get_pixmap(matrix=fitz.Matrix(float(zoom), float(zoom)), clip=clip_rect, alpha=False)
    return f"data:image/png;base64,{base64.b64encode(pix.tobytes('png')).decode('utf-8')}"


def _normalize_table_match_text(text: str) -> str:
    normalized = html.unescape(normalize_text(text))
    normalized = re.sub(r"\s+", " ", normalized)
    return normalized.strip().lower()


def _bbox_to_attr_value(bbox: Any) -> str:
    if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
        return ""
    try:
        return ",".join(f"{float(value):.2f}" for value in bbox)
    except (TypeError, ValueError):
        return ""


def _sequence_similarity(left_text: str, right_text: str) -> float:
    left_normalized = _normalize_table_match_text(left_text)
    right_normalized = _normalize_table_match_text(right_text)
    if not left_normalized or not right_normalized:
        return 0.0
    return float(difflib.SequenceMatcher(None, left_normalized, right_normalized).ratio())


def _table_text_overlap_score(left_texts: List[str], right_texts: List[str]) -> float:
    left_set = {_normalize_table_match_text(text) for text in left_texts if _normalize_table_match_text(text)}
    right_set = {_normalize_table_match_text(text) for text in right_texts if _normalize_table_match_text(text)}
    if not left_set or not right_set:
        return 0.0
    intersection = len(left_set & right_set)
    union = max(1, len(left_set | right_set))
    return float(intersection) / float(union)


def _parse_html_table_cells(table_tag: Any, *, table_index: int) -> Dict[str, Any]:
    occupied: Dict[Tuple[int, int], bool] = {}
    cells: List[Dict[str, Any]] = []
    row_tags = list(table_tag.find_all("tr"))
    max_column = 0
    for row_index, row_tag in enumerate(row_tags):
        column_index = 0
        for cell_tag in row_tag.find_all(["th", "td"], recursive=False):
            while occupied.get((row_index, column_index)):
                column_index += 1
            try:
                rowspan = max(1, int(cell_tag.get("rowspan", 1)))
            except (TypeError, ValueError):
                rowspan = 1
            try:
                colspan = max(1, int(cell_tag.get("colspan", 1)))
            except (TypeError, ValueError):
                colspan = 1
            for row_offset in range(rowspan):
                for column_offset in range(colspan):
                    occupied[(row_index + row_offset, column_index + column_offset)] = True
            cell_text = normalize_text(cell_tag.get_text(" ", strip=True))
            cells.append(
                {
                    "row": row_index,
                    "col": column_index,
                    "rowspan": rowspan,
                    "colspan": colspan,
                    "text": cell_text,
                    "match_text": _normalize_table_match_text(cell_text),
                    "tag": cell_tag,
                }
            )
            max_column = max(max_column, column_index + colspan)
            column_index += colspan
    return {
        "index": table_index,
        "tag": table_tag,
        "cells": cells,
        "texts": [cell["text"] for cell in cells if normalize_text(cell["text"])],
        "row_count": len(row_tags),
        "column_count": max_column,
        "match_text": " | ".join(
            _normalize_table_match_text(cell["text"])
            for cell in cells
            if _normalize_table_match_text(cell["text"])
        ),
    }


def _build_native_table_descriptor(table_payload: Dict[str, Any], *, table_index: int) -> Dict[str, Any]:
    cells = [
        cell
        for cell in list(table_payload.get("cells") or [])
        if isinstance(cell, dict)
    ]
    row_count = max(
        (
            int(cell.get("row", 0)) + max(1, int(cell.get("rowspan", 1)))
            for cell in cells
        ),
        default=0,
    )
    column_count = max(
        (
            int(cell.get("col", 0)) + max(1, int(cell.get("colspan", 1)))
            for cell in cells
        ),
        default=0,
    )
    texts = [normalize_text(str(cell.get("text", ""))) for cell in cells if normalize_text(str(cell.get("text", "")))]
    for cell in cells:
        cell["match_text"] = _normalize_table_match_text(str(cell.get("text", "")))
    return {
        "index": table_index,
        "bbox": list(table_payload.get("bbox") or []),
        "source": normalize_text(str(table_payload.get("source", ""))),
        "cells": cells,
        "texts": texts,
        "row_count": row_count,
        "column_count": column_count,
        "match_text": " | ".join(cell["match_text"] for cell in cells if cell["match_text"]),
    }


def _score_html_table_match(html_table: Dict[str, Any], native_table: Dict[str, Any]) -> float:
    text_score = _sequence_similarity(str(html_table.get("match_text", "")), str(native_table.get("match_text", "")))
    overlap_score = _table_text_overlap_score(
        list(html_table.get("texts") or []),
        list(native_table.get("texts") or []),
    )
    row_score = 1.0 / (1.0 + abs(int(html_table.get("row_count", 0)) - int(native_table.get("row_count", 0))))
    column_score = 1.0 / (1.0 + abs(int(html_table.get("column_count", 0)) - int(native_table.get("column_count", 0))))
    return (0.55 * text_score) + (0.20 * overlap_score) + (0.15 * row_score) + (0.10 * column_score)


def _match_html_tables_to_native_tables(
    html_tables: List[Dict[str, Any]],
    native_tables: List[Dict[str, Any]],
) -> Dict[int, Dict[str, Any]]:
    scored_pairs: List[Tuple[float, int, int]] = []
    for html_table in html_tables:
        for native_table in native_tables:
            scored_pairs.append(
                (
                    _score_html_table_match(html_table, native_table),
                    int(html_table["index"]),
                    int(native_table["index"]),
                )
            )
    scored_pairs.sort(reverse=True)
    assignments: Dict[int, Dict[str, Any]] = {}
    used_html: set[int] = set()
    used_native: set[int] = set()
    for score, html_index, native_index in scored_pairs:
        if score <= 0.10 or html_index in used_html or native_index in used_native:
            continue
        assignments[html_index] = {
            "native_index": native_index,
            "score": float(score),
        }
        used_html.add(html_index)
        used_native.add(native_index)
    return assignments


def _grid_iou(left_cell: Dict[str, Any], right_cell: Dict[str, Any]) -> float:
    left_row_start = int(left_cell.get("row", 0))
    left_row_end = left_row_start + max(1, int(left_cell.get("rowspan", 1)))
    left_col_start = int(left_cell.get("col", 0))
    left_col_end = left_col_start + max(1, int(left_cell.get("colspan", 1)))
    right_row_start = int(right_cell.get("row", 0))
    right_row_end = right_row_start + max(1, int(right_cell.get("rowspan", 1)))
    right_col_start = int(right_cell.get("col", 0))
    right_col_end = right_col_start + max(1, int(right_cell.get("colspan", 1)))

    row_overlap = max(0, min(left_row_end, right_row_end) - max(left_row_start, right_row_start))
    col_overlap = max(0, min(left_col_end, right_col_end) - max(left_col_start, right_col_start))
    intersection = row_overlap * col_overlap
    left_area = max(1, left_row_end - left_row_start) * max(1, left_col_end - left_col_start)
    right_area = max(1, right_row_end - right_row_start) * max(1, right_col_end - right_col_start)
    union = max(1, left_area + right_area - intersection)
    return float(intersection) / float(union)


def _score_html_cell_match(html_cell: Dict[str, Any], native_cell: Dict[str, Any]) -> float:
    text_score = _sequence_similarity(str(html_cell.get("text", "")), str(native_cell.get("text", "")))
    grid_score = _grid_iou(html_cell, native_cell)
    same_anchor_score = (
        1.0
        if (
            int(html_cell.get("row", -1)) == int(native_cell.get("row", -2))
            and int(html_cell.get("col", -1)) == int(native_cell.get("col", -2))
        )
        else 0.0
    )
    span_score = 1.0 / (
        1.0
        + abs(int(html_cell.get("rowspan", 1)) - int(native_cell.get("rowspan", 1)))
        + abs(int(html_cell.get("colspan", 1)) - int(native_cell.get("colspan", 1)))
    )
    if not _normalize_table_match_text(str(html_cell.get("text", ""))) or not _normalize_table_match_text(str(native_cell.get("text", ""))):
        return (0.65 * grid_score) + (0.20 * same_anchor_score) + (0.15 * span_score)
    return (0.50 * text_score) + (0.25 * grid_score) + (0.15 * same_anchor_score) + (0.10 * span_score)


def _match_html_cells_to_native_cells(
    html_table: Dict[str, Any],
    native_table: Dict[str, Any],
) -> Dict[int, Dict[str, Any]]:
    matches: Dict[int, Dict[str, Any]] = {}
    native_cells = list(native_table.get("cells") or [])
    unused_native_indexes = set(range(len(native_cells)))
    exact_key_to_indexes: Dict[Tuple[int, int, int, int], List[int]] = {}
    for index, native_cell in enumerate(native_cells):
        key = (
            int(native_cell.get("row", 0)),
            int(native_cell.get("col", 0)),
            max(1, int(native_cell.get("rowspan", 1))),
            max(1, int(native_cell.get("colspan", 1))),
        )
        exact_key_to_indexes.setdefault(key, []).append(index)

    for html_cell_index, html_cell in enumerate(list(html_table.get("cells") or [])):
        key = (
            int(html_cell.get("row", 0)),
            int(html_cell.get("col", 0)),
            max(1, int(html_cell.get("rowspan", 1))),
            max(1, int(html_cell.get("colspan", 1))),
        )
        exact_indexes = [index for index in exact_key_to_indexes.get(key, []) if index in unused_native_indexes]
        if exact_indexes:
            native_index = exact_indexes[0]
            unused_native_indexes.remove(native_index)
            matches[html_cell_index] = {
                "native_cell": native_cells[native_index],
                "score": 1.0,
            }

    for html_cell_index, html_cell in enumerate(list(html_table.get("cells") or [])):
        if html_cell_index in matches:
            continue
        best_native_index: Optional[int] = None
        best_score = 0.0
        for native_index in unused_native_indexes:
            candidate_score = _score_html_cell_match(html_cell, native_cells[native_index])
            if candidate_score <= best_score:
                continue
            best_score = candidate_score
            best_native_index = native_index
        if best_native_index is None or best_score <= 0.15:
            continue
        unused_native_indexes.remove(best_native_index)
        matches[html_cell_index] = {
            "native_cell": native_cells[best_native_index],
            "score": float(best_score),
        }
    return matches


def _soup_fragment_contents(soup: Any) -> str:
    body = getattr(soup, "body", None)
    if body is not None:
        return body.decode_contents()
    return str(soup)


def _cell_markup_has_tag(markup: str, *tag_names: str) -> bool:
    if not markup:
        return False
    pattern = r"<(?:%s)\b" % "|".join(re.escape(tag_name) for tag_name in tag_names)
    return bool(re.search(pattern, markup, flags=re.IGNORECASE))


def _style_attr_text(value: Any) -> str:
    return re.sub(r"\s+", " ", str(value or "")).strip().lower()


def _tag_and_descendants(tag: Any) -> List[Any]:
    tags = [tag]
    if hasattr(tag, "find_all"):
        try:
            tags.extend(list(tag.find_all(True)))
        except Exception:
            pass
    return tags


def _tag_descendants_have_css_style(tag: Any, pattern: str) -> bool:
    compiled = re.compile(pattern, re.IGNORECASE)
    for candidate in _tag_and_descendants(tag):
        style_text = ""
        if hasattr(candidate, "get"):
            style_text = _style_attr_text(candidate.get("style", ""))
        if style_text and compiled.search(style_text):
            return True
    return False


def _tag_has_bold_style(tag: Any) -> bool:
    return _cell_markup_has_tag(str(tag), "strong", "b") or _tag_descendants_have_css_style(
        tag,
        r"font-weight\s*:\s*(?:bold|bolder|[6-9]00)\b",
    )


def _tag_has_italic_style(tag: Any) -> bool:
    return _cell_markup_has_tag(str(tag), "em", "i") or _tag_descendants_have_css_style(
        tag,
        r"font-style\s*:\s*(?:italic|oblique)\b",
    )


def _tag_has_underline_style(tag: Any) -> bool:
    return _cell_markup_has_tag(str(tag), "u") or _tag_descendants_have_css_style(
        tag,
        r"text-decoration(?:-line)?\s*:[^;]*underline\b",
    )


def _replace_tag_contents_with_html(tag: Any, html_fragment: str) -> None:
    try:
        from bs4 import BeautifulSoup
    except ImportError as exc:
        raise RuntimeError("beautifulsoup4 is required for HTML fragment replacement.") from exc

    fragment_soup = BeautifulSoup(f"<body>{html_fragment}</body>", "html.parser")
    body = getattr(fragment_soup, "body", None)
    replacement_nodes = list(body.contents if body is not None else fragment_soup.contents)
    tag.clear()
    for node in replacement_nodes:
        tag.append(node)


def _wrap_cell_markup_with_style_tags(markup: str, *, bold: bool, italic: bool, underline: bool) -> str:
    rendered = str(markup or "")
    if bold and not _cell_markup_has_tag(rendered, "strong", "b"):
        rendered = f"<strong>{rendered}</strong>"
    if italic and not _cell_markup_has_tag(rendered, "em", "i"):
        rendered = f"<em>{rendered}</em>"
    if underline and not _cell_markup_has_tag(rendered, "u"):
        rendered = f"<u>{rendered}</u>"
    return rendered


def _style_overlay_min_match_score() -> float:
    return _env_float("PDF_STYLE_OVERLAY_MIN_MATCH_SCORE", 0.75, min_value=0.0, max_value=1.0)


def _style_overlay_min_text_similarity() -> float:
    return _env_float("PDF_STYLE_OVERLAY_MIN_TEXT_SIMILARITY", 0.90, min_value=0.0, max_value=1.0)


def _style_overlay_bold_min_match_score() -> float:
    return _env_float("PDF_STYLE_OVERLAY_BOLD_MIN_MATCH_SCORE", 0.90, min_value=0.0, max_value=1.0)


def _style_overlay_bold_min_text_similarity() -> float:
    return _env_float("PDF_STYLE_OVERLAY_BOLD_MIN_TEXT_SIMILARITY", 0.97, min_value=0.0, max_value=1.0)


def _resolved_style_overlay_flags(
    *,
    current_text: str,
    native_text: str,
    match_score: Optional[float],
    bold: bool,
    italic: bool,
    underline: bool,
) -> Dict[str, bool]:
    normalized_current = _normalize_table_match_text(current_text)
    normalized_native = _normalize_table_match_text(native_text)
    if not normalized_current or not normalized_native:
        return {
            "bold": False,
            "italic": False,
            "underline": False,
        }

    score = max(0.0, min(1.0, float(match_score))) if isinstance(match_score, (int, float)) else 0.0
    text_similarity = _sequence_similarity(current_text, native_text)
    texts_match = normalized_current == normalized_native

    general_confident = score >= _style_overlay_min_match_score() and (
        texts_match or text_similarity >= _style_overlay_min_text_similarity()
    )
    bold_confident = score >= _style_overlay_bold_min_match_score() and (
        texts_match or text_similarity >= _style_overlay_bold_min_text_similarity()
    )

    return {
        "bold": bool(bold) and bold_confident,
        "italic": bool(italic) and general_confident,
        "underline": bool(underline) and general_confident,
    }


def _resolve_style_overlay_mode(style_overlay_mode: Optional[str]) -> str:
    normalized = normalize_text(style_overlay_mode or "auto").lower() or "auto"
    if normalized in {"none", "attrs_only", "formatting_only", "auto", "aggressive"}:
        return normalized
    return "auto"


def _apply_native_style_overlay_to_cell(
    cell_tag: Any,
    *,
    html_cell: Dict[str, Any],
    native_cell: Dict[str, Any],
    style_overlay_mode: str,
    match_score: Optional[float] = None,
) -> str:
    current_markup = str(cell_tag.decode_contents() or "")
    native_html = normalize_text(str(native_cell.get("html", "")))
    current_text = str(html_cell.get("text", ""))
    native_text = str(native_cell.get("text", ""))
    text_similarity = _sequence_similarity(current_text, native_text)
    texts_match = _normalize_table_match_text(current_text) == _normalize_table_match_text(native_text)
    style_flags = _resolved_style_overlay_flags(
        current_text=current_text,
        native_text=native_text,
        match_score=match_score,
        bold=bool(native_cell.get("bold")),
        italic=bool(native_cell.get("italic")),
        underline=bool(native_cell.get("underline")),
    )
    uniform_style_markup = _wrap_cell_markup_with_style_tags(
        current_markup,
        bold=style_flags["bold"],
        italic=style_flags["italic"],
        underline=style_flags["underline"],
    )

    if style_overlay_mode == "none":
        return current_markup
    if style_overlay_mode == "attrs_only":
        return current_markup
    if style_overlay_mode == "formatting_only":
        if uniform_style_markup != current_markup:
            _replace_tag_contents_with_html(cell_tag, uniform_style_markup)
        return str(cell_tag.decode_contents() or "")
    if style_overlay_mode == "aggressive" and native_html:
        _replace_tag_contents_with_html(cell_tag, native_html)
        return str(cell_tag.decode_contents() or "")
    if style_overlay_mode == "auto" and native_html and (texts_match or text_similarity >= 0.92):
        _replace_tag_contents_with_html(cell_tag, native_html)
        return str(cell_tag.decode_contents() or "")
    if uniform_style_markup != current_markup:
        _replace_tag_contents_with_html(cell_tag, uniform_style_markup)
    return str(cell_tag.decode_contents() or "")


def annotate_table_html_with_pdf_cells(
    table_html: str,
    *,
    pdf_path: str | Path,
    page_number: int,
    native_payload: Optional[Dict[str, Any]] = None,
    style_overlay_mode: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> Dict[str, Any]:
    try:
        import pdf_table_fastpath
    except ImportError as exc:
        raise RuntimeError(
            "The pdf_table_fastpath module is required for PDF cell/style annotation."
        ) from exc
    try:
        from bs4 import BeautifulSoup
    except ImportError as exc:
        raise RuntimeError(
            "beautifulsoup4 is required for annotating Mistral HTML with PDF cell metadata."
        ) from exc

    resolved_pdf_path = Path(pdf_path).resolve()
    resolved_page_number = max(1, int(page_number))
    resolved_style_overlay_mode = _resolve_style_overlay_mode(style_overlay_mode)
    started_at = time.perf_counter()
    if native_payload is None:
        emit_progress(
            f"[pdf-cell-overlay] {resolved_pdf_path.name} | page {resolved_page_number} | extract native cells",
            progress_handler=progress_handler,
        )
        native_payload = pdf_table_fastpath.extract_tables_from_pdf_page(
            resolved_pdf_path,
            page_number=resolved_page_number,
        )

    soup = BeautifulSoup(str(table_html or ""), "html.parser")
    html_tables = [
        _parse_html_table_cells(table_tag, table_index=index)
        for index, table_tag in enumerate(soup.find_all("table"))
    ]
    native_tables = [
        _build_native_table_descriptor(table_payload, table_index=index)
        for index, table_payload in enumerate(list((native_payload or {}).get("tables") or []))
        if isinstance(table_payload, dict)
    ]

    annotated_tables: List[Dict[str, Any]] = []
    if html_tables and native_tables and normalize_text(str((native_payload or {}).get("mode", ""))) == "pdf_native":
        table_matches = _match_html_tables_to_native_tables(html_tables, native_tables)
        for html_table in html_tables:
            match = table_matches.get(int(html_table["index"]))
            if match is None:
                annotated_tables.append(
                    {
                        "table_index": int(html_table["index"]),
                        "matched": False,
                        "cells": [],
                    }
                )
                continue

            native_table = native_tables[int(match["native_index"])]
            table_tag = html_table["tag"]
            table_bbox_attr = _bbox_to_attr_value(native_table.get("bbox"))
            table_tag["data-pdf-native-index"] = str(native_table["index"])
            table_tag["data-pdf-match-score"] = f"{float(match['score']):.3f}"
            if table_bbox_attr:
                table_tag["data-pdf-bbox"] = table_bbox_attr
            if normalize_text(str(native_table.get("source", ""))):
                table_tag["data-pdf-source"] = str(native_table["source"])

            cell_matches = _match_html_cells_to_native_cells(html_table, native_table)
            annotated_cells: List[Dict[str, Any]] = []
            for html_cell_index, html_cell in enumerate(list(html_table.get("cells") or [])):
                cell_tag = html_cell["tag"]
                matched_payload = cell_matches.get(html_cell_index)
                if matched_payload is None:
                    cell_tag["data-pdf-matched"] = "0"
                    annotated_cells.append(
                        {
                            "row": int(html_cell["row"]),
                            "col": int(html_cell["col"]),
                            "rowspan": int(html_cell["rowspan"]),
                            "colspan": int(html_cell["colspan"]),
                            "text": str(html_cell["text"]),
                            "matched": False,
                        }
                    )
                    continue

                native_cell = matched_payload["native_cell"]
                cell_tag["data-pdf-matched"] = "1"
                cell_tag["data-pdf-match-score"] = f"{float(matched_payload['score']):.3f}"
                bbox_attr = _bbox_to_attr_value(native_cell.get("bbox"))
                if bbox_attr:
                    cell_tag["data-pdf-bbox"] = bbox_attr
                cell_tag["data-pdf-native-row"] = str(int(native_cell.get("row", 0)))
                cell_tag["data-pdf-native-col"] = str(int(native_cell.get("col", 0)))
                cell_tag["data-pdf-bold"] = "1" if bool(native_cell.get("bold")) else "0"
                cell_tag["data-pdf-italic"] = "1" if bool(native_cell.get("italic")) else "0"
                cell_tag["data-pdf-underline"] = "1" if bool(native_cell.get("underline")) else "0"
                cell_tag["data-pdf-header"] = "1" if bool(native_cell.get("header")) else "0"
                styled_html = _apply_native_style_overlay_to_cell(
                    cell_tag,
                    html_cell=html_cell,
                    native_cell=native_cell,
                    style_overlay_mode=resolved_style_overlay_mode,
                    match_score=float(matched_payload["score"]),
                )
                annotated_cells.append(
                    {
                        "row": int(html_cell["row"]),
                        "col": int(html_cell["col"]),
                        "rowspan": int(html_cell["rowspan"]),
                        "colspan": int(html_cell["colspan"]),
                        "text": str(html_cell["text"]),
                        "matched": True,
                        "match_score": round(float(matched_payload["score"]), 4),
                        "bbox": list(native_cell.get("bbox") or []),
                        "native_row": int(native_cell.get("row", 0)),
                        "native_col": int(native_cell.get("col", 0)),
                        "bold": bool(native_cell.get("bold")),
                        "italic": bool(native_cell.get("italic")),
                        "underline": bool(native_cell.get("underline")),
                        "header": bool(native_cell.get("header")),
                        "styled_html": styled_html,
                    }
                )
            annotated_tables.append(
                {
                    "table_index": int(html_table["index"]),
                    "matched": True,
                    "match_score": round(float(match["score"]), 4),
                    "native_table_index": int(native_table["index"]),
                    "bbox": list(native_table.get("bbox") or []),
                    "source": str(native_table.get("source", "")),
                    "cells": annotated_cells,
                }
            )

    elapsed_ms = (time.perf_counter() - started_at) * 1000.0
    return {
        "html": _soup_fragment_contents(soup),
        "mode": normalize_text(str((native_payload or {}).get("mode", ""))) or None,
        "tables": annotated_tables,
        "native_tables": native_tables,
        "style_overlay_mode": resolved_style_overlay_mode,
        "timings_ms": {
            "annotation_ms": round(float(elapsed_ms), 2),
        },
    }


def _build_native_html_table_descriptor(table_tag: Any, *, table_index: int) -> Dict[str, Any]:
    parsed = _parse_html_table_cells(table_tag, table_index=table_index)
    native_cells: List[Dict[str, Any]] = []
    texts: List[str] = []
    for cell in list(parsed.get("cells") or []):
        source_tag = cell["tag"]
        bold = _tag_has_bold_style(source_tag)
        italic = _tag_has_italic_style(source_tag)
        underline = _tag_has_underline_style(source_tag)
        rendered_html = _wrap_cell_markup_with_style_tags(
            str(source_tag.decode_contents() or ""),
            bold=bold,
            italic=italic,
            underline=underline,
        )
        text = normalize_text(str(cell.get("text", "")))
        if text:
            texts.append(text)
        native_cells.append(
            {
                "row": int(cell["row"]),
                "col": int(cell["col"]),
                "rowspan": int(cell["rowspan"]),
                "colspan": int(cell["colspan"]),
                "text": text,
                "html": rendered_html,
                "bold": bold,
                "italic": italic,
                "underline": underline,
                "header": normalize_text(getattr(source_tag, "name", "")).lower() == "th",
                "match_text": _normalize_table_match_text(text),
            }
        )
    return {
        "index": table_index,
        "source": "html_native",
        "cells": native_cells,
        "texts": texts,
        "row_count": int(parsed.get("row_count", 0)),
        "column_count": int(parsed.get("column_count", 0)),
        "match_text": str(parsed.get("match_text", "")),
    }


def annotate_table_html_with_native_html(
    table_html: str,
    *,
    native_html: str,
    style_overlay_mode: Optional[str] = None,
) -> Dict[str, Any]:
    try:
        from bs4 import BeautifulSoup
    except ImportError as exc:
        raise RuntimeError(
            "beautifulsoup4 is required for annotating OCR HTML with native HTML style metadata."
        ) from exc

    resolved_style_overlay_mode = _resolve_style_overlay_mode(style_overlay_mode)
    started_at = time.perf_counter()

    soup = BeautifulSoup(str(table_html or ""), "html.parser")
    native_soup = BeautifulSoup(str(native_html or ""), "html.parser")
    html_tables = [
        _parse_html_table_cells(table_tag, table_index=index)
        for index, table_tag in enumerate(soup.find_all("table"))
    ]
    native_tables = [
        _build_native_html_table_descriptor(table_tag, table_index=index)
        for index, table_tag in enumerate(native_soup.find_all("table"))
    ]

    annotated_tables: List[Dict[str, Any]] = []
    if html_tables and native_tables:
        table_matches = _match_html_tables_to_native_tables(html_tables, native_tables)
        for html_table in html_tables:
            match = table_matches.get(int(html_table["index"]))
            if match is None:
                annotated_tables.append(
                    {
                        "table_index": int(html_table["index"]),
                        "matched": False,
                        "cells": [],
                    }
                )
                continue

            native_table = native_tables[int(match["native_index"])]
            table_tag = html_table["tag"]
            table_tag["data-native-index"] = str(native_table["index"])
            table_tag["data-native-match-score"] = f"{float(match['score']):.3f}"
            if normalize_text(str(native_table.get("source", ""))):
                table_tag["data-native-source"] = str(native_table["source"])

            cell_matches = _match_html_cells_to_native_cells(html_table, native_table)
            annotated_cells: List[Dict[str, Any]] = []
            for html_cell_index, html_cell in enumerate(list(html_table.get("cells") or [])):
                cell_tag = html_cell["tag"]
                matched_payload = cell_matches.get(html_cell_index)
                if matched_payload is None:
                    cell_tag["data-native-matched"] = "0"
                    annotated_cells.append(
                        {
                            "row": int(html_cell["row"]),
                            "col": int(html_cell["col"]),
                            "rowspan": int(html_cell["rowspan"]),
                            "colspan": int(html_cell["colspan"]),
                            "text": str(html_cell["text"]),
                            "matched": False,
                        }
                    )
                    continue

                native_cell = matched_payload["native_cell"]
                cell_tag["data-native-matched"] = "1"
                cell_tag["data-native-match-score"] = f"{float(matched_payload['score']):.3f}"
                cell_tag["data-native-row"] = str(int(native_cell.get("row", 0)))
                cell_tag["data-native-col"] = str(int(native_cell.get("col", 0)))
                cell_tag["data-native-bold"] = "1" if bool(native_cell.get("bold")) else "0"
                cell_tag["data-native-italic"] = "1" if bool(native_cell.get("italic")) else "0"
                cell_tag["data-native-underline"] = "1" if bool(native_cell.get("underline")) else "0"
                cell_tag["data-native-header"] = "1" if bool(native_cell.get("header")) else "0"
                styled_html = _apply_native_style_overlay_to_cell(
                    cell_tag,
                    html_cell=html_cell,
                    native_cell=native_cell,
                    style_overlay_mode=resolved_style_overlay_mode,
                    match_score=float(matched_payload["score"]),
                )
                annotated_cells.append(
                    {
                        "row": int(html_cell["row"]),
                        "col": int(html_cell["col"]),
                        "rowspan": int(html_cell["rowspan"]),
                        "colspan": int(html_cell["colspan"]),
                        "text": str(html_cell["text"]),
                        "matched": True,
                        "match_score": round(float(matched_payload["score"]), 4),
                        "native_row": int(native_cell.get("row", 0)),
                        "native_col": int(native_cell.get("col", 0)),
                        "bold": bool(native_cell.get("bold")),
                        "italic": bool(native_cell.get("italic")),
                        "underline": bool(native_cell.get("underline")),
                        "header": bool(native_cell.get("header")),
                        "styled_html": styled_html,
                    }
                )
            annotated_tables.append(
                {
                    "table_index": int(html_table["index"]),
                    "matched": True,
                    "match_score": round(float(match["score"]), 4),
                    "native_table_index": int(native_table["index"]),
                    "source": str(native_table.get("source", "")),
                    "cells": annotated_cells,
                }
            )

    elapsed_ms = (time.perf_counter() - started_at) * 1000.0
    return {
        "html": _soup_fragment_contents(soup),
        "mode": "html_native",
        "tables": annotated_tables,
        "native_tables": native_tables,
        "style_overlay_mode": resolved_style_overlay_mode,
        "timings_ms": {
            "annotation_ms": round(float(elapsed_ms), 2),
        },
    }


def overlay_table_html_with_native_html(
    table_html: str,
    *,
    native_html: str,
    effective_model_id: Optional[str] = None,
    style_overlay_mode: Optional[str] = None,
    timings_ms: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    annotation = annotate_table_html_with_native_html(
        table_html,
        native_html=native_html,
        style_overlay_mode=style_overlay_mode,
    )
    matched_table_count = sum(1 for table in annotation["tables"] if bool(table.get("matched")))
    resolved_timings_ms: Dict[str, Any] = {}
    for key, value in dict(timings_ms or {}).items():
        if isinstance(value, (int, float)):
            resolved_timings_ms[str(key)] = round(float(value), 2)
    annotation_ms = annotation.get("timings_ms", {}).get("annotation_ms")
    if isinstance(annotation_ms, (int, float)):
        resolved_timings_ms["annotation_ms"] = round(float(annotation_ms), 2)
    return {
        "html": str(annotation["html"]),
        "raw_html": strip_code_fences(str(table_html)),
        "tables": list(annotation["tables"]),
        "overlay_mode": annotation.get("mode"),
        "overlay_applied": bool(matched_table_count),
        "style_overlay_mode": annotation.get("style_overlay_mode"),
        "effective_model_id": normalize_text(effective_model_id or ""),
        "timings_ms": resolved_timings_ms,
        "native_payload": {
            "mode": annotation.get("mode"),
            "tables": annotation.get("native_tables"),
        },
    }


def overlay_pdf_page_html_with_native_cells(
    table_html: str,
    *,
    pdf_path: str | Path,
    page_number: int,
    effective_model_id: Optional[str] = None,
    native_payload: Optional[Dict[str, Any]] = None,
    style_overlay_mode: Optional[str] = None,
    timings_ms: Optional[Dict[str, Any]] = None,
    progress_handler: ProgressHandler = None,
) -> Dict[str, Any]:
    annotation = annotate_table_html_with_pdf_cells(
        table_html,
        pdf_path=pdf_path,
        page_number=page_number,
        native_payload=native_payload,
        style_overlay_mode=style_overlay_mode,
        progress_handler=progress_handler,
    )
    matched_table_count = sum(1 for table in annotation["tables"] if bool(table.get("matched")))
    resolved_timings_ms: Dict[str, Any] = {}
    for key, value in dict(timings_ms or {}).items():
        if isinstance(value, (int, float)):
            resolved_timings_ms[str(key)] = round(float(value), 2)
    annotation_ms = annotation.get("timings_ms", {}).get("annotation_ms")
    if isinstance(annotation_ms, (int, float)):
        resolved_timings_ms["annotation_ms"] = round(float(annotation_ms), 2)
    resolved_native_payload = native_payload
    if resolved_native_payload is None:
        resolved_native_payload = {
            "mode": annotation.get("mode"),
            "tables": annotation.get("native_tables"),
        }
    return {
        "html": str(annotation["html"]),
        "raw_html": strip_code_fences(str(table_html)),
        "tables": list(annotation["tables"]),
        "overlay_mode": annotation.get("mode"),
        "overlay_applied": bool(matched_table_count),
        "style_overlay_mode": annotation.get("style_overlay_mode"),
        "effective_model_id": normalize_text(effective_model_id or ""),
        "timings_ms": resolved_timings_ms,
        "native_payload": resolved_native_payload,
    }


def _table_ocr_transcription_text_from_pdf_payload(payload: Dict[str, Any]) -> TableOCRTranscriptionText:
    transcription = TableOCRTranscriptionText(
        str(payload.get("html") or ""),
        effective_model_id=normalize_text(str(payload.get("effective_model_id") or "")),
    )
    transcription.raw_html = str(payload.get("raw_html") or "")
    transcription.tables = list(payload.get("tables") or [])
    transcription.overlay_mode = normalize_text(str(payload.get("overlay_mode") or ""))
    transcription.overlay_applied = bool(payload.get("overlay_applied"))
    transcription.style_overlay_mode = normalize_text(str(payload.get("style_overlay_mode") or ""))
    transcription.native_payload = payload.get("native_payload")
    transcription.timings_ms = dict(payload.get("timings_ms") or {})
    transcription.payload = payload
    return transcription


def transcribe_pdf_page_with_mistral_and_pdf_cells(
    pdf_path: str | Path,
    *,
    page_number: int,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    page_render_zoom: Optional[float] = None,
    style_overlay_mode: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> Dict[str, Any]:
    try:
        import fitz
    except ImportError as exc:
        raise RuntimeError("PyMuPDF is required for PDF page rendering.") from exc
    try:
        import pdf_table_fastpath
    except ImportError as exc:
        raise RuntimeError(
            "The pdf_table_fastpath module is required for Mistral PDF cell/style overlay."
        ) from exc

    resolved_pdf_path = Path(pdf_path).resolve()
    resolved_page_number = max(1, int(page_number))
    resolved_zoom = max(1.0, float(page_render_zoom or _pdf_fastpath_page_render_zoom()))
    total_started_at = time.perf_counter()

    emit_progress(
        f"[mistral+pdf-cells] {resolved_pdf_path.name} | page {resolved_page_number} | render page",
        progress_handler=progress_handler,
    )
    render_started_at = time.perf_counter()
    with fitz.open(str(resolved_pdf_path)) as document:
        page = document.load_page(resolved_page_number - 1)
        image_data_uri = _render_pdf_page_data_uri(
            page,
            zoom=resolved_zoom,
        )
    page_render_ms = (time.perf_counter() - render_started_at) * 1000.0

    emit_progress(
        f"[mistral+pdf-cells] {resolved_pdf_path.name} | page {resolved_page_number} | extract native cells",
        progress_handler=progress_handler,
    )
    native_started_at = time.perf_counter()
    native_payload = pdf_table_fastpath.extract_tables_from_pdf_page(
        resolved_pdf_path,
        page_number=resolved_page_number,
    )
    native_overlay_ms = (time.perf_counter() - native_started_at) * 1000.0

    emit_progress(
        f"[mistral+pdf-cells] {resolved_pdf_path.name} | page {resolved_page_number} | mistral OCR",
        progress_handler=progress_handler,
    )
    mistral_started_at = time.perf_counter()
    mistral_html = transcribe_table_image_with_mistral(
        image_data_uri,
        model_id=model_id,
        prompt=prompt,
        progress_handler=progress_handler,
    )
    mistral_ocr_ms = (time.perf_counter() - mistral_started_at) * 1000.0

    payload = overlay_pdf_page_html_with_native_cells(
        str(mistral_html),
        pdf_path=resolved_pdf_path,
        page_number=resolved_page_number,
        effective_model_id=(
            normalize_text(getattr(mistral_html, "effective_model_id", "") or model_id or default_mistral_ocr_model_id())
        ),
        native_payload=native_payload,
        style_overlay_mode=style_overlay_mode,
        timings_ms={
            "page_render_ms": page_render_ms,
            "native_overlay_ms": native_overlay_ms,
            "mistral_ocr_ms": mistral_ocr_ms,
        },
        progress_handler=progress_handler,
    )
    total_ms = (time.perf_counter() - total_started_at) * 1000.0
    payload["timings_ms"]["total_ms"] = round(float(total_ms), 2)
    emit_progress(
        f"[mistral+pdf-cells] {resolved_pdf_path.name} | page {resolved_page_number} | "
        f"matched_tables={sum(1 for table in payload['tables'] if bool(table.get('matched')))}/{len(payload['tables'])} | "
        f"total_ms={total_ms:.2f}",
        progress_handler=progress_handler,
    )
    return payload


def transcribe_pdf_page_to_payload(
    pdf_path: str | Path,
    *,
    page_number: int,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    page_render_zoom: Optional[float] = None,
    overlay_pdf_cells: Optional[bool] = None,
    style_overlay_mode: Optional[str] = None,
    max_tables: Optional[int] = None,
    progress_handler: ProgressHandler = None,
) -> Dict[str, Any]:
    resolved_pdf_path = Path(pdf_path).resolve()
    resolved_page_number = max(1, int(page_number))
    resolved_model = normalize_text(model_id or default_pdf_page_ocr_model_id())
    if not resolved_model:
        raise RuntimeError(
            "Missing PDF page OCR model id. Pass model_id=... or set PDF_PAGE_OCR_MODEL_ID / MISTRAL_OCR_MODEL_ID."
        )

    if resolved_model.lower() in {"pdf_native_fastpath", "pdf_fastpath"}:
        started_at = time.perf_counter()
        rendered = transcribe_pdf_page_with_fastpath(
            resolved_pdf_path,
            page_number=resolved_page_number,
            ocr_model_id=None,
            prompt=prompt,
            max_tables=max_tables,
            progress_handler=progress_handler,
        )
        return {
            "html": str(rendered),
            "raw_html": str(rendered),
            "tables": [],
            "overlay_mode": None,
            "overlay_applied": False,
            "style_overlay_mode": _resolve_style_overlay_mode(style_overlay_mode),
            "effective_model_id": normalize_text(getattr(rendered, "effective_model_id", "") or resolved_model),
            "timings_ms": {
                "total_ms": round((time.perf_counter() - started_at) * 1000.0, 2),
            },
            "native_payload": None,
        }

    backend = resolve_table_ocr_backend(resolved_model)
    if overlay_pdf_cells is None:
        overlay_pdf_cells = backend == "mistral"
    if backend == "mistral" and overlay_pdf_cells:
        return transcribe_pdf_page_with_mistral_and_pdf_cells(
            resolved_pdf_path,
            page_number=resolved_page_number,
            model_id=resolved_model,
            prompt=prompt,
            page_render_zoom=page_render_zoom,
            style_overlay_mode=style_overlay_mode,
            progress_handler=progress_handler,
        )

    try:
        import fitz
    except ImportError as exc:
        raise RuntimeError("PyMuPDF is required for PDF page rendering.") from exc

    total_started_at = time.perf_counter()
    resolved_zoom = max(1.0, float(page_render_zoom or _pdf_fastpath_page_render_zoom()))
    emit_progress(
        f"[pdf-page-ocr] {resolved_pdf_path.name} | page {resolved_page_number} | render page",
        progress_handler=progress_handler,
    )
    render_started_at = time.perf_counter()
    with fitz.open(str(resolved_pdf_path)) as document:
        page = document.load_page(resolved_page_number - 1)
        image_data_uri = _render_pdf_page_data_uri(
            page,
            zoom=resolved_zoom,
        )
    page_render_ms = (time.perf_counter() - render_started_at) * 1000.0

    emit_progress(
        f"[pdf-page-ocr] {resolved_pdf_path.name} | page {resolved_page_number} | {resolved_model}",
        progress_handler=progress_handler,
    )
    ocr_started_at = time.perf_counter()
    rendered_html = transcribe_table_image(
        image_data_uri,
        model_id=resolved_model,
        prompt=prompt,
        progress_handler=progress_handler,
    )
    ocr_ms = (time.perf_counter() - ocr_started_at) * 1000.0
    effective_model_id = normalize_text(getattr(rendered_html, "effective_model_id", "") or resolved_model)

    if overlay_pdf_cells:
        try:
            import pdf_table_fastpath
        except ImportError as exc:
            raise RuntimeError(
                "The pdf_table_fastpath module is required for PDF cell/style overlay."
            ) from exc
        emit_progress(
            f"[pdf-page-ocr] {resolved_pdf_path.name} | page {resolved_page_number} | extract native cells",
            progress_handler=progress_handler,
        )
        native_started_at = time.perf_counter()
        native_payload = pdf_table_fastpath.extract_tables_from_pdf_page(
            resolved_pdf_path,
            page_number=resolved_page_number,
        )
        native_overlay_ms = (time.perf_counter() - native_started_at) * 1000.0
        payload = overlay_pdf_page_html_with_native_cells(
            str(rendered_html),
            pdf_path=resolved_pdf_path,
            page_number=resolved_page_number,
            effective_model_id=effective_model_id,
            native_payload=native_payload,
            style_overlay_mode=style_overlay_mode,
            timings_ms={
                "page_render_ms": page_render_ms,
                "ocr_ms": ocr_ms,
                "native_overlay_ms": native_overlay_ms,
            },
            progress_handler=progress_handler,
        )
    else:
        payload = {
            "html": strip_code_fences(str(rendered_html)),
            "raw_html": strip_code_fences(str(rendered_html)),
            "tables": [],
            "overlay_mode": None,
            "overlay_applied": False,
            "style_overlay_mode": _resolve_style_overlay_mode(style_overlay_mode),
            "effective_model_id": effective_model_id,
            "timings_ms": {
                "page_render_ms": round(float(page_render_ms), 2),
                "ocr_ms": round(float(ocr_ms), 2),
            },
            "native_payload": None,
        }

    total_ms = (time.perf_counter() - total_started_at) * 1000.0
    payload["timings_ms"]["total_ms"] = round(float(total_ms), 2)
    emit_progress(
        f"[pdf-page-ocr] {resolved_pdf_path.name} | page {resolved_page_number} | "
        f"overlay={'on' if payload.get('overlay_applied') else 'off'} | total_ms={total_ms:.2f}",
        progress_handler=progress_handler,
    )
    return payload


def transcribe_pdf_page(
    pdf_path: str | Path,
    *,
    page_number: int,
    model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    page_render_zoom: Optional[float] = None,
    overlay_pdf_cells: Optional[bool] = None,
    style_overlay_mode: Optional[str] = None,
    max_tables: Optional[int] = None,
    progress_handler: ProgressHandler = None,
) -> TableOCRTranscriptionText:
    payload = transcribe_pdf_page_to_payload(
        pdf_path,
        page_number=page_number,
        model_id=model_id,
        prompt=prompt,
        page_render_zoom=page_render_zoom,
        overlay_pdf_cells=overlay_pdf_cells,
        style_overlay_mode=style_overlay_mode,
        max_tables=max_tables,
        progress_handler=progress_handler,
    )
    return _table_ocr_transcription_text_from_pdf_payload(payload)


def transcribe_pdf_page_with_fastpath(
    pdf_path: str | Path,
    *,
    page_number: int,
    ocr_model_id: Optional[str] = None,
    prompt: Optional[str] = None,
    max_tables: Optional[int] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    try:
        import pdf_table_fastpath
    except ImportError as exc:
        raise RuntimeError(
            "The pdf_table_fastpath module is required for native PDF table extraction."
        ) from exc

    resolved_pdf_path = Path(pdf_path).resolve()
    resolved_page_number = max(1, int(page_number))
    emit_progress(
        f"[pdf-fastpath] {resolved_pdf_path.name} | page {resolved_page_number}",
        progress_handler=progress_handler,
    )
    payload = pdf_table_fastpath.extract_tables_from_pdf_page(
        resolved_pdf_path,
        page_number=resolved_page_number,
    )
    html_fragments = [
        str(fragment)
        for fragment in payload.get("html_fragments") or []
        if normalize_text(fragment)
    ]
    if payload.get("mode") == "image_morphology" and payload.get("tables"):
        try:
            import fitz
        except ImportError as exc:
            raise RuntimeError("PyMuPDF is required for PDF fast-path raster fallback OCR.") from exc

        resolved_fallback_model = _pdf_fastpath_raster_fallback_model_id(ocr_model_id)
        zoom = _pdf_fastpath_raster_render_zoom()
        padding_pt = _pdf_fastpath_raster_padding_pt()
        table_limit = max(1, int(max_tables or _pdf_fastpath_raster_max_tables()))
        raster_tables = list(payload.get("tables") or [])[:table_limit]
        emitted_fragments: List[str] = []
        with fitz.open(str(resolved_pdf_path)) as document:
            page = document.load_page(resolved_page_number - 1)
            for table_index, table_payload in enumerate(raster_tables, start=1):
                bbox = table_payload.get("bbox") if isinstance(table_payload, dict) else None
                if not isinstance(bbox, list) or len(bbox) != 4:
                    continue
                emit_progress(
                    f"[pdf-fastpath] {resolved_pdf_path.name} | page {resolved_page_number} | raster table {table_index}/{len(raster_tables)} -> {resolved_fallback_model}",
                    progress_handler=progress_handler,
                )
                image_data_uri = _render_pdf_table_region_data_uri(
                    page,
                    bbox=bbox,
                    zoom=zoom,
                    padding_pt=padding_pt,
                )
                rendered_fragment = transcribe_table_image(
                    image_data_uri,
                    model_id=resolved_fallback_model,
                    prompt=prompt,
                    progress_handler=progress_handler,
                )
                if normalize_text(rendered_fragment):
                    emitted_fragments.append(strip_code_fences(str(rendered_fragment)))
        if not emitted_fragments:
            raise TableOCRContentError(
                "PDF fast-path raster fallback found candidate regions but OCR did not return table HTML.",
                details={
                    "pdf_path": str(resolved_pdf_path),
                    "page_number": resolved_page_number,
                    "mode": payload.get("mode"),
                    "table_count": len(payload.get("tables") or []),
                    "ocr_model_id": resolved_fallback_model,
                },
            )
        emit_progress(
            f"[pdf-fastpath] {resolved_pdf_path.name} | page {resolved_page_number} | raster tables={len(emitted_fragments)}",
            progress_handler=progress_handler,
        )
        return TableOCRTranscriptionText(
            "\n".join(emitted_fragments),
            effective_model_id=f"pdf_fastpath_raster+{resolved_fallback_model}",
        )
    if not html_fragments:
        raise TableOCRContentError(
            "Native PDF fast path did not find any renderable table HTML fragments.",
            details={
                "pdf_path": str(resolved_pdf_path),
                "page_number": resolved_page_number,
                "mode": payload.get("mode"),
                "table_count": len(payload.get("tables") or []),
            },
        )
    emit_progress(
        f"[pdf-fastpath] {resolved_pdf_path.name} | page {resolved_page_number} | tables={len(html_fragments)}",
        progress_handler=progress_handler,
    )
    return TableOCRTranscriptionText(
        "\n".join(html_fragments),
        effective_model_id="pdf_native_fastpath",
    )


def transcribe_table_image(
    image_data_uri: str,
    *,
    model_id: str,
    prompt: Optional[str] = None,
    progress_handler: ProgressHandler = None,
) -> str:
    resolved_model = normalize_text(model_id)
    if not resolved_model:
        raise RuntimeError(
            "Missing OCR model id. Pass an explicit model id or set DEEPSEEK_OCR_MODEL_ID / OPENROUTER_MODEL_ID."
        )

    backend = resolve_table_ocr_backend(resolved_model)
    image_data_uri = _normalize_table_ocr_image_data_uri(
        image_data_uri,
        progress_handler=progress_handler,
    )
    if backend == "firered":
        return transcribe_table_image_with_firered(
            image_data_uri,
            model_id=resolved_model,
            prompt=prompt,
            progress_handler=progress_handler,
        )
    if backend == "deepseek":
        return transcribe_table_image_with_deepseek(
            image_data_uri,
            model_id=resolved_model,
            prompt=prompt,
            progress_handler=progress_handler,
        )
    if backend == "mistral":
        return transcribe_table_image_with_mistral(
            image_data_uri,
            model_id=resolved_model,
            prompt=prompt,
            progress_handler=progress_handler,
        )
    if backend == "qianfan":
        return transcribe_table_image_with_qianfan(
            image_data_uri,
            model_id=resolved_model,
            prompt=prompt,
            progress_handler=progress_handler,
        )
    if backend == "glm_ocr":
        return transcribe_table_image_with_glm_ocr(
            image_data_uri,
            model_id=resolved_model,
            prompt=prompt,
            progress_handler=progress_handler,
        )
    if backend == "paddleocr_vl":
        return transcribe_table_image_with_paddleocr_vl(
            image_data_uri,
            model_id=resolved_model,
            prompt=prompt,
            progress_handler=progress_handler,
        )
    if backend == "got_ocr":
        return transcribe_table_image_with_got_ocr(
            image_data_uri,
            model_id=resolved_model,
            prompt=prompt,
            progress_handler=progress_handler,
        )
    if backend == "monkeyocr":
        return transcribe_table_image_with_monkeyocr(
            image_data_uri,
            model_id=resolved_model,
            prompt=prompt,
            progress_handler=progress_handler,
        )
    if backend == "qwen_ocr":
        return transcribe_table_image_with_qwen_ocr(
            image_data_uri,
            model_id=resolved_model,
            prompt=prompt,
            progress_handler=progress_handler,
        )
    if backend == "gemma4_hf":
        return transcribe_table_image_with_gemma4_hf(
            image_data_uri,
            model_id=resolved_model,
            prompt=prompt,
            progress_handler=progress_handler,
        )
    if backend == "gemma4_llamacpp":
        return transcribe_table_image_with_gemma4_llamacpp(
            image_data_uri,
            model_id=resolved_model,
            prompt=prompt,
            progress_handler=progress_handler,
        )
    if backend == "gemma4_vllm":
        return transcribe_table_image_with_gemma4_vllm(
            image_data_uri,
            model_id=resolved_model,
            prompt=prompt,
            progress_handler=progress_handler,
        )
    return transcribe_table_image_with_openrouter(
        image_data_uri,
        model_id=resolved_model,
        prompt=prompt,
        progress_handler=progress_handler,
    )