import fitz, random, os from pathlib import Path from PIL import Image, ImageDraw, ImageFont import numpy as np import random from typing import Union, List from PIL import Image, ImageDraw, ImageFont import math print(fitz.version) # مثلاً ('1.24.4', '...', ...) # ---------- تنظیمات شما ---------- INPUT_DIR = Path(r"D:\init_mahdi\project\watermark_source\in_test") # INPUT_DIR = Path(r"D:\init_mahdi\project\watermark_source\in_test\4712") OUTPUT_DIR = Path(r"D:\init_mahdi\project\watermark_source\o_test") WATERMARK_TEXT = [ " معاونت قوانین مجلس شورای اسلامی", "اداره کل اسناد و اطلاع رسانی قوانین", ] WATERMARK2_TEXT = "قانون‌یار" DPI = 150 MAX_SIZE = 300 # ---------------------------------- FONT_PATH = r"Iranian Sans.ttf" SUPPORTED_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tiff", ".tif"} SUPPORTED_PDF_EXTS = {".pdf"} import random from pathlib import Path from typing import Union, List, Tuple from PIL import Image, ImageDraw, ImageFont def add_watermark( img: Image.Image, primary_text: Union[str, List[str]], sec_text: str, font_path: str = FONT_PATH, primary_opacity: int = 50, secondary_opacity: int = 15, grid_rows: int = 10, # ✅ تعداد سطرهای شبکه grid_cols: int = 1, # ✅ تعداد ستون‌های شبکه rotation_range: Tuple[int, int] = (-15, 13), font_size_primary: int = 16, font_size_secondary: int = 10, ) -> Image.Image: """ اعمال واترمارک: - primary: شبکه‌ای (grid_rows × grid_cols)، هر سلول یک متن تصادفی، موقعیت و زاویه رندوم درون سلول - secondary: فقط 4 گوشه """ img = img.convert("RGBA") width, height = img.size # ===== بارگذاری فونت ===== def get_font(size): if font_path and Path(font_path).exists(): return ImageFont.truetype(font_path, size) for fallback in ["Arial.ttf", "DejaVuSans.ttf", "NotoSans-Regular.ttf"]: try: return ImageFont.truetype(fallback, size) except OSError: continue return ImageFont.load_default() font_p = get_font(font_size_primary) font_s = get_font(font_size_secondary) draw = ImageDraw.Draw(img) # ===== کمک‌تابع: رسم متن با حاشیه و opacity ===== def draw_text_with_stroke( draw_obj, xy, text, font, fill_color, stroke_color, opacity, stroke_width=1 ): x, y = xy fill = ( (*fill_color[:3], int(fill_color[3] * opacity / 255)) if len(fill_color) == 4 else (*fill_color, opacity) ) stroke = ( (*stroke_color[:3], int(stroke_color[3] * opacity / 255)) if len(stroke_color) == 4 else (*stroke_color, opacity) ) for dx in range(-stroke_width, stroke_width + 1): for dy in range(-stroke_width, stroke_width + 1): if dx == 0 and dy == 0: continue draw_obj.text((x + dx, y + dy), text, font=font, fill=stroke) draw_obj.text((x, y), text, font=font, fill=fill) # ===== 1. واترمارک ثانویه: فقط 4 گوشه ===== if sec_text.strip(): bbox = draw.textbbox((0, 0), sec_text, font=font_s) tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1] padding = 10 corners = [ (padding, padding), (width - tw - padding, padding), (padding, height - th - padding), (width - tw - padding, height - th - padding), ] for x, y in corners: draw_text_with_stroke( draw, (x, y), sec_text, font_s, fill_color=(255, 255, 255), stroke_color=(0, 0, 0), opacity=secondary_opacity, stroke_width=1, ) # ===== 2. واترمارک اصلی: شبکه‌بندی + رندوم درون هر سلول ===== primary_texts = ( [primary_text] if isinstance(primary_text, str) else [t for t in primary_text if t.strip()] ) if not primary_texts: return img.convert("RGB") # اندازه هر سلول cell_width = width / grid_cols cell_height = height / grid_rows # حداکثر ابعاد متن برای جلوگیری از خروج از سلول (اجباری نیست، اما برای بهینه‌سازی موقعیت تصادفی مفید است) max_tw, max_th = 0, 0 for txt in primary_texts: bbox = draw.textbbox((0, 0), txt, font=font_p) tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1] max_tw = max(max_tw, tw) max_th = max(max_th, th) # ✅ اصلاح: حاشیه ایمنی کوچک‌تر و منطقی‌تر برای حالت ستونی # اجازه دهید متن تا ~30% پهنای سلول جابجا شود (نه محدود به safe_w که وقتی grid_cols=1 خیلی بزرگ است!) offset_limit_x = min(cell_width * 0.3, max_tw * 1.5) # max انحراف افقی offset_limit_y = min(cell_height * 0.4, max_th * 2.0) # max انحراف عمودی for row in range(grid_rows): for col in range(grid_cols): # محدوده سلول x0 = col * cell_width y0 = row * cell_height x1 = x0 + cell_width y1 = y0 + cell_height text = random.choice(primary_texts).strip() if not text: continue # ابعاد دقیق متن bbox = draw.textbbox((0, 0), text, font=font_p) tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1] # ✅ موقعیت پایه: یک نقطه داخل سلول، نه الزاماً مرکز # مثلاً 20%~80% عرض سلول و 30%~70% ارتفاع سلول base_x = x0 + random.uniform(0.2, 0.8) * cell_width base_y = y0 + random.uniform(0.3, 0.7) * cell_height # ✅ انحراف تصادفی در محدوده منطقی (نه بسته به safe_w که گاهی صفر می‌شد) dx = random.uniform(-offset_limit_x, offset_limit_x) dy = random.uniform(-offset_limit_y, offset_limit_y) final_x = max(0, min(width - 1, base_x + dx)) final_y = max(0, min(height - 1, base_y + dy)) # ✅ زاویه تصادفی angle = random.randint(*rotation_range) # ساخت لایه متن pad = 20 # padding around text for rotation layer_w, layer_h = int(tw + 2 * pad), int(th + 2 * pad) txt_layer = Image.new("RGBA", (layer_w, layer_h), (0, 0, 0, 0)) d = ImageDraw.Draw(txt_layer) draw_text_with_stroke( d, (pad, pad), # متن از گوشه شروع می‌شود — ساده‌تر و دقیق‌تر text, font_p, fill_color=(255, 255, 255), stroke_color=(0, 0, 0), opacity=primary_opacity, stroke_width=1, ) rotated = txt_layer.rotate(angle, expand=True, resample=Image.BICUBIC) rw, rh = rotated.size # موقعیت نهایی: مرکز لایه چرخیده روی (final_x, final_y) pos_x = int(final_x - rw / 2) pos_y = int(final_y - rh / 2) pos_x = max(0, min(pos_x, width - rw)) pos_y = max(0, min(pos_y, height - rh)) img.alpha_composite(rotated, (pos_x, pos_y)) return img.convert("RGB") def create_thumbnail( img: Image.Image, max_width: int = 300, # ✅ فقط عرض هدف — ارتفاع پویا method: str = "width", # "width", "height", "contain", "cover" bg_color: tuple = (255, 255, 255), antialias: bool = True, ) -> Image.Image: """ تولید تامنیل با کنترل دقیق ابعاد. method: - "width": عرض = max_width، ارتفاع متناسب (نسبت حفظ می‌شود) - "height": ارتفاع = max_width (نام پارامتر حفظ شد)، عرض متناسب - "contain": مربع با حاشیه - "cover": مربع با برش """ img = img.copy() # تبدیل حالت برای پردازش if img.mode in ("RGBA", "LA", "P"): img = img.convert("RGBA") else: img = img.convert("RGB") orig_w, orig_h = img.size # انتخاب resampling resample = ( Image.Resampling.LANCZOS if (antialias and hasattr(Image, "Resampling")) else Image.LANCZOS ) # ✅ روش جدید: فقط عرض تنظیم شود — ارتفاع نسبتی if method == "width": if orig_w == 0: raise ValueError("عرض تصویر نمی‌تواند صفر باشد") ratio = max_width / orig_w new_w = max_width new_h = int(orig_h * ratio) return img.resize((new_w, new_h), resample=resample).convert("RGB") elif method == "height": if orig_h == 0: raise ValueError("ارتفاع تصویر نمی‌تواند صفر باشد") ratio = max_width / orig_h # max_width اینجا به معنای max_height است! new_h = max_width new_w = int(orig_w * ratio) return img.resize((new_w, new_h), resample=resample).convert("RGB") # --- بقیه روش‌های قبلی --- elif method == "contain": ratio = min(max_width / orig_w, max_width / orig_h) new_w = int(orig_w * ratio) new_h = int(orig_h * ratio) img = img.resize((new_w, new_h), resample=resample) thumb = Image.new("RGB", (max_width, max_width), bg_color) x = (max_width - new_w) // 2 y = (max_width - new_h) // 2 if img.mode == "RGBA": thumb.paste(img, (x, y), img) else: thumb.paste(img, (x, y)) return thumb elif method == "cover": ratio = max(max_width / orig_w, max_width / orig_h) new_w = int(orig_w * ratio) new_h = int(orig_h * ratio) img = img.resize((new_w, new_h), resample=resample) left = (new_w - max_width) // 2 top = (new_h - max_width) // 2 return img.crop((left, top, left + max_width, top + max_width)).convert("RGB") else: raise ValueError("method must be 'width', 'height', 'contain', or 'cover'") def process_image(input_path: Path, output_path: Path): try: with Image.open(input_path) as img: # تبدیل حالت if img.mode in ("RGBA", "LA", "P"): img = img.convert("RGBA") elif img.mode in ("I", "I;16", "F"): img = img.convert("RGB") elif img.mode == "CMYK": img = img.convert("RGB") else: img = img.convert("RGB") # ✅ ایجاد تامنیل (مثلاً 300px) img = create_thumbnail( img, max_width=MAX_SIZE, method="width", bg_color=(255, 255, 255), ) # اعمال واترمارک img = add_watermark( img=img, primary_text=WATERMARK_TEXT, sec_text=WATERMARK2_TEXT, ) # ذخیره — DPI دیگر مهم نیست، ولی برای ثبت متادیتا می‌گذاریم img.save( output_path, format="JPEG", dpi=(72, 72), # یا هر چیزی — تأثیری ندارد quality=85, # کیفیت فشرده‌سازی (80-90 برای تامنیل مناسب است) optimize=True, ) print(f"✅ Thumbnail saved: {output_path} | Size: {img.size}") except Exception as e: print(f"❌ Image Error {input_path}: {e}") def is_image_mostly_white( img: Image.Image, white_threshold: int = 240, white_ratio: float = 0.95 ) -> bool: """ بررسی می‌کند که آیا تصویر عمدتاً سفید است. :param img: تصویر PIL (ترجیحاً RGB) :param white_threshold: مقدار آستانه برای سفید بودن یک پیکسل (0–255). مثلاً 240 یعنی R,G,B ≥ 240 :param white_ratio: نسبت پیکسل‌های سفید لازم برای در نظر گرفتن تصویر به عنوان "خالی" (مثلاً 0.95 = 95%) :return: True اگر تصویر عمدتاً سفید باشد """ img = img.convert("RGB") arr = np.array(img) # تعداد پیکسل‌هایی که R,G,B همگی ≥ white_threshold # شکل arr: (height, width, 3) white_pixels = np.sum( (arr[:, :, 0] >= white_threshold) & (arr[:, :, 1] >= white_threshold) & (arr[:, :, 2] >= white_threshold) ) total_pixels = arr.shape[0] * arr.shape[1] ratio = white_pixels / total_pixels return ratio >= white_ratio def process_pdf(input_path: Path, output_path: Path): """صفحه اول غیرخالی PDF را با 24 DPI رندر می‌کند، اما تصویر نهایی را به MAX_SIZE تغییر اندازه می‌دهد.""" try: doc = fitz.open(input_path) if doc.page_count == 0: print(f"⚠️ PDF is Empty: {input_path}") doc.close() return zoom = DPI / 72.0 mat = fitz.Matrix(zoom, zoom) target_page = None target_pix = None for page_num in range(doc.page_count): page = doc.load_page(page_num) pix = page.get_pixmap(matrix=mat) # فقط برای تست خالی بودن — نه نهایی! img_check = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) img_thumb = create_thumbnail( img_check, max_width=MAX_SIZE, method="width", bg_color=(255, 255, 255) ) if not is_image_mostly_white(img_thumb, white_threshold=240, white_ratio=0.95): target_page = page_num target_pix = pix print(f"📄 Page {page_num + 1} selected (non-empty) in {input_path.name}") break if target_pix is None: print(f"❗ All pages empty; using page 1: {input_path}") page = doc.load_page(0) target_pix = page.get_pixmap(matrix=mat) # ✅ تبدیل واقعی به تصویر + تامنیل‌سازی img = Image.frombytes("RGB", [target_pix.width, target_pix.height], target_pix.samples) img = create_thumbnail( # ← این خط جدید کل مشکل را حل می‌کند img, max_width=MAX_SIZE, method="width", bg_color=(255, 255, 255), antialias=True, ) # اعمال واترمارک img = add_watermark( img=img, primary_text=WATERMARK_TEXT, sec_text=WATERMARK2_TEXT, font_size_primary=12, # کمی کاهش برای تامنیل primary_opacity=60, ) # ذخیره out_img_path = output_path.with_suffix(".jpg") # یا .png img.save( out_img_path, format="JPEG", dpi=(DPI, DPI), # فقط برای متادیتا — اندازه پیکسلی از img.size می‌آید quality=85, optimize=True, ) doc.close() print(f"✅ PDF Thumbnail Saved: {out_img_path} | Size: {img.size}") except Exception as e: print(f"❌ PDF Error {input_path}: {e}") import traceback traceback.print_exc() def copy_and_process_structure(input_dir: Path, output_dir: Path): for root, dirs, files in os.walk(input_dir): rel_path = Path(root).relative_to(input_dir) target_dir = output_dir / rel_path target_dir.mkdir(parents=True, exist_ok=True) for file in files: src_file = Path(root) / file ext = src_file.suffix.lower() if ext in SUPPORTED_IMAGE_EXTS: dst_file = (target_dir / src_file.stem).with_suffix(".jpg") process_image(src_file, dst_file) elif ext in SUPPORTED_PDF_EXTS: # حفظ نام فایل اما تبدیل به تصویر (پسوند عوض می‌شود به .png) dst_file = target_dir / src_file.stem # بدون پسوند process_pdf(src_file, dst_file) else: print(f"⏭️ This File {src_file} Not Supported Ext") # ========== اجرای اصلی ========== if __name__ == "__main__": OUTPUT_DIR.mkdir(parents=True, exist_ok=True) print(f"Start from {INPUT_DIR} to {OUTPUT_DIR}") copy_and_process_structure(INPUT_DIR, OUTPUT_DIR) print("End") print(":D")