OpenEnergyPlatform / omi

Repository for the Open Metadata Integration (OMI). For metadata definition see metadata repo:
https://github.com/OpenEnergyPlatform/metadata
GNU Affero General Public License v3.0
7 stars 4 forks source link

Use OMI translate in Python #41

Closed nesnoj closed 2 years ago

nesnoj commented 2 years ago

I expected OMI to work in Python using translate(), I tried

from omi.cli import translate
translate('oep-v1.4', 'oep-v1.4', 'out.json', 'in.json')

but it outputs

Usage: oep-v1.4 [OPTIONS] FILE_PATH
Try 'oep-v1.4 --help' for help.

Error: Got unexpected extra arguments (e p - v 1 . 4)

and exits Python. What's wrong here?

MGlauer commented 2 years ago

This looks like the wrong function call. Everything in the cli.py is intended to be called via the command line interface (hence the name). They look like callable python functions, but the @-wrappers actually change how the function call works. What you want is what is inside the function, i.e.:

from omi.dialects import get_dialect

file_path = "in.json"
o = "out.json" # or None for printing
f = "oep-v1.4"
t = "oep-v1.4"

with open(file_path, "r") as infile:
        from_dialect = get_dialect(f)()
        obj = from_dialect.parse(infile.read())
        to_dialect = get_dialect(t)()
        s = to_dialect.compile_and_render(obj)
        if o:
            with open(o, "w") as outfile:
                outfile.write(s)
        else:
            print(s)

Instead of loading the dialects dynamically (get_dialect(f)(), etc.), you can also use the respective dialect directly: from_dialect = to_dialect = OEP_V_1_4_Dialect

nesnoj commented 2 years ago

Thanks @MGlauer, works like a charm :+1: