Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

__init__.py 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import base64
  17. import datetime
  18. import io
  19. import json
  20. import os
  21. import pickle
  22. import socket
  23. import time
  24. import uuid
  25. import requests
  26. from enum import Enum, IntEnum
  27. import importlib
  28. from Cryptodome.PublicKey import RSA
  29. from Cryptodome.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
  30. from filelock import FileLock
  31. from . import file_utils
  32. SERVICE_CONF = "service_conf.yaml"
  33. def conf_realpath(conf_name):
  34. conf_path = f"conf/{conf_name}"
  35. return os.path.join(file_utils.get_project_base_directory(), conf_path)
  36. def get_base_config(key, default=None, conf_name=SERVICE_CONF) -> dict:
  37. local_config = {}
  38. local_path = conf_realpath(f'local.{conf_name}')
  39. if default is None:
  40. default = os.environ.get(key.upper())
  41. if os.path.exists(local_path):
  42. local_config = file_utils.load_yaml_conf(local_path)
  43. if not isinstance(local_config, dict):
  44. raise ValueError(f'Invalid config file: "{local_path}".')
  45. if key is not None and key in local_config:
  46. return local_config[key]
  47. config_path = conf_realpath(conf_name)
  48. config = file_utils.load_yaml_conf(config_path)
  49. if not isinstance(config, dict):
  50. raise ValueError(f'Invalid config file: "{config_path}".')
  51. config.update(local_config)
  52. return config.get(key, default) if key is not None else config
  53. use_deserialize_safe_module = get_base_config(
  54. 'use_deserialize_safe_module', False)
  55. class CoordinationCommunicationProtocol(object):
  56. HTTP = "http"
  57. GRPC = "grpc"
  58. class BaseType:
  59. def to_dict(self):
  60. return dict([(k.lstrip("_"), v) for k, v in self.__dict__.items()])
  61. def to_dict_with_type(self):
  62. def _dict(obj):
  63. module = None
  64. if issubclass(obj.__class__, BaseType):
  65. data = {}
  66. for attr, v in obj.__dict__.items():
  67. k = attr.lstrip("_")
  68. data[k] = _dict(v)
  69. module = obj.__module__
  70. elif isinstance(obj, (list, tuple)):
  71. data = []
  72. for i, vv in enumerate(obj):
  73. data.append(_dict(vv))
  74. elif isinstance(obj, dict):
  75. data = {}
  76. for _k, vv in obj.items():
  77. data[_k] = _dict(vv)
  78. else:
  79. data = obj
  80. return {"type": obj.__class__.__name__,
  81. "data": data, "module": module}
  82. return _dict(self)
  83. class CustomJSONEncoder(json.JSONEncoder):
  84. def __init__(self, **kwargs):
  85. self._with_type = kwargs.pop("with_type", False)
  86. super().__init__(**kwargs)
  87. def default(self, obj):
  88. if isinstance(obj, datetime.datetime):
  89. return obj.strftime('%Y-%m-%d %H:%M:%S')
  90. elif isinstance(obj, datetime.date):
  91. return obj.strftime('%Y-%m-%d')
  92. elif isinstance(obj, datetime.timedelta):
  93. return str(obj)
  94. elif issubclass(type(obj), Enum) or issubclass(type(obj), IntEnum):
  95. return obj.value
  96. elif isinstance(obj, set):
  97. return list(obj)
  98. elif issubclass(type(obj), BaseType):
  99. if not self._with_type:
  100. return obj.to_dict()
  101. else:
  102. return obj.to_dict_with_type()
  103. elif isinstance(obj, type):
  104. return obj.__name__
  105. else:
  106. return json.JSONEncoder.default(self, obj)
  107. def rag_uuid():
  108. return uuid.uuid1().hex
  109. def string_to_bytes(string):
  110. return string if isinstance(
  111. string, bytes) else string.encode(encoding="utf-8")
  112. def bytes_to_string(byte):
  113. return byte.decode(encoding="utf-8")
  114. def json_dumps(src, byte=False, indent=None, with_type=False):
  115. dest = json.dumps(
  116. src,
  117. indent=indent,
  118. cls=CustomJSONEncoder,
  119. with_type=with_type)
  120. if byte:
  121. dest = string_to_bytes(dest)
  122. return dest
  123. def json_loads(src, object_hook=None, object_pairs_hook=None):
  124. if isinstance(src, bytes):
  125. src = bytes_to_string(src)
  126. return json.loads(src, object_hook=object_hook,
  127. object_pairs_hook=object_pairs_hook)
  128. def current_timestamp():
  129. return int(time.time() * 1000)
  130. def timestamp_to_date(timestamp, format_string="%Y-%m-%d %H:%M:%S"):
  131. if not timestamp:
  132. timestamp = time.time()
  133. timestamp = int(timestamp) / 1000
  134. time_array = time.localtime(timestamp)
  135. str_date = time.strftime(format_string, time_array)
  136. return str_date
  137. def date_string_to_timestamp(time_str, format_string="%Y-%m-%d %H:%M:%S"):
  138. time_array = time.strptime(time_str, format_string)
  139. time_stamp = int(time.mktime(time_array) * 1000)
  140. return time_stamp
  141. def serialize_b64(src, to_str=False):
  142. dest = base64.b64encode(pickle.dumps(src))
  143. if not to_str:
  144. return dest
  145. else:
  146. return bytes_to_string(dest)
  147. def deserialize_b64(src):
  148. src = base64.b64decode(
  149. string_to_bytes(src) if isinstance(
  150. src, str) else src)
  151. if use_deserialize_safe_module:
  152. return restricted_loads(src)
  153. return pickle.loads(src)
  154. safe_module = {
  155. 'numpy',
  156. 'rag_flow'
  157. }
  158. class RestrictedUnpickler(pickle.Unpickler):
  159. def find_class(self, module, name):
  160. import importlib
  161. if module.split('.')[0] in safe_module:
  162. _module = importlib.import_module(module)
  163. return getattr(_module, name)
  164. # Forbid everything else.
  165. raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
  166. (module, name))
  167. def restricted_loads(src):
  168. """Helper function analogous to pickle.loads()."""
  169. return RestrictedUnpickler(io.BytesIO(src)).load()
  170. def get_lan_ip():
  171. if os.name != "nt":
  172. import fcntl
  173. import struct
  174. def get_interface_ip(ifname):
  175. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  176. return socket.inet_ntoa(
  177. fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', string_to_bytes(ifname[:15])))[20:24])
  178. ip = socket.gethostbyname(socket.getfqdn())
  179. if ip.startswith("127.") and os.name != "nt":
  180. interfaces = [
  181. "bond1",
  182. "eth0",
  183. "eth1",
  184. "eth2",
  185. "wlan0",
  186. "wlan1",
  187. "wifi0",
  188. "ath0",
  189. "ath1",
  190. "ppp0",
  191. ]
  192. for ifname in interfaces:
  193. try:
  194. ip = get_interface_ip(ifname)
  195. break
  196. except IOError as e:
  197. pass
  198. return ip or ''
  199. def from_dict_hook(in_dict: dict):
  200. if "type" in in_dict and "data" in in_dict:
  201. if in_dict["module"] is None:
  202. return in_dict["data"]
  203. else:
  204. return getattr(importlib.import_module(
  205. in_dict["module"]), in_dict["type"])(**in_dict["data"])
  206. else:
  207. return in_dict
  208. def decrypt_database_password(password):
  209. encrypt_password = get_base_config("encrypt_password", False)
  210. encrypt_module = get_base_config("encrypt_module", False)
  211. private_key = get_base_config("private_key", None)
  212. if not password or not encrypt_password:
  213. return password
  214. if not private_key:
  215. raise ValueError("No private key")
  216. module_fun = encrypt_module.split("#")
  217. pwdecrypt_fun = getattr(
  218. importlib.import_module(
  219. module_fun[0]),
  220. module_fun[1])
  221. return pwdecrypt_fun(private_key, password)
  222. def decrypt_database_config(
  223. database=None, passwd_key="password", name="database"):
  224. if not database:
  225. database = get_base_config(name, {})
  226. database[passwd_key] = decrypt_database_password(database[passwd_key])
  227. return database
  228. def update_config(key, value, conf_name=SERVICE_CONF):
  229. conf_path = conf_realpath(conf_name=conf_name)
  230. if not os.path.isabs(conf_path):
  231. conf_path = os.path.join(
  232. file_utils.get_project_base_directory(), conf_path)
  233. with FileLock(os.path.join(os.path.dirname(conf_path), ".lock")):
  234. config = file_utils.load_yaml_conf(conf_path=conf_path) or {}
  235. config[key] = value
  236. file_utils.rewrite_yaml_conf(conf_path=conf_path, config=config)
  237. def get_uuid():
  238. return uuid.uuid1().hex
  239. def datetime_format(date_time: datetime.datetime) -> datetime.datetime:
  240. return datetime.datetime(date_time.year, date_time.month, date_time.day,
  241. date_time.hour, date_time.minute, date_time.second)
  242. def get_format_time() -> datetime.datetime:
  243. return datetime_format(datetime.datetime.now())
  244. def str2date(date_time: str):
  245. return datetime.datetime.strptime(date_time, '%Y-%m-%d')
  246. def elapsed2time(elapsed):
  247. seconds = elapsed / 1000
  248. minuter, second = divmod(seconds, 60)
  249. hour, minuter = divmod(minuter, 60)
  250. return '%02d:%02d:%02d' % (hour, minuter, second)
  251. def decrypt(line):
  252. file_path = os.path.join(
  253. file_utils.get_project_base_directory(),
  254. "conf",
  255. "private.pem")
  256. rsa_key = RSA.importKey(open(file_path).read(), "Welcome")
  257. cipher = Cipher_pkcs1_v1_5.new(rsa_key)
  258. return cipher.decrypt(base64.b64decode(
  259. line), "Fail to decrypt password!").decode('utf-8')
  260. def download_img(url):
  261. if not url:
  262. return ""
  263. response = requests.get(url)
  264. return "data:" + \
  265. response.headers.get('Content-Type', 'image/jpg') + ";" + \
  266. "base64," + base64.b64encode(response.content).decode("utf-8")