Skip to content

Commit

Permalink
Use context manager for temporary file (#865)
Browse files Browse the repository at this point in the history
Fix for an issue during a file removal (occurs in Windows):
Use tempfile.NamedTemporaryFile as a context manager, which handles close/removal of the file automatically, and will also clean up the file if an error occurs during export.
  • Loading branch information
jgerityneurala authored Nov 27, 2023
1 parent 49ada26 commit c1551a4
Showing 1 changed file with 6 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,13 @@ def export(self):
"""
# Use Keras exporter to quantize model's weights before converting it to TFLite.
# Since exporter saves the model, we use a tmp path for saving, and then we delete it.
_, tmp_file = tempfile.mkstemp(TMP_KERAS_EXPORT_FORMAT)
custom_objects = FakelyQuantKerasExporter(self.model,
self.is_layer_exportable_fn,
tmp_file).export()
# Since exporter saves the model, we use a tmp path for saving, and then we delete it automatically.
with tempfile.NamedTemporaryFile(suffix=TMP_KERAS_EXPORT_FORMAT) as tmp_file:
custom_objects = FakelyQuantKerasExporter(self.model,
self.is_layer_exportable_fn,
tmp_file.name).export()

model = keras_load_quantized_model(tmp_file)
os.remove(tmp_file)
model = keras_load_quantized_model(tmp_file.name)

self.exported_model = tf.lite.TFLiteConverter.from_keras_model(model).convert()
Logger.info(f'Exporting FQ tflite model to: {self.save_model_path}')
Expand Down

0 comments on commit c1551a4

Please sign in to comment.