wwpdb.apps.console 0.0.1__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.
@@ -0,0 +1,5 @@
1
+ __docformat__ = "restructuredtext en"
2
+ __author__ = "Deborah Harrus"
3
+ __email__ = "ezra.peisach@rcsb.org"
4
+ __license__ = "Apache 2.0"
5
+ __version__ = "0.0.1"
@@ -0,0 +1 @@
1
+ # Isolated annotator batch console (served at /console/).
@@ -0,0 +1,134 @@
1
+ ##
2
+ # File: actions.py
3
+ # Date: 28-Oct-2026
4
+ ##
5
+ """Per-deposition backends for console actions (To Do, Level 2, Status, Communication, AnnMod)."""
6
+
7
+ from wwpdb.apps.console.console import catalog
8
+
9
+
10
+ def _level2_class_id(module_row, operation):
11
+ class_id = module_row["class_id"]
12
+ if operation == "run_ui":
13
+ return class_id + "UI"
14
+ return class_id
15
+
16
+
17
+ def _level2_class_file(sdb, class_id, operation):
18
+ class_info = sdb.getWfClassByID(classID=class_id)
19
+ if not class_info or not class_info.get("class_file"):
20
+ raise ValueError("Unknown workflow class '%s'." % class_id)
21
+ class_file = str(class_info["class_file"])
22
+ if operation == "restart":
23
+ if class_file.find(".bf.xml") < 0:
24
+ class_file = "Annotation.bf.xml:" + str(class_id)
25
+ return class_file
26
+
27
+
28
+ def run_add_to_my_todo(sdb, deposition_id, annotator):
29
+ existing = sdb.getAnnoSelection(depositionids=[deposition_id])
30
+ if existing:
31
+ return "already on TO DO"
32
+ sdb.addToMyList(deposition_id, annotator)
33
+ return "added to TO DO"
34
+
35
+
36
+ def run_remove_from_my_todo(sdb, deposition_id, annotator): # pylint: disable=unused-argument
37
+ existing = sdb.getAnnoSelection(depositionids=[deposition_id])
38
+ if not existing:
39
+ return "not on TO DO"
40
+ sdb.removeFromMyList(deposition_id)
41
+ return "removed from TO DO"
42
+
43
+
44
+ def run_level2(sdb, deposition_id, module_row, operation):
45
+ class_id = _level2_class_id(module_row, operation)
46
+ class_file = _level2_class_file(sdb, class_id, operation)
47
+ # communication.parent_wf_inst_id is NOT NULL. WFM Level 2 Run / Run+UI /
48
+ # Restart buttons always pass the literal string "None"; omitting it (Python
49
+ # None) makes insertCommunicationCommand write Null and the UPDATE fails
50
+ # with "Start Annotate workflow failed." That hits Run+UI hardest because
51
+ # *UI classes usually have no prior wf_instance row.
52
+ instance_id = "None"
53
+ last = sdb.getLastWFInstance(depositionid=deposition_id, classid=class_id)
54
+ if last and last.get("wf_inst_id"):
55
+ instance_id = last["wf_inst_id"]
56
+ msg = sdb.insertCommunicationCommand(
57
+ depositionid=deposition_id,
58
+ instid=instance_id,
59
+ classid=class_id,
60
+ command="restartGoWF",
61
+ classname=class_file,
62
+ dataversion="latest",
63
+ )
64
+ if msg != "OK":
65
+ raise ValueError(msg or "Failed to queue workflow command.")
66
+ op_label = "Run+UI" if operation == "run_ui" else ("Restart" if operation == "restart" else "Run")
67
+ return "queued %s %s" % (op_label, class_id)
68
+
69
+
70
+ def run_action(site_id, action_id, deposition_id, annotator, extra, verbose=False, log=None, req_obj=None):
71
+ from wwpdb.apps.workmanager.db_access.StatusDbApi import StatusDbApi
72
+
73
+ sdb = StatusDbApi(siteId=site_id, verbose=verbose, log=log)
74
+ if action_id == catalog.ACTION_ADD_TO_MY_TODO:
75
+ return run_add_to_my_todo(sdb, deposition_id, annotator)
76
+ if action_id == catalog.ACTION_REMOVE_FROM_MY_TODO:
77
+ return run_remove_from_my_todo(sdb, deposition_id, annotator)
78
+ if action_id == catalog.ACTION_RUN_OR_RESTART_LEVEL2_MODULE:
79
+ module_row, operation = catalog.validate_level2_choice(
80
+ (extra or {}).get("level2_module"),
81
+ (extra or {}).get("level2_operation"),
82
+ )
83
+ return run_level2(sdb, deposition_id, module_row, operation)
84
+ if action_id in (
85
+ catalog.ACTION_RELOAD_DATA_FILE,
86
+ catalog.ACTION_EXTEND_HOLD_DATE,
87
+ catalog.ACTION_SET_AUTH_VALIDATION_LETTER,
88
+ catalog.ACTION_SEND_TEMPLATE_MESSAGE,
89
+ catalog.ACTION_ADD_INTERNAL_NOTE,
90
+ catalog.ACTION_SET_INTERNAL_NOTES_FLAG,
91
+ catalog.ACTION_ANNMOD_FINISH,
92
+ catalog.ACTION_ANNMOD_ASSIGN_ALL_MONOMERS,
93
+ ):
94
+ if req_obj is None:
95
+ raise ValueError("This action needs a Work Manager session.")
96
+ if action_id == catalog.ACTION_RELOAD_DATA_FILE:
97
+ from wwpdb.apps.console.console import status_ops
98
+
99
+ return status_ops.run_reload(req_obj, deposition_id, annotator, verbose=verbose, log=log)
100
+ if action_id == catalog.ACTION_EXTEND_HOLD_DATE:
101
+ from wwpdb.apps.console.console import status_ops
102
+
103
+ return status_ops.run_extend_hold(req_obj, deposition_id, annotator, extra, verbose=verbose, log=log)
104
+ if action_id == catalog.ACTION_SET_AUTH_VALIDATION_LETTER:
105
+ from wwpdb.apps.console.console import status_ops
106
+
107
+ return status_ops.run_set_auth(req_obj, deposition_id, annotator, extra, verbose=verbose, log=log)
108
+ if action_id == catalog.ACTION_SEND_TEMPLATE_MESSAGE:
109
+ from wwpdb.apps.console.console import msg_ops
110
+
111
+ return msg_ops.send_template(
112
+ req_obj, deposition_id, annotator, (extra or {}).get("message_template_id"), verbose=verbose, log=log
113
+ )
114
+ if action_id == catalog.ACTION_ADD_INTERNAL_NOTE:
115
+ from wwpdb.apps.console.console import msg_ops
116
+
117
+ return msg_ops.add_internal_note(req_obj, deposition_id, annotator, extra, verbose=verbose, log=log)
118
+ if action_id == catalog.ACTION_SET_INTERNAL_NOTES_FLAG:
119
+ from wwpdb.apps.console.console import msg_ops
120
+
121
+ return msg_ops.set_notes_flag(req_obj, deposition_id, annotator, extra, verbose=verbose, log=log)
122
+ if action_id == catalog.ACTION_ANNMOD_FINISH:
123
+ from wwpdb.apps.console.console import annmod_ops
124
+
125
+ return annmod_ops.run_open_and_finish(req_obj, deposition_id, annotator, extra=None, verbose=verbose, log=log)
126
+ if action_id == catalog.ACTION_ANNMOD_ASSIGN_ALL_MONOMERS:
127
+ from wwpdb.apps.console.console import annmod_ops
128
+
129
+ extra_ann = dict(extra or {})
130
+ extra_ann["assign_all_monomers"] = True
131
+ return annmod_ops.run_open_and_finish(
132
+ req_obj, deposition_id, annotator, extra=extra_ann, verbose=verbose, log=log
133
+ )
134
+ raise ValueError("Unknown or not-yet-implemented action.")
@@ -0,0 +1,118 @@
1
+ ##
2
+ # File: annmod_ops.py
3
+ # Date: 28-Oct-2026
4
+ ##
5
+ """Annotation Module actions for the annotator batch console (open + Finish)."""
6
+
7
+ import re
8
+ import sys
9
+
10
+ from wwpdb.apps.workmanager.db_access.StatusDbApi import StatusDbApi
11
+ from wwpdb.io.locator.PathInfo import PathInfo
12
+ from wwpdb.utils.config.ConfigInfo import ConfigInfo
13
+ from wwpdb.utils.session.WebRequest import InputRequest
14
+
15
+ _ANNMOD_CLASSES = ("AnnMod", "AnnModUI")
16
+
17
+
18
+ def _waiting_annmod(site_id, deposition_id, verbose, log):
19
+ sdb = StatusDbApi(siteId=site_id, verbose=verbose, log=log)
20
+ last = sdb.getLastInstance(depositionid=deposition_id)
21
+ if not last:
22
+ raise ValueError("No workflow instance for this deposition.")
23
+ class_id = str(last.get("wf_class_id") or last.get("class_id") or "").strip()
24
+ inst_id = str(last.get("wf_inst_id") or last.get("inst_id") or "").strip()
25
+ status = str(last.get("inst_status") or "").strip().lower()
26
+ method = str(last.get("dep_exp_method") or "").strip()
27
+ if status != "waiting":
28
+ raise ValueError("AnnMod is not waiting (status is %s)." % (last.get("inst_status") or "unknown"))
29
+ if class_id not in _ANNMOD_CLASSES:
30
+ raise ValueError("Current module is %s, not AnnMod." % (class_id or "unknown"))
31
+ if not inst_id:
32
+ raise ValueError("No waiting AnnMod instance id.")
33
+ return class_id, inst_id, method
34
+
35
+
36
+ def _new_annmod_req(site_id, values, verbose, log):
37
+ cI = ConfigInfo(site_id)
38
+ req = InputRequest({}, verbose=verbose, log=log)
39
+ req.setValue("TopSessionPath", cI.get("SITE_WEB_APPS_TOP_SESSIONS_PATH"))
40
+ req.setValue("TopPath", cI.get("SITE_WEB_APPS_TOP_PATH"))
41
+ req.setValue("WWPDB_SITE_ID", site_id)
42
+ for key, val in values.items():
43
+ if val is None:
44
+ continue
45
+ req.setValue(key, val)
46
+ return req
47
+
48
+
49
+ def _error_text(rC, fallback):
50
+ if rC is None:
51
+ return fallback
52
+ try:
53
+ if rC.isError():
54
+ payload = getattr(rC, "_cD", {}) # pylint: disable=protected-access
55
+ text = str(payload.get("errortext") or payload.get("statustext") or "").strip()
56
+ text = re.sub(r"<[^>]+>", " ", text)
57
+ text = " ".join(text.split())
58
+ if text:
59
+ return text
60
+ except Exception: # noqa: BLE001
61
+ pass
62
+ return fallback
63
+
64
+
65
+ def _do_annmod(req, verbose, log):
66
+ from wwpdb.apps.ann_tasks_v2.webapp.AnnTasksWebAppWorker import AnnTasksWebAppWorker # pylint: disable=import-error,no-name-in-module
67
+
68
+ worker = AnnTasksWebAppWorker(reqObj=req, verbose=verbose, log=log)
69
+ return worker.doOp()
70
+
71
+
72
+ def run_open_and_finish(req_obj, deposition_id, annotator, extra=None, verbose=False, log=sys.stderr):
73
+ """Open waiting AnnMod (live instance) and Finish. Optional all-monomer assign first."""
74
+ assign = bool((extra or {}).get("assign_all_monomers"))
75
+ site_id = str((req_obj.getValue("WWPDB_SITE_ID") if req_obj is not None else "") or "")
76
+ class_id, inst_id, method = _waiting_annmod(site_id, deposition_id, verbose, log)
77
+ req = _new_annmod_req(
78
+ site_id,
79
+ {
80
+ "identifier": deposition_id,
81
+ "idcode": deposition_id,
82
+ "instance": inst_id,
83
+ "classID": class_id,
84
+ "filesource": "wf-instance",
85
+ "method": method,
86
+ "annotator": annotator,
87
+ "expmethod": method,
88
+ },
89
+ verbose,
90
+ log,
91
+ )
92
+ req.setValue("request_path", "/service/ann_tasks_v2/new_session/wf")
93
+ rC = _do_annmod(req, verbose, log)
94
+ if rC is None or rC.isError():
95
+ raise ValueError(_error_text(rC, "Failed to open AnnMod."))
96
+ session_id = str(req.getSessionId() or "").strip()
97
+ if not session_id:
98
+ raise ValueError("AnnMod session was not created.")
99
+ session_path = req.getSessionObj().getPath()
100
+ pI = PathInfo(siteId=site_id, sessionPath=session_path, verbose=verbose, log=log)
101
+ entry_file = pI.getFileName(
102
+ deposition_id, contentType="model", formatType="pdbx", versionId="none", partNumber="1"
103
+ )
104
+ if assign:
105
+ req.setValue("entryid", deposition_id)
106
+ req.setValue("entryfilename", entry_file)
107
+ req.setValue("allmonomerflag", "yes")
108
+ req.setValue("request_path", "/service/ann_tasks_v2/assemblysavedefaultinfo")
109
+ rC = _do_annmod(req, verbose, log)
110
+ if rC is None or rC.isError():
111
+ raise ValueError(_error_text(rC, "Assign all monomers failed. AnnMod is open; Finish was not run."))
112
+ req.setValue("request_path", "/service/ann_tasks_v2/finish")
113
+ rC = _do_annmod(req, verbose, log)
114
+ if rC is None or rC.isError():
115
+ raise ValueError(_error_text(rC, "AnnMod opened but Finish failed."))
116
+ if assign:
117
+ return "assigned all monomers and finished %s %s" % (class_id, inst_id)
118
+ return "finished %s %s" % (class_id, inst_id)
@@ -0,0 +1,76 @@
1
+ ##
2
+ # File: auth.py
3
+ # Date: 28-Oct-2026
4
+ ##
5
+ """Session file for the annotator batch console (no password stored)."""
6
+
7
+ import json
8
+ import os
9
+
10
+ AUTH_FILENAME = "console_auth.json"
11
+ ALLOWED_GROUP_CODES = frozenset(("ANN", "LANN"))
12
+
13
+
14
+ def auth_path(session_path):
15
+ return os.path.join(session_path, AUTH_FILENAME)
16
+
17
+
18
+ def write_auth(session_path, user_info):
19
+ data = {
20
+ "username": str(user_info.get("user_name") or ""),
21
+ "annotator": str(user_info.get("initials") or "").strip().upper(),
22
+ "first_name": str(user_info.get("first_name") or ""),
23
+ "last_name": str(user_info.get("last_name") or ""),
24
+ "group_code": str(user_info.get("code") or "").strip().upper(),
25
+ "group_name": str(user_info.get("group_name") or ""),
26
+ "site": str(user_info.get("site") or ""),
27
+ }
28
+ fp = open(auth_path(session_path), "w")
29
+ try:
30
+ json.dump(data, fp, indent=2)
31
+ finally:
32
+ fp.close()
33
+ return data
34
+
35
+
36
+ def read_auth(session_path):
37
+ path = auth_path(session_path)
38
+ if not os.path.isfile(path):
39
+ return None
40
+ try:
41
+ fp = open(path, "r")
42
+ try:
43
+ data = json.load(fp)
44
+ finally:
45
+ fp.close()
46
+ except (IOError, ValueError, TypeError):
47
+ return None
48
+ if not isinstance(data, dict) or not data.get("annotator"):
49
+ return None
50
+ return data
51
+
52
+
53
+ def clear_auth(session_path):
54
+ path = auth_path(session_path)
55
+ try:
56
+ if os.path.isfile(path):
57
+ os.remove(path)
58
+ except OSError:
59
+ pass
60
+
61
+
62
+ def group_allowed(user_info):
63
+ code = str((user_info or {}).get("code") or "").strip().upper()
64
+ return code in ALLOWED_GROUP_CODES
65
+
66
+
67
+ def require_console_user(session_path, annotator):
68
+ """Return auth dict or raise ValueError if the session is not a console login."""
69
+ data = read_auth(session_path)
70
+ if not data:
71
+ raise ValueError("Not signed in. Open /console/ and sign in with your Work Manager username and password.")
72
+ wanted = str(annotator or "").strip().upper()
73
+ stored = str(data.get("annotator") or "").strip().upper()
74
+ if wanted and stored and wanted != stored:
75
+ raise ValueError("Session initials do not match. Sign in again.")
76
+ return data
@@ -0,0 +1,146 @@
1
+ ##
2
+ # File: catalog.py
3
+ # Date: 28-Oct-2026
4
+ #
5
+ # Action ids and Level 2 module choices for the annotator batch console.
6
+ ##
7
+ """Catalog of console actions. Keep in sync with htdocs/console/js/console.js labels."""
8
+
9
+ ACTION_ADD_TO_MY_TODO = "add_to_my_todo"
10
+ ACTION_REMOVE_FROM_MY_TODO = "remove_from_my_todo"
11
+ ACTION_RUN_OR_RESTART_LEVEL2_MODULE = "run_or_restart_level2_module"
12
+ ACTION_RELOAD_DATA_FILE = "reload_data_file"
13
+ ACTION_EXTEND_HOLD_DATE = "extend_hold_date"
14
+ ACTION_SET_AUTH_VALIDATION_LETTER = "set_auth_validation_letter"
15
+ ACTION_SEND_TEMPLATE_MESSAGE = "send_template_message"
16
+ ACTION_ADD_INTERNAL_NOTE = "add_internal_note"
17
+ ACTION_SET_INTERNAL_NOTES_FLAG = "set_internal_notes_flag"
18
+ ACTION_ANNMOD_FINISH = "annmod_finish"
19
+ ACTION_ANNMOD_ASSIGN_ALL_MONOMERS = "annmod_assign_all_monomers"
20
+
21
+ IMPLEMENTED_ACTION_IDS = frozenset(
22
+ (
23
+ ACTION_ADD_TO_MY_TODO,
24
+ ACTION_REMOVE_FROM_MY_TODO,
25
+ ACTION_RUN_OR_RESTART_LEVEL2_MODULE,
26
+ ACTION_RELOAD_DATA_FILE,
27
+ ACTION_EXTEND_HOLD_DATE,
28
+ ACTION_SET_AUTH_VALIDATION_LETTER,
29
+ ACTION_SEND_TEMPLATE_MESSAGE,
30
+ ACTION_ADD_INTERNAL_NOTE,
31
+ ACTION_SET_INTERNAL_NOTES_FLAG,
32
+ ACTION_ANNMOD_FINISH,
33
+ ACTION_ANNMOD_ASSIGN_ALL_MONOMERS,
34
+ )
35
+ )
36
+
37
+ ACTION_LABELS = {
38
+ ACTION_ADD_TO_MY_TODO: "Add to my TO DO",
39
+ ACTION_REMOVE_FROM_MY_TODO: "Remove from my TO DO",
40
+ ACTION_RUN_OR_RESTART_LEVEL2_MODULE: "Run or Restart a module",
41
+ ACTION_RELOAD_DATA_FILE: "Reload data file",
42
+ ACTION_EXTEND_HOLD_DATE: "Extend hold date",
43
+ ACTION_SET_AUTH_VALIDATION_LETTER: "Set to AUTH and send Validation Letter",
44
+ ACTION_SEND_TEMPLATE_MESSAGE: "Send template message",
45
+ ACTION_ADD_INTERNAL_NOTE: "Add internal note",
46
+ ACTION_SET_INTERNAL_NOTES_FLAG: "Enable or disable internal notes",
47
+ ACTION_ANNMOD_FINISH: "Open AnnMod and Finish",
48
+ ACTION_ANNMOD_ASSIGN_ALL_MONOMERS: "Open AnnMod, assign all monomers, and Finish",
49
+ }
50
+
51
+ # Communication UI ids (cmps_*) and the context_type stored on the message.
52
+ MESSAGE_TEMPLATES = (
53
+ {"id": "cmps_default", "context": "default", "label": "Default"},
54
+ {"id": "cmps_vldtn", "context": "vldtn", "label": "Validation Report"},
55
+ {"id": "cmps_approval-expl", "context": "approval-expl", "label": "Approval Explicit"},
56
+ {"id": "cmps_approval-impl", "context": "approval-impl", "label": "Approval Implicit"},
57
+ {"id": "cmps_reminder", "context": "reminder", "label": "Reminder"},
58
+ {"id": "cmps_extension-3mo", "context": "extension-3mo", "label": "Extension 3 months"},
59
+ {"id": "cmps_extension-6mo", "context": "extension-6mo", "label": "Extension 6 months"},
60
+ {"id": "cmps_release-publ", "context": "release-publ", "label": "Release w/ Publication"},
61
+ {"id": "cmps_release-nopubl", "context": "release-nopubl", "label": "Release w/o Publication"},
62
+ {"id": "cmps_system-unlocked", "context": "system-unlocked", "label": "System Unlocked"},
63
+ {"id": "cmps_withdrawn", "context": "withdrawn", "label": "Withdrawn"},
64
+ )
65
+
66
+ AUTOMSG_CONTEXTS = frozenset(
67
+ ("approval-expl", "approval-impl", "reminder", "release-publ", "release-nopubl")
68
+ )
69
+ HOLD_EXTENSION_CONTEXTS = {"extension-3mo": "3", "extension-6mo": "6"}
70
+
71
+ # id -> workflow class_id used in status.communication / wf_class_dict
72
+ LEVEL2_MODULES = (
73
+ {"id": "reportmod", "class_id": "ReportMod", "label": "ReportMod", "has_run_ui": False},
74
+ {"id": "transmod", "class_id": "TransMod", "label": "TransMod", "has_run_ui": True},
75
+ {"id": "ligmod", "class_id": "LigMod", "label": "LigMod", "has_run_ui": True},
76
+ {"id": "seqmod", "class_id": "SeqMod", "label": "SeqMod", "has_run_ui": True},
77
+ {"id": "annmod", "class_id": "AnnMod", "label": "AnnMod", "has_run_ui": True},
78
+ {"id": "valmod", "class_id": "ValMod", "label": "ValMod", "has_run_ui": False},
79
+ {"id": "reportmod2", "class_id": "ReportMod2", "label": "ReportMod2", "has_run_ui": False},
80
+ {"id": "statmod", "class_id": "StatMod", "label": "StatMod", "has_run_ui": False},
81
+ )
82
+
83
+ LEVEL2_OPERATIONS = (
84
+ {"id": "run", "label": "Run"},
85
+ {"id": "run_ui", "label": "Run+UI"},
86
+ {"id": "restart", "label": "Restart"},
87
+ )
88
+
89
+
90
+ def action_label(action_id):
91
+ return ACTION_LABELS.get(action_id, action_id)
92
+
93
+
94
+ def level2_module_by_id(module_id):
95
+ wanted = str(module_id or "").strip().lower()
96
+ for row in LEVEL2_MODULES:
97
+ if row["id"] == wanted:
98
+ return row
99
+ return None
100
+
101
+
102
+ def validate_level2_choice(module_id, operation):
103
+ row = level2_module_by_id(module_id)
104
+ op = str(operation or "").strip().lower()
105
+ if not row:
106
+ raise ValueError("Choose a Level 2 module.")
107
+ if op not in ("run", "run_ui", "restart"):
108
+ raise ValueError("Choose Run, Run+UI, or Restart.")
109
+ if op == "run_ui" and not row.get("has_run_ui"):
110
+ raise ValueError("Run+UI is not available for that module. Choose Run or Restart.")
111
+ return row, op
112
+
113
+
114
+ def message_template_by_id(template_id):
115
+ wanted = str(template_id or "").strip()
116
+ if wanted.startswith("cmps_"):
117
+ wanted_ctx = wanted[5:]
118
+ else:
119
+ wanted_ctx = wanted
120
+ for row in MESSAGE_TEMPLATES:
121
+ if row["id"] == wanted or row["context"] == wanted or row["context"] == wanted_ctx:
122
+ return row
123
+ return None
124
+
125
+
126
+ def validate_message_template(template_id):
127
+ row = message_template_by_id(template_id)
128
+ if not row:
129
+ raise ValueError("Choose a Communication template.")
130
+ return row
131
+
132
+
133
+ def validate_hold_months(raw):
134
+ months = str(raw or "").strip()
135
+ if months not in ("3", "6"):
136
+ raise ValueError("Choose 3 or 6 months.")
137
+ return months
138
+
139
+
140
+ def validate_notes_flag(raw):
141
+ val = str(raw or "").strip().lower()
142
+ if val in ("enable", "on", "true", "yes", "1"):
143
+ return "true"
144
+ if val in ("disable", "off", "false", "no", "0"):
145
+ return "false"
146
+ raise ValueError("Choose enable or disable for the notes flag.")
@@ -0,0 +1,177 @@
1
+ ##
2
+ # File: jobs.py
3
+ # Date: 28-Oct-2026
4
+ ##
5
+ """Ephemeral console job progress, stored under the WFM session directory."""
6
+
7
+ import json
8
+ import os
9
+ import re
10
+ import uuid
11
+ from datetime import datetime
12
+
13
+ from wwpdb.apps.console.console import catalog
14
+
15
+ _DEP_ID = re.compile(r"^D_\d+$", re.I)
16
+
17
+
18
+ def parse_deposition_ids(raw):
19
+ ids = []
20
+ seen = set()
21
+ text = str(raw or "")
22
+ for part in re.split(r"[\s,;]+", text):
23
+ s = part.strip().upper()
24
+ if not s:
25
+ continue
26
+ if s.startswith("D") and not s.startswith("D_"):
27
+ s = "D_" + s[1:].lstrip("_")
28
+ if not _DEP_ID.match(s):
29
+ continue
30
+ if s not in seen:
31
+ seen.add(s)
32
+ ids.append(s)
33
+ return ids
34
+
35
+
36
+ def jobs_root(session_path):
37
+ return os.path.join(session_path, "console_jobs")
38
+
39
+
40
+ def job_dir(session_path, job_id):
41
+ return os.path.join(jobs_root(session_path), job_id)
42
+
43
+
44
+ def _progress_path(session_path, job_id):
45
+ return os.path.join(job_dir(session_path, job_id), "progress.json")
46
+
47
+
48
+ def _log_path(session_path, job_id):
49
+ return os.path.join(job_dir(session_path, job_id), "run.log")
50
+
51
+
52
+ def _cancel_path(session_path, job_id):
53
+ return os.path.join(job_dir(session_path, job_id), "cancel.flag")
54
+
55
+
56
+ def _now():
57
+ return datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
58
+
59
+
60
+ def _atomic_write_json(path, data):
61
+ tmp = path + ".tmp"
62
+ fp = open(tmp, "w")
63
+ try:
64
+ json.dump(data, fp, indent=2)
65
+ fp.flush()
66
+ os.fsync(fp.fileno())
67
+ finally:
68
+ fp.close()
69
+ if os.path.exists(path):
70
+ os.remove(path)
71
+ os.rename(tmp, path)
72
+
73
+
74
+ def new_job(session_path, action_id, annotator, deposition_ids, extra=None):
75
+ job_id = str(uuid.uuid4())
76
+ dest = job_dir(session_path, job_id)
77
+ os.makedirs(dest)
78
+ rows = []
79
+ for dep_id in deposition_ids:
80
+ rows.append({"deposition_id": dep_id, "status": "waiting", "error": ""})
81
+ progress = {
82
+ "job_id": job_id,
83
+ "action_id": action_id,
84
+ "action_title": catalog.action_label(action_id),
85
+ "annotator": annotator,
86
+ "status": "running",
87
+ "created_at": _now(),
88
+ "updated_at": _now(),
89
+ "error": "",
90
+ "deposition_ids": list(deposition_ids),
91
+ "rows": rows,
92
+ "ok": 0,
93
+ "failed": 0,
94
+ "running": 0,
95
+ "waiting": len(deposition_ids),
96
+ "log": [],
97
+ "extra": extra or {},
98
+ }
99
+ _atomic_write_json(_progress_path(session_path, job_id), progress)
100
+ fp = open(_log_path(session_path, job_id), "w")
101
+ fp.close()
102
+ return progress
103
+
104
+
105
+ def load_progress(session_path, job_id):
106
+ path = _progress_path(session_path, job_id)
107
+ if not os.path.isfile(path):
108
+ return None
109
+ fp = open(path, "r")
110
+ try:
111
+ return json.load(fp)
112
+ except (IOError, ValueError, TypeError):
113
+ return None
114
+ finally:
115
+ fp.close()
116
+
117
+
118
+ def append_log(session_path, job_id, line):
119
+ text = str(line or "").rstrip() + "\n"
120
+ fp = open(_log_path(session_path, job_id), "a")
121
+ try:
122
+ fp.write(text)
123
+ finally:
124
+ fp.close()
125
+ progress = load_progress(session_path, job_id)
126
+ if not progress:
127
+ return
128
+ log_lines = list(progress.get("log") or [])
129
+ log_lines.append(text.rstrip("\n"))
130
+ if len(log_lines) > 400:
131
+ log_lines = log_lines[-400:]
132
+ progress["log"] = log_lines
133
+ progress["updated_at"] = _now()
134
+ _atomic_write_json(_progress_path(session_path, job_id), progress)
135
+
136
+
137
+ def set_row(session_path, job_id, deposition_id, status, error=""):
138
+ progress = load_progress(session_path, job_id)
139
+ if not progress:
140
+ return
141
+ for row in progress.get("rows") or []:
142
+ if row.get("deposition_id") == deposition_id:
143
+ row["status"] = status
144
+ row["error"] = error or ""
145
+ break
146
+ counts = {"ok": 0, "failed": 0, "running": 0, "waiting": 0}
147
+ for row in progress.get("rows") or []:
148
+ st = str(row.get("status") or "waiting")
149
+ if st in counts:
150
+ counts[st] += 1
151
+ progress.update(counts)
152
+ progress["updated_at"] = _now()
153
+ _atomic_write_json(_progress_path(session_path, job_id), progress)
154
+
155
+
156
+ def finish_job(session_path, job_id, status="done", error=""):
157
+ progress = load_progress(session_path, job_id)
158
+ if not progress:
159
+ return
160
+ progress["status"] = status
161
+ progress["error"] = error or ""
162
+ progress["updated_at"] = _now()
163
+ _atomic_write_json(_progress_path(session_path, job_id), progress)
164
+
165
+
166
+ def request_cancel(session_path, job_id):
167
+ dest = job_dir(session_path, job_id)
168
+ if not os.path.isdir(dest):
169
+ return False
170
+ fp = open(_cancel_path(session_path, job_id), "w")
171
+ fp.write("1\n")
172
+ fp.close()
173
+ return True
174
+
175
+
176
+ def cancel_requested(session_path, job_id):
177
+ return os.path.isfile(_cancel_path(session_path, job_id))