Skip to content

pdf broken encoding reader #522

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: develop
Choose a base branch
from
Open

Conversation

sinkudo
Copy link

@sinkudo sinkudo commented Apr 3, 2025

Reader to extract code from PDF with complex background using information from PDF

added my code from project needed to extract text:

  1. reader
  2. config
  3. h5 models
  4. text post processing
  5. fontforge wrapper
  6. example pdf

added script to scripts dir to extract text using reader

edited index.html, api_args, manager_config, gitignore and requirements

@NastyBoget NastyBoget self-requested a review April 7, 2025 11:10
@NastyBoget NastyBoget added the enhancement New feature or request label Apr 7, 2025
requirements.txt Outdated
@@ -40,3 +39,6 @@ wget==3.2
xgbfir>=0.3.1,<1.0
xgboost>=1.6.0,<2.0 # lower versions aren't compatible with pandas>2
xlrd>=1.2.0,<2.0
nltk==3.9.1
tensorflow==2.13.0
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tensorflow import should be optional similarly to torch (https://github.com/ispras/dedoc/blob/master/pyproject.toml)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


from dedoc.readers.pdf_reader.pdf_txtlayer_reader.pdf_broken_encoding_reader.pdf_broken_encoding_reader import PdfBrokenEncodingReader

if __name__ == "__main__":
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

@@ -24,7 +24,7 @@ class QueryParameters:
table_type: str = Form("", description="Pipeline mode for table recognition")

# pdf handling
pdf_with_text_layer: str = Form("auto_tabby", enum=["true", "false", "auto", "auto_tabby", "tabby"],
pdf_with_text_layer: str = Form("auto_tabby", enum=["true", "false", "auto", "auto_tabby", "tabby","bad_encoding_reader"],
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

API test should be written for a new parameter: you can create file test_pdf_bad_encoding_reader.py similarly to test_api_format_pdf_with_text.py

.gitignore Outdated
@@ -26,6 +26,7 @@ var/
*.egg-info/
.installed.cfg
*.egg
dedoc/readers/pdf_reader/pdf_txtlayer_reader/pdf_broken_encoding_reader/data/pdfdata
Copy link
Collaborator

@NastyBoget NastyBoget Apr 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the directory should be placed in cache ("resources_path" of dedoc config) and downloaded if needed, as it is done for other data (datasets, models) in download_models.py - this script is used in Docker for downloading data in advance

For PyPI library, readers download their data if needed, e.g. for PdfAutoReader - pdf_auto_reader/txtlayer_classifier.py#L27

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


class PdfBrokenEncodingReader(PdfBaseReader):
"""
This class allows to extract content (text, tables, attachments) from the .pdf documents with a textual layer (copyable documents).
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrong docstring (it's doc for other reader)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

self.extractor_layer = PdfminerExtractor(config=self.config)
self.__pdf_txtlayer_reader = PdfTxtlayerReader(config=config)

def can_read(self, file_path: Optional[str] = None, mime: Optional[str] = None, extension: Optional[str] = None,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrong docstring

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

return super().can_read(file_path=file_path, mime=mime, extension=extension) and get_param_pdf_with_txt_layer(
parameters) == "bad_encoding_reader"

def read(self, file_path: str, parameters: Optional[dict] = None) -> UnstructuredDocument:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Docstring is needed

@@ -110,6 +110,7 @@ <h4>PDF handling</h4>
<option value="auto">auto</option>
<option value="auto_tabby" selected>auto_tabby</option>
<option value="tabby">tabby</option>
<option value="bad_encoding_reader">bad_encoding_reader</option>
Copy link
Collaborator

@NastyBoget NastyBoget Apr 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

WordObj = namedtuple("Word", ["start", "end", "value"])


class PdfBrokenEncodingReader(PdfBaseReader):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

@NastyBoget
Copy link
Collaborator

Please look to the logs of test pipelines - they all should pass before merge

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All binary files should be downloaded as needed at the reader initialization stage.

all binary files should be downloaded as needed at the reader initialization stage
You can see how it is done in dedoc/readers/pdf_reader/pdf_image_reader/pdf_image_reader.py
in the line:

checkpoint_path=os.path.join(get_config()["resources_path"],
"scan_orientation_efficient_net_b0.pth"),
...
  • Binary files should be downloaded to the "resources_path" directory of config file

  • an example of initialization and downloading of weights dedoc/readers/pdf_reader/pdf_image_reader/columns_orientation_classifier/columns_orientation_classifier.py (function _load_weights)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

args = parser.parse_args()
reader = PdfBrokenEncodingReader()
document = reader.read(args.pdf_path)
print(document.get_text())
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should add more then one tests:

  • add api tests into tests/api_tests to check that your reader is working correctly via api
  • add a unit test to test/unit_test to check that your reader is working correctly



class PdfBrokenEncodingReader(PdfBaseReader):
"""
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a detailed description of the functionality of your reader

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

except Exception as e:
raise Exception(f"some problem occured: {e}")
pages, layouts = reader.get_correct_layout(file_path)
tables = []
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'tables' unused

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

image_page = cv2.cvtColor(image_page, cv2.COLOR_GRAY2BGR)
return image_page

def __debug_extract_layout(self, image_src: np.ndarray, layout: LTContainer, page_num: int, k_w: float, k_h: float,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is a dublicate code of dedoc/readers/pdf_reader/pdf_txtlayer_reader/pdfminer_reader/pdfminer_extractor.py

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

cv2.imwrite(os.path.join(tmp_dir, f"img_page_{page_num}.png"), image_src)
file_text.close()

def __extract_image(self,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is a dublicate code of dedoc/readers/pdf_reader/pdf_txtlayer_reader/pdfminer_reader/pdfminer_extractor.py

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


return text_with_bbox

def __get_line_annotations(self, lobj: LTTextLineHorizontal, height: int, width: int) -> Tuple[
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is a dublicate code of dedoc/readers/pdf_reader/pdf_txtlayer_reader/pdfminer_reader/pdfminer_extractor.py

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

def _get_new_weight(self) -> str:
return binascii.hexlify(os.urandom(8)).decode("ascii")

def __parse_style_string(self, chars_with_meta: str, begin: int, end: int) -> List[Annotation]:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is a dublicate code of dedoc/readers/pdf_reader/pdf_txtlayer_reader/pdfminer_reader/pdfminer_extractor.py

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

call_classifier=False))
return lines, tables, page.attachments, []

def __handle_page(self, page: PDFPage, page_number: int, path: str,
Copy link
Collaborator

@oksidgy oksidgy Apr 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is dublicated code of dedoc/readers/pdf_reader/pdf_txtlayer_reader/pdfminer_reader/pdfminer_extractor.py with different that you use own layout (pass own layout ). Try to use code of dedoc/readers/pdf_reader/pdf_txtlayer_reader/pdfminer_reader/pdfminer_extractor.py with small changes of code of pdfminer_extractor.py.

For example in file dedoc/readers/pdf_reader/pdf_txtlayer_reader/pdfminer_reader/pdfminer_extractor.py:

  1. do pubic function def __handle_page(...) -> def handle_page(...)
  2. added small changes into code:
def handle_page(self, page: PDFPage, page_number: int, path: str, parameters: ParametersForParseDoc, Layout: Optional[LTPage] = None) -> PageWithBBox:
...
if not layout:
     layout = device.get_result()
...

So, by adding these small changes you will get rid of 300 lines of duplicate code!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

onlyRus = ['я', 'й', 'ц', 'б', 'ж', 'з', 'д', 'л', 'ф', 'ш', 'щ', "ч", "ъ", "ь", "э", "ю", 'г']
onlyEng = ['q', 'w', 'f', 'i', 'j', 'l', 'z', 's', 'v', 'g']

from nltk.corpus import words
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from nltk.corpus import words put inside code of function substitute_chars_by_dict

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

from dedoc.readers.pdf_reader.pdf_txtlayer_reader.pdf_broken_encoding_reader.functions import get_project_root


class Model:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Docstring is needed

import tensorflow as tf
from keras import layers
from keras.callbacks import TensorBoard
from keras.models import load_model
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move all external imports inside the function codes where they are called

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


import PIL.ImageOps
from PIL import Image
from pdfminer.high_level import extract_text
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move all external imports inside the function codes where they are called

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

import warnings
from pathlib import Path

import fontforge
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move all external imports inside the function codes where they are called

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

import os
from pathlib import Path

from keras.models import load_model
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move all external imports inside the function codes where they are called

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants