Spaces:
Running
on
Zero
Running
on
Zero
File size: 30,335 Bytes
ced6a25 7742f47 ced6a25 7742f47 38d4a7e 1935d38 7742f47 ced6a25 7742f47 2f01800 7742f47 2f01800 7742f47 2f01800 7742f47 2f01800 7742f47 2f01800 7742f47 6ba6190 eb521b9 7742f47 bc72ac7 1935d38 1a7d9b4 1935d38 bc72ac7 2f01800 bc72ac7 7742f47 bc72ac7 1935d38 bc72ac7 7742f47 bc72ac7 7742f47 bc72ac7 1935d38 bc72ac7 7742f47 bc72ac7 7742f47 bc72ac7 7742f47 ced6a25 6ba6190 bc72ac7 ced6a25 7742f47 ced6a25 fa788e6 ced6a25 2210ab4 7742f47 2210ab4 c7971eb 7742f47 1935d38 7742f47 1ebd128 af6ede9 7742f47 af6ede9 c7971eb 7742f47 c7971eb 7742f47 2f01800 7742f47 6ba6190 7742f47 6ba6190 7742f47 2f01800 2210ab4 7742f47 1935d38 6ba6190 7742f47 2210ab4 7742f47 ced6a25 1935d38 7742f47 6ba6190 1935d38 7742f47 1ebd128 1935d38 ced6a25 c7971eb 7742f47 c7971eb 1af347d 7742f47 1af347d ced6a25 6ba6190 ced6a25 7742f47 c7971eb 7742f47 7d604f7 7742f47 3c1a2de 7742f47 3c1a2de 7742f47 2f01800 7742f47 2f01800 7742f47 2f01800 7742f47 2f01800 7742f47 2f01800 7742f47 2f01800 7742f47 2f01800 7742f47 3c32107 7742f47 b4f468a 7742f47 1a7d9b4 7742f47 1a7d9b4 4d3509e 7742f47 4d3509e 63b19ec 7742f47 3c1a2de fc6783c 7742f47 c7971eb 7742f47 3c1a2de 7742f47 2f01800 7742f47 41af4d0 7742f47 3c1a2de 7742f47 3c1a2de 7742f47 3c1a2de 7742f47 7d604f7 7742f47 3c1a2de 7742f47 3c1a2de ced6a25 7742f47 6ba6190 ced6a25 c7971eb 2f01800 7742f47 c7971eb ced6a25 6ba6190 2f01800 c7971eb 7742f47 6ba6190 ced6a25 c7971eb 7742f47 1ebd128 2f01800 7742f47 8f59b64 2f01800 7742f47 8f59b64 7742f47 2f01800 8f59b64 7742f47 8f59b64 7742f47 8f59b64 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 |
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"""<div style="background-color: #fee2e2; border: 1px solid #ef4444; color: #b91c1c; padding: 12px; border-radius: 8px; text-align: center; margin-bottom: 10px; font-weight: bold; display: flex; align-items: center; justify-content: center; gap: 8px;"><span style="font-size: 1.2em;">⛔</span> {message}</div>"""
def get_success_html(message):
return f"""<div style="background-color: #dcfce7; border: 1px solid #22c55e; color: #15803d; padding: 12px; border-radius: 8px; text-align: center; margin-bottom: 10px; font-weight: bold; display: flex; align-items: center; justify-content: center; gap: 8px;"><span style="font-size: 1.2em;">✅</span> {message}</div>"""
@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 = """
<script>
// --- START OF JS LOGIC FOR USER AUTH & CREDITS ---
document.addEventListener('DOMContentLoaded', () => {
// --- بخش جدید: مدیریت وضعیت کاربر و اعتبار ---
const PREMIUM_PAGE_ID = '1149636'; // شناسه صفحه کاربران ویژه
const PREMIUM_URL = '#/nav/online/news/getSingle/1149636/eyJpdiI6InZSVUdlLzBlR0FzOHZJdXFZeWhER0E9PSIsInZhbHVlIjoiWFhqRXBLc29vSFpHdk9nYmRjZGVuWHRHRHVSZHRlTG1BUENLaE5mNXBNVVRGWFg3ZWN0djJ5K1dIY1RqTHJGaCIsIm1hYyI6IjIzYzFlZTMwYmVmMTdkYjQ0YTQ4YWMxNmFhN2RmNWQ2OTc1NDIyNGVlZGI3ZjJjMjhkNmQxNjM4MDFlZTIxNmUiLCJ0YWciOiIifQ==/20934991';
let userFingerprint = null;
let isPaidUser = false;
let countdownInterval = null;
// توابع UI برای نمایش وضعیت
const statusContainer = document.getElementById('user-status-section');
const badgeEl = document.getElementById('subscription-badge');
const creditTextEl = document.getElementById('credit-status-text');
const countdownEl = document.getElementById('countdown-timer');
const upgradeBtn = document.getElementById('upgrade-btn');
const runBtn = document.getElementById('run-btn');
// تابع اصلی برای آپدیت UI بر اساس وضعیت کاربر
function updateUIForUserStatus(statusData) {
statusContainer.style.display = 'block';
if (countdownInterval) clearInterval(countdownInterval);
if (isPaidUser) {
badgeEl.textContent = 'کاربر ویژه';
badgeEl.className = 'paid-badge';
creditTextEl.innerHTML = 'دسترسی شما <strong>نامحدود</strong> است.';
countdownEl.style.display = 'none';
upgradeBtn.style.display = 'none';
runBtn.disabled = false;
} else {
badgeEl.textContent = 'کاربر رایگان';
badgeEl.className = 'free-badge';
const credits = statusData.credits || 0;
if (credits > 0) {
creditTextEl.innerHTML = `شما <strong>${credits} اعتبار</strong> ساخت تصویر برای امروز دارید.`;
runBtn.disabled = false;
upgradeBtn.style.display = 'none';
} else {
creditTextEl.innerHTML = 'اعتبار رایگان امروز شما تمام شده است.';
runBtn.disabled = true;
upgradeBtn.style.display = 'block';
}
// شروع شمارش معکوس
const resetTimestamp = statusData.next_reset_timestamp;
const updateTimer = () => {
const now = Date.now() / 1000;
const timeLeft = Math.max(0, resetTimestamp - now);
if (timeLeft === 0) {
clearInterval(countdownInterval);
initializeApp(); // برای گرفتن اعتبار جدید
return;
}
const h = Math.floor(timeLeft / 3600);
const m = Math.floor((timeLeft % 3600) / 60);
const s = Math.floor(timeLeft % 60);
countdownEl.querySelector('span').textContent = `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
};
updateTimer();
countdownInterval = setInterval(updateTimer, 1000);
countdownEl.style.display = 'block';
}
}
// ارتباط با برنامه اصلی (Parent)
window.addEventListener('message', (event) => {
if (event.data && event.data.type === 'USER_STATUS_RESPONSE') {
try {
const userObject = JSON.parse(event.data.payload || '{}');
isPaidUser = userObject && userObject.isLogin && userObject.accessible_pages &&
(userObject.accessible_pages.includes(PREMIUM_PAGE_ID) || userObject.accessible_pages.includes(parseInt(PREMIUM_PAGE_ID)));
// آپدیت کردن کامپوننتهای مخفی گرادیو
const fingerprintInput = document.querySelector('#fingerprint-input-for-backend textarea');
const isPaidInput = document.querySelector('#is-paid-input-for-backend textarea');
if(fingerprintInput) fingerprintInput.value = userFingerprint;
if(isPaidInput) isPaidInput.value = isPaidUser ? 'true' : 'false';
// ایجاد یک Event برای اینکه گرادیو تغییر را تشخیص دهد
const eventToDispatch = new Event('input', { bubbles: true });
if(fingerprintInput) fingerprintInput.dispatchEvent(eventToDispatch);
if(isPaidInput) isPaidInput.dispatchEvent(eventToDispatch);
// حالا که اطلاعات کاربر را داریم، از بکاند گرادیو وضعیت اعتبار را میپرسیم
// با کلیک کردن روی دکمه مخفی، تابع پایتون را فراخوانی میکنیم
const statusCheckBtn = document.getElementById('status-check-btn-hidden');
if(statusCheckBtn) statusCheckBtn.click();
} catch (e) {
console.error("Error processing user status:", e);
isPaidUser = false; // در صورت خطا، کاربر رایگان در نظر گرفته میشود
}
}
if (event.data.type === 'DOWNLOAD_REQUEST' && event.data.url) {
// این بخش برای دکمه دانلود است که در HTML دیگر تعریف شده
}
if (event.data.type === 'NAVIGATE_TO_URL' && event.data.url) {
window.top.location.href = event.data.url;
}
});
// تابع برای ساخت اثرانگشت مرورگر
async function getBrowserFingerprint() {
const components = [navigator.userAgent, navigator.language, screen.width+'x'+screen.height, new Date().getTimezoneOffset()];
const fingerprintString = components.join('~~~');
let hash = 0;
for (let i = 0; i < fingerprintString.length; i++) {
const char = fingerprintString.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash |= 0;
}
return 'fp_' + Math.abs(hash).toString(16);
}
// تابع اصلی برای شروع
async function initializeApp() {
userFingerprint = await getBrowserFingerprint();
// درخواست اطلاعات کاربر از برنامه اصلی
parent.postMessage({ type: 'REQUEST_USER_STATUS' }, '*');
}
// اتصال دکمه ارتقا
if(upgradeBtn) {
upgradeBtn.addEventListener('click', () => {
parent.postMessage({ type: 'NAVIGATE_TO_PREMIUM', payload: { url: PREMIUM_URL } }, '*');
});
}
// --- مدیریت خطای Quota (بدون تغییر) ---
const showQuotaModal = () => {
if (document.getElementById('custom-quota-modal')) return;
const modalHtml = `<div id="custom-quota-modal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); backdrop-filter: blur(5px); z-index: 99999; display: flex; align-items: center; justify-content: center; font-family: 'Vazirmatn', sans-serif;"><div class="ip-reset-guide-container"><div class="guide-header"><h2>یک قدم تا ساخت تصاویر جدید</h2><p>نیازمند تغییر نقطه دستیابی</p></div><div class="guide-content"><p>برای استفاده نامحدود از هوش مصنوعی، لطفاً نقطه اتصال اینترنت (IP) خود را تغییر دهید (مثلاً با خاموش/روشن کردن حالت پرواز) و دوباره تلاش کنید.</p><button onclick="parent.postMessage({ type: 'NAVIGATE_TO_URL', url: '#/nav/online/news/getSingle/1149635/...'}, '*')">دیدن ویدیو آموزشی</button></div><div class="guide-actions"><button class="action-button back-button" onclick="this.closest('#custom-quota-modal').remove()">بازگشت</button><button class="action-button retry-button" onclick="document.getElementById('run-btn').click(); this.closest('#custom-quota-modal').remove();">تلاش مجدد</button></div></div></div>`;
document.body.insertAdjacentHTML('beforeend', modalHtml);
};
setInterval(() => {
document.querySelectorAll('.toast-body, .error').forEach(el => {
if ((el.innerText || "").toLowerCase().includes('quota')) {
showQuotaModal();
el.style.display = 'none';
}
});
}, 100);
initializeApp();
// این تابع مخصوص گرادیو است تا وقتی خروجی JSON آپدیت شد، UI را آپدیت کند
window.updateUIFromGradio = function(jsonData) {
updateUIForUserStatus(jsonData);
}
});
</script>
<style>
/* --- استایلهای اصلی (مشابه قبل با اضافات جدید) --- */
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;700&display=swap');
body, .gradio-container { font-family: 'Vazirmatn', sans-serif !important; background-color: #f5f7fa !important; color-scheme: light !important; }
#col-container { direction: rtl; text-align: right; max-width: 980px; margin: 0 auto; padding: 30px; background: #ffffff; border-radius: 24px; box-shadow: 0 10px 40px -10px rgba(0,0,0,0.08); }
#main-title h1 { text-align: center; font-size: 2.4em !important; font-weight: 800; background: -webkit-linear-gradient(45deg, #2563eb, #1e40af); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
#main-description { text-align: center; font-size: 1.15em; color: #4b5563 !important; margin-bottom: 25px; line-height: 1.6; }
footer, .flagging { display: none !important; }
/* --- استایلهای جدید برای بخش وضعیت کاربر --- */
#user-status-section {
display: none; /* Initially hidden */
text-align: center;
margin-bottom: 25px;
padding: 15px;
background-color: #f8f9fa;
border-radius: 14px;
border: 1px solid #e9ecef;
}
#subscription-badge {
display: inline-block;
padding: 6px 16px;
border-radius: 20px;
font-size: 0.9em;
font-weight: 700;
margin-bottom: 10px;
}
#subscription-badge.free-badge { background: linear-gradient(45deg, #6c757d, #495057); color: white; }
#subscription-badge.paid-badge { background: linear-gradient(45deg, #198754, #157347); color: white; }
#credit-status-text {
font-size: 1em;
color: #495057;
margin-bottom: 10px;
}
#credit-status-text strong { color: #0d6efd; }
#countdown-timer {
font-size: 0.9em;
color: #6c757d;
}
#countdown-timer span { font-weight: bold; font-variant-numeric: tabular-nums; }
#upgrade-btn {
display: none; /* Initially hidden */
margin-top: 15px;
padding: 10px 20px;
font-family: 'Vazirmatn', sans-serif;
font-weight: 700;
font-size: 1em;
color: white;
background: linear-gradient(135deg, #ffc107, #ff9800);
border: none;
border-radius: 12px;
cursor: pointer;
transition: all 0.2s ease;
box-shadow: 0 4px 10px rgba(255, 193, 7, 0.3);
}
#upgrade-btn:hover { transform: translateY(-2px); box-shadow: 0 6px 15px rgba(255, 193, 7, 0.4); }
.primary-btn:disabled {
background: #adb5bd !important;
cursor: not-allowed;
box-shadow: none !important;
transform: none !important;
}
/* --- بقیه استایلها (بدون تغییر) --- */
.primary-btn { background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important; border:none !important; color:white !important; font-weight:700 !important; font-size:1.1em !important; padding:14px 28px !important; border-radius:14px !important; box-shadow:0 4px 15px rgba(16,185,129,0.3) !important; transition:all 0.3s ease !important; cursor:pointer !important; width:100%; margin-top:15px; }
.primary-btn:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(16,185,129,0.45) !important; }
.ip-reset-guide-container { direction: rtl; ... } /* Styles for quota modal */
</style>
"""
# استفاده از 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("""
<div id="user-status-section">
<div id="subscription-badge">...</div>
<p id="credit-status-text">در حال بررسی وضعیت حساب...</p>
<div id="countdown-timer" style="display: none;">
زمان تا شارژ مجدد اعتبار: <span></span>
</div>
<button id="upgrade-btn">⭐️ ارتقا به نسخه کامل و نامحدود</button>
</div>
""")
# --- بخش جدید: کامپوننتهای مخفی برای ارتباط 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) |