File size: 11,412 Bytes
f3350ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from pathlib import Path
from typing import Optional

import chromadb
from groq import Groq
from sentence_transformers import SentenceTransformer

CHROMA_DIR = Path(__file__).parent / "chroma_db"
COLLECTION_NAME = "skincare_products"

_model: Optional[SentenceTransformer] = None
_collection = None

ROUTINE_STEPS = {
    "matin": ["cleanser", "toner", "serum", "moisturizer"],
    "soir":  ["cleanser", "serum", "moisturizer"],
}
SKIN_RULES = {
    "oily": {
        "avoid": ["oil", "heavy", "comedogenic"],
        "prefer": ["oil-free", "non-comedogenic", "light", "gel"],
    },
    "dry": {
        "avoid": ["alcohol"],
        "prefer": ["hydrating", "ceramides", "rich"],
    }
}

def _get_model() -> SentenceTransformer:
    global _model
    if _model is None:
        _model = SentenceTransformer("all-MiniLM-L6-v2")
    return _model


def _get_collection():
    global _collection
    if _collection is None:
        client = chromadb.PersistentClient(path=str(CHROMA_DIR))
        _collection = client.get_collection(COLLECTION_NAME)
    return _collection


def _build_query(skin_type: str, acne: bool, preferences: dict) -> str:
    parts = [f"skincare product for {skin_type} skin"]
    if acne:
        parts.append("acne-prone")
    if pt := preferences.get("product_type"):
        parts.append(pt)
    for f in preferences.get("formulation", []):
        parts.append(f)
    if "french" in preferences.get("origin", []):
        parts.append("French brand")
    return ", ".join(parts)


def _build_where(preferences: dict) -> Optional[dict]:
    conditions = []
    for flag, key in [("vegan", "is_vegan"), ("clean", "is_clean"), ("bio", "is_bio")]:
        if flag in preferences.get("formulation", []):
            conditions.append({key: {"$eq": True}})
    if "french" in preferences.get("origin", []):
        conditions.append({"is_french": {"$eq": True}})
    if (pb := preferences.get("price_band")) and pb not in ("any", None):
        conditions.append({"price_band": {"$eq": pb}})
    if not conditions:
        return None
    if len(conditions) == 1:
        return conditions[0]
    return {"$and": conditions}


def _query(query_text: str, where: Optional[dict], n_results: int = 5) -> dict:
    collection = _get_collection()
    model      = _get_model()  # ← ton SentenceTransformer, enfin utilisé

    embedding = model.encode(query_text).tolist()  # même modèle qu'ingest.py

    try:
        kwargs: dict = {
            "query_embeddings": [embedding],  # ← vecteur, plus query_texts
            "n_results": n_results,
        }
        if where:
            kwargs["where"] = where
        return collection.query(**kwargs)
    except Exception:
        return {"ids": [[]], "documents": [[]], "metadatas": [[]]}
    

def _generate_explanation(product_doc: str, skin_type: str, acne: bool, preferences: dict) -> str:
    prefs = []
    for f in preferences.get("formulation", []):
        prefs.append(f)
    if "french" in preferences.get("origin", []):
        prefs.append("marque française")
    if pt := preferences.get("product_type"):
        prefs.append(f"type : {pt}")
    if pb := preferences.get("price_band"):
        prefs.append(f"budget : {pb}")

    profile = f"peau {skin_type}"
    if acne:
        profile += ", tendance acnéique"
    if prefs:
        profile += f", préférences : {', '.join(prefs)}"

    client = Groq(api_key=os.environ["GROQ_API_KEY"])
    response = client.chat.completions.create(
        model="llama-3.3-70b-versatile",
        messages=[
            {
                "role": "system",
                "content": (
                    "Tu es un expert en soins de la peau. "
                    "En 2 à 3 phrases courtes en français, explique pourquoi ce produit "
                    "est adapté au profil de l'utilisateur. Sois précis et bienveillant. "
                ),
            },
            {
                "role": "user",
                "content": f"Profil : {profile}\n\nProduit : {product_doc}",
            },
        ],
        max_tokens=350,
    )
    return response.choices[0].message.content

def routine_with_llm(routine: dict, skin_type: str, acne: bool) -> str:
    import os
    from groq import Groq

    client = Groq(api_key=os.environ["GROQ_API_KEY"])

    # 1. FIX: On boucle sur la 'routine' envoyée, pas sur le dictionnaire brut ROUTINE_STEPS
    routine_text = ""
    for moment, steps in routine.items():
        routine_text += f"\n{moment.upper()}:\n"
        for step in steps:
            if step["product_name"]:
                routine_text += f"- {step['etape']}: {step['product_name']} ({step['brand']})\n"
            else:
                routine_text += f"- {step['etape']}: Aucun produit\n"

    profile = f"peau {skin_type}"
    if acne:
        profile += ", tendance acnéique"

    response = client.chat.completions.create(
        model="llama-3.3-70b-versatile",
        messages=[
            {
                "role": "system",
                "content": (
                    "Tu es un influenceur beauté expert en skincare. "
                    "Propose ta routine skincare en suivant la routine skincare qui t'a été fournie. "
                    "1. Verifie que le produit recommandé est adapté et si c'est le cas propose le dans ta routine"
                    "2. Propose un produit adapte au resultat du type de peau. "
                    "3. Explique avec enthousiasme et brievement le rôle de chaque produit. "
                    "Réponds en français avec un ton chaleureux. "
                    "CRUCIAL : Tu dois ABSOLUMENT utiliser la syntaxe Markdown suivante pour structurer ta réponse.\n\n"
                    "Format OBLIGATOIRE:\n"
                    "Coucou ! Voici ta routine sur-mesure ✨ :\n\n"
                    "### 🌞 Matin\n"
                    "- **[product_type]** :[Nom du produit] [Ton explication...]\n\n"
                    "### 🌙 Soir\n"
                    "- **[product_type]** : [Nom du produit][Ton explication...]\n"
                    "J'espère que cette routine te conviendra 😎!"
                ),
            },
            {
                "role": "user",
                "content": f"Profil: {profile}\n\nRoutine exacte à présenter:\n{routine_text}",
            },
        ],
        max_tokens=550,
    )

    return response.choices[0].message.content


def is_compatible(meta: dict, skin_type: str) -> bool:
    """Vérifie que le produit ne contient pas d'ingrédients déconseillés."""
    rules = SKIN_RULES.get(skin_type, {})
    name  = meta.get("name", "").lower()
    return not any(word in name for word in rules.get("avoid", []))


# 2. FIX: Il FAUT garder cette fonction dé-commentée, c'est elle qui interroge ChromaDB !
def _build_routine_steps(
    skin_type: str,
    acne: bool,
    main_product: dict,
    preferences: dict
) -> dict:

    routine = {}

    for moment, steps in ROUTINE_STEPS.items():
        routine[moment] = []

        for step in steps:
            # Produit principal = on prend direct
            if main_product.get("product_type") == step:
                routine[moment].append({
                    "etape":         step,
                    "product_name":  main_product["product_name"],
                    "brand":         main_product["brand"],
                    "price_display": main_product["price_display"],
                    "is_vegan":      main_product["is_vegan"],
                    "is_clean":      main_product["is_clean"],
                    "is_main":       True,
                })
                continue

            # Sinon -> chercher un produit
            query = f"{step} pour peau {skin_type}"
            if acne and step in ("serum", "cleanser", "exfoliant"):
                query += " acnéique"

            if skin_type == "oily" and step == "serum":
                query += " oil-free serum gel"
            if skin_type == "oily" and step == "moisturizer":
                query += " lightweight oil-free gel moisturizer"
            if step == "toner":
                query += " toner astringent niacinamide"
            if step == "exfoliant":
                if acne:
                    query += " salicylic acid bha exfoliant" 

            where = {"product_type": {"$eq": step}}
            
            results = _query(query, where, n_results=5)

            if results["ids"][0]:
                candidates = results["metadatas"][0]
                chosen = None
                for m in candidates:
                    if is_compatible(m, skin_type):
                        chosen = m
                        break

                if not chosen:
                    chosen = candidates[0]
                    
                routine[moment].append({
                    "etape":         step,
                    "product_name":  chosen["name"],
                    "brand":         chosen["brand"],
                    "price_display": f"{chosen['price_eur']}€" if chosen["price_eur"] > 0 else "",
                    "is_vegan":      chosen["is_vegan"],
                    "is_clean":      chosen["is_clean"],
                    "is_main":       False,
                })
            else:
                routine[moment].append({
                    "etape":         step,
                    "product_name":  None,
                    "brand":         None,
                    "is_main":       False,
                })

    return routine


def recommend(skin_type: str, acne: bool, preferences: dict) -> dict:
    query_text = _build_query(skin_type, acne, preferences)
    where      = _build_where(preferences)

    results = _query(query_text, where, n_results=5)

    if not results["ids"][0] and where:
        results = _query(query_text, None, n_results=5)

    if not results["ids"][0]:
        results = _query(query_text, None, n_results=5)

    if not results["ids"][0]:
        return {"error": "Aucun produit trouvé"}

    meta = results["metadatas"][0][0]
    doc  = results["documents"][0][0]

    main_product_dict = {
        "product_name":  meta["name"],
        "brand":         meta["brand"],
        "product_type":  meta["product_type"],
        "price_display": f"{meta['price_eur']}€" if meta["price_eur"] > 0 else "",
        "is_vegan":      meta["is_vegan"],
        "is_clean":      meta["is_clean"],
    }

    # 3. FIX: On dé-commente la création de la routine !
    routine_complete = _build_routine_steps(skin_type, acne, main_product_dict, preferences)
    
    # 4. FIX: On passe bien `routine_complete` à l'influenceur LLM
    validated_routine = routine_with_llm(
        routine=routine_complete,
        skin_type=skin_type,
        acne=acne
    )

    explanation = _generate_explanation(
        doc,
        skin_type,
        acne,
        preferences
    )
    
    return {
        "product_name":  meta["name"],
        "brand":         meta["brand"],
        "product_type":  meta["product_type"],
        "price_display": f"{meta['price_eur']}€" if meta["price_eur"] > 0 else "",
        "source":        meta["source"],
        "is_french":     meta["is_french"],
        "is_vegan":      meta["is_vegan"],
        "is_clean":      meta["is_clean"],
        "explanation":   explanation,
        "routine":       routine_complete,
        "routine_validated": validated_routine
    }