# -*- coding: utf-8 -*-
"""OCR (Optical Character Recognition).ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1vi7og9nPVTiRNFFAnmOTrR0XPVqqgej6
"""

pip install pdf2image

!apt-get install poppler-utils #First, we'll install deps for pdf2image.

from pdf2image import convert_from_path, convert_from_bytes
from IPython.display import display, Image

images = convert_from_bytes(open('/content/wordpress-pdf-invoice-plugin-sample(1).pdf', 'rb').read(), size=800)
display(images[0])

# import module
from pdf2image import convert_from_path
 
 
# Store Pdf with convert_from_path function
images = convert_from_path('/content/wordpress-pdf-invoice-plugin-sample(1).pdf')
 
for i in range(len(images)):
   
      # Save pages as images in the pdf
    images[i].save('page'+ str(i) +'.jpg', 'JPEG')

!pip install pytesseract

!sudo apt install tesseract-ocr

try:
 from PIL import Image
except ImportError:
 import Image
import cv2
import pytesseract

!which tesseract

pytesseract.pytesseract.tesseract_cmd = (
    r'/usr/bin/tesseract'
)

img_cv = cv2.imread(r'/content/page0.jpg')# By default OpenCV stores images in BGR format and since pytesseract assumes RGB format,
# we need to convert from BGR to RGB format/mode:
#d = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB)

#by using print we avoid a single string containing various /n
print(pytesseract.image_to_string(img_cv, lang='eng', config='-psm 1'))

# from pdf2image import convert_from_path
# images = convert_from_path("/content/wordpress-pdf-invoice-plugin-sample(1).pdf", 500,poppler_path=r'C:\Program Files\poppler-0.68.0\bin')
# for i, image in enumerate(images):
#     fname = 'image'+str(i)+'.png'
#     image.save(fname, "PNG")