Spaces:
Paused
Paused
File size: 2,174 Bytes
54a11dd | 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 | // CPU monitoring utility for HuggingFace free tier
class CPUMonitor {
private cpuUsageHistory: number[] = [];
private maxCpuThreshold = 80; // Maximum CPU percentage before throttling
private throttleActive = false;
constructor() {
this.startMonitoring();
}
private startMonitoring() {
if (typeof window === 'undefined') return; // Server-side only
setInterval(() => {
this.checkCPUUsage();
}, 1000); // Check every second
}
private async checkCPUUsage() {
// Simple CPU usage estimation based on frame timing
const start = performance.now();
await new Promise(resolve => setTimeout(resolve, 10));
const duration = performance.now() - start;
// If tasks take longer than expected, assume high CPU
const estimatedCPU = Math.min(100, (duration / 10) * 100);
this.cpuUsageHistory.push(estimatedCPU);
if (this.cpuUsageHistory.length > 5) {
this.cpuUsageHistory.shift();
}
const avgCPU = this.cpuUsageHistory.reduce((a, b) => a + b, 0) / this.cpuUsageHistory.length;
if (avgCPU > this.maxCpuThreshold && !this.throttleActive) {
console.warn(`[CPU Monitor] High CPU usage detected: ${avgCPU.toFixed(1)}%. Activating throttling.`);
this.activateThrottling();
} else if (avgCPU < this.maxCpuThreshold * 0.7 && this.throttleActive) {
console.log(`[CPU Monitor] CPU usage normalized: ${avgCPU.toFixed(1)}%. Deactivating throttling.`);
this.deactivateThrottling();
}
}
private activateThrottling() {
this.throttleActive = true;
// Dispatch event for components to react
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('cpu-throttle-active'));
}
}
private deactivateThrottling() {
this.throttleActive = false;
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('cpu-throttle-inactive'));
}
}
public isThrottling(): boolean {
return this.throttleActive;
}
public getCurrentCPU(): number {
return this.cpuUsageHistory[this.cpuUsageHistory.length - 1] || 0;
}
}
export const cpuMonitor = new CPUMonitor();
|