doc_analyze_by_custom_model.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import fitz
  2. import cv2
  3. from PIL import Image
  4. import numpy as np
  5. from magic_pdf.model.model_list import MODEL
  6. from magic_pdf.model.pp_structure_v2 import CustomPaddleModel
  7. def dict_compare(d1, d2):
  8. return d1.items() == d2.items()
  9. def remove_duplicates_dicts(lst):
  10. unique_dicts = []
  11. for dict_item in lst:
  12. if not any(
  13. dict_compare(dict_item, existing_dict) for existing_dict in unique_dicts
  14. ):
  15. unique_dicts.append(dict_item)
  16. return unique_dicts
  17. def load_images_from_pdf(pdf_bytes: bytes, dpi=200) -> list:
  18. images = []
  19. with fitz.open("pdf", pdf_bytes) as doc:
  20. for index in range(0, doc.page_count):
  21. page = doc[index]
  22. mat = fitz.Matrix(dpi / 72, dpi / 72)
  23. pm = page.get_pixmap(matrix=mat, alpha=False)
  24. # if width or height > 2000 pixels, don't enlarge the image
  25. # if pm.width > 2000 or pm.height > 2000:
  26. # pm = page.get_pixmap(matrix=fitz.Matrix(1, 1), alpha=False)
  27. img = Image.frombytes("RGB", [pm.width, pm.height], pm.samples)
  28. img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
  29. img_dict = {"img": img, "width": pm.width, "height": pm.height}
  30. images.append(img_dict)
  31. return images
  32. def doc_analyze(pdf_bytes: bytes, ocr: bool = False, show_log: bool = False, model=MODEL.Paddle):
  33. images = load_images_from_pdf(pdf_bytes)
  34. custom_model = None
  35. if model == MODEL.Paddle:
  36. custom_model = CustomPaddleModel(ocr=ocr, show_log=show_log)
  37. else:
  38. pass
  39. model_json = []
  40. for index, img_dict in enumerate(images):
  41. img = img_dict["img"]
  42. page_width = img_dict["width"]
  43. page_height = img_dict["height"]
  44. result = custom_model(img)
  45. page_info = {"page_no": index, "height": page_height, "width": page_width}
  46. page_dict = {"layout_dets": result, "page_info": page_info}
  47. model_json.append(page_dict)
  48. return model_json