Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """Document loader helpers."""
  2. import concurrent.futures
  3. from typing import NamedTuple, Optional, cast
  4. class FileEncoding(NamedTuple):
  5. """A file encoding as the NamedTuple."""
  6. encoding: Optional[str]
  7. """The encoding of the file."""
  8. confidence: float
  9. """The confidence of the encoding."""
  10. language: Optional[str]
  11. """The language of the file."""
  12. def detect_file_encodings(file_path: str, timeout: int = 5, sample_size: int = 1024 * 1024) -> list[FileEncoding]:
  13. """Try to detect the file encoding.
  14. Returns a list of `FileEncoding` tuples with the detected encodings ordered
  15. by confidence.
  16. Args:
  17. file_path: The path to the file to detect the encoding for.
  18. timeout: The timeout in seconds for the encoding detection.
  19. sample_size: The number of bytes to read for encoding detection. Default is 1MB.
  20. For large files, reading only a sample is sufficient and prevents timeout.
  21. """
  22. import chardet
  23. def read_and_detect(file_path: str) -> list[dict]:
  24. with open(file_path, "rb") as f:
  25. # Read only a sample of the file for encoding detection
  26. # This prevents timeout on large files while still providing accurate encoding detection
  27. rawdata = f.read(sample_size)
  28. return cast(list[dict], chardet.detect_all(rawdata))
  29. with concurrent.futures.ThreadPoolExecutor() as executor:
  30. future = executor.submit(read_and_detect, file_path)
  31. try:
  32. encodings = future.result(timeout=timeout)
  33. except concurrent.futures.TimeoutError:
  34. raise TimeoutError(f"Timeout reached while detecting encoding for {file_path}")
  35. if all(encoding["encoding"] is None for encoding in encodings):
  36. raise RuntimeError(f"Could not detect encoding for {file_path}")
  37. return [FileEncoding(**enc) for enc in encodings if enc["encoding"] is not None]