Julien Lestel
Refactor ingredient recommendation system with Gradio interface and semantic embeddings
5bf5270 Download app.py from jlestel/test: direct link, hf CLI and curl.
- Browser
- Download file 4.28 kB
-
https://huggingface.co/spaces/jlestel/test/resolve/main/app.py
- Command line
-
hf download hf://spaces/jlestel/test/app.py
-
curl -L -o app.py https://huggingface.co/spaces/jlestel/test/resolve/main/app.py
4.28 kB
| import gradio as gr | |
| from sentence_transformers import SentenceTransformer, util | |
| import torch | |
| # Mapping ingrédient -> liste de produits connus | |
| INGREDIENT_MAPPING = { | |
| "lait demi-écrémé": [ | |
| "Lait bio demi-écrémé Carrefour", | |
| "Lait UHT demi-écrémé Lactel", | |
| "Lait demi-écrémé Leader Price" | |
| ], | |
| "huile d'olive": [ | |
| "Huile d'olive vierge extra Monoprix", | |
| "Huile d'olive bio Carrefour", | |
| "Huile d'olive pressée à froid" | |
| ], | |
| "farine de blé": [ | |
| "Farine de blé T45", | |
| "Farine de blé fluide Francine" | |
| ], | |
| "beurre": [ | |
| "Beurre doux Président", | |
| "Beurre bio Carrefour", | |
| "Beurre de baratte" | |
| ], | |
| "sucre": [ | |
| "Sucre blanc cristallisé", | |
| "Sucre en poudre Daddy", | |
| "Sucre de canne bio" | |
| ] | |
| } | |
| # Charger le modèle (une seule fois au démarrage) | |
| print("Chargement du modèle...") | |
| model = SentenceTransformer("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2") | |
| # Précalculer les embeddings moyens pour chaque ingrédient | |
| print("Calcul des embeddings des ingrédients...") | |
| ingredient_embeddings = {} | |
| for ingredient, produits in INGREDIENT_MAPPING.items(): | |
| prod_embeds = model.encode(produits, convert_to_tensor=True) | |
| ingredient_embeddings[ingredient] = prod_embeds.mean(dim=0) | |
| print("Modèle prêt!") | |
| def recommander_ingredient(nom_produit: str, top_k: int = 3): | |
| """ | |
| Recommande les ingrédients les plus probables pour un produit donné. | |
| Args: | |
| nom_produit: Le nom du produit à classifier | |
| top_k: Nombre de recommandations à retourner | |
| Returns: | |
| Un texte formaté avec les recommandations | |
| """ | |
| if not nom_produit or nom_produit.strip() == "": | |
| return "Veuillez entrer un nom de produit." | |
| # Encoder le nouveau produit | |
| prod_emb = model.encode(nom_produit, convert_to_tensor=True) | |
| # Calculer la similarité avec chaque ingrédient | |
| scores = {} | |
| for ingredient, emb in ingredient_embeddings.items(): | |
| similarity = float(util.cos_sim(prod_emb, emb)) | |
| scores[ingredient] = similarity | |
| # Trier par score décroissant | |
| sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True) | |
| # Formater la sortie | |
| result = f"**Produit analysé:** {nom_produit}\n\n" | |
| result += "**Recommandations d'ingrédients:**\n\n" | |
| for i, (ingredient, score) in enumerate(sorted_scores[:top_k], 1): | |
| percentage = score * 100 | |
| result += f"{i}. **{ingredient}** - Score: {score:.3f} ({percentage:.1f}%)\n" | |
| return result | |
| # Interface Gradio | |
| with gr.Blocks(title="Recommandation d'Ingrédients") as demo: | |
| gr.Markdown(""" | |
| # Recommandation d'Ingrédients | |
| Entrez le nom d'un produit et obtenez les ingrédients les plus probables correspondants. | |
| Le système utilise des embeddings sémantiques pour trouver les correspondances. | |
| """) | |
| with gr.Row(): | |
| with gr.Column(): | |
| input_produit = gr.Textbox( | |
| label="Nom du produit", | |
| placeholder="Ex: Huile d'olive extra vierge bio Herta", | |
| lines=2 | |
| ) | |
| top_k_slider = gr.Slider( | |
| minimum=1, | |
| maximum=len(INGREDIENT_MAPPING), | |
| value=3, | |
| step=1, | |
| label="Nombre de recommandations" | |
| ) | |
| btn_recommander = gr.Button("Recommander", variant="primary") | |
| with gr.Column(): | |
| output_result = gr.Markdown(label="Résultats") | |
| # Exemples | |
| gr.Examples( | |
| examples=[ | |
| ["Huile d'olive extra vierge bio Herta", 3], | |
| ["Lait entier bio Lactel", 3], | |
| ["Farine de blé complète", 3], | |
| ["Beurre salé AOP", 3], | |
| ["Sucre roux de canne", 3], | |
| ], | |
| inputs=[input_produit, top_k_slider] | |
| ) | |
| # Événement de clic | |
| btn_recommander.click( | |
| fn=recommander_ingredient, | |
| inputs=[input_produit, top_k_slider], | |
| outputs=output_result | |
| ) | |
| # Également déclencher sur Enter | |
| input_produit.submit( | |
| fn=recommander_ingredient, | |
| inputs=[input_produit, top_k_slider], | |
| outputs=output_result | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |