noumanjavaid commited on
Commit
5e1d775
Β·
verified Β·
1 Parent(s): 6077200

Create realtime.py

Browse files
Files changed (1) hide show
  1. realtime.py +295 -0
realtime.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import plotly.express as px
5
+ from openai import OpenAI
6
+ import os
7
+ from dotenv import load_dotenv
8
+ import json
9
+
10
+ # Load environment variables
11
+ load_dotenv()
12
+
13
+ # Set page config
14
+ st.set_page_config(
15
+ page_title="GPT-4o Calculator & Demo",
16
+ page_icon="πŸ€–",
17
+ layout="wide",
18
+ initial_sidebar_state="collapsed"
19
+ )
20
+
21
+ # Custom CSS for dark theme
22
+ st.markdown("""
23
+ <style>
24
+ /* Dark theme */
25
+ .stApp {
26
+ background-color: #0e1117;
27
+ color: #ffffff;
28
+ }
29
+
30
+ /* Tab styling */
31
+ .stTabs [data-baseweb="tab-list"] {
32
+ gap: 1rem;
33
+ background-color: #1a1f2b;
34
+ padding: 0.5rem;
35
+ border-radius: 0.5rem;
36
+ }
37
+
38
+ .stTabs [data-baseweb="tab"] {
39
+ height: auto;
40
+ padding: 1rem;
41
+ background-color: #262b37;
42
+ border: 1px solid #2d3748;
43
+ border-radius: 0.5rem;
44
+ color: #e2e8f0;
45
+ font-weight: 500;
46
+ }
47
+
48
+ .stTabs [data-baseweb="tab"]:hover {
49
+ background-color: #2d3748;
50
+ }
51
+
52
+ /* Card styling */
53
+ .card {
54
+ padding: 1.5rem;
55
+ background-color: #1a1f2b;
56
+ border: 1px solid #2d3748;
57
+ border-radius: 0.5rem;
58
+ margin: 1rem 0;
59
+ }
60
+
61
+ /* Text styling */
62
+ h1, h2, h3 {
63
+ color: #e2e8f0;
64
+ }
65
+
66
+ p {
67
+ color: #a0aec0;
68
+ }
69
+
70
+ /* Input styling */
71
+ .stTextInput > div > div {
72
+ background-color: #262b37;
73
+ color: #e2e8f0;
74
+ }
75
+
76
+ /* Metric styling */
77
+ [data-testid="stMetricValue"] {
78
+ color: #e2e8f0;
79
+ }
80
+ </style>
81
+ """, unsafe_allow_html=True)
82
+
83
+ # Check for API key
84
+ if 'OPENAI_API_KEY' not in st.session_state:
85
+ api_key = st.text_input('Enter your OpenAI API key:', type='password')
86
+ if api_key:
87
+ st.session_state['OPENAI_API_KEY'] = api_key
88
+ st.success('API key saved!')
89
+ else:
90
+ st.warning('Please enter your OpenAI API key to continue.')
91
+ st.stop()
92
+
93
+ # Initialize OpenAI client
94
+ client = OpenAI(api_key=st.session_state['OPENAI_API_KEY'])
95
+
96
+ # Pricing data
97
+ pricing_data = {
98
+ "gpt-4o-audio-preview": {
99
+ "text_input": 2.50,
100
+ "text_output": 10.00,
101
+ "audio_input": 100.00,
102
+ "audio_output": 200.00,
103
+ "description": "Full-featured model with highest quality"
104
+ },
105
+ "gpt-4o-mini-audio-preview": {
106
+ "text_input": 0.150,
107
+ "text_output": 0.600,
108
+ "audio_input": 10.000,
109
+ "audio_output": 20.000,
110
+ "description": "Cost-effective model for development"
111
+ }
112
+ }
113
+
114
+ def make_api_call(text_input, model="gpt-4o-mini-audio-preview"):
115
+ """Make actual API call to OpenAI"""
116
+ try:
117
+ response = client.chat.completions.create(
118
+ model=model,
119
+ messages=[
120
+ {
121
+ "role": "user",
122
+ "content": [
123
+ {
124
+ "type": "text",
125
+ "text": text_input
126
+ }
127
+ ]
128
+ }
129
+ ],
130
+ modalities=["text", "audio"],
131
+ audio={
132
+ "voice": "verse",
133
+ "format": "pcm16"
134
+ },
135
+ response_format={
136
+ "type": "text"
137
+ },
138
+ temperature=0,
139
+ max_completion_tokens=2048
140
+ )
141
+ return response
142
+ except Exception as e:
143
+ return f"Error: {str(e)}"
144
+
145
+ def calculate_cost(model, input_type, duration):
146
+ """Calculate cost based on input parameters"""
147
+ pricing = pricing_data[model]
148
+
149
+ if input_type == "Audio":
150
+ tokens = duration * 1000 # ~1000 tokens per minute of audio
151
+ input_cost = (tokens * pricing["audio_input"]) / 1000000
152
+ output_cost = (tokens * pricing["audio_output"]) / 1000000
153
+ else:
154
+ words = duration * 150 # ~150 words per minute
155
+ tokens = words * 1.3 # ~1.3 tokens per word
156
+ input_cost = (tokens * pricing["text_input"]) / 1000000
157
+ output_cost = (tokens * pricing["text_output"]) / 1000000
158
+
159
+ return {
160
+ "tokens": tokens,
161
+ "input_cost": input_cost,
162
+ "output_cost": output_cost,
163
+ "total": input_cost + output_cost
164
+ }
165
+
166
+ # Main app
167
+ st.title("GPT-4o Calculator & Demo πŸ€–")
168
+
169
+ # Create tabs
170
+ tab1, tab2, tab3 = st.tabs([
171
+ "πŸ’° Cost Calculator",
172
+ "🎯 Live Demo",
173
+ "πŸ“š Documentation"
174
+ ])
175
+
176
+ # Tab 1: Cost Calculator
177
+ with tab1:
178
+ st.header("Cost Calculator")
179
+
180
+ col1, col2 = st.columns([1, 1])
181
+
182
+ with col1:
183
+ model = st.selectbox(
184
+ "Select Model",
185
+ options=list(pricing_data.keys()),
186
+ help="Choose the GPT-4o model"
187
+ )
188
+
189
+ input_type = st.radio(
190
+ "Input Type",
191
+ options=["Text", "Audio"],
192
+ horizontal=True,
193
+ help="Select the type of content you're processing"
194
+ )
195
+
196
+ duration = st.number_input(
197
+ "Duration (minutes)",
198
+ min_value=0.0,
199
+ value=1.0,
200
+ step=0.5,
201
+ help="Enter the duration of your content"
202
+ )
203
+
204
+ costs = calculate_cost(model, input_type, duration)
205
+
206
+ with col2:
207
+ st.subheader("Cost Breakdown")
208
+
209
+ col_a, col_b = st.columns(2)
210
+ with col_a:
211
+ st.metric("Input Cost", f"${costs['input_cost']:.2f}")
212
+ with col_b:
213
+ st.metric("Output Cost", f"${costs['output_cost']:.2f}")
214
+
215
+ st.metric("Total Cost", f"${costs['total']:.2f}")
216
+
217
+ # Visualize token usage
218
+ fig = px.pie(
219
+ values=[costs['input_cost'], costs['output_cost']],
220
+ names=['Input Cost', 'Output Cost'],
221
+ title='Cost Distribution'
222
+ )
223
+ fig.update_layout(
224
+ paper_bgcolor='rgba(0,0,0,0)',
225
+ plot_bgcolor='rgba(0,0,0,0)',
226
+ font_color='#e2e8f0'
227
+ )
228
+ st.plotly_chart(fig, use_container_width=True)
229
+
230
+ # Tab 2: Live Demo
231
+ with tab2:
232
+ st.header("Live API Demo")
233
+
234
+ demo_text = st.text_input(
235
+ "Enter your message",
236
+ value="Hello, how are you today?",
237
+ help="Enter the text you want to process"
238
+ )
239
+
240
+ demo_model = st.selectbox(
241
+ "Select Model",
242
+ options=list(pricing_data.keys()),
243
+ key="demo_model"
244
+ )
245
+
246
+ if st.button("Send Message"):
247
+ with st.spinner("Processing your request..."):
248
+ response = make_api_call(demo_text, demo_model)
249
+
250
+ st.subheader("API Response")
251
+ if isinstance(response, str) and response.startswith("Error"):
252
+ st.error(response)
253
+ else:
254
+ st.code(json.dumps(response, indent=2), language="json")
255
+
256
+ # Calculate cost for this request
257
+ text_costs = calculate_cost(demo_model, "Text", len(demo_text.split()) / 150)
258
+ st.info(f"Cost for this request: ${text_costs['total']:.4f}")
259
+
260
+ # Tab 3: Documentation
261
+ with tab3:
262
+ st.header("Documentation")
263
+
264
+ st.subheader("Model Capabilities")
265
+ st.markdown("""
266
+ GPT-4o supports:
267
+ - Text-to-text conversion
268
+ - Text-to-audio conversion
269
+ - Audio-to-text conversion
270
+ - Audio-to-audio conversion
271
+ """)
272
+
273
+ st.subheader("Token Usage")
274
+ token_data = pd.DataFrame([
275
+ {"Content Type": "Text", "Token Rate": "~1.3 tokens per word"},
276
+ {"Content Type": "Audio", "Token Rate": "~1000 tokens per minute"}
277
+ ])
278
+ st.table(token_data)
279
+
280
+ st.subheader("Pricing Details")
281
+ for model, prices in pricing_data.items():
282
+ with st.expander(model):
283
+ st.markdown(f"""
284
+ **Text Processing**
285
+ - Input: ${prices['text_input']}/1M tokens
286
+ - Output: ${prices['text_output']}/1M tokens
287
+
288
+ **Audio Processing**
289
+ - Input: ${prices['audio_input']}/1M tokens
290
+ - Output: ${prices['audio_output']}/1M tokens
291
+ """)
292
+
293
+ # Footer
294
+ st.markdown("---")
295
+ st.caption("Note: All calculations are estimates. Actual costs may vary based on specific usage patterns.")