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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#installations
|
2 |
+
!pip install gradio
|
3 |
+
!pip install transformers
|
4 |
+
!pip install torch
|
5 |
+
|
6 |
+
!pip install PyPDF2
|
7 |
+
!pip install pdfminer.six
|
8 |
+
!pip install pdfplumber
|
9 |
+
!pip install pdf2image
|
10 |
+
!pip install Pillow
|
11 |
+
!pip install pytesseract
|
12 |
+
|
13 |
+
!apt-get install poppler-utils
|
14 |
+
!apt install tesseract-ocr
|
15 |
+
!apt install libtesseract-dev
|
16 |
+
|
17 |
+
|
18 |
+
#imports
|
19 |
+
from transformers import pipeline
|
20 |
+
import gradio as gr
|
21 |
+
import torch
|
22 |
+
import PyPDF2
|
23 |
+
import pdfplumber
|
24 |
+
|
25 |
+
|
26 |
+
|
27 |
+
|
28 |
+
#Reading the PDFs and extracting the abstract from my previous code:
|
29 |
+
|
30 |
+
from pdfminer.high_level import extract_pages, extract_text
|
31 |
+
from pdfminer.layout import LTTextContainer, LTChar, LTRect, LTFigure
|
32 |
+
|
33 |
+
from PIL import Image
|
34 |
+
from pdf2image import convert_from_path
|
35 |
+
|
36 |
+
def text_extraction(element):
|
37 |
+
# Extracting the text from the in-line text element
|
38 |
+
line_text = element.get_text()
|
39 |
+
|
40 |
+
# Find the formats of the text
|
41 |
+
# Initialize the list with all the formats that appeared in the line of text
|
42 |
+
line_formats = []
|
43 |
+
for text_line in element:
|
44 |
+
if isinstance(text_line, LTTextContainer):
|
45 |
+
# Iterating through each character in the line of text
|
46 |
+
for character in text_line:
|
47 |
+
if isinstance(character, LTChar):
|
48 |
+
# Append the font name of the character
|
49 |
+
line_formats.append(character.fontname)
|
50 |
+
# Append the font size of the character
|
51 |
+
line_formats.append(character.size)
|
52 |
+
# Find the unique font sizes and names in the line
|
53 |
+
format_per_line = list(set(line_formats))
|
54 |
+
|
55 |
+
# Return a tuple with the text in each line along with its format
|
56 |
+
return (line_text, format_per_line)
|
57 |
+
|
58 |
+
# Create a function to crop the image elements from PDFs
|
59 |
+
def crop_image(element, pageObj):
|
60 |
+
# Get the coordinates to crop the image from the PDF
|
61 |
+
[image_left, image_top, image_right, image_bottom] = [element.x0,element.y0,element.x1,element.y1]
|
62 |
+
# Crop the page using coordinates (left, bottom, right, top)
|
63 |
+
pageObj.mediabox.lower_left = (image_left, image_bottom)
|
64 |
+
pageObj.mediabox.upper_right = (image_right, image_top)
|
65 |
+
# Save the cropped page to a new PDF
|
66 |
+
cropped_pdf_writer = PyPDF2.PdfWriter()
|
67 |
+
cropped_pdf_writer.add_page(pageObj)
|
68 |
+
# Save the cropped PDF to a new file
|
69 |
+
with open('cropped_image.pdf', 'wb') as cropped_pdf_file:
|
70 |
+
cropped_pdf_writer.write(cropped_pdf_file)
|
71 |
+
|
72 |
+
# Create a function to convert the PDF to images
|
73 |
+
def convert_to_images(input_file,):
|
74 |
+
images = convert_from_path(input_file)
|
75 |
+
image = images[0]
|
76 |
+
output_file = "PDF_image.png"
|
77 |
+
image.save(output_file, "PNG")
|
78 |
+
|
79 |
+
# Create a function to read text from images
|
80 |
+
def image_to_text(image_path):
|
81 |
+
# Read the image
|
82 |
+
img = Image.open(image_path)
|
83 |
+
# Extract the text from the image
|
84 |
+
text = pytesseract.image_to_string(img)
|
85 |
+
return text
|
86 |
+
|
87 |
+
# Extracting tables from the page
|
88 |
+
|
89 |
+
def extract_table(pdf_path, page_num, table_num):
|
90 |
+
# Open the pdf file
|
91 |
+
pdf = pdfplumber.open(pdf_path)
|
92 |
+
# Find the examined page
|
93 |
+
table_page = pdf.pages[page_num]
|
94 |
+
# Extract the appropriate table
|
95 |
+
table = table_page.extract_tables()[table_num]
|
96 |
+
return table
|
97 |
+
|
98 |
+
# Convert table into the appropriate format
|
99 |
+
def table_converter(table):
|
100 |
+
table_string = ''
|
101 |
+
# Iterate through each row of the table
|
102 |
+
for row_num in range(len(table)):
|
103 |
+
row = table[row_num]
|
104 |
+
# Remove the line breaker from the wrapped texts
|
105 |
+
cleaned_row = [item.replace('\n', ' ') if item is not None and '\n' in item else 'None' if item is None else item for item in row]
|
106 |
+
# Convert the table into a string
|
107 |
+
table_string+=('|'+'|'.join(cleaned_row)+'|'+'\n')
|
108 |
+
# Removing the last line break
|
109 |
+
table_string = table_string[:-1]
|
110 |
+
return table_string
|
111 |
+
|
112 |
+
def read_pdf(pdf_path):
|
113 |
+
# create a PDF file object
|
114 |
+
pdfFileObj = open('/content/Article_11', 'rb')
|
115 |
+
# create a PDF reader object
|
116 |
+
pdfReaded = PyPDF2.PdfReader(pdfFileObj)
|
117 |
+
|
118 |
+
# Create the dictionary to extract text from each image
|
119 |
+
text_per_page = {}
|
120 |
+
# We extract the pages from the PDF
|
121 |
+
for pagenum, page in enumerate(extract_pages(pdf_path)):
|
122 |
+
print("Elaborating Page_" +str(pagenum))
|
123 |
+
# Initialize the variables needed for the text extraction from the page
|
124 |
+
pageObj = pdfReaded.pages[pagenum]
|
125 |
+
page_text = []
|
126 |
+
line_format = []
|
127 |
+
text_from_images = []
|
128 |
+
text_from_tables = []
|
129 |
+
page_content = []
|
130 |
+
# Initialize the number of the examined tables
|
131 |
+
table_num = 0
|
132 |
+
first_element= True
|
133 |
+
table_extraction_flag= False
|
134 |
+
# Open the pdf file
|
135 |
+
pdf = pdfplumber.open(pdf_path)
|
136 |
+
# Find the examined page
|
137 |
+
page_tables = pdf.pages[pagenum]
|
138 |
+
# Find the number of tables on the page
|
139 |
+
tables = page_tables.find_tables()
|
140 |
+
|
141 |
+
|
142 |
+
# Find all the elements
|
143 |
+
page_elements = [(element.y1, element) for element in page._objs]
|
144 |
+
# Sort all the elements as they appear in the page
|
145 |
+
page_elements.sort(key=lambda a: a[0], reverse=True)
|
146 |
+
|
147 |
+
# Find the elements that composed a page
|
148 |
+
for i,component in enumerate(page_elements):
|
149 |
+
# Extract the position of the top side of the element in the PDF
|
150 |
+
pos= component[0]
|
151 |
+
# Extract the element of the page layout
|
152 |
+
element = component[1]
|
153 |
+
|
154 |
+
# Check if the element is a text element
|
155 |
+
if isinstance(element, LTTextContainer):
|
156 |
+
# Check if the text appeared in a table
|
157 |
+
if table_extraction_flag == False:
|
158 |
+
# Use the function to extract the text and format for each text element
|
159 |
+
(line_text, format_per_line) = text_extraction(element)
|
160 |
+
# Append the text of each line to the page text
|
161 |
+
page_text.append(line_text)
|
162 |
+
# Append the format for each line containing text
|
163 |
+
line_format.append(format_per_line)
|
164 |
+
page_content.append(line_text)
|
165 |
+
else:
|
166 |
+
# Omit the text that appeared in a table
|
167 |
+
pass
|
168 |
+
|
169 |
+
# Check the elements for images
|
170 |
+
if isinstance(element, LTFigure):
|
171 |
+
# Crop the image from the PDF
|
172 |
+
crop_image(element, pageObj)
|
173 |
+
# Convert the cropped pdf to an image
|
174 |
+
convert_to_images('cropped_image.pdf')
|
175 |
+
# Extract the text from the image
|
176 |
+
image_text = image_to_text('PDF_image.png')
|
177 |
+
text_from_images.append(image_text)
|
178 |
+
page_content.append(image_text)
|
179 |
+
# Add a placeholder in the text and format lists
|
180 |
+
page_text.append('image')
|
181 |
+
line_format.append('image')
|
182 |
+
|
183 |
+
# Check the elements for tables
|
184 |
+
if isinstance(element, LTRect):
|
185 |
+
# If the first rectangular element
|
186 |
+
if first_element == True and (table_num+1) <= len(tables):
|
187 |
+
# Find the bounding box of the table
|
188 |
+
lower_side = page.bbox[3] - tables[table_num].bbox[3]
|
189 |
+
upper_side = element.y1
|
190 |
+
# Extract the information from the table
|
191 |
+
table = extract_table(pdf_path, pagenum, table_num)
|
192 |
+
# Convert the table information in structured string format
|
193 |
+
table_string = table_converter(table)
|
194 |
+
# Append the table string into a list
|
195 |
+
text_from_tables.append(table_string)
|
196 |
+
page_content.append(table_string)
|
197 |
+
# Set the flag as True to avoid the content again
|
198 |
+
table_extraction_flag = True
|
199 |
+
# Make it another element
|
200 |
+
first_element = False
|
201 |
+
# Add a placeholder in the text and format lists
|
202 |
+
page_text.append('table')
|
203 |
+
line_format.append('table')
|
204 |
+
|
205 |
+
# Check if we already extracted the tables from the page
|
206 |
+
if element.y0 >= lower_side and element.y1 <= upper_side:
|
207 |
+
pass
|
208 |
+
elif not isinstance(page_elements[i+1][1], LTRect):
|
209 |
+
table_extraction_flag = False
|
210 |
+
first_element = True
|
211 |
+
table_num+=1
|
212 |
+
|
213 |
+
|
214 |
+
# Create the key of the dictionary
|
215 |
+
dctkey = 'Page_'+str(pagenum)
|
216 |
+
# Add the list of list as the value of the page key
|
217 |
+
text_per_page[dctkey]= [page_text, line_format, text_from_images,text_from_tables, page_content]
|
218 |
+
|
219 |
+
# Closing the pdf file object
|
220 |
+
pdfFileObj.close()
|
221 |
+
|
222 |
+
return text_per_page
|
223 |
+
|
224 |
+
pdf_path = '/content/Article_11' #paper.pdf
|
225 |
+
|
226 |
+
text_per_page = read_pdf(pdf_path)
|
227 |
+
|
228 |
+
text_per_page.keys()
|
229 |
+
page_0 = text_per_page['Page_0']
|
230 |
+
page_0
|
231 |
+
|
232 |
+
page_0_clean = [item for sublist in page_0 for item in sublist if isinstance(item, str)]
|
233 |
+
for i in range(len(page_0_clean)):
|
234 |
+
page_0_clean[i] = page_0_clean[i].replace('\n', ' ').strip()
|
235 |
+
|
236 |
+
|
237 |
+
page_0_clean
|
238 |
+
|
239 |
+
|
240 |
+
def process_pdf(pdf):
|
241 |
+
|
242 |
+
|
243 |
+
def speech(audio):
|
244 |
+
sr, y = audio
|
245 |
+
y = y.astype(np.float32)
|
246 |
+
y /= np.max(np.abs(y))
|
247 |
+
|
248 |
+
return transcriber({"sampling_rate": sr, "raw": y})["text"]
|
249 |
+
|
250 |
+
|
251 |
+
demo = gr.Interface(
|
252 |
+
transcribe,
|
253 |
+
gr.Audio(sources=["microphone"]),
|
254 |
+
"text",
|
255 |
+
)
|
256 |
+
|
257 |
+
demo.launch()
|