Spaces:
Sleeping
Sleeping
Update api.py
Browse files
api.py
CHANGED
|
@@ -83,6 +83,9 @@ from typing import Optional
|
|
| 83 |
from PIL import Image
|
| 84 |
import logging
|
| 85 |
import io
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
logging.basicConfig(
|
| 88 |
level=logging.INFO,
|
|
@@ -106,6 +109,13 @@ logger.info("TextFilterService initialized.")
|
|
| 106 |
image_classifier = ImageClassifier()
|
| 107 |
logger.info("ImageClassifier initialized.")
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
@app.route("/filtercomment", methods=["POST"])
|
| 110 |
def filter_comment():
|
| 111 |
text = request.form.get("text")
|
|
@@ -119,16 +129,52 @@ def filter_comment():
|
|
| 119 |
if image_file:
|
| 120 |
try:
|
| 121 |
logger.info("Processing uploaded image file: %s", image_file.filename)
|
| 122 |
-
image_bytes = image_file.read()
|
| 123 |
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
|
|
|
| 124 |
result = image_classifier.classify(image)
|
|
|
|
| 125 |
if result.get("text"):
|
| 126 |
result['toxic_result'] = text_filter_service.process_text(result.get("text"))
|
|
|
|
| 127 |
logger.info("Image classification result: %s", result)
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
except Exception as e:
|
| 130 |
logger.error("Image file processing failed: %s", str(e))
|
| 131 |
-
return
|
| 132 |
|
| 133 |
# Case 2: Extract text from image URL
|
| 134 |
if image_url:
|
|
|
|
| 83 |
from PIL import Image
|
| 84 |
import logging
|
| 85 |
import io
|
| 86 |
+
import cv2
|
| 87 |
+
import numpy as np
|
| 88 |
+
import base64
|
| 89 |
|
| 90 |
logging.basicConfig(
|
| 91 |
level=logging.INFO,
|
|
|
|
| 109 |
image_classifier = ImageClassifier()
|
| 110 |
logger.info("ImageClassifier initialized.")
|
| 111 |
|
| 112 |
+
def blur_image(pil_image: Image.Image) -> Image.Image:
|
| 113 |
+
"""Convert PIL image to OpenCV, apply Gaussian blur, and return as PIL."""
|
| 114 |
+
cv_image = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
|
| 115 |
+
blurred_cv = cv2.GaussianBlur(cv_image, (25, 25), 0)
|
| 116 |
+
blurred_pil = Image.fromarray(cv2.cvtColor(blurred_cv, cv2.COLOR_BGR2RGB))
|
| 117 |
+
return blurred_pil
|
| 118 |
+
|
| 119 |
@app.route("/filtercomment", methods=["POST"])
|
| 120 |
def filter_comment():
|
| 121 |
text = request.form.get("text")
|
|
|
|
| 129 |
if image_file:
|
| 130 |
try:
|
| 131 |
logger.info("Processing uploaded image file: %s", image_file.filename)
|
| 132 |
+
image_bytes = await image_file.read()
|
| 133 |
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
| 134 |
+
|
| 135 |
result = image_classifier.classify(image)
|
| 136 |
+
|
| 137 |
if result.get("text"):
|
| 138 |
result['toxic_result'] = text_filter_service.process_text(result.get("text"))
|
| 139 |
+
|
| 140 |
logger.info("Image classification result: %s", result)
|
| 141 |
+
|
| 142 |
+
# Check if content is toxic or unsafe
|
| 143 |
+
is_toxic = result.get("toxic") is True or not result.get("toxic_result", {}).get("safe", True)
|
| 144 |
+
|
| 145 |
+
if is_toxic:
|
| 146 |
+
logger.info("Toxic content detected. Blurring image.")
|
| 147 |
+
blurred_image = blur_image(image)
|
| 148 |
+
|
| 149 |
+
# Compose annotation message
|
| 150 |
+
if not result.get("text"):
|
| 151 |
+
message = "Toxic content is present\nImage is blurred"
|
| 152 |
+
else:
|
| 153 |
+
toxic_result = result.get("toxic_result", {})
|
| 154 |
+
exclude_keys = {"safe", "identity_hate_custom", "not_identity_hate_custom"}
|
| 155 |
+
filtered = {k: v for k, v in toxic_result.items() if k not in exclude_keys}
|
| 156 |
+
if filtered:
|
| 157 |
+
max_label = max(filtered, key=filtered.get)
|
| 158 |
+
message = f"The image contains {max_label} ({filtered[max_label]:.2f}) content"
|
| 159 |
+
else:
|
| 160 |
+
message = "Toxic content is present\nImage is blurred"
|
| 161 |
+
|
| 162 |
+
# Encode blurred image to base64
|
| 163 |
+
buffer = io.BytesIO()
|
| 164 |
+
blurred_image.save(buffer, format="JPEG")
|
| 165 |
+
encoded_image = base64.b64encode(buffer.getvalue()).decode("utf-8")
|
| 166 |
+
|
| 167 |
+
result["blurred_image_base64"] = encoded_image
|
| 168 |
+
result["blurred"] = True
|
| 169 |
+
result["alert_message"] = message
|
| 170 |
+
else:
|
| 171 |
+
result["blurred"] = False
|
| 172 |
+
|
| 173 |
+
return JSONResponse(content={"image_classification": result})
|
| 174 |
+
|
| 175 |
except Exception as e:
|
| 176 |
logger.error("Image file processing failed: %s", str(e))
|
| 177 |
+
return JSONResponse(status_code=400, content={"error": f"Image file processing failed: {str(e)}"})
|
| 178 |
|
| 179 |
# Case 2: Extract text from image URL
|
| 180 |
if image_url:
|