|
| 1 | +import asyncio |
| 2 | +import re |
| 3 | +from functools import lru_cache |
| 4 | +from string import Formatter |
| 5 | +from typing import Any, Callable, Mapping, Sequence, Union |
| 6 | + |
| 7 | +import pendulum |
| 8 | +import tiktoken |
| 9 | +import xxhash |
| 10 | +from jinja2 import ChoiceLoader, Environment, StrictUndefined, select_autoescape |
| 11 | + |
| 12 | +import marvin |
| 13 | + |
| 14 | +jinja_env = Environment( |
| 15 | + loader=ChoiceLoader( |
| 16 | + [ |
| 17 | + # PackageLoader("marvin", "prompts"), |
| 18 | + # PackageLoader("marvin", "programs"), |
| 19 | + ] |
| 20 | + ), |
| 21 | + autoescape=select_autoescape(default_for_string=False), |
| 22 | + trim_blocks=True, |
| 23 | + lstrip_blocks=True, |
| 24 | + enable_async=True, |
| 25 | + auto_reload=True, |
| 26 | + undefined=StrictUndefined, |
| 27 | +) |
| 28 | +jinja_env.globals.update( |
| 29 | + zip=zip, |
| 30 | + str=str, |
| 31 | + len=len, |
| 32 | + arun=asyncio.run, |
| 33 | + pendulum=pendulum, |
| 34 | + dt=lambda: pendulum.now("UTC").to_day_datetime_string(), |
| 35 | +) |
| 36 | + |
| 37 | + |
| 38 | +class StrictFormatter(Formatter): |
| 39 | + """A subclass of formatter that checks for extra keys.""" |
| 40 | + |
| 41 | + def check_unused_args( |
| 42 | + self, |
| 43 | + used_args: Sequence[Union[int, str]], |
| 44 | + args: Sequence, |
| 45 | + kwargs: Mapping[str, Any], |
| 46 | + ) -> None: |
| 47 | + """Check to see if extra parameters are passed.""" |
| 48 | + extra = set(kwargs).difference(used_args) |
| 49 | + if extra: |
| 50 | + raise KeyError(extra) |
| 51 | + |
| 52 | + |
| 53 | +@lru_cache(maxsize=2000) |
| 54 | +def hash_text(*text: str) -> str: |
| 55 | + bs = [t.encode() if not isinstance(t, bytes) else t for t in text] |
| 56 | + return xxhash.xxh3_128_hexdigest(b"".join(bs)) |
| 57 | + |
| 58 | + |
| 59 | +VERSION_NUMBERS = re.compile(r"\b\d+\.\d+(?:\.\d+)?\w*\b") |
| 60 | + |
| 61 | + |
| 62 | +def tokenize(text: str) -> list[int]: |
| 63 | + tokenizer = tiktoken.encoding_for_model("gpt-3.5-turbo") |
| 64 | + return tokenizer.encode(text) |
| 65 | + |
| 66 | + |
| 67 | +def detokenize(tokens: list[int]) -> str: |
| 68 | + tokenizer = tiktoken.encoding_for_model("gpt-3.5-turbo") |
| 69 | + return tokenizer.decode(tokens) |
| 70 | + |
| 71 | + |
| 72 | +def count_tokens(text: str) -> int: |
| 73 | + return len(tokenize(text)) |
| 74 | + |
| 75 | + |
| 76 | +def slice_tokens(text: str, n_tokens: int) -> str: |
| 77 | + tokens = tokenize(text) |
| 78 | + return detokenize(tokens[:n_tokens]) |
| 79 | + |
| 80 | + |
| 81 | +def split_text( |
| 82 | + text: str, |
| 83 | + chunk_size: int, |
| 84 | + chunk_overlap: float = None, |
| 85 | + last_chunk_threshold: float = None, |
| 86 | + return_index: bool = False, |
| 87 | +) -> str | tuple[str, int]: |
| 88 | + """ |
| 89 | + Split a text into a list of strings. Chunks are split by tokens. |
| 90 | +
|
| 91 | + Args: |
| 92 | + text (str): The text to split. |
| 93 | + chunk_size (int): The number of tokens in each chunk. |
| 94 | + chunk_overlap (float): The fraction of overlap between chunks. |
| 95 | + last_chunk_threshold (float): If the last chunk is less than this fraction of |
| 96 | + the chunk_size, it will be added to the prior chunk |
| 97 | + return_index (bool): If True, return a tuple of (chunk, index) where index is the |
| 98 | + character index of the start of the chunk in the original text. |
| 99 | + """ |
| 100 | + if chunk_overlap is None: |
| 101 | + chunk_overlap = 0.1 |
| 102 | + if chunk_overlap < 0 or chunk_overlap > 1: |
| 103 | + raise ValueError("chunk_overlap must be between 0 and 1") |
| 104 | + if last_chunk_threshold is None: |
| 105 | + last_chunk_threshold = 0.25 |
| 106 | + |
| 107 | + tokens = tokenize(text) |
| 108 | + |
| 109 | + chunks = [] |
| 110 | + for i in range(0, len(tokens), chunk_size - int(chunk_overlap * chunk_size)): |
| 111 | + chunks.append((tokens[i : i + chunk_size], len(detokenize(tokens[:i])))) |
| 112 | + |
| 113 | + # if the last chunk is too small, merge it with the previous chunk |
| 114 | + if len(chunks) > 1 and len(chunks[-1][0]) < chunk_size * last_chunk_threshold: |
| 115 | + chunks[-2][0].extend(chunks.pop(-1)[0]) |
| 116 | + |
| 117 | + if return_index: |
| 118 | + return [(detokenize(chunk), index) for chunk, index in chunks] |
| 119 | + else: |
| 120 | + return [detokenize(chunk) for chunk, _ in chunks] |
| 121 | + |
| 122 | + |
| 123 | +def _extract_keywords(text: str, n_keywords: int = None) -> list[str]: |
| 124 | + # deferred import |
| 125 | + import yake |
| 126 | + |
| 127 | + kw = yake.KeywordExtractor( |
| 128 | + lan="en", |
| 129 | + n=1, |
| 130 | + dedupLim=0.9, |
| 131 | + dedupFunc="seqm", |
| 132 | + windowsSize=1, |
| 133 | + top=n_keywords or marvin.settings.default_n_keywords, |
| 134 | + features=None, |
| 135 | + ) |
| 136 | + keywords = kw.extract_keywords(text) |
| 137 | + # return only keyword, not score |
| 138 | + return [k[0] for k in keywords] |
| 139 | + |
| 140 | + |
| 141 | +async def extract_keywords(text: str, n_keywords: int = None) -> list[str]: |
| 142 | + # keyword extraction can take a while and is blocking |
| 143 | + return await marvin.utilities.async_utils.run_async_process( |
| 144 | + _extract_keywords, text=text, n_keywords=n_keywords |
| 145 | + ) |
| 146 | + # return _extract_keywords(text=text, n_keywords=n_keywords) |
| 147 | + |
| 148 | + |
| 149 | +def create_minimap_fn(content: str) -> Callable[[int], str]: |
| 150 | + """ |
| 151 | + Given a document with markdown headers, returns a function that outputs the current headers |
| 152 | + for any character position in the document. |
| 153 | + """ |
| 154 | + minimap: dict[int, str] = {} |
| 155 | + in_code_block = False |
| 156 | + current_stack = {} |
| 157 | + characters = 0 |
| 158 | + for line in content.splitlines(): |
| 159 | + characters += len(line) |
| 160 | + if line.startswith("```"): |
| 161 | + in_code_block = not in_code_block |
| 162 | + if in_code_block: |
| 163 | + continue |
| 164 | + |
| 165 | + if line.startswith("# "): |
| 166 | + current_stack = {1: line} |
| 167 | + elif line.startswith("## "): |
| 168 | + for i in range(2, 6): |
| 169 | + current_stack.pop(i, None) |
| 170 | + current_stack[2] = line |
| 171 | + elif line.startswith("### "): |
| 172 | + for i in range(3, 6): |
| 173 | + current_stack.pop(i, None) |
| 174 | + current_stack[3] = line |
| 175 | + elif line.startswith("#### "): |
| 176 | + for i in range(4, 6): |
| 177 | + current_stack.pop(i, None) |
| 178 | + current_stack[4] = line |
| 179 | + elif line.startswith("##### "): |
| 180 | + for i in range(5, 6): |
| 181 | + current_stack.pop(i, None) |
| 182 | + current_stack[5] = line |
| 183 | + else: |
| 184 | + continue |
| 185 | + |
| 186 | + minimap[characters - len(line)] = current_stack |
| 187 | + |
| 188 | + def get_location_fn(n: int) -> str: |
| 189 | + if n < 0: |
| 190 | + raise ValueError("n must be >= 0") |
| 191 | + # get the stack of headers that is closest to - but before - the current position |
| 192 | + stack = minimap.get(max((k for k in minimap if k <= n), default=0), {}) |
| 193 | + |
| 194 | + ordered_stack = [stack.get(i) for i in range(1, 6)] |
| 195 | + return "\n".join([s for s in ordered_stack if s is not None]) |
| 196 | + |
| 197 | + return get_location_fn |
0 commit comments