File size: 8,922 Bytes
ddcb55f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
185
186
187
188
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
"""

Hierarchical Topic Stack & Tracker

----------------------------------

Maintains a scoped topic hierarchy for multi-turn conversational reasoning.

Supports topic drill-down, topic shift detection, tangents, and topic resumption.

"""

from __future__ import annotations

import time
import logging
from dataclasses import dataclass, field, asdict
from typing import Optional, Any

logger = logging.getLogger(__name__)


@dataclass
class TopicFrame:
    """A single frame in the hierarchical topic stack."""

    topic: str
    topic_type: str = "concept"  # "algorithm", "data_structure", "concept", "aspect"
    aspect: Optional[str] = None  # e.g., "time_complexity", "code", "space_complexity"
    depth: int = 0
    confidence: float = 1.0
    turns_active: int = 1
    timestamp: float = field(default_factory=time.time)

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> "TopicFrame":
        return cls(**data)


class HierarchicalTopicTracker:
    """

    Manages a stack of topics to allow conversational drill-down and topic shifts.



    Examples:

    - User: "What is a binary tree?" -> Stack: [binary_tree]

    - User: "What is an AVL tree?" -> Drill-down / Subtopic: [binary_tree, avl_tree]

    - User: "How do rotations work?" -> Drill-down Aspect: [binary_tree, avl_tree, rotations]

    - User: "Now tell me about Dijkstra" -> Topic Shift: [dijkstra]

    - User: "Going back to AVL trees" -> Topic Resume: [binary_tree, avl_tree]

    """

    def __init__(self, max_depth: int = 5) -> None:
        self.max_depth = max_depth
        self.stack: list[TopicFrame] = []

    @property
    def current_topic(self) -> Optional[str]:
        """Return the active topic at the top of the stack."""
        return self.stack[-1].topic if self.stack else None

    @property
    def parent_topic(self) -> Optional[str]:
        """Return the parent topic directly below the current active topic."""
        return self.stack[-2].topic if len(self.stack) >= 2 else None

    @property
    def stack_depth(self) -> int:
        """Return current depth of the topic stack."""
        return len(self.stack)

    @property
    def current_aspect(self) -> Optional[str]:
        """Return the active aspect at the top of the stack."""
        return self.stack[-1].aspect if self.stack else None

    @property
    def topic_path(self) -> list[str]:
        """Return list of topic names from root to top of stack."""
        return [frame.topic for frame in self.stack]

    def pop(self) -> Optional[TopicFrame]:
        """Pop the current active frame and restore the prior topic."""
        return self.stack.pop() if self.stack else None

    def shift_topic(

        self,

        topic: str,

        topic_type: str = "concept",

        aspect: Optional[str] = None,

        confidence: float = 1.0,

    ) -> TopicFrame:
        """Explicitly reset stack and set a new primary topic."""
        clean_topic = topic.strip().lower()
        new_frame = TopicFrame(
            topic=clean_topic,
            topic_type=topic_type,
            aspect=aspect,
            depth=0,
            confidence=confidence,
        )
        self.stack = [new_frame]
        logger.debug(f"Topic explicitly shifted to: {clean_topic}")
        return new_frame

    def push(

        self,

        topic: str,

        topic_type: str = "concept",

        aspect: Optional[str] = None,

        confidence: float = 1.0,

    ) -> TopicFrame:
        """

        Push or update a topic on the stack.

        Returns the active TopicFrame.

        """
        clean_topic = topic.strip().lower()
        if not clean_topic:
            return self.stack[-1] if self.stack else TopicFrame(topic="")

        # Check if topic already exists in stack (Topic Resume)
        for i, frame in enumerate(self.stack):
            if frame.topic == clean_topic:
                # Pop frames above it to resume this topic
                self.stack = self.stack[: i + 1]
                self.stack[-1].turns_active += 1
                if aspect:
                    self.stack[-1].aspect = aspect
                logger.debug(f"Topic resumed: {clean_topic} at depth {i}")
                return self.stack[-1]

        # Check if this is a sub-aspect or continuation of current topic
        if self.stack:
            curr = self.stack[-1]
            if curr.topic == clean_topic:
                curr.turns_active += 1
                if aspect:
                    curr.aspect = aspect
                return curr

            # Check for drill-down (if topic is related or explicitly scoped or aspect/concept)
            if self._is_subtopic(curr.topic, clean_topic) or topic_type in ("aspect", "concept"):
                new_frame = TopicFrame(
                    topic=clean_topic,
                    topic_type=topic_type,
                    aspect=aspect,
                    depth=len(self.stack),
                    confidence=confidence,
                )
                if len(self.stack) >= self.max_depth:
                    self.stack.pop(0)
                self.stack.append(new_frame)
                logger.debug(f"Topic drill-down: {curr.topic} -> {clean_topic}")
                return new_frame

        # Otherwise, complete Topic Shift
        new_frame = TopicFrame(
            topic=clean_topic,
            topic_type=topic_type,
            aspect=aspect,
            depth=0,
            confidence=confidence,
        )
        self.stack = [new_frame]
        logger.debug(f"Topic shifted to: {clean_topic}")
        return new_frame

    def update_aspect(self, aspect: str) -> None:
        """Update aspect of current top topic (e.g. time_complexity)."""
        if self.stack:
            self.stack[-1].aspect = aspect

    def decay_topics(self) -> None:
        """Increment turns active and prune stale topics."""
        for frame in self.stack:
            frame.turns_active += 1

    def clear(self) -> None:
        """Clear topic stack."""
        self.stack.clear()

    def to_dict(self) -> list[dict[str, Any]]:
        return [f.to_dict() for f in self.stack]

    @classmethod
    def from_dict(cls, data: list[dict[str, Any]], max_depth: int = 5) -> "HierarchicalTopicTracker":
        tracker = cls(max_depth=max_depth)
        if isinstance(data, list):
            tracker.stack = [TopicFrame.from_dict(d) for d in data if isinstance(d, dict)]
        return tracker

    def _is_subtopic(self, parent: str, candidate: str) -> bool:
        """Heuristic to check if candidate is a subtopic of parent."""
        parent_words = set(parent.split())
        candidate_words = set(candidate.split())
        if parent_words & candidate_words:
            return True

        subtopic_map = {
            # DSA Data Structures
            "tree": {"binary_tree", "bst", "avl", "red_black_tree", "trie", "heap", "rotations", "traversal"},
            "binary_tree": {"bst", "avl", "traversal", "diameter", "balanced_tree", "rotations"},
            "graph": {"dijkstra", "bfs", "dfs", "a_star", "kruskal", "prim", "floyd_warshall", "cycle_detection"},
            "sorting": {"quick_sort", "merge_sort", "radix_sort", "bubble_sort", "counting_sort", "custom_comparator"},
            "linked_list": {"singly_linked_list", "doubly_linked_list", "circular_linked_list"},
            # OOP & Programming Language Concepts (pl_extra.csv)
            "oop": {"class", "object", "encapsulation", "abstraction", "inheritance", "polymorphism", "solid"},
            "object_oriented_programming": {"class", "object", "encapsulation", "abstraction", "inheritance", "polymorphism", "solid"},
            "inheritance": {"diamond_problem", "single", "multiple", "multilevel", "hierarchical", "hybrid", "super", "subclass", "overriding"},
            "polymorphism": {"overloading", "overriding", "virtual_function", "dynamic_dispatch", "compile_time", "runtime"},
            "class": {"constructor", "destructor", "method", "variable", "static", "instance", "abstract_class", "interface"},
            "memory": {"stack", "heap", "pointer", "reference", "garbage_collection", "memory_leak", "cache_locality"},
            # Complexity & Platform (extra.csv)
            "complexity": {"time_complexity", "space_complexity", "auxiliary_space", "amortized", "big_o", "worst_case", "best_case", "average_case"},
            "platform": {"tle", "mle", "runtime_error", "wrong_answer", "fast_io", "constraints"},
        }
        for k, sub_set in subtopic_map.items():
            if k in parent and any(sub in candidate for sub in sub_set):
                return True
        return False