コード例 #1
0
ファイル: setup.py プロジェクト: alfonsodg/sdaps
def setup(survey, cmdline):
    if os.access(survey.path(), os.F_OK):
        log.error(_('The survey directory already exists.'))
        return 1

    questionnaire_tex = cmdline['questionnaire.tex']
    additionalqobjects = cmdline['additional_questions']

    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.mkdir(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')
            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')
            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'))
        for dict_file in dict_files:
            shutil.copyfile(dict_file, survey.path(os.path.basename(dict_file)))

        for add_file in cmdline['add']:
            shutil.copyfile(add_file, survey.path(os.path.basename(add_file)))

        print _("Running %s now twice to generate the questionnaire.") % defs.latex_engine
        subprocess.call([defs.latex_engine, '-halt-on-error',
                         '-interaction', 'batchmode', 'questionnaire.tex'],
                        cwd=survey.path())
        # And again, without the draft mode
        subprocess.call([defs.latex_engine, '-halt-on-error',
                         '-interaction', 'batchmode', '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)
        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'))
        subprocess.call([defs.latex_engine, '-halt-on-error',
                         '-interaction', 'batchmode', 'questionnaire.tex'],
                        cwd=survey.path())
        # And again, without the draft mode
        subprocess.call([defs.latex_engine, '-halt-on-error',
                         '-interaction', 'batchmode', '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')

        # 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()
コード例 #2
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
コード例 #3
0
ファイル: setup.py プロジェクト: jnm/sdaps
def setup(survey, cmdline):

    if os.access(survey.path(), os.F_OK):
        log.error(_('The survey directory already exists.'))
        return 1

    questionnaire_odt = cmdline['questionnaire.odt']
    questionnaire_pdf = cmdline['questionnaire.pdf']
    additionalqobjects = cmdline['additional_questions']

    mime = mimetype(questionnaire_odt)
    if mime != 'application/vnd.oasis.opendocument.text' and mime not in ['', 'binary']:
        log.error(_('Unknown file type (%s). questionnaire_odt should be application/vnd.oasis.opendocument.text.') % mime)
        return 1

    mime = mimetype(questionnaire_pdf)
    if mime != 'application/pdf' and mime != '':
        log.error(_('Unknown file type (%s). questionnaire_pdf should be application/pdf.') % mime)
        return 1

    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())

    # Parse the box objects into a cache
    boxes, page_count = boxesparser.parse(questionnaire_pdf)
    survey.questionnaire.page_count = page_count

    # Get the papersize
    doc = pdffile.PDFDocument(questionnaire_pdf)
    page = doc.read_page(1)
    survey.defs.paper_width = abs(page.MediaBox[0] - page.MediaBox[2]) / 72.0 * 25.4
    survey.defs.paper_height = abs(page.MediaBox[1] - page.MediaBox[3]) / 72.0 * 25.4
    survey.defs.print_questionnaire_id = cmdline['print_questionnaire_id']
    survey.defs.print_survey_id = cmdline['print_survey_id']

    survey.defs.style = cmdline['style']
    # Force simplex if page count is one.
    survey.defs.duplex = False if page_count == 1 else cmdline['duplex']

    survey.global_id = cmdline['global_id']

    # Parse qobjects
    try:
        qobjectsparser.parse(survey, questionnaire_odt, boxes)
    except:
        log.error(_("Caught an Exception while parsing the ODT file. The current state is:"))
        print unicode(survey.questionnaire)
        print "------------------------------------"
        print _("If the dependencies for the \"annotate\" command are installed, then an annotated version will be created next to the original PDF file.")
        print "------------------------------------"

        # Try to make an annotation
        try:
            if questionnaire_pdf.lower().endswith('.pdf'):
                annotated_pdf = questionnaire_pdf[:-4] + '_annotated.pdf'
            else:
                # No .pdf ending? Just append the _annotated.pdf.
                annotated_pdf = questionnaire_pdf + '_annotated.pdf'

            import sdaps.annotate.annotate as annotate
            annotate.annotate(survey, questionnaire_pdf, annotated_pdf)
        except:
            # Well, whatever
            pass

        raise

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

    # Parse Metadata
    metaparser.parse(survey, questionnaire_odt)

    # 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."))
        return 1

    # Print the result
    print survey.title

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

    print unicode(survey.questionnaire)

    # Create the survey
    os.mkdir(survey.path())

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

    shutil.copy(questionnaire_odt, survey.path('questionnaire.odt'))
    shutil.copy(questionnaire_pdf, survey.path('questionnaire.pdf'))

    survey.save()
    log.logfile.close()
コード例 #4
0
ファイル: setup.py プロジェクト: edemocracy/sdaps
def setup(survey, cmdline):

    if os.access(survey.path(), os.F_OK):
        log.error(_('The survey directory already exists.'))
        return 1

    questionnaire_odt = cmdline['questionnaire.odt']
    questionnaire_pdf = cmdline['questionnaire.pdf']
    additionalqobjects = cmdline['additional_questions']

    mime = mimetype(questionnaire_odt)
    if mime != 'application/vnd.oasis.opendocument.text' and mime != '':
        log.error(
            _('Unknown file type (%s). questionnaire_odt should be application/vnd.oasis.opendocument.text.'
              ) % mime)
        return 1

    mime = mimetype(questionnaire_pdf)
    if mime != 'application/pdf' and mime != '':
        log.error(
            _('Unknown file type (%s). questionnaire_pdf should be application/pdf.'
              ) % mime)
        return 1

    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())

    # Parse the box objects into a cache
    boxes, page_count = boxesparser.parse(questionnaire_pdf)
    survey.questionnaire.page_count = page_count

    # Get the papersize
    doc = pdffile.PDFDocument(questionnaire_pdf)
    page = doc.read_page(1)
    survey.defs.paper_width = abs(page.MediaBox[0] -
                                  page.MediaBox[2]) / 72.0 * 25.4
    survey.defs.paper_height = abs(page.MediaBox[1] -
                                   page.MediaBox[3]) / 72.0 * 25.4
    survey.defs.print_questionnaire_id = cmdline['print_questionnaire_id']
    survey.defs.print_survey_id = cmdline['print_survey_id']

    survey.defs.style = cmdline['style']
    # Force simplex if page count is one.
    survey.defs.duplex = False if page_count == 1 else cmdline['duplex']

    survey.global_id = cmdline['global_id']

    # Parse qobjects
    try:
        qobjectsparser.parse(survey, questionnaire_odt, boxes)
    except:
        log.error(
            _("Caught an Exception while parsing the ODT file. The current state is:"
              ))
        print unicode(survey.questionnaire)
        print "------------------------------------"
        print _(
            "If the dependencies for the \"annotate\" command are installed, then an annotated version will be created next to the original PDF file."
        )
        print "------------------------------------"

        # Try to make an annotation
        try:
            if questionnaire_pdf.lower().endswith('.pdf'):
                annotated_pdf = questionnaire_pdf[:-4] + '_annotated.pdf'
            else:
                # No .pdf ending? Just append the _annotated.pdf.
                annotated_pdf = questionnaire_pdf + '_annotated.pdf'

            import sdaps.annotate.annotate as annotate
            annotate.annotate(survey, questionnaire_pdf, annotated_pdf)
        except:
            # Well, whatever
            pass

        raise

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

    # Parse Metadata
    metaparser.parse(survey, questionnaire_odt)

    # 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."
              ))
        return 1

    # Print the result
    print survey.title

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

    print unicode(survey.questionnaire)

    # Create the survey
    os.mkdir(survey.path())

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

    shutil.copy(questionnaire_odt, survey.path('questionnaire.odt'))
    shutil.copy(questionnaire_pdf, survey.path('questionnaire.pdf'))

    survey.save()
    log.logfile.close()
コード例 #5
0
ファイル: setup.py プロジェクト: edemocracy/sdaps
def setup(survey, cmdline):
    if os.access(survey.path(), os.F_OK):
        log.error(_('The survey directory already exists.'))
        return 1

    questionnaire_tex = cmdline['questionnaire.tex']
    additionalqobjects = cmdline['additional_questions']

    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.mkdir(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')
            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')
            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'))
        for dict_file in dict_files:
            shutil.copyfile(dict_file,
                            survey.path(os.path.basename(dict_file)))

        for add_file in cmdline['add']:
            shutil.copyfile(add_file, survey.path(os.path.basename(add_file)))

        print _("Running %s now twice to generate the questionnaire."
                ) % defs.latex_engine
        subprocess.call([
            defs.latex_engine, '-halt-on-error', '-interaction', 'batchmode',
            'questionnaire.tex'
        ],
                        cwd=survey.path())
        # And again, without the draft mode
        subprocess.call([
            defs.latex_engine, '-halt-on-error', '-interaction', 'batchmode',
            '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)
        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'))
        subprocess.call([
            defs.latex_engine, '-halt-on-error', '-interaction', 'batchmode',
            'questionnaire.tex'
        ],
                        cwd=survey.path())
        # And again, without the draft mode
        subprocess.call([
            defs.latex_engine, '-halt-on-error', '-interaction', 'batchmode',
            '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')

        # 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()
コード例 #6
0
ファイル: __init__.py プロジェクト: isleon/sdaps
def setup(survey, questionnaire_odt, questionnaire_pdf, additionalqobjects, options):

    if os.access(survey.path(), os.F_OK):
        log.error(_("The survey directory already exists."))
        return 1

    mime = mimetype(questionnaire_odt)
    if mime != "application/vnd.oasis.opendocument.text" and mime not in ["", "binary", "application/octet-stream"]:
        log.error(
            _("Unknown file type (%s). questionnaire_odt should be application/vnd.oasis.opendocument.text.") % mime
        )
        return 1

    mime = mimetype(questionnaire_pdf)
    if mime != "application/pdf" and mime != "":
        log.error(_("Unknown file type (%s). questionnaire_pdf should be application/pdf.") % mime)
        return 1

    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())

    # Parse the box objects into a cache
    boxes, page_count = boxesparser.parse(questionnaire_pdf)
    survey.questionnaire.page_count = page_count

    # Get the papersize
    doc = pdffile.PDFDocument(questionnaire_pdf)
    page = doc.read_page(1)
    survey.defs.paper_width = abs(page.MediaBox[0] - page.MediaBox[2]) / 72.0 * 25.4
    survey.defs.paper_height = abs(page.MediaBox[1] - page.MediaBox[3]) / 72.0 * 25.4
    survey.defs.print_questionnaire_id = options["print_questionnaire_id"]
    survey.defs.print_survey_id = options["print_survey_id"]

    survey.defs.style = options["style"]
    survey.defs.checkmode = options["checkmode"]
    # Force simplex if page count is one.
    survey.defs.duplex = False if page_count == 1 else options["duplex"]

    survey.global_id = options["global_id"]

    # Parse qobjects
    try:
        qobjectsparser.parse(survey, questionnaire_odt, boxes)
    except:
        log.error(_("Caught an Exception while parsing the ODT file. The current state is:"))
        print unicode(survey.questionnaire)
        print "------------------------------------"
        print _(
            'If the dependencies for the "annotate" command are installed, then an annotated version will be created next to the original PDF file.'
        )
        print "------------------------------------"

        # Try to make an annotation
        try:
            if questionnaire_pdf.lower().endswith(".pdf"):
                annotated_pdf = questionnaire_pdf[:-4] + "_annotated.pdf"
            else:
                # No .pdf ending? Just append the _annotated.pdf.
                annotated_pdf = questionnaire_pdf + "_annotated.pdf"

            import sdaps.annotate as annotate

            annotate.annotate(survey, questionnaire_pdf, annotated_pdf)
        except:
            # Well, whatever
            pass

        raise

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

    # Parse Metadata
    metaparser.parse(survey, questionnaire_odt)

    # 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."))
        return 1

    # Print the result
    print survey.title

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

    print unicode(survey.questionnaire)

    # Create the survey
    os.makedirs(survey.path())

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

    shutil.copy(questionnaire_odt, survey.path("questionnaire.odt"))
    shutil.copy(questionnaire_pdf, survey.path("questionnaire.pdf"))

    survey.save()
    log.logfile.close()
コード例 #7
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
コード例 #8
0
ファイル: setup.py プロジェクト: stroobandt/sdaps
def setup(survey, cmdline):

    if os.access(survey.path(), os.F_OK):
        log.error(_("The survey directory already exists."))
        return 1

    questionnaire_odt = cmdline["questionnaire.odt"]
    questionnaire_pdf = cmdline["questionnaire.pdf"]
    additionalqobjects = cmdline["additional_questions"]

    mime = mimetype(questionnaire_odt)
    if mime != "application/vnd.oasis.opendocument.text" and mime != "":
        log.error(
            _("Unknown file type (%s). questionnaire_odt should be application/vnd.oasis.opendocument.text.") % mime
        )
        return 1

    mime = mimetype(questionnaire_pdf)
    if mime != "application/pdf" and mime != "":
        log.error(_("Unknown file type (%s). questionnaire_pdf should be application/pdf.") % mime)
        return 1

    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())

    # Parse the box objects into a cache
    boxes, page_count = boxesparser.parse(questionnaire_pdf)
    survey.questionnaire.page_count = page_count

    # Get the papersize
    doc = pdffile.PDFDocument(questionnaire_pdf)
    page = doc.read_page(1)
    survey.defs.paper_width = abs(page.MediaBox[0] - page.MediaBox[2]) / 72.0 * 25.4
    survey.defs.paper_height = abs(page.MediaBox[1] - page.MediaBox[3]) / 72.0 * 25.4
    survey.defs.print_questionnaire_id = cmdline["print_questionnaire_id"]
    survey.defs.print_survey_id = cmdline["print_survey_id"]

    survey.defs.style = cmdline["style"]
    # Force simplex if page count is one.
    survey.defs.duplex = False if page_count == 1 else cmdline["duplex"]

    survey.global_id = cmdline["global_id"]

    # Parse qobjects
    try:
        qobjectsparser.parse(survey, questionnaire_odt, boxes)
    except:
        log.error(_("Caught an Exception while parsing the ODT file. The current state is:"))
        print unicode(survey.questionnaire)
        print "------------------------------------"

        raise

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

    # Parse Metadata
    metaparser.parse(survey, questionnaire_odt)

    # 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."))
        return 1

    # Print the result
    print survey.title

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

    print unicode(survey.questionnaire)

    # Create the survey
    os.mkdir(survey.path())

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

    shutil.copy(questionnaire_odt, survey.path("questionnaire.odt"))
    shutil.copy(questionnaire_pdf, survey.path("questionnaire.pdf"))

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