Ejemplo n.º 1
0
def _renderMathTexvc(latex,
                     output_path,
                     output_mode='png',
                     resolution_in_dpi=120):
    """only render mode is png"""
    if not texvc_available:
        return None
    cmd = [
        'texvc', output_path, output_path,
        latex.encode('utf-8'), "UTF-8",
        str(resolution_in_dpi)
    ]
    try:
        sub = Popen(cmd, stdout=PIPE, stdin=PIPE, stderr=PIPE)
    except OSError:
        log.error('error with texvc. cmd:', repr(' '.join(cmd)))
        return None
    (result, error) = sub.communicate()
    del sub

    if output_mode == 'png':
        if len(result) >= 32:
            png_fn = os.path.join(output_path, result[1:33] + '.png')
            if os.path.exists(png_fn):
                return png_fn

    log.error('error converting math (texvc). source: %r \nerror: %r' %
              (latex, result))
    return None
Ejemplo n.º 2
0
    def dispatch(self, request):
        try:
            command = request.params['command']
        except KeyError:
            log.error("no command given")
            return Response(body="no command given", status=400)

        try:
            method = getattr(self, 'do_%s' % command)
        except AttributeError:
            log.error("no such command: %r" %(command, ))
            return Response(body="no such command: %r" % (command, ), status=400)

        collection_id = request.params.get('collection_id')
        if not collection_id:
            collection_id = self.new_collection(request.params)
            is_new = True
        else:
            is_new = False
        
        if not self.check_collection_id(collection_id):
            return Response(status=404)

        lock = FileLock(self.get_collection_dir(collection_id))
        lock.acquire()
        try:
            return method(collection_id, request.params, is_new)
        except Exception, exc:
            self.send_report_mail('exception', command=command)
            return self.error_response('error executing command %r: %s' % (
                    command, exc,))
Ejemplo n.º 3
0
def _renderMathBlahtex(latex, output_path, output_mode):
    if not blahtexml_available:
        return None
    cmd = ['blahtexml', '--texvc-compatible-commands']
    if output_mode == 'mathml':
        cmd.append('--mathml')
    elif output_mode == 'png':
        cmd.append('--png')
    else:
        return None

    if output_path:
        try:  # for some reason os.getcwd failed at some point. this should be investigated...
            curdir = os.getcwd()
        except:
            curdir = None
        os.chdir(output_path)
    latex = latex.lstrip()
    if not latex:
        return None

    try:
        sub = Popen(cmd, stdout=PIPE, stdin=PIPE, stderr=PIPE)
    except OSError:
        log.error('error with blahtexml. cmd:', repr(' '.join(cmd)))
        if curdir:
            os.chdir(curdir)
        return None

    (result, error) = sub.communicate(latex.encode('utf-8'))
    del sub

    if curdir is not None:
        os.chdir(curdir)
    if result:
        p = ET.fromstring(result)
        if output_mode == 'png':
            r = p.getiterator('png')
            if r:
                png_fn = r[0].findtext('md5')
                if png_fn:
                    png_fn = os.path.join(output_path, png_fn + '.png')
                    if os.path.exists(png_fn):
                        return png_fn
        elif output_mode == 'mathml':
            mathml = p.getiterator('mathml')
            if mathml:
                mathml = mathml[0]
                mathml.set("xmlns", "http://www.w3.org/1998/Math/MathML")
                return mathml
    log.error('error converting math (blahtexml). source: %r \nerror: %r' %
              (latex, result))
    return None
Ejemplo n.º 4
0
def _renderMathBlahtex(latex, output_path, output_mode):
    if not blahtexml_available:
        return None
    cmd = ['blahtexml', '--texvc-compatible-commands']
    if output_mode == 'mathml':
        cmd.append('--mathml')
    elif output_mode == 'png':
        cmd.append('--png')
    else:
        return None

    if output_path:
        try: # for some reason os.getcwd failed at some point. this should be investigated...
            curdir = os.getcwd()
        except:
            curdir = None
        os.chdir(output_path)    
    latex = latex.strip()
    if not latex:
        return None

    try:
        sub = Popen(cmd, stdout=PIPE, stdin=PIPE, stderr=PIPE)
    except OSError:
        log.error('error with blahtexml. cmd:', repr(' '.join(cmd)))
        if curdir:
            os.chdir(curdir)
        return None

    (result, error) = sub.communicate(latex.encode('utf-8'))
    del sub

    if curdir is not None:
        os.chdir(curdir)
    if result:
        p = ET.fromstring(result)
        if output_mode == 'png':
            r = p.getiterator('png')
            if r:
                png_fn =  r[0].findtext('md5')
                if png_fn:
                    png_fn = os.path.join(output_path, png_fn + '.png')
                    if os.path.exists(png_fn):
                        return png_fn
        elif output_mode == 'mathml':
            mathml = p.getiterator('mathml')            
            if mathml:
                mathml = mathml[0]
                mathml.set("xmlns","http://www.w3.org/1998/Math/MathML")
                return mathml
    log.error('error converting math (blahtexml). source: %r \nerror: %r' % (latex, result))
    return None
Ejemplo n.º 5
0
def renderMath(latex,
               output_path=None,
               output_mode='png',
               render_engine='blahtexml',
               resolution_in_dpi=120):
    """
    @param latex: LaTeX code
    @type latex: unicode

    @param output_mode: one of the values 'png' or 'mathml'. mathml only works
        with blahtexml as render_engine
    @type output_mode: str

    @param render_engine: one of the value 'blahtexml' or 'texvc'
    @type render_engine: str

    @returns: either path to generated png or mathml string
    @rtype: basestring
    """
    if not latex:
        return
    assert output_mode in ("png", "mathml")
    assert render_engine in ("texvc", "blahtexml")
    assert isinstance(latex, unicode), 'latex must be of type unicode'

    if output_mode == 'png' and not output_path:
        log.error(
            'math rendering with output_mode png requires an output_path')
        raise Exception("output path required")

    removeTmpDir = False
    if output_mode == 'mathml' and not output_path:
        output_path = tempfile.mkdtemp()
        removeTmpDir = True
    output_path = os.path.abspath(output_path)
    result = None

    if render_engine == 'blahtexml':
        result = _renderMathBlahtex(latex,
                                    output_path=output_path,
                                    output_mode=output_mode)
    if result is None and output_mode == 'png':
        result = _renderMathTexvc(latex,
                                  output_path=output_path,
                                  output_mode=output_mode,
                                  resolution_in_dpi=resolution_in_dpi)

    if removeTmpDir:
        shutil.rmtree(output_path)
    return result
Ejemplo n.º 6
0
    def dispatch(self, request):
        try:
            command = request.params['command']
        except KeyError:
            log.error("no command given")
            raise HTTPResponse("no command given", status=400)

        try:
            method = getattr(self, 'do_%s' % command)
        except AttributeError:
            log.error("no such command: %r" % (command, ))
            raise HTTPResponse("no such command: %r" % (command, ), status=400)

        collection_id = request.params.get('collection_id')
        if not collection_id:
            collection_id = self.new_collection(request.params)
            is_new = True
        else:
            is_new = False
            if not self.check_collection_id(collection_id):
                raise HTTPResponse(status=404)

        try:
            qserve = collid2qserve[collection_id]
        except KeyError:
            qserve = choose_idle_qserve()
            if qserve is None:
                return self.error_response(
                    "system overloaded. please try again later.", queue_full=1)
            collid2qserve[collection_id] = qserve

        self.qserve = rpcclient.serverproxy(host=qserve[0], port=qserve[1])

        try:
            return method(collection_id, request.params, is_new)
        except Exception, exc:
            print "ERROR while dispatching %r: %s" % (
                command,
                dict(collection_id=collection_id, is_new=is_new,
                     qserve=qserve))
            traceback.print_exc()
            if command == "download":
                raise exc

            return self.error_response('error executing command %r: %s' % (
                command,
                exc,
            ))
Ejemplo n.º 7
0
    def dispatch(self, request):
        try:
            command = request.params['command']
        except KeyError:
            log.error("no command given")
            raise HTTPResponse("no command given", status=400)

        try:
            method = getattr(self, 'do_%s' % command)
        except AttributeError:
            log.error("no such command: %r" % (command, ))
            raise HTTPResponse("no such command: %r" % (command, ), status=400)

        collection_id = request.params.get('collection_id')
        if not collection_id:
            collection_id = self.new_collection(request.params)
            is_new = True
        else:
            is_new = False
            if not self.check_collection_id(collection_id):
                raise HTTPResponse(status=404)

        try:
            qserve = collid2qserve[collection_id]
        except KeyError:
            qserve = choose_idle_qserve()
            if qserve is None:
                return self.error_response(
                    "system overloaded. please try again later.", queue_full=1)
            collid2qserve[collection_id] = qserve

        self.qserve = rpcclient.serverproxy(host=qserve[0], port=qserve[1])

        try:
            return method(collection_id, request.params, is_new)
        except Exception as exc:
            print "ERROR while dispatching %r: %s" % (command, dict(
                collection_id=collection_id, is_new=is_new, qserve=qserve))
            traceback.print_exc()
            if command == "download":
                raise exc

            return self.error_response('error executing command %r: %s' % (
                command, exc,))
Ejemplo n.º 8
0
def renderMath(latex, output_path=None, output_mode='png',
               render_engine='blahtexml', resolution_in_dpi=120):
    """
    @param latex: LaTeX code
    @type latex: unicode

    @param output_mode: one of the values 'png' or 'mathml'. mathml only works
        with blahtexml as render_engine
    @type output_mode: str

    @param render_engine: one of the value 'blahtexml' or 'texvc'
    @type render_engine: str

    @returns: either path to generated png or mathml string
    @rtype: basestring
    """
    if not latex:
        return
    assert output_mode in ("png", "mathml")
    assert render_engine in ("texvc", "blahtexml")
    assert isinstance(latex, unicode), 'latex must be of type unicode'

    if output_mode == 'png' and not output_path:
        log.error('math rendering with output_mode png requires an output_path')
        raise Exception("output path required")

    removeTmpDir = False
    if output_mode == 'mathml' and not output_path:
        output_path = tempfile.mkdtemp()
        removeTmpDir = True
    output_path = os.path.abspath(output_path)
    result = None

    if render_engine == 'blahtexml':
        result = _renderMathBlahtex(latex, output_path=output_path, output_mode=output_mode)
    if result is None and output_mode == 'png':
        result = _renderMathTexvc(latex, output_path=output_path,
                                  output_mode=output_mode, resolution_in_dpi=resolution_in_dpi)

    if removeTmpDir:
        shutil.rmtree(output_path)
    return result
Ejemplo n.º 9
0
def _renderMathTexvc(latex, output_path, output_mode='png'):
    """only render mode is png"""
    if not texvc_available:
        return None
    cmd = ['texvc', output_path, output_path, latex.encode('utf-8')]
    try:
        sub = Popen(cmd, stdout=PIPE, stdin=PIPE, stderr=PIPE)
    except OSError:
        log.error('error with texvc. cmd:', repr(' '.join(cmd)))
        return None
    (result, error) = sub.communicate()
    del sub

    if output_mode == 'png':
        if len(result) >= 32:
            png_fn = os.path.join(output_path, result[1:33] + '.png')
            if os.path.exists(png_fn):
                return png_fn
            
    log.error('error converting math (texvc). source: %r \nerror: %r' % (latex, result))              
    return None