示例#1
0
文件: latex.py 项目: sdaps/sdaps
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)
示例#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(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)
示例#3
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
示例#4
0
文件: __init__.py 项目: sdaps/sdaps
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
示例#5
0
文件: tasks.py 项目: sdaps/sdaps_web
def build_survey(self, djsurvey_id):
    """Creates the SDAPS project and database for the survey.
    This process should be run on an already initialized survey that
    has a questionnaire written to it."""
    djsurvey = get_object_or_404(models.Survey, pk=djsurvey_id)

    assert(djsurvey.initialized == False)

    lock_id = ('%s_build_survey' % djsurvey.id)

    with task_lock(lock_id, self.app.oid) as acquired:
        if acquired:
            import sdaps.setuptex as setup
            from sdaps.utils import latex
            from sdaps.setuptex import sdapsfileparser
            survey = model.survey.Survey.new(djsurvey.path)

            latex.write_override(survey, survey.path('sdaps.opt'), draft=True)
            if not utils.atomic_latex_compile(djsurvey.path, 'questionnaire.tex', need_sdaps=True):
                # XXX: The sqlite file should not be created immediately!
                os.unlink(survey.path('survey.sqlite'))
                return False

            # We now have the .sdaps file that can be parsed
            # Defaults
            survey.defs.print_questionnaire_id = False
            survey.defs.print_survey_id = True
            survey.defs.engine = defs.latex_engine

            survey.add_questionnaire(model.questionnaire.Questionnaire())

            # 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 AssertionError("Exception while parsing the SDAPS file.")

            # 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.")
                os.unlink(survey.path('survey.sqlite'))
                return False

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

            if not utils.atomic_latex_compile(djsurvey.path, 'questionnaire.tex', need_sdaps=True):
                os.unlink(survey.path('survey.sqlite'))
                return False
            # TODO: If something goes wrong while initializing the survey,
            # there should be an option to delete the files.
            survey.save()

            djsurvey.initialized = True
            djsurvey.title = survey.title
            if 'Author' in survey.info:
                djsurvey.author = survey.info['Author']
            djsurvey.save()

            log.logfile.close()
示例#6
0
def build_survey(self, djsurvey_id):
    """Creates the SDAPS project and database for the survey.
    This process should be run on an already initialized survey that
    has a questionnaire written to it."""
    djsurvey = get_object_or_404(models.Survey, pk=djsurvey_id)

    assert (djsurvey.initialized == False)

    lock_id = ('%s_build_survey' % djsurvey.id)

    with task_lock(lock_id, self.app.oid) as acquired:
        if acquired:
            import sdaps.setuptex as setup
            from sdaps.utils import latex
            from sdaps.setuptex import sdapsfileparser
            survey = model.survey.Survey.new(djsurvey.path)

            latex.write_override(survey, survey.path('sdaps.opt'), draft=True)
            if not utils.atomic_latex_compile(
                    djsurvey.path, 'questionnaire.tex', need_sdaps=True):
                # XXX: The sqlite file should not be created immediately!
                os.unlink(survey.path('survey.sqlite'))
                return False

            # We now have the .sdaps file that can be parsed
            # Defaults
            survey.defs.print_questionnaire_id = False
            survey.defs.print_survey_id = True
            survey.defs.engine = defs.latex_engine

            survey.add_questionnaire(model.questionnaire.Questionnaire())

            # 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 AssertionError("Exception while parsing the SDAPS file.")

            # 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."
                )
                os.unlink(survey.path('survey.sqlite'))
                return False

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

            if not utils.atomic_latex_compile(
                    djsurvey.path, 'questionnaire.tex', need_sdaps=True):
                os.unlink(survey.path('survey.sqlite'))
                return False
            # TODO: If something goes wrong while initializing the survey,
            # there should be an option to delete the files.
            survey.save()

            djsurvey.initialized = True
            djsurvey.title = survey.title
            if 'Author' in survey.info:
                djsurvey.author = survey.info['Author']
            djsurvey.save()

            log.logfile.close()