dataset.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. pass
  105. class PymuDocDataset(Dataset):
  106. def __init__(self, bits: bytes, lang=None):
  107. """Initialize the dataset, which wraps the pymudoc documents.
  108. Args:
  109. bits (bytes): the bytes of the pdf
  110. """
  111. self._raw_fitz = fitz.open('pdf', bits)
  112. self._records = [Doc(v) for v in self._raw_fitz]
  113. self._data_bits = bits
  114. self._raw_data = bits
  115. if lang == '':
  116. self._lang = None
  117. elif lang == 'auto':
  118. from magic_pdf.model.sub_modules.language_detection.utils import \
  119. 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. return PymuDocDataset(self._raw_data)
  177. def set_images(self, images):
  178. for i in range(len(self._records)):
  179. self._records[i].set_image(images[i])
  180. class ImageDataset(Dataset):
  181. def __init__(self, bits: bytes):
  182. """Initialize the dataset, which wraps the pymudoc documents.
  183. Args:
  184. bits (bytes): the bytes of the photo which will be converted to pdf first. then converted to pymudoc.
  185. """
  186. pdf_bytes = fitz.open(stream=bits).convert_to_pdf()
  187. self._raw_fitz = fitz.open('pdf', pdf_bytes)
  188. self._records = [Doc(v) for v in self._raw_fitz]
  189. self._raw_data = bits
  190. self._data_bits = pdf_bytes
  191. def __len__(self) -> int:
  192. """The length of the dataset."""
  193. return len(self._records)
  194. def __iter__(self) -> Iterator[PageableData]:
  195. """Yield the page object."""
  196. return iter(self._records)
  197. def supported_methods(self):
  198. """The method supported by this dataset.
  199. Returns:
  200. list[SupportedPdfParseMethod]: the supported methods
  201. """
  202. return [SupportedPdfParseMethod.OCR]
  203. def data_bits(self) -> bytes:
  204. """The pdf bits used to create this dataset."""
  205. return self._data_bits
  206. def get_page(self, page_id: int) -> PageableData:
  207. """The page doc object.
  208. Args:
  209. page_id (int): the page doc index
  210. Returns:
  211. PageableData: the page doc object
  212. """
  213. return self._records[page_id]
  214. def dump_to_file(self, file_path: str):
  215. """Dump the file.
  216. Args:
  217. file_path (str): the file path
  218. """
  219. dir_name = os.path.dirname(file_path)
  220. if dir_name not in ('', '.', '..'):
  221. os.makedirs(dir_name, exist_ok=True)
  222. self._raw_fitz.save(file_path)
  223. def apply(self, proc: Callable, *args, **kwargs):
  224. """Apply callable method which.
  225. Args:
  226. proc (Callable): invoke proc as follows:
  227. proc(dataset, *args, **kwargs)
  228. Returns:
  229. Any: return the result generated by proc
  230. """
  231. return proc(self, *args, **kwargs)
  232. def classify(self) -> SupportedPdfParseMethod:
  233. """classify the dataset.
  234. Returns:
  235. SupportedPdfParseMethod: _description_
  236. """
  237. return SupportedPdfParseMethod.OCR
  238. def clone(self):
  239. """clone this dataset."""
  240. return ImageDataset(self._raw_data)
  241. def set_images(self, images):
  242. for i in range(len(self._records)):
  243. self._records[i].set_image(images[i])
  244. class Doc(PageableData):
  245. """Initialized with pymudoc object."""
  246. def __init__(self, doc: fitz.Page):
  247. self._doc = doc
  248. self._img = None
  249. def get_image(self):
  250. """Return the image info.
  251. Returns:
  252. dict: {
  253. img: np.ndarray,
  254. width: int,
  255. height: int
  256. }
  257. """
  258. if self._img is None:
  259. self._img = fitz_doc_to_image(self._doc)
  260. return self._img
  261. def set_image(self, img):
  262. """
  263. Args:
  264. img (np.ndarray): the image
  265. """
  266. if self._img is None:
  267. self._img = img
  268. def get_doc(self) -> fitz.Page:
  269. """Get the pymudoc object.
  270. Returns:
  271. fitz.Page: the pymudoc object
  272. """
  273. return self._doc
  274. def get_page_info(self) -> PageInfo:
  275. """Get the page info of the page.
  276. Returns:
  277. PageInfo: the page info of this page
  278. """
  279. page_w = self._doc.rect.width
  280. page_h = self._doc.rect.height
  281. return PageInfo(w=page_w, h=page_h)
  282. def __getattr__(self, name):
  283. if hasattr(self._doc, name):
  284. return getattr(self._doc, name)
  285. def draw_rect(self, rect_coords, color, fill, fill_opacity, width, overlay):
  286. """draw rectangle.
  287. Args:
  288. rect_coords (list[float]): four elements array contain the top-left and bottom-right coordinates, [x0, y0, x1, y1]
  289. color (list[float] | None): three element tuple which describe the RGB of the board line, None means no board line
  290. fill (list[float] | None): fill the board with RGB, None means will not fill with color
  291. fill_opacity (float): opacity of the fill, range from [0, 1]
  292. width (float): the width of board
  293. overlay (bool): fill the color in foreground or background. True means fill in background.
  294. """
  295. self._doc.draw_rect(
  296. rect_coords,
  297. color=color,
  298. fill=fill,
  299. fill_opacity=fill_opacity,
  300. width=width,
  301. overlay=overlay,
  302. )
  303. def insert_text(self, coord, content, fontsize, color):
  304. """insert text.
  305. Args:
  306. coord (list[float]): four elements array contain the top-left and bottom-right coordinates, [x0, y0, x1, y1]
  307. content (str): the text content
  308. fontsize (int): font size of the text
  309. color (list[float] | None): three element tuple which describe the RGB of the board line, None will use the default font color!
  310. """
  311. self._doc.insert_text(coord, content, fontsize=fontsize, color=color)