Skip to content

Commit

Permalink
Add mime_type field to ByteStream
Browse files Browse the repository at this point in the history
  • Loading branch information
silvanocerza committed Oct 23, 2023
1 parent 9d8979a commit 3b2f90a
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions haystack/preview/dataclasses/byte_stream.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, Any
from typing import Optional, Dict, Any


@dataclass(frozen=True)
Expand All @@ -11,27 +11,28 @@ class ByteStream:

data: bytes
metadata: Dict[str, Any] = field(default_factory=dict, hash=False)
mime_type: Optional[str] = field(default=None)

def to_file(self, destination_path: Path):
with open(destination_path, "wb") as fd:
fd.write(self.data)

@classmethod
def from_file_path(cls, filepath: Path) -> "ByteStream":
def from_file_path(cls, filepath: Path, mime_type: Optional[str] = None) -> "ByteStream":
"""
Create a ByteStream from the contents read from a file.
:param filepath: A valid path to a file.
"""
with open(filepath, "rb") as fd:
return cls(data=fd.read())
return cls(data=fd.read(), mime_type=mime_type)

@classmethod
def from_string(cls, text: str, encoding: str = "utf-8") -> "ByteStream":
def from_string(cls, text: str, encoding: str = "utf-8", mime_type: Optional[str] = None) -> "ByteStream":
"""
Create a ByteStream encoding a string.
:param text: The string to encode
:param encoding: The encoding used to convert the string into bytes
"""
return cls(data=text.encode(encoding))
return cls(data=text.encode(encoding), mime_type=mime_type)

0 comments on commit 3b2f90a

Please sign in to comment.