ext.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import hashlib
  2. import mimetypes
  3. def is_pdf(filename, file):
  4. """
  5. 判断文件是否为PDF格式。
  6. :param filename: 文件名
  7. :param file: 文件对象
  8. :return: 如果文件是PDF格式,则返回True,否则返回False
  9. """
  10. # 检查文件扩展名 https://arxiv.org/pdf/2405.08702 pdf链接可能存在不带扩展名的情况,先注释
  11. if not filename.endswith('.pdf'):
  12. return False
  13. # 检查MIME类型
  14. mime_type, _ = mimetypes.guess_type(filename)
  15. print(mime_type)
  16. if mime_type != 'application/pdf':
  17. return False
  18. # 可选:读取文件的前几KB内容并检查MIME类型
  19. # 这一步是可选的,用于更严格的检查
  20. # if not mimetypes.guess_type(filename, strict=False)[0] == 'application/pdf':
  21. # return False
  22. # 检查文件内容
  23. file_start = file.read(5)
  24. file.seek(0)
  25. if not file_start.startswith(b'%PDF-'):
  26. return False
  27. return True
  28. def url_is_pdf(file):
  29. """
  30. 判断文件是否为PDF格式。
  31. :param file: 文件对象
  32. :return: 如果文件是PDF格式,则返回True,否则返回False
  33. """
  34. # 检查文件内容
  35. file_start = file.read(5)
  36. file.seek(0)
  37. if not file_start.startswith(b'%PDF-'):
  38. return False
  39. return True
  40. def calculate_file_hash(file, algorithm='sha256'):
  41. """
  42. 计算给定文件的哈希值。
  43. :param file: 文件对象
  44. :param algorithm: 哈希算法的名字,如:'sha256', 'md5', 'sha1'等
  45. :return: 文件的哈希值
  46. """
  47. hash_func = getattr(hashlib, algorithm)()
  48. block_size = 65536 # 64KB chunks
  49. # with open(file_path, 'rb') as file:
  50. buffer = file.read(block_size)
  51. while len(buffer) > 0:
  52. hash_func.update(buffer)
  53. buffer = file.read(block_size)
  54. file.seek(0)
  55. return hash_func.hexdigest()
  56. def singleton_func(cls):
  57. instance = {}
  58. def _singleton(*args, **kwargs):
  59. if cls not in instance:
  60. instance[cls] = cls(*args, **kwargs)
  61. return instance[cls]
  62. return _singleton