FredinVázquez commited on
Commit
c795fe5
·
1 Parent(s): ba424d1

update prompt and output format

Browse files
src/agents/mise_en_place.py CHANGED
@@ -5,40 +5,40 @@ from typing import Optional
5
  import os
6
  import torch
7
  from transformers import AutoProcessor, MiniCPMV4_6ForConditionalGeneration
 
8
 
9
  MODEL_ID = "openbmb/MiniCPM-V-4.6"
10
 
11
  # Detectar el entorno: Si estás en Hugging Face ZeroGPU, forzamos "auto" (CPU inicial).
12
  # Si estás en tu PC local con una GPU Nvidia, usamos "cuda". De lo contrario, "cpu".
13
  if os.environ.get("SPACE_ID") is not None:
14
- # Estamos dentro de un Hugging Face Space
15
  ENV_DEVICE = "auto"
16
  print("Entorno detectado: Hugging Face Spaces (ZeroGPU).")
17
  else:
18
- # Estamos en tu máquina local
19
  ENV_DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
20
  print(f"Entorno detectado: Local. Usando dispositivo: {ENV_DEVICE.upper()}")
21
 
22
- print(f"Loading processor: {MODEL_ID}")
23
  processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
24
 
25
- print(f"Loading model: {MODEL_ID}")
26
  model = MiniCPMV4_6ForConditionalGeneration.from_pretrained(
27
  MODEL_ID,
28
  torch_dtype=torch.bfloat16,
29
  attn_implementation="sdpa",
30
  trust_remote_code=True,
31
- device_map=ENV_DEVICE # <--- Configuración dinámica según el entorno
32
  ).eval()
33
 
34
- _prompt = "Describe the given image in detail. Be honest, do not say liers."
35
-
 
36
 
37
  @spaces.GPU(duration=30)
38
  def identify_ingredients(image: Optional[Image.Image]) -> list[str]:
39
  try:
40
  img = image.convert("RGB")
41
- messages = [{"role": "user", "content": [{"type": "image", "image": img}, {"type": "text", "text": _prompt}]}]
42
 
43
  # Procesamiento de tokens
44
  inputs = processor.apply_chat_template(
@@ -46,8 +46,6 @@ def identify_ingredients(image: Optional[Image.Image]) -> list[str]:
46
  enable_thinking=False, processor_kwargs={"downsample_mode": "16x", "max_slice_nums": 9, "use_image_id": True}
47
  )
48
 
49
- # LOCAL: model.device será 'cuda' (Tu tarjeta gráfica)
50
- # ZERO_GPU: model.device cambiará a 'cuda:0' dinámicamente gracias al decorador
51
  inputs = inputs.to(model.device)
52
 
53
  for k, v in inputs.items():
@@ -60,10 +58,11 @@ def identify_ingredients(image: Optional[Image.Image]) -> list[str]:
60
  generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
61
  raw_output = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
62
 
63
- # (Tu lógica de limpieza de JSON e ingredientes aquí...)
64
  print(raw_output)
65
- return ['testing']
 
 
66
 
67
  except Exception as e:
68
  print(f"Error: {e}")
69
- return ["there are not ingredients detected"]
 
5
  import os
6
  import torch
7
  from transformers import AutoProcessor, MiniCPMV4_6ForConditionalGeneration
8
+ from src import config
9
 
10
  MODEL_ID = "openbmb/MiniCPM-V-4.6"
11
 
12
  # Detectar el entorno: Si estás en Hugging Face ZeroGPU, forzamos "auto" (CPU inicial).
13
  # Si estás en tu PC local con una GPU Nvidia, usamos "cuda". De lo contrario, "cpu".
14
  if os.environ.get("SPACE_ID") is not None:
15
+ # Hugging Face Space
16
  ENV_DEVICE = "auto"
17
  print("Entorno detectado: Hugging Face Spaces (ZeroGPU).")
18
  else:
19
+ # máquina local
20
  ENV_DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
21
  print(f"Entorno detectado: Local. Usando dispositivo: {ENV_DEVICE.upper()}")
22
 
 
23
  processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
24
 
 
25
  model = MiniCPMV4_6ForConditionalGeneration.from_pretrained(
26
  MODEL_ID,
27
  torch_dtype=torch.bfloat16,
28
  attn_implementation="sdpa",
29
  trust_remote_code=True,
30
+ device_map=ENV_DEVICE
31
  ).eval()
32
 
33
+ _PROMPT_PATH = config.PROMPTS_DIR / "vision_prompt.txt"
34
+ def _prompt() -> str:
35
+ return _PROMPT_PATH.read_text(encoding="utf-8")
36
 
37
  @spaces.GPU(duration=30)
38
  def identify_ingredients(image: Optional[Image.Image]) -> list[str]:
39
  try:
40
  img = image.convert("RGB")
41
+ messages = [{"role": "user", "content": [{"type": "image", "image": img}, {"type": "text", "text": _prompt()}]}]
42
 
43
  # Procesamiento de tokens
44
  inputs = processor.apply_chat_template(
 
46
  enable_thinking=False, processor_kwargs={"downsample_mode": "16x", "max_slice_nums": 9, "use_image_id": True}
47
  )
48
 
 
 
49
  inputs = inputs.to(model.device)
50
 
51
  for k, v in inputs.items():
 
58
  generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
59
  raw_output = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
60
 
 
61
  print(raw_output)
62
+ data = json.loads(raw_output)
63
+ ingredients = [str(x).lower().strip() for x in data.get("ingredients", [])]
64
+ return [x for x in ingredients if x] or list("There are no ingredients detected")
65
 
66
  except Exception as e:
67
  print(f"Error: {e}")
68
+ return ["There are not ingredients detected"]
src/prompts/vision_prompt.txt CHANGED
@@ -1 +1,20 @@
1
- Describe the given image in detail. Be honest, do not say liers.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Context:
2
+ You are going to be provided by an image of a fridge, or image where you will see different ingredientes or food supplies.
3
+
4
+ # Task:
5
+ You have to detect every kind of food, such as vegetables, meat, condiments, oil, milk, eggs, etc. After detect specific ingredients, you have to return that list as your response.
6
+
7
+ # Output format:
8
+ Your output should be in json format, follow the example:
9
+ {
10
+ 'ingredients': [
11
+ 'ingredient 1',
12
+ 'ingredient 2',
13
+ ...
14
+ ]
15
+ }
16
+
17
+ # Contraints
18
+ If you do not see any kind of ingredient you must return a empty json.
19
+ You have to be honest, only add existent ingredients.
20
+ Follow the output format always.