Spaces:
Build error
Build error
Create utils.py
Browse files
utils.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# utils.py
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 5 |
+
|
| 6 |
+
logger = logging.getLogger(__name__)
|
| 7 |
+
|
| 8 |
+
def add_watermark(image_path: str, watermark_text: str) -> str:
|
| 9 |
+
"""
|
| 10 |
+
Adds a text watermark to an image and saves it over the original file.
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
image_path (str): The path to the input image.
|
| 14 |
+
watermark_text (str): The text to use for the watermark.
|
| 15 |
+
|
| 16 |
+
Returns:
|
| 17 |
+
str: The path to the watermarked image (same as input).
|
| 18 |
+
"""
|
| 19 |
+
try:
|
| 20 |
+
with Image.open(image_path).convert("RGBA") as base:
|
| 21 |
+
# Create a transparent layer for the text
|
| 22 |
+
txt_layer = Image.new("RGBA", base.size, (255, 255, 255, 0))
|
| 23 |
+
|
| 24 |
+
# Choose a font
|
| 25 |
+
try:
|
| 26 |
+
# Use a common system font if available
|
| 27 |
+
font = ImageFont.truetype("arial.ttf", 40)
|
| 28 |
+
except IOError:
|
| 29 |
+
# Use a default font if the specific one isn't found
|
| 30 |
+
logger.warning("Arial font not found. Using default PIL font.")
|
| 31 |
+
font = ImageFont.load_default()
|
| 32 |
+
|
| 33 |
+
# Get a drawing context
|
| 34 |
+
d = ImageDraw.Draw(txt_layer)
|
| 35 |
+
|
| 36 |
+
# Calculate the x,y coordinates of the text
|
| 37 |
+
# We'll place it in the bottom right corner
|
| 38 |
+
width, height = base.size
|
| 39 |
+
textwidth, textheight = d.textbbox((0, 0), watermark_text, font=font)[2:]
|
| 40 |
+
x = width - textwidth - 10
|
| 41 |
+
y = height - textheight - 10
|
| 42 |
+
|
| 43 |
+
# Draw text with a semi-transparent white color
|
| 44 |
+
d.text((x, y), watermark_text, font=font, fill=(255, 255, 255, 128))
|
| 45 |
+
|
| 46 |
+
# Composite the text layer over the base image
|
| 47 |
+
out = Image.alpha_composite(base, txt_layer)
|
| 48 |
+
|
| 49 |
+
# Convert back to RGB and save over the original file
|
| 50 |
+
out.convert("RGB").save(image_path, "PNG")
|
| 51 |
+
|
| 52 |
+
logger.info(f"Watermark '{watermark_text}' added to {image_path}")
|
| 53 |
+
return image_path
|
| 54 |
+
|
| 55 |
+
except Exception as e:
|
| 56 |
+
logger.error(f"Failed to add watermark to {image_path}: {e}")
|
| 57 |
+
# Return the original path even if watermarking fails
|
| 58 |
+
return image_path
|
| 59 |
+
|