浏览代码

rm input_img when printing result or saving result to json (#2797)

Tingquan Gao 10 月之前
父节点
当前提交
6f4b4f0965

+ 1 - 1
paddlex/engine.py

@@ -47,7 +47,7 @@ class Engine(object):
             return self._model.export()
         elif self._mode == "predict":
             for res in self._model.predict():
-                res.print(json_format=False)
+                res.print()
                 if self._output:
                     res.save_all(save_path=self._output)
         else:

+ 5 - 26
paddlex/inference/common/result/mixin.py

@@ -46,19 +46,14 @@ class StrMixin:
             Dict[str, str]: The string representation of the result.
         """
 
-        return self._to_str(self)
+        return self._to_str()
 
     def _to_str(
         self,
-        data: dict,
-        json_format: bool = False,
-        indent: int = 4,
-        ensure_ascii: bool = False,
     ):
         """Convert the given result data to a string representation.
 
         Args:
-            data (dict): The data would be converted to str.
             json_format (bool): If True, return a JSON formatted string. Default is False.
             indent (int): Number of spaces to indent for JSON formatting. Default is 4.
             ensure_ascii (bool): If True, ensure all characters are ASCII. Default is False.
@@ -66,27 +61,11 @@ class StrMixin:
         Returns:
             Dict[str, str]: The string representation of the result.
         """
-        if json_format:
-            return {
-                "res": json.dumps(data.json, indent=indent, ensure_ascii=ensure_ascii)
-            }
-        else:
-            return {"res": str(data)}
-
-    def print(
-        self, json_format: bool = False, indent: int = 4, ensure_ascii: bool = False
-    ) -> None:
-        """Print the string representation of the result.
+        return {"res": str(self)}
 
-        Args:
-            json_format (bool): If True, print a JSON formatted string. Default is False.
-            indent (int): Number of spaces to indent for JSON formatting. Default is 4.
-            ensure_ascii (bool): If True, ensure all characters are ASCII. Default is False.
-        """
-        str_ = self._to_str(
-            self, json_format=json_format, indent=indent, ensure_ascii=ensure_ascii
-        )
-        logging.info(str_["res"])
+    def print(self) -> None:
+        """Print the string representation of the result."""
+        logging.info(self.str)
 
 
 class JsonMixin:

+ 10 - 3
paddlex/inference/models_new/anomaly_detection/result.py

@@ -12,9 +12,9 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import copy
 import numpy as np
 from PIL import Image
-import copy
 
 from ...common.result import BaseCVResult
 
@@ -58,7 +58,14 @@ class UadResult(BaseCVResult):
             color_map[: len(custom_color)] = custom_color
         return color_map
 
-    def _to_str(self, _, *args, **kwargs):
+    def _to_str(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data["pred"] = "..."
+        data.pop("input_img")
+        return data._to_str(*args, **kwargs)
+
+    def _to_json(self, *args, **kwargs):
         data = copy.deepcopy(self)
         data["pred"] = "..."
-        return super()._to_str(data, *args, **kwargs)
+        data.pop("input_img")
+        return data._to_json(*args, **kwargs)

+ 10 - 2
paddlex/inference/models_new/formula_recognition/result.py

@@ -17,6 +17,7 @@ from typing import Any, Dict, Optional, List
 import cv2
 import PIL
 import fitz
+import copy
 import math
 import random
 import tempfile
@@ -25,7 +26,7 @@ import numpy as np
 from pathlib import Path
 from PIL import Image, ImageDraw, ImageFont
 
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 from ....utils import logging
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ....utils.file_interface import custom_open
@@ -33,7 +34,14 @@ from ....utils.file_interface import custom_open
 
 class FormulaRecResult(BaseCVResult):
     def _to_str(self, *args, **kwargs):
-        return super()._to_str(*args, **kwargs).replace("\\\\", "\\")
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return StrMixin._to_str(data, *args, **kwargs).replace("\\\\", "\\")
+
+    def _to_json(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return JsonMixin._to_json(data, *args, **kwargs)
 
     def _to_img(
         self,

+ 11 - 1
paddlex/inference/models_new/image_classification/result.py

@@ -13,16 +13,26 @@
 # limitations under the License.
 
 
+import copy
 import PIL
 from PIL import Image, ImageDraw, ImageFont
 import numpy as np
 
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ...utils.color_map import get_colormap
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 class TopkResult(BaseCVResult):
+    def _to_str(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return StrMixin._to_str(data, *args, **kwargs)
+
+    def _to_json(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return JsonMixin._to_json(data, *args, **kwargs)
 
     def _to_img(self):
         """Draw label on image"""

+ 12 - 3
paddlex/inference/models_new/image_feature/result.py

@@ -12,10 +12,19 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import copy
 from PIL import Image
 
-from ...common.result import BaseResult
+from ...common.result import BaseResult, StrMixin, JsonMixin
 
 
-class IdentityResult(BaseResult):
-    pass
+class IdentityResult(BaseResult, StrMixin, JsonMixin):
+    def _to_str(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return StrMixin._to_str(data, *args, **kwargs)
+
+    def _to_json(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return JsonMixin._to_json(data, *args, **kwargs)

+ 12 - 2
paddlex/inference/models_new/image_multilabel_classification/result.py

@@ -12,17 +12,27 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-
+import copy
 import PIL
 from PIL import Image, ImageDraw, ImageFont
 import numpy as np
 
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ...utils.color_map import get_colormap
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 class MLClassResult(BaseCVResult):
+    def _to_str(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return StrMixin._to_str(data, *args, **kwargs)
+
+    def _to_json(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return JsonMixin._to_json(data, *args, **kwargs)
+
     def _to_img(self):
         """Draw label on image"""
         image = Image.fromarray(self["input_img"])

+ 9 - 3
paddlex/inference/models_new/image_unwarping/result.py

@@ -14,7 +14,7 @@
 
 import copy
 import numpy as np
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 class DocTrResult(BaseCVResult):
@@ -33,7 +33,13 @@ class DocTrResult(BaseCVResult):
         result = np.array(self["doctr_img"])
         return {"res": result}
 
-    def _to_str(self, _, *args, **kwargs):
+    def _to_str(self, *args, **kwargs):
         data = copy.deepcopy(self)
+        data.pop("input_img")
         data["doctr_img"] = "..."
-        return super()._to_str(data, *args, **kwargs)
+        return StrMixin._to_str(data, *args, **kwargs)
+
+    def _to_json(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return JsonMixin._to_json(data, *args, **kwargs)

+ 9 - 3
paddlex/inference/models_new/instance_segmentation/result.py

@@ -20,7 +20,7 @@ import PIL
 from PIL import Image, ImageDraw, ImageFont
 
 from ...utils.color_map import get_colormap, font_colormap
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ..object_detection.result import draw_box
 
@@ -149,7 +149,13 @@ class InstanceSegResult(BaseCVResult):
 
         return {"res": image}
 
-    def _to_str(self, _, *args, **kwargs):
+    def _to_str(self, *args, **kwargs):
         data = copy.deepcopy(self)
+        data.pop("input_img")
         data["masks"] = "..."
-        return super()._to_str(data, *args, **kwargs)
+        return StrMixin._to_str(data, *args, **kwargs)
+
+    def _to_json(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return JsonMixin._to_json(data, *args, **kwargs)

+ 12 - 2
paddlex/inference/models_new/object_detection/result.py

@@ -13,13 +13,13 @@
 # limitations under the License.
 
 from typing import List
-
+import copy
 import PIL
 from PIL import Image, ImageDraw, ImageFont
 
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ...utils.color_map import get_colormap, font_colormap
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 def draw_box(img: Image.Image, boxes: List[dict]) -> Image.Image:
@@ -101,3 +101,13 @@ class DetResult(BaseCVResult):
         boxes = self["boxes"]
         image = Image.fromarray(self["input_img"])
         return {"res": draw_box(image, boxes)}
+
+    def _to_str(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return StrMixin._to_str(data, *args, **kwargs)
+
+    def _to_json(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return JsonMixin._to_json(data, *args, **kwargs)

+ 9 - 3
paddlex/inference/models_new/semantic_segmentation/result.py

@@ -16,7 +16,7 @@ import numpy as np
 from PIL import Image
 import copy
 
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 class SegResult(BaseCVResult):
@@ -60,7 +60,13 @@ class SegResult(BaseCVResult):
             color_map[: len(custom_color)] = custom_color
         return color_map
 
-    def _to_str(self, _, *args, **kwargs):
+    def _to_str(self, *args, **kwargs):
         data = copy.deepcopy(self)
+        data.pop("input_img")
         data["pred"] = "..."
-        return super()._to_str(data, *args, **kwargs)
+        return StrMixin._to_str(data, *args, **kwargs)
+
+    def _to_json(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return JsonMixin._to_json(data, *args, **kwargs)

+ 12 - 1
paddlex/inference/models_new/table_structure_recognition/result.py

@@ -12,13 +12,14 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import copy
 import cv2
 import numpy as np
 from pathlib import Path
 import PIL
 from PIL import Image, ImageDraw, ImageFont
 
-from ...common.result import BaseResult, BaseCVResult, HtmlMixin, XlsxMixin
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 class TableRecResult(BaseCVResult):
@@ -51,3 +52,13 @@ class TableRecResult(BaseCVResult):
             box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64)
             image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)
         return image
+
+    def _to_str(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return StrMixin._to_str(data, *args, **kwargs)
+
+    def _to_json(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return JsonMixin._to_json(data, *args, **kwargs)

+ 12 - 1
paddlex/inference/models_new/text_detection/result.py

@@ -12,10 +12,11 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import copy
 import numpy as np
 import cv2
 
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 class TextDetResult(BaseCVResult):
@@ -31,3 +32,13 @@ class TextDetResult(BaseCVResult):
             box = np.reshape(np.array(box).astype(int), [-1, 1, 2]).astype(np.int64)
             cv2.polylines(image, [box], True, (0, 0, 255), 2)
         return {"res": image[:, :, ::-1]}
+
+    def _to_str(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return StrMixin._to_str(data, *args, **kwargs)
+
+    def _to_json(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return JsonMixin._to_json(data, *args, **kwargs)

+ 12 - 1
paddlex/inference/models_new/text_recognition/result.py

@@ -12,15 +12,26 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import copy
 import PIL
 from PIL import Image, ImageDraw, ImageFont
 
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 class TextRecResult(BaseCVResult):
 
+    def _to_str(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return StrMixin._to_str(data, *args, **kwargs)
+
+    def _to_json(self, *args, **kwargs):
+        data = copy.deepcopy(self)
+        data.pop("input_img")
+        return JsonMixin._to_json(data, *args, **kwargs)
+
     def _to_img(self):
         """Draw label on image"""
         image = Image.fromarray(self["input_img"])