misc.py 9.4 KB

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