Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import gradio as grimport randomfrom huggingface_hub import InferenceClient# import lines go at the top: any libraries I need to import go up here ^^from sentence_transformers import SentenceTransformerimport torchclient = InferenceClient("HuggingFaceH4/zephyr-7b-beta")# Step 1with open("Untitled document.txt", "r", encoding="utf-8") as f:skincare_text = f.read()# Step 2: Preprocess text into sentence chunksdef preprocess_text(text):cleaned_text = text.strip()sentences = [s.strip() for s in cleaned_text.split('.') if s.strip()]sentence_chunks = [s.strip() for s in sentences if len(s.strip()) > 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_text.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 = set()final_chunks = []for chunk in all_chunks:if chunk not in seen and len(chunk) > 15:seen.add(chunk)final_chunks.append(chunk)print(f"Created {len(final_chunks)} chunks using advanced strategy")print(f"Sample chunks: {final_chunks[:3]}")return final_chunkscleaned_chunks = preprocess_text(skincare_text)# Step 3: Convert chunks into embeddingsmodel = SentenceTransformer('all-MiniLM-L6-v2')def create_embeddings(text_chunks):chunk_embeddings = model.encode(text_chunks, convert_to_tensor=True)print(f"Embeddings shape: {chunk_embeddings.shape}")return chunk_embeddingschunk_embeddings = create_embeddings(cleaned_chunks)# Step 4: Retrieve top matching chunksdef get_top_chunks(query, chunk_embeddings, text_chunks, top_k=3):query_embedding = model.encode(query, convert_to_tensor=True)query_norm = query_embedding / query_embedding.norm()chunks_norm = chunk_embeddings / chunk_embeddings.norm(dim=1, keepdim=True)similarities = torch.matmul(chunks_norm, query_norm)top_scores, top_indices = torch.topk(similarities, k=min(top_k, len(text_chunks)))results = []for i, idx in enumerate(top_indices):score = top_scores[i].item()if score > 0.3: # Only include reasonably relevant chunksresults.append(text_chunks[idx])return results, top_scores[:len(results)]# Step 5: Relevance checkerdef is_skincare_related(query):skincare_keywords = ['skin', 'skincare', 'acne', 'wrinkles', 'moisturizer', 'cleanser','sunscreen', 'serum', 'retinol', 'vitamin', 'dry', 'oily', 'sensitive','aging', 'pores', 'blackheads', 'routine', 'face', 'facial', 'beauty','dermatology', 'cosmetic', 'cream', 'lotion', 'toner', 'exfoliate','hydration', 'anti-aging', 'blemish', 'spot', 'dark circles']query_lower = query.lower()return any(keyword in query_lower for keyword in skincare_keywords)queries = ["Consistent skincare routine","Applying sunscreen daily","Choosing products that match your skin type"]for q in queries:print(f"\nQuery: {q}")results = get_top_chunks(q, chunk_embeddings, cleaned_chunks)for idx, res in enumerate(results, 1):print(f"Result {idx}: {res}")def respond(message, history):top_results = get_top_chunks(message, chunk_embeddings, cleaned_chunks)print(top_results)messages = [{"role": "system", "content": f"You are a friendly chatbot. You give people advice about skincare. Base your response on the following information: {top_results}"}]if history:messages.extend(history)messages.append({"role": "user", "content": message})response = client.chat_completion(messages, max_tokens=100)return response['choices'][0]['message']['content'].strip()def echo(message, history):return messagedef yes_or_no(message, history):return random.choice(['Yes', 'No', 'Maybe', 'Ask Again'])chatbot = gr.ChatInterface(respond)# defining my chatbot so that the user can interact and see their conversation history and send new messageschatbot.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186import gradio as grfrom huggingface_hub import InferenceClientfrom 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()if len(out) + len(c) + 2 > max_chars:breakout += (("\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.","Send a kind message to a friend.","Play a short upbeat song."],"Monk": ["Close your eyes, breathe 4 in, hold 4, breathe 4 out.","Choose one small task to finish after this.","Turn your phone face down for a minute."],"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__":chatbot.launch()
app.py+161-92