From 58784ae2667a8e76b9c1d2aa32765a30900a09a7 Mon Sep 17 00:00:00 2001
From: mhby1g21 <mhby1g21@soton.ac.uk>
Date: Wed, 4 Dec 2024 21:48:59 +0000
Subject: [PATCH] modified run_shifter to be thread safe and fixed the steps
 when image is shifted

---
 scripts/debug_tool/tabs/shifter_tab.py | 34 ++++++++++++++----
 scripts/simple_tab.py                  | 49 ++++++++++++++++++++------
 2 files changed, 66 insertions(+), 17 deletions(-)

diff --git a/scripts/debug_tool/tabs/shifter_tab.py b/scripts/debug_tool/tabs/shifter_tab.py
index d532b5d..7add01b 100644
--- a/scripts/debug_tool/tabs/shifter_tab.py
+++ b/scripts/debug_tool/tabs/shifter_tab.py
@@ -104,18 +104,38 @@ class ShifterTab(QWidget):
         scrollbar.setValue(scrollbar.maximum())
 
     def run_shifter(self):
+        """GUI version of shifter - calls the thread-safe version"""
         if not self.input_file_path:
             QMessageBox.warning(self, "Warning", "Please select an input file first")
-            return
+            return False
         
         self.update_status("\nRunning image shifter...")
-        success, _ = run_command(
-            self, 
-            self.cmd_text.toPlainText(),
-            self.update_status
-        )
+        success, _ = self.run_shifter_process(self.update_status)
         
         if success and os.path.exists(self.shifted_image_path):
             self.update_status(f"Shifted image saved to: {self.shifted_image_path}")
             update_preview(self.output_preview, self.shifted_image_path, 
-                         error_callback=self.update_status)
\ No newline at end of file
+                         error_callback=self.update_status)
+        return success
+    
+    def run_shifter_process(self, status_callback=None):
+        """Thread-safe version of shifter that doesn't use GUI components"""
+        try:
+            if not self.input_file_path:
+                raise ValueError("No input file selected")
+
+            # Construct command without using GUI components
+            conda_dir = self.config_reader.config["condaDir"]
+            material_env = self.config_reader.config["materialEnv"]
+            shifter_script = os.path.join(self.config_reader.directories['scriptDir'], "shifter.py")
+            
+            command = f'"{conda_dir}\\condabin\\activate.bat" {material_env} && ' \
+                     f'python "{shifter_script}" "{self.input_file_path}" "{self.shifted_image_path}"'
+            
+            # Run the command
+            return run_command(None, command, status_callback)
+            
+        except Exception as e:
+            if status_callback:
+                status_callback(f"Error in shifter process: {str(e)}")
+            return False, str(e)
\ No newline at end of file
diff --git a/scripts/simple_tab.py b/scripts/simple_tab.py
index 750eb08..3f66b8d 100644
--- a/scripts/simple_tab.py
+++ b/scripts/simple_tab.py
@@ -45,17 +45,41 @@ class PipelineWorker(QThread):
         self.progress.emit("Cleaning EdgeNet output directory...")
     
     def copy_file(self):
-        self.progress.emit("Copying input file to scripts/360monodepthexecution...")
+        # Determine which file to use as input
+        self.tab.depth.depth_input_path = self.tab.shifter.shifted_image_path if self.tab.should_shift_image else self.tab.input_path
+        
+        if self.tab.should_shift_image:
+            self.progress.emit("Copying shifted image to scripts/360monodepthexecution...")
+        else:
+            self.progress.emit("Copying input file to scripts/360monodepthexecution...")
+            
         self.tab.depth.copy_file()
         
     def shift_image(self):
         print("Starting shift_image")  # Debug print
-        if not self.tab.shift_image_check.isChecked():
+        if not self.tab.should_shift_image:
             self.progress.emit("Skipping image shift...")
             return
-        self.progress.emit("Shifting input image...")
-        self.tab.shifter.run_shifter()
-        print("Completed shift_image")  # Debug print
+            
+        try:
+            self.progress.emit("Shifting input image...")
+            # Set input path for shifter
+            self.tab.shifter.input_file_path = self.tab.input_path
+            # Use the thread-safe version
+            success, output = self.tab.shifter.run_shifter_process(self.progress.emit)
+            
+            if not success:
+                raise RuntimeError(f"Image shifting failed: {output}")
+            
+            print("Completed shift_image")
+            
+            # Change material recognition input file path to shifted image
+            self.tab.material.input_file_path = self.tab.shifter.shifted_image_path
+            
+            return self.tab.shifter.shifted_image_path
+        except Exception as e:
+            print(f"Shift image failed: {str(e)}")
+            raise
         
     def run_depth_estimation(self):
         print("Starting depth_estimation")  # Debug print
@@ -107,7 +131,7 @@ class PipelineWorker(QThread):
         self.progress.emit("Running EdgeNet enhance360.py and infer360.py...")
 
         try:
-            self.tab.edge_net.include_top = self.tab.include_top_check.isChecked()
+            self.tab.edge_net.include_top = self.tab.should_include_top  # Use cached state
             self.tab.edge_net._run_edge_net_process()
             print("Completed edge_net")
         except Exception as e:
@@ -124,8 +148,8 @@ class PipelineWorker(QThread):
     
     def run_pipeline(self):
         self.clean_temp_files()
-        self.copy_file()
         self.shift_image()
+        self.copy_file()
         self.run_depth_estimation()
         self.run_material_recognition()
         self.run_edge_net()
@@ -138,6 +162,10 @@ class SimpleTab(QWidget):
         self.config_reader = config_reader
         self.input_path = None
         self.pipeline_thread = None
+    
+        # Store states that will be used by worker thread
+        self.should_shift_image = False
+        self.should_include_top = False
         
         # Initialize module instances
         self.shifter = ShifterTab(self.config_reader)
@@ -244,9 +272,6 @@ class SimpleTab(QWidget):
         self.shift_image_check.setStyleSheet("QCheckBox { margin: 5px; background-color: #3e3e3e;}")
         options_layout.addWidget(self.shift_image_check)
 
-        #TODO: FIX THIS, BREAKS THE APP WHEN ENABLED AND PIPELINE IS RUN
-        self.shift_image_check.setEnabled(False)
-
         # SSC Model selection
         ssc_model_layout = QHBoxLayout()
         ssc_model_label = QLabel("SSC Model:")
@@ -577,6 +602,10 @@ class SimpleTab(QWidget):
         if self.pipeline_thread and self.pipeline_thread.isRunning():
             QMessageBox.warning(self, "Warning", "Pipeline is already running")
             return
+        
+        # Cache checkbox states before starting thread
+        self.should_shift_image = self.shift_image_check.isChecked()
+        self.should_include_top = self.include_top_check.isChecked()
             
         # Show progress bar and update status
         self.progress_bar.show()
-- 
GitLab