Skip to content

Commit b554ea5

Browse files
refactor: Improve context item retrieval logic
- Add ordered_ids and id_to_index for efficient lookups - Update row iteration for context retrieval - Handle out-of-bounds indices gracefully
1 parent 0b610d8 commit b554ea5

1 file changed

Lines changed: 11 additions & 7 deletions

File tree

lib/context.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,30 +21,34 @@ def __init__(self, paragraph_limit: int = 3, max_tokens: int = 2000, position: s
2121
self.max_tokens = max_tokens
2222
self.position = position
2323
self.paragraphs = {}
24+
self.ordered_ids = []
25+
self.id_to_index = {}
2426

2527
def load_paragraphs(self, paragraphs):
2628
"""Load all paragraphs to allow direct lookup by row index for concurrent translation."""
2729
self.paragraphs = {int(p.id): p for p in paragraphs}
28-
# print(f"DEBUG: ContextManager loaded {len(self.paragraphs)} paragraphs. Keys: {list(self.paragraphs.keys())[:10]}...")
30+
self.ordered_ids = sorted(self.paragraphs.keys())
31+
self.id_to_index = {id_: idx for idx, id_ in enumerate(self.ordered_ids)}
2932

3033
def get_context_items(self, current_row: int) -> List[dict]:
3134
"""Fetch the previous or next valid context paragraphs based on the current row and stored position."""
32-
if current_row < 0 or not self.paragraphs:
35+
if current_row < 0 or not self.paragraphs or current_row not in self.id_to_index:
3336
return []
3437

38+
current_idx = self.id_to_index[current_row]
3539
items = []
3640
total_chars = 0
3741

3842
# Determine search range based on stored position
3943
if self.position == 'before':
40-
rows = range(current_row - 1, current_row - 1 - self.paragraph_limit, -1)
44+
rows = range(current_idx - 1, max(current_idx - self.paragraph_limit - 1, -1), -1)
4145
else:
42-
rows = range(current_row + 1, current_row + 1 + self.paragraph_limit)
43-
46+
rows = range(current_idx + 1, min(current_idx + self.paragraph_limit + 1, len(self.ordered_ids)))
47+
4448
for row in rows:
45-
if row not in self.paragraphs:
49+
if row < 0 or row >= len(self.ordered_ids):
4650
continue
47-
51+
row = self.ordered_ids[row]
4852
p = self.paragraphs.get(row)
4953
if not p:
5054
continue

0 commit comments

Comments
 (0)