-
Notifications
You must be signed in to change notification settings - Fork 230
feat(reporting): add passive voice detection to TipTap editor #796
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
marcpfuller
wants to merge
16
commits into
GhostManager:master
Choose a base branch
from
marcpfuller:passive_voice_detection
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
cd4fcfa
feat(reporting): add passive voice detection to TipTap editor
marcpfuller e64858d
fix: resolve issures with tests
marcpfuller c4c4f67
fix: resolve pylint issues
marcpfuller ac0545b
fix: resolve github security stack trace issue
marcpfuller 0d67486
Merge branch 'master' into passive_voice_detection
marcpfuller 05061fb
fix: resolve comments made by @ColonelThirtyTwo in PR
marcpfuller a78cf05
fix: add null check to upload.tsx when getting csrf token
marcpfuller d2f10f0
Merge branch 'master' into passive_voice_detection
marcpfuller eff2e67
fix: resolve Passive detector test
marcpfuller 316a44d
fix: added another test to increase code coverage
marcpfuller 310d099
fix: optimize the nlp model for improved performance
marcpfuller ecba774
Merge branch 'master' into passive_voice_detection
marcpfuller 8dac7bf
fix: allow nlp model to be swapped
marcpfuller 356615e
Merge branch 'passive_voice_detection' of https://github.com/marcpful…
marcpfuller 2355c4d
fix: remove unused variable from exception in detector.py
marcpfuller 068e54d
Merge branch 'master' into passive_voice_detection
marcpfuller File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Passive voice detection module using spaCy NLP.""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,165 @@ | ||
| """Passive voice detection service using spaCy NLP.""" | ||
|
|
||
| # Standard Libraries | ||
| import logging | ||
| import threading | ||
| import time | ||
| from typing import List, Tuple | ||
|
|
||
| # 3rd Party Libraries | ||
| import spacy | ||
|
|
||
| # Django Imports | ||
| from django.conf import settings | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class PassiveVoiceDetector: | ||
| """Thread-safe singleton service for detecting passive voice in text.""" | ||
|
|
||
| _instance = None | ||
| _nlp = None | ||
| _lock = threading.Lock() | ||
| _initialized = False | ||
|
|
||
| def __new__(cls): | ||
| """Implement singleton pattern to load spaCy model once.""" | ||
| if cls._instance is None: | ||
| with cls._lock: | ||
| # Double-check locking pattern | ||
| if cls._instance is None: | ||
| cls._instance = super().__new__(cls) | ||
| return cls._instance | ||
|
|
||
| def _ensure_initialized(self): | ||
| """Ensure model is loaded. Thread-safe initialization.""" | ||
| if self._initialized: | ||
| return | ||
|
|
||
| with self._lock: | ||
| # Double-check inside lock | ||
| if self._initialized: | ||
| return | ||
|
|
||
| try: | ||
| model_name = settings.SPACY_MODEL | ||
| logger.info("Loading spaCy model: %s", model_name) | ||
|
|
||
| start_time = time.perf_counter() | ||
|
|
||
| # Optimize: disable unused components for 30-40% speed improvement | ||
| # Only need: tagger (POS tags), parser (dependencies + sentences) | ||
| # Disable: ner (named entities), lemmatizer, textcat, etc. | ||
| self._nlp = spacy.load( | ||
| model_name, | ||
| disable=["ner", "lemmatizer", "textcat"] | ||
| ) | ||
|
|
||
| # Performance optimizations: | ||
| # 1. Remove attribute ruler if present (saves memory and time) | ||
| if self._nlp.has_pipe("attribute_ruler"): | ||
| self._nlp.remove_pipe("attribute_ruler") | ||
|
|
||
| # 2. Intern strings for faster lookups | ||
| # This reduces memory usage and improves cache locality | ||
| self._nlp.vocab.strings.add("auxpass") | ||
| self._nlp.vocab.strings.add("VBN") | ||
|
|
||
| load_time = (time.perf_counter() - start_time) * 1000 | ||
| logger.info("spaCy model '%s' loaded in %.2fms with optimizations", model_name, load_time) | ||
|
|
||
| self._initialized = True | ||
| except OSError: | ||
| logger.exception( | ||
| "Failed to load spaCy model '%s'. " | ||
| "Ensure the model is installed: python -m spacy download %s", | ||
| settings.SPACY_MODEL, | ||
| settings.SPACY_MODEL | ||
| ) | ||
| raise | ||
|
|
||
| def detect_passive_sentences(self, text: str) -> List[Tuple[int, int]]: | ||
| """ | ||
| Detect passive voice sentences in text with optimized performance. | ||
|
|
||
| Args: | ||
| text: Plain text to analyze | ||
|
|
||
| Returns: | ||
| List of (start_char, end_char) tuples for passive sentences | ||
|
|
||
| Example: | ||
| >>> detector = PassiveVoiceDetector() | ||
| >>> detector.detect_passive_sentences("The report was written.") | ||
| [(0, 23)] | ||
| """ | ||
| # Model is initialized in __new__, but double-check for thread safety | ||
| if not self._initialized: | ||
| self._ensure_initialized() | ||
|
|
||
| if not text or not text.strip(): | ||
| return [] | ||
|
|
||
| # Process text with spaCy (thread-safe after initialization) | ||
| doc = self._nlp(text) | ||
|
|
||
| # Optimized: use list comprehension instead of loop with append | ||
| passive_ranges = [ | ||
| (sent.start_char, sent.end_char) | ||
| for sent in doc.sents | ||
| if self._is_passive_voice(sent) | ||
| ] | ||
|
|
||
| return passive_ranges | ||
|
|
||
| def _is_passive_voice(self, sent) -> bool: | ||
| """ | ||
| Check if sentence contains passive voice construction (optimized). | ||
|
|
||
| Looks for auxiliary verb (auxpass) + past participle (VBN). | ||
| This pattern identifies constructions like: | ||
| - "was written" (auxpass: was, VBN: written) | ||
| - "were exploited" (auxpass: were, VBN: exploited) | ||
| - "has been analyzed" (auxpass: been, VBN: analyzed) | ||
|
|
||
| Args: | ||
| sent: spaCy Span object representing a sentence | ||
|
|
||
| Returns: | ||
| True if sentence contains passive voice, False otherwise | ||
| """ | ||
| # Optimized: single-pass check for both patterns | ||
| # Eliminates redundant token iteration | ||
| for token in sent: | ||
| # Pattern 1: Direct passive auxiliary dependency (most common) | ||
| if token.dep_ == "auxpass": | ||
| return True | ||
|
|
||
| # Pattern 2: Past participle with auxpass child (less common) | ||
| # Check inline to avoid second loop | ||
| if token.tag_ == "VBN": | ||
| # Check children efficiently with any() | ||
| if any(child.dep_ == "auxpass" for child in token.children): | ||
| return True | ||
|
|
||
| return False | ||
|
|
||
|
|
||
| def get_detector() -> PassiveVoiceDetector: | ||
marcpfuller marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| """ | ||
| Get the singleton detector instance. | ||
|
|
||
| The PassiveVoiceDetector class implements singleton pattern via __new__, | ||
| so calling this function always returns the same instance. | ||
|
|
||
| Returns: | ||
| PassiveVoiceDetector: The singleton detector instance | ||
|
|
||
| Example: | ||
| >>> from ghostwriter.modules.passive_voice.detector import get_detector | ||
| >>> detector = get_detector() | ||
| >>> detector.detect_passive_sentences("The bug was fixed.") | ||
| [(0, 18)] | ||
| """ | ||
| return PassiveVoiceDetector() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Tests for passive voice detection module.""" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.