misc.py 9.44 KB
Newer Older
1
from pathlib import Path
Timothy J. Baek's avatar
Timothy J. Baek committed
2
import hashlib
3
import re
Timothy J. Baek's avatar
Timothy J. Baek committed
4
from datetime import timedelta
5
from typing import Optional, List, Tuple
Timothy J. Baek's avatar
Timothy J. Baek committed
6
7
import uuid
import time
Timothy J. Baek's avatar
Timothy J. Baek committed
8
9


10
def get_last_user_message_item(messages: List[dict]) -> Optional[dict]:
Timothy J. Baek's avatar
Timothy J. Baek committed
11
12
    for message in reversed(messages):
        if message["role"] == "user":
13
14
15
16
            return message
    return None


17
18
19
20
21
22
def get_content_from_message(message: dict) -> Optional[str]:
    if isinstance(message["content"], list):
        for item in message["content"]:
            if item["type"] == "text":
                return item["text"]
    else:
23
        return message["content"]
Timothy J. Baek's avatar
Timothy J. Baek committed
24
25
26
    return None


27
28
29
30
31
32
33
34
35
def get_last_user_message(messages: List[dict]) -> Optional[str]:
    message = get_last_user_message_item(messages)
    if message is None:
        return None

    return get_content_from_message(message)


def get_last_assistant_message(messages: List[dict]) -> Optional[str]:
Timothy J. Baek's avatar
Timothy J. Baek committed
36
37
    for message in reversed(messages):
        if message["role"] == "assistant":
38
            return get_content_from_message(message)
Timothy J. Baek's avatar
Timothy J. Baek committed
39
40
41
    return None


42
def get_system_message(messages: List[dict]) -> Optional[dict]:
43
44
45
46
47
48
49
50
51
52
    for message in messages:
        if message["role"] == "system":
            return message
    return None


def remove_system_message(messages: List[dict]) -> List[dict]:
    return [message for message in messages if message["role"] != "system"]


53
def pop_system_message(messages: List[dict]) -> Tuple[Optional[dict], List[dict]]:
54
55
56
    return get_system_message(messages), remove_system_message(messages)


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def prepend_to_first_user_message_content(
    content: str, messages: List[dict]
) -> List[dict]:
    for message in messages:
        if message["role"] == "user":
            if isinstance(message["content"], list):
                for item in message["content"]:
                    if item["type"] == "text":
                        item["text"] = f"{content}\n{item['text']}"
            else:
                message["content"] = f"{content}\n{message['content']}"
            break
    return messages


Timothy J. Baek's avatar
Timothy J. Baek committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def add_or_update_system_message(content: str, messages: List[dict]):
    """
    Adds a new system message at the beginning of the messages list
    or updates the existing system message at the beginning.

    :param msg: The message to be added or appended.
    :param messages: The list of message dictionaries.
    :return: The updated list of message dictionaries.
    """

    if messages and messages[0].get("role") == "system":
        messages[0]["content"] += f"{content}\n{messages[0]['content']}"
    else:
        # Insert at the beginning
        messages.insert(0, {"role": "system", "content": content})

    return messages
Timothy J. Baek's avatar
Timothy J. Baek committed
89

Timothy J. Baek's avatar
Timothy J. Baek committed
90

91
def openai_chat_message_template(model: str):
Timothy J. Baek's avatar
Timothy J. Baek committed
92
93
94
95
    return {
        "id": f"{model}-{str(uuid.uuid4())}",
        "created": int(time.time()),
        "model": model,
96
        "choices": [{"index": 0, "logprobs": None, "finish_reason": None}],
Timothy J. Baek's avatar
Timothy J. Baek committed
97
98
    }

99

100
def openai_chat_chunk_message_template(model: str, message: str) -> dict:
101
    template = openai_chat_message_template(model)
102
103
104
105
106
    template["object"] = "chat.completion.chunk"
    template["choices"][0]["delta"] = {"content": message}
    return template


107
def openai_chat_completion_message_template(model: str, message: str) -> dict:
108
    template = openai_chat_message_template(model)
109
110
111
    template["object"] = "chat.completion"
    template["choices"][0]["message"] = {"content": message, "role": "assistant"}
    template["choices"][0]["finish_reason"] = "stop"
112
    return template
113

Timothy J. Baek's avatar
Timothy J. Baek committed
114
115
116
117
118
119
120
121
122
123
124
125

def get_gravatar_url(email):
    # Trim leading and trailing whitespace from
    # an email address and force all characters
    # to lower case
    address = str(email).strip().lower()

    # Create a SHA256 hash of the final string
    hash_object = hashlib.sha256(address.encode())
    hash_hex = hash_object.hexdigest()

    # Grab the actual image URL
126
    return f"https://www.gravatar.com/avatar/{hash_hex}?d=mp"
Timothy J. Baek's avatar
Timothy J. Baek committed
127
128
129
130
131
132
133
134


def calculate_sha256(file):
    sha256 = hashlib.sha256()
    # Read the file in chunks to efficiently handle large files
    for chunk in iter(lambda: file.read(8192), b""):
        sha256.update(chunk)
    return sha256.hexdigest()
135
136


Timothy J. Baek's avatar
Timothy J. Baek committed
137
138
139
140
141
142
143
144
145
146
def calculate_sha256_string(string):
    # Create a new SHA-256 hash object
    sha256_hash = hashlib.sha256()
    # Update the hash object with the bytes of the input string
    sha256_hash.update(string.encode("utf-8"))
    # Get the hexadecimal representation of the hash
    hashed_string = sha256_hash.hexdigest()
    return hashed_string


147
def validate_email_format(email: str) -> bool:
148
149
150
151
    if email.endswith("@localhost"):
        return True

    return bool(re.match(r"[^@]+@[^@]+\.[^@]+", email))
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184


def sanitize_filename(file_name):
    # Convert to lowercase
    lower_case_file_name = file_name.lower()

    # Remove special characters using regular expression
    sanitized_file_name = re.sub(r"[^\w\s]", "", lower_case_file_name)

    # Replace spaces with dashes
    final_file_name = re.sub(r"\s+", "-", sanitized_file_name)

    return final_file_name


def extract_folders_after_data_docs(path):
    # Convert the path to a Path object if it's not already
    path = Path(path)

    # Extract parts of the path
    parts = path.parts

    # Find the index of '/data/docs' in the path
    try:
        index_data_docs = parts.index("data") + 1
        index_docs = parts.index("docs", index_data_docs) + 1
    except ValueError:
        return []

    # Exclude the filename and accumulate folder names
    tags = []

    folders = parts[index_docs:-1]
185
    for idx, _ in enumerate(folders):
186
187
188
        tags.append("/".join(folders[: idx + 1]))

    return tags
Timothy J. Baek's avatar
Timothy J. Baek committed
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219


def parse_duration(duration: str) -> Optional[timedelta]:
    if duration == "-1" or duration == "0":
        return None

    # Regular expression to find number and unit pairs
    pattern = r"(-?\d+(\.\d+)?)(ms|s|m|h|d|w)"
    matches = re.findall(pattern, duration)

    if not matches:
        raise ValueError("Invalid duration string")

    total_duration = timedelta()

    for number, _, unit in matches:
        number = float(number)
        if unit == "ms":
            total_duration += timedelta(milliseconds=number)
        elif unit == "s":
            total_duration += timedelta(seconds=number)
        elif unit == "m":
            total_duration += timedelta(minutes=number)
        elif unit == "h":
            total_duration += timedelta(hours=number)
        elif unit == "d":
            total_duration += timedelta(days=number)
        elif unit == "w":
            total_duration += timedelta(weeks=number)

    return total_duration
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235


def parse_ollama_modelfile(model_text):
    parameters_meta = {
        "mirostat": int,
        "mirostat_eta": float,
        "mirostat_tau": float,
        "num_ctx": int,
        "repeat_last_n": int,
        "repeat_penalty": float,
        "temperature": float,
        "seed": int,
        "tfs_z": float,
        "num_predict": int,
        "top_k": int,
        "top_p": float,
Timothy J. Baek's avatar
Timothy J. Baek committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
        "num_keep": int,
        "typical_p": float,
        "presence_penalty": float,
        "frequency_penalty": float,
        "penalize_newline": bool,
        "numa": bool,
        "num_batch": int,
        "num_gpu": int,
        "main_gpu": int,
        "low_vram": bool,
        "f16_kv": bool,
        "vocab_only": bool,
        "use_mmap": bool,
        "use_mlock": bool,
        "num_thread": int,
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
    }

    data = {"base_model_id": None, "params": {}}

    # Parse base model
    base_model_match = re.search(
        r"^FROM\s+(\w+)", model_text, re.MULTILINE | re.IGNORECASE
    )
    if base_model_match:
        data["base_model_id"] = base_model_match.group(1)

    # Parse template
    template_match = re.search(
        r'TEMPLATE\s+"""(.+?)"""', model_text, re.DOTALL | re.IGNORECASE
    )
    if template_match:
        data["params"] = {"template": template_match.group(1).strip()}

    # Parse stops
    stops = re.findall(r'PARAMETER stop "(.*?)"', model_text, re.IGNORECASE)
    if stops:
        data["params"]["stop"] = stops

    # Parse other parameters from the provided list
    for param, param_type in parameters_meta.items():
        param_match = re.search(rf"PARAMETER {param} (.+)", model_text, re.IGNORECASE)
        if param_match:
            value = param_match.group(1)
Timothy J. Baek's avatar
Timothy J. Baek committed
279
280

            try:
281
                if param_type is int:
Timothy J. Baek's avatar
Timothy J. Baek committed
282
                    value = int(value)
283
                elif param_type is float:
Timothy J. Baek's avatar
Timothy J. Baek committed
284
                    value = float(value)
285
                elif param_type is bool:
Timothy J. Baek's avatar
Timothy J. Baek committed
286
287
288
289
290
                    value = value.lower() == "true"
            except Exception as e:
                print(e)
                continue

291
292
293
294
295
296
297
298
299
300
301
            data["params"][param] = value

    # Parse adapter
    adapter_match = re.search(r"ADAPTER (.+)", model_text, re.IGNORECASE)
    if adapter_match:
        data["params"]["adapter"] = adapter_match.group(1)

    # Parse system description
    system_desc_match = re.search(
        r'SYSTEM\s+"""(.+?)"""', model_text, re.DOTALL | re.IGNORECASE
    )
Timothy J. Baek's avatar
Timothy J. Baek committed
302
303
304
305
    system_desc_match_single = re.search(
        r"SYSTEM\s+([^\n]+)", model_text, re.IGNORECASE
    )

306
307
    if system_desc_match:
        data["params"]["system"] = system_desc_match.group(1).strip()
Timothy J. Baek's avatar
Timothy J. Baek committed
308
309
    elif system_desc_match_single:
        data["params"]["system"] = system_desc_match_single.group(1).strip()
310
311
312
313
314
315
316
317
318
319
320

    # Parse messages
    messages = []
    message_matches = re.findall(r"MESSAGE (\w+) (.+)", model_text, re.IGNORECASE)
    for role, content in message_matches:
        messages.append({"role": role, "content": content})

    if messages:
        data["params"]["messages"] = messages

    return data