|
| 1 | +from ...core.data import GeoModel |
| 2 | +from ...core.data.encoders.converters import loading_model_injection |
| 3 | + |
| 4 | + |
| 5 | +def save_model(model: GeoModel, path: str): |
| 6 | + |
| 7 | + # TODO: Serialize to json |
| 8 | + model_json = model.model_dump_json(by_alias=True, indent=4) |
| 9 | + |
| 10 | + # TODO: Serialize to binary |
| 11 | + sp_binary = model.structural_frame.surface_points_copy.data.tobytes() |
| 12 | + ori_binary = model.structural_frame.orientations_copy.data.tobytes() |
| 13 | + |
| 14 | + # TODO: Putting both together |
| 15 | + binary_file = _to_binary(model_json, sp_binary + ori_binary) |
| 16 | + with open(path, 'wb') as f: |
| 17 | + f.write(binary_file) |
| 18 | + |
| 19 | +def load_model(path: str) -> GeoModel: |
| 20 | + with open(path, 'rb') as f: |
| 21 | + binary_file = f.read() |
| 22 | + |
| 23 | + # Get header length from first 4 bytes |
| 24 | + header_length = int.from_bytes(binary_file[:4], byteorder='little') |
| 25 | + |
| 26 | + # Split header and body |
| 27 | + header_json = binary_file[4:4 + header_length].decode('utf-8') |
| 28 | + body = binary_file[4 + header_length:] |
| 29 | + |
| 30 | + # Split body into surface points and orientations |
| 31 | + # They are equal size so we can split in half |
| 32 | + sp_binary = body[:len(body) // 2] |
| 33 | + ori_binary = body[len(body) // 2:] |
| 34 | + |
| 35 | + with loading_model_injection( |
| 36 | + surface_points_binary=sp_binary, |
| 37 | + orientations_binary=ori_binary |
| 38 | + ): |
| 39 | + model = GeoModel.model_validate_json(header_json) |
| 40 | + |
| 41 | + return model |
| 42 | + |
| 43 | + |
| 44 | +def _to_binary(header_json, body_) -> bytes: |
| 45 | + header_json_bytes = header_json.encode('utf-8') |
| 46 | + header_json_length = len(header_json_bytes) |
| 47 | + header_json_length_bytes = header_json_length.to_bytes(4, byteorder='little') |
| 48 | + file = header_json_length_bytes + header_json_bytes + body_ |
| 49 | + return file |
| 50 | + |
| 51 | + |
0 commit comments