Skip to content
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

Small refactor for MarkItDown.convert_response function. #168

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
28 changes: 8 additions & 20 deletions src/markitdown/_markitdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -1390,38 +1390,26 @@ def convert_response(
content_disposition = response.headers.get("content-disposition", "")
m = re.search(r"filename=([^;]+)", content_disposition)
if m:
base, ext = os.path.splitext(m.group(1).strip("\"'"))
_, ext = os.path.splitext(m.group(1).strip("\"'"))
self._append_ext(extensions, ext)

# Read from the extension from the path
base, ext = os.path.splitext(urlparse(response.url).path)
_, ext = os.path.splitext(urlparse(response.url).path)
self._append_ext(extensions, ext)

# Save the file locally to a temporary file. It will be deleted before this method exits
handle, temp_path = tempfile.mkstemp()
fh = os.fdopen(handle, "wb")
result = None
try:
with tempfile.NamedTemporaryFile("wb") as temp_file:
# Download the file
for chunk in response.iter_content(chunk_size=512):
fh.write(chunk)
fh.close()
temp_file.write(chunk)
temp_file.flush()

# Use puremagic to check for more extension options
for g in self._guess_ext_magic(temp_path):
for g in self._guess_ext_magic(temp_file.name):
self._append_ext(extensions, g)

# Convert
result = self._convert(temp_path, extensions, url=response.url, **kwargs)
# Clean up
finally:
try:
fh.close()
except Exception:
pass
os.unlink(temp_path)

return result
# Convert and return
return self._convert(temp_file.name, extensions, url=response.url, **kwargs)

def _convert(
self, local_path: str, extensions: List[Union[str, None]], **kwargs
Expand Down