Spaces:
Sleeping
Sleeping
File size: 11,299 Bytes
4e067f2 |
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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
# coding: utf-8
# Copyright (c) 2025 inclusionAI.
import asyncio
import inspect
import os
import pkgutil
import re
import socket
import sys
import threading
import time
from functools import wraps
from types import FunctionType
from typing import Callable, Any, Tuple, List, Iterator, Dict, Union
from aworld.logs.util import logger
def convert_to_snake(name: str) -> str:
"""Class name convert to snake."""
if '_' not in name:
name = re.sub(r'([a-z])([A-Z])', r'\1_\2', name)
return name.lower()
def snake_to_camel(snake):
words = snake.split('_')
return ''.join([w.capitalize() for w in words])
def is_abstract_method(cls, method_name):
method = getattr(cls, method_name)
return (hasattr(method, '__isabstractmethod__') and method.__isabstractmethod__) or (
isinstance(method, FunctionType) and hasattr(
method, '__abstractmethods__') and method in method.__abstractmethods__)
def override_in_subclass(name: str, sub_cls: object, base_cls: object) -> bool:
"""Judge whether a subclass overrides a specified method.
Args:
name: The method name of sub class and base class
sub_cls: Specify subclasses of the base class.
base_cls: The parent class of the subclass.
Returns:
Overwrite as true in subclasses, vice versa.
"""
if not issubclass(sub_cls, base_cls):
logger.warning(f"{sub_cls} is not sub class of {base_cls}")
return False
if sub_cls == base_cls and hasattr(sub_cls, name) and not is_abstract_method(sub_cls, name):
return True
this_method = getattr(sub_cls, name)
base_method = getattr(base_cls, name)
return this_method is not base_method
def convert_to_subclass(obj, subclass):
obj.__class__ = subclass
return obj
def _walk_to_root(path: str) -> Iterator[str]:
"""Yield directories starting from the given directory up to the root."""
if not os.path.exists(path):
yield ''
if os.path.isfile(path):
path = os.path.dirname(path)
last_dir = None
current_dir = os.path.abspath(path)
while last_dir != current_dir:
yield current_dir
parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir))
last_dir, current_dir = current_dir, parent_dir
def find_file(filename: str) -> str:
"""Find file from the folders for the given file.
NOTE: Current running path priority, followed by the execution file path, and finally the aworld package path.
Args:
filename: The file name that you want to search.
"""
def run_dir():
try:
main = __import__('__main__', None, None, fromlist=['__file__'])
return os.path.dirname(main.__file__)
except ModuleNotFoundError:
return os.getcwd()
path = os.getcwd()
if os.path.exists(os.path.join(path, filename)):
path = os.getcwd()
elif os.path.exists(os.path.join(run_dir(), filename)):
path = run_dir()
else:
frame = inspect.currentframe()
current_file = __file__
while frame.f_code.co_filename == current_file or not os.path.exists(
frame.f_code.co_filename
):
assert frame.f_back is not None
frame = frame.f_back
frame_filename = frame.f_code.co_filename
path = os.path.dirname(os.path.abspath(frame_filename))
for dirname in _walk_to_root(path):
if not dirname:
continue
check_path = os.path.join(dirname, filename)
if os.path.isfile(check_path):
return check_path
return ''
def search_in_module(module: object, base_classes: List[type]) -> List[Tuple[str, type]]:
"""Find all classes that inherit from a specific base class in the module."""
results = []
for name, obj in inspect.getmembers(module, inspect.isclass):
for base_class in base_classes:
if issubclass(obj, base_class) and obj is not base_class:
results.append((name, obj))
return results
def _scan_package(package_name: str, base_classes: List[type], results: List[Tuple[str, type]] = []):
try:
package = sys.modules[package_name]
except:
return
try:
for sub_package, name, is_pkg in pkgutil.walk_packages(package.__path__):
try:
__import__(f"{package_name}.{name}")
except:
continue
if is_pkg:
_scan_package(package_name + "." + name, base_classes, results)
try:
module = __import__(f"{package_name}.{name}", fromlist=[name])
results.extend(search_in_module(module, base_classes))
except:
continue
except:
pass
def scan_packages(package: str, base_classes: List[type]) -> List[Tuple[str, type]]:
results = []
_scan_package(package, base_classes, results)
return results
class ReturnThread(threading.Thread):
def __init__(self, func, *args, **kwargs):
threading.Thread.__init__(self)
self.func = func
self.args = args
self.kwargs = kwargs
self.result = None
self.daemon = True
def run(self):
self.result = asyncio.run(self.func(*self.args, **self.kwargs))
def asyncio_loop():
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = None
return loop
def sync_exec(async_func: Callable[..., Any], *args, **kwargs):
"""Async function to sync execution."""
if not asyncio.iscoroutinefunction(async_func):
return async_func(*args, **kwargs)
loop = asyncio_loop()
if loop and loop.is_running():
thread = ReturnThread(async_func, *args, **kwargs)
thread.start()
thread.join()
result = thread.result
else:
loop = asyncio.get_event_loop()
result = loop.run_until_complete(async_func(*args, **kwargs))
return result
def nest_dict_counter(usage: Dict[str, Union[int, Dict[str, int]]],
other: Dict[str, Union[int, Dict[str, int]]],
ignore_zero: bool = True):
"""Add counts from two dicts or nest dicts."""
result = {}
for elem, count in usage.items():
# nest dict
if isinstance(count, Dict):
res = nest_dict_counter(usage[elem], other.get(elem, {}))
result[elem] = res
continue
newcount = count + other.get(elem, 0)
if not ignore_zero or newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in usage and not ignore_zero:
result[elem] = count
return result
def get_class(module_class: str):
import importlib
assert module_class
module_class = module_class.strip()
idx = module_class.rfind('.')
if idx != -1:
module = importlib.import_module(module_class[0:idx])
class_names = module_class[idx + 1:].split(":")
cls_obj = getattr(module, class_names[0])
for inner_class_name in class_names[1:]:
cls_obj = getattr(cls_obj, inner_class_name)
return cls_obj
else:
raise Exception("{} can not find!".format(module_class))
def new_instance(module_class: str, *args, **kwargs):
"""Create module class instance based on module name."""
return get_class(module_class)(*args, **kwargs)
def retryable(tries: int = 3, delay: int = 1):
def inner_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 0:
try:
return f(*args, **kwargs)
except Exception as e:
msg = f"{str(e)}, Retrying in {mdelay} seconds..."
logger.warning(msg)
time.sleep(mdelay)
mtries -= 1
return f(*args, **kwargs)
return f_retry
return inner_retry
def get_local_ip():
try:
# build UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# connect to an external address (no need to connect)
s.connect(("8.8.8.8", 80))
# get local IP
local_ip = s.getsockname()[0]
s.close()
return local_ip
except Exception:
return "127.0.0.1"
def replace_env_variables(config) -> Any:
"""Replace environment variables in configuration.
Environment variables should be in the format ${ENV_VAR_NAME}.
Args:
config: Configuration to process (dict, list, or other value)
Returns:
Processed configuration with environment variables replaced
"""
if isinstance(config, dict):
for key, value in config.items():
if isinstance(value, str):
if "${" in value and "}" in value:
pattern = r'\${([^}]+)}'
matches = re.findall(pattern, value)
result = value
for env_var_name in matches:
env_var_value = os.getenv(env_var_name, f"${{{env_var_name}}}")
result = result.replace(f"${{{env_var_name}}}", env_var_value)
config[key] = result
logger.info(f"Replaced {value} with {config[key]}")
if isinstance(value, dict) or isinstance(value, list):
replace_env_variables(value)
elif isinstance(config, list):
for index, item in enumerate(config):
if isinstance(item, str):
if "${" in item and "}" in item:
pattern = r'\${([^}]+)}'
matches = re.findall(pattern, item)
result = item
for env_var_name in matches:
env_var_value = os.getenv(env_var_name, f"${{{env_var_name}}}")
result = result.replace(f"${{{env_var_name}}}", env_var_value)
config[index] = result
logger.info(f"Replaced {item} with {config[index]}")
if isinstance(item, dict) or isinstance(item, list):
replace_env_variables(item)
return config
def get_local_hostname():
"""
Get the local hostname.
First try `socket.gethostname()`, if it fails or returns an invalid value,
then try reverse DNS lookup using local IP.
"""
try:
hostname = socket.gethostname()
# Simple validation - if hostname contains '.', consider it a valid FQDN (Fully Qualified Domain Name)
if hostname and '.' in hostname:
return hostname
# If hostname is not qualified, try reverse lookup via IP
local_ip = get_local_ip()
if local_ip:
try:
# Get hostname from IP
hostname, _, _ = socket.gethostbyaddr(local_ip)
return hostname
except (socket.herror, socket.gaierror):
# Reverse lookup failed, return original hostname or IP
pass
# If all methods fail, return original gethostname() result or IP
return hostname if hostname else local_ip
except Exception:
# Final fallback strategy
return "localhost" |