Fixed tmp file usage

This commit is contained in:
Pünkösd Marcell 2020-10-01 16:13:58 +02:00
parent b3770a6de9
commit 28833f0f12

View File

@ -10,48 +10,48 @@ from cnn_classifier import Classifier
def run_everything(parameters: dict): def run_everything(parameters: dict):
tag = parameters['tag'] tag = parameters['tag']
_, file_path = tempfile.mkstemp(prefix=f"{tag}_", suffix=".wav") sample_file_handle, sample_file_path = tempfile.mkstemp(prefix=f"{tag}_", suffix=".wav")
_, temp_model_name = tempfile.mkstemp(suffix=".json") model_file_handle, model_file_path = tempfile.mkstemp(suffix=".json")
_, temp_weights_name = tempfile.mkstemp(suffix=".h5") weights_file_handle, weights_file_path = tempfile.mkstemp(suffix=".h5")
try: try:
logging.info(f"Downloading sample: {tag}") logging.info(f"Downloading sample: {tag}")
r = requests.get(f"http://storage-service/object/{tag}") r = requests.get(f"http://storage-service/object/{tag}")
with open(file_path, 'wb') as f: with open(sample_file_handle, 'wb') as f:
f.write(r.content) f.write(r.content)
logging.debug(f"Downloaded sample to {file_path}") logging.debug(f"Downloaded sample to {sample_file_path}")
r = requests.get(f"http://model-service/model/cnn/$default") r = requests.get(f"http://model-service/model/cnn/$default")
r.raise_for_status() r.raise_for_status()
with open(temp_model_name, 'wb') as f: with open(model_file_handle, 'wb') as f:
f.write(r.content) f.write(r.content)
r = requests.get(f"http://model-service/model/cnn/$default?weights") r = requests.get(f"http://model-service/model/cnn/$default?weights")
r.raise_for_status() r.raise_for_status()
with open(temp_weights_name, 'wb') as f: with open(weights_file_handle, 'wb') as f:
f.write(r.content) f.write(r.content)
# magic happens here # magic happens here
classifier = Classifier(temp_model_name, temp_weights_name) classifier = Classifier(model_file_path, weights_file_path)
results = classifier.predict(file_path) results = classifier.predict(sample_file_path)
finally: # bruuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuh finally: # bruuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuh
try: try:
os.remove(temp_model_name) os.remove(model_file_path)
except FileNotFoundError: except FileNotFoundError:
pass pass
try: try:
os.remove(temp_weights_name) os.remove(weights_file_path)
except FileNotFoundError: except FileNotFoundError:
pass pass
try: try:
os.remove(file_path) os.remove(sample_file_path)
except FileNotFoundError: except FileNotFoundError:
pass pass