dataset.py 11 KB

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