Finds the shortest valid context at the beginning of the input text. Scans the text `txt` from the beginning up to `max_len` characters. It looks for the first occurrence of a character from `self.split_tokens`. If found, it checks if the substring ending at that to
(self, txt: str, min_len: int = 6, max_len: int = 120, min_alnum_count: int = 10)
| 31 | self.split_tokens: Set[str] = set(split_tokens) |
| 32 | |
| 33 | def get_context(self, txt: str, min_len: int = 6, max_len: int = 120, min_alnum_count: int = 10) -> Tuple[Optional[str], Optional[str]]: |
| 34 | """ |
| 35 | Finds the shortest valid context at the beginning of the input text. |
| 36 | |
| 37 | Scans the text `txt` from the beginning up to `max_len` characters. It looks |
| 38 | for the first occurrence of a character from `self.split_tokens`. If found, |
| 39 | it checks if the substring ending at that token meets the `min_len` (overall |
| 40 | length) and `min_alnum_count` (alphanumeric character count) criteria. |
| 41 | |
| 42 | Args: |
| 43 | txt: The input string from which to extract the context. |
| 44 | min_len: The minimum allowable overall length for the extracted context substring. |
| 45 | max_len: The maximum allowable overall length for the extracted context substring. |
| 46 | The search stops after examining this many characters. |
| 47 | min_alnum_count: The minimum number of alphanumeric characters required within |
| 48 | the extracted context substring. |
| 49 | |
| 50 | Returns: |
| 51 | A tuple containing: |
| 52 | - The extracted context string if found, otherwise None. |
| 53 | - The remaining part of the input string after the context, otherwise None. |
| 54 | Returns (None, None) if no suitable context is found within the constraints. |
| 55 | """ |
| 56 | alnum_count = 0 |
| 57 | |
| 58 | for i in range(1, min(len(txt), max_len) + 1): |
| 59 | char = txt[i - 1] |
| 60 | if char.isalnum(): |
| 61 | alnum_count += 1 |
| 62 | |
| 63 | # Check if the current character is a potential context end |
| 64 | if char in self.split_tokens: |
| 65 | # Check if length and alphanumeric count criteria are met |
| 66 | if i >= min_len and alnum_count >= min_alnum_count: |
| 67 | context_str = txt[:i] |
| 68 | remaining_str = txt[i:] |
| 69 | logger.info(f"🧠 {Colors.MAGENTA}Context found after char no: {i}, context: {context_str}") |
| 70 | return context_str, remaining_str |
| 71 | |
| 72 | # No suitable context found within the max_len limit |
| 73 | return None, None |
no outgoing calls
no test coverage detected