Skip to content

Commit 44ecf6f

Browse files
committed
Changed file loggin optional
1 parent 723df6b commit 44ecf6f

File tree

10 files changed

+81
-57
lines changed

10 files changed

+81
-57
lines changed

src/superannotate/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,4 +239,5 @@ def log_version_info():
239239
)
240240

241241

242-
log_version_info()
242+
if not os.environ.get("SA_VERSION_CHECK", "True").lower() == "false":
243+
log_version_info()

src/superannotate/lib/app/interface/base_interface.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,5 @@ def controller(self):
1212
raise Exception("Config does not exists!")
1313
controller = Controller()
1414
if self._config_path:
15-
controller.init(self._config_path)
15+
controller.init(config_path=self._config_path)
1616
return controller

src/superannotate/lib/app/interface/sdk_interface.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,17 +53,20 @@
5353

5454

5555
@validate_arguments
56-
def init(path_to_config_json: Optional[str] = None):
56+
def init(path_to_config_json: Optional[str] = None, token: str = None):
5757
"""
5858
Initializes and authenticates to SuperAnnotate platform using the config file.
5959
If not initialized then $HOME/.superannotate/config.json
6060
will be used.
6161
6262
:param path_to_config_json: Location to config JSON file
6363
:type path_to_config_json: str or Path
64+
65+
:param token: Team token
66+
:type token: str
6467
"""
6568
global controller
66-
controller.init(path_to_config_json)
69+
controller.init(config_path=path_to_config_json, token=token)
6770

6871

6972
@validate_arguments

src/superannotate/lib/app/interface/types.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from pydantic import validate_arguments as pydantic_validate_arguments
1313
from pydantic import ValidationError
1414
from pydantic.errors import StrRegexError
15-
from superannotate_schemas.schemas.base import ClassTypeEnum
15+
1616

1717
NotEmptyStr = constr(strict=True, min_length=1)
1818

src/superannotate/lib/core/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from superannotate.lib.core.enums import UploadState
1010
from superannotate.lib.core.enums import UserRole
1111

12+
1213
CONFIG_FILE_LOCATION = str(Path.home() / ".superannotate" / "config.json")
1314
LOG_FILE_LOCATION = str(Path.home() / ".superannotate" / "sa.log")
1415
BACKEND_URL = "https://api.annotate.online"

src/superannotate/lib/infrastructure/controller.py

Lines changed: 37 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def get_instance(cls):
5252

5353

5454
class BaseController(metaclass=SingleInstanceMetaClass):
55-
def __init__(self, config_path=constances.CONFIG_FILE_LOCATION, token: str = None):
55+
def __init__(self, config_path: str, token: str = None):
5656
self._team_data = None
5757
self._token = None
5858
self._backend_url = None
@@ -69,36 +69,36 @@ def __init__(self, config_path=constances.CONFIG_FILE_LOCATION, token: str = Non
6969
self._user_id = None
7070
self._team_name = None
7171
self._reporter = None
72-
self._config_path = expanduser(config_path)
73-
self._token, self._backend_url = (
74-
os.environ.get("SA_TOKEN"),
75-
os.environ.get("SA_URL"),
76-
)
72+
self._ssl_verify = not os.environ.get("SA_TESTING", False)
73+
self._config_path = expanduser(config_path) if config_path else constances.CONFIG_FILE_LOCATION
74+
75+
self._backend_url = os.environ.get("SA_URL", constances.BACKEND_URL)
76+
if not token and not config_path:
77+
env_token = os.environ.get("SA_TOKEN")
78+
if env_token:
79+
self._token = self._validate_token(os.environ.get("SA_TOKEN"))
80+
if token:
81+
self._token = self._validate_token(token)
7782

78-
if not self._token and token:
79-
if self._validate_token(token):
80-
self._token = token
81-
else:
82-
raise AppException("Invalid token.")
83-
if not self._token and config_path:
84-
self._token, self._backend_url, ssl_verify = self.retrieve_configs(
85-
Path(config_path), raise_exception=False
83+
if not self._token:
84+
self._token, self._backend_url, self._ssl_verify = self.retrieve_configs(
85+
Path(self._config_path), raise_exception=False
8686
)
8787

8888
def retrieve_configs(
8989
self, path: Path, raise_exception=True
9090
) -> Tuple[Optional[str], Optional[str], Optional[str]]:
91-
if not path.is_file():
91+
if not path.is_file() or not os.access(path, os.R_OK):
9292
if raise_exception:
9393
raise AppException(
9494
f"SuperAnnotate config file {str(path)} not found."
9595
f" Please provide correct config file location to sa.init(<path>) or use "
9696
f"CLI's superannotate init to generate default location config file."
9797
)
9898
try:
99-
config_repo = ConfigRepository(self._config_path)
99+
config_repo = ConfigRepository(str(path))
100100
return (
101-
config_repo.get_one("token").value,
101+
self._validate_token(config_repo.get_one("token").value),
102102
config_repo.get_one("main_endpoint").value,
103103
config_repo.get_one("ssl_verify").value,
104104
)
@@ -110,23 +110,32 @@ def retrieve_configs(
110110
return None, None, None
111111

112112
def init(
113-
self, config_path: str = constances.CONFIG_FILE_LOCATION, token: str = None
113+
self, token: str = None, backend_url: str = None, config_path: str = None,
114114
):
115+
if backend_url:
116+
self._backend_url = backend_url
115117
if token:
116118
if self._validate_token(token):
117119
self._token = token
120+
return self
118121
else:
119122
raise AppException("Invalid token.")
120-
if not token and config_path:
121-
self._config_path = config_path
122-
self._token, self._backend_url, ssl_verify = self.retrieve_configs(
123-
Path(config_path), raise_exception=True
123+
if not config_path:
124+
raise AppException(
125+
" Please provide correct config file location to sa.init(<path>)."
124126
)
125-
self._ssl_verify = False # TODO fix if ssl_verify is False else True
127+
self._config_path = config_path
128+
self._token, self._backend_url, ssl_verify = self.retrieve_configs(
129+
Path(config_path), raise_exception=True
130+
)
131+
self._ssl_verify = ssl_verify
132+
return self
126133

127134
@property
128135
def backend_client(self):
129136
if not self._backend_client:
137+
if not self._token:
138+
raise AppException("Team token not provided")
130139
self._backend_client = SuperannotateBackendService(
131140
api_url=self._backend_url,
132141
auth_token=self._token,
@@ -164,14 +173,12 @@ def _validate_token(token: str):
164173
int(token.split("=")[-1])
165174
except ValueError:
166175
raise AppException("Invalid token.")
176+
return token
167177

168178
def set_token(self, token: str, backend_url: str = constances.BACKEND_URL):
169-
self._validate_token(token)
170-
self._token = token
179+
self._token = self._validate_token(token)
180+
self._backend_url = backend_url
171181
self._backend_client = self.backend_client
172-
self._backend_client._api_url = backend_url
173-
self._backend_client._auth_token = token
174-
self._backend_client.get_session.cache_clear()
175182

176183
@property
177184
def projects(self):
@@ -254,7 +261,8 @@ def annotation_validators(self) -> AnnotationValidators:
254261

255262

256263
class Controller(BaseController):
257-
def __init__(self, config_path=constances.CONFIG_FILE_LOCATION):
264+
265+
def __init__(self, config_path: str = None):
258266
super().__init__(config_path)
259267
self._team = None
260268

src/superannotate/lib/infrastructure/repositories.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,8 @@ def _create_config(self):
4545
return {}
4646

4747
def _get_config(self) -> Optional[dict]:
48-
if not os.path.exists(self.config_path):
49-
return
50-
with open(self.config_path) as config:
51-
return json.load(config)
48+
if os.path.exists(self.config_path):
49+
return json.load(open(self.config_path))
5250

5351
def get_one(self, uuid: str) -> Optional[ConfigEntity]:
5452
config = self._get_config()

src/superannotate/lib/infrastructure/services.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@
1818
from lib.core.service_types import UserLimits
1919
from lib.core.serviceproviders import SuerannotateServiceProvider
2020
from lib.infrastructure.helpers import timed_lru_cache
21-
from pydantic import BaseModel
2221
from requests.exceptions import HTTPError
2322

23+
2424
requests.packages.urllib3.disable_warnings()
2525

2626

src/superannotate/logger.py

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
import logging.config
2+
import os
3+
from logging import Formatter
4+
from logging.handlers import RotatingFileHandler
25
from os.path import expanduser
36

47
from superannotate import constances
58

9+
default_logger = None
10+
11+
log_path = "/Users/vaghinak.basentsyan/private/log.log"
612
logging.config.dictConfig(
713
{
814
"version": 1,
@@ -14,29 +20,35 @@
1420
"formatter": "consoleFormatter",
1521
"stream": "ext://sys.stdout",
1622
},
17-
"fileHandler": {
18-
"class": "logging.handlers.RotatingFileHandler",
19-
"level": "DEBUG",
20-
"formatter": "fileFormatter",
21-
"filename": expanduser(constances.LOG_FILE_LOCATION),
22-
"mode": "a",
23-
"maxBytes": 5 * 1024 * 1024,
24-
"backupCount": 5,
25-
},
2623
},
2724
"formatters": {
2825
"consoleFormatter": {
2926
"format": "SA-PYTHON-SDK - %(levelname)s - %(message)s",
3027
},
31-
"fileFormatter": {
32-
"format": "SA-PYTHON-SDK - %(levelname)s - %(asctime)s - %(message)s"
33-
},
3428
},
35-
"loggers": {"sa": {"handlers": ["console", "fileHandler"], "level": "DEBUG"}},
29+
"loggers": {"sa": {"handlers": ["console"], "level": "DEBUG"}},
3630
}
3731
)
3832

3933

4034
def get_default_logger():
41-
logger = logging.getLogger("sa")
42-
return logger
35+
global default_logger
36+
if not default_logger:
37+
default_logger = logging.getLogger("sa")
38+
try:
39+
log_file_path = expanduser(constances.LOG_FILE_LOCATION)
40+
open(log_file_path, "w").close()
41+
if os.access(log_file_path, os.W_OK):
42+
file_handler = RotatingFileHandler(
43+
expanduser(constances.LOG_FILE_LOCATION),
44+
maxBytes=5 * 1024 * 1024,
45+
backupCount=5,
46+
mode="a"
47+
)
48+
formatter = Formatter("SA-PYTHON-SDK - %(levelname)s - %(asctime)s - %(message)s")
49+
file_handler.setFormatter(formatter)
50+
file_handler.setLevel("DEBUG")
51+
default_logger.addHandler(file_handler)
52+
except OSError:
53+
pass
54+
return default_logger

tests/unit/test_controller_init.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,12 @@ class SKDInitTest(TestCase):
6868
VALID_JSON = {
6969
"token": "a"*28 + "=1234"
7070
}
71-
INVALID_JSON ={
71+
INVALID_JSON = {
7272
"token": "a" * 28 + "=1234asd"
7373
}
7474
FILE_NAME = "config.json"
7575
FILE_NAME_2 = "config.json"
7676

77-
@pytest.mark.skip(reason="Need to adjust")
7877
def test_init_flow(self):
7978
with tempfile.TemporaryDirectory() as temp_dir:
8079
token_path = f"{temp_dir}/config.json"
@@ -84,7 +83,6 @@ def test_init_flow(self):
8483
import src.superannotate as sa
8584
sa.init(token_path)
8685

87-
@pytest.mark.skip(reason="Need to adjust")
8886
def test_init(self):
8987
with tempfile.TemporaryDirectory() as temp_dir:
9088
path = join(temp_dir, self.FILE_NAME)
@@ -93,3 +91,6 @@ def test_init(self):
9391
import src.superannotate as sa
9492
sa.init(path)
9593
self.assertEqual(sa.controller.team_id, 1234)
94+
95+
def test_(self):
96+
import superannotate as sa

0 commit comments

Comments
 (0)