Coverage for collectra/pipelines/handlers.py: 20.80%

125 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1"""Artefact handling and persistence classes for Collectra workflows. 

2 

3This module provides specialized handlers for saving workflow configurations 

4and artifacts to different storage formats. It supports both directory-based 

5and zip-based storage options with proper model artifact management. 

6 

7The handlers manage: 

8 - Workflow configuration serialization 

9 - Machine learning model artifact storage 

10 - File system operations for different output formats 

11 - Model versioning and cleanup operations 

12 

13Classes: 

14 DataHandler: Abstract base class for data handling operations 

15 DirectoryHandler: Handler for directory-based workflow storage 

16 ZipHandler: Handler for zip-based workflow storage 

17""" 

18 

19import os 

20import shutil 

21import tempfile 

22import zipfile 

23from typing import Any 

24from pydantic import BaseModel, ConfigDict 

25from datetime import datetime 

26from pathlib import Path 

27 

28import yaml 

29 

30from collectra.pipelines.base import Pipeline 

31from collectra.tasks.base import Task 

32from collectra.utils import error_msg, processing_msg, success_msg 

33 

34 

35class DataHandler(BaseModel): 

36 """Abstract base class for workflow data handling operations. 

37 

38 Provides common functionality for saving workflow configurations and 

39 managing machine learning model artifacts across different storage formats. 

40 

41 Attributes: 

42 pipeline (Pipeline): The workflow pipeline to save. 

43 """ 

44 

45 model_config = ConfigDict(arbitrary_types_allowed=True) 

46 

47 pipeline: Any 

48 

49 def save(self): 

50 """Save the workflow configuration and artifacts. 

51 

52 Raises: 

53 NotImplementedError: This method must be implemented by subclasses. 

54 """ 

55 raise NotImplementedError( 

56 "If this is being called, the incorrect handler is not assigned." 

57 ) 

58 

59 def get_models(self, task: Task) -> tuple[str, str]: 

60 """Extract current and previous model paths from a machine learning task. 

61 

62 Args: 

63 task: A task exposing a model attribute. 

64 

65 Returns: 

66 tuple[str, str]: Current model path and old model path. 

67 """ 

68 task_config = self.pipeline.data.get(task.name, {}) 

69 return str(getattr(task, "model", "") or ""), str( 

70 task_config.get("old_model", "") 

71 ) 

72 

73 def has_model(self, task: Task) -> bool: 

74 """Return whether a task exposes a model artifact. 

75 

76 Args: 

77 task: Task to inspect. 

78 

79 Returns: 

80 bool: True if the task is a machine learning task, False otherwise. 

81 """ 

82 if not hasattr(task, "model"): 

83 error_message = f"Task {task.name} does not expose a model. Skipping..." 

84 print(error_msg(error_message)) 

85 return False 

86 return True 

87 

88 def _save_config(self, tmp_dir: Path) -> None: 

89 """Save the workflow configuration to a YAML file. 

90 

91 Args: 

92 tmp_dir (Path): Temporary directory to save the configuration file. 

93 """ 

94 pipeline_yaml = tmp_dir / "pipeline.yaml" 

95 data = self.pipeline.get_config() 

96 with open(pipeline_yaml, "w") as f: 

97 for key in data: 

98 f.write( 

99 yaml.dump( 

100 {key: data[key]}, default_flow_style=False, sort_keys=False 

101 ) 

102 ) 

103 f.write("\n") 

104 

105 

106class DirectoryHandler(DataHandler): 

107 """Handler for saving workflows as directory structures. 

108 

109 Saves workflow configurations and artifacts to a directory structure, 

110 making them easy to inspect and modify manually. 

111 """ 

112 

113 def save(self): 

114 """Save the workflow and its artifacts to a directory structure. 

115 

116 Creates a temporary directory for staging files, then moves them to 

117 the final output directory location. 

118 """ 

119 with tempfile.TemporaryDirectory() as tmpdirname: 

120 out_dir = self.pipeline.get_out_dir() 

121 tmp_dir = Path(tmpdirname) 

122 self._save_artifacts(tmp_dir) 

123 self._save_config(tmp_dir) 

124 out_dir.mkdir( 

125 parents=True, exist_ok=True 

126 ) # Ensure the output directory exists 

127 for item in tmp_dir.iterdir(): 

128 shutil.move(item, out_dir / item.name) 

129 success_message = ( 

130 f"Workflow {self.pipeline.name} was saved successfully to {out_dir}" 

131 ) 

132 print(success_msg(success_message)) 

133 

134 def _save_artifacts(self, tmp_dir: Path) -> None: 

135 """Save machine learning model artifacts to the temporary directory. 

136 

137 Processes all machine learning tasks in the pipeline to save their model 

138 artifacts. Handles model versioning, file movement, and cleanup of old models. 

139 

140 Args: 

141 tmp_dir (Path): Temporary directory to save artifacts to. 

142 """ 

143 old_models: dict[str, Path] = dict() 

144 for task_item in self.pipeline.tasks: 

145 if not self.has_model(task_item): 

146 continue 

147 task = task_item 

148 model, old_model = self.get_models(task) 

149 if not model: 

150 error_message = f"Task {task.name} does not have a model associated with it. Skipping..." 

151 print(error_msg(error_message)) 

152 continue 

153 # Ensure the model path is a Path object 

154 model_path = Path(model) 

155 task_model_path = f"{task.name}-{datetime.now().strftime('%Y%m%d_%H%M%S')}-best.pt" # Default model path for the task 

156 new_model = old_model != model 

157 if not (model_path.exists() and model_path.is_file()): 

158 error_message = f"Model for {task.name} does not point to a valid file or doesn't exist: {model_path}. Attempting to download..." 

159 print(error_msg(error_message)) 

160 task.load(model_path.name) 

161 model_path = Path(model_path.name) 

162 new_model = True 

163 if new_model: 

164 print( 

165 f"Moving model {model_path} to temporary directory with new name {task_model_path}..." 

166 ) 

167 shutil.move(model_path, tmp_dir / task_model_path) 

168 if old_model and Path(old_model).exists(): 

169 old_models[old_model] = Path(old_model) 

170 self.pipeline.data[task.name]["model"] = task_model_path 

171 else: 

172 old_models.pop(model, None) 

173 processing_message = f"Model {model_path} already exists. Copying to temporary directory..." 

174 print(processing_msg(processing_message)) 

175 shutil.copy(model_path, tmp_dir / model_path.name) 

176 self.pipeline.data[task.name]["model"] = model_path.name 

177 

178 for old_model in old_models: 

179 if old_models[old_model].exists(): 

180 print(f"Removing old model {old_models[old_model]}...") 

181 os.remove(old_models[old_model]) 

182 

183 

184class ZipHandler(DataHandler): 

185 """Handler for saving workflows as compressed zip files. 

186 

187 Saves workflow configurations and artifacts to a single zip file, 

188 making them portable and easy to distribute. 

189 """ 

190 

191 def save(self): 

192 """Save the workflow and its artifacts to a compressed zip file. 

193 

194 Creates a temporary directory for staging files, then compresses 

195 them into a single zip file at the output location. 

196 

197 Raises: 

198 ValueError: If the output directory is not specified. 

199 """ 

200 with tempfile.TemporaryDirectory() as tmpdirname: 

201 if not self.pipeline.out_dir: 

202 raise ValueError("Output directory is not specified.") 

203 tmp_dir = Path(tmpdirname) 

204 self._save_artifacts(tmp_dir) 

205 self._save_config(tmp_dir) 

206 with zipfile.ZipFile( 

207 f"{self.pipeline.out_dir}", "w", zipfile.ZIP_DEFLATED, allowZip64=True 

208 ) as zipf: 

209 for root, _, files in os.walk(tmp_dir): 

210 for file in files: 

211 zipf.write(os.path.join(root, file), file) 

212 processing_message = ( 

213 f"Saved {file} to {Path(self.pipeline.out_dir) / file}" 

214 ) 

215 print(processing_msg(processing_message)) 

216 success_message = f"Workflow {self.pipeline.name} was saved successfully at {self.pipeline.out_dir}" 

217 print(success_msg(success_message)) 

218 

219 def _save_artifacts(self, tmp_dir: Path) -> None: 

220 """Save machine learning model artifacts to the temporary directory for zip compression. 

221 

222 Processes all machine learning tasks in the pipeline to save their model 

223 artifacts for zip archive creation. Handles model extraction from existing 

224 zip files and version management. 

225 

226 Args: 

227 tmp_dir (Path): Temporary directory to save artifacts to. 

228 

229 Raises: 

230 ValueError: If the output directory is not specified. 

231 """ 

232 if not self.pipeline.out_dir: 

233 raise ValueError("Output directory is not specified.") 

234 for task_item in self.pipeline.tasks: 

235 if not self.has_model(task_item): 

236 continue 

237 task = task_item 

238 model, old_model = self.get_models(task) 

239 if not model: 

240 error_message = f"Task {task.name} does not have a model associated with it. Skipping..." 

241 print(error_msg(error_message)) 

242 continue 

243 model_path = Path(model) 

244 task_model_path = ( 

245 f"{task.name}-{datetime.now().strftime('%Y%m%d_%H%M%S')}-best.pt" 

246 ) 

247 new_model: bool = old_model != model 

248 with zipfile.ZipFile(self.pipeline.out_dir, "r") as zipf: 

249 if not model_path.name in zipf.namelist(): 

250 task.load(model_path.name) 

251 model_path = Path(model_path.name) 

252 new_model = True 

253 if new_model: 

254 print( 

255 f"Moving model {model_path} to temporary directory with new name {task_model_path}..." 

256 ) 

257 shutil.move(model_path, tmp_dir / task_model_path) 

258 self.pipeline.data[task.name]["model"] = task_model_path 

259 else: 

260 processing_message = f"Model {model_path} already exists. Copying to temporary directory..." 

261 zipf.extract(str(model_path.name), tmp_dir) 

262 print(processing_msg(processing_message)) 

263 shutil.copy(model_path, tmp_dir / model_path.name) 

264 self.pipeline.data[task.name]["model"] = model_path.name