File size: 28,868 Bytes
0548bcb
 
 
35dac7a
 
9481783
0548bcb
02267af
938e515
f364720
0548bcb
9e832a5
74cc200
9e832a5
387c683
 
 
 
 
 
 
9e832a5
387c683
 
 
 
9e832a5
387c683
 
9e832a5
387c683
 
74cc200
387c683
 
 
 
74cc200
387c683
 
74cc200
387c683
 
74cc200
387c683
 
 
 
74cc200
387c683
 
74cc200
387c683
 
 
 
 
 
 
74cc200
9e832a5
eef0060
978ca4f
0548bcb
 
a5c6d21
0548bcb
938e515
 
 
0548bcb
938e515
 
 
 
 
0548bcb
938e515
 
0548bcb
 
938e515
0548bcb
938e515
 
0548bcb
 
 
 
509937b
0548bcb
 
 
f364720
0548bcb
 
84301a0
509937b
 
 
c2ede28
509937b
0548bcb
 
509937b
 
 
 
0548bcb
 
 
9e832a5
0548bcb
9e832a5
0548bcb
 
 
 
 
 
 
 
 
9e832a5
0548bcb
9e832a5
0548bcb
84301a0
f0dae96
 
 
 
 
84301a0
 
0548bcb
f0dae96
 
509937b
f0dae96
 
 
 
 
 
 
 
 
84301a0
 
 
 
 
 
 
 
0548bcb
509937b
 
0548bcb
84301a0
509937b
 
0548bcb
509937b
0548bcb
 
 
 
 
 
 
84301a0
0548bcb
 
 
 
509937b
c2ede28
509937b
0548bcb
eef0060
 
9481783
0548bcb
 
 
 
 
 
 
 
 
 
9d74976
0548bcb
 
 
 
 
9e832a5
0548bcb
ad05eaa
 
 
 
84301a0
0548bcb
 
938e515
0548bcb
 
938e515
 
 
0548bcb
 
938e515
0548bcb
 
938e515
0548bcb
 
 
938e515
 
 
0548bcb
 
 
938e515
0548bcb
 
 
 
 
 
 
 
 
 
 
938e515
 
 
0548bcb
978ca4f
9d74976
978ca4f
84301a0
0548bcb
 
 
84301a0
9edb378
 
0548bcb
9edb378
 
 
 
938e515
9481783
0548bcb
f364720
509937b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
938e515
9481783
 
938e515
eef0060
 
 
 
 
 
 
 
 
 
 
 
9481783
 
 
0cb8e39
9481783
 
 
 
0cb8e39
509937b
 
 
 
0548bcb
 
 
 
 
 
040143e
 
 
 
 
 
0548bcb
 
 
 
 
 
 
 
 
 
 
 
 
 
938e515
0cb8e39
0548bcb
 
 
 
 
938e515
0548bcb
9481783
 
0548bcb
 
9edb378
0548bcb
 
 
 
 
 
509937b
0548bcb
 
 
 
9481783
 
 
 
509937b
9edb378
 
9481783
509937b
 
 
0548bcb
 
 
c2ede28
0548bcb
 
 
 
 
 
c2ede28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad05eaa
c2ede28
 
 
 
 
 
 
 
 
ad05eaa
c2ede28
0548bcb
 
c2ede28
6a69f5d
9d74976
6a69f5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0dae96
 
509937b
f0dae96
0548bcb
509937b
9d74976
f0dae96
 
0548bcb
 
040143e
0548bcb
 
35dac7a
 
 
 
ad05eaa
35dac7a
 
 
bca5c4e
 
 
a5c6d21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bca5c4e
a5c6d21
 
 
bca5c4e
 
a5c6d21
 
 
 
 
 
 
 
 
 
bca5c4e
 
c2ede28
a5c6d21
 
ad05eaa
a5c6d21
 
 
 
 
 
bca5c4e
 
a5c6d21
 
 
35dac7a
 
ad05eaa
a5c6d21
 
 
 
 
 
 
 
 
 
 
 
 
ad05eaa
a5c6d21
bca5c4e
 
ad05eaa
a5c6d21
 
 
 
 
 
 
 
ad05eaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2ede28
 
ad05eaa
c2ede28
 
ad05eaa
c2ede28
 
 
 
ad05eaa
c2ede28
 
6359d76
ad05eaa
 
 
 
 
 
 
 
c2ede28
 
 
 
ad05eaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2ede28
 
9d74976
c2ede28
ad05eaa
 
 
 
 
 
 
 
c2ede28
 
 
 
ad05eaa
9d74976
ad05eaa
 
c2ede28
 
 
9d74976
ad05eaa
 
c2ede28
 
0548bcb
eef0060
ad05eaa
 
 
509937b
8f4c906
c272213
 
 
 
 
 
 
 
 
602036b
c272213
 
602036b
c272213
602036b
c272213
c2ede28
 
 
 
 
ad05eaa
 
c2ede28
49ba79d
d59a1ed
9481783
d59a1ed
c2ede28
 
 
 
 
ad05eaa
 
c2ede28
d59a1ed
 
 
c2ede28
 
 
 
 
ad05eaa
 
c2ede28
ae35dbd
c2ede28
d59a1ed
c2ede28
 
 
 
 
ad05eaa
 
c2ede28
d59a1ed
 
 
 
c2ede28
 
 
 
 
ad05eaa
 
c2ede28
d59a1ed
 
 
509937b
c2ede28
 
ad05eaa
c2ede28
 
ad05eaa
 
c2ede28
7b90188
c2ede28
 
 
 
 
ad05eaa
 
c2ede28
7b90188
 
ad05eaa
 
 
509937b
f0dae96
 
0548bcb
164e9d5
0548bcb
 
ab2e314
0548bcb
 
938e515
0548bcb
938e515
0548bcb
938e515
37d6b3d
 
 
 
 
 
 
 
 
 
49ba79d
6a69f5d
 
 
 
 
c2ede28
6a69f5d
 
 
f0dae96
 
 
 
 
 
35dac7a
0548bcb
 
 
 
 
 
 
 
938e515
0548bcb
49ba79d
6de0e51
0548bcb
978ca4f
938e515
c2ede28
 
9d74976
ad05eaa
c2ede28
 
 
ad05eaa
c2ede28
ad05eaa
c2ede28
ad05eaa
c2ede28
 
ad05eaa
 
c2ede28
ad05eaa
 
c2ede28
 
35dac7a
f0dae96
509937b
f0dae96
 
 
 
0548bcb
 
 
040143e
0548bcb
938e515
978ca4f
 
509937b
ad05eaa
35dac7a
 
 
 
9d74976
ad05eaa
 
35dac7a
 
 
 
9d74976
ad05eaa
 
 
 
 
 
 
c2ede28
ad05eaa
978ca4f
 
 
d59a1ed
84301a0
0548bcb
 
 
 
 
486cf9e
9e832a5
0cb8e39
 
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
# -*- coding: utf-8 -*-
import os
import time
import json
from datetime import datetime
from typing import List, Optional, Tuple

import spaces
import gradio as gr
from PIL import Image

# =========================
# FIX: gradio 4.24 / gradio_client crashes on boolean JSON Schemas in /api_info
# =========================
def _patch_gradio_client_bool_schema():
    try:
        import gradio_client.utils as gcu
        patched_any = False

        if hasattr(gcu, "get_type"):
            _orig_get_type = gcu.get_type

            def _get_type_patched(schema):
                if isinstance(schema, bool):
                    return "any"
                return _orig_get_type(schema)

            gcu.get_type = _get_type_patched
            patched_any = True

        if hasattr(gcu, "get_desc"):
            _orig_get_desc = gcu.get_desc

            def _get_desc_patched(schema):
                if isinstance(schema, bool):
                    return ""
                return _orig_get_desc(schema)

            gcu.get_desc = _get_desc_patched
            patched_any = True

        if hasattr(gcu, "_json_schema_to_python_type"):
            _orig_json2py = gcu._json_schema_to_python_type

            def _json_schema_to_python_type_patched(schema, defs=None):
                if isinstance(schema, bool):
                    return "any"
                return _orig_json2py(schema, defs)

            gcu._json_schema_to_python_type = _json_schema_to_python_type_patched
            patched_any = True

        if patched_any:
            print("Patched gradio_client.utils for boolean JSON Schemas (/api_info)", flush=True)
        else:
            print("gradio_client patch: nothing to patch (unexpected utils layout)", flush=True)

    except Exception as e:
        print("gradio_client patch failed:", repr(e), flush=True)


_patch_gradio_client_bool_schema()

import torch
from torchvision import transforms
from huggingface_hub import login, snapshot_download, HfApi, hf_hub_download

from src.tryon_pipeline import StableDiffusionXLInpaintPipeline as TryonPipeline
from src.unet_hacked_garmnet import UNet2DConditionModel as UNet2DConditionModel_ref
from src.unet_hacked_tryon import UNet2DConditionModel

from transformers import (
    CLIPImageProcessor,
    CLIPVisionModelWithProjection,
    CLIPTextModel,
    CLIPTextModelWithProjection,
    AutoTokenizer,
)

from diffusers import DDPMScheduler, AutoencoderKL

import apply_net
from utils_mask import get_mask_location
from preprocess.humanparsing.run_parsing import Parsing
from preprocess.openpose.run_openpose import OpenPose
from detectron2.data.detection_utils import convert_PIL_to_numpy, _apply_exif_orientation


# =========================
# Garments catalog (only)
# =========================
GARMENT_DIR = "garments"
ALLOWED_EXTS = (".png", ".jpg", ".jpeg", ".webp")
GARMENTS_DATASET = os.getenv("GARMENTS_DATASET", "").strip()
HF_TOKEN = os.getenv("HF_TOKEN", "").strip()


def ensure_garments_available() -> None:
    """
    Если GARMENTS_DATASET не задан — используем локальную папку ./garments.
    Если задан — скачиваем датасет HF в ./garments.
    """
    os.makedirs(GARMENT_DIR, exist_ok=True)

    if not GARMENTS_DATASET:
        print("GARMENTS_DATASET not set. Using local ./garments (if any).", flush=True)
        return

    if HF_TOKEN:
        try:
            login(token=HF_TOKEN, add_to_git_credential=False)
            print("HF login: OK", flush=True)
        except Exception as e:
            print("HF login: FAILED:", str(e)[:200], flush=True)

    try:
        snapshot_download(
            repo_id=GARMENTS_DATASET,
            repo_type="dataset",
            local_dir=GARMENT_DIR,
            local_dir_use_symlinks=False,
            token=HF_TOKEN if HF_TOKEN else None,
        )
        print(f"Garments dataset downloaded: {GARMENTS_DATASET} -> {GARMENT_DIR}/", flush=True)
    except Exception as e:
        print("Garments download FAILED:", str(e)[:300], flush=True)


def _gender_subdir(gender: str) -> str:
    return "male" if gender == "Мужская" else "female"


def list_garments(gender: Optional[str] = None) -> List[str]:
    files: List[str] = []
    if not os.path.isdir(GARMENT_DIR):
        return files

    if gender:
        base = os.path.join(GARMENT_DIR, _gender_subdir(gender))
        if os.path.isdir(base):
            for root, _, fnames in os.walk(base):
                for f in fnames:
                    if f.lower().endswith(ALLOWED_EXTS) and not f.startswith("."):
                        rel = os.path.relpath(os.path.join(root, f), GARMENT_DIR)
                        files.append(rel)
            files.sort()
            return files

    for root, _, fnames in os.walk(GARMENT_DIR):
        for f in fnames:
            if f.lower().endswith(ALLOWED_EXTS) and not f.startswith("."):
                rel = os.path.relpath(os.path.join(root, f), GARMENT_DIR)
                files.append(rel)
    files.sort()
    return files


def garment_path(relpath: str) -> str:
    return os.path.join(GARMENT_DIR, relpath)


def load_garment_pil(relpath: str) -> Optional[Image.Image]:
    if not relpath:
        return None
    path = garment_path(relpath)
    if not os.path.exists(path):
        return None
    try:
        return Image.open(path).convert("RGB")
    except Exception:
        return None


def build_gallery_items(files: List[str]):
    return [(garment_path(f), "") for f in files]


# =========================
# Rate limit
# =========================
_last_call_ts = 0.0


def allow_call(min_interval_sec: float = 2.5) -> Tuple[bool, str]:
    global _last_call_ts
    now = time.time()
    if now - _last_call_ts < min_interval_sec:
        wait = min_interval_sec - (now - _last_call_ts)
        return False, f"⏳ Подождите {wait:.1f} сек."
    _last_call_ts = now
    return True, ""


# =========================
# Model init (BASELINE)
# =========================
base_path = "yisol/IDM-VTON"

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32
print("DEVICE:", DEVICE, "DTYPE:", DTYPE, flush=True)

tensor_transfrom = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize([0.5], [0.5]),
])

unet = UNet2DConditionModel.from_pretrained(base_path, subfolder="unet", torch_dtype=DTYPE)
unet.requires_grad_(False)

tokenizer_one = AutoTokenizer.from_pretrained(base_path, subfolder="tokenizer", revision=None, use_fast=False)
tokenizer_two = AutoTokenizer.from_pretrained(base_path, subfolder="tokenizer_2", revision=None, use_fast=False)

noise_scheduler = DDPMScheduler.from_pretrained(base_path, subfolder="scheduler")

text_encoder_one = CLIPTextModel.from_pretrained(base_path, subfolder="text_encoder", torch_dtype=DTYPE)
text_encoder_two = CLIPTextModelWithProjection.from_pretrained(base_path, subfolder="text_encoder_2", torch_dtype=DTYPE)

image_encoder = CLIPVisionModelWithProjection.from_pretrained(base_path, subfolder="image_encoder", torch_dtype=DTYPE)
vae = AutoencoderKL.from_pretrained(base_path, subfolder="vae", torch_dtype=DTYPE)

UNet_Encoder = UNet2DConditionModel_ref.from_pretrained(base_path, subfolder="unet_encoder", torch_dtype=DTYPE)
UNet_Encoder.requires_grad_(False)

parsing_model = Parsing(0)
openpose_model = OpenPose(0)

for m in [UNet_Encoder, image_encoder, vae, unet, text_encoder_one, text_encoder_two]:
    m.requires_grad_(False)

pipe = TryonPipeline.from_pretrained(
    base_path,
    unet=unet,
    vae=vae,
    feature_extractor=CLIPImageProcessor(),
    text_encoder=text_encoder_one,
    text_encoder_2=text_encoder_two,
    tokenizer=tokenizer_one,
    tokenizer_2=tokenizer_two,
    scheduler=noise_scheduler,
    image_encoder=image_encoder,
    torch_dtype=DTYPE,
)
pipe.unet_encoder = UNet_Encoder


# =========================
# Inference (BASELINE params)
# =========================
@spaces.GPU
def start_tryon(
    human_pil: Image.Image,
    garm_img: Image.Image,
) -> Image.Image:
    device = "cuda" if torch.cuda.is_available() else "cpu"
    dtype = torch.float16 if device == "cuda" else torch.float32

    if device == "cuda":
        openpose_model.preprocessor.body_estimation.model.to(device)
    pipe.to(device)
    pipe.unet_encoder.to(device)

    garm_img = garm_img.convert("RGB").resize((768, 1024))
    human_img_orig = human_pil.convert("RGB")

    width, height = human_img_orig.size
    target_width = int(min(width, height * (3 / 4)))
    target_height = int(min(height, width * (4 / 3)))
    left = (width - target_width) / 2
    top = (height - target_height) / 2
    right = (width + target_width) / 2
    bottom = (height + target_height) / 2
    cropped_img = human_img_orig.crop((left, top, right, bottom))
    crop_size = cropped_img.size
    human_img = cropped_img.resize((768, 1024))

    keypoints = openpose_model(human_img.resize((384, 512)))
    model_parse, _ = parsing_model(human_img.resize((384, 512)))
    mask, _ = get_mask_location("hd", "upper_body", model_parse, keypoints)
    mask = mask.resize((768, 1024))

    human_img_arg = _apply_exif_orientation(human_img.resize((384, 512)))
    human_img_arg = convert_PIL_to_numpy(human_img_arg, format="BGR")

    args = apply_net.create_argument_parser().parse_args(
        (
            "show",
            "./configs/densepose_rcnn_R_50_FPN_s1x.yaml",
            "./ckpt/densepose/model_final_162be9.pkl",
            "dp_segm",
            "-v",
            "--opts",
            "MODEL.DEVICE",
            "cuda" if device == "cuda" else "cpu",
        )
    )
    pose_img = args.func(args, human_img_arg)
    pose_img = pose_img[:, :, ::-1]
    pose_img = Image.fromarray(pose_img).resize((768, 1024))

    garment_des = "a garment"
    prompt_main = "model is wearing " + garment_des
    prompt_cloth = "a photo of " + garment_des
    negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"

    denoise_steps = 30
    guidance_scale = 2.0
    strength = 1.0
    seed = 42

    with torch.no_grad():
        if device == "cuda":
            autocast_ctx = torch.cuda.amp.autocast()
        else:
            class _NoCtx:
                def __enter__(self):
                    return None

                def __exit__(self, *args):
                    return False

            autocast_ctx = _NoCtx()

        with autocast_ctx:
            (
                prompt_embeds,
                negative_prompt_embeds,
                pooled_prompt_embeds,
                negative_pooled_prompt_embeds,
            ) = pipe.encode_prompt(
                prompt_main,
                num_images_per_prompt=1,
                do_classifier_free_guidance=True,
                negative_prompt=negative_prompt,
            )

            (prompt_embeds_c, _, _, _) = pipe.encode_prompt(
                [prompt_cloth],
                num_images_per_prompt=1,
                do_classifier_free_guidance=False,
                negative_prompt=[negative_prompt],
            )

            pose_t = tensor_transfrom(pose_img).unsqueeze(0).to(device=device, dtype=dtype)
            garm_t = tensor_transfrom(garm_img).unsqueeze(0).to(device=device, dtype=dtype)

            generator = torch.Generator(device).manual_seed(seed)

            images = pipe(
                prompt_embeds=prompt_embeds.to(device=device, dtype=dtype),
                negative_prompt_embeds=negative_prompt_embeds.to(device=device, dtype=dtype),
                pooled_prompt_embeds=pooled_prompt_embeds.to(device=device, dtype=dtype),
                negative_pooled_prompt_embeds=negative_pooled_prompt_embeds.to(device=device, dtype=dtype),
                num_inference_steps=denoise_steps,
                generator=generator,
                strength=strength,
                pose_img=pose_t,
                text_embeds_cloth=prompt_embeds_c.to(device=device, dtype=dtype),
                cloth=garm_t,
                mask_image=mask,
                image=human_img,
                height=1024,
                width=768,
                ip_adapter_image=garm_img.resize((768, 1024)),
                guidance_scale=guidance_scale,
            )[0]

    out_img = images[0]
    out_img_rs = out_img.resize(crop_size)
    human_img_orig.paste(out_img_rs, (int(left), int(top)))
    return human_img_orig


# =========================
# UI / CSS
# =========================
CUSTOM_CSS = """
footer {display:none !important;}
#api-info {display:none !important;}
div[class*="footer"] {display:none !important;}
button[aria-label="Settings"] {display:none !important;}

.feedback-box {
    border: 1px solid #e5e7eb;
    border-radius: 14px;
    padding: 12px 14px;
    background: #fafafa;
    margin-top: 10px;
}

.feedback-ok {
    border: 1px solid #b7ebc6;
    background: #f0fff4;
    color: #166534;
    border-radius: 12px;
    padding: 10px 12px;
    font-size: 14px;
    margin-top: 8px;
}

.feedback-idle {
    border: 1px dashed #d1d5db;
    background: #ffffff;
    color: #6b7280;
    border-radius: 12px;
    padding: 10px 12px;
    font-size: 14px;
    margin-top: 8px;
}
"""


# =========================
# UX example image
# =========================
UX_EXAMPLE_IMG_PATH = "assets/photo_2026-02-26_14-56-24.jpg"


def _load_ux_example_pil() -> Optional[Image.Image]:
    try:
        if UX_EXAMPLE_IMG_PATH and os.path.exists(UX_EXAMPLE_IMG_PATH):
            return Image.open(UX_EXAMPLE_IMG_PATH).convert("RGB")
    except Exception as e:
        print("UX example image load failed:", repr(e), flush=True)
    return None


_UX_EXAMPLE_PIL = _load_ux_example_pil()


def refresh_catalog(gender: str):
    ensure_garments_available()
    files = list_garments(gender=gender)
    items = build_gallery_items(files)
    status = f"✅ Каталог: {gender} ({len(files)})" if files else f"⚠️ Каталог пуст: {gender}"
    return items, files, None, status, "👕 Выберите одежду ниже"


def on_gallery_select(files_list: List[str], evt: gr.SelectData):
    if not files_list:
        return None, "⚠️ Каталог пуст"
    idx = int(evt.index) if evt.index is not None else 0
    idx = max(0, min(idx, len(files_list) - 1))
    return files_list[idx], "👕 Одежда выбрана"


# =========================
# Feedback storage
# =========================
FEEDBACK_DIR = "./feedback"
FEEDBACK_PATH = os.path.join(FEEDBACK_DIR, "feedback.jsonl")

FEEDBACK_REPO_ID = os.getenv("FEEDBACK_REPO_ID", "").strip()
FEEDBACK_REPO_TYPE = "dataset"
FEEDBACK_REPO_FILEPATH = "feedback/feedback.jsonl"


def _read_local_feedback_text() -> str:
    if not os.path.exists(FEEDBACK_PATH):
        return ""
    with open(FEEDBACK_PATH, "r", encoding="utf-8") as f:
        return f.read()


def _write_local_feedback_text(text: str) -> None:
    os.makedirs(FEEDBACK_DIR, exist_ok=True)
    with open(FEEDBACK_PATH, "w", encoding="utf-8") as f:
        f.write(text)


def _download_repo_feedback(api: HfApi, token: str) -> str:
    if not FEEDBACK_REPO_ID:
        return ""
    try:
        local_path = hf_hub_download(
            repo_id=FEEDBACK_REPO_ID,
            repo_type=FEEDBACK_REPO_TYPE,
            filename=FEEDBACK_REPO_FILEPATH,
            token=token,
        )
        with open(local_path, "r", encoding="utf-8") as f:
            return f.read()
    except Exception:
        return ""


def _upload_repo_feedback(api: HfApi, token: str, text: str) -> None:
    if not FEEDBACK_REPO_ID:
        raise RuntimeError("FEEDBACK_REPO_ID not set")

    os.makedirs(FEEDBACK_DIR, exist_ok=True)
    tmp_path = os.path.join(FEEDBACK_DIR, "_feedback_upload.jsonl")

    with open(tmp_path, "w", encoding="utf-8") as f:
        f.write(text)

    api.upload_file(
        path_or_fileobj=tmp_path,
        path_in_repo=FEEDBACK_REPO_FILEPATH,
        repo_id=FEEDBACK_REPO_ID,
        repo_type=FEEDBACK_REPO_TYPE,
        token=token,
        commit_message="Add try-on feedback",
    )


def _append_feedback_record(record: dict) -> None:
    line = json.dumps(record, ensure_ascii=False) + "\n"

    try:
        local_text = _read_local_feedback_text()
        local_text += line
        _write_local_feedback_text(local_text)
    except Exception as e:
        print("Feedback local write failed:", repr(e), flush=True)

    try:
        token = (os.getenv("HF_TOKEN", "").strip() or os.getenv("HUGGINGFACEHUB_API_TOKEN", "").strip())
        if not token:
            print("Feedback repo sync skipped: HF_TOKEN not set", flush=True)
            return

        if not FEEDBACK_REPO_ID:
            print("Feedback repo sync skipped: FEEDBACK_REPO_ID not set", flush=True)
            return

        api = HfApi()
        repo_text = _download_repo_feedback(api, token)
        repo_text += line
        _upload_repo_feedback(api, token, repo_text)
    except Exception as e:
        print("Feedback repo sync failed:", repr(e), flush=True)


def save_rating_feedback(is_like: bool, garment_name: str) -> None:
    record = {
        "timestamp": datetime.utcnow().isoformat(),
        "event": "rating",
        "like": bool(is_like),
        "garment": garment_name or "",
    }
    _append_feedback_record(record)


def save_comment_feedback(garment_name: str, comment: str) -> None:
    clean_comment = (comment or "").strip()
    if len(clean_comment) > 1500:
        clean_comment = clean_comment[:1500]

    record = {
        "timestamp": datetime.utcnow().isoformat(),
        "event": "comment",
        "garment": garment_name or "",
        "comment": clean_comment,
    }
    _append_feedback_record(record)


# =========================
# Feedback UI helpers
# =========================
def _rating_notice_idle_html():
    return """
    <div class="feedback-idle">
        Оцените результат: нажмите лайк или дизлайк.
    </div>
    """


def _comment_notice_idle_html():
    return """
    <div class="feedback-idle">
        При желании напишите комментарий и нажмите кнопку отправки.
    </div>
    """


def _rating_notice_ok_html(action_text: str):
    return f"""
    <div class="feedback-ok">
        ✅ Ваша оценка <b style="color:#166534;">{action_text}</b> сохранена.
    </div>
    """


def _comment_notice_ok_html():
    return """
    <div class="feedback-ok">
        ✅ Комментарий отправлен. Спасибо за обратную связь.
    </div>
    """


# =========================
# Feedback actions
# =========================
def submit_like_feedback(garment_name: str):
    if not garment_name:
        return "⚠️ Сначала выполните примерку и выберите одежду", _rating_notice_idle_html()

    try:
        save_rating_feedback(True, garment_name)
        return "✅ Оценка сохранена: «Нравится»", _rating_notice_ok_html("«Нравится»")
    except Exception as e:
        return (
            f"❌ Ошибка сохранения оценки: {type(e).__name__}: {str(e)[:200]}",
            _rating_notice_idle_html(),
        )


def submit_dislike_feedback(garment_name: str):
    if not garment_name:
        return "⚠️ Сначала выполните примерку и выберите одежду", _rating_notice_idle_html()

    try:
        save_rating_feedback(False, garment_name)
        return "✅ Оценка сохранена: «Не нравится»", _rating_notice_ok_html("«Не нравится»")
    except Exception as e:
        return (
            f"❌ Ошибка сохранения оценки: {type(e).__name__}: {str(e)[:200]}",
            _rating_notice_idle_html(),
        )


def submit_comment_feedback(garment_name: str, comment: str):
    clean_comment = (comment or "").strip()

    if not garment_name:
        return (
            "⚠️ Сначала выполните примерку и выберите одежду",
            _comment_notice_idle_html(),
            gr.update(value=comment),
        )

    if not clean_comment:
        return (
            "⚠️ Напишите комментарий перед отправкой",
            _comment_notice_idle_html(),
            gr.update(value=comment),
        )

    try:
        save_comment_feedback(garment_name, clean_comment)
        return (
            "✅ Комментарий отправлен",
            _comment_notice_ok_html(),
            gr.update(value=""),
        )
    except Exception as e:
        return (
            f"❌ Ошибка отправки комментария: {type(e).__name__}: {str(e)[:200]}",
            _comment_notice_idle_html(),
            gr.update(value=comment),
        )


# =========================
# Try-on UI
# =========================
def tryon_ui(person_pil, selected_filename):
    for msg in [
    "🧵 Анализируем посадку ткани…",
    "📏 Подбираем пропорции одежды…",
    "🧍 Определяем позу и положение тела…",
    "📐 Выравниваем геометрию одежды…",
    "🎨 Сохраняем цвет и фактуру ткани…",
    "🪡 Прорисовываем швы и детали…",
    "🧶 Адаптируем складки ткани…",
    "🧥 Корректируем посадку на фигуре…",
    "✨ Улучшаем освещение и тени…",
    "🔬 Уточняем текстуру материала…"    
    "🔍 Проверяем мелкие детали…",
    "🎯 Финальная корректировка результата…",
    "🌟 Последние штрихи…",    
    "🪄 Почти готово…",
        
]:
        yield (
            None,
            msg,
            gr.update(visible=False),
            gr.update(value=""),
            gr.update(value=_rating_notice_idle_html()),
            gr.update(value=_comment_notice_idle_html()),
        )
        time.sleep(2.3)

    ok, msg = allow_call(2.5)
    if not ok:
        yield (
            None,
            msg,
            gr.update(visible=False),
            gr.update(value=""),
            gr.update(value=_rating_notice_idle_html()),
            gr.update(value=_comment_notice_idle_html()),
        )
        return

    if person_pil is None:
        yield (
            None,
            "❌ Загрузите фото человека",
            gr.update(visible=False),
            gr.update(value=""),
            gr.update(value=_rating_notice_idle_html()),
            gr.update(value=_comment_notice_idle_html()),
        )
        return

    if not selected_filename:
        yield (
            None,
            "❌ Выберите одежду (клик по превью)",
            gr.update(visible=False),
            gr.update(value=""),
            gr.update(value=_rating_notice_idle_html()),
            gr.update(value=_comment_notice_idle_html()),
        )
        return

    garm = load_garment_pil(selected_filename)
    if garm is None:
        yield (
            None,
            "❌ Не удалось загрузить выбранную одежду",
            gr.update(visible=False),
            gr.update(value=""),
            gr.update(value=_rating_notice_idle_html()),
            gr.update(value=_comment_notice_idle_html()),
        )
        return

    try:
        out_img = start_tryon(human_pil=person_pil, garm_img=garm)
        yield (
            out_img,
            "✅ Готово — оцените результат и при желании оставьте комментарий",
            gr.update(visible=True),
            gr.update(value=""),
            gr.update(value=_rating_notice_idle_html()),
            gr.update(value=_comment_notice_idle_html()),
        )
    except Exception as e:
        yield (
            None,
            f"❌ Ошибка: {type(e).__name__}: {str(e)[:220]}",
            gr.update(visible=False),
            gr.update(value=""),
            gr.update(value=_rating_notice_idle_html()),
            gr.update(value=_comment_notice_idle_html()),
        )


# =========================
# Boot
# =========================
ensure_garments_available()
_default_gender = "Женская"
_initial_files = list_garments(gender=_default_gender)
_initial_items = build_gallery_items(_initial_files)

with gr.Blocks(title="Virtual Try-On Rendez-vous", css=CUSTOM_CSS) as demo:
    gr.Markdown("# Virtual Try-On Rendez-vous")

    garment_files_state = gr.State(_initial_files)
    selected_garment_state = gr.State(None)

    with gr.Row():
        with gr.Column():
            person = gr.Image(label="Фото человека", type="pil", height=420)

            gr.Markdown("""
    ### Какое фото подойдёт

    ✔ В полный рост или по пояс  
    ✔ Одежда по фигуре  
    ✔ Стоите прямо, смотрите в камеру  
    ✔ Руки и предметы не закрывают тело  
    ✔ Хороший свет, без резких теней  
    ✔ В кадре только вы
    """)

            gr.Image(
                value=_UX_EXAMPLE_PIL,
                label="",
                show_label=False,
                interactive=False,
                height=340,
                visible=bool(_UX_EXAMPLE_PIL),
            )

            gender = gr.Radio(
                choices=["Женская", "Мужская"],
                value=_default_gender,
                label="Раздел каталога",
            )

            selected_label = gr.Markdown("👕 Выберите одежду ниже")

            garment_gallery = gr.Gallery(
                label="Одежда для примерки",
                value=_initial_items,
                columns=4,
                height=340,
                allow_preview=True,
            )

            run = gr.Button("Примерить", variant="primary")
            status = gr.Textbox(value="Ожидание...", interactive=False, show_label=False)

        with gr.Column():
            out = gr.Image(label="Результат", type="pil", height=760)

            with gr.Column(visible=False) as feedback_box:
                gr.HTML('<div class="feedback-box">')

                gr.Markdown("### Оценка результата")
                with gr.Row():
                    like_btn = gr.Button("👍 Нравится")
                    dislike_btn = gr.Button("👎 Не нравится")
                rating_notice = gr.HTML(_rating_notice_idle_html())

                gr.Markdown("### Комментарий")
                feedback_comment = gr.Textbox(
                    label="",
                    placeholder="Напишите, что понравилось или что стоит улучшить...",
                    lines=3,
                    max_lines=6,
                    show_label=False,
                )
                submit_comment_btn = gr.Button("Отправить комментарий")
                comment_notice = gr.HTML(_comment_notice_idle_html())

                gr.HTML("</div>")

    gender.change(
        fn=refresh_catalog,
        inputs=[gender],
        outputs=[garment_gallery, garment_files_state, selected_garment_state, status, selected_label],
    )

    garment_gallery.select(
        fn=on_gallery_select,
        inputs=[garment_files_state],
        outputs=[selected_garment_state, selected_label],
    )

    run.click(
        fn=tryon_ui,
        inputs=[person, selected_garment_state],
        outputs=[out, status, feedback_box, feedback_comment, rating_notice, comment_notice],
        concurrency_limit=1,
    )

    like_btn.click(
        fn=submit_like_feedback,
        inputs=[selected_garment_state],
        outputs=[status, rating_notice],
        concurrency_limit=1,
    )

    dislike_btn.click(
        fn=submit_dislike_feedback,
        inputs=[selected_garment_state],
        outputs=[status, rating_notice],
        concurrency_limit=1,
    )

    submit_comment_btn.click(
        fn=submit_comment_feedback,
        inputs=[selected_garment_state, feedback_comment],
        outputs=[status, comment_notice, feedback_comment],
        concurrency_limit=1,
    )

demo.queue(max_size=20)

if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        max_threads=4,
        show_error=True,
        show_api=False,
    )