misc.py 9.1 KB

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