import os
import gradio as gr
import numpy as np
import spaces
import torch
import random
import gc
from PIL import Image
from typing import Iterable
from gradio.themes import Soft
from gradio.themes.utils import colors, fonts, sizes
from deep_translator import GoogleTranslator
from transformers import pipeline
from datetime import date
import json
# ==========================================
# 1. تنظیمات تم (Orange Red Theme)
# ==========================================
colors.orange_red = colors.Color(
name="orange_red",
c50="#FFF0E5",
c100="#FFE0CC",
c200="#FFC299",
c300="#FFA366",
c400="#FF8533",
c500="#FF4500",
c600="#E63E00",
c700="#CC3700",
c800="#B33000",
c900="#992900",
c950="#802200",
)
class OrangeRedTheme(Soft):
def __init__(
self,
*,
primary_hue: colors.Color | str = colors.gray,
secondary_hue: colors.Color | str = colors.orange_red,
neutral_hue: colors.Color | str = colors.slate,
text_size: sizes.Size | str = sizes.text_lg,
font: fonts.Font | str | Iterable[fonts.Font | str] = (
fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
),
font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
),
):
super().__init__(
primary_hue=primary_hue,
secondary_hue=secondary_hue,
neutral_hue=neutral_hue,
text_size=text_size,
font=font,
font_mono=font_mono,
)
super().set(
background_fill_primary="*primary_50",
background_fill_primary_dark="*primary_900",
body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
button_primary_text_color="white",
button_primary_text_color_hover="white",
button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",
button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",
button_secondary_text_color="black",
button_secondary_text_color_hover="white",
button_secondary_background_fill="linear-gradient(90deg, *primary_300, *primary_300)",
button_secondary_background_fill_hover="linear-gradient(90deg, *primary_400, *primary_400)",
button_secondary_background_fill_dark="linear-gradient(90deg, *primary_500, *primary_600)",
button_secondary_background_fill_hover_dark="linear-gradient(90deg, *primary_500, *primary_500)",
slider_color="*secondary_500",
slider_color_dark="*secondary_600",
block_title_text_weight="600",
block_border_width="3px",
block_shadow="*shadow_drop_lg",
button_primary_shadow="*shadow_drop_lg",
button_large_padding="11px",
color_accent_soft="*primary_100",
block_label_background_fill="*primary_200",
)
orange_red_theme = OrangeRedTheme()
# ==========================================
# 2. تنظیمات سیستم اعتبار (Limit = 3)
# ==========================================
USAGE_LIMIT = 3
DATA_FILE = "usage_data_fusion.json"
PREMIUM_PAGE_ID = '1149636'
def load_usage_data():
if os.path.exists(DATA_FILE):
try:
with open(DATA_FILE, 'r') as f:
return json.load(f)
except:
return {}
return {}
def save_usage_data(data):
try:
with open(DATA_FILE, 'w') as f:
json.dump(data, f)
except Exception as e:
print(f"Error saving data: {e}")
usage_data_cache = load_usage_data()
def get_user_record(fingerprint):
global usage_data_cache
if not fingerprint: return None
usage_data_cache = load_usage_data()
today_str = date.today().isoformat()
user_record = usage_data_cache.get(fingerprint)
if not user_record or user_record.get("last_reset") != today_str:
return {"count": 0, "last_reset": today_str}
return user_record
def consume_quota(fingerprint):
global usage_data_cache
today_str = date.today().isoformat()
usage_data_cache = load_usage_data()
user_record = usage_data_cache.get(fingerprint)
if not user_record or user_record.get("last_reset") != today_str:
user_record = {"count": 0, "last_reset": today_str}
user_record["count"] += 1
usage_data_cache[fingerprint] = user_record
save_usage_data(usage_data_cache)
return user_record["count"]
# ==========================================
# 3. سیستم ایمنی (Safety - Strict Mode)
# ==========================================
print("Loading Safety Checker...")
safety_classifier = pipeline("image-classification", model="Falconsai/nsfw_image_detection", device=-1)
def is_image_nsfw(image):
if image is None: return False
try:
results = safety_classifier(image)
for result in results:
if result['label'] == 'nsfw' and result['score'] > 0.75:
return True
return False
except Exception as e:
print(f"Safety check error: {e}")
return False
BANNED_WORDS = [
"nsfw", "nude", "naked", "sex", "porn", "erotic", "xxx", "18+", "adult",
"explicit", "uncensored", "sexual", "lewd", "sensual", "lust", "horny",
"breast", "breasts", "nipple", "nipples", "vagina", "pussy", "cunt",
"penis", "dick", "cock", "genital", "genitals", "groin", "pubic",
"ass", "butt", "buttocks", "anus", "anal", "rectum",
"intercourse", "masturbation", "orgasm", "blowjob", "bj", "cum", "sperm",
"ejaculation", "penetration", "fucking", "sucking", "licking",
"lingerie", "bikini", "swimwear", "underwear", "panties", "bra", "thong",
"topless", "bottomless", "undressed", "unclothed", "skimpy", "transparent",
"see-through", "fetish", "bdsm", "bondage", "latex", "hentai", "ecchi", "ahegao",
"exhibitionism", "voyeur", "harem", "gore", "bloody", "blood", "kill", "murder",
"dead", "torture", "abuse"
]
def check_text_safety(text):
if not text: return True
text_lower = text.lower()
padded_text = f" {text_lower} "
for char in [".", ",", "!", "?", "-", "_", "(", ")", "[", "]", "{", "}"]:
padded_text = padded_text.replace(char, " ")
for word in BANNED_WORDS:
if f" {word} " in padded_text:
return False
return True
def translate_prompt(text):
if not text: return ""
try:
translated = GoogleTranslator(source='auto', target='en').translate(text)
return translated
except Exception as e:
print(f"Translation Error: {e}")
return text
# ==========================================
# 4. بارگذاری مدل و LoRA ها + مدیریت حافظه
# ==========================================
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
dtype = torch.bfloat16
# تابع مهم برای خالی کردن حافظه و جلوگیری از ارور NVML
def flush():
gc.collect()
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
from diffusers import FlowMatchEulerDiscreteScheduler
from qwenimage.pipeline_qwenimage_edit_plus import QwenImageEditPlusPipeline
from qwenimage.transformer_qwenimage import QwenImageTransformer2DModel
from qwenimage.qwen_fa3_processor import QwenDoubleStreamAttnProcessorFA3
print("Loading Qwen Image Edit Pipeline...")
pipe = QwenImageEditPlusPipeline.from_pretrained(
"Qwen/Qwen-Image-Edit-2509",
transformer=QwenImageTransformer2DModel.from_pretrained(
"linoyts/Qwen-Image-Edit-Rapid-AIO",
subfolder='transformer',
torch_dtype=dtype,
device_map='cuda'
),
torch_dtype=dtype
).to(device)
print("Loading and Fusing Lightning LoRA...")
pipe.load_lora_weights("lightx2v/Qwen-Image-Lightning", weight_name="Qwen-Image-Lightning-4steps-V2.0-bf16.safetensors", adapter_name="lightning")
pipe.fuse_lora(adapter_names=["lightning"], lora_scale=1.0)
print("Loading Task Adapters...")
pipe.load_lora_weights("tarn59/apply_texture_qwen_image_edit_2509", weight_name="apply_texture_v2_qwen_image_edit_2509.safetensors", adapter_name="texture")
pipe.load_lora_weights("ostris/qwen_image_edit_inpainting", weight_name="qwen_image_edit_inpainting.safetensors", adapter_name="fusion")
pipe.load_lora_weights("ostris/qwen_image_edit_2509_shirt_design", weight_name="qwen_image_edit_2509_shirt_design.safetensors", adapter_name="shirt_design")
pipe.load_lora_weights("dx8152/Qwen-Image-Edit-2509-Fusion", weight_name="溶图.safetensors", adapter_name="fusion-x")
pipe.load_lora_weights("oumoumad/Qwen-Edit-2509-Material-transfer", weight_name="material-transfer_000004769.safetensors", adapter_name="material-transfer")
pipe.load_lora_weights("dx8152/Qwen-Edit-2509-Light-Migration", weight_name="参考色调.safetensors", adapter_name="light-migration")
try:
pipe.transformer.set_attn_processor(QwenDoubleStreamAttnProcessorFA3())
print("Flash Attention 3 Processor set successfully.")
except Exception as e:
print(f"Could not set FA3 processor: {e}. using default attention.")
MAX_SEED = np.iinfo(np.int32).max
LORA_MAPPING_PERSIAN = {
"ویرایش بافت (Texture Edit)": "Texture Edit",
"طراحی روی لباس (Cloth-Design)": "Cloth-Design-Fuse",
"ترکیب اشیاء (Fuse-Objects)": "Fuse-Objects",
"ترکیب پیشرفته (Super-Fusion)": "Super-Fusion",
"انتقال نور (Light-Migration)": "Light-Migration",
"انتقال متریال (Material-Transfer)": "Material-Transfer"
}
ASPECT_RATIOS_LIST = [
"خودکار (پیشفرض)",
"۱:۱ (مربع - 1024x1024)",
"۱۶:۹ (افقی - 1344x768)",
"۹:۱۶ (عمودی - 768x1344)",
"شخصیسازی (Custom)"
]
ASPECT_RATIOS_MAP = {
"خودکار (پیشفرض)": "Auto",
"۱:۱ (مربع - 1024x1024)": (1024, 1024),
"۱۶:۹ (افقی - 1344x768)": (1344, 768),
"۹:۱۶ (عمودی - 768x1344)": (768, 1344),
"شخصیسازی (Custom)": "Custom"
}
def update_dimensions_on_upload(image):
if image is None: return 1024, 1024
original_width, original_height = image.size
if original_width > original_height:
new_width = 1024
aspect_ratio = original_height / original_width
new_height = int(new_width * aspect_ratio)
else:
new_height = 1024
aspect_ratio = original_width / original_height
new_width = int(new_height * aspect_ratio)
new_width = (new_width // 16) * 16
new_height = (new_height // 16) * 16
return new_width, new_height
def update_sliders_visibility(choice):
if choice == "شخصیسازی (Custom)":
return gr.update(visible=True), gr.update(visible=True)
else:
return gr.update(visible=False), gr.update(visible=False)
# ==========================================
# 5. HTML Helpers
# ==========================================
def get_error_html(message):
return f"""
⛔{message}
"""
def get_success_html(message):
return f"""✅{message}
"""
def get_quota_exceeded_html():
return """💎
اعتبار رایگان امروز تمام شد
شما از ۳ تصویر رایگان امروز استفاده کردهاید.
برای ساخت تصاویر نامحدود و حرفهای، لطفا نسخه خود را ارتقا دهید.
"""
# ==========================================
# 6. منطق اصلی پردازش (Infer)
# ==========================================
def check_initial_quota(fingerprint, subscription_status):
if not fingerprint:
return gr.update(visible=True), gr.update(visible=False), None
if subscription_status == 'paid':
return gr.update(visible=True), gr.update(visible=False), None
user_record = get_user_record(fingerprint)
current_usage = user_record["count"] if user_record else 0
if current_usage >= USAGE_LIMIT:
return gr.update(visible=False), gr.update(visible=True), get_quota_exceeded_html()
else:
return gr.update(visible=True), gr.update(visible=False), None
@spaces.GPU(duration=30)
def infer(
image_1,
image_2,
prompt,
lora_adapter_persian,
seed,
randomize_seed,
guidance_scale,
steps,
aspect_ratio_selection,
custom_width,
custom_height,
fingerprint,
subscription_status,
progress=gr.Progress(track_tqdm=True)
):
# پاکسازی حافظه قبل از شروع
flush()
# 1. بررسی اعتبار
if subscription_status != 'paid':
user_record = get_user_record(fingerprint)
if user_record and user_record["count"] >= USAGE_LIMIT:
return None, seed, get_quota_exceeded_html(), gr.update(visible=False), gr.update(visible=True)
# 2. بررسی ورودیها
if image_1 is None or image_2 is None:
return None, seed, get_error_html("لطفاً هر دو تصویر پایه و مرجع را بارگذاری کنید."), gr.update(visible=True), gr.update(visible=False)
# 3. بررسی ایمنی تصاویر ورودی
if is_image_nsfw(image_1) or is_image_nsfw(image_2):
return None, seed, get_error_html("یکی از تصاویر ورودی حاوی محتوای نامناسب است."), gr.update(visible=True), gr.update(visible=False)
# 4. ترجمه و بررسی ایمنی متن
lora_adapter = LORA_MAPPING_PERSIAN.get(lora_adapter_persian, "Texture Edit")
english_prompt = translate_prompt(prompt)
if not check_text_safety(english_prompt):
return None, seed, get_error_html("متن درخواست شامل کلمات غیرمجاز است."), gr.update(visible=True), gr.update(visible=False)
if not english_prompt:
if lora_adapter == "Cloth-Design-Fuse": english_prompt = "Put this design on their shirt."
elif lora_adapter == "Texture Edit": english_prompt = "Apply texture to object."
elif lora_adapter == "Fuse-Objects": english_prompt = "Fuse object into background."
elif lora_adapter == "Super-Fusion": english_prompt = "Blend the product into the background, correct its perspective and lighting, and make it naturally integrated with the scene."
elif lora_adapter == "Material-Transfer": english_prompt = "change materials of image1 to match the reference in image2"
elif lora_adapter == "Light-Migration": english_prompt = "Refer to the color tone, remove the original lighting from Image 1, and relight Image 1 based on the lighting and color tone of Image 2."
# 5. کسر اعتبار
if subscription_status != 'paid':
consume_quota(fingerprint)
# 6. تنظیم آداپتر
adapters_map = {
"Texture Edit": "texture",
"Fuse-Objects": "fusion",
"Cloth-Design-Fuse": "shirt_design",
"Super-Fusion": "fusion-x",
"Material-Transfer": "material-transfer",
"Light-Migration": "light-migration",
}
active_adapter = adapters_map.get(lora_adapter)
if active_adapter:
pipe.set_adapters([active_adapter], adapter_weights=[1.0])
else:
pipe.set_adapters([], adapter_weights=[])
if randomize_seed:
seed = random.randint(0, MAX_SEED)
generator = torch.Generator(device=device).manual_seed(seed)
negative_prompt = "worst quality, low quality, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, jpeg artifacts, signature, watermark, username, blurry, nsfw, nude"
img1_pil = image_1.convert("RGB")
img2_pil = image_2.convert("RGB")
# 7. تنظیم ابعاد تصویر
selection_value = ASPECT_RATIOS_MAP.get(aspect_ratio_selection)
if selection_value == "Custom":
width = (int(custom_width) // 16) * 16
height = (int(custom_height) // 16) * 16
elif selection_value == "Auto" or selection_value is None:
width, height = update_dimensions_on_upload(img1_pil)
else:
width, height = selection_value
try:
result = pipe(
image=[img1_pil, img2_pil],
prompt=english_prompt,
negative_prompt=negative_prompt,
height=height,
width=width,
num_inference_steps=steps,
generator=generator,
true_cfg_scale=guidance_scale,
).images[0]
# 8. بررسی ایمنی خروجی
if is_image_nsfw(result):
return None, seed, get_error_html("تصویر خروجی حاوی محتوای نامناسب بود."), gr.update(visible=True), gr.update(visible=False)
# 9. پیام موفقیت
user_record = get_user_record(fingerprint)
remaining = USAGE_LIMIT - user_record["count"] if user_record else 0
success_msg = "تصویر با موفقیت ترکیب شد."
if subscription_status != 'paid':
success_msg += f" (اعتبار باقیمانده: {remaining})"
if subscription_status != 'paid' and remaining <= 0:
return result, seed, get_success_html(success_msg), gr.update(visible=False), gr.update(visible=True)
return result, seed, get_success_html(success_msg), gr.update(visible=True), gr.update(visible=False)
except Exception as e:
error_str = str(e)
if "quota" in error_str.lower() or "exceeded" in error_str.lower():
raise e
return None, seed, get_error_html(f"خطا در پردازش: {error_str}"), gr.update(visible=True), gr.update(visible=False)
finally:
# پاکسازی حافظه بعد از پایان (موفق یا ناموفق)
flush()
@spaces.GPU(duration=30)
def infer_example(image_1, image_2, prompt, lora_adapter):
flush() # پاکسازی قبل از مثال
res, s, status, btn1, btn2 = infer(image_1, image_2, prompt, lora_adapter, 0, True, 1.0, 4, "خودکار (پیشفرض)", 1024, 1024, "example", "paid")
flush() # پاکسازی بعد از مثال
return res, s
# ==========================================
# 7. JS & CSS
# ==========================================
js_download_func = """
async (image) => {
if (!image) { alert("لطفاً ابتدا تصویر را تولید کنید."); return; }
let fileUrl = image.url;
if (fileUrl && !fileUrl.startsWith('http')) { fileUrl = window.location.origin + fileUrl; }
else if (!fileUrl && image.path) { fileUrl = window.location.origin + "/file=" + image.path; }
window.parent.postMessage({ type: 'DOWNLOAD_REQUEST', url: fileUrl }, '*');
}
"""
js_upgrade_func = """() => { window.parent.postMessage({ type: 'NAVIGATE_TO_PREMIUM' }, '*'); }"""
# جاوا اسکریپت اصلاح شده برای رفع باگ دکمهها
js_global = """
"""
css_code = """
"""
# ==========================================
# 8. رابط کاربری (Gradio Blocks)
# ==========================================
with gr.Blocks(theme=orange_red_theme) as demo:
gr.HTML(css_code + js_global)
fingerprint_box = gr.Textbox(elem_id="fingerprint_storage", visible=True)
status_box_input = gr.Textbox(elem_id="status_storage", visible=True)
with gr.Column(elem_id="col-container"):
gr.Markdown("# **ویرایشگر ترکیبی هوشمند (Fusion)**", elem_id="main-title")
gr.Markdown(
"ترکیب، انتقال بافت و ویرایش دو تصویر با هوش مصنوعی آلفا",
elem_id="main-description"
)
gr.HTML('
')
with gr.Row(equal_height=True):
with gr.Column(scale=1):
with gr.Row():
image_1 = gr.Image(label="تصویر پایه (Base)", type="pil", height=290)
image_2 = gr.Image(label="تصویر مرجع (Reference)", type="pil", height=290)
prompt = gr.Text(
label="دستور ویرایش (فارسی)",
show_label=True,
placeholder="مثال: بافت تصویر دوم را روی لیوان اعمال کن...",
rtl=True
)
status_box = gr.HTML(label="وضعیت")
run_button = gr.Button("🔥 شروع ترکیب تصاویر", variant="primary", elem_classes="primary-btn", elem_id="run-btn")
upgrade_button = gr.Button("💎 ارتقا به نسخه نامحدود", variant="primary", elem_classes="upgrade-btn", elem_id="upgrade-btn", visible=False)
with gr.Accordion("تنظیمات پیشرفته", open=False, visible=True):
aspect_ratio_selection = gr.Dropdown(
label="ابعاد تصویر خروجی",
choices=ASPECT_RATIOS_LIST,
value="خودکار (پیشفرض)",
interactive=True
)
with gr.Row(visible=False) as custom_dims_row:
custom_width = gr.Slider(
label="عرض دلخواه (Width)",
minimum=256, maximum=2048, step=16, value=1024
)
custom_height = gr.Slider(
label="ارتفاع دلخواه (Height)",
minimum=256, maximum=2048, step=16, value=1024
)
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
randomize_seed = gr.Checkbox(label="تصادفی", value=True)
guidance_scale = gr.Slider(label="Guidance Scale", minimum=1.0, maximum=10.0, step=0.1, value=1.0)
steps = gr.Slider(label="تعداد مراحل (Steps)", minimum=1, maximum=50, step=1, value=4)
with gr.Column(scale=1):
output_image = gr.Image(label="تصویر نهایی", interactive=False, format="png", height=350)
download_button = gr.Button("📥 دانلود تصویر", variant="secondary", elem_classes="primary-btn")
with gr.Row():
lora_adapter = gr.Dropdown(
label="نوع عملیات (LoRA)",
choices=list(LORA_MAPPING_PERSIAN.keys()),
value="ویرایش بافت (Texture Edit)",
)
gr.Examples(
examples=[
["examples/M1.jpg", "examples/M2.jpg", "نورپردازی تصویر اول را حذف کن و بر اساس نور و رنگ تصویر دوم آن را مجدداً نورپردازی کن.", "انتقال نور (Light-Migration)"],
["examples/Cloth2.jpg", "examples/Design2.png", "این طرح را روی پیراهن قرار بده.", "طراحی روی لباس (Cloth-Design)"],
["examples/Cup1.png", "examples/Wood1.png", "بافت چوب را روی ماگ اعمال کن.", "ویرایش بافت (Texture Edit)"],
["examples/Cloth1.jpg", "examples/Design1.png", "این طرح را روی پیراهن قرار بده.", "طراحی روی لباس (Cloth-Design)"],
["examples/F3.jpg", "examples/F4.jpg", "عینک او را با عینک جدید از تصویر ۱ جایگزین کن.", "ترکیب پیشرفته (Super-Fusion)"],
["examples/Chair.jpg", "examples/Material.jpg", "متریال تصویر ۱ را دقیقاً شبیه به مرجع تصویر ۲ کن.", "انتقال متریال (Material-Transfer)"],
["examples/F1.jpg", "examples/F2.jpg", "بطری کوچک را روی میز قرار بده.", "ترکیب پیشرفته (Super-Fusion)"],
["examples/Mug1.jpg", "examples/Texture1.jpg", "طرح تصویر ۲ را روی ماگ اعمال کن.", "ویرایش بافت (Texture Edit)"],
["examples/Cat1.jpg", "examples/Glass1.webp", "یک گربه که عینک تصویر دوم را زده است.", "ترکیب اشیاء (Fuse-Objects)"],
],
inputs=[image_1, image_2, prompt, lora_adapter],
outputs=[output_image, seed],
fn=infer_example,
cache_examples=False,
label="نمونهها"
)
# تابع نمایش/مخفی کردن اسلایدر ابعاد
def toggle_row(choice):
if choice == "شخصیسازی (Custom)":
return gr.update(visible=True)
return gr.update(visible=False)
aspect_ratio_selection.change(fn=toggle_row, inputs=aspect_ratio_selection, outputs=custom_dims_row)
# اتصال رویدادها
fingerprint_box.change(fn=check_initial_quota, inputs=[fingerprint_box, status_box_input], outputs=[run_button, upgrade_button, status_box])
run_button.click(
fn=infer,
inputs=[
image_1, image_2, prompt, lora_adapter, seed, randomize_seed,
guidance_scale, steps, aspect_ratio_selection, custom_width, custom_height,
fingerprint_box, status_box_input
],
outputs=[output_image, seed, status_box, run_button, upgrade_button]
)
upgrade_button.click(fn=None, js=js_upgrade_func)
download_button.click(fn=None, inputs=[output_image], js=js_download_func)
if __name__ == "__main__":
demo.queue(max_size=30).launch(show_error=True)