|
| 1 | +"""Flask app with /health and /predict endpoint.""" |
| 2 | + |
| 3 | +import importlib.util |
| 4 | +import logging |
| 5 | +import os |
| 6 | +import sys |
| 7 | +import traceback |
| 8 | + |
| 9 | +from flask import Flask, request |
| 10 | + |
| 11 | + |
| 12 | +# Get logging and debugging settings from environment variables |
| 13 | +LOG_LEVEL = os.environ.get("LOG_LEVEL", logging.INFO) |
| 14 | +MODEL_DIR = os.environ.get("MODEL_DIR", "/opt/ds/model/deployed_model") |
| 15 | +FLASK_DEBUG = os.environ.get("FLASK_DEBUG", False) |
| 16 | + |
| 17 | + |
| 18 | +def set_log_level(the_logger: logging.Logger, log_level=None): |
| 19 | + """Sets the log level of a logger based on the environment variable. |
| 20 | + This will also set the log level of logging.lastResort. |
| 21 | + """ |
| 22 | + if not log_level: |
| 23 | + return the_logger |
| 24 | + try: |
| 25 | + the_logger.setLevel(log_level) |
| 26 | + logging.lastResort.setLevel(log_level) |
| 27 | + the_logger.info(f"Log level set to {log_level}") |
| 28 | + except Exception: |
| 29 | + # Catching all exceptions here |
| 30 | + # Setting log level should not interrupt the job run even if there is an exception. |
| 31 | + the_logger.warning("Failed to set log level.") |
| 32 | + the_logger.debug(traceback.format_exc()) |
| 33 | + return the_logger |
| 34 | + |
| 35 | + |
| 36 | +def import_from_path(file_path, module_name="score"): |
| 37 | + """Imports a module from file path.""" |
| 38 | + spec = importlib.util.spec_from_file_location(module_name, file_path) |
| 39 | + module = importlib.util.module_from_spec(spec) |
| 40 | + sys.modules[module_name] = module |
| 41 | + spec.loader.exec_module(module) |
| 42 | + return module |
| 43 | + |
| 44 | + |
| 45 | +logger = logging.getLogger(__name__) |
| 46 | +set_log_level(logger, LOG_LEVEL) |
| 47 | + |
| 48 | +score = import_from_path(os.path.join(MODEL_DIR, "score.py")) |
| 49 | +app = Flask(__name__) |
| 50 | + |
| 51 | + |
| 52 | +@app.route("/health") |
| 53 | +def health(): |
| 54 | + """Health check.""" |
| 55 | + return {"status": "success"} |
| 56 | + |
| 57 | + |
| 58 | +@app.route("/predict", methods=["POST"]) |
| 59 | +def predict(): |
| 60 | + """Make prediction.""" |
| 61 | + payload = request.get_data() |
| 62 | + results = score.predict(payload) |
| 63 | + return results |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + app.run(debug=FLASK_DEBUG, host="0.0.0.0", port=8080) |
0 commit comments