|
| 1 | +import email |
| 2 | +from typing import Dict, Final, IO, List, Optional |
| 3 | + |
| 4 | +from unstructured.cleaners.core import replace_mime_encodings |
| 5 | +from unstructured.documents.elements import Element, Text |
| 6 | +from unstructured.partition.html import partition_html |
| 7 | + |
| 8 | + |
| 9 | +VALID_CONTENT_SOURCES: Final[List[str]] = ["text/html"] |
| 10 | + |
| 11 | + |
| 12 | +def partition_email( |
| 13 | + filename: Optional[str] = None, |
| 14 | + file: Optional[IO] = None, |
| 15 | + text: Optional[str] = None, |
| 16 | + content_source: str = "text/html", |
| 17 | +) -> List[Element]: |
| 18 | + """Partitions an .eml documents into its constituent elements. |
| 19 | + Parameters |
| 20 | + ---------- |
| 21 | + filename |
| 22 | + A string defining the target filename path. |
| 23 | + file |
| 24 | + A file-like object using "r" mode --> open(filename, "r"). |
| 25 | + text |
| 26 | + The string representation of the .eml document. |
| 27 | + """ |
| 28 | + if content_source not in VALID_CONTENT_SOURCES: |
| 29 | + raise ValueError( |
| 30 | + f"{content_source} is not a valid value for content_source. " |
| 31 | + f"Valid content sources are: {VALID_CONTENT_SOURCES}" |
| 32 | + ) |
| 33 | + |
| 34 | + if not any([filename, file, text]): |
| 35 | + raise ValueError("One of filename, file, or text must be specified.") |
| 36 | + |
| 37 | + if filename is not None and not file and not text: |
| 38 | + with open(filename, "r") as f: |
| 39 | + msg = email.message_from_file(f) |
| 40 | + |
| 41 | + elif file is not None and not filename and not text: |
| 42 | + file_text = file.read() |
| 43 | + msg = email.message_from_string(file_text) |
| 44 | + |
| 45 | + elif text is not None and not filename and not file: |
| 46 | + _text: str = str(text) |
| 47 | + msg = email.message_from_string(_text) |
| 48 | + |
| 49 | + else: |
| 50 | + raise ValueError("Only one of filename, file, or text can be specified.") |
| 51 | + |
| 52 | + content_map: Dict[str, str] = { |
| 53 | + part.get_content_type(): part.get_payload() for part in msg.walk() |
| 54 | + } |
| 55 | + |
| 56 | + content = content_map.get(content_source, "") |
| 57 | + if not content: |
| 58 | + raise ValueError("text/html content not found in email") |
| 59 | + |
| 60 | + # NOTE(robinson) - In the .eml files, the HTML content gets stored in a format that |
| 61 | + # looks like the following, resulting in extraneous "=" chracters in the output if |
| 62 | + # you don't clean it up |
| 63 | + # <ul> = |
| 64 | + # <li>Item 1</li>= |
| 65 | + # <li>Item 2<li>= |
| 66 | + # </ul> |
| 67 | + content = "".join(content.split("=\n")) |
| 68 | + |
| 69 | + elements = partition_html(text=content) |
| 70 | + for element in elements: |
| 71 | + if isinstance(element, Text): |
| 72 | + element.apply(replace_mime_encodings) |
| 73 | + |
| 74 | + return elements |
0 commit comments