ChinmayBH commited on
Commit
bd889e8
1 Parent(s): 364c770

created app.py

Browse files
Files changed (1) hide show
  1. app.py +298 -0
app.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import fitz
4
+ import streamlit as st
5
+ from PIL import Image
6
+ import io
7
+ import pandas as pd
8
+ import pickle
9
+ import zipfile
10
+ import tempfile
11
+
12
+ def extract_text_images(
13
+ pdf_path: str, output_folder: str,
14
+ minimum_font_size: int,
15
+ mode: str = 'headerwise',
16
+ header_font_sizes: list[float] = None,
17
+ tolerance: float = 0.01,
18
+ extraction_type: str = 'both',
19
+ headers_are_capital: bool = False
20
+ ) -> str:
21
+ if not os.path.exists(output_folder):
22
+ os.makedirs(output_folder)
23
+
24
+ extraction_data = []
25
+ current_header = None
26
+ current_header_content = []
27
+
28
+ def add_current_header_content() -> None:
29
+ nonlocal current_header, current_header_content
30
+ if current_header:
31
+ extraction_data.append({
32
+ 'header': current_header,
33
+ 'content': current_header_content
34
+ })
35
+ current_header_content = []
36
+ current_header = None
37
+
38
+ def is_header_font_size(font_size: float) -> bool:
39
+ return any(
40
+ abs(font_size - header_font_size) <= tolerance
41
+ for header_font_size in header_font_sizes
42
+ )
43
+
44
+ def is_bold(font: str) -> bool:
45
+ return 'bold' in font.lower()
46
+
47
+ pdf_document = fitz.open(pdf_path)
48
+
49
+ for page_number in range(pdf_document.page_count):
50
+ page = pdf_document.load_page(page_number)
51
+ elements = []
52
+
53
+ if extraction_type in ('text', 'both'):
54
+ text_blocks = page.get_text("dict")["blocks"]
55
+ lines = {}
56
+
57
+ for block in text_blocks:
58
+ if block["type"] == 0: # Text block
59
+ for line in block["lines"]:
60
+ for span in line["spans"]:
61
+ font_size = span["size"]
62
+ top = span["bbox"][1]
63
+ font = span["font"]
64
+
65
+ if font_size < minimum_font_size:
66
+ continue
67
+
68
+ if top not in lines:
69
+ lines[top] = []
70
+ lines[top].append(span)
71
+
72
+ for top in sorted(lines.keys()):
73
+ line = lines[top]
74
+ line_text = " ".join([span['text'] for span in line])
75
+ line_font_size = line[0]['size']
76
+ font = line[0]['font']
77
+
78
+ if headers_are_capital:
79
+ line_text_is_header = line_text.isupper()
80
+ else:
81
+ line_text_is_header = True
82
+
83
+ elements.append({
84
+ 'type': 'text',
85
+ 'font_size': line_font_size,
86
+ 'page': page_number + 1,
87
+ 'content': line_text,
88
+ 'x0': line[0]['bbox'][0],
89
+ 'top': top,
90
+ 'font': font,
91
+ 'is_header': line_text_is_header
92
+ })
93
+
94
+ if extraction_type in ('images', 'both'):
95
+ image_list = page.get_images(full=True)
96
+
97
+ for img_index, img in enumerate(image_list):
98
+ xref = img[0]
99
+ base_image = pdf_document.extract_image(xref)
100
+ image_bytes = base_image["image"]
101
+ image_filename = os.path.join(
102
+ output_folder,
103
+ f"page_{page_number + 1}_img_{img_index + 1}.png"
104
+ )
105
+
106
+ with open(image_filename, "wb") as img_file:
107
+ img_file.write(image_bytes)
108
+
109
+ img_rect = page.get_image_bbox(img)
110
+ elements.append({
111
+ 'type': 'image',
112
+ 'page': page_number + 1,
113
+ 'path': image_filename,
114
+ 'x0': img_rect.x0,
115
+ 'top': img_rect.y0
116
+ })
117
+
118
+ elements.sort(key=lambda e: (e['top'], e['x0']))
119
+
120
+ if mode == 'headerwise':
121
+ for element in elements:
122
+ if element['type'] == 'text' and element['is_header'] and is_header_font_size(element['font_size']) and is_bold(element['font']):
123
+ add_current_header_content()
124
+ current_header = element['content']
125
+ elif element['type'] == 'text':
126
+ if current_header_content and current_header_content[-1]['type'] == 'text':
127
+ current_header_content[-1]['content'] += " " + element['content']
128
+ else:
129
+ current_header_content.append({
130
+ 'type': 'text',
131
+ 'content': element['content']
132
+ })
133
+ elif element['type'] == 'image':
134
+ current_header_content.append({
135
+ 'type': 'image',
136
+ 'path': element['path']
137
+ })
138
+
139
+ if mode == 'headerwise':
140
+ add_current_header_content()
141
+
142
+ pdf_document.close()
143
+
144
+ json_output_path = os.path.join(output_folder, 'extraction_data.json')
145
+ with open(json_output_path, 'w', encoding='utf-8') as json_file:
146
+ json.dump(extraction_data, json_file, ensure_ascii=False, indent=4)
147
+
148
+ # Save to XLSX
149
+ df = pd.json_normalize(extraction_data, sep='_')
150
+ xlsx_output_path = os.path.join(output_folder, 'extraction_data.xlsx')
151
+ df.to_excel(xlsx_output_path, index=False)
152
+
153
+ # Save to Pickle
154
+ pickle_output_path = os.path.join(output_folder, 'extraction_data.pkl')
155
+ with open(pickle_output_path, 'wb') as pickle_file:
156
+ pickle.dump(extraction_data, pickle_file)
157
+
158
+ # Create ZIP file
159
+ zip_output_path = os.path.join(output_folder, 'extraction_data.zip')
160
+ with zipfile.ZipFile(zip_output_path, 'w') as zipf:
161
+ zipf.write(json_output_path, os.path.basename(json_output_path))
162
+ zipf.write(xlsx_output_path, os.path.basename(xlsx_output_path))
163
+ zipf.write(pickle_output_path, os.path.basename(pickle_output_path))
164
+ if extraction_type in ('images', 'both'):
165
+ for root, _, files in os.walk(output_folder):
166
+ for file in files:
167
+ if file.endswith('.png'):
168
+ zipf.write(os.path.join(root, file), file)
169
+
170
+ return json_output_path, xlsx_output_path, pickle_output_path, zip_output_path
171
+
172
+ def render_pdf_page_as_image(pdf_path: str, page_number: int, zoom: float = 2.0) -> io.BytesIO:
173
+ # Render PDF page as an image
174
+ pdf_document = fitz.open(pdf_path)
175
+ page = pdf_document.load_page(page_number - 1) # Page number is zero-indexed in fitz
176
+ pix = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom))
177
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
178
+ img_bytes = io.BytesIO()
179
+ img.save(img_bytes, format="PNG")
180
+ img_bytes.seek(0)
181
+ pdf_document.close()
182
+ return img_bytes
183
+
184
+ # Streamlit UI
185
+
186
+ st.markdown("<h1 style='text-align: center; color: blue;'>PDF DATA SNATCHER: HEADERWISE</h1>", unsafe_allow_html=True)
187
+ st.markdown("<h3 style='text-align: center;color: brown;'>Extract valuable text and images from PDFs effortlessly and Convert PDFs into editable text and high-quality images </h3>", unsafe_allow_html=True)
188
+
189
+ with st.expander("Click here for more information"):
190
+ st.write("""
191
+ **This application allows you to extract text and images from PDF files Headerswise. You can choose to extract only text, only images, or both, and the extracted data can be downloaded in JSON or XLSX format. Additionally, if you choose to extract images, you can download a ZIP file containing both the images and the JSON data.**
192
+ - **What is different about this app?**
193
+ - 1. The sequence of text and images will get maintained as per its order in pdf file
194
+ - 2. You have options to extract entities from pdf
195
+ - 3. You can download data in JSON or XLSX format
196
+ - **PDF Preview:** You can preview a few pages of the uploaded PDF in the sidebar.
197
+ - **Extraction Type:** Choose whether to extract text, images, or both.
198
+ - **Minimum Font Size:** Set a threshold for the font size; text below this size will be ignored during extraction.
199
+ - **Output:** Download the extracted data as a JSON file, an Excel file, or a ZIP file (if images are included).
200
+ - *AUTHOR : CHINMAY BHALERAO*
201
+ """)
202
+
203
+ st.sidebar.markdown(
204
+ """
205
+ <div style="background-color: lightgray; padding: 2px; border-radius: 2px; text-align: center;">
206
+ <h2 style="color: blue; margin: 0;">PDF PREVIEW</h2>
207
+ </div>
208
+ """, unsafe_allow_html=True)
209
+
210
+ # Upload PDF file
211
+ uploaded_file = st.file_uploader("Upload a PDF file", type=["pdf"])
212
+
213
+ if uploaded_file is not None:
214
+ # Create a temporary directory
215
+ with tempfile.TemporaryDirectory() as temp_dir:
216
+ # Save uploaded file to a temporary path
217
+ temp_pdf_path = os.path.join(temp_dir, "temp_uploaded_file.pdf")
218
+ with open(temp_pdf_path, "wb") as f:
219
+ f.write(uploaded_file.getbuffer())
220
+
221
+ # Number of pages to preview
222
+ num_pages_to_preview = st.sidebar.slider("Number of Pages to Preview", min_value=1, max_value=5, value=1)
223
+
224
+ # Generate and display thumbnails for selected number of pages
225
+ st.sidebar.write("Preview of Uploaded PDF:")
226
+ for page_number in range(1, num_pages_to_preview + 1):
227
+ thumbnail_bytes = render_pdf_page_as_image(temp_pdf_path, page_number=page_number)
228
+ st.sidebar.image(thumbnail_bytes, caption=f"Page {page_number}", width=300)
229
+
230
+ # Extraction type
231
+ st.info("You can select **only text** or **only images** or **text and images both** to extract form pdf")
232
+
233
+ extraction_type = st.radio("Extraction Type", options=['text', 'images', 'both'])
234
+
235
+ # Headers are capital
236
+ headers_are_capital = st.checkbox("Are Headers in Capital Letters?", value=False)
237
+
238
+ # Minimum font size
239
+ st.info("Minimum font size is the size below which size, the text will get ignored for extraction")
240
+
241
+ minimum_font_size = st.slider("Minimum Font Size", min_value=8, max_value=20, value=10)
242
+
243
+ # Header font sizes
244
+ header_font_sizes_input = st.text_input(
245
+ "Header Font Sizes (comma-separated, e.g., 10, 12.5, 14.75)", value="16.0")
246
+ header_font_sizes = [float(size.strip()) for size in header_font_sizes_input.split(',') if size.strip().replace('.', '', 1).isdigit()]
247
+
248
+ if st.button("Start Extraction"):
249
+ # Run extraction
250
+ json_output_path, xlsx_output_path, pickle_output_path, zip_output_path = extract_text_images(
251
+ pdf_path=temp_pdf_path,
252
+ output_folder=temp_dir,
253
+ minimum_font_size=minimum_font_size,
254
+ mode='headerwise', # Pagewise mode has been removed
255
+ header_font_sizes=header_font_sizes,
256
+ extraction_type=extraction_type,
257
+ headers_are_capital=headers_are_capital
258
+ )
259
+
260
+ st.success("Extraction complete!")
261
+
262
+ # Display download options
263
+ with open(json_output_path, 'r', encoding='utf-8') as json_file:
264
+ extracted_data = json.load(json_file)
265
+ st.json(extracted_data) # Display JSON data in Streamlit
266
+
267
+ with open(json_output_path, "rb") as file:
268
+ st.download_button(
269
+ label="Download JSON",
270
+ data=file,
271
+ file_name="extraction_data.json",
272
+ mime="application/json"
273
+ )
274
+
275
+ with open(xlsx_output_path, "rb") as file:
276
+ st.download_button(
277
+ label="Download XLSX",
278
+ data=file,
279
+ file_name="extraction_data.xlsx",
280
+ mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
281
+ )
282
+
283
+ with open(pickle_output_path, "rb") as file:
284
+ st.download_button(
285
+ label="Download Pickle",
286
+ data=file,
287
+ file_name="extraction_data.pkl",
288
+ mime="application/octet-stream"
289
+ )
290
+
291
+ if extraction_type in ('images', 'both'):
292
+ with open(zip_output_path, "rb") as file:
293
+ st.download_button(
294
+ label="Download ZIP",
295
+ data=file,
296
+ file_name="extraction_data.zip",
297
+ mime="application/zip"
298
+ )