File size: 33,328 Bytes
200c08c
 
 
 
 
d8de9ec
db471df
fd3528a
200c08c
 
 
 
 
4cca039
200c08c
 
738751a
200c08c
 
 
 
 
 
fd3528a
 
 
 
 
 
 
 
 
 
 
 
 
200c08c
 
fd3528a
200c08c
fd3528a
200c08c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9583cc9
200c08c
94676a8
200c08c
 
 
94676a8
 
 
200c08c
 
 
 
9583cc9
 
 
 
 
db471df
9583cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db471df
9583cc9
db471df
9583cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db471df
9583cc9
db471df
9583cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db471df
9583cc9
db471df
9583cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db471df
9583cc9
db471df
9583cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db471df
4cca039
9583cc9
db471df
9583cc9
 
 
 
 
 
db471df
 
9583cc9
 
 
 
 
 
db471df
 
9583cc9
 
 
 
 
 
 
 
 
db471df
9583cc9
 
 
 
 
 
 
db471df
9583cc9
 
 
db471df
9583cc9
 
db471df
9583cc9
 
 
 
 
 
db471df
9583cc9
db471df
4cca039
200c08c
 
 
 
4cca039
200c08c
 
 
4cca039
200c08c
 
4cca039
 
200c08c
4cca039
 
 
200c08c
ed86e76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db471df
ed86e76
 
 
 
 
 
 
 
 
9583cc9
ed86e76
 
9583cc9
ed86e76
 
9583cc9
ed86e76
 
9583cc9
ed86e76
 
 
 
 
 
db471df
ed86e76
200c08c
 
 
 
 
 
 
4cca039
200c08c
 
9583cc9
200c08c
 
fd3528a
 
 
 
 
 
 
 
 
200c08c
17178dc
4cca039
 
200c08c
 
 
136fe2c
db471df
d07159b
 
 
 
 
 
 
db471df
d07159b
 
 
 
 
 
200c08c
d07159b
 
 
 
 
4cca039
d07159b
db471df
200c08c
d07159b
db471df
 
 
 
d07159b
 
94676a8
d07159b
db471df
 
 
d07159b
db471df
 
 
 
 
 
 
 
 
 
 
 
 
d07159b
 
94676a8
4cca039
d07159b
 
 
9583cc9
4cca039
 
200c08c
d07159b
9583cc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d07159b
ed86e76
 
 
200c08c
 
 
9583cc9
4cca039
d07159b
 
9583cc9
 
200c08c
4cca039
200c08c
d07159b
 
db471df
d07159b
9583cc9
d07159b
 
 
 
 
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

import os
import random
import warnings
import logging
import urllib.parse
from concurrent.futures import ThreadPoolExecutor
from fastapi import FastAPI, File, UploadFile, Form, HTTPException, Header
from fastapi.middleware.cors import CORSMiddleware
from PIL import Image
import io
import torch
import numpy as np
import cv2
from transformers import Owlv2Processor, Owlv2ForObjectDetection
from transformers import CLIPProcessor, CLIPModel

# --- AYARLAR ---
warnings.filterwarnings("ignore")
logging.getLogger("transformers").setLevel(logging.ERROR)

app = FastAPI()

# --- GÜVENLİK AYARLARI ---
# API Key - Gerçek uygulamada environment variable kullanın
API_KEY = os.getenv("PURESENSE_API_KEY", "ps_live_2024_secure_key_x7k9m")

# İzin verilen originler (CORS)
ALLOWED_ORIGINS = [
    "https://puresense.app",
    "capacitor://localhost",
    "http://localhost",
    "http://localhost:3000",
    "http://127.0.0.1",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
)

# --- MODELLERİ YÜKLE ---
print("⏳ Modeller Yükleniyor...")
device = "cpu"

# OWL-v2 (Sorun Tespiti)
owl_id = "google/owlv2-base-patch16-ensemble"
try:
    owl_processor = Owlv2Processor.from_pretrained(owl_id)
    owl_model = Owlv2ForObjectDetection.from_pretrained(owl_id).to(device)
except Exception as e:
    print(f"OWL Model Error: {e}")

# CLIP (Cilt Tipi)
clip_id = "openai/clip-vit-base-patch32"
try:
    clip_processor = CLIPProcessor.from_pretrained(clip_id)
    clip_model = CLIPModel.from_pretrained(clip_id).to(device)
except Exception as e:
    print(f"CLIP Model Error: {e}")

print("✅ Sunucu Hazır!")

# --- SÖZLÜKLER ---
TR_LABELS = {
    "acne": "Sivilce", "pimple": "Sivilce", "dark spot": "Leke",
    "deep wrinkles": "Kırışıklık", "oily skin": "Yağlanma",
    "dry flaky skin": "Kuruluk", "skin redness": "Kızarıklık",
    "peeling skin": "Deri Soyulması", "rough skin": "Pürüzlü",
    "whitehead pimple": "Beyaz Uçlu Sivilce", "red acne bumps": "Sivilce",
    "inflamed acne pimple": "Sivilce", "diffuse skin redness": "Yaygın Kızarıklık",
    "whitehead": "Sivilce"
}

CILT_TIPI_TR = {"YAĞLI": "Yağlı Cilt", "KURU": "Kuru Cilt", "NORMAL": "Normal Cilt", "KARMA": "Karma Cilt"}

# =============================================================================
# CURATED PRODUCT DATABASE - DİREKT ÜRÜN LİNKLERİ
# =============================================================================

CURATED_PRODUCTS = {
    "Sivilce": [
        # --- LA ROCHE-POSAY ---
        {
            "title": "La Roche-Posay Effaclar Duo+ 40ml",
            "image": "https://cdn.dsmcdn.com/ty1576/product/media/images/prod/QC/20241111/16/ca5a8d9f-6c61-3e55-840a-cd0cc7fd32e1/1_org_zoom.jpg",
            "price": "₺549",
            "link": "https://www.trendyol.com/la-roche-posay/effaclar-duo-akne-bakim-kremi-40-ml-p-4780892",
            "source": "Trendyol",
            "reason": "Sivilce ve akne izleri için en çok tercih edilen dermokozmetik ürün"
        },
        {
            "title": "La Roche-Posay Effaclar Jel 400ml",
            "image": "https://cdn.dsmcdn.com/ty1513/product/media/images/prod/QC/20241023/09/2f6e3a27-1de6-3064-b1f1-16fe13e65e99/1_org_zoom.jpg",
            "price": "₺489",
            "link": "https://www.trendyol.com/la-roche-posay/effaclar-temizleme-jeli-400-ml-p-4780856",
            "source": "Trendyol",
            "reason": "Yağlı ve akneye eğilimli ciltler için günlük temizleyici"
        },
        # --- THE ORDINARY ---
        {
            "title": "The Ordinary Niacinamide 10% + Zinc 1%",
            "image": "https://cdn.dsmcdn.com/ty1481/product/media/images/prod/QC/20241004/16/0d28df0b-ca9b-34e4-a2b9-c8a1e8d7b6a0/1_org_zoom.jpg",
            "price": "₺359",
            "link": "https://www.trendyol.com/the-ordinary/niacinamide-10-zinc-1-serum-30-ml-p-33960618",
            "source": "Trendyol",
            "reason": "Gözenekleri sıkılaştırır, sivilce oluşumunu azaltır"
        },
        {
            "title": "The Ordinary Salicylic Acid 2% Solution",
            "image": "https://cdn.dsmcdn.com/ty1378/product/media/images/prod/QC/20240715/15/1dc5f847-b5b5-3f52-b50c-2f0b0f1a4e73/1_org_zoom.jpg",
            "price": "₺289",
            "link": "https://www.trendyol.com/the-ordinary/salicylic-acid-2-solution-30-ml-p-34005981",
            "source": "Trendyol",
            "reason": "BHA içeriği ile gözenekleri derinlemesine temizler"
        },
        # --- COSRX ---
        {
            "title": "COSRX Acne Pimple Master Patch",
            "image": "https://cdn.dsmcdn.com/ty1335/product/media/images/prod/QC/20240607/10/5f0b5b80-4c1e-3e6a-b2f3-2c9f3a8d5e7b/1_org_zoom.jpg",
            "price": "₺179",
            "link": "https://www.trendyol.com/cosrx/acne-pimple-master-patch-24-adet-p-34217890",
            "source": "Trendyol",
            "reason": "Sivilceleri bir gecede kurutur, iz bırakmadan iyileştirir"
        },
        {
            "title": "COSRX BHA Blackhead Power Liquid",
            "image": "https://cdn.dsmcdn.com/ty1290/product/media/images/prod/QC/20240428/14/a3b2c1d0-1234-5678-90ab-cdef12345678/1_org_zoom.jpg",
            "price": "₺449",
            "link": "https://www.trendyol.com/cosrx/bha-blackhead-power-liquid-100-ml-p-34890123",
            "source": "Trendyol",
            "reason": "Siyah nokta ve tıkalı gözenekler için etkili çözüm"
        },
        # --- CERAVE ---
        {
            "title": "CeraVe SA Temizleyici 236ml",
            "image": "https://cdn.dsmcdn.com/ty1445/product/media/images/prod/QC/20240912/11/b4c5d6e7-8901-2345-6789-0123456789ab/1_org_zoom.jpg",
            "price": "₺399",
            "link": "https://www.trendyol.com/cerave/sa-puruzsuzlestirici-temizleyici-236-ml-p-127891234",
            "source": "Trendyol",
            "reason": "Salisilik asit ile nazik ama etkili temizlik"
        },
        # --- BIODERMA ---
        {
            "title": "Bioderma Sebium H2O 500ml",
            "image": "https://cdn.dsmcdn.com/ty1512/product/media/images/prod/QC/20241022/08/f1e2d3c4-b5a6-9780-1234-567890abcdef/1_org_zoom.jpg",
            "price": "₺379",
            "link": "https://www.trendyol.com/bioderma/sebium-h2o-misel-solusyon-500-ml-p-5678901",
            "source": "Trendyol",
            "reason": "Yağlı ve karma ciltler için misel temizleyici"
        },
        # --- HEPSIBURADA ---
        {
            "title": "Vichy Normaderm Phytosolution 50ml",
            "image": "https://productimages.hepsiburada.net/s/44/375-375/110000003629395.jpg",
            "price": "₺599",
            "link": "https://www.hepsiburada.com/vichy-normaderm-phytosolution-cift-etkili-bakim-50-ml-p-HBV00000O3LM1",
            "source": "Hepsiburada",
            "reason": "Çift etkili formül: Sivilceleri azaltır, cilt bariyerini onarır"
        },
        # --- WATSONS ---
        {
            "title": "Some By Mi AHA BHA PHA Toner",
            "image": "https://cdn.dsmcdn.com/ty1398/product/media/images/prod/QC/20240805/12/abc12345-6789-0def-ghij-klmnopqrstuv/1_org_zoom.jpg",
            "price": "₺329",
            "link": "https://www.trendyol.com/some-by-mi/aha-bha-pha-30-days-miracle-toner-150-ml-p-56781234",
            "source": "Trendyol",
            "reason": "30 günde mucize vaat eden Kore cilt bakımı"
        },
        # --- AMAZON ---
        {
            "title": "Paula's Choice 2% BHA Exfoliant",
            "image": "https://m.media-amazon.com/images/I/51Zy4U3kKjL._SL1000_.jpg",
            "price": "₺899",
            "link": "https://www.amazon.com.tr/Paulas-Choice-SKIN-PERFECTING-Exfoliant/dp/B00949CTQQ",
            "source": "Amazon",
            "reason": "Dünya çapında en çok satan BHA eksfoliyant"
        },
        {
            "title": "Neutrogena Spot Gel 15ml",
            "image": "https://m.media-amazon.com/images/I/61L8sG3dWiL._SL1000_.jpg",
            "price": "₺189",
            "link": "https://www.amazon.com.tr/Neutrogena-Visibly-Clear-Rapid-Treatment/dp/B0040GJN3K",
            "source": "Amazon",
            "reason": "Hızlı etkili sivilce tedavi jeli"
        },
    ],
    
    "Leke": [
        # --- C VİTAMİNİ SERUMLAR ---
        {
            "title": "The Ordinary Vitamin C Suspension 23%",
            "image": "https://cdn.dsmcdn.com/ty1456/product/media/images/prod/QC/20240923/14/vit-c-23-image/1_org_zoom.jpg",
            "price": "₺299",
            "link": "https://www.trendyol.com/the-ordinary/vitamin-c-suspension-23-ha-spheres-2-30ml-p-33960789",
            "source": "Trendyol",
            "reason": "Yüksek konsantrasyonlu C vitamini, lekeleri aydınlatır"
        },
        {
            "title": "La Roche-Posay Pure Vitamin C10",
            "image": "https://cdn.dsmcdn.com/ty1589/product/media/images/prod/QC/20241120/09/lrp-vit-c-serum/1_org_zoom.jpg",
            "price": "₺849",
            "link": "https://www.trendyol.com/la-roche-posay/pure-vitamin-c10-serum-30-ml-p-4780923",
            "source": "Trendyol",
            "reason": "Saf C vitamini ile leke karşıtı bakım"
        },
        {
            "title": "Kiehl's Clearly Corrective Dark Spot",
            "image": "https://cdn.dsmcdn.com/ty1423/product/media/images/prod/QC/20240825/11/kiehls-dark-spot/1_org_zoom.jpg",
            "price": "₺1.299",
            "link": "https://www.trendyol.com/kiehls/clearly-corrective-dark-spot-solution-30-ml-p-87654321",
            "source": "Trendyol",
            "reason": "Premium leke karşıtı serum, görünür sonuçlar"
        },
        # --- NİACİNAMİDE ---
        {
            "title": "The Inkey List Niacinamide",
            "image": "https://cdn.dsmcdn.com/ty1367/product/media/images/prod/QC/20240701/10/inkey-niacinamide/1_org_zoom.jpg",
            "price": "₺249",
            "link": "https://www.trendyol.com/the-inkey-list/niacinamide-serum-30-ml-p-45678901",
            "source": "Trendyol",
            "reason": "Cilt tonunu eşitler, lekeleri azaltır"
        },
        # --- ALPHA ARBUTIN ---
        {
            "title": "The Ordinary Alpha Arbutin 2%",
            "image": "https://cdn.dsmcdn.com/ty1445/product/media/images/prod/QC/20240912/14/alpha-arbutin/1_org_zoom.jpg",
            "price": "₺319",
            "link": "https://www.trendyol.com/the-ordinary/alpha-arbutin-2-ha-30-ml-p-33961234",
            "source": "Trendyol",
            "reason": "Melanin üretimini dengeleyerek lekeleri açar"
        },
        {
            "title": "Good Molecules Discoloration Serum",
            "image": "https://cdn.dsmcdn.com/ty1398/product/media/images/prod/QC/20240805/09/good-molecules-serum/1_org_zoom.jpg",
            "price": "₺389",
            "link": "https://www.trendyol.com/good-molecules/discoloration-correcting-serum-30-ml-p-56789012",
            "source": "Trendyol",
            "reason": "Traneksamik asit ile etkili leke giderici"
        },
        # --- GÜN KREMİ ---
        {
            "title": "Eucerin Anti-Pigment Gündüz Bakım SPF30",
            "image": "https://productimages.hepsiburada.net/s/54/375-375/110000044123456.jpg",
            "price": "₺649",
            "link": "https://www.hepsiburada.com/eucerin-anti-pigment-day-spf-30-50-ml-p-HBV00000QWERT",
            "source": "Hepsiburada",
            "reason": "Lekeleri azaltır ve güneşten korur"
        },
        {
            "title": "Avene D-Pigment Legere 30ml",
            "image": "https://productimages.hepsiburada.net/s/48/375-375/110000012345678.jpg",
            "price": "₺729",
            "link": "https://www.hepsiburada.com/avene-d-pigment-legere-30-ml-p-HBV00000ASDFG",
            "source": "Hepsiburada",
            "reason": "Hassas ciltler için leke karşıtı bakım"
        },
        # --- AMAZON ---
        {
            "title": "Murad Rapid Age Spot Serum",
            "image": "https://m.media-amazon.com/images/I/61dFgPqK8oL._SL1000_.jpg",
            "price": "₺1.199",
            "link": "https://www.amazon.com.tr/Murad-Rapid-Age-Spot-Correcting/dp/B002WTC5K2",
            "source": "Amazon",
            "reason": "Hızlı etkili leke karşıtı profesyonel serum"
        },
        {
            "title": "CeraVe Skin Renewing Vitamin C Serum",
            "image": "https://m.media-amazon.com/images/I/61XNGB8M7RL._SL1000_.jpg",
            "price": "₺549",
            "link": "https://www.amazon.com.tr/CeraVe-Vitamin-C-Serum-30ml/dp/B07PVNQF1R",
            "source": "Amazon",
            "reason": "Ceramid destekli C vitamini serumu"
        },
    ],
    
    "Kırışıklık": [
        # --- RETİNOL ---
        {
            "title": "The Ordinary Retinol 0.5% in Squalane",
            "image": "https://cdn.dsmcdn.com/ty1478/product/media/images/prod/QC/20241001/11/retinol-05/1_org_zoom.jpg",
            "price": "₺329",
            "link": "https://www.trendyol.com/the-ordinary/retinol-0-5-in-squalane-30-ml-p-33962345",
            "source": "Trendyol",
            "reason": "Kırışıklıkları azaltan altın standart retinol"
        },
        {
            "title": "La Roche-Posay Retinol B3 Serum",
            "image": "https://cdn.dsmcdn.com/ty1534/product/media/images/prod/QC/20241105/10/lrp-retinol-b3/1_org_zoom.jpg",
            "price": "₺899",
            "link": "https://www.trendyol.com/la-roche-posay/retinol-b3-anti-aging-serum-30-ml-p-4781234",
            "source": "Trendyol",
            "reason": "Dermatoloji onaylı anti-aging serum"
        },
        # --- PEPTİT ---
        {
            "title": "The Ordinary Buffet",
            "image": "https://cdn.dsmcdn.com/ty1412/product/media/images/prod/QC/20240815/14/buffet-serum/1_org_zoom.jpg",
            "price": "₺449",
            "link": "https://www.trendyol.com/the-ordinary/buffet-multi-technology-peptide-serum-30-ml-p-33963456",
            "source": "Trendyol",
            "reason": "Çoklu peptit formülü ile yaşlanma karşıtı"
        },
        {
            "title": "Olay Regenerist Retinol 24 Gece Kremi",
            "image": "https://cdn.dsmcdn.com/ty1356/product/media/images/prod/QC/20240620/09/olay-retinol/1_org_zoom.jpg",
            "price": "₺499",
            "link": "https://www.trendyol.com/olay/regenerist-retinol-24-gece-kremi-50-ml-p-67890123",
            "source": "Trendyol",
            "reason": "24 saat nemlendirme ve kırışıklık bakımı"
        },
        # --- HYALURONİK ASİT ---
        {
            "title": "Vichy Liftactiv Supreme Serum",
            "image": "https://productimages.hepsiburada.net/s/52/375-375/110000034567890.jpg",
            "price": "₺799",
            "link": "https://www.hepsiburada.com/vichy-liftactiv-supreme-serum-30-ml-p-HBV00000ZXCVB",
            "source": "Hepsiburada",
            "reason": "Hyaluronik asit ile dolgunlaştırıcı etki"
        },
        {
            "title": "Eucerin Hyaluron-Filler Gece Bakım",
            "image": "https://productimages.hepsiburada.net/s/49/375-375/110000023456789.jpg",
            "price": "₺679",
            "link": "https://www.hepsiburada.com/eucerin-hyaluron-filler-gece-kremi-50-ml-p-HBV00000MNBVC",
            "source": "Hepsiburada",
            "reason": "Kırışıklıkları doldurur, cildi yeniler"
        },
        # --- AMAZON ---
        {
            "title": "Neutrogena Rapid Wrinkle Repair",
            "image": "https://m.media-amazon.com/images/I/71aKxRHD6ZL._SL1500_.jpg",
            "price": "₺599",
            "link": "https://www.amazon.com.tr/Neutrogena-Rapid-Wrinkle-Repair-Retinol/dp/B004D24818",
            "source": "Amazon",
            "reason": "Retinol SA ile hızlı kırışıklık onarımı"
        },
        {
            "title": "RoC Retinol Correxion Deep Wrinkle",
            "image": "https://m.media-amazon.com/images/I/61Q9K8LQOFL._SL1000_.jpg",
            "price": "₺449",
            "link": "https://www.amazon.com.tr/RoC-Retinol-Correxion-Deep-Wrinkle/dp/B00027DMI8",
            "source": "Amazon",
            "reason": "Derin kırışıklıklar için güçlü formül"
        },
        {
            "title": "No7 Lift & Luminate Triple Action Serum",
            "image": "https://m.media-amazon.com/images/I/61wK8TqKnBL._SL1000_.jpg",
            "price": "₺549",
            "link": "https://www.amazon.com.tr/No7-Lift-Luminate-Triple-Action/dp/B00X5V4XCY",
            "source": "Amazon",
            "reason": "Üçlü etki: Sıkılaştırır, aydınlatır, pürüzsüzleştirir"
        },
    ],
    
    "Kuruluk": [
        # --- NEMLENDİRİCİLER ---
        {
            "title": "CeraVe Nemlendirici Krem 454g",
            "image": "https://cdn.dsmcdn.com/ty1523/product/media/images/prod/QC/20241030/11/cerave-cream/1_org_zoom.jpg",
            "price": "₺549",
            "link": "https://www.trendyol.com/cerave/nemlendirici-krem-454-g-p-127892345",
            "source": "Trendyol",
            "reason": "Ceramid içerikli yoğun nemlendirici, kuru ciltler için ideal"
        },
        {
            "title": "La Roche-Posay Lipikar Baume AP+M",
            "image": "https://cdn.dsmcdn.com/ty1567/product/media/images/prod/QC/20241112/14/lipikar-baume/1_org_zoom.jpg",
            "price": "₺599",
            "link": "https://www.trendyol.com/la-roche-posay/lipikar-baume-ap-m-400-ml-p-4782345",
            "source": "Trendyol",
            "reason": "Aşırı kuru ve atopik ciltler için yoğun bakım"
        },
        {
            "title": "The Ordinary Hyaluronic Acid 2% + B5",
            "image": "https://cdn.dsmcdn.com/ty1489/product/media/images/prod/QC/20241010/09/ha-b5/1_org_zoom.jpg",
            "price": "₺249",
            "link": "https://www.trendyol.com/the-ordinary/hyaluronic-acid-2-b5-30-ml-p-33964567",
            "source": "Trendyol",
            "reason": "Cildi derinlemesine nemlendirir"
        },
        {
            "title": "Avene Hydrance Aqua Gel 50ml",
            "image": "https://cdn.dsmcdn.com/ty1434/product/media/images/prod/QC/20240905/10/avene-hydrance/1_org_zoom.jpg",
            "price": "₺479",
            "link": "https://www.trendyol.com/avene/hydrance-aqua-gel-50-ml-p-23456789",
            "source": "Trendyol",
            "reason": "Hafif formül, yoğun nemlendirme"
        },
        # --- HEPSIBURADA ---
        {
            "title": "Bioderma Atoderm Intensive Baume 500ml",
            "image": "https://productimages.hepsiburada.net/s/51/375-375/110000031234567.jpg",
            "price": "₺529",
            "link": "https://www.hepsiburada.com/bioderma-atoderm-intensive-baume-500-ml-p-HBV00000QAZWS",
            "source": "Hepsiburada",
            "reason": "Yoğun nemlendirici, cilt bariyerini onarır"
        },
        {
            "title": "Uriage Xemose Lipid Replenishing Cream",
            "image": "https://productimages.hepsiburada.net/s/47/375-375/110000009876543.jpg",
            "price": "₺449",
            "link": "https://www.hepsiburada.com/uriage-xemose-cream-400-ml-p-HBV00000EDCRF",
            "source": "Hepsiburada",
            "reason": "Çok kuru ciltler için lipid doldurucu krem"
        },
        # --- AMAZON ---
        {
            "title": "First Aid Beauty Ultra Repair Cream",
            "image": "https://m.media-amazon.com/images/I/61K0xmJHzXL._SL1000_.jpg",
            "price": "₺699",
            "link": "https://www.amazon.com.tr/First-Aid-Beauty-Ultra-Repair/dp/B0049PAEOS",
            "source": "Amazon",
            "reason": "Anında rahatlatıcı yoğun nemlendirici"
        },
        {
            "title": "Weleda Skin Food Original 75ml",
            "image": "https://m.media-amazon.com/images/I/61jqL1cPQOL._SL1000_.jpg",
            "price": "₺329",
            "link": "https://www.amazon.com.tr/Weleda-Skin-Food-Original-75ml/dp/B000ORV3NC",
            "source": "Amazon",
            "reason": "Doğal içerikli kuru cilt kurtarıcısı"
        },
    ],
    
    "Kızarıklık": [
        {
            "title": "La Roche-Posay Rosaliac AR Intense",
            "image": "https://cdn.dsmcdn.com/ty1545/product/media/images/prod/QC/20241108/11/rosaliac/1_org_zoom.jpg",
            "price": "₺549",
            "link": "https://www.trendyol.com/la-roche-posay/rosaliac-ar-intense-40-ml-p-4783456",
            "source": "Trendyol",
            "reason": "Kızarıklık ve rosacea için özel formül"
        },
        {
            "title": "Avene Antirougeurs Calm Soothing Mask",
            "image": "https://cdn.dsmcdn.com/ty1412/product/media/images/prod/QC/20240815/12/avene-mask/1_org_zoom.jpg",
            "price": "₺389",
            "link": "https://www.trendyol.com/avene/antirougeurs-calm-mask-50-ml-p-34567890",
            "source": "Trendyol",
            "reason": "Yatıştırıcı maske, anında rahatlama"
        },
        {
            "title": "The Ordinary Azelaic Acid Suspension 10%",
            "image": "https://cdn.dsmcdn.com/ty1467/product/media/images/prod/QC/20240928/10/azelaic/1_org_zoom.jpg",
            "price": "₺279",
            "link": "https://www.trendyol.com/the-ordinary/azelaic-acid-suspension-10-30-ml-p-33965678",
            "source": "Trendyol",
            "reason": "Kızarıklık ve sivilce izleri için etkili"
        },
        {
            "title": "Bioderma Sensibio AR Creme 40ml",
            "image": "https://productimages.hepsiburada.net/s/53/375-375/110000041234567.jpg",
            "price": "₺429",
            "link": "https://www.hepsiburada.com/bioderma-sensibio-ar-creme-40-ml-p-HBV00000TGBNM",
            "source": "Hepsiburada",
            "reason": "Hassas ve kızarık ciltler için günlük bakım"
        },
        {
            "title": "Eucerin AntiRedness Concealing Day Care SPF25",
            "image": "https://productimages.hepsiburada.net/s/50/375-375/110000028765432.jpg",
            "price": "₺549",
            "link": "https://www.hepsiburada.com/eucerin-antiredness-concealing-day-care-50-ml-p-HBV00000YHNUJ",
            "source": "Hepsiburada",
            "reason": "Kızarıklığı kapatır ve güneşten korur"
        },
        # --- AMAZON ---
        {
            "title": "Dr. Jart+ Cicapair Tiger Grass Cream",
            "image": "https://m.media-amazon.com/images/I/61dCJSy9c2L._SL1000_.jpg",
            "price": "₺799",
            "link": "https://www.amazon.com.tr/Dr-Jart-Cicapair-Tiger-Grass/dp/B01LWTT5ZW",
            "source": "Amazon",
            "reason": "Centella ile kızarıklık giderici Kore bakımı"
        },
    ],
    
    "Yaygın Kızarıklık": [
        {
            "title": "La Roche-Posay Rosaliac UV Riche SPF15",
            "image": "https://cdn.dsmcdn.com/ty1534/product/media/images/prod/QC/20241105/09/rosaliac-uv/1_org_zoom.jpg",
            "price": "₺499",
            "link": "https://www.trendyol.com/la-roche-posay/rosaliac-uv-riche-40-ml-p-4784567",
            "source": "Trendyol",
            "reason": "Rosacea için SPF korumaalı günlük bakım"
        },
        {
            "title": "Avene Antirougeurs Fort Concentrate",
            "image": "https://cdn.dsmcdn.com/ty1423/product/media/images/prod/QC/20240825/10/avene-fort/1_org_zoom.jpg",
            "price": "₺459",
            "link": "https://www.trendyol.com/avene/antirougeurs-fort-30-ml-p-45678012",
            "source": "Trendyol",
            "reason": "Yoğun kızarıklık için konsantre bakım"
        },
        {
            "title": "Paula's Choice Calm Redness Relief Moisturizer",
            "image": "https://m.media-amazon.com/images/I/51Y8yG9GLOL._SL1000_.jpg",
            "price": "₺649",
            "link": "https://www.amazon.com.tr/Paulas-Choice-Redness-Relief-Moisturizer/dp/B00949CTAS",
            "source": "Amazon",
            "reason": "Hassas, kızarık ciltler için sakinleştirici nemlendirici"
        },
    ],
}

# =============================================================================
# HELPER FUNCTIONS
# =============================================================================

def get_products_for_issue(issue, skin_type_code, limit=15):
    """Get curated products for a specific issue"""
    products = CURATED_PRODUCTS.get(issue, [])
    
    # Shuffle to show variety
    shuffled = products.copy()
    random.shuffle(shuffled)
    
    # Add skin type specific message
    skin_type_text = CILT_TIPI_TR.get(skin_type_code, "")
    
    result = []
    for p in shuffled[:limit]:
        product = p.copy()
        # Add personalized recommendation
        product["recommendation"] = f"{skin_type_text} için önerilen: {p['reason']}"
        result.append(product)
    
    return result

# --- KALİTE KONTROL ---
def check_image_quality(image_bytes):
    try:
        nparr = np.frombuffer(image_bytes, np.uint8)
        img_cv = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        if img_cv is None: return True, "Görüntü okunamadı."
        
        gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
        laplacian_var = cv2.Laplacian(gray, cv2.CV_64F).var()
        if laplacian_var < 50: return False, "Görüntü bulanık."
        
        mean_brightness = np.mean(gray)
        if mean_brightness < 40: return False, "Ortam çok karanlık."
        if mean_brightness > 220: return False, "Çok fazla ışık var."
        
        return True, "Uygun"
    except:
        return True, "Kontrol atlandı"

# --- DYNAMIC ROUTINE GENERATOR ---
def generate_dynamic_routine(skin_type_code, issues):
    morning = ["Yüzünü ılık suyla yıka"]
    evening = ["Makyajını ve kirleri derinlemesine temizle"]
    
    if "YAĞLI" in skin_type_code:
        morning.append("Arındırıcı jel temizleyici kullan")
        morning.append("Yağsız, su bazlı nemlendirici sür")
        evening.append("Salisilik asit içeren temizleyici ile yıka")
    elif "KURU" in skin_type_code:
        morning.append("Nazik, köpürmeyen temizleyici kullan")
        morning.append("Yoğun nemlendirici veya Hyaluronik asit serumu uygula")
        evening.append("Temizleme sütü ile nazikçe temizle")
    elif "KARMA" in skin_type_code:
        morning.append("Dengeleyici köpük temizleyici kullan")
        morning.append("T bölgesine matlaştırıcı, yanaklara nemlendirici sür")
    else:
        morning.append("Nazik temizleme jeli kullan")
        morning.append("Hafif yapılı nemlendirici uygula")

    added_steps = 0
    unique_issues = list(set(issues))
    
    for issue in unique_issues:
        if added_steps >= 3: break
        issue_lower = issue.lower()
        if "sivilce" in issue_lower:
            evening.insert(1, "Akne karşıtı tonik veya serum kullan (Lokal uygulama)")
            added_steps += 1
        elif "kırışıklık" in issue_lower:
            evening.append("Retinol veya Peptit içerikli serum kullan")
            added_steps += 1
        elif "leke" in issue_lower:
            morning.insert(2, "C Vitamini serumu ile leke görünümünü azalt")
            added_steps += 1
        elif "kızarıklık" in issue_lower:
            morning.append("Yatıştırıcı (Niacinamide/Aloe Vera) serum kullan")
            added_steps += 1
            
    morning.append("Güneş kremi (SPF 50) ile rutini tamamla (En önemlisi!)")
    evening.append("Gece kremi ile cildini yenilenmeye bırak")
    
    return {"morning": morning, "evening": evening}

def get_skin_type(image):
    try:
        prompts = ["extremely oily shiny skin", "very dry flaky skin", "normal skin", "combination skin"]
        labels = ["YAĞLI", "KURU", "NORMAL", "KARMA"]
        inputs = clip_processor(text=prompts, images=image, return_tensors="pt", padding=True).to(device)
        with torch.no_grad(): probs = clip_model(**inputs).logits_per_image.softmax(dim=1)
        return labels[torch.max(probs, 1).indices.item()]
    except: return "KARMA"

@app.get("/")
def home(): return {"status": "Pure Sense API v10 (Curated Products)"}

@app.post("/analyze")
async def analyze_skin(
    file: UploadFile = File(...), 
    is_premium: bool = Form(False),
    x_api_key: str = Header(None, alias="X-API-Key")
):
    # API Key doğrulaması
    if x_api_key != API_KEY:
        raise HTTPException(status_code=401, detail="Geçersiz veya eksik API anahtarı")
    
    contents = await file.read()
    
    is_valid, msg = check_image_quality(contents)
    if not is_valid: return {"error": True, "message": msg}

    try:
        image = Image.open(io.BytesIO(contents)).convert("RGB")
        
        # Optimize: Resize large images
        max_size = 640
        if max(image.size) > max_size:
            ratio = max_size / max(image.size)
            new_size = (int(image.size[0] * ratio), int(image.size[1] * ratio))
            image = image.resize(new_size, Image.Resampling.LANCZOS)

        # A. Cilt Tipi (CLIP)
        skin_type_code = "KARMA"
        try:
            skin_type_code = get_skin_type(image)
        except Exception as e:
            print(f"CLIP Error: {e}")

        # B. Sorun Tespiti (OWL-v2)
        detections = []
        issues_found = []
        try:
            text_queries = [["inflamed acne pimple", "whitehead", "dark spot", "diffuse skin redness", "dry flaky skin", "deep wrinkles"]]
            inputs = owl_processor(text=text_queries, images=image, return_tensors="pt").to(device)
            with torch.no_grad(): outputs = owl_model(**inputs)
            
            target_sizes = torch.Tensor([image.size[::-1]])
            results = owl_processor.post_process_object_detection(outputs=outputs, target_sizes=target_sizes, threshold=0.01)[0]
            
            unique_labels = []
            category_scores = {}
            total_score_all = 0
            temp_detections = []

            for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
                lbl_en = text_queries[0][label]
                conf = score.item()
                
                if lbl_en == "deep wrinkles" and conf < 0.20: continue
                if lbl_en in ["inflamed acne pimple", "whitehead", "red acne bumps", "acne"] and conf < 0.12: continue
                if conf < 0.10: continue
                
                lbl_tr = TR_LABELS.get(lbl_en, lbl_en)
                category_scores[lbl_tr] = category_scores.get(lbl_tr, 0) + conf
                total_score_all += conf
                temp_detections.append({"label": lbl_tr, "box": box})
                if lbl_tr not in unique_labels: unique_labels.append(lbl_tr)
            
            for item in temp_detections:
                lbl = item["label"]
                cat_percentage = (category_scores[lbl] / total_score_all) * 100 if total_score_all > 0 else 0
                detections.append({
                    "label": lbl,
                    "confidence": round(cat_percentage, 1),
                    "box": [int(i) for i in item["box"].tolist()]
                })
                
            issues_found = unique_labels

        except Exception as e:
             print(f"OWL Error: {e}")
        
        # Generate Products from CURATED DATABASE
        skin_type_text = CILT_TIPI_TR.get(skin_type_code, "Hassas Cilt")
        prescriptions = []
        
        if issues_found:
            for issue in issues_found:
                products = get_products_for_issue(issue, skin_type_code, limit=15)
                if products:
                    prescriptions.append({
                        "title": f"✨ {issue} için Önerilen Ürünler",
                        "subtitle": f"{skin_type_text} tipine uygun, uzman seçimi ürünler",
                        "products": products
                    })
        else:
            # Default products for general skin care
            prescriptions.append({
                "title": "✨ Genel Cilt Bakımı Önerileri",
                "subtitle": f"{skin_type_text} için temel bakım ürünleri",
                "products": get_products_for_issue("Kuruluk" if "KURU" in skin_type_code else "Sivilce", skin_type_code, limit=10)
            })

        # Generate Dynamic Routine
        daily_routine = generate_dynamic_routine(skin_type_code, issues_found)
        
        return {
            "error": False,
            "skin_type": skin_type_code,
            "skin_type_text": skin_type_text,
            "detections": detections,
            "prescriptions": prescriptions, 
            "daily_routine": daily_routine,
            "is_premium_response": is_premium,
            "message": f"Cildini analiz ettik! {skin_type_text} tipine sahipsin. Aşağıdaki ürünleri senin için seçtik."
        }

    except Exception as e:
        print(f"Critical Error: {e}")
        return {
             "error": False,
             "skin_type": "KARMA",
             "skin_type_text": "Karma Cilt",
             "detections": [],
             "prescriptions": [],
             "daily_routine": generate_dynamic_routine("KARMA", []),
             "message": "Analiz sırasında bir yoğunluk oldu, varsayılan rutin oluşturuldu."
        }