mSOP-765k / code /fine_tuning /use_vlm_ft_OpenAI.py
retail-product-promotion's picture
code of experiments
ff1b346 verified
import httpx
import json
import os
import requests
import subprocess
import time
import openai
from enum import Enum
from pydantic import BaseModel, Field
from typing_extensions import List
from typing import Literal, Optional
from requests.exceptions import ConnectionError
VLM_TEMPERATURE = 0
######################################################################
######################################################################
class WeightUnit(Enum):
GRAMM = "Gramm"
KILOGRAM = "Kilogramm"
MILLILITER = "Milliliter"
LITER = "Liter"
WASCHLADUNGEN = "Waschladungen"
BLATT = "Blatt"
STUECK = "Stück"
class YesNo(Enum):
YES = "yes"
NO = "no"
class product_promotion_data(BaseModel):
"""Collection of product and promotion data of an product advertisement."""
brand: str = Field(description="The brand associated with the product")
product_category: List[str] = Field(description="List of categories associated with the product.")
price: float = Field(description="The promotional price.")
regular_price: Optional[float] = Field(default=None, description="The regular price of the promotion.")
relative_discount: Optional[int] = Field(default=None, description="The relative discount of the promotion.")
absolute_discount: Optional[float] = Field(default=None, description="The absolute discount of the promotion.")
GTINs: List[str] = Field(description="List of the GTINs for the products.")
weight_number: float = Field(description="Only the numerical weight specication.")
# weight_unit: WeightUnit = Field(description="Only the weight unit.")
weight_unit: Literal["Gramm", "Kilogramm", "Milliliter", "Liter", "Waschladungen", "Blatt", "Stück"] = Field(description="Only the weight unit.")
# different_types: YesNo = Field(description="If promotion offer different sorts.")
different_types: Literal["yes", "no"] = Field(description="If promotion offer different sorts.")
######################################################################
######################################################################
def convert_items_to_strings(prediction):
if isinstance(prediction, str):
return prediction
elif isinstance(prediction, list):
return ', '.join(prediction)
else:
return str(prediction)
def get_output_results(dict_output, dict_result):
for key, value in dict_output.items():
if key == 'brand':
dict_result['brand'] = convert_items_to_strings(dict_output['brand'])
elif key == 'product_category':
dict_result['product_category'] = convert_items_to_strings(dict_output['product_category'])
elif key == 'price':
dict_result['price'] = convert_items_to_strings(dict_output['price'])
elif key == 'regular_price':
dict_result['regular_price'] = convert_items_to_strings(dict_output['regular_price'])
elif key == 'relative_discount':
dict_result['relative_discount'] = convert_items_to_strings(dict_output['relative_discount'])
elif key == 'absolute_discount':
dict_result['absolute_discount'] = convert_items_to_strings(dict_output['absolute_discount'])
elif key == 'GTINs':
dict_result['GTINs'] = convert_items_to_strings(dict_output['GTINs'])
elif key == 'weight_number':
dict_result['weight_number'] = convert_items_to_strings(dict_output['weight_number'])
elif key == 'weight_unit':
dict_result['weight_unit'] = convert_items_to_strings(dict_output['weight_unit'])
elif key == 'different_types':
dict_result['different_types'] = convert_items_to_strings(dict_output['different_types'])
return dict_result
def prompt(query_image, task, dict_log):
system_message = "You are an assistant for question-answering tasks."
dict_log['system_message'] = system_message
human_message_text = "Do the user-provided task on the input image. \
The answer must be provided in JSON format. \
The task is: " + task + ".\
If there is no information of a target, return NaN."
dict_log['human_message_text'] = human_message_text
human_messages = [
{
"type": "input_text",
"text": human_message_text
},
{
"type": "input_image",
"image_url": f"data:image/jpeg;base64,{query_image}",
},
]
input_messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": human_messages}
]
return dict_log, input_messages
def get_response_format():
schema = product_promotion_data.model_json_schema()
schema['type'] = 'object'
schema['additionalProperties'] = False
schema['required'] = list(schema.get('properties', {}).keys())
return {
"type": "json_schema",
"name": "product_promotion_data",
"schema": schema
}
def do_request(api_key, ft_model, query_image_base64, task, dict_log, dict_result, dict_result_cost):
dict_log, messages = prompt(query_image_base64, task, dict_log)
response_format = get_response_format()
try:
start_time = time.time()
while True:
try:
payload = {
"model": ft_model,
"input": messages,
"text": {
"format": response_format
}
}
payload_json = json.dumps(payload)
curl_cmd = [
"curl",
f"https://api.openai.com/v1/responses",
"-H", "Content-Type: application/json",
"-H", f"Authorization: Bearer {api_key}",
"-d", payload_json,
"--max-time", "60" # timeout in seconds
]
result = subprocess.run(curl_cmd, capture_output=True, text=True)
except:
print("FAILED")
continue
break
elapsed_time = time.time() - start_time
dict_result_cost['elapsed_time_[s]'] = float("{:.2f}".format(elapsed_time))
raw = result.stdout
response = json.loads(raw)
if response['output'][0]['content'][0]['text']:
dict_result = get_output_results(json.loads(response['output'][0]['content'][0]['text']), dict_result)
print('dict_result')
print(dict_result)
print(response['usage'])
dict_result_cost = token_price_evaluation(response['usage'], dict_result_cost)
except (KeyError, IndexError) as e:
print(f"Key or index missing: {e}")
return dict_log, dict_result, dict_result_cost
except openai.BadRequestError as e:
print(f"BadRequestError: {e}")
return dict_log, dict_result, dict_result_cost
except openai.ContentFilterFinishReasonError as e:
print(f"ContentFilterFinishReasonError: {e}")
return dict_log, dict_result, dict_result_cost
except ConnectionError as e:
print(f"Connection error occurred: {e}")
return dict_log, dict_result, dict_result_cost
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
return dict_log, dict_result, dict_result_cost
except ValueError as ve:
print(f"Validation error: {ve}")
return dict_log, dict_result, dict_result_cost
except httpx.HTTPStatusError as e:
print(f"HTTPStatusError: {e}")
time.sleep(60)
return dict_log, dict_result, dict_result_cost
except openai.RateLimitError as e:
print(f"RateLimitError: {e}")
time.sleep(60)
return dict_log, dict_result, dict_result_cost
except openai.InternalServerError as e:
print(f"InternalServerError: {e}")
time.sleep(60)
return dict_log, dict_result, dict_result_cost
return dict_log, dict_result, dict_result_cost
# https://ai.google.dev/gemini-api/docs/pricing
def token_price_evaluation(response, dict_result_cost):
PRICING = {
"gpt-5-mini": {"input": 0.25 / 1000000, "output": 2.00 / 1000000},
"gpt-5": {"input": 1.25 / 1000000, "output": 10.00 / 1000000},
"gpt-4o-2024-08-06": {"input": 2.50 / 1000000, "output": 10.00 / 1000000},
}
MODEL = os.environ["USED_MODEL"]
# OpenAI payload
input_tokens = response['input_tokens']
output_tokens = response['output_tokens']
total_tokens = response['total_tokens']
input_cost = input_tokens * PRICING[MODEL]["input"]
output_cost = output_tokens * PRICING[MODEL]["output"]
total_cost = input_cost + output_cost
print(f"Model Used: {MODEL}")
print(f"Input Tokens: {input_tokens}, Cost: ${input_cost:.4f}")
print(f"Output Tokens: {output_tokens}, Cost: ${output_cost:.4f}")
print(f"Total Tokens: {total_tokens}")
print(f"Total Cost: ${total_cost:.4f}")
print('*'*30)
dict_result_cost['input_tokens'] = input_tokens
dict_result_cost['output_tokens'] = output_tokens
dict_result_cost['total_tokens'] = total_tokens
dict_result_cost['total_cost'] = float(total_cost)
return dict_result_cost