Skip to content

Commit

Permalink
Fix Python 3.9 Windows file permission error in Fakely TFlite exporter (
Browse files Browse the repository at this point in the history
#936)

replacing the use of NamedTemporaryFile for creating a temporary file for export with mkstemp command and ensuring file removal afterward.
  • Loading branch information
jraynal authored Jan 31, 2024
1 parent caeea28 commit 872ccf8
Showing 1 changed file with 14 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.
# ==============================================================================
import os
from pathlib import Path
import tempfile
from typing import Callable

Expand Down Expand Up @@ -56,14 +57,20 @@ 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 automatically.
with tempfile.NamedTemporaryFile(suffix=DEFAULT_KERAS_EXPORT_EXTENTION) as tmp_file:
FakelyQuantKerasExporter(self.model,
self.is_layer_exportable_fn,
tmp_file.name,
verbose=False).export()
# Since exporter saves the model, we use a tmp path for saving, and then we delete it.
handle, tmp_file = tempfile.mkstemp(DEFAULT_KERAS_EXPORT_EXTENTION)
# Close handle right away, the file is going to be reopenned by Keras exporter
os.close(handle)
try:
custom_objects = FakelyQuantKerasExporter(self.model,
self.is_layer_exportable_fn,
tmp_file,
verbose=False).export()

model = keras_load_quantized_model(tmp_file.name)
model = keras_load_quantized_model(tmp_file)
# Ensures artifact is removed even in case of error
finally:
Path(tmp_file).unlink(missing_ok=True)

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 872ccf8

Please sign in to comment.