Spaces:
Sleeping
Sleeping
SmallConfidence deploy
Deploy 1c7e795: sign-in, rate limits, content, crisis lines, streaming
73ecc58 Download content.py from scchess/confidence-api: direct link, hf CLI and curl.
- Browser
- Download file 5 kB
-
https://huggingface.co/spaces/scchess/confidence-api/resolve/main/content.py
- Command line
-
hf download hf://spaces/scchess/confidence-api/content.py
-
curl -L -o content.py https://huggingface.co/spaces/scchess/confidence-api/resolve/main/content.py
5 kB
| """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 | |
| 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 | |
| ) | |