-
Notifications
You must be signed in to change notification settings - Fork 453
Add Microsoft OneDrive DOCX/Markdown conversion functions #548
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
jiwei-aipolabs
wants to merge
1
commit into
main
Choose a base branch
from
microsoft_docs_integration
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.
Open
Changes from all commits
Commits
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
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 |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| import csv | ||
| import io | ||
| import tempfile | ||
| from typing import override | ||
|
|
||
| import requests | ||
|
|
@@ -161,3 +162,189 @@ def create_excel_from_csv( | |
| except Exception as e: | ||
| logger.error(f"Failed to create CSV file from CSV data: {e}") | ||
| raise Exception(f"Failed to create CSV file: {e}") from e | ||
|
|
||
| def create_docx_from_markdown( | ||
| self, markdown_data: str, parent_folder_id: str, filename: str | None = None | ||
| ) -> dict[str, str | int]: | ||
| """ | ||
| Convert Markdown text to a formatted DOCX document and save it to OneDrive. | ||
| Uses the md2docx-python library for robust conversion. | ||
|
|
||
| Args: | ||
| markdown_data: The Markdown text as a string to convert | ||
| parent_folder_id: The identifier of the parent folder where the DOCX file will be created | ||
| filename: Optional custom name for the DOCX file (without .docx extension) | ||
|
|
||
| Returns: | ||
| dict: Response containing the created DOCX file metadata | ||
| """ | ||
| logger.info(f"Creating DOCX file from Markdown on OneDrive, folder: {parent_folder_id}") | ||
|
|
||
| try: | ||
| from md2docx_python.src.md2docx_python import markdown_to_word | ||
|
|
||
| # Determine filename | ||
| if not filename: | ||
| filename = "converted_document" | ||
|
|
||
| # Ensure .docx extension | ||
| if not filename.endswith(".docx"): | ||
| filename += ".docx" | ||
|
|
||
| # Create temporary files for conversion | ||
| with tempfile.NamedTemporaryFile(mode="w", suffix=".md", delete=False) as md_file: | ||
| md_file.write(markdown_data) | ||
| md_file_path = md_file.name | ||
|
|
||
| with tempfile.NamedTemporaryFile(suffix=".docx", delete=False) as docx_file: | ||
| docx_file_path = docx_file.name | ||
|
|
||
| try: | ||
| # Convert markdown to DOCX using the well-maintained library | ||
| markdown_to_word(md_file_path, docx_file_path) | ||
|
|
||
| # Read the generated DOCX file | ||
| with open(docx_file_path, "rb") as docx_file: | ||
| docx_bytes = docx_file.read() | ||
|
|
||
| # Upload DOCX file to OneDrive | ||
| upload_url = ( | ||
| f"{self.base_url}/me/drive/items/{parent_folder_id}:/{filename}:/content" | ||
| ) | ||
|
|
||
| headers = { | ||
| "Authorization": f"Bearer {self.access_token}", | ||
| "Content-Type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", | ||
| } | ||
|
|
||
| upload_response = requests.put( | ||
| upload_url, headers=headers, data=docx_bytes, timeout=60 | ||
| ) | ||
| upload_response.raise_for_status() | ||
|
|
||
| result = upload_response.json() | ||
|
|
||
| # Count some basic stats for the response | ||
| lines = markdown_data.split("\n") | ||
| word_count = len(markdown_data.split()) | ||
|
|
||
| logger.info( | ||
| f"Successfully created DOCX file: {filename}, ID: {result.get('id', '')}" | ||
| ) | ||
|
|
||
| return { | ||
| "id": result.get("id", ""), | ||
| "name": result.get("name", ""), | ||
| "path": result.get("parentReference", {}).get("path", "") | ||
| + "/" | ||
| + result.get("name", ""), | ||
| "size": result.get("size", 0), | ||
| "mime_type": result.get("file", {}).get("mimeType", ""), | ||
| "created_datetime": result.get("createdDateTime", ""), | ||
| "modified_datetime": result.get("lastModifiedDateTime", ""), | ||
| "download_url": result.get("@microsoft.graph.downloadUrl", ""), | ||
| "lines_converted": len(lines), | ||
| "word_count": word_count, | ||
| "note": "DOCX file created successfully from Markdown using md2docx-python library.", | ||
| } | ||
|
|
||
| finally: | ||
| # Clean up temporary files | ||
| import os | ||
|
|
||
| try: | ||
| os.unlink(md_file_path) | ||
| os.unlink(docx_file_path) | ||
| except OSError: | ||
| pass # Files already cleaned up | ||
|
|
||
| except Exception as e: | ||
| logger.error(f"Failed to create DOCX file from Markdown data: {e}") | ||
| raise Exception(f"Failed to create DOCX file: {e}") from e | ||
|
|
||
| def read_markdown_from_docx(self, item_id: str) -> dict[str, str | int]: | ||
| """ | ||
| Convert a DOCX file from OneDrive to Markdown text. | ||
| Uses the md2docx-python library for robust conversion. | ||
|
|
||
| Args: | ||
| item_id: The identifier of the DOCX file in OneDrive to convert | ||
|
|
||
| Returns: | ||
| dict: Response containing the markdown content and metadata | ||
| """ | ||
| logger.info(f"Converting DOCX file to Markdown from OneDrive: {item_id}") | ||
|
|
||
| try: | ||
| from md2docx_python.src.docx2md_python import word_to_markdown | ||
|
|
||
| # Download the DOCX file from OneDrive | ||
| download_url = f"{self.base_url}/me/drive/items/{item_id}/content" | ||
| headers = {"Authorization": f"Bearer {self.access_token}"} | ||
|
|
||
| download_response = requests.get(download_url, headers=headers, timeout=30) | ||
| download_response.raise_for_status() | ||
|
|
||
| # Get file metadata for response details | ||
| metadata_url = f"{self.base_url}/me/drive/items/{item_id}" | ||
| metadata_response = requests.get(metadata_url, headers=headers, timeout=30) | ||
| metadata_response.raise_for_status() | ||
| metadata = metadata_response.json() | ||
|
|
||
| # Verify it's a DOCX file | ||
| if not metadata.get("name", "").lower().endswith((".docx", ".doc")): | ||
| raise Exception(f"File '{metadata.get('name', '')}' is not a Word document") | ||
|
|
||
| # Create temporary files for conversion | ||
| with tempfile.NamedTemporaryFile(suffix=".docx", delete=False) as docx_file: | ||
| docx_file.write(download_response.content) | ||
| docx_file_path = docx_file.name | ||
|
|
||
| with tempfile.NamedTemporaryFile(mode="w", suffix=".md", delete=False) as md_file: | ||
| md_file_path = md_file.name | ||
|
|
||
| try: | ||
| # Convert DOCX to Markdown using the well-maintained library | ||
| word_to_markdown(docx_file_path, md_file_path) | ||
|
|
||
| # Read the generated Markdown file | ||
| with open(md_file_path, encoding="utf-8") as md_file: | ||
| markdown_content = md_file.read() | ||
|
|
||
| # Count some basic stats for the response | ||
| lines = markdown_content.split("\n") | ||
| word_count = len(markdown_content.split()) | ||
|
|
||
| logger.info( | ||
| f"Successfully converted DOCX to Markdown: {item_id}, {len(markdown_content)} characters" | ||
| ) | ||
|
|
||
| return { | ||
| "content": markdown_content, | ||
| "id": metadata.get("id", ""), | ||
| "name": metadata.get("name", ""), | ||
| "path": metadata.get("parentReference", {}).get("path", "") | ||
| + "/" | ||
| + metadata.get("name", ""), | ||
| "size": metadata.get("size", 0), | ||
| "mime_type": metadata.get("file", {}).get("mimeType", ""), | ||
| "created_datetime": metadata.get("createdDateTime", ""), | ||
| "modified_datetime": metadata.get("lastModifiedDateTime", ""), | ||
| "lines_extracted": len(lines), | ||
| "word_count": word_count, | ||
| "note": "DOCX file successfully converted to Markdown using md2docx-python library.", | ||
| } | ||
|
|
||
| finally: | ||
| # Clean up temporary files | ||
| import os | ||
|
|
||
| try: | ||
| os.unlink(docx_file_path) | ||
| os.unlink(md_file_path) | ||
| except OSError: | ||
| pass # Files already cleaned up | ||
|
|
||
| except Exception as e: | ||
| logger.error(f"Failed to convert DOCX file to Markdown: {item_id}, error: {e}") | ||
| raise Exception(f"Failed to convert DOCX file: {e}") from e | ||
|
Comment on lines
+265
to
+350
Contributor
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. 🛠️ Refactor suggestion Refactor duplicate code patterns This method has the same issues as
Consider extracting the temporary file cleanup logic into a helper method: def _cleanup_temp_files(self, *file_paths: str) -> None:
"""Clean up temporary files, logging any errors."""
for file_path in file_paths:
try:
os.unlink(file_path)
except OSError as e:
logger.debug(f"Failed to clean up temporary file {file_path}: {e}")Then use it in both methods: finally:
- # Clean up temporary files
- import os
-
- try:
- os.unlink(docx_file_path)
- os.unlink(md_file_path)
- except OSError:
- pass # Files already cleaned up
+ self._cleanup_temp_files(docx_file_path, md_file_path)🤖 Prompt for AI Agents |
||
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
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.
💡 Verification agent
🧩 Analysis chain
Move imports to module level and verify import paths
Several issues with imports and code organization:
md2docx_python.src.md2docx_pythonseems unusual - typically src directories are not part of the import pathosmodule is imported inside the finally block but should be at module levelApply this refactor to move imports to module level:
And update the method to remove internal imports:
- from md2docx_python.src.md2docx_python import markdown_to_word # Determine filenamefinally: # Clean up temporary files - import os - try:🏁 Script executed:
Length of output: 412
Ensure module-level imports and correct md2docx-python dependency
The inline import and unusual path for the md2docx-python library will break at runtime (the package isn’t found in your environment). Please:
md2docx-pythonto your project’s dependencies (e.g. requirements.txt or pyproject.toml) so it can be installed.from md2docx_python.src.md2docx_python import markdown_to_wordinsidecreate_docx_from_markdownand theimport osin thefinallyblock.These changes will prevent import errors, follow best practices, and make the code easier to maintain.
🤖 Prompt for AI Agents