Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162632 unmodified lines6667686970717273747576777879808182837 unmodified lines9192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841852 unmodified linesfrom sentence_transformers import SentenceTransformerimport torchimport random# Modelsclient = InferenceClient("HuggingFaceH4/zephyr-7b-beta")embedder = SentenceTransformer("all-MiniLM-L6-v2")# Load corpuswith open("journal.txt", "r", encoding="utf-8") as f:journal_text = f.read()# Preprocess into chunksdef preprocess_text(text):cleaned = text.strip()sentences = [s.strip() for s in cleaned.split('.') if s.strip()]sentence_chunks = [s for s in sentences if len(s) > 10]combined_chunks = []for i in range(0, len(sentences), 2):chunk = '. '.join(sentences[i:i+3]).strip()if len(chunk) > 20:combined_chunks.append(chunk)paragraphs = [p.strip() for p in cleaned.split('\n\n') if p.strip()]paragraph_chunks = [p for p in paragraphs if len(p) > 30]all_chunks = sentence_chunks + combined_chunks + paragraph_chunksseen, final_chunks = set(), []for ch in all_chunks:if ch not in seen and len(ch) > 15:seen.add(ch)final_chunks.append(ch)print(f"Prepared {len(final_chunks)} chunks")return final_chunkschunks = preprocess_text(journal_text)# Embeddingsembeddings = embedder.encode(chunks, convert_to_tensor=True)print(f"Embeddings ready: {embeddings.shape}")# Retrievaldef get_top_chunks(query, embeddings, text_chunks, top_k=5):if not query:return [], []q = embedder.encode(query, convert_to_tensor=True)q = q / q.norm()M = embeddings / embeddings.norm(dim=1, keepdim=True)sims = torch.matmul(M, q)k = min(top_k, len(text_chunks))scores, idxs = torch.topk(sims, k=k)results, kept_scores = [], []for i, idx in enumerate(idxs):sc = scores[i].item()if sc > 0.25:results.append(text_chunks[int(idx)])kept_scores.append(sc)return results, kept_scoresdef join_context(chunks_list, max_chars=1000):out = ""for c in chunks_list:c = c.strip()2 unmodified linesout += (("\n\n" if out else "") + c)return out# Safety netCRISIS_TERMS = ["suicide","kill myself","end my life","self-harm","hurt myself","overdose","harm others","kill someone"]def is_crisis(message: str) -> bool:m = (message or "").lower()return any(term in m for term in CRISIS_TERMS)# Personas + break ideasBREAK_IDEAS = {"Sage": ["Look out the window for 1 minute and notice what moves.","Breathe in 4, out 6, slowly.","Think of 3 natural places you enjoy."],"Buddy": ["Stand and stretch for 20 seconds.",7 unmodified lines],"Librarian": ["Write one sentence starting with: 'Today I noticed...'.","Put 3 things neatly in place.","Organize a small space for 1 minute."],"Cozy": ["Make a warm drink or sip water slowly.","Wrap yourself in a blanket for 1 minute.","Notice 3 soft textures nearby."],}PERSONALITY_TONES = {"Sage": "calm, thoughtful, nature imagery","Buddy": "upbeat, encouraging, simple language","Monk": "minimalist, focused, mindful","Librarian": "gentle, organized, caring","Cozy": "warm, comforting, home-like"}CURRENT_PERSONA = {"name": "Cozy"}def set_persona(name: str) -> str:names = list(PERSONALITY_TONES.keys())lookup = {n.lower(): n for n in names}key = (name or "").strip().lower()if key in lookup:CURRENT_PERSONA["name"] = lookup[key]return f"Persona set to {CURRENT_PERSONA['name']}."else:return "Unknown persona. Options: Sage, Buddy, Monk, Librarian, Cozy."def pick_break() -> str:persona = CURRENT_PERSONA["name"]return random.choice(BREAK_IDEAS.get(persona, BREAK_IDEAS["Cozy"]))def build_system_message(context_block: str) -> str:persona = CURRENT_PERSONA["name"]tone = PERSONALITY_TONES.get(persona, PERSONALITY_TONES["Cozy"])return ("You are Otium, a warm journaling buddy. Not medical advice. "f"Adopt the persona {persona}. Style: {tone}. ""Use plain, kind language. Reflect feelings from the user’s message, ""ask 1–2 gentle follow-up questions, keep replies short (3–6 sentences). ""Offer exactly one tiny break idea. Avoid clinical diagnoses or medical guidance.\n\n"f"Helpful snippets from the user's content:\n{context_block}")# Chat handlerHELP_TEXT = ("Type `/personas` to see options, or `/persona NAME` to switch.\n""Choices: Sage, Buddy, Monk, Librarian, Cozy.")def respond(message, history):if (message or "").strip().lower() == "/personas":return HELP_TEXTif (message or "").strip().lower().startswith("/persona"):parts = message.split(maxsplit=1)if len(parts) == 1:return "Usage: `/persona NAME` — " + HELP_TEXTreturn set_persona(parts[1])if is_crisis(message):return ("I’m glad you reached out. I’m not a crisis service, but help is available:\n""• U.S.: call or text 988 (988lifeline.org)\n""• Elsewhere: contact local emergency services.")top_chunks, _ = get_top_chunks(message, embeddings, chunks, top_k=5)context_block = join_context(top_chunks)system_msg = build_system_message(context_block)messages = [{"role": "system", "content": system_msg}]if history:for u, a in history:if u: messages.append({"role": "user", "content": u})if a: messages.append({"role": "assistant", "content": a})messages.append({"role": "user", "content": message or ""})resp = client.chat_completion(messages=messages, max_tokens=220, temperature=0.7)text = resp["choices"][0]["message"]["content"].strip()return f"{text}\n\n**Tiny break idea:** {pick_break()}"# Minimal UIchatbot = gr.ChatInterface(respond,title="Otium — A Friendly Check-In",description="Talk about your day. Otium reflects feelings and suggests tiny breaks. Type `/personas` for options.")if __name__ == "__main__":2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889902 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291307 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462 unmodified linesfrom sentence_transformers import SentenceTransformerimport torchimport randomimport re# ========================# Models# ========================client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")embedder = SentenceTransformer("all-MiniLM-L6-v2")# ========================# Load corpus (journal.txt in same folder)# ========================with open("journal.txt", "r", encoding="utf-8") as f:raw_text = f.read()# ========================# --- KEEPING THE OG STRIP/SANITIZER STUFF ---# Remove role tags and chat-log lines from the corpus so they never leak# ========================ROLE_TAGS = re.compile(r'\[/?(?:USER|ASST)\]|\</?(?:user|assistant)\>|<\|(?:user|assistant)\|>',re.IGNORECASE,)def clean_corpus(text: str) -> str:text = ROLE_TAGS.sub('', text or '')out_lines = []for line in text.splitlines():low = line.strip().lower()if low.startswith("user wrote:"): continueif low.startswith("/user wrote:"): continueif low.startswith("assistant wrote:"): continueif low.startswith("/assistant wrote:"): continueif low.startswith("user:"): continueif low.startswith("assistant:"): continueout_lines.append(line)return "\n".join(out_lines)journal_text = clean_corpus(raw_text)# ========================# Chunk + embed (simple)# ========================def preprocess_text(text):cleaned = text.strip()sents = [s.strip() for s in cleaned.split('.') if s.strip()]sentence_chunks = [s for s in sents if len(s) > 10]combined = []for i in range(0, len(sents), 3):chunk = '. '.join(sents[i:i+3]).strip()if len(chunk) > 20:combined.append(chunk)paras = [p.strip() for p in cleaned.split('\n\n') if p.strip() and len(p) > 30]seen, chunks = set(), []for c in sentence_chunks + combined + paras:c = c.strip()if c and c not in seen and len(c) > 15:seen.add(c)chunks.append(c)return chunkschunks = preprocess_text(journal_text)embeddings = embedder.encode(chunks, convert_to_tensor=True)def get_top_chunks(query, top_k=5):if not query:return []q = embedder.encode(query, convert_to_tensor=True)q = q / q.norm()M = embeddings / embeddings.norm(dim=1, keepdim=True)sims = torch.matmul(M, q)k = min(top_k, len(chunks))scores, idxs = torch.topk(sims, k=k)out = []for i, idx in enumerate(idxs):if scores[i].item() > 0.25:out.append(chunks[int(idx)])return outdef join_context(chunks_list, max_chars=900):out = ""for c in chunks_list:c = c.strip()2 unmodified linesout += (("\n\n" if out else "") + c)return out# ========================# Tiny safety (quiet unless triggered)# ========================CRISIS_TERMS = ["suicide","kill myself","end my life","self-harm","hurt myself","overdose","harm others","kill someone"]def is_crisis(msg: str) -> bool:m = (msg or "").lower()return any(t in m for t in CRISIS_TERMS)# ========================# Emotion gate (only help if feelings are mentioned)# ========================EMOTION_HINTS = ["i feel", "i'm feeling", "i am feeling", "feelings","overwhelmed", "stressed", "anxious", "sad", "lonely","angry", "upset", "worried", "guilty", "ashamed","proud", "happy", "excited", "tired", "burned out", "burnt out"]def mentions_emotion(msg: str) -> bool:m = (msg or "").lower()return any(k in m for k in EMOTION_HINTS)# ========================# Personas (simple) + break ideas# ========================BREAKS = {"Sage": ["Look out the window for 1 minute and notice what moves.","Breathe in 4, out 6, slowly.","Think of three natural places you enjoy."],"Buddy": ["Stand and stretch for 20 seconds.",7 unmodified lines],"Librarian": ["Write one sentence starting with: 'Today I noticed...'.","Put three things neatly in place.","Organize a small space for 1 minute."],"Cozy": ["Sip water slowly like a warm drink.","Wrap yourself in a blanket for 1 minute.","Notice three soft textures nearby."],}TONES = {"Sage": "calm, thoughtful, nature imagery","Buddy": "upbeat, encouraging, simple language","Monk": "minimalist, focused, mindful","Librarian": "gentle, organized, caring","Cozy": "warm, comforting, home-like",}CURRENT_PERSONA = {"name": "Cozy"} # kept mutable in a dict for simplicitydef set_persona(name: str) -> str:names = list(TONES.keys())lookup = {n.lower(): n for n in names}key = (name or "").strip().lower()if key in lookup:CURRENT_PERSONA["name"] = lookup[key]return f"Persona set to {CURRENT_PERSONA['name']}."return "Unknown persona. Options: Sage, Buddy, Monk, Librarian, Cozy."def pick_break() -> str:persona = CURRENT_PERSONA["name"]return random.choice(BREAKS.get(persona, BREAKS["Cozy"]))# ========================# Chat handler# ========================HELP_TEXT = ("Type `/personas` to see options, or `/persona NAME` to switch. ""Choices: Sage, Buddy, Monk, Librarian, Cozy.")def respond(message, history):msg = (message or "").strip()# Commands (no extra UI)low = msg.lower()if low == "/personas":return HELP_TEXTif low.startswith("/persona"):parts = msg.split(maxsplit=1)if len(parts) == 1:return "Usage: `/persona NAME` — " + HELP_TEXTreturn set_persona(parts[1])# Safetyif is_crisis(msg):return ("I’m glad you reached out. I’m not a crisis service, but help is available:\n""• U.S.: call or text 988 (988lifeline.org)\n""• Elsewhere: contact local emergency services.")# If user hasn't talked about emotions yet → friend-like greeting onlyif not mentions_emotion(msg):return ("Hey, I’m Otium. I’m here to listen whenever you want to talk about your day ""or how you’re feeling. No pressure—share only when you’re ready.")# Emotions present → retrieve, reflect, short follow-up, one tiny breaktop = get_top_chunks(msg, top_k=5)context_block = join_context(top)system_msg = ("You are Otium, a warm journaling buddy. Not medical advice. "f"Adopt the persona {CURRENT_PERSONA['name']}. Style: {TONES[CURRENT_PERSONA['name']]}. ""Output plain text only (no role labels or chat logs). ""Reflect the user’s feelings in simple, kind language, ask ONE gentle follow-up question, ""keep it short (3–5 sentences), and end with one tiny break idea. ""Avoid clinical terms or medical guidance.\n\n"f"Helpful snippets from the user's content:\n{context_block}")messages = [{"role": "system", "content": system_msg}]if history:for u, a in history:if u: messages.append({"role": "user", "content": u})if a: messages.append({"role": "assistant", "content": a})messages.append({"role": "user", "content": msg})resp = client.chat_completion(messages=messages,max_tokens=220,temperature=0.7,stop=["User wrote:", "Assistant wrote:", "User:", "Assistant:"])text = resp["choices"][0]["message"]["content"].strip()return f"{text}\n\n**Tiny break idea:** {pick_break()}"# ========================# Minimal UI (single chat box)# ========================chatbot = gr.ChatInterface(respond,title="Otium — A Friendly Check-In",description="Say hello whenever you’re ready. Otium only offers support once you talk about feelings. Type /personas for options. (Not medical advice.)")if __name__ == "__main__":
app.py+139-78