import os
import gradio as gr
import numpy as np
import spaces
import torch
import random
from PIL import Image
from typing import Iterable
from gradio.themes.utils import colors
from deep_translator import GoogleTranslator
from transformers import pipeline
import datetime
import time
from collections import defaultdict
import threading
# --- تعریف تم (بدون تغییر) ---
colors.steel_blue = colors.Color(
name="steel_blue", c50="#EBF3F8", c100="#D3E5F0", c200="#A8CCE1", c300="#7DB3D2", c400="#529AC3", c500="#4682B4", c600="#3E72A0", c700="#36638C", c800="#2E5378", c900="#264364", c950="#1E3450",
)
# --- سیستم مدیریت اعتبار کاربران (بخش جدید) ---
USER_DATA = {}
USER_LOCKS = defaultdict(threading.Lock)
DAILY_CREDIT_LIMIT = 5
def check_and_use_credit(fingerprint: str) -> bool:
"""اعتبار کاربر را بررسی و در صورت وجود، یکی کم میکند."""
if not fingerprint:
return False
with USER_LOCKS[fingerprint]:
today = datetime.date.today().isoformat()
user = USER_DATA.get(fingerprint, {'credits': DAILY_CREDIT_LIMIT, 'last_reset': today})
# اگر تاریخ گذشته بود، اعتبار را ریست کن
if user['last_reset'] != today:
user['credits'] = DAILY_CREDIT_LIMIT
user['last_reset'] = today
if user['credits'] > 0:
user['credits'] -= 1
USER_DATA[fingerprint] = user
print(f"Credit used for {fingerprint}. Remaining: {user['credits']}")
return True
else:
print(f"No credits left for {fingerprint}.")
return False
def get_user_status_api(fingerprint: str) -> dict:
"""وضعیت فعلی کاربر را برای نمایش در UI برمیگرداند."""
if not fingerprint:
return {'credits': 0, 'next_reset_timestamp': 0}
with USER_LOCKS[fingerprint]:
today = datetime.date.today()
user = USER_DATA.get(fingerprint, {'credits': DAILY_CREDIT_LIMIT, 'last_reset': today.isoformat()})
if user['last_reset'] != today.isoformat():
user['credits'] = DAILY_CREDIT_LIMIT
user['last_reset'] = today.isoformat()
USER_DATA[fingerprint] = user
tomorrow = today + datetime.timedelta(days=1)
next_reset_timestamp = int(time.mktime(tomorrow.timetuple()))
return {'credits': user['credits'], 'next_reset_timestamp': next_reset_timestamp}
# --- بارگذاری سیستم امنیتی دوگانه (بدون تغییر) ---
print("Loading Safety Checkers...")
safety_classifier_1 = pipeline("image-classification", model="Falconsai/nsfw_image_detection", device=-1)
safety_classifier_2 = pipeline("image-classification", model="AdamCodd/vit-base-nsfw-detector", device=-1)
def is_image_nsfw(image):
if image is None: return False
try:
results1 = safety_classifier_1(image)
for result in results1:
if result['label'] == 'nsfw' and result['score'] > 0.5:
print(f"Safety Check 1 Failed: {result['score']}")
return True
results2 = safety_classifier_2(image)
for result in results2:
label, score = result['label'].lower(), result['score']
if label == 'nsfw' and score > 0.3:
print(f"Safety Check 2 (NSFW) Failed: {score}")
return True
if label in ['sexy', 'porn', 'hentai'] and score > 0.4:
print(f"Safety Check 2 (Partial) Failed: {label} - {score}")
return True
return False
except Exception as e:
print(f"Safety check error: {e}")
return True
BANNED_WORDS = [
"nsfw", "nude", "naked", "sex", "porn", "erotic", "xxx", "18+", "uncensored", "breast", "nipple", "areola", "cleavage", "topless", "open chest", "genital", "vagina", "penis", "dick", "cock", "pussy", "ass", "butt", "anus", "lingerie", "bikini", "swimwear", "underwear", "panties", "bra", "fetish", "bdsm", "bondage", "exhibitionism", "voyeur", "hentai", "ecchi", "ahegao", "paizuri", "undressed", "stripping", "naked body", "exposed skin", "sheer", "see-through", "rape", "violence", "blood", "gore", "sexual"
]
def check_text_safety(text):
if not text: return True
text_lower = text.lower()
for word in BANNED_WORDS:
if word in text_lower:
print(f"Banned word found: {word}")
return False
return True
def translate_prompt(text):
if not text: return ""
try:
return GoogleTranslator(source='auto', target='en').translate(text)
except Exception as e:
print(f"Translation Error: {e}")
return text
# --- بارگذاری مدل اصلی ویرایش تصویر (بدون تغییر) ---
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
dtype = torch.bfloat16
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Loading Generation 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)
pipe.load_lora_weights("autoweeb/Qwen-Image-Edit-2509-Photo-to-Anime", weight_name="Qwen-Image-Edit-2509-Photo-to-Anime_000001000.safetensors", adapter_name="anime")
pipe.load_lora_weights("dx8152/Qwen-Edit-2509-Multiple-angles", weight_name="镜头转换.safetensors", adapter_name="multiple-angles")
pipe.load_lora_weights("dx8152/Qwen-Image-Edit-2509-Light_restoration", weight_name="移除光影.safetensors", adapter_name="light-restoration")
pipe.load_lora_weights("dx8152/Qwen-Image-Edit-2509-Relight", weight_name="Qwen-Edit-Relight.safetensors", adapter_name="relight")
pipe.load_lora_weights("dx8152/Qwen-Edit-2509-Multi-Angle-Lighting", weight_name="多角度灯光-251116.safetensors", adapter_name="multi-angle-lighting")
pipe.load_lora_weights("tlennon-ie/qwen-edit-skin", weight_name="qwen-edit-skin_1.1_000002750.safetensors", adapter_name="edit-skin")
pipe.load_lora_weights("lovis93/next-scene-qwen-image-lora-2509", weight_name="next-scene_lora-v2-3000.safetensors", adapter_name="next-scene")
pipe.load_lora_weights("vafipas663/Qwen-Edit-2509-Upscale-LoRA", weight_name="qwen-edit-enhance_64-v3_000001000.safetensors", adapter_name="upscale-image")
pipe.transformer.set_attn_processor(QwenDoubleStreamAttnProcessorFA3())
MAX_SEED = np.iinfo(np.int32).max
LORA_MAPPING = {
"تبدیل عکس به انیمه": "anime", "تغییر زاویه دید": "multiple-angles", "اصلاح نور و سایه": "light-restoration", "نورپردازی مجدد (Relight)": "relight", "نورپردازی چند زاویهای": "multi-angle-lighting", "روتوش پوست": "edit-skin", "صحنه بعدی (سینمایی)": "next-scene", "افزایش کیفیت (Upscale)": "upscale-image"
}
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
w, h = image.size
new_w, new_h = (1024, int(1024 * h / w)) if w > h else (int(1024 * w / h), 1024)
return (new_w // 8) * 8, (new_h // 8) * 8
def get_error_html(message):
return f"""
⛔ {message}
"""
def get_success_html(message):
return f"""✅ {message}
"""
@spaces.GPU(duration=45)
def infer(
input_image, prompt, lora_adapter_persian, seed, randomize_seed,
guidance_scale, steps, aspect_ratio_selection, custom_width, custom_height,
is_paid_user, user_fingerprint, # ورودیهای جدید برای مدیریت اعتبار
progress=gr.Progress(track_tqdm=True)
):
# --- بخش جدید: بررسی اعتبار قبل از هر چیز ---
if not is_paid_user:
can_generate = check_and_use_credit(user_fingerprint)
if not can_generate:
return None, seed, get_error_html("اعتبار رایگان روزانه شما تمام شده است. اعتبار فردا مجدداً شارژ خواهد شد.")
if input_image is None: return None, seed, get_error_html("لطفاً ابتدا یک تصویر بارگذاری کنید.")
if is_image_nsfw(input_image): return None, seed, get_error_html("تصویر ورودی دارای محتوای نامناسب است.")
english_prompt = translate_prompt(prompt)
if not check_text_safety(english_prompt): return None, seed, get_error_html("متن درخواست شامل کلمات غیرمجاز است.")
adapter_internal_name = LORA_MAPPING.get(lora_adapter_persian)
if adapter_internal_name: pipe.set_adapters([adapter_internal_name], adapter_weights=[1.0])
if randomize_seed: seed = random.randint(0, MAX_SEED)
generator = torch.Generator(device=device).manual_seed(seed)
safety_negative = "nsfw, nude, naked, porn, sexual, xxx, breast, nipple, areola, genital, vagina, penis, ass, lingerie, bikini, swimwear, underwear, fetish, topless, open chest, revealing clothes, cleavage, see-through, sheer, gore, violence, blood, navel, midriff, exposed skin, erotic, ecchi, hentai, uncensored, stripping"
final_negative_prompt = f"{safety_negative}, worst quality, low quality"
original_image = input_image.convert("RGB")
selection_value = ASPECT_RATIOS_MAP.get(aspect_ratio_selection)
if selection_value == "Custom":
width, height = (int(custom_width) // 8) * 8, (int(custom_height) // 8) * 8
elif selection_value == "Auto":
width, height = update_dimensions_on_upload(original_image)
else:
width, height = selection_value
try:
result = pipe(image=original_image, prompt=english_prompt, negative_prompt=final_negative_prompt, height=height, width=width, num_inference_steps=steps, generator=generator, true_cfg_scale=guidance_scale).images[0]
if is_image_nsfw(result): return None, seed, get_error_html("تصویر تولید شده حاوی محتوای نامناسب بود و حذف شد.")
return result, seed, get_success_html("تصویر با موفقیت ویرایش شد.")
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}")
@spaces.GPU(duration=30)
def infer_example(input_image, prompt, lora_adapter):
# مثالها اعتبار کم نمیکنند
res, s, status = infer(input_image, prompt, lora_adapter, 0, True, 1.0, 4, "خودکار (پیشفرض)", 1024, 1024, True, "example_user")
return res, s, status
# --- جاوااسکریپت برای دانلود (بدون تغییر) ---
js_download_func = "async(e)=>{if(!e){return void alert('لطفاً ابتدا تصویر را تولید کنید.')};let o=e.url;o&&!o.startsWith('http')?o=window.location.origin+o:!o&&e.path&&(o=window.location.origin+'/file='+e.path),window.parent.postMessage({type:'DOWNLOAD_REQUEST',url:o},'*')}"
# --- جاوااسکریپت و CSS اصلی (با تغییرات زیاد) ---
js_and_css_code = """
"""
# استفاده از gr.Blocks
with gr.Blocks(theme=gr.themes.Soft(primary_hue=colors.steel_blue)) as demo:
gr.HTML(js_and_css_code)
with gr.Column(elem_id="col-container"):
gr.Markdown("# **ویرایشگر هوشمند آلفا**", elem_id="main-title")
gr.Markdown("با هوش مصنوعی آلفا تصاویر تونو به مدل های مختلف ویرایش کنید.", elem_id="main-description")
# --- بخش جدید: نمایش وضعیت کاربر ---
gr.HTML("""
...
در حال بررسی وضعیت حساب...
زمان تا شارژ مجدد اعتبار:
""")
# --- بخش جدید: کامپوننتهای مخفی برای ارتباط JS و Python ---
with gr.Row(visible=False):
fingerprint_input = gr.Textbox(elem_id="fingerprint-input-for-backend", label="FP")
is_paid_input = gr.Textbox(elem_id="is-paid-input-for-backend", label="Paid")
status_check_btn = gr.Button(elem_id="status-check-btn-hidden")
status_json_output = gr.JSON(label="Status JSON")
with gr.Row(equal_height=True):
with gr.Column():
input_image = gr.Image(label="بارگذاری تصویر", type="pil", height=320)
prompt = gr.Text(label="دستور ویرایش (به فارسی)", placeholder="مثال: تصویر را به سبک انیمه تبدیل کن...", rtl=True, lines=3)
status_box = gr.HTML(label="وضعیت")
run_button = gr.Button("✨ شروع پردازش و ساخت تصویر", variant="primary", elem_classes="primary-btn", elem_id="run-btn")
with gr.Column():
output_image = gr.Image(label="تصویر نهایی", interactive=False, format="png", height=380)
download_button = gr.Button("📥 دانلود و ذخیره تصویر", variant="secondary", elem_id="download-btn", elem_classes="primary-btn")
lora_adapter = gr.Dropdown(label="انتخاب سبک ویرایش (LoRA)", choices=list(LORA_MAPPING.keys()), value="تبدیل عکس به انیمه")
with gr.Accordion("تنظیمات پیشرفته", open=False):
aspect_ratio_selection = gr.Dropdown(label="ابعاد تصویر خروجی", choices=ASPECT_RATIOS_LIST, value="خودکار (پیشفرض)")
with gr.Row(visible=False) as custom_dims_row:
custom_width = gr.Slider(label="عرض", minimum=256, maximum=2048, step=8, value=1024)
custom_height = gr.Slider(label="ارتفاع", minimum=256, maximum=2048, step=8, value=1024)
seed = gr.Slider(label="دانه تصادفی (Seed)", minimum=0, maximum=MAX_SEED, step=1, value=0)
randomize_seed = gr.Checkbox(label="استفاده از Seed تصادفی", value=True)
guidance_scale = gr.Slider(label="وفاداری به متن", minimum=1.0, maximum=10.0, step=0.1, value=1.0)
steps = gr.Slider(label="مراحل پردازش", minimum=1, maximum=50, step=1, value=4)
def toggle_row(choice):
return gr.update(visible=choice == "شخصیسازی (Custom)")
aspect_ratio_selection.change(fn=toggle_row, inputs=aspect_ratio_selection, outputs=custom_dims_row)
gr.Examples(
examples=[["examples/1.jpg", "تبدیل به انیمه کن.", "تبدیل عکس به انیمه"], ["examples/5.jpg", "سایهها را حذف کن و نورپردازی نرم بده.", "اصلاح نور و سایه"]],
inputs=[input_image, prompt, lora_adapter], outputs=[output_image, seed, status_box], fn=infer_example, cache_examples=False, label="نمونهها"
)
# --- اتصال رویدادها ---
run_button.click(
fn=infer,
inputs=[input_image, prompt, lora_adapter, seed, randomize_seed, guidance_scale, steps, aspect_ratio_selection, custom_width, custom_height, is_paid_input, fingerprint_input],
outputs=[output_image, seed, status_box],
api_name="predict"
)
# رویداد دکمه مخفی برای گرفتن وضعیت کاربر
status_check_btn.click(
fn=get_user_status_api,
inputs=[fingerprint_input],
outputs=[status_json_output]
)
# وقتی خروجی JSON آپدیت شد، تابع جاوااسکریپت را صدا بزن
status_json_output.change(
fn=None,
inputs=[status_json_output],
js="""
(jsonData) => {
// Check if the function exists on window before calling
if (window.updateUIFromGradio) {
window.updateUIFromGradio(jsonData);
} else {
console.error("Gradio UI update function not found!");
}
}
"""
)
download_button.click(fn=None, inputs=[output_image], outputs=None, js=js_download_func)
# --- تعریف API برای ارتباط مستقیم (در صورت نیاز) ---
demo.api(name="get_status")(get_user_status_api)
if __name__ == "__main__":
demo.queue(max_size=30).launch(show_error=True)