import os
#adding os library

#selecting torch environment for ml
os.environ['USE_TORCH'] = '1'

#importing matplotlib to show results
import matplotlib.pyplot as plt

#the model used to detect the text
from doctr.io import DocumentFile
from doctr.models import ocr_predictor


#setting document to be analyzed for text
doc = DocumentFile.from_images("test_image_travis.png")
print(f"Number of pages: {len(doc)}")

# Instantiate a pretrained model
predictor = ocr_predictor(pretrained=True)

# Display the architecture
print(predictor)
result = predictor(doc)

exported_result = result.export()
print(exported_result)

#keeping text in order from left top corner to bottom right corner
extracted_text = ""
for page in exported_result.get('pages', []):
    for block in page.get('blocks', []):
        for line in block.get('lines', []):
            for word in line.get('words', []):
                extracted_text += word['value'] + " "
            extracted_text += "\n"

#writing text file and send to make audio transcript
with open('output.txt', 'w') as f:
    f.write(extracted_text)
#end

result.show()


#recreating document with text in same position
synthetic_pages = result.synthesize()
plt.imshow(synthetic_pages[0]); plt.axis('off'); plt.show()