atomict 0.1.2__py3-none-any.whl → 0.1.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. atomict/__init__.py +1 -1
  2. atomict/__version__.py +1 -0
  3. atomict/api.py +182 -0
  4. atomict/auth.py +47 -0
  5. atomict/cli/commands/adsorbate.py +183 -0
  6. atomict/cli/commands/ai_assist.py +111 -0
  7. atomict/cli/commands/catalysis.py +171 -0
  8. atomict/cli/commands/common.py +57 -0
  9. atomict/cli/commands/exploration/__init__.py +7 -0
  10. atomict/cli/commands/exploration/soec.py +564 -0
  11. atomict/cli/commands/exploration/sqs.py +440 -0
  12. atomict/cli/commands/helpers.py +74 -0
  13. atomict/cli/commands/k8s.py +211 -0
  14. atomict/cli/commands/login.py +34 -0
  15. atomict/cli/commands/organization.py +76 -0
  16. atomict/cli/commands/project.py +876 -0
  17. atomict/cli/commands/simulation/__init__.py +20 -0
  18. atomict/cli/commands/simulation/catalysis.py +223 -0
  19. atomict/cli/commands/simulation/fhiaims.py +279 -0
  20. atomict/cli/commands/simulation/kpoint.py +380 -0
  21. atomict/cli/commands/simulation/vibes.py +161 -0
  22. atomict/cli/commands/simulation.py +176 -0
  23. atomict/cli/commands/task.py +181 -0
  24. atomict/cli/commands/upload.py +84 -0
  25. atomict/cli/commands/user.py +201 -0
  26. atomict/cli/core/client.py +202 -0
  27. atomict/cli/core/config.py +43 -0
  28. atomict/cli/core/utils.py +32 -0
  29. atomict/cli/main.py +124 -0
  30. atomict/env.py +79 -0
  31. atomict/exceptions.py +12 -0
  32. atomict/infra/distwork/environment.py +26 -0
  33. atomict/infra/distwork/task.py +49 -0
  34. atomict/infra/logging.py +22 -0
  35. atomict/io/cif.py +131 -0
  36. atomict/io/fhiaims.py +24 -0
  37. atomict/io/json.py +22 -0
  38. atomict/io/utils.py +11 -0
  39. atomict/ml/__init__.py +0 -0
  40. atomict/ml/model.py +13 -0
  41. atomict/project/__init__.py +1 -0
  42. atomict/project/link.py +26 -0
  43. atomict/project/note.py +18 -0
  44. atomict/project/project.py +32 -0
  45. atomict/project/tags.py +48 -0
  46. atomict/project/workbench.py +6 -0
  47. atomict/reality/__init__.py +0 -0
  48. atomict/reality/oqmd.py +5 -0
  49. atomict/reality/slabs.py +5 -0
  50. atomict/simulation/__init__.py +0 -0
  51. atomict/simulation/cantera.py +35 -0
  52. atomict/simulation/catalysis.py +20 -0
  53. atomict/simulation/counterfactual.py +28 -0
  54. atomict/simulation/ea.py +64 -0
  55. atomict/simulation/fhi_aims.py +72 -0
  56. atomict/simulation/kpoint.py +74 -0
  57. atomict/simulation/mlrelax.py +83 -0
  58. atomict/simulation/phonon.py +12 -0
  59. atomict/simulation/qe.py +74 -0
  60. atomict/simulation/sqs.py +24 -0
  61. atomict/simulation/utils.py +83 -0
  62. atomict/user/__init__.py +0 -0
  63. atomict/user/files.py +31 -0
  64. atomict/user/workspace.py +112 -0
  65. atomict/utils/fhiaims/__init__.py +0 -0
  66. atomict/utils/fhiaims/geometry.py +65 -0
  67. atomict/utils/tenacity.py +36 -0
  68. {atomict-0.1.2.dist-info → atomict-0.1.4.dist-info}/LICENSE +0 -0
  69. atomict-0.1.4.dist-info/METADATA +105 -0
  70. atomict-0.1.4.dist-info/RECORD +77 -0
  71. {atomict-0.1.2.dist-info → atomict-0.1.4.dist-info}/WHEEL +1 -1
  72. atomict-0.1.4.dist-info/entry_points.txt +2 -0
  73. {atomict-0.1.2.dist-info → atomict-0.1.4.dist-info}/top_level.txt +0 -1
  74. atomict/__main__.py +0 -3
  75. atomict/cli.py +0 -59
  76. atomict/datasets/__init__.py +0 -25
  77. atomict/datasets/io.py +0 -47
  78. atomict/datasets/public.py +0 -32
  79. atomict/utils/requests.py +0 -19
  80. atomict/version.py +0 -2
  81. atomict-0.1.2.dist-info/METADATA +0 -97
  82. atomict-0.1.2.dist-info/RECORD +0 -19
  83. atomict-0.1.2.dist-info/entry_points.txt +0 -2
  84. tests/test_sdk.py +0 -16
  85. /atomict/{auth → cli}/__init__.py +0 -0
  86. /atomict/{utils → infra}/__init__.py +0 -0
  87. {tests → atomict/infra/distwork}/__init__.py +0 -0
  88. /tests/test_cli.py → /atomict/io/__init__.py +0 -0
@@ -0,0 +1,202 @@
1
+ # cli/core/client.py
2
+ import logging
3
+ import os
4
+ import sys
5
+ from functools import wraps
6
+ from typing import Any, Dict, Iterator, List, Optional, Union
7
+
8
+ import httpx
9
+ from rich.console import Console
10
+
11
+ from .config import Config
12
+
13
+ console = Console(stderr=True)
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def handle_connection_errors(func):
18
+ @wraps(func)
19
+ def wrapper(*args, **kwargs):
20
+ try:
21
+ return func(*args, **kwargs)
22
+ except (httpx.ConnectError, httpx.ReadError, httpx.ReadTimeout) as e:
23
+ console.print(
24
+ "[red]Connection error: Unable to communicate with the server.[/red]"
25
+ )
26
+ console.print(
27
+ "[white]Make sure the server is running and accessible.[/white]"
28
+ )
29
+ logger.error(f"Connection error: {str(e)}")
30
+ sys.exit(1)
31
+
32
+ return wrapper
33
+
34
+
35
+ class APIClient:
36
+ def __init__(self, config: Config = None, base_url: str = "https://api.atomictessellator.com"):
37
+ self.base_url = os.getenv("AT_SERVER", base_url)
38
+ self.params = {"limit": 20}
39
+ self.client = httpx.Client(base_url=self.base_url, timeout=30.0)
40
+ self.username = None
41
+ self.password = None
42
+ self._token = None
43
+ if config and config.username and config.password:
44
+ self.username = config.username
45
+ self.password = config.password
46
+ if config and config.token:
47
+ self.set_token(config.token)
48
+
49
+ def set_token(self, token: str):
50
+ """Set bearer token"""
51
+ self._token = token
52
+ self.client.headers["Authorization"] = f"Token {token}"
53
+
54
+ def _handle_response(self, response: httpx.Response) -> Union[List, Dict[str, Any]]:
55
+ """Handle API response and common status codes"""
56
+ try:
57
+ response.raise_for_status()
58
+ if response.request.method in ("DELETE", "HEAD", "TRACE"):
59
+ # no JSON returned
60
+ return
61
+ return response.json()
62
+ except httpx.ConnectError as e:
63
+ console.print(
64
+ "[red]Unable to connect to the server. Please check if the server is running and accessible.[/red]"
65
+ )
66
+ logger.debug(f"Connection error: {str(e)}")
67
+ sys.exit(1)
68
+ except httpx.ReadError as e:
69
+ console.print(
70
+ "[red]Connection lost while communicating with the server.[/red]"
71
+ )
72
+ logger.debug(f"Read error: {str(e)}")
73
+ sys.exit(1)
74
+ except httpx.HTTPStatusError as e:
75
+ error_data = {}
76
+ try:
77
+ error_data = e.response.json()
78
+ except ValueError:
79
+ pass
80
+
81
+ # TODO: standardize error message responses
82
+ if isinstance(error_data, dict):
83
+ error_message = error_data.get("errors", e.response.text)
84
+ elif isinstance(error_data, list):
85
+ error_message = ", ".join(error_data)
86
+ else:
87
+ error_message = ""
88
+
89
+ if e.response.status_code == 400:
90
+ console.print("[red]Invalid request. Please check your input.[/red]")
91
+ if isinstance(error_message, dict):
92
+ for field, errors in error_message.items():
93
+ console.print(f"[red] {field}: {', '.join(errors)}[/red]")
94
+ elif e.response.status_code == 401:
95
+ console.print(
96
+ "[red]Authentication failed. Please check your credentials/env variables or log in again.[/red]"
97
+ )
98
+ elif e.response.status_code == 403:
99
+ console.print(
100
+ "[red]Permission denied. You don't have access to this resource.[/red]"
101
+ )
102
+ console.print(f"[white]{error_data}")
103
+ elif e.response.status_code == 404:
104
+ console.print(
105
+ "[red]Resource not found. Please check the ID or path.[/red]"
106
+ )
107
+ elif e.response.status_code == 429:
108
+ console.print("[red]Too many requests. Please try again later.[/red]")
109
+ elif e.response.status_code >= 500:
110
+ console.print(
111
+ "[red]Server error. Please try again later or contact support.[/red]"
112
+ )
113
+
114
+ logger.debug(f"Server error response: {error_data}")
115
+ sys.exit(1)
116
+
117
+ @handle_connection_errors
118
+ def get(self, path: str, params: Optional[Dict] = None) -> Dict[str, Any]:
119
+ """Make GET request"""
120
+ params = {**self.params, **params} if params else self.params
121
+ response = self.client.get(path, params=params)
122
+ return self._handle_response(response)
123
+
124
+ @handle_connection_errors
125
+ def post(self, path: str, data: Dict) -> Dict[str, Any]:
126
+ """Make POST request"""
127
+ response = self.client.post(path, json=data)
128
+ return self._handle_response(response)
129
+
130
+ @handle_connection_errors
131
+ def put(self, path: str, data: Dict) -> Dict[str, Any]:
132
+ """Make PUT request"""
133
+ response = self.client.put(path, json=data)
134
+ return self._handle_response(response)
135
+
136
+ @handle_connection_errors
137
+ def delete(self, path: str) -> None:
138
+ """Make DELETE request"""
139
+ response = self.client.delete(path)
140
+ self._handle_response(response)
141
+
142
+ @handle_connection_errors
143
+ def patch(self, path: str, data: Dict) -> Dict[str, Any]:
144
+ """Make PATCH request"""
145
+ response = self.client.patch(path, json=data)
146
+ return self._handle_response(response)
147
+
148
+ @handle_connection_errors
149
+ def auth(self, username: Union[str, None] = None, password: Union[str, None] = None) -> None:
150
+ """ Login via username and password """
151
+ return self.post("api-auth/", {"username": username or self.username, "password": password or self.password})
152
+
153
+ @handle_connection_errors
154
+ def paginate(
155
+ self, path: str, params: Optional[Dict] = None
156
+ ) -> Iterator[Dict[str, Any]]:
157
+ """Handle paginated responses"""
158
+ params = params or {}
159
+ while path:
160
+ response = self.get(path, params)
161
+ if isinstance(response, list):
162
+ raise RuntimeError(
163
+ "Not supported. Please contact support with this error."
164
+ )
165
+ elif isinstance(response, dict):
166
+ for result in response.get("results", []):
167
+ yield result
168
+ path = response.get("next")
169
+ # If there's a next page, convert full URL back to path
170
+ if path:
171
+ path = path.replace(self.base_url, "")
172
+ params = {} # Clear params for subsequent requests
173
+ else:
174
+ break
175
+
176
+ def get_all(self, path: str, params: Optional[Dict] = None) -> List[Dict[str, Any]]:
177
+ """Get all results from a paginated endpoint"""
178
+ return list(self.paginate(path, params))
179
+
180
+
181
+ def get_client() -> APIClient:
182
+ """Get a configured API client instance"""
183
+ config = Config()
184
+ client = APIClient(config=config)
185
+
186
+ if client._token:
187
+ return client
188
+
189
+ config.ensure_auth()
190
+ client.set_auth(config.username, config.password)
191
+ response = client.auth()
192
+ token = response.get("token")
193
+ if token:
194
+ config.save_token(token)
195
+ client.set_token(token)
196
+ else:
197
+ console.print(
198
+ "[red]✗ Failed to authenticate (no token returned). Please check your credentials and/or environment variables.[/red]"
199
+ )
200
+ sys.exit(1)
201
+
202
+ return client
@@ -0,0 +1,43 @@
1
+ # cli/core/config.py
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Optional
6
+
7
+ import click
8
+ from rich.prompt import Prompt
9
+
10
+ CONFIG_DIR = Path.home() / ".config" / "atomict"
11
+ CONFIG_FILE = CONFIG_DIR / "config.json"
12
+
13
+
14
+ class Config:
15
+ def __init__(self):
16
+ self.username: Optional[str] = os.getenv("AT_USER")
17
+ self.password: Optional[str] = os.getenv("AT_PASS")
18
+ self.token: Optional[str] = None
19
+ self.load_config()
20
+
21
+ def load_config(self):
22
+ """Load config from file. """
23
+ if CONFIG_FILE.exists():
24
+ try:
25
+ with open(CONFIG_FILE) as f:
26
+ config_data = json.load(f)
27
+ self.token = config_data.get("token")
28
+ except json.JSONDecodeError:
29
+ click.secho("Warning: Invalid config file", fg="yellow", err=True)
30
+
31
+ def ensure_auth(self):
32
+ """Ensure we have authentication credentials"""
33
+ if not self.username:
34
+ self.username = Prompt.ask("Enter your username")
35
+ if not self.password:
36
+ self.password = Prompt.ask("Enter your password", password=True)
37
+
38
+ def save_token(self, token: str):
39
+ """Save token to config file"""
40
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
41
+ with open(CONFIG_FILE, "w") as f:
42
+ json.dump({"token": token}, f)
43
+ self.token = token
@@ -0,0 +1,32 @@
1
+ def format_pagination_footer(count: int, page_size: int) -> str:
2
+ """Format pagination footer string
3
+
4
+ Args:
5
+ count: Total number of items
6
+ page_size: Number of items per page
7
+
8
+ Returns:
9
+ Formatted footer string with pagination details
10
+ """
11
+ total_pages = (count - 1) // page_size + 1
12
+ return (
13
+ f"Showing page 1 of {total_pages}, "
14
+ f"Total items: {count}. "
15
+ "Use --all to fetch all results"
16
+ )
17
+
18
+
19
+ def get_pagination_info(results: dict | list) -> tuple[list, str]:
20
+ """Extract pagination information from API response"""
21
+ if isinstance(results, dict):
22
+ items = results.get("results", [])
23
+ count = results.get("count")
24
+ page_size = len(items)
25
+
26
+ if count and page_size:
27
+ return items, format_pagination_footer(count, page_size)
28
+
29
+ return items, ""
30
+
31
+ # All pages were fetched
32
+ return results, f"All {len(results)} results"
atomict/cli/main.py ADDED
@@ -0,0 +1,124 @@
1
+ # cli/main.py
2
+ import logging
3
+ import os
4
+
5
+ import click
6
+ from rich.console import Console
7
+
8
+ from atomict.__version__ import __version__
9
+ from atomict.cli.commands import login, user
10
+
11
+ # Import command groups
12
+ from .commands import adsorbate, catalysis, k8s, project, task, upload
13
+ from .commands.exploration import soec, sqs
14
+ from .commands.simulation import fhiaims, kpoint, vibes
15
+
16
+ console = Console()
17
+
18
+
19
+ def setup_logging(verbose: bool):
20
+ """Configure logging based on verbose flag and AT_DEBUG env var"""
21
+ if os.getenv("AT_DEBUG") == "enabled":
22
+ # Most verbose logging when AT_DEBUG is set
23
+ logging.basicConfig(
24
+ level=logging.DEBUG,
25
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
26
+ handlers=[logging.StreamHandler(), logging.FileHandler("atomict.log")],
27
+ )
28
+ # Also enable HTTP library debugging
29
+ logging.getLogger("httpx").setLevel(logging.DEBUG)
30
+ logging.getLogger("httpcore").setLevel(logging.DEBUG)
31
+
32
+ # Log some debug info
33
+ logging.debug("Debug mode enabled via AT_DEBUG")
34
+ logging.debug(f'Python path: {os.getenv("PYTHONPATH")}')
35
+ logging.debug(f"Working directory: {os.getcwd()}")
36
+ else:
37
+ # Normal logging based on verbose flag
38
+ level = logging.DEBUG if verbose else logging.ERROR
39
+ logging.basicConfig(
40
+ level=level, format="%(asctime)s - %(levelname)s - %(message)s"
41
+ )
42
+
43
+
44
+ @click.group()
45
+ @click.option(
46
+ "-v", "--verbose", is_flag=True, default=False, help="Enable verbose output"
47
+ )
48
+ @click.version_option(prog_name="at", version=__version__)
49
+ def cli(verbose: bool):
50
+ """Atomic Tessellator CLI - Manage simulations and computational resources"""
51
+ setup_logging(verbose)
52
+
53
+
54
+ # Add a completion command
55
+ @cli.command(hidden=True)
56
+ @click.argument("shell", type=click.Choice(["bash", "zsh", "fish"]), required=False)
57
+ def completion(shell):
58
+ """Generate shell completion script"""
59
+ if shell is None:
60
+ shell = os.environ.get("SHELL", "")
61
+ shell = shell.split("/")[-1]
62
+ if shell not in ["bash", "zsh", "fish"]:
63
+ shell = "bash" # default to bash if shell not detected
64
+
65
+ completion_script = None
66
+ if shell == "bash":
67
+ completion_script = """
68
+ # Add to ~/.bashrc:
69
+ eval "$(_AT_COMPLETE=bash_source at)"
70
+ """
71
+ elif shell == "zsh":
72
+ completion_script = """
73
+ # Add to ~/.zshrc:
74
+ eval "$(_AT_COMPLETE=zsh_source at)"
75
+ """
76
+ elif shell == "fish":
77
+ completion_script = """
78
+ # Add to ~/.config/fish/config.fish:
79
+ eval "$(_AT_COMPLETE=fish_source at)"
80
+ """
81
+ click.echo(f"# Shell completion for {shell}")
82
+ click.echo(completion_script.strip())
83
+ click.echo(
84
+ "# Don't forget to source your rc file! `source ~/.bashrc` or `source ~/.zshrc` ..."
85
+ )
86
+
87
+
88
+ cli.add_command(completion)
89
+
90
+ # TODO: rename these to group
91
+ cli.add_command(task.task)
92
+ cli.add_command(upload.upload)
93
+ cli.add_command(project.project)
94
+ cli.add_command(k8s.k8s)
95
+ cli.add_command(adsorbate.adsorbate)
96
+
97
+ # raise commands to top-level
98
+ cli.add_command(fhiaims.fhiaims_group)
99
+ cli.add_command(kpoint.kpoint_group)
100
+ cli.add_command(catalysis.catalysis_group) # WIP
101
+ cli.add_command(sqs.sqs_group)
102
+ cli.add_command(soec.soecexploration_group)
103
+ cli.add_command(user.user_group)
104
+ cli.add_command(login._login)
105
+ cli.add_command(vibes.vibes_group)
106
+ # from .commands.exploration import exploration_group
107
+ # cli.add_command(exploration.exploration) # move this
108
+ # TBD: decide on how to group or put all commands at top level
109
+ # standardize this later
110
+ # cli.add_command(exploration_group)
111
+
112
+ # we could do `at [exploration/simulation/project/user/etc] [get/create/delete] [id]`
113
+ # OR
114
+ # `at [get/create/delete] [exploration/simulation/project/user/etc] [id]`
115
+ # OR
116
+ # some other grouping that reflects a user's workflow
117
+
118
+
119
+ def main():
120
+ cli()
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
atomict/env.py ADDED
@@ -0,0 +1,79 @@
1
+ import json
2
+ import os
3
+ import platform
4
+
5
+ DEFAULT_ATOMICT_API_ROOT = "https://api.atomictessellator.com"
6
+
7
+
8
+ def store(key, value):
9
+ cfg_path = get_config_path("config.json")
10
+
11
+ if os.path.exists(cfg_path):
12
+ with open(get_config_path("config.json"), 'r') as f:
13
+ config = json.load(f)
14
+ config[key] = value
15
+ else:
16
+ config = {key: value}
17
+
18
+ with open(get_config_path("config.json"), 'w') as f:
19
+ json.dump(config, f)
20
+
21
+
22
+ def get(key):
23
+ with open(get_config_path("config.json")) as f:
24
+ config = json.load(f)
25
+ return config.get(key)
26
+
27
+
28
+ def delete(key):
29
+ with open(get_config_path("config.json")) as f:
30
+ config = json.load(f)
31
+ del config[key]
32
+
33
+ with open(get_config_path("config.json"), "w") as f:
34
+ json.dump(config, f)
35
+
36
+
37
+ def clear():
38
+ path = get_config_path("config.json")
39
+
40
+ if os.path.exists(path):
41
+ os.remove(path)
42
+
43
+
44
+ def get_config_path(filename):
45
+ system = platform.system()
46
+ if system == "Darwin": # macOS
47
+ base_path = os.path.join(
48
+ os.path.expanduser("~/Library/Application Support"), "atomict"
49
+ )
50
+ elif system == "Windows":
51
+ base_path = os.path.join(os.environ["APPDATA"], "atomict")
52
+ else: # Linux and other Unix-like systems
53
+ config_path = os.path.join(os.path.expanduser("~"), ".config")
54
+ base_path = os.path.join(config_path, "atomict")
55
+
56
+ # Create directory if it doesn't exist
57
+ if not os.path.exists(base_path):
58
+ os.makedirs(base_path)
59
+
60
+ return os.path.join(base_path, filename)
61
+
62
+
63
+ def check_api_root():
64
+ api_root = os.environ.get("ATOMICT_API_ROOT")
65
+
66
+ if api_root is not None:
67
+ # Make sure it's a valid URL without a trailing slash
68
+ if not api_root.startswith("http"):
69
+ raise ValueError(
70
+ "ATOMICT_API_ROOT must be a valid URL, currently: {api_root}"
71
+ )
72
+ if api_root.endswith("/"):
73
+ raise ValueError(
74
+ "ATOMICT_API_ROOT must not end with a trailing slash, currently: {api_root}"
75
+ )
76
+
77
+
78
+ def check_environment():
79
+ check_api_root()
atomict/exceptions.py ADDED
@@ -0,0 +1,12 @@
1
+
2
+
3
+ class APIValidationError(Exception):
4
+ pass
5
+
6
+
7
+ class PermissionDenied(Exception):
8
+ pass
9
+
10
+
11
+ class UserTaskAbortException(Exception):
12
+ pass
@@ -0,0 +1,26 @@
1
+ import os
2
+ from typing import List
3
+
4
+
5
+ def environment_check(required_env_keys: List[str] = []):
6
+ """
7
+ Check if the environment is set up correctly.
8
+
9
+ Args:
10
+ required_env_keys (List[str]): List of environment keys that are required.
11
+
12
+ Raises:
13
+ ValueError: If any of the required environment keys are not set.
14
+ ValueError: If the AT_USER and AT_PASS or AT_TOKEN are not set.
15
+ ValueError: If the AT_SERVER is not set.
16
+ """
17
+ expected_env_keys = ["AT_SERVER", *required_env_keys]
18
+
19
+ for k in expected_env_keys:
20
+ if os.environ.get(k) in ["", None]:
21
+ raise ValueError(f"{k} is not set")
22
+
23
+ auth_creds = [os.environ.get("AT_USER"), os.environ.get("AT_PASS")]
24
+ if None in auth_creds:
25
+ if os.environ.get("AT_TOKEN") in ["", None]:
26
+ raise ValueError("No authentication credentials found, please set AT_USER and AT_PASS or AT_TOKEN")
@@ -0,0 +1,49 @@
1
+ from enum import Enum
2
+
3
+ from atomict.api import get, patch
4
+ from atomict.exceptions import UserTaskAbortException
5
+
6
+
7
+ class TaskStatus(Enum):
8
+ DRAFT = 0
9
+ READY = 1
10
+ RUNNING = 2
11
+ COMPLETED = 3
12
+ ERROR = 4
13
+ PAUSED = 5
14
+ USER_ABORTED = 6
15
+
16
+
17
+ def get_task(task_uuid: str):
18
+ return get(f"api/tasks/{task_uuid}/")
19
+
20
+
21
+ def task_should_abort(task_uuid: str) -> bool:
22
+ task = get_task(task_uuid)
23
+ return task["user_aborted_flag"]
24
+
25
+
26
+ def except_on_user_abort(task_uuid: str):
27
+ if task_should_abort(task_uuid):
28
+ raise UserTaskAbortException(f"User aborted task {task_uuid}")
29
+
30
+
31
+ def update_task_status(
32
+ task_uuid: str, status: TaskStatus = None, error_msg: str = None, percent: int = None, progress_indeterminate: bool = None
33
+ ):
34
+ payload = {}
35
+
36
+ if status:
37
+ payload["status"] = status.value
38
+
39
+ if error_msg:
40
+ payload["error"] = error_msg
41
+
42
+ if percent:
43
+ payload["progress"] = percent
44
+
45
+ if progress_indeterminate is not None:
46
+ payload["progress_indeterminate"] = progress_indeterminate
47
+
48
+ res = patch(f"api/tasks/{task_uuid}/", payload=payload)
49
+ return res
@@ -0,0 +1,22 @@
1
+ from logging.config import dictConfig
2
+
3
+
4
+ def config_loggers(prefix: str = '', *args, **kwargs):
5
+ logging_config = dict(
6
+ version=1,
7
+ formatters={
8
+ "verbose": {"format": f"%(levelname)s %(asctime)s {prefix} %(message)s"}
9
+ },
10
+ handlers={
11
+ "console": {"class": "logging.StreamHandler", "formatter": "verbose"}
12
+ },
13
+ root={"handlers": ["console"], "level": "INFO"},
14
+ loggers={
15
+ "atomict.api": {
16
+ "handlers": ["console"],
17
+ "level": "INFO",
18
+ "propagate": False
19
+ }
20
+ }
21
+ )
22
+ dictConfig(logging_config)