Example #1
0
    def convert(self, infile, output_dir, report_dir):
        """
        Convert a module's code, code converted will be save in output_dir, and a report will be save in report_dir.

        Args:
            infile (str): The script to convert.
            output_dir (str): The path to save converted file.
            report_dir (str): The path to save report file.
        """
        in_file_split = _path_split(infile)
        in_file_split[-1], _ = _get_name_ext(in_file_split[-1])
        module_name = '.'.join(in_file_split)
        with open(infile, 'r') as file:
            content = ''.join(file.readlines())

        self._infile = infile
        self._tree = pasta.parse(content)
        self._report.clear()
        try:
            logger.info("Script file is %s", infile)
            logger.info("Start converting %s", module_name)
            self._report.append('[Start Convert]')
            self._ast_editor = AstEditVisitor()
            self._ast_editor.process(self._tree)
            self._report.extend(self._ast_editor.get_logs())
            self._report.append('[Convert Over]')
            dest_file = os.path.join(output_dir, os.path.basename(infile))
            with os.fdopen(os.open(dest_file, self.flags, self.modes),
                           'w') as file:
                file.write(pasta.dump(self._tree))
            logger.info("Convert success. Result is wrote to %s.", dest_file)
        except ScriptNotSupport as error:
            self._report.append('[ScriptNotSupport] ' + error.message)
            self._report.append('[Convert failed]')
            raise error
        except Exception as error:
            self._report.clear()
            raise error
        finally:
            if self._report:
                dest_report_file = os.path.join(
                    report_dir,
                    '_'.join(os.path.basename(infile).split('.')[:-1]) +
                    '_report.txt')
                with os.fdopen(
                        os.open(dest_report_file, self.flags, self.modes),
                        'a') as file:
                    file.write('\n'.join(self._report))
                logger.info("Convert report is saved in %s", dest_report_file)
Example #2
0
    def convert_api(source_code):
        """
        Convert api_name in code to MindSpore api, if api_name is a python api, code will not convert.

        Args:
            source_code (ast.Call): The ast node to convert.
        Returns:
            str, the converted code.
        """
        ast_node = pasta.parse(source_code).body[0].value
        check_context = False
        replaced_code = AstEditVisitor().mapping_api(ast_node, check_context)
        return replaced_code
Example #3
0
class Converter:
    """Convert class"""

    flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
    modes = stat.S_IWUSR | stat.S_IRUSR

    def __init__(self):
        self._tree = None
        self._infile = None
        self._code_analyzer = None
        self._ast_editor = None
        self._report = []

    def convert(self, infile, output_dir, report_dir):
        """
        Convert a module's code, code converted will be save in output_dir, and a report will be save in report_dir.

        Args:
            infile (str): The script to convert.
            output_dir (str): The path to save converted file.
            report_dir (str): The path to save report file.
        """
        in_file_split = _path_split(infile)
        in_file_split[-1], _ = _get_name_ext(in_file_split[-1])
        module_name = '.'.join(in_file_split)
        with open(infile, 'r') as file:
            content = ''.join(file.readlines())

        self._infile = infile
        self._tree = pasta.parse(content)
        self._report.clear()
        try:
            logger.info("Script file is %s", infile)
            logger.info("Start converting %s", module_name)
            self._report.append('[Start Convert]')
            self._ast_editor = AstEditVisitor()
            self._ast_editor.process(self._tree)
            self._report.extend(self._ast_editor.get_logs())
            self._report.append('[Convert Over]')
            dest_file = os.path.join(output_dir, os.path.basename(infile))
            with os.fdopen(os.open(dest_file, self.flags, self.modes),
                           'w') as file:
                file.write(pasta.dump(self._tree))
            logger.info("Convert success. Result is wrote to %s.", dest_file)
        except ScriptNotSupport as error:
            self._report.append('[ScriptNotSupport] ' + error.message)
            self._report.append('[Convert failed]')
            raise error
        except Exception as error:
            self._report.clear()
            raise error
        finally:
            if self._report:
                dest_report_file = os.path.join(
                    report_dir,
                    '_'.join(os.path.basename(infile).split('.')[:-1]) +
                    '_report.txt')
                with os.fdopen(
                        os.open(dest_report_file, self.flags, self.modes),
                        'a') as file:
                    file.write('\n'.join(self._report))
                logger.info("Convert report is saved in %s", dest_report_file)

    @staticmethod
    def convert_api(source_code):
        """
        Convert api_name in code to MindSpore api, if api_name is a python api, code will not convert.

        Args:
            source_code (ast.Call): The ast node to convert.
        Returns:
            str, the converted code.
        """
        ast_node = pasta.parse(source_code).body[0].value
        check_context = False
        replaced_code = AstEditVisitor().mapping_api(ast_node, check_context)
        return replaced_code