misc.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. from utils.task import prompt_template
  9. def get_last_user_message_item(messages: List[dict]) -> Optional[dict]:
  10. for message in reversed(messages):
  11. if message["role"] == "user":
  12. return message
  13. return None
  14. def get_content_from_message(message: dict) -> Optional[str]:
  15. if isinstance(message["content"], list):
  16. for item in message["content"]:
  17. if item["type"] == "text":
  18. return item["text"]
  19. else:
  20. return message["content"]
  21. return None
  22. def get_last_user_message(messages: List[dict]) -> Optional[str]:
  23. message = get_last_user_message_item(messages)
  24. if message is None:
  25. return None
  26. return get_content_from_message(message)
  27. def get_last_assistant_message(messages: List[dict]) -> Optional[str]:
  28. for message in reversed(messages):
  29. if message["role"] == "assistant":
  30. return get_content_from_message(message)
  31. return None
  32. def get_system_message(messages: List[dict]) -> Optional[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[Optional[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 openai_chat_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 openai_chat_chunk_message_template(model: str, message: str):
  76. template = openai_chat_message_template(model)
  77. template["object"] = "chat.completion.chunk"
  78. template["choices"][0]["delta"] = {"content": message}
  79. return template
  80. def openai_chat_completion_message_template(model: str, message: str):
  81. template = openai_chat_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. # inplace function: form_data is modified
  86. def apply_model_system_prompt_to_body(params: dict, form_data: dict, user) -> dict:
  87. system = params.get("system", None)
  88. if not system:
  89. return form_data
  90. if user:
  91. template_params = {
  92. "user_name": user.name,
  93. "user_location": user.info.get("location") if user.info else None,
  94. }
  95. else:
  96. template_params = {}
  97. system = prompt_template(system, **template_params)
  98. form_data["messages"] = add_or_update_system_message(
  99. system, form_data.get("messages", [])
  100. )
  101. return form_data
  102. # inplace function: form_data is modified
  103. def apply_model_params_to_body(params: dict, form_data: dict) -> dict:
  104. if not params:
  105. return form_data
  106. mappings = {
  107. "temperature": float,
  108. "top_p": int,
  109. "max_tokens": int,
  110. "frequency_penalty": int,
  111. "seed": lambda x: x,
  112. "stop": lambda x: [bytes(s, "utf-8").decode("unicode_escape") for s in x],
  113. }
  114. for key, cast_func in mappings.items():
  115. if (value := params.get(key)) is not None:
  116. form_data[key] = cast_func(value)
  117. return form_data
  118. def get_gravatar_url(email):
  119. # Trim leading and trailing whitespace from
  120. # an email address and force all characters
  121. # to lower case
  122. address = str(email).strip().lower()
  123. # Create a SHA256 hash of the final string
  124. hash_object = hashlib.sha256(address.encode())
  125. hash_hex = hash_object.hexdigest()
  126. # Grab the actual image URL
  127. return f"https://www.gravatar.com/avatar/{hash_hex}?d=mp"
  128. def calculate_sha256(file):
  129. sha256 = hashlib.sha256()
  130. # Read the file in chunks to efficiently handle large files
  131. for chunk in iter(lambda: file.read(8192), b""):
  132. sha256.update(chunk)
  133. return sha256.hexdigest()
  134. def calculate_sha256_string(string):
  135. # Create a new SHA-256 hash object
  136. sha256_hash = hashlib.sha256()
  137. # Update the hash object with the bytes of the input string
  138. sha256_hash.update(string.encode("utf-8"))
  139. # Get the hexadecimal representation of the hash
  140. hashed_string = sha256_hash.hexdigest()
  141. return hashed_string
  142. def validate_email_format(email: str) -> bool:
  143. if email.endswith("@localhost"):
  144. return True
  145. return bool(re.match(r"[^@]+@[^@]+\.[^@]+", email))
  146. def sanitize_filename(file_name):
  147. # Convert to lowercase
  148. lower_case_file_name = file_name.lower()
  149. # Remove special characters using regular expression
  150. sanitized_file_name = re.sub(r"[^\w\s]", "", lower_case_file_name)
  151. # Replace spaces with dashes
  152. final_file_name = re.sub(r"\s+", "-", sanitized_file_name)
  153. return final_file_name
  154. def extract_folders_after_data_docs(path):
  155. # Convert the path to a Path object if it's not already
  156. path = Path(path)
  157. # Extract parts of the path
  158. parts = path.parts
  159. # Find the index of '/data/docs' in the path
  160. try:
  161. index_data_docs = parts.index("data") + 1
  162. index_docs = parts.index("docs", index_data_docs) + 1
  163. except ValueError:
  164. return []
  165. # Exclude the filename and accumulate folder names
  166. tags = []
  167. folders = parts[index_docs:-1]
  168. for idx, _ in enumerate(folders):
  169. tags.append("/".join(folders[: idx + 1]))
  170. return tags
  171. def parse_duration(duration: str) -> Optional[timedelta]:
  172. if duration == "-1" or duration == "0":
  173. return None
  174. # Regular expression to find number and unit pairs
  175. pattern = r"(-?\d+(\.\d+)?)(ms|s|m|h|d|w)"
  176. matches = re.findall(pattern, duration)
  177. if not matches:
  178. raise ValueError("Invalid duration string")
  179. total_duration = timedelta()
  180. for number, _, unit in matches:
  181. number = float(number)
  182. if unit == "ms":
  183. total_duration += timedelta(milliseconds=number)
  184. elif unit == "s":
  185. total_duration += timedelta(seconds=number)
  186. elif unit == "m":
  187. total_duration += timedelta(minutes=number)
  188. elif unit == "h":
  189. total_duration += timedelta(hours=number)
  190. elif unit == "d":
  191. total_duration += timedelta(days=number)
  192. elif unit == "w":
  193. total_duration += timedelta(weeks=number)
  194. return total_duration
  195. def parse_ollama_modelfile(model_text):
  196. parameters_meta = {
  197. "mirostat": int,
  198. "mirostat_eta": float,
  199. "mirostat_tau": float,
  200. "num_ctx": int,
  201. "repeat_last_n": int,
  202. "repeat_penalty": float,
  203. "temperature": float,
  204. "seed": int,
  205. "tfs_z": float,
  206. "num_predict": int,
  207. "top_k": int,
  208. "top_p": float,
  209. "num_keep": int,
  210. "typical_p": float,
  211. "presence_penalty": float,
  212. "frequency_penalty": float,
  213. "penalize_newline": bool,
  214. "numa": bool,
  215. "num_batch": int,
  216. "num_gpu": int,
  217. "main_gpu": int,
  218. "low_vram": bool,
  219. "f16_kv": bool,
  220. "vocab_only": bool,
  221. "use_mmap": bool,
  222. "use_mlock": bool,
  223. "num_thread": int,
  224. }
  225. data = {"base_model_id": None, "params": {}}
  226. # Parse base model
  227. base_model_match = re.search(
  228. r"^FROM\s+(\w+)", model_text, re.MULTILINE | re.IGNORECASE
  229. )
  230. if base_model_match:
  231. data["base_model_id"] = base_model_match.group(1)
  232. # Parse template
  233. template_match = re.search(
  234. r'TEMPLATE\s+"""(.+?)"""', model_text, re.DOTALL | re.IGNORECASE
  235. )
  236. if template_match:
  237. data["params"] = {"template": template_match.group(1).strip()}
  238. # Parse stops
  239. stops = re.findall(r'PARAMETER stop "(.*?)"', model_text, re.IGNORECASE)
  240. if stops:
  241. data["params"]["stop"] = stops
  242. # Parse other parameters from the provided list
  243. for param, param_type in parameters_meta.items():
  244. param_match = re.search(rf"PARAMETER {param} (.+)", model_text, re.IGNORECASE)
  245. if param_match:
  246. value = param_match.group(1)
  247. try:
  248. if param_type is int:
  249. value = int(value)
  250. elif param_type is float:
  251. value = float(value)
  252. elif param_type is bool:
  253. value = value.lower() == "true"
  254. except Exception as e:
  255. print(e)
  256. continue
  257. data["params"][param] = value
  258. # Parse adapter
  259. adapter_match = re.search(r"ADAPTER (.+)", model_text, re.IGNORECASE)
  260. if adapter_match:
  261. data["params"]["adapter"] = adapter_match.group(1)
  262. # Parse system description
  263. system_desc_match = re.search(
  264. r'SYSTEM\s+"""(.+?)"""', model_text, re.DOTALL | re.IGNORECASE
  265. )
  266. system_desc_match_single = re.search(
  267. r"SYSTEM\s+([^\n]+)", model_text, re.IGNORECASE
  268. )
  269. if system_desc_match:
  270. data["params"]["system"] = system_desc_match.group(1).strip()
  271. elif system_desc_match_single:
  272. data["params"]["system"] = system_desc_match_single.group(1).strip()
  273. # Parse messages
  274. messages = []
  275. message_matches = re.findall(r"MESSAGE (\w+) (.+)", model_text, re.IGNORECASE)
  276. for role, content in message_matches:
  277. messages.append({"role": role, "content": content})
  278. if messages:
  279. data["params"]["messages"] = messages
  280. return data