ankz22 commited on
Commit
7ddf71b
·
1 Parent(s): 417a04e

add json reponse

Browse files
Files changed (3) hide show
  1. .gradio/certificate.pem +31 -0
  2. app.py +48 -24
  3. requirements.txt +1 -0
.gradio/certificate.pem ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -----BEGIN CERTIFICATE-----
2
+ MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
3
+ TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
4
+ cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
5
+ WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
6
+ ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
7
+ MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
8
+ h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
9
+ 0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
10
+ A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
11
+ T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
12
+ B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
13
+ B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
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U0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
30
+ emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
31
+ -----END CERTIFICATE-----
app.py CHANGED
@@ -3,10 +3,11 @@ from transformers import pipeline
3
  from PIL import Image
4
  import torch
5
  from torchvision import transforms
 
6
 
7
  # MODELES
8
  INGREDIENT_MODEL_ID = "stchakman/Fridge_Items_Model"
9
- RECIPE_MODEL_ID = "flax-community/t5-recipe-generation"
10
 
11
  # PIPELINES
12
  ingredient_classifier = pipeline(
@@ -15,11 +16,10 @@ ingredient_classifier = pipeline(
15
  device=0 if torch.cuda.is_available() else -1,
16
  top_k=5
17
  )
18
-
19
  recipe_generator = pipeline(
20
  "text2text-generation",
21
  model=RECIPE_MODEL_ID,
22
- device=0 if torch.cuda.is_available() else -1
23
  )
24
 
25
  # AUGMENTATION
@@ -29,37 +29,61 @@ augment = transforms.Compose([
29
  transforms.ColorJitter(brightness=0.2, contrast=0.2),
30
  ])
31
 
32
- # FONCTION PRINCIPALE
33
- def generate_recipe(image: Image.Image):
34
- # Affichage "Processing..." temporaire
35
- yield "🔄 Traitement de l'image... Veuillez patienter."
 
 
 
 
36
 
37
- # Augmentation
38
- image_aug = augment(image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- # Classification
 
 
 
 
41
  results = ingredient_classifier(image_aug)
42
  ingredients = [res["label"] for res in results]
43
  ingredient_str = ", ".join(ingredients)
44
-
45
- yield f"🥕 Ingrédients détectés : {ingredient_str}\n\n🍳 Génération de la recette..."
46
-
47
- # Génération recette
48
  prompt = f"Ingredients: {ingredient_str}. Recipe:"
49
- recipe = recipe_generator(prompt, max_new_tokens=256, do_sample=True)[0]["generated_text"]
50
 
51
- # Affichage final
52
- yield f"### 🥕 Ingrédients détectés :\n{ingredient_str}\n\n### 🍽️ Recette générée :\n{recipe}"
 
 
 
 
 
53
 
54
- # INTERFACE
55
  interface = gr.Interface(
56
- fn=generate_recipe,
57
- inputs=gr.Image(type="pil", label="📷 Image de vos ingrédients"),
58
- outputs=gr.Markdown(),
59
- title="🥕 Générateur de Recettes 🧑‍🍳",
60
- description="Dépose une image d'ingrédients pour obtenir une recette automatiquement générée à partir d'un modèle IA.",
61
  allow_flagging="never"
62
  )
63
 
64
  if __name__ == "__main__":
65
- interface.launch(share=True) # Mets share=True pour générer le lien Gradio public
 
3
  from PIL import Image
4
  import torch
5
  from torchvision import transforms
6
+ import re
7
 
8
  # MODELES
9
  INGREDIENT_MODEL_ID = "stchakman/Fridge_Items_Model"
10
+ RECIPE_MODEL_ID = "flax-community/t5-recipe-generation"
11
 
12
  # PIPELINES
13
  ingredient_classifier = pipeline(
 
16
  device=0 if torch.cuda.is_available() else -1,
17
  top_k=5
18
  )
 
19
  recipe_generator = pipeline(
20
  "text2text-generation",
21
  model=RECIPE_MODEL_ID,
22
+ device=0 if torch.cuda.is_available() else -1,
23
  )
24
 
25
  # AUGMENTATION
 
29
  transforms.ColorJitter(brightness=0.2, contrast=0.2),
30
  ])
31
 
32
+ def parse_recipe_text(raw: str):
33
+ """
34
+ Parse le texte brut retourne par le modele en JSON { ingredients: [...], steps: [...] }.
35
+ """
36
+ raw = raw.replace("ingredients: ingredients:", "ingredients:")
37
+ # On cherche la section ingredients et directions
38
+ ing_match = re.search(r"ingredients:\s*(.*?)\s*directions:", raw, re.IGNORECASE | re.DOTALL)
39
+ dir_match = re.search(r"directions:\s*(.+)$", raw, re.IGNORECASE | re.DOTALL)
40
 
41
+ # ingredients
42
+ ingredients = []
43
+ if ing_match:
44
+ ing_str = ing_match.group(1).strip()
45
+ parts = re.findall(r"(\d+\s+[^\d,\.]+(?: [^\d,\.]+)*)", ing_str)
46
+ if parts:
47
+ ingredients = [p.strip() for p in parts]
48
+ else:
49
+ ingredients = [i.strip() for i in ing_str.split(",") if i.strip()]
50
+
51
+ # etapes
52
+ steps = []
53
+ if dir_match:
54
+ steps_str = dir_match.group(1).strip()
55
+ for s in re.split(r"\.\s*", steps_str):
56
+ s = s.strip()
57
+ if s:
58
+ steps.append(s.endswith(".") and s or s + ".")
59
 
60
+ return {"ingredients": ingredients, "steps": steps}
61
+
62
+ def generate_recipe_json(image: Image.Image):
63
+ # Aug
64
+ image_aug = augment(image)
65
  results = ingredient_classifier(image_aug)
66
  ingredients = [res["label"] for res in results]
67
  ingredient_str = ", ".join(ingredients)
 
 
 
 
68
  prompt = f"Ingredients: {ingredient_str}. Recipe:"
69
+ raw = recipe_generator(prompt, max_new_tokens=256, do_sample=True)[0]["generated_text"]
70
 
71
+ parsed = parse_recipe_text(raw)
72
+ return {
73
+ "detected_ingredients": ingredients,
74
+ "recipe_text": raw,
75
+ "ingredients_parsed": parsed["ingredients"],
76
+ "steps": parsed["steps"]
77
+ }
78
 
 
79
  interface = gr.Interface(
80
+ fn=generate_recipe_json,
81
+ inputs=gr.Image(type="pil", label="📷 Image de vos ingredients"),
82
+ outputs="json",
83
+ title="🧑‍🍳 Generateur de Recettes (JSON) 🧑‍🍳",
84
+ description="Depose une image d'ingredients, recupere directement un JSON structure avec ingredients et etapes.",
85
  allow_flagging="never"
86
  )
87
 
88
  if __name__ == "__main__":
89
+ interface.launch(share=True)
requirements.txt CHANGED
@@ -3,3 +3,4 @@ transformers
3
  torch
4
  torchvision
5
  pillow
 
 
3
  torch
4
  torchvision
5
  pillow
6
+ re