Spaces:
Sleeping
Sleeping
import gradio as gr | |
from transformers import pipeline | |
from PIL import Image | |
import torch | |
import re | |
# βββββββββββββββββββββββββββββ | |
# 1. CLASSIFICATION DβINGReDIENTS | |
# βββββββββββββββββββββββββββββ | |
INGREDIENT_MODEL_ID = "stchakman/Fridge_Items_Model" | |
ingredient_classifier = pipeline( | |
"image-classification", | |
model=INGREDIENT_MODEL_ID, | |
device=0 if torch.cuda.is_available() else -1, | |
top_k=4 | |
) | |
# βββββββββββββββββββββββββββββ | |
# 2. MODeLE DE GeNeRATION | |
# βββββββββββββββββββββββββββββ | |
recipe_generator = pipeline( | |
"text2text-generation", | |
model="flax-community/t5-recipe-generation", | |
device=0 if torch.cuda.is_available() else -1 | |
) | |
# βββββββββββββββββββββββββββββ | |
# 3. FONCTION PRINCIPALE | |
# βββββββββββββββββββββββββββββ | |
def generate_recipe(image: Image.Image): | |
try: | |
# Detection ingredients | |
results = ingredient_classifier(image) | |
ingredients = [res["label"].lower() for res in results] | |
if not ingredients: | |
return { | |
"error": "Aucun ingredient detecte.", | |
"ingredients_detected": [] | |
} | |
prompt = ", ".join(ingredients) | |
generated = recipe_generator(prompt, max_length=200)[0]["generated_text"] | |
# extraction par expressions regulieres | |
title_match = re.search(r"title\s*:\s*(.+?)(ingredients\s*:|$)", generated, re.IGNORECASE | re.DOTALL) | |
ingredients_match = re.search(r"ingredients\s*:\s*(.+?)(directions\s*:|$)", generated, re.IGNORECASE | re.DOTALL) | |
directions_match = re.search(r"directions\s*:\s*(.+)", generated, re.IGNORECASE | re.DOTALL) | |
title = title_match.group(1).strip() if title_match else None | |
ingredients_list = ingredients_match.group(1).strip().split('\n') if ingredients_match else [] | |
directions_raw = directions_match.group(1).strip() if directions_match else None | |
directions_list = re.split(r"\.\s*", directions_raw) if directions_raw else [] | |
# nettoyage des listes | |
ingredients_list = [line.strip("- ").strip() for line in ingredients_list if line.strip()] | |
directions_list = [step.strip("- ").strip() for step in directions_list if step.strip()] | |
return { | |
"ingredients_detected": ingredients, | |
"generated": { | |
"title": title, | |
"ingredients": ingredients_list, | |
"instructions": directions_list | |
} | |
} | |
except Exception as e: | |
return {"error": str(e)} | |
# βββββββββββββββββββββββββββββ | |
# 4. INTERFACE GRADIO | |
# βββββββββββββββββββββββββββββ | |
interface = gr.Interface( | |
fn=generate_recipe, | |
inputs=gr.Image(type="pil", label="π· Image de vos ingredients"), | |
outputs=gr.JSON(), | |
title="π₯ Generateur de Recettes", | |
description="Deposez une image d'ingredients pour generer une recette automatiquement (resultat JSON structure).", | |
allow_flagging="never" | |
) | |
if __name__ == "__main__": | |
interface.launch(share=True) | |