Spaces:
Runtime error
Runtime error
| import os | |
| import gradio as gr | |
| from PIL import Image, ImageEnhance, ImageFilter, ImageDraw, ImageFont | |
| from modules.utils.file_utils import _get_all_image_paths | |
| def _apply_pil_enhancement(img: Image.Image, enhancer_type: ImageEnhance, level: int) -> Image.Image: | |
| """PIL ImageEnhance kullanarak parlaklık veya kontrast ayarı yapar.""" | |
| # Level: -100'den 100'e. Factor: 0.0'dan 2.0'a (1.0 orijinal) | |
| factor = (level / 100.0) + 1.0 | |
| factor = max(0.0, factor) | |
| enhancer = enhancer_type(img) | |
| return enhancer.enhance(factor) | |
| def process_brightness_contrast(progress=gr.Progress(), folder_paths_str: str="", brightness_level: int=0, contrast_level: int=0): | |
| folder_paths = [p.strip() for p in folder_paths_str.split('\n') if p.strip()] | |
| if not folder_paths: return "⚠️ Klasör yolu girin.", gr.update(value="⚠️ İptal.", visible=True) | |
| if brightness_level == 0 and contrast_level == 0: return "⚠️ Değişiklik yok.", gr.update(value="⚠️ İptal.", visible=True) | |
| processed_count = 0 | |
| output_messages = [f"ℹ️ Parlaklık/Kontrast işlemi (P: {brightness_level}, K: {contrast_level})."] | |
| all_image_paths = _get_all_image_paths(folder_paths) | |
| total = len(all_image_paths) | |
| if total == 0: return "⚠️ Resim bulunamadı.", gr.update(value="⚠️ Resim Yok.", visible=True) | |
| for i, file_path in enumerate(all_image_paths): | |
| filename = os.path.basename(file_path) | |
| progress((i / total), desc=f"İşleniyor: {filename}") | |
| try: | |
| with Image.open(file_path) as img: | |
| orig_mode = img.mode | |
| if brightness_level != 0: img = _apply_pil_enhancement(img, ImageEnhance.Brightness, brightness_level) | |
| if contrast_level != 0: img = _apply_pil_enhancement(img, ImageEnhance.Contrast, contrast_level) | |
| ext = os.path.splitext(filename)[1].lower() | |
| if ext in ('.jpg', '.jpeg'): img.convert("RGB").save(file_path, "JPEG", quality=95) | |
| elif ext == '.webp': img.save(file_path, "WEBP", lossless=True) | |
| else: | |
| if orig_mode in ('RGBA', 'P'): img.save(file_path) | |
| else: img.convert(orig_mode).save(file_path) | |
| processed_count += 1 | |
| except Exception as e: output_messages.append(f"❌ Hata ({filename}): {e}") | |
| return "\n".join(output_messages), gr.update(value=f"✅ {processed_count} resim işlendi.", visible=True) | |
| def process_denoise_sharpen(progress=gr.Progress(), folder_paths_str: str="", denoise_level: int=0, sharpen_amount: float=0.0): | |
| folder_paths = [p.strip() for p in folder_paths_str.split('\n') if p.strip()] | |
| if not folder_paths: return "⚠️ Klasör yolu girin.", gr.update(value="⚠️ İptal.", visible=True) | |
| if denoise_level == 0 and sharpen_amount == 0.0: return "⚠️ Değişiklik yok.", gr.update(value="⚠️ İptal.", visible=True) | |
| processed_count = 0 | |
| output_messages = [f"ℹ️ Gürültü/Netlik işlemi (G: {denoise_level}, N: {sharpen_amount})."] | |
| all_image_paths = _get_all_image_paths(folder_paths) | |
| total = len(all_image_paths) | |
| if total == 0: return "⚠️ Resim bulunamadı.", gr.update(value="⚠️ Resim Yok.", visible=True) | |
| for i, file_path in enumerate(all_image_paths): | |
| filename = os.path.basename(file_path) | |
| progress((i / total), desc=f"İşleniyor: {filename}") | |
| try: | |
| with Image.open(file_path) as img: | |
| orig_mode = img.mode | |
| if denoise_level > 0: img = img.filter(ImageFilter.MedianFilter(size=denoise_level * 2 + 1)) | |
| if sharpen_amount > 0.0: img = ImageEnhance.Sharpness(img).enhance(sharpen_amount) | |
| ext = os.path.splitext(filename)[1].lower() | |
| if ext in ('.jpg', '.jpeg'): img.convert("RGB").save(file_path, "JPEG", quality=95) | |
| elif ext == '.webp': img.save(file_path, "WEBP", lossless=True) | |
| else: | |
| if orig_mode in ('RGBA', 'P'): img.save(file_path) | |
| else: img.convert(orig_mode).save(file_path) | |
| processed_count += 1 | |
| except Exception as e: output_messages.append(f"❌ Hata ({filename}): {e}") | |
| return "\n".join(output_messages), gr.update(value=f"✅ {processed_count} resim işlendi.", visible=True) | |
| def process_resolution_change(progress=gr.Progress(), folder_paths_str="", scale_factor=1.0): | |
| folder_paths = [p.strip() for p in folder_paths_str.split('\n') if p.strip()] | |
| if not folder_paths: return "⚠️ Klasör yolu girin.", gr.update(value="⚠️ İptal.", visible=True) | |
| scale = float(scale_factor) | |
| processed_count = 0 | |
| output_messages = ["ℹ️ Çözünürlük değiştirme işlemi başladı."] | |
| all_image_paths = _get_all_image_paths(folder_paths) | |
| total = len(all_image_paths) | |
| if total == 0: return "⚠️ Resim bulunamadı.", gr.update(value="⚠️ Resim Yok.", visible=True) | |
| for i, file_path in enumerate(all_image_paths): | |
| filename = os.path.basename(file_path) | |
| progress((i / total), desc=f"İşleniyor: {filename}") | |
| try: | |
| with Image.open(file_path) as img: | |
| nw = int(img.width * scale) | |
| nh = int(img.height * scale) | |
| if abs(nw - img.width) < 1 and abs(nh - img.height) < 1: continue | |
| img.resize((nw, nh), Image.Resampling.LANCZOS).save(file_path) | |
| processed_count += 1 | |
| except Exception as e: output_messages.append(f"❌ Hata ({filename}): {e}") | |
| return "\n".join(output_messages), gr.update(value=f"✅ {processed_count} resim yeniden boyutlandırıldı.", visible=True) | |
| def process_text_watermark(progress=gr.Progress(), folder_paths_str="", watermark_text="", opacity=0.35, font_size_ratio=0.05, rotation_angle=-45): | |
| folder_paths = [p.strip() for p in folder_paths_str.split('\n') if p.strip()] | |
| if not folder_paths or not watermark_text: return "⚠️ Yol veya metin eksik.", gr.update(value="⚠️ İptal.", visible=True) | |
| processed = 0 | |
| all_paths = _get_all_image_paths(folder_paths) | |
| total = len(all_paths) | |
| if total == 0: return "⚠️ Resim yok.", gr.update(value="⚠️ İptal.", visible=True) | |
| font_path = "arial.ttf" | |
| try: ImageFont.truetype(font_path, 10) | |
| except: font_path = None # Default kullan | |
| for i, path in enumerate(all_paths): | |
| progress(i/total, desc=f"Filigran: {os.path.basename(path)}") | |
| try: | |
| with Image.open(path).convert("RGBA") as base: | |
| W, H = base.size | |
| fs = max(10, int(W * font_size_ratio)) | |
| font = ImageFont.truetype(font_path, fs) if font_path else ImageFont.load_default() | |
| # Layer oluştur | |
| txt_layer = Image.new('RGBA', (W*2, H*2), (0,0,0,0)) | |
| draw = ImageDraw.Draw(txt_layer) | |
| fill = (255, 255, 255, int(255 * opacity)) | |
| # Metin boyutu | |
| bbox = draw.textbbox((0,0), watermark_text, font=font) | |
| tw, th = bbox[2]-bbox[0], bbox[3]-bbox[1] | |
| # Döşeme (Tiling) | |
| xspace, yspace = max(50, tw*2), max(50, th*4) | |
| for y in range(0, H*2, yspace): | |
| for x in range(0, W*2, xspace): | |
| draw.text((x + (y//yspace % 2)*(xspace//2), y), watermark_text, font=font, fill=fill) | |
| # Döndür ve Kırp | |
| if rotation_angle != 0: | |
| txt_layer = txt_layer.rotate(rotation_angle, resample=Image.BICUBIC) | |
| cx, cy = txt_layer.width//2, txt_layer.height//2 | |
| final_layer = txt_layer.crop((cx - W//2, cy - H//2, cx + W//2, cy + H//2)) | |
| base.alpha_composite(final_layer) | |
| ext = os.path.splitext(path)[1].lower() | |
| if ext in ('.jpg', '.jpeg'): base.convert("RGB").save(path, "JPEG", quality=95) | |
| else: base.save(path) | |
| processed += 1 | |
| except Exception as e: print(f"Hata: {e}") | |
| return "İşlem tamam.", gr.update(value=f"✅ {processed} resme filigran eklendi.", visible=True) | |
| def process_format_change(progress=gr.Progress(), folder_paths_str="", target_format=""): | |
| folder_paths = [p.strip() for p in folder_paths_str.split('\n') if p.strip()] | |
| if not folder_paths: return "⚠️ Yol girin.", gr.update(value="⚠️ İptal.", visible=True) | |
| fmt = target_format.strip().lower() | |
| if fmt == '.svg': return "❌ SVG desteklenmez.", gr.update(value="❌ Hata.", visible=True) | |
| processed = 0 | |
| all_paths = _get_all_image_paths(folder_paths) | |
| total = len(all_paths) | |
| for i, path in enumerate(all_paths): | |
| progress(i/total, desc=f"Dönüştürülüyor: {os.path.basename(path)}") | |
| name, ext = os.path.splitext(path) | |
| if ext.lower() == fmt: continue | |
| try: | |
| with Image.open(path) as img: | |
| new_path = f"{name}{fmt}" | |
| save_fmt = "JPEG" if fmt in ('.jpg', '.jpeg') else fmt.replace('.', '').upper() | |
| if img.mode == 'RGBA' and save_fmt == 'JPEG': | |
| bg = Image.new('RGB', img.size, (255,255,255)) | |
| bg.paste(img, mask=img.split()[3]) | |
| bg.save(new_path, quality=95) | |
| elif save_fmt == 'PNG': | |
| img.save(new_path) # RGBA korur | |
| else: | |
| img.convert('RGB').save(new_path) | |
| # Eskiyi sil | |
| if os.path.exists(new_path): os.remove(path) | |
| processed += 1 | |
| except Exception as e: print(f"Hata: {e}") | |
| return "İşlem tamam.", gr.update(value=f"✅ {processed} resim dönüştürüldü.", visible=True) | |