Spaces:
Sleeping

File size: 4,999 Bytes
73ecc58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Picks app-content notes (src/content.json) to ground a coach's reply.

Notes are tagged with the topic they were written under. A coach draws from
its own topics first, ranked by word overlap with the user's message (BM25),
then adds a couple of strong matches from other topics.
"""

from __future__ import annotations

import json
import math
import re
from collections import Counter
from pathlib import Path
from typing import Any

CONTENT_PATH = Path(__file__).with_name("content.json")

# Top-level coaches cover the topics filed under them in the app.
COACH_SECTIONS: dict[str, list[str]] = {
    "self-acceptance": [
        "self-acceptance",
        "internal-confidence",
        "self-compassion",
        "positive-self-talk",
    ],
    "social-situations": [
        "interactions-in-daily-situations",
        "meeting-new-people",
        "tackling-performance-anxiety",
    ],
    "relationships": [
        "dating-with-confidence",
        "strengthening-existing-relationships",
        "setting-boundaries",
    ],
    "work-life-management": [
        "disarming-imposter-syndrome",
        "confidence-in-your-skills",
        "commanding-the-best-for-yourself",
    ],
    "pressure": ["tackling-performance-anxiety", "positive-self-talk"],
}

_STOP = set(
    """a about after again all am an and any are as at be because been but by can
    could did do does doing don't for from get got had has have having he her him
    his how i i'm if in into is it it's its just know like me more my myself no not
    now of on or our out over really should so some such than that the their them
    then there these they this to too up us very was we were what when where which
    who why will with would you your yours yourself""".split()
)


def _tokens(text: str) -> list[str]:
    words = re.findall(r"[a-z']+", text.lower())
    out = []
    for w in words:
        w = w.strip("'")
        if len(w) < 3 or w in _STOP:
            continue
        # Light stemming so "boundaries"/"boundary", "nervous"/"nerves" meet.
        for suffix in ("ies", "ing", "ed", "es", "s", "ous"):
            if w.endswith(suffix) and len(w) - len(suffix) >= 4:
                w = w[: -len(suffix)]
                break
        out.append(w)
    return out


class ContentIndex:
    def __init__(self, notes: list[dict[str, Any]]):
        self.notes = notes
        self._docs = [_tokens(n["text"]) for n in notes]
        self._tf = [Counter(d) for d in self._docs]
        n = len(notes) or 1
        df: Counter[str] = Counter()
        for doc in self._docs:
            df.update(set(doc))
        self._idf = {
            term: math.log(1 + (n - freq + 0.5) / (freq + 0.5)) for term, freq in df.items()
        }
        self._avg_len = sum(len(d) for d in self._docs) / n

    @classmethod
    def load(cls, path: Path = CONTENT_PATH) -> "ContentIndex":
        if not path.is_file():
            return cls([])
        return cls(json.loads(path.read_text(encoding="utf-8")))

    def _score(self, i: int, query: list[str]) -> float:
        k1, b = 1.5, 0.75
        tf = self._tf[i]
        length = len(self._docs[i]) or 1
        score = 0.0
        for term in query:
            f = tf.get(term)
            if not f:
                continue
            idf = self._idf.get(term, 0.0)
            score += idf * f * (k1 + 1) / (f + k1 * (1 - b + b * length / self._avg_len))
        return score

    def sections_for(self, personality_id: str) -> list[str]:
        return COACH_SECTIONS.get(personality_id, [personality_id])

    def search(
        self,
        personality_id: str,
        message: str,
        own: int = 4,
        other: int = 2,
        min_other_score: float = 2.0,
    ) -> list[str]:
        """Notes for this coach and message, best first."""
        if not self.notes:
            return []
        query = _tokens(message)
        sections = set(self.sections_for(personality_id))

        own_ranked: list[tuple[float, int]] = []
        other_ranked: list[tuple[float, int]] = []
        for i, note in enumerate(self.notes):
            score = self._score(i, query) if query else 0.0
            if note["section"] in sections:
                own_ranked.append((score, i))
            elif score >= min_other_score:
                other_ranked.append((score, i))

        # Ties keep document order, so a greeting-only message gets the
        # opening notes of the coach's own topic.
        own_ranked.sort(key=lambda s: (-s[0], s[1]))
        other_ranked.sort(key=lambda s: (-s[0], s[1]))
        picked = [i for _, i in own_ranked[:own]] + [i for _, i in other_ranked[:other]]
        return [self.notes[i]["text"] for i in picked]


def prompt_block(notes: list[str]) -> str:
    if not notes:
        return ""
    lines = "\n".join(f"- {n}" for n in notes)
    return (
        "App content for this topic (your main source; weave in what fits, in your own "
        "words, and never paste it as a list):\n" + lines
    )