misc.py 9.4 KB

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