dataset.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import os
  2. from abc import ABC, abstractmethod
  3. from typing import Callable, Iterator
  4. import fitz
  5. from magic_pdf.config.enums import SupportedPdfParseMethod
  6. from magic_pdf.data.schemas import PageInfo
  7. from magic_pdf.data.utils import fitz_doc_to_image
  8. from magic_pdf.filter import classify
  9. class PageableData(ABC):
  10. @abstractmethod
  11. def get_image(self) -> dict:
  12. """Transform data to image."""
  13. pass
  14. @abstractmethod
  15. def get_doc(self) -> fitz.Page:
  16. """Get the pymudoc page."""
  17. pass
  18. @abstractmethod
  19. def get_page_info(self) -> PageInfo:
  20. """Get the page info of the page.
  21. Returns:
  22. PageInfo: the page info of this page
  23. """
  24. pass
  25. @abstractmethod
  26. def draw_rect(self, rect_coords, color, fill, fill_opacity, width, overlay):
  27. """draw rectangle.
  28. Args:
  29. rect_coords (list[float]): four elements array contain the top-left and bottom-right coordinates, [x0, y0, x1, y1]
  30. color (list[float] | None): three element tuple which descript the RGB of the board line, None means no board line
  31. fill (list[float] | None): fill the board with RGB, None means will not fill with color
  32. fill_opacity (float): opacity of the fill, range from [0, 1]
  33. width (float): the width of board
  34. overlay (bool): fill the color in foreground or background. True means fill in background.
  35. """
  36. pass
  37. @abstractmethod
  38. def insert_text(self, coord, content, fontsize, color):
  39. """insert text.
  40. Args:
  41. coord (list[float]): four elements array contain the top-left and bottom-right coordinates, [x0, y0, x1, y1]
  42. content (str): the text content
  43. fontsize (int): font size of the text
  44. color (list[float] | None): three element tuple which descript the RGB of the board line, None will use the default font color!
  45. """
  46. pass
  47. class Dataset(ABC):
  48. @abstractmethod
  49. def __len__(self) -> int:
  50. """The length of the dataset."""
  51. pass
  52. @abstractmethod
  53. def __iter__(self) -> Iterator[PageableData]:
  54. """Yield the page data."""
  55. pass
  56. @abstractmethod
  57. def supported_methods(self) -> list[SupportedPdfParseMethod]:
  58. """The methods that this dataset support.
  59. Returns:
  60. list[SupportedPdfParseMethod]: The supported methods, Valid methods are: OCR, TXT
  61. """
  62. pass
  63. @abstractmethod
  64. def data_bits(self) -> bytes:
  65. """The bits used to create this dataset."""
  66. pass
  67. @abstractmethod
  68. def get_page(self, page_id: int) -> PageableData:
  69. """Get the page indexed by page_id.
  70. Args:
  71. page_id (int): the index of the page
  72. Returns:
  73. PageableData: the page doc object
  74. """
  75. pass
  76. @abstractmethod
  77. def dump_to_file(self, file_path: str):
  78. pass
  79. @abstractmethod
  80. def apply(self, proc: Callable, *args, **kwargs):
  81. pass
  82. @abstractmethod
  83. def classify(self) -> SupportedPdfParseMethod:
  84. pass
  85. class PymuDocDataset(Dataset):
  86. def __init__(self, bits: bytes):
  87. """Initialize the dataset, which wraps the pymudoc documents.
  88. Args:
  89. bits (bytes): the bytes of the pdf
  90. """
  91. self._raw_fitz = fitz.open('pdf', bits)
  92. self._records = [Doc(v) for v in self._raw_fitz]
  93. self._data_bits = bits
  94. self._raw_data = bits
  95. def __len__(self) -> int:
  96. """The page number of the pdf."""
  97. return len(self._records)
  98. def __iter__(self) -> Iterator[PageableData]:
  99. """Yield the page doc object."""
  100. return iter(self._records)
  101. def supported_methods(self) -> list[SupportedPdfParseMethod]:
  102. """The method supported by this dataset.
  103. Returns:
  104. list[SupportedPdfParseMethod]: the supported methods
  105. """
  106. return [SupportedPdfParseMethod.OCR, SupportedPdfParseMethod.TXT]
  107. def data_bits(self) -> bytes:
  108. """The pdf bits used to create this dataset."""
  109. return self._data_bits
  110. def get_page(self, page_id: int) -> PageableData:
  111. """The page doc object.
  112. Args:
  113. page_id (int): the page doc index
  114. Returns:
  115. PageableData: the page doc object
  116. """
  117. return self._records[page_id]
  118. def dump_to_file(self, file_path: str):
  119. dir_name = os.path.dirname(file_path)
  120. if dir_name not in ('', '.', '..'):
  121. os.makedirs(dir_name, exist_ok=True)
  122. self._raw_fitz.save(file_path)
  123. def apply(self, proc: Callable, *args, **kwargs):
  124. new_args = tuple([self] + list(args))
  125. return proc(*new_args, **kwargs)
  126. def classify(self) -> SupportedPdfParseMethod:
  127. return classify(self._data_bits)
  128. class ImageDataset(Dataset):
  129. def __init__(self, bits: bytes):
  130. """Initialize the dataset, which wraps the pymudoc documents.
  131. Args:
  132. bits (bytes): the bytes of the photo which will be converted to pdf first. then converted to pymudoc.
  133. """
  134. pdf_bytes = fitz.open(stream=bits).convert_to_pdf()
  135. self._raw_fitz = fitz.open('pdf', pdf_bytes)
  136. self._records = [Doc(v) for v in self._raw_fitz]
  137. self._raw_data = bits
  138. self._data_bits = pdf_bytes
  139. def __len__(self) -> int:
  140. """The length of the dataset."""
  141. return len(self._records)
  142. def __iter__(self) -> Iterator[PageableData]:
  143. """Yield the page object."""
  144. return iter(self._records)
  145. def supported_methods(self):
  146. """The method supported by this dataset.
  147. Returns:
  148. list[SupportedPdfParseMethod]: the supported methods
  149. """
  150. return [SupportedPdfParseMethod.OCR]
  151. def data_bits(self) -> bytes:
  152. """The pdf bits used to create this dataset."""
  153. return self._data_bits
  154. def get_page(self, page_id: int) -> PageableData:
  155. """The page doc object.
  156. Args:
  157. page_id (int): the page doc index
  158. Returns:
  159. PageableData: the page doc object
  160. """
  161. return self._records[page_id]
  162. def dump_to_file(self, file_path: str):
  163. dir_name = os.path.dirname(file_path)
  164. if dir_name not in ('', '.', '..'):
  165. os.makedirs(dir_name, exist_ok=True)
  166. self._raw_fitz.save(file_path)
  167. def apply(self, proc: Callable, *args, **kwargs):
  168. return proc(self, *args, **kwargs)
  169. def classify(self) -> SupportedPdfParseMethod:
  170. return SupportedPdfParseMethod.OCR
  171. class Doc(PageableData):
  172. """Initialized with pymudoc object."""
  173. def __init__(self, doc: fitz.Page):
  174. self._doc = doc
  175. def get_image(self):
  176. """Return the imge info.
  177. Returns:
  178. dict: {
  179. img: np.ndarray,
  180. width: int,
  181. height: int
  182. }
  183. """
  184. return fitz_doc_to_image(self._doc)
  185. def get_doc(self) -> fitz.Page:
  186. """Get the pymudoc object.
  187. Returns:
  188. fitz.Page: the pymudoc object
  189. """
  190. return self._doc
  191. def get_page_info(self) -> PageInfo:
  192. """Get the page info of the page.
  193. Returns:
  194. PageInfo: the page info of this page
  195. """
  196. page_w = self._doc.rect.width
  197. page_h = self._doc.rect.height
  198. return PageInfo(w=page_w, h=page_h)
  199. def __getattr__(self, name):
  200. if hasattr(self._doc, name):
  201. return getattr(self._doc, name)
  202. def draw_rect(self, rect_coords, color, fill, fill_opacity, width, overlay):
  203. """draw rectangle.
  204. Args:
  205. rect_coords (list[float]): four elements array contain the top-left and bottom-right coordinates, [x0, y0, x1, y1]
  206. color (list[float] | None): three element tuple which descript the RGB of the board line, None means no board line
  207. fill (list[float] | None): fill the board with RGB, None means will not fill with color
  208. fill_opacity (float): opacity of the fill, range from [0, 1]
  209. width (float): the width of board
  210. overlay (bool): fill the color in foreground or background. True means fill in background.
  211. """
  212. self._doc.draw_rect(
  213. rect_coords,
  214. color=color,
  215. fill=fill,
  216. fill_opacity=fill_opacity,
  217. width=width,
  218. overlay=overlay,
  219. )
  220. def insert_text(self, coord, content, fontsize, color):
  221. """insert text.
  222. Args:
  223. coord (list[float]): four elements array contain the top-left and bottom-right coordinates, [x0, y0, x1, y1]
  224. content (str): the text content
  225. fontsize (int): font size of the text
  226. color (list[float] | None): three element tuple which descript the RGB of the board line, None will use the default font color!
  227. """
  228. self._doc.insert_text(coord, content, fontsize=fontsize, color=color)