LPX commited on
Commit
d20c076
·
1 Parent(s): c1d03da

feat: enhance image handling by ensuring input is a PIL Image and updating forensic image logging

Browse files
Files changed (3) hide show
  1. app_mcp.py +11 -1
  2. utils/ela.py +2 -1
  3. utils/hf_logger.py +18 -2
app_mcp.py CHANGED
@@ -261,6 +261,16 @@ def get_consensus_label(results):
261
  # Update predict_image_with_json to return consensus label
262
 
263
  def predict_image_with_json(img, confidence_threshold, augment_methods, rotate_degrees, noise_level, sharpen_strength):
 
 
 
 
 
 
 
 
 
 
264
  # Initialize agents
265
  monitor_agent = EnsembleMonitorAgent()
266
  weight_manager = ModelWeightManager()
@@ -537,4 +547,4 @@ with gr.Blocks(css="#post-gallery { overflow: hidden !important;} .grid-wrap{ ov
537
 
538
  # --- MCP-Ready Launch ---
539
  if __name__ == "__main__":
540
- demo.launch(mcp_server=True)
 
261
  # Update predict_image_with_json to return consensus label
262
 
263
  def predict_image_with_json(img, confidence_threshold, augment_methods, rotate_degrees, noise_level, sharpen_strength):
264
+ # Ensure img is a PIL Image (if it's not already)
265
+ if not isinstance(img, Image.Image):
266
+ try:
267
+ # If it's a numpy array, convert it
268
+ img = Image.fromarray(img)
269
+ except Exception as e:
270
+ logger.error(f"Error converting input image to PIL: {e}")
271
+ # If conversion fails, it's a critical error for the whole process
272
+ raise ValueError("Input image could not be converted to PIL Image.")
273
+
274
  # Initialize agents
275
  monitor_agent = EnsembleMonitorAgent()
276
  weight_manager = ModelWeightManager()
 
547
 
548
  # --- MCP-Ready Launch ---
549
  if __name__ == "__main__":
550
+ demo.launch(share=True, mcp_server=True)
utils/ela.py CHANGED
@@ -1,6 +1,7 @@
1
  import numpy as np
2
  import cv2 as cv
3
  from time import time
 
4
 
5
  def compress_jpg(image, quality):
6
  """Compress image using JPEG compression."""
@@ -60,4 +61,4 @@ def genELA(img, quality=75, scale=50, contrast=20, linear=False, grayscale=False
60
  if grayscale:
61
  ela = desaturate(ela)
62
 
63
- return ela
 
1
  import numpy as np
2
  import cv2 as cv
3
  from time import time
4
+ from PIL import Image
5
 
6
  def compress_jpg(image, quality):
7
  """Compress image using JPEG compression."""
 
61
  if grayscale:
62
  ela = desaturate(ela)
63
 
64
+ return Image.fromarray(ela)
utils/hf_logger.py CHANGED
@@ -13,6 +13,10 @@ HF_DATASET_NAME = "aiwithoutborders-xyz/degentic_rd0" # TODO: Replace with your
13
 
14
  def _pil_to_base64(image: Image.Image) -> str:
15
  """Converts a PIL Image to a base64 string."""
 
 
 
 
16
  buffered = io.BytesIO()
17
  # Ensure image is in RGB mode before saving as JPEG
18
  if image.mode != 'RGB':
@@ -56,7 +60,19 @@ def log_inference_data(
56
 
57
  # Convert PIL Images to base64 strings for storage
58
  original_image_b64 = _pil_to_base64(original_image)
59
- forensic_images_b64 = [_pil_to_base64(img) for img in forensic_images if img is not None]
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  new_entry = {
62
  "timestamp": datetime.datetime.now().isoformat(),
@@ -64,7 +80,7 @@ def log_inference_data(
64
  "inference_request": inference_params,
65
  "model_predictions": model_predictions,
66
  "ensemble_output": ensemble_output,
67
- "forensic_outputs": forensic_images_b64,
68
  "agent_monitoring_data": agent_monitoring_data,
69
  "human_feedback": human_feedback if human_feedback is not None else {}
70
  }
 
13
 
14
  def _pil_to_base64(image: Image.Image) -> str:
15
  """Converts a PIL Image to a base64 string."""
16
+ # Explicitly check if the input is a PIL Image
17
+ if not isinstance(image, Image.Image):
18
+ raise TypeError(f"Expected a PIL Image, but received type: {type(image)}")
19
+
20
  buffered = io.BytesIO()
21
  # Ensure image is in RGB mode before saving as JPEG
22
  if image.mode != 'RGB':
 
60
 
61
  # Convert PIL Images to base64 strings for storage
62
  original_image_b64 = _pil_to_base64(original_image)
63
+
64
+ forensic_images_b64 = []
65
+ for img_item in forensic_images:
66
+ if img_item is not None:
67
+ if not isinstance(img_item, Image.Image):
68
+ try:
69
+ img_item = Image.fromarray(img_item)
70
+ except Exception as e:
71
+ logger.error(f"Error converting forensic image to PIL for base64 encoding: {e}")
72
+ continue # Skip this image if conversion fails
73
+
74
+ # Now img_item should be a PIL Image, safe to pass to _pil_to_base64
75
+ forensic_images_b64.append(_pil_to_base64(img_item))
76
 
77
  new_entry = {
78
  "timestamp": datetime.datetime.now().isoformat(),
 
80
  "inference_request": inference_params,
81
  "model_predictions": model_predictions,
82
  "ensemble_output": ensemble_output,
83
+ "forensic_outputs": forensic_images_b64, # List of base64 image strings
84
  "agent_monitoring_data": agent_monitoring_data,
85
  "human_feedback": human_feedback if human_feedback is not None else {}
86
  }