unaiverse 0.1.12__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.
Files changed (47) hide show
  1. unaiverse/__init__.py +19 -0
  2. unaiverse/agent.py +2226 -0
  3. unaiverse/agent_basics.py +2389 -0
  4. unaiverse/clock.py +234 -0
  5. unaiverse/dataprops.py +1282 -0
  6. unaiverse/hsm.py +2471 -0
  7. unaiverse/modules/__init__.py +18 -0
  8. unaiverse/modules/cnu/__init__.py +17 -0
  9. unaiverse/modules/cnu/cnus.py +536 -0
  10. unaiverse/modules/cnu/layers.py +261 -0
  11. unaiverse/modules/cnu/psi.py +60 -0
  12. unaiverse/modules/hl/__init__.py +15 -0
  13. unaiverse/modules/hl/hl_utils.py +411 -0
  14. unaiverse/modules/networks.py +1509 -0
  15. unaiverse/modules/utils.py +748 -0
  16. unaiverse/networking/__init__.py +16 -0
  17. unaiverse/networking/node/__init__.py +18 -0
  18. unaiverse/networking/node/connpool.py +1332 -0
  19. unaiverse/networking/node/node.py +2752 -0
  20. unaiverse/networking/node/profile.py +446 -0
  21. unaiverse/networking/node/tokens.py +79 -0
  22. unaiverse/networking/p2p/__init__.py +188 -0
  23. unaiverse/networking/p2p/go.mod +127 -0
  24. unaiverse/networking/p2p/go.sum +548 -0
  25. unaiverse/networking/p2p/golibp2p.py +18 -0
  26. unaiverse/networking/p2p/golibp2p.pyi +136 -0
  27. unaiverse/networking/p2p/lib.go +2765 -0
  28. unaiverse/networking/p2p/lib_types.py +311 -0
  29. unaiverse/networking/p2p/message_pb2.py +50 -0
  30. unaiverse/networking/p2p/messages.py +360 -0
  31. unaiverse/networking/p2p/mylogger.py +78 -0
  32. unaiverse/networking/p2p/p2p.py +900 -0
  33. unaiverse/networking/p2p/proto-go/message.pb.go +846 -0
  34. unaiverse/stats.py +1506 -0
  35. unaiverse/streamlib/__init__.py +15 -0
  36. unaiverse/streamlib/streamlib.py +210 -0
  37. unaiverse/streams.py +804 -0
  38. unaiverse/utils/__init__.py +16 -0
  39. unaiverse/utils/lone_wolf.json +28 -0
  40. unaiverse/utils/misc.py +441 -0
  41. unaiverse/utils/sandbox.py +292 -0
  42. unaiverse/world.py +384 -0
  43. unaiverse-0.1.12.dist-info/METADATA +366 -0
  44. unaiverse-0.1.12.dist-info/RECORD +47 -0
  45. unaiverse-0.1.12.dist-info/WHEEL +5 -0
  46. unaiverse-0.1.12.dist-info/licenses/LICENSE +177 -0
  47. unaiverse-0.1.12.dist-info/top_level.txt +1 -0
@@ -0,0 +1,311 @@
1
+ """
2
+ █████ █████ ██████ █████ █████ █████ █████ ██████████ ███████████ █████████ ██████████
3
+ ░░███ ░░███ ░░██████ ░░███ ░░███ ░░███ ░░███ ░░███░░░░░█░░███░░░░░███ ███░░░░░███░░███░░░░░█
4
+ ░███ ░███ ░███░███ ░███ ██████ ░███ ░███ ░███ ░███ █ ░ ░███ ░███ ░███ ░░░ ░███ █ ░
5
+ ░███ ░███ ░███░░███░███ ░░░░░███ ░███ ░███ ░███ ░██████ ░██████████ ░░█████████ ░██████
6
+ ░███ ░███ ░███ ░░██████ ███████ ░███ ░░███ ███ ░███░░█ ░███░░░░░███ ░░░░░░░░███ ░███░░█
7
+ ░███ ░███ ░███ ░░█████ ███░░███ ░███ ░░░█████░ ░███ ░ █ ░███ ░███ ███ ░███ ░███ ░ █
8
+ ░░████████ █████ ░░█████░░████████ █████ ░░███ ██████████ █████ █████░░█████████ ██████████
9
+ ░░░░░░░░ ░░░░░ ░░░░░ ░░░░░░░░ ░░░░░ ░░░ ░░░░░░░░░░ ░░░░░ ░░░░░ ░░░░░░░░░ ░░░░░░░░░░
10
+ A Collectionless AI Project (https://collectionless.ai)
11
+ Registration/Login: https://unaiverse.io
12
+ Code Repositories: https://github.com/collectionlessai/
13
+ Main Developers: Stefano Melacci (Project Leader), Christian Di Maio, Tommaso Guidi
14
+ """
15
+ import json
16
+ import ctypes
17
+ import logging
18
+ from threading import Lock
19
+ from typing import List, Any
20
+
21
+ from .golibp2p import GoLibP2P # Assuming this class loads the library
22
+
23
+ logger = logging.getLogger('LIB-TYPES')
24
+
25
+
26
+ class TypeInterface:
27
+ """
28
+ Helper class for converting between Python types and Go types using ctypes.
29
+ """
30
+ def __init__(self, libp2p_instance: GoLibP2P):
31
+ self.__freed_pointers: set[int] = set() # Track freed pointers to prevent double-free errors
32
+ self.__freed_pointers_lock: Any = Lock() # A threading lock
33
+ self.libp2p: GoLibP2P = libp2p_instance # Store the shared library object instance
34
+
35
+ def to_go_string(self, s: str) -> bytes:
36
+ """
37
+ Converts a Python string to a UTF-8 encoded Python 'bytes' object.
38
+
39
+ This 'bytes' object is suitable for direct use with ctypes when passing
40
+ to a C function expecting a 'char*' (ctypes.c_char_p), as ctypes
41
+ will automatically pass a pointer to the byte string's data.
42
+
43
+ Args:
44
+ s: The Python string.
45
+
46
+ Returns:
47
+ A Python 'bytes' object containing the UTF-8 encoded string.
48
+ """
49
+ if s is None:
50
+ s = ""
51
+ return s.encode("utf-8")
52
+
53
+ def from_go_string(self, cstr: bytes) -> str:
54
+ """
55
+ Converts a C char pointer (Go string) to a Python string.
56
+
57
+ Args:
58
+ cstr: The C char pointer.
59
+
60
+ Returns:
61
+ The decoded Python string.
62
+ """
63
+ if not cstr:
64
+ return ""
65
+ return cstr.decode("utf-8")
66
+
67
+ def to_go_int(self, i: int) -> ctypes.c_int:
68
+ """
69
+ Converts a Python integer to a Go-compatible ctypes integer.
70
+
71
+ Args:
72
+ i: The Python integer.
73
+
74
+ Returns:
75
+ A ctypes.c_int equivalent.
76
+ """
77
+ return ctypes.c_int(i)
78
+
79
+ def from_go_int(self, val: ctypes.c_int) -> int:
80
+ """
81
+ Converts a ctypes.c_int from Go to a Python integer.
82
+
83
+ Args:
84
+ val: The ctypes.c_int value.
85
+
86
+ Returns:
87
+ The corresponding Python integer.
88
+ """
89
+ return int(val)
90
+
91
+ def to_go_float(self, f: float) -> ctypes.c_float:
92
+ """
93
+ Converts a Python float to a Go-compatible ctypes float.
94
+
95
+ Args:
96
+ f: The Python float.
97
+
98
+ Returns:
99
+ A ctypes.c_float equivalent.
100
+ """
101
+ return ctypes.c_float(f)
102
+
103
+ def from_go_float(self, val: ctypes.c_float) -> float:
104
+ """
105
+ Converts a ctypes.c_float from Go to a Python float.
106
+
107
+ Args:
108
+ val: The ctypes.c_float value.
109
+
110
+ Returns:
111
+ The corresponding Python float.
112
+ """
113
+ return float(val)
114
+
115
+ def to_go_bool(self, b: bool) -> ctypes.c_int:
116
+ """
117
+ Converts a Python boolean to a Go-compatible integer (1 if True, 0 if False).
118
+
119
+ Args:
120
+ b: The Python boolean.
121
+
122
+ Returns:
123
+ A ctypes.c_int (1 or 0).
124
+ """
125
+ return ctypes.c_int(1 if b else 0)
126
+
127
+ def from_go_bool(self, val: ctypes.c_int) -> bool:
128
+ """
129
+ Converts a Go-compatible integer (ctypes.c_int) to a Python boolean.
130
+
131
+ Args:
132
+ val: The ctypes.c_int value.
133
+
134
+ Returns:
135
+ True if the value equals 1, False otherwise.
136
+ """
137
+ return val == 1
138
+
139
+ def to_go_bytes(self, b: bytes) -> ctypes.c_char_p:
140
+ """
141
+ Converts a Python bytes object to a Go-compatible C char pointer.
142
+
143
+ Args:
144
+ b: The Python bytes.
145
+
146
+ Returns:
147
+ A ctypes.c_char_p pointing to the byte data.
148
+ """
149
+ if b is None:
150
+ b = b""
151
+ buf = ctypes.create_string_buffer(b, len(b))
152
+ return ctypes.cast(buf, ctypes.c_char_p)
153
+
154
+ def from_go_bytes(self, cptr: ctypes.c_char_p, length: int) -> bytes:
155
+ """
156
+ Converts a Go pointer representing a byte array to a Python bytes object.
157
+
158
+ Args:
159
+ cptr: The C pointer to the byte array.
160
+ length: The number of bytes to read.
161
+
162
+ Returns:
163
+ A Python bytes object containing the read data.
164
+ """
165
+ if not cptr or length <= 0:
166
+ return bytes()
167
+ return ctypes.string_at(cptr, length)
168
+
169
+ def from_go_ptr_to_json(self, c_void_ptr_val: int) -> Any:
170
+ """
171
+ Converts a C void* pointer (returned by Go as int) pointing to a
172
+ null-terminated C string containing JSON into a Python object.
173
+
174
+ It reads the string, parses it as JSON, and crucially frees the C memory
175
+ using the provided FreeString function from the Go library.
176
+
177
+ Args:
178
+ c_void_ptr_val: The integer value representing the C pointer address.
179
+
180
+ Returns:
181
+ The parsed Python object from the JSON string.
182
+
183
+ Raises:
184
+ GoLibError: If the pointer is NULL, reading/decoding fails, or
185
+ JSON parsing fails.
186
+ TypeError: When go_lib is not a valid ctypes library object.
187
+ """
188
+
189
+ if not c_void_ptr_val: # Check if the address is NULL (0)
190
+ raise print("Received a NULL pointer from Go function")
191
+
192
+ try:
193
+
194
+ # --- Double-Free Check (Before Reading/Casting) ---
195
+ self.__freed_pointers_lock.acquire() # Acquire lock if using threading
196
+ if c_void_ptr_val in self.__freed_pointers:
197
+
198
+ # This indicates a serious logic error elsewhere - the pointer
199
+ # was already freed but somehow passed here again.
200
+ logger.warning(f"🔥🔥🔥 ATTEMPT TO PROCESS ALREADY FREED POINTER {hex(c_void_ptr_val)}! 🔥🔥🔥")
201
+
202
+ # Raising an error is safer than trying to read potentially invalid memory.
203
+ logger.error(f"Attempt to process pointer {hex(c_void_ptr_val)} which was already freed")
204
+ raise Exception(f"Attempt to process pointer {hex(c_void_ptr_val)} which was already freed")
205
+ self.__freed_pointers_lock.release() # Release lock if using threading
206
+
207
+ # --- Cast void* to c_char_p and Read String ---
208
+ try:
209
+
210
+ # Perform the cast only when needed for reading
211
+ c_char_ptr_for_read = ctypes.cast(c_void_ptr_val, ctypes.c_char_p)
212
+ raw_bytes = ctypes.string_at(c_char_ptr_for_read)
213
+ json_string = raw_bytes.decode('utf-8')
214
+
215
+ # Logger.debug(f"Read string (len={len(json_string)})
216
+ # from pointer {hex(c_void_ptr_val)}: %.100s...", json_string)
217
+ except (ctypes.ArgumentError, ValueError, UnicodeDecodeError) as read_err:
218
+ logger.error(f"Failed to read/decode string from pointer {hex(c_void_ptr_val)}: "
219
+ f"{read_err}", exc_info=False)
220
+
221
+ # Even if reading fails, the pointer itself *might* still be valid C memory
222
+ # that Go expects us to free. We will proceed to free it in finally.
223
+ raise Exception(f"Failed to read string from pointer {hex(c_void_ptr_val)}: {read_err}") from read_err
224
+ except Exception as unexpected_read_err: # Catch other potential ctypes issues
225
+ logger.error(f"Unexpected error reading C string from pointer {hex(c_void_ptr_val)}: "
226
+ f"{unexpected_read_err}", exc_info=True)
227
+ raise Exception(f"Unexpected error reading C string from pointer {hex(c_void_ptr_val)}: "
228
+ f"{unexpected_read_err}") from unexpected_read_err
229
+
230
+ # --- Check for Empty String ---
231
+
232
+ # --- Parse JSON ---
233
+ try:
234
+
235
+ # Now that we have the string, parse it
236
+ logger.debug(f"Parsing JSON from string: {json_string}")
237
+ parsed_data = json.loads(json_string)
238
+ logger.debug(f"Parsed JSON data: {parsed_data}")
239
+
240
+ # Logger.debug(f"Successfully parsed JSON from pointer {hex(c_void_ptr_val)}")
241
+ return parsed_data # Return the parsed Python object
242
+
243
+ except json.JSONDecodeError as json_err:
244
+ logger.error(f"Failed to decode JSON from pointer {hex(c_void_ptr_val)}: {json_err}", exc_info=False)
245
+
246
+ # Again, the pointer is likely valid C memory, but the content is bad.
247
+ # Let the block handle freeing.
248
+ raise Exception(f"Failed to decode JSON from pointer {hex(c_void_ptr_val)}: {json_err}") from json_err
249
+
250
+ finally:
251
+
252
+ # --- CRITICAL: Free C Memory ---
253
+ # This block executes even if errors occurred during read/parse,
254
+ # ensuring we attempt to free any non-NULL pointer received from Go.
255
+ with self.__freed_pointers_lock:
256
+ if c_void_ptr_val:
257
+ logger.info(f"🐍 FINALLY: Freeing pointer {hex(c_void_ptr_val)}...")
258
+ if c_void_ptr_val in self.__freed_pointers:
259
+
260
+ # This check is technically redundant if the initial check worked,
261
+ # but provides an extra safety layer in case of concurrency issues
262
+ # (if freed_pointers is shared without locks - which it shouldn't be).
263
+ logger.warning(f"🔥🔥🔥 DOUBLE FREE DETECTED in finally block for "
264
+ f"{hex(c_void_ptr_val)}! Skipping FreeString call again. 🔥🔥🔥")
265
+ else:
266
+
267
+ # Add before calling free
268
+ try:
269
+ self.libp2p.FreeString(c_void_ptr_val) # Pass the original void* value
270
+ logger.info(f"✅ FINALLY: FreeString successful for {hex(c_void_ptr_val)}.")
271
+ except Exception as free_err:
272
+
273
+ # Log if FreeString fails, but don't raise from finally
274
+ # as it might hide the original error.
275
+ logger.critical(f"🚨 FAILED TO FREE C MEMORY for pointer "
276
+ f"{hex(c_void_ptr_val)} via FreeString: {free_err}", exc_info=True)
277
+
278
+ # Consider removing from freed_pointers if free failed?
279
+ # freed_pointers.discard(c_void_ptr_val) # Maybe, to allow retry? Risky.
280
+ # But if FreeString fails, the pointer is likely invalid anyway.
281
+
282
+ def to_go_json(self, data: Any) -> bytes:
283
+ """
284
+ Encodes a Python object to a JSON string, returning a UTF-8 encoded
285
+ Python 'bytes' object.
286
+
287
+ This 'bytes' object is suitable for direct use with ctypes when passing
288
+ to a C function expecting a 'char*' (ctypes.c_char_p).
289
+
290
+ Args:
291
+ data: The Python object (e.g., dict, list) to encode.
292
+
293
+ Returns:
294
+ A Python 'bytes' object containing the JSON string, UTF-8 encoded.
295
+ """
296
+ json_str = json.dumps(data)
297
+ return self.to_go_string(json_str)
298
+
299
+ def from_go_string_to_list(self, cstr: ctypes.c_char_p) -> List[Any]:
300
+ """
301
+ Decodes a JSON-encoded list from a Go C char pointer into a Python list.
302
+
303
+ Args:
304
+ cstr: The Go string (C char pointer) containing a JSON list.
305
+
306
+ Returns:
307
+ A Python list representing the JSON data.
308
+ """
309
+ s = self.from_go_string(cstr)
310
+
311
+ return json.loads(s)
@@ -0,0 +1,50 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # source: message.proto
4
+ # Protobuf Python Version: 4.25.3
5
+ """Generated protocol buffer code."""
6
+ from google.protobuf import descriptor as _descriptor
7
+ from google.protobuf import descriptor_pool as _descriptor_pool
8
+ from google.protobuf import symbol_database as _symbol_database
9
+ from google.protobuf.internal import builder as _builder
10
+ # @@protoc_insertion_point(imports)
11
+
12
+ _sym_db = _symbol_database.Default()
13
+
14
+
15
+ from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2
16
+
17
+
18
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\rmessage.proto\x12\x03p2p\x1a\x1cgoogle/protobuf/struct.proto\"\xe8\x01\n\x07Message\x12\x0e\n\x06sender\x18\x01 \x01(\t\x12\x14\n\x0c\x63ontent_type\x18\x02 \x01(\t\x12\x0f\n\x07\x63hannel\x18\x03 \x01(\t\x12\x11\n\tpiggyback\x18\x04 \x01(\t\x12\x15\n\rtimestamp_net\x18\x05 \x01(\t\x12\x31\n\rstream_sample\x18\x06 \x01(\x0b\x32\x18.p2p.StreamSampleContentH\x00\x12\x16\n\x0cjson_content\x18\x07 \x01(\tH\x00\x12&\n\x0cstats_update\x18\x08 \x01(\x0b\x32\x0e.p2p.StatBatchH\x00\x42\t\n\x07\x63ontent\"\x90\x01\n\x13StreamSampleContent\x12\x36\n\x07samples\x18\x01 \x03(\x0b\x32%.p2p.StreamSampleContent.SamplesEntry\x1a\x41\n\x0cSamplesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12 \n\x05value\x18\x02 \x01(\x0b\x32\x11.p2p.StreamSample:\x02\x38\x01\"e\n\x0cStreamSample\x12\x1d\n\x04\x64\x61ta\x18\x01 \x01(\x0b\x32\x0f.p2p.SampleData\x12\x10\n\x08\x64\x61ta_tag\x18\x02 \x01(\x05\x12\x16\n\tdata_uuid\x18\x03 \x01(\tH\x00\x88\x01\x01\x42\x0c\n\n_data_uuid\"\xb2\x01\n\nSampleData\x12&\n\x0btensor_data\x18\x01 \x01(\x0b\x32\x0f.p2p.TensorDataH\x00\x12$\n\nimage_data\x18\x02 \x01(\x0b\x32\x0e.p2p.ImageDataH\x00\x12\"\n\ttext_data\x18\x03 \x01(\x0b\x32\r.p2p.TextDataH\x00\x12\"\n\tfile_data\x18\x04 \x01(\x0b\x32\r.p2p.FileDataH\x00\x42\x0e\n\x0c\x64\x61ta_payload\"8\n\nTensorData\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\x12\r\n\x05\x64type\x18\x02 \x01(\t\x12\r\n\x05shape\x18\x03 \x03(\x05\"\x19\n\tImageData\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\"\x18\n\x08TextData\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\t\"@\n\x08\x46ileData\x12\x0f\n\x07\x63ontent\x18\x01 \x01(\x0c\x12\x10\n\x08\x66ilename\x18\x02 \x01(\t\x12\x11\n\tmime_type\x18\x03 \x01(\t\"j\n\nStatUpdate\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x11\n\tstat_name\x18\x02 \x01(\t\x12\x11\n\ttimestamp\x18\x03 \x01(\x03\x12%\n\x05value\x18\x04 \x01(\x0b\x32\x16.google.protobuf.Value\"-\n\tStatBatch\x12 \n\x07updates\x18\x01 \x03(\x0b\x32\x0f.p2p.StatUpdateB\x0cZ\n./proto-gob\x06proto3')
19
+
20
+ _globals = globals()
21
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
22
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'message_pb2', _globals)
23
+ if _descriptor._USE_C_DESCRIPTORS == False:
24
+ _globals['DESCRIPTOR']._options = None
25
+ _globals['DESCRIPTOR']._serialized_options = b'Z\n./proto-go'
26
+ _globals['_STREAMSAMPLECONTENT_SAMPLESENTRY']._options = None
27
+ _globals['_STREAMSAMPLECONTENT_SAMPLESENTRY']._serialized_options = b'8\001'
28
+ _globals['_MESSAGE']._serialized_start=53
29
+ _globals['_MESSAGE']._serialized_end=285
30
+ _globals['_STREAMSAMPLECONTENT']._serialized_start=288
31
+ _globals['_STREAMSAMPLECONTENT']._serialized_end=432
32
+ _globals['_STREAMSAMPLECONTENT_SAMPLESENTRY']._serialized_start=367
33
+ _globals['_STREAMSAMPLECONTENT_SAMPLESENTRY']._serialized_end=432
34
+ _globals['_STREAMSAMPLE']._serialized_start=434
35
+ _globals['_STREAMSAMPLE']._serialized_end=535
36
+ _globals['_SAMPLEDATA']._serialized_start=538
37
+ _globals['_SAMPLEDATA']._serialized_end=716
38
+ _globals['_TENSORDATA']._serialized_start=718
39
+ _globals['_TENSORDATA']._serialized_end=774
40
+ _globals['_IMAGEDATA']._serialized_start=776
41
+ _globals['_IMAGEDATA']._serialized_end=801
42
+ _globals['_TEXTDATA']._serialized_start=803
43
+ _globals['_TEXTDATA']._serialized_end=827
44
+ _globals['_FILEDATA']._serialized_start=829
45
+ _globals['_FILEDATA']._serialized_end=893
46
+ _globals['_STATUPDATE']._serialized_start=895
47
+ _globals['_STATUPDATE']._serialized_end=1001
48
+ _globals['_STATBATCH']._serialized_start=1003
49
+ _globals['_STATBATCH']._serialized_end=1048
50
+ # @@protoc_insertion_point(module_scope)