model-converter-python/d3/model/tools.py

63 lines
1.7 KiB
Python
Raw Normal View History

2016-12-02 14:52:01 +00:00
import os
from importlib import import_module
from . import formats
from .formats import *
2016-11-25 13:56:37 +00:00
from .basemodel import ModelParser, Exporter
2016-11-22 10:27:42 +00:00
2016-12-02 14:52:01 +00:00
from types import ModuleType
supported_formats = []
class ModelType:
def __init__(self, typename, inner_module):
self.typename = typename
self.inner_module = inner_module
def test_type(self, file):
return getattr(self.inner_module, 'is_' + self.typename)(file)
def create_parser(self, *args, **kwargs):
return getattr(self.inner_module, self.typename.upper() + 'Parser')(*args, **kwargs)
def create_exporter(self, *args, **kwargs):
return getattr(self.inner_module, self.typename.upper() + 'Exporter')(*args, **kwargs)
def find_type(filename, supported_formats):
for type in supported_formats:
if type.test_type(filename):
return type
for name in formats.__dict__:
if isinstance(formats.__dict__[name], ModuleType) and name != 'glob':
type = ModelType(name, formats.__dict__[name])
supported_formats.append(type)
2016-11-30 14:37:58 +00:00
def load_model(path, up_conversion = None):
2016-11-22 10:27:42 +00:00
parser = None
2016-12-02 14:52:01 +00:00
type = find_type(path, supported_formats)
2016-11-22 10:27:42 +00:00
2016-12-02 14:52:01 +00:00
if type is None:
2016-11-22 10:27:42 +00:00
raise Exception("File format not supported")
2016-12-02 14:52:01 +00:00
parser = type.create_parser(up_conversion)
2016-11-22 10:27:42 +00:00
parser.parse_file(path)
return parser
2016-11-22 14:23:53 +00:00
def export_model(model, path):
exporter = None
2016-12-02 14:52:01 +00:00
type = find_type(path, supported_formats)
2016-11-22 14:23:53 +00:00
2016-12-02 14:52:01 +00:00
if type is None:
raise Exception('File format is not supported')
2016-11-22 14:23:53 +00:00
2016-12-02 14:52:01 +00:00
exporter = type.create_exporter(model)
2016-11-22 14:23:53 +00:00
return exporter
2016-11-30 14:37:58 +00:00
def convert(input, output, up_conversion = None):
model = load_model(input, up_conversion)
2016-11-22 14:23:53 +00:00
exporter = export_model(model, output)
return str(exporter)