File size: 175,932 Bytes
2e415b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Hugging Face Spaces deployment for SPaCial AI OCR Service
FastAPI HTTP Server for OCR Service using PaddleOCR
"""

from fastapi import FastAPI, File, UploadFile, HTTPException, Query, Body, Request
from fastapi.responses import JSONResponse, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
import uvicorn
from contextlib import asynccontextmanager
import cv2
import numpy as np
import os
import tempfile
import math
import re
from pathlib import Path
import logging
from collections import defaultdict
import time
import asyncio
import concurrent.futures
from functools import lru_cache
import atexit
import gc
import shutil
import json
try:
    import psutil
    PSUTIL_AVAILABLE = True
except ImportError:
    PSUTIL_AVAILABLE = False
    logger.warning("psutil not available - memory monitoring disabled")

# Excel imports
try:
    from openpyxl import Workbook
    from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
    OPENPYXL_AVAILABLE = True
except ImportError:
    OPENPYXL_AVAILABLE = False
    print("Warning: openpyxl not available - Excel export will not work")

# Set up logging first
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Set environment variables BEFORE importing PaddleOCR
os.environ['PADDLE_PDX_MODEL_SOURCE'] = 'BOS'

# Determine base directory (works for both local and HF Spaces)
base_dir = os.getcwd()  # Always use current directory for simplicity
home_dir = os.getenv('HOME')
if home_dir and os.path.exists(home_dir) and os.access(home_dir, os.W_OK):
    base_dir = home_dir

# Set paths relative to base directory
paddle_home = os.path.join(base_dir, '.paddlex')
paddleocr_home = os.path.join(base_dir, '.paddleocr')
temp_dir = os.path.join(base_dir, 'temp')

# Set environment variables
os.environ['PADDLE_HOME'] = paddle_home
os.environ['PADDLEX_HOME'] = paddle_home
os.environ['PADDLEOCR_HOME'] = paddleocr_home
os.environ['TEMP'] = temp_dir
os.environ['TMP'] = temp_dir
os.environ['TMPDIR'] = temp_dir

logger.info(f"Using base directory: {base_dir}")
logger.info(f"PaddleOCR home: {paddleocr_home}")
logger.info(f"Temp directory: {temp_dir}")

# Let PaddleOCR auto-detect GPU/CPU (newer versions handle this automatically)

# Create directories with proper permissions for all PaddleOCR models
def create_directories():
    """Create necessary directories for PaddleOCR"""
    directories_to_create = [
        paddle_home,
        paddleocr_home,
        os.path.join(paddleocr_home, 'whl'),
        os.path.join(paddleocr_home, 'whl', 'det', 'en', 'en_PP-OCRv3_det_infer'),
        os.path.join(paddleocr_home, 'whl', 'rec', 'en', 'en_PP-OCRv3_rec_infer'),
        os.path.join(paddleocr_home, 'whl', 'cls', 'en_ppocr_mobile_v2.0_cls_infer'),
        temp_dir
    ]
    
    created_count = 0
    for directory in directories_to_create:
        try:
            os.makedirs(directory, mode=0o755, exist_ok=True)
            created_count += 1
        except Exception as e:
            logger.warning(f"Failed to create directory {directory}: {e}")
    
    if created_count == len(directories_to_create):
        logger.info(f"Successfully created all {created_count} PaddleOCR directories")
    else:
        logger.warning(f"Created {created_count}/{len(directories_to_create)} directories, continuing with defaults...")

try:
    create_directories()
except Exception as e:
    logger.error(f"Failed to create directories: {e}")
    logger.warning("Continuing with default PaddleOCR paths...")

# Now import PaddleOCR
from paddleocr import PaddleOCR

# Import YOLOv11
try:
    from ultralytics import YOLO
    YOLO_AVAILABLE = True
    logger.info("✅ YOLOv11 (ultralytics) available")
except ImportError as e:
    YOLO_AVAILABLE = False
    logger.warning(f"⚠️ YOLOv11 not available: {e}")
    logger.info("Install with: pip install ultralytics")

# Import correction post-processor
try:
    from correction_post_processor import CorrectionPostProcessor
    correction_processor = CorrectionPostProcessor('correction_rules.json')
    logger.info("✅ Correction post-processor loaded")
except Exception as e:
    logger.warning(f"⚠️  Correction post-processor not available: {e}")
    correction_processor = None


# Global OCR instance (initialize once at startup)
ocr = None

# Global YOLO instance
yolo_model = None

# Thread pool for CPU-intensive tasks
executor = concurrent.futures.ThreadPoolExecutor(max_workers=4)

# Cleanup function for temporary files and resources
def cleanup_resources():
    """Clean up temporary files and resources"""
    try:
        # Force garbage collection
        gc.collect()
        
        # Log memory usage (if psutil is available)
        if PSUTIL_AVAILABLE:
            try:
                memory_info = psutil.virtual_memory()
                logger.info(f"Memory usage: {memory_info.percent}% ({memory_info.used / 1024 / 1024 / 1024:.2f}GB / {memory_info.total / 1024 / 1024 / 1024:.2f}GB)")
            except Exception as e:
                logger.warning(f"Failed to get memory info: {e}")
        else:
            logger.info("Memory monitoring not available (psutil not installed)")
        
        # Clean up temp directory
        temp_files = []
        for root, dirs, files in os.walk(temp_dir):
            for file in files:
                if file.startswith('temp_') or file.endswith('_temp.jpg') or file.endswith('_cropped.jpg'):
                    temp_files.append(os.path.join(root, file))
        
        for temp_file in temp_files:
            try:
                if os.path.exists(temp_file):
                    os.unlink(temp_file)
                    logger.info(f"Cleaned up temp file: {temp_file}")
            except Exception as e:
                logger.warning(f"Failed to clean up temp file {temp_file}: {e}")
                
    except Exception as e:
        logger.error(f"Error during cleanup: {e}")

# Register cleanup function
atexit.register(cleanup_resources)

# Periodic cleanup function (run every 30 minutes)
def periodic_cleanup():
    """Run periodic cleanup to manage resources"""
    while True:
        try:
            time.sleep(1800)  # 30 minutes
            cleanup_resources()
        except Exception as e:
            logger.error(f"Error in periodic cleanup: {e}")

# Start periodic cleanup in background thread
import threading
cleanup_thread = threading.Thread(target=periodic_cleanup, daemon=True)
cleanup_thread.start()

# Import PDF service (optional)
try:
    from pdf_service import pdf_service
    PDF_AVAILABLE = True
    logger.info("✅ PDF service loaded successfully")
except ImportError as e:
    PDF_AVAILABLE = False
    pdf_service = None
    logger.warning(f"⚠️ PDF service not available: {e}")
    logger.info("PDF export feature will be disabled")

# Advanced processing configuration
merge_overlapping_zones = False  # Disable merging to prevent over-merging dimensions
remove_duplicate_zones = True

@asynccontextmanager
async def lifespan(app: FastAPI):
    """Handle application lifespan events"""
    # Startup
    global ocr, executor, yolo_model
    logger.info("="*60)
    logger.info("🚀 STARTING APPLICATION INITIALIZATION")
    logger.info("="*60)
    logger.info("Initializing PaddleOCR model...")
    
    # Single OCR instance (auto GPU detection for newer PaddleOCR)
    try:
        logger.info("Initializing PaddleOCR with auto GPU detection...")
        logger.info("Creating PaddleOCR object...")
        ocr = PaddleOCR(
            use_doc_orientation_classify=False,  # Disable for better performance
            use_doc_unwarping=False,
            use_textline_orientation=True,  # Enable text line orientation
            lang='en'
        )
        print("="*60)
        print("✅ PaddleOCR object created!")
        print("="*60)
        logger.info("PaddleOCR object created!")
        logger.info("✅ PaddleOCR initialized successfully!")
        
    except ImportError as error:
        logger.error(f"PaddleOCR import failed: {error}")
        logger.error("Please install PaddleOCR: pip install paddleocr")
        raise HTTPException(status_code=500, detail="PaddleOCR not available")
    except Exception as error:
        logger.error(f"PaddleOCR initialization failed: {error}")
        logger.error("This might be due to missing models or insufficient memory")
        raise HTTPException(status_code=500, detail="OCR service initialization failed")
    
    print("="*60)
    print("✅ PaddleOCR COMPLETE - Moving to YOLO...")
    print("="*60)
    logger.info("="*60)
    logger.info("✅ PaddleOCR COMPLETE - Moving to YOLO...")
    logger.info("="*60)
    
    # Initialize YOLOv11 (pre-trained model for object detection)
    print(f"YOLO_AVAILABLE check: {YOLO_AVAILABLE}")
    logger.info(f"YOLO_AVAILABLE check: {YOLO_AVAILABLE}")
    if YOLO_AVAILABLE:
        try:
            print("🎯 Starting YOLO initialization...")
            logger.info("🎯 Initializing YOLOv11 pre-trained model...")
            
            # Check if custom trained model exists
            # Priority order: custom_ocr_model3 (latest) > custom_ocr_model2 > custom_ocr_model > models/yolo11_custom.pt
            custom_model_paths = [
                os.path.join(base_dir, 'yolo_training', 'custom_ocr_model3', 'weights', 'best.pt'),
                os.path.join(base_dir, 'yolo_training', 'custom_ocr_model2', 'weights', 'best.pt'),
                os.path.join(base_dir, 'yolo_training', 'custom_ocr_model', 'weights', 'best.pt'),
                os.path.join(base_dir, 'models', 'yolo11_custom.pt')
            ]
            
            custom_model_path = None
            for path in custom_model_paths:
                if os.path.exists(path):
                    custom_model_path = path
                    break
            
            if custom_model_path:
                print(f"📦 Found custom model: {custom_model_path}")
                yolo_model = YOLO(custom_model_path)
                model_name = f"{os.path.basename(custom_model_path)} (CUSTOM TRAINED MODEL)"
            else:
                # Use generic pre-trained model (won't detect text well!)
                print("⚠️  No custom model found, using generic yolo11n.pt")
                print("⚠️  Pre-trained YOLO doesn't know technical drawings!")
                print("💡 Collect training data and run train_yolo_custom.py")
                yolo_model = YOLO('yolo11n.pt')
                model_name = "yolo11n.pt (generic - not trained for technical drawings)"
            
            print(f"✅ YOLO model loaded: {model_name}")
            logger.info(f"✅ YOLOv11 initialized successfully!")
            logger.info(f"   Model: {model_name}")
            logger.info(f"   yolo_model type: {type(yolo_model)}")
        except Exception as e:
            print(f"❌ YOLO FAILED: {e}")
            logger.warning(f"⚠️ YOLOv11 initialization failed: {e}")
            logger.warning(f"   Exception type: {type(e)}")
            logger.warning(f"   Exception details: {str(e)}")
            logger.info("YOLOv11 detection will not be available")
            yolo_model = None
    else:
        print("❌ YOLO_AVAILABLE is False!")
        logger.warning("⚠️ YOLOv11 not available (ultralytics not installed)")
        yolo_model = None
    
    print("="*60)
    print(f"Final check: yolo_model = {yolo_model}")
    print("="*60)
    
    yield
    
    # Shutdown
    logger.info("Shutting down OCR service...")
    
    # Clean up global resources
    if ocr:
        del ocr
        ocr = None
    
    if yolo_model:
        del yolo_model
        yolo_model = None
    
    # Shutdown thread executor
    executor.shutdown(wait=True)
    
    # Stop background cleanup thread
    if 'cleanup_thread' in globals() and cleanup_thread.is_alive():
        logger.info("Stopping background cleanup thread...")
        cleanup_thread.join(timeout=5)
    
    # Force garbage collection
    gc.collect()
    
    logger.info("OCR service shutdown complete")

# Initialize FastAPI app with lifespan handler
app = FastAPI(
    title="SPaCial AI OCR Service",
    description="OCR service for dimension detection using PaddleOCR",
    version="1.0.0",
    lifespan=lifespan
)

# Add CORS middleware with proper security
ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://localhost:5173", 
    "http://127.0.0.1:3000",
    "http://127.0.0.1:5173",
    "https://cooldan-spacial-server-api.hf.space",
    "https://*.onrender.com",
]

# Allow all origins only in development
if os.getenv('ENVIRONMENT') == 'development':
    ALLOWED_ORIGINS = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["*"],

)

# Add trusted host middleware for security
app.add_middleware(
    TrustedHostMiddleware, 
    allowed_hosts=["localhost", "127.0.0.1", "*.hf.space", "*.onrender.com"]
)

# Rate limiting will be added after function definition


# File validation constants
MAX_FILE_SIZE = 50 * 1024 * 1024  # 50MB
MAX_IMAGE_DIMENSIONS = 4096  # Max width/height to prevent memory issues
ALLOWED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp', '.pdf'}
ALLOWED_MIME_TYPES = {
    'image/jpeg', 'image/jpg', 'image/png', 'image/bmp', 
    'image/tiff', 'image/webp', 'application/pdf'
}

# Security: Generate secure temp file names
def create_secure_temp_file(suffix='.jpg'):
    """Create a secure temporary file with random name"""
    import secrets
    import string
    
    # Generate random filename using secrets.choice (correct method)
    random_name = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(16))
    temp_path = os.path.join(temp_dir, f"secure_{random_name}_{int(time.time())}{suffix}")
    
    # Ensure directory exists
    os.makedirs(os.path.dirname(temp_path), exist_ok=True)
    
    return temp_path

def validate_uploaded_file(file: UploadFile) -> bool:
    """Validate uploaded file for security and size"""
    if not file:
        logger.warning("❌ File validation failed: No file provided")
        return False
    
    # Log file details for debugging
    logger.info(f"🔍 File validation: filename='{file.filename}', content_type='{file.content_type}'")
    
    # Check file size (only if size is available)
    if hasattr(file, 'size') and file.size:
        logger.info(f"📏 File size: {file.size} bytes")
        if file.size > MAX_FILE_SIZE:
            logger.warning(f"❌ File too large: {file.size} bytes > {MAX_FILE_SIZE} bytes")
            return False
    
    # Check file extension (more lenient)
    if file.filename:
        # Sanitize filename to prevent path traversal
        safe_filename = os.path.basename(file.filename)
        if safe_filename != file.filename:
            logger.warning(f"❌ Unsafe filename detected: '{file.filename}' -> '{safe_filename}'")
            return False
            
        file_ext = os.path.splitext(safe_filename.lower())[1]
        logger.info(f"📁 File extension: '{file_ext}'")
        if file_ext not in ALLOWED_EXTENSIONS:
            logger.warning(f"❌ Invalid file extension: '{file_ext}' not in {ALLOWED_EXTENSIONS}")
            return False
    else:
        logger.warning("❌ No filename provided")
        return False
    
    # Check MIME type (more lenient - allow if not specified)
    if file.content_type:
        logger.info(f"🎭 MIME type: '{file.content_type}'")
        if file.content_type not in ALLOWED_MIME_TYPES:
            logger.warning(f"❌ Invalid MIME type: '{file.content_type}' not in {ALLOWED_MIME_TYPES}")
            return False
    else:
        logger.info("ℹ️ No MIME type specified, allowing based on extension")
    
    logger.info("✅ File validation passed")
    return True

def convert_pdf_to_image(pdf_path: str, page_number: int = 0, dpi: int = 300) -> str:
    """Convert PDF page to image for OCR processing"""
    try:
        import fitz  # PyMuPDF
        
        # Open PDF
        pdf_document = fitz.open(pdf_path)
        
        # Check if page exists
        if page_number >= len(pdf_document):
            page_number = 0
        
        # Get page
        page = pdf_document[page_number]
        
        # Convert to image with high DPI for better OCR
        mat = fitz.Matrix(dpi / 72, dpi / 72)  # 72 is default DPI
        pix = page.get_pixmap(matrix=mat)
        
        # Save as temporary image
        temp_image_path = create_secure_temp_file('.png')
        pix.save(temp_image_path)
        
        pdf_document.close()
        
        logger.info(f"✅ Converted PDF page {page_number} to image: {temp_image_path}")
        return temp_image_path
        
    except ImportError:
        logger.error("❌ PyMuPDF (fitz) not installed. Install with: pip install PyMuPDF")
        raise HTTPException(status_code=503, detail="PDF processing not available. PyMuPDF not installed.")
    except Exception as e:
        logger.error(f"❌ Error converting PDF to image: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to convert PDF: {str(e)}")

def validate_image_dimensions(image_path: str) -> bool:
    """Validate image dimensions to prevent memory issues"""
    try:
        import cv2
        img = cv2.imread(image_path)
        if img is None:
            return False
            
        height, width = img.shape[:2]
        logger.info(f"📐 Image dimensions: {width}x{height}")
        
        if width > MAX_IMAGE_DIMENSIONS or height > MAX_IMAGE_DIMENSIONS:
            logger.warning(f"❌ Image too large: {width}x{height} > {MAX_IMAGE_DIMENSIONS}x{MAX_IMAGE_DIMENSIONS}")
            return False
            
        return True
    except Exception as e:
        logger.error(f"Error validating image dimensions: {e}")
        return False

# Rate limiting
RATE_LIMIT_REQUESTS = 1000  # requests per minute (increased for training data manager)
RATE_LIMIT_WINDOW = 60  # seconds

# Store request counts per IP
request_counts = defaultdict(list)

def rate_limit_middleware(request, call_next):
    """Simple rate limiting middleware"""
    client_ip = request.client.host
    current_time = time.time()
    
    # Clean old requests
    request_counts[client_ip] = [
        req_time for req_time in request_counts[client_ip] 
        if current_time - req_time < RATE_LIMIT_WINDOW
    ]
    
    # Check rate limit
    if len(request_counts[client_ip]) >= RATE_LIMIT_REQUESTS:
        raise HTTPException(status_code=429, detail="Rate limit exceeded")
    
    # Add current request
    request_counts[client_ip].append(current_time)
    
    return call_next(request)

# Add rate limiting middleware
app.middleware("http")(rate_limit_middleware)

def is_dimension_text(text):
    """Check if text looks like a dimension"""
    # Look for numbers, possibly with units or decimal points
    if re.search(r'\d+\.?\d*\s*(mm|cm|m|in|inch)?', text.strip(), re.IGNORECASE):
        return True
    # Look for pure numbers
    if re.match(r'^\d+\.?\d*$', text.strip()):
        return True
    return False

def parse_tolerance(text):
    """Parse tolerance information from text with improved patterns including thread tolerances"""
    
    if not text:
        return None
    
    # Keep original text - DON'T do aggressive replacements!
    clean_text = text.strip()
    
    # Pattern 0: ISO 2768 General Tolerances (check FIRST!)
    iso_2768_patterns = [
        r'General tolerance DIN 150 2768.*?medium',  # DIN 150 2768 medium
        r'General tolerance DIN 150 2768.*?fine',    # DIN 150 2768 fine  
        r'General tolerance DIN 150 2768.*?coarse',  # DIN 150 2768 coarse
        r'ISO 2768.*?medium',                        # ISO 2768 medium
        r'ISO 2768.*?fine',                          # ISO 2768 fine
        r'ISO 2768.*?coarse',                        # ISO 2768 coarse
    ]
    
    for pattern in iso_2768_patterns:
        iso_match = re.search(pattern, clean_text, re.IGNORECASE)
        if iso_match:
            # Extract tolerance class
            if 'medium' in clean_text.lower():
                tolerance_class = 'medium'
            elif 'fine' in clean_text.lower():
                tolerance_class = 'fine'
            elif 'coarse' in clean_text.lower():
                tolerance_class = 'coarse'
            else:
                tolerance_class = 'medium'  # Default
            
            print(f"✓ ISO 2768 General Tolerance: {text} -> {tolerance_class}")
            
            return {
                "value": None,  # General tolerance doesn't have a specific value
                "tolerance_class": tolerance_class,
                "tolerance_type": "iso_2768_general",
                "standard": "ISO 2768-1",
                "is_diameter": False,
                "original_text": text
            }
    
    # Normalize ± symbol for easier parsing and fix common OCR errors
    clean_text = clean_text.replace('±', '+-')
    # Fix common OCR errors: ± is sometimes read as = or :
    clean_text = re.sub(r'(\d+\.?\d*)=(\d+\.?\d*)$', r'\1+-\2', clean_text)
    clean_text = re.sub(r'(\d+\.?\d*):(\d+\.?\d*)$', r'\1+-\2', clean_text)
    
    # Only log meaningful tolerance parsing results
    
    # Pattern 0: Thread tolerances (M30X2-6G, 6G, 8H, etc.) - check FIRST!
    # Handle OCR errors: 'g' might be read as '9', 'G' as '6', etc.
    thread_patterns = [
        r'M(\d+\.?\d*)[Xx×]?(\d+\.?\d*)?[-]?([A-HG]+\d*)',  # Standard thread
        r'M(\d+\.?\d*)[Xx×]?(\d+\.?\d*)?[-]?(\d+[A-HG]*)',  # OCR error: G->6, g->9
        r'M(\d+\.?\d*)[Xx×]?(\d+\.?\d*)?[-]?([A-H]\d*)',    # Without G
    ]
    
    for i, pattern in enumerate(thread_patterns):
        thread_tolerance_match = re.search(pattern, clean_text, re.IGNORECASE)
        if thread_tolerance_match:
            size = float(thread_tolerance_match.group(1))
            pitch = thread_tolerance_match.group(2)
            tolerance_class_raw = thread_tolerance_match.group(3)
            
            # Fix common OCR errors
            tolerance_class = tolerance_class_raw.upper()
            if '69' in tolerance_class:
                tolerance_class = tolerance_class.replace('69', '6G')  # 69 -> 6G
            elif '6G' in tolerance_class:
                tolerance_class = tolerance_class.replace('6G', '6G')  # Already correct
            elif tolerance_class.isdigit() and len(tolerance_class) == 2:
                # Convert pure numbers like "69" to "6G"
                if tolerance_class.startswith('6'):
                    tolerance_class = '6G'
                elif tolerance_class.startswith('8'):
                    tolerance_class = '8H'
            
            print(f"✓ Thread tolerance: {text} -> M{size}X{pitch}-{tolerance_class}")
            
            return {
                "value": size,
                "thread_pitch": float(pitch) if pitch else None,
                "tolerance_class": tolerance_class,
                "tolerance_type": "thread",
                "is_diameter": False,
                "original_text": text
            }
    
    # Pattern 1: ± tolerance with various symbols (e.g., "28±0.03", "104±0.04", "Ø48±0.03", "2±0.05")
    # Handle both ± and +- variations
    plus_minus_patterns = [
        r'(\d+\.?\d*)\+\-(\d+\.?\d*)',          # Normalized ± symbol (no spaces)
        r'(\d+\.?\d*)\s*\+\-\s*(\d+\.?\d*)',    # +- variation with spaces
        r'(\d+\.?\d*)\s*\+\s*(\d+\.?\d*)\s*$',  # Single + at end
        r'(\d+\.?\d*)\s*\+\s*(\d+\.?\d*)',      # Any + followed by number
    ]
    
    for pattern in plus_minus_patterns:
        plus_minus_match = re.search(pattern, clean_text, re.IGNORECASE)
        if plus_minus_match:
            value = float(plus_minus_match.group(1))
            tolerance = float(plus_minus_match.group(2))
            is_diameter = bool(re.search(r'[ØDIA]', clean_text, re.IGNORECASE))
            print(f"✓ ± Tolerance: {text} -> {value}±{tolerance}")
            return {
                "value": value,
                "tolerance_plus": tolerance,
                "tolerance_minus": tolerance,
                "tolerance_type": "+/-",
                "is_diameter": is_diameter,
                "original_text": text
            }
    
    # Pattern 2: +tolerance/-tolerance (e.g., "25.5+0.1/-0.05", "Ø48+0.1/-0.05", "25.5 +0.1 / -0.05")
    asymmetric_patterns = [
        r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)\s*\+\s*(\d+\.?\d*)\s*/\s*-\s*(\d+\.?\d*)',  # Standard +/-
        r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)\s*\+\s*(\d+\.?\d*)\s*/\s*(\d+\.?\d*)',     # +/ (without -)
        r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)\s*\+\s*(\d+\.?\d*)\s*-\s*(\d+\.?\d*)',    # +- (no slash)
    ]
    
    for pattern in asymmetric_patterns:
        asymmetric_match = re.search(pattern, clean_text, re.IGNORECASE)
        if asymmetric_match:
            value = float(asymmetric_match.group(1))
            plus_tolerance = float(asymmetric_match.group(2))
            minus_tolerance = float(asymmetric_match.group(3))
            is_diameter = bool(re.search(r'[ØDIA]', clean_text, re.IGNORECASE))
            return {
                "value": value,
                "tolerance_plus": plus_tolerance,
                "tolerance_minus": minus_tolerance,
                "tolerance_type": "+/-",
                "is_diameter": is_diameter,
                "original_text": text
            }
    
    # Pattern 3: Value with dual negative tolerances (e.g., "Ø18⁻⁰·¹⁵₋₀·₂₂")
    dual_negative_patterns = [
        r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)\s*[⁻\-]\s*(\d+\.?\d*)\s*[₋\-]\s*(\d+\.?\d*)',  # Flexible format with any minus
        r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)\s*-\s*(\d+\.?\d*)\s*-\s*(\d+\.?\d*)',  # Standard format
    ]
    
    # Pattern 3.5: Special case for Ø48⁻⁰·⁰³ (zero upper tolerance, negative lower tolerance)
    zero_upper_patterns = [
        r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)\s*⁻⁰·(\d+\.?\d*)',  # Ø48⁻⁰·⁰³ format
        r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)\s*⁻0\.(\d+\.?\d*)',  # Ø48⁻0.03 format
    ]
    
    # Check zero upper tolerance patterns first
    for pattern in zero_upper_patterns:
        zero_upper_match = re.search(pattern, clean_text, re.IGNORECASE)
        if zero_upper_match:
            value = float(zero_upper_match.group(1))
            
            try:
                # Handle superscript format
                def parse_number(text):
                    superscript_map = {'⁰': '0', '¹': '1', '²': '2', '³': '3', '⁴': '4', 
                                     '⁵': '5', '⁶': '6', '⁷': '7', '⁸': '8', '⁹': '9', '·': '.'}
                    result = ''
                    for char in text:
                        result += superscript_map.get(char, char)
                    return float(result)
                
                lower_tol = parse_number(zero_upper_match.group(2))
                
                is_diameter = bool(re.search(r'[ØDIA]', clean_text, re.IGNORECASE))
                print(f"✓ Zero upper tolerance: {text} -> {value} (upper: 0, lower: -{lower_tol})")
                
                return {
                    "value": value,
                    "tolerance_plus": 0.0,      # Zero upper tolerance
                    "tolerance_minus": lower_tol, # Negative lower tolerance
                    "tolerance_type": "zero-upper",
                    "is_diameter": is_diameter,
                    "original_text": text
                }
            except ValueError:
                continue  # Try next pattern
    
    for pattern in dual_negative_patterns:
        dual_negative_match = re.search(pattern, clean_text, re.IGNORECASE)
        if dual_negative_match:
            value = float(dual_negative_match.group(1))
            
            try:
                # Handle both superscript and standard formats
                def parse_number(text):
                    # Convert superscript to normal numbers if needed
                    superscript_map = {'⁰': '0', '¹': '1', '²': '2', '³': '3', '⁴': '4', 
                                     '⁵': '5', '⁶': '6', '⁷': '7', '⁸': '8', '⁹': '9', '·': '.'}
                    result = ''
                    for char in text:
                        result += superscript_map.get(char, char)
                    return float(result)
                
                upper_tol = parse_number(dual_negative_match.group(2))
                lower_tol = parse_number(dual_negative_match.group(3))
                
                is_diameter = bool(re.search(r'[ØDIA]', clean_text, re.IGNORECASE))
                print(f"✓ Dual negative tolerance: {text} -> {value} (upper: {upper_tol}, lower: {lower_tol})")
                
                return {
                    "value": value,
                    "tolerance_plus": upper_tol,  # Upper tolerance (less negative)
                    "tolerance_minus": lower_tol, # Lower tolerance (more negative)
                    "tolerance_type": "dual-negative",
                    "is_diameter": is_diameter,
                    "original_text": text
                }
            except ValueError:
                continue  # Try next pattern
    
    # Pattern 4: Value with negative tolerance only (e.g., "Ø48-0.03", "48 -0.03")
    negative_patterns = [
        r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)\s*-\s*(\d+\.?\d*)',  # With space
        r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)\s*⁻\s*(\d+\.?\d*)',  # Superscript minus
        r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)\s*⁻⁰\s*(\d+\.?\d*)', # With superscript 0
    ]
    
    for pattern in negative_patterns:
        negative_only_match = re.search(pattern, clean_text, re.IGNORECASE)
        if negative_only_match:
            value = float(negative_only_match.group(1))
            minus_tolerance = float(negative_only_match.group(2))
            is_diameter = bool(re.search(r'[ØDIA]', clean_text, re.IGNORECASE))
            return {
                "value": value,
                "tolerance_plus": 0.0,
                "tolerance_minus": minus_tolerance,
                "tolerance_type": "-only",
                "is_diameter": is_diameter,
                "original_text": text
            }
    
    # Pattern 4: Value with positive tolerance only (e.g., "Ø48+0.03", "48 +0.03")
    positive_only_match = re.search(r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)\s*\+\s*(\d+\.?\d*)', clean_text, re.IGNORECASE)
    if positive_only_match:
        value = float(positive_only_match.group(1))
        plus_tolerance = float(positive_only_match.group(2))
        is_diameter = bool(re.search(r'[ØDIA]', clean_text, re.IGNORECASE))
        return {
            "value": value,
            "tolerance_plus": plus_tolerance,
            "tolerance_minus": 0.0,
            "tolerance_type": "+only",
            "is_diameter": is_diameter,
            "original_text": text
        }
    
    # Pattern 5: ISO tolerance classes (e.g., "48H7", "25.5f6", "Ø48H7")
    iso_tolerance_match = re.search(r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)\s*([A-Za-z]\d+)', clean_text, re.IGNORECASE)
    if iso_tolerance_match:
        value = float(iso_tolerance_match.group(1))
        tolerance_class = iso_tolerance_match.group(2).upper()
        is_diameter = bool(re.search(r'[ØDIA]', clean_text, re.IGNORECASE))
        
        # Comprehensive ISO tolerance lookup (simplified but more complete)
        iso_tolerances = {
            # Hole basis (H series)
            'H6': {'plus': 0.016, 'minus': 0.0},
            'H7': {'plus': 0.025, 'minus': 0.0},
            'H8': {'plus': 0.039, 'minus': 0.0},
            'H9': {'plus': 0.062, 'minus': 0.0},
            'H10': {'plus': 0.100, 'minus': 0.0},
            'H11': {'plus': 0.160, 'minus': 0.0},
            
            # Shaft basis (f, g series)
            'F6': {'plus': 0.0, 'minus': 0.013},
            'F7': {'plus': 0.0, 'minus': 0.025},
            'F8': {'plus': 0.0, 'minus': 0.039},
            'G6': {'plus': 0.0, 'minus': 0.009},
            'G7': {'plus': 0.0, 'minus': 0.020},
            'G8': {'plus': 0.0, 'minus': 0.032},
            
            # Common fits
            'E7': {'plus': 0.0, 'minus': 0.040},
            'E8': {'plus': 0.0, 'minus': 0.059},
            'E9': {'plus': 0.0, 'minus': 0.087},
            'D9': {'plus': 0.0, 'minus': 0.087},
            'C11': {'plus': 0.0, 'minus': 0.160}
        }
        
        tolerance_info = iso_tolerances.get(tolerance_class, {'plus': 0.0, 'minus': 0.0})
        
        if tolerance_info['plus'] > 0 or tolerance_info['minus'] > 0:
            print(f"✓ ISO tolerance: {text} -> {value}{tolerance_class}")
        
        return {
            "value": value,
            "tolerance_plus": tolerance_info['plus'],
            "tolerance_minus": tolerance_info['minus'],
            "tolerance_type": f"ISO {tolerance_class}",
            "is_diameter": is_diameter,
            "original_text": text
        }
    
    # Pattern 6: Special diameter symbols and edge cases
    # Handle cases like "Ø48⁰-0.03" (with superscript 0)
    diameter_superscript_match = re.search(r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)\s*⁰\s*[-]\s*(\d+\.?\d*)', clean_text, re.IGNORECASE)
    if diameter_superscript_match:
        value = float(diameter_superscript_match.group(1))
        minus_tolerance = float(diameter_superscript_match.group(2))
        is_diameter = True  # Always diameter when Ø is present
        return {
            "value": value,
            "tolerance_plus": 0.0,
            "tolerance_minus": minus_tolerance,
            "tolerance_type": "diameter-superscript",
            "is_diameter": is_diameter,
            "original_text": text
        }
    
    # Pattern 7: Single value with no tolerance (e.g., "48", "Ø48", "DIA 48")
    single_value_match = re.search(r'(?:Ø|DIA|DIAMETER)?\s*(\d+\.?\d*)', clean_text, re.IGNORECASE)
    if single_value_match:
        value = float(single_value_match.group(1))
        is_diameter = bool(re.search(r'[ØDIA]', clean_text, re.IGNORECASE))
        return {
            "value": value,
            "tolerance_plus": 0.0,
            "tolerance_minus": 0.0,
            "tolerance_type": "none",
            "is_diameter": is_diameter,
            "original_text": text
        }
    
    # No pattern matched - only log for complex text to avoid spam
    if len(clean_text) > 3 or re.search(r'[A-Za-z±\+\-]', clean_text):
        print(f"✗ No tolerance pattern: '{text}'")
    return None

def preprocess_image_for_ocr(image_path):
    """Preprocess image for better OCR results in hardcore mode"""
    try:
        img = cv2.imread(str(image_path))
        if img is None:
            return image_path
        
        # Convert to grayscale
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        
        # Apply denoising
        denoised = cv2.fastNlMeansDenoising(gray)
        
        # Apply adaptive thresholding for better text contrast
        adaptive_thresh = cv2.adaptiveThreshold(
            denoised, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2
        )
        
        # Apply morphological operations to clean up
        kernel = np.ones((2,2), np.uint8)
        cleaned = cv2.morphologyEx(adaptive_thresh, cv2.MORPH_CLOSE, kernel)
        
        # Save preprocessed image
        preprocessed_path = str(image_path).replace('.jpg', '_preprocessed.jpg')
        cv2.imwrite(preprocessed_path, cleaned)
        
        logger.info(f"Image preprocessed: {preprocessed_path}")
        return preprocessed_path
        
    except Exception as e:
        logger.warning(f"Preprocessing failed: {e}")
        return image_path

def detect_text_orientation_advanced(polygon, text):
    """Improved text orientation detection with better vertical text handling"""
    try:
        if not polygon or len(polygon) < 4:
            return 0
        
        # Calculate bounding box dimensions
        x_coords = [point[0] for point in polygon]
        y_coords = [point[1] for point in polygon]
        bbox_width = max(x_coords) - min(x_coords)
        bbox_height = max(y_coords) - min(y_coords)
        aspect_ratio = bbox_height / bbox_width if bbox_width > 0 else 1
        
        # Calculate the main orientation based on the longest edge
        edge1 = [polygon[1][0] - polygon[0][0], polygon[1][1] - polygon[0][1]]
        edge2 = [polygon[2][0] - polygon[1][0], polygon[2][1] - polygon[1][1]]
        
        edge1_length = math.sqrt(edge1[0]**2 + edge1[1]**2)
        edge2_length = math.sqrt(edge2[0]**2 + edge2[1]**2)
        
        # Use the longer edge for orientation calculation
        if edge1_length > edge2_length:
            main_edge = edge1
        else:
            main_edge = edge2
            
        # Calculate angle of the main edge
        angle = math.degrees(math.atan2(main_edge[1], main_edge[0]))
        angle = (angle + 360) % 360  # Normalize to 0-360
        
        logger.info(f"🔍 Orientation: bbox={bbox_width:.1f}x{bbox_height:.1f}, aspect={aspect_ratio:.2f}, angle={angle:.1f}°")
        
        # Simplified orientation detection
        if aspect_ratio > 1.3:  # Clearly vertical (height > width * 1.3)
            # For vertical text, determine if it's 90° or 270°
            if 45 <= angle <= 135:  # Text reads from bottom to top
                return 90
            elif 225 <= angle <= 315:  # Text reads from top to bottom
                return 270
            else:
                return 90  # Default for vertical
        elif aspect_ratio < 0.7:  # Clearly horizontal (width > height * 1.4)
            # For horizontal text, determine if it's 0° or 180°
            if 315 <= angle or angle <= 45:  # Text reads left to right
                return 0
            elif 135 <= angle <= 225:  # Text reads right to left
                return 180
            else:
                return 0  # Default for horizontal
        else:
            # Ambiguous case - use angle-based detection
            if 315 <= angle or angle <= 45:
                return 0
            elif 45 < angle <= 135:
                return 90
            elif 135 < angle <= 225:
                return 180
            else:  # 225 < angle < 315
                return 270
        
    except Exception as e:
        logger.warning(f"Orientation detection failed: {e}")
        return 0

def is_dimension_text_advanced(text):
    """Advanced dimension text detection"""
    if not text:
        return False
    
    # Enhanced patterns for dimension detection
    patterns = [
        r'\d+\.?\d*\s*±\s*\d+\.?\d*',  # ± tolerance
        r'\d+\.?\d*\s*\+\s*\d+\.?\d*\s*/\s*-\s*\d+\.?\d*',  # +/- tolerance
        r'\d+\.?\d*\s*-\s*\d+\.?\d*',  # negative tolerance
        r'\d+\.?\d*\s*\+\s*\d+\.?\d*',  # positive tolerance
        r'\d+\.?\d*\s*[A-Za-z]\d+',  # ISO tolerance
        r'M?\d+\.?\d*[Xx×]?\d+\.?\d*?[-]?[A-HG]+\d*',  # Thread tolerances
        r'\d+\.?\d*\s*(mm|cm|m|in|inch)',  # With units
        r'^\d+\.?\d*$'  # Pure numbers
    ]
    
    for pattern in patterns:
        if re.search(pattern, text.strip(), re.IGNORECASE):
            return True
    
    return False

def detect_zone_category(text):
    """Detect zone category based on text content"""
    if not text:
        return 'measure'
    
    text_lower = text.lower().strip()
    
    # General tolerance keywords (check FIRST!)
    general_tolerance_keywords = [
        'general tolerance', 'iso 2768', 'din 150 2768', 'general tol',
        'gen tolerance', 'gen tol', 'iso2768', 'din2768'
    ]
    
    # Material keywords
    material_keywords = [
        'matiere', 'material', 'acier', 'steel', 'aluminium', 'aluminum',
        'inox', 'stainless', 'bronze', 'laiton', 'brass', 'cuivre', 'copper',
        'plastique', 'plastic', 'caoutchouc', 'rubber'
    ]
    
    # Radius keywords
    radius_keywords = ['r', 'radius', 'rayon']
    
    # Diameter keywords
    diameter_keywords = ['ø', 'diameter', 'diametre', 'dia', 'd']
    
    # Thread keywords
    thread_keywords = ['m', 'thread', 'filetage', 'pas']
    
    # Check for general tolerance FIRST
    for keyword in general_tolerance_keywords:
        if keyword in text_lower:
            return 'gdt'  # Geometric Dimensioning & Tolerancing
    
    # Check for material
    for keyword in material_keywords:
        if keyword in text_lower:
            return 'material'
    
    # Check for radius (R followed by number, or √ symbol with number)
    if (re.search(r'^r\d+', text_lower) or 'radius' in text_lower or 'rayon' in text_lower or 
        re.search(r'√\d+', text) or re.search(r'\d+√', text)):
        return 'radius'
    
    # Check for diameter (Ø followed by number or diameter keywords, or numbers that should be diameter)
    if (re.search(r'[øØ]\d+', text) or any(keyword in text_lower for keyword in diameter_keywords) or
        re.search(r'^\d+\.\d{3}$', text) or re.search(r'^\d{2,3}$', text) or  # Common diameter patterns
        re.search(r'^\d+[,.]\d+$', text)):  # Decimal numbers like 0,8 or 0.8 (likely diameters)
        return 'diameter'
    
    # Check for thread (M followed by number)
    if re.search(r'^m\d+', text_lower) or 'thread' in text_lower or 'filetage' in text_lower:
        return 'thread'
    
    # Check for tolerance patterns
    if re.search(r'[±\+\-]\d+', text) or re.search(r'[A-Z]\d+', text):
        return 'tolerance'
    
    # Default to measure for dimensions
    return 'measure'

def clean_ocr_text_advanced(text):
    """Advanced OCR text cleaning with better dimension handling"""
    if not text:
        return ""
    
    # Remove common OCR artifacts
    cleaned = text.strip()
    
    # Remove trailing periods that aren't part of decimal numbers
    if cleaned.endswith('.') and not re.search(r'\d+\.\d*$', cleaned):
        cleaned = cleaned[:-1]
        logger.info(f"🧹 Removed trailing period: '{text}' -> '{cleaned}'")
    
    # Fix common OCR mistakes in dimension text
    replacements = {
        'O': '0',  # Letter O to number 0 in numeric contexts
        'o': '0',  # Lowercase o to number 0
        'l': '1',  # Lowercase l to 1 in numeric contexts
        'I': '1',  # Letter I to number 1
        'S': '5',  # S to 5 in numeric contexts
        'B': '8',  # B to 8 in numeric contexts
        'G': '6',  # G to 6 in numeric contexts
        'q': '9',  # Lowercase q to number 9
        'g': '9',  # Lowercase g to number 9
        'C': '6',  # Letter C to number 6
        'D': '0',  # Letter D to number 0
        'T': '7',  # Letter T to number 7
        'J': '1',  # Letter J to number 1
        'P': '9',  # Letter P to number 9
        'R': '6',  # Letter R to number 6
        'F': '7',  # Letter F to number 7
        'E': '8',  # Letter E to number 8
    }
    
    # Apply replacements only in numeric contexts
    for old, new in replacements.items():
        # Only replace if surrounded by digits or at start/end of number
        pattern = f'(?<=\\d){re.escape(old)}(?=\\d)|(?<=\\d){re.escape(old)}$|^{re.escape(old)}(?=\\d)'
        cleaned = re.sub(pattern, new, cleaned)
    
    # Special handling for tolerance values and common OCR errors
    tolerance_fixes = {
        r'±0\.0([2-9])': r'±0.0\1',  # Ensure proper decimal format
        r'±([0-9])\.([0-9][0-9])': r'±\1.\2',  # Fix decimal tolerance
        r'([0-9]+)±([0-9])\.([0-9][0-9])': r'\1±\2.\3',  # Fix tolerance after number
        r'^: 4$': r'11.5',  # Fix specific OCR error ": 4" -> "11.5"
        r'^6$': r'5',  # Fix specific OCR error "6" -> "5"
        r'^\.\,$': r'',  # Remove meaningless OCR artifacts
        r'^\.\,,\s*$': r'',  # Remove meaningless OCR artifacts
        r'^15$': r'9.5',  # Fix common OCR error "15" -> "9.5" for vertical text
    }
    
    for pattern, replacement in tolerance_fixes.items():
        if re.match(pattern, cleaned):
            cleaned = re.sub(pattern, replacement, cleaned)
            logger.info(f"🧹 Applied tolerance fix: '{text}' -> '{cleaned}'")
    
    # Remove extra spaces and normalize
    cleaned = re.sub(r'\s+', ' ', cleaned).strip()
    
    return cleaned

def smart_zone_merger(zones, horizontal_gap=80, vertical_gap=50):
    """Smart merging of overlapping or nearby zones"""
    if len(zones) < 2:
        return zones
    
    merged_zones = []
    used_indices = set()
    
    for i, zone1 in enumerate(zones):
        if i in used_indices:
            continue
            
        bbox1 = zone1.get('bbox', {})
        if not bbox1:
            merged_zones.append(zone1)
            continue
            
        x1_1, y1_1, x2_1, y2_1 = bbox1.get('x1', 0), bbox1.get('y1', 0), bbox1.get('x2', 0), bbox1.get('y2', 0)
        text1 = zone1.get('text', '')
        
        # Look for nearby zones to merge
        merged_text = text1
        merged_bbox = {'x1': x1_1, 'y1': y1_1, 'x2': x2_1, 'y2': y2_1}
        
        for j, zone2 in enumerate(zones[i+1:], i+1):
            if j in used_indices:
                continue
                
            bbox2 = zone2.get('bbox', {})
            if not bbox2:
                continue
                
            x1_2, y1_2, x2_2, y2_2 = bbox2.get('x1', 0), bbox2.get('y1', 0), bbox2.get('x2', 0), bbox2.get('y2', 0)
            text2 = zone2.get('text', '')
            
            # Check if zones are close enough to merge
            horizontal_distance = min(abs(x1_1 - x2_2), abs(x1_2 - x2_1))
            vertical_distance = min(abs(y1_1 - y2_2), abs(y1_2 - y2_1))
            
            # Don't merge if both zones contain dimension-like text (likely separate dimensions)
            text1_has_dim = bool(re.search(r'\d+\.?\d*\s*[±\+\-]?\s*\d*\.?\d*', text1))
            text2_has_dim = bool(re.search(r'\d+\.?\d*\s*[±\+\-]?\s*\d*\.?\d*', text2))
            
            # Don't merge if both are dimensions and they're not very close
            if text1_has_dim and text2_has_dim and (horizontal_distance > 15 or vertical_distance > 15):
                continue
                
            if horizontal_distance < horizontal_gap and vertical_distance < vertical_gap:
                # Merge zones
                merged_text = text1 + " " + text2
                merged_bbox = {
                    'x1': min(x1_1, x1_2),
                    'y1': min(y1_1, y1_2),
                    'x2': max(x2_1, x2_2),
                    'y2': max(y2_1, y2_2)
                }
                
                used_indices.add(j)
                logger.info(f"Merged zones: '{text1}' + '{text2}' = '{merged_text}'")
        
        # Create merged zone
        merged_zone = {
            **zone1,
            "text": merged_text,
            "bbox": {
                **merged_bbox,
                "width": merged_bbox['x2'] - merged_bbox['x1'],
                "height": merged_bbox['y2'] - merged_bbox['y1']
            }
        }
        
        merged_zones.append(merged_zone)
        used_indices.add(i)
    
    # Add any remaining zones that weren't merged
    for i, zone in enumerate(zones):
        if i not in used_indices:
            merged_zones.append(zone)
    
    logger.info(f"Smart merge: {len(zones)} -> {len(merged_zones)} zones")
    return merged_zones

def remove_duplicate_zones(zones, overlap_threshold=0.8):
    """Remove duplicate zones based on overlap"""
    if len(zones) < 2:
        return zones
    
    filtered_zones = []
    
    for i, zone1 in enumerate(zones):
        is_duplicate = False
        bbox1 = zone1.get('bbox', {})
        
        if not bbox1:
            filtered_zones.append(zone1)
            continue
        
        x1_1, y1_1, x2_1, y2_1 = bbox1.get('x1', 0), bbox1.get('y1', 0), bbox1.get('x2', 0), bbox1.get('y2', 0)
        area1 = (x2_1 - x1_1) * (y2_1 - y1_1)
        
        for j, zone2 in enumerate(filtered_zones):
            bbox2 = zone2.get('bbox', {})
            if not bbox2:
                continue
                
            x1_2, y1_2, x2_2, y2_2 = bbox2.get('x1', 0), bbox2.get('y1', 0), bbox2.get('x2', 0), bbox2.get('y2', 0)
            
            # Calculate overlap
            overlap_x1 = max(x1_1, x1_2)
            overlap_y1 = max(y1_1, y1_2)
            overlap_x2 = min(x2_1, x2_2)
            overlap_y2 = min(y2_1, y2_2)
            
            if overlap_x1 < overlap_x2 and overlap_y1 < overlap_y2:
                overlap_area = (overlap_x2 - overlap_x1) * (overlap_y2 - overlap_y1)
                overlap_ratio = overlap_area / area1
                
                if overlap_ratio > overlap_threshold:
                    # Keep the zone with higher confidence
                    if zone1.get('confidence', 0) > zone2.get('confidence', 0):
                        filtered_zones[j] = zone1
                    is_duplicate = True
                    break
        
        if not is_duplicate:
            filtered_zones.append(zone1)
    
    removed_count = len(zones) - len(filtered_zones)
    if removed_count > 0:
        logger.info(f"Removed {removed_count} duplicate zones")
    
    return filtered_zones

def detect_dimension_lines_enhanced(image_path):
    """Enhanced dimension line detection"""
    try:
        img = cv2.imread(image_path)
        if img is None:
            return []
        
        # Convert to grayscale
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        
        # Apply edge detection with multiple thresholds
        edges1 = cv2.Canny(gray, 50, 150, apertureSize=3)
        edges2 = cv2.Canny(gray, 30, 100, apertureSize=3)
        edges = cv2.bitwise_or(edges1, edges2)
        
        # Detect lines using HoughLinesP with enhanced parameters
        lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=30, 
                               minLineLength=20, maxLineGap=8)
        
        detected_lines = []
        if lines is not None:
            for line in lines:
                x1, y1, x2, y2 = line[0]
                length = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
                
                # Filter out very short lines
                if length > 15:
                    # Calculate angle
                    angle = math.atan2(y2 - y1, x2 - x1) * 180 / math.pi
                    if angle < 0:
                        angle += 180
                    
                    detected_lines.append({
                        'x1': float(x1), 'y1': float(y1),
                        'x2': float(x2), 'y2': float(y2),
                        'length': float(length),
                        'angle': float(angle)
                    })
        
        return detected_lines
        
    except Exception as e:
        logger.error(f"Enhanced line detection failed: {e}")
        return []

def merge_vertical_text(zones):
    """Merge nearby vertical text that might have been split by OCR"""
    if len(zones) < 2:
        return zones
    
    merged_zones = []
    used_indices = set()
    
    for i, zone1 in enumerate(zones):
        if i in used_indices:
            continue
            
        bbox1 = zone1.get('bbox', [])
        if len(bbox1) < 4:
            merged_zones.append(zone1)
            continue
            
        x1_1, y1_1, x2_1, y2_1 = bbox1[0], bbox1[1], bbox1[2], bbox1[3]
        text1 = zone1.get('text', '')
        
        # Look for nearby zones to merge
        merged_text = text1
        merged_bbox = [x1_1, y1_1, x2_1, y2_1]
        
        for j, zone2 in enumerate(zones[i+1:], i+1):
            if j in used_indices:
                continue
                
            bbox2 = zone2.get('bbox', [])
            if len(bbox2) < 4:
                continue
                
            x1_2, y1_2, x2_2, y2_2 = bbox2[0], bbox2[1], bbox2[2], bbox2[3]
            text2 = zone2.get('text', '')
            
            # Check if zones are vertically close and horizontally aligned
            vertical_distance = abs((y1_1 + y2_1) / 2 - (y1_2 + y2_2) / 2)
            horizontal_overlap = not (x2_1 < x1_2 or x2_2 < x1_1)
            
            # If zones are close vertically and overlap horizontally, merge them
            if vertical_distance < 30 and horizontal_overlap:
                # Merge text
                if y1_2 < y1_1:  # zone2 is above zone1
                    merged_text = text2 + text1
                    merged_bbox = [min(x1_1, x1_2), min(y1_1, y1_2), 
                                 max(x2_1, x2_2), max(y2_1, y2_2)]
                else:  # zone1 is above zone2
                    merged_text = text1 + text2
                    merged_bbox = [min(x1_1, x1_2), min(y1_1, y1_2), 
                                 max(x2_1, x2_2), max(y2_1, y2_2)]
                
                used_indices.add(j)
                logger.info(f"Merged vertical text: '{text1}' + '{text2}' = '{merged_text}'")
        
        # Create merged zone
        merged_zone = {
            "id": f"ocr_zone_{len(merged_zones)}",
            "text": merged_text,
            "confidence": zone1.get('confidence', 0.9),
            "bbox": merged_bbox,
            "x": float(merged_bbox[0]),
            "y": float(merged_bbox[1]),
            "width": float(merged_bbox[2] - merged_bbox[0]),
            "height": float(merged_bbox[3] - merged_bbox[1]),
            "orientation": zone1.get('orientation', 0),
            "rotation": 0
        }
        
        merged_zones.append(merged_zone)
        used_indices.add(i)
    
    # Add any remaining zones that weren't merged
    for i, zone in enumerate(zones):
        if i not in used_indices:
            merged_zones.append(zone)
    
    logger.info(f"Merged {len(zones)} zones into {len(merged_zones)} zones")
    return merged_zones

def crop_image_to_rectangle(image_path, rectangle_bounds):
    """Crop image to the specified rectangle bounds and rotate if needed"""
    try:
        import cv2
        
        # Load image
        img = cv2.imread(image_path)
        if img is None:
            logger.error(f"Failed to load image: {image_path}")
            return None
        
        # Get rectangle coordinates
        x1 = int(rectangle_bounds.get('x1', 0))
        y1 = int(rectangle_bounds.get('y1', 0))
        x2 = int(rectangle_bounds.get('x2', 0))
        y2 = int(rectangle_bounds.get('y2', 0))
        
        # Validate coordinates
        if x1 >= x2 or y1 >= y2:
            logger.error(f"Invalid rectangle coordinates: ({x1}, {y1}, {x2}, {y2})")
            return None
        
        # Ensure coordinates are within image bounds
        height, width = img.shape[:2]
        x1 = max(0, min(x1, width))
        y1 = max(0, min(y1, height))
        x2 = max(0, min(x2, width))
        y2 = max(0, min(y2, height))
        
        if x1 >= x2 or y1 >= y2:
            logger.error(f"Rectangle coordinates out of bounds: ({x1}, {y1}, {x2}, {y2})")
            return None
        
        # Crop image
        cropped_img = img[y1:y2, x1:x2]
        
        # Check if rectangle is taller than wide (likely vertical text)
        crop_height, crop_width = cropped_img.shape[:2]
        aspect_ratio = crop_height / crop_width if crop_width > 0 else 1
        
        was_rotated = False
        # If aspect ratio > 1.2, rotate to horizontal for better OCR
        if aspect_ratio > 1.2:
            logger.info(f"Rotating cropped image (aspect_ratio={aspect_ratio:.2f}) for better OCR")
            # Rotate 90 degrees counter-clockwise to make vertical text horizontal
            rotated_img = cv2.rotate(cropped_img, cv2.ROTATE_90_COUNTERCLOCKWISE)
            cropped_img = rotated_img
            was_rotated = True
        
        # Save cropped (and possibly rotated) image
        cropped_path = image_path.replace('.jpg', '_cropped.jpg')
        cv2.imwrite(cropped_path, cropped_img)
        
        logger.info(f"Cropped image from ({x1}, {y1}, {x2}, {y2}) to {cropped_path}")
        return cropped_path, was_rotated
        
    except Exception as e:
        logger.error(f"Failed to crop image: {e}")
        return None, False

def detect_and_process_vertical_text(img):
    """Detect vertical text regions and process them with rotation for better OCR"""
    try:
        logger.info("🔍 Detecting vertical text regions...")
        
        # Convert to grayscale
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        
        # Use edge detection to find text-like regions
        edges = cv2.Canny(gray, 50, 150)
        
        # Find contours
        contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        vertical_zones = []
        logger.info(f"🔍 Found {len(contours)} contours from edge detection")
        
        for i, contour in enumerate(contours):
            # Get bounding rectangle
            x, y, w, h = cv2.boundingRect(contour)
            
            # Filter by size (text-like dimensions)
            if w < 10 or h < 10 or w > 200 or h > 200:
                continue
            
            # Check if region looks like vertical text (height > width)
            aspect_ratio = h / w if w > 0 else 0
            logger.info(f"🔍 Contour {i}: w={w}, h={h}, aspect_ratio={aspect_ratio:.2f}")
            
            if aspect_ratio < 1.2:  # More lenient threshold
                continue
            
            # Extract region
            region = img[y:y+h, x:x+w]
            
            # Rotate region 90 degrees counter-clockwise for better OCR
            rotated_region = cv2.rotate(region, cv2.ROTATE_90_COUNTERCLOCKWISE)
            
            # Save rotated region temporarily
            temp_path = f"temp_vertical_{x}_{y}.jpg"
            cv2.imwrite(temp_path, rotated_region)
            
            try:
                # Run OCR on rotated region
                result = ocr.predict(temp_path)
                
                if result and result[0]:
                    for detection in result[0]:
                        if detection and len(detection) >= 2:
                            text = detection[1][0] if detection[1] else ""
                            confidence = detection[1][1] if detection[1] and len(detection[1]) > 1 else 0
                            
                            if confidence > 0.3 and text.strip():  # Only keep confident detections
                                # Convert coordinates back to original image
                                # The rotated region coordinates need to be mapped back
                                rotated_bbox = detection[0]
                                
                                # Map rotated coordinates back to original image
                                # Since we rotated 90° counter-clockwise, we need to rotate back
                                orig_x1 = x + (h - rotated_bbox[2][1])  # y becomes x
                                orig_y1 = y + rotated_bbox[0][0]       # x becomes y
                                orig_x2 = x + (h - rotated_bbox[0][1])
                                orig_y2 = y + rotated_bbox[2][0]
                                
                                zone = {
                                    "text": text,
                                    "confidence": confidence,
                                    "bbox": {
                                        "x1": int(orig_x1),
                                        "y1": int(orig_y1),
                                        "x2": int(orig_x2),
                                        "y2": int(orig_y2),
                                        "width": int(orig_x2 - orig_x1),
                                        "height": int(orig_y2 - orig_y1)
                                    },
                                    "text_orientation": 90,  # Mark as vertical
                                    "rotation": 90,
                                    "is_dimension": is_dimension_text_advanced(text),
                                    "tolerance_info": parse_tolerance(text)
                                }
                                
                                vertical_zones.append(zone)
                                logger.info(f"🔍 Found vertical text: '{text}' at ({orig_x1},{orig_y1},{orig_x2},{orig_y2})")
                
                # Clean up temp file
                os.unlink(temp_path)
                
            except Exception as e:
                logger.error(f"Error processing vertical region: {e}")
                if os.path.exists(temp_path):
                    os.unlink(temp_path)
        
        logger.info(f"🔍 Found {len(vertical_zones)} vertical text zones")
        return vertical_zones
        
    except Exception as e:
        logger.error(f"Error in vertical text detection: {e}")
        return []

def smart_text_completion(zones):
    """Smart text completion for common patterns like .5 -> 11.5"""
    logger.info("🧠 Running smart text completion...")
    
    # Common patterns to look for
    patterns = {
        '.5': ['11.5', '9.5', '7.5', '5.5', '3.5', '1.5'],
        '.0': ['10.0', '20.0', '30.0', '40.0', '50.0'],
        '.25': ['11.25', '9.25', '7.25'],
        '.75': ['11.75', '9.75', '7.75'],
        '5': ['15', '25', '35', '45', '55'],
        '0': ['10', '20', '30', '40', '50']
    }
    
    completed_zones = []
    
    for zone in zones:
        text = zone.get('text', '').strip()
        completed_zone = zone.copy()
        
        # Check if text matches a pattern
        for pattern, completions in patterns.items():
            if text == pattern:
                logger.info(f"🧠 Found pattern '{pattern}', trying completions: {completions}")
                
                # Try to find nearby zones that could complete this pattern
                bbox = zone.get('bbox', {})
                if bbox:
                    zone_center_x = (bbox.get('x1', 0) + bbox.get('x2', 0)) / 2
                    zone_center_y = (bbox.get('y1', 0) + bbox.get('y2', 0)) / 2
                    
                    # Look for nearby zones that could be the missing part
                    for other_zone in zones:
                        if other_zone == zone:
                            continue
                            
                        other_bbox = other_zone.get('bbox', {})
                        if not other_bbox:
                            continue
                            
                        other_center_x = (other_bbox.get('x1', 0) + other_bbox.get('x2', 0)) / 2
                        other_center_y = (other_bbox.get('y1', 0) + other_bbox.get('y2', 0)) / 2
                        
                        distance = ((other_center_x - zone_center_x) ** 2 + (other_center_y - zone_center_y) ** 2) ** 0.5
                        
                        # If zones are close (within 100px), try to combine them
                        if distance < 100:
                            other_text = other_zone.get('text', '').strip()
                            
                            # Try different combinations
                            for completion in completions:
                                if completion.startswith(other_text) and completion.endswith(text):
                                    logger.info(f"🧠 Smart completion: '{other_text}' + '{text}' = '{completion}'")
                                    
                                    # Update the zone with completed text
                                    completed_zone['text'] = completion
                                    completed_zone['confidence'] = min(zone.get('confidence', 0), other_zone.get('confidence', 0))
                                    
                                    # Merge bounding boxes
                                    merged_bbox = {
                                        'x1': min(bbox.get('x1', 0), other_bbox.get('x1', 0)),
                                        'y1': min(bbox.get('y1', 0), other_bbox.get('y1', 0)),
                                        'x2': max(bbox.get('x2', 0), other_bbox.get('x2', 0)),
                                        'y2': max(bbox.get('y2', 0), other_bbox.get('y2', 0))
                                    }
                                    merged_bbox['width'] = merged_bbox['x2'] - merged_bbox['x1']
                                    merged_bbox['height'] = merged_bbox['y2'] - merged_bbox['y1']
                                    completed_zone['bbox'] = merged_bbox
                                    
                                    break
                            break
        
        completed_zones.append(completed_zone)
    
    logger.info(f"🧠 Smart completion processed {len(zones)} zones")
    return completed_zones

def merge_nearby_text_zones(zones):
    """Merge nearby text zones that might be parts of the same number"""
    if len(zones) <= 1:
        return zones
    
    merged_zones = []
    used_indices = set()
    
    for i, zone1 in enumerate(zones):
        if i in used_indices:
            continue
            
        text1 = zone1.get('text', '')
        bbox1 = zone1.get('bbox', {})
        orientation1 = zone1.get('text_orientation', 0)
        
        if not bbox1:
            merged_zones.append(zone1)
            continue
            
        # Find nearby zones to merge (within 50 pixels)
        merge_candidates = []
        for j, zone2 in enumerate(zones[i+1:], i+1):
            if j in used_indices:
                continue
                
            text2 = zone2.get('text', '')
            bbox2 = zone2.get('bbox', {})
            orientation2 = zone2.get('text_orientation', 0)
            
            if not bbox2:
                continue
                
            # Check if orientations are similar (within 45 degrees)
            orientation_diff = abs(orientation1 - orientation2)
            if orientation_diff > 45 and orientation_diff < 315:  # Account for 0/360 wrap
                continue
                
            # Calculate distance between zone centers
            center1_x = (bbox1.get('x1', 0) + bbox1.get('x2', 0)) / 2
            center1_y = (bbox1.get('y1', 0) + bbox1.get('y2', 0)) / 2
            center2_x = (bbox2.get('x1', 0) + bbox2.get('x2', 0)) / 2
            center2_y = (bbox2.get('y1', 0) + bbox2.get('y2', 0)) / 2
            
            distance = ((center1_x - center2_x) ** 2 + (center1_y - center2_y) ** 2) ** 0.5
            
            # If zones are close and text looks like it could be merged
            if distance < 50 and (text1.isdigit() or text1 in '.-') and (text2.isdigit() or text2 in '.-'):
                merge_candidates.append((j, zone2, distance))
        
        if merge_candidates:
            # Sort by distance and merge with the closest candidate
            merge_candidates.sort(key=lambda x: x[2])
            closest_j, closest_zone, _ = merge_candidates[0]
            
            # Determine merge order based on position
            if orientation1 == 90:  # Vertical text
                # For vertical text, merge top to bottom
                if bbox1.get('y1', 0) < closest_zone.get('bbox', {}).get('y1', 0):
                    merged_text = text1 + text2
                else:
                    merged_text = text2 + text1
            else:  # Horizontal text
                # For horizontal text, merge left to right
                if bbox1.get('x1', 0) < closest_zone.get('bbox', {}).get('x1', 0):
                    merged_text = text1 + text2
                else:
                    merged_text = text2 + text1
            
            # Create merged zone
            merged_bbox = {
                'x1': min(bbox1.get('x1', 0), closest_zone.get('bbox', {}).get('x1', 0)),
                'y1': min(bbox1.get('y1', 0), closest_zone.get('bbox', {}).get('y1', 0)),
                'x2': max(bbox1.get('x2', 0), closest_zone.get('bbox', {}).get('x2', 0)),
                'y2': max(bbox1.get('y2', 0), closest_zone.get('bbox', {}).get('y2', 0))
            }
            
            merged_zone = {
                'id': f"merged_zone_{i}_{closest_j}",
                'text': merged_text,
                'confidence': min(zone1.get('confidence', 0), closest_zone.get('confidence', 0)),
                'bbox': merged_bbox,
                'text_orientation': orientation1,
                'is_dimension': is_dimension_text_advanced(merged_text),
                'tolerance_info': parse_tolerance(merged_text)
            }
            
            merged_zones.append(merged_zone)
            used_indices.add(i)
            used_indices.add(closest_j)
            
            logger.info(f"Merged nearby zones: '{text1}' + '{text2}' = '{merged_text}'")
        else:
            merged_zones.append(zone1)
            used_indices.add(i)
    
    return merged_zones

def create_overlay_image(image_path, zones, lines=None, dimension_lines=None):
    """Create overlay image with bounding boxes and lines (using direct coordinates, no rotation)"""
    try:
        # Load original image
        img = cv2.imread(str(image_path))
        if img is None:
            return None
        
        # Create overlay with better visualization
        overlay = img.copy()
        
        # Create a separate overlay for semi-transparent rectangles
        overlay_color = np.zeros_like(img)
        
        # Draw lines first (so they appear behind text boxes)
        if lines:
            for line in lines:
                x1, y1, x2, y2 = int(line['x1']), int(line['y1']), int(line['x2']), int(line['y2'])
                cv2.line(overlay, (x1, y1), (x2, y2), (128, 128, 128), 1)  # Gray lines
        
        # Draw dimension lines in different color
        if dimension_lines:
            for dim_line in dimension_lines:
                line = dim_line['closest_line']
                x1, y1, x2, y2 = int(line['x1']), int(line['y1']), int(line['x2']), int(line['y2'])
                cv2.line(overlay, (x1, y1), (x2, y2), (0, 255, 255), 2)  # Yellow for dimension lines
        
        # Draw clean bounding boxes for each zone
        for i, zone in enumerate(zones):
            bbox = zone.get("bbox", {})
            if not bbox:
                continue
            
            # Extract coordinates with NaN and type safety
            x1 = bbox.get("x1", 0)
            y1 = bbox.get("y1", 0)
            x2 = bbox.get("x2", 0)
            y2 = bbox.get("y2", 0)
            
            # Validate coordinates
            if not all(isinstance(coord, (int, float)) and not math.isnan(coord) for coord in [x1, y1, x2, y2]):
                logger.warning(f"Invalid coordinates in zone {i}: x1={x1}, y1={y1}, x2={x2}, y2={y2}")
                continue
            
            # Ensure coordinates are within image bounds
            x1 = max(0, min(int(x1), img.shape[1] - 1))
            y1 = max(0, min(int(y1), img.shape[0] - 1))
            x2 = max(0, min(int(x2), img.shape[1]))
            y2 = max(0, min(int(y2), img.shape[0]))
            
            # Skip if box is too small
            if x2 - x1 < 1 or y2 - y1 < 1:
                continue
            
            # Color for this zone (cycling through colors)
            colors = [(0, 255, 0), (255, 0, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
            color = colors[i % len(colors)]
            
            # Draw semi-transparent rectangle
            cv2.rectangle(overlay_color, 
                         (x1, y1), 
                         (x2, y2), 
                         color, -1)  # Filled rectangle
            
            # Draw clean border
            cv2.rectangle(overlay, 
                         (x1, y1), 
                         (x2, y2), 
                         color, 2)  # Border only
            
            # Draw clean text label with background
            label_text = f"{i+1}. {zone.get('text', '')} ({int(zone.get('confidence', 0)*100)}%)"
            font_scale = 0.5
            thickness = 1
            (text_width, text_height), _ = cv2.getTextSize(label_text, cv2.FONT_HERSHEY_SIMPLEX, font_scale, thickness)
            
            # Position label above the box
            label_x = x1
            label_y = max(y1 - 10, text_height + 5)
            
            # Ensure label is within image bounds
            if label_y > 0 and label_x >= 0:
                # Draw text background
                cv2.rectangle(overlay, 
                             (label_x - 2, label_y - text_height - 2), 
                             (label_x + text_width + 2, label_y + 2), 
                             (255, 255, 255), -1)  # White background
                
                # Draw text border for better readability
                cv2.putText(overlay, label_text, 
                           (label_x, label_y), 
                           cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), thickness + 1)  # White border
                cv2.putText(overlay, label_text, 
                           (label_x, label_y), 
                           cv2.FONT_HERSHEY_SIMPLEX, font_scale, (0, 0, 0), thickness)  # Black text
        
        # Blend the colored overlay with the original image
        alpha = 0.3
        overlay = cv2.addWeighted(overlay, 1, overlay_color, alpha, 0)
                    
        # Save overlay image
        overlay_path = str(image_path).replace('.', '_overlay.')
        cv2.imwrite(overlay_path, overlay)
        
        return overlay_path
        
    except Exception as e:
        logger.error(f"Error creating overlay: {e}")
        import traceback
        logger.error(f"Traceback: {traceback.format_exc()}")
        return None

def process_ocr_result(result, mode="fast"):
    """Process OCR result and extract zones"""
    zones = []
    
    if not result or len(result) == 0:
        return zones
    
    logger.info(f"🔍 OCR result type: {type(result)}, length: {len(result)}")
    
    # Check if it's predict format (with .json attribute)
    if hasattr(result[0], 'json'):
        zones = process_predict_format(result)
    else:
        zones = process_ocr_format(result)
    
    return zones

def process_predict_format(result):
    """Process predict() format OCR results"""
    zones = []
    
    for res in result:
        if hasattr(res, 'json') and 'res' in res.json:
            res_data = res.json['res']
            if 'rec_texts' in res_data and 'rec_scores' in res_data:
                texts = res_data['rec_texts']
                scores = res_data['rec_scores']
                dt_polys = res_data.get('dt_polys', [])
                
                logger.info(f"📝 Found {len(texts)} texts: {texts}")
                logger.info(f"📊 Found {len(scores)} scores: {[f'{s:.3f}' for s in scores]}")
                logger.info(f"📐 Found {len(dt_polys)} polygons")
                
                # Debug: Log each text with its polygon coordinates
                for i, (text, score, poly) in enumerate(zip(texts, scores, dt_polys)):
                    logger.info(f"DEBUG Text {i}: '{text}' (score: {score:.3f}) at polygon: {poly}")
                
                for i, (text, score) in enumerate(zip(texts, scores)):
                    zone = create_zone_from_predict(text, score, dt_polys, i)
                    if zone:
                        zones.append(zone)
    
    return zones

def process_ocr_format(result):
    """Process ocr() format OCR results"""
    zones = []
    
    for line in result:
        if line:
            for item in line:
                if len(item) >= 2:
                    bbox = item[0]
                    text_info = item[1]
                    
                    # Handle text that might be tuple or string
                    if isinstance(text_info, (tuple, list)) and len(text_info) >= 2:
                        text = text_info[0]
                        confidence = text_info[1]
                    elif isinstance(text_info, str):
                        text = text_info
                        confidence = 0.9
                    else:
                        continue
                    
                    if isinstance(text, str) and text.strip():
                        zone = create_zone_from_ocr(text, confidence, bbox, len(zones))
                        if zone:
                            zones.append(zone)
    
    return zones

def create_zone_from_predict(text, score, dt_polys, index):
    """Create zone from predict format data with improved confidence handling"""
    if not text.strip() or index >= len(dt_polys):
        return None
    
    # Filter out meaningless text
    if (len(text.strip()) < 1 or 
        text.strip() in ['.', '-', ',', ':', ';'] or 
        score <= 0.3):
        return None
    
    poly = dt_polys[index]
    
    # Convert polygon to bounding box
    x_coords = [p[0] for p in poly]
    y_coords = [p[1] for p in poly]
    x1, x2 = min(x_coords), max(x_coords)
    y1, y2 = min(y_coords), max(y_coords)
    
    # Validate coordinates
    if (math.isnan(x1) or math.isnan(x2) or math.isnan(y1) or math.isnan(y2) or
        x1 >= x2 or y1 >= y2 or x2 - x1 < 1 or y2 - y1 < 1):
        logger.warning(f"❌ Invalid coordinates for text '{text}'")
        return None
    
    # Detect orientation
    text_orientation = detect_text_orientation_advanced(poly, text)
    
    # Calculate bounding box dimensions for confidence adjustment
    bbox_width = x2 - x1
    bbox_height = y2 - y1
    aspect_ratio = bbox_height / bbox_width if bbox_width > 0 else 1
    
    # Adjust confidence for vertical text (they often have lower raw scores)
    adjusted_score = float(score)
    if text_orientation in [90, 270] and aspect_ratio > 1.2:
        # Boost confidence for vertical text that looks like dimensions
        if is_dimension_text_advanced(text):
            adjusted_score = min(0.95, adjusted_score + 0.2)
            logger.info(f"🔍 Boosted confidence for vertical dimension '{text}': {score:.3f} -> {adjusted_score:.3f}")
    
    # Clean text - remove trailing periods that aren't part of decimal numbers
    clean_text = text.strip()
    if clean_text.endswith('.') and not re.search(r'\d+\.\d*$', clean_text):
        clean_text = clean_text[:-1]
        logger.info(f"🧹 Cleaned trailing period: '{text}' -> '{clean_text}'")
    
    # Detect category automatically
    detected_category = detect_zone_category(clean_text)
    
    # Create zone
    zone = {
        "id": f"ocr_zone_{index}",
        "text": clean_text,
        "confidence": adjusted_score,
        "bbox": {
            "x1": int(x1),
            "y1": int(y1),
            "x2": int(x2),
            "y2": int(y2),
            "width": int(x2 - x1),
            "height": int(y2 - y1)
        },
        "polygon": poly,
        "text_orientation": text_orientation,
        "rotation": text_orientation,  # Also send as 'rotation' for frontend compatibility
        "is_dimension": is_dimension_text_advanced(clean_text),
        "tolerance_info": parse_tolerance(clean_text),
        "category": detected_category
    }
    
    # Log tolerance parsing results
    tolerance_info = zone.get("tolerance_info")
    if tolerance_info:
        print(f"🔍 ZONE TOLERANCE: '{clean_text}' -> {tolerance_info}")
    
    logger.info(f"✅ Zone {index} CREATED: text='{clean_text}', orient={text_orientation}°, conf={adjusted_score:.3f}, bbox=({x1},{y1},{x2},{y2})")
    return zone

def create_zone_from_ocr(text, confidence, bbox, index):
    """Create zone from ocr format data"""
    # Extract coordinates from bbox
    x_coords = [point[0] for point in bbox]
    y_coords = [point[1] for point in bbox]
    x1, x2 = min(x_coords), max(x_coords)
    y1, y2 = min(y_coords), max(y_coords)
    
    # Validate coordinates
    if (math.isnan(x1) or math.isnan(x2) or math.isnan(y1) or math.isnan(y2) or
        x1 >= x2 or y1 >= y2 or x2 - x1 < 1 or y2 - y1 < 1):
        return None
    
    # Basic orientation detection
    text_orientation = 0
    width_bbox = x2 - x1
    height_bbox = y2 - y1
    if height_bbox > width_bbox * 1.5:
        text_orientation = 90
    
    # Detect category automatically
    detected_category = detect_zone_category(text)
    
    # Create zone
    zone = {
        "id": f"ocr_zone_{index}",
        "text": text,
        "confidence": float(confidence),
        "bbox": {
            "x1": int(x1),
            "y1": int(y1),
            "x2": int(x2),
            "y2": int(y2),
            "width": int(x2 - x1),
            "height": int(y2 - y1)
        },
        "polygon": bbox,
        "text_orientation": text_orientation,
        "is_dimension": is_dimension_text(text),
        "tolerance_info": parse_tolerance(text),
        "category": detected_category
    }
    
    # Log tolerance parsing results
    tolerance_info = zone.get("tolerance_info")
    if tolerance_info:
        print(f"🔍 ZONE TOLERANCE: '{text}' -> {tolerance_info}")
    
    return zone

def resize_image_for_speed(image_path, max_dimension=1024):
    """Resize large images to speed up OCR processing"""
    img = cv2.imread(str(image_path))
    if img is None:
        return image_path
    
    height, width = img.shape[:2]
    max_size = max(height, width)
    
    # Only resize if image is larger than max_dimension
    if max_size > max_dimension:
        scale = max_dimension / max_size
        new_width = int(width * scale)
        new_height = int(height * scale)
        
        logger.info(f"🚀 Resizing image from {width}x{height} to {new_width}x{new_height} for faster OCR")
        
        resized_img = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_AREA)
        
        # Save resized image to temporary file
        temp_path = create_secure_temp_file('.jpg')
        cv2.imwrite(temp_path, resized_img)
        
        return temp_path
    
    return image_path

def process_image(image_path, mode="fast", rotation=0):
    """Process a single image and return OCR results with specified mode"""
    logger.info(f">>> process_image CALLED! image_path={image_path}, mode={mode}, rotation={rotation}")
    
    # Resize image for faster processing (except in hardcore mode)
    if mode != "hardcore":
        image_path = resize_image_for_speed(image_path, max_dimension=1024)
    
    # Preprocessing if hardcore mode
    if mode == "hardcore":
        logger.info("🔥 HARDCORE MODE: Applying image preprocessing...")
        original_path = image_path
        image_path = preprocess_image_for_ocr(image_path)
        logger.info(f"🔥 Preprocessing complete: {original_path} -> {image_path}")
    
    try:
        # Get image dimensions for coordinate transformation
        img = cv2.imread(str(image_path))
        if img is None:
            logger.error(f"Failed to load image: {image_path}")
            return {"zones": [], "metadata": {"error": "Failed to load image"}}
        
        height, width = img.shape[:2]
        
        # Apply rotation if specified
        if rotation != 0:
            center = (width // 2, height // 2)
            rotation_matrix = cv2.getRotationMatrix2D(center, rotation, 1.0)
            img = cv2.warpAffine(img, rotation_matrix, (width, height))
            
            # Save rotated image temporarily
            import tempfile
            rotated_fd, rotated_path = tempfile.mkstemp(suffix='_rotated.jpg')
            os.close(rotated_fd)  # Close the file descriptor
            cv2.imwrite(rotated_path, img)
            logger.info(f"Saved rotated image to: {rotated_path}")
            image_path = rotated_path
        
        # Use single OCR model
        logger.info(f"Processing image with OCR mode: {mode}, rotation: {rotation}")
        
        # OCR with parameters according to mode
        try:
            if mode in ["accurate", "hardcore"]:
                logger.info("🔥 Using HARDCORE OCR parameters for maximum detection")
                result = ocr.predict(str(image_path))
            else:
                logger.info("⚡ Using FAST mode OCR parameters")
                result = ocr.predict(str(image_path))
        except Exception as ocr_error:
            logger.error(f"❌ OCR processing failed: {ocr_error}")
            logger.error(f"❌ Error type: {type(ocr_error).__name__}")
            
            # Try fallback with minimal parameters
            try:
                logger.info("🔄 Trying fallback OCR with minimal parameters...")
                result = ocr.predict(str(image_path))
            except Exception as fallback_error:
                logger.error(f"❌ Fallback OCR also failed: {fallback_error}")
                return {"zones": [], "metadata": {"error": f"OCR processing failed: {str(ocr_error)}"}}
        
        # Process OCR result using helper functions
        zones = process_ocr_result(result, mode)
        
        # ENHANCED VERTICAL TEXT DETECTION
        logger.info("🔍 Running enhanced vertical text detection...")
        logger.info(f"🔍 Image shape: {img.shape}, zones before vertical detection: {len(zones)}")
        
        # First, check existing zones for vertical text that might be misclassified
        logger.info("🔍 Checking existing zones for vertical text...")
        for i, zone in enumerate(zones):
            bbox = zone.get('bbox', {})
            if bbox:
                w = bbox.get('width', 0)
                h = bbox.get('height', 0)
                aspect_ratio = h / w if w > 0 else 0
                logger.info(f"🔍 Zone {i}: '{zone.get('text', '')}' w={w}, h={h}, aspect_ratio={aspect_ratio:.2f}")
                
                # If aspect ratio suggests vertical text but orientation is wrong, try re-OCR
                if aspect_ratio > 1.2 and zone.get('text_orientation', 0) == 0:
                    logger.info(f"🔍 Zone {i} might be vertical text - aspect ratio {aspect_ratio:.2f} but orientation 0°")
                    # Try re-OCR with 90° rotation
                    try:
                        # Create a temporary rotated version of this zone
                        zone_img = img[bbox.get('y1', 0):bbox.get('y2', 0), bbox.get('x1', 0):bbox.get('x2', 0)]
                        rotated_zone = cv2.rotate(zone_img, cv2.ROTATE_90_COUNTERCLOCKWISE)
                        
                        # Save and OCR the rotated zone
                        temp_path = f"temp_zone_{i}_rotated.jpg"
                        cv2.imwrite(temp_path, rotated_zone)
                        
                        try:
                            result = ocr.predict(temp_path)
                            if result and result[0]:
                                for detection in result[0]:
                                    if detection and len(detection) >= 2:
                                        rotated_text = detection[1][0] if detection[1] else ""
                                        rotated_conf = detection[1][1] if detection[1] and len(detection[1]) > 1 else 0
                                    
                                    if rotated_conf > zone.get('confidence', 0):
                                        logger.info(f"🔍 Zone {i} rotated OCR better: '{zone.get('text', '')}' → '{rotated_text}' ({rotated_conf:.2f})")
                                        # Update the zone with rotated results
                                        zone['text'] = rotated_text
                                        zone['confidence'] = rotated_conf
                                        zone['text_orientation'] = 90
                                        zone['rotation'] = 90
                        except Exception as ocr_error:
                            logger.error(f"🔍 OCR error for rotated zone {i}: {ocr_error}")
                        
                        # Clean up
                        if os.path.exists(temp_path):
                            os.unlink(temp_path)
                            
                    except Exception as e:
                        logger.error(f"🔍 Error re-OCR zone {i}: {e}")
        
        try:
            vertical_zones = detect_and_process_vertical_text(img)
            logger.info(f"🔍 Vertical detection completed, found {len(vertical_zones)} zones")
            if vertical_zones:
                logger.info(f"🔍 Vertical zones details: {[z.get('text', '') for z in vertical_zones]}")
            zones.extend(vertical_zones)
            logger.info(f"🔍 Added {len(vertical_zones)} vertical text zones to total zones")
        except Exception as e:
            logger.error(f"🔍 Error in vertical text detection: {e}")
            import traceback
            logger.error(f"🔍 Traceback: {traceback.format_exc()}")
        
        # Smart text completion for common patterns like .5 -> 11.5
        zones = smart_text_completion(zones)
        
        # Merge nearby text zones (for cases like "11.5" split into "1", "1", ".", "5")
        zones = merge_nearby_text_zones(zones)
        
        # Apply post-processing
        zones = apply_post_processing(zones)
        
        # Clean up rotated image if created
        if rotation != 0 and os.path.exists(str(image_path)) and '_rotated' in str(image_path):
            try:
                os.unlink(str(image_path))
            except OSError:
                pass
        
        # Create overlay image
        overlay_path = create_overlay_image(image_path, zones)
        
        # Return result
        result = {
            "zones": zones,
            "metadata": {
                "total_zones": len(zones),
                "original_zones_detected": len(zones),
                "zones_merged": 0,
                "overlay_path": overlay_path,
                "detected_angle": 0
            }
        }
        
        logger.info(f"📊 FINAL RESULT: {len(zones)} zones detected")
        return result
        
    except Exception as e:
        logger.error(f"Error processing image: {e}")
        import traceback
        logger.error(f"Traceback: {traceback.format_exc()}")
        return {
            "zones": [],
            "metadata": {"error": str(e)}
        }

def apply_post_processing(zones):
    """Apply post-processing to zones"""
    # Apply correction post-processing if available
    logger.info(f"🔧 Post-processing {len(zones)} zones...")
    if correction_processor:
        try:
            zones_before_corrections = len(zones)
            zones = correction_processor.process_zones(zones)
            post_processing_stats = correction_processor.get_stats()
            logger.info(f"🔧 Applied corrections: {post_processing_stats['total_corrected']} out of {post_processing_stats['total_processed']} zones")
        except Exception as e:
            logger.warning(f"❌ Failed to apply corrections: {e}")
    else:
        logger.info("🔧 No correction processor available")
    
    # Clean OCR text
    logger.info(f"🧹 Cleaning {len(zones)} zones...")
    for i, zone in enumerate(zones):
        original_text = zone.get('text', '')
        cleaned_text = clean_ocr_text_advanced(original_text)
        zone['text'] = cleaned_text
        if original_text != cleaned_text:
            logger.info(f"🧹 Zone {i}: '{original_text}' -> '{cleaned_text}'")
    
    # Remove duplicates
    logger.info(f"🗑️ Checking for duplicate zones (threshold=0.9)...")
    if remove_duplicate_zones:
        zones_before = len(zones)
        zones = remove_duplicate_zones(zones, overlap_threshold=0.9)
        if len(zones) < zones_before:
            logger.info(f"🗑️ Removed {zones_before - len(zones)} duplicate zones")
        else:
            logger.info(f"🗑️ No duplicate zones found")
    
    return zones

async def process_image_async(image_path, mode="fast", rotation=0):
    """Async wrapper for process_image function"""
    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(executor, process_image, image_path, mode, rotation)


@app.get("/yolo/status")
async def yolo_status():
    """Check YOLO availability"""
    return {
        "yolo_available": YOLO_AVAILABLE,
        "yolo_model_loaded": yolo_model is not None,
        "yolo_model_type": str(type(yolo_model)) if yolo_model else None
    }

@app.get("/")
async def root():
    """Health check endpoint"""
    return {
        "message": "SPaCial AI OCR Service",
        "status": "running",
        "ocr_initialized": ocr is not None,
        "service": "SPaCial AI OCR Service",
        "version": "1.0.0"
    }

@app.post("/ocr/process")
async def process_ocr(
    file: UploadFile = File(...), 
    mode: str = Query("fast", description="OCR mode: 'fast' for position detection, 'accurate' or 'hardcore' for maximum text detection"),
    rotation: int = Query(0, description="Rotation angle in degrees (0, 90, 180, 270)")
):
    """
    Process uploaded image with OCR
    Returns detected zones with bounding boxes and text
    
    Parameters:
    - file: Image file to process
    - mode: 'fast' (default) or 'accurate'/'hardcore' for maximum detection
    - rotation: Rotation angle in degrees (0, 90, 180, 270)
    """
    if ocr is None:
        raise HTTPException(status_code=503, detail="OCR service not initialized")
    
    # Validate input parameters
    if mode not in ["fast", "accurate", "hardcore"]:
        raise HTTPException(status_code=400, detail="Invalid mode. Must be 'fast', 'accurate', or 'hardcore'")
    
    if rotation not in [0, 90, 180, 270]:
        raise HTTPException(status_code=400, detail="Invalid rotation. Must be 0, 90, 180, or 270 degrees")
    
    # Validate file for security
    if not validate_uploaded_file(file):
        raise HTTPException(status_code=400, detail="Invalid file: must be a valid image file under 10MB")
    
    # Check if file is PDF
    is_pdf = file.filename and file.filename.lower().endswith('.pdf')
    
    # Save uploaded file to secure temporary location
    temp_path = create_secure_temp_file('.pdf' if is_pdf else '.jpg')
    try:
        content = await file.read()
        with open(temp_path, 'wb') as temp_file:
            temp_file.write(content)
    except Exception as e:
        logger.error(f"Failed to save uploaded file: {e}")
        raise HTTPException(status_code=500, detail="Failed to process uploaded file")
    
    # If PDF, convert to image first
    if is_pdf:
        logger.info(f"📄 PDF detected, converting to image...")
        try:
            image_path = convert_pdf_to_image(temp_path, page_number=0, dpi=300)
            # Clean up original PDF temp file
            try:
                os.unlink(temp_path)
            except:
                pass
            temp_path = image_path
            logger.info(f"✅ PDF converted to image: {temp_path}")
        except Exception as e:
            logger.error(f"Failed to convert PDF: {e}")
            raise HTTPException(status_code=500, detail=f"Failed to convert PDF: {str(e)}")
    
    try:
        logger.info(f"🚀 API CALL: Processing {'PDF' if is_pdf else 'image'}: {file.filename}, mode: {mode}, rotation: {rotation}")
        logger.info(f"📁 Temp file saved: {temp_path}")
        
        # Validate image dimensions
        if not validate_image_dimensions(temp_path):
            raise HTTPException(status_code=400, detail="Image dimensions too large. Maximum allowed: 4096x4096 pixels")
        
        # Process image with specified mode and rotation
        result = await process_image_async(temp_path, mode, rotation)
        logger.info(f"✅ API RESPONSE: Returning {len(result.get('zones', []))} zones")
        
        logger.info(f"OCR result: {len(result.get('zones', []))} zones found")
        
        # If it was a PDF, include the converted image as base64 for frontend display
        if is_pdf:
            import base64
            with open(temp_path, 'rb') as img_file:
                image_base64 = base64.b64encode(img_file.read()).decode('utf-8')
                result['converted_image'] = f"data:image/png;base64,{image_base64}"
                logger.info("✅ Added converted PDF image to response")
        
        return JSONResponse(content=result)
        
    except Exception as e:
        logger.error(f"Error processing uploaded file: {e}")
        import traceback
        logger.error(f"Traceback: {traceback.format_exc()}")
        
        # Return structured error response
        raise HTTPException(
            status_code=500, 
            detail={
                "error": "Image processing failed",
                "message": str(e),
                "type": type(e).__name__
            }
        )
    finally:
        # Always clean up temporary file
        if 'temp_path' in locals() and os.path.exists(temp_path):
            try:
                os.unlink(temp_path)
                logger.info(f"Cleaned up temp file: {temp_path}")
            except OSError as cleanup_error:
                logger.warning(f"Failed to clean up temp file {temp_path}: {cleanup_error}")

@app.post("/ocr/process-path")
async def process_ocr_path(image_path: str = Query(...), mode: str = Query("fast", description="OCR mode: 'fast' for position detection, 'accurate' for hard text search")):
    """
    Process image from file path
    Returns detected zones with bounding boxes and text
    """
    if ocr is None:
        raise HTTPException(status_code=503, detail="OCR service not initialized")
    
    if not os.path.exists(image_path):
        raise HTTPException(status_code=404, detail="Image file not found")
    
    try:
        result = process_image(image_path, mode)
        return JSONResponse(content=result)
        
    except Exception as e:
        logger.error(f"Error processing image path: {e}")
        raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")

@app.post("/ocr/process-center")
async def process_center_point(request: dict = Body(...)):
    """Process center point to find dimension and fit box to text"""
    try:
        logger.info(f"Processing center point request: {list(request.keys())}")
        
        # Extract data from request
        image_data = request.get('image', '')
        center_point = request.get('center_point', {})
        center_x = center_point.get('x', 0)
        center_y = center_point.get('y', 0)
        rectangle_bounds = request.get('rectangle_bounds', {})
        use_rectangle = request.get('use_rectangle', False)
        rotation = request.get('rotation', 0)  # Add rotation support
        
        logger.info(f"Center point: ({center_x}, {center_y}), Image data length: {len(image_data) if image_data else 0}")
        if use_rectangle and rectangle_bounds:
            logger.info(f"Using rectangle bounds: {rectangle_bounds}")
        logger.info(f"Rotation parameter: {rotation}°")
        
        if not image_data:
            raise HTTPException(status_code=400, detail="No image data provided")
        
        # Decode base64 image
        import base64
        try:
            if image_data.startswith('data:image'):
                image_data = image_data.split(',')[1]
            
            image_bytes = base64.b64decode(image_data)
            logger.info(f"Successfully decoded image, size: {len(image_bytes)} bytes")
        except Exception as e:
            logger.error(f"Failed to decode base64 image: {e}")
            raise HTTPException(status_code=400, detail="Invalid image data format")
        
        # Save temporary image
        with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp_file:
            tmp_file.write(image_bytes)
            tmp_path = tmp_file.name
        
        try:
            if use_rectangle and rectangle_bounds:
                # RECTANGLE MODE: Use user's rectangle directly
                logger.info(f"RECTANGLE MODE: Using user's rectangle bounds: {rectangle_bounds}")
                
                # Load image and crop to user's rectangle
                img = cv2.imread(tmp_path)
                if img is None:
                    raise HTTPException(status_code=400, detail="Failed to load image")
                
                # Extract rectangle bounds
                rect_x1 = int(rectangle_bounds.get('x1', 0))
                rect_y1 = int(rectangle_bounds.get('y1', 0))
                rect_x2 = int(rectangle_bounds.get('x2', 0))
                rect_y2 = int(rectangle_bounds.get('y2', 0))
                
                # Validate bounds
                img_height, img_width = img.shape[:2]
                rect_x1 = max(0, min(rect_x1, img_width))
                rect_y1 = max(0, min(rect_y1, img_height))
                rect_x2 = max(rect_x1, min(rect_x2, img_width))
                rect_y2 = max(rect_y1, min(rect_y2, img_height))
                
                logger.info(f"Cropping image to rectangle: ({rect_x1}, {rect_y1}) to ({rect_x2}, {rect_y2})")
                
                # Crop image to rectangle
                cropped_img = img[rect_y1:rect_y2, rect_x1:rect_x2]
                
                # Apply rotation if specified
                if rotation != 0:
                    logger.info(f"Rotating cropped image by {rotation}°")
                    height, width = cropped_img.shape[:2]
                    center = (width // 2, height // 2)
                    rotation_matrix = cv2.getRotationMatrix2D(center, rotation, 1.0)
                    cropped_img = cv2.warpAffine(cropped_img, rotation_matrix, (width, height))
                
                # Save cropped image temporarily
                cropped_path = tmp_path.replace('.jpg', '_cropped.jpg')
                cv2.imwrite(cropped_path, cropped_img)
                
                # Run OCR on cropped image
                logger.info(f"Running OCR on cropped image with rotation: {rotation}°")
                result = await process_image_async(cropped_path, mode="hardcore", rotation=0)  # No additional rotation
                
                # Clean up cropped image
                if os.path.exists(cropped_path):
                    os.unlink(cropped_path)
                
                if result and result.get('zones'):
                    # Use the first (and likely only) zone from cropped image
                    zone = result['zones'][0]
                    
                    # Adjust coordinates back to original image
                    zone_bbox = zone.get('bbox', {})
                    adjusted_bbox = {
                        'x1': rect_x1 + zone_bbox.get('x1', 0),
                        'y1': rect_y1 + zone_bbox.get('y1', 0),
                        'x2': rect_x1 + zone_bbox.get('x2', 0),
                        'y2': rect_y1 + zone_bbox.get('y2', 0),
                        'width': zone_bbox.get('width', 0),
                        'height': zone_bbox.get('height', 0)
                    }
                    
                    logger.info(f"RECTANGLE RESULT: '{zone.get('text', '')}' at adjusted bbox: {adjusted_bbox}")
                    
                    return {
                        "zone": {
                            "text": zone.get('text', ''),
                            "confidence": zone.get('confidence', 0),
                            "bbox": adjusted_bbox,
                            "x": adjusted_bbox.get('x1', 0),
                            "y": adjusted_bbox.get('y1', 0),
                            "width": adjusted_bbox.get('width', 0),
                            "height": adjusted_bbox.get('height', 0),
                            "tolerance_info": zone.get('tolerance_info', {}),
                            "text_orientation": zone.get('text_orientation', rotation),
                            "rotation": zone.get('rotation', rotation)
                        },
                        "message": f"Found dimension: '{zone.get('text', '')}' in user's rectangle",
                        "center_point": {"x": center_x, "y": center_y},
                        "found_zone": zone.get('text', ''),
                        "fitted": True
                    }
                else:
                    logger.warning("No text found in user's rectangle - creating empty zone")
                    
                    # Create empty zone with the user's rectangle bounds
                    empty_zone_bbox = {
                        'x1': rect_x1,
                        'y1': rect_y1,
                        'x2': rect_x2,
                        'y2': rect_y2,
                        'width': rect_x2 - rect_x1,
                        'height': rect_y2 - rect_y1
                    }
                    
                    return {
                        "zone": {
                            "text": "[No Text]",
                            "confidence": 0.0,
                            "bbox": empty_zone_bbox,
                            "x": rect_x1,
                            "y": rect_y1,
                            "width": empty_zone_bbox['width'],
                            "height": empty_zone_bbox['height'],
                            "tolerance_info": {},
                            "text_orientation": rotation,
                            "rotation": rotation,
                            "is_empty": True  # Flag to identify empty zones
                        },
                        "message": "Empty zone created (no text detected)",
                        "center_point": {"x": center_x, "y": center_y},
                        "found_zone": "[No Text]",
                        "fitted": True
                    }
            else:
                # POINT MODE: Use existing logic for center point detection
                logger.info(f"POINT MODE: Processing center point ({center_x}, {center_y})")
                result = await process_image_async(tmp_path, mode="fast", rotation=rotation)
                
                if not result or not result.get('zones'):
                    logger.warning("No zones found in processed result")
                    return {"zones": [], "message": "No text detected"}
                
                zones = result['zones']
                logger.info(f"Found {len(zones)} zones, looking for best match...")
                
                best_zone = None
                best_score = -1
                
                for zone in zones:
                    bbox = zone.get('bbox', {})
                    if not bbox:
                        continue
                    
                    zone_center_x = (bbox.get('x1', 0) + bbox.get('x2', 0)) / 2
                    zone_center_y = (bbox.get('y1', 0) + bbox.get('y2', 0)) / 2
                    zone_confidence = zone.get('confidence', 0)
                    
                    # Calculate distance score
                    distance = ((center_x - zone_center_x) ** 2 + (center_y - zone_center_y) ** 2) ** 0.5
                    score = zone_confidence / (1 + distance / 100)
                    
                    logger.info(f"POINT: Zone '{zone.get('text', '')}' dist={distance:.1f}, conf={zone_confidence:.3f}, score={score:.3f}")
                    
                    if score > best_score:
                        best_score = score
                        best_zone = zone
                
                min_score = 0.05
                logger.info(f"BEST ZONE: {best_zone.get('text', 'None') if best_zone else 'None'}, score={best_score:.3f}, threshold={min_score}")
                
                if best_zone and best_score >= min_score:
                    zone_bbox = best_zone.get('bbox', {})
                    return {
                        "zone": {
                            "text": best_zone.get('text', ''),
                            "confidence": best_zone.get('confidence', 0),
                            "bbox": zone_bbox,
                            "x": zone_bbox.get('x1', 0),
                            "y": zone_bbox.get('y1', 0),
                            "width": zone_bbox.get('width', 0),
                            "height": zone_bbox.get('height', 0),
                            "tolerance_info": best_zone.get('tolerance_info', {})
                        },
                        "message": f"Found dimension: '{best_zone.get('text', '')}' (score: {best_score:.3f})",
                        "center_point": {"x": center_x, "y": center_y},
                        "found_zone": best_zone.get('text', ''),
                        "fitted": True
                    }
                else:
                    return {
                        "zones": [],
                        "message": f"No dimension found (best score: {best_score:.3f}, threshold: {min_score})",
                        "center_point": {"x": center_x, "y": center_y}
                    }
                
        finally:
            # Clean up temporary file
            if os.path.exists(tmp_path):
                os.unlink(tmp_path)
                
    except Exception as e:
        logger.error(f"Error processing center point: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/yolo/detect-zones")
async def yolo_detect_zones(
    file: UploadFile = File(...),
    confidence: float = Query(0.01, description="Confidence threshold for YOLO detection"),
    use_obb: bool = Query(True, description="Use Oriented Bounding Boxes for rotated text")
):
    """
    Use YOLOv11 to detect text regions, then use PaddleOCR to read them
    Hybrid approach: YOLO for fast detection + PaddleOCR for text recognition
    """
    logger.info(f"🎯 YOLO endpoint called! YOLO_AVAILABLE={YOLO_AVAILABLE}, yolo_model={yolo_model is not None}")
    
    if not YOLO_AVAILABLE or yolo_model is None:
        raise HTTPException(status_code=503, detail=f"YOLOv11 not available. YOLO_AVAILABLE={YOLO_AVAILABLE}, yolo_model={'None' if yolo_model is None else 'exists'}")
    
    if not ocr:
        raise HTTPException(status_code=503, detail="OCR service not initialized")
    
    tmp_path = None
    try:
        # Save uploaded file
        with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp_file:
            content = await file.read()
            tmp_file.write(content)
            tmp_path = tmp_file.name
        
        logger.info(f"🎯 YOLO: Detecting zones in {file.filename}...")
        
        # Use YOLO for detection
        results = yolo_model.predict(
            source=tmp_path,
            conf=confidence,
            verbose=False,
            device='cpu'  # Use CPU by default, can be changed to 'cuda' for GPU
        )
        
        # Load image for OCR
        img = cv2.imread(tmp_path)
        if img is None:
            raise HTTPException(status_code=400, detail="Failed to load image")
        
        detected_zones = []
        
        # Process each detection
        for result in results:
            boxes = result.boxes
            for box in boxes:
                # Get bounding box coordinates
                x1, y1, x2, y2 = box.xyxy[0].cpu().numpy()
                conf = float(box.conf[0])
                cls = int(box.cls[0])
                
                # Crop the detected region
                x1_int, y1_int = int(x1), int(y1)
                x2_int, y2_int = int(x2), int(y2)
                
                # Ensure coordinates are within image bounds
                x1_int = max(0, x1_int)
                y1_int = max(0, y1_int)
                x2_int = min(img.shape[1], x2_int)
                y2_int = min(img.shape[0], y2_int)
                
                if x2_int <= x1_int or y2_int <= y1_int:
                    continue
                
                cropped = img[y1_int:y2_int, x1_int:x2_int]
                
                # Save cropped region temporarily for OCR
                with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as crop_tmp:
                    cv2.imwrite(crop_tmp.name, cropped)
                    crop_tmp_path = crop_tmp.name
                
                try:
                    # Run OCR on the cropped region using predict
                    ocr_result = ocr.predict(crop_tmp_path)
                    
                    # Extract text from OCR result
                    text = ""
                    ocr_confidence = 0
                    if ocr_result and ocr_result[0]:
                        for detection in ocr_result[0]:
                            if detection and len(detection) >= 2:
                                detected_text = detection[1]
                                if isinstance(detected_text, (list, tuple)) and len(detected_text) >= 2:
                                    text += str(detected_text[0]) + " "
                                    ocr_confidence = max(ocr_confidence, float(detected_text[1]))
                                elif isinstance(detected_text, str):
                                    text += detected_text + " "
                    
                    text = text.strip()
                finally:
                    # Clean up temporary cropped file
                    if os.path.exists(crop_tmp_path):
                        os.unlink(crop_tmp_path)
                
                if text:  # Only add zones with detected text
                    detected_zones.append({
                        "text": text,
                        "confidence": float(ocr_confidence),
                        "yolo_confidence": conf,
                        "bbox": {
                            "x1": float(x1),
                            "y1": float(y1),
                            "x2": float(x2),
                            "y2": float(y2),
                            "width": float(x2 - x1),
                            "height": float(y2 - y1)
                        },
                        "category": result.names[cls] if hasattr(result, 'names') else "text",
                        "source": "yolo_paddleocr"
                    })
        
        logger.info(f"✅ YOLO: Detected {len(detected_zones)} text zones")
        
        return {
            "zones": detected_zones,
            "metadata": {
                "total_zones": len(detected_zones),
                "confidence_threshold": confidence,
                "model": "YOLOv11n + PaddleOCR",
                "use_obb": use_obb
            }
        }
        
    except Exception as e:
        logger.error(f"Error in YOLO detection: {e}")
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        if tmp_path and os.path.exists(tmp_path):
            os.unlink(tmp_path)

@app.post("/ocr/process-with-lines")
async def process_with_lines(request: dict = Body(...)):
    """Process image with OCR and detect dimension lines"""
    try:
        # Extract data from request
        image_data = request.get('image', '')
        
        if not image_data:
            raise HTTPException(status_code=400, detail="No image data provided")
        
        # Decode base64 image
        import base64
        if image_data.startswith('data:image'):
            image_data = image_data.split(',')[1]
        
        image_bytes = base64.b64decode(image_data)
        
        # Save temporary image
        with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp_file:
            tmp_file.write(image_bytes)
            tmp_path = tmp_file.name
        
        try:
            # Process image with OCR
            result = await process_image_async(tmp_path, mode="fast")
            
            if not result or not result.get('zones'):
                return {"zones": [], "lines": [], "dimension_lines": [], "message": "No text detected"}
            
            # Detect lines in the image
            detected_lines = detect_dimension_lines(tmp_path)
            
            # Find lines near dimensions
            dimension_lines = find_lines_near_dimensions(result['zones'], detected_lines)
            
            # Create overlay image with lines
            overlay_image = create_overlay_image(tmp_path, result['zones'], detected_lines, dimension_lines)
            
            # Convert overlay to base64
            overlay_base64 = None
            if overlay_image is not None:
                import base64
                _, buffer = cv2.imencode('.jpg', overlay_image)
                overlay_base64 = base64.b64encode(buffer).decode('utf-8')
            
            return {
                "zones": result['zones'],
                "lines": detected_lines,
                "dimension_lines": dimension_lines,
                "overlay_image": overlay_base64,
                "message": f"Found {len(result['zones'])} text zones, {len(detected_lines)} lines, {len(dimension_lines)} dimension-line pairs"
            }
                
        finally:
            # Clean up temporary file
            if os.path.exists(tmp_path):
                os.unlink(tmp_path)
                
    except Exception as e:
        logger.error(f"Error processing image with lines: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/ocr/get-text-properties")
async def get_text_properties(request: dict = Body(...)):
    """Get original text properties for precise box fitting"""
    try:
        # Extract data from request
        image_data = request.get('image', '')
        bbox = request.get('bbox', {})
        
        if not image_data or not bbox:
            raise HTTPException(status_code=400, detail="Image data and bbox required")
        
        # Decode base64 image
        import base64
        if image_data.startswith('data:image'):
            image_data = image_data.split(',')[1]
        
        image_bytes = base64.b64decode(image_data)
        
        # Save temporary image
        with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp_file:
            tmp_file.write(image_bytes)
            tmp_path = tmp_file.name
        
        try:
            # Process image with OCR
            result = await process_image_async(tmp_path, mode="fast")
            
            if not result or not result.get('zones'):
                return {"error": "No text detected"}
            
            # Find the zone that matches the bbox
            target_zone = None
            for zone in result['zones']:
                zone_bbox = zone.get('bbox', {})
                if (isinstance(zone_bbox, dict) and 
                    abs(zone_bbox.get('x1', 0) - bbox.get('x1', 0)) < 10 and
                    abs(zone_bbox.get('y1', 0) - bbox.get('y1', 0)) < 10):
                    target_zone = zone
                    break
            
            if not target_zone:
                return {"error": "Matching zone not found"}
            
            # Extract text properties
            text_properties = {
                "text": target_zone.get('text', ''),
                "confidence": target_zone.get('confidence', 0),
                "bbox": target_zone.get('bbox', {}),
                "orientation": target_zone.get('orientation', 0),
                "rotation": target_zone.get('rotation', 0),
                "width": target_zone.get('width', 0),
                "height": target_zone.get('height', 0)
            }
            
            return text_properties
                
        finally:
            # Clean up temporary file
            if os.path.exists(tmp_path):
                os.unlink(tmp_path)
                
    except Exception as e:
        logger.error(f"Error getting text properties: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/ocr/process-baseline")
async def process_baseline(request: dict = Body(...)):
    """Process baseline to find text and fit precise box"""
    try:
        # Extract data from request
        image_data = request.get('image', '')
        baseline = request.get('baseline', {})
        x1 = baseline.get('x1', 0)
        y1 = baseline.get('y1', 0)
        x2 = baseline.get('x2', 0)
        y2 = baseline.get('y2', 0)
        
        if not image_data:
            raise HTTPException(status_code=400, detail="No image data provided")
        
        # Decode base64 image
        import base64
        if image_data.startswith('data:image'):
            image_data = image_data.split(',')[1]
        
        image_bytes = base64.b64decode(image_data)
        
        # Save temporary image
        with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp_file:
            tmp_file.write(image_bytes)
            tmp_path = tmp_file.name
        
        try:
            # Process full image with OCR
            result = process_image(tmp_path, mode="fast")
            
            if not result or not result.get('zones'):
                return {"zones": [], "message": "No text detected"}
            
            # Find text zones that intersect with the baseline
            zones = result['zones']
            intersecting_zones = []
            
            for zone in zones:
                bbox = zone.get('bbox', {})
                if not bbox:
                    continue
                
                # Check if zone intersects with baseline
                if intersects_with_line(bbox, x1, y1, x2, y2):
                    # Calculate distance from zone center to baseline
                    zone_center_x = (bbox.get('x1', 0) + bbox.get('x2', 0)) / 2
                    zone_center_y = (bbox.get('y1', 0) + bbox.get('y2', 0)) / 2
                    distance = distance_point_to_line(zone_center_x, zone_center_y, x1, y1, x2, y2)
                    
                    intersecting_zones.append({
                        'zone': zone,
                        'distance': distance
                    })
            
            # Sort by distance to baseline (closest first)
            intersecting_zones.sort(key=lambda x: x['distance'])
            
            if intersecting_zones:
                # Return the closest zone
                closest = intersecting_zones[0]
                zone = closest['zone']
                zone_bbox = zone.get('bbox', {})
                
                # Ensure we return the zone with proper bbox coordinates
                if isinstance(zone_bbox, dict):
                    return {
                        "zone": {
                            "text": zone.get('text', ''),
                            "confidence": zone.get('confidence', 0),
                            "bbox": zone_bbox,
                            "x": zone_bbox.get('x1', 0),
                            "y": zone_bbox.get('y1', 0),
                            "width": zone_bbox.get('width', 0),
                            "height": zone_bbox.get('height', 0),
                            "tolerance_info": zone.get('tolerance_info', {})
                        },
                        "message": f"Found text along baseline (distance: {closest['distance']:.1f}px)",
                        "baseline": {"x1": x1, "y1": y1, "x2": x2, "y2": y2},
                        "found_zone": zone.get('text', ''),
                        "fitted": True
                    }
                else:
                    return {
                        "zone": zone,
                        "message": f"Found text along baseline (distance: {closest['distance']:.1f}px)",
                        "baseline": {"x1": x1, "y1": y1, "x2": x2, "y2": y2},
                        "found_zone": zone.get('text', ''),
                        "fitted": True
                    }
            else:
                return {
                    "zones": [],
                    "message": "No text found along baseline",
                    "baseline": {"x1": x1, "y1": y1, "x2": x2, "y2": y2}
                }
                
        finally:
            # Clean up temporary file
            if os.path.exists(tmp_path):
                os.unlink(tmp_path)
                
    except Exception as e:
        logger.error(f"Error processing baseline: {e}")
        raise HTTPException(status_code=500, detail=str(e))

def intersects_with_line(bbox, x1, y1, x2, y2):
    """Check if bounding box intersects with line"""
    bx1, by1 = bbox.get('x1', 0), bbox.get('y1', 0)
    bx2, by2 = bbox.get('x2', 0), bbox.get('y2', 0)
    
    # Check if any corner of the box is close to the line
    corners = [(bx1, by1), (bx2, by1), (bx2, by2), (bx1, by2)]
    
    for cx, cy in corners:
        distance = distance_point_to_line(cx, cy, x1, y1, x2, y2)
        if distance < 20:  # Within 20 pixels
            return True
    
    return False

def distance_point_to_line(px, py, x1, y1, x2, y2):
    """Calculate distance from point to line"""
    # Line vector
    line_dx = x2 - x1
    line_dy = y2 - y1
    
    # Point vector
    point_dx = px - x1
    point_dy = py - y1
    
    # Calculate distance using cross product
    if line_dx == 0 and line_dy == 0:
        # Line is a point
        return ((px - x1) ** 2 + (py - y1) ** 2) ** 0.5
    
    # Distance = |cross_product| / |line_vector|
    cross_product = abs(point_dx * line_dy - point_dy * line_dx)
    line_length = (line_dx ** 2 + line_dy ** 2) ** 0.5
    
    return cross_product / line_length

def detect_dimension_lines(image_path):
    """Detect lines in the image that could be dimension lines"""
    import cv2
    import numpy as np
    
    # Read image
    img = cv2.imread(image_path)
    if img is None:
        return []
    
    # Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # Apply edge detection
    edges = cv2.Canny(gray, 50, 150, apertureSize=3)
    
    # Detect lines using HoughLinesP
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=50, minLineLength=30, maxLineGap=10)
    
    detected_lines = []
    if lines is not None:
        for line in lines:
            x1, y1, x2, y2 = line[0]
            length = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
            
            # Filter out very short lines
            if length > 20:
                # Calculate angle
                angle = math.atan2(y2 - y1, x2 - x1) * 180 / math.pi
                if angle < 0:
                    angle += 180
                
                detected_lines.append({
                    'x1': float(x1),
                    'y1': float(y1),
                    'x2': float(x2),
                    'y2': float(y2),
                    'length': float(length),
                    'angle': float(angle)
                })
    
    return detected_lines

def find_lines_near_dimensions(zones, lines, max_distance=50):
    """Find lines that are close to dimension text"""
    dimension_lines = []
    
    for zone in zones:
        bbox = zone.get('bbox', {})
        if not bbox:
            continue
        
        # Get zone center
        zone_center_x = (bbox.get('x1', 0) + bbox.get('x2', 0)) / 2
        zone_center_y = (bbox.get('y1', 0) + bbox.get('y2', 0)) / 2
        
        # Find closest lines
        nearby_lines = []
        for line in lines:
            distance = distance_point_to_line(zone_center_x, zone_center_y, 
                                            line['x1'], line['y1'], line['x2'], line['y2'])
            
            if distance < max_distance:
                nearby_lines.append({
                    'line': line,
                    'distance': distance
                })
        
        # Sort by distance
        nearby_lines.sort(key=lambda x: x['distance'])
        
        if nearby_lines:
            dimension_lines.append({
                'zone': zone,
                'closest_line': nearby_lines[0]['line'],
                'distance': nearby_lines[0]['distance'],
                'all_nearby_lines': [nl['line'] for nl in nearby_lines[:3]]  # Top 3 closest
            })
    
    return dimension_lines

# Telegram Bot Integration
import requests
import json
from fastapi import Request
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles

# Mount static files with error handling
static_dir = os.path.join(os.path.dirname(__file__), "static")
if os.path.exists(static_dir):
    app.mount("/static", StaticFiles(directory=static_dir), name="static")
    logger.info(f"Static files mounted from: {static_dir}")
else:
    logger.warning(f"Static directory not found: {static_dir}")
    # Create static directory if it doesn't exist
    try:
        os.makedirs(static_dir, exist_ok=True)
        app.mount("/static", StaticFiles(directory=static_dir), name="static")
        logger.info(f"Created and mounted static directory: {static_dir}")
    except Exception as e:
        logger.error(f"Failed to create static directory: {e}")

def send_telegram_message(message, chat_id=None):
    """Send message to Telegram"""
    bot_token = os.getenv('TELEGRAM_BOT_TOKEN')
    if not bot_token:
        return False
    
    target_chat_id = chat_id or os.getenv('TELEGRAM_CHAT_ID')
    if not target_chat_id:
        return False
    
    # Try multiple Telegram API endpoints for better connectivity
    api_urls = [
        "https://api.telegram.org",
        "https://api.telegram.org:443"
    ]
    
    for api_url in api_urls:
        try:
            url = f"{api_url}/bot{bot_token}/sendMessage"
            data = {
                'chat_id': target_chat_id,
                'text': message,
                'parse_mode': 'Markdown'
            }
            
            # Add timeout and retry logic
            session = requests.Session()
            session.timeout = 10
            
            response = session.post(url, data=data, timeout=10)
            if response.status_code == 200:
                logger.info(f"Successfully sent Telegram message via {api_url}")
                return True
                
        except Exception as e:
            logger.warning(f"Failed to send via {api_url}: {e}")
            continue
    
    logger.error("Failed to send Telegram message via all endpoints")
    return False

def send_telegram_photo(image_path, caption="", chat_id=None):
    """Send photo to Telegram"""
    bot_token = os.getenv('TELEGRAM_BOT_TOKEN')
    if not bot_token:
        return False
    
    target_chat_id = chat_id or os.getenv('TELEGRAM_CHAT_ID')
    if not target_chat_id:
        return False
    
    url = f"https://api.telegram.org/bot{bot_token}/sendPhoto"
    
    try:
        with open(image_path, 'rb') as photo:
            files = {'photo': photo}
            data = {
                'chat_id': target_chat_id,
                'caption': caption
            }
            response = requests.post(url, files=files, data=data)
            return response.status_code == 200
    except Exception as e:
        logger.error(f"Failed to send Telegram photo: {e}")
        return False

def send_telegram_document(file_path, caption="", chat_id=None):
    """Send document to Telegram"""
    bot_token = os.getenv('TELEGRAM_BOT_TOKEN')
    if not bot_token:
        return False
    
    target_chat_id = chat_id or os.getenv('TELEGRAM_CHAT_ID')
    if not target_chat_id:
        return False
    
    url = f"https://api.telegram.org/bot{bot_token}/sendDocument"
    
    try:
        with open(file_path, 'rb') as document:
            files = {'document': document}
            data = {
                'chat_id': target_chat_id,
                'caption': caption
            }
            response = requests.post(url, files=files, data=data)
            return response.status_code == 200
    except Exception as e:
        logger.error(f"Failed to send Telegram document: {e}")
        return False

def send_correction_to_telegram(correction_data):
    """Send correction data to Telegram channel"""
    try:
        # Create message
        message = f"""📊 New Training Data Received

🆔 Image ID: {correction_data.get('image_id', 'unknown')}
👤 User: {correction_data.get('user_id', 'unknown')}
⏰ Time: {correction_data.get('timestamp', 'unknown')}

📈 Statistics:
• Original zones: {len(correction_data.get('original_zones', []))}
• Corrected zones: {len(correction_data.get('corrected_zones', []))}
• Text fixed: {sum(1 for zone in correction_data.get('corrected_zones', []) if zone.get('correction_type') == 'text_fixed')}
• Boxes moved: {sum(1 for zone in correction_data.get('corrected_zones', []) if zone.get('correction_type') == 'box_moved')}
• New zones added: {sum(1 for zone in correction_data.get('corrected_zones', []) if zone.get('correction_type') == 'new_zone')}
• Zones deleted: {sum(1 for zone in correction_data.get('corrected_zones', []) if zone.get('correction_type') == 'deleted')}
• Validated (OK): {sum(1 for zone in correction_data.get('corrected_zones', []) if zone.get('correction_type') == 'validated')}

✅ Data saved for model training"""

        # Send message
        send_telegram_message(message)
        
        # Create JSON file with training data
        import tempfile
        with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
            json.dump(correction_data, f, indent=2)
            json_path = f.name
        
        # Send JSON file
        send_telegram_document(json_path, "Training data JSON")
        
        # Clean up
        os.unlink(json_path)
        
        return True
    except Exception as e:
        logger.error(f"Failed to send correction to Telegram: {e}")
        return False

@app.get("/telegram/status")
async def telegram_status():
    """Check Telegram bot configuration"""
    bot_token = os.getenv('TELEGRAM_BOT_TOKEN')
    chat_id = os.getenv('TELEGRAM_CHAT_ID')
    
    return {
        "configured": bool(bot_token and chat_id),
        "bot_token_set": bool(bot_token),
        "chat_id_set": bool(chat_id),
        "connection": "ok" if (bot_token and chat_id) else "missing_config",
        "bot_username": "unknown"  # Would need to fetch from Telegram API
    }

@app.post("/telegram/set-webhook")
async def set_telegram_webhook(webhook_url: str = Query(...)):
    """Set Telegram webhook URL"""
    bot_token = os.getenv('TELEGRAM_BOT_TOKEN')
    if not bot_token:
        return {"success": False, "message": "Bot token not configured"}
    
    url = f"https://api.telegram.org/bot{bot_token}/setWebhook"
    data = {"url": webhook_url}
    
    try:
        response = requests.post(url, data=data)
        result = response.json()
        return {
            "success": result.get("ok", False),
            "message": result.get("description", "Unknown error"),
            "webhook_url": webhook_url,
            "telegram_response": result
        }
    except Exception as e:
        return {"success": False, "message": f"Error setting webhook: {str(e)}"}

@app.post("/telegram/webhook")
async def telegram_webhook(request: Request):
    """Handle incoming Telegram messages"""
    try:
        data = await request.json()
        logger.info(f"Received Telegram webhook: {data}")
        
        # Extract message info
        message = data.get('message', {})
        chat_id = message.get('chat', {}).get('id')
        user_id = message.get('from', {}).get('id')
        text = message.get('text', '')
        photo = message.get('photo', [])
        
        # Handle text commands
        if text:
            if text.startswith('/start'):
                # Log the command but don't send response due to DNS issues
                logger.info(f"User {user_id} sent /start command")
                # Just return success - user can access mini app directly
                pass
            
            elif text.startswith('/help'):
                logger.info(f"User {user_id} requested help")
                # Just return success
                pass
            
            elif text.startswith('/status'):
                logger.info(f"User {user_id} checked status")
                # Just return success
                pass
        
        # Handle photo uploads
        elif photo:
            # Get the largest photo
            largest_photo = max(photo, key=lambda x: x.get('file_size', 0))
            file_id = largest_photo.get('file_id')
            
            # Download photo
            photo_path = await download_telegram_photo(file_id)
            if photo_path:
                try:
                    # Process with OCR
                    result = process_image(photo_path, mode="fast")
                    
                    if result and result.get('zones'):
                        zones = result['zones']
                        logger.info(f"Processed photo for user {user_id}: Found {len(zones)} zones")
                        
                        # Log the results instead of sending message
                        for i, zone in enumerate(zones[:5]):
                            logger.info(f"Zone {i+1}: {zone.get('text', '')} ({int(zone.get('confidence', 0)*100)}%)")
                        
                        if len(zones) > 5:
                            logger.info(f"... and {len(zones)-5} more zones")
                    else:
                        logger.info(f"No text detected in photo from user {user_id}")
                    
                except Exception as ocr_error:
                    logger.error(f"OCR processing error for user {user_id}: {ocr_error}")
                finally:
                    # Clean up
                    if os.path.exists(photo_path):
                        os.unlink(photo_path)
        
        return {"status": "ok"}
        
    except Exception as e:
        logger.error(f"Error handling Telegram webhook: {e}")
        return {"status": "error", "message": str(e)}

def send_telegram_message_with_keyboard(message, chat_id, keyboard):
    """Send message with inline keyboard"""
    bot_token = os.getenv('TELEGRAM_BOT_TOKEN')
    if not bot_token:
        return False
    
    # Try multiple Telegram API endpoints for better connectivity
    api_urls = [
        "https://api.telegram.org",
        "https://api.telegram.org:443"
    ]
    
    for api_url in api_urls:
        try:
            url = f"{api_url}/bot{bot_token}/sendMessage"
            data = {
                'chat_id': chat_id,
                'text': message,
                'parse_mode': 'Markdown',
                'reply_markup': json.dumps(keyboard)
            }
            
            # Add timeout and retry logic
            session = requests.Session()
            session.timeout = 10
            
            response = session.post(url, data=data, timeout=10)
            if response.status_code == 200:
                logger.info(f"Successfully sent Telegram message with keyboard via {api_url}")
                return True
                
        except Exception as e:
            logger.warning(f"Failed to send keyboard message via {api_url}: {e}")
            continue
    
    logger.error("Failed to send Telegram message with keyboard via all endpoints")
    return False

async def download_telegram_photo(file_id):
    """Download photo from Telegram"""
    bot_token = os.getenv('TELEGRAM_BOT_TOKEN')
    if not bot_token:
        return None
    
    try:
        # Get file info
        url = f"https://api.telegram.org/bot{bot_token}/getFile"
        response = requests.get(url, params={'file_id': file_id})
        file_info = response.json()
        
        if not file_info.get('ok'):
            return None
        
        file_path = file_info['result']['file_path']
        
        # Download file
        download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
        response = requests.get(download_url)
        
        # Save to temporary file
        with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp_file:
            tmp_file.write(response.content)
            return tmp_file.name
            
    except Exception as e:
        logger.error(f"Failed to download Telegram photo: {e}")
        return None

@app.get("/camera")
async def camera_mini_app():
    """Serve the camera mini app"""
    return FileResponse("static/camera.html")

@app.post("/blueprint/quick-validate")
async def quick_validate_blueprint(file: UploadFile = File(...)):
    """
    Validation rapide d'un plan - retourne juste les statistiques
    Utile pour un aperçu rapide avant traitement complet
    """
    with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as temp_file:
        content = await file.read()
        temp_file.write(content)
        temp_path = temp_file.name
    
    try:
        # OCR rapide
        result = process_image(temp_path, mode="fast")
        zones = result.get('zones', [])
        
        # Statistiques rapides
        stats = {
            'total_zones': len(zones),
            'dimension_count': sum(1 for z in zones if z.get('is_dimension')),
            'with_tolerance': sum(1 for z in zones if z.get('tolerance_info')),
            'avg_confidence': sum(z.get('confidence', 0) for z in zones) / len(zones) if zones else 0,
            'low_confidence_zones': sum(1 for z in zones if z.get('confidence', 0) < 0.7),
            'recommendation': ''
        }
        
        # Recommandation
        if stats['avg_confidence'] < 0.7:
            stats['recommendation'] = "Qualité d'image faible - essayez le mode 'quality_control'"
        elif stats['dimension_count'] < 5:
            stats['recommendation'] = "Peu de dimensions détectées - vérifiez l'image"
        else:
            stats['recommendation'] = "Qualité acceptable - traitement complet recommandé"
        
        os.unlink(temp_path)
        
        return JSONResponse(content=stats)
        
    except Exception as e:
        if os.path.exists(temp_path):
            os.unlink(temp_path)
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/blueprint/stats")
async def get_blueprint_stats():
    """Obtenir des statistiques sur le système OCR"""
    return {
        "system_status": "operational",
        "blueprint_processor_available": True,
        "features": [
            "Enhanced dimension detection",
            "Tolerance parsing",
            "Quality analysis",
            "Smart zone merging",
            "Advanced text cleaning",
            "Thread specification support"
        ],
        "supported_modes": ["fast", "accurate", "hardcore"],
        "advanced_processing": {
            "smart_merging": merge_overlapping_zones,
            "duplicate_removal": remove_duplicate_zones,
            "text_cleaning": True,
            "orientation_detection": True
        }
    }

@app.post("/export/pdf")
async def export_pdf_report(
    image: UploadFile = File(...),
    zones: str = Body(...),
    title: str = Body("OCR Measurement Report"),
    part_number: str = Body("Part 1")
):
    """Export PDF report with image, bubbles, and tolerance grid"""
    try:
        # Check if PDF service is available
        if not PDF_AVAILABLE or not pdf_service:
            raise HTTPException(
                status_code=503, 
                detail="PDF export service not available. Please ensure reportlab is installed."
            )
        
        # Validate image
        if not image.content_type or not image.content_type.startswith('image/'):
            raise HTTPException(status_code=400, detail="Invalid image file")
        
        # Parse zones data
        import json
        try:
            zones_data = json.loads(zones)
            logger.info(f"PDF Export: Parsed {len(zones_data)} zones")
            
            # Debug: Check for None zones
            none_zones = [i for i, zone in enumerate(zones_data) if zone is None]
            if none_zones:
                logger.error(f"PDF Export: Found None zones at indices: {none_zones}")
                # Filter out None zones
                zones_data = [zone for zone in zones_data if zone is not None]
                logger.info(f"PDF Export: Filtered to {len(zones_data)} valid zones")
                
        except json.JSONDecodeError:
            raise HTTPException(status_code=400, detail="Invalid zones data format")
        
        # Read image data
        image_data = await image.read()
        
        # Generate PDF
        if not pdf_service:
            raise HTTPException(
                status_code=503, 
                detail="PDF service not initialized"
            )
        
        pdf_bytes = pdf_service.generate_pdf_report(
            image_data=image_data,
            zones=zones_data,
            title=title,
            part_number=part_number
        )
        
        # Return PDF as response
        return Response(
            content=pdf_bytes,
            media_type="application/pdf",
            headers={
                "Content-Disposition": f"attachment; filename={part_number}_measurement_report.pdf"
            }
        )
        
    except Exception as e:
        logger.error(f"PDF export error: {e}")
        raise HTTPException(status_code=500, detail=f"PDF generation failed: {str(e)}")

def create_measurement_sheet(ws, part_number, language, zones=None):
    """Create a measurement sheet for the specified language"""
    
    # Language-specific translations
    translations = {
        "en": {
            "title": f"Measurement Grid - {part_number}",
            "date": "Date: _______________",
            "operator": "Operator: _______________",
            "annotations": "Annotations",
            "part": "Part",
            "headers": ['#', 'Value Name', 'Min Tol', 'Max Tol', 'Mid Value', '1', '2', '3', '4', '5', '6']
        },
        "fr": {
            "title": f"Grille de Mesure - {part_number}",
            "date": "Date: _______________",
            "operator": "Opérateur: _______________",
            "annotations": "Annotations",
            "part": "Pièce",
            "headers": ['#', 'Nom Valeur', 'Min Tol', 'Max Tol', 'Valeur Mil', '1', '2', '3', '4', '5', '6']
        }
    }
    
    trans = translations[language]
    
    # Set column widths - new layout with more parts
    ws.column_dimensions['A'].width = 4   # #
    ws.column_dimensions['B'].width = 15  # Value name (more space)
    ws.column_dimensions['C'].width = 8   # Min tolerance
    ws.column_dimensions['D'].width = 8   # Max tolerance
    ws.column_dimensions['E'].width = 10  # Mid value to check
    # Parts columns - more space for handwriting
    ws.column_dimensions['F'].width = 15  # Part 1
    ws.column_dimensions['G'].width = 15  # Part 2
    ws.column_dimensions['H'].width = 15  # Part 3
    ws.column_dimensions['I'].width = 15  # Part 4
    ws.column_dimensions['J'].width = 15  # Part 5
    ws.column_dimensions['K'].width = 15  # Part 6
    
    # Define styles
    header_fill = PatternFill(start_color="0088FF", end_color="0088FF", fill_type="solid")
    header_font = Font(bold=True, color="FFFFFF", size=12)
    border = Border(
        left=Side(style='thin'),
        right=Side(style='thin'),
        top=Side(style='thin'),
        bottom=Side(style='thin')
    )
    
    # Add title
    ws['A1'] = trans["title"]
    ws['A1'].font = Font(bold=True, size=14)
    ws.merge_cells('A1:K1')
    
    # Add date and operator fields for template
    ws['A2'] = trans["date"]
    ws['A2'].font = Font(size=11)
    ws.merge_cells('A2:C2')
    
    ws['D2'] = trans["operator"]
    ws['D2'].font = Font(size=11)
    ws.merge_cells('D2:F2')
    
    # Add grid headers - Annotations and Parts
    ws['A3'] = trans["annotations"]
    ws['A3'].font = Font(bold=True, size=10)
    ws.merge_cells('A3:E3')
    
    ws['F3'] = "Parts"
    ws['F3'].font = Font(bold=True, size=10)
    ws.merge_cells('F3:K3')
    
    # Add compact headers
    headers = trans["headers"]
    for col, header in enumerate(headers, start=1):
        cell = ws.cell(row=4, column=col, value=header)
        cell.fill = header_fill
        cell.font = Font(bold=True, color="FFFFFF", size=9)  # Smaller font
        cell.alignment = Alignment(horizontal='center', vertical='center')
        cell.border = border
    
    # Add data rows - populate with extracted features if available
    row = 5
    if zones and len(zones) > 0:
        # Populate with ALL extracted zones (no limit)
        for idx, zone in enumerate(zones, start=1):  # Export ALL zones
            if zone is None:
                continue
            
            # Extract zone data safely
            text = zone.get('text', '') if isinstance(zone, dict) else ''
            tolerance_info = zone.get('tolerance_info', {}) if isinstance(zone, dict) else {}
            
            # Ensure tolerance_info is a dict
            if not isinstance(tolerance_info, dict):
                tolerance_info = {}
            
            # Extract tolerance data
            min_tol = tolerance_info.get('min_tolerance', '')
            max_tol = tolerance_info.get('max_tolerance', '')
            middle_value = tolerance_info.get('middle_value', '')
            
            # Write row with extracted data
            ws.cell(row=row, column=1, value=idx).border = border  # #
            ws.cell(row=row, column=2, value=text).border = border  # Value Name
            ws.cell(row=row, column=3, value=min_tol).border = border  # Min Tol
            ws.cell(row=row, column=4, value=max_tol).border = border  # Max Tol
            ws.cell(row=row, column=5, value=middle_value).border = border  # Mid Value
            # Parts columns - empty for operators to fill
            ws.cell(row=row, column=6, value='').border = border   # Part 1
            ws.cell(row=row, column=7, value='').border = border   # Part 2
            ws.cell(row=row, column=8, value='').border = border   # Part 3
            ws.cell(row=row, column=9, value='').border = border   # Part 4
            ws.cell(row=row, column=10, value='').border = border  # Part 5
            ws.cell(row=row, column=11, value='').border = border  # Part 6
            
            row += 1
    else:
        # Create empty template rows if no zones provided
        for idx in range(1, 21):
            ws.cell(row=row, column=1, value=idx).border = border  # #
            ws.cell(row=row, column=2, value='').border = border   # Value Name
            ws.cell(row=row, column=3, value='').border = border   # Min Tol
            ws.cell(row=row, column=4, value='').border = border   # Max Tol
            ws.cell(row=row, column=5, value='').border = border   # Mid Value
            # Parts columns - empty for operators to fill
            ws.cell(row=row, column=6, value='').border = border   # Part 1
            ws.cell(row=row, column=7, value='').border = border   # Part 2
            ws.cell(row=row, column=8, value='').border = border   # Part 3
            ws.cell(row=row, column=9, value='').border = border   # Part 4
            ws.cell(row=row, column=10, value='').border = border  # Part 5
            ws.cell(row=row, column=11, value='').border = border  # Part 6
            
            row += 1

@app.post("/export/excel")
async def export_excel_report(request: Request):
    """Export Excel report with tolerance data"""
    try:
        # Check if openpyxl is available
        if not OPENPYXL_AVAILABLE:
            raise HTTPException(
                status_code=503, 
                detail="Excel export service not available. Please ensure openpyxl is installed."
            )
        
        # Parse request data
        import json
        data = await request.json()
        zones = data.get('zones', [])
        title = data.get('title', 'OCR Measurement Report')
        part_number = data.get('part_number', 'Part 1')
        
        logger.info(f"Excel Export: Processing {len(zones)} zones for {part_number}")
        
        # Create workbook with two sheets
        wb = Workbook()
        
        # English sheet
        ws_en = wb.active
        ws_en.title = "Measurements_EN"
        
        # French sheet
        ws_fr = wb.create_sheet("Measurements_FR")
        
        # Process both sheets
        for ws, lang in [(ws_en, "en"), (ws_fr, "fr")]:
            create_measurement_sheet(ws, part_number, lang, zones)
        
        # Save to bytes
        from io import BytesIO
        excel_buffer = BytesIO()
        wb.save(excel_buffer)
        excel_bytes = excel_buffer.getvalue()
        
        logger.info(f"Excel Export: Generated dual-language template with {len(excel_bytes)} bytes")
        
        # Return Excel as response
        return Response(
            content=excel_bytes,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            headers={
                "Content-Disposition": f"attachment; filename={part_number}_measurement_template_bilingual.xlsx"
            }
        )
        
    except Exception as e:
        logger.error(f"Excel export error: {e}")
        raise HTTPException(status_code=500, detail=f"Excel generation failed: {str(e)}")

@app.post("/training/save-zone")
async def save_training_zone(request: Request):
    """
    Save validated zone as training data for custom YOLOv11 model
    Collects: thumbnail, text, bbox, category, rotation
    ALSO saves full image with bbox for proper detection training
    """
    try:
        data = await request.json()
        
        # Extract zone data
        zone_id = data.get('zone_id')
        image_data = data.get('image')  # Base64 cropped image
        full_image_data = data.get('full_image')  # Base64 full image (NEW!)
        text = data.get('text', '')  # Allow empty text
        bbox = data.get('bbox')
        category = data.get('category', 'measure')  # Default to measure
        rotation = data.get('rotation', 0)
        confidence = data.get('confidence', 0)
        tolerance_info = data.get('tolerance_info')  # Include tolerance data
        
        # Validate required fields with better error messages
        missing_fields = []
        if not zone_id:
            missing_fields.append('zone_id')
        if not image_data:
            missing_fields.append('image')
        if not bbox or not isinstance(bbox, dict):
            missing_fields.append('bbox')
        
        if missing_fields:
            logger.error(f"Missing required fields for zone {zone_id}: {missing_fields}")
            raise HTTPException(status_code=400, detail=f"Missing required fields: {', '.join(missing_fields)}")
        
        # Skip zones with no text (likely false detections)
        if not text or text.strip() == '' or text == '[No Text]':
            logger.warning(f"Skipping zone {zone_id} - no valid text detected")
            return {"status": "skipped", "reason": "no_text", "zone_id": zone_id}
        
        # Create training data directory structure
        training_dir = os.path.join(base_dir, 'training_data')
        images_dir = os.path.join(training_dir, 'images', category)
        labels_dir = os.path.join(training_dir, 'labels', category)
        metadata_dir = os.path.join(training_dir, 'metadata')
        
        # NEW: Full images for detection training
        full_images_dir = os.path.join(training_dir, 'full_images')
        full_labels_dir = os.path.join(training_dir, 'full_labels')
        
        os.makedirs(images_dir, exist_ok=True)
        os.makedirs(labels_dir, exist_ok=True)
        os.makedirs(metadata_dir, exist_ok=True)
        os.makedirs(full_images_dir, exist_ok=True)
        os.makedirs(full_labels_dir, exist_ok=True)
        
        # Generate unique filename
        timestamp = int(time.time() * 1000)
        filename = f"{category}_{zone_id}_{timestamp}"
        
        # Save cropped image (for classification)
        import base64
        if image_data.startswith('data:image'):
            image_data = image_data.split(',')[1]
        
        image_bytes = base64.b64decode(image_data)
        image_path = os.path.join(images_dir, f"{filename}.jpg")
        
        with open(image_path, 'wb') as f:
            f.write(image_bytes)
        
        # Category mapping for YOLO
        category_mapping = {
            'measure': 0,
            'diameter': 1,
            'radius': 2,
            'tolerance': 3,
            'thread': 4,
            'material': 5,
            'gdt': 6,
            'note': 7,
            'surface_roughness': 8,
            'title_block': 9
        }
        
        class_id = category_mapping.get(category.lower(), 0)  # Default to measure
        
        # Save full image with YOLO label (NEW for detection training)
        if full_image_data:
            try:
                # Decode and save full image
                if full_image_data.startswith('data:image'):
                    full_image_data = full_image_data.split(',')[1]
                
                full_image_bytes = base64.b64decode(full_image_data)
                full_image_path = os.path.join(full_images_dir, f"{filename}.jpg")
                
                with open(full_image_path, 'wb') as f:
                    f.write(full_image_bytes)
                
                # Get image dimensions to normalize bbox
                from PIL import Image
                import io
                img = Image.open(io.BytesIO(full_image_bytes))
                img_width, img_height = img.size
                
                # Calculate normalized YOLO format bbox
                x1, y1 = bbox['x1'], bbox['y1']
                x2, y2 = bbox['x2'], bbox['y2']
                
                center_x = (x1 + x2) / 2 / img_width
                center_y = (y1 + y2) / 2 / img_height
                width = (x2 - x1) / img_width
                height = (y2 - y1) / img_height
                
                # Clamp to [0, 1]
                center_x = max(0, min(1, center_x))
                center_y = max(0, min(1, center_y))
                width = max(0, min(1, width))
                height = max(0, min(1, height))
                
                # Save YOLO format label
                label_path = os.path.join(full_labels_dir, f"{filename}.txt")
                with open(label_path, 'w') as f:
                    f.write(f"{class_id} {center_x:.6f} {center_y:.6f} {width:.6f} {height:.6f}\n")
                
                logger.info(f"💾 Saved full image + YOLO label for detection training")
                
            except Exception as e:
                logger.warning(f"Could not save full image for detection training: {e}")
        
        # Save metadata JSON (for reference and Donut training)
        metadata = {
            'zone_id': zone_id,
            'text': text,
            'bbox': bbox,
            'category': category,
            'rotation': rotation,
            'confidence': confidence,
            'ocr_confidence': confidence,
            'timestamp': timestamp,
            'image_path': image_path,
            'tolerance_info': tolerance_info,  # Include tolerance data for training
            'user_edited': False  # Flag to prevent auto-correction of user-edited values
        }
        
        metadata_path = os.path.join(metadata_dir, f"{filename}.json")
        import json
        with open(metadata_path, 'w', encoding='utf-8') as f:
            json.dump(metadata, f, indent=2, ensure_ascii=False)
        
        logger.info(f"💾 Saved training data: {filename} (category: {category})")
        
        return {
            "success": True,
            "message": f"Training data saved: {category}/{filename}",
            "image_path": image_path,
            "metadata_path": metadata_path
        }
        
    except Exception as e:
        logger.error(f"Error saving training data: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/corrections/submit")
async def submit_corrections(request: Request):
    """Submit corrections for training data"""
    try:
        data = await request.json()
        
        # Send to Telegram channel
        success = send_correction_to_telegram(data)
        
        return {
            "status": "success" if success else "error",
            "message": "Corrections submitted successfully" if success else "Failed to submit corrections",
            "total_zones": len(data.get('corrected_zones', []))
        }
        
    except Exception as e:
        logger.error(f"Error submitting corrections: {e}")
        return {"status": "error", "message": str(e)}


# ============================================================
# TRAINING DATA MANAGEMENT ENDPOINTS
# ============================================================

@app.get("/training-data/list")
async def list_training_data(
    category: str = Query(None, description="Filter by category")
):
    """List all training data samples with metadata - no pagination, frontend handles it"""
    try:
        metadata_dir = os.path.join(base_dir, 'training_data', 'metadata')
        
        if not os.path.exists(metadata_dir):
            return {"samples": [], "total": 0}
        
        # Get all JSON files
        json_files = [f for f in os.listdir(metadata_dir) if f.endswith('.json')]
        
        samples = []
        for json_file in json_files:
            try:
                json_path = os.path.join(metadata_dir, json_file)
                with open(json_path, 'r', encoding='utf-8') as f:
                    metadata = json.load(f)
                
                # Filter by category if specified
                if category and metadata.get('category') != category:
                    continue
                
                # Add file reference
                metadata['metadata_file'] = json_file
                metadata['id'] = os.path.splitext(json_file)[0]
                
                samples.append(metadata)
            except Exception as e:
                logger.error(f"Error reading {json_file}: {e}")
                continue
        
        # Sort by timestamp (newest first)
        samples.sort(key=lambda x: x.get('timestamp', 0), reverse=True)
        
        return {
            "samples": samples,
            "total": len(samples)
        }
        
    except Exception as e:
        logger.error(f"Error listing training data: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/training-data/{sample_id}")
async def get_training_sample(sample_id: str):
    """Get a single training sample with full details"""
    try:
        metadata_dir = os.path.join(base_dir, 'training_data', 'metadata')
        json_path = os.path.join(metadata_dir, f"{sample_id}.json")
        
        if not os.path.exists(json_path):
            raise HTTPException(status_code=404, detail="Sample not found")
        
        with open(json_path, 'r', encoding='utf-8') as f:
            metadata = json.load(f)
        
        metadata['id'] = sample_id
        metadata['metadata_file'] = f"{sample_id}.json"
        
        # Get image data
        category = metadata.get('category', 'measure')
        images_dir = os.path.join(base_dir, 'training_data', 'images', category)
        
        # Find the image file
        image_filename = None
        for ext in ['.jpg', '.png', '.jpeg']:
            possible_path = os.path.join(images_dir, f"{sample_id}{ext}")
            if os.path.exists(possible_path):
                image_filename = f"{sample_id}{ext}"
                # Read and encode image
                import base64
                with open(possible_path, 'rb') as img_file:
                    img_data = base64.b64encode(img_file.read()).decode('utf-8')
                    metadata['cropped_image_data'] = f"data:image/jpeg;base64,{img_data}"
                break
        
        return metadata
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error getting training sample: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.put("/training-data/{sample_id}")
async def update_training_sample(sample_id: str, request: Request):
    """Update a training sample (category, text, bbox, etc.)"""
    try:
        data = await request.json()
        
        metadata_dir = os.path.join(base_dir, 'training_data', 'metadata')
        json_path = os.path.join(metadata_dir, f"{sample_id}.json")
        
        if not os.path.exists(json_path):
            raise HTTPException(status_code=404, detail="Sample not found")
        
        # Load existing metadata
        with open(json_path, 'r', encoding='utf-8') as f:
            metadata = json.load(f)
        
        old_category = metadata.get('category', 'measure')
        new_category = data.get('category', old_category)
        
        # Update metadata fields
        for key in ['text', 'category', 'bbox', 'confidence', 'rotation', 'tolerance_info']:
            if key in data:
                metadata[key] = data[key]
        
        # Mark as user-edited if text or category was changed
        if 'text' in data or 'category' in data:
            metadata['user_edited'] = True
        
        # Save updated metadata
        with open(json_path, 'w', encoding='utf-8') as f:
            json.dump(metadata, f, indent=2, ensure_ascii=False)
        
        # If category changed, move the image file
        if old_category != new_category:
            old_images_dir = os.path.join(base_dir, 'training_data', 'images', old_category)
            new_images_dir = os.path.join(base_dir, 'training_data', 'images', new_category)
            os.makedirs(new_images_dir, exist_ok=True)
            
            # Find and move the image
            for ext in ['.jpg', '.png', '.jpeg']:
                old_path = os.path.join(old_images_dir, f"{sample_id}{ext}")
                if os.path.exists(old_path):
                    new_path = os.path.join(new_images_dir, f"{sample_id}{ext}")
                    shutil.move(old_path, new_path)
                    logger.info(f"Moved image from {old_category} to {new_category}")
                    break
        
        return {
            "success": True,
            "message": "Sample updated successfully",
            "sample_id": sample_id
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error updating training sample: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.delete("/training-data/{sample_id}")
async def delete_training_sample(sample_id: str):
    """Delete a training sample (metadata + images)"""
    try:
        metadata_dir = os.path.join(base_dir, 'training_data', 'metadata')
        json_path = os.path.join(metadata_dir, f"{sample_id}.json")
        
        if not os.path.exists(json_path):
            raise HTTPException(status_code=404, detail="Sample not found")
        
        # Load metadata to get category
        with open(json_path, 'r', encoding='utf-8') as f:
            metadata = json.load(f)
        
        category = metadata.get('category', 'measure')
        
        # Delete metadata file
        os.remove(json_path)
        
        # Delete cropped image
        images_dir = os.path.join(base_dir, 'training_data', 'images', category)
        for ext in ['.jpg', '.png', '.jpeg']:
            img_path = os.path.join(images_dir, f"{sample_id}{ext}")
            if os.path.exists(img_path):
                os.remove(img_path)
                break
        
        # Delete full image and label if they exist
        full_images_dir = os.path.join(base_dir, 'training_data', 'full_images')
        full_labels_dir = os.path.join(base_dir, 'training_data', 'full_labels')
        
        for ext in ['.jpg', '.png', '.jpeg']:
            full_img_path = os.path.join(full_images_dir, f"{sample_id}{ext}")
            if os.path.exists(full_img_path):
                os.remove(full_img_path)
                break
        
        label_path = os.path.join(full_labels_dir, f"{sample_id}.txt")
        if os.path.exists(label_path):
            os.remove(label_path)
        
        logger.info(f"Deleted training sample: {sample_id}")
        
        return {
            "success": True,
            "message": "Sample deleted successfully",
            "sample_id": sample_id
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error deleting training sample: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/training-data/stats")
async def get_training_stats():
    """Get statistics about training data"""
    try:
        metadata_dir = os.path.join(base_dir, 'training_data', 'metadata')
        
        if not os.path.exists(metadata_dir):
            return {"total": 0, "by_category": {}}
        
        json_files = [f for f in os.listdir(metadata_dir) if f.endswith('.json')]
        
        stats = {
            "total": 0,
            "by_category": {},
            "avg_confidence": 0,
            "with_tolerance": 0
        }
        
        total_confidence = 0
        
        for json_file in json_files:
            try:
                json_path = os.path.join(metadata_dir, json_file)
                with open(json_path, 'r', encoding='utf-8') as f:
                    metadata = json.load(f)
                
                stats["total"] += 1
                
                category = metadata.get('category', 'unknown')
                stats["by_category"][category] = stats["by_category"].get(category, 0) + 1
                
                confidence = metadata.get('confidence', 0)
                total_confidence += confidence
                
                if metadata.get('tolerance_info'):
                    stats["with_tolerance"] += 1
                    
            except Exception as e:
                logger.error(f"Error reading {json_file}: {e}")
                continue
        
        if stats["total"] > 0:
            stats["avg_confidence"] = total_confidence / stats["total"]
        
        return stats
        
    except Exception as e:
        logger.error(f"Error getting training stats: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/training-data/{sample_id}/validate")
async def validate_training_sample(sample_id: str):
    """Re-run OCR on a training sample to validate/correct the text - uses SAME method as main UI"""
    try:
        if ocr is None:
            raise HTTPException(status_code=503, detail="OCR service not initialized")
        
        metadata_dir = os.path.join(base_dir, 'training_data', 'metadata')
        json_path = os.path.join(metadata_dir, f"{sample_id}.json")
        
        if not os.path.exists(json_path):
            raise HTTPException(status_code=404, detail="Sample not found")
        
        # Load metadata
        with open(json_path, 'r', encoding='utf-8') as f:
            metadata = json.load(f)
        
        category = metadata.get('category', 'measure')
        bbox = metadata.get('bbox')
        user_edited = metadata.get('user_edited', False)
        
        if not bbox:
            raise HTTPException(status_code=400, detail="No bbox information in metadata")
        
        # Skip auto-correction for user-edited samples
        if user_edited:
            return {
                "success": True,
                "original_text": metadata.get('text', ''),
                "new_text": metadata.get('text', ''),
                "original_confidence": metadata.get('confidence', 0),
                "new_confidence": metadata.get('confidence', 0),
                "original_category": category,
                "suggested_category": category,
                "tolerance_info": metadata.get('tolerance_info', {}),
                "text_changed": False,
                "category_changed": False,
                "user_edited": True,
                "message": "Sample marked as user-edited, skipping auto-correction"
            }
        
        # Find the cropped image file
        images_dir = os.path.join(base_dir, 'training_data', 'images', category)
        image_path = None
        for ext in ['.jpg', '.png', '.jpeg']:
            possible_path = os.path.join(images_dir, f"{sample_id}{ext}")
            if os.path.exists(possible_path):
                image_path = possible_path
                break
        
        if not image_path:
            raise HTTPException(status_code=404, detail="Image file not found")
        
        # Load the cropped image
        import cv2
        img = cv2.imread(image_path)
        if img is None:
            raise HTTPException(status_code=500, detail="Failed to load image")
        
        # Log image info for debugging
        logger.info(f"Validation: Processing image {image_path}, size: {img.shape}")
        
        # Use the EXACT SAME method as main UI: process_image()
        try:
            # Process using the exact same function as main UI
            result = process_image(image_path, mode="accurate", rotation=0)
            logger.info(f"Validation: Processing {sample_id} with process_image(), found {len(result.get('zones', []))} zones")
            
            # Extract text from zones (same as UI)
            new_text = ""
            new_confidence = 0
            tolerance_info = {}
            
            zones = result.get('zones', [])
            if zones and len(zones) > 0:
                # Combine text from all zones
                for zone in zones:
                    if zone and zone.get('text'):
                        zone_text = zone.get('text', '')
                        zone_conf = zone.get('confidence', 0)
                        
                        new_text += zone_text + " "
                        new_confidence = max(new_confidence, zone_conf)
                
                # Get tolerance info from first zone if available
                if zones[0]:
                    tolerance_info = zones[0].get('tolerance_info', {})
            
            new_text = new_text.strip()
            
            # Detect category based on text (same as UI)
            detected_category = detect_zone_category(new_text)
        
        except Exception as e:
            logger.error(f"Error running OCR validation: {e}")
            # Set defaults if OCR fails
            new_text = ""
            new_confidence = 0
            tolerance_info = {}
            detected_category = "note"
        
        return {
            "success": True,
            "original_text": metadata.get('text', ''),
            "new_text": new_text,
            "original_confidence": metadata.get('confidence', 0),
            "new_confidence": new_confidence,
            "original_category": category,
            "suggested_category": detected_category,
            "tolerance_info": tolerance_info,
            "text_changed": new_text != metadata.get('text', ''),
            "category_changed": detected_category != category
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error validating training sample: {e}")
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    import uvicorn
    # Get port from environment variable (for Hugging Face Spaces) or default to 8000
    port = int(os.getenv("PORT", 8000))
    uvicorn.run(app, host="0.0.0.0", port=port)