Opera8 commited on
Commit
2f01800
·
verified ·
1 Parent(s): bc72ac7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +277 -426
app.py CHANGED
@@ -4,6 +4,9 @@ import numpy as np
4
  import spaces
5
  import torch
6
  import random
 
 
 
7
  from PIL import Image, ImageFilter
8
  from typing import Iterable
9
  from gradio.themes import Soft
@@ -11,6 +14,71 @@ from gradio.themes.utils import colors, fonts, sizes
11
  from deep_translator import GoogleTranslator
12
  from transformers import pipeline
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  # --- تعریف تم ---
15
  colors.steel_blue = colors.Color(
16
  name="steel_blue",
@@ -44,22 +112,20 @@ def is_image_nsfw(image):
44
  # بررسی با مدل اول
45
  results1 = safety_classifier_1(image)
46
  for result in results1:
47
- if result['label'] == 'nsfw' and result['score'] > 0.5: # حساسیت متوسط
48
  print(f"Safety Check 1 Failed: {result['score']}")
49
  return True
50
 
51
- # بررسی با مدل دوم (سخت‌گیرانه برای موارد نیمه برهنه)
52
  results2 = safety_classifier_2(image)
53
  for result in results2:
54
  label = result['label'].lower()
55
  score = result['score']
56
 
57
- # اگر مدل تشخیص دهد nsfw است (حتی با احتمال ۳۰ درصد)
58
  if label == 'nsfw' and score > 0.3:
59
  print(f"Safety Check 2 (NSFW) Failed: {score}")
60
  return True
61
 
62
- # اگر مدل تشخیص دهد تصویر سکسی یا نیمه برهنه است
63
  if label in ['sexy', 'porn', 'hentai'] and score > 0.4:
64
  print(f"Safety Check 2 (Partial) Failed: {label} - {score}")
65
  return True
@@ -67,11 +133,9 @@ def is_image_nsfw(image):
67
  return False
68
  except Exception as e:
69
  print(f"Safety check error: {e}")
70
- # در صورت خطا در سیستم امنیتی، جانب احتیاط رعایت شود
71
  return True
72
 
73
- # --- لیست کلمات ممنوعه (انگلیسی) ---
74
- # این لیست بعد از ترجمه متن کاربر چک می‌شود
75
  BANNED_WORDS = [
76
  "nsfw", "nude", "naked", "sex", "porn", "erotic", "xxx", "18+", "uncensored",
77
  "breast", "nipple", "areola", "cleavage", "topless", "open chest",
@@ -84,11 +148,9 @@ BANNED_WORDS = [
84
  ]
85
 
86
  def check_text_safety(text):
87
- """بررسی متن انگلیسی برای کلمات ممنوعه"""
88
  if not text: return True
89
  text_lower = text.lower()
90
  for word in BANNED_WORDS:
91
- # بررسی کلمه به صورت مستقل یا چسبیده
92
  if word in text_lower:
93
  print(f"Banned word found: {word}")
94
  return False
@@ -104,7 +166,7 @@ def translate_prompt(text):
104
  print(f"Translation Error: {e}")
105
  return text
106
 
107
- # --- بارگذاری مدل اصلی ویرایش تصویر ---
108
  from diffusers import FlowMatchEulerDiscreteScheduler
109
  from qwenimage.pipeline_qwenimage_edit_plus import QwenImageEditPlusPipeline
110
  from qwenimage.transformer_qwenimage import QwenImageTransformer2DModel
@@ -197,6 +259,16 @@ def get_success_html(message):
197
  </div>
198
  """
199
 
 
 
 
 
 
 
 
 
 
 
200
  @spaces.GPU(duration=30)
201
  def infer(
202
  input_image,
@@ -209,17 +281,26 @@ def infer(
209
  aspect_ratio_selection,
210
  custom_width,
211
  custom_height,
 
 
212
  progress=gr.Progress(track_tqdm=True)
213
  ):
214
- # 1. بررسی وجود تصویر
 
 
 
 
 
 
 
215
  if input_image is None:
216
  return None, seed, get_error_html("لطفاً ابتدا یک تصویر بارگذاری کنید.")
217
 
218
- # 2. بررسی امنیتی تصویر ورودی (با دو مدل)
219
  if is_image_nsfw(input_image):
220
  return None, seed, get_error_html("تصویر ورودی دارای محتوای نامناسب است و پردازش نمی‌شود.")
221
 
222
- # 3. ترجمه و بررسی متن
223
  english_prompt = translate_prompt(prompt)
224
  if not check_text_safety(english_prompt):
225
  return None, seed, get_error_html("متن درخواست شامل کلمات غیرمجاز یا غیراخلاقی است.")
@@ -233,8 +314,6 @@ def infer(
233
 
234
  generator = torch.Generator(device=device).manual_seed(seed)
235
 
236
- # 4. تنظیم دستورات منفی (Negative Prompt) سخت‌گیرانه
237
- # این کلمات به هوش مصنوعی می‌گویند که چه چیزهایی نسازد
238
  safety_negative = (
239
  "nsfw, nude, naked, porn, sexual, xxx, breast, nipple, areola, genital, "
240
  "vagina, penis, ass, lingerie, bikini, swimwear, underwear, fetish, "
@@ -269,10 +348,13 @@ def infer(
269
  true_cfg_scale=guidance_scale,
270
  ).images[0]
271
 
272
- # 5. بررسی امنیتی تصویر خروجی (با دو مدل)
273
  if is_image_nsfw(result):
274
  return None, seed, get_error_html("تصویر تولید شده حاوی محتوای نامناسب بود و حذف شد.")
275
 
 
 
 
276
  return result, seed, get_success_html("تصویر با موفقیت ویرایش شد.")
277
 
278
  except Exception as e:
@@ -283,7 +365,8 @@ def infer(
283
 
284
  @spaces.GPU(duration=30)
285
  def infer_example(input_image, prompt, lora_adapter):
286
- res, s, status = infer(input_image, prompt, lora_adapter, 0, True, 1.0, 4, "خودکار (پیش‌فرض)", 1024, 1024)
 
287
  return res, s, status
288
 
289
  # --- جاوااسکریپت برای دکمه دانلود ---
@@ -306,11 +389,85 @@ async (image) => {
306
  }
307
  """
308
 
309
- # --- جاوااسکریپت سراسری (استراتژی موبایل + بستن خودکار ۱۰ ثانیه) ---
310
  js_global_content = """
311
  <script>
312
  document.addEventListener('DOMContentLoaded', () => {
313
- // 1. Force Light Mode
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  const forceLight = () => {
315
  const body = document.querySelector('body');
316
  if (body) {
@@ -323,22 +480,24 @@ document.addEventListener('DOMContentLoaded', () => {
323
  forceLight();
324
  setInterval(forceLight, 1000);
325
 
326
- // 2. RETRY FUNCTION
 
 
327
  window.retryGeneration = function() {
328
  const modal = document.getElementById('custom-quota-modal');
329
  if (modal) modal.remove();
330
-
331
  const runBtn = document.getElementById('run-btn');
332
  if(runBtn) runBtn.click();
333
  };
334
 
335
- // Close function
336
  window.closeErrorModal = function() {
337
  const modal = document.getElementById('custom-quota-modal');
338
  if (modal) modal.remove();
339
  };
340
 
341
- // 3. SHOW MODAL FUNCTION
 
 
342
  const showQuotaModal = () => {
343
  if (document.getElementById('custom-quota-modal')) return;
344
 
@@ -359,7 +518,6 @@ document.addEventListener('DOMContentLoaded', () => {
359
  <p>نیازمند تغییر نقطه دستیابی</p>
360
  </div>
361
  </div>
362
-
363
  <div class="guide-content">
364
  <div class="info-card">
365
  <div class="info-card-header">
@@ -368,15 +526,13 @@ document.addEventListener('DOMContentLoaded', () => {
368
  </div>
369
  <p>طبق ویدیو آموزشی پایین بین نقطه دستیابی جابجا شوید تلاش مجدد بزنید تا تصاویر مجدداً تولید بشه.</p>
370
  </div>
371
-
372
  <div class="summary-section">
373
  <div class="summary-header">
374
  <svg class="summary-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" fill="#56ab2f" opacity="0.2"></circle><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z" stroke="#56ab2f" stroke-width="2"></path><path d="M9 12l2 2 4-4" stroke="#56ab2f" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
375
  <span class="summary-title">خلاصه راهنما</span>
376
  </div>
377
- <div class="summary-text">هربار که این صفحه را مشاهده کردید: از اینترنت سیم‌کارت استفاده کنید، VPN را خاموش کرده و طبق ویدیو آموزشی پایین نقطه دستیابی رو تغییر دهید. «تلاش مجدد» کلیک کنید. با این روش ساده می‌توانید به صورت نامحدود تصویر بسازید! ☘️</div>
378
  </div>
379
-
380
  <div class="video-button-container">
381
  <button onclick="parent.postMessage({ type: 'NAVIGATE_TO_URL', url: '#/nav/online/news/getSingle/1149635/eyJpdiI6IjhHVGhPQWJwb3E0cjRXbnFWTW5BaUE9PSIsInZhbHVlIjoiS1V0dTdvT21wbXAwSXZaK1RCTG1pVXZqdlFJa1hXV1RKa2FLem9zU3pXMjd5MmlVOGc2YWY0NVdNR3h3Smp1aSIsIm1hYyI6IjY1NTA5ZDYzMjAzMTJhMGQyMWQ4NjA4ZDgyNGZjZDVlY2MyNjdiMjA2NWYzOWRjY2M4ZmVjYWRlMWNlMWQ3ODEiLCJ0YWciOiIifQ==/21135210' }, '*')" class="elegant-video-button">
382
  <svg class="elegant-video-button-icon" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 24 24"><path d="M8 5v14l11-7z"></path></svg>
@@ -384,7 +540,6 @@ document.addEventListener('DOMContentLoaded', () => {
384
  </button>
385
  </div>
386
  </div>
387
-
388
  <div class="guide-actions">
389
  <button class="action-button back-button" onclick="window.closeErrorModal()">
390
  <svg class="action-button-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
@@ -398,30 +553,22 @@ document.addEventListener('DOMContentLoaded', () => {
398
  </div>
399
  </div>
400
  `;
401
-
402
  document.body.insertAdjacentHTML('beforeend', modalHtml);
403
-
404
- // Auto close after 10 seconds
405
- setTimeout(() => {
406
- window.closeErrorModal();
407
- }, 10000);
408
  };
409
 
410
- // 4. SCANNER
 
 
411
  setInterval(() => {
412
  const potentialErrors = document.querySelectorAll('.toast-body, .error, .toast-wrap, .eta-bar, div[class*="error"]');
413
-
414
  potentialErrors.forEach(el => {
415
  const text = el.innerText || "";
416
  if (text.toLowerCase().includes('quota') || text.toLowerCase().includes('exceeded')) {
417
-
418
  showQuotaModal();
419
-
420
- // Immediately hide the Gradio error
421
  el.style.display = 'none';
422
  el.style.opacity = '0';
423
  el.innerText = '';
424
-
425
  const parentWrap = el.closest('.toast-wrap');
426
  if(parentWrap) parentWrap.style.display = 'none';
427
  }
@@ -431,7 +578,7 @@ document.addEventListener('DOMContentLoaded', () => {
431
  </script>
432
  """
433
 
434
- # --- CSS Updated (Larger & Auto Scroll) ---
435
  css_code = """
436
  <style>
437
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;700&display=swap');
@@ -439,441 +586,145 @@ css_code = """
439
  :root, .dark, body, .gradio-container {
440
  --body-background-fill: #f5f7fa !important;
441
  --body-text-color: #1f2937 !important;
442
- --background-fill-primary: #ffffff !important;
443
- --background-fill-secondary: #f3f4f6 !important;
444
- --border-color-primary: #e5e7eb !important;
445
- --block-background-fill: #ffffff !important;
446
- --block-label-text-color: #374151 !important;
447
- --block-title-text-color: #111827 !important;
448
- --input-background-fill: #ffffff !important;
449
- color-scheme: light !important;
450
- }
451
-
452
- /* --- IP Reset Guide CSS --- */
453
- :root {
454
- --guide-bg: rgba(255, 255, 255, 0.98);
455
- --guide-border: rgba(102, 126, 234, 0.2);
456
- --guide-text-title: #2d3748;
457
- --guide-text-body: #4a5568;
458
- --guide-accent: #667eea;
459
- --primary-gradient-guide: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
460
- --success-gradient-guide: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);
461
- --radius-md-guide: 12px;
462
- --radius-lg-guide: 16px;
463
- --shadow-sm: 0 1px 2px 0 rgba(26, 32, 44, 0.03);
464
- --shadow-md: 0 4px 6px -1px rgba(26, 32, 44, 0.05), 0 2px 4px -2px rgba(26, 32, 44, 0.04);
465
- --shadow-xl: 0 20px 25px -5px rgba(26, 32, 44, 0.07), 0 8px 10px -6px rgba(26, 32, 44, 0.05);
466
- }
467
-
468
- @keyframes float {
469
- 0%, 100% { transform: translateY(0px); }
470
- 50% { transform: translateY(-10px); }
471
- }
472
- @keyframes slideInUp {
473
- from { opacity: 0; transform: translateY(30px); }
474
- to { opacity: 1; transform: translateY(0); }
475
- }
476
-
477
- .ip-reset-guide-container {
478
- text-align: right;
479
- direction: rtl;
480
- background: var(--guide-bg);
481
- backdrop-filter: blur(10px);
482
- padding: 20px; /* Increased Padding */
483
- border-radius: var(--radius-lg-guide);
484
- box-shadow: var(--shadow-xl);
485
- border: 1px solid var(--guide-border);
486
- animation: slideInUp 0.6s cubic-bezier(0.4, 0, 0.2, 1) both;
487
- width: 90%;
488
- max-width: 420px; /* Increased width slightly */
489
- max-height: 90vh; /* Prevent overflow on small screens */
490
- overflow-y: auto; /* Enable scroll if needed */
491
- position: relative;
492
- box-sizing: border-box;
493
- font-family: 'Vazirmatn', sans-serif !important;
494
- }
495
- .ip-reset-guide-container::before {
496
- content: ''; position: absolute; top: 0; left: 0; right: 0; height: 4px; background: var(--primary-gradient-guide);
497
- }
498
- .guide-header { display: flex; align-items: center; margin-bottom: 15px; }
499
- .guide-header-icon { width: 45px; height: 45px; margin-left: 15px; animation: float 3s ease-in-out infinite; flex-shrink: 0; }
500
- .guide-header h2 { font-size: 1.2rem; color: var(--guide-text-title); font-weight: 700; margin: 0; }
501
- .guide-header p { color: var(--guide-text-body); font-size: 0.8rem; margin-top: 3px; margin-bottom: 0; }
502
-
503
- .guide-content { font-size: 0.9rem; color: var(--guide-text-body); line-height: 1.6; }
504
-
505
- .info-card { background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%); border: 1px solid rgba(102, 126, 234, 0.2); border-radius: var(--radius-md-guide); padding: 12px; margin: 12px 0; position: relative; overflow: hidden; }
506
- .info-card p { font-size: 0.85rem; line-height: 1.6; margin: 0; }
507
- .info-card::before { content: ''; position: absolute; top: 0; right: 0; width: 3px; height: 100%; background: var(--primary-gradient-guide); }
508
- .info-card-header { display: flex; align-items: center; margin-bottom: 8px; }
509
- .info-card-icon { width: 18px; height: 18px; margin-left: 8px; }
510
- .info-card-title { font-weight: 600; color: var(--guide-text-title); font-size: 0.95rem; }
511
-
512
- .summary-section { margin-top: 12px; padding: 12px; border-radius: var(--radius-md-guide); background: linear-gradient(135deg, #56ab2f15 0%, #a8e06315 100%); border: 1px solid rgba(86, 171, 47, 0.2); position: relative; overflow: hidden; }
513
- .summary-section::before { content: ''; position: absolute; top: 0; right: 0; width: 3px; height: 100%; background: var(--success-gradient-guide); }
514
- .summary-header { display: flex; align-items: center; margin-bottom: 8px; }
515
- .summary-icon { width: 18px; height: 18px; margin-left: 8px; }
516
- .summary-title { font-weight: 600; color: #2f5a33; font-size: 0.95rem; }
517
- .summary-text { color: #2f5a33; font-size: 0.85rem; line-height: 1.6; }
518
-
519
- /* Tutorial Button */
520
- .video-button-container { text-align: center; margin: 20px 0 15px 0; width: 100%; }
521
- .elegant-video-button {
522
- display: inline-flex !important;
523
- align-items: center;
524
- justify-content: center;
525
- padding: 10px 20px !important;
526
- background-color: #fff !important;
527
- color: var(--guide-accent) !important;
528
- border: 1px solid #e2e8f0 !important;
529
- text-decoration: none;
530
- border-radius: 50px !important;
531
- font-weight: 600 !important;
532
- font-size: 0.9rem !important;
533
- cursor: pointer !important;
534
- font-family: inherit;
535
- transition: all 0.3s ease !important;
536
- box-shadow: 0 2px 10px rgba(0,0,0,0.05) !important;
537
- width: auto !important;
538
- }
539
- .elegant-video-button:hover {
540
- background: var(--primary-gradient-guide) !important;
541
- color: white !important;
542
- border-color: transparent !important;
543
- transform: translateY(-2px);
544
- box-shadow: 0 6px 16px rgba(102, 126, 234, 0.3) !important;
545
- }
546
- .elegant-video-button-icon { width: 18px; height: 18px; margin-left: 8px; fill: currentColor; }
547
-
548
- /* Action Buttons */
549
- .guide-actions {
550
- display: flex !important;
551
- gap: 12px !important;
552
- margin-top: 20px;
553
- padding-top: 20px;
554
- border-top: 1px solid #e2e8f0;
555
- width: 100% !important;
556
- }
557
- .action-button {
558
- padding: 12px 15px !important;
559
- border: none !important;
560
- border-radius: 12px !important;
561
- font-size: 0.95rem !important;
562
- font-weight: 600 !important;
563
- cursor: pointer !important;
564
- flex: 1 !important;
565
- transition: all 0.3s ease !important;
566
- display: flex !important;
567
- align-items: center;
568
- justify-content: center;
569
- font-family: inherit;
570
- height: 48px !important;
571
- }
572
- .action-button-icon { width: 20px; height: 20px; margin-right: 0; margin-left: 8px; }
573
-
574
- .back-button {
575
- background: white !important;
576
- color: var(--guide-text-body) !important;
577
- border: 2px solid #e2e8f0 !important;
578
- }
579
- .back-button:hover {
580
- background: #f7fafc !important;
581
- border-color: var(--guide-accent) !important;
582
- transform: translateY(-2px);
583
- box-shadow: var(--shadow-md) !important;
584
- }
585
-
586
- .retry-button {
587
- background: var(--primary-gradient-guide) !important;
588
- color: white !important;
589
- box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3) !important;
590
- }
591
- .retry-button:hover {
592
- transform: translateY(-2px);
593
- box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important;
594
- }
595
-
596
- /* --- Main App CSS --- */
597
- body {
598
  font-family: 'Vazirmatn', sans-serif !important;
599
- background-color: #f5f7fa !important;
600
- margin: 0;
601
- padding: 10px;
602
  }
603
 
604
- #col-container {
605
- margin: 0 auto;
606
- max-width: 980px;
607
- direction: rtl;
608
- text-align: right;
609
- padding: 30px;
610
- background: #ffffff !important;
611
- border-radius: 24px;
612
- box-shadow: 0 10px 40px -10px rgba(0,0,0,0.08);
613
- border: 1px solid rgba(255,255,255,0.8);
 
 
 
614
  }
615
 
616
- #main-title h1 {
617
- font-size: 2.4em !important;
618
- text-align: center;
619
- color: #1a202c !important;
620
- margin-bottom: 15px;
621
- font-weight: 800;
622
- background: -webkit-linear-gradient(45deg, #2563eb, #1e40af);
623
- -webkit-background-clip: text;
624
- -webkit-text-fill-color: transparent;
625
  }
626
 
627
- #main-description {
628
- text-align: center;
629
- font-size: 1.15em;
630
- color: #4b5563 !important;
631
- margin-bottom: 40px;
632
- line-height: 1.6;
633
  }
634
 
635
- .gr-input-label, span.label-wrap, label span {
636
- font-weight: 700 !important;
637
- color: #374151 !important;
638
- font-size: 0.95em !important;
639
- margin-bottom: 8px !important;
640
  }
641
 
642
- textarea, input[type="text"] {
643
- border: 2px solid #e2e8f0 !important;
644
- border-radius: 12px !important;
645
- background-color: #ffffff !important;
646
- color: #111827 !important;
647
- padding: 12px !important;
648
- transition: all 0.3s ease;
649
  font-family: 'Vazirmatn', sans-serif !important;
650
  }
651
-
652
- textarea:focus, input[type="text"]:focus {
653
- border-color: #3b82f6 !important;
654
- box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1) !important;
655
- outline: none;
656
- }
657
-
658
- .gr-dropdown {
659
- background: #ffffff !important;
660
- border-radius: 12px !important;
661
- }
662
-
663
- .primary-btn, button.primary {
664
- background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
665
- border: none !important;
666
- color: white !important;
667
- font-weight: 700 !important;
668
- font-size: 1.1em !important;
669
- padding: 14px 28px !important;
670
- border-radius: 14px !important;
671
- box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3) !important;
672
- transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
673
- cursor: pointer !important;
674
- width: 100%;
675
- margin-top: 15px;
676
- }
677
-
678
- .primary-btn:hover, button.primary:hover {
679
- transform: translateY(-2px);
680
- box-shadow: 0 8px 25px rgba(16, 185, 129, 0.45) !important;
681
- }
682
-
683
- .primary-btn:active, button.primary:active {
684
- transform: translateY(1px);
685
- }
686
-
687
- #download-btn {
688
- background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%) !important;
689
- box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3) !important;
690
- }
691
- #download-btn:hover {
692
- box-shadow: 0 8px 25px rgba(59, 130, 246, 0.45) !important;
693
- }
694
-
695
- .gradio-container .prose table,
696
- .gradio-container table {
697
- background-color: #ffffff !important;
698
- color: #111827 !important;
699
- border: 1px solid #e5e7eb !important;
700
- border-radius: 12px !important;
701
- overflow: hidden !important;
702
- width: 100% !important;
703
- margin-top: 20px !important;
704
- }
705
-
706
- .gradio-container thead th {
707
- background-color: #f3f4f6 !important;
708
- color: #374151 !important;
709
- font-weight: 700 !important;
710
- border-bottom: 2px solid #e5e7eb !important;
711
- padding: 12px !important;
712
- text-align: right !important;
713
- }
714
-
715
- .gradio-container tbody tr {
716
- background-color: #ffffff !important;
717
- border-bottom: 1px solid #f3f4f6 !important;
718
- }
719
-
720
- .gradio-container tbody tr:hover {
721
- background-color: #f9fafb !important;
722
- }
723
-
724
- .gradio-container tbody td {
725
- background-color: #ffffff !important;
726
- color: #374151 !important;
727
- padding: 10px !important;
728
- }
729
-
730
- .gradio-container tbody td span,
731
- .gradio-container tbody td p {
732
- color: #374151 !important;
733
- }
734
-
735
  footer { display: none !important; }
736
- .flagging { display: none !important; }
737
-
738
- /* Force toast transparency */
739
- .toast-body {
740
- direction: rtl !important;
741
- text-align: right !important;
742
- background: transparent !important;
743
- box-shadow: none !important;
744
- border: none !important;
745
- padding: 0 !important;
746
- max-width: 100% !important;
747
- width: auto !important;
748
- }
749
- .toast-wrap {
750
- background: transparent !important;
751
- border: none !important;
752
- box-shadow: none !important;
753
- }
754
-
755
- @media (prefers-color-scheme: dark) {
756
- body, .gradio-container, .prose, table, tr, td, th {
757
- background-color: #ffffff !important;
758
- color: #333333 !important;
759
- }
760
- }
761
  </style>
762
  """
763
 
764
- # ادغام CSS و JS
765
  combined_html = css_code + js_global_content
766
 
767
- # استفاده از gr.Blocks
768
  with gr.Blocks() as demo:
769
- # تزریق کدها به عنوان HTML
770
  gr.HTML(combined_html)
771
 
772
  with gr.Column(elem_id="col-container"):
773
  gr.Markdown("# **ویرایشگر هوشمند آلفا**", elem_id="main-title")
774
- gr.Markdown(
775
- "با هوش مصنوعی آلفا تصاویر تونو به مدل های مختلف ویرایش کنید.",
776
- elem_id="main-description"
777
- )
 
 
 
 
778
 
779
  with gr.Row(equal_height=True):
780
  with gr.Column():
781
  input_image = gr.Image(label="بارگذاری تصویر", type="pil", height=320)
782
-
783
- prompt = gr.Text(
784
- label="دستور ویرایش (به فارسی)",
785
- show_label=True,
786
- placeholder="مثال: تصویر را به سبک انیمه تبدیل کن...",
787
- rtl=True,
788
- lines=3
789
- )
790
-
791
  status_box = gr.HTML(label="وضعیت")
792
-
793
- # IMPORTANT: Added elem_id="run-btn" here for JS targeting
794
- run_button = gr.Button("✨ شروع پردازش و ساخت تصویر", variant="primary", elem_classes="primary-btn", elem_id="run-btn")
795
 
796
  with gr.Column():
797
  output_image = gr.Image(label="تصویر نهایی", interactive=False, format="png", height=380)
798
-
799
  download_button = gr.Button("📥 دانلود و ذخیره تصویر", variant="secondary", elem_id="download-btn", elem_classes="primary-btn")
800
 
801
  with gr.Row():
802
- lora_adapter = gr.Dropdown(
803
- label="انتخاب سبک ویرایش (LoRA)",
804
- choices=list(LORA_MAPPING.keys()),
805
- value="تبدیل عکس به انیمه"
806
- )
807
 
808
- with gr.Accordion("تنظیمات پیشرفته", open=False, visible=True):
809
- aspect_ratio_selection = gr.Dropdown(
810
- label="ابعاد تصویر خروجی",
811
- choices=ASPECT_RATIOS_LIST,
812
- value="خودکار (پیش‌فرض)",
813
- interactive=True
814
- )
815
-
816
  with gr.Row(visible=False) as custom_dims_row:
817
- custom_width = gr.Slider(
818
- label="عرض دلخواه (Width)",
819
- minimum=256, maximum=2048, step=8, value=1024
820
- )
821
- custom_height = gr.Slider(
822
- label="ارتفاع دلخواه (Height)",
823
- minimum=256, maximum=2048, step=8, value=1024
824
- )
825
-
826
- seed = gr.Slider(label="دانه تصادفی (Seed)", minimum=0, maximum=MAX_SEED, step=1, value=0)
827
- randomize_seed = gr.Checkbox(label="استفاده از Seed تصادفی", value=True)
828
- guidance_scale = gr.Slider(label="میزان وفاداری به متن (Guidance Scale)", minimum=1.0, maximum=10.0, step=0.1, value=1.0)
829
- steps = gr.Slider(label="تعداد مراحل پردازش (Steps)", minimum=1, maximum=50, step=1, value=4)
830
 
831
- # اصلاح تابع نمایش ردیف اسلایدرها
832
  def toggle_row(choice):
833
- if choice == "شخصی‌سازی (Custom)":
834
- return gr.update(visible=True)
835
- return gr.update(visible=False)
836
-
837
- aspect_ratio_selection.change(
838
- fn=toggle_row,
839
- inputs=aspect_ratio_selection,
840
- outputs=custom_dims_row
 
 
 
 
 
 
841
  )
842
 
 
 
 
843
  gr.Examples(
844
  examples=[
845
  ["examples/1.jpg", "تبدیل به انیمه کن.", "تبدیل عکس به انیمه"],
846
- ["examples/5.jpg", "سایه‌ها را حذف کن و نورپردازی نرم به تصویر بده.", "اصلاح نور و سایه"],
847
- ["examples/4.jpg", "از فیلتر ساعت طلایی با پخش نور ملایم استفاده کن.", "نورپردازی مجدد (Relight)"],
848
- ["examples/2.jpeg", "دوربین را ۴۵ درجه به سمت چپ بچرخان.", "تغییر زاویه دید"],
849
- ["examples/7.jpg", "منبع نور را از سمت راست عقب قرار بده.", "نورپردازی چند زاویه‌ای"],
850
- ["examples/10.jpeg", "کیفیت تصویر را افزایش بده (Upscale).", "افزایش کیفیت (Upscale)"],
851
- ["examples/7.jpg", "منبع نور را از پایین بتابان.", "نورپردازی چند زاویه‌ای"],
852
- ["examples/2.jpeg", "زاویه دوربین را به نمای بالا گوشه راست تغییر بده.", "تغییر زاویه دید"],
853
- ["examples/9.jpg", "دوربین کمی به جلو حرکت می‌کند در حالی که نور خورشید از میان ابرها می‌تابد و درخششی نرم اطراف شبح شخصیت در مه ایجاد می‌کند. سبک سینمایی واقعی.", "صحنه بعدی (سینمایی)"],
854
- ["examples/8.jpg", "جزئیات پوست سوژه را برجسته‌تر و طبیعی‌تر کن.", "روتوش پوست"],
855
- ["examples/6.jpg", "دوربین را به نمای پایین به بالا تغییر بده.", "تغییر زاویه دید"],
856
  ],
857
  inputs=[input_image, prompt, lora_adapter],
858
  outputs=[output_image, seed, status_box],
859
  fn=infer_example,
860
  cache_examples=False,
861
- label="نمونه‌ها (برای تست کلیک کنید)"
862
  )
863
 
864
- run_button.click(
865
- fn=infer,
866
- inputs=[input_image, prompt, lora_adapter, seed, randomize_seed, guidance_scale, steps, aspect_ratio_selection, custom_width, custom_height],
867
- outputs=[output_image, seed, status_box],
868
- api_name="predict"
869
- )
870
-
871
- download_button.click(
872
- fn=None,
873
- inputs=[output_image],
874
- outputs=None,
875
- js=js_download_func
876
- )
877
-
878
  if __name__ == "__main__":
879
  demo.queue(max_size=30).launch(show_error=True)
 
4
  import spaces
5
  import torch
6
  import random
7
+ import sqlite3
8
+ import json
9
+ from datetime import datetime
10
  from PIL import Image, ImageFilter
11
  from typing import Iterable
12
  from gradio.themes import Soft
 
14
  from deep_translator import GoogleTranslator
15
  from transformers import pipeline
16
 
17
+ # --- تنظیمات دیتابیس برای مدیریت کردیت کاربران ---
18
+ DB_NAME = "user_limits.db"
19
+
20
+ def init_db():
21
+ """ایجاد جدول برای ذخیره تعداد استفاده کاربران"""
22
+ conn = sqlite3.connect(DB_NAME)
23
+ c = conn.cursor()
24
+ c.execute('''
25
+ CREATE TABLE IF NOT EXISTS usage_logs (
26
+ user_id TEXT,
27
+ date TEXT,
28
+ count INTEGER,
29
+ PRIMARY KEY (user_id, date)
30
+ )
31
+ ''')
32
+ conn.commit()
33
+ conn.close()
34
+
35
+ init_db()
36
+
37
+ def check_and_update_quota(user_id, is_premium):
38
+ """
39
+ بررسی مجاز بودن کاربر برای تولید تصویر
40
+ کاربران پریمیوم: همیشه مجاز
41
+ کاربران رایگان: حداکثر 5 تصویر در روز
42
+ """
43
+ if not user_id:
44
+ return True, "Guest" # اگر یوزر آیدی نبود، سختگیری نمی‌کنیم (یا می‌توان محدود کرد)
45
+
46
+ if is_premium:
47
+ return True, "نامحدود"
48
+
49
+ today = datetime.now().strftime("%Y-%m-%d")
50
+
51
+ conn = sqlite3.connect(DB_NAME)
52
+ c = conn.cursor()
53
+
54
+ c.execute("SELECT count FROM usage_logs WHERE user_id = ? AND date = ?", (user_id, today))
55
+ result = c.fetchone()
56
+
57
+ current_count = result[0] if result else 0
58
+ limit = 5
59
+
60
+ conn.close()
61
+
62
+ if current_count >= limit:
63
+ return False, f"0 از {limit}"
64
+
65
+ return True, f"{limit - current_count} از {limit}"
66
+
67
+ def increment_usage(user_id, is_premium):
68
+ """افزایش شمارنده استفاده کاربر پس از تولید موفق"""
69
+ if not user_id or is_premium:
70
+ return
71
+
72
+ today = datetime.now().strftime("%Y-%m-%d")
73
+ conn = sqlite3.connect(DB_NAME)
74
+ c = conn.cursor()
75
+
76
+ c.execute("INSERT OR IGNORE INTO usage_logs (user_id, date, count) VALUES (?, ?, 0)", (user_id, today))
77
+ c.execute("UPDATE usage_logs SET count = count + 1 WHERE user_id = ? AND date = ?", (user_id, today))
78
+
79
+ conn.commit()
80
+ conn.close()
81
+
82
  # --- تعریف تم ---
83
  colors.steel_blue = colors.Color(
84
  name="steel_blue",
 
112
  # بررسی با مدل اول
113
  results1 = safety_classifier_1(image)
114
  for result in results1:
115
+ if result['label'] == 'nsfw' and result['score'] > 0.5:
116
  print(f"Safety Check 1 Failed: {result['score']}")
117
  return True
118
 
119
+ # بررسی با مدل دوم
120
  results2 = safety_classifier_2(image)
121
  for result in results2:
122
  label = result['label'].lower()
123
  score = result['score']
124
 
 
125
  if label == 'nsfw' and score > 0.3:
126
  print(f"Safety Check 2 (NSFW) Failed: {score}")
127
  return True
128
 
 
129
  if label in ['sexy', 'porn', 'hentai'] and score > 0.4:
130
  print(f"Safety Check 2 (Partial) Failed: {label} - {score}")
131
  return True
 
133
  return False
134
  except Exception as e:
135
  print(f"Safety check error: {e}")
 
136
  return True
137
 
138
+ # --- لیست کلمات ممنوعه ---
 
139
  BANNED_WORDS = [
140
  "nsfw", "nude", "naked", "sex", "porn", "erotic", "xxx", "18+", "uncensored",
141
  "breast", "nipple", "areola", "cleavage", "topless", "open chest",
 
148
  ]
149
 
150
  def check_text_safety(text):
 
151
  if not text: return True
152
  text_lower = text.lower()
153
  for word in BANNED_WORDS:
 
154
  if word in text_lower:
155
  print(f"Banned word found: {word}")
156
  return False
 
166
  print(f"Translation Error: {e}")
167
  return text
168
 
169
+ # --- بارگذاری مدل اصلی ---
170
  from diffusers import FlowMatchEulerDiscreteScheduler
171
  from qwenimage.pipeline_qwenimage_edit_plus import QwenImageEditPlusPipeline
172
  from qwenimage.transformer_qwenimage import QwenImageTransformer2DModel
 
259
  </div>
260
  """
261
 
262
+ def get_limit_error_html():
263
+ return f"""
264
+ <div style="background-color: #fff3cd; border: 1px solid #ffc107; color: #856404; padding: 16px; border-radius: 12px; text-align: center; margin-bottom: 15px; direction: rtl;">
265
+ <h3 style="margin: 0 0 10px 0;">🚫 محدودیت اعتبار روزانه</h3>
266
+ <p style="margin: 0;">شما از سهمیه ۵ تصویر رایگان امروز خود استفاده کرده‌اید.</p>
267
+ <p style="margin: 8px 0 0 0; font-size: 0.9em;">برای استفاده نامحدود، حساب خود را به نسخه ویژه ارتقا دهید.</p>
268
+ <button onclick="window.parent.postMessage({{type: 'NAVIGATE_TO_PREMIUM'}}, '*')" style="margin-top: 12px; background: linear-gradient(90deg, #FFD700, #FFA500); border: none; padding: 8px 16px; border-radius: 20px; color: black; font-weight: bold; cursor: pointer;">ارتقا به نسخه ویژه ⭐️</button>
269
+ </div>
270
+ """
271
+
272
  @spaces.GPU(duration=30)
273
  def infer(
274
  input_image,
 
281
  aspect_ratio_selection,
282
  custom_width,
283
  custom_height,
284
+ user_id_hidden, # دریافت شناسه کاربر از فرانت
285
+ is_premium_hidden, # دریافت وضعیت پریمیوم از فرانت
286
  progress=gr.Progress(track_tqdm=True)
287
  ):
288
+ # --- بررسی اعتبار کاربر ---
289
+ is_premium = str(is_premium_hidden).lower() == "true"
290
+ allowed, limit_msg = check_and_update_quota(user_id_hidden, is_premium)
291
+
292
+ if not allowed:
293
+ return None, seed, get_limit_error_html()
294
+
295
+ # --- بررسی وجود تصویر ---
296
  if input_image is None:
297
  return None, seed, get_error_html("لطفاً ابتدا یک تصویر بارگذاری کنید.")
298
 
299
+ # --- بررسی امنیتی ورودی ---
300
  if is_image_nsfw(input_image):
301
  return None, seed, get_error_html("تصویر ورودی دارای محتوای نامناسب است و پردازش نمی‌شود.")
302
 
303
+ # --- ترجمه و بررسی متن ---
304
  english_prompt = translate_prompt(prompt)
305
  if not check_text_safety(english_prompt):
306
  return None, seed, get_error_html("متن درخواست شامل کلمات غیرمجاز یا غیراخلاقی است.")
 
314
 
315
  generator = torch.Generator(device=device).manual_seed(seed)
316
 
 
 
317
  safety_negative = (
318
  "nsfw, nude, naked, porn, sexual, xxx, breast, nipple, areola, genital, "
319
  "vagina, penis, ass, lingerie, bikini, swimwear, underwear, fetish, "
 
348
  true_cfg_scale=guidance_scale,
349
  ).images[0]
350
 
351
+ # --- بررسی امنیتی خروجی ---
352
  if is_image_nsfw(result):
353
  return None, seed, get_error_html("تصویر تولید شده حاوی محتوای نامناسب بود و حذف شد.")
354
 
355
+ # --- کسر اعتبار (فقط برای کاربران رایگان) ---
356
+ increment_usage(user_id_hidden, is_premium)
357
+
358
  return result, seed, get_success_html("تصویر با موفقیت ویرایش شد.")
359
 
360
  except Exception as e:
 
365
 
366
  @spaces.GPU(duration=30)
367
  def infer_example(input_image, prompt, lora_adapter):
368
+ # برای مثال‌ها، آیدی کاربر فرضی و پریمیوم در نظر گرفته می‌شود تا محدودیت اعمال نشود
369
+ res, s, status = infer(input_image, prompt, lora_adapter, 0, True, 1.0, 4, "خودکار (پیش‌فرض)", 1024, 1024, "example_user", "true")
370
  return res, s, status
371
 
372
  # --- جاوااسکریپت برای دکمه دانلود ---
 
389
  }
390
  """
391
 
392
+ # --- جاوااسکریپت سراسری (شناسایی کاربر، پیام رفع محدودیت، دانلود) ---
393
  js_global_content = """
394
  <script>
395
  document.addEventListener('DOMContentLoaded', () => {
396
+ // --------------------------------------------------------
397
+ // 1. User Identification & Credit Logic (PostMessage)
398
+ // --------------------------------------------------------
399
+ const PREMIUM_PAGE_ID = '1149636';
400
+ let userId = "guest_" + Math.random().toString(36).substr(2, 9);
401
+ let isPremium = false;
402
+
403
+ // Listen for response from Parent (Android/Iframe)
404
+ window.addEventListener('message', (event) => {
405
+ if (event.data && event.data.type === 'USER_DATA_RESPONSE') {
406
+ const payload = event.data.payload;
407
+
408
+ if (payload) {
409
+ try {
410
+ const userObj = JSON.parse(payload);
411
+ if (userObj.id) userId = userObj.id;
412
+
413
+ // Check Premium Status
414
+ if (userObj.isLogin && userObj.accessible_pages) {
415
+ const pages = userObj.accessible_pages;
416
+ // Check if premium page ID exists in allowed pages
417
+ if (pages.includes(PREMIUM_PAGE_ID) || pages.includes(parseInt(PREMIUM_PAGE_ID))) {
418
+ isPremium = true;
419
+ }
420
+ }
421
+ } catch (e) {
422
+ console.error("Error parsing user data:", e);
423
+ }
424
+ }
425
+ updateUserStatusUI();
426
+ updateHiddenInputs();
427
+ }
428
+ });
429
+
430
+ // Request User Data on Load
431
+ window.parent.postMessage({ type: 'REQUEST_USER_DATA' }, '*');
432
+
433
+ function updateUserStatusUI() {
434
+ const badge = document.getElementById('user-status-badge');
435
+ if (!badge) return;
436
+
437
+ if (isPremium) {
438
+ badge.className = 'status-badge premium';
439
+ badge.innerHTML = '⭐️ نسخه نامحدود ویژه';
440
+ } else {
441
+ badge.className = 'status-badge free';
442
+ badge.innerHTML = '👤 نسخه رایگان (۵ تصویر در روز)';
443
+ }
444
+ badge.style.display = 'inline-flex';
445
+ }
446
+
447
+ function updateHiddenInputs() {
448
+ // Find hidden textboxes in Gradio (hacky but standard for Gradio)
449
+ // We look for elements with specific IDs assigned in Python
450
+ const idInput = document.querySelector('#hidden_user_id textarea');
451
+ const premiumInput = document.querySelector('#hidden_user_premium textarea');
452
+
453
+ if (idInput) {
454
+ idInput.value = userId;
455
+ idInput.dispatchEvent(new Event('input', { bubbles: true }));
456
+ }
457
+ if (premiumInput) {
458
+ premiumInput.value = isPremium ? "true" : "false";
459
+ premiumInput.dispatchEvent(new Event('input', { bubbles: true }));
460
+ }
461
+ }
462
+
463
+ // Retry finding elements if Gradio hasn't fully loaded them
464
+ setTimeout(updateHiddenInputs, 2000);
465
+ setTimeout(updateHiddenInputs, 5000);
466
+
467
+
468
+ // --------------------------------------------------------
469
+ // 2. Force Light Mode
470
+ // --------------------------------------------------------
471
  const forceLight = () => {
472
  const body = document.querySelector('body');
473
  if (body) {
 
480
  forceLight();
481
  setInterval(forceLight, 1000);
482
 
483
+ // --------------------------------------------------------
484
+ // 3. Retry Functionality
485
+ // --------------------------------------------------------
486
  window.retryGeneration = function() {
487
  const modal = document.getElementById('custom-quota-modal');
488
  if (modal) modal.remove();
 
489
  const runBtn = document.getElementById('run-btn');
490
  if(runBtn) runBtn.click();
491
  };
492
 
 
493
  window.closeErrorModal = function() {
494
  const modal = document.getElementById('custom-quota-modal');
495
  if (modal) modal.remove();
496
  };
497
 
498
+ // --------------------------------------------------------
499
+ // 4. Quota Modal (IP Reset Guide)
500
+ // --------------------------------------------------------
501
  const showQuotaModal = () => {
502
  if (document.getElementById('custom-quota-modal')) return;
503
 
 
518
  <p>نیازمند تغییر نقطه دستیابی</p>
519
  </div>
520
  </div>
 
521
  <div class="guide-content">
522
  <div class="info-card">
523
  <div class="info-card-header">
 
526
  </div>
527
  <p>طبق ویدیو آموزشی پایین بین نقطه دستیابی جابجا شوید تلاش مجدد بزنید تا تصاویر مجدداً تولید بشه.</p>
528
  </div>
 
529
  <div class="summary-section">
530
  <div class="summary-header">
531
  <svg class="summary-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" fill="#56ab2f" opacity="0.2"></circle><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z" stroke="#56ab2f" stroke-width="2"></path><path d="M9 12l2 2 4-4" stroke="#56ab2f" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
532
  <span class="summary-title">خلاصه راهنما</span>
533
  </div>
534
+ <div class="summary-text">هربار که این صفحه را مشاهده کردید: از اینترنت سیم‌کارت استفاده کنید، VPN را خاموش کرده و طبق ویدیو آموزشی پایین نقطه دستیابی رو تغییر دهید. «تلاش مجدد» کلیک کنید.</div>
535
  </div>
 
536
  <div class="video-button-container">
537
  <button onclick="parent.postMessage({ type: 'NAVIGATE_TO_URL', url: '#/nav/online/news/getSingle/1149635/eyJpdiI6IjhHVGhPQWJwb3E0cjRXbnFWTW5BaUE9PSIsInZhbHVlIjoiS1V0dTdvT21wbXAwSXZaK1RCTG1pVXZqdlFJa1hXV1RKa2FLem9zU3pXMjd5MmlVOGc2YWY0NVdNR3h3Smp1aSIsIm1hYyI6IjY1NTA5ZDYzMjAzMTJhMGQyMWQ4NjA4ZDgyNGZjZDVlY2MyNjdiMjA2NWYzOWRjY2M4ZmVjYWRlMWNlMWQ3ODEiLCJ0YWciOiIifQ==/21135210' }, '*')" class="elegant-video-button">
538
  <svg class="elegant-video-button-icon" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 24 24"><path d="M8 5v14l11-7z"></path></svg>
 
540
  </button>
541
  </div>
542
  </div>
 
543
  <div class="guide-actions">
544
  <button class="action-button back-button" onclick="window.closeErrorModal()">
545
  <svg class="action-button-icon" viewbox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
 
553
  </div>
554
  </div>
555
  `;
 
556
  document.body.insertAdjacentHTML('beforeend', modalHtml);
557
+ setTimeout(() => { window.closeErrorModal(); }, 10000);
 
 
 
 
558
  };
559
 
560
+ // --------------------------------------------------------
561
+ // 5. Error Scanner
562
+ // --------------------------------------------------------
563
  setInterval(() => {
564
  const potentialErrors = document.querySelectorAll('.toast-body, .error, .toast-wrap, .eta-bar, div[class*="error"]');
 
565
  potentialErrors.forEach(el => {
566
  const text = el.innerText || "";
567
  if (text.toLowerCase().includes('quota') || text.toLowerCase().includes('exceeded')) {
 
568
  showQuotaModal();
 
 
569
  el.style.display = 'none';
570
  el.style.opacity = '0';
571
  el.innerText = '';
 
572
  const parentWrap = el.closest('.toast-wrap');
573
  if(parentWrap) parentWrap.style.display = 'none';
574
  }
 
578
  </script>
579
  """
580
 
581
+ # --- CSS Updated ---
582
  css_code = """
583
  <style>
584
  @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;700&display=swap');
 
586
  :root, .dark, body, .gradio-container {
587
  --body-background-fill: #f5f7fa !important;
588
  --body-text-color: #1f2937 !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589
  font-family: 'Vazirmatn', sans-serif !important;
 
 
 
590
  }
591
 
592
+ /* User Status Badge CSS */
593
+ .status-badge {
594
+ display: none; /* Initially hidden until JS detects user */
595
+ align-items: center;
596
+ justify-content: center;
597
+ padding: 8px 16px;
598
+ border-radius: 50px;
599
+ font-size: 0.95em;
600
+ font-weight: 700;
601
+ margin: 10px auto 20px auto;
602
+ width: fit-content;
603
+ box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
604
+ animation: fadeInBadge 0.5s ease-out;
605
  }
606
 
607
+ .status-badge.premium {
608
+ background: linear-gradient(135deg, #FFD700 0%, #FDB931 100%);
609
+ color: #333;
610
+ border: 2px solid #fff;
611
+ box-shadow: 0 0 15px rgba(255, 215, 0, 0.4);
 
 
 
 
612
  }
613
 
614
+ .status-badge.free {
615
+ background: #e2e8f0;
616
+ color: #475569;
617
+ border: 1px solid #cbd5e1;
 
 
618
  }
619
 
620
+ @keyframes fadeInBadge {
621
+ from { opacity: 0; transform: translateY(-10px); }
622
+ to { opacity: 1; transform: translateY(0); }
 
 
623
  }
624
 
625
+ /* Existing CSS for Guide, Buttons, etc. */
626
+ .ip-reset-guide-container {
627
+ text-align: right; direction: rtl; background: rgba(255, 255, 255, 0.98);
628
+ backdrop-filter: blur(10px); padding: 20px; border-radius: 16px;
629
+ box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); border: 1px solid rgba(102, 126, 234, 0.2);
630
+ width: 90%; max-width: 420px; max-height: 90vh; overflow-y: auto;
 
631
  font-family: 'Vazirmatn', sans-serif !important;
632
  }
633
+ .guide-header { display: flex; align-items: center; margin-bottom: 15px; }
634
+ .guide-header-icon { width: 45px; height: 45px; margin-left: 15px; }
635
+ .guide-header h2 { font-size: 1.2rem; margin: 0; }
636
+ .guide-content { font-size: 0.9rem; line-height: 1.6; }
637
+ .info-card, .summary-section { margin-top: 12px; padding: 12px; border-radius: 12px; }
638
+ .info-card { background: #f0f4ff; border: 1px solid #c3dafe; }
639
+ .summary-section { background: #f0fff4; border: 1px solid #c6f6d5; }
640
+ .video-button-container { text-align: center; margin-top: 15px; }
641
+ .elegant-video-button { padding: 8px 16px; border-radius: 20px; border: 1px solid #ddd; background: white; cursor: pointer; display: inline-flex; align-items: center; }
642
+ .guide-actions { display: flex; gap: 10px; margin-top: 20px; }
643
+ .action-button { flex: 1; padding: 10px; border-radius: 10px; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; font-weight: bold; }
644
+ .back-button { background: white; border: 1px solid #ddd; }
645
+ .retry-button { background: #667eea; color: white; }
646
+
647
+ /* Main UI Tweaks */
648
+ #col-container { max-width: 980px; margin: 0 auto; direction: rtl; text-align: right; background: white; padding: 20px; border-radius: 20px; }
649
+ #main-title h1 { text-align: center; color: #2563eb; }
650
+ #main-description { text-align: center; color: #4b5563; }
651
+ .primary-btn { background: linear-gradient(135deg, #10b981, #059669); color: white; border: none; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
652
  footer { display: none !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
653
  </style>
654
  """
655
 
 
656
  combined_html = css_code + js_global_content
657
 
 
658
  with gr.Blocks() as demo:
 
659
  gr.HTML(combined_html)
660
 
661
  with gr.Column(elem_id="col-container"):
662
  gr.Markdown("# **ویرایشگر هوشمند آلفا**", elem_id="main-title")
663
+ gr.Markdown("با هوش مصنوعی آلفا تصاویر تونو به مدل های مختلف ویرایش کنید.", elem_id="main-description")
664
+
665
+ # بج وضعیت کاربر (HTML خالی که توسط JS پر می‌شود)
666
+ gr.HTML('<div id="user-status-badge" class="status-badge"></div>')
667
+
668
+ # فیلدهای مخفی برای انتقال اطلاعات کاربر از JS به پایتون
669
+ user_id_storage = gr.Textbox(visible=False, elem_id="hidden_user_id")
670
+ premium_status_storage = gr.Textbox(visible=False, elem_id="hidden_user_premium")
671
 
672
  with gr.Row(equal_height=True):
673
  with gr.Column():
674
  input_image = gr.Image(label="بارگذاری تصویر", type="pil", height=320)
675
+ prompt = gr.Text(label="دستور ویرایش (به فارسی)", placeholder="مثال: تصویر را به سبک انیمه تبدیل کن...", rtl=True, lines=3)
 
 
 
 
 
 
 
 
676
  status_box = gr.HTML(label="وضعیت")
677
+ run_button = gr.Button("✨ شروع پردازش", variant="primary", elem_classes="primary-btn", elem_id="run-btn")
 
 
678
 
679
  with gr.Column():
680
  output_image = gr.Image(label="تصویر نهایی", interactive=False, format="png", height=380)
 
681
  download_button = gr.Button("📥 دانلود و ذخیره تصویر", variant="secondary", elem_id="download-btn", elem_classes="primary-btn")
682
 
683
  with gr.Row():
684
+ lora_adapter = gr.Dropdown(label="انتخاب سبک", choices=list(LORA_MAPPING.keys()), value="تبدیل عکس به انیمه")
 
 
 
 
685
 
686
+ with gr.Accordion("تنظیمات پیشرفته", open=False):
687
+ aspect_ratio_selection = gr.Dropdown(label="ابعاد", choices=ASPECT_RATIOS_LIST, value="خودکار (پیش‌فرض)")
 
 
 
 
 
 
688
  with gr.Row(visible=False) as custom_dims_row:
689
+ custom_width = gr.Slider(label="عرض", minimum=256, maximum=2048, step=8, value=1024)
690
+ custom_height = gr.Slider(label="ارتفاع", minimum=256, maximum=2048, step=8, value=1024)
691
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
692
+ randomize_seed = gr.Checkbox(label="Seed تصادفی", value=True)
693
+ guidance_scale = gr.Slider(label="Guidance Scale", minimum=1.0, maximum=10.0, step=0.1, value=1.0)
694
+ steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=4)
 
 
 
 
 
 
 
695
 
696
+ # لاجیک نمایش تنظیمات ابعاد
697
  def toggle_row(choice):
698
+ return gr.update(visible=True) if choice == "شخصی‌سازی (Custom)" else gr.update(visible=False)
699
+
700
+ aspect_ratio_selection.change(fn=toggle_row, inputs=aspect_ratio_selection, outputs=custom_dims_row)
701
+
702
+ # اجرای مدل
703
+ run_button.click(
704
+ fn=infer,
705
+ inputs=[
706
+ input_image, prompt, lora_adapter, seed, randomize_seed, guidance_scale, steps,
707
+ aspect_ratio_selection, custom_width, custom_height,
708
+ user_id_storage, premium_status_storage # ارسال اطلاعات کاربر به تابع infer
709
+ ],
710
+ outputs=[output_image, seed, status_box],
711
+ api_name="predict"
712
  )
713
 
714
+ download_button.click(fn=None, inputs=[output_image], outputs=None, js=js_download_func)
715
+
716
+ # نمونه‌ها
717
  gr.Examples(
718
  examples=[
719
  ["examples/1.jpg", "تبدیل به انیمه کن.", "تبدیل عکس به انیمه"],
720
+ ["examples/5.jpg", "سایه‌ها را حذف کن.", "اصلاح نور و سایه"],
 
 
 
 
 
 
 
 
 
721
  ],
722
  inputs=[input_image, prompt, lora_adapter],
723
  outputs=[output_image, seed, status_box],
724
  fn=infer_example,
725
  cache_examples=False,
726
+ label="نمونه‌ها"
727
  )
728
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
729
  if __name__ == "__main__":
730
  demo.queue(max_size=30).launch(show_error=True)