extract_metadata: add support for ufp file extraction

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
This commit is contained in:
Arksine 2021-03-21 11:16:59 -04:00 committed by Eric Callahan
parent ecbf663b18
commit eaf35ded0c
1 changed files with 42 additions and 2 deletions

View File

@ -13,8 +13,14 @@ import sys
import base64
import traceback
import io
import tempfile
import zipfile
import shutil
from PIL import Image
UFP_MODEL_PATH = "/3D/model.gcode"
UFP_THUMB_PATH = "/Metadata/thumbnail.png"
def log_to_stderr(msg):
sys.stderr.write(f"{msg}\n")
sys.stderr.flush()
@ -656,8 +662,38 @@ def extract_metadata(file_path):
metadata[key] = result
return metadata
def main(path, filename):
def extract_ufp(ufp_path, dest_path):
if not os.path.isfile(ufp_path):
log_to_stderr(f"UFP file Not Found: {ufp_path}")
sys.exit(-1)
thumb_name = os.path.splitext(
os.path.basename(dest_path))[0] + ".png"
dest_thumb_dir = os.path.join(os.path.dirname(dest_path), ".thumbs")
dest_thumb_path = os.path.join(dest_thumb_dir, thumb_name)
try:
with tempfile.TemporaryDirectory() as tmp_dir_name:
tmp_thumb_path = ""
with zipfile.ZipFile(ufp_path) as zf:
tmp_model_path = zf.extract(
UFP_MODEL_PATH, path=tmp_dir_name)
if UFP_THUMB_PATH in zf.namelist():
tmp_thumb_path = zf.extract(
UFP_THUMB_PATH, path=tmp_dir_name)
shutil.move(tmp_model_path, dest_path)
if tmp_thumb_path:
if not os.path.exists(dest_thumb_dir):
os.mkdir(dest_thumb_dir)
shutil.move(tmp_thumb_path, dest_thumb_path)
finally:
try:
os.remove(ufp_path)
except Exception:
log_to_stderr(f"Error removing ufp file: {ufp_path}")
def main(path, filename, ufp):
file_path = os.path.join(path, filename)
if ufp is not None:
extract_ufp(ufp, file_path)
metadata = {}
if not os.path.isfile(file_path):
log_to_stderr(f"File Not Found: {file_path}")
@ -690,5 +726,9 @@ if __name__ == "__main__":
metavar='<path>',
help="optional absolute path for file"
)
parser.add_argument(
"-u", "--ufp", metavar="<ufp file>", default=None,
help="optional path of ufp file to extract"
)
args = parser.parse_args()
main(args.path, args.filename)
main(args.path, args.filename, args.ufp)