-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathstats.py
More file actions
217 lines (184 loc) · 7.97 KB
/
stats.py
File metadata and controls
217 lines (184 loc) · 7.97 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
"""
MasterCryptoFarmBot — Aggregated statistics and reporting.
Collects runtime metrics from all managed bot instances and produces
summary reports, per-bot breakdowns, and exportable data.
"""
import json
import time
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional
@dataclass
class BotMetrics:
bot_id: str
name: str
module: str
total_cycles: int = 0
successful_cycles: int = 0
failed_cycles: int = 0
total_uptime_seconds: float = 0.0
total_tasks_executed: int = 0
rewards_collected: float = 0.0
errors: List[str] = field(default_factory=list)
last_activity: float = 0.0
@property
def success_rate(self) -> float:
if self.total_cycles == 0:
return 0.0
return self.successful_cycles / self.total_cycles * 100.0
@property
def avg_cycle_time(self) -> float:
if self.total_cycles == 0:
return 0.0
return self.total_uptime_seconds / self.total_cycles
def to_dict(self) -> Dict[str, Any]:
return {
"bot_id": self.bot_id,
"name": self.name,
"module": self.module,
"total_cycles": self.total_cycles,
"successful_cycles": self.successful_cycles,
"failed_cycles": self.failed_cycles,
"success_rate": round(self.success_rate, 2),
"total_uptime_seconds": round(self.total_uptime_seconds, 2),
"avg_cycle_time": round(self.avg_cycle_time, 2),
"total_tasks_executed": self.total_tasks_executed,
"rewards_collected": self.rewards_collected,
"recent_errors": self.errors[-5:] if self.errors else [],
"last_activity": self.last_activity,
}
@dataclass
class AggregatedStats:
total_bots: int = 0
active_bots: int = 0
total_cycles: int = 0
total_successful: int = 0
total_failed: int = 0
total_uptime_hours: float = 0.0
total_rewards: float = 0.0
overall_success_rate: float = 0.0
module_distribution: Dict[str, int] = field(default_factory=dict)
top_performers: List[Dict[str, Any]] = field(default_factory=list)
timestamp: float = field(default_factory=time.time)
def to_dict(self) -> Dict[str, Any]:
return {
"total_bots": self.total_bots,
"active_bots": self.active_bots,
"total_cycles": self.total_cycles,
"total_successful": self.total_successful,
"total_failed": self.total_failed,
"total_uptime_hours": round(self.total_uptime_hours, 2),
"total_rewards": self.total_rewards,
"overall_success_rate": round(self.overall_success_rate, 2),
"module_distribution": self.module_distribution,
"top_performers": self.top_performers,
"timestamp": self.timestamp,
}
class StatsCollector:
"""
Collects and aggregates runtime statistics across all farming bots.
Provides per-bot breakdowns, module-level summaries, and export functionality.
"""
def __init__(self):
self._metrics: Dict[str, BotMetrics] = {}
self._snapshots: List[AggregatedStats] = []
def register_bot(self, bot_id: str, name: str, module: str) -> BotMetrics:
"""Register a bot for metrics tracking."""
if bot_id in self._metrics:
return self._metrics[bot_id]
metrics = BotMetrics(bot_id=bot_id, name=name, module=module)
self._metrics[bot_id] = metrics
return metrics
def record_cycle(
self, bot_id: str, success: bool, duration_seconds: float = 0.0
) -> None:
"""Record a completed farming cycle for a bot."""
m = self._get_metrics(bot_id)
m.total_cycles += 1
if success:
m.successful_cycles += 1
else:
m.failed_cycles += 1
m.total_uptime_seconds += duration_seconds
m.last_activity = time.time()
def record_task(self, bot_id: str, count: int = 1) -> None:
"""Record executed tasks for a bot."""
m = self._get_metrics(bot_id)
m.total_tasks_executed += count
m.last_activity = time.time()
def record_reward(self, bot_id: str, amount: float) -> None:
"""Record collected rewards for a bot."""
m = self._get_metrics(bot_id)
m.rewards_collected += amount
m.last_activity = time.time()
def record_error(self, bot_id: str, error: str) -> None:
"""Record an error occurrence for a bot."""
m = self._get_metrics(bot_id)
m.errors.append(error)
m.last_activity = time.time()
def get_bot_metrics(self, bot_id: str) -> Optional[BotMetrics]:
return self._metrics.get(bot_id)
def get_all_metrics(self) -> List[BotMetrics]:
return list(self._metrics.values())
def aggregate(self, active_bot_ids: Optional[List[str]] = None) -> AggregatedStats:
"""Compute aggregated statistics across all tracked bots."""
stats = AggregatedStats()
stats.total_bots = len(self._metrics)
module_counter: Counter = Counter()
bot_scores: List[tuple] = []
for m in self._metrics.values():
stats.total_cycles += m.total_cycles
stats.total_successful += m.successful_cycles
stats.total_failed += m.failed_cycles
stats.total_uptime_hours += m.total_uptime_seconds / 3600.0
stats.total_rewards += m.rewards_collected
module_counter[m.module] += 1
if active_bot_ids and m.bot_id in active_bot_ids:
stats.active_bots += 1
bot_scores.append((m.success_rate, m.total_cycles, m.bot_id, m.name))
if stats.total_cycles > 0:
stats.overall_success_rate = stats.total_successful / stats.total_cycles * 100.0
stats.module_distribution = dict(module_counter.most_common())
bot_scores.sort(key=lambda x: (-x[0], -x[1]))
stats.top_performers = [
{"bot_id": bid, "name": name, "success_rate": rate, "cycles": cycles}
for rate, cycles, bid, name in bot_scores[:5]
]
self._snapshots.append(stats)
return stats
def get_module_summary(self) -> Dict[str, Dict[str, Any]]:
"""Group metrics by module and return per-module summaries."""
module_map: Dict[str, List[BotMetrics]] = defaultdict(list)
for m in self._metrics.values():
module_map[m.module].append(m)
result: Dict[str, Dict[str, Any]] = {}
for module, metrics_list in module_map.items():
total = sum(m.total_cycles for m in metrics_list)
success = sum(m.successful_cycles for m in metrics_list)
rewards = sum(m.rewards_collected for m in metrics_list)
result[module] = {
"bot_count": len(metrics_list),
"total_cycles": total,
"success_rate": round(success / total * 100 if total else 0, 2),
"total_rewards": rewards,
}
return result
def export_json(self, filepath: str) -> None:
"""Export all metrics to a JSON file."""
data = {
"aggregate": self.aggregate().to_dict(),
"bots": {bid: m.to_dict() for bid, m in self._metrics.items()},
"module_summary": self.get_module_summary(),
}
Path(filepath).write_text(
json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8"
)
def reset(self) -> None:
"""Clear all collected metrics."""
self._metrics.clear()
self._snapshots.clear()
def _get_metrics(self, bot_id: str) -> BotMetrics:
if bot_id not in self._metrics:
raise KeyError(f"Bot '{bot_id}' not registered for stats tracking")
return self._metrics[bot_id]