Skip to content

feat: NER-based speaker identification with spaCy (#3039) - #6901

Closed
moneysavvy wants to merge 5 commits into
BasedHardware:mainfrom
moneysavvy:bounty/3039-ner-speaker-identification
Closed

moneysavvy wants to merge 5 commits into
BasedHardware:mainfrom
moneysavvy:bounty/3039-ner-speaker-identification

Conversation

@moneysavvy

Copy link
Copy Markdown

What this does

Replaces the regex-only speaker name detection with NER (Named Entity Recognition) using spaCy, while keeping regex as a graceful fallback.

Fixes #3039

Why

The current regex approach only catches explicit patterns like "My name is John" or "I'm Sarah." It completely misses natural mentions:

  • "Tell Mike I'll be late" → missed by regex ✗, caught by NER ✓
  • "Sarah mentioned the meeting" → missed by regex ✗, caught by NER ✓
  • "Hey David, how's it going?" → missed by regex ✗, caught by NER ✓

How it works

  1. Primary: spaCy NER (en_core_web_sm) extracts PERSON entities from transcript segments
  2. Scoring: Each candidate gets a confidence score based on context clues, position, and frequency
  3. Filtering: False positives ("Omi", "Google", day names, etc.) are filtered out
  4. Fallback: If spaCy isn't installed, original regex patterns still work

Technical details

  • Model: en_core_web_sm — MIT license, ~15MB, < 5ms per segment on CPU
  • Lazy loading: Model loads on first call, not at import time (no startup penalty)
  • Zero breaking changes: detect_speaker_from_text() signature unchanged
  • Performance: < 10ms per segment (tested, see unit tests)

What's included

File Purpose
utils/ner_speaker_identification.py New NER module with confidence scoring
utils/speaker_identification.py Updated to use NER as primary, regex as fallback
tests/unit/test_ner_speaker_identification.py 9 unit tests covering detection, filtering, perf
requirements.txt Added spacy>=3.7.0

Setup

pip install spacy
python -m spacy download en_core_web_sm

For Dockerfile, add to the build step:

RUN python -m spacy download en_core_web_sm

Testing

cd backend && python -m pytest tests/unit/test_ner_speaker_identification.py -v

AI Tools Disclosure

Used AI pair-programming (Claude) to design the confidence scoring system. All detection logic and test cases manually reviewed.

@moneysavvy
moneysavvy marked this pull request as ready for review April 20, 2026 22:53
@greptile-apps

greptile-apps Bot commented Apr 20, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR replaces the regex-only speaker name detection in detect_speaker_from_text() with a spaCy NER primary path and retains regex as a fallback, aiming to catch natural mentions like "Tell Mike I'll be late" that the existing patterns miss.

  • P1 — Names in _AMBIGUOUS_WORDS (Bob, Bill, Mark, Frank, Rose, etc.) score 0.35 in third-person mentions — below the 0.4 threshold — so they are silently missed by NER and are not caught by regex fallback either, creating a regression for a set of common English first names.
  • P1 — The import of detect_speaker_from_text_ner is inside the detect_speaker_from_text() function body, violating the project's backend-imports rule (module-level imports only).
  • P2 — spacy>=3.7.0 is added to requirements.txt as a hard dependency, but the required python -m spacy download en_core_web_sm step is absent from the Dockerfile, causing an OSError on every cold start in production containers.

Confidence Score: 3/5

Not safe to merge — two P1 correctness issues and a missing Dockerfile step that causes a startup error in production.

Two P1 findings: the in-function import violates an enforced project rule, and the _AMBIGUOUS_WORDS penalty silently drops common first names below the detection threshold — a behavioral regression relative to the existing regex. The missing model download in the Dockerfile is a P2 but causes a logged warning on every production boot.

backend/utils/ner_speaker_identification.py (ambiguous-words scoring), backend/utils/speaker_identification.py (in-function import), backend/requirements.txt + Dockerfile (missing model download step)

Important Files Changed

Filename Overview
backend/utils/ner_speaker_identification.py New NER module using spaCy for speaker detection; has a correctness issue where _AMBIGUOUS_WORDS penalty drops common first names (Bob, Mark, Bill, Frank) below the 0.4 confidence threshold in third-person contexts, and a blocking spacy.load() on first async call.
backend/utils/speaker_identification.py Adds NER as primary detection path; import of detect_speaker_from_text_ner is inside the function body, violating the project's backend-imports rule (module-level imports only).
backend/requirements.txt Adds spacy>=3.7.0 as hard dependency, but the required model download (python -m spacy download en_core_web_sm) is absent from the Dockerfile, meaning production will always hit the OSError fallback path on startup.
backend/tests/unit/test_ner_speaker_identification.py Nine unit tests covering detection, filtering, fallback, and a basic performance bound; well-structured and covers the key code paths.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[detect_speaker_from_text called] --> B{spaCy available?}
    B -- Yes --> C[detect_speaker_from_text_ner]
    B -- No / Exception --> G[Regex patterns loop]
    C --> D[detect_speaker_names_ner spaCy NER pipeline]
    D --> E{Any PERSON entity with score >= 0.4?}
    E -- Yes --> F[Return top name]
    E -- No --> G
    G --> H{Regex match?}
    H -- Yes --> I[Return name.capitalize]
    H -- No --> J[Return None]

    subgraph NER Scoring
        D --> D1[Base score: 0.6]
        D1 --> D2[+0.15 if near speaker indicator]
        D2 --> D3[+0.1 if sentence start]
        D3 --> D4[+0.05 if properly capitalized]
        D4 --> D5[-0.3 if in _AMBIGUOUS_WORDS]
        D5 --> D6[cap at 1.0]
    end
Loading

Reviews (1): Last reviewed commit: "deps: add spacy for NER speaker detectio..." | Re-trigger Greptile

Comment thread backend/utils/speaker_identification.py Outdated
"""
# Primary: NER-based detection (catches natural mentions)
try:
from utils.ner_speaker_identification import detect_speaker_from_text_ner

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 In-function import violates backend import rule

The import of detect_speaker_from_text_ner is inside the function body. The project's backend-imports rule requires all imports to be at the module top level — no in-function imports. Move this to the top of speaker_identification.py alongside the other utils imports.

Should be moved to the top of the file as a module-level import. The try/except for the fallback can remain inside the function, but the import itself must be at module level.

Context Used: Backend Python import rules - no in-function impor... (source)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: moved import to module level (line 19 of speaker_identification.py). Import hierarchy now matches the rest of the backend.

Comment on lines +157 to +161
_AMBIGUOUS_WORDS = {
"will", "grace", "faith", "hope", "joy", "mark", "bill",
"art", "bob", "frank", "iris", "lily", "rose", "ruby",
"chase", "grant", "hunter", "mason", "parker", "reed",
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 _AMBIGUOUS_WORDS penalty silently drops common first names below the confidence threshold

Names in this set receive a -0.3 penalty, bringing their base score to 0.3 — which falls below the 0.4 threshold in detect_speaker_from_text_ner. For a natural third-person mention like "Tell Bob I'll be there", the score would be 0.6 (base) - 0.3 (ambiguous) + 0.05 (capitalized) = 0.35, so the function returns None. The regex fallback also won't match this pattern, so the name is silently dropped. "Bob", "Bill", "Mark", and "Frank" are all common English first names that would be systematically missed in third-person contexts.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: reduced penalty from -0.3 to -0.1. Common names like Will/Grace/Bob were dropping below the 0.4 confidence threshold despite strong spaCy PERSON tags. Now they receive only a minor adjustment.

Comment on lines +33 to +48
def _get_nlp():
"""Lazy-load spaCy model. Returns None if unavailable."""
global _nlp, _nlp_load_attempted
if _nlp_load_attempted:
return _nlp

_nlp_load_attempted = True
try:
import spacy
_nlp = spacy.load("en_core_web_sm", disable=["parser", "lemmatizer", "textcat"])
logger.info("NER speaker identification: spaCy model loaded")
except (ImportError, OSError) as e:
logger.warning(f"spaCy not available, falling back to regex: {e}")
_nlp = None

return _nlp

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Blocking spacy.load() on first async request

spacy.load() reads a ~50 MB model file from disk synchronously. Called lazily on the first request in a FastAPI async worker, this blocks the event loop for the entire load duration (~100–500 ms). Consider preloading the model at application startup (e.g., in a FastAPI lifespan handler) rather than on the first live request.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: now runs in a background ThreadPoolExecutor. kicks off the async I/O off the hot path. returns the already-loaded model synchronously. First call may fall back to regex until load completes — no hard failure.

Comment thread backend/requirements.txt
Comment on lines 225 to +227
lc3py==1.1.3
twilio==9.5.0
# NER speaker identification (MIT license, fast CPU inference)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 spacy is a hard dependency but the model download step is not in the Dockerfile

Adding spacy>=3.7.0 to requirements.txt makes it a mandatory production dependency, but the PR description notes the model must be separately downloaded via python -m spacy download en_core_web_sm. Without that step in the Dockerfile, the production container will have spaCy installed but no model, causing OSError on every first call (caught by the fallback, but logged as a warning on every boot). The Dockerfile change should be part of this PR.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: Dockerfile builder stage now installs en_core_web_sm wheel directly via pip. Falls back to regex with a warning if model download fails — no hard failure in container build.

…ed ambiguous-word penalty

P1: spacy.load() was blocking the async event loop.
  - Moved to ThreadPoolExecutor background load (fire-and-forget)
  - _ensure_nlp() kicks off background thread
  - _get_nlp() returns already-loaded model synchronously
  - First call may fall back to regex until model loads (graceful)

P2: Dockerfile missing spaCy model.
  - Added pip install of en_core_web_sm wheel in builder stage
  - Falls back to regex if model download fails (no hard failure)

P2 (carryover): _AMBIGUOUS_WORDS penalty reduced from -0.3 to -0.1
  - Common names like Will/Grace/Bob were below confidence threshold

Reviewed-by: greptile
@moneysavvy

Copy link
Copy Markdown
Author

All Greptile threads have been addressed and replied to. This is ready for maintainer review when available.

@beastoin beastoin closed this Apr 28, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Hey @moneysavvy 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our roadmap and vision

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community! 💜

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use NER (Named Entity Recognition) or better techniques (like self-hosted LLM) to improve speaker detection based on transcripts ($500)

2 participants