Skip to content
Shrijayan
Go back

OCR + NLP: From Images and PDFs to Questions

OCR + NLP: From Images and PDFs to Questions

Download original notebook: [OCR NLP](/notebooks/OCR NLP)

###BASE

!pip install -U transformers==3.0.0
#NLP
!python -m nltk.downloader punkt
!git clone https://github.com/patil-suraj/question_generation.git
%cd question_generation

#OCR
import cv2
import numpy as np
import requests
import io
#import pdfplumber
import json
#import pdfplumber
#import PyPDF2
from pipelines import pipeline
nlp = pipeline("question-generation")
nlp = pipeline("question-generation", model="valhalla/t5-base-qg-hl")

nlp2 = pipeline("multitask-qa-qg")
nlp2 = pipeline("multitask-qa-qg", model="valhalla/t5-base-qa-qg-hl")

nlp3 = pipeline("e2e-qg")
nlp3 = pipeline("e2e-qg", model="valhalla/t5-base-e2e-qg")

###OCR

img = cv2.imread("/content/image-3899-434.png")
height, width, _ = img.shape

roi = img

url_api = "https://api.ocr.space/parse/image"
_, compressedimage = cv2.imencode(".png", roi, [1, 90])
file_bytes = io.BytesIO(compressedimage)

result = requests.post(url_api,
              files = {"screenshot.png": file_bytes},
              data = {"apikey": "helloworld",
                      "language": "eng"})
result = result.content.decode()
result = json.loads(result)
parsed_results = result.get("ParsedResults")[0]
text1 = parsed_results.get("ParsedText")
print(text1)

###NLP

Single task QA

b=nlp(text1)
b
a=nlp(text1)
for i in range(len(a)):
  print("Question:",a[i]['question'])
  print("Answer:",a[i]['answer'])

End-to-End QG

nlp3(text1)

Multitask QA-QG

QG

nlp2(text1)

QA

nlp2({
  "question": "What does a magician create ?",
  "context": text1
})

PDF EXTRACT

!pip install pdfplumber
!pip install PyPDF2
!pip install pdfplumber -q
import pdfplumber
import json
import pdfplumber
import PyPDF2
file = open('/content/SKMBT_C22416062911140.pdf', 'rb')
readpdf = PyPDF2.PdfFileReader(file)
total= readpdf.numPages
with pdfplumber.open(file) as pdf:
    for i in range(0,total):
      page = pdf.pages[i]
      text = page.extract_text()
      print(text)

Untitled7

Merged from Untitled7.ipynb (2022-03-03)

!sudo apt install tesseract-ocr

!pip install pytesseract
!pip install pillow==4.1.1
import pytesseract

import shutil

import os

import random

try:

  from PIL import Image

except ImportError:

  import Image

from google.colab import files

uploaded = files.upload()
image_path_in_colab='ggg (1).png'

extractedInformation = pytesseract.image_to_string(Image.open(image_path_in_colab))

print(extractedInformation)

Share this post on:

Next Post
Vector Databases: A Survey of the Landscape