test_commons.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import io
  2. import json
  3. import os
  4. from magic_pdf.libs.commons import fitz
  5. from app.common.s3 import get_s3_config, get_s3_client
  6. from magic_pdf.libs.commons import join_path, json_dump_path, read_file, parse_bucket_key
  7. from loguru import logger
  8. test_pdf_dir_path = "s3://llm-pdf-text/unittest/pdf/"
  9. def get_test_pdf_json(book_name):
  10. json_path = join_path(json_dump_path, book_name + ".json")
  11. s3_config = get_s3_config(json_path)
  12. file_content = read_file(json_path, s3_config)
  13. json_str = file_content.decode('utf-8')
  14. json_object = json.loads(json_str)
  15. return json_object
  16. def read_test_file(book_name):
  17. test_pdf_path = join_path(test_pdf_dir_path, book_name + ".pdf")
  18. s3_config = get_s3_config(test_pdf_path)
  19. try:
  20. file_content = read_file(test_pdf_path, s3_config)
  21. return file_content
  22. except Exception as e:
  23. if "NoSuchKey" in str(e):
  24. logger.warning("File not found in test_pdf_path. Downloading from orig_s3_pdf_path.")
  25. try:
  26. json_object = get_test_pdf_json(book_name)
  27. orig_s3_pdf_path = json_object.get('file_location')
  28. s3_config = get_s3_config(orig_s3_pdf_path)
  29. file_content = read_file(orig_s3_pdf_path, s3_config)
  30. s3_client = get_s3_client(test_pdf_path)
  31. bucket_name, bucket_key = parse_bucket_key(test_pdf_path)
  32. file_obj = io.BytesIO(file_content)
  33. s3_client.upload_fileobj(file_obj, bucket_name, bucket_key)
  34. return file_content
  35. except Exception as e:
  36. logger.exception(e)
  37. else:
  38. logger.exception(e)
  39. def get_docs_from_test_pdf(book_name):
  40. file_content = read_test_file(book_name)
  41. return fitz.open("pdf", file_content)
  42. def get_test_json_data(directory_path, json_file_name):
  43. with open(os.path.join(directory_path, json_file_name), "r", encoding='utf-8') as f:
  44. test_data = json.load(f)
  45. return test_data