cnn-classification-service/cnn_classification_service/magic_doer.py

50 lines
1.4 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
2020-10-06 00:41:54 +02:00
from classifier_cache import ClassifierCache
2020-10-02 03:59:09 +02:00
2020-07-28 18:10:19 +02:00
2020-10-06 00:41:54 +02:00
class MagicDoer:
classifier_cache = ClassifierCache()
2020-07-28 18:10:19 +02:00
2020-10-06 00:41:54 +02:00
@classmethod
def run_everything(cls, parameters: dict) -> dict:
tag = parameters['tag']
sample_file_handle, sample_file_path = tempfile.mkstemp(prefix=f"{tag}_", suffix=".wav")
try:
2020-07-28 18:10:19 +02:00
2020-10-06 00:41:54 +02:00
# Download Sample
2020-07-28 18:10:19 +02:00
2020-10-06 00:41:54 +02:00
logging.info(f"Downloading sample: {tag}")
r = requests.get(f"http://storage-service/object/{tag}")
with open(sample_file_handle, 'wb') as f:
f.write(r.content)
2020-07-28 18:10:19 +02:00
2020-10-06 00:41:54 +02:00
logging.debug(f"Downloaded sample to {sample_file_path}")
2020-07-28 18:10:19 +02:00
2020-10-06 00:41:54 +02:00
# Get a classifier that uses the default model
model_details, classifier = cls.classifier_cache.get_default_classifier()
2020-07-28 18:10:19 +02:00
2020-10-06 00:41:54 +02:00
# do the majic
results = classifier.predict(sample_file_path)
2020-07-28 18:10:19 +02:00
2020-10-06 00:41:54 +02:00
finally:
try:
os.remove(sample_file_path)
except FileNotFoundError:
pass
2020-07-28 18:10:19 +02:00
2020-10-06 00:41:54 +02:00
response = {
"tag": tag,
"probability": 1.0 if results[0] == model_details['target_class_name'] else 0.0,
"model": model_details['id']
}
2020-07-28 18:10:19 +02:00
2020-10-06 00:41:54 +02:00
logging.info(f"Classification done!")
logging.debug(f"Results: {response}")
2020-07-28 18:10:19 +02:00
2020-10-06 00:41:54 +02:00
return response