misc.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. import hashlib
  2. import re
  3. import time
  4. import uuid
  5. from datetime import timedelta
  6. from pathlib import Path
  7. from typing import Callable, Optional
  8. import collections.abc
  9. def deep_update(d, u):
  10. for k, v in u.items():
  11. if isinstance(v, collections.abc.Mapping):
  12. d[k] = deep_update(d.get(k, {}), v)
  13. else:
  14. d[k] = v
  15. return d
  16. def get_message_list(messages, message_id):
  17. """
  18. Reconstructs a list of messages in order up to the specified message_id.
  19. :param message_id: ID of the message to reconstruct the chain
  20. :param messages: Message history dict containing all messages
  21. :return: List of ordered messages starting from the root to the given message
  22. """
  23. # Find the message by its id
  24. current_message = messages.get(message_id)
  25. if not current_message:
  26. return None
  27. # Reconstruct the chain by following the parentId links
  28. message_list = []
  29. while current_message:
  30. message_list.insert(
  31. 0, current_message
  32. ) # Insert the message at the beginning of the list
  33. parent_id = current_message["parentId"]
  34. current_message = messages.get(parent_id) if parent_id else None
  35. return message_list
  36. def get_messages_content(messages: list[dict]) -> str:
  37. return "\n".join(
  38. [
  39. f"{message['role'].upper()}: {get_content_from_message(message)}"
  40. for message in messages
  41. ]
  42. )
  43. def get_last_user_message_item(messages: list[dict]) -> Optional[dict]:
  44. for message in reversed(messages):
  45. if message["role"] == "user":
  46. return message
  47. return None
  48. def get_content_from_message(message: dict) -> Optional[str]:
  49. if isinstance(message["content"], list):
  50. for item in message["content"]:
  51. if item["type"] == "text":
  52. return item["text"]
  53. else:
  54. return message["content"]
  55. return None
  56. def get_last_user_message(messages: list[dict]) -> Optional[str]:
  57. message = get_last_user_message_item(messages)
  58. if message is None:
  59. return None
  60. return get_content_from_message(message)
  61. def get_last_assistant_message_item(messages: list[dict]) -> Optional[dict]:
  62. for message in reversed(messages):
  63. if message["role"] == "assistant":
  64. return message
  65. return None
  66. def get_last_assistant_message(messages: list[dict]) -> Optional[str]:
  67. for message in reversed(messages):
  68. if message["role"] == "assistant":
  69. return get_content_from_message(message)
  70. return None
  71. def get_system_message(messages: list[dict]) -> Optional[dict]:
  72. for message in messages:
  73. if message["role"] == "system":
  74. return message
  75. return None
  76. def remove_system_message(messages: list[dict]) -> list[dict]:
  77. return [message for message in messages if message["role"] != "system"]
  78. def pop_system_message(messages: list[dict]) -> tuple[Optional[dict], list[dict]]:
  79. return get_system_message(messages), remove_system_message(messages)
  80. def prepend_to_first_user_message_content(
  81. content: str, messages: list[dict]
  82. ) -> list[dict]:
  83. for message in messages:
  84. if message["role"] == "user":
  85. if isinstance(message["content"], list):
  86. for item in message["content"]:
  87. if item["type"] == "text":
  88. item["text"] = f"{content}\n{item['text']}"
  89. else:
  90. message["content"] = f"{content}\n{message['content']}"
  91. break
  92. return messages
  93. def add_or_update_system_message(content: str, messages: list[dict]):
  94. """
  95. Adds a new system message at the beginning of the messages list
  96. or updates the existing system message at the beginning.
  97. :param msg: The message to be added or appended.
  98. :param messages: The list of message dictionaries.
  99. :return: The updated list of message dictionaries.
  100. """
  101. if messages and messages[0].get("role") == "system":
  102. messages[0]["content"] = f"{content}\n{messages[0]['content']}"
  103. else:
  104. # Insert at the beginning
  105. messages.insert(0, {"role": "system", "content": content})
  106. return messages
  107. def add_or_update_user_message(content: str, messages: list[dict]):
  108. """
  109. Adds a new user message at the end of the messages list
  110. or updates the existing user message at the end.
  111. :param msg: The message to be added or appended.
  112. :param messages: The list of message dictionaries.
  113. :return: The updated list of message dictionaries.
  114. """
  115. if messages and messages[-1].get("role") == "user":
  116. messages[-1]["content"] = f"{messages[-1]['content']}\n{content}"
  117. else:
  118. # Insert at the end
  119. messages.append({"role": "user", "content": content})
  120. return messages
  121. def append_or_update_assistant_message(content: str, messages: list[dict]):
  122. """
  123. Adds a new assistant message at the end of the messages list
  124. or updates the existing assistant message at the end.
  125. :param msg: The message to be added or appended.
  126. :param messages: The list of message dictionaries.
  127. :return: The updated list of message dictionaries.
  128. """
  129. if messages and messages[-1].get("role") == "assistant":
  130. messages[-1]["content"] = f"{messages[-1]['content']}\n{content}"
  131. else:
  132. # Insert at the end
  133. messages.append({"role": "assistant", "content": content})
  134. return messages
  135. def openai_chat_message_template(model: str):
  136. return {
  137. "id": f"{model}-{str(uuid.uuid4())}",
  138. "created": int(time.time()),
  139. "model": model,
  140. "choices": [{"index": 0, "logprobs": None, "finish_reason": None}],
  141. }
  142. def openai_chat_chunk_message_template(
  143. model: str,
  144. content: Optional[str] = None,
  145. tool_calls: Optional[list[dict]] = None,
  146. usage: Optional[dict] = None,
  147. ) -> dict:
  148. template = openai_chat_message_template(model)
  149. template["object"] = "chat.completion.chunk"
  150. template["choices"][0]["index"] = 0
  151. template["choices"][0]["delta"] = {}
  152. if content:
  153. template["choices"][0]["delta"]["content"] = content
  154. if tool_calls:
  155. template["choices"][0]["delta"]["tool_calls"] = tool_calls
  156. if not content and not tool_calls:
  157. template["choices"][0]["finish_reason"] = "stop"
  158. if usage:
  159. template["usage"] = usage
  160. return template
  161. def openai_chat_completion_message_template(
  162. model: str, message: Optional[str] = None, usage: Optional[dict] = None
  163. ) -> dict:
  164. template = openai_chat_message_template(model)
  165. template["object"] = "chat.completion"
  166. if message is not None:
  167. template["choices"][0]["message"] = {"content": message, "role": "assistant"}
  168. template["choices"][0]["finish_reason"] = "stop"
  169. if usage:
  170. template["usage"] = usage
  171. return template
  172. def get_gravatar_url(email):
  173. # Trim leading and trailing whitespace from
  174. # an email address and force all characters
  175. # to lower case
  176. address = str(email).strip().lower()
  177. # Create a SHA256 hash of the final string
  178. hash_object = hashlib.sha256(address.encode())
  179. hash_hex = hash_object.hexdigest()
  180. # Grab the actual image URL
  181. return f"https://www.gravatar.com/avatar/{hash_hex}?d=mp"
  182. def calculate_sha256(file_path, chunk_size):
  183. # Compute SHA-256 hash of a file efficiently in chunks
  184. sha256 = hashlib.sha256()
  185. with open(file_path, "rb") as f:
  186. while chunk := f.read(chunk_size):
  187. sha256.update(chunk)
  188. return sha256.hexdigest()
  189. def calculate_sha256_string(string):
  190. # Create a new SHA-256 hash object
  191. sha256_hash = hashlib.sha256()
  192. # Update the hash object with the bytes of the input string
  193. sha256_hash.update(string.encode("utf-8"))
  194. # Get the hexadecimal representation of the hash
  195. hashed_string = sha256_hash.hexdigest()
  196. return hashed_string
  197. def validate_email_format(email: str) -> bool:
  198. if email.endswith("@localhost"):
  199. return True
  200. return bool(re.match(r"[^@]+@[^@]+\.[^@]+", email))
  201. def sanitize_filename(file_name):
  202. # Convert to lowercase
  203. lower_case_file_name = file_name.lower()
  204. # Remove special characters using regular expression
  205. sanitized_file_name = re.sub(r"[^\w\s]", "", lower_case_file_name)
  206. # Replace spaces with dashes
  207. final_file_name = re.sub(r"\s+", "-", sanitized_file_name)
  208. return final_file_name
  209. def extract_folders_after_data_docs(path):
  210. # Convert the path to a Path object if it's not already
  211. path = Path(path)
  212. # Extract parts of the path
  213. parts = path.parts
  214. # Find the index of '/data/docs' in the path
  215. try:
  216. index_data_docs = parts.index("data") + 1
  217. index_docs = parts.index("docs", index_data_docs) + 1
  218. except ValueError:
  219. return []
  220. # Exclude the filename and accumulate folder names
  221. tags = []
  222. folders = parts[index_docs:-1]
  223. for idx, _ in enumerate(folders):
  224. tags.append("/".join(folders[: idx + 1]))
  225. return tags
  226. def parse_duration(duration: str) -> Optional[timedelta]:
  227. if duration == "-1" or duration == "0":
  228. return None
  229. # Regular expression to find number and unit pairs
  230. pattern = r"(-?\d+(\.\d+)?)(ms|s|m|h|d|w)"
  231. matches = re.findall(pattern, duration)
  232. if not matches:
  233. raise ValueError("Invalid duration string")
  234. total_duration = timedelta()
  235. for number, _, unit in matches:
  236. number = float(number)
  237. if unit == "ms":
  238. total_duration += timedelta(milliseconds=number)
  239. elif unit == "s":
  240. total_duration += timedelta(seconds=number)
  241. elif unit == "m":
  242. total_duration += timedelta(minutes=number)
  243. elif unit == "h":
  244. total_duration += timedelta(hours=number)
  245. elif unit == "d":
  246. total_duration += timedelta(days=number)
  247. elif unit == "w":
  248. total_duration += timedelta(weeks=number)
  249. return total_duration
  250. def parse_ollama_modelfile(model_text):
  251. parameters_meta = {
  252. "mirostat": int,
  253. "mirostat_eta": float,
  254. "mirostat_tau": float,
  255. "num_ctx": int,
  256. "repeat_last_n": int,
  257. "repeat_penalty": float,
  258. "temperature": float,
  259. "seed": int,
  260. "tfs_z": float,
  261. "num_predict": int,
  262. "top_k": int,
  263. "top_p": float,
  264. "num_keep": int,
  265. "typical_p": float,
  266. "presence_penalty": float,
  267. "frequency_penalty": float,
  268. "penalize_newline": bool,
  269. "numa": bool,
  270. "num_batch": int,
  271. "num_gpu": int,
  272. "main_gpu": int,
  273. "low_vram": bool,
  274. "f16_kv": bool,
  275. "vocab_only": bool,
  276. "use_mmap": bool,
  277. "use_mlock": bool,
  278. "num_thread": int,
  279. }
  280. data = {"base_model_id": None, "params": {}}
  281. # Parse base model
  282. base_model_match = re.search(
  283. r"^FROM\s+(\w+)", model_text, re.MULTILINE | re.IGNORECASE
  284. )
  285. if base_model_match:
  286. data["base_model_id"] = base_model_match.group(1)
  287. # Parse template
  288. template_match = re.search(
  289. r'TEMPLATE\s+"""(.+?)"""', model_text, re.DOTALL | re.IGNORECASE
  290. )
  291. if template_match:
  292. data["params"] = {"template": template_match.group(1).strip()}
  293. # Parse stops
  294. stops = re.findall(r'PARAMETER stop "(.*?)"', model_text, re.IGNORECASE)
  295. if stops:
  296. data["params"]["stop"] = stops
  297. # Parse other parameters from the provided list
  298. for param, param_type in parameters_meta.items():
  299. param_match = re.search(rf"PARAMETER {param} (.+)", model_text, re.IGNORECASE)
  300. if param_match:
  301. value = param_match.group(1)
  302. try:
  303. if param_type is int:
  304. value = int(value)
  305. elif param_type is float:
  306. value = float(value)
  307. elif param_type is bool:
  308. value = value.lower() == "true"
  309. except Exception as e:
  310. print(e)
  311. continue
  312. data["params"][param] = value
  313. # Parse adapter
  314. adapter_match = re.search(r"ADAPTER (.+)", model_text, re.IGNORECASE)
  315. if adapter_match:
  316. data["params"]["adapter"] = adapter_match.group(1)
  317. # Parse system description
  318. system_desc_match = re.search(
  319. r'SYSTEM\s+"""(.+?)"""', model_text, re.DOTALL | re.IGNORECASE
  320. )
  321. system_desc_match_single = re.search(
  322. r"SYSTEM\s+([^\n]+)", model_text, re.IGNORECASE
  323. )
  324. if system_desc_match:
  325. data["params"]["system"] = system_desc_match.group(1).strip()
  326. elif system_desc_match_single:
  327. data["params"]["system"] = system_desc_match_single.group(1).strip()
  328. # Parse messages
  329. messages = []
  330. message_matches = re.findall(r"MESSAGE (\w+) (.+)", model_text, re.IGNORECASE)
  331. for role, content in message_matches:
  332. messages.append({"role": role, "content": content})
  333. if messages:
  334. data["params"]["messages"] = messages
  335. return data