test_commons.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import io
  2. import json
  3. import os
  4. import boto3
  5. from botocore.config import Config
  6. from magic_pdf.libs.commons import fitz
  7. from magic_pdf.libs.config_reader import get_s3_config_dict
  8. from magic_pdf.libs.commons import join_path, json_dump_path, read_file, parse_bucket_key
  9. from loguru import logger
  10. test_pdf_dir_path = "s3://llm-pdf-text/unittest/pdf/"
  11. def get_test_pdf_json(book_name):
  12. json_path = join_path(json_dump_path, book_name + ".json")
  13. s3_config = get_s3_config_dict(json_path)
  14. file_content = read_file(json_path, s3_config)
  15. json_str = file_content.decode('utf-8')
  16. json_object = json.loads(json_str)
  17. return json_object
  18. def read_test_file(book_name):
  19. test_pdf_path = join_path(test_pdf_dir_path, book_name + ".pdf")
  20. s3_config = get_s3_config_dict(test_pdf_path)
  21. try:
  22. file_content = read_file(test_pdf_path, s3_config)
  23. return file_content
  24. except Exception as e:
  25. if "NoSuchKey" in str(e):
  26. logger.warning("File not found in test_pdf_path. Downloading from orig_s3_pdf_path.")
  27. try:
  28. json_object = get_test_pdf_json(book_name)
  29. orig_s3_pdf_path = json_object.get('file_location')
  30. s3_config = get_s3_config_dict(orig_s3_pdf_path)
  31. file_content = read_file(orig_s3_pdf_path, s3_config)
  32. s3_client = get_s3_client(test_pdf_path)
  33. bucket_name, bucket_key = parse_bucket_key(test_pdf_path)
  34. file_obj = io.BytesIO(file_content)
  35. s3_client.upload_fileobj(file_obj, bucket_name, bucket_key)
  36. return file_content
  37. except Exception as e:
  38. logger.exception(e)
  39. else:
  40. logger.exception(e)
  41. def get_docs_from_test_pdf(book_name):
  42. file_content = read_test_file(book_name)
  43. return fitz.open("pdf", file_content)
  44. def get_test_json_data(directory_path, json_file_name):
  45. with open(os.path.join(directory_path, json_file_name), "r", encoding='utf-8') as f:
  46. test_data = json.load(f)
  47. return test_data
  48. def get_s3_client(path):
  49. s3_config = get_s3_config_dict(path)
  50. try:
  51. return boto3.client(
  52. "s3",
  53. aws_access_key_id=s3_config["ak"],
  54. aws_secret_access_key=s3_config["sk"],
  55. endpoint_url=s3_config["endpoint"],
  56. config=Config(s3={"addressing_style": "path"}, retries={"max_attempts": 8, "mode": "standard"}),
  57. )
  58. except:
  59. # older boto3 do not support retries.mode param.
  60. return boto3.client(
  61. "s3",
  62. aws_access_key_id=s3_config["ak"],
  63. aws_secret_access_key=s3_config["sk"],
  64. endpoint_url=s3_config["endpoint"],
  65. config=Config(s3={"addressing_style": "path"}, retries={"max_attempts": 8}),
  66. )