chaos4455 commited on
Commit
fb367af
·
verified ·
1 Parent(s): 4c0d169

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +492 -0
app.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import time
4
+ import logging
5
+ import shutil
6
+ from pathlib import Path
7
+ import fitz # PyMuPDF
8
+ from PIL import Image, ImageDraw
9
+ import pandas as pd
10
+ from rich.console import Console
11
+ from rich.panel import Panel
12
+ from rich.progress import Progress
13
+ from rich.table import Table
14
+ import concurrent.futures
15
+ import numpy as np
16
+ from skimage import filters, morphology
17
+ from scipy.ndimage import gaussian_filter
18
+ import easyocr
19
+ from transformers import BertTokenizer, BertModel
20
+ import torch
21
+ from sklearn.metrics.pairwise import cosine_similarity
22
+ import matplotlib.cm as cm
23
+ import psutil
24
+ from sklearn.cluster import AgglomerativeClustering
25
+ import zipfile
26
+ from io import BytesIO
27
+
28
+
29
+ # Configuração do Logging
30
+ logging.basicConfig(
31
+ level=logging.INFO,
32
+ format='%(asctime)s - %(levelname)s - %(message)s',
33
+ handlers=[
34
+ logging.FileHandler('pdf_processor_streamlit.log', mode='w', encoding='utf-8'), # Log em arquivo
35
+ logging.StreamHandler() # Log na saída do console
36
+ ]
37
+ )
38
+
39
+ # Variáveis de Ambiente (carregadas de .env)
40
+ EXTRACTED_FOLDER = 'extracted' # Diretório de saída
41
+ MAX_WORKERS = 4 # Número de threads/processos
42
+ IMAGE_FORMAT = 'jpeg' # Formato da imagem de saída
43
+ IMAGE_DPI = 300 # DPI da imagem
44
+ LOG_PROCESS = True
45
+ REMOVE_EXTRACTED = True
46
+ HEATMAP_ALPHA = 0.3 # Transparência do heatmap
47
+ BLUR_RADIUS = 10 # Raio do Blur
48
+ THRESHOLD = 0.1 # Limiar do Threshold
49
+ HEATMAP_COLOR_SCHEME = 'viridis' # Color Scheme do Heatmap
50
+ TEXT_HEATMAP_ALPHA = 0.5
51
+ SIMILARITY_THRESHOLD = 0.7
52
+ OCR_DETECTION_THRESHOLD = 0.1
53
+ JPEG_QUALITY = 90
54
+ MAX_IMAGE_SIZE = 1000
55
+
56
+
57
+ # Inicialização do OCR e do Modelo BERT
58
+ # Tenta usar detect_threshold, se falhar, usa threshold
59
+ try:
60
+ ocr_reader = easyocr.Reader(['en'], detect_threshold=OCR_DETECTION_THRESHOLD)
61
+ except TypeError:
62
+ try:
63
+ ocr_reader = easyocr.Reader(['en'], threshold=OCR_DETECTION_THRESHOLD)
64
+ except TypeError:
65
+ ocr_reader = easyocr.Reader(['en'])
66
+
67
+ tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
68
+ model = BertModel.from_pretrained('bert-base-uncased')
69
+
70
+ # Paletas de cores simplificadas
71
+ COLOR_SCHEMES = {
72
+ 'red': [(i, 0, 0) for i in range(256)],
73
+ 'green': [(0, i, 0) for i in range(256)],
74
+ 'blue': [(0, 0, i) for i in range(256)],
75
+ 'viridis': [
76
+ (48, 7, 75), (53, 8, 87), (59, 8, 99), (65, 7, 112),
77
+ (71, 7, 125), (77, 7, 139), (84, 9, 154), (90, 10, 170),
78
+ (97, 12, 187), (105, 16, 203), (112, 22, 220), (120, 29, 237),
79
+ (128, 38, 253), (136, 51, 255), (145, 65, 255), (154, 80, 254),
80
+ (163, 97, 252), (173, 114, 249), (183, 132, 244), (193, 150, 238),
81
+ (203, 167, 231), (213, 184, 223), (223, 199, 215), (232, 213, 206),
82
+ (240, 227, 197), (247, 240, 188), (252, 252, 178), (255, 255, 168),
83
+ (255, 252, 158), (255, 244, 147), (255, 233, 137), (255, 221, 126),
84
+ (255, 208, 115), (255, 195, 104), (255, 181, 92), (255, 167, 81),
85
+ (255, 153, 69), (255, 138, 58), (255, 123, 46), (255, 108, 35),
86
+ (255, 92, 23), (255, 77, 12), (255, 61, 0)
87
+ ],
88
+ 'magma': [
89
+ (0, 0, 0), (7, 0, 9), (13, 2, 18), (19, 5, 28),
90
+ (24, 9, 38), (29, 13, 48), (34, 18, 58), (39, 24, 68),
91
+ (43, 31, 78), (48, 39, 88), (52, 48, 98), (57, 58, 108),
92
+ (61, 69, 118), (65, 81, 127), (69, 94, 137), (73, 108, 146),
93
+ (77, 122, 154), (81, 136, 162), (85, 150, 169), (89, 164, 176),
94
+ (92, 178, 183), (96, 192, 189), (99, 205, 195), (102, 219, 201),
95
+ (105, 232, 206), (108, 245, 212), (111, 255, 217)
96
+ ],
97
+ 'inferno': [
98
+ (0, 0, 0), (3, 1, 8), (7, 1, 16), (11, 2, 24),
99
+ (15, 3, 32), (19, 4, 40), (23, 5, 48), (27, 7, 56),
100
+ (32, 8, 64), (36, 9, 72), (40, 11, 80), (44, 13, 88),
101
+ (49, 15, 96), (54, 17, 104), (59, 19, 112), (64, 22, 120),
102
+ (69, 24, 128), (75, 26, 136), (80, 29, 143), (86, 32, 151),
103
+ (92, 35, 159), (98, 38, 166), (104, 42, 174), (111, 45, 181),
104
+ (118, 49, 188), (125, 53, 195), (132, 58, 202), (140, 62, 209),
105
+ (148, 67, 215), (156, 72, 222), (164, 78, 228), (172, 84, 234),
106
+ (181, 90, 239), (190, 97, 244), (199, 104, 248), (208, 111, 252),
107
+ (217, 119, 255), (227, 127, 255), (236, 135, 255), (246, 145, 254),
108
+ (255, 154, 252), (255, 164, 248), (255, 174, 243), (255, 185, 237),
109
+ (255, 196, 230),(255, 207, 223), (255, 219, 214),(255, 231, 205),
110
+ (255, 242, 195), (255, 253, 184), (255, 255, 171), (255, 255, 155)
111
+ ],
112
+ 'plasma': [
113
+ (0, 0, 0), (3, 0, 6), (6, 1, 13), (9, 2, 19), (11, 3, 26),
114
+ (14, 5, 32), (17, 8, 39), (20, 11, 45), (22, 15, 51), (24, 19, 57),
115
+ (26, 23, 63), (28, 28, 69), (30, 32, 75), (31, 37, 81), (33, 42, 87),
116
+ (34, 47, 92), (35, 53, 98), (36, 59, 104), (36, 65, 109), (37, 71, 115),
117
+ (38, 77, 120), (38, 83, 125), (39, 90, 130), (39, 96, 135), (40, 102, 140),
118
+ (41, 109, 144), (42, 115, 149), (44, 122, 154), (46, 128, 158), (47, 135, 162),
119
+ (49, 142, 166), (51, 148, 170), (54, 155, 173), (56, 161, 177), (59, 168, 180),
120
+ (61, 174, 183), (64, 181, 186), (67, 187, 189), (70, 193, 192), (73, 199, 194),
121
+ (76, 206, 197), (79, 212, 199), (83, 218, 201), (86, 224, 203),
122
+ (89, 230, 205), (92, 236, 208), (96, 241, 208), (100, 246, 210),
123
+ (103, 251, 211), (106, 255, 212)
124
+ ]
125
+ }
126
+
127
+
128
+ def list_pdf_files(root_dir='.'):
129
+ """Lista todos os arquivos PDF em um diretório."""
130
+ logging.info(f"🔎 Iniciando a busca por arquivos PDF em: {root_dir}")
131
+ pdf_files = [f for f in Path(root_dir).glob('*.pdf')]
132
+ logging.info(f"📚 Encontrados {len(pdf_files)} arquivos PDF.")
133
+ return pdf_files
134
+
135
+ def create_dataframe(pdf_files):
136
+ """Cria um DataFrame com informações sobre os arquivos PDF."""
137
+ logging.info("📊 Criando DataFrame...")
138
+ df = pd.DataFrame(pdf_files, columns=['filepath'])
139
+ df['filename'] = df['filepath'].apply(lambda x: x.name)
140
+ df['pages_processed'] = 0 # Coluna para contar páginas processadas
141
+ logging.info("✅ DataFrame criado.")
142
+ return df
143
+
144
+ def create_output_folder(filename):
145
+ """Cria a pasta de saída para um arquivo PDF específico."""
146
+ output_path = Path(EXTRACTED_FOLDER) / Path(filename).stem
147
+ os.makedirs(output_path, exist_ok=True)
148
+ return output_path
149
+
150
+ def create_image_heatmap(image_array, heatmap_type='object'):
151
+ """Gera um mapa de calor a partir de uma matriz de imagem."""
152
+ gray_image = np.mean(image_array, axis=2)
153
+
154
+ # Aplica um filtro gaussiano
155
+ blurred_image = gaussian_filter(gray_image, sigma=BLUR_RADIUS)
156
+
157
+ # Aplica um limiar adaptativo
158
+ thresh = filters.threshold_otsu(blurred_image)
159
+ binary_mask = blurred_image > thresh
160
+
161
+ if heatmap_type == 'object':
162
+ # Preenche pequenos buracos e remove objetos pequenos
163
+ binary_mask = morphology.remove_small_objects(binary_mask, min_size=100)
164
+ binary_mask = morphology.remove_small_holes(binary_mask, area_threshold=50)
165
+ elif heatmap_type == 'logo':
166
+ binary_mask = morphology.remove_small_objects(binary_mask, min_size=50)
167
+
168
+ # Filtra novamente
169
+ filtered_image = gaussian_filter(binary_mask.astype(float), sigma=BLUR_RADIUS)
170
+
171
+ # Escala para [0, 255]
172
+ heatmap = (filtered_image * 255).astype(np.uint8)
173
+ if heatmap.shape[0] == 0 or heatmap.shape[1] == 0:
174
+ return np.zeros((image_array.shape[0],image_array.shape[1]), dtype=np.uint8)
175
+ return heatmap
176
+
177
+
178
+ def apply_heatmap_overlay(image, heatmap, alpha=HEATMAP_ALPHA, color_scheme = HEATMAP_COLOR_SCHEME):
179
+ """Aplica a sobreposição de mapa de calor a uma imagem."""
180
+
181
+ heatmap_pil = Image.fromarray(heatmap)
182
+ heatmap_pil = heatmap_pil.convert("RGBA")
183
+
184
+ # Aplica a paleta de cores
185
+ if color_scheme in COLOR_SCHEMES:
186
+ colormap = COLOR_SCHEMES[color_scheme]
187
+ # Garante que a paleta de cores tenha pelo menos 256 cores
188
+ while len(colormap) < 256:
189
+ colormap.extend(colormap[-1:]) # Duplica a ultima cor
190
+ else:
191
+ colormap = [(i, i, i) for i in range(256)] # Default grayscale if color_scheme is not found
192
+
193
+ heatmap_pil = Image.new("RGBA", heatmap_pil.size)
194
+ pixels = heatmap_pil.load()
195
+
196
+ for y in range(heatmap_pil.size[1]):
197
+ for x in range(heatmap_pil.size[0]):
198
+ pixel_value = heatmap[y][x]
199
+ pixels[x, y] = colormap[pixel_value] + (int(alpha * 255),)
200
+
201
+ image.paste(heatmap_pil, (0, 0), heatmap_pil)
202
+ return image
203
+
204
+ def extract_text_from_page(image):
205
+ """Extrai o texto de uma imagem usando EasyOCR."""
206
+ results = ocr_reader.readtext(np.array(image))
207
+ return results
208
+
209
+ def get_text_embeddings(text):
210
+ """Obtém os embeddings de texto usando o modelo BERT."""
211
+ tokens = tokenizer(text, return_tensors='pt', padding=True, truncation=True)
212
+ with torch.no_grad():
213
+ outputs = model(**tokens)
214
+ return outputs.last_hidden_state.mean(dim=1).squeeze().numpy()
215
+
216
+ def create_text_heatmap(image, text_boxes, similarity_threshold = SIMILARITY_THRESHOLD, text_heatmap_alpha = TEXT_HEATMAP_ALPHA):
217
+ """Cria um mapa de calor de texto sobrepondo na imagem."""
218
+ image_with_text_heatmap = image.copy().convert("RGBA")
219
+ draw = ImageDraw.Draw(image_with_text_heatmap)
220
+
221
+ if not text_boxes or len(text_boxes) < 2:
222
+ return image_with_text_heatmap
223
+
224
+ texts = [text for (_, text, _) in text_boxes]
225
+ embeddings = [get_text_embeddings(text) for text in texts]
226
+
227
+ # Calcula a similaridade entre todos os pares de textos
228
+ similarity_matrix = cosine_similarity(embeddings)
229
+
230
+ #Normalização das similaridades para o range [0, 1]
231
+ min_similarity = np.min(similarity_matrix)
232
+ max_similarity = np.max(similarity_matrix)
233
+
234
+ normalized_similarity_matrix = (similarity_matrix - min_similarity) / (max_similarity - min_similarity)
235
+
236
+ # Define uma paleta de cores
237
+ cmap = cm.get_cmap('viridis')
238
+
239
+ for i, (bbox, text, _) in enumerate(text_boxes):
240
+ x1, y1 = int(bbox[0][0]), int(bbox[0][1])
241
+ x2, y2 = int(bbox[2][0]), int(bbox[2][1])
242
+
243
+ # Calcula a similaridade com outros textos e cria a média
244
+ average_similarity = np.mean([normalized_similarity_matrix[i][j] for j in range(len(texts)) if i != j])
245
+
246
+ if average_similarity > similarity_threshold:
247
+ color = tuple(int(c * 255) for c in cmap(average_similarity)[:3]) + (int(text_heatmap_alpha * 255),)
248
+ draw.rectangle([(x1, y1), (x2, y2)], fill=color)
249
+ return image_with_text_heatmap
250
+
251
+ def resize_image(image, max_size):
252
+ """Redimensiona a imagem mantendo a proporção."""
253
+
254
+ width, height = image.size
255
+ if width > max_size or height > max_size:
256
+ if width > height:
257
+ new_width = max_size
258
+ new_height = int(height * (max_size / width))
259
+ else:
260
+ new_height = max_size
261
+ new_width = int(width * (max_size / height))
262
+
263
+ return image.resize((new_width, new_height), Image.LANCZOS)
264
+ return image
265
+
266
+ def cluster_text_by_similarity(image, text_boxes, num_clusters=3):
267
+ """Agrupa os blocos de texto por similaridade semântica."""
268
+ if not text_boxes or len(text_boxes) < 2:
269
+ return image
270
+
271
+ texts = [text for (_, text, _) in text_boxes]
272
+ embeddings = [get_text_embeddings(text) for text in texts]
273
+
274
+ if len(embeddings) < num_clusters:
275
+ num_clusters = len(embeddings)
276
+
277
+ # Agrupar embeddings
278
+ clustering = AgglomerativeClustering(n_clusters=num_clusters, linkage='ward')
279
+ clustering.fit(embeddings)
280
+ labels = clustering.labels_
281
+
282
+ # Define uma paleta de cores
283
+ cmap = cm.get_cmap('viridis', num_clusters)
284
+
285
+ image_with_text_clusters = image.copy().convert("RGBA")
286
+ draw = ImageDraw.Draw(image_with_text_clusters)
287
+
288
+ for i, (bbox, _, _) in enumerate(text_boxes):
289
+ x1, y1 = int(bbox[0][0]), int(bbox[0][1])
290
+ x2, y2 = int(bbox[2][0]), int(bbox[2][1])
291
+
292
+ color = tuple(int(c * 255) for c in cmap(labels[i])[:3]) + (int(TEXT_HEATMAP_ALPHA * 255),)
293
+ draw.rectangle([(x1, y1), (x2, y2)], fill=color)
294
+
295
+ return image_with_text_clusters
296
+
297
+ def process_image(image, console, page_number):
298
+ """Processa a imagem, aplicando todos os filtros e análises."""
299
+
300
+ # Redimensionar a imagem
301
+ image = resize_image(image, MAX_IMAGE_SIZE)
302
+ image_array = np.array(image)
303
+
304
+ # Criar uma imagem transparente para sobreposições
305
+ image_rgba = Image.new("RGBA", image.size, (0, 0, 0, 0))
306
+
307
+ # 1. Criar Mapa de Calor para Objetos (Vermelho)
308
+ object_heatmap = create_image_heatmap(image_array, heatmap_type='object')
309
+ image_rgba = apply_heatmap_overlay(image_rgba, object_heatmap, color_scheme='red')
310
+
311
+ # 2. Criar Mapa de Calor para Blocos de Texto (Azul)
312
+ text_heatmap = create_image_heatmap(image_array, heatmap_type='text')
313
+ image_rgba = apply_heatmap_overlay(image_rgba, text_heatmap, color_scheme='blue')
314
+
315
+ # 3. Extrair e Analisar o Texto
316
+ text_boxes = extract_text_from_page(image)
317
+
318
+ # 4. Agrupar texto por similaridade
319
+ image_with_semantic_overlay = cluster_text_by_similarity(image_rgba, text_boxes)
320
+
321
+ # 5. Criar Mapa de Calor para Logos (Verde)
322
+ logo_heatmap = create_image_heatmap(image_array, heatmap_type='logo')
323
+ final_image = apply_heatmap_overlay(image_with_semantic_overlay, logo_heatmap, color_scheme='green')
324
+
325
+ # Sobrepõe a imagem com os heatmaps
326
+ image.paste(final_image, (0, 0), final_image)
327
+
328
+
329
+ return image
330
+
331
+ def process_pdf_page(page, output_path, page_number, filename, console, image_placeholder):
332
+ """Processa uma única página do PDF."""
333
+ try:
334
+ pix = page.get_pixmap(dpi=IMAGE_DPI)
335
+ image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
336
+ processed_image = process_image(image, console, page_number)
337
+ image_path = output_path / f"page_{page_number + 1}.{IMAGE_FORMAT}"
338
+ # Convert to RGB before saving as JPEG
339
+ processed_image.convert('RGB').save(image_path, quality=JPEG_QUALITY, format=IMAGE_FORMAT)
340
+ if LOG_PROCESS:
341
+ st.success(f"🖼️ Página {page_number + 1} de '{filename}' salva em: {image_path}")
342
+
343
+ # Exibe a imagem processada na tela
344
+ st.image(processed_image, caption=f"Página {page_number + 1}", use_column_width=True)
345
+
346
+ return True # Marca sucesso
347
+ except Exception as e:
348
+ logging.error(f"❌ Erro ao processar a página {page_number+1} de '{filename}': {e}")
349
+ return False # Marca falha
350
+
351
+ def process_pdf(row, image_placeholder):
352
+ """Processa um único arquivo PDF."""
353
+ console = Console() # Cria console por thread
354
+ filepath = row['filepath']
355
+ filename = row['filename']
356
+ output_path = create_output_folder(filename)
357
+ total_pages = 0 # Para marcar no DF
358
+ pages_processed = 0 # Para rastrear páginas processadas
359
+ try:
360
+ doc = fitz.open(str(filepath))
361
+ total_pages = len(doc)
362
+ progress_bar = st.progress(0)
363
+ for page_number, page in enumerate(doc):
364
+ if process_pdf_page(page, output_path, page_number, filename, console, image_placeholder):
365
+ pages_processed += 1
366
+ progress_bar.progress((page_number + 1) / total_pages)
367
+ doc.close()
368
+ if LOG_PROCESS:
369
+ st.success(f"✅ '{filename}' concluído. {pages_processed} de {total_pages} páginas processadas.")
370
+
371
+ except Exception as e:
372
+ logging.error(f"🚨 Erro ao processar o PDF '{filename}': {e}")
373
+ return pages_processed, output_path
374
+
375
+ def parallel_pdf_processing(df, image_placeholder):
376
+ """Processa os PDFs em paralelo, atualizando o DataFrame."""
377
+ logging.info(f"🚀 Iniciando o processamento paralelo com {MAX_WORKERS} threads.")
378
+
379
+ with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
380
+ futures = [executor.submit(process_pdf, row, image_placeholder) for index, row in df.iterrows()]
381
+ processed_paths = {}
382
+ # Usar tqdm para acompanhar o progresso geral
383
+ with st.spinner("Processando PDFs..."):
384
+ for index, future in enumerate(concurrent.futures.as_completed(futures)):
385
+ try:
386
+ pages_processed, output_path = future.result()
387
+ df.loc[index, 'pages_processed'] = pages_processed
388
+ processed_paths[df.loc[index, 'filename']] = output_path
389
+ except Exception as e:
390
+ logging.error(f"❌ Erro no processamento do PDF: {e}")
391
+
392
+ logging.info("🏁 Processamento paralelo concluído.")
393
+ return df, processed_paths
394
+
395
+ def display_summary(df):
396
+ """Exibe um resumo do processamento em tabela."""
397
+ st.markdown("### 📊 Resumo do Processamento")
398
+ st.dataframe(df[['filename', 'pages_processed']])
399
+
400
+ def clean_extracted_folders():
401
+ if REMOVE_EXTRACTED:
402
+ logging.info(f"🧹 Limpando pasta de extração: {EXTRACTED_FOLDER}")
403
+ shutil.rmtree(EXTRACTED_FOLDER, ignore_errors=True)
404
+ logging.info("✅ Pasta de extração limpa.")
405
+ else:
406
+ logging.info("⚠️ Remoção da pasta de extração desabilitada")
407
+
408
+ def get_resource_usage():
409
+ """Obtém o uso de CPU e memória."""
410
+ cpu_percent = psutil.cpu_percent()
411
+ memory_usage = psutil.virtual_memory().percent
412
+ return cpu_percent, memory_usage
413
+
414
+ def display_initialization_info():
415
+ """Exibe informações de inicialização no console."""
416
+ st.markdown("## 🚀 Iniciando o Processamento de PDFs 🚀", unsafe_allow_html=True)
417
+ st.markdown("### 📚 Bibliotecas carregadas:")
418
+ st.markdown(" - `fitz` 📄 (PyMuPDF)")
419
+ st.markdown(" - `Pillow` 🖼️ (PIL)")
420
+ st.markdown(" - `rich` 🎨 (Console Ricos)")
421
+ st.markdown(" - `tqdm` ⏳ (Barra de Progresso)")
422
+ st.markdown(" - `scikit-image` 🔬 (Processamento de Imagem)")
423
+ st.markdown(" - `numpy` 🔢 (Arrays Numéricos)")
424
+ st.markdown(" - `scipy` 📈 (Filtro Gaussiano)")
425
+ st.markdown(" - `easyocr` 👁️ (OCR)")
426
+ st.markdown(" - `transformers` 🤖 (Modelos NLP)")
427
+ st.markdown(" - `torch` 🔥 (Tensor Engine)")
428
+ st.markdown(" - `psutil` ⚙️ (Monitor de Recursos)")
429
+
430
+ st.markdown("### 🤖 Modelos inicializados:")
431
+ st.markdown(" - `BERT` 🧠 (Modelo de Embedding de Texto)")
432
+ st.markdown(" - `EasyOCR` 👁️ (Modelo de OCR)")
433
+
434
+ cpu_percent, memory_usage = get_resource_usage()
435
+ st.markdown("### ⚙️ Recursos:")
436
+ st.markdown(f" - 🎛️ CPU: `{cpu_percent:.2f}%`")
437
+ st.markdown(f" - 💾 Memória: `{memory_usage:.2f}%`")
438
+
439
+ st.markdown("### 🔀 Pipelines Multi-Thread:")
440
+ st.markdown(f" - 🧵 Máximo de Threads: `{MAX_WORKERS}`")
441
+ st.markdown(" - 🔄 Processamento Paralelo Ativo")
442
+
443
+ def create_zip_archive(output_paths, zip_name = "processed_images.zip"):
444
+ """Cria um arquivo zip com todas as imagens processadas."""
445
+ zip_buffer = BytesIO()
446
+ with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zipf:
447
+ for filename, output_path in output_paths.items():
448
+ for image_file in output_path.glob(f"*.{IMAGE_FORMAT}"):
449
+ zipf.write(image_file, arcname=f"{Path(filename).stem}/{image_file.name}")
450
+ zip_buffer.seek(0) # Move para o início do buffer
451
+ return zip_buffer
452
+
453
+ def main():
454
+ """Função principal que coordena todo o processo."""
455
+ start_time = time.time()
456
+
457
+ display_initialization_info()
458
+
459
+ uploaded_file = st.file_uploader("Carregue um arquivo PDF", type=['pdf'])
460
+ image_placeholder = st.empty() # Placeholder para exibir as imagens
461
+
462
+ if uploaded_file is not None:
463
+ # Salvar o arquivo PDF temporariamente
464
+ with open("temp.pdf", "wb") as f:
465
+ f.write(uploaded_file.getbuffer())
466
+ pdf_files = [Path("temp.pdf")]
467
+
468
+ df = create_dataframe(pdf_files)
469
+ df, processed_paths = parallel_pdf_processing(df, image_placeholder)
470
+ display_summary(df)
471
+
472
+ zip_buffer = create_zip_archive(processed_paths)
473
+ st.download_button(
474
+ label="Baixar Imagens Processadas (ZIP)",
475
+ data=zip_buffer,
476
+ file_name="processed_images.zip",
477
+ mime="application/zip",
478
+ )
479
+ os.remove("temp.pdf") # Remove o arquivo temporario
480
+
481
+
482
+ end_time = time.time()
483
+ duration = end_time - start_time
484
+ st.success(f"🎉 Processo Concluído em {duration:.2f} segundos!", icon="🎉")
485
+
486
+ cpu_percent, memory_usage = get_resource_usage()
487
+ st.markdown("### ⚙️ Consumo Final de Recursos:")
488
+ st.markdown(f" - 🎛️ CPU: `{cpu_percent:.2f}%`")
489
+ st.markdown(f" - 💾 Memória: `{memory_usage:.2f}%`")
490
+
491
+ if __name__ == "__main__":
492
+ main()