misc.py 8.4 KB

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