-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathocr_processor.py
More file actions
795 lines (672 loc) · 35.4 KB
/
Copy pathocr_processor.py
File metadata and controls
795 lines (672 loc) · 35.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
"""
Processador principal de OCR usando PaddleOCR.
"""
import shutil
import tempfile
from pathlib import Path
from typing import Optional, Tuple, List
from logger import setup_logger
from config import OCR_CONFIG, FILE_CONFIG, FOLDERS
logger = setup_logger('ocr_processor')
class OCRProcessor:
"""Processador de OCR usando PaddleOCR."""
def __init__(self):
self.config = OCR_CONFIG
self.file_config = FILE_CONFIG
self.paddleocr = None
self._init_paddleocr()
def validate_file(self, file_path: Path) -> Tuple[bool, Optional[str]]:
"""
Valida se o arquivo pode ser processado.
Args:
file_path: Caminho do arquivo PDF
Returns:
Tupla (é_válido, mensagem_erro)
"""
if not file_path.exists():
return False, "Arquivo não existe"
if not file_path.is_file():
return False, "Não é um arquivo"
if file_path.suffix.lower() != '.pdf':
return False, "Não é um arquivo PDF"
file_size = file_path.stat().st_size
if file_size < self.file_config['min_file_size']:
return False, f"Arquivo muito pequeno ({file_size} bytes)"
if file_size > self.file_config['max_file_size']:
return False, f"Arquivo muito grande ({file_size} bytes)"
# Verificar se arquivo está sendo usado
try:
with open(file_path, 'rb'):
pass
except PermissionError:
return False, "Arquivo está em uso ou sem permissão"
return True, None
def _init_paddleocr(self):
"""Inicializa PaddleOCR."""
try:
from paddleocr import PaddleOCR
lang = self.config['paddleocr_lang']
# Versão nova do PaddleOCR usa use_textline_orientation ao invés de use_angle_cls
# E não aceita show_log
try:
self.paddleocr = PaddleOCR(
use_textline_orientation=True,
lang=lang
)
except TypeError:
# Fallback para versão antiga
try:
self.paddleocr = PaddleOCR(
use_angle_cls=True,
lang=lang,
show_log=False
)
except TypeError:
# Versão mais antiga ainda
self.paddleocr = PaddleOCR(lang=lang)
logger.info(f"PaddleOCR inicializado com sucesso (idioma: {lang})")
except ImportError:
logger.warning("PaddleOCR não encontrado. Usando OCRmyPDF como motor principal.")
self.paddleocr = None
except Exception as e:
error_msg = str(e).lower()
if 'dll' in error_msg or 'política' in error_msg or 'policy' in error_msg:
logger.warning(f"PaddleOCR bloqueado por política de segurança (DLL). Usando OCRmyPDF como motor principal.")
else:
logger.warning(f"Erro ao inicializar PaddleOCR: {e}. Usando OCRmyPDF como motor principal.")
self.paddleocr = None
def _pdf_to_images(self, pdf_path: Path) -> List[Path]:
"""
Converte PDF em imagens.
Args:
pdf_path: Caminho do PDF
Returns:
Lista de caminhos das imagens
"""
try:
import fitz # PyMuPDF
doc = fitz.open(str(pdf_path))
images = []
temp_dir = tempfile.mkdtemp()
for page_num in range(len(doc)):
page = doc[page_num]
# Renderizar página como imagem (DPI configurável)
dpi = self.config.get('pdf_dpi', 300)
mat = fitz.Matrix(dpi/72, dpi/72)
pix = page.get_pixmap(matrix=mat)
# Salvar imagem temporária
img_path = Path(temp_dir) / f"page_{page_num:04d}.png"
pix.save(str(img_path))
images.append(img_path)
doc.close()
logger.debug(f"PDF convertido em {len(images)} imagens")
return images
except ImportError:
logger.error("PyMuPDF não encontrado. Instale com: pip install PyMuPDF")
return []
except Exception as e:
logger.error(f"Erro ao converter PDF em imagens: {e}")
return []
def _process_image_with_paddleocr(self, image_path: Path) -> List[dict]:
"""
Processa imagem com PaddleOCR.
Args:
image_path: Caminho da imagem
Returns:
Lista de resultados OCR (cada item: {'bbox': [...], 'text': '...', 'score': ...})
"""
if not self.paddleocr:
return []
try:
# Usar .ocr() que ainda funciona (mesmo com aviso de deprecação)
# Não usar .predict() pois retorna estrutura diferente
result = self.paddleocr.ocr(str(image_path))
if not result or not result[0]:
logger.warning(f"Nenhum texto detectado em {image_path.name}")
return []
ocr_results = []
ocr_result = result[0]
# OCRResult é um dicionário-like, não uma lista
# Precisamos acessar os dados através de métodos ou chaves específicas
logger.info(f"DEBUG: OCRResult tipo: {type(ocr_result)}")
# Tentar método get_minarea_rect() que retorna lista de retângulos
try:
if hasattr(ocr_result, 'get_minarea_rect'):
rects = ocr_result.get_minarea_rect()
logger.info(f"DEBUG: get_minarea_rect() retornou {len(rects) if rects else 0} retângulos")
if rects:
# Obter textos e scores
rec_texts = ocr_result.get('rec_texts', []) if hasattr(ocr_result, 'get') else []
rec_scores = ocr_result.get('rec_scores', []) if hasattr(ocr_result, 'get') else []
# Se não conseguiu via get(), tentar acesso direto
if not rec_texts:
rec_texts = getattr(ocr_result, 'rec_texts', [])
if not rec_scores:
rec_scores = getattr(ocr_result, 'rec_scores', [])
for idx, bbox in enumerate(rects):
text = rec_texts[idx] if idx < len(rec_texts) else ""
score = float(rec_scores[idx]) if idx < len(rec_scores) else 1.0
ocr_results.append({
'bbox': bbox,
'text': str(text) if text else '',
'score': score
})
except Exception as e:
logger.debug(f"get_minarea_rect() falhou: {e}")
# Se ainda não temos resultados, tentar acessar diretamente dt_polys, rec_texts, rec_scores
if not ocr_results:
try:
# Tentar acesso via get() (se for dict-like)
dt_polys = ocr_result.get('dt_polys', []) if hasattr(ocr_result, 'get') else None
rec_texts = ocr_result.get('rec_texts', []) if hasattr(ocr_result, 'get') else None
rec_scores = ocr_result.get('rec_scores', []) if hasattr(ocr_result, 'get') else None
# Se não conseguiu via get(), tentar acesso direto como atributo
if dt_polys is None:
dt_polys = getattr(ocr_result, 'dt_polys', None)
if rec_texts is None:
rec_texts = getattr(ocr_result, 'rec_texts', None)
if rec_scores is None:
rec_scores = getattr(ocr_result, 'rec_scores', None)
# Tentar dt_boxes como alternativa
if dt_polys is None:
dt_polys = ocr_result.get('dt_boxes', []) if hasattr(ocr_result, 'get') else getattr(ocr_result, 'dt_boxes', None)
if dt_polys and rec_texts:
logger.info(f"DEBUG: Encontrados {len(dt_polys)} bboxes e {len(rec_texts)} textos")
for idx, (bbox, text) in enumerate(zip(dt_polys, rec_texts)):
score = float(rec_scores[idx]) if rec_scores and idx < len(rec_scores) else 1.0
ocr_results.append({
'bbox': bbox,
'text': str(text) if text else '',
'score': score
})
except Exception as e:
logger.debug(f"Erro ao acessar dt_polys/rec_texts: {e}")
# Se ainda não temos resultados, tentar formato antigo (lista)
if not ocr_results and isinstance(ocr_result, (list, tuple)):
logger.info("DEBUG: Tentando formato antigo (lista)")
for line in ocr_result:
if line and len(line) >= 2:
try:
bbox = line[0]
text_data = line[1]
if isinstance(text_data, (list, tuple)) and len(text_data) >= 2:
text = text_data[0]
score = float(text_data[1])
else:
text = str(text_data) if text_data else ""
score = 1.0
ocr_results.append({
'bbox': bbox,
'text': text,
'score': score
})
except (IndexError, TypeError, ValueError) as e:
logger.debug(f"Erro ao processar linha OCR: {e}")
continue
if not ocr_results:
logger.warning(f"Nenhum resultado válido extraído de {image_path.name}")
# Log adicional para debug
if hasattr(ocr_result, 'keys'):
logger.debug(f"Chaves disponíveis no OCRResult: {list(ocr_result.keys())}")
if hasattr(ocr_result, 'json'):
try:
import json
json_str = ocr_result.json()
logger.debug(f"JSON do OCRResult: {json_str[:500] if len(json_str) > 500 else json_str}")
except:
pass
return ocr_results
except Exception as e:
logger.error(f"Erro ao processar imagem {image_path.name}: {e}")
import traceback
logger.debug(traceback.format_exc())
return []
def _images_to_pdf_with_ocr(
self,
images: List[Path],
ocr_results: List[List[dict]],
output_path: Path
) -> bool:
"""
Reconstrói PDF com texto pesquisável a partir das imagens e resultados OCR.
Args:
images: Lista de caminhos das imagens
ocr_results: Lista de resultados OCR por página
output_path: Caminho do PDF de saída
Returns:
True se criado com sucesso
"""
try:
import fitz # PyMuPDF
from PIL import Image
# Criar novo PDF
doc = fitz.open()
for img_path, page_ocr in zip(images, ocr_results):
# Abrir imagem
img = Image.open(img_path)
width, height = img.size
# Criar página com dimensões da imagem
page = doc.new_page(width=width, height=height)
# Inserir imagem na página
rect = fitz.Rect(0, 0, width, height)
page.insert_image(rect, filename=str(img_path))
# Adicionar texto pesquisável baseado no OCR
texts_inserted = 0
page_rect = page.rect # Retângulo da página (limites)
logger.info(f"Processando {len(page_ocr)} textos OCR na página {len(doc)} (dimensões: {width}x{height})")
for idx, ocr_item in enumerate(page_ocr):
try:
bbox = ocr_item.get('bbox', [])
text = ocr_item.get('text', '')
# Converter arrays NumPy para tipos Python nativos ANTES de qualquer validação
try:
import numpy as np
if isinstance(bbox, np.ndarray):
bbox = bbox.tolist()
if isinstance(text, np.ndarray):
text = text.tolist()
# Se text for lista/array, pegar primeiro elemento ou converter para string
if isinstance(text, (list, tuple, np.ndarray)):
text = str(text[0]) if len(text) > 0 else ''
except ImportError:
pass # NumPy não disponível, continuar
except Exception:
pass # Erro ao converter, continuar
# Converter text para string e limpar
text = str(text).strip() if text else ''
# Validar dados de forma segura (sem comparar arrays diretamente)
if len(text) == 0:
logger.debug(f"Item {idx}: texto vazio - ignorando")
continue
# Validar bbox de forma segura
try:
import numpy as np
if isinstance(bbox, np.ndarray):
bbox = bbox.tolist()
# Verificar se bbox está vazio de forma segura
if isinstance(bbox, (list, tuple)):
if len(bbox) == 0:
logger.debug(f"Item {idx}: bbox vazio - ignorando")
continue
else:
logger.debug(f"Item {idx}: bbox não é lista/tupla: {type(bbox)}")
continue
except (ImportError, Exception):
if not isinstance(bbox, (list, tuple)) or len(bbox) == 0:
logger.debug(f"Item {idx}: bbox inválido - ignorando")
continue
# Validar formato do bbox
if not isinstance(bbox, (list, tuple)):
logger.debug(f"Item {idx}: Bbox não é lista/tupla: {type(bbox)}")
continue
if len(bbox) < 4:
logger.debug(f"Item {idx}: Bbox tem {len(bbox)} elementos ao invés de 4")
continue
# Converter bbox do PaddleOCR para retângulo do PyMuPDF
# PaddleOCR retorna: [[x1,y1], [x2,y2], [x3,y3], [x4,y4]]
try:
x_coords = []
y_coords = []
for point in bbox:
# Converter ponto para lista se for array NumPy
try:
import numpy as np
if isinstance(point, np.ndarray):
point = point.tolist()
except (ImportError, Exception):
pass
if isinstance(point, (list, tuple)) and len(point) >= 2:
x_coords.append(float(point[0]))
y_coords.append(float(point[1]))
else:
logger.debug(f"Item {idx}: Ponto inválido no bbox: {type(point)}")
break
if len(x_coords) == 0 or len(y_coords) == 0:
logger.debug(f"Item {idx}: Bbox sem coordenadas válidas")
continue
x0, y0 = min(x_coords), min(y_coords)
x1, y1 = max(x_coords), max(y_coords)
# Validar dimensões
if x1 <= x0 or y1 <= y0:
logger.debug(f"Item {idx}: Bbox com dimensões inválidas")
continue
# Garantir que o retângulo está dentro dos limites da página
x0 = max(0, min(x0, width))
y0 = max(0, min(y0, height))
x1 = max(0, min(x1, width))
y1 = max(0, min(y1, height))
# Validar novamente após ajuste
if x1 <= x0 or y1 <= y0:
logger.debug(f"Item {idx}: Bbox inválido após ajuste")
continue
text_rect = fitz.Rect(x0, y0, x1, y1)
# Inserir texto pesquisável usando insert_textbox (mais confiável)
text_success = False
try:
# Calcular tamanho de fonte baseado na altura do retângulo
fontsize = max(8, min(12, (y1 - y0) * 0.8))
# Tentar insert_textbox com render_mode=0 (visível e pesquisável)
rc = page.insert_textbox(
text_rect,
text,
fontsize=fontsize,
color=(0, 0, 0), # Preto (visível)
align=0, # Alinhamento à esquerda
render_mode=0 # Visível e pesquisável
)
if rc < 0:
# Se não coube, tentar com fonte menor
logger.debug(f"Item {idx}: Texto não coube no retângulo (rc={rc}), tentando fonte menor: {text[:20]}")
fontsize_small = max(6, fontsize * 0.7)
rc = page.insert_textbox(
text_rect,
text,
fontsize=fontsize_small,
color=(0, 0, 0),
align=0,
render_mode=0
)
if rc < 0:
# Tentar com render_mode=3 (invisível mas pesquisável)
logger.debug(f"Item {idx}: Tentando com render_mode=3 (invisível): {text[:20]}")
rc = page.insert_textbox(
text_rect,
text,
fontsize=fontsize,
color=(0, 0, 0),
align=0,
render_mode=3 # Invisível mas pesquisável
)
if rc < 0:
# Se ainda não coube, usar insert_text como fallback
logger.debug(f"Item {idx}: Usando insert_text como fallback (rc={rc}): {text[:20]}")
try:
page.insert_text(
text_rect.tl,
text,
fontsize=fontsize,
color=(0, 0, 0),
render_mode=0
)
text_success = True
except Exception as e_insert:
# Última tentativa: insert_text com render_mode=3
try:
page.insert_text(
text_rect.tl,
text,
fontsize=fontsize,
color=(0, 0, 0),
render_mode=3
)
text_success = True
except Exception as e3:
logger.debug(f"Item {idx}: Falha ao inserir texto: {e3}")
else:
# insert_textbox funcionou (rc >= 0 significa sucesso)
text_success = True
except Exception as e:
logger.debug(f"Item {idx}: Erro ao inserir texto: {e}")
# Tentar método mais simples como último recurso
try:
page.insert_text(
text_rect.tl,
text,
fontsize=8,
color=(0, 0, 0),
render_mode=0
)
text_success = True
except Exception as e2:
# Última tentativa: render_mode=3
try:
page.insert_text(
text_rect.tl,
text,
fontsize=8,
color=(0, 0, 0),
render_mode=3
)
text_success = True
except Exception as e3:
logger.debug(f"Item {idx}: Todas as tentativas falharam")
continue
# Contar apenas se realmente inseriu o texto
if text_success:
texts_inserted += 1
except (IndexError, TypeError, ValueError) as e:
logger.warning(f"Item {idx}: Erro ao processar bbox {bbox}: {e}")
continue
except Exception as e:
logger.warning(f"Item {idx}: Erro ao processar item OCR: {e}")
import traceback
logger.debug(f"Traceback: {traceback.format_exc()}")
continue
if texts_inserted > 0:
logger.info(f"Página {len(doc)}: {texts_inserted} textos inseridos com sucesso")
else:
logger.warning(f"Página {len(doc)}: Nenhum texto foi inserido (mas {len(page_ocr)} textos foram detectados pelo OCR)")
# Salvar PDF
output_path.parent.mkdir(parents=True, exist_ok=True)
doc.save(str(output_path))
doc.close()
return True
except ImportError as e:
logger.error(f"Biblioteca necessária não encontrada: {e}")
return False
except Exception as e:
logger.error(f"Erro ao criar PDF: {e}")
return False
def process_with_paddleocr(
self,
input_path: Path,
output_path: Path
) -> Tuple[bool, Optional[str]]:
"""
Processa PDF com PaddleOCR.
Args:
input_path: Caminho do arquivo de entrada
output_path: Caminho do arquivo de saída
Returns:
Tupla (sucesso, mensagem_erro)
"""
if not self.paddleocr:
return False, "PaddleOCR não inicializado"
images = []
temp_dir = None
try:
logger.info(f"Processando {input_path.name} com PaddleOCR...")
# 1. Converter PDF em imagens
images = self._pdf_to_images(input_path)
if not images:
return False, "Falha ao converter PDF em imagens"
temp_dir = images[0].parent if images else None
# 2. Processar cada imagem com OCR
ocr_results = []
total_text_found = 0
for i, img_path in enumerate(images):
logger.debug(f"Processando página {i+1}/{len(images)}")
page_ocr = self._process_image_with_paddleocr(img_path)
ocr_results.append(page_ocr)
text_count = len(page_ocr)
total_text_found += text_count
logger.info(f"Página {i+1}: {text_count} textos detectados")
if total_text_found == 0:
logger.warning(f"Nenhum texto detectado em nenhuma página do arquivo {input_path.name}")
return False, "Nenhum texto detectado"
# 3. Reconstruir PDF com texto pesquisável
success = self._images_to_pdf_with_ocr(images, ocr_results, output_path)
if success:
# Verificar se o PDF realmente tem texto pesquisável
try:
import fitz
doc = fitz.open(str(output_path))
total_text_chars = 0
for page in doc:
total_text_chars += len(page.get_text())
doc.close()
if total_text_chars > 0:
logger.info(f"✓ Processado com sucesso: {output_path.name} ({total_text_found} textos, {total_text_chars} caracteres pesquisáveis)")
else:
logger.warning(f"PDF criado mas sem texto pesquisável detectado ({total_text_found} textos processados)")
except Exception as e:
logger.debug(f"Erro ao verificar texto no PDF: {e}")
return True, None
else:
return False, "Falha ao reconstruir PDF"
except Exception as e:
error_msg = f"Erro inesperado: {str(e)}"
logger.error(f"✗ {error_msg}: {input_path.name}")
return False, error_msg
finally:
# Limpar imagens temporárias sempre
if temp_dir and temp_dir.exists():
try:
shutil.rmtree(temp_dir)
logger.debug(f"Arquivos temporários removidos: {temp_dir}")
except Exception as e:
logger.warning(f"Não foi possível remover arquivos temporários: {e}")
def move_to_processed(self, file_path: Path) -> bool:
"""
Move arquivo para pasta processed.
Args:
file_path: Caminho do arquivo
Returns:
True se moveu com sucesso
"""
try:
if not self.file_config['preserve_original']:
file_path.unlink()
return True
processed_path = FOLDERS['processed'] / file_path.name
# Se arquivo já existe, adicionar sufixo numérico
counter = 1
while processed_path.exists():
stem = file_path.stem
suffix = file_path.suffix
processed_path = FOLDERS['processed'] / f"{stem}_{counter}{suffix}"
counter += 1
shutil.move(str(file_path), str(processed_path))
logger.debug(f"Arquivo movido para processed: {processed_path.name}")
return True
except Exception as e:
logger.error(f"Erro ao mover arquivo para processed: {e}")
return False
def move_to_failed(self, file_path: Path) -> bool:
"""
Move arquivo para pasta failed.
Args:
file_path: Caminho do arquivo
Returns:
True se moveu com sucesso
"""
try:
failed_path = FOLDERS['failed'] / file_path.name
# Se arquivo já existe, adicionar sufixo numérico
counter = 1
while failed_path.exists():
stem = file_path.stem
suffix = file_path.suffix
failed_path = FOLDERS['failed'] / f"{stem}_{counter}{suffix}"
counter += 1
shutil.move(str(file_path), str(failed_path))
logger.debug(f"Arquivo movido para failed: {failed_path.name}")
return True
except Exception as e:
logger.error(f"Erro ao mover arquivo para failed: {e}")
return False
def generate_output_path(self, input_path: Path, output_folder: Path = None) -> Path:
"""
Gera caminho de saída baseado no arquivo de entrada.
Args:
input_path: Caminho do arquivo de entrada
output_folder: Pasta de saída (opcional, usa FOLDERS['output'] se não especificado)
Returns:
Caminho do arquivo de saída
"""
stem = input_path.stem
suffix = input_path.suffix
output_name = f"{stem}{self.file_config['output_suffix']}{suffix}"
if output_folder:
return output_folder / output_name
else:
# Fallback para compatibilidade com código antigo
return FOLDERS.get('output', Path('output')) / output_name
def process_file(self, file_path: Path, output_folder: Path = None) -> bool:
"""
Processa um arquivo PDF completo (validação + OCR + movimentação).
Args:
file_path: Caminho do arquivo PDF
output_folder: Pasta de saída (opcional, usa FOLDERS['output'] se não especificado)
Returns:
True se processado com sucesso
"""
logger.info(f"Iniciando processamento: {file_path.name}")
# Validar arquivo
is_valid, error_msg = self.validate_file(file_path)
if not is_valid:
logger.warning(f"Arquivo inválido: {file_path.name} - {error_msg}")
self.move_to_failed(file_path)
return False
# Gerar caminho de saída
output_path = self.generate_output_path(file_path, output_folder)
# PRINCIPAL: OCRmyPDF (mais confiável para criar PDFs com texto pesquisável)
logger.info(f"Processando {file_path.name} com OCRmyPDF (motor principal)...")
try:
from ocr_fallback import OCRFallback
ocrmypdf_processor = OCRFallback()
ocrmypdf_success = ocrmypdf_processor.process_file(file_path, output_path)
if ocrmypdf_success:
# Verificar se o PDF tem texto pesquisável
try:
import fitz
doc = fitz.open(str(output_path))
total_chars = sum(len(page.get_text()) for page in doc)
doc.close()
if total_chars > 0:
self.move_to_processed(file_path)
logger.info(f"✓ Processamento concluído com OCRmyPDF: {file_path.name} → {output_path.name} ({total_chars} caracteres)")
return True
else:
logger.warning(f"OCRmyPDF processou mas sem texto pesquisável. Tentando fallback...")
except Exception as e:
logger.warning(f"Erro ao verificar texto: {e}. Tentando fallback...")
else:
logger.warning(f"OCRmyPDF não conseguiu processar {file_path.name}. Tentando fallback...")
except Exception as e:
logger.warning(f"Erro ao processar com OCRmyPDF: {e}. Tentando fallback...")
# FALLBACK 1: Tesseract direto (evita DLLs problemáticas)
logger.info(f"Tentando Tesseract direto como fallback para {file_path.name}...")
try:
from ocr_tesseract_direct import TesseractDirectProcessor
tesseract_processor = TesseractDirectProcessor()
tesseract_success = tesseract_processor.process_file(file_path, output_path)
if tesseract_success:
self.move_to_processed(file_path)
logger.info(f"✓ Processamento concluído com Tesseract: {file_path.name} → {output_path.name}")
return True
except Exception as e:
logger.warning(f"Erro ao processar com Tesseract: {e}. Tentando próximo fallback...")
# FALLBACK 2: PaddleOCR (se disponível, mas pode ter problemas com arrays NumPy)
if self.paddleocr:
logger.info(f"Tentando PaddleOCR como último fallback para {file_path.name}...")
try:
success, error_msg = self.process_with_paddleocr(file_path, output_path)
if success:
try:
import fitz
doc = fitz.open(str(output_path))
has_text = any(len(page.get_text()) > 0 for page in doc)
doc.close()
if has_text:
self.move_to_processed(file_path)
logger.info(f"✓ Processamento concluído com PaddleOCR: {file_path.name} → {output_path.name}")
return True
except Exception:
pass
except Exception as e:
logger.warning(f"Erro ao processar com PaddleOCR: {e}")
# Se tudo falhou, mover para failed
logger.error(f"✗ Falha no processamento: {file_path.name} (todos os métodos falharam)")
self.move_to_failed(file_path)
return False