misc.py 9.6 KB

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