File size: 29,651 Bytes
7f4c99b
 
 
 
 
a516620
 
989c44e
a516620
 
 
989c44e
a516620
 
 
 
b2efe41
 
 
 
 
 
 
 
 
7f4c99b
a516620
 
 
7f4c99b
a516620
 
826d34e
a516620
7f4c99b
 
a516620
7f4c99b
b2efe41
 
 
a516620
 
 
989c44e
a516620
 
 
989c44e
a516620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f4c99b
a516620
b2efe41
a516620
b2efe41
aa0cb15
 
7f4c99b
 
 
 
 
 
 
 
 
 
 
 
b2efe41
 
 
 
 
 
 
 
 
 
 
989c44e
7f4c99b
a516620
b695f49
7f4c99b
a516620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
826d34e
a516620
 
 
 
826d34e
a516620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
826d34e
a516620
826d34e
a516620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
989c44e
 
 
 
 
0fb3ed4
a516620
 
 
 
 
 
989c44e
 
 
 
 
 
 
a516620
 
989c44e
 
a516620
826d34e
a516620
989c44e
 
 
 
 
b2efe41
02b00c0
989c44e
 
b2efe41
 
0fb3ed4
a516620
b2efe41
a516620
 
0fb3ed4
02b00c0
989c44e
 
826d34e
989c44e
 
 
b2efe41
989c44e
 
02b00c0
 
989c44e
826d34e
b2efe41
 
 
 
 
989c44e
 
 
a516620
826d34e
a516620
 
 
 
 
 
 
 
 
 
 
 
7f4c99b
 
a516620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
826d34e
a516620
 
 
 
 
 
826d34e
a516620
 
 
826d34e
b2efe41
 
 
a516620
826d34e
a516620
 
826d34e
a516620
 
 
826d34e
a516620
 
 
b2efe41
a516620
 
826d34e
a516620
 
7f4c99b
a516620
 
 
7f4c99b
a516620
 
 
 
 
 
 
7f4c99b
a516620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f4c99b
a516620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
826d34e
a516620
826d34e
a516620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
826d34e
a516620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
826d34e
a516620
 
 
 
 
 
 
 
 
 
 
826d34e
 
a516620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
989c44e
a516620
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f4c99b
 
a516620
 
 
 
826d34e
a516620
826d34e
a516620
 
826d34e
7f4c99b
b2efe41
 
a516620
826d34e
7f4c99b
02b00c0
 
 
a516620
 
 
 
 
02b00c0
826d34e
a516620
02b00c0
a516620
02b00c0
 
 
a516620
02b00c0
826d34e
a516620
826d34e
b2efe41
a516620
826d34e
a516620
 
 
 
 
 
 
 
b2efe41
 
 
7f4c99b
a516620
 
 
7f4c99b
a516620
826d34e
a516620
02b00c0
 
 
 
 
 
a516620
 
 
 
 
 
 
 
 
7f4c99b
a516620
826d34e
a516620
 
 
 
7f4c99b
 
a516620
 
 
 
 
 
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
import os
import gradio as gr
import numpy as np
import spaces
import torch
import random
import io
import base64
import json
from PIL import Image
from gradio_client import Client
from huggingface_hub import InferenceClient
from deep_translator import GoogleTranslator
from transformers import pipeline
from diffusers import Flux2Pipeline, Flux2Transformer2DModel
from datetime import date
import subprocess
import sys

# نصب پکیج spaces در صورت نیاز (برای اطمینان)
try:
    import spaces
except ImportError:
    subprocess.check_call([sys.executable, "-m", "pip", "install", "spaces==0.43.0"])
    import spaces

# ==========================================
# 1. تنظیمات و پیکربندی سیستم (Configuration)
# ==========================================

# رنگ‌ها و تنظیمات ظاهری
USAGE_LIMIT = 5
DATA_FILE = "usage_data.json"
PREMIUM_PAGE_ID = '1149636'
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024
device = "cuda" if torch.cuda.is_available() else "cpu"

# مقادیر سیگما مخصوص حالت توربو (8 مرحله)
TURBO_SIGMAS = [1.0, 0.6509, 0.4374, 0.2932, 0.1893, 0.1108, 0.0495, 0.00031]

# بارگذاری مدل تشخیص محتوای نامناسب (Safety Checker)
print("Loading Safety Checker...")
safety_classifier = pipeline("image-classification", model="Falconsai/nsfw_image_detection", device=-1)

# کلاینت‌های هوش مصنوعی
hf_client = InferenceClient(api_key=os.environ.get("HF_TOKEN"))
VLM_MODEL = "baidu/ERNIE-4.5-VL-424B-A47B-Base-PT"

# پرامپت‌های سیستمی برای بهبود متن
SYSTEM_PROMPT_TEXT_ONLY = """You are an expert prompt engineer for FLUX.2. Rewrite user prompts to be more descriptive while strictly preserving their core subject and intent. Add concrete visual specifics."""
SYSTEM_PROMPT_WITH_IMAGES = """You are FLUX.2 image-editing expert. Convert editing requests into one concise instruction (50-80 words)."""

# لیست کلمات ممنوعه (Strict Mode)
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",
    "fetish", "bdsm", "bondage", "latex", "hentai", "ecchi", "ahegao",
    "gore", "bloody", "blood", "kill", "murder", "dead", "torture", "abuse"
]

# ==========================================
# 2. بارگذاری مدل FLUX.2 با حالت TURBO
# ==========================================
print("Loading FLUX.2 Pipeline with Turbo LoRA...")
repo_id = "black-forest-labs/FLUX.2-dev"

dit = Flux2Transformer2DModel.from_pretrained(
    repo_id,
    subfolder="transformer",
    torch_dtype=torch.bfloat16
)

pipe = Flux2Pipeline.from_pretrained(
    repo_id,
    text_encoder=None,
    transformer=dit,
    torch_dtype=torch.bfloat16
)

# بارگذاری وزن‌های توربو (Turbo LoRA)
# این بخش باعث می‌شود مدل به جای ۳۰ مرحله، در ۸ مرحله تصویر بسازد
print("Loading Turbo LoRA weights...")
pipe.load_lora_weights(
    "fal/FLUX.2-dev-Turbo", 
    weight_name="flux.2-turbo-lora.safetensors"
)
pipe.fuse_lora()
pipe.unload_lora_weights() # ادغام وزن‌ها برای سرعت بیشتر

pipe.to(device)

# بهینه‌سازی ZeroGPU
spaces.aoti_blocks_load(pipe.transformer, "zerogpu-aoti/FLUX.2", variant="fa3")

# ==========================================
# 3. توابع کمکی (Helpers)
# ==========================================

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 is_image_nsfw(image):
    if image is None: return False
    try:
        img_to_check = image
        if isinstance(image, list):
             if len(image) > 0:
                img_to_check = image[0][0] if isinstance(image[0], tuple) else image[0]
             else:
                return False

        results = safety_classifier(img_to_check)
        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

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

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>"""

def get_quota_exceeded_html():
    return """<div style="background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%); border: 2px solid #f59e0b; padding: 20px; border-radius: 16px; text-align: center; box-shadow: 0 4px 15px rgba(245, 158, 11, 0.1);"><div style="font-size: 3rem; margin-bottom: 10px;">💎</div><h3 style="color: #92400e; margin: 0 0 10px 0; font-weight: 800;">اعتبار رایگان امروز تمام شد</h3><p style="color: #b45309; margin: 0; font-size: 0.95em;">شما از ۵ تصویر رایگان امروز استفاده کرده‌اید.<br>برای ساخت تصاویر نامحدود و حرفه‌ای، لطفا نسخه خود را ارتقا دهید.</p></div>"""

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"]

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

def image_to_data_uri(img):
    buffered = io.BytesIO()
    img.save(buffered, format="PNG")
    img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
    return f"data:image/png;base64,{img_str}"

def remote_text_encoder(prompts):
    client = Client("multimodalart/mistral-text-encoder")
    result = client.predict(prompt=prompts, api_name="/encode_text")
    prompt_embeds = torch.load(result[0])
    return prompt_embeds

def upsample_prompt_logic(prompt, image_list):
    try:
        if image_list and len(image_list) > 0:
            system_content = SYSTEM_PROMPT_WITH_IMAGES
            user_content = [{"type": "text", "text": prompt}]
            for img in image_list:
                data_uri = image_to_data_uri(img)
                user_content.append({"type": "image_url", "image_url": {"url": data_uri}})
            messages = [{"role": "system", "content": system_content}, {"role": "user", "content": user_content}]
        else:
            system_content = SYSTEM_PROMPT_TEXT_ONLY
            messages = [{"role": "system", "content": system_content}, {"role": "user", "content": prompt}]

        completion = hf_client.chat.completions.create(model=VLM_MODEL, messages=messages, max_tokens=1024)
        return completion.choices[0].message.content
    except Exception as e:
        print(f"Upsampling failed: {e}")
        return prompt

# محاسبه زمان برای GPU (برای حالت توربو بسیار کمتر است)
def get_duration(prompt_embeds, image_list, width, height, num_inference_steps, guidance_scale, seed, progress=gr.Progress(track_tqdm=True)):
    num_images = 0 if image_list is None else len(image_list)
    step_duration = 1 + 0.8 * num_images
    # در حالت توربو همیشه ۸ مرحله داریم، پس زمان محاسبه ثابت و کم است
    return max(30, 8 * step_duration + 10)

# ==========================================
# 4. تابع اصلی GPU (Inference) - Turbo Optimized
# ==========================================

@spaces.GPU(duration=get_duration)
def generate_image(prompt_embeds, image_list, width, height, num_inference_steps, guidance_scale, seed, progress=gr.Progress(track_tqdm=True)):
    prompt_embeds = prompt_embeds.to(device)
    generator = torch.Generator(device=device).manual_seed(seed)

    pipe_kwargs = {
        "prompt_embeds": prompt_embeds,
        "image": image_list,
        # "num_inference_steps": num_inference_steps, # نادیده گرفته می‌شود به نفع توربو
        "guidance_scale": guidance_scale,
        "generator": generator,
        "width": width,
        "height": height,
    }

    # اعمال تنظیمات اجباری توربو
    pipe_kwargs["sigmas"] = TURBO_SIGMAS
    pipe_kwargs["num_inference_steps"] = 8  # همیشه ۸ مرحله برای توربو

    if progress: progress(0, desc="Starting Turbo generation...")
    image = pipe(**pipe_kwargs).images[0]
    return image

def infer(
    prompt, input_images, seed, randomize_seed, width, height,
    num_inference_steps, guidance_scale, prompt_upsampling,
    fingerprint, subscription_status,
    progress=gr.Progress(track_tqdm=True)
):
    # 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. بررسی‌های ایمنی (Safety Checks)
    # الف) بررسی تصویر ورودی
    image_list = None
    if input_images is not None and len(input_images) > 0:
        image_list = [item[0] for item in input_images]
        if is_image_nsfw(image_list):
             return None, seed, get_error_html("تصویر ورودی دارای محتوای نامناسب است."), gr.update(visible=True), gr.update(visible=False)

    # ب) ترجمه و بررسی متن
    progress(0.1, desc="Translating...")
    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)

    # 3. کسر اعتبار (اگر کاربر رایگان است)
    if subscription_status != 'paid':
        consume_quota(fingerprint)

    # 4. آماده‌سازی تنظیمات
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)

    try:
        # Upsampling Prompt (Optional)
        final_prompt = english_prompt
        if prompt_upsampling:
            progress(0.2, desc="Enhancing prompt...")
            final_prompt = upsample_prompt_logic(english_prompt, image_list)

        # Text Encoding (CPU/Network)
        progress(0.3, desc="Encoding...")
        prompt_embeds = remote_text_encoder(final_prompt)

        # Generation (GPU) - TURBO MODE
        progress(0.4, desc="Generating (Turbo)...")
        # ورودی num_inference_steps از UI گرفته می‌شود اما در تابع generate_image نادیده گرفته می‌شود (روی ۸ قفل است)
        result_image = generate_image(
            prompt_embeds, image_list, width, height,
            num_inference_steps, guidance_scale, seed, progress
        )

        # 5. بررسی تصویر خروجی
        if is_image_nsfw(result_image):
            return None, seed, get_error_html("تصویر تولید شده حاوی محتوای نامناسب بود."), gr.update(visible=True), gr.update(visible=False)

        # 6. محاسبه اعتبار باقی‌مانده
        user_record = get_user_record(fingerprint)
        remaining = USAGE_LIMIT - user_record["count"] if user_record else 0
        success_msg = f"تصویر با موفقیت ساخته شد (Turbo)."
        if subscription_status != 'paid':
             success_msg += f" (اعتبار باقی‌مانده امروز: {remaining})"

        btn_run_update = gr.update(visible=True)
        btn_upg_update = gr.update(visible=False)

        if subscription_status != 'paid' and remaining <= 0:
             btn_run_update = gr.update(visible=False)
             btn_upg_update = gr.update(visible=True)

        return result_image, seed, get_success_html(success_msg), btn_run_update, btn_upg_update

    except Exception as e:
        error_str = str(e)
        if "quota" in error_str.lower() or "exceeded" in error_str.lower():
             raise e # Raise to be caught by JS
        return None, seed, get_error_html(f"خطا در پردازش: {error_str}"), gr.update(visible=True), gr.update(visible=False)


def update_dimensions_from_image(image_list):
    if image_list is None or len(image_list) == 0:
        return 1024, 1024
    img = image_list[0][0]
    img_width, img_height = img.size
    aspect_ratio = img_width / img_height
    if aspect_ratio >= 1:
        new_width = 1024
        new_height = int(1024 / aspect_ratio)
    else:
        new_height = 1024
        new_width = int(1024 * aspect_ratio)
    new_width = round(new_width / 8) * 8
    new_height = round(new_height / 8) * 8
    return max(256, min(1024, new_width)), max(256, min(1024, new_height))

# ==========================================
# 5. جاوااسکریپت و CSS (UI/UX)
# ==========================================

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_content = """
<script>
document.addEventListener('DOMContentLoaded', () => {
    async function getBrowserFingerprint() {
        const components = [navigator.userAgent, navigator.language, screen.colorDepth, screen.width + 'x' + screen.height, new Date().getTimezoneOffset()];
        try {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            ctx.textBaseline = "top"; ctx.font = "14px 'Arial'"; ctx.textBaseline = "alphabetic";
            ctx.fillStyle = "#f60"; ctx.fillRect(125, 1, 62, 20);
            ctx.fillStyle = "#069"; ctx.fillText("Alpha_Flux_FP_v1", 2, 15);
            components.push(canvas.toDataURL());
        } catch (e) { components.push("canvas-err"); }
        const str = components.join('~~~');
        let hash = 0;
        for (let i = 0; i < str.length; i++) { hash = ((hash << 5) - hash) + str.charCodeAt(i); hash |= 0; }
        return 'fp_' + Math.abs(hash).toString(16);
    }

    function isUserPaid(userObject) {
        const PREMIUM_PAGE_ID = '1149636';
        if (userObject && userObject.isLogin && userObject.accessible_pages) {
            if (Array.isArray(userObject.accessible_pages)) return userObject.accessible_pages.some(page => String(page) === String(PREMIUM_PAGE_ID));
        }
        return false;
    }

    function updateHiddenInputs(fingerprint, status) {
        const fpInput = document.querySelector('#fingerprint_storage textarea');
        const stInput = document.querySelector('#status_storage textarea');
        if(fpInput && fingerprint && fpInput.value !== fingerprint) { fpInput.value = fingerprint; fpInput.dispatchEvent(new Event('input', { bubbles: true })); }
        if(stInput && status && stInput.value !== status) { stInput.value = status; stInput.dispatchEvent(new Event('input', { bubbles: true })); }
    }

    function updateSubscriptionBadge(status) {
        const badge = document.getElementById('user-sub-badge');
        if (!badge) return;
        if (status === 'paid') {
            badge.innerHTML = '✨ اشتراک: <span style="color: #FFD700; font-weight: bold;">نامحدود (PRO)</span>';
            badge.style.background = 'linear-gradient(45deg, #1e3a8a, #3b82f6)';
        } else {
            badge.innerHTML = '👤 اشتراک: <span style="color: #fff; font-weight: bold;">رایگان (۵ اعتبار روزانه)</span>';
            badge.style.background = 'linear-gradient(45deg, #4b5563, #6b7280)';
        }
        badge.style.display = 'inline-block';
    }

    async function initUserIdentity() {
        window.userFingerprint = await getBrowserFingerprint();
        window.userStatus = 'free';
        window.parent.postMessage({ type: 'REQUEST_USER_STATUS' }, '*');
        updateSubscriptionBadge('free');
        updateHiddenInputs(window.userFingerprint, window.userStatus);
        setInterval(() => { if(window.userFingerprint) updateHiddenInputs(window.userFingerprint, window.userStatus || 'free'); }, 1500);
    }

    window.addEventListener('message', (event) => {
        if (event.data && event.data.type === 'USER_STATUS_RESPONSE') {
            try {
                const userObject = typeof event.data.payload === 'string' ? JSON.parse(event.data.payload) : event.data.payload;
                const status = isUserPaid(userObject) ? 'paid' : 'free';
                window.userStatus = status;
                updateSubscriptionBadge(status);
                updateHiddenInputs(window.userFingerprint, status);
            } catch (e) { console.error(e); }
        }
    });

    initUserIdentity();

    // GPU Quota Modal
    window.retryGeneration = function() { document.getElementById('custom-quota-modal')?.remove(); document.getElementById('run-btn')?.click(); };
    window.closeErrorModal = function() { document.getElementById('custom-quota-modal')?.remove(); };

    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>
                    </div>
                    <div class="guide-content">
                        <p>برای ادامه ساخت تصویر، لطفاً طبق آموزش زیر IP خود را تغییر دهید (اینترنت را خاموش/روشن کنید یا VPN را قطع کنید) و سپس دکمه تلاش مجدد را بزنید.</p>
                        <div class="video-button-container">
                            <button onclick="parent.postMessage({ type: 'NAVIGATE_TO_URL', url: '#/nav/online/news/getSingle/1149635' }, '*')" class="elegant-video-button">
                                <span>دیدن ویدیو آموزشی</span>
                            </button>
                        </div>
                    </div>
                    <div class="guide-actions">
                        <button class="action-button back-button" onclick="window.closeErrorModal()">بازگشت</button>
                        <button class="action-button retry-button" onclick="window.retryGeneration()">تلاش مجدد</button>
                    </div>
                </div>
            </div>`;
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        setTimeout(window.closeErrorModal, 15000);
    };

    setInterval(() => {
        const potentialErrors = document.querySelectorAll('.toast-body, .error, .toast-wrap');
        potentialErrors.forEach(el => {
            const text = el.innerText || "";
            if (text.toLowerCase().includes('quota') || text.toLowerCase().includes('exceeded')) {
                 showQuotaModal();
                 el.style.display = 'none';
                 const parent = el.closest('.toast-wrap');
                 if(parent) parent.style.display = 'none';
            }
        });
    }, 100);

    const forceLight = () => {
        document.body.classList.remove('dark');
        document.body.style.backgroundColor = '#f5f7fa';
        document.body.style.color = '#333333';
    };
    forceLight(); setInterval(forceLight, 1000);
});
</script>
"""

css_code = """
<style>
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;700&display=swap');
:root, .dark, body, .gradio-container {
    --body-background-fill: #f5f7fa !important;
    --body-text-color: #1f2937 !important;
    font-family: 'Vazirmatn', sans-serif !important;
}
.ip-reset-guide-container { text-align: right; direction: rtl; background: white; padding: 20px; border-radius: 16px; width: 90%; max-width: 420px; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); }
.elegant-video-button { background: #fff; color: #667eea; border: 1px solid #e2e8f0; padding: 10px 20px; border-radius: 50px; cursor: pointer; font-weight: bold; margin-top: 10px; }
.guide-actions { display: flex; gap: 10px; margin-top: 20px; }
.action-button { flex: 1; padding: 10px; border-radius: 12px; border: none; cursor: pointer; font-weight: bold; }
.retry-button { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
.back-button { background: white; border: 1px solid #e2e8f0; }

#col-container { max-width: 1200px; margin: 0 auto; direction: rtl; text-align: right; padding: 30px; background: white; border-radius: 24px; box-shadow: 0 10px 40px -10px rgba(0,0,0,0.08); }
#badge-container { text-align: center; margin-bottom: 20px; height: 30px; }
#user-sub-badge { padding: 6px 16px; border-radius: 20px; font-size: 0.9em; color: white; display: none; }
.primary-btn { background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important; color: white !important; font-size: 1.1em !important; border-radius: 14px !important; margin-top: 15px; border: none !important; }
.upgrade-btn { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%) !important; color: white !important; font-size: 1.1em !important; border-radius: 14px !important; margin-top: 15px; animation: pulse 2s infinite; border: none !important; }
@keyframes pulse { 0% { transform: scale(1); } 70% { transform: scale(1.02); } 100% { transform: scale(1); } }
footer { display: none !important; }
#fingerprint_storage, #status_storage { display: none !important; }
</style>
"""

# ==========================================
# 6. ساخت رابط کاربری (Gradio Blocks)
# ==========================================

with gr.Blocks() as demo:
    gr.HTML(js_global_content + css_code)

    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("# **ساخت تصویر با FLUX.2 Turbo (فوق سریع)**", elem_id="main-title")
        gr.Markdown("با استفاده از مدل قدرتمند FLUX.2 Turbo متن فارسی خود را در چند ثانیه به تصاویر شگفت‌انگیز تبدیل کنید.", elem_id="main-description")
        gr.HTML('<div id="badge-container"><span id="user-sub-badge"></span></div>')

        with gr.Row():
            with gr.Column():
                with gr.Row():
                    prompt = gr.Text(
                        label="توصیف تصویر (به فارسی)",
                        show_label=True,
                        max_lines=3,
                        placeholder="یک منظره زیبا از...",
                        rtl=True
                    )

                with gr.Accordion("بارگذاری تصویر (اختیاری برای ویرایش/ایده)", open=False):
                    input_images = gr.Gallery(
                        label="تصاویر ورودی",
                        type="pil",
                        columns=3,
                        rows=1,
                        height=200
                    )

                status_box = gr.HTML(label="وضعیت")

                run_button = gr.Button("✨ ساخت سریع تصویر (Turbo)", variant="primary", elem_classes="primary-btn", elem_id="run-btn", visible=True)
                upgrade_button = gr.Button("💎 خرید نسخه نامحدود", variant="primary", elem_classes="upgrade-btn", elem_id="upgrade-btn", visible=False)

                with gr.Accordion("تنظیمات پیشرفته", open=False):
                    prompt_upsampling = gr.Checkbox(label="بهبود خودکار پرامپت (هوشمند)", value=True)
                    seed = gr.Slider(label="دانه تصادفی (Seed)", minimum=0, maximum=MAX_SEED, step=1, value=0)
                    randomize_seed = gr.Checkbox(label="Seed تصادفی", value=True)
                    with gr.Row():
                        width = gr.Slider(label="عرض (Width)", minimum=256, maximum=MAX_IMAGE_SIZE, step=8, value=1024)
                        height = gr.Slider(label="ارتفاع (Height)", minimum=256, maximum=MAX_IMAGE_SIZE, step=8, value=1024)
                    with gr.Row():
                        # این اسلایدر در حالت توربو بی تاثیر است و روی ۸ قفل می شود
                        num_inference_steps = gr.Slider(label="تعداد مراحل (ثابت در حالت Turbo)", minimum=1, maximum=50, step=1, value=8, interactive=False)
                        guidance_scale = gr.Slider(label="میزان وفاداری (Guidance)", minimum=1.0, maximum=10.0, step=0.1, value=2.5)

            with gr.Column():
                result = gr.Image(label="تصویر نهایی", show_label=True, interactive=False)
                download_button = gr.Button("📥 دانلود تصویر", variant="secondary", elem_id="download-btn")

    # اتصال رویدادها

    # 1. آپدیت ابعاد بر اساس تصویر آپلودی
    input_images.upload(
        fn=update_dimensions_from_image,
        inputs=[input_images],
        outputs=[width, height]
    )

    # 2. بررسی اولیه اعتبار
    fingerprint_box.change(
        fn=check_initial_quota,
        inputs=[fingerprint_box, status_box_input],
        outputs=[run_button, upgrade_button, status_box]
    )

    # 3. اجرای مدل
    run_button.click(
        fn=infer,
        inputs=[
            prompt, input_images, seed, randomize_seed, width, height,
            num_inference_steps, guidance_scale, prompt_upsampling,
            fingerprint_box, status_box_input
        ],
        outputs=[result, seed, status_box, run_button, upgrade_button]
    )

    # 4. دکمه‌های دانلود و ارتقا
    upgrade_button.click(fn=None, js=js_upgrade_func)
    download_button.click(fn=None, inputs=[result], js=js_download_func)

if __name__ == "__main__":
    demo.queue(max_size=30).launch(show_error=True)