cnn-classification-service/cnn_classification_service/magic_doer.py

60 lines
1.9 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
2021-06-14 03:14:58 +02:00
import time
2020-07-28 18:10:19 +02:00
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")
2021-06-14 03:12:44 +02:00
response = None
2020-10-06 00:41:54 +02:00
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
2021-06-14 03:14:58 +02:00
classification_start_time = time.time()
2021-06-14 03:12:44 +02:00
predicted_class_name, labeled_predictions = classifier.predict(sample_file_path)
2021-06-14 03:14:58 +02:00
classification_duration = time.time() - classification_start_time
2021-06-14 03:12:44 +02:00
response = {
"tag": tag,
"probability": labeled_predictions[model_details['target_class_name']],
"all_predictions": labeled_predictions,
"class": predicted_class_name,
2021-06-14 03:14:58 +02:00
"model": model_details['id'],
"classification_duration": classification_duration
2021-06-14 03:12:44 +02:00
}
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
2021-06-14 03:12:44 +02:00
if not response:
logging.error("Something went wrong during classification!")
else:
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