misc.py 11 KB

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