Skip to content
Open
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
8 changes: 7 additions & 1 deletion haystack/components/routers/document_type_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,15 @@ def run(self, documents: list[Document]) -> dict[str, list[Document]]:
mime_type = doc.meta.get(self.mime_type_meta_field) if self.mime_type_meta_field else None
file_path = doc.meta.get(self.file_path_meta_field) if self.file_path_meta_field else None

if not isinstance(mime_type, str):
mime_type = None

if mime_type is None and file_path:
# if mime_type is not provided, try to guess it from the file path
mime_type = _guess_mime_type(Path(file_path))
try:
mime_type = _guess_mime_type(Path(file_path))
except (TypeError, ValueError):
mime_type = None

matched = False
if mime_type:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
fixes:
- |
``DocumentTypeRouter`` now routes documents whose MIME metadata is not a string to ``unclassified``,
instead of raising ``TypeError`` inside ``re.fullmatch``.
29 changes: 29 additions & 0 deletions test/components/routers/test_document_type_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,35 @@ def test_run_with_missing_metadata(self):
assert len(result["unclassified"]) == 3
assert "text/plain" not in result

def test_run_with_non_string_mime_type_metadata(self):
docs = [
Document(content="List mime", meta={"mime_type": ["text/plain"]}),
Document(content="Int mime", meta={"mime_type": 123}),
Document(content="None mime", meta={"mime_type": None}),
Document(content="Valid mime", meta={"mime_type": "text/plain"}),
]

router = DocumentTypeRouter(mime_type_meta_field="mime_type", mime_types=["text/plain"])
result = router.run(documents=docs)

assert len(result["text/plain"]) == 1
assert result["text/plain"][0].content == "Valid mime"
assert len(result["unclassified"]) == 3

def test_run_with_non_string_file_path_metadata(self):
docs = [
Document(content="List path", meta={"file_path": ["example.txt"]}),
Document(content="Int path", meta={"file_path": 123}),
Document(content="Valid path", meta={"file_path": "example.txt"}),
]

router = DocumentTypeRouter(file_path_meta_field="file_path", mime_types=["text/plain"])
result = router.run(documents=docs)

assert len(result["text/plain"]) == 1
assert result["text/plain"][0].content == "Valid path"
assert len(result["unclassified"]) == 2

def test_run_with_regex_patterns(self):
docs = [
Document(content="Plain text", meta={"mime_type": "text/plain"}),
Expand Down
Loading