Commit 57c8f712 authored by Kantz's avatar Kantz
Browse files

spiechern überarbeitet sodass es nun auch "nicht-mathe" uploads korrekt speichert.

parent 925d5684
from __future__ import annotations
import base64
import os
import time
from pathlib import Path
from typing import Optional
import logging
from app import config
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
......@@ -14,7 +13,6 @@ from mpxpy.mathpix_client import MathpixClient
router = APIRouter()
logger = logging.getLogger(__name__)
settings = config.get_mathpix_settings()
......@@ -57,22 +55,28 @@ def save_canvas(request: CanvasSaveRequest) -> CanvasSaveResponse:
if not safe_hint:
safe_hint = "drawing"
filename = f"{safe_hint}-{timestamp}.png"
file_path = drawings_dir / filename
base_name = f"{safe_hint}-{timestamp}"
img_path = drawings_dir / f"{base_name}.png"
txt_path = drawings_dir / f"{base_name}.txt"
with file_path.open("wb") as handle:
with img_path.open("wb") as handle:
handle.write(raw)
try:
image = mathpix_client.image_new(file_path=str(file_path), include_line_data=True)
image = mathpix_client.image_new(file_path=str(img_path), include_line_data=True)
lines = image.lines_json()
logger.info("Mathpix lines: %s", lines)
line_type = lines[0]["type"] if lines else None
if line_type != "math":
nf_img_path = img_path.with_name(f"nf_{img_path.name}")
nf_txt_path = txt_path.with_name(f"nf_{txt_path.name}")
os.rename(img_path, nf_img_path)
nf_txt_path.write_text(
lines[0]["text"]
)
return CanvasSaveResponse(
status="error",
latex=f"Please provide a math-formula, you provided a {line_type}.",
saved_as=str(file_path),
saved_as=str(nf_img_path),
)
mmd = image.mmd()
conversion = mathpix_client.conversion_new(
......@@ -84,8 +88,10 @@ def save_canvas(request: CanvasSaveRequest) -> CanvasSaveResponse:
except Exception as exc:
raise HTTPException(status_code=500, detail="mathpix failed") from exc
txt_path.write_text(latex, encoding="utf-8")
return CanvasSaveResponse(
status="ok",
latex=latex,
saved_as=str(file_path),
saved_as=str(img_path),
)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment