Parcourir la source

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

Tingquan Gao il y a 10 mois
Parent
commit
6f4b4f0965

+ 1 - 1
paddlex/engine.py

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

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

@@ -46,19 +46,14 @@ class StrMixin:
             Dict[str, str]: The string representation of the result.
             Dict[str, str]: The string representation of the result.
         """
         """
 
 
-        return self._to_str(self)
+        return self._to_str()
 
 
     def _to_str(
     def _to_str(
         self,
         self,
-        data: dict,
-        json_format: bool = False,
-        indent: int = 4,
-        ensure_ascii: bool = False,
     ):
     ):
         """Convert the given result data to a string representation.
         """Convert the given result data to a string representation.
 
 
         Args:
         Args:
-            data (dict): The data would be converted to str.
             json_format (bool): If True, return a JSON formatted string. Default is False.
             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.
             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.
             ensure_ascii (bool): If True, ensure all characters are ASCII. Default is False.
@@ -66,27 +61,11 @@ class StrMixin:
         Returns:
         Returns:
             Dict[str, str]: The string representation of the result.
             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:
 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
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # limitations under the License.
 
 
+import copy
 import numpy as np
 import numpy as np
 from PIL import Image
 from PIL import Image
-import copy
 
 
 from ...common.result import BaseCVResult
 from ...common.result import BaseCVResult
 
 
@@ -58,7 +58,14 @@ class UadResult(BaseCVResult):
             color_map[: len(custom_color)] = custom_color
             color_map[: len(custom_color)] = custom_color
         return color_map
         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 = copy.deepcopy(self)
         data["pred"] = "..."
         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 cv2
 import PIL
 import PIL
 import fitz
 import fitz
+import copy
 import math
 import math
 import random
 import random
 import tempfile
 import tempfile
@@ -25,7 +26,7 @@ import numpy as np
 from pathlib import Path
 from pathlib import Path
 from PIL import Image, ImageDraw, ImageFont
 from PIL import Image, ImageDraw, ImageFont
 
 
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 from ....utils import logging
 from ....utils import logging
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ....utils.file_interface import custom_open
 from ....utils.file_interface import custom_open
@@ -33,7 +34,14 @@ from ....utils.file_interface import custom_open
 
 
 class FormulaRecResult(BaseCVResult):
 class FormulaRecResult(BaseCVResult):
     def _to_str(self, *args, **kwargs):
     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(
     def _to_img(
         self,
         self,

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

@@ -13,16 +13,26 @@
 # limitations under the License.
 # limitations under the License.
 
 
 
 
+import copy
 import PIL
 import PIL
 from PIL import Image, ImageDraw, ImageFont
 from PIL import Image, ImageDraw, ImageFont
 import numpy as np
 import numpy as np
 
 
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ...utils.color_map import get_colormap
 from ...utils.color_map import get_colormap
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 
 
 class TopkResult(BaseCVResult):
 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):
     def _to_img(self):
         """Draw label on image"""
         """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
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # limitations under the License.
 
 
+import copy
 from PIL import Image
 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
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # limitations under the License.
 
 
-
+import copy
 import PIL
 import PIL
 from PIL import Image, ImageDraw, ImageFont
 from PIL import Image, ImageDraw, ImageFont
 import numpy as np
 import numpy as np
 
 
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ...utils.color_map import get_colormap
 from ...utils.color_map import get_colormap
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 
 
 class MLClassResult(BaseCVResult):
 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):
     def _to_img(self):
         """Draw label on image"""
         """Draw label on image"""
         image = Image.fromarray(self["input_img"])
         image = Image.fromarray(self["input_img"])

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

@@ -14,7 +14,7 @@
 
 
 import copy
 import copy
 import numpy as np
 import numpy as np
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 
 
 class DocTrResult(BaseCVResult):
 class DocTrResult(BaseCVResult):
@@ -33,7 +33,13 @@ class DocTrResult(BaseCVResult):
         result = np.array(self["doctr_img"])
         result = np.array(self["doctr_img"])
         return {"res": result}
         return {"res": result}
 
 
-    def _to_str(self, _, *args, **kwargs):
+    def _to_str(self, *args, **kwargs):
         data = copy.deepcopy(self)
         data = copy.deepcopy(self)
+        data.pop("input_img")
         data["doctr_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 PIL import Image, ImageDraw, ImageFont
 
 
 from ...utils.color_map import get_colormap, font_colormap
 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 ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ..object_detection.result import draw_box
 from ..object_detection.result import draw_box
 
 
@@ -149,7 +149,13 @@ class InstanceSegResult(BaseCVResult):
 
 
         return {"res": image}
         return {"res": image}
 
 
-    def _to_str(self, _, *args, **kwargs):
+    def _to_str(self, *args, **kwargs):
         data = copy.deepcopy(self)
         data = copy.deepcopy(self)
+        data.pop("input_img")
         data["masks"] = "..."
         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.
 # limitations under the License.
 
 
 from typing import List
 from typing import List
-
+import copy
 import PIL
 import PIL
 from PIL import Image, ImageDraw, ImageFont
 from PIL import Image, ImageDraw, ImageFont
 
 
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ...utils.color_map import get_colormap, font_colormap
 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:
 def draw_box(img: Image.Image, boxes: List[dict]) -> Image.Image:
@@ -101,3 +101,13 @@ class DetResult(BaseCVResult):
         boxes = self["boxes"]
         boxes = self["boxes"]
         image = Image.fromarray(self["input_img"])
         image = Image.fromarray(self["input_img"])
         return {"res": draw_box(image, boxes)}
         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
 from PIL import Image
 import copy
 import copy
 
 
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 
 
 class SegResult(BaseCVResult):
 class SegResult(BaseCVResult):
@@ -60,7 +60,13 @@ class SegResult(BaseCVResult):
             color_map[: len(custom_color)] = custom_color
             color_map[: len(custom_color)] = custom_color
         return color_map
         return color_map
 
 
-    def _to_str(self, _, *args, **kwargs):
+    def _to_str(self, *args, **kwargs):
         data = copy.deepcopy(self)
         data = copy.deepcopy(self)
+        data.pop("input_img")
         data["pred"] = "..."
         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
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # limitations under the License.
 
 
+import copy
 import cv2
 import cv2
 import numpy as np
 import numpy as np
 from pathlib import Path
 from pathlib import Path
 import PIL
 import PIL
 from PIL import Image, ImageDraw, ImageFont
 from PIL import Image, ImageDraw, ImageFont
 
 
-from ...common.result import BaseResult, BaseCVResult, HtmlMixin, XlsxMixin
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 
 
 class TableRecResult(BaseCVResult):
 class TableRecResult(BaseCVResult):
@@ -51,3 +52,13 @@ class TableRecResult(BaseCVResult):
             box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64)
             box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64)
             image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)
             image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)
         return image
         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
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # limitations under the License.
 
 
+import copy
 import numpy as np
 import numpy as np
 import cv2
 import cv2
 
 
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 
 
 class TextDetResult(BaseCVResult):
 class TextDetResult(BaseCVResult):
@@ -31,3 +32,13 @@ class TextDetResult(BaseCVResult):
             box = np.reshape(np.array(box).astype(int), [-1, 1, 2]).astype(np.int64)
             box = np.reshape(np.array(box).astype(int), [-1, 1, 2]).astype(np.int64)
             cv2.polylines(image, [box], True, (0, 0, 255), 2)
             cv2.polylines(image, [box], True, (0, 0, 255), 2)
         return {"res": image[:, :, ::-1]}
         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
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # limitations under the License.
 
 
+import copy
 import PIL
 import PIL
 from PIL import Image, ImageDraw, ImageFont
 from PIL import Image, ImageDraw, ImageFont
 
 
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
 from ....utils.fonts import PINGFANG_FONT_FILE_PATH
-from ...common.result import BaseCVResult
+from ...common.result import BaseCVResult, StrMixin, JsonMixin
 
 
 
 
 class TextRecResult(BaseCVResult):
 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):
     def _to_img(self):
         """Draw label on image"""
         """Draw label on image"""
         image = Image.fromarray(self["input_img"])
         image = Image.fromarray(self["input_img"])