cnn-classification-service/cnn_classification_service/magic_doer.py

68 lines
1.8 KiB
Python
Raw Normal View History

2020-07-28 18:10:19 +02:00
#!/usr/bin/env python3
import os
import logging
import tempfile
import requests
from cnn_classifier import Classifier
def run_everything(parameters: dict):
tag = parameters['tag']
2020-10-01 16:13:58 +02:00
sample_file_handle, sample_file_path = tempfile.mkstemp(prefix=f"{tag}_", suffix=".wav")
model_file_handle, model_file_path = tempfile.mkstemp(suffix=".json")
weights_file_handle, weights_file_path = tempfile.mkstemp(suffix=".h5")
2020-07-28 18:10:19 +02:00
try:
logging.info(f"Downloading sample: {tag}")
r = requests.get(f"http://storage-service/object/{tag}")
2020-10-01 16:13:58 +02:00
with open(sample_file_handle, 'wb') as f:
2020-07-28 18:10:19 +02:00
f.write(r.content)
2020-10-01 16:13:58 +02:00
logging.debug(f"Downloaded sample to {sample_file_path}")
2020-07-28 18:10:19 +02:00
r = requests.get(f"http://model-service/model/cnn/$default")
r.raise_for_status()
2020-10-01 16:13:58 +02:00
with open(model_file_handle, 'wb') as f:
2020-07-28 18:10:19 +02:00
f.write(r.content)
r = requests.get(f"http://model-service/model/cnn/$default?weights")
r.raise_for_status()
2020-10-01 16:13:58 +02:00
with open(weights_file_handle, 'wb') as f:
2020-07-28 18:10:19 +02:00
f.write(r.content)
# magic happens here
2020-10-01 16:13:58 +02:00
classifier = Classifier(model_file_path, weights_file_path)
results = classifier.predict(sample_file_path)
2020-07-28 18:10:19 +02:00
finally: # bruuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuh
try:
2020-10-01 16:13:58 +02:00
os.remove(model_file_path)
2020-07-28 18:10:19 +02:00
except FileNotFoundError:
pass
try:
2020-10-01 16:13:58 +02:00
os.remove(weights_file_path)
2020-07-28 18:10:19 +02:00
except FileNotFoundError:
pass
try:
2020-10-01 16:13:58 +02:00
os.remove(sample_file_path)
2020-07-28 18:10:19 +02:00
except FileNotFoundError:
pass
response = {
"tag": tag,
"probability": 1.0 if results[0] == 'sturnus' else 0.0,
2020-09-18 00:47:05 +02:00
"model": "TODO"
2020-07-28 18:10:19 +02:00
}
logging.info(f"Classification done!")
logging.debug(f"Results: {response}")
return response