diff --git a/ODM/ODM.py b/ODM/ODM.py index 2458cf5..eb52f07 100644 --- a/ODM/ODM.py +++ b/ODM/ODM.py @@ -57,6 +57,9 @@ def __init__(self, parent=None): self.launchWebODMTaskButton = None self.webodmLogTextEdit = None self.stopMonitoringButton = None + self.cancelTaskButton = None + self.reconnectTaskButton = None + self.nodeDashboardLabel = None # NodeODM management self.launchWebODMButton = None @@ -86,7 +89,7 @@ def __init__(self, parent=None): "min-num-features": [50000, 10000, 20000], "pc-filter": [1, 2, 3, 4, 5], "depthmap-resolution": [3072, 2048, 4096, 8192], - "matcher-type": ["bruteforce", "bow", "flann"], + "matcher-type": ["flann", "bow", "bruteforce"], "feature-type": ["dspsift", "akaze", "hahog", "orb", "sift"], "feature-quality": ["ultra", "medium", "high"], "pc-quality": ["high", "medium", "ultra"], @@ -99,6 +102,8 @@ def __init__(self, parent=None): # Dataset name and concurrency self.datasetNameLineEdit = None self.maxConcurrencySpinBox = None + # Set once the user types their own dataset name; stops it tracking the folder. + self._datasetNameEdited = False # GCP (Ground Control Points) self.findGCPScriptSelector = None @@ -203,7 +208,18 @@ def setup(self): self.nodePortSpinBox.setValue(3002) self.nodePortSpinBox.setToolTip("Port number on which NodeODM is listening. Commonly 3001 or 3002.") webodmTaskFormLayout.addRow("Node Port:", self.nodePortSpinBox) - + + self.nodeDashboardLabel = qt.QLabel() + self.nodeDashboardLabel.setOpenExternalLinks(True) + self.nodeDashboardLabel.setToolTip( + "Opens the NodeODM dashboard in your browser.\n" + "Shows every task on this node (running, queued and finished) and lets you cancel them." + ) + webodmTaskFormLayout.addRow("Node Dashboard:", self.nodeDashboardLabel) + self.nodeIPLineEdit.connect('textChanged(QString)', self.onNodeAddressChanged) + self.nodePortSpinBox.connect('valueChanged(int)', self.onNodeAddressChanged) + self.updateNodeDashboardLink() + # WebODM parameter tooltips parameterTooltips = { "ignore-gsd": ( @@ -296,10 +312,19 @@ def setup(self): # TODO: Add WebODM parameter controls here (will be added in next step) self.datasetNameLineEdit = qt.QLineEdit("SlicerReconstruction") - self.datasetNameLineEdit.setToolTip("Name of the dataset in WebODM.\\nThis will be the reconstruction folder label.") + self.datasetNameLineEdit.setToolTip( + "Labels this dataset on the node, and names the WebODM_ results folder.\n\n" + "Defaults to the images folder's own name (e.g. UWBM_82409), so a task on the node\n" + "says which photos it came from rather than only when it ran.\n" + "Type your own and it stops following the folder." + ) webodmTaskFormLayout.addRow("name:", self.datasetNameLineEdit) - self.launchWebODMTaskButton = qt.QPushButton("Run NodeODM Task With Selected Parameters (non-blocking)") + self.launchWebODMTaskButton = qt.QPushButton("Run NodeODM Task With Selected Parameters") + self.launchWebODMTaskButton.setToolTip( + "Uploads the images and queues one reconstruction task on the node.\n" + "Uploading can take several minutes for large image sets." + ) webodmTaskFormLayout.addWidget(self.launchWebODMTaskButton) self.launchWebODMTaskButton.setEnabled(True) @@ -307,9 +332,30 @@ def setup(self): self.webodmLogTextEdit.setReadOnly(True) webodmTaskFormLayout.addRow("Console Log:", self.webodmLogTextEdit) + taskControlRow = qt.QHBoxLayout() self.stopMonitoringButton = qt.QPushButton("Stop Monitoring") self.stopMonitoringButton.setEnabled(False) - webodmTaskFormLayout.addWidget(self.stopMonitoringButton) + self.stopMonitoringButton.setToolTip( + "Stop updating this log. The task keeps running on the node.\n" + "Use 'Cancel Task' to actually stop it." + ) + taskControlRow.addWidget(self.stopMonitoringButton) + + self.cancelTaskButton = qt.QPushButton("Cancel Task") + self.cancelTaskButton.setEnabled(False) + self.cancelTaskButton.setToolTip("Cancel the monitored task on the node itself.") + taskControlRow.addWidget(self.cancelTaskButton) + webodmTaskFormLayout.addRow(taskControlRow) + + self.reconnectTaskButton = qt.QPushButton("Reconnect to Task on Node...") + self.reconnectTaskButton.setToolTip( + "Pick up a task that is already on the node - one left behind by 'Stop Monitoring',\n" + "or started in an earlier Slicer session - and resume watching it, downloading the\n" + "results when it finishes.\n\n" + "NodeODM deletes finished tasks after 48 hours by default, so this only reaches\n" + "tasks the node still remembers." + ) + webodmTaskFormLayout.addRow(self.reconnectTaskButton) self.importModelButton = qt.QPushButton("Import Reconstructed Model") self.layout.addWidget(self.importModelButton) @@ -339,7 +385,16 @@ def setup(self): self.stopWebODMButton.connect('clicked(bool)', self.onStopNodeClicked) self.launchWebODMTaskButton.connect('clicked(bool)', self.onRunWebODMTask) self.stopMonitoringButton.connect('clicked(bool)', self.onStopMonitoring) + self.cancelTaskButton.connect('clicked(bool)', self.onCancelTaskClicked) + self.reconnectTaskButton.connect('clicked(bool)', self.onReconnectTaskClicked) self.importModelButton.connect('clicked(bool)', self.onImportModelClicked) + + # Keep the dataset name following the images folder until the user overrides it. + # textEdited fires only for real typing, not for setText, so the flag below is + # never tripped by our own updates. + self.inputFolderSelector.connect('directoryChanged(QString)', self.onInputFolderChanged) + self.datasetNameLineEdit.connect('textEdited(QString)', self.onDatasetNameEdited) + self.onInputFolderChanged(self.inputFolderSelector.directory) # self.saveTaskButton.connect('clicked(bool)', self.onSaveTaskClicked) # self.restoreTaskButton.connect('clicked(bool)', self.onRestoreTaskClicked) @@ -365,7 +420,7 @@ def ensure_webodm_folder_permissions(self): os.chmod(self.webODMLocalFolder, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) logging.info(f"WebODM folder created and permissions set: {self.webODMLocalFolder}") except Exception as e: - slicer.util.errorDisplay(f"Failed to create or set permissions for WebODM folder:\\n{str(e)}") + slicer.util.errorDisplay(f"Failed to create or set permissions for WebODM folder:\n{str(e)}") def _ensurePyODMInstalled(self): """Check if pyodm is installed, and install it if missing.""" @@ -378,13 +433,13 @@ def _ensurePyODMInstalled(self): # Ask user to install if not slicer.util.confirmOkCancelDisplay( - "The ODM module requires the 'pyodm' Python package.\\n\\n" + "The ODM module requires the 'pyodm' Python package.\n\n" "Install it now?", "Install pyodm" ): slicer.util.warningDisplay( - "pyodm is required for this module to function.\\n" - "You can install it manually via:\\n" + "pyodm is required for this module to function.\n" + "You can install it manually via:\n" "pip install pyodm" ) return @@ -393,7 +448,7 @@ def _ensurePyODMInstalled(self): slicer.util.pip_install("pyodm") slicer.util.infoDisplay("pyodm installed successfully!") except Exception as e: - slicer.util.errorDisplay(f"Failed to install pyodm:\\n{e}\\n\\nPlease install manually:\\npip install pyodm") + slicer.util.errorDisplay(f"Failed to install pyodm:\n{e}\n\nPlease install manually:\npip install pyodm") def onLaunchWebODMClicked(self): """Launch NodeODM container with GPU support on port 3002""" @@ -410,7 +465,57 @@ def onRunWebODMTask(self): def onStopMonitoring(self): """Stop monitoring the current task""" self.webODMManager.onStopMonitoring() - + + def onCancelTaskClicked(self): + """Cancel the monitored task on the node""" + self.webODMManager.onCancelTaskClicked() + + def onReconnectTaskClicked(self): + """Resume monitoring a task that is already on the node""" + self.webODMManager.onReconnectTaskClicked() + + def sanitizeDatasetName(self, text): + """ + Reduce a dataset name to characters that are safe in a folder name. + + This names WebODM_ and WebODM_.json on disk, so it has to hold for + anything the user types, not just names derived from a folder. + """ + import re + cleaned = re.sub(r'[^A-Za-z0-9._-]+', '_', text or "").strip('_.') + return cleaned or "SlicerReconstruction" + + def datasetNameFromFolder(self, folder): + """ + Name a dataset after the folder its photos came from. + + The name is all the node knows about a task: it has no idea which folder was + uploaded. Left at the default, every task was called 'SlicerReconstruction' and + two different specimens were indistinguishable on the dashboard. + """ + return self.sanitizeDatasetName(os.path.basename(os.path.normpath(folder or ""))) + + def onInputFolderChanged(self, folder): + """Track the images folder, unless the user has named the dataset themselves.""" + if self._datasetNameEdited: + return + self.datasetNameLineEdit.setText(self.datasetNameFromFolder(folder)) + + def onDatasetNameEdited(self, unusedText=None): + self._datasetNameEdited = True + + def nodeDashboardUrl(self): + """URL of the NodeODM dashboard for the currently configured node.""" + return f"http://{self.nodeIPLineEdit.text.strip()}:{self.nodePortSpinBox.value}" + + def onNodeAddressChanged(self, unusedValue=None): + """Keep the dashboard link in sync with the IP/port fields.""" + self.updateNodeDashboardLink() + + def updateNodeDashboardLink(self): + url = self.nodeDashboardUrl() + self.nodeDashboardLabel.setText(f'{url}') + def onImportModelClicked(self): """Import the reconstructed 3D model into Slicer""" self.webODMManager.onImportModelClicked() @@ -601,7 +706,7 @@ def onLaunchWebODMClicked(self): """ proceed = slicer.util.confirmYesNoDisplay( "This action will ensure nodeodm:gpu is installed (pull if needed), " - "stop any running container on port 3002, and launch a new one.\\n\\n" + "stop any running container on port 3002, and launch a new one.\n\n" "Proceed?" ) if not proceed: @@ -612,7 +717,7 @@ def onLaunchWebODMClicked(self): try: subprocess.run(["docker", "--version"], check=True, capture_output=True) except Exception as e: - slicer.util.warningDisplay(f"Docker not found or not in PATH.\\nError: {str(e)}") + slicer.util.warningDisplay(f"Docker not found or not in PATH.\nError: {str(e)}") return # Check if image exists, pull if needed @@ -677,7 +782,7 @@ def onLaunchWebODMClicked(self): slicer.app.settings().setValue("ODM/WebODMIP", "127.0.0.1") slicer.app.settings().setValue("ODM/WebODMPort", "3002") except Exception as e: - slicer.util.errorDisplay(f"Failed to launch WebODM container:\\n{str(e)}") + slicer.util.errorDisplay(f"Failed to launch WebODM container:\n{str(e)}") def onStopNodeClicked(self): """ @@ -687,7 +792,7 @@ def onStopNodeClicked(self): if jobInProgress: proceed = slicer.util.confirmYesNoDisplay( - "A WebODM task appears to be in progress. Stopping the node now will cancel that task.\\n\\n" + "A WebODM task appears to be in progress. Stopping the node now will cancel that task.\n\n" "Do you want to continue?" ) if not proceed: @@ -710,12 +815,46 @@ def onStopNodeClicked(self): subprocess.run(["docker", "stop", cid], check=True) slicer.util.infoDisplay("NodeODM container stopped.") except Exception as e: - slicer.util.errorDisplay(f"Failed to stop container:\\n{str(e)}") + slicer.util.errorDisplay(f"Failed to stop container:\n{str(e)}") + + def _updateTaskButtons(self): + """ + Single source of truth for the task buttons: Run is available only when no task + is tracked, and the task controls only when one is. Re-enabling Run while a task + is still tracked is what let a second click orphan the first task. + """ + hasTask = self.webodmTask is not None + self.widget.launchWebODMTaskButton.setEnabled(not hasTask) + self.widget.reconnectTaskButton.setEnabled(not hasTask) + self.widget.stopMonitoringButton.setEnabled(hasTask) + self.widget.cancelTaskButton.setEnabled(hasTask) def onRunWebODMTask(self): """ - Create and execute a WebODM reconstruction task + Create and execute a WebODM reconstruction task. + + Run is disabled for the whole call (the upload runs on the UI thread, so clicks + would otherwise queue up behind it) and stays disabled afterwards for as long as + the created task is still being tracked. """ + self.widget.launchWebODMTaskButton.setEnabled(False) + try: + self._runWebODMTask() + finally: + self._updateTaskButtons() + + def _runWebODMTask(self): + # Slicer tracks exactly one task. Starting another would overwrite webodmTask and + # webodmTimer, leaving the previous one running on the node with no way to monitor + # or cancel it from here. + if self.webodmTask is not None: + slicer.util.warningDisplay( + "A task is already being monitored.\n\n" + "Use 'Cancel Task' to stop it, or 'Stop Monitoring' to leave it running on " + "the node, before starting another one." + ) + return + try: from pyodm import Node except ImportError: @@ -727,7 +866,7 @@ def onRunWebODMTask(self): try: node = Node(node_ip, node_port) except Exception as e: - slicer.util.errorDisplay(f"Failed to connect to Node at {node_ip}:{node_port}\\n{str(e)}") + slicer.util.errorDisplay(f"Failed to connect to Node at {node_ip}:{node_port}\n{str(e)}") return inputFolder = self.widget.inputFolderSelector.directory @@ -761,6 +900,30 @@ def onRunWebODMTask(self): else: slicer.util.infoDisplay("No combined_gcp_list.txt found. Proceeding without GCP...") + # Node.__init__ does not talk to the network, so this is the first call that + # actually proves the node is up -- and it tells us what is already queued. + dashboardUrl = self.widget.nodeDashboardUrl() + try: + nodeInfo = node.info() + except Exception as e: + slicer.util.errorDisplay( + f"Could not reach NodeODM at {dashboardUrl}\n\n{str(e)}\n\n" + "Is the node running? Use 'Launch NodeODM' above to start it." + ) + return + + queuedCount = nodeInfo.task_queue_count or 0 + if queuedCount > 0: + proceed = slicer.util.confirmYesNoDisplay( + f"This node already has {queuedCount} task(s) running or queued.\n\n" + "A new task waits in line behind them, and will just report " + "'Queued, Progress: 0%' until they finish.\n\n" + f"Review or cancel existing tasks at:\n{dashboardUrl}\n\n" + "Queue another task anyway?" + ) + if not proceed: + return + # Build parameters from baseline + UI selections params = dict(self.widget.baselineParams) @@ -782,24 +945,69 @@ def onRunWebODMTask(self): params["max-concurrency"] = self.widget.maxConcurrencySpinBox.value # Generate task name based on parameters (creates a short hash-based name) - prefix = self.widget.datasetNameLineEdit.text.strip() or "SlicerReconstruction" - shortTaskName = self.generateShortTaskName(prefix, params) + # Sanitize here too: the field is free text, and folder-tracking stops the moment + # the user types their own name, so this is the only guard on what they typed. + prefix = self.widget.sanitizeDatasetName(self.widget.datasetNameLineEdit.text.strip()) + shortTaskName = self.generateShortTaskName(prefix, params, inputFolder) + + # create_task uploads every file on the UI thread, which for a few hundred images + # means minutes of frozen application. Drive a progress dialog from pyodm's + # callback so the upload is visibly alive. + fileCount = len(files_to_upload) + progressDialog = slicer.util.createProgressDialog( + windowTitle="Creating NodeODM Task", + labelText=f"Uploading {fileCount} file(s) to NodeODM...", + maximum=100 + ) + progressDialog.setCancelButton(None) + progressDialog.show() + slicer.app.processEvents() - slicer.util.infoDisplay("Creating WebODM Task (non-blocking). Upload may take time...") + def onUploadProgress(percent): + progressDialog.labelText = f"Uploading {fileCount} file(s) to NodeODM... {percent:.0f}%" + progressDialog.setValue(int(percent)) + slicer.app.processEvents() + # Report the error only after the progress dialog is down: errorDisplay is modal, + # so raising it from the except block would strand the upload dialog behind it. + createError = None try: - self.webodmTask = node.create_task(files=files_to_upload, options=params, name=shortTaskName) + self.webodmTask = node.create_task( + files=files_to_upload, + options=params, + name=shortTaskName, + progress_callback=onUploadProgress + ) except Exception as e: - slicer.util.errorDisplay(f"Task creation failed:\\n{str(e)}") + createError = e + finally: + progressDialog.close() + slicer.app.processEvents() + + if createError is not None: + slicer.util.errorDisplay(f"Task creation failed:\n{str(createError)}") return - slicer.util.infoDisplay(f"Task '{shortTaskName}' created successfully. Monitoring progress...") + slicer.util.infoDisplay( + f"Task '{shortTaskName}' created successfully. Monitoring progress...", + autoCloseMsec=3000 + ) + # Path only -- the folder is created at download time. Creating it here left an + # empty WebODM_ folder behind whenever a task was never downloaded (Stop + # Monitoring, a failure, a Slicer restart), which then looked like output and + # sent 'Import Reconstructed Model' hunting for an odm_texturing that never came. self.webodmOutDir = os.path.join(inputFolder, f"WebODM_{shortTaskName}") - os.makedirs(self.webodmOutDir, exist_ok=True) self.widget.webodmLogTextEdit.clear() - self.widget.stopMonitoringButton.setEnabled(True) + self.widget.webodmLogTextEdit.append(f"Task '{shortTaskName}' queued on {dashboardUrl}") + self.widget.webodmLogTextEdit.append(f" node task UUID: {self.webodmTask.uuid}") + self.widget.webodmLogTextEdit.append(f" results will download to: {self.webodmOutDir}") + + recordPath = self.writeTaskRecord( + inputFolder, shortTaskName, dashboardUrl, params, len(all_images)) + if recordPath: + self.widget.webodmLogTextEdit.append(f" task record: {recordPath}") self.lastWebODMOutputLineIndex = 0 @@ -816,31 +1024,281 @@ def onRunWebODMTask(self): if hasattr(self.widget, 'saveTaskButton') and self.widget.saveTaskButton: self.widget.saveTaskButton.enabled = True - def generateShortTaskName(self, basePrefix, paramsDict): + def uniqueTaskName(self, inputFolder, name): + """ + Make sure the name is not already spoken for on disk. + + The stamp has one-second resolution, so two jobs submitted inside the same second + get the same name -- and a colliding name means the second job's record and + results land on top of the first's. Rare with real uploads, silent when it does + happen, so check rather than assume. + """ + candidate, n = name, 1 + while (os.path.exists(self.taskRecordPath(inputFolder, candidate)) or + os.path.exists(os.path.join(inputFolder, f"WebODM_{candidate}"))): + n += 1 + candidate = f"{name}-{n}" + return candidate + + def generateShortTaskName(self, basePrefix, paramsDict, inputFolder=None): """ - Generate a short task name based on prefix and parameter hash. - Similar to PhotoMasking's generateShortTaskName method. + Name a task uniquely: prefix, a hash of the parameters, and the start time. + + The hash alone is a pure function of the parameters, so re-running the same + settings produced the same name every time -- two tasks on the node sharing one + name, both pointing at one WebODM_ folder, the second download landing on + top of the first. The timestamp is what makes a run identifiable; the hash is + kept so the settings are still readable at a glance. """ import hashlib import json - + import datetime + # Convert params to a stable JSON string paramsStr = json.dumps(paramsDict, sort_keys=True) hashObj = hashlib.sha256(paramsStr.encode('utf-8')) shortHash = hashObj.hexdigest()[:8] - return f"{basePrefix}_{shortHash}" + stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + name = f"{basePrefix}_{shortHash}_{stamp}" + return self.uniqueTaskName(inputFolder, name) if inputFolder else name def onStopMonitoring(self): """ Stop monitoring the current task (task continues on server) """ + self._stopMonitoringTimer() + self.webodmTask = None + self._updateTaskButtons() + self.widget.webodmLogTextEdit.append( + "Stopped monitoring. The task is still running on the node -- see " + f"{self.widget.nodeDashboardUrl()} to follow or cancel it." + ) + + def _stopMonitoringTimer(self): if self.webodmTimer: self.webodmTimer.stop() self.webodmTimer.deleteLater() self.webodmTimer = None + + def onCancelTaskClicked(self): + """ + Cancel the monitored task on the node itself (unlike Stop Monitoring, + which only stops Slicer from watching it). + """ + if not self.webodmTask: + slicer.util.infoDisplay("No task is currently being monitored.") + return + + if not slicer.util.confirmYesNoDisplay( + "Cancel the monitored task on the node?\n\nThis cannot be undone." + ): + return + + try: + self.webodmTask.cancel() + except Exception as e: + slicer.util.warningDisplay( + f"Failed to cancel the task:\n{str(e)}\n\n" + f"You can also cancel it at {self.widget.nodeDashboardUrl()}" + ) + return + + self.widget.webodmLogTextEdit.append("Task canceled on the node.") + self._stopMonitoringTimer() self.webodmTask = None - self.widget.stopMonitoringButton.setEnabled(False) - self.widget.webodmLogTextEdit.append("Stopped monitoring.") + self._updateTaskButtons() + + def taskRecordPath(self, inputFolder, taskName): + """The record sits beside the results: WebODM_.json next to WebODM_/.""" + return os.path.join(inputFolder, f"WebODM_{taskName}.json") + + def writeTaskRecord(self, inputFolder, taskName, dashboardUrl, params, imageCount): + """ + Write down the tie between this folder and the node's task. + + The node's UUID is the only identifier that is unique by construction, but it + lives only on the node -- which forgets finished tasks after 48h by default. The + record is what survives that, plus Stop Monitoring and Slicer restarts, and it + makes an images folder self-describing: one .json per job submitted from it, + sitting next to the results folder it will produce. + """ + import datetime + record = { + "uuid": self.webodmTask.uuid, + "name": taskName, + "node": dashboardUrl, + "created": datetime.datetime.now().isoformat(timespec="seconds"), + "images_folder": inputFolder, + "image_count": imageCount, + "output_folder": f"WebODM_{taskName}", + "options": params, + } + path = self.taskRecordPath(inputFolder, taskName) + try: + with open(path, "w") as f: + json.dump(record, f, indent=2, sort_keys=True) + except Exception as e: + # A record is a convenience; never fail a live task over it. + self.widget.webodmLogTextEdit.append(f" (could not write task record: {e})") + return None + return path + + def readTaskRecords(self, inputFolder): + """uuid -> record, for every job submitted from this folder.""" + records = {} + try: + names = os.listdir(inputFolder) + except Exception: + return records + for fn in names: + if not (fn.startswith("WebODM_") and fn.endswith(".json")): + continue + try: + with open(os.path.join(inputFolder, fn)) as f: + rec = json.load(f) + except Exception: + continue # hand-edited or truncated; ignore rather than break the picker + if isinstance(rec, dict) and rec.get("uuid"): + records[rec["uuid"]] = rec + return records + + def describeTask(self, info, records=None): + """ + One line per task for the reconnect picker. + + Leads with the UUID: the picker returns the chosen string and we map it back by + index, so two tasks rendering the same text would attach the wrong one -- and + unnamed tasks with matching status/date/count do collide. The UUID is unique by + construction, and it is also the first thing the NodeODM dashboard shows, so it + is what you match against by eye. + """ + stamp = info.date_created.strftime("%Y-%m-%d %H:%M") if info.date_created else "?" + tag = " <- from this folder" if records and info.uuid in records else "" + return (f"{info.uuid[:8]} | {info.name or '(unnamed)'} | {info.status.name} | " + f"{stamp} UTC | {info.images_count} images{tag}") + + def onReconnectTaskClicked(self): + """ + Attach to a task that is already on the node -- left running by Stop Monitoring, + or started in an earlier Slicer session -- and resume monitoring it, so its + results can still be downloaded. + """ + if self.webodmTask is not None: + slicer.util.warningDisplay( + "A task is already being monitored.\n\nUse 'Stop Monitoring' first." + ) + return + + inputFolder = self.widget.inputFolderSelector.directory + if not inputFolder or not os.path.isdir(inputFolder): + slicer.util.errorDisplay( + "Select the masked images folder first - it is where the results are downloaded to." + ) + return + + try: + from pyodm import Node + except ImportError: + slicer.util.errorDisplay("pyodm module not found. Please install it via pip.") + return + + dashboardUrl = self.widget.nodeDashboardUrl() + node = Node(self.widget.nodeIPLineEdit.text.strip(), self.widget.nodePortSpinBox.value) + + try: + entries = node.get('/task/list') or [] + except Exception as e: + slicer.util.errorDisplay( + f"Could not reach NodeODM at {dashboardUrl}\n\n{str(e)}\n\n" + "Is the node running? Use 'Launch NodeODM' above to start it." + ) + return + + if not entries: + slicer.util.infoDisplay(f"The node at {dashboardUrl} has no tasks.") + return + + # /task/list returns UUIDs only, so ask each task for its name/status/date. + tasks = [] + for entry in entries: + uuid = entry.get('uuid') if isinstance(entry, dict) else None + if not uuid: + continue + try: + tasks.append(node.get_task(uuid).info()) + except Exception: + continue # vanished between listing and asking; skip it + + if not tasks: + slicer.util.warningDisplay( + f"The node at {dashboardUrl} listed tasks, but none of them could be read." + ) + return + + # Cross-reference the node's tasks against the records written from this folder, + # so the picker can say which of them are yours. + records = self.readTaskRecords(inputFolder) + tasks.sort(key=lambda i: i.date_created, reverse=True) + labels = [self.describeTask(i, records) for i in tasks] + + # PythonQt's binding for QInputDialog.getItem returns just the selected string + # (empty on cancel), not the (value, ok) tuple the C++/PyQt API uses. + chosen = qt.QInputDialog.getItem( + slicer.util.mainWindow(), + "Reconnect to Task", + f"Tasks on {dashboardUrl}:", + labels, + 0, + False, + ) + if not chosen or chosen not in labels: + return + + self.attachToTask(node, tasks[labels.index(chosen)], inputFolder, dashboardUrl, records) + + def attachToTask(self, node, info, inputFolder, dashboardUrl, records=None): + """Resume monitoring an existing node task and route its results to disk.""" + self.webodmTask = node.get_task(info.uuid) + + # A record written when we submitted the task is authoritative about where its + # results belong. Failing that, fall back to the task name (which is what names + # WebODM_), and for tasks created outside Slicer, which have no name, to + # the UUID. + record = (records or {}).get(info.uuid) + if record and record.get("output_folder"): + folderKey = record["output_folder"][len("WebODM_"):] + else: + folderKey = info.name or f"task_{info.uuid[:8]}" + self.webodmOutDir = os.path.join(inputFolder, f"WebODM_{folderKey}") + + self.widget.webodmLogTextEdit.clear() + self.widget.webodmLogTextEdit.append(f"Reconnected to '{folderKey}' on {dashboardUrl}") + self.widget.webodmLogTextEdit.append(f" node task UUID: {info.uuid}") + self.widget.webodmLogTextEdit.append(f" results will download to: {self.webodmOutDir}") + + self.lastWebODMOutputLineIndex = 0 + self._stopMonitoringTimer() + self.webodmTimer = qt.QTimer() + self.webodmTimer.setInterval(5000) + self.webodmTimer.timeout.connect(self.checkWebODMTaskStatus) + self.webodmTimer.start() + self._updateTaskButtons() + + # Poll once now rather than making the user wait for the first tick -- and if the + # task already finished, this downloads it immediately. + self.checkWebODMTaskStatus() + + def queuedTaskCount(self): + """ + How many tasks are QUEUED or RUNNING on the node (this one included), or None if + it can't be asked. Used to explain a task sitting at 'Queued, Progress: 0%'. + """ + try: + from pyodm import Node + node = Node(self.widget.nodeIPLineEdit.text.strip(), self.widget.nodePortSpinBox.value) + return node.info().task_queue_count + except Exception: + return None def checkWebODMTaskStatus(self): """ @@ -861,7 +1319,18 @@ def checkWebODMTaskStatus(self): self.widget.webodmLogTextEdit.append(line) self.lastWebODMOutputLineIndex += len(newLines) - self.widget.webodmLogTextEdit.append(f"Status: {info.status.name}, Progress: {info.progress}%") + statusLine = f"Status: {info.status.name}, Progress: {info.progress}%" + if info.status.name.lower() == "queued": + # "Queued, 0%" on its own reads as a hang. Say what it is waiting behind. + # NodeODM counts QUEUED+RUNNING including this task, so drop it to get the + # number actually ahead. + totalCount = self.queuedTaskCount() + if totalCount is not None and totalCount > 1: + statusLine += ( + f" -- {totalCount - 1} task(s) ahead of yours on this node. " + f"See {self.widget.nodeDashboardUrl()}" + ) + self.widget.webodmLogTextEdit.append(statusLine) cursor = self.widget.webodmLogTextEdit.textCursor() cursor.movePosition(qt.QTextCursor.End) self.widget.webodmLogTextEdit.setTextCursor(cursor) @@ -872,26 +1341,21 @@ def checkWebODMTaskStatus(self): self.widget.webodmLogTextEdit.append(f"Task completed! Downloading results to {self.webodmOutDir} ...") slicer.app.processEvents() try: + os.makedirs(self.webodmOutDir, exist_ok=True) self.webodmTask.download_assets(self.webodmOutDir) - slicer.util.infoDisplay(f"Results downloaded to:\\n{self.webodmOutDir}") + slicer.util.infoDisplay(f"Results downloaded to:\n{self.webodmOutDir}") except Exception as e: slicer.util.warningDisplay(f"Download failed: {str(e)}") - if self.webodmTimer: - self.webodmTimer.stop() - self.webodmTimer.deleteLater() - self.webodmTimer = None + self._stopMonitoringTimer() self.webodmTask = None - self.widget.stopMonitoringButton.setEnabled(False) + self._updateTaskButtons() elif info.status.name.lower() in ["failed", "canceled"]: self.widget.webodmLogTextEdit.append("Task failed or canceled. Stopping.") slicer.app.processEvents() - if self.webodmTimer: - self.webodmTimer.stop() - self.webodmTimer.deleteLater() - self.webodmTimer = None + self._stopMonitoringTimer() self.webodmTask = None - self.widget.stopMonitoringButton.setEnabled(False) + self._updateTaskButtons() def onImportModelClicked(self): """ @@ -902,13 +1366,22 @@ def onImportModelClicked(self): slicer.util.errorDisplay("No input folder selected.") return - # Search for WebODM output folders - webodm_dirs = [d for d in os.listdir(inputFolder) if d.startswith("WebODM_")] + # Results folders only. writeTaskRecord drops a WebODM_.json beside each + # results folder, and "WebODM_X.json" sorts after "WebODM_X", so matching on the + # prefix alone would pick the record file every time. + # + # Order by mtime, not by name: a name leads with the dataset name and a settings + # hash, so lexicographic order stops being chronological as soon as either + # differs between runs. mtime is when the results actually landed. + webodm_dirs = sorted( + (d for d in os.listdir(inputFolder) + if d.startswith("WebODM_") and os.path.isdir(os.path.join(inputFolder, d))), + key=lambda d: os.path.getmtime(os.path.join(inputFolder, d)) + ) if not webodm_dirs: slicer.util.errorDisplay("No WebODM output folders found.") return - # For now, use the first one found (could add selection dialog) latest_dir = os.path.join(inputFolder, webodm_dirs[-1]) odm_texturing = os.path.join(latest_dir, "odm_texturing") @@ -922,7 +1395,7 @@ def onImportModelClicked(self): return obj_path = os.path.join(odm_texturing, obj_files[0]) - slicer.util.infoDisplay(f"Importing model from:\\n{obj_path}") + slicer.util.infoDisplay(f"Importing model from:\n{obj_path}") try: modelNode = slicer.util.loadModel(obj_path) @@ -932,7 +1405,7 @@ def onImportModelClicked(self): layoutManager.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpView) slicer.util.infoDisplay("Model imported successfully!") except Exception as e: - slicer.util.errorDisplay(f"Failed to import model:\\n{str(e)}") + slicer.util.errorDisplay(f"Failed to import model:\n{str(e)}") class ODMLogic(ScriptedLoadableModuleLogic):