Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -147,19 +147,28 @@ def clear_conversation():
|
|
| 147 |
"""Clear the conversation history."""
|
| 148 |
return []
|
| 149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
def generate_analytics():
|
| 151 |
"""Generate analytics from the chat log"""
|
| 152 |
log_file = "analytics/chat_log.json"
|
| 153 |
|
| 154 |
if not os.path.exists(log_file):
|
| 155 |
-
return "No analytics data available yet.", None, None, None,
|
| 156 |
|
| 157 |
try:
|
| 158 |
with open(log_file, "r") as f:
|
| 159 |
logs = json.load(f)
|
| 160 |
|
| 161 |
if not logs:
|
| 162 |
-
return "No analytics data available yet.", None, None, None,
|
| 163 |
|
| 164 |
# Convert to DataFrame
|
| 165 |
df = pd.DataFrame(logs)
|
|
@@ -172,18 +181,14 @@ def generate_analytics():
|
|
| 172 |
}).reset_index()
|
| 173 |
model_usage.columns = ["model", "total_tokens", "request_count"]
|
| 174 |
|
| 175 |
-
plt.figure(figsize=(10, 6))
|
| 176 |
plt.bar(model_usage["model"], model_usage["total_tokens"])
|
| 177 |
plt.title("Token Usage by Model")
|
| 178 |
plt.xlabel("Model")
|
| 179 |
plt.ylabel("Total Tokens Used")
|
| 180 |
plt.xticks(rotation=45)
|
| 181 |
-
|
| 182 |
-
model_usage_img =
|
| 183 |
-
plt.savefig(model_usage_img, format="png", bbox_inches="tight")
|
| 184 |
-
model_usage_img.seek(0)
|
| 185 |
-
model_usage_b64 = base64.b64encode(model_usage_img.read()).decode("utf-8")
|
| 186 |
-
plt.close()
|
| 187 |
|
| 188 |
# Generate usage over time chart
|
| 189 |
df["date"] = df["timestamp"].dt.date
|
|
@@ -191,56 +196,55 @@ def generate_analytics():
|
|
| 191 |
"tokens_used": "sum"
|
| 192 |
}).reset_index()
|
| 193 |
|
| 194 |
-
plt.figure(figsize=(10, 6))
|
| 195 |
plt.plot(daily_usage["date"], daily_usage["tokens_used"], marker="o")
|
| 196 |
plt.title("Daily Token Usage")
|
| 197 |
plt.xlabel("Date")
|
| 198 |
plt.ylabel("Tokens Used")
|
| 199 |
plt.grid(True)
|
| 200 |
-
|
| 201 |
-
daily_usage_img =
|
| 202 |
-
plt.savefig(daily_usage_img, format="png", bbox_inches="tight")
|
| 203 |
-
daily_usage_img.seek(0)
|
| 204 |
-
daily_usage_b64 = base64.b64encode(daily_usage_img.read()).decode("utf-8")
|
| 205 |
-
plt.close()
|
| 206 |
|
| 207 |
# Generate response time chart
|
| 208 |
model_response_time = df.groupby("model").agg({
|
| 209 |
"response_time_sec": "mean"
|
| 210 |
}).reset_index()
|
| 211 |
|
| 212 |
-
plt.figure(figsize=(10, 6))
|
| 213 |
plt.bar(model_response_time["model"], model_response_time["response_time_sec"])
|
| 214 |
plt.title("Average Response Time by Model")
|
| 215 |
plt.xlabel("Model")
|
| 216 |
plt.ylabel("Response Time (seconds)")
|
| 217 |
plt.xticks(rotation=45)
|
| 218 |
-
|
| 219 |
-
response_time_img =
|
| 220 |
-
plt.savefig(response_time_img, format="png", bbox_inches="tight")
|
| 221 |
-
response_time_img.seek(0)
|
| 222 |
-
response_time_b64 = base64.b64encode(response_time_img.read()).decode("utf-8")
|
| 223 |
-
plt.close()
|
| 224 |
|
| 225 |
# Summary statistics
|
| 226 |
total_tokens = df["tokens_used"].sum()
|
| 227 |
total_requests = len(df)
|
| 228 |
avg_response_time = df["response_time_sec"].mean()
|
| 229 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
summary = f"""
|
| 231 |
## Analytics Summary
|
| 232 |
|
| 233 |
- **Total API Requests**: {total_requests}
|
| 234 |
- **Total Tokens Used**: {total_tokens:,}
|
| 235 |
- **Average Response Time**: {avg_response_time:.2f} seconds
|
| 236 |
-
- **Most Used Model**: {
|
| 237 |
- **Date Range**: {df["timestamp"].min().date()} to {df["timestamp"].max().date()}
|
| 238 |
"""
|
| 239 |
|
| 240 |
-
return summary,
|
| 241 |
|
| 242 |
except Exception as e:
|
| 243 |
-
|
|
|
|
| 244 |
|
| 245 |
# Define available models
|
| 246 |
models = [
|
|
@@ -366,11 +370,11 @@ with gr.Blocks(title="Groq AI Chat Playground") as app:
|
|
| 366 |
|
| 367 |
with gr.Row():
|
| 368 |
with gr.Column():
|
| 369 |
-
model_usage_chart = gr.
|
| 370 |
with gr.Column():
|
| 371 |
-
daily_usage_chart = gr.
|
| 372 |
|
| 373 |
-
response_time_chart = gr.
|
| 374 |
|
| 375 |
with gr.Accordion("Raw Data", open=False):
|
| 376 |
analytics_table = gr.DataFrame(label="Raw Analytics Data")
|
|
|
|
| 147 |
"""Clear the conversation history."""
|
| 148 |
return []
|
| 149 |
|
| 150 |
+
def plt_to_html(fig):
|
| 151 |
+
"""Convert matplotlib figure to HTML img tag"""
|
| 152 |
+
buf = io.BytesIO()
|
| 153 |
+
fig.savefig(buf, format="png", bbox_inches="tight")
|
| 154 |
+
buf.seek(0)
|
| 155 |
+
img_str = base64.b64encode(buf.read()).decode("utf-8")
|
| 156 |
+
plt.close(fig)
|
| 157 |
+
return f'<img src="data:image/png;base64,{img_str}" alt="Chart">'
|
| 158 |
+
|
| 159 |
def generate_analytics():
|
| 160 |
"""Generate analytics from the chat log"""
|
| 161 |
log_file = "analytics/chat_log.json"
|
| 162 |
|
| 163 |
if not os.path.exists(log_file):
|
| 164 |
+
return "No analytics data available yet.", None, None, None, []
|
| 165 |
|
| 166 |
try:
|
| 167 |
with open(log_file, "r") as f:
|
| 168 |
logs = json.load(f)
|
| 169 |
|
| 170 |
if not logs:
|
| 171 |
+
return "No analytics data available yet.", None, None, None, []
|
| 172 |
|
| 173 |
# Convert to DataFrame
|
| 174 |
df = pd.DataFrame(logs)
|
|
|
|
| 181 |
}).reset_index()
|
| 182 |
model_usage.columns = ["model", "total_tokens", "request_count"]
|
| 183 |
|
| 184 |
+
fig1 = plt.figure(figsize=(10, 6))
|
| 185 |
plt.bar(model_usage["model"], model_usage["total_tokens"])
|
| 186 |
plt.title("Token Usage by Model")
|
| 187 |
plt.xlabel("Model")
|
| 188 |
plt.ylabel("Total Tokens Used")
|
| 189 |
plt.xticks(rotation=45)
|
| 190 |
+
plt.tight_layout()
|
| 191 |
+
model_usage_img = plt_to_html(fig1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
# Generate usage over time chart
|
| 194 |
df["date"] = df["timestamp"].dt.date
|
|
|
|
| 196 |
"tokens_used": "sum"
|
| 197 |
}).reset_index()
|
| 198 |
|
| 199 |
+
fig2 = plt.figure(figsize=(10, 6))
|
| 200 |
plt.plot(daily_usage["date"], daily_usage["tokens_used"], marker="o")
|
| 201 |
plt.title("Daily Token Usage")
|
| 202 |
plt.xlabel("Date")
|
| 203 |
plt.ylabel("Tokens Used")
|
| 204 |
plt.grid(True)
|
| 205 |
+
plt.tight_layout()
|
| 206 |
+
daily_usage_img = plt_to_html(fig2)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
# Generate response time chart
|
| 209 |
model_response_time = df.groupby("model").agg({
|
| 210 |
"response_time_sec": "mean"
|
| 211 |
}).reset_index()
|
| 212 |
|
| 213 |
+
fig3 = plt.figure(figsize=(10, 6))
|
| 214 |
plt.bar(model_response_time["model"], model_response_time["response_time_sec"])
|
| 215 |
plt.title("Average Response Time by Model")
|
| 216 |
plt.xlabel("Model")
|
| 217 |
plt.ylabel("Response Time (seconds)")
|
| 218 |
plt.xticks(rotation=45)
|
| 219 |
+
plt.tight_layout()
|
| 220 |
+
response_time_img = plt_to_html(fig3)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
# Summary statistics
|
| 223 |
total_tokens = df["tokens_used"].sum()
|
| 224 |
total_requests = len(df)
|
| 225 |
avg_response_time = df["response_time_sec"].mean()
|
| 226 |
|
| 227 |
+
# Handling the case where there might not be enough data
|
| 228 |
+
if not model_usage.empty:
|
| 229 |
+
most_used_model = model_usage.iloc[model_usage["request_count"].argmax()]["model"]
|
| 230 |
+
else:
|
| 231 |
+
most_used_model = "N/A"
|
| 232 |
+
|
| 233 |
summary = f"""
|
| 234 |
## Analytics Summary
|
| 235 |
|
| 236 |
- **Total API Requests**: {total_requests}
|
| 237 |
- **Total Tokens Used**: {total_tokens:,}
|
| 238 |
- **Average Response Time**: {avg_response_time:.2f} seconds
|
| 239 |
+
- **Most Used Model**: {most_used_model}
|
| 240 |
- **Date Range**: {df["timestamp"].min().date()} to {df["timestamp"].max().date()}
|
| 241 |
"""
|
| 242 |
|
| 243 |
+
return summary, model_usage_img, daily_usage_img, response_time_img, df.to_dict("records")
|
| 244 |
|
| 245 |
except Exception as e:
|
| 246 |
+
error_message = f"Error generating analytics: {str(e)}"
|
| 247 |
+
return error_message, None, None, None, []
|
| 248 |
|
| 249 |
# Define available models
|
| 250 |
models = [
|
|
|
|
| 370 |
|
| 371 |
with gr.Row():
|
| 372 |
with gr.Column():
|
| 373 |
+
model_usage_chart = gr.HTML(label="Token Usage by Model")
|
| 374 |
with gr.Column():
|
| 375 |
+
daily_usage_chart = gr.HTML(label="Daily Token Usage")
|
| 376 |
|
| 377 |
+
response_time_chart = gr.HTML(label="Response Time by Model")
|
| 378 |
|
| 379 |
with gr.Accordion("Raw Data", open=False):
|
| 380 |
analytics_table = gr.DataFrame(label="Raw Analytics Data")
|