### Run the Next.js Moderated Comments example Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/nextjs-moderated-comments/README.md Commands to install dependencies and start the development server for the moderated comments example. ```bash # from this directory npm install npm run dev # open http://localhost:3000 ``` -------------------------------- ### Install allprofanity Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Install the package using npm or yarn. ```bash npm install allprofanity # or yarn add allprofanity ``` -------------------------------- ### Install Dependencies Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md Run this command to install the necessary project dependencies. ```bash npm install ``` -------------------------------- ### Example Config File Structure Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md The structure of the allprofanity.config.json file. ```json { "algorithm": { "matching": "hybrid", "useAhoCorasick": true, "useBloomFilter": true, "useContextAnalysis": true }, "contextAnalysis": { "enabled": true, "contextWindow": 50, "languages": ["en"], "scoreThreshold": 0.5 }, "profanityDetection": { "enableLeetSpeak": true, "caseSensitive": false, "strictMode": false }, "performance": { "enableCaching": true, "cacheSize": 1000 } } ``` -------------------------------- ### Run the AllProfanity Demo Client Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/mcp/README.md Commands to build the project and execute the demo client to verify the MCP server setup. ```bash # from the repository root npm run build node examples/mcp/demo-client.mjs ``` -------------------------------- ### Initialize AllProfanity with Config Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples-config/README.md Example of importing a local configuration file and initializing the AllProfanity filter. ```typescript import { AllProfanity } from 'allprofanity'; import config from './allprofanity.config.json'; const filter = AllProfanity.fromConfig(config); filter.check('user message here'); ``` -------------------------------- ### Start Express Server Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md Starts the Express server, which defaults to http://localhost:3000. ```bash npm start # Server runs at http://localhost:3000 ``` -------------------------------- ### Troubleshoot Port Already in Use Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md Command to start the application on a different port if the default is occupied. ```bash # Use different port PORT=3001 npm start ``` -------------------------------- ### Load Configuration in Code Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Examples for loading the configuration file into the AllProfanity instance using ES Modules or CommonJS. ```typescript // ES Modules / TypeScript import { AllProfanity } from 'allprofanity'; import config from './allprofanity.config.json'; const filter = AllProfanity.fromConfig(config); ``` ```javascript // CommonJS (Node.js) const { AllProfanity } = require('allprofanity'); const config = require('./allprofanity.config.json'); const filter = AllProfanity.fromConfig(config); ``` -------------------------------- ### Setup AllProfanity Configuration Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples-config/README.md Commands to copy a preset configuration file into your project and generate a JSON schema for IDE autocomplete. ```bash # 1. Copy a preset into your project as allprofanity.config.json cp node_modules/allprofanity/examples-config/chat-app.json ./allprofanity.config.json # 2. (Optional) generate the JSON schema for IDE autocomplete npx allprofanity ``` -------------------------------- ### Default Configuration in allprofanity.config.json Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md The default setup using the hybrid algorithm with Aho-Corasick, Bloom filter, and context analysis enabled. ```json { "algorithm": { "matching": "hybrid", "useAhoCorasick": true, "useBloomFilter": true, "useContextAnalysis": true }, "performance": { "enableCaching": true, "cacheSize": 1000 } } ``` -------------------------------- ### Full Example of AllProfanity Features Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Demonstrates core library functionality including multi-language loading, leet-speak detection, whitelisting, severity analysis, custom dictionaries, and placeholder configuration. ```typescript import profanity, { ProfanitySeverity } from 'allprofanity'; // Multi-language detection profanity.loadLanguages(['english', 'french', 'tamil']); console.log(profanity.check('Ce mot est merde.')); // true // Leet-speak detection console.log(profanity.check('You a f#cking a55hole!')); // true // Whitelisting profanity.addToWhitelist(['anal', 'ass']); console.log(profanity.check('He is an associate professor.')); // false // Severity const result = profanity.detect('This is fucking bullshit and chutiya.'); console.log(ProfanitySeverity[result.severity]); // "SEVERE" // Custom dictionary profanity.loadCustomDictionary('pirate', ['barnacle-head', 'landlubber']); profanity.loadLanguage('pirate'); console.log(profanity.check('You barnacle-head!')); // true // Placeholder configuration profanity.setPlaceholder('#'); console.log(profanity.clean('This is bullshit.')); // "This is ########." profanity.setPlaceholder('*'); // Reset ``` -------------------------------- ### Project Testing and Build Commands Source: https://github.com/ayush-jadaun/allprofanity/blob/main/CONTRIBUTORS.md Run these commands to install dependencies, execute tests, lint the code, and build the project before submitting a pull request. ```bash # Install dependencies npm install # Run tests npm test # Run linting (if applicable) npm run lint # Build the project npm run build ``` -------------------------------- ### Negation Pattern Detection Example Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/SPEED_VS_ACCURACY.md Demonstrates how negation keywords preceding a flagged word can reduce the score to mark it as clean. ```text Text: "This is not fucking acceptable" Without Context: FLAGGED ❌ With Context: CLEAN ✅ Reason: "not" keyword before "fucking" triggers negation pattern ``` -------------------------------- ### Word Boundaries Example Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/SPEED_VS_ACCURACY.md Demonstrates how the isWholeWord() function prevents false positives by ensuring matches are standalone words. ```text Text: "The assassin was caught yesterday" Result: CLEAN ✅ Reason: Word boundary detection - "ass" is part of "assassin", not standalone Feature: isWholeWord() function (NOT context analysis) ``` -------------------------------- ### Real Profanity Detection Example Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/SPEED_VS_ACCURACY.md Shows that clear profanity without mitigating keywords is correctly flagged. ```text Text: "You're a fucking idiot" Result: FLAGGED ✅ Reason: No mitigating keywords, clear profanity usage ``` -------------------------------- ### clearList(): void Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Removes all loaded languages and dynamic words to start with a clean filter. ```typescript profanity.clearList(); profanity.check('fuck'); // false profanity.loadLanguage('english'); profanity.check('fuck'); // true ``` -------------------------------- ### Severity Scoring Example Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md Demonstrates how the filter returns a severity score based on the number of detected words. ```javascript const result = filter.detect(text); // MILD (1) - 1 word // MODERATE (2) - 2 words // SEVERE (3) - 3 words // EXTREME (4) - 4+ words ``` -------------------------------- ### Quick Start profanity check Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Import the default profanity instance to check strings for offensive content, including various evasion techniques. ```typescript import profanity from 'allprofanity'; // Simple check profanity.check('This is a clean sentence.'); // false profanity.check('What the f#ck is this?'); // true (masked character) profanity.check('This is sh1t'); // true (leet-speak) profanity.check('fuuuuck this'); // true (stretched letters) profanity.check('f u c k you'); // true (separated letters) profanity.check('fuck and fυck'); // true (unicode evasion) profanity.check('यह एक चूतिया परीक्षण है।'); // true (Hindi) profanity.check('Ye ek chutiya test hai.'); // true (Hinglish Roman script) // But the classics stay clean: profanity.check('I live in Scunthorpe'); // false profanity.check('a classic bass guitar class'); // false profanity.check('I write c# code, get 5% off'); // false ``` -------------------------------- ### Customizing profanity detection configuration Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples-config/README.md Examples of adding custom dictionaries, whitelisting domain-specific vocabulary, and modifying the default censor character. ```jsonc // Add your own brand-specific blocklist "customDictionaries": { "brand": ["competitorname", "internalcodename"] } // Whitelist domain vocabulary "whitelistWords": ["analysis", "assessment"] // Change the censor character "profanityDetection": { "defaultPlaceholder": "#" } ``` -------------------------------- ### Define Transliteration Expansion Mapping Source: https://github.com/ayush-jadaun/allprofanity/blob/main/ROADMAP.md Example of a bidirectional transliteration mapping dictionary used to catch cross-script profanity. ```typescript // Bidirectional transliteration mapping private readonly transliterations: Record = { // Hindi → Latin variants 'चूतिया': ['chutiya', 'chutia', 'chutya', 'chotiya'], 'मादरचोद': ['madarchod', 'madarchod', 'maderchod'], 'बहनचोद': ['bhenchod', 'banchod', 'bahnchod'], // Latin → Devanagari 'chutiya': ['चूतिया'], 'madarchod': ['मादरचोद'], // Arabic → Latin // ... }; // Add all transliterations to dictionary during initialization ``` -------------------------------- ### Troubleshoot TypeScript Compilation Error Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md Commands to resolve TypeScript compilation issues by installing the compiler globally or using ts-node. ```bash # Install TypeScript globally npm install -g typescript # Or use ts-node npx ts-node basic-usage.ts ``` -------------------------------- ### Medical Context Detection Example Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/SPEED_VS_ACCURACY.md Shows how the presence of medical keywords near a flagged word can reduce the score to mark it as clean. ```text Text: "The doctor examined the anal region" Without Context: FLAGGED ❌ With Context: CLEAN ✅ Reason: "doctor" keyword near "anal" triggers medical pattern ``` -------------------------------- ### ML-Based Intent Classification Implementation Source: https://github.com/ayush-jadaun/allprofanity/blob/main/ROADMAP.md An example of how to implement ML-based intent classification using TensorFlow.js. This approach is discouraged due to high latency and large model sizes. ```typescript import * as tf from '@tensorflow/tfjs'; // OR import { InferenceSession } from 'onnxruntime-web'; class IntentClassifier { private model: tf.LayersModel | null = null; async initialize() { console.warn('⚠️ ML model loading will add 100-500ms to first request'); this.model = await tf.loadLayersModel('path/to/model.json'); } async classifyIntent(text: string): Promise<{ intent: 'hostile' | 'casual' | 'positive'; confidence: number; responseTime: number; // Track performance }> { const startTime = performance.now(); // Tokenize and predict const tokens = await this.tokenize(text); const prediction = await this.model!.predict(tokens); const responseTime = performance.now() - startTime; if (responseTime > 100) { console.warn(`⚠️ ML inference took ${responseTime}ms - significantly slower than pattern matching`); } return { intent: this.mapToIntent(prediction), confidence: prediction.confidence, responseTime }; } } ``` -------------------------------- ### Apply Plug-and-Play Presets Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Copy a pre-made configuration preset to your project and load it using AllProfanity.fromConfig. ```bash cp node_modules/allprofanity/examples-config/chat-app.json ./allprofanity.config.json ``` ```typescript import { AllProfanity } from 'allprofanity'; import config from './allprofanity.config.json'; const filter = AllProfanity.fromConfig(config); ``` -------------------------------- ### Configure via Config File Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Generate the configuration files and load them into the AllProfanity instance. ```bash # Generate config files in your project npx allprofanity # This creates: # - allprofanity.config.json (main config) # - config.schema.json (for IDE autocomplete) ``` ```typescript import { AllProfanity } from 'allprofanity'; import config from './allprofanity.config.json'; // Load from generated config file const filter = AllProfanity.fromConfig(config); // Or directly from object (no file needed) const filter2 = AllProfanity.fromConfig({ algorithm: { matching: "hybrid", useContextAnalysis: true }, performance: { enableCaching: true, cacheSize: 1000 } }); ``` -------------------------------- ### Generate Configuration Files Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Command to initialize the project with default configuration files. ```bash # Run this in your project directory npx allprofanity # Output: # ✅ AllProfanity configuration files created! # # Created files: # 📄 allprofanity.config.json - Main configuration # 📄 config.schema.json - JSON schema for IDE autocomplete ``` -------------------------------- ### Initialize AllProfanity with advanced features Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/SPEED_VS_ACCURACY.md Shows how to opt-in to advanced features like hybrid matching, context analysis, and caching for improved accuracy and performance. ```typescript const filter = new AllProfanity({ algorithm: { matching: "hybrid", useContextAnalysis: true }, performance: { enableCaching: true } }); ``` -------------------------------- ### Configure AllProfanity algorithm settings Source: https://github.com/ayush-jadaun/allprofanity/blob/main/ROADMAP.md Demonstrates the default fast configuration versus opt-in advanced features, while explicitly warning against high-latency ML classification settings. ```typescript // Default config - FAST (< 1ms) const filter = new AllProfanity(); // Advanced config - MODERATE (< 10ms) const filter = new AllProfanity({ algorithm: { matching: "hybrid", usePhoneticMatching: true, // OPT-IN } }); // DO NOT PROVIDE THIS const filter = new AllProfanity({ algorithm: { useMLClassification: true, // ❌ 100-500ms } }); ``` -------------------------------- ### Generate configuration file Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Use npx to generate the default configuration and schema files in your project. ```bash npx allprofanity # Creates allprofanity.config.json and config.schema.json in your project ``` -------------------------------- ### Define CulturalContext and culturalContexts Source: https://github.com/ayush-jadaun/allprofanity/blob/main/ROADMAP.md Defines the structure for regional profanity severity multipliers and provides example configurations for US, IN, and SA regions. ```typescript interface CulturalContext { region: 'US' | 'UK' | 'IN' | 'BR' | 'DE' | 'FR' | 'MX' | 'SA' | 'CN'; severityMultipliers: Record; } const culturalContexts: Record = { 'US': { region: 'US', severityMultipliers: { [ProfanityCategory.RACIST]: 1.5, [ProfanityCategory.SEXUAL]: 1.0, [ProfanityCategory.RELIGIOUS]: 0.7 } }, 'IN': { region: 'IN', severityMultipliers: { [ProfanityCategory.RELIGIOUS]: 1.5, [ProfanityCategory.SEXUAL]: 1.3, [ProfanityCategory.RACIST]: 1.2 } }, 'SA': { // Saudi Arabia region: 'SA', severityMultipliers: { [ProfanityCategory.RELIGIOUS]: 2.0, [ProfanityCategory.SEXUAL]: 1.8 } } }; ``` -------------------------------- ### V2.2 Algorithm and Performance Configuration Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/process.md Demonstrates configuring AllProfanity for specific use cases including Aho-Corasick for large texts, caching for repeated inputs, and a hybrid production configuration. ```typescript // Short texts: Use Trie (default) const chatFilter = new AllProfanity(); // ~27K ops/sec // Large texts: Use Aho-Corasick const docFilter = new AllProfanity({ algorithm: { matching: "aho-corasick" } }); // ~9.6K ops/sec (664% faster!) // Repeated inputs: Use Caching const formFilter = new AllProfanity({ performance: { enableCaching: true } }); // ~3.4M ops/sec on cache hits (123x faster!) // Production: Use Everything const prodFilter = new AllProfanity({ algorithm: { matching: "hybrid", useBloomFilter: true, useAhoCorasick: true, useContextAnalysis: true }, performance: { enableCaching: true } }); // Optimized for all scenarios ``` -------------------------------- ### Full Configuration Schema Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md The complete JSON structure for configuring AllProfanity algorithms, detection settings, and performance options. ```typescript { "algorithm": { "matching": "trie" | "aho-corasick" | "hybrid", // Algorithm selection "useAhoCorasick": boolean, // Enable Aho-Corasick "useBloomFilter": boolean, // Enable Bloom Filter "useContextAnalysis": boolean // Enable context analysis }, "bloomFilter": { "enabled": boolean, // Enable/disable "expectedItems": number, // Expected dictionary size (default: 10000) "falsePositiveRate": number // Acceptable false positive rate (default: 0.01) }, "ahoCorasick": { "enabled": boolean, // Enable/disable "prebuild": boolean // Prebuild automaton (default: true) }, "contextAnalysis": { "enabled": boolean, // Enable/disable pattern-based context detection "contextWindow": number, // Characters around match to check (default: 50) "languages": string[], // Languages for keyword patterns (default: ["en"]) "scoreThreshold": number // Detection threshold 0-1 (default: 0.5) }, "profanityDetection": { "enableLeetSpeak": boolean, // Detect l33t speak (default: true) "caseSensitive": boolean, // Case sensitive matching (default: false) "strictMode": boolean, // Require word boundaries (default: false) "detectPartialWords": boolean, // Detect within words (default: false) "defaultPlaceholder": string // Default censoring character (default: "*") }, "evasionProtection": { "unicode": boolean, // Fold fullwidth/homoglyphs/diacritics/invisibles (default: true) "repeatedCharacters": boolean, // Collapse "fuuuuck" (default: true) "maskedCharacters": boolean, // Resolve "f*ck", "f#ck" (default: true) "separatedLetters": boolean // Catch "f u c k" (default: true) }, "performance": { "enableCaching": boolean, // Enable result cache (default: false) "cacheSize": number // Cache size limit (default: 1000) } } ``` -------------------------------- ### Connect AllProfanity to Claude Code Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/mcp/README.md Use this command to add the AllProfanity MCP server to Claude Code. ```bash claude mcp add allprofanity -- npx -y -p allprofanity allprofanity-mcp ``` -------------------------------- ### AllProfanity.fromConfig(config: object) Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Creates an instance of the AllProfanity filter using a provided configuration object. ```APIDOC ## AllProfanity.fromConfig(config: object) ### Description Initializes a new AllProfanity instance based on a configuration object, which can be loaded from a JSON file or defined inline. ### Parameters - **config** (object) - Required - Configuration object containing algorithm, performance, and detection settings. ### Returns - **AllProfanity** - An instance of the profanity filter configured with the provided settings. ``` -------------------------------- ### Configure AllProfanity for Claude Desktop or Cursor Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/mcp/README.md Add this configuration to your claude_desktop_config.json to enable the AllProfanity MCP server with specific language support. ```json { "mcpServers": { "allprofanity": { "command": "npx", "args": ["-y", "-p", "allprofanity", "allprofanity-mcp"], "env": { "ALLPROFANITY_LANGUAGES": "french,german,spanish" } } } } ``` -------------------------------- ### updateConfig(options: Partial): void Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/process.md Updates the library configuration at runtime. ```APIDOC ## updateConfig(options: Partial) ### Description Modifies settings such as leet-speak detection or case sensitivity. Note that changing case sensitivity may trigger a trie rebuild. ### Parameters - **options** (Partial) - Required - The configuration options to update. ``` -------------------------------- ### Initialize AllProfanity with default behavior Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/SPEED_VS_ACCURACY.md Demonstrates the default initialization of the AllProfanity filter, which maintains backward compatibility with previous versions. ```typescript const filter = new AllProfanity(); filter.check("text"); // Works exactly as before ``` -------------------------------- ### AllProfanity Constructor Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Initializes the AllProfanity filter with specific configuration options for algorithms, performance, context analysis, and evasion protection. ```APIDOC ## new AllProfanity(options) ### Description Initializes a new instance of the profanity filter. The behavior can be customized via the options object to balance performance, accuracy, and evasion detection. ### Parameters - **options** (object) - Optional - Configuration object - **algorithm** (object) - Optional - Matching algorithm settings - **matching** (string) - Optional - Algorithm type (e.g., "aho-corasick", "hybrid") - **useBloomFilter** (boolean) - Optional - Enable bloom filter - **useAhoCorasick** (boolean) - Optional - Enable Aho-Corasick algorithm - **useContextAnalysis** (boolean) - Optional - Enable context analysis - **contextAnalysis** (object) - Optional - Context analysis settings - **enabled** (boolean) - Optional - Enable context analysis - **contextWindow** (number) - Optional - Size of the context window - **languages** (array) - Optional - Supported languages - **scoreThreshold** (number) - Optional - Sensitivity threshold - **performance** (object) - Optional - Performance settings - **enableCaching** (boolean) - Optional - Enable result caching - **cacheSize** (number) - Optional - Maximum cache size - **evasionProtection** (object) - Optional - Evasion protection settings - **unicode** (boolean) - Optional - Fold homoglyphs/diacritics - **repeatedCharacters** (boolean) - Optional - Collapse repeated characters - **maskedCharacters** (boolean) - Optional - Resolve masked characters - **separatedLetters** (boolean) - Optional - Catch separated letters ``` -------------------------------- ### Balanced Production Template Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md General purpose configuration template for production environments. ```json { "algorithm": { "matching": "hybrid", "useAhoCorasick": true, "useBloomFilter": true }, "profanityDetection": { "enableLeetSpeak": true }, "performance": { "enableCaching": true, "cacheSize": 1000 } } ``` -------------------------------- ### new AllProfanity(options: object) Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Creates a new instance of the AllProfanity filter using constructor options. ```APIDOC ## new AllProfanity(options: object) ### Description Constructs a new AllProfanity filter instance with specific algorithm and performance options. ### Parameters - **options** (object) - Required - Configuration options for the filter, such as algorithm matching types and performance settings. ``` -------------------------------- ### Configure via Constructor Options Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Initialize the filter directly with configuration options passed to the constructor. ```typescript import { AllProfanity } from 'allprofanity'; const filter = new AllProfanity({ algorithm: { matching: "hybrid" }, performance: { enableCaching: true } }); ``` -------------------------------- ### getConfig(): Partial Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Retrieves the current configuration object. ```typescript console.log(profanity.getConfig()); /* { defaultPlaceholder: '*', enableLeetSpeak: true, caseSensitive: false, strictMode: false, detectPartialWords: false, languages: [...], whitelistWords: [...] } */ ``` -------------------------------- ### Performance Caching Configuration Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md Configures the AllProfanity instance to enable caching for improved performance on repeated inputs. ```javascript const filter = new AllProfanity({ performance: { enableCaching: true, cacheSize: 1000 } }); ``` -------------------------------- ### getConfig Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/process.md Retrieves the current configuration settings. ```APIDOC ## getConfig(): Partial ### Description Accesses the current configuration for display, audit logs, admin panels, or debugging. ``` -------------------------------- ### Troubleshoot Module Not Found Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md Commands to resolve module errors by clearing and reinstalling dependencies. ```bash # Reinstall dependencies rm -rf node_modules npm install ``` -------------------------------- ### addToWhitelist(words: string[]): void Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Adds words to the whitelist so they are never flagged as profane. ```APIDOC ## addToWhitelist(words: string[]): void ### Description Whitelist words so they are never flagged as profane. ### Parameters - **words** (string[]) - Required - The list of words to whitelist. ``` -------------------------------- ### Load Languages and Dictionaries Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md Demonstrates how to load specific languages, all Indian languages, or a custom dictionary into the filter. ```javascript // Load specific languages filter.loadLanguages(['english', 'french', 'hindi']); // Load all Indian languages filter.loadIndianLanguages(); // Load custom dictionary filter.loadCustomDictionary('pirate', ['barnacle-head', 'landlubber']); ``` -------------------------------- ### Implement Phonetic Matching with Soundex Source: https://github.com/ayush-jadaun/allprofanity/blob/main/ROADMAP.md Provides a basic Soundex algorithm implementation to detect phonetic variants of profanity. This approach has a moderate performance cost and is recommended as an opt-in feature. ```typescript // Simple Soundex algorithm (no external deps) class PhoneticMatcher { private soundexMap: Map = new Map(); private soundex(word: string): string { // Simple soundex: keep first letter, encode rest const code = word[0].toUpperCase(); const encoded = word.slice(1) .replace(/[aeiouyhw]/gi, '0') .replace(/[bfpv]/gi, '1') .replace(/[cgjkqsxz]/gi, '2') .replace(/[dt]/gi, '3') .replace(/[l]/gi, '4') .replace(/[mn]/gi, '5') .replace(/[r]/gi, '6') .replace(/0+/g, '') .replace(/(.)\\\1+/g, '$1'); return (code + encoded + '000').substring(0, 4); } addWord(word: string): void { const code = this.soundex(word); if (!this.soundexMap.has(code)) { this.soundexMap.set(code, []); } this.soundexMap.get(code)!.push(word); } findPhoneticMatches(word: string): string[] { const code = this.soundex(word); return this.soundexMap.get(code) || []; } } ``` -------------------------------- ### Chat/Comments Configuration Preset Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md Optimized for speed, this preset uses the trie algorithm and is best for texts under 500 characters. ```javascript const filter = new AllProfanity({ algorithm: { matching: "trie" }, performance: { enableCaching: true } }); // ~27K ops/sec - best for <500 char texts ``` -------------------------------- ### Configure AllProfanity for High Accuracy Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/SPEED_VS_ACCURACY.md Enable hybrid matching, Bloom filters, Aho-Corasick, and context analysis for social media or user-generated content to achieve near-perfect accuracy and reduce false positives. ```typescript const filter = new AllProfanity({ algorithm: { matching: "hybrid", useBloomFilter: true, useAhoCorasick: true, useContextAnalysis: true }, contextAnalysis: { enabled: true, contextWindow: 50, languages: ["en"], scoreThreshold: 0.5 } }); // Near-perfect accuracy, reduces false positives ``` -------------------------------- ### Add custom dictionary via loadCustomDictionary Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/process.md Create a string array and register it using the loadCustomDictionary function to extend the system's vocabulary. ```javascript loadCustomDictionary('myLang', [...]) ``` -------------------------------- ### Implement AdaptiveLearning class Source: https://github.com/ayush-jadaun/allprofanity/blob/main/ROADMAP.md Provides a mechanism to collect user feedback and automatically adjust whitelists based on common false positives identified in batch processing. ```typescript class AdaptiveLearning { private feedbackDb: FeedbackData[] = []; submitFeedback(feedback: { text: string; detectionResult: boolean; userFeedback: 'correct' | 'false_positive' | 'false_negative'; }): void { this.feedbackDb.push({ ...feedback, timestamp: Date.now() }); // Batch processing every 100 feedbacks if (this.feedbackDb.length >= 100) { this.analyzeAndAdjust(); } } private analyzeAndAdjust(): void { // Find common false positives const falsePositives = this.feedbackDb .filter(f => f.userFeedback === 'false_positive') .map(f => this.extractWords(f.text)); // Auto-whitelist words that appear in >80% of false positives const commonFalsePositives = this.findCommonPatterns( falsePositives, 0.8 ); // Add to whitelist (with option to review) this.addToWhitelist(commonFalsePositives); } } ``` -------------------------------- ### Configure AllProfanity for Maximum Speed Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/SPEED_VS_ACCURACY.md Use the trie algorithm for real-time chat applications where speed is the primary constraint, achieving approximately 27,000 operations per second. ```typescript const filter = new AllProfanity({ algorithm: { matching: "trie" } }); // ~27,000 ops/sec, simple and fast ``` -------------------------------- ### Reduced False Positives Template Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Configuration template optimized for content moderation to minimize false positives. ```json { "algorithm": { "matching": "hybrid", "useContextAnalysis": true, "useBloomFilter": true }, "contextAnalysis": { "enabled": true, "contextWindow": 50, "scoreThreshold": 0.5 }, "performance": { "enableCaching": true } } ``` -------------------------------- ### cleanWithPlaceholder(text: string, placeholder?: string): string Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/process.md Replaces entire profane words with a fixed placeholder string. ```APIDOC ## cleanWithPlaceholder(text: string, placeholder?: string): string ### Description Replaces each detected profane word with a fixed placeholder string, such as '[CENSORED]'. ### Parameters - **text** (string) - Required - The text to clean. - **placeholder** (string) - Optional - The string to replace the word with (default: '***'). ``` -------------------------------- ### loadCustomDictionary(name: string, words: string[]): void Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Adds a custom dictionary as an additional language. After loading, the language must be explicitly set using loadLanguage before it can be used for checks. ```typescript profanity.loadCustomDictionary('swedish', ['fan', 'jävla', 'skit']); profanity.loadLanguage('swedish'); profanity.check('Det här är skit.'); // true ``` -------------------------------- ### Configure AllProfanity for Large Text Processing Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/SPEED_VS_ACCURACY.md Use the aho-corasick algorithm for processing large documents, which is 664% faster on texts larger than 1KB. ```typescript const filter = new AllProfanity({ algorithm: { matching: "aho-corasick" } }); // 664% faster on 1KB+ texts ``` -------------------------------- ### Reduced False Positives Configuration Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Configures a hybrid matching algorithm with context analysis to reduce false positives in social media and content moderation scenarios. ```typescript const filter = new AllProfanity({ algorithm: { matching: "hybrid", useBloomFilter: true, useAhoCorasick: true, useContextAnalysis: true }, contextAnalysis: { enabled: true, contextWindow: 50, languages: ["en"], scoreThreshold: 0.5 } }); // Pattern-based context detection reduces medical/negation false positives ``` -------------------------------- ### Document Processing Configuration Preset Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md A balanced configuration using the aho-corasick algorithm, designed for faster processing of large texts. ```javascript const filter = new AllProfanity({ algorithm: { matching: "aho-corasick" }, performance: { enableCaching: true } }); // ~9.6K ops/sec - 664% faster on large texts ``` -------------------------------- ### Default Configuration Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md The default configuration uses an optimized Trie structure, providing fast and reliable performance for general use cases. ```typescript import { AllProfanity } from 'allprofanity'; const filter = new AllProfanity(); // Uses optimized Trie - fast and reliable (300K+ ops/sec on short texts) ``` -------------------------------- ### getConfig() Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Retrieves the current configuration settings of the profanity filter. ```APIDOC ## getConfig() ### Description Get the current configuration. ### Returns - **Partial** - The current configuration object. ``` -------------------------------- ### addToWhitelist / removeFromWhitelist Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/process.md Manage the whitelist to prevent false positives. ```APIDOC ## addToWhitelist(words: string[]) / removeFromWhitelist(words: string[]) ### Description Updates the whitelist to ensure specific words are never flagged as profanity. ### Parameters - **words** (string[]) - Required - The list of words to add to or remove from the whitelist. ``` -------------------------------- ### loadCustomDictionary Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/process.md Adds a custom language pack at runtime for use in profanity filtering. ```APIDOC ## loadCustomDictionary(name: string, words: string[]): void ### Description Adds a custom language pack at runtime. This is useful for company-specific slang, new languages, or UGC-driven dictionaries. ### Parameters - **name** (string) - Required - The name to register the dictionary under. - **words** (string[]) - Required - The list of words to include in the dictionary. ``` -------------------------------- ### Configure AllProfanity for Repeated Checks Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/SPEED_VS_ACCURACY.md Enable caching for form validation or API endpoints to achieve up to 123x speedup on repeated inputs. ```typescript const filter = new AllProfanity({ algorithm: { matching: "hybrid" }, performance: { enableCaching: true, cacheSize: 1000 } }); // 123x speedup on cache hits ``` -------------------------------- ### Configure AllProfanity for Medical or Professional Content Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/SPEED_VS_ACCURACY.md Adjust context analysis settings with a wider window and higher score threshold to prevent false flags in professional or medical contexts. ```typescript const filter = new AllProfanity({ algorithm: { matching: "hybrid", useContextAnalysis: true }, contextAnalysis: { enabled: true, contextWindow: 100, // Wider context scoreThreshold: 0.7 // Higher threshold (less sensitive) } }); // Prevents false flags in professional contexts ``` -------------------------------- ### loadCustomDictionary(name: string, words: string[]) Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Adds a custom dictionary as an additional language for the profanity filter. ```APIDOC ## loadCustomDictionary(name: string, words: string[]) ### Description Adds a custom dictionary as an additional language for the profanity filter. ### Parameters - **name** (string) - Required - The name of the language dictionary. - **words** (string[]) - Required - An array of words to include in the dictionary. ``` -------------------------------- ### High Performance Template Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Configuration template optimized for processing large texts. ```json { "algorithm": { "matching": "aho-corasick" }, "ahoCorasick": { "enabled": true, "prebuild": true }, "profanityDetection": { "enableLeetSpeak": true } } ``` -------------------------------- ### Test API Endpoints Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md Use these curl commands to test blocking mode, cleaning mode, and chat message processing. ```bash # Test blocking mode (rejects profanity) curl -X POST http://localhost:3000/block \ -H "Content-Type: application/json" \ -d '{"content":"This is bullshit"}' # Test cleaning mode (sanitizes profanity) curl -X POST http://localhost:3000/clean \ -H "Content-Type: application/json" \ -d '{"content":"What the fuck is this?"}' # Test chat message (real-world example) curl -X POST http://localhost:3000/send-message \ -H "Content-Type: application/json" \ -d '{"content":"This is fucking bullshit","userId":"user123"}' ``` -------------------------------- ### Manage whitelist with addToWhitelist() Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Adds words to a whitelist so they are ignored by the profanity filter. ```typescript profanity.addToWhitelist(['fuck', 'idiot','shit']); profanity.check('He is an fucking idiot.'); // false profanity.check('Fuck this shit.'); // false // Remove from whitelist to restore detection profanity.removeFromWhitelist(['fuck', 'idiot','shit']); ``` -------------------------------- ### getAvailableLanguages() Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Returns the names of all available built-in language packs. ```APIDOC ## getAvailableLanguages() ### Description Returns the names of all available built-in language packs. ### Returns - **string[]** - A list of names of available built-in languages. ``` -------------------------------- ### clean(text: string, placeholder?: string): string Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/process.md Replaces each character of detected profane words with a placeholder character. ```APIDOC ## clean(text: string, placeholder?: string): string ### Description Masks profane words by replacing each character with a placeholder, preserving the original word length. ### Parameters - **text** (string) - Required - The text to clean. - **placeholder** (string) - Optional - The character to use for masking (default: '*'). ``` -------------------------------- ### profanity.loadLanguages(languages: string[]) Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Loads specific language dictionaries for profanity detection. ```APIDOC ## profanity.loadLanguages(languages: string[]) ### Description Loads the specified language dictionaries into the profanity filter. ### Parameters - **languages** (string[]) - Required - An array of language names to load. ``` -------------------------------- ### Configure Phonetic Matching Options Source: https://github.com/ayush-jadaun/allprofanity/blob/main/ROADMAP.md Configuration structure for enabling phonetic matching, defaulting to disabled to maintain performance. ```typescript { algorithm: { usePhoneticMatching: false // Default OFF for performance }, phoneticMatching: { enabled: false, algorithm: 'soundex' | 'metaphone' } } ``` -------------------------------- ### loadLanguage / loadLanguages / loadIndianLanguages Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/process.md Methods to load built-in language dictionaries. ```APIDOC ## loadLanguage(language: string) / loadLanguages(languages: string[]) / loadIndianLanguages() ### Description Loads built-in profanity dictionaries into the filter. `loadIndianLanguages` is a shortcut for loading Hindi, Bengali, Tamil, and Telugu. ``` -------------------------------- ### Test Blocking Middleware Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md cURL commands to test the /block endpoint with and without profanity. ```bash # With profanity (should fail) curl -X POST http://localhost:3000/block \ -H "Content-Type: application/json" \ -d '{"content":"This is bullshit"}' # Returns: 400 Bad Request # Without profanity (should pass) curl -X POST http://localhost:3000/block \ -H "Content-Type: application/json" \ -d '{"content":"This is clean content"}' # Returns: 200 OK ``` -------------------------------- ### Update configuration with updateConfig() Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Modifies library settings at runtime, such as case sensitivity or leetspeak detection. ```typescript profanity.updateConfig({ caseSensitive: true, enableLeetSpeak: false }); profanity.check('FUCK'); // false (if caseSensitive) profanity.updateConfig({ caseSensitive: false, enableLeetSpeak: true }); profanity.check('f#ck'); // true ``` -------------------------------- ### Detect profanity details with detect() Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Returns a detailed object containing detection status, matched words, severity, and character-masked text. ```typescript const result = profanity.detect('This is fucking bullshit and chutiya.'); console.log(result.hasProfanity); // true console.log(result.detectedWords); // ['fucking', 'bullshit', 'chutiya'] console.log(result.severity); // 3 (SEVERE) console.log(result.cleanedText); // "This is ******* ******** and ******." console.log(result.positions); // e.g. [{word: 'fucking', start: 8, end: 15}, ...] ``` -------------------------------- ### getAvailableLanguages(): string[] Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Returns the names of all available built-in language packs. ```typescript console.log(profanity.getAvailableLanguages()); // ['english', 'hindi', 'french', 'german', 'spanish', 'bengali', 'tamil', 'telugu', 'brazilian', 'greek'] ``` -------------------------------- ### Test Cleaning Middleware Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md cURL commands to test the /clean and /translate endpoints for content sanitization. ```bash # With profanity (should clean) curl -X POST http://localhost:3000/clean \ -H "Content-Type: application/json" \ -d '{"content":"What the fuck is this bullshit?"}' # Returns: 200 OK with cleaned content # Multi-language curl -X POST http://localhost:3000/translate \ -H "Content-Type: application/json" \ -d '{"content":"यह एक चूतिया परीक्षण है","language":"hindi"}' ``` -------------------------------- ### Content Moderation Configuration Preset Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md Focuses on accuracy by enabling context analysis with a specific score threshold to reduce false positives. ```javascript const filter = new AllProfanity({ algorithm: { matching: "hybrid", useContextAnalysis: true }, contextAnalysis: { enabled: true, scoreThreshold: 0.7 } }); // Balanced accuracy - reduces false positives ``` -------------------------------- ### POST /block Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md Checks content for profanity and returns a 400 error if detected, or 200 if clean. ```APIDOC ## POST /block ### Description Validates input content for profanity. Returns 400 Bad Request if profanity is found, otherwise returns 200 OK. ### Method POST ### Endpoint /block ### Request Body - **content** (string) - Required - The text content to check for profanity. ``` -------------------------------- ### Load multiple languages with loadLanguages() Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Loads multiple built-in language packs simultaneously. ```typescript profanity.loadLanguages(['english', 'french', 'german']); profanity.check('Das ist scheiße.'); // true (German) ``` -------------------------------- ### add(word: string | string[]): void Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Adds a word or an array of words to the profanity filter list. ```APIDOC ## add(word: string | string[]): void ### Description Add a word or an array of words to the profanity filter. ### Parameters - **word** (string | string[]) - Required - The word or list of words to add. ``` -------------------------------- ### Load Indian languages with loadIndianLanguages() Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Convenience method to load all major Indian language packs. ```typescript profanity.loadIndianLanguages(); profanity.check('यह एक बेंगाली गाली है।'); // true (Bengali) profanity.check('This is a Tamil profanity: புண்டை'); // true ``` -------------------------------- ### Legacy Trie-only implementation Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/process.md The original implementation using a single Trie algorithm, which was limited in performance for large texts. ```typescript // Simple, fast, but limited to one algorithm const filter = new AllProfanity(); // ~27K ops/sec on short texts // ~1.2K ops/sec on large texts ``` -------------------------------- ### POST /clean Source: https://github.com/ayush-jadaun/allprofanity/blob/main/examples/README.md Processes text to remove or mask profanity. ```APIDOC ## POST /clean ### Description Cleans the provided text by removing or masking detected profanity. ### Method POST ### Endpoint /clean ### Request Body - **content** (string) - Required - The text content to be cleaned. ``` -------------------------------- ### getLoadedLanguages(): string[] Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Returns the names of all currently loaded language packs. ```typescript console.log(profanity.getLoadedLanguages()); // ['english', 'hindi', ...] ``` -------------------------------- ### getLoadedLanguages() Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Returns the names of all currently loaded language packs. ```APIDOC ## getLoadedLanguages() ### Description Returns the names of all currently loaded language packs. ### Returns - **string[]** - A list of names of currently loaded languages. ``` -------------------------------- ### getLoadedLanguages / getAvailableLanguages Source: https://github.com/ayush-jadaun/allprofanity/blob/main/docs/process.md Methods for retrieving lists of currently loaded or available languages. ```APIDOC ## getLoadedLanguages(): string[] / getAvailableLanguages(): string[] ### Description Provides introspection for UI or admin use by returning the names of current or possible languages. ``` -------------------------------- ### Load Greek language support Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Use the loadLanguage function to enable Greek language filtering. ```javascript loadLanguage('greek') ``` -------------------------------- ### Implement Spacing and Punctuation Normalization Source: https://github.com/ayush-jadaun/allprofanity/blob/main/ROADMAP.md Normalizes words that have been obfuscated by inserting spaces, dots, dashes, or underscores between characters. ```typescript private normalizeSpacing(text: string): string { // Pattern 1: Single characters separated by spaces/punctuation // "f u c k" → "fuck", "f.u.c.k" → "fuck" let normalized = text.replace( /\b(\w)[\s\.\-_\*]+(\w)[\s\.\-_\*]+(\w)[\s\.\-_\*]+(\w)\b/gi, '$1$2$3$4' ); // Pattern 2: Longer words with excessive spacing // "f u c k i n g" → "fucking" normalized = normalized.replace( /\b(\w)[\s\.\-_\*]+(\w)[\s\.\-_\*]+(\w)[\s\.\-_\*]+(\w)[\s\.\-_\*]+(\w)[\s\.\-_\*]+(\w)[\s\.\-_\*]+(\w)\b/gi, '$1$2$3$4$5$6$7' ); return normalized; } ``` -------------------------------- ### Load language with loadLanguage() Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Loads a specific built-in language pack. ```typescript profanity.loadLanguage('french'); profanity.check('Ce mot est merde.'); // true ``` -------------------------------- ### Remove from whitelist with removeFromWhitelist() Source: https://github.com/ayush-jadaun/allprofanity/blob/main/README.md Removes words from the whitelist to allow them to be detected again. ```typescript profanity.removeFromWhitelist(['anal']); ```