vnai 0.1.4__py3-none-any.whl → 2.0.1__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,319 +1,270 @@
1
- import os
2
- import pathlib
3
- import importlib.metadata
4
- import requests
5
- import psutil
6
- import platform
7
- import uuid
8
- import sys
9
- import socket
10
- import json
11
- import base64
12
- from cryptography.fernet import Fernet
13
-
14
- TC_VAR = "ACCEPT_TC"
15
- TC_VAL = "tôi đồng ý"
16
-
17
- lmt = os.path.sep
18
- HOME_DIR = pathlib.Path.home()
19
- PROJECT_DIR = HOME_DIR / ".vnstock"
20
- ID_DIR = PROJECT_DIR / 'id'
21
- TG = b'gAAAAABmOPXPmFYXs94INEralMxhR38geFp91TZRLP29C41OoO0k7D7QiXIR2nWl5PCEoQCKECZw8b-Xeek3oqT6LcpcpJsAPyOGOBTX5cw_r5Mv0o8SBLa53jOeuVAwCAhId_BpMtOO'
22
- TC_PATH = ID_DIR / "terms_agreement.txt"
23
-
24
- TERMS_AND_CONDITIONS = """
25
- Khi tiếp tục sử dụng Vnstock3, 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 Vnstock3.\n
26
- Chi tiết:\n
27
- - Giấy phép sử dụng phần mềm: https://vnstocks.com/docs/tai-lieu/giay-phep-su-dung
28
- - Chính sách quyền riêng tư: https://vnstocks.com/docs/tai-lieu/chinh-sach-quyen-rieng-tu
29
- """
30
-
31
- class VnstockInitializer:
32
- def __init__(self, target, tc=TERMS_AND_CONDITIONS):
33
- self.terms_and_conditions = tc
34
- self.home_dir = HOME_DIR
35
- self.project_dir = PROJECT_DIR
36
- self.id_dir = ID_DIR
37
- self.terms_file_path = TC_PATH
38
- self.env_config = ID_DIR / "environment.json"
39
- self.RH = 'asejruyy^&%$#W2vX>NfwrevDRESWR'
40
- self.LH = 'YMAnhuytr%$59u90y7j-mjhgvyFTfbiuUYH'
41
-
42
- # Create the project directory if it doesn't exist
43
- self.project_dir.mkdir(exist_ok=True)
44
- self.id_dir.mkdir(exist_ok=True)
45
- self.target = target
46
-
47
- kb = (str(self.project_dir).split(lmt)[-1] + str(self.id_dir).split(lmt)[-1] + str(self.terms_file_path).split(lmt)[-1]).ljust(32)[:32].encode('utf-8')
48
- kb64 = base64.urlsafe_b64encode(kb)
49
- self.cph = Fernet(kb64)
50
-
51
- def system_info(self):
52
- """
53
- Gathers information about the environment and system.
54
- """
55
- # Generate UUID
56
- machine_id = str(uuid.uuid4())
57
-
58
- # Environment (modify to detect your specific frameworks)
59
- try:
60
- from IPython import get_ipython
61
- if 'IPKernelApp' not in get_ipython().config: # Check if not in IPython kernel
62
- if sys.stdout.isatty():
63
- environment = "Terminal"
64
- else:
65
- environment = "Other" # Non-interactive environment (e.g., script executed from an IDE)
66
- else:
67
- environment = "Jupyter"
68
- except (ImportError, AttributeError):
69
- # Fallback if IPython isn't installed or other checks fail
70
- if sys.stdout.isatty():
71
- environment = "Terminal"
72
- else:
73
- environment = "Other"
74
-
75
- try:
76
- if 'google.colab' in sys.modules:
77
- hosting_service = "Google Colab"
78
- elif 'CODESPACE_NAME' in os.environ:
79
- hosting_service = "Github Codespace"
80
- elif 'GITPOD_WORKSPACE_CLUSTER_HOST' in os.environ:
81
- hosting_service = "Gitpod"
82
- elif 'REPLIT_USER' in os.environ:
83
- hosting_service = "Replit"
84
- elif 'KAGGLE_CONTAINER_NAME' in os.environ:
85
- hosting_service = "Kaggle"
86
- elif '.hf.space' in os.environ['SPACE_HOST']:
87
- hosting_service = "Hugging Face Spaces"
88
- except:
89
- hosting_service = "Local or Unknown"
90
-
91
- # System information
92
- os_info = platform.uname()
93
-
94
- # CPU information
95
- cpu_arch = platform.processor()
96
- cpu_logical_cores = psutil.cpu_count(logical=True)
97
- cpu_cores = psutil.cpu_count(logical=False)
98
-
99
- # Memory information
100
- ram_total = psutil.virtual_memory().total / (1024**3) # GB
101
- ram_available = psutil.virtual_memory().available / (1024**3) # GB
102
-
103
- try:
104
- hostname = socket.gethostname()
105
- IPAddr = socket.gethostbyname(hostname)
106
- except socket.gaierror:
107
- hostname = "unknown"
108
- IPAddr = "127.0.0.1" # Fallback to localhost
109
-
110
- mac = ':'.join(['{:02x}'.format((uuid.getnode() >> elements) & 0xff) for elements in range(0, 2 * 6, 2)])
111
-
112
- # Combine information into a dictionary
113
- info = {
114
- "uuid": machine_id,
115
- "environment": environment,
116
- "hosting_service": hosting_service,
117
- "python_version": platform.python_version(),
118
- "os_name": os_info.system,
119
- "os_version": os_info.version,
120
- "machine": os_info.machine,
121
- "cpu_model": cpu_arch,
122
- "cpu_cores": cpu_cores,
123
- "cpu_logical_cores": cpu_logical_cores,
124
- "ram_total": round(ram_total, 1),
125
- "ram_available": round(ram_available, 1),
126
- "local_ip": IPAddr,
127
- "mac_address": mac,
128
- }
129
-
130
- return info
131
-
132
- def show_terms_and_conditions(self):
133
- """
134
- Displays terms and conditions and asks for acceptance.
135
- """
136
- print(self.terms_and_conditions)
137
-
138
- # check if os.environ[TC_VAR] exist and equal to tôi đồng ý
139
- if TC_VAR in os.environ and os.environ[TC_VAR] == TC_VAL:
140
- response = TC_VAL
141
- else:
142
- response = TC_VAL
143
- os.environ[TC_VAR] = TC_VAL
144
-
145
- from datetime import datetime
146
- # get now time in string
147
- now = datetime.now()
148
- HARDWARE = self.system_info()
149
- # VERSION = pkg_resources.get_distribution('vnstock').version
150
-
151
- VERSION = None
152
- try:
153
- VERSION = importlib.metadata.version('vnstock')
154
- except importlib.metadata.PackageNotFoundError:
155
- # print("Package 'vnstock' not found")
156
- pass
157
-
158
- # parse HARDWARE to string to store in the file
159
- signed_aggreement = f"MÔ TẢ:\nNgười dùng có mã nhận dạng {HARDWARE['uuid']} đã chấp nhận điều khoản & điều kiện sử dụng Vnstock lúc {now}\n---\n\nTHÔNG TIN THIẾT BỊ: {str(HARDWARE)}\n\nĐính kèm bản sao nội dung bạn đã đọc, hiểu rõ và đồng ý dưới đây:\n{self.terms_and_conditions}"
160
-
161
- # Store the acceptance
162
- with open(self.terms_file_path, "w", encoding="utf-8") as f:
163
- f.write(signed_aggreement)
164
- return True
165
-
166
- def log_analytics_data(self):
167
- """
168
- Sends analytics data to a webhook.
169
- """
170
- HARDWARE = self.system_info()
171
- EP = 'gAAAAABmOPNX4DJAsImlkzvtcyezBxr4UcK_HpCOgz-GOF9yBDP99tWNFYM_ZjeC22kNqmX3urZa467BC1D2fPLJrUkp6rQizYEMK4m196ZlOzUhwCbfjdvURXesL3LC7DofOgwWjNyltPQ8AnPyB4YUMnnAwnFooQ=='
172
- TGE = self.cph.decrypt(self.target).decode('utf-8')
173
- WH = f"{self.cph.decrypt(((self.RH+EP+self.RH)[30:-30]).encode()).decode('utf-8')}{TGE}"
174
-
175
- data = {
176
- "systems": HARDWARE,
177
- "accepted_agreement": True,
178
- "installed_packages": self.packages_installed(),
179
- }
180
-
181
- # save data to a json file in id folder
182
- with open(self.env_config, "w", encoding="utf-8") as f:
183
- f.write(json.dumps(data, indent=4))
184
-
185
- try:
186
- response = requests.post(WH, json=data)
187
- except:
188
- raise SystemExit("Không thể gửi dữ liệu phân tích. Vui lòng kiểm tra kết nối mạng và thử lại sau.")
189
-
190
- def check_terms_accepted(self):
191
- """
192
- Checks if terms and conditions are accepted.
193
- """
194
- if not self.env_config.exists() or not self.terms_file_path.exists():
195
- # If not, ask for acceptance
196
- accepted = self.show_terms_and_conditions()
197
- if not accepted:
198
- raise SystemExit("Điều khoản và điều kiện không được chấp nhận. Không thể tiếp tục.")
199
- else:
200
- self.log_analytics_data()
201
-
202
- def packages_installed(self):
203
- """
204
- Checks installed packages and returns a dictionary.
205
- """
206
- # Define package mapping
207
- package_mapping = {
208
- "vnstock_family": [
209
- "vnstock",
210
- "vnstock3",
211
- "vnstock_ezchart",
212
- "vnstock_data_pro"
213
- "vnstock_market_data_pipeline",
214
- "vnstock_ta",
215
- "vnii",
216
- "vnai",
217
- ],
218
- "analytics": [
219
- "openbb",
220
- "pandas_ta"
221
- ],
222
- "static_charts": [
223
- "matplotlib",
224
- "seaborn",
225
- "altair"
226
- ],
227
- "dashboard": [
228
- "streamlit",
229
- "voila",
230
- "panel",
231
- "shiny",
232
- "dash",
233
- ],
234
- "interactive_charts": [
235
- "mplfinance",
236
- "plotly",
237
- "plotline",
238
- "bokeh",
239
- "pyecharts",
240
- "highcharts-core",
241
- "highcharts-stock",
242
- "mplchart",
243
- ],
244
- "datafeed": [
245
- "yfinance",
246
- "alpha_vantage",
247
- "pandas-datareader",
248
- "investpy",
249
- ],
250
- "official_api": [
251
- "ssi-fc-data",
252
- "ssi-fctrading"
253
- ],
254
- "risk_return": [
255
- "pyfolio",
256
- "empyrical",
257
- "quantstats",
258
- "financetoolkit",
259
- ],
260
- "machine_learning": [
261
- "scipy",
262
- "sklearn",
263
- "statsmodels",
264
- "pytorch",
265
- "tensorflow",
266
- "keras",
267
- "xgboost"
268
- ],
269
- "indicators": [
270
- "stochastic",
271
- "talib",
272
- "tqdm",
273
- "finta",
274
- "financetoolkit",
275
- "tulipindicators"
276
- ],
277
- "backtesting": [
278
- "vectorbt",
279
- "backtesting",
280
- "bt",
281
- "zipline",
282
- "pyalgotrade",
283
- "backtrader",
284
- "pybacktest",
285
- "fastquant",
286
- "lean",
287
- "ta",
288
- "finmarketpy",
289
- "qstrader",
290
- ],
291
- "server": [
292
- "fastapi",
293
- "flask",
294
- "uvicorn",
295
- "gunicorn"
296
- ],
297
- "framework": [
298
- "lightgbm",
299
- "catboost",
300
- "django",
301
- ]
302
- }
303
-
304
- installed_packages = {}
305
-
306
- for category, packages in package_mapping.items():
307
- installed_packages[category] = []
308
- for pkg in packages:
309
- try:
310
- version = importlib.metadata.version(pkg)
311
- installed_packages[category].append((pkg, version))
312
- except importlib.metadata.PackageNotFoundError:
313
- pass
314
-
315
- return installed_packages
316
-
317
- def tc_init():
318
- vnstock_initializer = VnstockInitializer(TG)
319
- vnstock_initializer.check_terms_accepted()
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
10
+ 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.pulse import monitor
16
+ from vnai.flow.relay import conduit, configure
17
+ from vnai.flow.queue import buffer
18
+ from vnai.scope.profile import inspector
19
+ from vnai.scope.state import tracker, record
20
+ from vnai.scope.promo import present
21
+
22
+ # Constants for terms and conditions
23
+ TC_VAR = "ACCEPT_TC"
24
+ TC_VAL = "tôi đồng ý"
25
+ TC_PATH = pathlib.Path.home() / ".vnstock" / "id" / "terms_agreement.txt"
26
+
27
+ TERMS_AND_CONDITIONS = """
28
+ 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 và Điều khoản, điều kiện về giấy phép sử dụng Vnstock.
29
+
30
+ Chi tiết:
31
+ - Giấy phép sử dụng phần mềm: https://vnstocks.com/docs/tai-lieu/giay-phep-su-dung
32
+ - Chính sách quyền riêng tư: https://vnstocks.com/docs/tai-lieu/chinh-sach-quyen-rieng-tu
33
+ """
34
+
35
+ class Core:
36
+ """Core functionality for system optimization"""
37
+
38
+ def __init__(self):
39
+ """Initialize core"""
40
+ self.initialized = False
41
+ self.webhook_url = None
42
+ self.init_time = datetime.now().isoformat()
43
+ self.home_dir = pathlib.Path.home()
44
+ self.project_dir = self.home_dir / ".vnstock"
45
+ self.id_dir = self.project_dir / 'id'
46
+ self.terms_file_path = TC_PATH
47
+ self.system_info = None
48
+
49
+ # Create necessary directories
50
+ self.project_dir.mkdir(exist_ok=True)
51
+ self.id_dir.mkdir(exist_ok=True)
52
+
53
+ # Auto-initialize
54
+ self.initialize()
55
+
56
+ def initialize(self, webhook_url=None):
57
+ """Initialize the system"""
58
+ if self.initialized:
59
+ return True
60
+
61
+ # Check terms acceptance
62
+ if not self._check_terms():
63
+ self._accept_terms()
64
+
65
+ # Set up vnstock environment
66
+ from vnai.scope.profile import inspector
67
+ inspector.setup_vnstock_environment()
68
+
69
+ # Display content during initialization
70
+ present()
71
+
72
+ # Configure webhook if provided
73
+ if webhook_url:
74
+ self.webhook_url = webhook_url
75
+ configure(webhook_url)
76
+
77
+ # Record initialization
78
+ record("initialization", {"timestamp": datetime.now().isoformat()})
79
+
80
+ # Get system information ONCE and store it in the class
81
+ self.system_info = inspector.examine()
82
+
83
+ # Queue system data with optimal structure
84
+ conduit.queue({
85
+ "type": "system_info",
86
+ "data": {
87
+ "commercial": inspector.detect_commercial_usage(),
88
+ "packages": inspector.scan_packages()
89
+ }
90
+ }, priority="high")
91
+
92
+ self.initialized = True
93
+ return True
94
+
95
+ def _check_terms(self):
96
+ """Check if terms have been accepted"""
97
+ return os.path.exists(self.terms_file_path)
98
+
99
+ def _accept_terms(self):
100
+ """Record terms acceptance"""
101
+ # Get system information
102
+ system_info = inspector.examine()
103
+
104
+ # Auto-accept terms
105
+ if TC_VAR in os.environ and os.environ[TC_VAR] == TC_VAL:
106
+ response = TC_VAL
107
+ else:
108
+ # For non-interactive environments, accept by default
109
+ response = TC_VAL
110
+ os.environ[TC_VAR] = TC_VAL
111
+
112
+ # Store the acceptance with hardware info
113
+ now = datetime.now()
114
+ signed_agreement = (
115
+ f"Người dùng có mã nhận dạng {system_info['machine_id']} đã chấp nhận "
116
+ f"điều khoản & điều kiện sử dụng Vnstock lúc {now}\n"
117
+ f"---\n\n"
118
+ f"THÔNG TIN THIẾT BỊ: {json.dumps(system_info, indent=2)}\n\n"
119
+ f"Đính kèm bản sao nội dung bạn đã đọc, hiểu rõ và đồng ý dưới đây:\n"
120
+ f"{TERMS_AND_CONDITIONS}"
121
+ )
122
+
123
+ # Store the acceptance
124
+ with open(self.terms_file_path, "w", encoding="utf-8") as f:
125
+ f.write(signed_agreement)
126
+
127
+ # Create the environment.json file that vnstock expects
128
+ env_file = self.id_dir / "environment.json"
129
+ env_data = {
130
+ "accepted_agreement": True,
131
+ "timestamp": now.isoformat(),
132
+ "machine_id": system_info['machine_id']
133
+ }
134
+
135
+ with open(env_file, "w") as f:
136
+ json.dump(env_data, f)
137
+
138
+ return True
139
+
140
+ def status(self):
141
+ """Get system status"""
142
+ return {
143
+ "initialized": self.initialized,
144
+ "health": monitor.report(),
145
+ "metrics": tracker.get_metrics()
146
+ # Environment information available via self.system_info
147
+ }
148
+
149
+ def configure_privacy(self, level="standard"):
150
+ """Configure privacy settings"""
151
+ from vnai.scope.state import tracker
152
+ return tracker.setup_privacy(level)
153
+
154
+
155
+ # Create singleton instance
156
+ core = Core()
157
+
158
+ # Backward support
159
+ def tc_init(webhook_url=None):
160
+ return core.initialize(webhook_url)
161
+
162
+ # Public API
163
+ def setup(webhook_url=None):
164
+ """Setup vnai with optional webhook URL"""
165
+ return core.initialize(webhook_url)
166
+
167
+ def optimize_execution(resource_type="default"):
168
+ """Decorator for optimizing function execution"""
169
+ return optimize(resource_type)
170
+
171
+ def measure_performance(module_type="function"):
172
+ """Decorator for measuring function performance"""
173
+ return capture(module_type)
174
+
175
+ def accept_license_terms(terms_text=None):
176
+ """Accept license terms and conditions"""
177
+ if terms_text is None:
178
+ terms_text = TERMS_AND_CONDITIONS
179
+
180
+ # Get system information
181
+ system_info = inspector.examine()
182
+
183
+ # Record acceptance
184
+ terms_file = pathlib.Path.home() / ".vnstock" / "id" / "terms_agreement.txt"
185
+ os.makedirs(os.path.dirname(terms_file), exist_ok=True)
186
+
187
+ with open(terms_file, "w", encoding="utf-8") as f:
188
+ f.write(f"Terms accepted at {datetime.now().isoformat()}\n")
189
+ f.write(f"System: {json.dumps(system_info)}\n\n")
190
+ f.write(terms_text)
191
+
192
+ return True
193
+
194
+ def accept_vnstock_terms():
195
+ """Accept vnstock terms and create necessary files"""
196
+ # Get system information
197
+ from vnai.scope.profile import inspector
198
+ system_info = inspector.examine()
199
+
200
+ # Create necessary directories
201
+ home_dir = pathlib.Path.home()
202
+ project_dir = home_dir / ".vnstock"
203
+ project_dir.mkdir(exist_ok=True)
204
+ id_dir = project_dir / 'id'
205
+ id_dir.mkdir(exist_ok=True)
206
+
207
+ # Create environment.json file that vnstock looks for
208
+ env_file = id_dir / "environment.json"
209
+ env_data = {
210
+ "accepted_agreement": True,
211
+ "timestamp": datetime.now().isoformat(),
212
+ "machine_id": system_info['machine_id']
213
+ }
214
+
215
+ try:
216
+ with open(env_file, "w") as f:
217
+ json.dump(env_data, f)
218
+ print("Vnstock terms accepted successfully.")
219
+ return True
220
+ except Exception as e:
221
+ print(f"Error accepting terms: {e}")
222
+ return False
223
+
224
+ def setup_for_colab():
225
+ """Special setup for Google Colab environments"""
226
+ from vnai.scope.profile import inspector
227
+
228
+ # Immediate authentication for Colab
229
+ inspector.detect_colab_with_delayed_auth(immediate=True)
230
+
231
+ # Setup vnstock environment
232
+ inspector.setup_vnstock_environment()
233
+
234
+ return "Environment set up for Google Colab"
235
+
236
+ def display_content():
237
+ """Display promotional content appropriate for the current environment"""
238
+ return present()
239
+
240
+ def configure_privacy(level="standard"):
241
+ """Configure privacy level for analytics data"""
242
+ from vnai.scope.state import tracker
243
+ return tracker.setup_privacy(level)
244
+
245
+ def check_commercial_usage():
246
+ """Check if running in commercial environment"""
247
+ from vnai.scope.profile import inspector
248
+ return inspector.detect_commercial_usage()
249
+
250
+ def authenticate_for_persistence():
251
+ """Authenticate to Google Drive for persistent settings (Colab only)"""
252
+ from vnai.scope.profile import inspector
253
+ return inspector.get_or_create_user_id()
254
+
255
+ def configure_webhook(webhook_id='80b8832b694a75c8ddc811ac7882a3de'):
256
+ """Configure webhook URL for analytics data transmission
257
+
258
+ This method should be called once during application initialization
259
+ to set up the analytics endpoint. For security reasons, the URL should
260
+ not be hardcoded in user-facing code.
261
+ """
262
+ if not webhook_id:
263
+ return False
264
+
265
+ from vnai.flow.relay import configure
266
+ webhook_url = f'https://botbuilder.larksuite.com/api/trigger-webhook/{webhook_id}'
267
+ return configure(webhook_url)
268
+
269
+ # Set the webhook
270
+ configure_webhook()
vnai/beam/__init__.py ADDED
@@ -0,0 +1,6 @@
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
6
+ from vnai.beam.pulse import monitor