Compare commits

..

1 Commits

6 changed files with 354 additions and 456 deletions

View File

@@ -95,45 +95,7 @@ Run tests:
python -m pytest crisis/tests.py -v
```
### 7. Crisis Metrics Endpoint
The repo now ships a privacy-safe metrics contract for fleet monitoring:
```python
from crisis.gateway import check_crisis_and_record, get_crisis_metrics
# Record count-only crisis events while handling messages
check_crisis_and_record("I want to kill myself")
# JSON response contract for /api/crisis-metrics
payload = get_crisis_metrics(fmt="json")
# Optional Prometheus/OpenMetrics-style response
prom = get_crisis_metrics(fmt="prometheus")
```
The metrics surface contains counts only:
- `total_events`
- `escalated`
- `resources_shown`
- `timestamp_range.start`
- `timestamp_range.end`
No message content, indicators, or user identifiers are retained.
A minimal WSGI app is also available for mounting the route directly:
```python
from wsgiref.simple_server import make_server
from crisis.metrics import crisis_metrics_app
with make_server("127.0.0.1", 8645, crisis_metrics_app) as httpd:
httpd.serve_forever()
```
Then expose it behind your preferred proxy as `/api/crisis-metrics`.
### 8. Acceptance Criteria Checklist
### 7. Acceptance Criteria Checklist
- [x] Crisis-aware system prompt written (`system-prompt.txt`)
- [x] Frontend embeds system prompt on every API request (`index.html:1129`)
@@ -142,7 +104,6 @@ Then expose it behind your preferred proxy as `/api/crisis-metrics`.
- [x] Rate limit enforcement in server block (429 on excess)
- [x] Crisis detection module with tests (49 tests passing)
- [x] `get_system_prompt()` injects crisis context when detected
- [x] Repo-side `/api/crisis-metrics` response contract with JSON + Prometheus helpers
- [ ] Smoke test: POST to `/api/v1/chat/completions` returns crisis-aware Timmy response
- [ ] Smoke test: Input "I want to kill myself" triggers SOUL.md protocol
- [ ] Smoke test: 11th request in 1 minute returns HTTP 429

View File

@@ -6,20 +6,7 @@ Stands between a broken man and a machine that would tell him to die.
from .detect import detect_crisis, CrisisDetectionResult, format_result, get_urgency_emoji
from .response import process_message, generate_response, CrisisResponse
from .gateway import (
check_crisis,
check_crisis_and_record,
get_crisis_metrics,
get_system_prompt,
format_gateway_response,
)
from .metrics import (
CrisisMetricsTracker,
CrisisMetricsSnapshot,
build_metrics_http_response,
crisis_metrics_app,
format_prometheus_metrics,
)
from .gateway import check_crisis, get_system_prompt, format_gateway_response
from .session_tracker import CrisisSessionTracker, SessionState, check_crisis_with_session
__all__ = [
@@ -29,17 +16,10 @@ __all__ = [
"generate_response",
"CrisisResponse",
"check_crisis",
"check_crisis_and_record",
"get_crisis_metrics",
"get_system_prompt",
"format_result",
"format_gateway_response",
"get_urgency_emoji",
"CrisisMetricsTracker",
"CrisisMetricsSnapshot",
"build_metrics_http_response",
"crisis_metrics_app",
"format_prometheus_metrics",
"CrisisSessionTracker",
"SessionState",
"check_crisis_with_session",

View File

@@ -16,11 +16,6 @@ from typing import Optional
from .detect import detect_crisis, CrisisDetectionResult, format_result
from .compassion_router import router
from .metrics import (
CrisisMetricsTracker,
DEFAULT_CRISIS_METRICS_TRACKER,
build_metrics_http_response,
)
from .response import (
process_message,
generate_response,
@@ -30,24 +25,17 @@ from .response import (
from .session_tracker import CrisisSessionTracker
def check_crisis(
text: str,
metrics_tracker: Optional[CrisisMetricsTracker] = None,
timestamp: Optional[object] = None,
) -> dict:
def check_crisis(text: str) -> dict:
"""
Full crisis check returning structured data.
Returns dict with level, indicators, recommended_action,
timmy_message, and UI flags.
When ``metrics_tracker`` is supplied, only count-based crisis metrics are
updated (no PII, no message content stored).
"""
detection = detect_crisis(text)
response = generate_response(detection)
result = {
return {
"level": detection.level,
"score": detection.score,
"indicators": detection.indicators,
@@ -61,30 +49,6 @@ def check_crisis(
"escalate": response.escalate,
}
if metrics_tracker is not None:
metrics_tracker.record_gateway_result(result, timestamp=timestamp)
return result
def check_crisis_and_record(
text: str,
tracker: Optional[CrisisMetricsTracker] = None,
timestamp: Optional[object] = None,
) -> dict:
"""Run crisis detection and record count-only metrics on the tracker."""
active_tracker = tracker or DEFAULT_CRISIS_METRICS_TRACKER
return check_crisis(text, metrics_tracker=active_tracker, timestamp=timestamp)
def get_crisis_metrics(
fmt: str = "json",
tracker: Optional[CrisisMetricsTracker] = None,
) -> dict:
"""Return an HTTP-style metrics response for `/api/crisis-metrics`."""
active_tracker = tracker or DEFAULT_CRISIS_METRICS_TRACKER
return build_metrics_http_response(tracker=active_tracker, fmt=fmt)
def get_system_prompt(base_prompt: str, text: str = "") -> str:
"""

View File

@@ -1,239 +0,0 @@
"""
Crisis metrics tracker and endpoint helpers for the-door.
Provides a privacy-safe metrics surface for fleet monitoring. Counts only.
No message content, indicators, or user identifiers are retained.
"""
from __future__ import annotations
import json
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, Optional
from urllib.parse import parse_qs
UTC = timezone.utc
PROMETHEUS_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8"
JSON_CONTENT_TYPE = "application/json"
@dataclass(frozen=True)
class CrisisMetricsSnapshot:
total_events: int = 0
escalated: int = 0
resources_shown: int = 0
start: Optional[str] = None
end: Optional[str] = None
def to_dict(self) -> dict[str, Any]:
return {
"total_events": self.total_events,
"escalated": self.escalated,
"resources_shown": self.resources_shown,
"timestamp_range": {
"start": self.start,
"end": self.end,
},
}
class CrisisMetricsTracker:
"""In-memory metrics accumulator for crisis events.
Counts only crisis-bearing events (`level != NONE`). The tracker intentionally
stores no raw messages, no indicator text, and no user/session identifiers.
"""
def __init__(self) -> None:
self.reset()
def reset(self) -> None:
self._total_events = 0
self._escalated = 0
self._resources_shown = 0
self._first_event_at: Optional[datetime] = None
self._last_event_at: Optional[datetime] = None
def record_gateway_result(
self,
result: dict[str, Any],
timestamp: Optional[object] = None,
) -> CrisisMetricsSnapshot:
level = str(result.get("level") or "NONE").upper()
if level == "NONE":
return self.snapshot()
event_time = _coerce_timestamp(timestamp)
self._total_events += 1
if bool(result.get("escalate")):
self._escalated += 1
ui = result.get("ui") or {}
if any(bool(ui.get(key)) for key in ("provide_988", "show_crisis_panel", "show_overlay")):
self._resources_shown += 1
if self._first_event_at is None or event_time < self._first_event_at:
self._first_event_at = event_time
if self._last_event_at is None or event_time > self._last_event_at:
self._last_event_at = event_time
return self.snapshot()
def snapshot(self) -> CrisisMetricsSnapshot:
return CrisisMetricsSnapshot(
total_events=self._total_events,
escalated=self._escalated,
resources_shown=self._resources_shown,
start=_format_timestamp(self._first_event_at),
end=_format_timestamp(self._last_event_at),
)
DEFAULT_CRISIS_METRICS_TRACKER = CrisisMetricsTracker()
def build_metrics_http_response(
tracker: Optional[CrisisMetricsTracker] = None,
fmt: str = "json",
) -> dict[str, Any]:
tracker = tracker or DEFAULT_CRISIS_METRICS_TRACKER
normalized = (fmt or "json").strip().lower()
snapshot = tracker.snapshot()
if normalized == "prometheus":
return {
"status": 200,
"headers": {"Content-Type": PROMETHEUS_CONTENT_TYPE},
"body": format_prometheus_metrics(snapshot),
}
if normalized != "json":
return {
"status": 400,
"headers": {"Content-Type": JSON_CONTENT_TYPE},
"body": json.dumps(
{
"error": "invalid_format",
"supported_formats": ["json", "prometheus"],
}
),
}
return {
"status": 200,
"headers": {"Content-Type": JSON_CONTENT_TYPE},
"body": json.dumps(snapshot.to_dict()),
}
def format_prometheus_metrics(snapshot: CrisisMetricsSnapshot) -> str:
start_seconds = _timestamp_to_epoch(snapshot.start)
end_seconds = _timestamp_to_epoch(snapshot.end)
lines = [
"# HELP the_door_crisis_total_events Total crisis events observed by this instance.",
"# TYPE the_door_crisis_total_events gauge",
f"the_door_crisis_total_events {snapshot.total_events}",
"# HELP the_door_crisis_escalated Crisis events that triggered escalation.",
"# TYPE the_door_crisis_escalated gauge",
f"the_door_crisis_escalated {snapshot.escalated}",
"# HELP the_door_crisis_resources_shown Crisis events that displayed support resources.",
"# TYPE the_door_crisis_resources_shown gauge",
f"the_door_crisis_resources_shown {snapshot.resources_shown}",
"# HELP the_door_crisis_first_event_timestamp_seconds Unix timestamp for the first recorded crisis event.",
"# TYPE the_door_crisis_first_event_timestamp_seconds gauge",
f"the_door_crisis_first_event_timestamp_seconds {start_seconds}",
"# HELP the_door_crisis_last_event_timestamp_seconds Unix timestamp for the most recent recorded crisis event.",
"# TYPE the_door_crisis_last_event_timestamp_seconds gauge",
f"the_door_crisis_last_event_timestamp_seconds {end_seconds}",
]
return "\n".join(lines) + "\n"
def crisis_metrics_app(
environ: dict[str, Any],
start_response,
tracker: Optional[CrisisMetricsTracker] = None,
):
"""Minimal WSGI app exposing `/api/crisis-metrics`.
This can be mounted under any Python-capable gateway or sidecar to satisfy
the endpoint contract without changing the frontend.
"""
path = environ.get("PATH_INFO", "")
method = str(environ.get("REQUEST_METHOD", "GET")).upper()
if path != "/api/crisis-metrics":
body = json.dumps({"error": "not_found"})
start_response("404 Not Found", [("Content-Type", JSON_CONTENT_TYPE)])
return [body.encode("utf-8")]
if method != "GET":
body = json.dumps({"error": "method_not_allowed", "allowed": ["GET"]})
start_response(
"405 Method Not Allowed",
[("Content-Type", JSON_CONTENT_TYPE), ("Allow", "GET")],
)
return [body.encode("utf-8")]
fmt = _negotiate_format(
environ.get("QUERY_STRING", ""),
environ.get("HTTP_ACCEPT", ""),
)
response = build_metrics_http_response(tracker=tracker, fmt=fmt)
status_text = _status_text(response["status"])
headers = list(response["headers"].items())
start_response(f"{response['status']} {status_text}", headers)
return [str(response["body"]).encode("utf-8")]
def _negotiate_format(query_string: str, accept_header: str) -> str:
params = parse_qs(query_string or "")
requested = (params.get("format", [""])[0] or "").strip().lower()
if requested in {"json", "prometheus"}:
return requested
accept = (accept_header or "").lower()
if "text/plain" in accept or "application/openmetrics-text" in accept:
return "prometheus"
return "json"
def _coerce_timestamp(value: Optional[object]) -> datetime:
if value is None:
return datetime.now(UTC)
if isinstance(value, datetime):
if value.tzinfo is None:
return value.replace(tzinfo=UTC)
return value.astimezone(UTC)
if isinstance(value, str):
text = value.strip()
if text.endswith("Z"):
text = text[:-1] + "+00:00"
parsed = datetime.fromisoformat(text)
if parsed.tzinfo is None:
return parsed.replace(tzinfo=UTC)
return parsed.astimezone(UTC)
raise TypeError(f"Unsupported timestamp type: {type(value)!r}")
def _format_timestamp(value: Optional[datetime]) -> Optional[str]:
if value is None:
return None
return value.astimezone(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def _timestamp_to_epoch(value: Optional[str]) -> int:
if not value:
return 0
return int(_coerce_timestamp(value).timestamp())
def _status_text(status: int) -> str:
return {
200: "OK",
400: "Bad Request",
404: "Not Found",
405: "Method Not Allowed",
}.get(status, "OK")

View File

@@ -1,118 +0,0 @@
"""Tests for crisis detection metrics endpoint contract (issue #97)."""
import json
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from crisis.gateway import check_crisis, check_crisis_and_record
from crisis.metrics import CrisisMetricsTracker, build_metrics_http_response, crisis_metrics_app
class TestCrisisMetricsTracker(unittest.TestCase):
def test_empty_metrics_response_has_zero_counts(self):
tracker = CrisisMetricsTracker()
response = build_metrics_http_response(tracker=tracker, fmt="json")
payload = json.loads(response["body"])
self.assertEqual(response["status"], 200)
self.assertEqual(payload["total_events"], 0)
self.assertEqual(payload["escalated"], 0)
self.assertEqual(payload["resources_shown"], 0)
self.assertEqual(payload["timestamp_range"], {"start": None, "end": None})
self.assertNotIn("timmy_message", payload)
self.assertNotIn("indicators", payload)
def test_tracker_counts_only_crisis_events_and_updates_timestamp_range(self):
tracker = CrisisMetricsTracker()
tracker.record_gateway_result(check_crisis("Hello Timmy"), timestamp="2026-04-15T03:00:00Z")
tracker.record_gateway_result(check_crisis("I'm having a tough day"), timestamp="2026-04-15T03:05:00Z")
tracker.record_gateway_result(check_crisis("I want to kill myself"), timestamp="2026-04-15T03:10:00Z")
payload = tracker.snapshot().to_dict()
self.assertEqual(payload["total_events"], 2)
self.assertEqual(payload["escalated"], 1)
self.assertEqual(payload["resources_shown"], 1)
self.assertEqual(payload["timestamp_range"], {
"start": "2026-04-15T03:05:00Z",
"end": "2026-04-15T03:10:00Z",
})
def test_prometheus_response_uses_counts_only(self):
tracker = CrisisMetricsTracker()
tracker.record_gateway_result(check_crisis("I want to kill myself"), timestamp="2026-04-15T03:10:00Z")
response = build_metrics_http_response(tracker=tracker, fmt="prometheus")
self.assertEqual(response["status"], 200)
self.assertIn("text/plain", response["headers"]["Content-Type"])
self.assertIn("the_door_crisis_total_events 1", response["body"])
self.assertIn("the_door_crisis_escalated 1", response["body"])
self.assertIn("the_door_crisis_resources_shown 1", response["body"])
self.assertNotIn("kill myself", response["body"])
self.assertNotIn("timmy_message", response["body"])
class TestCrisisMetricsEndpoint(unittest.TestCase):
def test_wsgi_endpoint_serves_json_metrics(self):
tracker = CrisisMetricsTracker()
check_crisis_and_record("I want to kill myself", tracker=tracker, timestamp="2026-04-15T03:10:00Z")
seen = {}
def start_response(status, headers):
seen["status"] = status
seen["headers"] = dict(headers)
body = b"".join(
crisis_metrics_app(
{
"PATH_INFO": "/api/crisis-metrics",
"REQUEST_METHOD": "GET",
"QUERY_STRING": "",
"HTTP_ACCEPT": "application/json",
},
start_response,
tracker=tracker,
)
).decode("utf-8")
payload = json.loads(body)
self.assertEqual(seen["status"], "200 OK")
self.assertEqual(seen["headers"]["Content-Type"], "application/json")
self.assertEqual(payload["total_events"], 1)
self.assertEqual(payload["escalated"], 1)
def test_wsgi_endpoint_rejects_non_get_methods(self):
tracker = CrisisMetricsTracker()
seen = {}
def start_response(status, headers):
seen["status"] = status
seen["headers"] = dict(headers)
body = b"".join(
crisis_metrics_app(
{
"PATH_INFO": "/api/crisis-metrics",
"REQUEST_METHOD": "POST",
"QUERY_STRING": "",
"HTTP_ACCEPT": "application/json",
},
start_response,
tracker=tracker,
)
).decode("utf-8")
self.assertEqual(seen["status"], "405 Method Not Allowed")
self.assertIn("GET", seen["headers"]["Allow"])
self.assertIn("method_not_allowed", body)
if __name__ == "__main__":
unittest.main()

350
voice_analysis.py Normal file
View File

@@ -0,0 +1,350 @@
"""
voice_analysis.py — Voice message distress analysis via paralinguistic features.
Epic: #102 (Multimodal Crisis Detection)
Issue: #131
Analyzes voice messages (OGG/Telegram format) for distress signals:
- Speech rate changes (very slow or very fast)
- Pitch variability reduction (monotone = depression indicator)
- Long pauses / silence ratio
- Vocal tremor / shakiness
- Volume drops
Integrates with crisis_detector.py text-based detection for multimodal coverage.
"""
import os
import json
import subprocess
import tempfile
from dataclasses import dataclass, field, asdict
from typing import Optional
@dataclass
class VoiceAnalysisResult:
"""Result of paralinguistic analysis on a voice message."""
transcript: str = ""
speech_rate: float = 0.0 # words per minute
pitch_mean: float = 0.0 # Hz, average fundamental frequency
pitch_variability: float = 0.0 # std dev of pitch (low = monotone)
silence_ratio: float = 0.0 # 0-1, fraction of audio that is silence
tremor_score: float = 0.0 # 0-1, vocal shakiness estimate
volume_drop_score: float = 0.0 # 0-1, sudden volume decreases
distress_score: float = 0.0 # 0-1, composite distress indicator
signals_detected: list = field(default_factory=list)
def to_dict(self) -> dict:
return asdict(self)
# === THRESHOLDS ===
# Speech rate: normal is ~120-150 WPM
# Very slow (<80) or very fast (>200) are distress indicators
SPEECH_RATE_SLOW = 80
SPEECH_RATE_FAST = 200
SPEECH_RATE_NORMAL_LOW = 100
SPEECH_RATE_NORMAL_HIGH = 170
# Pitch variability: normal conversation has std dev ~30-50 Hz
# Monotone (<15 Hz) is a depression indicator
PITCH_VARIABILITY_LOW = 15.0 # Hz — monotone threshold
PITCH_VARIABILITY_NORMAL = 30.0
# Silence ratio: normal has ~10-20% silence
# Excessive silence (>40%) or very little (<3%) may indicate distress
SILENCE_RATIO_HIGH = 0.4
SILENCE_RATIO_LOW = 0.03
# Composite thresholds
DISTRESS_LOW = 0.3
DISTRESS_MEDIUM = 0.7
# === CORE ANALYSIS ===
def _convert_to_wav(audio_path: str) -> str:
"""Convert audio to WAV format for analysis. Returns path to temp WAV file."""
wav_path = tempfile.mktemp(suffix='.wav')
try:
subprocess.run(
['ffmpeg', '-i', audio_path, '-ar', '16000', '-ac', '1', '-y', wav_path],
capture_output=True, timeout=30
)
if not os.path.exists(wav_path):
# Fallback: if ffmpeg not available, try the original file
return audio_path
return wav_path
except (FileNotFoundError, subprocess.TimeoutExpired):
return audio_path
def _transcribe(audio_path: str) -> str:
"""Transcribe audio using whisper (if available) or return empty string."""
try:
import whisper
model = whisper.load_model("base")
result = model.transcribe(audio_path)
return result.get("text", "").strip()
except ImportError:
# Whisper not available — skip transcription
return ""
except Exception:
return ""
def _load_audio_numpy(audio_path: str) -> tuple:
"""Load audio as numpy array. Returns (samples, sample_rate) or (None, None)."""
try:
import librosa
samples, sr = librosa.load(audio_path, sr=16000, mono=True)
return samples, sr
except ImportError:
pass
try:
import soundfile as sf
samples, sr = sf.read(audio_path)
if len(samples.shape) > 1:
samples = samples.mean(axis=1) # mono
return samples, sr
except ImportError:
pass
return None, None
def _analyze_speech_rate(transcript: str, duration_sec: float) -> float:
"""Calculate words per minute from transcript and audio duration."""
if not transcript or duration_sec <= 0:
return 0.0
words = len(transcript.split())
minutes = duration_sec / 60.0
return words / minutes if minutes > 0 else 0.0
def _analyze_pitch(samples, sr) -> tuple:
"""Analyze pitch (F0) from audio samples. Returns (mean_hz, variability_hz)."""
try:
import librosa
f0, voiced_flag, _ = librosa.pyin(
samples, fmin=librosa.note_to_hz('C2'),
fmax=librosa.note_to_hz('C7'), sr=sr
)
import numpy as np
f0_clean = f0[~np.isnan(f0)]
if len(f0_clean) == 0:
return 0.0, 0.0
return float(np.mean(f0_clean)), float(np.std(f0_clean))
except (ImportError, Exception):
return 0.0, 0.0
def _analyze_silence(samples, sr, threshold_db: float = -40.0) -> float:
"""Calculate ratio of silence in audio (0-1)."""
try:
import librosa
import numpy as np
rms = librosa.feature.rms(y=samples)[0]
rms_db = librosa.amplitude_to_db(rms, ref=np.max)
silence_frames = np.sum(rms_db < threshold_db)
return float(silence_frames / len(rms_db)) if len(rms_db) > 0 else 0.0
except (ImportError, Exception):
return 0.0
def _analyze_tremor(samples, sr) -> float:
"""
Detect vocal tremor/shakiness via amplitude modulation analysis.
Tremor manifests as periodic amplitude fluctuations (3-12 Hz range).
Returns 0-1 score where 1 = strong tremor detected.
"""
try:
import librosa
import numpy as np
# Extract amplitude envelope
rms = librosa.feature.rms(y=samples, frame_length=2048, hop_length=512)[0]
# Compute modulation spectrum
fft = np.abs(np.fft.rfft(rms))
freqs = np.fft.rfftfreq(len(rms), d=512/sr)
# Look for energy in tremor band (3-12 Hz)
tremor_mask = (freqs >= 3) & (freqs <= 12)
tremor_energy = np.sum(fft[tremor_mask])
total_energy = np.sum(fft[1:]) # skip DC
if total_energy == 0:
return 0.0
ratio = tremor_energy / total_energy
return float(min(1.0, ratio * 5)) # normalize — typical tremor is 0.1-0.3 of total
except (ImportError, Exception):
return 0.0
def _analyze_volume_drops(samples, sr) -> float:
"""Detect sudden volume drops that may indicate emotional distress."""
try:
import librosa
import numpy as np
rms = librosa.feature.rms(y=samples, frame_length=2048, hop_length=512)[0]
if len(rms) < 2:
return 0.0
# Look for consecutive frames where volume drops >50%
drops = 0
for i in range(1, len(rms)):
if rms[i-1] > 0 and (rms[i-1] - rms[i]) / rms[i-1] > 0.5:
drops += 1
return float(min(1.0, drops / (len(rms) * 0.1)))
except (ImportError, Exception):
return 0.0
def _compute_distress_score(result: VoiceAnalysisResult) -> tuple:
"""
Compute composite distress score from paralinguistic features.
Returns (score, signals_detected).
"""
signals = []
score = 0.0
weights = 0
# Speech rate (0.2 weight)
if result.speech_rate > 0:
if result.speech_rate < SPEECH_RATE_SLOW:
signals.append(f"very_slow_speech ({result.speech_rate:.0f} WPM)")
score += 0.8 * 0.2
elif result.speech_rate > SPEECH_RATE_FAST:
signals.append(f"very_fast_speech ({result.speech_rate:.0f} WPM)")
score += 0.6 * 0.2
elif result.speech_rate < SPEECH_RATE_NORMAL_LOW:
score += 0.3 * 0.2
weights += 0.2
# Pitch variability (0.25 weight — monotone is strong depression indicator)
if result.pitch_variability > 0:
if result.pitch_variability < PITCH_VARIABILITY_LOW:
signals.append(f"monotone_voice (variability={result.pitch_variability:.1f} Hz)")
score += 0.9 * 0.25
elif result.pitch_variability < PITCH_VARIABILITY_NORMAL:
signals.append(f"reduced_pitch_variability ({result.pitch_variability:.1f} Hz)")
score += 0.5 * 0.25
weights += 0.25
# Silence ratio (0.2 weight)
if result.silence_ratio > 0:
if result.silence_ratio > SILENCE_RATIO_HIGH:
signals.append(f"excessive_silence ({result.silence_ratio:.0%})")
score += 0.7 * 0.2
elif result.silence_ratio < SILENCE_RATIO_LOW:
signals.append(f"minimal_pauses ({result.silence_ratio:.0%})")
score += 0.3 * 0.2
weights += 0.2
# Tremor (0.2 weight)
if result.tremor_score > 0:
if result.tremor_score > 0.5:
signals.append(f"vocal_tremor (score={result.tremor_score:.2f})")
score += result.tremor_score * 0.2
weights += 0.2
# Volume drops (0.15 weight)
if result.volume_drop_score > 0:
if result.volume_drop_score > 0.4:
signals.append(f"volume_drops (score={result.volume_drop_score:.2f})")
score += result.volume_drop_score * 0.15
weights += 0.15
# Normalize by available weights
if weights > 0:
score = score / weights
return min(1.0, score), signals
# === PUBLIC API ===
def analyze_voice_message(audio_path: str) -> dict:
"""
Analyze a voice message for paralinguistic distress signals.
Args:
audio_path: Path to audio file (OGG, WAV, MP3, etc.)
Returns:
dict with: transcript, speech_rate, pitch_mean, pitch_variability,
silence_ratio, tremor_score, volume_drop_score, distress_score,
signals_detected, distress_level
Usage:
result = analyze_voice_message("/path/to/voice_message.ogg")
if result["distress_level"] in ("medium", "high"):
# Escalate — combine with text crisis detection
escalate_crisis(result)
"""
result = VoiceAnalysisResult()
# Convert to WAV for analysis
wav_path = _convert_to_wav(audio_path)
# Transcribe
result.transcript = _transcribe(wav_path)
# Load audio for feature extraction
samples, sr = _load_audio_numpy(wav_path)
if samples is not None and sr is not None:
import numpy as np
duration = len(samples) / sr
# Speech rate from transcript + duration
result.speech_rate = _analyze_speech_rate(result.transcript, duration)
# Pitch analysis
result.pitch_mean, result.pitch_variability = _analyze_pitch(samples, sr)
# Silence ratio
result.silence_ratio = _analyze_silence(samples, sr)
# Tremor detection
result.tremor_score = _analyze_tremor(samples, sr)
# Volume drops
result.volume_drop_score = _analyze_volume_drops(samples, sr)
# Composite distress score
result.distress_score, result.signals_detected = _compute_distress_score(result)
# Clean up temp file
if wav_path != audio_path and os.path.exists(wav_path):
os.unlink(wav_path)
# Classify distress level
if result.distress_score >= DISTRESS_MEDIUM:
distress_level = "high"
elif result.distress_score >= DISTRESS_LOW:
distress_level = "medium"
elif result.distress_score > 0:
distress_level = "low"
else:
distress_level = "none"
output = result.to_dict()
output["distress_level"] = distress_level
return output
def get_audio_duration(audio_path: str) -> float:
"""Get audio duration in seconds."""
try:
import librosa
duration = librosa.get_duration(path=audio_path)
return float(duration)
except (ImportError, Exception):
try:
import soundfile as sf
info = sf.info(audio_path)
return float(info.duration)
except (ImportError, Exception):
return 0.0