Passed
Push — upgrade-to-connexion3 ( e417e0...5d7ec9 )
by Juho
09:39 queued 05:10
created

annif._set_tensorflow_loglevel()   A

Complexity

Conditions 1

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 11
nop 0
dl 0
loc 15
rs 9.85
c 0
b 0
f 0
1
#!/usr/bin/env python3
2
3
from __future__ import annotations
4
5
import logging
6
import os
7
import os.path
8
from typing import TYPE_CHECKING
9
10
logging.basicConfig()
11
logger = logging.getLogger("annif")
12
logger.setLevel(level=logging.INFO)
13
14
import annif.backend  # noqa
15
16
if TYPE_CHECKING:
17
    from flask.app import Flask
18
19
20
def create_flask_app(config_name: str | None = None) -> Flask:
21
    """Create a Flask app to be used by the CLI."""
22
    from flask import Flask
23
24
    _set_tensorflow_loglevel()
25
26
    app = Flask(__name__)
27
    config_name = _get_config_name(config_name)
28
    logger.debug(f"creating flask app with configuration {config_name}")
29
    app.config.from_object(config_name)
30
    app.config.from_envvar("ANNIF_SETTINGS", silent=True)
31
    return app
32
33
34
def create_app(config_name: str | None = None) -> Flask:
35
    """Create a Connexion app to be used for the API."""
36
    # 'cxapp' here is the Connexion application that has a normal Flask app
37
    # as a property (cxapp.app)
38
    import connexion
39
    from flask_cors import CORS
40
41
    import annif.registry
42
43
    # from annif.openapi.validation import CustomRequestBodyValidator  # TODO Re-enable
44
45
    specdir = os.path.join(os.path.dirname(__file__), "openapi")
46
    cxapp = connexion.FlaskApp(__name__, specification_dir=specdir)
47
    config_name = _get_config_name(config_name)
48
    logger.debug(f"creating connexion app with configuration {config_name}")
49
    cxapp.app.config.from_object(config_name)
50
    cxapp.app.config.from_envvar("ANNIF_SETTINGS", silent=True)
51
52
    # validator_map = {
53
    #     "body": CustomRequestBodyValidator,
54
    # }
55
    cxapp.add_api("annif.yaml")  # validator_map=validator_map)
56
57
    # add CORS support
58
    CORS(cxapp.app)
59
60
    if cxapp.app.config["INITIALIZE_PROJECTS"]:
61
        annif.registry.initialize_projects(cxapp.app)
62
        logger.info("finished initializing projects")
63
64
    # register the views via blueprints
65
    from annif.views import bp
66
67
    cxapp.app.register_blueprint(bp)
68
69
    # return the Connexion app
70
    return cxapp
71
72
73
def _get_config_name(config_name: str | None) -> str:
74
    if config_name is None:
75
        config_name = os.environ.get("ANNIF_CONFIG")
76
    if config_name is None:
77
        if os.environ.get("FLASK_RUN_FROM_CLI") == "true":  # pragma: no cover
78
            config_name = "annif.default_config.Config"
79
        else:
80
            config_name = "annif.default_config.ProductionConfig"  # pragma: no cover
81
    return config_name
82
83
84
def _set_tensorflow_loglevel():
85
    """Set TensorFlow log level based on Annif log level (--verbosity/-v
86
    option) using an environment variable. INFO messages by TF are shown only on
87
    DEBUG (or NOTSET) level of Annif."""
88
    annif_loglevel = logger.getEffectiveLevel()
89
    tf_loglevel_mapping = {
90
        0: "0",  # NOTSET
91
        10: "0",  # DEBUG
92
        20: "1",  # INFO
93
        30: "1",  # WARNING
94
        40: "2",  # ERROR
95
        50: "3",  # CRITICAL
96
    }
97
    tf_loglevel = tf_loglevel_mapping[annif_loglevel]
98
    os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", tf_loglevel)
99