Datasets:
code of experiments
Browse files- .gitattributes +2 -0
- code/fine_tuning/data/OpenAI_subset_random_train_10250.jsonl +3 -0
- code/fine_tuning/data/OpenAI_subset_random_val_2500.jsonl +3 -0
- code/fine_tuning/data/df_random_train_10250.parquet +3 -0
- code/fine_tuning/data/df_random_val_2500.parquet +3 -0
- code/fine_tuning/fine_tuning_Gemma3_run_inference.py +137 -0
- code/fine_tuning/fine_tuning_Gemma3_save_model_adapter.ipynb +40 -0
- code/fine_tuning/fine_tuning_Gemma3_train_model.py +328 -0
- code/fine_tuning/fine_tuning_OpenAI_run_inference.py +104 -0
- code/fine_tuning/fine_tuning_OpenAI_train_model.md +9 -0
- code/fine_tuning/use_vlm_ft_OpenAI.py +230 -0
- code/fine_tuning/use_vlm_ft_gemma3.py +226 -0
- code/visual_rag/custom_rag_metrics.py +297 -0
- code/visual_rag/evaluation_rag.ipynb +579 -0
- code/visual_rag/rag_retriever.py +30 -0
- code/visual_rag/rag_use_vlm.py +385 -0
- code/visual_rag/rag_vector_store.py +28 -0
- code/visual_rag/run_rag_pipeline.py +261 -0
- code/vlm/custom_vlm_metrics.py +250 -0
- code/vlm/evaluation_vlm.ipynb +575 -0
- code/vlm/run_vlm_commerical.py +125 -0
- code/vlm/run_vlm_ollama.py +113 -0
- code/vlm/use_vlm.py +217 -0
- code/vlm/use_vlm_ollama.py +140 -0
.gitattributes
CHANGED
|
@@ -57,3 +57,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 57 |
# Video files - compressed
|
| 58 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 59 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 57 |
# Video files - compressed
|
| 58 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 59 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
code/fine_tuning/data/OpenAI_subset_random_train_10250.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
code/fine_tuning/data/OpenAI_subset_random_val_2500.jsonl filter=lfs diff=lfs merge=lfs -text
|
code/fine_tuning/data/OpenAI_subset_random_train_10250.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:05972b0f5806e8c2ca33d493e29e88a9fb2ea19d74fcfcfd14a6e55aae4b4625
|
| 3 |
+
size 526903509
|
code/fine_tuning/data/OpenAI_subset_random_val_2500.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6dedf18a2e2bbdd6e3fa5bd0c7f069d77ef64a7ad16aab0f959979b632f3a7ab
|
| 3 |
+
size 128103663
|
code/fine_tuning/data/df_random_train_10250.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b864f791dcb98fc88ef73f83dc864bb3fadde5edde7b2c79d328e4ba90245996
|
| 3 |
+
size 429083
|
code/fine_tuning/data/df_random_val_2500.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e359ed368c9c404649a41ccc4caa081c7a607dfd870f0f7409dad5ce83ee44b8
|
| 3 |
+
size 160359
|
code/fine_tuning/fine_tuning_Gemma3_run_inference.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import time
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
|
| 11 |
+
from transformers import AutoProcessor, AutoModelForImageTextToText
|
| 12 |
+
|
| 13 |
+
import use_vlm_ft_gemma3
|
| 14 |
+
|
| 15 |
+
def clear_memory():
|
| 16 |
+
# Delete variables if they exist in the current global scope
|
| 17 |
+
if "inputs" in globals():
|
| 18 |
+
del globals()["inputs"]
|
| 19 |
+
if "model" in globals():
|
| 20 |
+
del globals()["model"]
|
| 21 |
+
if "processor" in globals():
|
| 22 |
+
del globals()["processor"]
|
| 23 |
+
if "trainer" in globals():
|
| 24 |
+
del globals()["trainer"]
|
| 25 |
+
if "peft_model" in globals():
|
| 26 |
+
del globals()["peft_model"]
|
| 27 |
+
if "bnb_config" in globals():
|
| 28 |
+
del globals()["bnb_config"]
|
| 29 |
+
time.sleep(2)
|
| 30 |
+
|
| 31 |
+
# Garbage collection and clearing CUDA memory
|
| 32 |
+
gc.collect()
|
| 33 |
+
time.sleep(2)
|
| 34 |
+
torch.cuda.empty_cache()
|
| 35 |
+
# torch.cuda.synchronize()
|
| 36 |
+
time.sleep(2)
|
| 37 |
+
gc.collect()
|
| 38 |
+
time.sleep(2)
|
| 39 |
+
|
| 40 |
+
print(f"GPU allocated memory: {torch.cuda.memory_allocated() / 1024**3:.2f} GB")
|
| 41 |
+
print(f"GPU reserved memory: {torch.cuda.memory_reserved() / 1024**3:.2f} GB")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if __name__ == "__main__":
|
| 46 |
+
clear_memory()
|
| 47 |
+
|
| 48 |
+
in_path_frame_images = './.../rpp-765k_512'
|
| 49 |
+
in_file_data_entering_test = './.../test.parquet'
|
| 50 |
+
|
| 51 |
+
in_model_name = "google_gemma-3-4b-pt_local_FT"
|
| 52 |
+
in_name_results_output = 'results'
|
| 53 |
+
out_path_results = './.../output'
|
| 54 |
+
os.environ["USED_MODEL"] = "google_gemma-3-4b_local_FT"
|
| 55 |
+
|
| 56 |
+
dict_log = {}
|
| 57 |
+
dict_log['model'] = in_model_name
|
| 58 |
+
|
| 59 |
+
print("in_model_name: " + str(in_model_name))
|
| 60 |
+
|
| 61 |
+
path_outputs = os.path.join(out_path_results, in_model_name)
|
| 62 |
+
os.makedirs(path_outputs, exist_ok=True)
|
| 63 |
+
|
| 64 |
+
df_result = pd.DataFrame(
|
| 65 |
+
columns=['label', 'filename', \
|
| 66 |
+
'brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'weight_number', 'weight_unit', 'different_types'])
|
| 67 |
+
df_result_cost = pd.DataFrame(
|
| 68 |
+
columns=['label', 'filename']
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
df_test = pd.read_parquet(in_file_data_entering_test, engine='pyarrow')
|
| 72 |
+
df_test.reset_index(drop=True, inplace=True)
|
| 73 |
+
|
| 74 |
+
output_dir = "path-to-checkpoints-directory/google-gemma3-4b-pt/random-subset"
|
| 75 |
+
# Load Model with PEFT adapter
|
| 76 |
+
ft_model = AutoModelForImageTextToText.from_pretrained(
|
| 77 |
+
output_dir,
|
| 78 |
+
device_map="auto",
|
| 79 |
+
torch_dtype=torch.bfloat16,
|
| 80 |
+
attn_implementation="eager",
|
| 81 |
+
)
|
| 82 |
+
processor = AutoProcessor.from_pretrained(output_dir)
|
| 83 |
+
|
| 84 |
+
start_index = 0
|
| 85 |
+
output_file = f'{datetime.now().strftime("%Y%m%d_%H%M%S")}_{in_name_results_output}'
|
| 86 |
+
|
| 87 |
+
for index, row in df_test.iloc[start_index:].iterrows():
|
| 88 |
+
label = str(row.label)
|
| 89 |
+
filename = row.filename
|
| 90 |
+
|
| 91 |
+
dict_result = {}
|
| 92 |
+
dict_result['label'] = label
|
| 93 |
+
dict_result['filename'] = filename
|
| 94 |
+
dict_result_cost = {}
|
| 95 |
+
dict_result_cost['label'] = label
|
| 96 |
+
dict_result_cost['filename'] = filename
|
| 97 |
+
|
| 98 |
+
############################################
|
| 99 |
+
# PROMPT
|
| 100 |
+
############################################
|
| 101 |
+
# IMAGE
|
| 102 |
+
image_path = os.path.join( in_path_frame_images, 'test', label, filename )
|
| 103 |
+
pil_image = Image.open(image_path)
|
| 104 |
+
|
| 105 |
+
# TASK
|
| 106 |
+
task = "Extract all targets."
|
| 107 |
+
dict_log['prompt_task'] = task
|
| 108 |
+
|
| 109 |
+
dict_log, dict_result, dict_result_cost = use_vlm_ft_gemma3.do_request(
|
| 110 |
+
ft_model,
|
| 111 |
+
processor,
|
| 112 |
+
pil_image,
|
| 113 |
+
task,
|
| 114 |
+
dict_log,
|
| 115 |
+
dict_result,
|
| 116 |
+
dict_result_cost,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
df_result = pd.concat( [ df_result, pd.DataFrame.from_dict([dict_result]) ], ignore_index=True)
|
| 120 |
+
df_result_cost = pd.concat( [ df_result_cost, pd.DataFrame.from_dict([dict_result_cost]) ], ignore_index=True)
|
| 121 |
+
|
| 122 |
+
if index%100 == 0:
|
| 123 |
+
df_result.to_parquet( os.path.join(path_outputs, output_file + '_' + str(index) + '_r.parquet'), index=False, engine='pyarrow')
|
| 124 |
+
df_result_cost.to_parquet( os.path.join(path_outputs, output_file + '_costs_' + str(index) + '_r.parquet'), index=False, engine='pyarrow')
|
| 125 |
+
df_result = pd.DataFrame( columns=['label', 'filename', \
|
| 126 |
+
'brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'weight_number', 'weight_unit', 'different_types'])
|
| 127 |
+
df_result_cost = pd.DataFrame(columns=['label', 'filename'])
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
df_result.to_parquet( os.path.join(path_outputs, output_file + '_' + str(index) + '_r.parquet'), index=False, engine='pyarrow')
|
| 131 |
+
df_result_cost.to_parquet( os.path.join(path_outputs, output_file + '_costs_' + str(index) + '_r.parquet'), index=False, engine='pyarrow')
|
| 132 |
+
|
| 133 |
+
#######################################################################
|
| 134 |
+
#######################################################################
|
| 135 |
+
|
| 136 |
+
with open(os.path.join(path_outputs, in_name_results_output + '.json'), 'w') as json_file:
|
| 137 |
+
json.dump(dict_log, json_file)
|
code/fine_tuning/fine_tuning_Gemma3_save_model_adapter.ipynb
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 6,
|
| 6 |
+
"id": "cf52e279",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"import os\n",
|
| 11 |
+
"from peft import PeftModel\n",
|
| 12 |
+
"from transformers import AutoProcessor, AutoModelForImageTextToText\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"model_id = \"google/gemma-3-4b-pt\"\n",
|
| 16 |
+
"output_dir = \"path-to-checkpoints-directory/google-gemma3-4b-pt/random-subset\"\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"# Load Model base model\n",
|
| 19 |
+
"model = AutoModelForImageTextToText.from_pretrained(model_id, low_cpu_mem_usage=True)\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"# Merge LoRA and base model and save\n",
|
| 22 |
+
"peft_model = PeftModel.from_pretrained(model, output_dir)\n",
|
| 23 |
+
"merged_model = peft_model.merge_and_unload()\n",
|
| 24 |
+
"merged_model.save_pretrained(os.path.join(output_dir, \"merged_model\"), safe_serialization=True, max_shard_size=\"2GB\")\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"processor = AutoProcessor.from_pretrained(output_dir)\n",
|
| 27 |
+
"processor.save_pretrained(os.path.join(output_dir, \"merged_model_processor\"))"
|
| 28 |
+
]
|
| 29 |
+
}
|
| 30 |
+
],
|
| 31 |
+
"metadata": {
|
| 32 |
+
"kernelspec": {
|
| 33 |
+
"display_name": "Python 3 (ipykernel)",
|
| 34 |
+
"language": "python",
|
| 35 |
+
"name": "python3"
|
| 36 |
+
}
|
| 37 |
+
},
|
| 38 |
+
"nbformat": 4,
|
| 39 |
+
"nbformat_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 1 |
+
import torch
|
| 2 |
+
import gc
|
| 3 |
+
import pickle
|
| 4 |
+
import shutil
|
| 5 |
+
import time
|
| 6 |
+
# PEFT: Parameter-Efficient Fine-Tuning
|
| 7 |
+
import peft
|
| 8 |
+
import os
|
| 9 |
+
# SFT: Supervised Fine-Tuning
|
| 10 |
+
import trl
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import pickle
|
| 13 |
+
import huggingface_hub
|
| 14 |
+
import getpass
|
| 15 |
+
# logging
|
| 16 |
+
import json
|
| 17 |
+
import datetime
|
| 18 |
+
import wandb
|
| 19 |
+
|
| 20 |
+
from PIL import Image
|
| 21 |
+
from tqdm import tqdm
|
| 22 |
+
from datasets import load_dataset
|
| 23 |
+
|
| 24 |
+
from transformers import AutoProcessor, AutoModelForImageTextToText, BitsAndBytesConfig
|
| 25 |
+
from torch.utils.data import Dataset
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def process_vision_info(messages: list[dict]) -> list[Image.Image]:
|
| 29 |
+
image_inputs = []
|
| 30 |
+
# Iterate through each conversation
|
| 31 |
+
for msg in messages:
|
| 32 |
+
# Get content (ensure it's a list)
|
| 33 |
+
content = msg.get("content", [])
|
| 34 |
+
if not isinstance(content, list):
|
| 35 |
+
content = [content]
|
| 36 |
+
|
| 37 |
+
# Check each content element for images
|
| 38 |
+
for element in content:
|
| 39 |
+
if isinstance(element, dict) and (
|
| 40 |
+
"image" in element or element.get("type") == "image"
|
| 41 |
+
):
|
| 42 |
+
# Get the image and convert to RGB
|
| 43 |
+
if "image" in element:
|
| 44 |
+
image = element["image"]
|
| 45 |
+
else:
|
| 46 |
+
image = element
|
| 47 |
+
image_inputs.append(image.convert("RGB"))
|
| 48 |
+
return image_inputs
|
| 49 |
+
|
| 50 |
+
# Create a data collator to encode text and image pairs
|
| 51 |
+
def collate_fn(examples):
|
| 52 |
+
texts = []
|
| 53 |
+
images = []
|
| 54 |
+
for example in examples:
|
| 55 |
+
image_inputs = process_vision_info(example["messages"])
|
| 56 |
+
text = processor.apply_chat_template(
|
| 57 |
+
example["messages"], add_generation_prompt=False, tokenize=False
|
| 58 |
+
)
|
| 59 |
+
texts.append(text.strip())
|
| 60 |
+
images.append(image_inputs)
|
| 61 |
+
|
| 62 |
+
# Tokenize the texts and process the images
|
| 63 |
+
batch = processor(text=texts, images=images, return_tensors="pt", padding=True)
|
| 64 |
+
|
| 65 |
+
# The labels are the input_ids, and we mask the padding tokens and image tokens in the loss computation
|
| 66 |
+
labels = batch["input_ids"].clone()
|
| 67 |
+
|
| 68 |
+
# Mask image tokens
|
| 69 |
+
image_token_id = [
|
| 70 |
+
processor.tokenizer.convert_tokens_to_ids(
|
| 71 |
+
processor.tokenizer.special_tokens_map["boi_token"]
|
| 72 |
+
)
|
| 73 |
+
]
|
| 74 |
+
# Mask tokens for not being used in the loss computation
|
| 75 |
+
labels[labels == processor.tokenizer.pad_token_id] = -100
|
| 76 |
+
labels[labels == image_token_id] = -100
|
| 77 |
+
labels[labels == 262144] = -100
|
| 78 |
+
|
| 79 |
+
batch["labels"] = labels
|
| 80 |
+
return batch
|
| 81 |
+
|
| 82 |
+
def clear_memory():
|
| 83 |
+
# Delete variables if they exist in the current global scope
|
| 84 |
+
if "inputs" in globals():
|
| 85 |
+
del globals()["inputs"]
|
| 86 |
+
if "model" in globals():
|
| 87 |
+
del globals()["model"]
|
| 88 |
+
if "processor" in globals():
|
| 89 |
+
del globals()["processor"]
|
| 90 |
+
if "trainer" in globals():
|
| 91 |
+
del globals()["trainer"]
|
| 92 |
+
if "peft_model" in globals():
|
| 93 |
+
del globals()["peft_model"]
|
| 94 |
+
if "bnb_config" in globals():
|
| 95 |
+
del globals()["bnb_config"]
|
| 96 |
+
time.sleep(2)
|
| 97 |
+
|
| 98 |
+
# Garbage collection and clearing CUDA memory
|
| 99 |
+
gc.collect()
|
| 100 |
+
time.sleep(2)
|
| 101 |
+
torch.cuda.empty_cache()
|
| 102 |
+
# torch.cuda.synchronize()
|
| 103 |
+
time.sleep(2)
|
| 104 |
+
gc.collect()
|
| 105 |
+
time.sleep(2)
|
| 106 |
+
|
| 107 |
+
print(f"GPU allocated memory: {torch.cuda.memory_allocated() / 1024**3:.2f} GB")
|
| 108 |
+
print(f"GPU reserved memory: {torch.cuda.memory_reserved() / 1024**3:.2f} GB")
|
| 109 |
+
|
| 110 |
+
import psutil
|
| 111 |
+
# Get memory details
|
| 112 |
+
mem = psutil.virtual_memory()
|
| 113 |
+
print(f"Total RAM: {mem.total / (1024 ** 3):.2f} GB")
|
| 114 |
+
print(f"Available RAM: {mem.available / (1024 ** 3):.2f} GB")
|
| 115 |
+
print(f"Used RAM: {mem.used / (1024 ** 3):.2f} GB")
|
| 116 |
+
print(f"Free RAM: {mem.free / (1024 ** 3):.2f} GB")
|
| 117 |
+
swap = psutil.swap_memory()
|
| 118 |
+
print(f"Total Swap: {swap.total / (1024 ** 3):.2f} GB")
|
| 119 |
+
print(f"Used Swap: {swap.used / (1024 ** 3):.2f} GB")
|
| 120 |
+
print(f"Free Swap: {swap.free / (1024 ** 3):.2f} GB")
|
| 121 |
+
|
| 122 |
+
def format_data_ft_local(sample, system_message_training_data, human_message_training_data):
|
| 123 |
+
return {
|
| 124 |
+
"messages": [
|
| 125 |
+
{
|
| 126 |
+
"role": "system",
|
| 127 |
+
"content": [{"type": "text", "text": system_message_training_data}],
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"role": "user",
|
| 131 |
+
"content": [
|
| 132 |
+
{
|
| 133 |
+
"type": "image",
|
| 134 |
+
"image": sample["image"],
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"type": "text",
|
| 138 |
+
"text": human_message_training_data,
|
| 139 |
+
},
|
| 140 |
+
],
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"role": "assistant",
|
| 144 |
+
"content": [{"type": "text", "text": sample["label"]}],
|
| 145 |
+
},
|
| 146 |
+
],
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
def create_data_pkl(df, output_path):
|
| 150 |
+
system_message_training_data = "You are an assistant for question-answering tasks."
|
| 151 |
+
|
| 152 |
+
human_message_training_data = "Do the user-provided task on the input image. \
|
| 153 |
+
The answer must be provided in JSON format. \
|
| 154 |
+
The task is: " + "Extract the features" + ".\
|
| 155 |
+
If there is no information of a target, return NaN."
|
| 156 |
+
|
| 157 |
+
dataset_id = "path-to-directory-of-training-dataset-from-HF"
|
| 158 |
+
train_dataset = load_dataset(dataset_id)
|
| 159 |
+
|
| 160 |
+
in_file_data_entering_train = 'path-to-file/train.parquet'
|
| 161 |
+
df_train = pd.read_parquet(in_file_data_entering_train, engine='pyarrow')
|
| 162 |
+
|
| 163 |
+
list_response_train = []
|
| 164 |
+
start_index = 0
|
| 165 |
+
for index, row in tqdm(df_train.iloc[start_index:].iterrows(), total=len(df_train)):
|
| 166 |
+
filename = row.filename
|
| 167 |
+
|
| 168 |
+
if filename not in df['filename'].values:
|
| 169 |
+
continue
|
| 170 |
+
|
| 171 |
+
sample = {}
|
| 172 |
+
|
| 173 |
+
# IMAGE
|
| 174 |
+
sample["image"] = train_dataset['train'][index]['image']
|
| 175 |
+
|
| 176 |
+
# RESPONSE EXAMPLES OF ASSISTANT
|
| 177 |
+
pp_data_per_image = ""
|
| 178 |
+
result = []
|
| 179 |
+
for idx, value in row.items():
|
| 180 |
+
if idx == 'label' or idx == 'filename':
|
| 181 |
+
continue
|
| 182 |
+
if pd.notnull(value):
|
| 183 |
+
if idx == 'product_weight':
|
| 184 |
+
number = value.split(' ')[0]
|
| 185 |
+
unit = value.split(' ')[1]
|
| 186 |
+
result.append(f"weight_number: {number}")
|
| 187 |
+
result.append(f"weight_unit: {unit}")
|
| 188 |
+
else:
|
| 189 |
+
result.append(f"{idx}: {value}")
|
| 190 |
+
pp_data_per_image = ", ".join(result)
|
| 191 |
+
|
| 192 |
+
sample["label"] = "{" + pp_data_per_image + "}"
|
| 193 |
+
|
| 194 |
+
list_response_train.append(format_data_ft_local(sample, system_message_training_data, human_message_training_data))
|
| 195 |
+
|
| 196 |
+
with open(output_path, 'wb') as f:
|
| 197 |
+
pickle.dump(list_response_train, f)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
if __name__ == "__main__":
|
| 201 |
+
hf_token = getpass.getpass("Enter your Hugging Face token: ")
|
| 202 |
+
huggingface_hub.login(token=hf_token)
|
| 203 |
+
|
| 204 |
+
wandb_token = getpass.getpass("Enter your Weight and Bias token: ")
|
| 205 |
+
wandb.login(key=wandb_token)
|
| 206 |
+
|
| 207 |
+
clear_memory()
|
| 208 |
+
|
| 209 |
+
# create .pkl files from random dataset (run only once)
|
| 210 |
+
df_train = pd.read_parquet("path-to-file/df_random_train_10250.parquet", engine="pyarrow")
|
| 211 |
+
df_val = pd.read_parquet("path-to-file/df_random_val_2500.parquet", engine="pyarrow")
|
| 212 |
+
create_data_pkl(df=df_train, output_path='path-to-file/training_data_random_10250.pkl')
|
| 213 |
+
create_data_pkl(df=df_val, output_path='path-to-file/validation_data_random_2500.pkl')
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
# load .pkl files from random dataset
|
| 217 |
+
with open('path-to-file/training_data_random_10250.pkl', 'rb') as f:
|
| 218 |
+
train_dataset = pickle.load(f)
|
| 219 |
+
with open('path-to-file/validation_data_random_2500.pkl', 'rb') as f:
|
| 220 |
+
val_dataset = pickle.load(f)
|
| 221 |
+
|
| 222 |
+
# Hugging Face model id
|
| 223 |
+
model_id = "google/gemma-3-4b-pt"
|
| 224 |
+
|
| 225 |
+
# Check if GPU benefits from bfloat16
|
| 226 |
+
if torch.cuda.get_device_capability()[0] < 8:
|
| 227 |
+
raise ValueError("GPU does not support bfloat16, please use a GPU that supports bfloat16.")
|
| 228 |
+
|
| 229 |
+
# Define model init arguments
|
| 230 |
+
model_kwargs = dict(
|
| 231 |
+
attn_implementation="eager",
|
| 232 |
+
torch_dtype=torch.bfloat16,
|
| 233 |
+
device_map="auto",
|
| 234 |
+
cache_dir="path-to-directory/tmp"
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
# BitsAndBytesConfig int-4 config
|
| 238 |
+
model_kwargs["quantization_config"] = BitsAndBytesConfig(
|
| 239 |
+
load_in_4bit=True,
|
| 240 |
+
bnb_4bit_use_double_quant=True,
|
| 241 |
+
bnb_4bit_quant_type="nf4",
|
| 242 |
+
bnb_4bit_compute_dtype=model_kwargs["torch_dtype"],
|
| 243 |
+
bnb_4bit_quant_storage=model_kwargs["torch_dtype"],
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
# Load model and tokenizer
|
| 247 |
+
model = AutoModelForImageTextToText.from_pretrained(model_id, **model_kwargs)
|
| 248 |
+
processor = AutoProcessor.from_pretrained("google/gemma-3-4b-it")
|
| 249 |
+
|
| 250 |
+
if torch.cuda.is_available():
|
| 251 |
+
for i in range(torch.cuda.device_count()):
|
| 252 |
+
print(f"GPU {i}: {torch.cuda.get_device_name(i)}")
|
| 253 |
+
else:
|
| 254 |
+
print("No GPU available.")
|
| 255 |
+
|
| 256 |
+
folder_date = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
| 257 |
+
output_path = os.path.join("path-to-result-directory", "google_gemma-3-4b-pt", "subset-random", folder_date)
|
| 258 |
+
os.makedirs(output_path, exist_ok=True)
|
| 259 |
+
|
| 260 |
+
cache_path = "~/.cache"
|
| 261 |
+
if os.path.exists(cache_path):
|
| 262 |
+
shutil.rmtree(cache_path)
|
| 263 |
+
|
| 264 |
+
peft_config = peft.LoraConfig(
|
| 265 |
+
lora_alpha=16,
|
| 266 |
+
lora_dropout=0.05,
|
| 267 |
+
r=16,
|
| 268 |
+
bias="none",
|
| 269 |
+
target_modules="all-linear",
|
| 270 |
+
task_type="CAUSAL_LM",
|
| 271 |
+
modules_to_save=[
|
| 272 |
+
"lm_head",
|
| 273 |
+
"embed_tokens",
|
| 274 |
+
],
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
args = trl.SFTConfig(
|
| 278 |
+
output_dir=output_path, # directory to save and repository id
|
| 279 |
+
num_train_epochs=3, # number of training epochs
|
| 280 |
+
per_device_train_batch_size=2, # batch size per device during training
|
| 281 |
+
per_device_eval_batch_size=2, # batch size per device during evaluation
|
| 282 |
+
gradient_accumulation_steps=4, # number of steps before performing a backward/update pass
|
| 283 |
+
gradient_checkpointing=True, # use gradient checkpointing to save memory
|
| 284 |
+
optim="adamw_torch_fused", # use fused adamw optimizer
|
| 285 |
+
logging_steps=5, # log every 5 steps
|
| 286 |
+
save_strategy="epoch", # save checkpoint every epoch
|
| 287 |
+
eval_strategy="epoch", # save checkpoint every epoch
|
| 288 |
+
learning_rate=2e-4, # learning rate, based on QLoRA paper
|
| 289 |
+
bf16=True, # use bfloat16 precision
|
| 290 |
+
max_grad_norm=0.3, # max gradient norm based on QLoRA paper
|
| 291 |
+
warmup_ratio=0.03, # warmup ratio based on QLoRA paper
|
| 292 |
+
lr_scheduler_type="constant", # use constant learning rate scheduler
|
| 293 |
+
push_to_hub=True, # push model to hub
|
| 294 |
+
report_to="wandb",
|
| 295 |
+
gradient_checkpointing_kwargs={
|
| 296 |
+
"use_reentrant": False
|
| 297 |
+
},
|
| 298 |
+
dataset_text_field="", # need a dummy field for collator
|
| 299 |
+
dataset_kwargs={"skip_prepare_dataset": True}, # important for collator
|
| 300 |
+
)
|
| 301 |
+
args.remove_unused_columns = False # important for collator
|
| 302 |
+
with open(os.path.join(output_path, "args.txt"), "w") as f:
|
| 303 |
+
f.write(json.dumps(args.to_dict(), indent=4))
|
| 304 |
+
|
| 305 |
+
trainer = trl.SFTTrainer(
|
| 306 |
+
model=model,
|
| 307 |
+
args=args,
|
| 308 |
+
train_dataset=train_dataset,
|
| 309 |
+
eval_dataset=val_dataset,
|
| 310 |
+
peft_config=peft_config,
|
| 311 |
+
processing_class=processor,
|
| 312 |
+
data_collator=collate_fn,
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
start_time = time.time()
|
| 316 |
+
trainer.train()
|
| 317 |
+
end_time = time.time()
|
| 318 |
+
elapsed_time = end_time - start_time
|
| 319 |
+
|
| 320 |
+
with open(os.path.join(output_path, "elapsed_time.txt"), "w") as file:
|
| 321 |
+
file.write(f"Elapsed time: {elapsed_time:.2f} seconds\n")
|
| 322 |
+
|
| 323 |
+
trainer.save_model(args.output_dir)
|
| 324 |
+
|
| 325 |
+
# free the memory again
|
| 326 |
+
del model
|
| 327 |
+
del trainer
|
| 328 |
+
torch.cuda.empty_cache()
|
code/fine_tuning/fine_tuning_OpenAI_run_inference.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import getpass
|
| 5 |
+
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import io
|
| 8 |
+
import base64
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
|
| 11 |
+
import use_vlm_ft_OpenAI
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def get_img_base64_str(image_path):
|
| 15 |
+
img = Image.open(image_path)
|
| 16 |
+
buffered = io.BytesIO()
|
| 17 |
+
img.save(buffered, format=img.format)
|
| 18 |
+
img_base64_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 19 |
+
return img_base64_str
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
api_key = getpass.getpass("Enter your OpenAI API key: ")
|
| 23 |
+
|
| 24 |
+
in_path_frame_images = './.../rpp-765k_512'
|
| 25 |
+
in_file_data_entering_test = './.../test.parquet'
|
| 26 |
+
|
| 27 |
+
in_model_name = "OpenAI_FT_gpt-4o-2024-08-06"
|
| 28 |
+
in_name_results_output = 'OpenAI_FT_gpt-4o-2024-08-06'
|
| 29 |
+
out_path_results = './.../output'
|
| 30 |
+
|
| 31 |
+
path_outputs = os.path.join(out_path_results, in_model_name)
|
| 32 |
+
os.makedirs(path_outputs, exist_ok=True)
|
| 33 |
+
|
| 34 |
+
os.environ["USED_MODEL"] = "gpt-4o-2024-08-06"
|
| 35 |
+
|
| 36 |
+
dict_log = {}
|
| 37 |
+
dict_log['model'] = in_model_name
|
| 38 |
+
|
| 39 |
+
ft_model = "id-of-fine-tuned-model"
|
| 40 |
+
#######################################################################
|
| 41 |
+
#######################################################################
|
| 42 |
+
df_result = pd.DataFrame(
|
| 43 |
+
columns=['label', 'filename', \
|
| 44 |
+
'brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'weight_number', 'weight_unit', 'different_types'])
|
| 45 |
+
df_result_cost = pd.DataFrame(
|
| 46 |
+
columns=['label', 'filename']
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
df_test = pd.read_parquet(in_file_data_entering_test, engine='pyarrow')
|
| 50 |
+
df_test.reset_index(drop=True, inplace=True)
|
| 51 |
+
|
| 52 |
+
start_index = 0
|
| 53 |
+
output_file = f'{datetime.now().strftime("%Y%m%d_%H%M%S")}_{in_name_results_output}'
|
| 54 |
+
for index, row in df_test.iloc[start_index:].iterrows():
|
| 55 |
+
label = str(row.label)
|
| 56 |
+
filename = row.filename
|
| 57 |
+
|
| 58 |
+
dict_result = {}
|
| 59 |
+
dict_result['label'] = label
|
| 60 |
+
dict_result['filename'] = filename
|
| 61 |
+
dict_result_cost = {}
|
| 62 |
+
dict_result_cost['label'] = label
|
| 63 |
+
dict_result_cost['filename'] = filename
|
| 64 |
+
|
| 65 |
+
############################################
|
| 66 |
+
# PROMPT
|
| 67 |
+
############################################
|
| 68 |
+
# IMAGE
|
| 69 |
+
# image_path = os.path.join( in_path_frame_images, 'test', label, filename )
|
| 70 |
+
image_path = os.path.join( in_path_frame_images, 'train', label, filename )
|
| 71 |
+
query_image_base64 = get_img_base64_str(image_path)
|
| 72 |
+
|
| 73 |
+
# TASK
|
| 74 |
+
task = "Extract all targets."
|
| 75 |
+
dict_log['prompt_task'] = task
|
| 76 |
+
|
| 77 |
+
dict_log, dict_result, dict_result_cost = use_vlm_ft_OpenAI.do_request(
|
| 78 |
+
api_key,
|
| 79 |
+
ft_model,
|
| 80 |
+
query_image_base64,
|
| 81 |
+
task,
|
| 82 |
+
dict_log,
|
| 83 |
+
dict_result,
|
| 84 |
+
dict_result_cost,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
df_result = pd.concat( [ df_result, pd.DataFrame.from_dict([dict_result]) ], ignore_index=True)
|
| 88 |
+
df_result_cost = pd.concat( [ df_result_cost, pd.DataFrame.from_dict([dict_result_cost]) ], ignore_index=True)
|
| 89 |
+
|
| 90 |
+
if index%100 == 0:
|
| 91 |
+
df_result.to_parquet( os.path.join(path_outputs, output_file + '_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 92 |
+
df_result_cost.to_parquet( os.path.join(path_outputs, output_file + '_costs_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 93 |
+
df_result = pd.DataFrame( columns=['label', 'filename', \
|
| 94 |
+
'brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'weight_number', 'weight_unit', 'different_types'])
|
| 95 |
+
df_result_cost = pd.DataFrame(columns=['label', 'filename'])
|
| 96 |
+
|
| 97 |
+
df_result.to_parquet( os.path.join(path_outputs, output_file + '_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 98 |
+
df_result_cost.to_parquet( os.path.join(path_outputs, output_file + '_costs_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 99 |
+
|
| 100 |
+
#######################################################################
|
| 101 |
+
#######################################################################
|
| 102 |
+
|
| 103 |
+
with open(os.path.join(path_outputs, in_name_results_output + '.json'), 'w') as json_file:
|
| 104 |
+
json.dump(dict_log, json_file)
|
code/fine_tuning/fine_tuning_OpenAI_train_model.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Upload training and validation file:<br>
|
| 2 |
+
<br>
|
| 3 |
+
curl -v https://api.openai.com/v1/files -H "Authorization: Bearer [OpenAI Key]" -F purpose="fine-tune" -F file="@OpenAI_subset_random_train_10250.jsonl"<br>
|
| 4 |
+
curl -v https://api.openai.com/v1/files -H "Authorization: Bearer [OpenAI Key]" -F purpose="fine-tune" -F file="@OpenAI_subset_random_val_2500.jsonl"<br>
|
| 5 |
+
<br>
|
| 6 |
+
<br>
|
| 7 |
+
Start fine-tuning job:<br>
|
| 8 |
+
<br>
|
| 9 |
+
curl -v https://api.openai.com/v1/fine_tuning/jobs -H "Content-Type: application/json" -H "Authorization: Bearer [OpenAI Key]" -d '{ "training_file": "file-[train-file-id]", "validation_file": "file-[val-file-id]", "model": "gpt-4o-2024-08-06", "method" : {"type": "supervised", "supervised": {"hyperparameters": {"n_epochs": 3}}} }'
|
code/fine_tuning/use_vlm_ft_OpenAI.py
ADDED
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import httpx
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import requests
|
| 5 |
+
import subprocess
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
import openai
|
| 9 |
+
|
| 10 |
+
from enum import Enum
|
| 11 |
+
from pydantic import BaseModel, Field
|
| 12 |
+
from typing_extensions import List
|
| 13 |
+
from typing import Literal, Optional
|
| 14 |
+
|
| 15 |
+
from requests.exceptions import ConnectionError
|
| 16 |
+
|
| 17 |
+
VLM_TEMPERATURE = 0
|
| 18 |
+
######################################################################
|
| 19 |
+
######################################################################
|
| 20 |
+
|
| 21 |
+
class WeightUnit(Enum):
|
| 22 |
+
GRAMM = "Gramm"
|
| 23 |
+
KILOGRAM = "Kilogramm"
|
| 24 |
+
MILLILITER = "Milliliter"
|
| 25 |
+
LITER = "Liter"
|
| 26 |
+
WASCHLADUNGEN = "Waschladungen"
|
| 27 |
+
BLATT = "Blatt"
|
| 28 |
+
STUECK = "Stück"
|
| 29 |
+
|
| 30 |
+
class YesNo(Enum):
|
| 31 |
+
YES = "yes"
|
| 32 |
+
NO = "no"
|
| 33 |
+
|
| 34 |
+
class product_promotion_data(BaseModel):
|
| 35 |
+
"""Collection of product and promotion data of an product advertisement."""
|
| 36 |
+
brand: str = Field(description="The brand associated with the product")
|
| 37 |
+
product_category: List[str] = Field(description="List of categories associated with the product.")
|
| 38 |
+
price: float = Field(description="The promotional price.")
|
| 39 |
+
regular_price: Optional[float] = Field(default=None, description="The regular price of the promotion.")
|
| 40 |
+
relative_discount: Optional[int] = Field(default=None, description="The relative discount of the promotion.")
|
| 41 |
+
absolute_discount: Optional[float] = Field(default=None, description="The absolute discount of the promotion.")
|
| 42 |
+
GTINs: List[str] = Field(description="List of the GTINs for the products.")
|
| 43 |
+
weight_number: float = Field(description="Only the numerical weight specication.")
|
| 44 |
+
# weight_unit: WeightUnit = Field(description="Only the weight unit.")
|
| 45 |
+
weight_unit: Literal["Gramm", "Kilogramm", "Milliliter", "Liter", "Waschladungen", "Blatt", "Stück"] = Field(description="Only the weight unit.")
|
| 46 |
+
# different_types: YesNo = Field(description="If promotion offer different sorts.")
|
| 47 |
+
different_types: Literal["yes", "no"] = Field(description="If promotion offer different sorts.")
|
| 48 |
+
|
| 49 |
+
######################################################################
|
| 50 |
+
######################################################################
|
| 51 |
+
|
| 52 |
+
def convert_items_to_strings(prediction):
|
| 53 |
+
if isinstance(prediction, str):
|
| 54 |
+
return prediction
|
| 55 |
+
elif isinstance(prediction, list):
|
| 56 |
+
return ', '.join(prediction)
|
| 57 |
+
else:
|
| 58 |
+
return str(prediction)
|
| 59 |
+
|
| 60 |
+
def get_output_results(dict_output, dict_result):
|
| 61 |
+
for key, value in dict_output.items():
|
| 62 |
+
if key == 'brand':
|
| 63 |
+
dict_result['brand'] = convert_items_to_strings(dict_output['brand'])
|
| 64 |
+
elif key == 'product_category':
|
| 65 |
+
dict_result['product_category'] = convert_items_to_strings(dict_output['product_category'])
|
| 66 |
+
elif key == 'price':
|
| 67 |
+
dict_result['price'] = convert_items_to_strings(dict_output['price'])
|
| 68 |
+
elif key == 'regular_price':
|
| 69 |
+
dict_result['regular_price'] = convert_items_to_strings(dict_output['regular_price'])
|
| 70 |
+
elif key == 'relative_discount':
|
| 71 |
+
dict_result['relative_discount'] = convert_items_to_strings(dict_output['relative_discount'])
|
| 72 |
+
elif key == 'absolute_discount':
|
| 73 |
+
dict_result['absolute_discount'] = convert_items_to_strings(dict_output['absolute_discount'])
|
| 74 |
+
elif key == 'GTINs':
|
| 75 |
+
dict_result['GTINs'] = convert_items_to_strings(dict_output['GTINs'])
|
| 76 |
+
elif key == 'weight_number':
|
| 77 |
+
dict_result['weight_number'] = convert_items_to_strings(dict_output['weight_number'])
|
| 78 |
+
elif key == 'weight_unit':
|
| 79 |
+
dict_result['weight_unit'] = convert_items_to_strings(dict_output['weight_unit'])
|
| 80 |
+
elif key == 'different_types':
|
| 81 |
+
dict_result['different_types'] = convert_items_to_strings(dict_output['different_types'])
|
| 82 |
+
return dict_result
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def prompt(query_image, task, dict_log):
|
| 86 |
+
system_message = "You are an assistant for question-answering tasks."
|
| 87 |
+
dict_log['system_message'] = system_message
|
| 88 |
+
|
| 89 |
+
human_message_text = "Do the user-provided task on the input image. \
|
| 90 |
+
The answer must be provided in JSON format. \
|
| 91 |
+
The task is: " + task + ".\
|
| 92 |
+
If there is no information of a target, return NaN."
|
| 93 |
+
dict_log['human_message_text'] = human_message_text
|
| 94 |
+
|
| 95 |
+
human_messages = [
|
| 96 |
+
{
|
| 97 |
+
"type": "input_text",
|
| 98 |
+
"text": human_message_text
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"type": "input_image",
|
| 102 |
+
"image_url": f"data:image/jpeg;base64,{query_image}",
|
| 103 |
+
},
|
| 104 |
+
]
|
| 105 |
+
|
| 106 |
+
input_messages = [
|
| 107 |
+
{"role": "system", "content": system_message},
|
| 108 |
+
{"role": "user", "content": human_messages}
|
| 109 |
+
]
|
| 110 |
+
|
| 111 |
+
return dict_log, input_messages
|
| 112 |
+
|
| 113 |
+
def get_response_format():
|
| 114 |
+
schema = product_promotion_data.model_json_schema()
|
| 115 |
+
schema['type'] = 'object'
|
| 116 |
+
schema['additionalProperties'] = False
|
| 117 |
+
schema['required'] = list(schema.get('properties', {}).keys())
|
| 118 |
+
|
| 119 |
+
return {
|
| 120 |
+
"type": "json_schema",
|
| 121 |
+
"name": "product_promotion_data",
|
| 122 |
+
"schema": schema
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
def do_request(api_key, ft_model, query_image_base64, task, dict_log, dict_result, dict_result_cost):
|
| 126 |
+
dict_log, messages = prompt(query_image_base64, task, dict_log)
|
| 127 |
+
response_format = get_response_format()
|
| 128 |
+
|
| 129 |
+
try:
|
| 130 |
+
start_time = time.time()
|
| 131 |
+
while True:
|
| 132 |
+
try:
|
| 133 |
+
payload = {
|
| 134 |
+
"model": ft_model,
|
| 135 |
+
"input": messages,
|
| 136 |
+
"text": {
|
| 137 |
+
"format": response_format
|
| 138 |
+
}
|
| 139 |
+
}
|
| 140 |
+
payload_json = json.dumps(payload)
|
| 141 |
+
|
| 142 |
+
curl_cmd = [
|
| 143 |
+
"curl",
|
| 144 |
+
f"https://api.openai.com/v1/responses",
|
| 145 |
+
"-H", "Content-Type: application/json",
|
| 146 |
+
"-H", f"Authorization: Bearer {api_key}",
|
| 147 |
+
"-d", payload_json,
|
| 148 |
+
"--max-time", "60" # timeout in seconds
|
| 149 |
+
]
|
| 150 |
+
result = subprocess.run(curl_cmd, capture_output=True, text=True)
|
| 151 |
+
except:
|
| 152 |
+
print("FAILED")
|
| 153 |
+
continue
|
| 154 |
+
break
|
| 155 |
+
elapsed_time = time.time() - start_time
|
| 156 |
+
dict_result_cost['elapsed_time_[s]'] = float("{:.2f}".format(elapsed_time))
|
| 157 |
+
|
| 158 |
+
raw = result.stdout
|
| 159 |
+
response = json.loads(raw)
|
| 160 |
+
|
| 161 |
+
if response['output'][0]['content'][0]['text']:
|
| 162 |
+
dict_result = get_output_results(json.loads(response['output'][0]['content'][0]['text']), dict_result)
|
| 163 |
+
print('dict_result')
|
| 164 |
+
print(dict_result)
|
| 165 |
+
print(response['usage'])
|
| 166 |
+
dict_result_cost = token_price_evaluation(response['usage'], dict_result_cost)
|
| 167 |
+
except (KeyError, IndexError) as e:
|
| 168 |
+
print(f"Key or index missing: {e}")
|
| 169 |
+
return dict_log, dict_result, dict_result_cost
|
| 170 |
+
except openai.BadRequestError as e:
|
| 171 |
+
print(f"BadRequestError: {e}")
|
| 172 |
+
return dict_log, dict_result, dict_result_cost
|
| 173 |
+
except openai.ContentFilterFinishReasonError as e:
|
| 174 |
+
print(f"ContentFilterFinishReasonError: {e}")
|
| 175 |
+
return dict_log, dict_result, dict_result_cost
|
| 176 |
+
except ConnectionError as e:
|
| 177 |
+
print(f"Connection error occurred: {e}")
|
| 178 |
+
return dict_log, dict_result, dict_result_cost
|
| 179 |
+
except requests.exceptions.RequestException as e:
|
| 180 |
+
print(f"An error occurred: {e}")
|
| 181 |
+
return dict_log, dict_result, dict_result_cost
|
| 182 |
+
except ValueError as ve:
|
| 183 |
+
print(f"Validation error: {ve}")
|
| 184 |
+
return dict_log, dict_result, dict_result_cost
|
| 185 |
+
except httpx.HTTPStatusError as e:
|
| 186 |
+
print(f"HTTPStatusError: {e}")
|
| 187 |
+
time.sleep(60)
|
| 188 |
+
return dict_log, dict_result, dict_result_cost
|
| 189 |
+
except openai.RateLimitError as e:
|
| 190 |
+
print(f"RateLimitError: {e}")
|
| 191 |
+
time.sleep(60)
|
| 192 |
+
return dict_log, dict_result, dict_result_cost
|
| 193 |
+
except openai.InternalServerError as e:
|
| 194 |
+
print(f"InternalServerError: {e}")
|
| 195 |
+
time.sleep(60)
|
| 196 |
+
return dict_log, dict_result, dict_result_cost
|
| 197 |
+
|
| 198 |
+
return dict_log, dict_result, dict_result_cost
|
| 199 |
+
|
| 200 |
+
# https://ai.google.dev/gemini-api/docs/pricing
|
| 201 |
+
def token_price_evaluation(response, dict_result_cost):
|
| 202 |
+
PRICING = {
|
| 203 |
+
"gpt-5-mini": {"input": 0.25 / 1000000, "output": 2.00 / 1000000},
|
| 204 |
+
"gpt-5": {"input": 1.25 / 1000000, "output": 10.00 / 1000000},
|
| 205 |
+
"gpt-4o-2024-08-06": {"input": 2.50 / 1000000, "output": 10.00 / 1000000},
|
| 206 |
+
}
|
| 207 |
+
MODEL = os.environ["USED_MODEL"]
|
| 208 |
+
|
| 209 |
+
# OpenAI payload
|
| 210 |
+
input_tokens = response['input_tokens']
|
| 211 |
+
output_tokens = response['output_tokens']
|
| 212 |
+
total_tokens = response['total_tokens']
|
| 213 |
+
|
| 214 |
+
input_cost = input_tokens * PRICING[MODEL]["input"]
|
| 215 |
+
output_cost = output_tokens * PRICING[MODEL]["output"]
|
| 216 |
+
total_cost = input_cost + output_cost
|
| 217 |
+
|
| 218 |
+
print(f"Model Used: {MODEL}")
|
| 219 |
+
print(f"Input Tokens: {input_tokens}, Cost: ${input_cost:.4f}")
|
| 220 |
+
print(f"Output Tokens: {output_tokens}, Cost: ${output_cost:.4f}")
|
| 221 |
+
print(f"Total Tokens: {total_tokens}")
|
| 222 |
+
print(f"Total Cost: ${total_cost:.4f}")
|
| 223 |
+
print('*'*30)
|
| 224 |
+
|
| 225 |
+
dict_result_cost['input_tokens'] = input_tokens
|
| 226 |
+
dict_result_cost['output_tokens'] = output_tokens
|
| 227 |
+
dict_result_cost['total_tokens'] = total_tokens
|
| 228 |
+
dict_result_cost['total_cost'] = float(total_cost)
|
| 229 |
+
|
| 230 |
+
return dict_result_cost
|
code/fine_tuning/use_vlm_ft_gemma3.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import httpx
|
| 2 |
+
import re
|
| 3 |
+
import requests
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
from enum import Enum
|
| 7 |
+
from pydantic import BaseModel, Field
|
| 8 |
+
from typing_extensions import List
|
| 9 |
+
from typing import Literal, Optional
|
| 10 |
+
|
| 11 |
+
from requests.exceptions import ConnectionError
|
| 12 |
+
|
| 13 |
+
from PIL import Image
|
| 14 |
+
|
| 15 |
+
VLM_TEMPERATURE = 0
|
| 16 |
+
######################################################################
|
| 17 |
+
######################################################################
|
| 18 |
+
|
| 19 |
+
class WeightUnit(Enum):
|
| 20 |
+
GRAMM = "Gramm"
|
| 21 |
+
KILOGRAM = "Kilogramm"
|
| 22 |
+
MILLILITER = "Milliliter"
|
| 23 |
+
LITER = "Liter"
|
| 24 |
+
WASCHLADUNGEN = "Waschladungen"
|
| 25 |
+
BLATT = "Blatt"
|
| 26 |
+
STUECK = "Stück"
|
| 27 |
+
|
| 28 |
+
class YesNo(Enum):
|
| 29 |
+
YES = "yes"
|
| 30 |
+
NO = "no"
|
| 31 |
+
|
| 32 |
+
class product_promotion_data(BaseModel):
|
| 33 |
+
"""Collection of product and promotion data of an product advertisement."""
|
| 34 |
+
brand: str = Field(description="The brand associated with the product")
|
| 35 |
+
product_category: List[str] = Field(description="List of categories associated with the product.")
|
| 36 |
+
price: float = Field(description="The promotional price.")
|
| 37 |
+
regular_price: Optional[float] = Field(default=None, description="The regular price of the promotion.")
|
| 38 |
+
relative_discount: Optional[int] = Field(default=None, description="The relative discount of the promotion.")
|
| 39 |
+
absolute_discount: Optional[float] = Field(default=None, description="The absolute discount of the promotion.")
|
| 40 |
+
GTINs: List[str] = Field(description="List of the GTINs for the products.")
|
| 41 |
+
weight_number: float = Field(description="Only the numerical weight specication.")
|
| 42 |
+
# weight_unit: WeightUnit = Field(description="Only the weight unit.")
|
| 43 |
+
weight_unit: Literal["Gramm", "Kilogramm", "Milliliter", "Liter", "Waschladungen", "Blatt", "Stück"] = Field(description="Only the weight unit.")
|
| 44 |
+
# different_types: YesNo = Field(description="If promotion offer different sorts.")
|
| 45 |
+
different_types: Literal["yes", "no"] = Field(description="If promotion offer different sorts.")
|
| 46 |
+
|
| 47 |
+
######################################################################
|
| 48 |
+
######################################################################
|
| 49 |
+
|
| 50 |
+
def convert_items_to_strings(prediction):
|
| 51 |
+
if isinstance(prediction, str):
|
| 52 |
+
return prediction
|
| 53 |
+
elif isinstance(prediction, list):
|
| 54 |
+
return ', '.join(prediction)
|
| 55 |
+
else:
|
| 56 |
+
return str(prediction)
|
| 57 |
+
|
| 58 |
+
def get_output_results(dict_output, dict_result):
|
| 59 |
+
for key, value in dict_output.items():
|
| 60 |
+
if key == 'brand':
|
| 61 |
+
dict_result['brand'] = convert_items_to_strings(dict_output['brand'])
|
| 62 |
+
elif key == 'product_category':
|
| 63 |
+
dict_result['product_category'] = convert_items_to_strings(dict_output['product_category'])
|
| 64 |
+
elif key == 'price':
|
| 65 |
+
dict_result['price'] = convert_items_to_strings(dict_output['price'])
|
| 66 |
+
elif key == 'regular_price':
|
| 67 |
+
dict_result['regular_price'] = convert_items_to_strings(dict_output['regular_price'])
|
| 68 |
+
elif key == 'relative_discount':
|
| 69 |
+
dict_result['relative_discount'] = convert_items_to_strings(dict_output['relative_discount'])
|
| 70 |
+
elif key == 'absolute_discount':
|
| 71 |
+
dict_result['absolute_discount'] = convert_items_to_strings(dict_output['absolute_discount'])
|
| 72 |
+
elif key == 'GTINs':
|
| 73 |
+
dict_result['GTINs'] = convert_items_to_strings(dict_output['GTINs'])
|
| 74 |
+
elif key == 'weight_number':
|
| 75 |
+
dict_result['weight_number'] = convert_items_to_strings(dict_output['weight_number'])
|
| 76 |
+
elif key == 'weight_unit':
|
| 77 |
+
dict_result['weight_unit'] = convert_items_to_strings(dict_output['weight_unit'])
|
| 78 |
+
elif key == 'different_types':
|
| 79 |
+
dict_result['different_types'] = convert_items_to_strings(dict_output['different_types'])
|
| 80 |
+
return dict_result
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def prompt(query_image, task, dict_log):
|
| 84 |
+
system_message = "You are an assistant for question-answering tasks."
|
| 85 |
+
dict_log['system_message'] = system_message
|
| 86 |
+
|
| 87 |
+
human_message_text = "Do the user-provided task on the input image. \
|
| 88 |
+
The answer must be provided in JSON format. \
|
| 89 |
+
The task is: " + task + ".\
|
| 90 |
+
If there is no information of a target, return NaN."
|
| 91 |
+
dict_log['human_message_text'] = human_message_text
|
| 92 |
+
|
| 93 |
+
input_messages = [
|
| 94 |
+
{
|
| 95 |
+
"role": "system",
|
| 96 |
+
"content": [{"type": "text", "text": system_message}],
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"role": "user",
|
| 100 |
+
"content": [
|
| 101 |
+
{
|
| 102 |
+
"type": "image",
|
| 103 |
+
"image": query_image,
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"type": "text",
|
| 107 |
+
"text": human_message_text,
|
| 108 |
+
},
|
| 109 |
+
],
|
| 110 |
+
},
|
| 111 |
+
]
|
| 112 |
+
|
| 113 |
+
return dict_log, input_messages
|
| 114 |
+
|
| 115 |
+
def process_vision_info(messages: list[dict]) -> list[Image.Image]:
|
| 116 |
+
image_inputs = []
|
| 117 |
+
# Iterate through each conversation
|
| 118 |
+
for msg in messages:
|
| 119 |
+
# Get content (ensure it's a list)
|
| 120 |
+
content = msg.get("content", [])
|
| 121 |
+
if not isinstance(content, list):
|
| 122 |
+
content = [content]
|
| 123 |
+
|
| 124 |
+
# Check each content element for images
|
| 125 |
+
for element in content:
|
| 126 |
+
if isinstance(element, dict) and (
|
| 127 |
+
"image" in element or element.get("type") == "image"
|
| 128 |
+
):
|
| 129 |
+
# Get the image and convert to RGB
|
| 130 |
+
if "image" in element:
|
| 131 |
+
image = element["image"]
|
| 132 |
+
else:
|
| 133 |
+
image = element
|
| 134 |
+
image_inputs.append(image.convert("RGB"))
|
| 135 |
+
return image_inputs
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def get_dict_from_output_text(output_text):
|
| 139 |
+
# Remove the surrounding braces:
|
| 140 |
+
trimmed = output_text[0].strip('{}').strip()
|
| 141 |
+
|
| 142 |
+
# Find all keys with their start positions:
|
| 143 |
+
# Key pattern: word characters followed by colon
|
| 144 |
+
matches = list(re.finditer(r'(\b\w+\b)\s*:', trimmed))
|
| 145 |
+
|
| 146 |
+
data = {}
|
| 147 |
+
for i, match in enumerate(matches):
|
| 148 |
+
key = match.group(1)
|
| 149 |
+
start = match.end() # position after colon
|
| 150 |
+
|
| 151 |
+
# end is start of next key or end of string
|
| 152 |
+
if i+1 < len(matches):
|
| 153 |
+
end = matches[i+1].start()
|
| 154 |
+
else:
|
| 155 |
+
end = len(trimmed)
|
| 156 |
+
|
| 157 |
+
# The value is substring from start:end
|
| 158 |
+
value = trimmed[start:end].strip().rstrip(',')
|
| 159 |
+
|
| 160 |
+
# Clean value - strip whitespace and trailing commas
|
| 161 |
+
value = value.strip()
|
| 162 |
+
|
| 163 |
+
data[key] = value
|
| 164 |
+
|
| 165 |
+
return data
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def do_request(ft_model, processor, pil_image, task, dict_log, dict_result, dict_result_cost):
|
| 169 |
+
dict_log, messages = prompt(pil_image, task, dict_log)
|
| 170 |
+
|
| 171 |
+
text = processor.apply_chat_template(
|
| 172 |
+
messages, tokenize=False, add_generation_prompt=True
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
# Process the image and text
|
| 176 |
+
image_inputs = process_vision_info(messages)
|
| 177 |
+
|
| 178 |
+
# Tokenize the text and process the images
|
| 179 |
+
inputs = processor(
|
| 180 |
+
text=[text],
|
| 181 |
+
images=image_inputs,
|
| 182 |
+
padding=True,
|
| 183 |
+
return_tensors="pt",
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
# Move the inputs to the device
|
| 187 |
+
inputs = inputs.to(ft_model.device)
|
| 188 |
+
|
| 189 |
+
stop_token_ids = [processor.tokenizer.eos_token_id, processor.tokenizer.convert_tokens_to_ids("<end_of_turn>")]
|
| 190 |
+
|
| 191 |
+
try:
|
| 192 |
+
start_time = time.time()
|
| 193 |
+
try:
|
| 194 |
+
# Generate the output
|
| 195 |
+
generated_ids = ft_model.generate(**inputs, max_new_tokens=256, top_p=1.0, do_sample=True, temperature=0.8, eos_token_id=stop_token_ids, disable_compile=True)
|
| 196 |
+
except:
|
| 197 |
+
print("FAILED")
|
| 198 |
+
elapsed_time = time.time() - start_time
|
| 199 |
+
dict_result_cost['elapsed_time_[s]'] = float("{:.2f}".format(elapsed_time))
|
| 200 |
+
|
| 201 |
+
# Trim the generation and decode the output to text
|
| 202 |
+
generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
|
| 203 |
+
output_text = processor.batch_decode(
|
| 204 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
if len(output_text) == 1:
|
| 208 |
+
dict_output = get_dict_from_output_text(output_text)
|
| 209 |
+
dict_result = get_output_results(dict_output, dict_result)
|
| 210 |
+
print('dict_result')
|
| 211 |
+
print(dict_result)
|
| 212 |
+
except ConnectionError as e:
|
| 213 |
+
print(f"Connection error occurred: {e}")
|
| 214 |
+
return dict_log, dict_result, dict_result_cost
|
| 215 |
+
except requests.exceptions.RequestException as e:
|
| 216 |
+
print(f"An error occurred: {e}")
|
| 217 |
+
return dict_log, dict_result, dict_result_cost
|
| 218 |
+
except ValueError as ve:
|
| 219 |
+
print(f"Validation error: {ve}")
|
| 220 |
+
return dict_log, dict_result, dict_result_cost
|
| 221 |
+
except httpx.HTTPStatusError as e:
|
| 222 |
+
print(f"HTTPStatusError: {e}")
|
| 223 |
+
time.sleep(60)
|
| 224 |
+
return dict_log, dict_result, dict_result_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numeric(df_pred_copy[f], errors='coerce')
|
| 9 |
+
|
| 10 |
+
mask = df_true[f].notna() & df_pred_copy[f].notna()
|
| 11 |
+
df_data_mse_rmse.at['non-null GT', f] = int(df_true[f].notna().value_counts().get(True, 0))
|
| 12 |
+
df_data_mse_rmse.at['non-null prediction', f] = int(df_pred_copy[f].notna().value_counts().get(True, 0))
|
| 13 |
+
df_data_mse_rmse.at['non-null GT AND prediction', f]= int(mask.value_counts().get(True, 0))
|
| 14 |
+
df_data_mse_rmse.at['null GT', f] = int(df_true[f].notna().value_counts().get(False, 0))
|
| 15 |
+
df_data_mse_rmse.at['null prediction', f] = int(df_pred_copy[f].notna().value_counts().get(False, 0))
|
| 16 |
+
df_data_mse_rmse.at['null GT AND prediction', f] = int(mask.value_counts().get(False, 0))
|
| 17 |
+
|
| 18 |
+
y_true_clean = df_true.loc[mask, f]
|
| 19 |
+
y_pred_clean = df_pred.loc[mask, f]
|
| 20 |
+
|
| 21 |
+
mse = mean_squared_error(y_true_clean, y_pred_clean)
|
| 22 |
+
df_data_mse_rmse.at['MSE', f] = mse
|
| 23 |
+
|
| 24 |
+
rmse = mean_squared_error(y_true_clean, y_pred_clean, squared=False)
|
| 25 |
+
df_data_mse_rmse.at['RMSE', f] = rmse
|
| 26 |
+
|
| 27 |
+
return df_data_mse_rmse
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_edit_distances(df_true , df_pred, f, df_edit_distance_brand):
|
| 31 |
+
mask = df_true[f].notna() & df_pred[f].notna()
|
| 32 |
+
|
| 33 |
+
y_true_clean = df_true.loc[mask, f]
|
| 34 |
+
y_pred_clean = df_pred.loc[mask, f]
|
| 35 |
+
|
| 36 |
+
df_feature_true = pd.DataFrame({
|
| 37 |
+
f : y_true_clean,
|
| 38 |
+
f + '_lower' : y_true_clean.str.lower()
|
| 39 |
+
})
|
| 40 |
+
df_feature_pred = pd.DataFrame({
|
| 41 |
+
f : y_pred_clean,
|
| 42 |
+
f + '_lower' : y_pred_clean.str.lower()
|
| 43 |
+
})
|
| 44 |
+
|
| 45 |
+
df_feature_true = df_feature_true.sort_index()
|
| 46 |
+
df_feature_pred = df_feature_pred.sort_index()
|
| 47 |
+
|
| 48 |
+
df_edit_distance_brand['true_' + f + '_lower'] = df_feature_true[f + '_lower']
|
| 49 |
+
df_edit_distance_brand['pred_' + f + '_lower'] = df_feature_pred[f + '_lower']
|
| 50 |
+
|
| 51 |
+
# Levenshtein distance
|
| 52 |
+
import Levenshtein
|
| 53 |
+
lev_dist = [
|
| 54 |
+
Levenshtein.distance(n1, n2)
|
| 55 |
+
for n1, n2 in zip(df_feature_true[f + '_lower'], df_feature_pred[f + '_lower'])
|
| 56 |
+
]
|
| 57 |
+
df_edit_distance_brand['levenshtein_dist'] = lev_dist
|
| 58 |
+
|
| 59 |
+
# Hamming Distance
|
| 60 |
+
ham_dist = [
|
| 61 |
+
sum(n1 != n2 for n1, n2 in zip(str(s1), str(s2))) if len(str(s1)) == len(str(s2)) else None
|
| 62 |
+
for s1, s2 in zip(df_feature_true[f + '_lower'], df_feature_pred[f + '_lower'])
|
| 63 |
+
]
|
| 64 |
+
df_edit_distance_brand['hamming_dist'] = ham_dist
|
| 65 |
+
|
| 66 |
+
# Damerau-Levenshtein Distance
|
| 67 |
+
import textdistance
|
| 68 |
+
damerau_lev_dist = [
|
| 69 |
+
textdistance.damerau_levenshtein.distance(str(n1), str(n2))
|
| 70 |
+
for n1, n2 in zip(df_feature_true[f + '_lower'], df_feature_pred[f + '_lower'])
|
| 71 |
+
]
|
| 72 |
+
df_edit_distance_brand['damerau_levenshtein_dist'] = damerau_lev_dist
|
| 73 |
+
|
| 74 |
+
# Jaro Distance
|
| 75 |
+
jaro_dist = [
|
| 76 |
+
textdistance.jaro.distance(str(n1), str(n2))
|
| 77 |
+
for n1, n2 in zip(df_feature_true[f + '_lower'], df_feature_pred[f + '_lower'])
|
| 78 |
+
]
|
| 79 |
+
df_edit_distance_brand['jaro_dist'] = jaro_dist
|
| 80 |
+
|
| 81 |
+
return df_edit_distance_brand
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def string_operations(string):
|
| 86 |
+
import unicodedata
|
| 87 |
+
import re
|
| 88 |
+
|
| 89 |
+
string = string.lower()
|
| 90 |
+
string = unicodedata.normalize('NFD', string)
|
| 91 |
+
string = ''.join(char for char in string if unicodedata.category(char) != 'Mn')
|
| 92 |
+
string = re.sub(r"[']", "", string)
|
| 93 |
+
|
| 94 |
+
return string
|
| 95 |
+
|
| 96 |
+
def brand_fuzzy_match(str_pred, str_gt):
|
| 97 |
+
import Levenshtein
|
| 98 |
+
import re
|
| 99 |
+
|
| 100 |
+
distance = Levenshtein.distance(str_pred, str_gt)
|
| 101 |
+
similarity = 1 - (distance / max(len(str_pred), len(str_gt)))
|
| 102 |
+
|
| 103 |
+
if similarity > 0.5:
|
| 104 |
+
return 1
|
| 105 |
+
else:
|
| 106 |
+
words = re.split(r'\W+', str_pred)
|
| 107 |
+
list_words_pred = [word for word in words if word]
|
| 108 |
+
words = re.split(r'\W+', str_gt)
|
| 109 |
+
list_words_gt = [word for word in words if word]
|
| 110 |
+
if any(item in list_words_gt for item in list_words_pred):
|
| 111 |
+
return 1
|
| 112 |
+
else:
|
| 113 |
+
return 0
|
| 114 |
+
|
| 115 |
+
def price_discount_fuzzy_match(f, str_pred, str_gt):
|
| 116 |
+
if f == 'relative_discount' and str_gt != 'nan':
|
| 117 |
+
str_gt = str(int(float(str_gt)))
|
| 118 |
+
|
| 119 |
+
if str_pred == str_gt:
|
| 120 |
+
return 1
|
| 121 |
+
else:
|
| 122 |
+
return 0
|
| 123 |
+
|
| 124 |
+
def product_category_fuzzy_match(str_pred, str_gt):
|
| 125 |
+
if str_pred == str_gt:
|
| 126 |
+
return 1
|
| 127 |
+
else:
|
| 128 |
+
return 0
|
| 129 |
+
|
| 130 |
+
def gtins_fuzzy_match(str_pred, str_gt):
|
| 131 |
+
if str_pred == str_gt:
|
| 132 |
+
return 1
|
| 133 |
+
else:
|
| 134 |
+
return 0
|
| 135 |
+
|
| 136 |
+
def product_weight_fuzzy_match(str_pred, str_gt, weight_number):
|
| 137 |
+
if str_pred == str_gt:
|
| 138 |
+
return 1
|
| 139 |
+
elif str_pred is not None and str_gt is None:
|
| 140 |
+
return 0
|
| 141 |
+
else:
|
| 142 |
+
if 'Gramm' in str_pred and 'Kilogramm' in str_gt:
|
| 143 |
+
str_pred = str(float(weight_number)/1000) + ' ' + 'Kilogramm'
|
| 144 |
+
if str_pred == str_gt:
|
| 145 |
+
return 1
|
| 146 |
+
elif 'Kilogramm' in str_pred and 'Gramm' in str_gt:
|
| 147 |
+
str_pred = str(float(weight_number)*1000) + ' ' + 'Gramm'
|
| 148 |
+
if str_pred == str_gt:
|
| 149 |
+
return 1
|
| 150 |
+
elif 'Milliliter' in str_pred and 'Liter' in str_gt:
|
| 151 |
+
str_pred = str(float(weight_number)/1000) + ' ' + 'Liter'
|
| 152 |
+
if str_pred == str_gt:
|
| 153 |
+
return 1
|
| 154 |
+
elif 'Liter' in str_pred and 'Milliliter' in str_gt:
|
| 155 |
+
str_pred = str(float(weight_number)*1000) + ' ' + 'Milliliter'
|
| 156 |
+
if str_pred == str_gt:
|
| 157 |
+
return 1
|
| 158 |
+
return 0
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def different_sorts_fuzzy_match(str_pred, str_gt):
|
| 162 |
+
if str_pred == str_gt:
|
| 163 |
+
return 1
|
| 164 |
+
else:
|
| 165 |
+
return 0
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def get_custom_accuracy(df_true, df_pred, f, df_custom_accuracy):
|
| 169 |
+
if f != 'product_weight' and f != 'different_types':
|
| 170 |
+
mask = df_true[f].notna() & df_pred[f].notna()
|
| 171 |
+
|
| 172 |
+
df_custom_accuracy.at['non-null GT', f] = int(df_true[f].notna().value_counts().get(True, 0))
|
| 173 |
+
df_custom_accuracy.at['non-null prediction', f] = int(df_pred[f].notna().value_counts().get(True, 0))
|
| 174 |
+
df_custom_accuracy.at['non-null GT AND prediction', f] = int(mask.value_counts().get(True, 0))
|
| 175 |
+
df_custom_accuracy.at['null GT', f] = int(df_true[f].notna().value_counts().get(False, 0))
|
| 176 |
+
df_custom_accuracy.at['null prediction', f] = int(df_pred[f].notna().value_counts().get(False, 0))
|
| 177 |
+
df_custom_accuracy.at['null GT AND prediction', f] = int(mask.value_counts().get(False, 0))
|
| 178 |
+
|
| 179 |
+
y_true_clean = df_true.loc[mask, f]
|
| 180 |
+
y_pred_clean = df_pred.loc[mask, f]
|
| 181 |
+
|
| 182 |
+
if f == 'brand':
|
| 183 |
+
df_feature_true = pd.DataFrame({
|
| 184 |
+
f : y_true_clean,
|
| 185 |
+
f + '_string_op' : y_true_clean.apply(string_operations)
|
| 186 |
+
})
|
| 187 |
+
df_feature_pred = pd.DataFrame({
|
| 188 |
+
f : y_pred_clean,
|
| 189 |
+
f + '_string_op' : y_pred_clean.apply(string_operations)
|
| 190 |
+
})
|
| 191 |
+
|
| 192 |
+
tmp = pd.DataFrame()
|
| 193 |
+
tmp['match'] = [
|
| 194 |
+
brand_fuzzy_match(pred, gt)
|
| 195 |
+
for pred, gt in zip(df_feature_pred[f + '_string_op'], df_feature_true[f + '_string_op'])
|
| 196 |
+
]
|
| 197 |
+
|
| 198 |
+
from sklearn.metrics import accuracy_score
|
| 199 |
+
df_custom_accuracy.at['custom_acc', f] = accuracy_score([1]*len(tmp['match']), tmp['match'])
|
| 200 |
+
|
| 201 |
+
elif f == 'price' or f == 'regular_price' or f == 'relative_discount' or f == 'absolute_discount':
|
| 202 |
+
df_feature_true = pd.DataFrame({
|
| 203 |
+
f : y_true_clean,
|
| 204 |
+
f + '_string_op' : y_true_clean
|
| 205 |
+
})
|
| 206 |
+
df_feature_pred = pd.DataFrame({
|
| 207 |
+
f : y_pred_clean,
|
| 208 |
+
f + '_string_op' : y_pred_clean.str.replace('-', '')
|
| 209 |
+
})
|
| 210 |
+
|
| 211 |
+
tmp = pd.DataFrame()
|
| 212 |
+
tmp['match'] = [
|
| 213 |
+
price_discount_fuzzy_match(f, str(pred), str(gt))
|
| 214 |
+
for pred, gt in zip(df_feature_pred[f + '_string_op'], df_feature_true[f + '_string_op'])
|
| 215 |
+
]
|
| 216 |
+
from sklearn.metrics import accuracy_score
|
| 217 |
+
df_custom_accuracy.at['custom_acc', f] = accuracy_score([1]*len(tmp['match']), tmp['match'])
|
| 218 |
+
|
| 219 |
+
elif f == 'product_weight':
|
| 220 |
+
df_pred[f] = df_pred['weight_number'].astype(str) + ' ' + df_pred['weight_unit'].astype(str)
|
| 221 |
+
mask = df_true[f].notna() & df_pred[f].notna()
|
| 222 |
+
|
| 223 |
+
df_custom_accuracy.at['non-null GT', f] = int(df_true[f].notna().value_counts().get(True, 0))
|
| 224 |
+
df_custom_accuracy.at['non-null prediction', f] = int(df_pred[f].notna().value_counts().get(True, 0))
|
| 225 |
+
df_custom_accuracy.at['non-null GT AND prediction', f] = int(mask.value_counts().get(True, 0))
|
| 226 |
+
df_custom_accuracy.at['null GT', f] = int(df_true[f].notna().value_counts().get(False, 0))
|
| 227 |
+
df_custom_accuracy.at['null prediction', f] = int(df_pred[f].notna().value_counts().get(False, 0))
|
| 228 |
+
df_custom_accuracy.at['null GT AND prediction', f] = int(mask.value_counts().get(False, 0))
|
| 229 |
+
|
| 230 |
+
y_true_clean = df_true.loc[mask, f]
|
| 231 |
+
y_pred_clean = df_pred.loc[mask, f]
|
| 232 |
+
y_pred_clean_weight_number = df_pred.loc[mask, 'weight_number']
|
| 233 |
+
y_pred_clean_weight_unit = df_pred.loc[mask, 'weight_unit']
|
| 234 |
+
|
| 235 |
+
df_feature_true = pd.DataFrame({
|
| 236 |
+
f : y_true_clean
|
| 237 |
+
})
|
| 238 |
+
df_feature_pred = pd.DataFrame({
|
| 239 |
+
f : y_pred_clean,
|
| 240 |
+
'weight_number' : y_pred_clean_weight_number,
|
| 241 |
+
'weight_unit' : y_pred_clean_weight_unit,
|
| 242 |
+
})
|
| 243 |
+
|
| 244 |
+
tmp = pd.DataFrame()
|
| 245 |
+
tmp['match'] = [
|
| 246 |
+
product_weight_fuzzy_match(str(pred), str(gt), weight_number)
|
| 247 |
+
for pred, gt, weight_number in zip(df_feature_pred[f], df_feature_true[f], df_feature_pred['weight_number'])
|
| 248 |
+
]
|
| 249 |
+
from sklearn.metrics import accuracy_score
|
| 250 |
+
df_custom_accuracy.at['custom_acc', f] = accuracy_score([1]*len(tmp['match']), tmp['match'])
|
| 251 |
+
|
| 252 |
+
elif f == 'different_types':
|
| 253 |
+
tmp = pd.DataFrame()
|
| 254 |
+
tmp['match'] = [
|
| 255 |
+
different_sorts_fuzzy_match(str(pred), str(gt))
|
| 256 |
+
for pred, gt in zip(df_true[f], df_pred[f])
|
| 257 |
+
]
|
| 258 |
+
from sklearn.metrics import accuracy_score
|
| 259 |
+
df_custom_accuracy.at['custom_acc', f] = accuracy_score([1]*len(tmp['match']), tmp['match'])
|
| 260 |
+
|
| 261 |
+
elif f == 'product_category':
|
| 262 |
+
df_feature_true = pd.DataFrame({
|
| 263 |
+
f : y_true_clean,
|
| 264 |
+
f + '_string_op' : y_true_clean
|
| 265 |
+
})
|
| 266 |
+
df_feature_pred = pd.DataFrame({
|
| 267 |
+
f : y_pred_clean,
|
| 268 |
+
f + '_string_op' : y_pred_clean
|
| 269 |
+
})
|
| 270 |
+
|
| 271 |
+
tmp = pd.DataFrame()
|
| 272 |
+
tmp['match'] = [
|
| 273 |
+
product_category_fuzzy_match(str(pred), str(gt))
|
| 274 |
+
for pred, gt in zip(df_feature_pred[f + '_string_op'], df_feature_true[f + '_string_op'])
|
| 275 |
+
]
|
| 276 |
+
from sklearn.metrics import accuracy_score
|
| 277 |
+
df_custom_accuracy.at['custom_acc', f] = accuracy_score([1]*len(tmp['match']), tmp['match'])
|
| 278 |
+
|
| 279 |
+
elif f == 'GTINs':
|
| 280 |
+
df_feature_true = pd.DataFrame({
|
| 281 |
+
f : y_true_clean,
|
| 282 |
+
f + '_string_op' : y_true_clean
|
| 283 |
+
})
|
| 284 |
+
df_feature_pred = pd.DataFrame({
|
| 285 |
+
f : y_pred_clean,
|
| 286 |
+
f + '_string_op' : y_pred_clean
|
| 287 |
+
})
|
| 288 |
+
|
| 289 |
+
tmp = pd.DataFrame()
|
| 290 |
+
tmp['match'] = [
|
| 291 |
+
gtins_fuzzy_match(str(pred), str(gt))
|
| 292 |
+
for pred, gt in zip(df_feature_pred[f + '_string_op'], df_feature_true[f + '_string_op'])
|
| 293 |
+
]
|
| 294 |
+
from sklearn.metrics import accuracy_score
|
| 295 |
+
df_custom_accuracy.at['custom_acc', f] = accuracy_score([1]*len(tmp['match']), tmp['match'])
|
| 296 |
+
|
| 297 |
+
return df_custom_accuracy
|
code/visual_rag/evaluation_rag.ipynb
ADDED
|
@@ -0,0 +1,579 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 13 |
+
"import pandas as pd\n",
|
| 14 |
+
"import matplotlib.pyplot as plt"
|
| 15 |
+
]
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"id": "7405fa4d",
|
| 21 |
+
"metadata": {},
|
| 22 |
+
"outputs": [],
|
| 23 |
+
"source": [
|
| 24 |
+
"%pip install Levenshtein\n",
|
| 25 |
+
"%pip install textdistance\n",
|
| 26 |
+
"%pip install scikit-learn"
|
| 27 |
+
]
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"execution_count": null,
|
| 32 |
+
"id": "489bd187",
|
| 33 |
+
"metadata": {},
|
| 34 |
+
"outputs": [],
|
| 35 |
+
"source": [
|
| 36 |
+
"df_test = pd.read_parquet('./.../test.parquet', engine='pyarrow')"
|
| 37 |
+
]
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "code",
|
| 41 |
+
"execution_count": null,
|
| 42 |
+
"id": "54b43403",
|
| 43 |
+
"metadata": {},
|
| 44 |
+
"outputs": [],
|
| 45 |
+
"source": [
|
| 46 |
+
"path_to_vlm_results = \"./.../vlm_results\"\n",
|
| 47 |
+
"vlm_name = \"your-vlm-name\"\n",
|
| 48 |
+
"file_vlm_results = \"./.../your-vlm-results.parquet\""
|
| 49 |
+
]
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "markdown",
|
| 53 |
+
"id": "d414ef1f",
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"source": [
|
| 56 |
+
"# Evaluation of VLM"
|
| 57 |
+
]
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"cell_type": "code",
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"id": "b5c664ed",
|
| 63 |
+
"metadata": {},
|
| 64 |
+
"outputs": [],
|
| 65 |
+
"source": [
|
| 66 |
+
"df_vlm = pd.read_parquet(os.path.join(path_to_vlm_results, file_vlm_results), engine='pyarrow')\n",
|
| 67 |
+
"df_vlm"
|
| 68 |
+
]
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"cell_type": "code",
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"id": "19e6c03f",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"outputs": [],
|
| 76 |
+
"source": [
|
| 77 |
+
"output_path = os.path.join('results', vlm_name)\n",
|
| 78 |
+
"os.makedirs(output_path, exist_ok=True)"
|
| 79 |
+
]
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "markdown",
|
| 83 |
+
"id": "a727018d",
|
| 84 |
+
"metadata": {},
|
| 85 |
+
"source": [
|
| 86 |
+
"check if all images have a response"
|
| 87 |
+
]
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"cell_type": "code",
|
| 91 |
+
"execution_count": null,
|
| 92 |
+
"id": "0e89a881",
|
| 93 |
+
"metadata": {},
|
| 94 |
+
"outputs": [],
|
| 95 |
+
"source": [
|
| 96 |
+
"df_vlm.loc[df_vlm.iloc[:, 2:12].isna().all(axis=1)]"
|
| 97 |
+
]
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"id": "f6874064",
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"outputs": [],
|
| 105 |
+
"source": [
|
| 106 |
+
"number_no_prediction = len(df_vlm.loc[df_vlm.iloc[:, 2:12].isna().all(axis=1)].filename.tolist())\n",
|
| 107 |
+
"print('number of images that have no prediction: ' + str(number_no_prediction))"
|
| 108 |
+
]
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "code",
|
| 112 |
+
"execution_count": null,
|
| 113 |
+
"id": "88081381",
|
| 114 |
+
"metadata": {},
|
| 115 |
+
"outputs": [],
|
| 116 |
+
"source": [
|
| 117 |
+
"data = {}\n",
|
| 118 |
+
"data['number_no_prediction'] = int(number_no_prediction)\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"with open(os.path.join(output_path, \"data.json\"), \"w\") as file:\n",
|
| 121 |
+
" json.dump(data, file, indent=2)"
|
| 122 |
+
]
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "markdown",
|
| 126 |
+
"id": "6cbbd3c7",
|
| 127 |
+
"metadata": {},
|
| 128 |
+
"source": [
|
| 129 |
+
"# Evaluation Metric: Single Target"
|
| 130 |
+
]
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"cell_type": "code",
|
| 134 |
+
"execution_count": null,
|
| 135 |
+
"id": "c34d6ec7",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"outputs": [],
|
| 138 |
+
"source": [
|
| 139 |
+
"import custom_rag_metrics\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"import importlib\n",
|
| 142 |
+
"importlib.reload(custom_rag_metrics)"
|
| 143 |
+
]
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"id": "1e90eb78",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"outputs": [],
|
| 151 |
+
"source": [
|
| 152 |
+
"list_features = ['brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'product_weight', 'different_types']\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"df_data_mse_rmse = pd.DataFrame()\n",
|
| 155 |
+
"df_edit_distance_brand = pd.DataFrame()\n",
|
| 156 |
+
"df_custom_accuracy = pd.DataFrame()\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"df_vlm['different_types'] = df_vlm['different_types'].apply(lambda x: x if x == 'yes' else None)\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"for f in list_features:\n",
|
| 161 |
+
" print(f)\n",
|
| 162 |
+
" if 'price' in f or 'discount' in f:\n",
|
| 163 |
+
" df_data_mse_rmse = custom_rag_metrics.get_mean_squared_error(df_test, df_vlm, f, df_data_mse_rmse)\n",
|
| 164 |
+
" elif f == 'brand':\n",
|
| 165 |
+
" df_edit_distance_brand = custom_rag_metrics.get_edit_distances(df_test, df_vlm, f, df_edit_distance_brand)\n",
|
| 166 |
+
" \n",
|
| 167 |
+
" df_custom_accuracy = custom_rag_metrics.get_custom_accuracy(df_test, df_vlm, f, df_custom_accuracy)"
|
| 168 |
+
]
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"cell_type": "code",
|
| 172 |
+
"execution_count": null,
|
| 173 |
+
"id": "fc194696",
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"outputs": [],
|
| 176 |
+
"source": [
|
| 177 |
+
"df_data_mse_rmse.to_parquet(os.path.join(output_path, vlm_name + '_mse_rmse.parquet'), engine='pyarrow')\n",
|
| 178 |
+
"df_data_mse_rmse"
|
| 179 |
+
]
|
| 180 |
+
},
|
| 181 |
+
{
|
| 182 |
+
"cell_type": "code",
|
| 183 |
+
"execution_count": null,
|
| 184 |
+
"id": "bf79860e",
|
| 185 |
+
"metadata": {},
|
| 186 |
+
"outputs": [],
|
| 187 |
+
"source": [
|
| 188 |
+
"df_edit_distance_brand.to_parquet(os.path.join(output_path, vlm_name + '_edit_distance_brand.parquet'), engine='pyarrow')\n",
|
| 189 |
+
"df_edit_distance_brand"
|
| 190 |
+
]
|
| 191 |
+
},
|
| 192 |
+
{
|
| 193 |
+
"cell_type": "code",
|
| 194 |
+
"execution_count": null,
|
| 195 |
+
"id": "2dc1346a",
|
| 196 |
+
"metadata": {},
|
| 197 |
+
"outputs": [],
|
| 198 |
+
"source": [
|
| 199 |
+
"mean_values = df_edit_distance_brand[['levenshtein_dist', 'hamming_dist', 'damerau_levenshtein_dist', 'jaro_dist']].mean()\n",
|
| 200 |
+
"mean_values.to_csv(os.path.join(output_path, vlm_name + '_edit_distance_brand_mean_values.csv'), header=True)\n",
|
| 201 |
+
"mean_values"
|
| 202 |
+
]
|
| 203 |
+
},
|
| 204 |
+
{
|
| 205 |
+
"cell_type": "code",
|
| 206 |
+
"execution_count": null,
|
| 207 |
+
"id": "d1d9374a",
|
| 208 |
+
"metadata": {},
|
| 209 |
+
"outputs": [],
|
| 210 |
+
"source": [
|
| 211 |
+
"for column in ['levenshtein_dist', 'hamming_dist', 'damerau_levenshtein_dist', 'jaro_dist']:\n",
|
| 212 |
+
" plt.figure()\n",
|
| 213 |
+
" df_edit_distance_brand.boxplot(column=column)\n",
|
| 214 |
+
" plt.savefig(os.path.join(output_path, vlm_name + f'_boxplot_{column}.png'))\n",
|
| 215 |
+
" plt.close()"
|
| 216 |
+
]
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
"cell_type": "code",
|
| 220 |
+
"execution_count": null,
|
| 221 |
+
"id": "a9dad775",
|
| 222 |
+
"metadata": {},
|
| 223 |
+
"outputs": [],
|
| 224 |
+
"source": [
|
| 225 |
+
"df_custom_accuracy.to_parquet(os.path.join(output_path, vlm_name + '_custom_accuracy.parquet'), engine='pyarrow')\n",
|
| 226 |
+
"df_custom_accuracy"
|
| 227 |
+
]
|
| 228 |
+
},
|
| 229 |
+
{
|
| 230 |
+
"cell_type": "markdown",
|
| 231 |
+
"id": "0d486fc3",
|
| 232 |
+
"metadata": {},
|
| 233 |
+
"source": [
|
| 234 |
+
"# Evaluation of costs"
|
| 235 |
+
]
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"cell_type": "code",
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"id": "c7e42d7b",
|
| 241 |
+
"metadata": {},
|
| 242 |
+
"outputs": [],
|
| 243 |
+
"source": [
|
| 244 |
+
"vlm_name = \"your-vlm-name\"\n",
|
| 245 |
+
"file_vlm_results = \"./.../your-vlm-results_of_costs.parquet\""
|
| 246 |
+
]
|
| 247 |
+
},
|
| 248 |
+
{
|
| 249 |
+
"cell_type": "code",
|
| 250 |
+
"execution_count": null,
|
| 251 |
+
"id": "c86f9406",
|
| 252 |
+
"metadata": {},
|
| 253 |
+
"outputs": [],
|
| 254 |
+
"source": [
|
| 255 |
+
"output_path = os.path.join('results', vlm_name)\n",
|
| 256 |
+
"os.makedirs(output_path, exist_ok=True)"
|
| 257 |
+
]
|
| 258 |
+
},
|
| 259 |
+
{
|
| 260 |
+
"cell_type": "code",
|
| 261 |
+
"execution_count": null,
|
| 262 |
+
"id": "d64a7f32",
|
| 263 |
+
"metadata": {},
|
| 264 |
+
"outputs": [],
|
| 265 |
+
"source": [
|
| 266 |
+
"df_vlm_costs = pd.read_parquet(os.path.join(path_to_vlm_results, file_vlm_results), engine='pyarrow')\n",
|
| 267 |
+
"df_vlm_costs"
|
| 268 |
+
]
|
| 269 |
+
},
|
| 270 |
+
{
|
| 271 |
+
"cell_type": "code",
|
| 272 |
+
"execution_count": null,
|
| 273 |
+
"id": "aabc0cd2",
|
| 274 |
+
"metadata": {},
|
| 275 |
+
"outputs": [],
|
| 276 |
+
"source": [
|
| 277 |
+
"columns_to_describe = ['elapsed_time_[s]']\n",
|
| 278 |
+
"\n",
|
| 279 |
+
"describe_df = df_vlm_costs[columns_to_describe].describe()\n",
|
| 280 |
+
"describe_df.to_parquet(os.path.join(output_path, vlm_name + '_costs_describe.parquet'), engine='pyarrow')\n",
|
| 281 |
+
"describe_df"
|
| 282 |
+
]
|
| 283 |
+
},
|
| 284 |
+
{
|
| 285 |
+
"cell_type": "code",
|
| 286 |
+
"execution_count": null,
|
| 287 |
+
"id": "cfe082fc",
|
| 288 |
+
"metadata": {},
|
| 289 |
+
"outputs": [],
|
| 290 |
+
"source": [
|
| 291 |
+
"# total elapsed time (all req.)\n",
|
| 292 |
+
"df_vlm_costs['elapsed_time_[s]'].sum()\n",
|
| 293 |
+
"# in hours\n",
|
| 294 |
+
"df_vlm_costs['elapsed_time_[s]'].sum() / 60 / 60"
|
| 295 |
+
]
|
| 296 |
+
},
|
| 297 |
+
{
|
| 298 |
+
"cell_type": "code",
|
| 299 |
+
"execution_count": null,
|
| 300 |
+
"id": "705293de",
|
| 301 |
+
"metadata": {},
|
| 302 |
+
"outputs": [],
|
| 303 |
+
"source": [
|
| 304 |
+
"df_vlm_costs['total_cost'].sum()"
|
| 305 |
+
]
|
| 306 |
+
},
|
| 307 |
+
{
|
| 308 |
+
"cell_type": "markdown",
|
| 309 |
+
"id": "e8d2c216",
|
| 310 |
+
"metadata": {},
|
| 311 |
+
"source": [
|
| 312 |
+
"# Evaluation Metric: Union Targets and Union Test"
|
| 313 |
+
]
|
| 314 |
+
},
|
| 315 |
+
{
|
| 316 |
+
"cell_type": "code",
|
| 317 |
+
"execution_count": null,
|
| 318 |
+
"id": "a42a6088",
|
| 319 |
+
"metadata": {},
|
| 320 |
+
"outputs": [],
|
| 321 |
+
"source": [
|
| 322 |
+
"from tqdm import tqdm\n",
|
| 323 |
+
"import custom_rag_metrics\n",
|
| 324 |
+
"import importlib\n",
|
| 325 |
+
"importlib.reload(custom_rag_metrics)\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"def string_operations(string):\n",
|
| 328 |
+
" import unicodedata\n",
|
| 329 |
+
" import re\n",
|
| 330 |
+
"\n",
|
| 331 |
+
" string = string.lower()\n",
|
| 332 |
+
" string = unicodedata.normalize('NFD', string)\n",
|
| 333 |
+
" string = ''.join(char for char in string if unicodedata.category(char) != 'Mn')\n",
|
| 334 |
+
" string = re.sub(r\"[']\", \"\", string)\n",
|
| 335 |
+
" \n",
|
| 336 |
+
" return string\n",
|
| 337 |
+
"\n",
|
| 338 |
+
"df_vlm = pd.read_parquet(os.path.join(path_to_vlm_results, file_vlm_results), engine='pyarrow')\n",
|
| 339 |
+
"df_vlm['different_types'] = df_vlm['different_types_manually'].apply(lambda x: x if x == 'yes' else None)\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"list_features = ['brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'product_weight', 'different_types']\n",
|
| 342 |
+
"\n",
|
| 343 |
+
"df_custom_accuracy_total = pd.DataFrame(columns=df_vlm.columns)\n",
|
| 344 |
+
"df_custom_accuracy_total.drop('weight_number', axis=1, inplace=True)\n",
|
| 345 |
+
"df_custom_accuracy_total.drop('weight_unit', axis=1, inplace=True)\n",
|
| 346 |
+
"df_custom_accuracy_total['product_weight'] = None\n",
|
| 347 |
+
"df_custom_accuracy_total['label'] = df_vlm['label']\n",
|
| 348 |
+
"df_custom_accuracy_total['filename'] = df_vlm['filename']\n",
|
| 349 |
+
"\n",
|
| 350 |
+
"for i, f in enumerate(list_features):\n",
|
| 351 |
+
" print(f)\n",
|
| 352 |
+
"\n",
|
| 353 |
+
" for index, row in tqdm(df_vlm.iterrows(), total=len(df_vlm)):\n",
|
| 354 |
+
" if f != 'product_weight':\n",
|
| 355 |
+
" y_pred = row[f]\n",
|
| 356 |
+
" \n",
|
| 357 |
+
" y_true = df_test.iloc[index][f]\n",
|
| 358 |
+
"\n",
|
| 359 |
+
" if y_pred is None:\n",
|
| 360 |
+
" df_custom_accuracy_total.at[index, f] = 0\n",
|
| 361 |
+
" continue\n",
|
| 362 |
+
" \n",
|
| 363 |
+
" if f == 'brand':\n",
|
| 364 |
+
" df_custom_accuracy_total.at[index, f] = custom_rag_metrics.brand_fuzzy_match(string_operations(y_pred), string_operations(y_true))\n",
|
| 365 |
+
" elif 'price' in f or 'discount' in f: \n",
|
| 366 |
+
" df_custom_accuracy_total.at[index, f] = custom_rag_metrics.price_discount_fuzzy_match(f, y_pred.replace('-', ''), str(y_true))\n",
|
| 367 |
+
" elif f == 'different_types':\n",
|
| 368 |
+
" df_custom_accuracy_total.at[index, f] = custom_rag_metrics.different_sorts_fuzzy_match(y_pred, str(y_true))\n",
|
| 369 |
+
" elif f == 'product_weight':\n",
|
| 370 |
+
" if row['weight_number'] is None or row['weight_unit'] is None:\n",
|
| 371 |
+
" df_custom_accuracy_total.at[index, f] = 0\n",
|
| 372 |
+
" continue\n",
|
| 373 |
+
"\n",
|
| 374 |
+
" y_pred = row['weight_number'] + ' ' + row['weight_unit']\n",
|
| 375 |
+
" weight_number = row['weight_number']\n",
|
| 376 |
+
"\n",
|
| 377 |
+
" df_custom_accuracy_total.at[index, f] = custom_rag_metrics.product_weight_fuzzy_match(y_pred, y_true, weight_number)\n",
|
| 378 |
+
" elif f == 'product_category':\n",
|
| 379 |
+
" df_custom_accuracy_total.at[index, f] = custom_rag_metrics.product_category_fuzzy_match(y_pred, y_true)\n",
|
| 380 |
+
" elif f == 'GTINs':\n",
|
| 381 |
+
" df_custom_accuracy_total.at[index, f] = custom_rag_metrics.gtins_fuzzy_match(y_pred, y_true)"
|
| 382 |
+
]
|
| 383 |
+
},
|
| 384 |
+
{
|
| 385 |
+
"cell_type": "code",
|
| 386 |
+
"execution_count": null,
|
| 387 |
+
"id": "4403d83a",
|
| 388 |
+
"metadata": {},
|
| 389 |
+
"outputs": [],
|
| 390 |
+
"source": [
|
| 391 |
+
"df_custom_accuracy_total"
|
| 392 |
+
]
|
| 393 |
+
},
|
| 394 |
+
{
|
| 395 |
+
"cell_type": "code",
|
| 396 |
+
"execution_count": null,
|
| 397 |
+
"id": "8995eaf3",
|
| 398 |
+
"metadata": {},
|
| 399 |
+
"outputs": [],
|
| 400 |
+
"source": [
|
| 401 |
+
"# uncomment the set of targets for which the evaluation should be done\n",
|
| 402 |
+
"\n",
|
| 403 |
+
"cols = ['brand']\n",
|
| 404 |
+
"# cols = ['brand', 'product_weight']\n",
|
| 405 |
+
"# cols = ['brand', 'product_weight', 'different_types']\n",
|
| 406 |
+
"# cols = ['brand', 'product_weight', 'different_types', 'price']\n",
|
| 407 |
+
"# cols = ['brand', 'product_weight', 'different_types', 'price', 'regular_price']\n",
|
| 408 |
+
"# cols = ['brand', 'product_weight', 'different_types', 'price', 'regular_price', 'relative_discount']\n",
|
| 409 |
+
"# cols = ['brand', 'product_weight', 'different_types', 'price', 'regular_price', 'relative_discount', 'product_category']\n",
|
| 410 |
+
"# cols = ['brand', 'product_weight', 'different_types', 'price', 'regular_price', 'relative_discount', 'product_category', 'GTINs']\n",
|
| 411 |
+
"# cols = ['brand', 'product_weight', 'different_types', 'price', 'regular_price', 'relative_discount', 'product_category', 'GTINs', 'absolute_discount']\n",
|
| 412 |
+
"df_custom_accuracy_total.loc[(df_custom_accuracy_total[cols] == 1).all(axis=1)]"
|
| 413 |
+
]
|
| 414 |
+
},
|
| 415 |
+
{
|
| 416 |
+
"cell_type": "markdown",
|
| 417 |
+
"id": "77728f07",
|
| 418 |
+
"metadata": {},
|
| 419 |
+
"source": [
|
| 420 |
+
"#### total custom accuracy regard to WHOLE test dataset"
|
| 421 |
+
]
|
| 422 |
+
},
|
| 423 |
+
{
|
| 424 |
+
"cell_type": "code",
|
| 425 |
+
"execution_count": null,
|
| 426 |
+
"id": "000737bc",
|
| 427 |
+
"metadata": {},
|
| 428 |
+
"outputs": [],
|
| 429 |
+
"source": [
|
| 430 |
+
"tmp = df_custom_accuracy_total.loc[(df_custom_accuracy_total[cols] == 1).all(axis=1)]\n",
|
| 431 |
+
"len(tmp) / 36571 * 100"
|
| 432 |
+
]
|
| 433 |
+
},
|
| 434 |
+
{
|
| 435 |
+
"cell_type": "markdown",
|
| 436 |
+
"id": "1502be2e",
|
| 437 |
+
"metadata": {},
|
| 438 |
+
"source": [
|
| 439 |
+
"#### total custom accuracy regard to VALID GT & PRED values"
|
| 440 |
+
]
|
| 441 |
+
},
|
| 442 |
+
{
|
| 443 |
+
"cell_type": "code",
|
| 444 |
+
"execution_count": null,
|
| 445 |
+
"id": "3381e144",
|
| 446 |
+
"metadata": {},
|
| 447 |
+
"outputs": [],
|
| 448 |
+
"source": [
|
| 449 |
+
"df_vlm['product_weight'] = df_vlm['weight_number'].astype(str) + ' ' + df_vlm['weight_unit'].astype(str)\n",
|
| 450 |
+
"\n",
|
| 451 |
+
"tmp = df_custom_accuracy_total.loc[(df_custom_accuracy_total[cols] == 1).all(axis=1)]\n",
|
| 452 |
+
"\n",
|
| 453 |
+
"mask = df_test[cols].notna().all(axis=1) & df_vlm[cols].notna().all(axis=1)\n",
|
| 454 |
+
"length = int(mask.value_counts().get(True, 0))\n",
|
| 455 |
+
"\n",
|
| 456 |
+
"print(len(tmp))\n",
|
| 457 |
+
"print(length)\n",
|
| 458 |
+
"\n",
|
| 459 |
+
"len(tmp) / length * 100"
|
| 460 |
+
]
|
| 461 |
+
},
|
| 462 |
+
{
|
| 463 |
+
"cell_type": "markdown",
|
| 464 |
+
"id": "b1fdf2ef",
|
| 465 |
+
"metadata": {},
|
| 466 |
+
"source": [
|
| 467 |
+
"### create boxplot for price"
|
| 468 |
+
]
|
| 469 |
+
},
|
| 470 |
+
{
|
| 471 |
+
"cell_type": "code",
|
| 472 |
+
"execution_count": null,
|
| 473 |
+
"id": "810f3459",
|
| 474 |
+
"metadata": {},
|
| 475 |
+
"outputs": [],
|
| 476 |
+
"source": [
|
| 477 |
+
"import matplotlib.pyplot as plt\n",
|
| 478 |
+
"import os\n",
|
| 479 |
+
"import pandas as pd\n",
|
| 480 |
+
"import numpy as np\n",
|
| 481 |
+
"\n",
|
| 482 |
+
"\n",
|
| 483 |
+
"df_test = pd.read_parquet('path-to-file/test.parquet', engine='pyarrow')\n",
|
| 484 |
+
"df_true = df_test.copy()\n",
|
| 485 |
+
"path_to_vlm_results = \"path-to-results\"\n",
|
| 486 |
+
"\n",
|
| 487 |
+
"list_model = [\n",
|
| 488 |
+
" \"your-vlm-name\",\n",
|
| 489 |
+
"]\n",
|
| 490 |
+
"\n",
|
| 491 |
+
"list_features = ['price']\n",
|
| 492 |
+
"df_price_errors = pd.DataFrame()\n",
|
| 493 |
+
"for f in list_features:\n",
|
| 494 |
+
" # all_errors = []\n",
|
| 495 |
+
" for m in list_model:\n",
|
| 496 |
+
" df_vlm = pd.read_parquet(os.path.join(path_to_vlm_results, m, m + '_test.parquet'), engine='pyarrow')\n",
|
| 497 |
+
" mask = df_true[f].notna() & df_vlm[f].notna()\n",
|
| 498 |
+
" y_true_clean = df_true.loc[mask, f]\n",
|
| 499 |
+
" y_pred_clean = df_vlm.loc[mask, f].astype(float)\n",
|
| 500 |
+
" errors_y = y_true_clean - y_pred_clean\n",
|
| 501 |
+
" \n",
|
| 502 |
+
" # Create a DataFrame from errors_y with column named by model\n",
|
| 503 |
+
" df_model_errors = pd.DataFrame({m: errors_y})\n",
|
| 504 |
+
"\n",
|
| 505 |
+
" # Concatenate preserving indices, axis=1 will join columns side-by-side\n",
|
| 506 |
+
" df_price_errors = pd.concat([df_price_errors, df_model_errors], axis=1)"
|
| 507 |
+
]
|
| 508 |
+
},
|
| 509 |
+
{
|
| 510 |
+
"cell_type": "code",
|
| 511 |
+
"execution_count": null,
|
| 512 |
+
"id": "e14db8eb",
|
| 513 |
+
"metadata": {},
|
| 514 |
+
"outputs": [],
|
| 515 |
+
"source": [
|
| 516 |
+
"import matplotlib.pyplot as plt\n",
|
| 517 |
+
"\n",
|
| 518 |
+
"########################################\n",
|
| 519 |
+
"plt.rcdefaults() # set default settings\n",
|
| 520 |
+
"plt.figure(figsize=(8, 5))\n",
|
| 521 |
+
"plt.rcParams.update({\n",
|
| 522 |
+
" \"text.usetex\": True, # Use LaTeX to render all text\n",
|
| 523 |
+
" \"font.family\": \"serif\", # Use serif font (matching typical LaTeX documents)\n",
|
| 524 |
+
" # \"text.latex.preamble\": r\"\\usepackage{lmodern}\"\n",
|
| 525 |
+
" \"font.size\": 12, # base font size for text\n",
|
| 526 |
+
" \"axes.titlesize\": 14, # title font size\n",
|
| 527 |
+
" \"axes.labelsize\": 13, # axis labels font size\n",
|
| 528 |
+
" \"xtick.labelsize\": 11, # x tick labels font size\n",
|
| 529 |
+
" \"ytick.labelsize\": 11, # y tick labels font size\n",
|
| 530 |
+
" \"legend.fontsize\": 12, # legend font size \n",
|
| 531 |
+
"})\n",
|
| 532 |
+
"from matplotlib.ticker import FuncFormatter, StrMethodFormatter\n",
|
| 533 |
+
"plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # comma as thousands separator\n",
|
| 534 |
+
"def format_with_commas(x, pos):\n",
|
| 535 |
+
" return f\"{x:,.2f}\"\n",
|
| 536 |
+
"plt.gca().xaxis.set_major_formatter(FuncFormatter(format_with_commas))\n",
|
| 537 |
+
"########################################\n",
|
| 538 |
+
"\n",
|
| 539 |
+
"# Simple boxplot for each column (model)\n",
|
| 540 |
+
"df_price_errors.boxplot()\n",
|
| 541 |
+
"\n",
|
| 542 |
+
"list_legend = [\n",
|
| 543 |
+
" \"your-vlm-name\",\n",
|
| 544 |
+
"]\n",
|
| 545 |
+
"\n",
|
| 546 |
+
"\n",
|
| 547 |
+
"# Set custom x-axis tick labels\n",
|
| 548 |
+
"plt.xticks(ticks=range(1, len(list_legend)+1), labels=list_legend)\n",
|
| 549 |
+
"\n",
|
| 550 |
+
"plt.ylabel('Prediction Error (Currency: EUR)')\n",
|
| 551 |
+
"plt.xlabel('Model')\n",
|
| 552 |
+
"\n",
|
| 553 |
+
"plt.savefig(\"boxplot_price.pdf\", bbox_inches='tight')\n",
|
| 554 |
+
"plt.show()"
|
| 555 |
+
]
|
| 556 |
+
}
|
| 557 |
+
],
|
| 558 |
+
"metadata": {
|
| 559 |
+
"kernelspec": {
|
| 560 |
+
"display_name": "latex",
|
| 561 |
+
"language": "python",
|
| 562 |
+
"name": "python3"
|
| 563 |
+
},
|
| 564 |
+
"language_info": {
|
| 565 |
+
"codemirror_mode": {
|
| 566 |
+
"name": "ipython",
|
| 567 |
+
"version": 3
|
| 568 |
+
},
|
| 569 |
+
"file_extension": ".py",
|
| 570 |
+
"mimetype": "text/x-python",
|
| 571 |
+
"name": "python",
|
| 572 |
+
"nbconvert_exporter": "python",
|
| 573 |
+
"pygments_lexer": "ipython3",
|
| 574 |
+
"version": "3.12.3"
|
| 575 |
+
}
|
| 576 |
+
},
|
| 577 |
+
"nbformat": 4,
|
| 578 |
+
"nbformat_minor": 5
|
| 579 |
+
}
|
code/visual_rag/rag_retriever.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
|
| 4 |
+
from langchain_core.retrievers import BaseRetriever
|
| 5 |
+
from langchain_core.documents import Document
|
| 6 |
+
from langchain_core.vectorstores import VectorStore
|
| 7 |
+
from langchain_core.embeddings import Embeddings
|
| 8 |
+
|
| 9 |
+
class custom_retriever(BaseRetriever, BaseModel):
|
| 10 |
+
vector_store: VectorStore
|
| 11 |
+
embeddings: Embeddings
|
| 12 |
+
k: int
|
| 13 |
+
|
| 14 |
+
def _get_relevant_documents(self, query: str) -> List[Document]:
|
| 15 |
+
query_type = query.split('*-*')[0]
|
| 16 |
+
query = query.split('*-*')[1]
|
| 17 |
+
|
| 18 |
+
if query_type == 'text':
|
| 19 |
+
query_embedding = self.embeddings.embed_documents([query])
|
| 20 |
+
elif query_type == 'image':
|
| 21 |
+
query_embedding = self.embeddings.embed_image([query])
|
| 22 |
+
|
| 23 |
+
list_doc_dis = self.vector_store.similarity_search_by_vector_with_relevance_scores(
|
| 24 |
+
embedding = query_embedding,
|
| 25 |
+
k = self.k
|
| 26 |
+
)
|
| 27 |
+
doc = [item[0] for item in list_doc_dis]
|
| 28 |
+
dis = [item[1] for item in list_doc_dis]
|
| 29 |
+
|
| 30 |
+
return doc, dis
|
code/visual_rag/rag_use_vlm.py
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import io
|
| 3 |
+
import json
|
| 4 |
+
import openai
|
| 5 |
+
import os
|
| 6 |
+
import requests
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
from PIL import Image
|
| 10 |
+
|
| 11 |
+
from enum import Enum
|
| 12 |
+
from pydantic import BaseModel, Field
|
| 13 |
+
from typing_extensions import List
|
| 14 |
+
from typing import Literal
|
| 15 |
+
|
| 16 |
+
from langchain_core.messages import HumanMessage, SystemMessage
|
| 17 |
+
from langchain_openai import ChatOpenAI
|
| 18 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 19 |
+
from langchain_ollama import ChatOllama
|
| 20 |
+
|
| 21 |
+
VLM_SEED = 0
|
| 22 |
+
VLM_TEMPERATURE = 0
|
| 23 |
+
######################################################################
|
| 24 |
+
######################################################################
|
| 25 |
+
|
| 26 |
+
class WeightUnit(Enum):
|
| 27 |
+
GRAMM = "Gramm"
|
| 28 |
+
KILOGRAM = "Kilogramm"
|
| 29 |
+
MILLILITER = "Milliliter"
|
| 30 |
+
LITER = "Liter"
|
| 31 |
+
WASCHLADUNGEN = "Waschladungen"
|
| 32 |
+
BLATT = "Blatt"
|
| 33 |
+
STUECK = "Stück"
|
| 34 |
+
|
| 35 |
+
class YesNo(Enum):
|
| 36 |
+
YES = "yes"
|
| 37 |
+
NO = "no"
|
| 38 |
+
|
| 39 |
+
class product_promotion_data(BaseModel):
|
| 40 |
+
"""Collection of product and promotion data of an product advertisement."""
|
| 41 |
+
brand: str = Field(description="The brand associated with the product")
|
| 42 |
+
product_category: List[str] = Field(description="List of categories associated with the product.")
|
| 43 |
+
price: float = Field(description="The promotional price.")
|
| 44 |
+
regular_price: float = Field(default=None, description="The regular price of the promotion.")
|
| 45 |
+
relative_discount: int = Field(default=None, description="The relative discount of the promotion.")
|
| 46 |
+
absolute_discount: float = Field(default=None, description="The absolute discount of the promotion.")
|
| 47 |
+
GTINs: List[str] = Field(description="List of the GTINs for the products.")
|
| 48 |
+
weight_number: float = Field(description="Only the numerical weight specication.")
|
| 49 |
+
weight_unit: WeightUnit = Field(description="Only the weight unit.")
|
| 50 |
+
# weight_unit: Literal["Gramm", "Kilogramm", "Milliliter", "Liter", "Waschladungen", "Blatt", "Stück"] = Field(description="Only the weight unit.")
|
| 51 |
+
different_sorts: YesNo = Field(description="If promotion offer different sorts.")
|
| 52 |
+
# different_types: Literal["yes", "no"] = Field(description="If promotion offer different sorts.")
|
| 53 |
+
|
| 54 |
+
######################################################################
|
| 55 |
+
######################################################################
|
| 56 |
+
|
| 57 |
+
def get_openai_client(key, model_name, context_str_len):
|
| 58 |
+
kwargs = {
|
| 59 |
+
"model": model_name,
|
| 60 |
+
"api_key": key,
|
| 61 |
+
"temperature": VLM_TEMPERATURE,
|
| 62 |
+
"seed": VLM_SEED,
|
| 63 |
+
}
|
| 64 |
+
client = ChatOpenAI(**kwargs)
|
| 65 |
+
|
| 66 |
+
os.environ["USED_MODEL"] = model_name
|
| 67 |
+
os.environ["CONTEXT_STRING_LENGTH"] = str(context_str_len)
|
| 68 |
+
|
| 69 |
+
return client
|
| 70 |
+
|
| 71 |
+
def get_google_client(key, model_name, context_str_len):
|
| 72 |
+
kwargs = {
|
| 73 |
+
"model": model_name,
|
| 74 |
+
"api_key": key,
|
| 75 |
+
"temperature": VLM_TEMPERATURE,
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
client = ChatGoogleGenerativeAI(**kwargs)
|
| 79 |
+
print(client)
|
| 80 |
+
|
| 81 |
+
os.environ["USED_MODEL"] = model_name
|
| 82 |
+
os.environ["CONTEXT_STRING_LENGTH"] = str(context_str_len)
|
| 83 |
+
|
| 84 |
+
return client
|
| 85 |
+
|
| 86 |
+
def set_ollama_settings(ip_address, model_name, context_str_len):
|
| 87 |
+
kwargs = {
|
| 88 |
+
"model": model_name,
|
| 89 |
+
"base_url": "your-request-url",
|
| 90 |
+
"temperature": VLM_TEMPERATURE,
|
| 91 |
+
"seed": VLM_SEED,
|
| 92 |
+
}
|
| 93 |
+
client = ChatOllama(**kwargs)
|
| 94 |
+
|
| 95 |
+
os.environ["USED_MODEL"] = model_name
|
| 96 |
+
os.environ["CONTEXT_STRING_LENGTH"] = str(context_str_len)
|
| 97 |
+
os.environ["IP_ADDRESS"] = ip_address
|
| 98 |
+
return client
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def prompt(query_image, question, dict_reference_data, index_neighbor=-1):
|
| 102 |
+
# Join the context into a single string
|
| 103 |
+
context = ''
|
| 104 |
+
for index, (image, text) in enumerate(zip(dict_reference_data['reference_data']['image'], dict_reference_data['reference_data']['text'])):
|
| 105 |
+
if index_neighbor != -1 and index != index_neighbor:
|
| 106 |
+
continue
|
| 107 |
+
tmp = 'image: ' + image + ' and its context: ' + text + "\n\n"
|
| 108 |
+
# condition due to maximum token length of model
|
| 109 |
+
if len(context + tmp) <= int(os.environ["CONTEXT_STRING_LENGTH"]):
|
| 110 |
+
context += tmp
|
| 111 |
+
else:
|
| 112 |
+
break
|
| 113 |
+
if index_neighbor == -1:
|
| 114 |
+
number_ref_data = index+1
|
| 115 |
+
print('number of reference data: ' + str(number_ref_data))
|
| 116 |
+
else:
|
| 117 |
+
number_ref_data = index_neighbor
|
| 118 |
+
print('number of reference data: 1')
|
| 119 |
+
|
| 120 |
+
system_message = "You are an assistant for question-answering tasks. \
|
| 121 |
+
You will receive examples of a reference image and its accompanying text. \
|
| 122 |
+
Using this data, you learn the meanings of different features by linking the text to the image. \
|
| 123 |
+
Features may be visually present in the image but do not have to be."
|
| 124 |
+
|
| 125 |
+
human_message_text = "Do the user-provided task on the input image. \
|
| 126 |
+
The answer must be provided in JSON format. \
|
| 127 |
+
The task is: {question}. \
|
| 128 |
+
The reference images and their context are: \n" + context + "."
|
| 129 |
+
|
| 130 |
+
human_messages = [
|
| 131 |
+
{
|
| 132 |
+
"type": "text",
|
| 133 |
+
"text": human_message_text
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"type": "image_url",
|
| 137 |
+
"image_url": {"url": f"data:image/jpeg;base64,{query_image}"},
|
| 138 |
+
},
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
return number_ref_data, [SystemMessage(content=system_message), HumanMessage(content=human_messages)]
|
| 142 |
+
|
| 143 |
+
def get_structured_vlm_model(vlm):
|
| 144 |
+
structured_vlm = vlm.with_structured_output(product_promotion_data, include_raw=True)
|
| 145 |
+
return structured_vlm
|
| 146 |
+
|
| 147 |
+
def get_img_base64_str(image_path):
|
| 148 |
+
img = Image.open(image_path)
|
| 149 |
+
buffered = io.BytesIO()
|
| 150 |
+
img.save(buffered, format=img.format)
|
| 151 |
+
img_base64_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 152 |
+
return img_base64_str
|
| 153 |
+
|
| 154 |
+
# https://platform.openai.com/docs/pricing
|
| 155 |
+
# https://ai.google.dev/gemini-api/docs/pricing
|
| 156 |
+
def token_price_evaluation(response, dict_result_cost):
|
| 157 |
+
PRICING = {
|
| 158 |
+
"gpt-4o-2024-08-06": {"input": 2.50 / 1000000, "output": 10.00 / 1000000},
|
| 159 |
+
"gpt-4o-2024-11-20": {"input": 2.50 / 1000000, "output": 10.00 / 1000000},
|
| 160 |
+
"gpt-4o-mini-2024-07-18": {"input": 0.15 / 1000000, "output": 0.60 / 1000000},
|
| 161 |
+
"gpt-4o-mini": {"input": 0.15 / 1000000, "output": 0.60 / 1000000},
|
| 162 |
+
"gemini/gemini-2.0-flash": {"input": 0.10 / 1000000, "output": 0.40 / 1000000},
|
| 163 |
+
"gemini-2.5-flash": {"input": 0.30 / 1000000, "output": 2.50 / 1000000},
|
| 164 |
+
}
|
| 165 |
+
MODEL = os.environ["USED_MODEL"]
|
| 166 |
+
|
| 167 |
+
# OpenAI
|
| 168 |
+
token_usage = response.response_metadata.get("token_usage", {})
|
| 169 |
+
input_tokens = token_usage.get("prompt_tokens", 0)
|
| 170 |
+
output_tokens = token_usage.get("completion_tokens", 0)
|
| 171 |
+
total_tokens = token_usage.get("total_tokens", input_tokens + output_tokens)
|
| 172 |
+
|
| 173 |
+
# Google Gemini
|
| 174 |
+
# token_usage = response.usage_metadata
|
| 175 |
+
# input_tokens = token_usage.get("input_tokens", 0)
|
| 176 |
+
# output_tokens = token_usage.get("output_tokens", 0)
|
| 177 |
+
# reasoning_tokens= token_usage.get("output_token_details", {}).get("reasoning", 0)
|
| 178 |
+
# total_tokens = token_usage.get("total_tokens", input_tokens + output_tokens)
|
| 179 |
+
|
| 180 |
+
input_cost = input_tokens * PRICING[MODEL]["input"]
|
| 181 |
+
output_cost = output_tokens * PRICING[MODEL]["output"]
|
| 182 |
+
total_cost = input_cost + output_cost
|
| 183 |
+
|
| 184 |
+
print(f"Model Used: {MODEL}")
|
| 185 |
+
print(f"Input Tokens: {input_tokens}, Cost: ${input_cost:.4f}")
|
| 186 |
+
print(f"Output Tokens: {output_tokens}, Cost: ${output_cost:.4f}")
|
| 187 |
+
print(f"Total Tokens: {total_tokens}")
|
| 188 |
+
print(f"Total Cost: ${total_cost:.4f}")
|
| 189 |
+
print('*'*30)
|
| 190 |
+
|
| 191 |
+
dict_result_cost['input_tokens'] = input_tokens
|
| 192 |
+
dict_result_cost['output_tokens'] = output_tokens
|
| 193 |
+
# dict_result_cost['reasoning_tokens'] = reasoning_tokens
|
| 194 |
+
dict_result_cost['total_tokens'] = total_tokens
|
| 195 |
+
dict_result_cost['total_cost'] = float("{:.4f}".format(total_cost))
|
| 196 |
+
|
| 197 |
+
return dict_result_cost
|
| 198 |
+
|
| 199 |
+
def convert_items_to_strings(prediction):
|
| 200 |
+
if isinstance(prediction, str): # special case for product weight
|
| 201 |
+
return prediction
|
| 202 |
+
elif isinstance(prediction, list):
|
| 203 |
+
return ', '.join(prediction)
|
| 204 |
+
else:
|
| 205 |
+
return str(prediction)
|
| 206 |
+
|
| 207 |
+
def get_output_results(dict_output, dict_result):
|
| 208 |
+
for key, value in dict_output.items():
|
| 209 |
+
if key == 'brand':
|
| 210 |
+
dict_result['brand'] = convert_items_to_strings(dict_output['brand'])
|
| 211 |
+
elif key == 'product_category':
|
| 212 |
+
dict_result['product_category'] = convert_items_to_strings(dict_output['product_category'])
|
| 213 |
+
elif key == 'price':
|
| 214 |
+
dict_result['price'] = convert_items_to_strings(dict_output['price'])
|
| 215 |
+
elif key == 'regular_price':
|
| 216 |
+
dict_result['regular_price'] = convert_items_to_strings(dict_output['regular_price'])
|
| 217 |
+
elif key == 'relative_discount':
|
| 218 |
+
dict_result['relative_discount'] = convert_items_to_strings(dict_output['relative_discount'])
|
| 219 |
+
elif key == 'absolute_discount':
|
| 220 |
+
dict_result['absolute_discount'] = convert_items_to_strings(dict_output['absolute_discount'])
|
| 221 |
+
elif key == 'GTINs':
|
| 222 |
+
dict_result['GTINs'] = convert_items_to_strings(dict_output['GTINs'])
|
| 223 |
+
elif key == 'weight_number':
|
| 224 |
+
dict_result['weight_number'] = convert_items_to_strings(dict_output['weight_number'])
|
| 225 |
+
elif key == 'weight_unit':
|
| 226 |
+
# dict_result['weight_unit'] = convert_items_to_strings(dict_output['weight_unit'].value)
|
| 227 |
+
dict_result['weight_unit'] = convert_items_to_strings(dict_output['weight_unit'])
|
| 228 |
+
elif key == 'different_sorts':
|
| 229 |
+
# dict_result['different_sorts'] = convert_items_to_strings(dict_output['different_sorts'].value)
|
| 230 |
+
dict_result['different_sorts'] = convert_items_to_strings(dict_output['different_sorts'])
|
| 231 |
+
elif key == 'different_types':
|
| 232 |
+
dict_result['different_types'] = convert_items_to_strings(dict_output['different_types'])
|
| 233 |
+
return dict_result
|
| 234 |
+
|
| 235 |
+
def deleting_neigbor(neighbor, dict_result):
|
| 236 |
+
dict_result[neighbor + 'label'] = None
|
| 237 |
+
dict_result[neighbor + 'filename'] = None
|
| 238 |
+
dict_result[neighbor + 'document'] = None
|
| 239 |
+
dict_result[neighbor + 'distance'] = None
|
| 240 |
+
return dict_result
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def do_ollama_request(messages, query_image_base64):
|
| 244 |
+
response = requests.post(
|
| 245 |
+
"requests-url",
|
| 246 |
+
json={
|
| 247 |
+
"model": os.environ["USED_MODEL"],
|
| 248 |
+
"prompt": messages[1].content[0]['text'],
|
| 249 |
+
"system": messages[0].content,
|
| 250 |
+
"stream": False,
|
| 251 |
+
"images": [query_image_base64],
|
| 252 |
+
"options": {
|
| 253 |
+
"temperature": VLM_TEMPERATURE,
|
| 254 |
+
"seed": VLM_SEED,
|
| 255 |
+
},
|
| 256 |
+
"format": product_promotion_data.model_json_schema()
|
| 257 |
+
},
|
| 258 |
+
timeout=60
|
| 259 |
+
)
|
| 260 |
+
parsed = json.loads(response.text)
|
| 261 |
+
return parsed
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def do_request(query_image_base64, question, dict_reference_data, vlm_rag_structured, dict_result, dict_result_cost, ollama=False):
|
| 266 |
+
index_neighbor = -1
|
| 267 |
+
number_ref_data, messages = prompt(query_image_base64, question, dict_reference_data)
|
| 268 |
+
|
| 269 |
+
if ollama:
|
| 270 |
+
|
| 271 |
+
try:
|
| 272 |
+
start_time = time.time()
|
| 273 |
+
parsed = do_ollama_request(messages, query_image_base64)
|
| 274 |
+
|
| 275 |
+
# reduced context
|
| 276 |
+
if not parsed['response']:
|
| 277 |
+
index_neighbor = 0
|
| 278 |
+
print('index_neighbor = 0')
|
| 279 |
+
number_ref_data, messages = prompt(query_image_base64, question, dict_reference_data, index_neighbor)
|
| 280 |
+
parsed = do_ollama_request(messages, query_image_base64)
|
| 281 |
+
|
| 282 |
+
if not parsed['response']:
|
| 283 |
+
index_neighbor = 1
|
| 284 |
+
print('index_neighbor = 1')
|
| 285 |
+
number_ref_data, messages = prompt(query_image_base64, question, dict_reference_data, index_neighbor)
|
| 286 |
+
parsed = do_ollama_request(messages, query_image_base64)
|
| 287 |
+
|
| 288 |
+
if not parsed['response']:
|
| 289 |
+
index_neighbor = 2
|
| 290 |
+
print('index_neighbor = 2')
|
| 291 |
+
number_ref_data, messages = prompt(query_image_base64, question, dict_reference_data, index_neighbor)
|
| 292 |
+
parsed = do_ollama_request(messages, query_image_base64)
|
| 293 |
+
|
| 294 |
+
if not parsed['response']:
|
| 295 |
+
number_ref_data = -1
|
| 296 |
+
print('index_neighbor = -1')
|
| 297 |
+
elapsed_time = time.time() - start_time
|
| 298 |
+
dict_result_cost['elapsed_time_[s]'] = float("{:.2f}".format(elapsed_time))
|
| 299 |
+
|
| 300 |
+
if parsed['response']:
|
| 301 |
+
dict_result = get_output_results(json.loads(parsed['response']), dict_result)
|
| 302 |
+
print('dict_result')
|
| 303 |
+
print(dict_result)
|
| 304 |
+
|
| 305 |
+
except requests.exceptions.RequestException as e:
|
| 306 |
+
print(f"Request failed: {e}")
|
| 307 |
+
return dict_result, dict_result_cost
|
| 308 |
+
except requests.Timeout as e:
|
| 309 |
+
print(f"Request failed: {e}")
|
| 310 |
+
return dict_result, dict_result_cost
|
| 311 |
+
except ValueError as ve:
|
| 312 |
+
print(f"Validation error: {ve}")
|
| 313 |
+
return dict_result, dict_result_cost
|
| 314 |
+
except KeyError as e:
|
| 315 |
+
print(f"Key error: {e}")
|
| 316 |
+
return dict_result, dict_result_cost
|
| 317 |
+
except ConnectionError as e:
|
| 318 |
+
print(f"Connection error occurred: {e}")
|
| 319 |
+
return dict_result, dict_result_cost
|
| 320 |
+
else:
|
| 321 |
+
try:
|
| 322 |
+
start_time = time.time()
|
| 323 |
+
response = vlm_rag_structured.invoke(messages)
|
| 324 |
+
|
| 325 |
+
# reduced context
|
| 326 |
+
if not response['parsed']:
|
| 327 |
+
index_neighbor = 0
|
| 328 |
+
number_ref_data, messages = prompt(query_image_base64, question, dict_reference_data, index_neighbor)
|
| 329 |
+
response = vlm_rag_structured.invoke(messages)
|
| 330 |
+
if not response['parsed']:
|
| 331 |
+
index_neighbor = 1
|
| 332 |
+
number_ref_data, messages = prompt(query_image_base64, question, dict_reference_data, index_neighbor)
|
| 333 |
+
response = vlm_rag_structured.invoke(messages)
|
| 334 |
+
if not response['parsed']:
|
| 335 |
+
index_neighbor = 2
|
| 336 |
+
number_ref_data, messages = prompt(query_image_base64, question, dict_reference_data, index_neighbor)
|
| 337 |
+
response = vlm_rag_structured.invoke(messages)
|
| 338 |
+
if not response['parsed']:
|
| 339 |
+
number_ref_data = -1
|
| 340 |
+
elapsed_time = time.time() - start_time
|
| 341 |
+
dict_result_cost['elapsed_time_[s]'] = float("{:.2f}".format(elapsed_time))
|
| 342 |
+
|
| 343 |
+
if response['parsed']:
|
| 344 |
+
dict_result = get_output_results(response['parsed'].dict(), dict_result)
|
| 345 |
+
|
| 346 |
+
except openai.BadRequestError as e:
|
| 347 |
+
print(f"BadRequestError: {e}")
|
| 348 |
+
except ValueError as ve:
|
| 349 |
+
print(f"Validation error: {ve}")
|
| 350 |
+
except openai.LengthFinishReasonError as e:
|
| 351 |
+
print(f"LengthFinishReasonError: {e}")
|
| 352 |
+
except openai.InternalServerError as e:
|
| 353 |
+
print(f"InternalServerError: {e}")
|
| 354 |
+
|
| 355 |
+
try:
|
| 356 |
+
dict_result_cost = token_price_evaluation(response['raw'], dict_result_cost)
|
| 357 |
+
except Exception as e:
|
| 358 |
+
print("Error occurred:", e)
|
| 359 |
+
|
| 360 |
+
if index_neighbor == -1:
|
| 361 |
+
if number_ref_data == 2:
|
| 362 |
+
dict_result = deleting_neigbor('N2_', dict_result)
|
| 363 |
+
elif number_ref_data == 1:
|
| 364 |
+
dict_result = deleting_neigbor('N2_', dict_result)
|
| 365 |
+
dict_result = deleting_neigbor('N1_', dict_result)
|
| 366 |
+
elif number_ref_data == 0:
|
| 367 |
+
dict_result = deleting_neigbor('N2_', dict_result)
|
| 368 |
+
dict_result = deleting_neigbor('N1_', dict_result)
|
| 369 |
+
dict_result = deleting_neigbor('N0_', dict_result)
|
| 370 |
+
else:
|
| 371 |
+
if number_ref_data == 0:
|
| 372 |
+
dict_result = deleting_neigbor('N2_', dict_result)
|
| 373 |
+
dict_result = deleting_neigbor('N1_', dict_result)
|
| 374 |
+
elif number_ref_data == 1:
|
| 375 |
+
dict_result = deleting_neigbor('N2_', dict_result)
|
| 376 |
+
dict_result = deleting_neigbor('N0_', dict_result)
|
| 377 |
+
elif number_ref_data == 2:
|
| 378 |
+
dict_result = deleting_neigbor('N1_', dict_result)
|
| 379 |
+
dict_result = deleting_neigbor('N0_', dict_result)
|
| 380 |
+
elif number_ref_data == -1:
|
| 381 |
+
dict_result = deleting_neigbor('N2_', dict_result)
|
| 382 |
+
dict_result = deleting_neigbor('N1_', dict_result)
|
| 383 |
+
dict_result = deleting_neigbor('N0_', dict_result)
|
| 384 |
+
|
| 385 |
+
return dict_result, dict_result_cost
|
code/visual_rag/rag_vector_store.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import chromadb
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
from langchain_chroma import Chroma
|
| 5 |
+
from langchain_experimental.open_clip import OpenCLIPEmbeddings
|
| 6 |
+
|
| 7 |
+
######################################################################
|
| 8 |
+
######################################################################
|
| 9 |
+
|
| 10 |
+
def get_open_clip_embedding(model_name, checkpoint):
|
| 11 |
+
embedding_function = OpenCLIPEmbeddings(
|
| 12 |
+
model_name=model_name,
|
| 13 |
+
checkpoint=checkpoint,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
return embedding_function
|
| 17 |
+
|
| 18 |
+
def get_chroma_vector_db(path_to_vector_db, name_vector_store, collection_name, embedding_function):
|
| 19 |
+
chroma_client = chromadb.PersistentClient(path = os.path.join(path_to_vector_db, name_vector_store))
|
| 20 |
+
|
| 21 |
+
vectorstore_disk_saved = Chroma(
|
| 22 |
+
client = chroma_client,
|
| 23 |
+
persist_directory = path_to_vector_db,
|
| 24 |
+
collection_name = collection_name,
|
| 25 |
+
embedding_function = embedding_function,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
return vectorstore_disk_saved
|
code/visual_rag/run_rag_pipeline.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import glob
|
| 3 |
+
import io
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
from PIL import Image
|
| 10 |
+
from pydantic import ValidationError
|
| 11 |
+
|
| 12 |
+
import rag_vector_store
|
| 13 |
+
import rag_retriever
|
| 14 |
+
import rag_use_vlm
|
| 15 |
+
|
| 16 |
+
NUMBER_EXAMPLES_IN_PROMPT = 3
|
| 17 |
+
NUMBER_NEIGHBOUR = 5
|
| 18 |
+
|
| 19 |
+
######################################################################
|
| 20 |
+
######################################################################
|
| 21 |
+
|
| 22 |
+
def most_frequent_label(lst):
|
| 23 |
+
return max(lst, key=lst.count)
|
| 24 |
+
|
| 25 |
+
def get_img_base64_str(image_path):
|
| 26 |
+
img = Image.open(image_path)
|
| 27 |
+
buffered = io.BytesIO()
|
| 28 |
+
img.save(buffered, format=img.format)
|
| 29 |
+
img_base64_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 30 |
+
return img_base64_str
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
###################################################################################################################################
|
| 34 |
+
###################################################################################################################################
|
| 35 |
+
###################################################################################################################################
|
| 36 |
+
if __name__ == '__main__':
|
| 37 |
+
|
| 38 |
+
in_path_frame_images = './.../rpp-765k_512'
|
| 39 |
+
in_file_data_entering_train = './.../train.parquet'
|
| 40 |
+
in_file_data_entering_test = './.../test.parquet'
|
| 41 |
+
|
| 42 |
+
in_path_product_image_test = "./.../folder-to-only-product-images"
|
| 43 |
+
in_file_predicted_description_test = "./.../file-of-predicted-description"
|
| 44 |
+
in_path_vector_store = "./.../vector_db"
|
| 45 |
+
in_name_vector_db_name = "name-of-vector-store"
|
| 46 |
+
in_name_vector_db_collection = "name-of-vector-store-collection"
|
| 47 |
+
out_path_results = "./.../output"
|
| 48 |
+
|
| 49 |
+
in_name_results_output = "results"
|
| 50 |
+
in_model_type = "custom-model-type"
|
| 51 |
+
|
| 52 |
+
path_outputs = os.path.join(out_path_results, in_name_results_output)
|
| 53 |
+
os.makedirs(path_outputs, exist_ok=True)
|
| 54 |
+
|
| 55 |
+
dict_rag_approach = {}
|
| 56 |
+
dict_rag_approach['dataset'] = 'rpp-765k_512'
|
| 57 |
+
dict_rag_approach['vector_store'] = in_name_vector_db_name
|
| 58 |
+
|
| 59 |
+
#######################################################################
|
| 60 |
+
#######################################################################
|
| 61 |
+
key = "your-api-key"
|
| 62 |
+
model_name = "your-vector-store-model"
|
| 63 |
+
checkpoint = "your-vector-store-checkpoint"
|
| 64 |
+
|
| 65 |
+
embedding_function = rag_vector_store.get_open_clip_embedding(
|
| 66 |
+
model_name = model_name,
|
| 67 |
+
checkpoint = checkpoint,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
vector_store = rag_vector_store.get_chroma_vector_db(
|
| 71 |
+
path_to_vector_db = in_path_vector_store,
|
| 72 |
+
name_vector_store = in_name_vector_db_name,
|
| 73 |
+
collection_name = in_name_vector_db_collection,
|
| 74 |
+
embedding_function = embedding_function,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
try:
|
| 78 |
+
retriever_rag = rag_retriever.custom_retriever(
|
| 79 |
+
vector_store = vector_store,
|
| 80 |
+
embeddings = vector_store._embedding_function,
|
| 81 |
+
k = NUMBER_NEIGHBOUR,
|
| 82 |
+
)
|
| 83 |
+
except ValidationError as e:
|
| 84 |
+
print(e)
|
| 85 |
+
|
| 86 |
+
df_result = pd.DataFrame(
|
| 87 |
+
columns=['label', 'filename', \
|
| 88 |
+
'brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'weight_number', 'weight_unit', 'different_sorts', 'different_types', \
|
| 89 |
+
'N0_label', 'N0_filename', 'N0_document', 'N0_distance', \
|
| 90 |
+
'N1_label', 'N1_filename', 'N1_document', 'N1_distance', \
|
| 91 |
+
'N2_label', 'N2_filename', 'N2_document', 'N2_distance'])
|
| 92 |
+
df_result_cost = pd.DataFrame(
|
| 93 |
+
columns=['label', 'filename']
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
df_train_data_entering = pd.read_parquet(in_file_data_entering_train, engine='pyarrow')
|
| 97 |
+
df_test_predicted_description = pd.read_parquet(in_file_predicted_description_test, engine='pyarrow')
|
| 98 |
+
df_test_data = pd.read_parquet(in_file_data_entering_test, engine='pyarrow')
|
| 99 |
+
|
| 100 |
+
start_index = 0
|
| 101 |
+
for index, row in df_test_data.iloc[start_index:].iterrows():
|
| 102 |
+
if in_model_type == "your-model-type":
|
| 103 |
+
vlm = rag_use_vlm.get_openai_client(key=key, model_name="your-model-name", context_str_len=int("your-context-length"))
|
| 104 |
+
vlm_rag_structured = rag_use_vlm.get_structured_vlm_model(vlm)
|
| 105 |
+
elif "ollama" in in_name_results_output:
|
| 106 |
+
rag_use_vlm.set_ollama_settings(ip_address="your-ip-address", model_name="your-ollama-model-name", context_str_len=int("your-context-length"))
|
| 107 |
+
|
| 108 |
+
label = str(row.label)
|
| 109 |
+
filename = row.filename
|
| 110 |
+
|
| 111 |
+
dict_result = {}
|
| 112 |
+
dict_result['label'] = label
|
| 113 |
+
dict_result['filename'] = filename
|
| 114 |
+
dict_result_cost = {}
|
| 115 |
+
dict_result_cost['label'] = label
|
| 116 |
+
dict_result_cost['filename'] = filename
|
| 117 |
+
|
| 118 |
+
############################################
|
| 119 |
+
# PREPROCESSING + RETRIEVE
|
| 120 |
+
############################################
|
| 121 |
+
list_path_products_per_frame = glob.glob(os.path.join(in_path_product_image_test, label, filename.split('.jpg')[0] + '*' ))
|
| 122 |
+
|
| 123 |
+
list_retrieve_doc_image = []
|
| 124 |
+
list_retrieve_dis_image = []
|
| 125 |
+
for path_product_image in list_path_products_per_frame:
|
| 126 |
+
retrieve_doc_image, retrieve_dis_image = retriever_rag.invoke('image*-*' + path_product_image)
|
| 127 |
+
list_retrieve_doc_image += retrieve_doc_image
|
| 128 |
+
list_retrieve_dis_image += retrieve_dis_image
|
| 129 |
+
|
| 130 |
+
df_predicted_text = df_test_predicted_description.loc[df_test_predicted_description.filename == filename.split('.')[0] + '_wo_product.jpg']
|
| 131 |
+
if len(df_predicted_text) == 0:
|
| 132 |
+
df_result = pd.concat( [ df_result, pd.DataFrame.from_dict([dict_result]) ], ignore_index=True)
|
| 133 |
+
df_result_cost = pd.concat( [ df_result_cost, pd.DataFrame.from_dict([dict_result_cost]) ], ignore_index=True)
|
| 134 |
+
continue
|
| 135 |
+
predicted_text_frame_wo = df_predicted_text['product_description_text'].values[0]
|
| 136 |
+
if predicted_text_frame_wo is None:
|
| 137 |
+
df_result = pd.concat( [ df_result, pd.DataFrame.from_dict([dict_result]) ], ignore_index=True)
|
| 138 |
+
df_result_cost = pd.concat( [ df_result_cost, pd.DataFrame.from_dict([dict_result_cost]) ], ignore_index=True)
|
| 139 |
+
continue
|
| 140 |
+
|
| 141 |
+
retrieve_doc_text, retrieve_dis_text = retriever_rag.invoke('text*-*' + predicted_text_frame_wo)
|
| 142 |
+
|
| 143 |
+
list_cls_label_image = [int(doc.metadata['path'].split('/')[-2]) for doc in list_retrieve_doc_image]
|
| 144 |
+
list_cls_label_text = [int(doc.metadata['path'].split('/')[-2]) for doc in retrieve_doc_text]
|
| 145 |
+
cls_label = most_frequent_label(list_cls_label_image + list_cls_label_text)
|
| 146 |
+
|
| 147 |
+
# getting all frame images and data entering info of images that belong to cls_label and were retrieved
|
| 148 |
+
indices = [idx for idx, value in enumerate(list_cls_label_image) if value == cls_label]
|
| 149 |
+
list_label_image = [list_retrieve_doc_image[idx].metadata['path'].split('/')[-2] for idx in indices]
|
| 150 |
+
list_frame_image = [list_retrieve_doc_image[idx].metadata['path'].split('/')[-1].split('_')[0] + '.jpg' for idx in indices]
|
| 151 |
+
list_dis_image = [list_retrieve_dis_image[idx] for idx in indices]
|
| 152 |
+
|
| 153 |
+
indices = [idx for idx, value in enumerate(list_cls_label_text) if value == cls_label]
|
| 154 |
+
list_label_text = [retrieve_doc_text[idx].metadata['path'].split('/')[-2] for idx in indices]
|
| 155 |
+
list_frame_text = [retrieve_doc_text[idx].metadata['path'].split('/')[-1] for idx in indices]
|
| 156 |
+
list_dis_text = [retrieve_dis_text[idx] for idx in indices]
|
| 157 |
+
|
| 158 |
+
df_image = pd.DataFrame({'distance': list_dis_image, 'label': list_label_image, 'filename': list_frame_image, 'document': ['image' for _ in range(len(list_frame_image))]})
|
| 159 |
+
df_text = pd.DataFrame({'distance': list_dis_text, 'label': list_label_text, 'filename': list_frame_text, 'document': ['text' for _ in range(len(list_frame_text))]})
|
| 160 |
+
df_image_text = pd.concat([df_image, df_text], ignore_index=True)
|
| 161 |
+
|
| 162 |
+
df_grouped = df_image_text.loc[df_image_text.groupby('filename')['distance'].idxmin()]
|
| 163 |
+
df_sorted = df_grouped.sort_values(by='distance').reset_index(drop=True)
|
| 164 |
+
df_sorted['filename'] = df_sorted['filename'].str.replace('_wo_product', '')
|
| 165 |
+
list_reference_filename = df_sorted['filename'].tolist()
|
| 166 |
+
|
| 167 |
+
dict_rag_approach['prompt_number_example_image'] = NUMBER_EXAMPLES_IN_PROMPT
|
| 168 |
+
dict_rag_approach['prompt_number_example_text'] = NUMBER_EXAMPLES_IN_PROMPT
|
| 169 |
+
|
| 170 |
+
for index_vectordb, row_vectordb in df_sorted.iloc[:NUMBER_EXAMPLES_IN_PROMPT].iterrows():
|
| 171 |
+
neighbor = 'N' + str(index_vectordb) + '_'
|
| 172 |
+
dict_result[neighbor + 'label'] = row_vectordb.label
|
| 173 |
+
dict_result[neighbor + 'filename'] = row_vectordb.filename
|
| 174 |
+
dict_result[neighbor + 'document'] = row_vectordb.document
|
| 175 |
+
dict_result[neighbor + 'distance'] = row_vectordb.distance
|
| 176 |
+
|
| 177 |
+
list_reference_filename = list_reference_filename[:NUMBER_EXAMPLES_IN_PROMPT]
|
| 178 |
+
|
| 179 |
+
############################################
|
| 180 |
+
# PROMPT
|
| 181 |
+
############################################
|
| 182 |
+
# IMAGE
|
| 183 |
+
image_path = os.path.join( in_path_frame_images, 'test', label, filename )
|
| 184 |
+
query_image_base64 = rag_use_vlm.get_img_base64_str(image_path)
|
| 185 |
+
|
| 186 |
+
# QUESTION
|
| 187 |
+
question = "Extract all features."
|
| 188 |
+
dict_rag_approach['prompt_question'] = question
|
| 189 |
+
|
| 190 |
+
# REFERENCE DATA
|
| 191 |
+
dict_reference_data = {}
|
| 192 |
+
dict_reference_data['reference_data'] = {}
|
| 193 |
+
list_ref_image_base64 = []
|
| 194 |
+
list_ref_text = []
|
| 195 |
+
|
| 196 |
+
for ref_filename in list_reference_filename:
|
| 197 |
+
tmp_image_bas64 = get_img_base64_str(os.path.join(in_path_frame_images, 'train', str(cls_label), ref_filename))
|
| 198 |
+
list_ref_image_base64.append(tmp_image_bas64)
|
| 199 |
+
dict_reference_data['reference_data']['image'] = list_ref_image_base64
|
| 200 |
+
|
| 201 |
+
for ref_filename in list_reference_filename:
|
| 202 |
+
series_row = df_train_data_entering.loc[df_train_data_entering.filename == ref_filename]
|
| 203 |
+
result = []
|
| 204 |
+
for idx, value in series_row.items():
|
| 205 |
+
if idx == 'label' or idx == 'filename':
|
| 206 |
+
continue
|
| 207 |
+
if pd.notnull(value).item():
|
| 208 |
+
if idx == 'product_weight':
|
| 209 |
+
number = value.values[0].split(' ')[0]
|
| 210 |
+
unit = value.values[0].split(' ')[1]
|
| 211 |
+
result.append(f"weight_number: {number}")
|
| 212 |
+
result.append(f"weight_unit: {unit}")
|
| 213 |
+
else:
|
| 214 |
+
result.append(f"{idx}: {value.values[0]}")
|
| 215 |
+
tmp_text = ", ".join(result)
|
| 216 |
+
list_ref_text.append(tmp_text)
|
| 217 |
+
|
| 218 |
+
dict_reference_data['reference_data']['text'] = list_ref_text
|
| 219 |
+
|
| 220 |
+
# adapt call depending on your model type
|
| 221 |
+
dict_result, dict_result_cost = rag_use_vlm.do_request(
|
| 222 |
+
query_image_base64,
|
| 223 |
+
question,
|
| 224 |
+
dict_reference_data,
|
| 225 |
+
vlm_rag_structured,
|
| 226 |
+
dict_result,
|
| 227 |
+
dict_result_cost
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
df_result = pd.concat( [ df_result, pd.DataFrame.from_dict([dict_result]) ], ignore_index=True)
|
| 231 |
+
df_result_cost = pd.concat( [ df_result_cost, pd.DataFrame.from_dict([dict_result_cost]) ], ignore_index=True)
|
| 232 |
+
|
| 233 |
+
if index%100 == 0:
|
| 234 |
+
df_result.to_parquet( os.path.join(path_outputs, 'df_result' + '_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 235 |
+
df_result_cost.to_parquet( os.path.join(path_outputs, 'df_result' + '_costs_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 236 |
+
|
| 237 |
+
df_result = pd.DataFrame(
|
| 238 |
+
columns=['label', 'filename', \
|
| 239 |
+
'brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'weight_number', 'weight_unit', 'different_sorts', 'different_types', \
|
| 240 |
+
'N0_label', 'N0_filename', 'N0_document', 'N0_distance', \
|
| 241 |
+
'N1_label', 'N1_filename', 'N1_document', 'N1_distance', \
|
| 242 |
+
'N2_label', 'N2_filename', 'N2_document', 'N2_distance'])
|
| 243 |
+
df_result_cost = pd.DataFrame(
|
| 244 |
+
columns=['label', 'filename']
|
| 245 |
+
)
|
| 246 |
+
time.sleep(60)
|
| 247 |
+
|
| 248 |
+
#######################################################################
|
| 249 |
+
#######################################################################
|
| 250 |
+
|
| 251 |
+
df_result.to_parquet( os.path.join(path_outputs, 'df_result' + '_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 252 |
+
df_result_cost.to_parquet( os.path.join(path_outputs, 'df_result' + '_costs_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 253 |
+
|
| 254 |
+
if in_model_type == "openai" or in_model_type == "gemini":
|
| 255 |
+
print(f"TOTAL COSTS")
|
| 256 |
+
sum_of_costs = df_result_cost['total_cost'].sum()
|
| 257 |
+
sum_of_costs = float(sum_of_costs)
|
| 258 |
+
print(f"${sum_of_costs:.2f}")
|
| 259 |
+
|
| 260 |
+
with open(os.path.join(path_outputs, in_name_results_output + '.json'), 'w') as json_file:
|
| 261 |
+
json.dump(dict_rag_approach, json_file)
|
code/vlm/custom_vlm_metrics.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def get_mean_squared_error(df_true , df_pred, f, df_data_mse_rmse):
|
| 5 |
+
from sklearn.metrics import mean_squared_error, root_mean_squared_error
|
| 6 |
+
|
| 7 |
+
df_pred_copy = df_pred.copy()
|
| 8 |
+
df_pred_copy[f] = pd.to_numeric(df_pred_copy[f], errors='coerce')
|
| 9 |
+
|
| 10 |
+
mask = df_true[f].notna() & df_pred_copy[f].notna()
|
| 11 |
+
df_data_mse_rmse.at['non-null GT', f] = int(df_true[f].notna().value_counts().get(True, 0))
|
| 12 |
+
df_data_mse_rmse.at['non-null prediction', f] = int(df_pred_copy[f].notna().value_counts().get(True, 0))
|
| 13 |
+
df_data_mse_rmse.at['non-null GT AND prediction', f]= int(mask.value_counts().get(True, 0))
|
| 14 |
+
df_data_mse_rmse.at['null GT', f] = int(df_true[f].notna().value_counts().get(False, 0))
|
| 15 |
+
df_data_mse_rmse.at['null prediction', f] = int(df_pred_copy[f].notna().value_counts().get(False, 0))
|
| 16 |
+
df_data_mse_rmse.at['null GT AND prediction', f] = int(mask.value_counts().get(False, 0))
|
| 17 |
+
|
| 18 |
+
y_true_clean = df_true.loc[mask, f]
|
| 19 |
+
y_pred_clean = df_pred_copy.loc[mask, f]
|
| 20 |
+
|
| 21 |
+
mse = mean_squared_error(y_true_clean, y_pred_clean)
|
| 22 |
+
df_data_mse_rmse.at['MSE', f] = mse
|
| 23 |
+
|
| 24 |
+
rmse = root_mean_squared_error(y_true_clean, y_pred_clean)
|
| 25 |
+
df_data_mse_rmse.at['RMSE', f] = rmse
|
| 26 |
+
|
| 27 |
+
return df_data_mse_rmse
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_edit_distances(df_true , df_pred, f, df_edit_distance_brand):
|
| 31 |
+
mask = df_true[f].notna() & df_pred[f].notna()
|
| 32 |
+
|
| 33 |
+
y_true_clean = df_true.loc[mask, f]
|
| 34 |
+
y_pred_clean = df_pred.loc[mask, f]
|
| 35 |
+
|
| 36 |
+
df_feature_true = pd.DataFrame({
|
| 37 |
+
f : y_true_clean,
|
| 38 |
+
f + '_lower' : y_true_clean.str.lower()
|
| 39 |
+
})
|
| 40 |
+
df_feature_pred = pd.DataFrame({
|
| 41 |
+
f : y_pred_clean,
|
| 42 |
+
f + '_lower' : y_pred_clean.str.lower()
|
| 43 |
+
})
|
| 44 |
+
|
| 45 |
+
df_feature_true = df_feature_true.sort_index()
|
| 46 |
+
df_feature_pred = df_feature_pred.sort_index()
|
| 47 |
+
|
| 48 |
+
df_edit_distance_brand['true_' + f + '_lower'] = df_feature_true[f + '_lower']
|
| 49 |
+
df_edit_distance_brand['pred_' + f + '_lower'] = df_feature_pred[f + '_lower']
|
| 50 |
+
|
| 51 |
+
# Levenshtein distance
|
| 52 |
+
import Levenshtein
|
| 53 |
+
lev_dist = [
|
| 54 |
+
Levenshtein.distance(n1, n2)
|
| 55 |
+
for n1, n2 in zip(df_feature_true[f + '_lower'], df_feature_pred[f + '_lower'])
|
| 56 |
+
]
|
| 57 |
+
df_edit_distance_brand['levenshtein_dist'] = lev_dist
|
| 58 |
+
|
| 59 |
+
# Hamming Distance
|
| 60 |
+
ham_dist = [
|
| 61 |
+
sum(n1 != n2 for n1, n2 in zip(str(s1), str(s2))) if len(str(s1)) == len(str(s2)) else None
|
| 62 |
+
for s1, s2 in zip(df_feature_true[f + '_lower'], df_feature_pred[f + '_lower'])
|
| 63 |
+
]
|
| 64 |
+
df_edit_distance_brand['hamming_dist'] = ham_dist
|
| 65 |
+
|
| 66 |
+
# Damerau-Levenshtein Distance
|
| 67 |
+
import textdistance
|
| 68 |
+
damerau_lev_dist = [
|
| 69 |
+
textdistance.damerau_levenshtein.distance(str(n1), str(n2))
|
| 70 |
+
for n1, n2 in zip(df_feature_true[f + '_lower'], df_feature_pred[f + '_lower'])
|
| 71 |
+
]
|
| 72 |
+
df_edit_distance_brand['damerau_levenshtein_dist'] = damerau_lev_dist
|
| 73 |
+
|
| 74 |
+
# Jaro Distance
|
| 75 |
+
jaro_dist = [
|
| 76 |
+
textdistance.jaro.distance(str(n1), str(n2))
|
| 77 |
+
for n1, n2 in zip(df_feature_true[f + '_lower'], df_feature_pred[f + '_lower'])
|
| 78 |
+
]
|
| 79 |
+
df_edit_distance_brand['jaro_dist'] = jaro_dist
|
| 80 |
+
|
| 81 |
+
return df_edit_distance_brand
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def string_operations(string):
|
| 86 |
+
import unicodedata
|
| 87 |
+
import re
|
| 88 |
+
|
| 89 |
+
string = string.lower()
|
| 90 |
+
string = unicodedata.normalize('NFD', string)
|
| 91 |
+
string = ''.join(char for char in string if unicodedata.category(char) != 'Mn')
|
| 92 |
+
string = re.sub(r"[']", "", string)
|
| 93 |
+
|
| 94 |
+
return string
|
| 95 |
+
|
| 96 |
+
def brand_fuzzy_match(str_pred, str_gt):
|
| 97 |
+
import Levenshtein
|
| 98 |
+
import re
|
| 99 |
+
|
| 100 |
+
distance = Levenshtein.distance(str_pred, str_gt)
|
| 101 |
+
similarity = 1 - (distance / max(len(str_pred), len(str_gt)))
|
| 102 |
+
|
| 103 |
+
if similarity > 0.5:
|
| 104 |
+
return 1
|
| 105 |
+
else:
|
| 106 |
+
words = re.split(r'\W+', str_pred)
|
| 107 |
+
list_words_pred = [word for word in words if word]
|
| 108 |
+
words = re.split(r'\W+', str_gt)
|
| 109 |
+
list_words_gt = [word for word in words if word]
|
| 110 |
+
if any(item in list_words_gt for item in list_words_pred):
|
| 111 |
+
return 1
|
| 112 |
+
else:
|
| 113 |
+
return 0
|
| 114 |
+
|
| 115 |
+
def price_discount_fuzzy_match(f, str_pred, str_gt):
|
| 116 |
+
if f == 'relative_discount' and str_gt != 'nan':
|
| 117 |
+
str_gt = str(int(float(str_gt)))
|
| 118 |
+
|
| 119 |
+
if str_pred == str_gt:
|
| 120 |
+
return 1
|
| 121 |
+
else:
|
| 122 |
+
return 0
|
| 123 |
+
|
| 124 |
+
def product_weight_fuzzy_match(str_pred, str_gt, weight_number):
|
| 125 |
+
if str_pred == str_gt:
|
| 126 |
+
return 1
|
| 127 |
+
elif str_pred is not None and str_gt is None:
|
| 128 |
+
return 0
|
| 129 |
+
else:
|
| 130 |
+
if 'Gramm' in str_pred and 'Kilogramm' in str_gt:
|
| 131 |
+
str_pred = str(float(weight_number)/1000) + ' ' + 'Kilogramm'
|
| 132 |
+
if str_pred == str_gt:
|
| 133 |
+
return 1
|
| 134 |
+
elif 'Kilogramm' in str_pred and 'Gramm' in str_gt:
|
| 135 |
+
str_pred = str(float(weight_number)*1000) + ' ' + 'Gramm'
|
| 136 |
+
if str_pred == str_gt:
|
| 137 |
+
return 1
|
| 138 |
+
elif 'Milliliter' in str_pred and 'Liter' in str_gt:
|
| 139 |
+
str_pred = str(float(weight_number)/1000) + ' ' + 'Liter'
|
| 140 |
+
if str_pred == str_gt:
|
| 141 |
+
return 1
|
| 142 |
+
elif 'Liter' in str_pred and 'Milliliter' in str_gt:
|
| 143 |
+
str_pred = str(float(weight_number)*1000) + ' ' + 'Milliliter'
|
| 144 |
+
if str_pred == str_gt:
|
| 145 |
+
return 1
|
| 146 |
+
return 0
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def different_sorts_fuzzy_match(str_pred, str_gt):
|
| 150 |
+
if str_pred == str_gt:
|
| 151 |
+
return 1
|
| 152 |
+
else:
|
| 153 |
+
return 0
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def get_custom_accuracy(df_true, df_pred, f, df_custom_accuracy):
|
| 157 |
+
if f != 'product_weight' and f != 'different_types':
|
| 158 |
+
mask = df_true[f].notna() & df_pred[f].notna()
|
| 159 |
+
|
| 160 |
+
df_custom_accuracy.at['non-null GT', f] = int(df_true[f].notna().value_counts().get(True, 0))
|
| 161 |
+
df_custom_accuracy.at['non-null prediction', f] = int(df_pred[f].notna().value_counts().get(True, 0))
|
| 162 |
+
df_custom_accuracy.at['non-null GT AND prediction', f] = int(mask.value_counts().get(True, 0))
|
| 163 |
+
df_custom_accuracy.at['null GT', f] = int(df_true[f].notna().value_counts().get(False, 0))
|
| 164 |
+
df_custom_accuracy.at['null prediction', f] = int(df_pred[f].notna().value_counts().get(False, 0))
|
| 165 |
+
df_custom_accuracy.at['null GT AND prediction', f] = int(mask.value_counts().get(False, 0))
|
| 166 |
+
|
| 167 |
+
y_true_clean = df_true.loc[mask, f]
|
| 168 |
+
y_pred_clean = df_pred.loc[mask, f]
|
| 169 |
+
|
| 170 |
+
if f == 'brand':
|
| 171 |
+
df_feature_true = pd.DataFrame({
|
| 172 |
+
f : y_true_clean,
|
| 173 |
+
f + '_string_op' : y_true_clean.apply(string_operations)
|
| 174 |
+
})
|
| 175 |
+
df_feature_pred = pd.DataFrame({
|
| 176 |
+
f : y_pred_clean,
|
| 177 |
+
f + '_string_op' : y_pred_clean.apply(string_operations)
|
| 178 |
+
})
|
| 179 |
+
|
| 180 |
+
tmp = pd.DataFrame()
|
| 181 |
+
tmp['match'] = [
|
| 182 |
+
brand_fuzzy_match(pred, gt)
|
| 183 |
+
for pred, gt in zip(df_feature_pred[f + '_string_op'], df_feature_true[f + '_string_op'])
|
| 184 |
+
]
|
| 185 |
+
|
| 186 |
+
from sklearn.metrics import accuracy_score
|
| 187 |
+
df_custom_accuracy.at['custom_acc', f] = accuracy_score([1]*len(tmp['match']), tmp['match'])
|
| 188 |
+
|
| 189 |
+
elif f == 'price' or f == 'regular_price' or f == 'relative_discount' or f == 'absolute_discount':
|
| 190 |
+
df_feature_true = pd.DataFrame({
|
| 191 |
+
f : y_true_clean,
|
| 192 |
+
f + '_string_op' : y_true_clean
|
| 193 |
+
})
|
| 194 |
+
df_feature_pred = pd.DataFrame({
|
| 195 |
+
f : y_pred_clean,
|
| 196 |
+
f + '_string_op' : y_pred_clean.str.replace('-', '')
|
| 197 |
+
})
|
| 198 |
+
|
| 199 |
+
tmp = pd.DataFrame()
|
| 200 |
+
tmp['match'] = [
|
| 201 |
+
price_discount_fuzzy_match(f, str(pred), str(gt))
|
| 202 |
+
for pred, gt in zip(df_feature_pred[f + '_string_op'], df_feature_true[f + '_string_op'])
|
| 203 |
+
]
|
| 204 |
+
from sklearn.metrics import accuracy_score
|
| 205 |
+
df_custom_accuracy.at['custom_acc', f] = accuracy_score([1]*len(tmp['match']), tmp['match'])
|
| 206 |
+
|
| 207 |
+
elif f == 'product_weight':
|
| 208 |
+
df_pred[f] = df_pred['weight_number'].astype(str) + ' ' + df_pred['weight_unit'].astype(str)
|
| 209 |
+
mask = df_true[f].notna() & df_pred[f].notna()
|
| 210 |
+
|
| 211 |
+
df_custom_accuracy.at['non-null GT', f] = int(df_true[f].notna().value_counts().get(True, 0))
|
| 212 |
+
df_custom_accuracy.at['non-null prediction', f] = int(df_pred[f].notna().value_counts().get(True, 0))
|
| 213 |
+
df_custom_accuracy.at['non-null GT AND prediction', f] = int(mask.value_counts().get(True, 0))
|
| 214 |
+
df_custom_accuracy.at['null GT', f] = int(df_true[f].notna().value_counts().get(False, 0))
|
| 215 |
+
df_custom_accuracy.at['null prediction', f] = int(df_pred[f].notna().value_counts().get(False, 0))
|
| 216 |
+
df_custom_accuracy.at['null GT AND prediction', f] = int(mask.value_counts().get(False, 0))
|
| 217 |
+
|
| 218 |
+
y_true_clean = df_true.loc[mask, f]
|
| 219 |
+
y_pred_clean = df_pred.loc[mask, f]
|
| 220 |
+
y_pred_clean_weight_number = df_pred.loc[mask, 'weight_number']
|
| 221 |
+
y_pred_clean_weight_unit = df_pred.loc[mask, 'weight_unit']
|
| 222 |
+
|
| 223 |
+
df_feature_true = pd.DataFrame({
|
| 224 |
+
f : y_true_clean
|
| 225 |
+
})
|
| 226 |
+
df_feature_pred = pd.DataFrame({
|
| 227 |
+
f : y_pred_clean,
|
| 228 |
+
'weight_number' : y_pred_clean_weight_number,
|
| 229 |
+
'weight_unit' : y_pred_clean_weight_unit,
|
| 230 |
+
})
|
| 231 |
+
|
| 232 |
+
tmp = pd.DataFrame()
|
| 233 |
+
tmp['match'] = [
|
| 234 |
+
product_weight_fuzzy_match(str(pred), str(gt), weight_number)
|
| 235 |
+
for pred, gt, weight_number in zip(df_feature_pred[f], df_feature_true[f], df_feature_pred['weight_number'])
|
| 236 |
+
]
|
| 237 |
+
from sklearn.metrics import accuracy_score
|
| 238 |
+
df_custom_accuracy.at['custom_acc', f] = accuracy_score([1]*len(tmp['match']), tmp['match'])
|
| 239 |
+
|
| 240 |
+
elif f == 'different_types':
|
| 241 |
+
|
| 242 |
+
tmp = pd.DataFrame()
|
| 243 |
+
tmp['match'] = [
|
| 244 |
+
different_sorts_fuzzy_match(str(pred), str(gt))
|
| 245 |
+
for pred, gt in zip(df_true[f], df_pred[f])
|
| 246 |
+
]
|
| 247 |
+
from sklearn.metrics import accuracy_score
|
| 248 |
+
df_custom_accuracy.at['custom_acc', f] = accuracy_score([1]*len(tmp['match']), tmp['match'])
|
| 249 |
+
|
| 250 |
+
return df_custom_accuracy
|
code/vlm/evaluation_vlm.ipynb
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "78b02192",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"import json\n",
|
| 11 |
+
"import os\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"import pandas as pd\n",
|
| 14 |
+
"import matplotlib.pyplot as plt"
|
| 15 |
+
]
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"id": "7405fa4d",
|
| 21 |
+
"metadata": {},
|
| 22 |
+
"outputs": [],
|
| 23 |
+
"source": [
|
| 24 |
+
"%pip install Levenshtein\n",
|
| 25 |
+
"%pip install textdistance\n",
|
| 26 |
+
"%pip install scikit-learn"
|
| 27 |
+
]
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"execution_count": null,
|
| 32 |
+
"id": "01b8aa75",
|
| 33 |
+
"metadata": {},
|
| 34 |
+
"outputs": [],
|
| 35 |
+
"source": [
|
| 36 |
+
"df_test = pd.read_parquet('./.../test.parquet', engine='pyarrow')"
|
| 37 |
+
]
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "code",
|
| 41 |
+
"execution_count": null,
|
| 42 |
+
"id": "07196ee1",
|
| 43 |
+
"metadata": {},
|
| 44 |
+
"outputs": [],
|
| 45 |
+
"source": [
|
| 46 |
+
"path_to_vlm_results = \"./.../vlm_results\"\n",
|
| 47 |
+
"vlm_name = \"your-vlm-name\"\n",
|
| 48 |
+
"file_vlm_results = \"./.../your-vlm-results.parquet\""
|
| 49 |
+
]
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "markdown",
|
| 53 |
+
"id": "d414ef1f",
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"source": [
|
| 56 |
+
"# Evaluation of VLM"
|
| 57 |
+
]
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"cell_type": "code",
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"id": "b5c664ed",
|
| 63 |
+
"metadata": {},
|
| 64 |
+
"outputs": [],
|
| 65 |
+
"source": [
|
| 66 |
+
"df_vlm = pd.read_parquet(os.path.join(path_to_vlm_results, file_vlm_results), engine='pyarrow')\n",
|
| 67 |
+
"df_vlm"
|
| 68 |
+
]
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"cell_type": "code",
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"id": "19e6c03f",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"outputs": [],
|
| 76 |
+
"source": [
|
| 77 |
+
"output_path = os.path.join('results', vlm_name)\n",
|
| 78 |
+
"os.makedirs(output_path, exist_ok=True)"
|
| 79 |
+
]
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "markdown",
|
| 83 |
+
"id": "a727018d",
|
| 84 |
+
"metadata": {},
|
| 85 |
+
"source": [
|
| 86 |
+
"check if all images have a response"
|
| 87 |
+
]
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"cell_type": "code",
|
| 91 |
+
"execution_count": null,
|
| 92 |
+
"id": "f6874064",
|
| 93 |
+
"metadata": {},
|
| 94 |
+
"outputs": [],
|
| 95 |
+
"source": [
|
| 96 |
+
"number_no_prediction = len(df_vlm.loc[df_vlm.iloc[:, 2:12].isna().all(axis=1)].filename.tolist())\n",
|
| 97 |
+
"print('number of images that have no prediction: ' + str(number_no_prediction))"
|
| 98 |
+
]
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"id": "88081381",
|
| 104 |
+
"metadata": {},
|
| 105 |
+
"outputs": [],
|
| 106 |
+
"source": [
|
| 107 |
+
"data = {}\n",
|
| 108 |
+
"data['number_no_prediction'] = int(number_no_prediction)\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"with open(os.path.join(output_path, \"data.json\"), \"w\") as file:\n",
|
| 111 |
+
" json.dump(data, file, indent=2)"
|
| 112 |
+
]
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "markdown",
|
| 116 |
+
"id": "ede59b34",
|
| 117 |
+
"metadata": {},
|
| 118 |
+
"source": [
|
| 119 |
+
"# Evaluation Metric: Single Target"
|
| 120 |
+
]
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"cell_type": "code",
|
| 124 |
+
"execution_count": null,
|
| 125 |
+
"id": "c34d6ec7",
|
| 126 |
+
"metadata": {},
|
| 127 |
+
"outputs": [],
|
| 128 |
+
"source": [
|
| 129 |
+
"import custom_vlm_metrics\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"import importlib\n",
|
| 132 |
+
"importlib.reload(custom_vlm_metrics)"
|
| 133 |
+
]
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"id": "1e90eb78",
|
| 139 |
+
"metadata": {},
|
| 140 |
+
"outputs": [],
|
| 141 |
+
"source": [
|
| 142 |
+
"list_features = ['brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'product_weight', 'different_types']\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"df_data_mse_rmse = pd.DataFrame()\n",
|
| 145 |
+
"df_edit_distance_brand = pd.DataFrame()\n",
|
| 146 |
+
"df_custom_accuracy = pd.DataFrame()\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"df_vlm['different_types'] = df_vlm['different_types'].apply(lambda x: x if x == 'yes' else None)\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"for f in list_features:\n",
|
| 151 |
+
" print(f)\n",
|
| 152 |
+
" if 'price' in f or 'discount' in f:\n",
|
| 153 |
+
" df_data_mse_rmse = custom_vlm_metrics.get_mean_squared_error(df_test, df_vlm, f, df_data_mse_rmse)\n",
|
| 154 |
+
" elif f == 'brand':\n",
|
| 155 |
+
" df_edit_distance_brand = custom_vlm_metrics.get_edit_distances(df_test, df_vlm, f, df_edit_distance_brand)\n",
|
| 156 |
+
" \n",
|
| 157 |
+
" if f != 'product_category' and f != 'GTINs':\n",
|
| 158 |
+
" df_custom_accuracy = custom_vlm_metrics.get_custom_accuracy(df_test, df_vlm, f, df_custom_accuracy)"
|
| 159 |
+
]
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"cell_type": "code",
|
| 163 |
+
"execution_count": null,
|
| 164 |
+
"id": "4340f330",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"outputs": [],
|
| 167 |
+
"source": [
|
| 168 |
+
"df_data_mse_rmse.to_parquet(os.path.join(output_path, vlm_name + '_mse_rmse.parquet'), engine='pyarrow')\n",
|
| 169 |
+
"df_data_mse_rmse"
|
| 170 |
+
]
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"execution_count": null,
|
| 175 |
+
"id": "10bcccc5",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"outputs": [],
|
| 178 |
+
"source": [
|
| 179 |
+
"df_edit_distance_brand.to_parquet(os.path.join(output_path, vlm_name + '_edit_distance_brand.parquet'), engine='pyarrow')\n",
|
| 180 |
+
"df_edit_distance_brand"
|
| 181 |
+
]
|
| 182 |
+
},
|
| 183 |
+
{
|
| 184 |
+
"cell_type": "code",
|
| 185 |
+
"execution_count": null,
|
| 186 |
+
"id": "76fad091",
|
| 187 |
+
"metadata": {},
|
| 188 |
+
"outputs": [],
|
| 189 |
+
"source": [
|
| 190 |
+
"for column in ['levenshtein_dist', 'hamming_dist', 'damerau_levenshtein_dist', 'jaro_dist']:\n",
|
| 191 |
+
" plt.figure()\n",
|
| 192 |
+
" df_edit_distance_brand.boxplot(column=column)\n",
|
| 193 |
+
" plt.savefig(os.path.join(output_path, vlm_name + f'_boxplot_{column}.png'))\n",
|
| 194 |
+
" plt.close()"
|
| 195 |
+
]
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"cell_type": "code",
|
| 199 |
+
"execution_count": null,
|
| 200 |
+
"id": "8f7aaf0c",
|
| 201 |
+
"metadata": {},
|
| 202 |
+
"outputs": [],
|
| 203 |
+
"source": [
|
| 204 |
+
"mean_values = df_edit_distance_brand[['levenshtein_dist', 'hamming_dist', 'damerau_levenshtein_dist', 'jaro_dist']].mean()\n",
|
| 205 |
+
"mean_values.to_csv(os.path.join(output_path, vlm_name + '_edit_distance_brand_mean_values.csv'), header=True)\n",
|
| 206 |
+
"mean_values"
|
| 207 |
+
]
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"cell_type": "code",
|
| 211 |
+
"execution_count": null,
|
| 212 |
+
"id": "08475d4b",
|
| 213 |
+
"metadata": {},
|
| 214 |
+
"outputs": [],
|
| 215 |
+
"source": [
|
| 216 |
+
"df_custom_accuracy.to_parquet(os.path.join(output_path, vlm_name + '_custom_accuracy.parquet'), engine='pyarrow')\n",
|
| 217 |
+
"df_custom_accuracy"
|
| 218 |
+
]
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"cell_type": "code",
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"id": "f8dc51a3",
|
| 224 |
+
"metadata": {},
|
| 225 |
+
"outputs": [],
|
| 226 |
+
"source": [
|
| 227 |
+
"# different types: valid prediction and GT values\n",
|
| 228 |
+
"\n",
|
| 229 |
+
"df = pd.read_parquet(\"./.../your-vlm-results.parquet\", engine='pyarrow')\n",
|
| 230 |
+
"print(len(df.loc[df.different_types == 'yes'] + df.loc[df.different_types == 'no']))"
|
| 231 |
+
]
|
| 232 |
+
},
|
| 233 |
+
{
|
| 234 |
+
"cell_type": "markdown",
|
| 235 |
+
"id": "0d486fc3",
|
| 236 |
+
"metadata": {},
|
| 237 |
+
"source": [
|
| 238 |
+
"# Evaluation of costs"
|
| 239 |
+
]
|
| 240 |
+
},
|
| 241 |
+
{
|
| 242 |
+
"cell_type": "code",
|
| 243 |
+
"execution_count": null,
|
| 244 |
+
"id": "8698d727",
|
| 245 |
+
"metadata": {},
|
| 246 |
+
"outputs": [],
|
| 247 |
+
"source": [
|
| 248 |
+
"vlm_name = \"your-vlm-name\"\n",
|
| 249 |
+
"file_vlm_results = \"./.../your-vlm-results_of_costs.parquet\""
|
| 250 |
+
]
|
| 251 |
+
},
|
| 252 |
+
{
|
| 253 |
+
"cell_type": "code",
|
| 254 |
+
"execution_count": null,
|
| 255 |
+
"id": "d64a7f32",
|
| 256 |
+
"metadata": {},
|
| 257 |
+
"outputs": [],
|
| 258 |
+
"source": [
|
| 259 |
+
"df_vlm_costs = pd.read_parquet(os.path.join(path_to_vlm_results, file_vlm_results), engine='pyarrow')\n",
|
| 260 |
+
"df_vlm_costs"
|
| 261 |
+
]
|
| 262 |
+
},
|
| 263 |
+
{
|
| 264 |
+
"cell_type": "code",
|
| 265 |
+
"execution_count": null,
|
| 266 |
+
"id": "ac287607",
|
| 267 |
+
"metadata": {},
|
| 268 |
+
"outputs": [],
|
| 269 |
+
"source": [
|
| 270 |
+
"# total elapsed time (all req.)\n",
|
| 271 |
+
"df_vlm_costs['elapsed_time_[s]'].sum()"
|
| 272 |
+
]
|
| 273 |
+
},
|
| 274 |
+
{
|
| 275 |
+
"cell_type": "code",
|
| 276 |
+
"execution_count": null,
|
| 277 |
+
"id": "d880640d",
|
| 278 |
+
"metadata": {},
|
| 279 |
+
"outputs": [],
|
| 280 |
+
"source": [
|
| 281 |
+
"# in hours\n",
|
| 282 |
+
"df_vlm_costs['elapsed_time_[s]'].sum() / 60 / 60"
|
| 283 |
+
]
|
| 284 |
+
},
|
| 285 |
+
{
|
| 286 |
+
"cell_type": "code",
|
| 287 |
+
"execution_count": null,
|
| 288 |
+
"id": "aabc0cd2",
|
| 289 |
+
"metadata": {},
|
| 290 |
+
"outputs": [],
|
| 291 |
+
"source": [
|
| 292 |
+
"columns_to_describe = ['elapsed_time_[s]', 'input_tokens', 'output_tokens', 'total_tokens', 'total_cost']\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"describe_df = df_vlm_costs[columns_to_describe].describe()\n",
|
| 295 |
+
"describe_df.to_parquet(os.path.join(output_path, vlm_name + '_costs_describe.parquet'), engine='pyarrow')\n",
|
| 296 |
+
"describe_df"
|
| 297 |
+
]
|
| 298 |
+
},
|
| 299 |
+
{
|
| 300 |
+
"cell_type": "markdown",
|
| 301 |
+
"id": "74795bcc",
|
| 302 |
+
"metadata": {},
|
| 303 |
+
"source": [
|
| 304 |
+
"# Evaluation Metric: Union Targets and Union Test"
|
| 305 |
+
]
|
| 306 |
+
},
|
| 307 |
+
{
|
| 308 |
+
"cell_type": "code",
|
| 309 |
+
"execution_count": null,
|
| 310 |
+
"id": "e00c6a78",
|
| 311 |
+
"metadata": {},
|
| 312 |
+
"outputs": [],
|
| 313 |
+
"source": [
|
| 314 |
+
"from tqdm import tqdm\n",
|
| 315 |
+
"import custom_vlm_metrics as custom_vlm_metrics\n",
|
| 316 |
+
"import importlib\n",
|
| 317 |
+
"importlib.reload(custom_vlm_metrics)\n",
|
| 318 |
+
"\n",
|
| 319 |
+
"print(vlm_name)\n",
|
| 320 |
+
"print('*'*30)\n",
|
| 321 |
+
"\n",
|
| 322 |
+
"def string_operations(string):\n",
|
| 323 |
+
" import unicodedata\n",
|
| 324 |
+
" import re\n",
|
| 325 |
+
"\n",
|
| 326 |
+
" string = string.lower()\n",
|
| 327 |
+
" string = unicodedata.normalize('NFD', string)\n",
|
| 328 |
+
" string = ''.join(char for char in string if unicodedata.category(char) != 'Mn')\n",
|
| 329 |
+
" string = re.sub(r\"[']\", \"\", string)\n",
|
| 330 |
+
" \n",
|
| 331 |
+
" return string\n",
|
| 332 |
+
"\n",
|
| 333 |
+
"df_vlm = pd.read_parquet(os.path.join(path_to_vlm_results, file_vlm_results), engine='pyarrow')\n",
|
| 334 |
+
"df_vlm['different_types'] = df_vlm['different_types'].apply(lambda x: x if x == 'yes' else None)\n",
|
| 335 |
+
"\n",
|
| 336 |
+
"list_features = ['brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'product_weight', 'different_types']\n",
|
| 337 |
+
"df_custom_accuracy_total = pd.DataFrame(columns=df_vlm.columns)\n",
|
| 338 |
+
"df_custom_accuracy_total.drop('weight_number', axis=1, inplace=True)\n",
|
| 339 |
+
"df_custom_accuracy_total.drop('weight_unit', axis=1, inplace=True)\n",
|
| 340 |
+
"df_custom_accuracy_total['product_weight'] = None\n",
|
| 341 |
+
"df_custom_accuracy_total['label'] = df_vlm['label']\n",
|
| 342 |
+
"df_custom_accuracy_total['filename'] = df_vlm['filename']\n",
|
| 343 |
+
"\n",
|
| 344 |
+
"for i, f in enumerate(list_features):\n",
|
| 345 |
+
" print(f)\n",
|
| 346 |
+
"\n",
|
| 347 |
+
" for index, row in tqdm(df_vlm.iterrows(), total=len(df_vlm)):\n",
|
| 348 |
+
" if f == 'product_category' or f == 'GTINs':\n",
|
| 349 |
+
" df_custom_accuracy_total.at[index, f] = 0\n",
|
| 350 |
+
" continue\n",
|
| 351 |
+
"\n",
|
| 352 |
+
" if f != 'product_weight':\n",
|
| 353 |
+
" y_pred = row[f]\n",
|
| 354 |
+
" \n",
|
| 355 |
+
" y_true = df_test.iloc[index][f]\n",
|
| 356 |
+
"\n",
|
| 357 |
+
" if y_pred is None:\n",
|
| 358 |
+
" df_custom_accuracy_total.at[index, f] = 0\n",
|
| 359 |
+
" continue\n",
|
| 360 |
+
" \n",
|
| 361 |
+
" if f == 'brand':\n",
|
| 362 |
+
" df_custom_accuracy_total.at[index, f] = custom_vlm_metrics.brand_fuzzy_match(string_operations(y_pred), string_operations(y_true))\n",
|
| 363 |
+
" elif 'price' in f or 'discount' in f: \n",
|
| 364 |
+
" df_custom_accuracy_total.at[index, f] = custom_vlm_metrics.price_discount_fuzzy_match(f, y_pred.replace('-', ''), str(y_true))\n",
|
| 365 |
+
" elif f == 'different_types':\n",
|
| 366 |
+
" df_custom_accuracy_total.at[index, f] = custom_vlm_metrics.different_sorts_fuzzy_match(y_pred, str(y_true))\n",
|
| 367 |
+
" elif f == 'product_weight':\n",
|
| 368 |
+
" if row['weight_number'] is None or row['weight_unit'] is None:\n",
|
| 369 |
+
" df_custom_accuracy_total.at[index, f] = 0\n",
|
| 370 |
+
" continue\n",
|
| 371 |
+
"\n",
|
| 372 |
+
" y_pred = row['weight_number'] + ' ' + row['weight_unit']\n",
|
| 373 |
+
" weight_number = row['weight_number']\n",
|
| 374 |
+
"\n",
|
| 375 |
+
" df_custom_accuracy_total.at[index, f] = custom_vlm_metrics.product_weight_fuzzy_match(y_pred, y_true, weight_number)"
|
| 376 |
+
]
|
| 377 |
+
},
|
| 378 |
+
{
|
| 379 |
+
"cell_type": "code",
|
| 380 |
+
"execution_count": null,
|
| 381 |
+
"id": "e68e00e0",
|
| 382 |
+
"metadata": {},
|
| 383 |
+
"outputs": [],
|
| 384 |
+
"source": [
|
| 385 |
+
"df_custom_accuracy_total"
|
| 386 |
+
]
|
| 387 |
+
},
|
| 388 |
+
{
|
| 389 |
+
"cell_type": "code",
|
| 390 |
+
"execution_count": null,
|
| 391 |
+
"id": "bba22b33",
|
| 392 |
+
"metadata": {},
|
| 393 |
+
"outputs": [],
|
| 394 |
+
"source": [
|
| 395 |
+
"# uncomment the set of targets for which the evaluation should be done\n",
|
| 396 |
+
"\n",
|
| 397 |
+
"cols = ['brand']\n",
|
| 398 |
+
"# cols = ['brand', 'product_weight']\n",
|
| 399 |
+
"# cols = ['brand', 'product_weight', 'different_types']\n",
|
| 400 |
+
"# cols = ['brand', 'product_weight', 'different_types', 'price']\n",
|
| 401 |
+
"# cols = ['brand', 'product_weight', 'different_types', 'price', 'regular_price']\n",
|
| 402 |
+
"# cols = ['brand', 'product_weight', 'different_types', 'price', 'regular_price', 'relative_discount']\n",
|
| 403 |
+
"# cols = ['brand', 'product_weight', 'different_types', 'price', 'regular_price', 'relative_discount', 'absolute_discount']\n",
|
| 404 |
+
"\n",
|
| 405 |
+
"df_custom_accuracy_total.loc[(df_custom_accuracy_total[cols] == 1).all(axis=1)]"
|
| 406 |
+
]
|
| 407 |
+
},
|
| 408 |
+
{
|
| 409 |
+
"cell_type": "markdown",
|
| 410 |
+
"id": "4746ee13",
|
| 411 |
+
"metadata": {},
|
| 412 |
+
"source": [
|
| 413 |
+
"#### total custom accuracy regard to WHOLE test dataset"
|
| 414 |
+
]
|
| 415 |
+
},
|
| 416 |
+
{
|
| 417 |
+
"cell_type": "code",
|
| 418 |
+
"execution_count": null,
|
| 419 |
+
"id": "7ff13437",
|
| 420 |
+
"metadata": {},
|
| 421 |
+
"outputs": [],
|
| 422 |
+
"source": [
|
| 423 |
+
"tmp = df_custom_accuracy_total.loc[(df_custom_accuracy_total[cols] == 1).all(axis=1)]\n",
|
| 424 |
+
"len(tmp) / 36571 * 100"
|
| 425 |
+
]
|
| 426 |
+
},
|
| 427 |
+
{
|
| 428 |
+
"cell_type": "markdown",
|
| 429 |
+
"id": "f97c81f7",
|
| 430 |
+
"metadata": {},
|
| 431 |
+
"source": [
|
| 432 |
+
"#### total custom accuracy regard to VALID GT & PRED values"
|
| 433 |
+
]
|
| 434 |
+
},
|
| 435 |
+
{
|
| 436 |
+
"cell_type": "code",
|
| 437 |
+
"execution_count": null,
|
| 438 |
+
"id": "a0c54387",
|
| 439 |
+
"metadata": {},
|
| 440 |
+
"outputs": [],
|
| 441 |
+
"source": [
|
| 442 |
+
"df_vlm['product_weight'] = df_vlm['weight_number'].astype(str) + ' ' + df_vlm['weight_unit'].astype(str)\n",
|
| 443 |
+
"\n",
|
| 444 |
+
"tmp = df_custom_accuracy_total.loc[(df_custom_accuracy_total[cols] == 1).all(axis=1)]\n",
|
| 445 |
+
"\n",
|
| 446 |
+
"mask = df_test[cols].notna().all(axis=1) & df_vlm[cols].notna().all(axis=1)\n",
|
| 447 |
+
"length = int(mask.value_counts().get(True, 0))\n",
|
| 448 |
+
"\n",
|
| 449 |
+
"len(tmp) / length * 100"
|
| 450 |
+
]
|
| 451 |
+
},
|
| 452 |
+
{
|
| 453 |
+
"cell_type": "markdown",
|
| 454 |
+
"id": "1d20d7ce",
|
| 455 |
+
"metadata": {},
|
| 456 |
+
"source": [
|
| 457 |
+
"#### Create Boxplot for Price"
|
| 458 |
+
]
|
| 459 |
+
},
|
| 460 |
+
{
|
| 461 |
+
"cell_type": "code",
|
| 462 |
+
"execution_count": null,
|
| 463 |
+
"id": "0946956d",
|
| 464 |
+
"metadata": {},
|
| 465 |
+
"outputs": [],
|
| 466 |
+
"source": [
|
| 467 |
+
"import matplotlib.pyplot as plt\n",
|
| 468 |
+
"import os\n",
|
| 469 |
+
"import pandas as pd\n",
|
| 470 |
+
"\n",
|
| 471 |
+
"df_test = pd.read_parquet('./.../test.parquet', engine='pyarrow')\n",
|
| 472 |
+
"df_true = df_test.copy()\n",
|
| 473 |
+
"path_to_vlm_results = \"./.../vlm_results\"\n",
|
| 474 |
+
"\n",
|
| 475 |
+
"list_model = [\n",
|
| 476 |
+
" \"your-vlm-name\",\n",
|
| 477 |
+
"]\n",
|
| 478 |
+
"\n",
|
| 479 |
+
"list_features = ['price']\n",
|
| 480 |
+
"df_price_errors = pd.DataFrame()\n",
|
| 481 |
+
"for f in list_features:\n",
|
| 482 |
+
" for m in list_model:\n",
|
| 483 |
+
" df_vlm = pd.read_parquet(os.path.join(path_to_vlm_results, m + '_test.parquet'), engine='pyarrow')\n",
|
| 484 |
+
" mask = df_true[f].notna() & df_vlm[f].notna()\n",
|
| 485 |
+
" y_true_clean = df_true.loc[mask, f]\n",
|
| 486 |
+
" y_pred_clean = df_vlm.loc[mask, f].astype(float)\n",
|
| 487 |
+
" errors_y = y_true_clean - y_pred_clean\n",
|
| 488 |
+
" \n",
|
| 489 |
+
" # Create a DataFrame from errors_y with column named by model\n",
|
| 490 |
+
" df_model_errors = pd.DataFrame({m: errors_y})\n",
|
| 491 |
+
"\n",
|
| 492 |
+
" # Concatenate preserving indices, axis=1 will join columns side-by-side\n",
|
| 493 |
+
" df_price_errors = pd.concat([df_price_errors, df_model_errors], axis=1)"
|
| 494 |
+
]
|
| 495 |
+
},
|
| 496 |
+
{
|
| 497 |
+
"cell_type": "code",
|
| 498 |
+
"execution_count": null,
|
| 499 |
+
"id": "4ccb9de3",
|
| 500 |
+
"metadata": {},
|
| 501 |
+
"outputs": [],
|
| 502 |
+
"source": [
|
| 503 |
+
"import matplotlib.pyplot as plt\n",
|
| 504 |
+
"\n",
|
| 505 |
+
"########################################\n",
|
| 506 |
+
"plt.rcdefaults() # set default settings\n",
|
| 507 |
+
"plt.figure(figsize=(8, 5))\n",
|
| 508 |
+
"plt.rcParams.update({\n",
|
| 509 |
+
" \"text.usetex\": True, # Use LaTeX to render all text\n",
|
| 510 |
+
" \"font.family\": \"serif\", # Use serif font (matching typical LaTeX documents)\n",
|
| 511 |
+
" # \"text.latex.preamble\": r\"\\usepackage{lmodern}\"\n",
|
| 512 |
+
" \"font.size\": 12, # base font size for text\n",
|
| 513 |
+
" \"axes.titlesize\": 14, # title font size\n",
|
| 514 |
+
" \"axes.labelsize\": 13, # axis labels font size\n",
|
| 515 |
+
" \"xtick.labelsize\": 11, # x tick labels font size\n",
|
| 516 |
+
" \"ytick.labelsize\": 11, # y tick labels font size\n",
|
| 517 |
+
" \"legend.fontsize\": 12, # legend font size \n",
|
| 518 |
+
"})\n",
|
| 519 |
+
"from matplotlib.ticker import FuncFormatter, StrMethodFormatter\n",
|
| 520 |
+
"plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # comma as thousands separator\n",
|
| 521 |
+
"def format_with_commas(x, pos):\n",
|
| 522 |
+
" return f\"{x:,.2f}\"\n",
|
| 523 |
+
"plt.gca().xaxis.set_major_formatter(FuncFormatter(format_with_commas))\n",
|
| 524 |
+
"########################################\n",
|
| 525 |
+
"\n",
|
| 526 |
+
"# Simple boxplot for each column (model)\n",
|
| 527 |
+
"df_price_errors.boxplot()#rot=45)\n",
|
| 528 |
+
"\n",
|
| 529 |
+
"list_legend = [\n",
|
| 530 |
+
" \"your-vlm-name\",\n",
|
| 531 |
+
"]\n",
|
| 532 |
+
"\n",
|
| 533 |
+
"# Set custom x-axis tick labels\n",
|
| 534 |
+
"plt.xticks(ticks=range(1, len(list_legend)+1), labels=list_legend)\n",
|
| 535 |
+
"\n",
|
| 536 |
+
"plt.ylabel('Prediction Error (Currency EUR)')\n",
|
| 537 |
+
"plt.xlabel('Model')\n",
|
| 538 |
+
"\n",
|
| 539 |
+
"plt.savefig(\"filename.pdf\", bbox_inches='tight')\n",
|
| 540 |
+
"plt.show()"
|
| 541 |
+
]
|
| 542 |
+
},
|
| 543 |
+
{
|
| 544 |
+
"cell_type": "code",
|
| 545 |
+
"execution_count": null,
|
| 546 |
+
"id": "784dc391",
|
| 547 |
+
"metadata": {},
|
| 548 |
+
"outputs": [],
|
| 549 |
+
"source": [
|
| 550 |
+
"df_price_errors.median(numeric_only=True)"
|
| 551 |
+
]
|
| 552 |
+
}
|
| 553 |
+
],
|
| 554 |
+
"metadata": {
|
| 555 |
+
"kernelspec": {
|
| 556 |
+
"display_name": "Python 3 (ipykernel)",
|
| 557 |
+
"language": "python",
|
| 558 |
+
"name": "python3"
|
| 559 |
+
},
|
| 560 |
+
"language_info": {
|
| 561 |
+
"codemirror_mode": {
|
| 562 |
+
"name": "ipython",
|
| 563 |
+
"version": 3
|
| 564 |
+
},
|
| 565 |
+
"file_extension": ".py",
|
| 566 |
+
"mimetype": "text/x-python",
|
| 567 |
+
"name": "python",
|
| 568 |
+
"nbconvert_exporter": "python",
|
| 569 |
+
"pygments_lexer": "ipython3",
|
| 570 |
+
"version": "3.8.10"
|
| 571 |
+
}
|
| 572 |
+
},
|
| 573 |
+
"nbformat": 4,
|
| 574 |
+
"nbformat_minor": 5
|
| 575 |
+
}
|
code/vlm/run_vlm_commerical.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import io
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from PIL import Image
|
| 10 |
+
|
| 11 |
+
import use_vlm
|
| 12 |
+
|
| 13 |
+
######################################################################
|
| 14 |
+
######################################################################
|
| 15 |
+
|
| 16 |
+
def get_img_base64_str(image_path):
|
| 17 |
+
img = Image.open(image_path)
|
| 18 |
+
buffered = io.BytesIO()
|
| 19 |
+
img.save(buffered, format=img.format)
|
| 20 |
+
img_base64_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 21 |
+
return img_base64_str
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
###################################################################################################################################
|
| 25 |
+
###################################################################################################################################
|
| 26 |
+
###################################################################################################################################
|
| 27 |
+
if __name__ == '__main__':
|
| 28 |
+
in_key = "your-api-key"
|
| 29 |
+
in_model_name = "name-of-model-used"
|
| 30 |
+
|
| 31 |
+
in_path_frame_images = './.../rpp-765k_512'
|
| 32 |
+
in_file_data_entering_train = './.../train.parquet'
|
| 33 |
+
in_file_data_entering_test = './.../test.parquet'
|
| 34 |
+
|
| 35 |
+
in_name_results_output = 'results'
|
| 36 |
+
out_path_results = './.../output'
|
| 37 |
+
|
| 38 |
+
path_outputs = os.path.join(out_path_results, in_model_name)
|
| 39 |
+
os.makedirs(path_outputs, exist_ok=True)
|
| 40 |
+
|
| 41 |
+
dict_log = {}
|
| 42 |
+
dict_log['model'] = in_model_name
|
| 43 |
+
|
| 44 |
+
print("in_model_name: " + str(in_model_name))
|
| 45 |
+
|
| 46 |
+
#######################################################################
|
| 47 |
+
#######################################################################
|
| 48 |
+
df_result = pd.DataFrame(
|
| 49 |
+
columns=['label', 'filename', \
|
| 50 |
+
'brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'weight_number', 'weight_unit', 'different_types'])
|
| 51 |
+
df_result_cost = pd.DataFrame(
|
| 52 |
+
columns=['label', 'filename']
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
df_train = pd.read_parquet(in_file_data_entering_train, engine='pyarrow')
|
| 56 |
+
df_test = pd.read_parquet(in_file_data_entering_test, engine='pyarrow')
|
| 57 |
+
|
| 58 |
+
print(datetime.now().strftime("%Y%m%d_%H%M%S"))
|
| 59 |
+
|
| 60 |
+
start_index = 0
|
| 61 |
+
output_file = f'{datetime.now().strftime("%Y%m%d_%H%M%S")}_{in_name_results_output}'
|
| 62 |
+
for index, row in df_test.iloc[start_index:].iterrows():
|
| 63 |
+
|
| 64 |
+
vlm = use_vlm.get_openai_client(in_key, in_model_name)
|
| 65 |
+
if index == 0:
|
| 66 |
+
print(vlm)
|
| 67 |
+
|
| 68 |
+
label = str(row.label)
|
| 69 |
+
filename = row.filename
|
| 70 |
+
|
| 71 |
+
dict_result = {}
|
| 72 |
+
dict_result['label'] = label
|
| 73 |
+
dict_result['filename'] = filename
|
| 74 |
+
dict_result_cost = {}
|
| 75 |
+
dict_result_cost['label'] = label
|
| 76 |
+
dict_result_cost['filename'] = filename
|
| 77 |
+
|
| 78 |
+
print('index')
|
| 79 |
+
print(index)
|
| 80 |
+
print('filename')
|
| 81 |
+
print(filename)
|
| 82 |
+
print('*'*30)
|
| 83 |
+
|
| 84 |
+
############################################
|
| 85 |
+
# PROMPT
|
| 86 |
+
############################################
|
| 87 |
+
# IMAGE
|
| 88 |
+
image_path = os.path.join( in_path_frame_images, 'test', label, filename )
|
| 89 |
+
query_image_base64 = get_img_base64_str(image_path)
|
| 90 |
+
|
| 91 |
+
# TASK
|
| 92 |
+
task = "Extract all targets."
|
| 93 |
+
dict_log['prompt_task'] = task
|
| 94 |
+
|
| 95 |
+
dict_log, dict_result, dict_result_cost = use_vlm.do_request(
|
| 96 |
+
vlm,
|
| 97 |
+
query_image_base64,
|
| 98 |
+
task,
|
| 99 |
+
dict_log,
|
| 100 |
+
dict_result,
|
| 101 |
+
dict_result_cost,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
df_result = pd.concat( [ df_result, pd.DataFrame.from_dict([dict_result]) ], ignore_index=True)
|
| 105 |
+
df_result_cost = pd.concat( [ df_result_cost, pd.DataFrame.from_dict([dict_result_cost]) ], ignore_index=True)
|
| 106 |
+
|
| 107 |
+
if index%100 == 0:
|
| 108 |
+
df_result.to_parquet( os.path.join(path_outputs, output_file + '_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 109 |
+
df_result_cost.to_parquet( os.path.join(path_outputs, output_file + '_costs_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 110 |
+
|
| 111 |
+
df_result = pd.DataFrame( columns=['label', 'filename', \
|
| 112 |
+
'brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'weight_number', 'weight_unit', 'different_types'])
|
| 113 |
+
df_result_cost = pd.DataFrame(columns=['label', 'filename'])
|
| 114 |
+
time.sleep(60)
|
| 115 |
+
|
| 116 |
+
print('/'*30)
|
| 117 |
+
|
| 118 |
+
df_result.to_parquet( os.path.join(path_outputs, output_file + '_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 119 |
+
df_result_cost.to_parquet( os.path.join(path_outputs, output_file + '_costs_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 120 |
+
|
| 121 |
+
#######################################################################
|
| 122 |
+
#######################################################################
|
| 123 |
+
|
| 124 |
+
with open(os.path.join(path_outputs, in_name_results_output + '.json'), 'w') as json_file:
|
| 125 |
+
json.dump(dict_log, json_file)
|
code/vlm/run_vlm_ollama.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import io
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
import use_vlm_ollama
|
| 11 |
+
|
| 12 |
+
######################################################################
|
| 13 |
+
######################################################################
|
| 14 |
+
|
| 15 |
+
def get_img_base64_str(image_path):
|
| 16 |
+
img = Image.open(image_path)
|
| 17 |
+
buffered = io.BytesIO()
|
| 18 |
+
img.save(buffered, format=img.format)
|
| 19 |
+
img_base64_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 20 |
+
return img_base64_str
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
###################################################################################################################################
|
| 24 |
+
###################################################################################################################################
|
| 25 |
+
###################################################################################################################################
|
| 26 |
+
if __name__ == '__main__':
|
| 27 |
+
in_model_name = "your-model-name"
|
| 28 |
+
in_name_results_output_path = "results"
|
| 29 |
+
in_name_results_output = "results-of-your-model"
|
| 30 |
+
#######################################################################
|
| 31 |
+
|
| 32 |
+
in_path_frame_images = './.../rpp-765k_512'
|
| 33 |
+
in_file_data_entering_train = './.../train.parquet'
|
| 34 |
+
in_file_data_entering_test = './.../test.parquet'
|
| 35 |
+
out_path_results = './.../results/'
|
| 36 |
+
|
| 37 |
+
path_outputs = os.path.join(out_path_results, in_name_results_output_path)
|
| 38 |
+
os.makedirs(path_outputs, exist_ok=True)
|
| 39 |
+
|
| 40 |
+
dict_log = {}
|
| 41 |
+
dict_log['model'] = in_model_name
|
| 42 |
+
|
| 43 |
+
print("in_model_name: " + str(in_model_name))
|
| 44 |
+
|
| 45 |
+
ip_address = "your-ip-address"
|
| 46 |
+
#######################################################################
|
| 47 |
+
#######################################################################
|
| 48 |
+
|
| 49 |
+
df_result = pd.DataFrame(
|
| 50 |
+
columns=['label', 'filename', \
|
| 51 |
+
'brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'weight_number', 'weight_unit', 'different_types'])
|
| 52 |
+
df_result_cost = pd.DataFrame(columns=['label', 'filename'])
|
| 53 |
+
|
| 54 |
+
df_train = pd.read_parquet(in_file_data_entering_train, engine='pyarrow')
|
| 55 |
+
df_test = pd.read_parquet(in_file_data_entering_test, engine='pyarrow')
|
| 56 |
+
|
| 57 |
+
dict_log['start_time'] = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 58 |
+
|
| 59 |
+
start_index = 0
|
| 60 |
+
output_file = f'{datetime.now().strftime("%Y%m%d_%H%M%S")}_{in_name_results_output}'
|
| 61 |
+
for index, row in df_test.iloc[start_index:].iterrows():
|
| 62 |
+
label = str(row.label)
|
| 63 |
+
filename = row.filename
|
| 64 |
+
|
| 65 |
+
dict_result = {}
|
| 66 |
+
dict_result['label'] = label
|
| 67 |
+
dict_result['filename'] = filename
|
| 68 |
+
dict_result_cost = {}
|
| 69 |
+
dict_result_cost['label'] = label
|
| 70 |
+
dict_result_cost['filename'] = filename
|
| 71 |
+
|
| 72 |
+
############################################
|
| 73 |
+
# PROMPT
|
| 74 |
+
############################################
|
| 75 |
+
# IMAGE
|
| 76 |
+
image_path = os.path.join(in_path_frame_images, 'test', label, filename)
|
| 77 |
+
query_image_base64 = get_img_base64_str(image_path)
|
| 78 |
+
|
| 79 |
+
# TASK
|
| 80 |
+
task = "Extract all targets."
|
| 81 |
+
dict_log['prompt_task'] = task
|
| 82 |
+
|
| 83 |
+
dict_log, dict_result, dict_result_cost = use_vlm_ollama.do_request(
|
| 84 |
+
ip_address,
|
| 85 |
+
in_model_name,
|
| 86 |
+
query_image_base64,
|
| 87 |
+
task,
|
| 88 |
+
dict_log,
|
| 89 |
+
dict_result,
|
| 90 |
+
dict_result_cost,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
df_result = pd.concat( [ df_result, pd.DataFrame.from_dict([dict_result]) ], ignore_index=True)
|
| 94 |
+
df_result_cost = pd.concat( [ df_result_cost, pd.DataFrame.from_dict([dict_result_cost]) ], ignore_index=True)
|
| 95 |
+
|
| 96 |
+
if index%100 == 0:
|
| 97 |
+
df_result.to_parquet( os.path.join(path_outputs, output_file + '_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 98 |
+
df_result_cost.to_parquet( os.path.join(path_outputs, output_file + '_costs_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 99 |
+
|
| 100 |
+
df_result = pd.DataFrame( columns=['label', 'filename', \
|
| 101 |
+
'brand', 'product_category', 'price', 'regular_price', 'relative_discount', 'absolute_discount', 'GTINs', 'weight_number', 'weight_unit', 'different_types'])
|
| 102 |
+
df_result_cost = pd.DataFrame(columns=['label', 'filename'])
|
| 103 |
+
|
| 104 |
+
df_result.to_parquet( os.path.join(path_outputs, output_file + '_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 105 |
+
df_result_cost.to_parquet( os.path.join(path_outputs, output_file + '_costs_' + str(index) + '.parquet'), index=False, engine='pyarrow')
|
| 106 |
+
|
| 107 |
+
#######################################################################
|
| 108 |
+
#######################################################################
|
| 109 |
+
|
| 110 |
+
dict_log['end_time'] = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 111 |
+
|
| 112 |
+
with open(os.path.join(path_outputs, in_name_results_output + '.json'), 'w') as json_file:
|
| 113 |
+
json.dump(dict_log, json_file)
|
code/vlm/use_vlm.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import httpx
|
| 2 |
+
import os
|
| 3 |
+
import requests
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import langchain_google_genai
|
| 7 |
+
import langchain_openai
|
| 8 |
+
import openai
|
| 9 |
+
from langchain_core.messages import HumanMessage, SystemMessage
|
| 10 |
+
|
| 11 |
+
from enum import Enum
|
| 12 |
+
from pydantic import BaseModel, Field
|
| 13 |
+
from typing_extensions import List
|
| 14 |
+
from typing import Literal
|
| 15 |
+
|
| 16 |
+
from requests.exceptions import ConnectionError
|
| 17 |
+
|
| 18 |
+
VLM_TEMPERATURE = 0
|
| 19 |
+
######################################################################
|
| 20 |
+
######################################################################
|
| 21 |
+
|
| 22 |
+
class WeightUnit(Enum):
|
| 23 |
+
GRAMM = "Gramm"
|
| 24 |
+
KILOGRAM = "Kilogramm"
|
| 25 |
+
MILLILITER = "Milliliter"
|
| 26 |
+
LITER = "Liter"
|
| 27 |
+
WASCHLADUNGEN = "Waschladungen"
|
| 28 |
+
BLATT = "Blatt"
|
| 29 |
+
STUECK = "Stück"
|
| 30 |
+
|
| 31 |
+
class YesNo(Enum):
|
| 32 |
+
YES = "yes"
|
| 33 |
+
NO = "no"
|
| 34 |
+
|
| 35 |
+
class product_promotion_data(BaseModel):
|
| 36 |
+
"""Collection of product and promotion data of an product advertisement."""
|
| 37 |
+
brand: str = Field(description="The brand associated with the product")
|
| 38 |
+
product_category: List[str] = Field(description="List of categories associated with the product.")
|
| 39 |
+
price: float = Field(description="The promotional price.")
|
| 40 |
+
regular_price: float = Field(default=None, description="The regular price of the promotion.")
|
| 41 |
+
relative_discount: int = Field(default=None, description="The relative discount of the promotion.")
|
| 42 |
+
absolute_discount: float = Field(default=None, description="The absolute discount of the promotion.")
|
| 43 |
+
GTINs: List[str] = Field(description="List of the GTINs for the products.")
|
| 44 |
+
weight_number: float = Field(description="Only the numerical weight specication.")
|
| 45 |
+
weight_unit: WeightUnit = Field(description="Only the weight unit.")
|
| 46 |
+
# weight_unit: Literal["Gramm", "Kilogramm", "Milliliter", "Liter", "Waschladungen", "Blatt", "Stück"] = Field(description="Only the weight unit.")
|
| 47 |
+
different_types: YesNo = Field(description="If promotion offer different sorts.")
|
| 48 |
+
# different_types: Literal["yes", "no"] = Field(description="If promotion offer different sorts.")
|
| 49 |
+
|
| 50 |
+
######################################################################
|
| 51 |
+
######################################################################
|
| 52 |
+
|
| 53 |
+
def convert_items_to_strings(prediction):
|
| 54 |
+
if isinstance(prediction, str):
|
| 55 |
+
return prediction
|
| 56 |
+
elif isinstance(prediction, list):
|
| 57 |
+
return ', '.join(prediction)
|
| 58 |
+
else:
|
| 59 |
+
return str(prediction)
|
| 60 |
+
|
| 61 |
+
def get_output_results(dict_output, dict_result):
|
| 62 |
+
for key, value in dict_output.items():
|
| 63 |
+
if key == 'brand':
|
| 64 |
+
dict_result['brand'] = convert_items_to_strings(dict_output['brand'])
|
| 65 |
+
elif key == 'product_category':
|
| 66 |
+
dict_result['product_category'] = convert_items_to_strings(dict_output['product_category'])
|
| 67 |
+
elif key == 'price':
|
| 68 |
+
dict_result['price'] = convert_items_to_strings(dict_output['price'])
|
| 69 |
+
elif key == 'regular_price':
|
| 70 |
+
dict_result['regular_price'] = convert_items_to_strings(dict_output['regular_price'])
|
| 71 |
+
elif key == 'relative_discount':
|
| 72 |
+
dict_result['relative_discount'] = convert_items_to_strings(dict_output['relative_discount'])
|
| 73 |
+
elif key == 'absolute_discount':
|
| 74 |
+
dict_result['absolute_discount'] = convert_items_to_strings(dict_output['absolute_discount'])
|
| 75 |
+
elif key == 'GTINs':
|
| 76 |
+
dict_result['GTINs'] = convert_items_to_strings(dict_output['GTINs'])
|
| 77 |
+
elif key == 'weight_number':
|
| 78 |
+
dict_result['weight_number'] = convert_items_to_strings(dict_output['weight_number'])
|
| 79 |
+
elif key == 'weight_unit':
|
| 80 |
+
dict_result['weight_unit'] = convert_items_to_strings(dict_output['weight_unit'])
|
| 81 |
+
elif key == 'different_types':
|
| 82 |
+
dict_result['different_types'] = convert_items_to_strings(dict_output['different_types'])
|
| 83 |
+
return dict_result
|
| 84 |
+
|
| 85 |
+
def get_openai_client(key, model_name):
|
| 86 |
+
# usage OpenAI
|
| 87 |
+
client = langchain_openai.ChatOpenAI(
|
| 88 |
+
api_key = key,
|
| 89 |
+
model = model_name,
|
| 90 |
+
temperature = VLM_TEMPERATURE,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
# usage Google
|
| 94 |
+
# client = langchain_google_genai.ChatGoogleGenerativeAI(
|
| 95 |
+
# api_key = key,
|
| 96 |
+
# model = model_name,
|
| 97 |
+
# temperature = VLM_TEMPERATURE,
|
| 98 |
+
# )
|
| 99 |
+
|
| 100 |
+
print(client)
|
| 101 |
+
client = client.with_structured_output(product_promotion_data, include_raw=True)
|
| 102 |
+
os.environ["GOOGLE_USED_MODEL"] = model_name
|
| 103 |
+
return client
|
| 104 |
+
|
| 105 |
+
def prompt(query_image, task, dict_log):
|
| 106 |
+
system_message = "You are an assistant for question-answering tasks."
|
| 107 |
+
dict_log['system_message'] = system_message
|
| 108 |
+
|
| 109 |
+
human_message_text = "Do the user-provided task on the input image. \
|
| 110 |
+
The answer must be provided in JSON format. \
|
| 111 |
+
The task is: " + task + ".\
|
| 112 |
+
If there is no information of a target, return NaN."
|
| 113 |
+
dict_log['human_message_text'] = human_message_text
|
| 114 |
+
|
| 115 |
+
human_messages = [
|
| 116 |
+
{
|
| 117 |
+
"type": "text",
|
| 118 |
+
"text": human_message_text
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"type": "image_url",
|
| 122 |
+
"image_url": {"url": f"data:image/jpeg;base64,{query_image}"},
|
| 123 |
+
},
|
| 124 |
+
]
|
| 125 |
+
return dict_log, [SystemMessage(content=system_message), HumanMessage(content=human_messages)]
|
| 126 |
+
|
| 127 |
+
def do_request(client, query_image_base64, task, dict_log, dict_result, dict_result_cost):
|
| 128 |
+
dict_log, messages = prompt(query_image_base64, task, dict_log)
|
| 129 |
+
|
| 130 |
+
try:
|
| 131 |
+
start_time = time.time()
|
| 132 |
+
while True:
|
| 133 |
+
try:
|
| 134 |
+
response = client.invoke(messages)
|
| 135 |
+
except:
|
| 136 |
+
print("FAILED")
|
| 137 |
+
continue
|
| 138 |
+
break
|
| 139 |
+
elapsed_time = time.time() - start_time
|
| 140 |
+
dict_result_cost['elapsed_time_[s]'] = float("{:.2f}".format(elapsed_time))
|
| 141 |
+
|
| 142 |
+
if response['parsed']:
|
| 143 |
+
dict_result = get_output_results(response['parsed'].dict(), dict_result)
|
| 144 |
+
dict_result_cost = token_price_evaluation(response['raw'], dict_result_cost)
|
| 145 |
+
|
| 146 |
+
except openai.BadRequestError as e:
|
| 147 |
+
print(f"BadRequestError: {e}")
|
| 148 |
+
return dict_log, dict_result, dict_result_cost
|
| 149 |
+
except openai.ContentFilterFinishReasonError as e:
|
| 150 |
+
print(f"ContentFilterFinishReasonError: {e}")
|
| 151 |
+
return dict_log, dict_result, dict_result_cost
|
| 152 |
+
except ConnectionError as e:
|
| 153 |
+
print(f"Connection error occurred: {e}")
|
| 154 |
+
return dict_log, dict_result, dict_result_cost
|
| 155 |
+
except requests.exceptions.RequestException as e:
|
| 156 |
+
print(f"An error occurred: {e}")
|
| 157 |
+
return dict_log, dict_result, dict_result_cost
|
| 158 |
+
except ValueError as ve:
|
| 159 |
+
print(f"Validation error: {ve}")
|
| 160 |
+
return dict_log, dict_result, dict_result_cost
|
| 161 |
+
except httpx.HTTPStatusError as e:
|
| 162 |
+
print(f"HTTPStatusError: {e}")
|
| 163 |
+
time.sleep(60)
|
| 164 |
+
return dict_log, dict_result, dict_result_cost
|
| 165 |
+
except openai.RateLimitError as e:
|
| 166 |
+
print(f"RateLimitError: {e}")
|
| 167 |
+
time.sleep(60)
|
| 168 |
+
return dict_log, dict_result, dict_result_cost
|
| 169 |
+
except openai.InternalServerError as e:
|
| 170 |
+
print(f"InternalServerError: {e}")
|
| 171 |
+
time.sleep(60)
|
| 172 |
+
return dict_log, dict_result, dict_result_cost
|
| 173 |
+
|
| 174 |
+
return dict_log, dict_result, dict_result_cost
|
| 175 |
+
|
| 176 |
+
# https://ai.google.dev/gemini-api/docs/pricing
|
| 177 |
+
# https://azure.microsoft.com/en-us/pricing/details/cognitive-services/openai-service/
|
| 178 |
+
def token_price_evaluation(response, dict_result_cost):
|
| 179 |
+
PRICING = {
|
| 180 |
+
"gpt-4-0-mini": {"input": 0.165 / 1000000, "output": 0.66 / 1000000},
|
| 181 |
+
"gemini-2.0-flash": {"input": 0.10 / 1000000, "output": 0.40 / 1000000},
|
| 182 |
+
"gemini-2.5-flash": {"input": 0.30 / 1000000, "output": 2.50 / 1000000},
|
| 183 |
+
}
|
| 184 |
+
MODEL = os.environ["GOOGLE_USED_MODEL"]
|
| 185 |
+
|
| 186 |
+
# usage OpenAI
|
| 187 |
+
token_usage = response.response_metadata.get("token_usage", {})
|
| 188 |
+
input_tokens = token_usage.get("prompt_tokens", 0)
|
| 189 |
+
output_tokens = token_usage.get("completion_tokens", 0)
|
| 190 |
+
total_tokens = token_usage.get("total_tokens", input_tokens + output_tokens)
|
| 191 |
+
|
| 192 |
+
# usage Google
|
| 193 |
+
# token_usage = response.usage_metadata
|
| 194 |
+
# input_tokens = token_usage.get("input_tokens", 0)
|
| 195 |
+
# output_tokens = token_usage.get("output_tokens", 0)
|
| 196 |
+
# reasoning_tokens= token_usage.get("output_token_details", {}).get("reasoning", 0)
|
| 197 |
+
# total_tokens = token_usage.get("total_tokens", input_tokens + output_tokens)
|
| 198 |
+
|
| 199 |
+
input_cost = input_tokens * PRICING[MODEL]["input"]
|
| 200 |
+
output_cost = output_tokens * PRICING[MODEL]["output"]
|
| 201 |
+
total_cost = input_cost + output_cost
|
| 202 |
+
|
| 203 |
+
print(f"Model Used: {MODEL}")
|
| 204 |
+
print(f"Input Tokens: {input_tokens}, Cost: ${input_cost:.4f}")
|
| 205 |
+
print(f"Output Tokens: {output_tokens}, Cost: ${output_cost:.4f}")
|
| 206 |
+
# print(f"Reasoning Tokens: {reasoning_tokens}")
|
| 207 |
+
print(f"Total Tokens: {total_tokens}")
|
| 208 |
+
print(f"Total Cost: ${total_cost:.4f}")
|
| 209 |
+
print('*'*30)
|
| 210 |
+
|
| 211 |
+
dict_result_cost['input_tokens'] = input_tokens
|
| 212 |
+
dict_result_cost['output_tokens'] = output_tokens
|
| 213 |
+
# dict_result_cost['reasoning_tokens'] = reasoning_tokens
|
| 214 |
+
dict_result_cost['total_tokens'] = total_tokens
|
| 215 |
+
dict_result_cost['total_cost'] = float(total_cost)
|
| 216 |
+
|
| 217 |
+
return dict_result_cost
|
code/vlm/use_vlm_ollama.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import httpx
|
| 2 |
+
import json
|
| 3 |
+
import requests
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
from enum import Enum
|
| 7 |
+
from pydantic import BaseModel, Field
|
| 8 |
+
from typing_extensions import List
|
| 9 |
+
from typing import Literal
|
| 10 |
+
|
| 11 |
+
from requests.exceptions import ConnectionError
|
| 12 |
+
|
| 13 |
+
VLM_TEMPERATURE = 0
|
| 14 |
+
######################################################################
|
| 15 |
+
######################################################################
|
| 16 |
+
|
| 17 |
+
class WeightUnit(Enum):
|
| 18 |
+
GRAMM = "Gramm"
|
| 19 |
+
KILOGRAM = "Kilogramm"
|
| 20 |
+
MILLILITER = "Milliliter"
|
| 21 |
+
LITER = "Liter"
|
| 22 |
+
WASCHLADUNGEN = "Waschladungen"
|
| 23 |
+
BLATT = "Blatt"
|
| 24 |
+
STUECK = "Stück"
|
| 25 |
+
|
| 26 |
+
class YesNo(Enum):
|
| 27 |
+
YES = "yes"
|
| 28 |
+
NO = "no"
|
| 29 |
+
|
| 30 |
+
class product_promotion_data(BaseModel):
|
| 31 |
+
"""Collection of product and promotion data of an product advertisement."""
|
| 32 |
+
brand: str = Field(description="The brand associated with the product")
|
| 33 |
+
product_category: List[str] = Field(description="List of categories associated with the product.")
|
| 34 |
+
price: float = Field(description="The promotional price.")
|
| 35 |
+
regular_price: float = Field(default=None, description="The regular price of the promotion.")
|
| 36 |
+
relative_discount: int = Field(default=None, description="The relative discount of the promotion.")
|
| 37 |
+
absolute_discount: float = Field(default=None, description="The absolute discount of the promotion.")
|
| 38 |
+
GTINs: List[str] = Field(description="List of the GTINs for the products.")
|
| 39 |
+
# weight_number: float = Field(description="Only the numerical weight specication.")
|
| 40 |
+
weight_unit: WeightUnit = Field(description="Only the weight unit.")
|
| 41 |
+
# weight_unit: Literal["Gramm", "Kilogramm", "Milliliter", "Liter", "Waschladungen", "Blatt", "Stück"] = Field(description="Only the weight unit.")
|
| 42 |
+
different_types: YesNo = Field(description="If promotion offer different sorts.")
|
| 43 |
+
# different_types: Literal["yes", "no"] = Field(description="If promotion offer different sorts.")
|
| 44 |
+
|
| 45 |
+
######################################################################
|
| 46 |
+
######################################################################
|
| 47 |
+
|
| 48 |
+
def convert_items_to_strings(prediction):
|
| 49 |
+
if isinstance(prediction, str):
|
| 50 |
+
return prediction
|
| 51 |
+
elif isinstance(prediction, list):
|
| 52 |
+
return ', '.join(prediction)
|
| 53 |
+
else:
|
| 54 |
+
return str(prediction)
|
| 55 |
+
|
| 56 |
+
def get_output_results(dict_output, dict_result):
|
| 57 |
+
for key, value in dict_output.items():
|
| 58 |
+
if key == 'brand':
|
| 59 |
+
dict_result['brand'] = convert_items_to_strings(dict_output['brand'])
|
| 60 |
+
elif key == 'product_category':
|
| 61 |
+
dict_result['product_category'] = convert_items_to_strings(dict_output['product_category'])
|
| 62 |
+
elif key == 'price':
|
| 63 |
+
dict_result['price'] = convert_items_to_strings(dict_output['price'])
|
| 64 |
+
elif key == 'regular_price':
|
| 65 |
+
dict_result['regular_price'] = convert_items_to_strings(dict_output['regular_price'])
|
| 66 |
+
elif key == 'relative_discount':
|
| 67 |
+
dict_result['relative_discount'] = convert_items_to_strings(dict_output['relative_discount'])
|
| 68 |
+
elif key == 'absolute_discount':
|
| 69 |
+
dict_result['absolute_discount'] = convert_items_to_strings(dict_output['absolute_discount'])
|
| 70 |
+
elif key == 'GTINs':
|
| 71 |
+
dict_result['GTINs'] = convert_items_to_strings(dict_output['GTINs'])
|
| 72 |
+
elif key == 'weight_number':
|
| 73 |
+
dict_result['weight_number'] = convert_items_to_strings(dict_output['weight_number'])
|
| 74 |
+
elif key == 'weight_unit':
|
| 75 |
+
dict_result['weight_unit'] = convert_items_to_strings(dict_output['weight_unit'])
|
| 76 |
+
elif key == 'different_types':
|
| 77 |
+
dict_result['different_types'] = convert_items_to_strings(dict_output['different_types'])
|
| 78 |
+
return dict_result
|
| 79 |
+
|
| 80 |
+
def do_request(ip_address, in_model_name, query_image_base64, task, dict_log, dict_result, dict_result_cost):
|
| 81 |
+
system_message = "You are an assistant for question-answering tasks."
|
| 82 |
+
human_message_text = "Do the user-provided task on the input image. \
|
| 83 |
+
The answer must be provided in JSON format. \
|
| 84 |
+
The task is: " + task + ".\
|
| 85 |
+
If there is no information of a target, return NaN."
|
| 86 |
+
|
| 87 |
+
dict_log['system_message'] = system_message
|
| 88 |
+
dict_log['human_message_text'] = human_message_text
|
| 89 |
+
|
| 90 |
+
try:
|
| 91 |
+
start_time = time.time()
|
| 92 |
+
response = requests.post(
|
| 93 |
+
"requests-url",
|
| 94 |
+
json={
|
| 95 |
+
"model": in_model_name,
|
| 96 |
+
"prompt": human_message_text,
|
| 97 |
+
"system": system_message,
|
| 98 |
+
"stream": False,
|
| 99 |
+
"images": [query_image_base64],
|
| 100 |
+
"options": {
|
| 101 |
+
"temperature": VLM_TEMPERATURE
|
| 102 |
+
},
|
| 103 |
+
"format": product_promotion_data.model_json_schema()
|
| 104 |
+
},
|
| 105 |
+
timeout=60
|
| 106 |
+
)
|
| 107 |
+
print(response)
|
| 108 |
+
elapsed_time = time.time() - start_time
|
| 109 |
+
dict_result_cost['elapsed_time_[s]'] = float("{:.2f}".format(elapsed_time))
|
| 110 |
+
|
| 111 |
+
parsed = json.loads(response.text)
|
| 112 |
+
print(parsed['response'])
|
| 113 |
+
|
| 114 |
+
if parsed['response']:
|
| 115 |
+
dict_result = get_output_results(json.loads(parsed['response']), dict_result)
|
| 116 |
+
print('dict_result')
|
| 117 |
+
print(dict_result)
|
| 118 |
+
|
| 119 |
+
except requests.exceptions.RequestException as e:
|
| 120 |
+
print(f"Request failed: {e}")
|
| 121 |
+
return dict_log, dict_result, dict_result_cost
|
| 122 |
+
except requests.Timeout as e:
|
| 123 |
+
print(f"Request failed: {e}")
|
| 124 |
+
return dict_log, dict_result, dict_result_cost
|
| 125 |
+
except ValueError as ve:
|
| 126 |
+
print(f"Validation error: {ve}")
|
| 127 |
+
return dict_log, dict_result, dict_result_cost
|
| 128 |
+
except httpx.HTTPStatusError as e:
|
| 129 |
+
print(f"HTTPStatusError: {e}")
|
| 130 |
+
time.sleep(60)
|
| 131 |
+
return dict_log, dict_result, dict_result_cost
|
| 132 |
+
except KeyError as e:
|
| 133 |
+
print(f"Key error: {e}")
|
| 134 |
+
return dict_log, dict_result, dict_result_cost
|
| 135 |
+
except ConnectionError as e:
|
| 136 |
+
print(f"Connection error occurred: {e}")
|
| 137 |
+
return dict_log, dict_result, dict_result_cost
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
return dict_log, dict_result, dict_result_cost
|