fix: add panic recovery and boundary checks for Math function
Build and Deploy / deploy (push) Has been cancelled
Build and Deploy / build (push) Has been cancelled

This commit is contained in:
2026-07-17 10:59:47 +00:00
parent 89b688424a
commit dc58cc1dba
+21 -2
View File
@@ -282,7 +282,14 @@ func (h *Handler) loadCharset() ([]string, error) {
const mathChars = "0123456789+-*/÷×=?"
func (h *Handler) Math(imageBase64 string) (string, error) {
func (h *Handler) Math(imageBase64 string) (result string, err error) {
// 捕获 panic
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("Math panic: %v", r)
}
}()
sess, ok := onnx.GetSession("math")
if !ok {
return "", fmt.Errorf("Math 模型未加载")
@@ -315,7 +322,7 @@ func (h *Handler) Math(imageBase64 string) (string, error) {
return "", fmt.Errorf("无法识别表达式")
}
result, err := evalMathExpression(expr)
result, err = evalMathExpression(expr)
if err != nil {
return "", err
}
@@ -330,11 +337,23 @@ func preprocessMath(img image.Image) ([]float32, error) {
// 计算缩放比例
bounds := img.Bounds()
srcW, srcH := bounds.Dx(), bounds.Dy()
if srcW <= 0 || srcH <= 0 {
return nil, fmt.Errorf("无效的图片尺寸")
}
ratio := minFloat(float64(targetW)/float64(srcW), float64(targetH)/float64(srcH))
newW := int(float64(srcW) * ratio)
newH := int(float64(srcH) * ratio)
// 确保至少 1 像素
if newW <= 0 {
newW = 1
}
if newH <= 0 {
newH = 1
}
// 缩放图片
resized := imaging.Resize(img, newW, newH, imaging.Lanczos)