ajay1710 commited on
Commit
905dde8
·
verified ·
1 Parent(s): 1f80b02

Upload folder using huggingface_hub

Browse files
Files changed (6) hide show
  1. .gitattributes +35 -35
  2. README.md +14 -12
  3. __pycache__/app.cpython-310.pyc +0 -0
  4. app.py +315 -0
  5. model_prices.json +0 -0
  6. requirements.txt +3 -0
.gitattributes CHANGED
@@ -1,35 +1,35 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,12 +1,14 @@
1
- ---
2
- title: Text To Dollars
3
- emoji: 🦀
4
- colorFrom: red
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 4.44.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
1
+ ---
2
+ title: Text-To-Dollars
3
+ emoji: 💰
4
+ colorFrom: yellow
5
+ colorTo: red
6
+ sdk: gradio
7
+ sdk_version: 4.43.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ short_description: Get the price for any API LLM call.
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
__pycache__/app.cpython-310.pyc ADDED
Binary file (8.84 kB). View file
 
app.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import requests
4
+ import json
5
+ import tiktoken
6
+ import matplotlib.pyplot as plt
7
+
8
+ # Constants
9
+ USD_TO_INR = 84
10
+ PRICES_URL = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"
11
+
12
+ # Fetch and process token costs
13
+ try:
14
+ response = requests.get(PRICES_URL)
15
+ if response.status_code == 200:
16
+ TOKEN_COSTS = response.json()
17
+ else:
18
+ raise Exception(f"Failed to fetch token costs, status code: {response.status_code}")
19
+ except Exception as e:
20
+ print(f'Failed to update token costs with error: {e}. Using static costs.')
21
+ with open("model_prices.json", "r") as f:
22
+ TOKEN_COSTS = json.load(f)
23
+
24
+ TOKEN_COSTS = pd.DataFrame.from_dict(TOKEN_COSTS, orient='index').reset_index()
25
+ TOKEN_COSTS.columns = ['model'] + list(TOKEN_COSTS.columns[1:])
26
+ TOKEN_COSTS = TOKEN_COSTS.loc[
27
+ (~TOKEN_COSTS["model"].str.contains("sample_spec"))
28
+ & (~TOKEN_COSTS["input_cost_per_token"].isnull())
29
+ & (~TOKEN_COSTS["output_cost_per_token"].isnull())
30
+ & (TOKEN_COSTS["input_cost_per_token"] > 0)
31
+ & (TOKEN_COSTS["output_cost_per_token"] > 0)
32
+ ]
33
+ TOKEN_COSTS["supports_vision"] = TOKEN_COSTS["supports_vision"].fillna(False)
34
+
35
+ # Convert USD costs to INR
36
+ TOKEN_COSTS["input_cost_per_token"] *= USD_TO_INR
37
+ TOKEN_COSTS["output_cost_per_token"] *= USD_TO_INR
38
+
39
+ def clean_names(s):
40
+ s = s.replace("_", " ").replace("ai", "AI")
41
+ return s[0].upper() + s[1:]
42
+
43
+ TOKEN_COSTS["litellm_provider"] = TOKEN_COSTS["litellm_provider"].apply(clean_names)
44
+
45
+ cmap = plt.get_cmap('RdYlGn_r') # Red-Yellow-Green colormap, reversed
46
+
47
+ def count_string_tokens(string: str, model: str) -> int:
48
+ try:
49
+ encoding = tiktoken.encoding_for_model(model.split('/')[-1])
50
+ except:
51
+ if len(model.split('/')) > 1:
52
+ try:
53
+ encoding = tiktoken.encoding_for_model(model.split('/')[-2] + '/' + model.split('/')[-1])
54
+ except KeyError:
55
+ print(f"Model {model} not found. Using cl100k_base encoding.")
56
+ encoding = tiktoken.get_encoding("cl100k_base")
57
+ else:
58
+ print(f"Model {model} not found. Using cl100k_base encoding.")
59
+ encoding = tiktoken.get_encoding("cl100k_base")
60
+ return len(encoding.encode(string))
61
+
62
+ def calculate_total_cost(prompt_tokens: int, completion_tokens: int, model: str) -> float:
63
+ model_data = TOKEN_COSTS[TOKEN_COSTS['model'] == model].iloc[0]
64
+ prompt_cost = prompt_tokens * model_data['input_cost_per_token']
65
+
66
+
67
+
68
+
69
+
70
+ completion_cost = completion_tokens * model_data['output_cost_per_token']
71
+
72
+ return prompt_cost, completion_cost
73
+
74
+ def update_model_list(function_calling, litellm_provider, max_price, supports_vision, supports_max_input_tokens):
75
+ filtered_models = TOKEN_COSTS.loc[TOKEN_COSTS["max_input_tokens"] >= supports_max_input_tokens*1000]
76
+
77
+ if litellm_provider != "Any":
78
+ filtered_models = filtered_models[filtered_models['litellm_provider'] == litellm_provider]
79
+
80
+ if supports_vision:
81
+ filtered_models = filtered_models[filtered_models['supports_vision']]
82
+
83
+ list_models = filtered_models['model'].tolist()
84
+ return gr.Dropdown(choices=list_models, value=list_models[0] if list_models else "No model found for this combination!")
85
+
86
+
87
+
88
+
89
+
90
+ def compute_all(input_type, prompt_text, completion_text, prompt_tokens, completion_tokens, models):
91
+ results = []
92
+ temp=prompt_tokens
93
+ temp2=completion_tokens
94
+ for model in models:
95
+ if input_type == "Text Input":
96
+ prompt_tokens = count_string_tokens(prompt_text, model)
97
+ completion_tokens = count_string_tokens(completion_text, model)
98
+ else: # Token Count Input
99
+
100
+
101
+ prompt_tokens= int(prompt_tokens * 1000)
102
+
103
+ completion_tokens = int(completion_tokens * 1000)
104
+
105
+ model_data = TOKEN_COSTS[TOKEN_COSTS['model'] == model].iloc[0]
106
+ prompt_cost, completion_cost = calculate_total_cost(prompt_tokens, completion_tokens, model)
107
+
108
+ total_cost = prompt_cost + completion_cost
109
+
110
+ results.append({
111
+ "Model": model,
112
+ "Provider": model_data['litellm_provider'],
113
+ "Input Cost / M tokens": model_data['input_cost_per_token']*1e6,
114
+ "Output Cost / M tokens": model_data['output_cost_per_token']*1e6,
115
+ "Total Cost": round(total_cost, 2),
116
+ })
117
+ prompt_tokens=temp
118
+ completion_tokens=temp2
119
+
120
+
121
+ df = pd.DataFrame(results)
122
+
123
+ if len(df) > 1:
124
+ norm = plt.Normalize(df['Total Cost'].min(), df['Total Cost'].max())
125
+
126
+ def get_color(val):
127
+ color = cmap(norm(val))
128
+ return f'rgba({int(color[0]*255)}, {int(color[1]*255)}, {int(color[2]*255)}, 0.3)'
129
+
130
+ else:
131
+ def get_color(val):
132
+ return "rgba(0, 0, 0, 0)"
133
+
134
+ # Create the HTML table with animations
135
+ html_table = '<table class="styled-table">'
136
+ html_table += '<thead><tr>'
137
+ for col in df.columns:
138
+ html_table += f'<th>{col}</th>'
139
+ html_table += '</tr></thead><tbody>'
140
+
141
+ for i, row in df.iterrows():
142
+ html_table += f'<tr class="animate-row" style="animation-delay: {i * 0.1}s;">'
143
+ for col in df.columns:
144
+ value = row[col]
145
+ if col == 'Total Cost':
146
+ color = get_color(value)
147
+ html_table += f'<td class="total-cost" style="background-color: {color};">₹{value:.2f}</td>'
148
+ elif col in ["Input Cost / M tokens", "Output Cost / M tokens"]:
149
+ html_table += f'<td>₹{value:.2f}</td>'
150
+ else:
151
+ html_table += f'<td>{value}</td>'
152
+ html_table += '</tr>'
153
+
154
+ html_table += '</tbody></table>'
155
+
156
+ return html_table
157
+
158
+ def toggle_input_visibility(choice):
159
+ return (
160
+ gr.Group(visible=(choice == "Text Input")),
161
+ gr.Group(visible=(choice == "Token Count Input"))
162
+ )
163
+
164
+ with gr.Blocks(css="""
165
+ .styled-table {
166
+ border-collapse: separate;
167
+ border-spacing: 0;
168
+ margin: 25px 0;
169
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
170
+ width: 100%;
171
+ box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
172
+ border-radius: 12px;
173
+ overflow: hidden;
174
+ background-color: #f8f9fa;
175
+ }
176
+ .styled-table thead tr {
177
+ background-color: #3a506b;
178
+ color: #ffffff;
179
+ text-align: left;
180
+ font-weight: bold;
181
+ }
182
+ .styled-table th,
183
+ .styled-table td {
184
+ padding: 14px 18px;
185
+ border-bottom: 1px solid #e0e0e0;
186
+ }
187
+ .styled-table tbody tr {
188
+ transition: all 0.3s ease;
189
+ }
190
+ .styled-table tbody tr:nth-of-type(even) {
191
+ background-color: #f0f4f8;
192
+ }
193
+ .styled-table tbody tr:last-of-type {
194
+ border-bottom: 2px solid #3a506b;
195
+ }
196
+ .styled-table tbody tr:hover {
197
+ background-color: #e3e8ef;
198
+ transform: scale(1.02);
199
+ box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
200
+ }
201
+ .total-cost {
202
+ font-weight: bold;
203
+ transition: all 0.3s ease;
204
+ color: #2c3e50;
205
+ }
206
+ .total-cost:hover {
207
+ transform: scale(1.1);
208
+ color: #e74c3c;
209
+ }
210
+ @keyframes fadeIn {
211
+ from { opacity: 0; transform: translateY(20px); }
212
+ to { opacity: 1; transform: translateY(0); }
213
+ }
214
+ .animate-row {
215
+ animation: fadeIn 0.5s ease-out forwards;
216
+ opacity: 0;
217
+ }
218
+ .styled-table tbody tr td {
219
+ color: #34495e;
220
+ }
221
+ .styled-table tbody tr:hover td {
222
+ color: #2c3e50;
223
+ }
224
+ """, theme=gr.themes.Soft(primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.slate)) as demo:
225
+ gr.Markdown("""
226
+ # 💰 Text-to-Rupees: Get the price of your LLM API calls in INR! 💰
227
+ Based on prices data from [BerriAI's litellm](https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json).
228
+ Prices converted to INR (1 USD = 84 INR).
229
+ """)
230
+
231
+ with gr.Row():
232
+ with gr.Column():
233
+ gr.Markdown("## Input type:")
234
+ input_type = gr.Radio(["Text Input", "Token Count Input"], label="Input Type", value="Text Input")
235
+
236
+ with gr.Group() as text_input_group:
237
+ prompt_text = gr.Textbox(label="Prompt", value="Tell me a joke about AI.", lines=3)
238
+ completion_text = gr.Textbox(label="Completion", value="Certainly: Why did the neural network go to therapy? It had too many deep issues!", lines=3)
239
+
240
+ with gr.Group(visible=False) as token_input_group:
241
+ prompt_tokens_input = gr.Number(label="Prompt Tokens (thousands)", value=1.5)
242
+ completion_tokens_input = gr.Number(label="Completion Tokens (thousands)", value=2)
243
+
244
+ with gr.Column():
245
+ gr.Markdown("## Model choice:")
246
+ with gr.Row():
247
+ with gr.Column():
248
+ function_calling = gr.Checkbox(label="Supports Tool Calling", value=False)
249
+ supports_vision = gr.Checkbox(label="Supports Vision", value=False)
250
+ with gr.Column():
251
+ supports_max_input_tokens = gr.Slider(label="Min Supported Input Length (thousands)", minimum=2, maximum=256, step=2, value=2)
252
+ max_price = gr.Slider(label="Max Price per Input Token", minimum=0, maximum=0.084, step=0.00084, value=0.084, visible=False, interactive=False)
253
+ litellm_provider = gr.Dropdown(label="Inference Provider", choices=["Any"] + TOKEN_COSTS['litellm_provider'].unique().tolist(), value="Any")
254
+
255
+ model = gr.Dropdown(label="Models (at least 1)", choices=TOKEN_COSTS['model'].tolist(), value=["anyscale/meta-llama/Meta-Llama-3-8B-Instruct", "gpt-4o", "claude-3-sonnet-20240229"], multiselect=True)
256
+
257
+ gr.Markdown("## Resulting Costs 👇")
258
+
259
+ with gr.Row():
260
+ results_table = gr.HTML()
261
+
262
+ input_type.change(
263
+ toggle_input_visibility,
264
+ inputs=[input_type],
265
+ outputs=[text_input_group, token_input_group]
266
+ )
267
+
268
+ gr.on(
269
+ triggers=[function_calling.change, litellm_provider.change, max_price.change, supports_vision.change, supports_max_input_tokens.change],
270
+ fn=update_model_list,
271
+ inputs=[function_calling, litellm_provider, max_price, supports_vision, supports_max_input_tokens],
272
+ outputs=model,
273
+ )
274
+
275
+ gr.on(
276
+ triggers=[
277
+ input_type.change,
278
+ prompt_text.change,
279
+ completion_text.change,
280
+ prompt_tokens_input.change,
281
+ completion_tokens_input.change,
282
+ function_calling.change,
283
+ litellm_provider.change,
284
+ supports_vision.change,
285
+ supports_max_input_tokens.change,
286
+ model.change
287
+ ],
288
+ fn=compute_all,
289
+ inputs=[
290
+ input_type,
291
+ prompt_text,
292
+ completion_text,
293
+ prompt_tokens_input,
294
+ completion_tokens_input,
295
+ model
296
+ ],
297
+ outputs=results_table
298
+ )
299
+
300
+ # Load results on page load
301
+ demo.load(
302
+ fn=compute_all,
303
+ inputs=[
304
+ input_type,
305
+ prompt_text,
306
+ completion_text,
307
+ prompt_tokens_input,
308
+ completion_tokens_input,
309
+ model
310
+ ],
311
+ outputs=results_table
312
+ )
313
+
314
+ if __name__ == "__main__":
315
+ demo.launch()
model_prices.json ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ pandas
2
+ tiktoken
3
+ matplotlib