misc.py 11 KB

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