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

Write downloaded model files atomically #3247

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,7 @@
- Akihiro Yamazaki <https://github.com/zakkie>
- Ron Urbach <https://github.com/sharpblade4>
- Vivek Kalyan <https://github.com/vivekkalyan>
- Rimvydas Naktinis <https://github.com/naktinis>

## Others whose work we've taken and included in NLTK, but who didn't directly contribute it:

Expand Down
8 changes: 7 additions & 1 deletion nltk/downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@
import shutil
import subprocess
import sys
import tempfile
import textwrap
import threading
import time
Expand Down Expand Up @@ -704,7 +705,9 @@ def _download_package(self, info, download_dir, force):
yield ProgressMessage(5)
try:
infile = urlopen(info.url)
with open(filepath, "wb") as outfile:
with tempfile.NamedTemporaryFile(
"wb", dir=download_dir, delete=False
) as outfile:
num_blocks = max(1, info.size / (1024 * 16))
for block in itertools.count():
s = infile.read(1024 * 16) # 16k blocks.
Expand All @@ -713,6 +716,9 @@ def _download_package(self, info, download_dir, force):
break
if block % 2 == 0: # how often?
yield ProgressMessage(min(80, 5 + 75 * (block / num_blocks)))
outfile.flush()
os.fsync(outfile.fileno())
os.replace(outfile.name, filepath)
infile.close()
except OSError as e:
yield ErrorMessage(
Expand Down