misc.py 12 KB

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