Exemplo n.º 1
0
    def _decode_one(self, val):

        if isinstance(val, (list, tuple)):
            for i in range(len(val)):
                val[i] = self._decode_one(val[i])
            return val

        elif isinstance(val, dict):
            return self._decoder(val)

        elif isinstance(val, str):
            if val.startswith("<PINTQUANT>"):
                val = re.sub("<PINTQUANT>", "", val)
                return Units.new(val)

            elif val.startswith("<RELATIVISM-PROGRAM>"):
                return RelGlobals.get_rel_instance()

            elif val.startswith("<RELOBJFILE>"):
                val = re.sub("<RELOBJFILE>", "", val)
                obj = self.load(val,
                                join_path(self.current_path, val, is_dir=True))
                self.need_parent.append(obj)
                return obj

            elif val.startswith("<RELSET>"):
                filename = re.sub("<RELSET>", "", val)
                fullpath = join_path(self.current_path,
                                     filename,
                                     ext=RelContainer.setfile_extension)
                with open(fullpath, "r") as f:
                    data = f.readlines()
                mod_name = data.pop(0).strip()
                clss_name = data.pop(0).strip()
                mod = importlib.import_module(mod_name)
                clss = getattr(mod, clss_name)

                val = json.loads("\n".join(data))
                if isinstance(val, dict):
                    for k, v in val.items():
                        val[k] = clss.load(clss, v)
                elif isinstance(val, (list, tuple)):
                    for i in range(len(val)):
                        val[i] = clss.load(clss, val[i])
                else:
                    raise UnexpectedIssue("this really shouldnt happen")

            elif val.startswith("<RELOBJ>"):
                val = re.sub("<RELOBJ>", "", val)
                ind = val.index(";")
                class_data, val = val[:ind], val[ind + 1:]
                mod_name, clss_name = class_data.split(",")
                mod = importlib.import_module(mod_name)
                clss = getattr(mod, clss_name)
                val = json.loads(val)
                return clss.load(clss, val)

        return val
Exemplo n.º 2
0
 def get_datafile_fullpath(self):
     """
     fullpath of datafile
     """
     return join_path(self.get_data_dir(),
                      self.get_data_filename(),
                      ext=self.datafile_extension)
Exemplo n.º 3
0
    def validate_child_name(self, child, new_name):
        if new_name in self.projects:
            err_mess("Project named '{0}' already exists!".format(new_name))
            return False
        if new_name == "see":
            err_mess("'see' is a protected keyword. Choose another name")
            return False

        # if no path, we have to wait until after path is selected to check.
        # this is verified in create_proj()
        if child.path is not None:
            newpath = join_path(child.path,
                                child.get_data_filename(new_name),
                                is_dir=True)
            if os.path.exists(newpath):
                err_mess(
                    "Something already exists at path '{0}'".format(newpath))
                return False

            # update projects file
            try:
                del self.projects[child.name]
            except KeyError:
                pass
            self.projects[new_name] = child.get_data_dir()
            self.write_proj_file()

        return True
Exemplo n.º 4
0
 def update_recents(self):
     """
     update recents arr to include last arr
     """
     recents_dir = self.get_path("recents", "dir")
     os.rename(
         self.get_path(self.get_data_filename(), "wav"),
         join_path(recents_dir, str(time.time_ns()), ext=".wav")
     )
Exemplo n.º 5
0
    def rename(self, name=None):
        """
        cat: meta
        dev: call this method via super, and implement renaming of files other than 
        datafile and its self.path directory
        """
        old_name = self.name
        if old_name is not None:
            old_data_dir = self.get_data_dir()
            old_datafile_name = self.get_data_filename()

        if name is None:
            p("Give this {0} a name".format(self.reltype))
            name = inpt("obj")
        else:
            name = inpt_validate(name, 'obj')

        # validate
        if hasattr(self.parent, "validate_child_name"):
            if self.parent.validate_child_name(self, name):
                self.name = name
                info_block("Named '{0}'".format(name))
            else:
                err_mess("Invalid name")
                self.rename()
        else:
            if Settings.is_debug():
                show_error(
                    AttributeError(
                        "Parent obj '{0}' does not have validate_child_name".
                        format(self.parent)))
            else:
                try:
                    log_err(
                        "Parent object type {0} has no 'validate_child_name' method"
                        .format(self.parent.reltype))
                except AttributeError:
                    log_err(
                        "Parent object '{0}' of '{1}' has no 'validate_child_name' method"
                        .format(self.parent, self))
            self.name = name
            info_block("Named '{0}'".format(name))

        # if actual renaming and not an initial naming
        if old_name is not None:
            new_data_dir = self.get_data_dir()
            # rename dir
            os.rename(old_data_dir, new_data_dir)

            # rename datafile (which is in newdatadir now)
            old_datafile = join_path(new_data_dir,
                                     old_datafile_name,
                                     ext=self.datafile_extension)
            new_datafile = self.get_datafile_fullpath()
            os.rename(old_datafile, new_datafile)
Exemplo n.º 6
0
    def __init__(self, reldata_dir, proj_filename):
        section_head("Initializing Program")

        RelGlobals.set_rel_instance(self)

        self.relfile_path = join_path(reldata_dir, proj_filename)

        # set default output
        self.output = "Built-in Output"
        self.reltype = "Program"

        # maps name : path to that proj's datafile
        self.projects = self.read_proj_file()
        self.current_open_proj = None
Exemplo n.º 7
0
 def see_proj(self, proj_name, proj_path):
     info_block("Previewing Project '{0}'".format(proj_name))
     fullpath = join_path(
         proj_path,
         proj_name + ".Project." + RelSavedObj.datafile_extension)
     with open(fullpath, "r") as f:
         data = json.load(f)
     info_title("Path: " + data["path"])
     info_line("Audio file: " + str(data["file"]))
     info_line("Children:")
     children = [
         re.sub(r"<.*>", "", i).split(".") for i in data["children"]
     ]
     children = ["{0} '{1}'".format(i[1], i[0]) for i in children]
     info_list(children)
Exemplo n.º 8
0
    def load(self, filename, directory=""):
        """
        load and return object from a file
        """
        prev_path = self.current_path
        self.current_path = directory
        path = join_path(directory, filename + "." + RelSavedObj.datafile_extension)

        with open(path, "r") as f:
            attrs = json.load(f, object_hook=self._decoder)

        attrs["mode"] = "load"

        self.current_path = prev_path
        mod = importlib.import_module(attrs.pop("__module__"))
        obj_class = getattr(mod, attrs.pop("__class__"))

        obj = obj_class(**attrs)
        for i in self.need_parent:
            i.parent = obj
        self.need_parent = []

        return obj
Exemplo n.º 9
0
    def get_path(self, filename, extension="obj"):
        """
        get path to a file or dir 
        args:
            extension: "obj" for datafile_extension, "dir" for directory, or "wav"
        """
        is_dir = False
        if extension == "obj":
            extension = self.datafile_extension
        elif extension in ("wav", ):
            pass
        elif extension == "dir":
            is_dir = True
            extension = None
        else:
            raise UnexpectedIssue(
                "Unrecognized extension '{0}'. Add it in RelObject.get_path".
                format(extension))

        path = join_path(self.get_data_dir(),
                         filename,
                         ext=extension,
                         is_dir=is_dir)
        return path
Exemplo n.º 10
0
### Initialize
import os, time, sys
SESS_START = time.time()

from src.utility import suppress_output
from src.path import join_path
from src.output_and_prompting import style

with style("cyan, bold"):
    print("\n***** RELATIVISM *****\n")

# paths

RELATIVISM_DIR = os.path.dirname(os.path.abspath(__file__))
RELDATA_DIR = join_path(RELATIVISM_DIR, "data/", is_dir=True)
os.makedirs(RELDATA_DIR, exist_ok=True)
ERROR_LOG = join_path(RELDATA_DIR, "errors.log")
DATA_FILE = join_path(RELDATA_DIR, "data.json")
SETTINGS_FILE = join_path(RELDATA_DIR, "settings.json")
PROJFILE_NAME = "projects.relativism-data"

# parameters

MAX_SESS_LOGS = 20


from src.relativism import *
from src.debug import *
from src.output_and_prompting import *
from src.globals import RelGlobals, Settings, init_globals, save_globals
Exemplo n.º 11
0
 def get_setfile_fullpath(self, attr_name, path):
     return join_path(
         path,
         self.get_set_filename(attr_name) + "." + self.setfile_extension)
Exemplo n.º 12
0
 def get_data_dir(self):
     """
     get the directory of this object's files
     """
     return join_path(self.path, self.get_data_filename(), is_dir=True)