misc.py 12 KB

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