fffiloni commited on
Commit
fe45d39
·
verified ·
1 Parent(s): 79106ac

Introduce real perfume recommendations

Browse files
Files changed (1) hide show
  1. app.py +106 -30
app.py CHANGED
@@ -70,36 +70,28 @@ You must always respond using the following structure:
70
  ---
71
  Perfume Name:
72
  An original, evocative, and unique name — in French or English.
73
-
74
  Tagline:
75
  A short, poetic sentence — like a perfume advertisement hook.
76
-
77
  Poetic Olfactory Description:
78
  A freeform and expressive description of the scent ambiance evoked by the scene. Use rich sensory, emotional, and metaphorical language. Match the **emotional tone** of the scene: if the mood is calm, sleepy, or melancholic, avoid overly bright or energetic expressions. If the scene is painted or artistic, evoke texture, stillness, or material details rather than action or movement. Be subtle and precise.
79
  **Important:** Any scents, herbs, or natural elements mentioned here must be consistent with the scene’s setting. Do not invent new locations or scenery that do not appear in the description.
80
-
81
  Olfactory Pyramid (technical):
82
  - Top Notes:
83
  List 3–4 real, concrete scent materials that would be perceived first. These must be plausible fragrance ingredients (e.g. herbs, resins, citrus peels, spices, aldehydes, etc.). Pick notes that reflect the **real mood, climate, and setting** of the scene. Do not add locations or elements that don’t appear in the scene. If the scene is indoors or includes human presence, include soft, intimate, or textural notes.
84
-
85
  - Heart Notes:
86
  List 3–4 real fragrance elements that give body and soul to the perfume. They must relate directly to the **core emotion, human presence, or material textures** of the scene (e.g. warm fabric, skin, dry flowers, books, wood, canvas). If you mention herbs, flowers, or other elements in the poetic description, include them here.
87
-
88
  - Base Notes:
89
  List 3–4 real, longer-lasting ingredients such as woods, musks, resins, or earthy accords. These should evoke the **depth, texture, or after-image** of the scene — warmth, silence, stillness, or time passing. Avoid generic bases unless they fit the mood. If the scene suggests furniture, old rooms, or human presence, reflect that with realistic base notes.
90
-
91
  Consistency Rule:
92
  The top, heart, and base notes must not introduce new ideas, plants, or places that were not in the poetic description or the scene. Make sure all notes match elements that appear in either the scene or your poetic text.
93
-
94
  General Atmosphere:
95
- Summarize the fragrance’s evolution and overall emotional impression. Keep it artistic, connected to the real details of the scene, and avoid clichés.
96
-
97
  Image Description (for marketing visuals):
98
  Describe an imagined marketing image that captures the perfume’s essence.
99
  Begin by describing a clear, modern perfume bottle as the main and visually dominant subject.
100
- The bottle must be obviously recognizable as a perfume bottle — featuring a sprayer or atomizer, an elegant cap, and a refined fragrance label. The label must clearly display the exact Perfume Name generated in this output, written exactly as it appears, along with a subtle, elegant mention of the imaginary luxury brand FILONI’S.” The brand name should appear in a smaller, complementary font style, placed above or below the Perfume Name to enhance the overall design without overpowering it.
101
  Do not use placeholder text like “Perfume Name” — always use the actual fragrance name exactly as you have suggested above.
102
- Important: If the input scene description includes human characters, narrative details, or historical references, do not depict them literally. Instead, translate these elements into abstract design cues, subtle decorative details, or soft textures on the bottle or in the minimal background. The only clear subject must be the perfume bottle itself (with optional small natural ingredients). Do not show people, animals, narrative scenes, or explicit props unrelated to the bottle design.
103
  Describe the bottle’s shape, glass texture, cap, and label in fine detail. The glass may have an elegant frosted or matte finish, subtle etching or engraving (such as delicate floral or botanical motifs), or soft decorative elements that evoke refinement and sophistication while remaining tasteful and minimal.
104
  Do not describe containers that look like liquor bottles, flower vases, or fantasy potion bottles.
105
  Do not add narrative illustrations, characters, or storytelling scenes on the bottle — only subtle, abstract decorative details that highlight a luxury perfume aesthetic.
@@ -108,17 +100,16 @@ The bottle must occupy most of the image frame and appear in sharp focus and fin
108
  Optionally, you may include one or two small, natural ingredients (such as herbs, flowers, citrus slices, or spices) placed tastefully near the bottle to subtly evoke the fragrance’s key notes — these must remain minimal and never overpower the bottle. Only use ingredients that appear in the Olfactory Pyramid above — do not invent or add any others. If you include an ingredient, depict it in a realistic, natural form.
109
  The background should be minimal, abstract, or atmospheric — such as gradients, soft light, fabric textures, or mist — with no depiction of people, animals, or narrative scenes.
110
  Use cinematic luxury advertising codes: refined shadows, soft directional lighting, elegant minimalism, and a sophisticated, editorial composition.
111
-
112
  ---
113
  Always ensure that:
114
- – The fragrance matches the mood and visual setting of the scene
115
- – All ingredients are real, plausible, and fit together naturally
116
- – No invented scenery or extra context is added
117
- – The poetic description and pyramid share the same notes and details
118
- – The image description **must mention the exact Perfume Name on the label**, and **focus exclusively on the perfume bottle as the main subject**
119
- No humans, animals, narrative scenes, or symbolic objects unrelated to the bottle design are described
120
- Each perfume feels unique and consistent
121
-
122
  Here is the scene description to analyze:
123
  \n<</SYS>>\n\n{} [/INST]"""
124
 
@@ -231,11 +222,9 @@ def parse_perfume_description(text: str) -> dict:
231
  def extract_field(data: Union[str, dict], field_name: str) -> str:
232
  """
233
  Extracts a specific field value from a JSON string or Python dict.
234
-
235
  Args:
236
  data (Union[str, dict]): The JSON string or dict to extract from.
237
  field_name (str): The exact field name to extract.
238
-
239
  Returns:
240
  str: The extracted field value as a string.
241
  """
@@ -269,11 +258,94 @@ def get_text_after_colon(input_text):
269
  # Return the original text if ":" is not found
270
  return input_text
271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  def infer(image_input):
273
 
274
  gr.Info('Calling CLIP Interrogator ...')
275
 
276
- yield None, None, None
277
  clipi_result = clipi_client.predict(
278
  image=handle_file(image_input),
279
  mode="best",
@@ -288,11 +360,14 @@ def infer(image_input):
288
  result = llama_gen_fragrance(llama_q)
289
 
290
  print(f"Llama2 result: {result}")
291
- yield result, None, None
292
 
293
  parsed = parse_perfume_description(result)
294
  image_desc = extract_field(parsed, "Image Description")
295
- yield result, parsed, image_desc
 
 
 
296
 
297
  css="""
298
  #col-container {max-width: 910px; margin-left: auto; margin-right: auto;}
@@ -315,27 +390,28 @@ with gr.Blocks(css=css) as demo:
315
  with gr.Column():
316
  #caption = gr.Textbox(label="Generated Caption")
317
  fragrance = gr.Textbox(label="generated Fragrance", elem_id="fragrance")
 
318
  get_flacon_btn = gr.Button("Generate Flacon image", interactive=False)
319
  bottle_res = gr.Image(label="Flacon")
320
 
321
  def disable_flacon_button():
322
- return gr.update(interactive=False)
323
 
324
  def allow_flacon_button():
325
- return gr.update(interactive=True)
326
 
327
  submit_btn.click(
328
  fn=disable_flacon_button,
329
  inputs = [],
330
- outputs = [get_flacon_btn]
331
  ).then(
332
  fn=infer,
333
  inputs=[image_in],
334
- outputs=[fragrance, json_res, flacon_desc]
335
  ).then(
336
  fn=allow_flacon_button,
337
  inputs=[],
338
- outputs=[get_flacon_btn]
339
  )
340
  get_flacon_btn.click(fn=infer_flux, inputs=[flacon_desc], outputs=[bottle_res])
341
 
 
70
  ---
71
  Perfume Name:
72
  An original, evocative, and unique name — in French or English.
 
73
  Tagline:
74
  A short, poetic sentence — like a perfume advertisement hook.
 
75
  Poetic Olfactory Description:
76
  A freeform and expressive description of the scent ambiance evoked by the scene. Use rich sensory, emotional, and metaphorical language. Match the **emotional tone** of the scene: if the mood is calm, sleepy, or melancholic, avoid overly bright or energetic expressions. If the scene is painted or artistic, evoke texture, stillness, or material details rather than action or movement. Be subtle and precise.
77
  **Important:** Any scents, herbs, or natural elements mentioned here must be consistent with the scene’s setting. Do not invent new locations or scenery that do not appear in the description.
 
78
  Olfactory Pyramid (technical):
79
  - Top Notes:
80
  List 3–4 real, concrete scent materials that would be perceived first. These must be plausible fragrance ingredients (e.g. herbs, resins, citrus peels, spices, aldehydes, etc.). Pick notes that reflect the **real mood, climate, and setting** of the scene. Do not add locations or elements that don’t appear in the scene. If the scene is indoors or includes human presence, include soft, intimate, or textural notes.
 
81
  - Heart Notes:
82
  List 3–4 real fragrance elements that give body and soul to the perfume. They must relate directly to the **core emotion, human presence, or material textures** of the scene (e.g. warm fabric, skin, dry flowers, books, wood, canvas). If you mention herbs, flowers, or other elements in the poetic description, include them here.
 
83
  - Base Notes:
84
  List 3–4 real, longer-lasting ingredients such as woods, musks, resins, or earthy accords. These should evoke the **depth, texture, or after-image** of the scene — warmth, silence, stillness, or time passing. Avoid generic bases unless they fit the mood. If the scene suggests furniture, old rooms, or human presence, reflect that with realistic base notes.
 
85
  Consistency Rule:
86
  The top, heart, and base notes must not introduce new ideas, plants, or places that were not in the poetic description or the scene. Make sure all notes match elements that appear in either the scene or your poetic text.
 
87
  General Atmosphere:
88
+ **This section is mandatory.** Provide a short, elegant paragraph summarizing the fragrance’s evolution and overall emotional impression. Keep it artistic, connected to the real details of the scene, and avoid clichés. **Never omit this section.**
 
89
  Image Description (for marketing visuals):
90
  Describe an imagined marketing image that captures the perfume’s essence.
91
  Begin by describing a clear, modern perfume bottle as the main and visually dominant subject.
92
+ The bottle must be obviously recognizable as a perfume bottle — featuring a sprayer or atomizer, an elegant cap, and a refined fragrance label. The label must clearly display the **exact Perfume Name** generated in this output, written exactly as it appears, along with a subtle, elegant mention of the imaginary luxury brand **“FILONI’S.”** The brand name should appear in a smaller, complementary font style, placed above or below the Perfume Name to enhance the overall design without overpowering it.
93
  Do not use placeholder text like “Perfume Name” — always use the actual fragrance name exactly as you have suggested above.
94
+ **Important:** If the input scene description includes human characters, narrative details, or historical references, do not depict them literally. Instead, translate these elements into abstract design cues, subtle decorative details, or soft textures on the bottle or in the minimal background. The only clear subject must be the perfume bottle itself (with optional small natural ingredients). Do not show people, animals, narrative scenes, or explicit props unrelated to the bottle design.
95
  Describe the bottle’s shape, glass texture, cap, and label in fine detail. The glass may have an elegant frosted or matte finish, subtle etching or engraving (such as delicate floral or botanical motifs), or soft decorative elements that evoke refinement and sophistication while remaining tasteful and minimal.
96
  Do not describe containers that look like liquor bottles, flower vases, or fantasy potion bottles.
97
  Do not add narrative illustrations, characters, or storytelling scenes on the bottle — only subtle, abstract decorative details that highlight a luxury perfume aesthetic.
 
100
  Optionally, you may include one or two small, natural ingredients (such as herbs, flowers, citrus slices, or spices) placed tastefully near the bottle to subtly evoke the fragrance’s key notes — these must remain minimal and never overpower the bottle. Only use ingredients that appear in the Olfactory Pyramid above — do not invent or add any others. If you include an ingredient, depict it in a realistic, natural form.
101
  The background should be minimal, abstract, or atmospheric — such as gradients, soft light, fabric textures, or mist — with no depiction of people, animals, or narrative scenes.
102
  Use cinematic luxury advertising codes: refined shadows, soft directional lighting, elegant minimalism, and a sophisticated, editorial composition.
 
103
  ---
104
  Always ensure that:
105
+ – The fragrance matches the mood and visual setting of the scene.
106
+ – All ingredients are real, plausible, and fit together naturally.
107
+ – No invented scenery or extra context is added.
108
+ – The poetic description and pyramid share the same notes and details.
109
+ – The **General Atmosphere** section is always included and consistent with the rest.
110
+ The image description **must mention the exact Perfume Name on the label**, and **focus exclusively on the perfume bottle as the main subject**.
111
+ No humans, animals, narrative scenes, or symbolic objects unrelated to the bottle design are described.
112
+ – Each perfume feels unique and consistent.
113
  Here is the scene description to analyze:
114
  \n<</SYS>>\n\n{} [/INST]"""
115
 
 
222
  def extract_field(data: Union[str, dict], field_name: str) -> str:
223
  """
224
  Extracts a specific field value from a JSON string or Python dict.
 
225
  Args:
226
  data (Union[str, dict]): The JSON string or dict to extract from.
227
  field_name (str): The exact field name to extract.
 
228
  Returns:
229
  str: The extracted field value as a string.
230
  """
 
258
  # Return the original text if ":" is not found
259
  return input_text
260
 
261
+ import pandas as pd
262
+
263
+ # Load your perfume database once
264
+ df = pd.read_excel('perfume_database_cleaned.xlsx')
265
+
266
+ def extract_notes_for_comparison(data: Union[str, dict]) -> list[str]:
267
+ """
268
+ Extracts all notes from the Olfactory Pyramid section of a JSON string or dict.
269
+ Args:
270
+ data (Union[str, dict]): The JSON string or Python dict.
271
+ Returns:
272
+ list[str]: A list of extracted note names.
273
+ """
274
+ if isinstance(data, str):
275
+ try:
276
+ data = json.loads(data)
277
+ except json.JSONDecodeError:
278
+ raise ValueError("Invalid JSON string provided")
279
+
280
+ if not isinstance(data, dict):
281
+ raise TypeError("Input must be a dict or a valid JSON string")
282
+
283
+ olfactory_pyramid = data.get("Olfactory Pyramid") or data.get("olfactory pyramid")
284
+ if not olfactory_pyramid:
285
+ raise KeyError("No 'Olfactory Pyramid' found in the data")
286
+
287
+ notes = []
288
+ for layer in ["Top Notes", "Heart Notes", "Base Notes"]:
289
+ layer_data = olfactory_pyramid.get(layer) or olfactory_pyramid.get(layer.lower())
290
+ if not layer_data:
291
+ continue # If a layer is missing, just skip
292
+ for item in layer_data:
293
+ note = item.get("note") or item.get("Note")
294
+ if note:
295
+ notes.append(note.strip())
296
+
297
+ if not notes:
298
+ raise ValueError("No notes found in the Olfactory Pyramid")
299
+
300
+ return notes
301
+
302
+ from rapidfuzz import fuzz
303
+
304
+ def find_best_perfumes_from_json(data: Union[str, dict], top_n: int = 5, threshold: int = 80):
305
+ """
306
+ Finds top N matching perfumes using fuzzy matching on notes.
307
+ Args:
308
+ data (Union[str, dict]): The input JSON or dict.
309
+ top_n (int): Number of results.
310
+ threshold (int): Minimum fuzz ratio to count as match.
311
+ Returns:
312
+ pd.DataFrame
313
+ """
314
+ user_notes = extract_notes_for_comparison(data)
315
+ user_notes_clean = [n.strip().lower() for n in user_notes]
316
+
317
+ matches = []
318
+ for _, row in df.iterrows():
319
+ perfume_notes = [n.strip().lower() for n in row['notes'].split(',')]
320
+ matched_notes = []
321
+
322
+ for u_note in user_notes_clean:
323
+ for p_note in perfume_notes:
324
+ ratio = fuzz.partial_ratio(u_note, p_note)
325
+ if ratio >= threshold:
326
+ matched_notes.append(p_note)
327
+
328
+ matched_notes = sorted(set(matched_notes))
329
+
330
+ matches.append({
331
+ 'brand': row['brand'],
332
+ 'perfume': row['perfume'],
333
+ 'matching_notes': ', '.join(matched_notes),
334
+ 'match_count': len(matched_notes)
335
+ })
336
+
337
+ result = pd.DataFrame(matches)
338
+ result = result[result['match_count'] > 0]
339
+ result = result.sort_values(by='match_count', ascending=False).head(top_n).reset_index(drop=True)
340
+
341
+ return result
342
+
343
+
344
  def infer(image_input):
345
 
346
  gr.Info('Calling CLIP Interrogator ...')
347
 
348
+ yield None, None, None, None
349
  clipi_result = clipi_client.predict(
350
  image=handle_file(image_input),
351
  mode="best",
 
360
  result = llama_gen_fragrance(llama_q)
361
 
362
  print(f"Llama2 result: {result}")
363
+ yield result, None, None, None
364
 
365
  parsed = parse_perfume_description(result)
366
  image_desc = extract_field(parsed, "Image Description")
367
+
368
+ real_correspondance = find_best_perfumes_from_json(parsed)
369
+
370
+ yield result, parsed, image_desc, real_correspondance
371
 
372
  css="""
373
  #col-container {max-width: 910px; margin-left: auto; margin-right: auto;}
 
390
  with gr.Column():
391
  #caption = gr.Textbox(label="Generated Caption")
392
  fragrance = gr.Textbox(label="generated Fragrance", elem_id="fragrance")
393
+ output_df = gr.Dataframe()
394
  get_flacon_btn = gr.Button("Generate Flacon image", interactive=False)
395
  bottle_res = gr.Image(label="Flacon")
396
 
397
  def disable_flacon_button():
398
+ return gr.update(interactive=False), gr.update(visible=False)
399
 
400
  def allow_flacon_button():
401
+ return gr.update(interactive=True), gr.update(visible=True)
402
 
403
  submit_btn.click(
404
  fn=disable_flacon_button,
405
  inputs = [],
406
+ outputs = [get_flacon_btn, output_df]
407
  ).then(
408
  fn=infer,
409
  inputs=[image_in],
410
+ outputs=[fragrance, json_res, flacon_desc, output_df]
411
  ).then(
412
  fn=allow_flacon_button,
413
  inputs=[],
414
+ outputs=[get_flacon_btn, output_df]
415
  )
416
  get_flacon_btn.click(fn=infer_flux, inputs=[flacon_desc], outputs=[bottle_res])
417