Spaces:
Sleeping
Sleeping
Download server.py from sarahzephyr/final: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/spaces/sarahzephyr/final/resolve/main/server.py
- Command line
-
hf download hf://spaces/sarahzephyr/final/server.py
-
curl -L -o server.py https://huggingface.co/spaces/sarahzephyr/final/resolve/main/server.py
12 kB
| """ | |
| PsycheOS — HuggingFace Spaces API Entrypoint | |
| Exposes a FastAPI app so Spaces can run this as a server. | |
| """ | |
| from pydantic import BaseModel | |
| from fastapi import FastAPI | |
| from fastapi.responses import HTMLResponse | |
| from agents.graph import run_psycheos | |
| app = FastAPI(title="PsycheOS API", version="2.0.0") | |
| class ChatRequest(BaseModel): | |
| message: str | |
| memory_hint: str = "" | |
| session: int = 1 | |
| mode_hint: str = "" | |
| trust_level: float = 0.5 | |
| session_history: list = [] | |
| def _baseline_chat(message: str) -> dict: | |
| """ | |
| Simple pre-training baseline heuristic for demo comparison. | |
| This is intentionally weaker than the trained multi-agent pipeline. | |
| """ | |
| text = message.lower() | |
| severe_hits = [ | |
| "suicide", "kill myself", "end my life", "goodbye", "can't do this", "plan", | |
| "pills", "hurt myself", "self harm", "not alive", | |
| ] | |
| moderate_hits = [ | |
| "anxious", "panic", "can't sleep", "depressed", "hopeless", "empty", | |
| "cry", "overwhelmed", "lost", | |
| ] | |
| mild_hits = ["stressed", "tired", "down", "sad", "low", "worried"] | |
| def count_hits(words): | |
| return sum(1 for w in words if w in text) | |
| severe = count_hits(severe_hits) | |
| moderate = count_hits(moderate_hits) | |
| mild = count_hits(mild_hits) | |
| if severe > 0: | |
| distress = 5 | |
| elif moderate >= 2: | |
| distress = 4 | |
| elif moderate == 1: | |
| distress = 3 | |
| elif mild >= 2: | |
| distress = 2 | |
| else: | |
| distress = 1 | |
| escalate = distress >= 4 | |
| response = ( | |
| "I hear you, and I am glad you shared this. " | |
| "Can you tell me a bit more about what feels hardest right now?" | |
| ) | |
| if escalate: | |
| response = ( | |
| "Thank you for telling me this. Your safety matters right now. " | |
| "Please reach out to local emergency services or a trusted person immediately." | |
| ) | |
| return { | |
| "source": "baseline", | |
| "distress_level": distress, | |
| "response": response, | |
| "escalate": escalate, | |
| "detected_mode": "open", | |
| "reward": 0.0, | |
| "dpo_score": 0.0, | |
| "f1_score": 0.0, | |
| } | |
| def root(): | |
| return HTMLResponse( | |
| """ | |
| <!doctype html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8" /> | |
| <meta name="viewport" content="width=device-width,initial-scale=1" /> | |
| <title>PsycheOS</title> | |
| <style> | |
| :root{ | |
| --bg:#0b1020; --card:#121a30; --line:#243253; --txt:#e8eeff; --muted:#9db0e6; | |
| --accent:#7c8bff; --accent2:#f672a7; --ok:#35d39a; --warn:#f4c95d; --danger:#ff7a7a; | |
| } | |
| *{box-sizing:border-box} | |
| body{ | |
| margin:0; font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif; | |
| background:radial-gradient(1200px 600px at 10% -10%, #243253 0%, transparent 60%), var(--bg); | |
| color:var(--txt); | |
| } | |
| .wrap{max-width:980px;margin:28px auto;padding:0 16px;} | |
| .hero{ | |
| border:1px solid var(--line); background:linear-gradient(140deg,#111a31,#0d1428); | |
| border-radius:16px; padding:20px; | |
| } | |
| .title{margin:0;font-size:30px;font-weight:800;letter-spacing:.2px} | |
| .sub{margin:6px 0 0;color:var(--muted);font-size:14px} | |
| .grid{display:grid;grid-template-columns:1fr 310px;gap:16px;margin-top:16px} | |
| .panel{border:1px solid var(--line);background:var(--card);border-radius:14px;padding:14px} | |
| .chatlog{height:420px;overflow:auto;padding:8px;border:1px solid var(--line);border-radius:12px;background:#0e1630} | |
| .msg{max-width:82%;padding:10px 12px;border-radius:12px;margin:8px 0;line-height:1.45;font-size:14px;white-space:pre-wrap} | |
| .u{margin-left:auto;background:#1b2b54;border:1px solid #2e4580} | |
| .a{margin-right:auto;background:#1b1730;border:1px solid #3b2c63} | |
| .meta{font-size:12px;color:var(--muted);margin-top:6px} | |
| .row{display:flex;gap:8px;margin-top:10px} | |
| textarea{ | |
| flex:1;height:78px;resize:vertical;border-radius:10px;border:1px solid var(--line); | |
| background:#0c1430;color:var(--txt);padding:10px;font:inherit | |
| } | |
| button{ | |
| border:0;border-radius:10px;padding:0 14px;font-weight:700;color:white;cursor:pointer; | |
| background:linear-gradient(135deg,var(--accent),var(--accent2)) | |
| } | |
| .k{display:flex;justify-content:space-between;margin:10px 0;padding:8px 0;border-bottom:1px dashed #2a385f;font-size:13px} | |
| .badge{display:inline-block;padding:4px 8px;border-radius:999px;border:1px solid #334a7d;color:#cfe0ff;background:#132043;font-size:12px} | |
| .switch{display:flex;gap:6px;align-items:center;flex-wrap:wrap;margin-top:10px} | |
| .chip{border:1px solid #334a7d;background:#0f1e40;color:#b8cbff;padding:6px 10px;border-radius:999px;font-size:12px;cursor:pointer} | |
| .chip.active{background:linear-gradient(135deg,var(--accent),var(--accent2));color:#fff;border-color:transparent} | |
| .compare{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:8px} | |
| .cmpbox{border:1px solid var(--line);border-radius:10px;padding:8px;background:#0d1630} | |
| .cmptitle{font-size:12px;color:#b5c8ff;margin-bottom:6px} | |
| .cmptext{font-size:13px;line-height:1.45;white-space:pre-wrap} | |
| .ok{color:var(--ok)} .warn{color:var(--warn)} .danger{color:var(--danger)} | |
| @media (max-width:880px){.grid{grid-template-columns:1fr}.compare{grid-template-columns:1fr}} | |
| </style> | |
| </head> | |
| <body> | |
| <div class="wrap"> | |
| <section class="hero"> | |
| <h1 class="title">PsycheOS</h1> | |
| <p class="sub">Multi-agent mental-health RL environment demo • FastAPI + Docker Space</p> | |
| </section> | |
| <div class="grid"> | |
| <section class="panel"> | |
| <div class="switch"> | |
| <span class="badge">Demo Mode</span> | |
| <button id="mode-trained" class="chip active" type="button">Trained only</button> | |
| <button id="mode-compare" class="chip" type="button">Before vs Trained</button> | |
| </div> | |
| <div id="chatlog" class="chatlog"> | |
| <div class="msg a">Hi, I am PsycheOS. Tell me what is on your mind.</div> | |
| </div> | |
| <div class="row"> | |
| <textarea id="input" placeholder="Share what's on your mind..."></textarea> | |
| <button id="send">Send</button> | |
| </div> | |
| </section> | |
| <aside class="panel"> | |
| <div class="badge">Live Agent Signals</div> | |
| <div class="k"><span>Distress level</span><strong id="distress">-</strong></div> | |
| <div class="k"><span>Escalation</span><strong id="escalate">-</strong></div> | |
| <div class="k"><span>Detected mode</span><strong id="mode">-</strong></div> | |
| <div class="k"><span>Reward</span><strong id="reward">-</strong></div> | |
| <div class="k"><span>DPO score</span><strong id="dpo">-</strong></div> | |
| <div class="k"><span>F1 score</span><strong id="f1">-</strong></div> | |
| <div class="meta">Tip: judges can also call <code>/chat</code> directly for API-level evaluation.</div> | |
| </aside> | |
| </div> | |
| </div> | |
| <script> | |
| const chatlog = document.getElementById("chatlog"); | |
| const input = document.getElementById("input"); | |
| const send = document.getElementById("send"); | |
| const modeTrainedBtn = document.getElementById("mode-trained"); | |
| const modeCompareBtn = document.getElementById("mode-compare"); | |
| let compareMode = false; | |
| function addMsg(text, cls){ | |
| const d = document.createElement("div"); | |
| d.className = "msg " + cls; | |
| d.textContent = text; | |
| chatlog.appendChild(d); | |
| chatlog.scrollTop = chatlog.scrollHeight; | |
| } | |
| function addCompare(before, trained){ | |
| const wrap = document.createElement("div"); | |
| wrap.className = "msg a"; | |
| wrap.innerHTML = ` | |
| <div class="compare"> | |
| <div class="cmpbox"> | |
| <div class="cmptitle">Before (baseline)</div> | |
| <div class="cmptext">${before}</div> | |
| </div> | |
| <div class="cmpbox"> | |
| <div class="cmptitle">Trained (PsycheOS)</div> | |
| <div class="cmptext">${trained}</div> | |
| </div> | |
| </div> | |
| `; | |
| chatlog.appendChild(wrap); | |
| chatlog.scrollTop = chatlog.scrollHeight; | |
| } | |
| function setSignal(id, value, level){ | |
| const el = document.getElementById(id); | |
| el.textContent = value; | |
| el.className = level || ""; | |
| } | |
| async function runChat(){ | |
| const message = input.value.trim(); | |
| if(!message) return; | |
| addMsg(message, "u"); | |
| input.value = ""; | |
| send.disabled = true; | |
| send.textContent = "Sending..."; | |
| try{ | |
| const trainedReq = fetch("/chat", { | |
| method: "POST", | |
| headers: {"Content-Type":"application/json"}, | |
| body: JSON.stringify({message, session: 1, trust_level: 0.5, session_history: []}) | |
| }); | |
| if (compareMode){ | |
| const baselineReq = fetch("/chat_baseline", { | |
| method: "POST", | |
| headers: {"Content-Type":"application/json"}, | |
| body: JSON.stringify({message, session: 1, trust_level: 0.5, session_history: []}) | |
| }); | |
| const [trainedRes, baselineRes] = await Promise.all([trainedReq, baselineReq]); | |
| if(!trainedRes.ok || !baselineRes.ok) throw new Error("Compare request failed"); | |
| const trained = await trainedRes.json(); | |
| const baseline = await baselineRes.json(); | |
| addCompare( | |
| baseline.response || "(no response)", | |
| trained.response || "(no response)" | |
| ); | |
| setSignal("distress", `${baseline.distress_level} → ${trained.distress_level}`, (trained.distress_level >= 4 ? "danger" : trained.distress_level >= 3 ? "warn" : "ok")); | |
| setSignal("escalate", `${baseline.escalate ? "YES" : "NO"} → ${trained.escalate ? "YES" : "NO"}`, trained.escalate ? "danger" : "ok"); | |
| setSignal("mode", trained.detected_mode || "-"); | |
| setSignal("reward", trained.reward ?? "-"); | |
| setSignal("dpo", trained.dpo_score ?? "-"); | |
| setSignal("f1", trained.f1_score ?? "-"); | |
| } else { | |
| const trainedRes = await trainedReq; | |
| if(!trainedRes.ok) throw new Error("Request failed"); | |
| const data = await trainedRes.json(); | |
| addMsg(data.response || "(no response)", "a"); | |
| setSignal("distress", data.distress_level ?? "-", (data.distress_level >= 4 ? "danger" : data.distress_level >= 3 ? "warn" : "ok")); | |
| setSignal("escalate", data.escalate ? "YES" : "NO", data.escalate ? "danger" : "ok"); | |
| setSignal("mode", data.detected_mode || "-"); | |
| setSignal("reward", data.reward ?? "-"); | |
| setSignal("dpo", data.dpo_score ?? "-"); | |
| setSignal("f1", data.f1_score ?? "-"); | |
| } | |
| } catch(e){ | |
| addMsg("Error: could not reach chat endpoints.", "a"); | |
| } finally { | |
| send.disabled = false; | |
| send.textContent = "Send"; | |
| } | |
| } | |
| modeTrainedBtn.addEventListener("click", () => { | |
| compareMode = false; | |
| modeTrainedBtn.classList.add("active"); | |
| modeCompareBtn.classList.remove("active"); | |
| }); | |
| modeCompareBtn.addEventListener("click", () => { | |
| compareMode = true; | |
| modeCompareBtn.classList.add("active"); | |
| modeTrainedBtn.classList.remove("active"); | |
| }); | |
| send.addEventListener("click", runChat); | |
| input.addEventListener("keydown", (e) => { | |
| if (e.key === "Enter" && !e.shiftKey) { | |
| e.preventDefault(); | |
| runChat(); | |
| } | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| ) | |
| def health(): | |
| return {"healthy": True} | |
| def api_status(): | |
| return {"status": "ok", "service": "PsycheOS API"} | |
| def chat_baseline(payload: ChatRequest): | |
| return _baseline_chat(payload.message) | |
| def chat(payload: ChatRequest): | |
| result = run_psycheos( | |
| message=payload.message, | |
| memory_hint=payload.memory_hint, | |
| session=payload.session, | |
| mode_hint=payload.mode_hint, | |
| trust_level=payload.trust_level, | |
| session_history=payload.session_history, | |
| ) | |
| return result | |