-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Allow for EML and MSG parsing / also check+replace if fileName has "#" character #2868
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kachihro
wants to merge
2
commits into
Azure-Samples:main
Choose a base branch
from
kachihro:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+772
−20
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| """ | ||
| Email parser for MSG and EML files. | ||
| Compatible with the prepdocs pipeline structure. | ||
| """ | ||
| import logging | ||
| import email | ||
| from email import policy | ||
| from typing import AsyncGenerator, IO, Union, Optional | ||
| import extract_msg | ||
| from io import BytesIO | ||
| import re | ||
|
|
||
| from .page import Page | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class EmailParser: | ||
| """Parser for EML email files.""" | ||
|
|
||
| async def parse(self, content: IO) -> AsyncGenerator[Page, None]: | ||
| """Parse EML file content.""" | ||
| try: | ||
| # Read bytes from IO object | ||
| content_bytes = content.read() | ||
| # Parse email from bytes | ||
| msg = email.message_from_bytes(content_bytes, policy=policy.default) | ||
|
|
||
| # Extract email metadata and body | ||
| text_parts = [] | ||
|
|
||
| # Add headers | ||
| text_parts.append(f"From: {msg.get('From', 'Unknown')}") | ||
| text_parts.append(f"To: {msg.get('To', 'Unknown')}") | ||
| text_parts.append(f"Subject: {msg.get('Subject', 'No Subject')}") | ||
| text_parts.append(f"Date: {msg.get('Date', 'Unknown')}") | ||
| text_parts.append("\n" + "="*80 + "\n") | ||
|
|
||
| # Extract body | ||
| if msg.is_multipart(): | ||
| for part in msg.walk(): | ||
| content_type = part.get_content_type() | ||
| content_disposition = str(part.get("Content-Disposition", "")) | ||
|
|
||
| # Get text content | ||
| if content_type == "text/plain" and "attachment" not in content_disposition: | ||
| try: | ||
| body = part.get_content() | ||
| text_parts.append(body) | ||
| except Exception as e: | ||
| logger.warning(f"Could not extract text part: {e}") | ||
|
|
||
| elif content_type == "text/html" and "attachment" not in content_disposition: | ||
| # Optionally extract HTML (you may want to strip HTML tags) | ||
| try: | ||
| html_body = part.get_content() | ||
| # Simple HTML tag removal (consider using BeautifulSoup for better results) | ||
| import re | ||
| text_body = re.sub('<[^<]+?>', '', html_body) | ||
| text_parts.append(text_body) | ||
| except Exception as e: | ||
| logger.warning(f"Could not extract HTML part: {e}") | ||
|
|
||
| # Note attachments | ||
| elif "attachment" in content_disposition: | ||
| filename = part.get_filename() | ||
| if filename: | ||
| text_parts.append(f"\n[Attachment: {filename}]") | ||
| else: | ||
| # Single part message | ||
| try: | ||
| body = msg.get_content() | ||
| text_parts.append(body) | ||
| except Exception as e: | ||
| logger.warning(f"Could not extract message body: {e}") | ||
|
|
||
| # Combine all parts | ||
| full_text = "\n".join(text_parts) | ||
|
|
||
| # Return as single page | ||
| yield Page(page_num=0, offset=0, text=full_text) | ||
|
|
||
| except Exception as e: | ||
| logger.error(f"Error parsing EML file: {e}") | ||
| raise ValueError(f"Failed to parse EML file: {e}") | ||
|
|
||
|
|
||
| class MsgParser: | ||
| """Parser for MSG (Outlook) email files.""" | ||
|
|
||
| async def parse(self, content: IO) -> AsyncGenerator[Page, None]: | ||
| """Parse MSG file content.""" | ||
| try: | ||
| # Read bytes from IO object and create BytesIO | ||
| content_bytes = content.read() | ||
| msg_file = BytesIO(content_bytes) | ||
|
|
||
| # Parse MSG file | ||
| msg = extract_msg.Message(msg_file) | ||
|
|
||
| # Extract email metadata and body | ||
| text_parts = [] | ||
|
|
||
| # Add headers | ||
| text_parts.append(f"From: {msg.sender or 'Unknown'}") | ||
| text_parts.append(f"To: {msg.to or 'Unknown'}") | ||
| text_parts.append(f"Subject: {msg.subject or 'No Subject'}") | ||
| text_parts.append(f"Date: {msg.date or 'Unknown'}") | ||
| text_parts.append("\n" + "="*80 + "\n") | ||
|
|
||
| # Add body (prefer plain text over HTML) | ||
| if msg.body: | ||
| text_parts.append(msg.body) | ||
| elif msg.htmlBody: | ||
| # Simple HTML tag removal | ||
| import re | ||
| text_body = re.sub('<[^<]+?>', '', msg.htmlBody) | ||
| text_parts.append(text_body) | ||
|
|
||
| # Note attachments | ||
| if msg.attachments: | ||
| text_parts.append("\n\nAttachments:") | ||
| for attachment in msg.attachments: | ||
| text_parts.append(f" - {attachment.longFilename or attachment.shortFilename}") | ||
|
|
||
| # Combine all parts | ||
| full_text = "\n".join(text_parts) | ||
|
|
||
| # Clean up | ||
| msg.close() | ||
|
|
||
| # Return as single page | ||
| yield Page(page_num=0, offset=0, text=full_text) | ||
|
|
||
| except Exception as e: | ||
| logger.error(f"Error parsing MSG file: {e}") | ||
| raise ValueError(f"Failed to parse MSG file: {e}") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -170,6 +170,28 @@ async def run(self): | |
| files = self.list_file_strategy.list() | ||
| async for file in files: | ||
| try: | ||
| # Check if filename contains # and rename on disk if it does | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We are going to deprecate integratedvectorizerstrategy.py in favor of cloud ingestion strategy only, so no changes should be needed to this file. |
||
| if hasattr(file.content, "name") and "#" in file.filename(): | ||
| original_path = file.content.name | ||
| if os.path.exists(original_path) and os.path.isfile(original_path): | ||
| # Get directory and filename | ||
| directory = os.path.dirname(original_path) | ||
| original_filename = os.path.basename(original_path) | ||
| new_filename = original_filename.replace("#", "_") | ||
| new_path = os.path.join(directory, new_filename) | ||
|
|
||
| # Only rename if the new filename is different | ||
| if new_path != original_path: | ||
| # Close the current file handle | ||
| file.content.close() | ||
|
|
||
| # Rename the file on disk | ||
| os.rename(original_path, new_path) | ||
| logger.info("Renamed file from '%s' to '%s' (replaced # with _)", original_filename, new_filename) | ||
|
|
||
| # Reopen the file with the new name | ||
| file.content = open(new_path, mode="rb") | ||
|
|
||
| await self.blob_manager.upload_blob(file) | ||
| finally: | ||
| if file: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -31,3 +31,4 @@ python-dotenv | |
| prompty | ||
| rich | ||
| typing-extensions | ||
| extract-msg | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please run pre-commit on all files to fix formatting, see CONTRIBUTING.md for instructions.