Пример #1
0
    def test_get_data_url_error(self):
        doc_path = get_latex_file_dir("xelatex")
        filename = os.listdir(doc_path)[0]
        file_path = os.path.join(doc_path, filename)
        tex_source = get_file_content(file_path).decode("utf-8")

        expected_error = "some error"
        with mock.patch("latex.converter.get_data_url") as mock_get_data_url:
            mock_get_data_url.side_effect = RuntimeError(expected_error)
            with self.assertRaises(ImageConvertError) as cm:
                tex_to_img_converter("xelatex", tex_source,
                                     "svg").get_converted_data_url()
            self.assertIn(expected_error, str(cm.exception))
Пример #2
0
    def test_do_convert_success_but_no_images(self):
        doc_path = get_latex_file_dir("xelatex")
        filename = os.listdir(doc_path)[0]
        file_path = os.path.join(doc_path, filename)
        tex_source = get_file_content(file_path).decode("utf-8")

        with mock.patch(
                "latex.converter.get_number_of_images") as mock_get_n_images:
            mock_get_n_images.return_value = 0
            with self.assertRaises(ImageConvertError) as cm:
                tex_to_img_converter("xelatex", tex_source,
                                     "png").get_converted_data_url()
            self.assertIn("No image was generated", str(cm.exception))
Пример #3
0
    def test_compile_no_error_but_no_compiled_pdf_file(self):
        doc_path = get_latex_file_dir("xelatex")
        filename = os.listdir(doc_path)[0]
        file_path = os.path.join(doc_path, filename)
        tex_source = get_file_content(file_path).decode("utf-8")

        with mock.patch("latex.converter.Tex2ImgBase.compile_popen"
                        ) as mock_compile_subprocess:
            mock_compile_subprocess.return_value = ["foo", "", 0]
            with self.assertRaises(UnknownCompileError) as cm:
                tex_to_img_converter("xelatex", tex_source,
                                     "png").get_converted_data_url()
            self.assertIn("No pdf file was generated.", str(cm.exception))
Пример #4
0
    def test_convert_error(self):
        doc_path = get_latex_file_dir("xelatex")
        filename = os.listdir(doc_path)[0]
        file_path = os.path.join(doc_path, filename)
        tex_source = get_file_content(file_path).decode("utf-8")

        expected_error = "some error"
        with mock.patch("latex.converter.ImageConverter.convert_popen"
                        ) as mock_compile_subprocess:
            mock_compile_subprocess.return_value = ["bar", expected_error, 1]
            with self.assertRaises(ImageConvertError) as cm:
                tex_to_img_converter("xelatex", tex_source,
                                     "svg").get_converted_data_url()
            self.assertIn(expected_error, str(cm.exception))
Пример #5
0
 def test_more_than_one_pages_error(self):
     latex_doc_path = get_latex_file_dir("pdflatex_multilple_pages")
     for filename in os.listdir(latex_doc_path):
         file_path = os.path.join(latex_doc_path, filename)
         image_format = "png"
         with self.subTest(filename=filename,
                           test_name="pdflatex",
                           image_format=image_format):
             tex_source = get_file_content(file_path).decode("utf-8")
             with self.assertRaises(ImageConvertError):
                 tex_to_img_converter(
                     "pdflatex",
                     tex_source,
                     image_format,
                 ).get_converted_data_url()
Пример #6
0
 def test_pdfsvg(self):
     pdf2svg_doc_path = get_latex_file_dir("pdf2svg")
     for filename in os.listdir(pdf2svg_doc_path):
         file_path = os.path.join(pdf2svg_doc_path, filename)
         with self.subTest(filename=filename, test_name="xelatex_svg"):
             tex_source = get_file_content(file_path).decode("utf-8")
             data_url = tex_to_img_converter(
                 "xelatex", tex_source, "svg").get_converted_data_url()
             self.assertIsNotNone(data_url)
             self.assertTrue(data_url.startswith("data:image/svg"))
Пример #7
0
 def test_latex_png_tizk_got_svg(self):
     latex_doc_path = get_latex_file_dir("latex2png")
     for image_format in ["png"]:
         for filename in os.listdir(latex_doc_path):
             file_path = os.path.join(latex_doc_path, filename)
             with self.subTest(filename=filename,
                               test_name="latex",
                               image_format=image_format):
                 tex_source = get_file_content(file_path).decode("utf-8")
                 data_url = tex_to_img_converter(
                     "latex",
                     tex_source,
                     image_format,
                 ).get_converted_data_url()
                 self.assertIsNotNone(data_url)
                 self.assertTrue(
                     data_url.startswith("data:image/%s" % image_format))
Пример #8
0
    def create(self, request, *args, **kwargs):
        try:
            req_params = JSONParser().parse(request)
            compiler = req_params.pop("compiler")
            tex_source = req_params.pop("tex_source")
            image_format = req_params.pop("image_format")
            tex_key = req_params.pop("tex_key", None)
            field_str = req_params.pop("fields", None)
        except Exception:
            from traceback import print_exc
            print_exc()
            tp, e, __ = sys.exc_info()
            error = "%s: %s" % (tp.__name__, str(e))
            return Response({"error": error},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        if field_str and tex_key:
            cached_result = (get_cached_results_from_field_and_tex_key(
                tex_key, field_str, request))
            if cached_result:
                return Response(cached_result, status=status.HTTP_200_OK)

        data_url = None
        error = None

        try:
            _converter = tex_to_img_converter(compiler, tex_source,
                                              image_format, tex_key,
                                              **req_params)
        except Exception as e:
            from traceback import print_exc
            print_exc()
            tp, e, __ = sys.exc_info()
            error = "%s: %s" % (tp.__name__, str(e))
            return Response({"error": error},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        qs = LatexImage.objects.filter(tex_key=_converter.tex_key)
        if qs.count():
            instance = qs[0]
            image_serializer = self.get_serializer(instance, fields=field_str)
            return Response(image_serializer.data, status=status.HTTP_200_OK)

        try:
            data_url = _converter.get_converted_data_url()
        except Exception as e:
            if isinstance(e, LatexCompileError):
                error = "%s: %s" % (type(e).__name__, str(e))
            else:
                from traceback import print_exc
                print_exc()
                tp, e, __ = sys.exc_info()
                error = "%s: %s" % (tp.__name__, str(e))
                return Response({"error": error},
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        assert not all([data_url is None, error is None])

        data = {"tex_key": _converter.tex_key}
        if data_url is not None:
            data["data_url"] = data_url
        else:
            data["compile_error"] = error

        data["creator"] = self.request.user.pk

        image_serializer = self.get_serializer(data=data)

        if image_serializer.is_valid():
            instance = image_serializer.save()
            return Response(self.get_serializer(instance,
                                                fields=field_str).data,
                            status=status.HTTP_201_CREATED)
        return Response(
            # For example, tex_key already exists.
            image_serializer.errors,
            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Пример #9
0
def request_get_data_url_from_latex_form_request(request):
    instance = None
    ctx = {}
    unknown_error = None
    if request.method == "POST":
        form = LatexToImageForm(request.POST, request.FILES)
        if form.is_valid():
            compiler, image_format = form.cleaned_data[
                "compiler_format"].split("2")
            tex_key = form.cleaned_data["tex_key"] or None

            added_tex_source_to_ctx = False

            f = request.FILES.get("latex_file", None)
            if f:
                f.seek(0)
                tex_source = f.read().decode("utf-8")
                added_tex_source_to_ctx = True
            else:
                tex_source = form.cleaned_data["latex_code"] or None

            if added_tex_source_to_ctx:
                ctx["tex_source"] = tex_source

            _converter = tex_to_img_converter(compiler,
                                              tex_source,
                                              image_format=image_format,
                                              tex_key=tex_key)

            instance = None

            try:
                instance = LatexImage.objects.get(tex_key=_converter.tex_key)
            except LatexImage.DoesNotExist:
                try:
                    data_url = _converter.get_converted_data_url()
                    instance = LatexImage(
                        tex_key=_converter.tex_key,
                        data_url=data_url,
                        creator=request.user,
                    )
                    with atomic():
                        instance.save()
                except Exception as e:
                    from traceback import print_exc
                    print_exc()

                    tp, err, __ = sys.exc_info()
                    error_str = "%s: %s" % (tp.__name__, str(err))
                    if isinstance(e, LatexCompileError):
                        instance = LatexImage(
                            tex_key=_converter.tex_key,
                            compile_error=error_str,
                            creator=request.user,
                        )
                        with atomic():
                            instance.save()
                    else:
                        unknown_error = ctx["unknown_error"] = error_str

            if instance is not None:
                if instance.image:
                    try:
                        ctx["size"] = instance.image.size
                    except OSError:
                        pass
                ctx["instance"] = instance
                ctx["tex_key"] = instance.tex_key

    else:
        form = LatexToImageForm()

    ctx["form"] = form
    ctx["form_description"] = _("Convert LaTeX code to Image")

    render_kwargs = {
        "request": request,
        "template_name": "latex/latex_form_page.html",
        "context": ctx
    }

    if instance is not None:
        if instance.compile_error:
            render_kwargs["status"] = status.HTTP_400_BAD_REQUEST

    if unknown_error:
        render_kwargs["status"] = status.HTTP_500_INTERNAL_SERVER_ERROR

    return render(**render_kwargs)