コード例 #1
0
    def choice_langs(self):
        """Discover all languages for these choices.

        Returns:
            list: Alphabetized list of languages.

        Raises:
            InvalidLanguageException: If languages of first row differ from
                languages in any other row.
        """
        langs = set()
        for datum in self.data:
            these_langs = set()
            for k in datum:
                if k == 'label':
                    these_langs.add('')  # Default language
                elif k.startswith('label::'):
                    lang = k[len('label::'):]
                    these_langs.add(lang)
            if not langs:
                langs = these_langs
            elif langs != these_langs:
                msg = 'In choice list {}, different languages found: {} and {}'
                msg = msg.format(self.list_name, langs, these_langs)
                raise InvalidLanguageException(msg)
        lang_list = sorted(list(langs))
        return lang_list
コード例 #2
0
    def labels(self, lang):
        """Get the labels for this choice list in the desired language.

        Args:
            lang (str): The language in which to return the choice labels.

        Returns:
            list: Correctly ordered list of choice labels.

        Raises:
            InvalidLanguageException
        """
        lang_col = 'label::{}'.format(lang) if lang else 'label'
        try:
            labels = [d[lang_col] for d in self.data]
            return labels
        except (KeyError, IndexError):
            msg = 'Language {} not found in choice list {}.'\
                .format(lang, self.list_name)
            raise InvalidLanguageException(msg)
コード例 #3
0
    def labels(self, lang=''):
        """Get the labels for this choice list in the desired language.

        Args:
            lang (str): The language in which to return the choice labels.

        Returns:
            list: Correctly ordered list of choice labels.

        Raises:
            InvalidLanguageException
        """
        label_variations = []
        if lang:
            label_variations += \
                [x.format(lang) for x in ('label::{}', 'label:{}')]
        else:
            label_variations.append('label')

        try:
            col_header = ''
            for label in label_variations:
                if label in self.data[0]:
                    col_header = label
            if not col_header:
                raise KeyError
            return [d[col_header] for d in self.data]
        except (KeyError, IndexError):
            msg = 'InvalidLanguageException: ' \
                  'Language \'{}\' not found in choice list \'{}\'.\n' \
                  'You may want to check for the following:\n' \
                  '- Are the languages in the \'survey\' and \'choices\' ' \
                  'worksheets consistent?\n' \
                  '- Is there an issue with \'default_language\' in the ' \
                  '\'settings\' worksheet?'\
                .format(lang, self.list_name)
            raise InvalidLanguageException(msg)
コード例 #4
0
ファイル: odkchoices.py プロジェクト: pmaengineering/ppp
    def labels(self, lang=""):
        """Get the labels for this choice list in the desired language.

        Args:
            lang (str): The language in which to return the choice labels.

        Returns:
            list: Correctly ordered list of choice labels.

        Raises:
            InvalidLanguageException
        """
        label_variations = []
        if lang:
            label_variations += [
                x.format(lang) for x in ("label::{}", "label:{}")
            ]
        else:
            label_variations.append("label")

        try:
            col_header = ""
            for label in label_variations:
                if label in self.data[0]:
                    col_header = label
            if not col_header:
                raise KeyError
            return [d[col_header] for d in self.data]
        except (KeyError, IndexError):
            msg = ("InvalidLanguageException: "
                   "Language '{}' not found in choice list '{}'.\n"
                   "You may want to check for the following:\n"
                   "- Are the languages in the 'survey' and 'choices' "
                   "worksheets consistent?\n"
                   "- Is there an issue with 'default_language' in the "
                   "'settings' worksheet?".format(lang, self.list_name))
            raise InvalidLanguageException(msg)
コード例 #5
0
    def labels(self, lang):
        """Get the labels for this choice list in the desired language.

        Args:
            lang (str): The language in which to return the choice labels.

        Returns:
            list: Correctly ordered list of choice labels.

        Raises:
            InvalidLanguageException
        """
        label_variations = ['label']
        if lang:
            label_variations += \
                [x.format(lang) for x in ('label::{}', 'label:{}')]
        try:
            for label in label_variations:
                if label in self.data[0]:
                    return [d[label] for d in self.data]
        except (KeyError, IndexError):
            msg = 'Language {} not found in choice list {}.'\
                .format(lang, self.list_name)
            raise InvalidLanguageException(msg)
コード例 #6
0
def convert_file(in_file, language=None, outpath=None, **kwargs):
    """Run ODK form conversion.

    Args:
        in_file (str): Path to load source file.
        language (str or None): Language to render form.
        outpath (str or None): Path to save converted file.
        **format (str): File format to be output.
        **debug (bool): Debugging on or off.
        **highlight (bool): Highlighting on or off.

    Raises:
        InvalidLanguageException: Language related.
        OdkChoicesError: Choice or choice list related.
        OdkFormError: General form related exception.
    """

    set_template_env(kwargs["style"] if "style" in kwargs else "default")

    form = OdkForm.from_file(in_file)

    try:
        output = None
        output_format = kwargs["format"] if "format" in kwargs else "html"
        if output_format == "text":
            output = form.to_text(lang=language, **kwargs)

        elif output_format in ("html", "doc"):
            output = form.to_html(lang=language, **kwargs)

        if outpath:
            if os.path.isdir(outpath) and not os.path.exists(outpath):
                os.makedirs(outpath)
            if os.path.isdir(outpath):
                base_filename = os.path.basename(os.path.splitext(in_file)[0])
                lang = "-" + language if language else ""
                options_affix = ("-" + kwargs["template"]
                                 if "template" in kwargs and kwargs["template"]
                                 not in ("standard", "minimal") else "")
                out_file = "{}{}{}{}.{}".format(outpath, base_filename, lang,
                                                options_affix, output_format)

                if isinstance(out_file, list):
                    if out_file[0] == "/":
                        out_file = out_file[1:]
            else:
                out_file = outpath
            with open(out_file, mode="w", encoding="utf-8") as file:
                file.write(output)
            print(out_file)
        else:
            try:
                print(output)
            except BrokenPipeError:  # If output is piped.
                signal(SIGPIPE, SIG_DFL)
                print(output)
    except InvalidLanguageException as err:
        if str(err):
            raise InvalidLanguageException(err)
        elif language is None:
            msg = ("InvalidLanguageException: An unknown error occurred when "
                   "attempting to convert form. If a language was not "
                   "supplied, please supply and try again.")
            raise InvalidLanguageException(msg)
    except OdkException as err:
        raise OdkException(err)
コード例 #7
0
def convert_file(in_file, language=None, outpath=None, **kwargs):
    """Run ODK form conversion.

    Args:
        in_file (str): Path to load source file.
        language (str or None): Language to render form.
        outpath (str or None): Path to save converted file.
        **format (str): File format to be output.
        **debug (bool): Debugging on or off.
        **highlight (bool): Highlighting on or off.

    Raises:
        InvalidLanguageException: Language related.
        OdkChoicesError: Choice or choice list related.
        OdkFormError: General form related exception.
    """
    form = OdkForm.from_file(in_file)

    try:
        output = None
        output_format = \
            kwargs['format'] if 'format' in kwargs else 'html'
        if output_format == 'text':
            output = form.to_text(lang=language, **kwargs)

        elif output_format in ('html', 'doc'):
            output = form.to_html(lang=language, **kwargs)

        if outpath:
            if os.path.isdir(outpath) and not os.path.exists(outpath):
                os.makedirs(outpath)
            if os.path.isdir(outpath):
                base_filename = os.path.basename(os.path.splitext(in_file)[0])
                lang = '-' + language if language else ''
                options_affix = '-' + kwargs['preset'] \
                    if 'preset' in kwargs and kwargs['preset'] != 'developer' \
                    else ''
                out_file = '{}{}{}{}.{}'.format(outpath, base_filename, lang,
                                                options_affix, output_format)

                if isinstance(out_file, list):
                    if out_file[0] == '/':
                        out_file = out_file[1:]
            else:
                out_file = outpath
            with open(out_file, mode='w', encoding='utf-8') as file:
                file.write(output)
            print(out_file)
        else:
            try:
                print(output)
            except BrokenPipeError:  # If output is piped.
                try:
                    signal(SIGPIPE, SIG_DFL)
                # noinspection PyBroadException
                except:
                    pass
                print(output)
    except InvalidLanguageException as err:
        if str(err):
            raise InvalidLanguageException(err)
        elif language is None:
            msg = 'InvalidLanguageException: An unknown error occurred when ' \
                  'attempting to convert form. If a language was not ' \
                  'supplied, please supply and try again.'
            raise InvalidLanguageException(msg)
    except OdkException as err:
        raise OdkException(err)