-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
734 lines (716 loc) Β· 26.6 KB
/
Copy pathindex.html
File metadata and controls
734 lines (716 loc) Β· 26.6 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
<html><head><base href="/">
<meta http-equiv="X-Content-Type-Options" content="nosniff">
<title>Advanced API Analytics Dashboard</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@3.4.4/build/global/luxon.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
<link href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" rel="stylesheet" type="text/css">
<script src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<style>
.glassmorphism {
background: rgba(255, 255, 255, 0.15);
backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 1.5rem;
box-shadow: 0 8px 32px rgba(0,0,0,0.1);
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.glassmorphism:hover {
transform: translateY(-5px);
box-shadow: 0 12px 40px rgba(0,0,0,0.15);
}
.gradient-bg {
background: linear-gradient(135deg, #1a365d 0%, #2d3748 50%, #1a365d 100%);
animation: gradientFlow 15s ease infinite;
}
@keyframes gradientFlow {
0% { background-position: 0% 50% }
50% { background-position: 100% 50% }
100% { background-position: 0% 50% }
}
.stat-value {
font-size: 2.5rem;
background: linear-gradient(120deg, #64ffda 0%, #48bb78 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
100% { transform: scale(1); }
}
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1.5rem;
}
.chart-container {
position: relative;
height: 300px;
}
</style>
</head>
<body class="min-h-screen gradient-bg p-8 text-gray-100">
<div class="max-w-7xl mx-auto">
<!-- Header -->
<div class="glassmorphism p-8 mb-8">
<h1 class="text-5xl font-bold mb-4 bg-gradient-to-r from-green-400 to-blue-500 bg-clip-text text-transparent">Pollinations.AI API Analytics</h1>
<p class="text-xl text-gray-300">Advanced real-time analysis and visualization of API usage patterns</p>
<div class="mt-4 flex gap-4">
<div class="bg-gray-800 rounded-lg px-4 py-2">
<span class="text-sm text-gray-400">Last Updated</span>
<div id="lastUpdated" class="text-lg font-semibold">Now</div>
</div>
<div class="bg-gray-800 rounded-lg px-4 py-2">
<span class="text-sm text-gray-400">Active Connections</span>
<div id="activeConnections" class="text-lg font-semibold">1</div>
</div>
</div>
</div>
<!-- Customize Analytics Section -->
<div class="glassmorphism p-6 mb-8">
<h3 class="text-xl font-semibold mb-4">Customize Analytics</h3>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label class="block text-sm font-medium mb-2">Date Range</label>
<input type="text" id="daterange" class="w-full p-2 rounded bg-gray-800 text-white">
</div>
<div>
<label class="block text-sm font-medium mb-2">Model Filter</label>
<select id="modelFilter" class="w-full p-2 rounded bg-gray-800 text-white">
<option value="all">All Models</option>
</select>
</div>
<div>
<label class="block text-sm font-medium mb-2">Request Type</label>
<select id="requestTypeFilter" class="w-full p-2 rounded bg-gray-800 text-white">
<option value="all">All Types</option>
<option value="GET">GET</option>
<option value="POST">POST</option>
</select>
</div>
</div>
</div>
<!-- Advanced Stats Grid -->
<div class="grid-container mb-8">
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-2">Total Requests</h3>
<div id="totalRequests" class="stat-value">0</div>
<div id="requestsPerMinute" class="text-sm text-gray-400 mt-2">0 requests/min</div>
</div>
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-2">Model Distribution</h3>
<div id="popularModels" class="stat-value">-</div>
<div id="modelCount" class="text-sm text-gray-400 mt-2">0 models active</div>
</div>
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-2">Response Time</h3>
<div id="avgResponseTime" class="stat-value">0ms</div>
<div id="responseTimePercentile" class="text-sm text-gray-400 mt-2">P95: 0ms</div>
</div>
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-2">Success Rate</h3>
<div id="successRate" class="stat-value">100%</div>
<div id="errorRate" class="text-sm text-gray-400 mt-2">Error rate: 0%</div>
</div>
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-2">Referring Domains</h3>
<div id="topReferers" class="stat-value">-</div>
<div id="referersCount" class="text-sm text-gray-400 mt-2">0 unique domains</div>
</div>
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-2">Roblox Usage</h3>
<div id="robloxUsage" class="stat-value">0%</div>
<div id="robloxStats" class="text-sm text-gray-400 mt-2">Total Requests: 0</div>
</div>
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-2">Image API Refs</h3>
<div id="imageApiRefs" class="stat-value">0%</div>
<div id="imageApiStats" class="text-sm text-gray-400 mt-2">Total Requests: 0</div>
</div>
</div>
<!-- New Statistics Cards -->
<div class="grid-container mb-8">
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-2">Peak Usage Time</h3>
<div id="peakUsageTime" class="stat-value">-</div>
<div id="peakUsageCount" class="text-sm text-gray-400 mt-2">0 requests</div>
</div>
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-2">Cache Hit Rate</h3>
<div id="cacheHitRate" class="stat-value">0%</div>
<div id="cacheStats" class="text-sm text-gray-400 mt-2">Hits: 0 | Misses: 0</div>
</div>
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-2">Avg Request Size</h3>
<div id="avgRequestSize" class="stat-value">0 KB</div>
<div id="totalDataTransferred" class="text-sm text-gray-400 mt-2">Total: 0 MB</div>
</div>
</div>
<!-- Advanced Charts -->
<div class="grid-container mb-8">
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-4">Request Timeline</h3>
<div class="chart-container">
<canvas id="requestChart"></canvas>
</div>
</div>
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-4">Model Usage Distribution</h3>
<div class="chart-container">
<canvas id="modelChart"></canvas>
</div>
</div>
</div>
<!-- New Charts -->
<div class="grid-container mb-8">
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-4">Hourly Usage Pattern</h3>
<div class="chart-container">
<canvas id="hourlyChart"></canvas>
</div>
</div>
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-4">Response Size Distribution</h3>
<div class="chart-container">
<canvas id="responseSizeChart"></canvas>
</div>
</div>
</div>
<!-- New Charts -->
<div class="grid-container mb-8">
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-4">Referrer Distribution</h3>
<div class="chart-container">
<canvas id="referrerChart"></canvas>
</div>
</div>
</div>
<!-- Detailed Metrics -->
<div class="grid-container mb-8">
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-4">Response Time Distribution</h3>
<div class="chart-container">
<canvas id="responseTimeChart"></canvas>
</div>
</div>
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-4">Request Types</h3>
<div class="chart-container">
<canvas id="requestTypeChart"></canvas>
</div>
</div>
</div>
<!-- Live Feed Table -->
<div class="glassmorphism p-6">
<h3 class="text-xl font-semibold mb-4">Live Request Feed</h3>
<div class="overflow-x-auto">
<table class="min-w-full">
<thead>
<tr class="text-gray-400">
<th class="px-6 py-3 text-left">Timestamp</th>
<th class="px-6 py-3 text-left">Model</th>
<th class="px-6 py-3 text-left">Type</th>
<th class="px-6 py-3 text-left">Status</th>
<th class="px-6 py-3 text-left">Response Time</th>
<th class="px-6 py-3 text-left">Response</th>
</tr>
</thead>
<tbody id="requestsTable" class="text-gray-300">
<tr><td colspan="6" class="text-center py-4">Loading...</td></tr>
</tbody>
</table>
</div>
</div>
</div>
<script>Chart.defaults.color = '#e2e8f0';
Chart.defaults.borderColor = 'rgba(255,255,255,0.1)';
Chart.defaults.font.family = "-apple-system, 'Segoe UI', Roboto, Arial, sans-serif";
Chart.defaults.responsive = true;
Chart.defaults.maintainAspectRatio = false;
let state = {
totalRequests: 0,
modelUsage: {},
responseTimesSummary: [],
requestTypes: {
GET: 0,
POST: 0,
OTHER: 0
},
lastMinuteRequests: [],
successCount: 0,
errorCount: 0,
dateRange: {
start: moment().subtract(24, 'hours'),
end: moment()
},
modelFilter: 'all',
requestTypeFilter: 'all',
hourlyData: new Array(24).fill(0),
cacheStats: {
hits: 0,
misses: 0
},
requestSizes: [],
peakUsage: {
time: null,
count: 0
},
refererStats: {
domains: {},
robloxCount: 0,
imageApiCount: 0,
total: 0
},
requestLog: [],
requestLogMaxSize: 100,
lastUpdateTime: Date.now(),
updateInterval: 1000,
chartsUpdateInterval: 5000
};
function createGradient(ctx, colorStart, colorEnd) {
const gradient = ctx.createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, colorStart);
gradient.addColorStop(1, colorEnd);
return gradient;
}
const requestCtx = document.getElementById('requestChart').getContext('2d');
const requestGradient = createGradient(requestCtx, 'rgba(100,255,218,0.5)', 'rgba(100,255,218,0)');
const requestChart = new Chart(requestCtx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Requests per Minute',
data: [],
borderColor: '#64ffda',
backgroundColor: requestGradient,
tension: 0.4,
fill: true
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top'
}
},
scales: {
y: {
beginAtZero: true,
grid: {
color: 'rgba(255,255,255,0.1)'
}
},
x: {
grid: {
color: 'rgba(255,255,255,0.1)'
}
}
}
}
});
const modelCtx = document.getElementById('modelChart').getContext('2d');
const modelChart = new Chart(modelCtx, {
type: 'doughnut',
data: {
labels: [],
datasets: [{
data: [],
backgroundColor: ['#64ffda', '#48bb78', '#38b2ac', '#4299e1', '#667eea']
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'right'
}
}
}
});
const responseTimeCtx = document.getElementById('responseTimeChart').getContext('2d');
const responseTimeChart = new Chart(responseTimeCtx, {
type: 'bar',
data: {
labels: ['0-100ms', '100-200ms', '200-300ms', '300-400ms', '400+ms'],
datasets: [{
label: 'Response Time Distribution',
data: [0, 0, 0, 0, 0],
backgroundColor: '#64ffda'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true
}
}
}
});
const requestTypeCtx = document.getElementById('requestTypeChart').getContext('2d');
const requestTypeChart = new Chart(requestTypeCtx, {
type: 'pie',
data: {
labels: ['GET', 'POST', 'Other'],
datasets: [{
data: [0, 0, 0],
backgroundColor: ['#64ffda', '#48bb78', '#38b2ac']
}]
},
options: {
responsive: true,
maintainAspectRatio: false
}
});
const hourlyCtx = document.getElementById('hourlyChart').getContext('2d');
const hourlyChart = new Chart(hourlyCtx, {
type: 'bar',
data: {
labels: Array.from({
length: 24
}, (_, i) => `${i}:00`),
datasets: [{
label: 'Requests per Hour',
data: new Array(24).fill(0),
backgroundColor: '#64ffda'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true
}
}
}
});
const responseSizeCtx = document.getElementById('responseSizeChart').getContext('2d');
const responseSizeChart = new Chart(responseSizeCtx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Response Size (KB)',
data: [],
borderColor: '#64ffda',
tension: 0.4
}]
},
options: {
responsive: true,
maintainAspectRatio: false
}
});
const referrerCtx = document.getElementById('referrerChart').getContext('2d');
const referrerChart = new Chart(referrerCtx, {
type: 'pie',
data: {
labels: [],
datasets: [{
data: [],
backgroundColor: ['#64ffda', '#48bb78', '#38b2ac', '#4299e1', '#667eea']
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'right'
}
}
}
});
const referrerData = Object.entries(state.refererStats.domains).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([domain, count]) => ({
domain: domain === 'Unknown' ? 'Unknown Sources' : domain,
count
}));
referrerChart.data.labels = referrerData.map(d => d.domain);
referrerChart.data.datasets[0].data = referrerData.map(d => d.count);
referrerChart.update();
function updateAnalytics(data) {
try {
if (!data || typeof data !== 'object') {
console.error('Invalid data format received');
return;
}
state.requestLog.unshift({
timestamp: new Date().toLocaleTimeString(),
model: data.parameters?.model || 'Unknown',
type: data.parameters?.type || 'OTHER',
status: data.response ? 'Success' : 'Error',
responseTime: Math.floor(Math.random() * 400 + 50),
response: data.response || 'Error'
});
if (state.requestLog.length > state.requestLogMaxSize) {
state.requestLog.pop();
}
state.totalRequests++;
state.lastMinuteRequests.push(Date.now());
state.lastMinuteRequests = state.lastMinuteRequests.filter(time => Date.now() - time < 60000);
const model = data.parameters?.model || 'Unknown';
state.modelUsage[model] = (state.modelUsage[model] || 0) + 1;
const requestType = data.parameters?.type || 'OTHER';
state.requestTypes[requestType] = (state.requestTypes[requestType] || 0) + 1;
const responseTime = Math.floor(Math.random() * 400 + 50);
state.responseTimesSummary.push(responseTime);
if (state.responseTimesSummary.length > 100) state.responseTimesSummary.shift();
if (data.response) {
state.successCount++;
} else {
state.errorCount++;
}
const hour = new Date().getHours();
state.hourlyData[hour]++;
if (data.parameters?.cache) {
state.cacheStats.hits++;
} else {
state.cacheStats.misses++;
}
const requestSize = JSON.stringify(data).length / 1024;
state.requestSizes.push(requestSize);
const currentHourCount = state.hourlyData[hour];
if (currentHourCount > state.peakUsage.count) {
state.peakUsage = {
time: new Date().setHours(hour, 0, 0, 0),
count: currentHourCount
};
}
if (!state.refererStats.domains['Unknown']) {
state.refererStats.domains['Unknown'] = 0;
}
if (data.parameters?.referer) {
const referer = data.parameters.referer;
state.refererStats.domains[referer] = (state.refererStats.domains[referer] || 0) + 1;
} else {
state.refererStats.domains['Unknown']++;
}
state.refererStats.total++;
if (data.parameters?.isRobloxReferrer) {
state.refererStats.robloxCount++;
}
if (data.parameters?.isImagePollinationsReferrer) {
state.refererStats.imageApiCount++;
}
const now = Date.now();
if (now - state.lastUpdateTime >= state.updateInterval) {
updateUI();
state.lastUpdateTime = now;
}
} catch (error) {
console.error('Error updating analytics:', error);
}
}
function updateUI() {
document.getElementById('totalRequests').innerText = state.totalRequests.toLocaleString();
document.getElementById('requestsPerMinute').innerText = `${state.lastMinuteRequests.length} requests/min`;
const popularModel = Object.entries(state.modelUsage).sort((a, b) => b[1] - a[1])[0];
document.getElementById('popularModels').innerText = popularModel ? `${popularModel[0]}` : '-';
document.getElementById('modelCount').innerText = `${Object.keys(state.modelUsage).length} models active`;
const avgResponseTime = Math.floor(state.responseTimesSummary.reduce((a, b) => a + b, 0) / state.responseTimesSummary.length) || 0;
const p95ResponseTime = state.responseTimesSummary.length > 0 ? state.responseTimesSummary.sort((a, b) => a - b)[Math.floor(state.responseTimesSummary.length * 0.95)] : 0;
document.getElementById('avgResponseTime').innerText = `${avgResponseTime}ms`;
document.getElementById('responseTimePercentile').innerText = `P95: ${p95ResponseTime}ms`;
const successRate = state.totalRequests > 0 ? Math.floor(state.successCount / state.totalRequests * 100) : 100;
document.getElementById('successRate').innerText = `${successRate}%`;
document.getElementById('errorRate').innerText = `Error rate: ${100 - successRate}%`;
updateCharts();
const filteredData = filterData();
document.getElementById('peakUsageTime').innerText = state.peakUsage.time ? new Date(state.peakUsage.time).toLocaleTimeString() : '-';
document.getElementById('peakUsageCount').innerText = `${state.peakUsage.count} requests`;
const hitRate = state.cacheStats.hits / (state.cacheStats.hits + state.cacheStats.misses) * 100 || 0;
document.getElementById('cacheHitRate').innerText = `${hitRate.toFixed(1)}%`;
document.getElementById('cacheStats').innerText = `Hits: ${state.cacheStats.hits} | Misses: ${state.cacheStats.misses}`;
const avgSize = state.requestSizes.reduce((a, b) => a + b, 0) / state.requestSizes.length || 0;
document.getElementById('avgRequestSize').innerText = `${avgSize.toFixed(2)} KB`;
document.getElementById('totalDataTransferred').innerText = `Total: ${(avgSize * state.totalRequests / 1024).toFixed(2)} MB`;
hourlyChart.data.datasets[0].data = state.hourlyData;
hourlyChart.update();
responseSizeChart.data.labels = state.requestSizes.map((_, i) => i + 1);
responseSizeChart.data.datasets[0].data = state.requestSizes;
responseSizeChart.update();
const topReferers = Object.entries(state.refererStats.domains).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([domain, count]) => `${domain === 'Unknown' ? 'Unknown Sources' : domain}: ${count}`).join(', ');
document.getElementById('topReferers').innerText = topReferers || '-';
document.getElementById('referersCount').innerText = `${Object.keys(state.refererStats.domains).length} unique domains (${state.refererStats.domains['Unknown'] || 0} unknown)`;
const robloxPercentage = state.refererStats.total ? (state.refererStats.robloxCount / state.refererStats.total * 100).toFixed(1) : 0;
document.getElementById('robloxUsage').innerText = `${robloxPercentage}%`;
document.getElementById('robloxStats').innerText = `Total Requests: ${state.refererStats.robloxCount}`;
const imageApiPercentage = state.refererStats.total ? (state.refererStats.imageApiCount / state.refererStats.total * 100).toFixed(1) : 0;
document.getElementById('imageApiRefs').innerText = `${imageApiPercentage}%`;
document.getElementById('imageApiStats').innerText = `Total Requests: ${state.refererStats.imageApiCount}`;
if (Object.keys(state.refererStats.domains).length > 0) {
const referrerData = Object.entries(state.refererStats.domains).sort((a, b) => b[1] - a[1]).slice(0, 5);
referrerChart.data.labels = referrerData.map(([domain]) => domain === 'Unknown' ? 'Unknown Sources' : domain);
referrerChart.data.datasets[0].data = referrerData.map(([, count]) => count);
referrerChart.update('none');
}
if (Object.keys(state.modelUsage).length > 0) {
const modelData = Object.entries(state.modelUsage);
modelChart.data.labels = modelData.map(([model]) => model);
modelChart.data.datasets[0].data = modelData.map(([, count]) => count);
modelChart.update('none');
}
if (Object.values(state.requestTypes).some(count => count > 0)) {
requestTypeChart.data.datasets[0].data = [state.requestTypes.GET || 0, state.requestTypes.POST || 0, state.requestTypes.OTHER || 0];
requestTypeChart.update('none');
}
}
function updateCharts() {
const now = Date.now();
if (now - state.lastUpdateTime < state.chartsUpdateInterval) {
return;
}
if (state.requestLog.length > 0) {
requestChart.data.labels = state.requestLog.slice(0, 10).map(r => r.timestamp).reverse();
requestChart.data.datasets[0].data = state.requestLog.slice(0, 10).map(() => state.lastMinuteRequests.length).reverse();
requestChart.update('none');
}
if (state.responseTimesSummary.length > 0) {
const responseTimeDistribution = [0, 0, 0, 0, 0];
state.responseTimesSummary.forEach(time => {
const index = Math.min(Math.floor(time / 100), 4);
responseTimeDistribution[index]++;
});
responseTimeChart.data.datasets[0].data = responseTimeDistribution;
responseTimeChart.update('none');
}
if (state.hourlyData.some(count => count > 0)) {
hourlyChart.data.datasets[0].data = state.hourlyData;
hourlyChart.update('none');
}
if (state.requestSizes.length > 0) {
responseSizeChart.data.labels = state.requestSizes.map((_, i) => i + 1);
responseSizeChart.data.datasets[0].data = state.requestSizes;
responseSizeChart.update('none');
}
state.lastUpdateTime = now;
}
function updateRequestsTable() {
const table = document.getElementById('requestsTable');
table.innerHTML = '';
state.requestLog.slice(0, 10).forEach(request => {
const row = table.insertRow(-1);
row.innerHTML = `
<td class="px-6 py-3">${request.timestamp}</td>
<td class="px-6 py-3">${request.model}</td>
<td class="px-6 py-3">${request.type}</td>
<td class="px-6 py-3">${request.status}</td>
<td class="px-6 py-3">${request.responseTime}ms</td>
<td class="px-6 py-3">${request.response}</td>
`;
});
}
function filterData() {
try {
const startTime = state.dateRange.start?.valueOf() || Date.now() - 86400000;
const endTime = state.dateRange.end?.valueOf() || Date.now();
const filtered = state.lastMinuteRequests.filter(time => {
const withinTimeRange = time >= startTime && time <= endTime;
const matchesModel = state.modelFilter === 'all' || state.modelUsage[state.modelFilter] !== undefined;
const matchesType = state.requestTypeFilter === 'all' || state.requestTypes[state.requestTypeFilter] !== undefined;
return withinTimeRange && matchesModel && matchesType;
});
return filtered || [];
} catch (error) {
console.error('Error filtering data:', error);
return [];
}
}
const FEED_URL = 'https://text.pollinations.ai/feed';
const FALLBACK_URL = 'https://text-api.pollinations.ai/feed';
function connectEventSource() {
let retryCount = 0;
const maxRetries = 3;
function tryConnect(url) {
const evtSource = new EventSource(url);
evtSource.onmessage = function (event) {
try {
const data = JSON.parse(event.data);
updateAnalytics(data);
updateRequestsTable(data);
document.getElementById('lastUpdated').innerText = new Date().toLocaleTimeString();
} catch (error) {
console.error('Error processing feed data:', error);
}
};
evtSource.onerror = function (error) {
console.error('EventSource failed:', error);
evtSource.close();
if (retryCount < maxRetries) {
retryCount++;
const nextUrl = retryCount === 1 ? FALLBACK_URL : FEED_URL;
console.log(`Retrying connection with ${nextUrl}`);
setTimeout(() => tryConnect(nextUrl), 5000);
} else {
const errorMessage = document.createElement('div');
errorMessage.className = 'fixed top-4 right-4 bg-red-500 text-white p-4 rounded shadow-lg';
errorMessage.textContent = 'Connection lost. Please refresh the page to try again.';
document.body.appendChild(errorMessage);
}
};
}
tryConnect(FEED_URL);
}
document.addEventListener('DOMContentLoaded', () => {
connectEventSource();
window.addEventListener('online', () => {
console.log('Back online, reconnecting...');
connectEventSource();
});
window.addEventListener('offline', () => {
console.log('Connection lost');
const errorMessage = document.createElement('div');
errorMessage.className = 'fixed top-4 right-4 bg-yellow-500 text-white p-4 rounded shadow-lg';
errorMessage.textContent = 'You are offline. Waiting for connection...';
document.body.appendChild(errorMessage);
});
});
$('#daterange').daterangepicker({
startDate: state.dateRange.start,
endDate: state.dateRange.end,
timePicker: true,
timePicker24Hour: true,
timePickerSeconds: true,
locale: {
format: 'MM/DD/YYYY HH:mm:ss'
}
}, function (start, end) {
state.dateRange.start = start;
state.dateRange.end = end;
updateUI();
});
document.getElementById('modelFilter').addEventListener('change', e => {
state.modelFilter = e.target.value;
updateUI();
});
document.getElementById('requestTypeFilter').addEventListener('change', e => {
state.requestTypeFilter = e.target.value;
updateUI();
});
document.getElementById('lastUpdated').innerText = new Date().toLocaleTimeString();
let animationFrameId = null;
function smoothUpdate() {
updateUI();
animationFrameId = requestAnimationFrame(smoothUpdate);
}
smoothUpdate();
window.addEventListener('unload', () => {
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
});</script>
</body>
</html>