Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## 0.27.32-dev0

### Enhancements

- **Read spooled uploads in place during file detection and partitioning, leaving spooled files at position 0. Generic file-like streams handled by `convert_to_bytes()` are rewound before and after reading; existing BytesIO and path-named buffered-reader cursor behavior is unchanged.**

## 0.27.31

### Fixes
Expand Down
65 changes: 65 additions & 0 deletions test_unstructured/file_utils/test_filetype.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import json
import os
import shutil
import tempfile
from pathlib import Path

import pytest

Expand Down Expand Up @@ -508,6 +510,54 @@ def test_it_detects_EMPTY_from_empty_file_like_object():
assert detect_filetype(file=f) == FileType.EMPTY


@pytest.mark.parametrize("max_size", [0, 1])
def test_it_detects_a_SpooledTemporaryFile_in_place_and_rewinds_it(max_size: int):
with open(example_doc_path("simple.docx"), "rb") as f:
content = f.read()

with tempfile.SpooledTemporaryFile(max_size=max_size) as spooled_file:
spooled_file.write(content)
spooled_file.seek(0)

with patch.object(
_FileTypeDetectionContext, "new", wraps=_FileTypeDetectionContext.new
) as new_:
file_type = detect_filetype(file=spooled_file)

assert file_type == FileType.DOCX
assert new_.call_args.kwargs["file"] is spooled_file
assert spooled_file.tell() == 0


def test_it_uses_metadata_file_path_extension_for_a_rolled_over_SpooledTemporaryFile():
with tempfile.SpooledTemporaryFile(max_size=1) as spooled_file:
spooled_file.write(b"# Heading\n\nSome *markdown* text.\n")
assert spooled_file._rolled

assert detect_filetype(file=spooled_file, metadata_file_path="notes.md") == FileType.MD


def test_it_ignores_the_temporary_file_name_of_a_rolled_over_SpooledTemporaryFile():
# -- on Windows a rolled-over spool is named by its temporary file, never the upload --
with tempfile.SpooledTemporaryFile(max_size=1) as spooled_file:
spooled_file.write(b"# Heading\n\nSome *markdown* text.\n")
spooled_file.seek(0)
named = tempfile.NamedTemporaryFile(suffix=".tmp") # noqa: SIM115 - closed by the spool
named.write(spooled_file.read())
spooled_file._file.close() # pyright: ignore[reportPrivateUsage]
spooled_file._file = named # pyright: ignore[reportPrivateUsage]
assert spooled_file.name.endswith(".tmp")

assert detect_filetype(file=spooled_file, metadata_file_path="notes.md") == FileType.MD


def test_it_preserves_a_path_like_stream_name_extension():
file = io.BytesIO(b"# Heading\n\nSome *markdown* text.\n")
file.name = Path("notes.md")

assert detect_filetype(file=file) == FileType.MD


def test_it_detect_CSV_from_path_and_file_when_content_contains_escaped_commas():
file_path = example_doc_path("csv-with-escaped-commas.csv")

Expand Down Expand Up @@ -1001,6 +1051,14 @@ def and_it_returns_the_empty_string_as_the_extension_when_there_are_no_file_name

assert _FileTypeDetectionContext(file=file).extension == ""

def and_it_ignores_a_file_name_that_is_not_a_string(self):
with tempfile.SpooledTemporaryFile(max_size=1) as spooled_file:
spooled_file.write(b"<html></html>")

ctx = _FileTypeDetectionContext(file=spooled_file, metadata_file_path="a/b/c.html")

assert ctx.extension == ".html"

# -- .file_head ---------------------------------------------

def it_grabs_the_first_8k_bytes_of_the_file_for_use_by_magic(self):
Expand Down Expand Up @@ -1427,3 +1485,10 @@ def test_office_files_when_document_archive_has_non_standard_prefix():
file_path=input_path("file_type/test_document_from_office365.docx")
)
assert predicted_type == FileType.DOCX


@pytest.mark.parametrize("name", ["temporary-upload", Path("temporary-upload"), 42, None])
def test_extensionless_stream_names_fall_back_to_metadata_file_path(name):
file = io.BytesIO(b"# Heading\n\nSome *markdown* text.\n")
file.name = name
assert detect_filetype(file=file, metadata_file_path="notes.md") == FileType.MD
122 changes: 122 additions & 0 deletions test_unstructured/partition/common/test_common.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import io
import logging
import os
import pathlib
from multiprocessing import Pool
from tempfile import SpooledTemporaryFile, TemporaryFile

import numpy as np
import pytest
Expand Down Expand Up @@ -30,6 +33,125 @@
from unstructured.partition.common import common


def test_rewind_if_spooled_rewinds_without_copying():
with SpooledTemporaryFile(max_size=1, mode="w+b") as spooled_file:
spooled_file.write(b"sample content")

result = common.rewind_if_spooled(spooled_file)

assert result is spooled_file
assert result.tell() == 0
assert result.read() == b"sample content"


@pytest.mark.parametrize("max_size", [0, 1])
def test_convert_to_bytes_reads_a_SpooledTemporaryFile_and_rewinds_it(max_size: int):
with SpooledTemporaryFile(max_size=max_size) as spooled_file:
spooled_file.write(b"sample content")

assert common.convert_to_bytes(spooled_file) == b"sample content"
assert spooled_file.tell() == 0


def test_convert_to_bytes_reads_any_seekable_binary_stream_and_rewinds_it():
with TemporaryFile() as file:
file.write(b"sample content")

assert common.convert_to_bytes(file) == b"sample content"
assert file.tell() == 0


def test_convert_to_bytes_reads_a_BufferedReader_without_a_path_name():
file = io.BufferedReader(io.BytesIO(b"sample content"))

assert common.convert_to_bytes(file) == b"sample content"
assert file.tell() == 0


def test_convert_to_bytes_leaves_a_BufferedReader_over_a_file_descriptor_open():
with TemporaryFile() as tmp:
tmp.write(b"sample content")
tmp.flush()
file = io.BufferedReader(io.FileIO(tmp.fileno(), "rb", closefd=False))

assert common.convert_to_bytes(file) == b"sample content"
assert file.tell() == 0
assert not tmp.closed
os.fstat(tmp.fileno())


@pytest.mark.parametrize("mode", ["rb", "r"])
def test_convert_to_bytes_reads_a_file_opened_by_bytes_path_without_moving_it(
tmp_path: pathlib.Path, mode: str
):
path = tmp_path / "sample.txt"
path.write_bytes(b"sample content")

with open(os.fsencode(path), mode) as file:
file.read(3)
position = file.tell()

assert common.convert_to_bytes(file) == b"sample content" # pyright: ignore[reportArgumentType]
assert file.tell() == position


@pytest.mark.parametrize("text", [False, True])
def test_convert_to_bytes_reads_a_file_named_by_a_path_object_without_moving_it(
tmp_path: pathlib.Path, text: bool
):
path = tmp_path / "sample.txt"
path.write_bytes(b"sample content")
reader = io.BufferedReader(io.FileIO(path))
file = io.TextIOWrapper(reader, encoding="utf-8") if text else reader

with file:
file.read(3)
position = file.tell()

assert common.convert_to_bytes(file) == b"sample content" # pyright: ignore[reportArgumentType]
assert file.tell() == position


@pytest.mark.parametrize("mode", ["rb", "r"])
def test_convert_to_bytes_reads_a_pipe_that_cannot_seek(mode: str):
read_fd, write_fd = os.pipe()
with os.fdopen(write_fd, "wb") as writer:
writer.write(b"sample content")

with os.fdopen(read_fd, mode) as file:
assert common.convert_to_bytes(file) == b"sample content" # pyright: ignore[reportArgumentType]


def test_convert_to_bytes_keeps_text_already_buffered_from_a_text_pipe():
read_fd, write_fd = os.pipe()
with os.fdopen(write_fd, "wb") as writer:
writer.write("sample content, café".encode("utf-8"))

with os.fdopen(read_fd, "r", encoding="utf-8") as file:
assert file.read(1) == "s"

assert common.convert_to_bytes(file) == "ample content, café".encode("utf-8") # pyright: ignore[reportArgumentType]


def test_convert_to_bytes_reads_bytes_from_a_text_file_opened_on_a_descriptor(
tmp_path: pathlib.Path,
):
path = tmp_path / "sample.txt"
path.write_bytes(b"sample content")

with os.fdopen(os.open(path, os.O_RDONLY), "r", encoding="utf-8") as file:
file.read(3)

assert common.convert_to_bytes(file) == b"sample content" # pyright: ignore[reportArgumentType]
assert file.tell() == 0
assert file.read() == "sample content"


def test_convert_to_bytes_raises_for_an_object_that_is_not_a_seekable_stream():
with pytest.raises(ValueError, match="Invalid file-like object type"):
common.convert_to_bytes(object()) # pyright: ignore[reportArgumentType]


class MockPageLayout(layout.PageLayout):
def __init__(self, number: int, image: Image.Image):
self.number = number
Expand Down
6 changes: 3 additions & 3 deletions test_unstructured/partition/test_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -1493,15 +1493,15 @@ def test_auto_partition_preserves_attachment_filetype_when_container_filename_is
assert all(e.metadata.filetype == FileType.TXT.mime_type for e in attachment_elements)


def test_detect_filetype_maps_file_to_bytes_io_when_spooled_temp_file_used(mocker):
def test_detect_filetype_reads_a_spooled_temp_file_in_place(mocker):
detect_filetype_mock = MagicMock(return_value=FileType.JSON)
mocker.patch("unstructured.file_utils.filetype._FileTypeDetector", detect_filetype_mock)
with tempfile.SpooledTemporaryFile() as f:
f.write(b'{"text": Hello, world!}')
f.seek(0)
detect_filetype(file=f)
file_detection_context = detect_filetype_mock.file_type.call_args[0][0]
assert file_detection_context.text_head == '{"text": Hello, world!}'
file_detection_context = detect_filetype_mock.file_type.call_args[0][0]
assert file_detection_context.text_head == '{"text": Hello, world!}'


# -- .languages -----------------------------------------------------------
Expand Down
9 changes: 3 additions & 6 deletions test_unstructured/partition/test_docx.py
Original file line number Diff line number Diff line change
Expand Up @@ -2320,19 +2320,16 @@ def it_uses_the_path_to_open_the_presentation_when_file_path_is_provided(

assert opts._docx_file == "l/m/n.docx"

def and_it_uses_a_BytesIO_file_to_replaces_a_SpooledTemporaryFile_provided(
self, opts_args: dict[str, Any]
):
def and_it_uses_a_SpooledTemporaryFile_directly(self, opts_args: dict[str, Any]):
with tempfile.SpooledTemporaryFile() as spooled_temp_file:
spooled_temp_file.write(b"abcdefg")
opts_args["file"] = spooled_temp_file
opts = DocxPartitionerOptions(**opts_args)

docx_file = opts._docx_file

assert docx_file is not spooled_temp_file
assert isinstance(docx_file, io.BytesIO)
assert docx_file.getvalue() == b"abcdefg"
assert docx_file is spooled_temp_file
assert docx_file.read() == b"abcdefg"

def and_it_uses_the_provided_file_directly_when_not_a_SpooledTemporaryFile(
self, opts_args: dict[str, Any]
Expand Down
9 changes: 3 additions & 6 deletions test_unstructured/partition/test_pptx.py
Original file line number Diff line number Diff line change
Expand Up @@ -704,19 +704,16 @@ def it_uses_the_path_to_open_the_presentation_when_file_path_is_provided(

assert opts.pptx_file == "l/m/n.pptx"

def and_it_uses_a_BytesIO_file_to_replaces_a_SpooledTemporaryFile_provided(
self, opts_args: dict[str, Any]
):
def and_it_uses_a_SpooledTemporaryFile_directly(self, opts_args: dict[str, Any]):
with tempfile.SpooledTemporaryFile() as spooled_temp_file:
spooled_temp_file.write(b"abcdefg")
opts_args["file"] = spooled_temp_file
opts = PptxPartitionerOptions(**opts_args)

pptx_file = opts.pptx_file

assert pptx_file is not spooled_temp_file
assert isinstance(pptx_file, io.BytesIO)
assert pptx_file.getvalue() == b"abcdefg"
assert pptx_file is spooled_temp_file
assert pptx_file.read() == b"abcdefg"

def and_it_uses_the_provided_file_directly_when_not_a_SpooledTemporaryFile(
self, opts_args: dict[str, Any]
Expand Down
2 changes: 1 addition & 1 deletion unstructured/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.27.31" # pragma: no cover
__version__ = "0.27.32-dev0" # pragma: no cover
26 changes: 16 additions & 10 deletions unstructured/file_utils/filetype.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
import contextlib
import functools
import importlib.util
import io
import json
import os
import re
Expand Down Expand Up @@ -101,19 +100,19 @@ def detect_filetype(
filesystem.
- Neither `file_path` nor `file` were specified.
"""
file_buffer = file
if isinstance(file, tempfile.SpooledTemporaryFile):
file_buffer = io.BytesIO(file.read())
file.seek(0)

ctx = _FileTypeDetectionContext.new(
file_path=file_path,
file=file_buffer,
file=file,
encoding=encoding,
content_type=content_type,
metadata_file_path=metadata_file_path,
)
return _FileTypeDetector.file_type(ctx)
try:
return _FileTypeDetector.file_type(ctx)
finally:
# -- a spooled upload is inspected in place and is returned at read position 0 --
if isinstance(file, tempfile.SpooledTemporaryFile):
file.seek(0)


def is_json_processable(
Expand Down Expand Up @@ -511,8 +510,15 @@ def extension(self) -> str:
"""Best filename-extension we can muster, "" when there is no available source."""
# -- get from file_path, or file when it has a name (path) --
with self.open() as file:
if hasattr(file, "name") and file.name:
return os.path.splitext(file.name)[1].lower()
# -- a temporary file can have an integer file-descriptor as its name, which carries
# -- no extension, and a spool is named by its temporary file, never by the document.
if (
not isinstance(file, tempfile.SpooledTemporaryFile)
and isinstance(name := getattr(file, "name", None), (str, os.PathLike))
and name
and (extension := os.path.splitext(name)[1].lower())
):
return extension

# -- otherwise use metadata file-path when provided --
if file_path := self._metadata_file_path:
Expand Down
Loading
Loading