File size: 1,234 Bytes
8d37eb3
 
 
38a9e38
 
 
 
 
 
 
8d37eb3
 
 
 
 
34ead5f
8d37eb3
 
 
 
 
 
38a9e38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from PIL import Image
from io import BytesIO
import base64
import streamlit as st


UNIT_COST = {
    "user": 0.01,
    "assistant": 0.03,
}


# Convert Image to Base64 
def im_2_b64(image):
    image = Image.open(image)
    image.thumbnail((512, 512), Image.Resampling.LANCZOS)
    image = image.convert("RGB")
    buff = BytesIO()
    image.save(buff, format="JPEG")
    img_str = base64.b64encode(buff.getvalue())
    return img_str


def calculate_cost():
    def get_text_cost(text, unit_cost):
        num_of_words = len(text.split(" "))
        tokens = max(1000.0 * num_of_words / 750.0, 0.0)
        tokens = tokens / 1000.0
        cost = tokens * unit_cost
        return cost
    def get_image_cost(unit_cost=0.01):
        cost = 0.00255 # 512x512 image: https://openai.com/pricing
        return cost

    messages = st.session_state.messages
    total_cost = 0
    for message in messages:
        role = message["role"]
        for content in message["content"]:
            if content["type"] == "image_url":
                total_cost += get_image_cost(UNIT_COST[role])
            else:
                total_cost += get_text_cost(content["text"], UNIT_COST[role])
    
    st.session_state.cost.append(total_cost)