vnai 2.0.7__py3-none-any.whl → 2.0.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
vnai/__init__.py CHANGED
@@ -1,275 +1,79 @@
1
- # vnai/__init__.py
2
- # Main entry point for vnai package
3
-
4
- import os
5
- import pathlib
6
- import json
7
- import time
8
- import threading
9
- import functools
1
+ _L='default'
2
+ _K='standard'
3
+ _J='accepted_agreement'
4
+ _I='environment.json'
5
+ _H='terms_agreement.txt'
6
+ _G='timestamp'
7
+ _F=False
8
+ _E='id'
9
+ _D='.vnstock'
10
+ _C='machine_id'
11
+ _B=None
12
+ _A=True
13
+ import os,pathlib,json,time,threading,functools
10
14
  from datetime import datetime
11
-
12
- # Import core functionality
13
- from vnai.beam.quota import guardian, optimize
14
- from vnai.beam.metrics import collector, capture
15
+ from vnai.beam.quota import guardian,optimize
16
+ from vnai.beam.metrics import collector,capture
15
17
  from vnai.beam.pulse import monitor
16
- from vnai.flow.relay import conduit, configure
18
+ from vnai.flow.relay import conduit,configure
17
19
  from vnai.flow.queue import buffer
18
20
  from vnai.scope.profile import inspector
19
- from vnai.scope.state import tracker, record
21
+ from vnai.scope.state import tracker,record
20
22
  import vnai.scope.promo
21
23
  from vnai.scope.promo import present
22
-
23
- # Constants for terms and conditions
24
- TC_VAR = "ACCEPT_TC"
25
- TC_VAL = "tôi đồng ý"
26
- TC_PATH = pathlib.Path.home() / ".vnstock" / "id" / "terms_agreement.txt"
27
-
28
- TERMS_AND_CONDITIONS = """
29
- Khi tiếp tục sử dụng Vnstock, bạn xác nhận rằng bạn đã đọc, hiểu và đồng ý với Chính sách quyền riêng tư và Điều khoản, điều kiện về giấy phép sử dụng Vnstock.
30
-
31
- Chi tiết:
32
- - Giấy phép sử dụng phần mềm: https://vnstocks.com/docs/tai-lieu/giay-phep-su-dung
33
- - Chính sách quyền riêng tư: https://vnstocks.com/docs/tai-lieu/chinh-sach-quyen-rieng-tu
34
- """
35
-
24
+ TC_VAR='ACCEPT_TC'
25
+ TC_VAL='tôi đồng ý'
26
+ TC_PATH=pathlib.Path.home()/_D/_E/_H
27
+ TERMS_AND_CONDITIONS='\nKhi tiếp tục sử dụng Vnstock, bạn xác nhận rằng bạn đã đọc, hiểu và đồng ý với Chính sách quyền riêng tư và Điều khoản, điều kiện về giấy phép sử dụng Vnstock.\n\nChi tiết:\n- Giấy phép sử dụng phần mềm: https://vnstocks.com/docs/tai-lieu/giay-phep-su-dung\n- Chính sách quyền riêng tư: https://vnstocks.com/docs/tai-lieu/chinh-sach-quyen-rieng-tu\n'
36
28
  class Core:
37
- """Core functionality for system optimization"""
38
-
39
- def __init__(self):
40
- """Initialize core"""
41
- self.initialized = False
42
- self.webhook_url = None
43
- self.init_time = datetime.now().isoformat()
44
- self.home_dir = pathlib.Path.home()
45
- self.project_dir = self.home_dir / ".vnstock"
46
- self.id_dir = self.project_dir / 'id'
47
- self.terms_file_path = TC_PATH
48
- self.system_info = None
49
-
50
- # Create necessary directories
51
- self.project_dir.mkdir(exist_ok=True)
52
- self.id_dir.mkdir(exist_ok=True)
53
-
54
- # Auto-initialize
55
- self.initialize()
56
-
57
- def initialize(self, webhook_url=None):
58
- """Initialize the system"""
59
- if self.initialized:
60
- return True
61
-
62
- # Check terms acceptance
63
- if not self._check_terms():
64
- self._accept_terms()
65
-
66
- # Set up vnstock environment
67
- from vnai.scope.profile import inspector
68
- inspector.setup_vnstock_environment()
69
-
70
- # Display content during initialization
71
- present()
72
-
73
- # Configure webhook if provided
74
- if webhook_url:
75
- self.webhook_url = webhook_url
76
- configure(webhook_url)
77
-
78
- # Record initialization
79
- record("initialization", {"timestamp": datetime.now().isoformat()})
80
-
81
- # Get system information ONCE and store it in the class
82
- self.system_info = inspector.examine()
83
-
84
- # Queue system data with optimal structure
85
- conduit.queue({
86
- "type": "system_info",
87
- "data": {
88
- "commercial": inspector.detect_commercial_usage(),
89
- "packages": inspector.scan_packages()
90
- }
91
- }, priority="high")
92
-
93
- self.initialized = True
94
- return True
95
-
96
- def _check_terms(self):
97
- """Check if terms have been accepted"""
98
- return os.path.exists(self.terms_file_path)
99
-
100
- def _accept_terms(self):
101
- """Record terms acceptance"""
102
- # Get system information
103
- system_info = inspector.examine()
104
-
105
- # Auto-accept terms
106
- if TC_VAR in os.environ and os.environ[TC_VAR] == TC_VAL:
107
- response = TC_VAL
108
- else:
109
- # For non-interactive environments, accept by default
110
- response = TC_VAL
111
- os.environ[TC_VAR] = TC_VAL
112
-
113
- # Store the acceptance with hardware info
114
- now = datetime.now()
115
- signed_agreement = (
116
- f"Người dùng có mã nhận dạng {system_info['machine_id']} đã chấp nhận "
117
- f"điều khoản & điều kiện sử dụng Vnstock lúc {now}\n"
118
- f"---\n\n"
119
- f"THÔNG TIN THIẾT BỊ: {json.dumps(system_info, indent=2)}\n\n"
120
- f"Đính kèm bản sao nội dung bạn đã đọc, hiểu rõ và đồng ý dưới đây:\n"
121
- f"{TERMS_AND_CONDITIONS}"
122
- )
123
-
124
- # Store the acceptance
125
- with open(self.terms_file_path, "w", encoding="utf-8") as f:
126
- f.write(signed_agreement)
127
-
128
- # Create the environment.json file that vnstock expects
129
- env_file = self.id_dir / "environment.json"
130
- env_data = {
131
- "accepted_agreement": True,
132
- "timestamp": now.isoformat(),
133
- "machine_id": system_info['machine_id']
134
- }
135
-
136
- with open(env_file, "w") as f:
137
- json.dump(env_data, f)
138
-
139
- return True
140
-
141
- def status(self):
142
- """Get system status"""
143
- return {
144
- "initialized": self.initialized,
145
- "health": monitor.report(),
146
- "metrics": tracker.get_metrics()
147
- # Environment information available via self.system_info
148
- }
149
-
150
- def configure_privacy(self, level="standard"):
151
- """Configure privacy settings"""
152
- from vnai.scope.state import tracker
153
- return tracker.setup_privacy(level)
154
-
155
-
156
- # Create singleton instance
157
- core = Core()
158
-
159
- # Backward support
160
- def tc_init(webhook_url=None):
161
- return core.initialize(webhook_url)
162
-
163
- # Public API
164
- def setup(webhook_url=None):
165
- """Setup vnai with optional webhook URL"""
166
- return core.initialize(webhook_url)
167
-
168
- def optimize_execution(resource_type="default"):
169
- """Decorator for optimizing function execution"""
170
- return optimize(resource_type)
171
-
172
- def agg_execution(resource_type="default"):
173
- """Decorator for aggregating function execution"""
174
- return optimize(resource_type, ad_cooldown=1500, content_trigger_threshold=100000)
175
-
176
- def measure_performance(module_type="function"):
177
- """Decorator for measuring function performance"""
178
- return capture(module_type)
179
-
180
- def accept_license_terms(terms_text=None):
181
- """Accept license terms and conditions"""
182
- if terms_text is None:
183
- terms_text = TERMS_AND_CONDITIONS
184
-
185
- # Get system information
186
- system_info = inspector.examine()
187
-
188
- # Record acceptance
189
- terms_file = pathlib.Path.home() / ".vnstock" / "id" / "terms_agreement.txt"
190
- os.makedirs(os.path.dirname(terms_file), exist_ok=True)
191
-
192
- with open(terms_file, "w", encoding="utf-8") as f:
193
- f.write(f"Terms accepted at {datetime.now().isoformat()}\n")
194
- f.write(f"System: {json.dumps(system_info)}\n\n")
195
- f.write(terms_text)
196
-
197
- return True
198
-
29
+ def __init__(self):self.initialized=_F;self.webhook_url=_B;self.init_time=datetime.now().isoformat();self.home_dir=pathlib.Path.home();self.project_dir=self.home_dir/_D;self.id_dir=self.project_dir/_E;self.terms_file_path=TC_PATH;self.system_info=_B;self.project_dir.mkdir(exist_ok=_A);self.id_dir.mkdir(exist_ok=_A);self.initialize()
30
+ def initialize(self,webhook_url=_B):
31
+ if self.initialized:return _A
32
+ if not self._check_terms():self._accept_terms()
33
+ from vnai.scope.profile import inspector;inspector.setup_vnstock_environment();present()
34
+ if webhook_url:self.webhook_url=webhook_url;configure(webhook_url)
35
+ record('initialization',{_G:datetime.now().isoformat()});self.system_info=inspector.examine();conduit.queue({'type':'system_info','data':{'commercial':inspector.detect_commercial_usage(),'packages':inspector.scan_packages()}},priority='high');self.initialized=_A;return _A
36
+ def _check_terms(self):return os.path.exists(self.terms_file_path)
37
+ def _accept_terms(self):
38
+ system_info=inspector.examine()
39
+ if TC_VAR in os.environ and os.environ[TC_VAR]==TC_VAL:response=TC_VAL
40
+ else:response=TC_VAL;os.environ[TC_VAR]=TC_VAL
41
+ now=datetime.now();signed_agreement=f"""Người dùng có mã nhận dạng {system_info[_C]} đã chấp nhận điều khoản & điều kiện sử dụng Vnstock lúc {now}
42
+ ---
43
+
44
+ THÔNG TIN THIẾT BỊ: {json.dumps(system_info,indent=2)}
45
+
46
+ Đính kèm bản sao nội dung bạn đã đọc, hiểu rõ và đồng ý dưới đây:
47
+ {TERMS_AND_CONDITIONS}"""
48
+ with open(self.terms_file_path,'w',encoding='utf-8')as f:f.write(signed_agreement)
49
+ env_file=self.id_dir/_I;env_data={_J:_A,_G:now.isoformat(),_C:system_info[_C]}
50
+ with open(env_file,'w')as f:json.dump(env_data,f)
51
+ return _A
52
+ def status(self):return{'initialized':self.initialized,'health':monitor.report(),'metrics':tracker.get_metrics()}
53
+ def configure_privacy(self,level=_K):from vnai.scope.state import tracker;return tracker.setup_privacy(level)
54
+ core=Core()
55
+ def tc_init(webhook_url=_B):return core.initialize(webhook_url)
56
+ def setup(webhook_url=_B):return core.initialize(webhook_url)
57
+ def optimize_execution(resource_type=_L):return optimize(resource_type)
58
+ def agg_execution(resource_type=_L):return optimize(resource_type,ad_cooldown=1500,content_trigger_threshold=100000)
59
+ def measure_performance(module_type='function'):return capture(module_type)
60
+ def accept_license_terms(terms_text=_B):
61
+ if terms_text is _B:terms_text=TERMS_AND_CONDITIONS
62
+ system_info=inspector.examine();terms_file=pathlib.Path.home()/_D/_E/_H;os.makedirs(os.path.dirname(terms_file),exist_ok=_A)
63
+ with open(terms_file,'w',encoding='utf-8')as f:f.write(f"Terms accepted at {datetime.now().isoformat()}\n");f.write(f"System: {json.dumps(system_info)}\n\n");f.write(terms_text)
64
+ return _A
199
65
  def accept_vnstock_terms():
200
- """Accept vnstock terms and create necessary files"""
201
- # Get system information
202
- from vnai.scope.profile import inspector
203
- system_info = inspector.examine()
204
-
205
- # Create necessary directories
206
- home_dir = pathlib.Path.home()
207
- project_dir = home_dir / ".vnstock"
208
- project_dir.mkdir(exist_ok=True)
209
- id_dir = project_dir / 'id'
210
- id_dir.mkdir(exist_ok=True)
211
-
212
- # Create environment.json file that vnstock looks for
213
- env_file = id_dir / "environment.json"
214
- env_data = {
215
- "accepted_agreement": True,
216
- "timestamp": datetime.now().isoformat(),
217
- "machine_id": system_info['machine_id']
218
- }
219
-
220
- try:
221
- with open(env_file, "w") as f:
222
- json.dump(env_data, f)
223
- print("Vnstock terms accepted successfully.")
224
- return True
225
- except Exception as e:
226
- print(f"Error accepting terms: {e}")
227
- return False
228
-
229
- def setup_for_colab():
230
- """Special setup for Google Colab environments"""
231
- from vnai.scope.profile import inspector
232
-
233
- # Immediate authentication for Colab
234
- inspector.detect_colab_with_delayed_auth(immediate=True)
235
-
236
- # Setup vnstock environment
237
- inspector.setup_vnstock_environment()
238
-
239
- return "Environment set up for Google Colab"
240
-
241
- def display_content():
242
- """Display promotional content appropriate for the current environment"""
243
- return present()
244
-
245
- def configure_privacy(level="standard"):
246
- """Configure privacy level for analytics data"""
247
- from vnai.scope.state import tracker
248
- return tracker.setup_privacy(level)
249
-
250
- def check_commercial_usage():
251
- """Check if running in commercial environment"""
252
- from vnai.scope.profile import inspector
253
- return inspector.detect_commercial_usage()
254
-
255
- def authenticate_for_persistence():
256
- """Authenticate to Google Drive for persistent settings (Colab only)"""
257
- from vnai.scope.profile import inspector
258
- return inspector.get_or_create_user_id()
259
-
66
+ from vnai.scope.profile import inspector;system_info=inspector.examine();home_dir=pathlib.Path.home();project_dir=home_dir/_D;project_dir.mkdir(exist_ok=_A);id_dir=project_dir/_E;id_dir.mkdir(exist_ok=_A);env_file=id_dir/_I;env_data={_J:_A,_G:datetime.now().isoformat(),_C:system_info[_C]}
67
+ try:
68
+ with open(env_file,'w')as f:json.dump(env_data,f)
69
+ print('Vnstock terms accepted successfully.');return _A
70
+ except Exception as e:print(f"Error accepting terms: {e}");return _F
71
+ def setup_for_colab():from vnai.scope.profile import inspector;inspector.detect_colab_with_delayed_auth(immediate=_A);inspector.setup_vnstock_environment();return'Environment set up for Google Colab'
72
+ def display_content():return present()
73
+ def configure_privacy(level=_K):from vnai.scope.state import tracker;return tracker.setup_privacy(level)
74
+ def check_commercial_usage():from vnai.scope.profile import inspector;return inspector.detect_commercial_usage()
75
+ def authenticate_for_persistence():from vnai.scope.profile import inspector;return inspector.get_or_create_user_id()
260
76
  def configure_webhook(webhook_id='80b8832b694a75c8ddc811ac7882a3de'):
261
- """Configure webhook URL for analytics data transmission
262
-
263
- This method should be called once during application initialization
264
- to set up the analytics endpoint. For security reasons, the URL should
265
- not be hardcoded in user-facing code.
266
- """
267
- if not webhook_id:
268
- return False
269
-
270
- from vnai.flow.relay import configure
271
- webhook_url = f'https://botbuilder.larksuite.com/api/trigger-webhook/{webhook_id}'
272
- return configure(webhook_url)
273
-
274
- # Set the webhook
77
+ if not webhook_id:return _F
78
+ from vnai.flow.relay import configure;webhook_url=f"https://botbuilder.larksuite.com/api/trigger-webhook/{webhook_id}";return configure(webhook_url)
275
79
  configure_webhook()
vnai/beam/__init__.py CHANGED
@@ -1,6 +1,3 @@
1
- # vnai/beam/__init__.py
2
- # System monitoring and resource management
3
-
4
- from vnai.beam.quota import guardian, optimize
5
- from vnai.beam.metrics import collector, capture
1
+ from vnai.beam.quota import guardian,optimize
2
+ from vnai.beam.metrics import collector,capture
6
3
  from vnai.beam.pulse import monitor
vnai/beam/metrics.py CHANGED
@@ -1,189 +1,64 @@
1
- # vnai/beam/metrics.py
2
- # System performance metrics collection (formerly analytics)
3
-
4
- import sys
5
- import time
6
- import threading
1
+ _K='success'
2
+ _J='buffer_size'
3
+ _I='request'
4
+ _H='rate_limit'
5
+ _G='execution_time'
6
+ _F='timestamp'
7
+ _E=False
8
+ _D='error'
9
+ _C=True
10
+ _B=None
11
+ _A='function'
12
+ import sys,time,threading
7
13
  from datetime import datetime
8
-
9
14
  class Collector:
10
- """Collects operation metrics for system optimization"""
11
-
12
- _instance = None
13
- _lock = threading.Lock()
14
-
15
- def __new__(cls):
16
- with cls._lock:
17
- if cls._instance is None:
18
- cls._instance = super(Collector, cls).__new__(cls)
19
- cls._instance._initialize()
20
- return cls._instance
21
-
22
- def _initialize(self):
23
- """Initialize collector"""
24
- self.metrics = {
25
- "function": [],
26
- "rate_limit": [],
27
- "request": [],
28
- "error": []
29
- }
30
- self.thresholds = {
31
- "buffer_size": 50,
32
- "error_threshold": 0.1,
33
- "performance_threshold": 5.0
34
- }
35
- self.function_count = 0
36
- self.colab_auth_triggered = False
37
- self.max_metric_length = 200 # Keep only the latest 200 entries
38
-
39
- def record(self, metric_type, data, priority=None):
40
- """Record operation metrics with deduplication and throttling"""
41
-
42
- # Ensure data is a dictionary
43
- if not isinstance(data, dict):
44
- data = {"value": str(data)}
45
-
46
- # Add timestamp if not present
47
- if "timestamp" not in data:
48
- data["timestamp"] = datetime.now().isoformat()
49
-
50
- # For non-system info, simplify and tag machine
51
- if metric_type != "system_info":
52
- data.pop("system", None)
53
- from vnai.scope.profile import inspector
54
- data["machine_id"] = inspector.fingerprint()
55
-
56
- # ==== THROTTLING ====
57
- now = time.time()
58
- last_time = self._last_record_time.get(metric_type, 0)
59
- if now - last_time < self.min_interval_per_type and priority != "high":
60
- return # Skip due to interval limit
61
- self._last_record_time[metric_type] = now
62
-
63
- # ==== DEDUPLICATION ====
64
- data_hash = hashlib.md5(json.dumps(data, sort_keys=True).encode()).hexdigest()
65
- if data_hash in self._recent_hashes and priority != "high":
66
- return # Skip duplicate
67
- self._recent_hashes.append(data_hash)
68
-
69
- # ==== RECORD LOGIC ====
70
- if metric_type in self.metrics:
71
- self.metrics[metric_type].append(data)
72
- # Prune oldest if too long
73
- if len(self.metrics[metric_type]) > self.max_metric_length:
74
- self.metrics[metric_type] = self.metrics[metric_type][-self.max_metric_length:]
75
- else:
76
- self.metrics["function"].append(data)
77
-
78
- # Function metric tracking (Colab trigger)
79
- if metric_type == "function":
80
- self.function_count += 1
81
- if self.function_count > 10 and not self.colab_auth_triggered and 'google.colab' in sys.modules:
82
- self.colab_auth_triggered = True
83
- threading.Thread(target=self._trigger_colab_auth, daemon=True).start()
84
-
85
- # Auto-send triggers
86
- if sum(len(metric_list) for metric_list in self.metrics.values()) >= self.thresholds["buffer_size"]:
87
- self._send_metrics()
88
- if priority == "high" or metric_type == "error":
89
- self._send_metrics()
90
-
91
- def _trigger_colab_auth(self):
92
- """Trigger Google Colab authentication in a background thread"""
93
- try:
94
- from vnai.scope.profile import inspector
95
- inspector.get_or_create_user_id()
96
- except:
97
- pass # Silently fail if there's an issue
98
-
99
- def _send_metrics(self):
100
- """Send collected metrics to data relay"""
101
- # Import here to avoid circular imports
102
- from vnai.flow.relay import track_function_call, track_rate_limit, track_api_request
103
-
104
- # Process and send each type of metric using the appropriate tracking function
105
- for metric_type, data_list in self.metrics.items():
106
- if not data_list:
107
- continue
108
-
109
- # Process each metric by type
110
- for data in data_list:
111
- try:
112
- if metric_type == "function":
113
- # Use the track_function_call interface
114
- track_function_call(
115
- function_name=data.get("function", "unknown"),
116
- source=data.get("source", "vnai"),
117
- execution_time=data.get("execution_time", 0),
118
- success=data.get("success", True),
119
- error=data.get("error"),
120
- args=data.get("args")
121
- )
122
- elif metric_type == "rate_limit":
123
- # Use the track_rate_limit interface
124
- track_rate_limit(
125
- source=data.get("source", "vnai"),
126
- limit_type=data.get("limit_type", "unknown"),
127
- limit_value=data.get("limit_value", 0),
128
- current_usage=data.get("current_usage", 0),
129
- is_exceeded=data.get("is_exceeded", False)
130
- )
131
- elif metric_type == "request":
132
- # Use the track_api_request interface
133
- track_api_request(
134
- endpoint=data.get("endpoint", "unknown"),
135
- source=data.get("source", "vnai"),
136
- method=data.get("method", "GET"),
137
- status_code=data.get("status_code", 200),
138
- execution_time=data.get("execution_time", 0),
139
- request_size=data.get("request_size", 0),
140
- response_size=data.get("response_size", 0)
141
- )
142
- except Exception as e:
143
- # If tracking fails, just continue with the next item
144
- continue
145
-
146
- # Clear the processed metrics
147
- self.metrics[metric_type] = []
148
-
149
- def get_metrics_summary(self):
150
- """Get summary of collected metrics"""
151
- return {
152
- metric_type: len(data_list)
153
- for metric_type, data_list in self.metrics.items()
154
- }
155
-
156
- # Create singleton instance
157
- collector = Collector()
158
-
159
- def capture(module_type="function"):
160
- """Decorator to capture metrics for any function"""
161
- def decorator(func):
162
- def wrapper(*args, **kwargs):
163
- start_time = time.time()
164
- success = False
165
- error = None
166
-
167
- try:
168
- result = func(*args, **kwargs)
169
- success = True
170
- return result
171
- except Exception as e:
172
- error = str(e)
173
- raise
174
- finally:
175
- execution_time = time.time() - start_time
176
-
177
- collector.record(
178
- module_type,
179
- {
180
- "function": func.__name__,
181
- "execution_time": execution_time,
182
- "success": success,
183
- "error": error,
184
- "timestamp": datetime.now().isoformat(),
185
- "args": str(args)[:100] if args else None # Truncate for privacy
186
- }
187
- )
188
- return wrapper
189
- return decorator
15
+ _instance=_B;_lock=threading.Lock()
16
+ def __new__(cls):
17
+ with cls._lock:
18
+ if cls._instance is _B:cls._instance=super(Collector,cls).__new__(cls);cls._instance._initialize()
19
+ return cls._instance
20
+ def _initialize(self):self.metrics={_A:[],_H:[],_I:[],_D:[]};self.thresholds={_J:50,'error_threshold':.1,'performance_threshold':5.};self.function_count=0;self.colab_auth_triggered=_E;self.max_metric_length=200
21
+ def record(self,metric_type,data,priority=_B):
22
+ A='high'
23
+ if not isinstance(data,dict):data={'value':str(data)}
24
+ if _F not in data:data[_F]=datetime.now().isoformat()
25
+ if metric_type!='system_info':data.pop('system',_B);from vnai.scope.profile import inspector;data['machine_id']=inspector.fingerprint()
26
+ now=time.time();last_time=self._last_record_time.get(metric_type,0)
27
+ if now-last_time<self.min_interval_per_type and priority!=A:return
28
+ self._last_record_time[metric_type]=now;data_hash=hashlib.md5(json.dumps(data,sort_keys=_C).encode()).hexdigest()
29
+ if data_hash in self._recent_hashes and priority!=A:return
30
+ self._recent_hashes.append(data_hash)
31
+ if metric_type in self.metrics:
32
+ self.metrics[metric_type].append(data)
33
+ if len(self.metrics[metric_type])>self.max_metric_length:self.metrics[metric_type]=self.metrics[metric_type][-self.max_metric_length:]
34
+ else:self.metrics[_A].append(data)
35
+ if metric_type==_A:
36
+ self.function_count+=1
37
+ if self.function_count>10 and not self.colab_auth_triggered and'google.colab'in sys.modules:self.colab_auth_triggered=_C;threading.Thread(target=self._trigger_colab_auth,daemon=_C).start()
38
+ if sum(len(metric_list)for metric_list in self.metrics.values())>=self.thresholds[_J]:self._send_metrics()
39
+ if priority==A or metric_type==_D:self._send_metrics()
40
+ def _trigger_colab_auth(self):
41
+ try:from vnai.scope.profile import inspector;inspector.get_or_create_user_id()
42
+ except:pass
43
+ def _send_metrics(self):
44
+ C='vnai';B='source';A='unknown';from vnai.flow.relay import track_function_call,track_rate_limit,track_api_request
45
+ for(metric_type,data_list)in self.metrics.items():
46
+ if not data_list:continue
47
+ for data in data_list:
48
+ try:
49
+ if metric_type==_A:track_function_call(function_name=data.get(_A,A),source=data.get(B,C),execution_time=data.get(_G,0),success=data.get(_K,_C),error=data.get(_D),args=data.get('args'))
50
+ elif metric_type==_H:track_rate_limit(source=data.get(B,C),limit_type=data.get('limit_type',A),limit_value=data.get('limit_value',0),current_usage=data.get('current_usage',0),is_exceeded=data.get('is_exceeded',_E))
51
+ elif metric_type==_I:track_api_request(endpoint=data.get('endpoint',A),source=data.get(B,C),method=data.get('method','GET'),status_code=data.get('status_code',200),execution_time=data.get(_G,0),request_size=data.get('request_size',0),response_size=data.get('response_size',0))
52
+ except Exception as e:continue
53
+ self.metrics[metric_type]=[]
54
+ def get_metrics_summary(self):return{metric_type:len(data_list)for(metric_type,data_list)in self.metrics.items()}
55
+ collector=Collector()
56
+ def capture(module_type=_A):
57
+ def decorator(func):
58
+ def wrapper(*args,**kwargs):
59
+ start_time=time.time();success=_E;error=_B
60
+ try:result=func(*args,**kwargs);success=_C;return result
61
+ except Exception as e:error=str(e);raise
62
+ finally:execution_time=time.time()-start_time;collector.record(module_type,{_A:func.__name__,_G:execution_time,_K:success,_D:error,_F:datetime.now().isoformat(),'args':str(args)[:100]if args else _B})
63
+ return wrapper
64
+ return decorator