-
Notifications
You must be signed in to change notification settings - Fork 697
Sort completion candidates by frecency from history #2158
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rolandwalker
wants to merge
1
commit into
main
Choose a base branch
from
RW/calculate-history-frecency
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,28 +1,152 @@ | ||
| from collections import defaultdict | ||
| from collections.abc import Iterable, Mapping | ||
| from itertools import islice | ||
| import logging | ||
| import os | ||
| from typing import Union | ||
| import re | ||
| import threading | ||
|
|
||
| from prompt_toolkit.history import FileHistory | ||
| from sqlglot import Token, TokenType, tokenize | ||
| from sqlglot.errors import TokenError | ||
|
|
||
| from mycli.packages.sql_utils import is_password_change | ||
|
|
||
| _StrOrBytesPath = Union[str, bytes, os.PathLike] | ||
| logger = logging.getLogger(__name__) | ||
|
|
||
| _StrOrBytesPath = str | bytes | os.PathLike[str] | os.PathLike[bytes] | ||
| FRECENCY_HISTORY_ENTRIES = 1000 | ||
| FRECENCY_REFRESH_INTERVAL = 50 | ||
| _FRECENCY_LITERAL_TYPES = frozenset({ | ||
| TokenType.STRING, | ||
| TokenType.NUMBER, | ||
| TokenType.BIT_STRING, | ||
| TokenType.HEX_STRING, | ||
| TokenType.BYTE_STRING, | ||
| TokenType.NATIONAL_STRING, | ||
| TokenType.RAW_STRING, | ||
| TokenType.HEREDOC_STRING, | ||
| TokenType.UNICODE_STRING, | ||
| }) | ||
| _FRECENCY_WORD_PATTERN = re.compile(r'^[^\W\d][\w$]*(?:\s+[^\W\d][\w$]*)*$') | ||
|
|
||
|
|
||
| def _normalize_frecency_token(token: Token) -> str | None: | ||
| if token.token_type in _FRECENCY_LITERAL_TYPES: | ||
| return None | ||
| if token.token_type != TokenType.IDENTIFIER and not _FRECENCY_WORD_PATTERN.fullmatch(token.text): | ||
| return None | ||
| return token.text.casefold() or None | ||
|
|
||
|
|
||
| def _calculate_frecency( | ||
| entries: Iterable[str], | ||
| history_entries: int = FRECENCY_HISTORY_ENTRIES, | ||
| ) -> dict[str, float]: | ||
| frecency: defaultdict[str, float] = defaultdict(float) | ||
| for position, entry in enumerate(islice(entries, max(0, history_entries))): | ||
| weight = 1 / (position + 1) | ||
| try: | ||
| tokens = tokenize(entry, dialect='mysql') | ||
| except TokenError: | ||
| continue | ||
| for token in tokens: | ||
| if normalized := _normalize_frecency_token(token): | ||
| frecency[normalized] += weight | ||
| return dict(frecency) | ||
|
|
||
|
|
||
| def frecency_score(text: str, frecency: Mapping[str, float]) -> float: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Potential for caching/memoization if you want to reduce load on larger schemas: |
||
| try: | ||
| tokens = tokenize(text, dialect='mysql') | ||
| except TokenError: | ||
| return 0.0 | ||
| normalized_tokens = [normalized for token in tokens if (normalized := _normalize_frecency_token(token))] | ||
| if not normalized_tokens: | ||
| return 0.0 | ||
| return sum(frecency.get(token, 0.0) for token in normalized_tokens) / len(normalized_tokens) | ||
|
|
||
|
|
||
| class FileHistoryWithTimestamp(FileHistory): | ||
| """ | ||
| :class:`.FileHistory` class that stores all strings in a file with timestamp. | ||
| """ | ||
|
|
||
| def __init__(self, filename: _StrOrBytesPath) -> None: | ||
| def __init__( | ||
| self, | ||
| filename: _StrOrBytesPath, | ||
| frecency_history_entries: int = FRECENCY_HISTORY_ENTRIES, | ||
| frecency_refresh_interval: int = FRECENCY_REFRESH_INTERVAL, | ||
| ) -> None: | ||
| self.filename = filename | ||
| super().__init__(filename) | ||
| self.frecency_history_entries = max(0, frecency_history_entries) | ||
| self.frecency_refresh_interval = max(0, frecency_refresh_interval) | ||
| self._frecency: dict[str, float] = {} | ||
| self._frecency_lock = threading.Lock() | ||
| self._frecency_generation = 0 | ||
| self._frecency_thread: threading.Thread | None = None | ||
| self._frecency_entries_since_refresh = 0 | ||
| if self.frecency_history_entries: | ||
| self._request_frecency_refresh() | ||
|
|
||
| @property | ||
| def frecency(self) -> dict[str, float]: | ||
| with self._frecency_lock: | ||
| return self._frecency | ||
|
|
||
| def _request_frecency_refresh(self) -> None: | ||
| with self._frecency_lock: | ||
| self._frecency_generation += 1 | ||
| if self._frecency_thread is not None: | ||
| return | ||
| thread = threading.Thread(target=self._refresh_frecency, name='frecency_refresh', daemon=True) | ||
| self._frecency_thread = thread | ||
|
|
||
| try: | ||
| thread.start() | ||
| except Exception: | ||
| with self._frecency_lock: | ||
| if self._frecency_thread is thread: | ||
| self._frecency_thread = None | ||
| logger.exception('Failed to start history frecency calculation.') | ||
|
|
||
| def _refresh_frecency(self) -> None: | ||
| while True: | ||
| with self._frecency_lock: | ||
| generation = self._frecency_generation | ||
|
|
||
| try: | ||
| frecency = _calculate_frecency(self.load_history_strings(), self.frecency_history_entries) | ||
| except Exception: | ||
| logger.exception('Failed to calculate history frecency.') | ||
| with self._frecency_lock: | ||
| if self._frecency_generation != generation: | ||
| continue | ||
| self._frecency_thread = None | ||
| return | ||
|
|
||
| with self._frecency_lock: | ||
| self._frecency = frecency | ||
| if self._frecency_generation == generation: | ||
| self._frecency_thread = None | ||
| return | ||
|
|
||
| def append_string(self, string: str) -> None: | ||
| "Add string to the history." | ||
| self._loaded_strings.insert(0, string) | ||
| if is_password_change(string): | ||
| return | ||
| self.store_string(string) | ||
| if not self.frecency_history_entries or not self.frecency_refresh_interval: | ||
| return | ||
| with self._frecency_lock: | ||
| self._frecency_entries_since_refresh += 1 | ||
| refresh = self._frecency_entries_since_refresh >= self.frecency_refresh_interval | ||
| if refresh: | ||
| self._frecency_entries_since_refresh = 0 | ||
| if refresh: | ||
| self._request_frecency_refresh() | ||
|
|
||
| def load_history_with_timestamp(self) -> list[tuple[str, str]]: | ||
| """ | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should this have similar if/else logic as
frecency_history_entriesabove?