Beispiel #1
0
def create_stamp_pdf(survey, output_filename, questionnaire_ids):

    if questionnaire_ids is None:
        log.warn(_("There should be no need to stamp a SDAPS Project that uses LaTeX and does not have different questionnaire IDs printed on each sheet.\nI am going to do so anyways."))

    # Temporary directory for TeX files.
    tmpdir = tempfile.mkdtemp(prefix='sdaps-stamp-')

    try:
        latex.write_override(survey, os.path.join(tmpdir, 'sdaps.opt'), questionnaire_ids=questionnaire_ids)

        print(_("Running %s now multiple times to generate the stamped questionnaire.") % survey.defs.engine)
        latex.compile(survey.defs.engine, 'questionnaire.tex', tmpdir, inputs=[os.path.abspath(survey.path())])

        if not os.path.exists(os.path.join(tmpdir, 'questionnaire.pdf')):
            log.error(_("Error running \"%s\" to compile the LaTeX file.") % defs.latex_engine)
            raise AssertionError('PDF file not generated')

        shutil.move(os.path.join(tmpdir, 'questionnaire.pdf'), output_filename)

    except:
        log.error(_("An error occured during creation of the report. Temporary files left in '%s'." % tmpdir))

        raise

    shutil.rmtree(tmpdir)
Beispiel #2
0
def create_stamp_pdf(survey, output_filename, questionnaire_ids):

    if questionnaire_ids is None:
        log.warn(
            _("There should be no need to stamp a SDAPS Project that uses LaTeX and does not have different questionnaire IDs printed on each sheet.\nI am going to do so anyways."
              ))

    # Temporary directory for TeX files.
    tmpdir = tempfile.mkdtemp()

    try:
        # Similar to setuptex/setup.py, but we also set questionnaire IDs
        latex_override = open(os.path.join(tmpdir, 'sdaps.opt'), 'w')
        latex_override.write(
            '% This file exists to force the latex document into "final" mode.\n'
        )
        latex_override.write(
            '% It is parsed after the setup phase of the SDAPS class.\n\n')
        latex_override.write('\setcounter{surveyidlshw}{%i}\n' %
                             (survey.survey_id % (2**16)))
        latex_override.write('\setcounter{surveyidmshw}{%i}\n' %
                             (survey.survey_id / (2**16)))
        latex_override.write('\def\surveyid{%i}\n' % (survey.survey_id))
        latex_override.write('\def\globalid{%s}\n' %
                             (tex_quote_braces(survey.global_id)) if survey.
                             global_id is not None else '')
        latex_override.write('\\@STAMPtrue\n')
        latex_override.write('\\@PAGEMARKtrue\n')
        latex_override.write('\\@sdaps@draftfalse\n')
        if questionnaire_ids is not None:
            quoted_ids = [
                tex_quote_braces(str(id)) for id in questionnaire_ids
            ]
            latex_override.write('\def\questionnaireids{{%s}}\n' %
                                 '},{'.join(quoted_ids))
        latex_override.close()

        print _("Running %s now twice to generate the stamped questionnaire."
                ) % defs.latex_engine
        latex.compile('questionnaire.tex',
                      tmpdir,
                      inputs=[os.path.abspath(survey.path())])

        if not os.path.exists(os.path.join(tmpdir, 'questionnaire.pdf')):
            log.error(
                _("Error running \"%s\" to compile the LaTeX file.") %
                defs.latex_engine)
            raise AssertionError('PDF file not generated')

        shutil.move(os.path.join(tmpdir, 'questionnaire.pdf'), output_filename)

    except:
        log.error(
            _("An error occured during creation of the report. Temporary files left in '%s'."
              % tmpdir))

        raise

    shutil.rmtree(tmpdir)
Beispiel #3
0
def create_stamp_pdf(survey, output_filename, questionnaire_ids):

    if questionnaire_ids is None:
        log.warn(
            _(
                "There should be no need to stamp a SDAPS Project that uses LaTeX and does not have different questionnaire IDs printed on each sheet.\nI am going to do so anyways."
            )
        )

    # Temporary directory for TeX files.
    tmpdir = tempfile.mkdtemp()

    try:
        # Similar to setuptex/setup.py, but we also set questionnaire IDs
        latex_override = open(os.path.join(tmpdir, "sdaps.opt"), "w")
        latex_override.write('% This file exists to force the latex document into "final" mode.\n')
        latex_override.write("% It is parsed after the setup phase of the SDAPS class.\n\n")
        latex_override.write("\setcounter{surveyidlshw}{%i}\n" % (survey.survey_id % (2 ** 16)))
        latex_override.write("\setcounter{surveyidmshw}{%i}\n" % (survey.survey_id / (2 ** 16)))
        latex_override.write("\def\surveyid{%i}\n" % (survey.survey_id))
        latex_override.write(
            "\def\globalid{%s}\n" % (tex_quote_braces(survey.global_id)) if survey.global_id is not None else ""
        )
        latex_override.write("\\@STAMPtrue\n")
        latex_override.write("\\@PAGEMARKtrue\n")
        latex_override.write("\\@sdaps@draftfalse\n")
        if questionnaire_ids is not None:
            quoted_ids = [tex_quote_braces(str(id)) for id in questionnaire_ids]
            latex_override.write("\def\questionnaireids{{%s}}\n" % "},{".join(quoted_ids))
        latex_override.close()

        print _("Running %s now twice to generate the stamped questionnaire.") % defs.latex_engine
        latex.compile("questionnaire.tex", tmpdir, inputs=[os.path.abspath(survey.path())])

        if not os.path.exists(os.path.join(tmpdir, "questionnaire.pdf")):
            log.error(_('Error running "%s" to compile the LaTeX file.') % defs.latex_engine)
            raise AssertionError("PDF file not generated")

        shutil.move(os.path.join(tmpdir, "questionnaire.pdf"), output_filename)

    except:
        log.error(_("An error occured during creation of the report. Temporary files left in '%s'." % tmpdir))

        raise

    shutil.rmtree(tmpdir)
Beispiel #4
0
def create_stamp_pdf(survey, output_filename, questionnaire_ids):

    if questionnaire_ids is None:
        log.warn(
            _("There should be no need to stamp a SDAPS Project that uses LaTeX and does not have different questionnaire IDs printed on each sheet.\nI am going to do so anyways."
              ))

    # Temporary directory for TeX files.
    tmpdir = tempfile.mkdtemp(prefix='sdaps-stamp-')

    try:
        latex.write_override(survey,
                             os.path.join(tmpdir, 'sdaps.opt'),
                             questionnaire_ids=questionnaire_ids)

        print(
            _("Running %s now multiple times to generate the stamped questionnaire."
              ) % survey.defs.engine)
        latex.compile(survey.defs.engine,
                      'questionnaire.tex',
                      tmpdir,
                      inputs=[os.path.abspath(survey.path())])

        if not os.path.exists(os.path.join(tmpdir, 'questionnaire.pdf')):
            log.error(
                _("Error running \"%s\" to compile the LaTeX file.") %
                defs.latex_engine)
            raise AssertionError('PDF file not generated')

        shutil.move(os.path.join(tmpdir, 'questionnaire.pdf'), output_filename)

    except:
        log.error(
            _("An error occured during creation of the report. Temporary files left in '%s'."
              % tmpdir))

        raise

    shutil.rmtree(tmpdir)
def report(survey, filter, filename=None, papersize=None, small=0, suppress=None, tex_only=False):
    assert isinstance(survey, model.survey.Survey)

    # compile clifilter
    filter = clifilter.clifilter(survey, filter)

    # First: calculate buddies

    # init buddies
    survey.questionnaire.calculate.init()

    # iterate over sheets
    survey.iterate(
        survey.questionnaire.calculate.read,
        lambda: survey.sheet.valid and filter()
    )

    # do calculations
    survey.questionnaire.calculate.calculate()

    # Temporary directory for TeX files.
    if tex_only and filename:
        tmpdir = filename

        # Create directory
        os.makedirs(tmpdir)
    else:
        tmpdir = tempfile.mkdtemp(prefix='sdaps-report-')

    # Second: report buddies

    # init buddies
    survey.questionnaire.report.init(tmpdir, small, suppress)

    # Filename of output
    if filename is None and tex_only == False:
        filename = survey.new_path('report_%i.pdf')

    try:
        # iterate over sheets
        survey.iterate(
            survey.questionnaire.report.report,
            lambda: survey.sheet.valid and filter(),
            tmpdir
        )

        # Copy class and dictionary files
        if paths.local_run:
            cls_file = os.path.join(paths.source_dir, 'tex', 'sdapsreport.cls')
            dict_files = os.path.join(paths.build_dir, 'tex', '*.dict')
            dict_files = glob.glob(dict_files)
        else:
            cls_file = os.path.join(paths.prefix, 'share', 'sdaps', 'tex', 'sdapsreport.cls')
            dict_files = os.path.join(paths.prefix, 'share', 'sdaps', 'tex', '*.dict')
            dict_files = glob.glob(dict_files)

        shutil.copyfile(cls_file, os.path.join(tmpdir, 'sdapsreport.cls'))
        for dict_file in dict_files:
            shutil.copyfile(dict_file, os.path.join(tmpdir, os.path.basename(dict_file)))

        texfile = codecs.open(os.path.join(tmpdir, 'report.tex'), 'w', 'utf-8')

        author = _('author|Unknown')

        extra_info = []
        for key, value in survey.info.items():
            if key == 'Author':
                author = value
                continue

            extra_info.append('\\addextrainfo{%(key)s}{%(value)s}' % {'key': key, 'value': value})

        extra_info = '\n'.join(extra_info)
        texfile.write(r"""\documentclass[%(language)s,%(papersize)s]{sdapsreport}

    \usepackage{ifxetex}
    \ifxetex
    \else
      \usepackage[utf8]{inputenc}
    \fi
    \usepackage[%(language)s]{babel}

    \usepackage{xltxtra}
    \setmainfont{IPAPMincho}
    \setsansfont{IPAPGothic}
    \setmonofont{IPAGothic}
    \XeTeXlinebreaklocale "ja"

    \title{%(title)s}
    \subject{%(title)s}
    \author{%(author)s}

    \addextrainfo{%(turned_in)s}{%(count)i}
    %(extra_info)s

    \begin{document}

    \maketitle

    """ % {'language': _('tex language|english'),
           'title': _('sdaps report'),
           'turned_in': _('Turned in Questionnaires'),
           'title': survey.title,
           'author': author,
           'extra_info': extra_info,
           'count': survey.questionnaire.calculate.count,
           'papersize' : paper.get_tex_papersize(papersize)})

        survey.questionnaire.report.write(texfile, tmpdir)

        texfile.write(r"""
    \end{document}
    """)
        texfile.close()

        if tex_only:
            print(_("The TeX project with the report data is located at '%s'.") % tmpdir)
            return

        print(_("Running %s now multiple times to generate the report.") % survey.defs.engine)
        latex.compile(survey.defs.engine, 'report.tex', cwd=tmpdir)

        if not os.path.exists(os.path.join(tmpdir, 'report.pdf')):
            print(_("Error running \"%s\" to compile the LaTeX file.") % survey.defs.engine)
            raise AssertionError('PDF file not generated')

        shutil.move(os.path.join(tmpdir, 'report.pdf'), filename)

    except:
        print(_("An occured during creation of the report. Temporary files left in '%s'." % tmpdir))

        raise

    shutil.rmtree(tmpdir)
Beispiel #6
0
def setup(survey, questionnaire_tex, additionalqobjects=None, extra_files=[]):
    if os.access(survey.path(), os.F_OK):
        log.error(_('The survey directory already exists.'))
        return 1

    mime = mimetype(questionnaire_tex)
    if mime != 'text/x-tex' and mime != '':
        log.warn(
            _('Unknown file type (%s). questionnaire_tex should be of type text/x-tex.'
              ) % mime)
        log.warn(_('Will keep going, but expect failure!'))

    if additionalqobjects is not None:
        mime = mimetype(additionalqobjects)
        if mime != 'text/plain' and mime != '':
            log.error(
                _('Unknown file type (%s). additionalqobjects should be text/plain.'
                  ) % mime)
            return 1

    # Add the new questionnaire
    survey.add_questionnaire(model.questionnaire.Questionnaire())

    # Create the survey directory, and copy the tex file.
    os.makedirs(survey.path())
    try:
        shutil.copy(questionnaire_tex, survey.path('questionnaire.tex'))

        latex.write_override(survey, survey.path('sdaps.opt'), draft=True)

        # Copy class and dictionary files
        if paths.local_run:
            cls_extra_files = os.path.join(paths.source_dir, 'tex', '*.cls')
            cls_files = os.path.join(paths.source_dir, 'tex', 'class', 'build',
                                     'local', '*.cls')
            tex_files = os.path.join(paths.source_dir, 'tex', 'class', 'build',
                                     'local', '*.tex')
            sty_files = os.path.join(paths.source_dir, 'tex', 'class', 'build',
                                     'local', '*.sty')
            dict_files = os.path.join(paths.build_dir, 'tex', '*.dict')
        else:
            cls_extra_files = None
            cls_files = os.path.join(paths.prefix, 'share', 'sdaps', 'tex',
                                     '*.cls')
            tex_files = os.path.join(paths.prefix, 'share', 'sdaps', 'tex',
                                     '*.tex')
            sty_files = os.path.join(paths.prefix, 'share', 'sdaps', 'tex',
                                     '*.sty')
            dict_files = os.path.join(paths.prefix, 'share', 'sdaps', 'tex',
                                      '*.dict')

        def copy_to_survey(files_glob):
            files = glob.glob(files_glob)
            for file in files:
                shutil.copyfile(file, survey.path(os.path.basename(file)))

        if cls_extra_files is not None:
            copy_to_survey(cls_extra_files)
        copy_to_survey(cls_files)
        copy_to_survey(tex_files)
        copy_to_survey(sty_files)
        copy_to_survey(dict_files)

        for add_file in extra_files:
            if os.path.isdir(add_file):
                shutil.copytree(add_file,
                                survey.path(os.path.basename(add_file)))
            else:
                shutil.copyfile(add_file,
                                survey.path(os.path.basename(add_file)))

        print _("Running %s now twice to generate the questionnaire."
                ) % defs.latex_engine
        latex.compile('questionnaire.tex', cwd=survey.path())

        if not os.path.exists(survey.path('questionnaire.pdf')):
            print _("Error running \"%s\" to compile the LaTeX file."
                    ) % defs.latex_engine
            raise AssertionError('PDF file not generated')

        survey.defs.print_questionnaire_id = False
        survey.defs.print_survey_id = True

        # Parse qobjects
        try:
            sdapsfileparser.parse(survey)

            for qobject in survey.questionnaire.qobjects:
                qobject.setup.setup()
                qobject.setup.validate()

        except:
            log.error(
                _("Caught an Exception while parsing the SDAPS file. The current state is:"
                  ))
            print >> sys.stderr, unicode(survey.questionnaire)
            print >> sys.stderr, "------------------------------------"

            raise

        # Parse additionalqobjects
        if additionalqobjects:
            additionalparser.parse(survey, additionalqobjects)

        # Last but not least calculate the survey id
        survey.calculate_survey_id()

        if not survey.check_settings():
            log.error(
                _("Some combination of options and project properties do not work. Aborted Setup."
                  ))
            shutil.rmtree(survey.path())
            return 1

        # We need to now rebuild everything so that the correct ID is at the bottom
        # Dissable draft mode if the survey doesn't have questionnaire IDs
        latex.write_override(survey,
                             survey.path('sdaps.opt'),
                             draft=survey.defs.print_questionnaire_id)
        print _("Running %s now twice to generate the questionnaire."
                ) % defs.latex_engine
        os.remove(survey.path('questionnaire.pdf'))
        latex.compile('questionnaire.tex', survey.path())

        if not os.path.exists(survey.path('questionnaire.pdf')):
            print _("Error running \"%s\" to compile the LaTeX file."
                    ) % defs.latex_engine
            raise AssertionError('PDF file not generated')

        # Print the result
        print survey.title

        for item in survey.info.items():
            print u'%s: %s' % item

        print unicode(survey.questionnaire)

        log.logfile.open(survey.path('log'))

        survey.save()
        log.logfile.close()
    except:
        log.error(
            _("An error occured in the setup routine. The survey directory still exists. You can for example check the questionnaire.log file for LaTeX compile errors."
              ))
        raise
Beispiel #7
0
def setup(survey_dir, questionnaire_tex, engine, additionalqobjects=None, extra_files=[]):
    if os.access(survey_dir, os.F_OK):
        log.error(_('The survey directory already exists.'))
        return 1

    mime = mimetype(questionnaire_tex)
    if mime != 'text/x-tex' and mime != '':
        log.warn(_('Unknown file type (%s). questionnaire_tex should be of type text/x-tex.') % mime)
        log.warn(_('Will keep going, but expect failure!'))

    if additionalqobjects is not None:
        mime = mimetype(additionalqobjects)
        if mime != 'text/plain' and mime != '':
            log.error(_('Unknown file type (%s). additionalqobjects should be text/plain.') % mime)
            return 1

    # Create the survey directory, and copy the tex file.
    survey = model.survey.Survey.new(survey_dir)
    survey.defs.engine = engine

    # Add the new questionnaire
    survey.add_questionnaire(model.questionnaire.Questionnaire())

    try:
        shutil.copy(questionnaire_tex, survey.path('questionnaire.tex'))

        latex.write_override(survey, survey.path('sdaps.opt'), draft=True)

        # Copy class and dictionary files
        if paths.local_run:
            cls_extra_files = os.path.join(paths.source_dir, 'tex', '*.cls')
            cls_files = os.path.join(paths.source_dir, 'tex', 'class', 'build', 'local', '*.cls')
            tex_files = os.path.join(paths.source_dir, 'tex', 'class', 'build', 'local', '*.tex')
            sty_files = os.path.join(paths.source_dir, 'tex', 'class', 'build', 'local', '*.sty')
            dict_files = os.path.join(paths.build_dir, 'tex', '*.dict')
        else:
            cls_extra_files = None
            cls_files = os.path.join(paths.prefix, 'share', 'sdaps', 'tex', '*.cls')
            tex_files = os.path.join(paths.prefix, 'share', 'sdaps', 'tex', '*.tex')
            sty_files = os.path.join(paths.prefix, 'share', 'sdaps', 'tex', '*.sty')
            dict_files = os.path.join(paths.prefix, 'share', 'sdaps', 'tex', '*.dict')

        def copy_to_survey(files_glob):
            files = glob.glob(files_glob)
            for file in files:
                shutil.copyfile(file, survey.path(os.path.basename(file)))

        if cls_extra_files is not None:
            copy_to_survey(cls_extra_files)
        copy_to_survey(cls_files)
        copy_to_survey(tex_files)
        copy_to_survey(sty_files)
        copy_to_survey(dict_files)

        for add_file in extra_files:
            if os.path.isdir(add_file):
                shutil.copytree(add_file, survey.path(os.path.basename(add_file)))
            else:
                shutil.copyfile(add_file, survey.path(os.path.basename(add_file)))

        print(_("Running %s now multiple times to generate the questionnaire.") % survey.defs.engine)
        latex.compile(survey.defs.engine, 'questionnaire.tex', cwd=survey.path())

        if not os.path.exists(survey.path('questionnaire.pdf')):
            print(_("Error running \"%s\" to compile the LaTeX file.") % defs.latex_engine)
            raise AssertionError('PDF file not generated')

        survey.defs.print_questionnaire_id = False
        survey.defs.print_survey_id = True

        # Parse qobjects
        try:
            sdapsfileparser.parse(survey)

            for qobject in survey.questionnaire.qobjects:
                qobject.setup.setup()
                qobject.setup.validate()

        except:
            log.error(_("Caught an Exception while parsing the SDAPS file. The current state is:"))
            print(str(survey.questionnaire), file=sys.stderr)
            print("------------------------------------", file=sys.stderr)

            raise

        # Parse additionalqobjects
        if additionalqobjects:
            additionalparser.parse(survey, additionalqobjects)

        # Last but not least calculate the survey id
        survey.calculate_survey_id()

        if not survey.check_settings():
            log.error(_("Some combination of options and project properties do not work. Aborted Setup."))
            shutil.rmtree(survey.path())
            return 1

        # We need to now rebuild everything so that the correct ID is at the bottom
        # Dissable draft mode if the survey doesn't have questionnaire IDs
        latex.write_override(survey, survey.path('sdaps.opt'), draft=survey.defs.print_questionnaire_id)
        print(_("Running %s now multiple imes to generate the questionnaire.") % survey.defs.engine)
        os.remove(survey.path('questionnaire.pdf'))
        latex.compile(survey.defs.engine, 'questionnaire.tex', survey.path())

        if not os.path.exists(survey.path('questionnaire.pdf')):
            print(_("Error running \"%s\" to compile the LaTeX file.") % survey.defs.engine)
            raise AssertionError('PDF file not generated')

        # Print the result
        print(survey.title)

        for item in list(survey.info.items()):
            print('%s: %s' % item)

        log.logfile.open(survey.path('log'))

        survey.save()
        log.logfile.close()
    except:
        log.error(_("An error occured in the setup routine. The survey directory still exists. You can for example check the questionnaire.log file for LaTeX compile errors."))
        raise
Beispiel #8
0
def report(survey, filter, filename=None, papersize=None, small=0, suppress=None, tex_only=False):
    assert isinstance(survey, model.survey.Survey)

    # compile clifilter
    filter = clifilter.clifilter(survey, filter)

    # First: calculate buddies

    # init buddies
    survey.questionnaire.calculate.init()

    # iterate over sheets
    survey.iterate(
        survey.questionnaire.calculate.read,
        lambda: survey.sheet.valid and filter()
    )

    # do calculations
    survey.questionnaire.calculate.calculate()

    # Temporary directory for TeX files.
    if tex_only and filename:
        tmpdir = filename

        # Create directory
        os.makedirs(tmpdir)
    else:
        tmpdir = tempfile.mkdtemp()

    # Second: report buddies

    # init buddies
    survey.questionnaire.report.init(tmpdir, small, suppress)

    # Filename of output
    if filename is None and tex_only == False:
        filename = survey.new_path('report_%i.pdf')

    try:
        # iterate over sheets
        survey.iterate(
            survey.questionnaire.report.report,
            lambda: survey.sheet.valid and filter(),
            tmpdir
        )

        # Copy class and dictionary files
        if paths.local_run:
            cls_file = os.path.join(paths.source_dir, 'tex', 'sdapsreport.cls')
            dict_files = os.path.join(paths.build_dir, 'tex', '*.dict')
            dict_files = glob.glob(dict_files)
        else:
            cls_file = os.path.join(paths.prefix, 'share', 'sdaps', 'tex', 'sdapsreport.cls')
            dict_files = os.path.join(paths.prefix, 'share', 'sdaps', 'tex', '*.dict')
            dict_files = glob.glob(dict_files)

        shutil.copyfile(cls_file, os.path.join(tmpdir, 'sdapsreport.cls'))
        for dict_file in dict_files:
            shutil.copyfile(dict_file, os.path.join(tmpdir, os.path.basename(dict_file)))

        texfile = codecs.open(os.path.join(tmpdir, 'report.tex'), 'w', 'utf-8')

        author = _('author|Unknown')

        extra_info = []
        for key, value in survey.info.iteritems():
            if key == 'Author':
                author = value
                continue

            extra_info.append(u'\\addextrainfo{%(key)s}{%(value)s}' % {'key': key, 'value': value})

        extra_info = u'\n'.join(extra_info)
        texfile.write(r"""\documentclass[%(language)s,%(papersize)s]{sdapsreport}

    \usepackage{ifxetex}
    \ifxetex
    \else
      \usepackage[utf8]{inputenc}
    \fi
    \usepackage[%(language)s]{babel}

    \title{%(title)s}
    \subject{%(title)s}
    \author{%(author)s}

    \addextrainfo{%(turned_in)s}{%(count)i}
    %(extra_info)s

    \begin{document}

    \maketitle

    """ % {'language': _('tex language|english'),
           'title': _(u'sdaps report'),
           'turned_in': _('Turned in Questionnaires'),
           'title': survey.title,
           'author': author,
           'extra_info': extra_info,
           'count': survey.questionnaire.calculate.count,
           'papersize' : paper.get_tex_papersize(papersize)})

        survey.questionnaire.report.write(texfile, tmpdir)

        texfile.write(r"""
    \end{document}
    """)

        if tex_only:
            print _("The TeX project with the report data is located at '%s'.") % tmpdir
            return

        print _("Running %s now twice to generate the report.") % defs.latex_engine
        latex.compile('report.tex', cwd=tmpdir)

        if not os.path.exists(os.path.join(tmpdir, 'report.pdf')):
            print _("Error running \"%s\" to compile the LaTeX file.") % defs.latex_engine
            raise AssertionError('PDF file not generated')

        shutil.move(os.path.join(tmpdir, 'report.pdf'), filename)

    except:
        print _("An occured during creation of the report. Temporary files left in '%s'." % tmpdir)

        raise

    shutil.rmtree(tmpdir)
Beispiel #9
0
def setup(survey, questionnaire_tex, additionalqobjects=None, extra_files=[]):
    if os.access(survey.path(), os.F_OK):
        log.error(_('The survey directory already exists.'))
        return 1

    mime = mimetype(questionnaire_tex)
    if mime != 'text/x-tex' and mime != '':
        log.warn(_('Unknown file type (%s). questionnaire_tex should be of type text/x-tex.') % mime)
        log.warn(_('Will keep going, but expect failure!'))

    if additionalqobjects is not None:
        mime = mimetype(additionalqobjects)
        if mime != 'text/plain' and mime != '':
            log.error(_('Unknown file type (%s). additionalqobjects should be text/plain.') % mime)
            return 1

    # Add the new questionnaire
    survey.add_questionnaire(model.questionnaire.Questionnaire())

    # Create the survey directory, and copy the tex file.
    os.makedirs(survey.path())
    try:
        shutil.copy(questionnaire_tex, survey.path('questionnaire.tex'))

        write_latex_override_file(survey, draft=True)

        # Copy class and dictionary files
        if paths.local_run:
            cls_file = os.path.join(paths.source_dir, 'tex', 'sdaps.cls')
            code128_file = os.path.join(paths.source_dir, 'tex', 'code128.tex')
            qrcode_style = os.path.join(paths.source_dir, 'tex', 'qrcode.sty')
            dict_files = os.path.join(paths.build_dir, 'tex', '*.dict')
            dict_files = glob.glob(dict_files)
        else:
            cls_file = os.path.join(paths.prefix, 'share', 'sdaps', 'tex', 'sdaps.cls')
            code128_file = os.path.join(paths.prefix, 'share', 'sdaps', 'tex', 'code128.tex')
            qrcode_style = os.path.join(paths.prefix, 'share', 'sdaps', 'tex', 'qrcode.sty')
            dict_files = os.path.join(paths.prefix, 'share', 'sdaps', 'tex', '*.dict')
            dict_files = glob.glob(dict_files)

        shutil.copyfile(cls_file, survey.path('sdaps.cls'))
        shutil.copyfile(code128_file, survey.path('code128.tex'))
        shutil.copyfile(qrcode_style, survey.path('qrcode.sty'))
        for dict_file in dict_files:
            shutil.copyfile(dict_file, survey.path(os.path.basename(dict_file)))

        for add_file in extra_files:
            shutil.copyfile(add_file, survey.path(os.path.basename(add_file)))

        print _("Running %s now twice to generate the questionnaire.") % defs.latex_engine
        latex.compile('questionnaire.tex', cwd=survey.path())

        if not os.path.exists(survey.path('questionnaire.pdf')):
            print _("Error running \"%s\" to compile the LaTeX file.") % defs.latex_engine
            raise AssertionError('PDF file not generated')

        survey.defs.print_questionnaire_id = False
        survey.defs.print_survey_id = True

        # Parse qobjects
        try:
            sdapsfileparser.parse(survey)

            # for qobject in survey.questionnaire.qobjects:
            #     qobject.setup.validate()

        except Exception, e:
            log.error(_("Caught an Exception while parsing the SDAPS file. The current state is:"))
            print >>sys.stderr, unicode(survey.questionnaire)
            print >>sys.stderr, "------------------------------------"

            raise e

        # Parse additionalqobjects
        if additionalqobjects:
            additionalparser.parse(survey, additionalqobjects)

        # Last but not least calculate the survey id
        survey.calculate_survey_id()

        if not survey.check_settings():
            log.error(_("Some combination of options and project properties do not work. Aborted Setup."))
            shutil.rmtree(survey.path())
            return 1

        # We need to now rebuild everything so that the correct ID is at the bottom
        write_latex_override_file(survey)
        print _("Running %s now twice to generate the questionnaire.") % defs.latex_engine
        os.remove(survey.path('questionnaire.pdf'))
        latex.compile('questionnaire.tex', survey.path())

        if not os.path.exists(survey.path('questionnaire.pdf')):
            print _("Error running \"%s\" to compile the LaTeX file.") % defs.latex_engine
            raise AssertionError('PDF file not generated')

        # Print the result
        print survey.title

        for item in survey.info.items():
            print u'%s: %s' % item

        print unicode(survey.questionnaire)

        log.logfile.open(survey.path('log'))

        survey.save()
        log.logfile.close()