Certainly! Let's create a complete TypeScript implementation based on your initial framework. We'll enhance the phonetic conversion by utilizing existing libraries where possible:
- English Phonetic Conversion: We'll use the
natural library, which provides the Metaphone algorithm.
- Russian Phonetic Conversion: Since specialized phonetic libraries for Russian are less common, we'll implement a basic transliteration approach using the
transliteration library to convert Cyrillic text to Latin characters. This isn't a perfect phonetic representation but serves as a reasonable approximation for our purposes.
Overview
The final implementation will:
- Convert text to phonetic representations for English and Russian.
- Identify similar-sounding patterns using the Levenshtein distance.
- Highlight similar-sounding parts with different colors.
- Provide example usage demonstrating the functionality.
Prerequisites
Before diving into the code, ensure that you have Node.js installed. We'll use npm to manage dependencies.
Install Required Packages
Open your terminal and navigate to your project directory. Run the following commands to initialize a new Node.js project and install the necessary dependencies:
# Initialize a new Node.js project
npm init -y
# Install TypeScript and necessary type definitions
npm install typescript @types/node --save-dev
# Install required libraries
npm install natural transliteration
# Initialize TypeScript configuration
npx tsc --init
This will set up a basic TypeScript environment with the necessary packages.
Complete TypeScript Implementation
Below is the complete TypeScript code incorporating actual phonetic conversion for English and Russian.
// Import required modules
import natural from 'natural';
import { transliterate } from 'transliteration';
/**
* Converts a word to its phonetic representation.
*
* @param word The word to convert.
* @param language The language of the word ('en' for English, 'ru' for Russian).
* @returns The phonetic representation of the word.
*/
function toPhonetic(word: string, language: 'en' | 'ru'): string {
if (language === 'en') {
return englishToPhonetic(word);
} else if (language === 'ru') {
return russianToPhonetic(word);
}
return ""; // Return empty string if language is not supported
}
/**
* Converts an English word to its Metaphone representation.
*
* @param word The English word to convert.
* @returns The Metaphone representation of the word.
*/
function englishToPhonetic(word: string): string {
const metaphone = natural.Metaphone;
return metaphone.process(word);
}
/**
* Converts a Russian word to its transliterated representation.
*
* @param word The Russian word to convert.
* @returns The transliterated representation of the word.
*/
function russianToPhonetic(word: string): string {
return transliterate(word);
}
/**
* Converts a text to its phonetic representation.
*
* @param text The text to convert.
* @param language The language of the text ('en' for English, 'ru' for Russian).
* @returns An array of phonetic representations for each word.
*/
function textToPhonetic(text: string, language: 'en' | 'ru'): string[] {
const words = text.split(/\s+/).map(word => word.replace(/[.,!?;:]/g, '')); // Remove punctuation
return words.map(word => toPhonetic(word, language));
}
/**
* Calculates the Levenshtein distance between two strings.
*
* @param a The first string.
* @param b The second string.
* @returns The Levenshtein distance between the two strings.
*/
function levenshteinDistance(a: string, b: string): number {
if (a.length === 0) return b.length;
if (b.length === 0) return a.length;
const matrix: number[][] = [];
// Initialize the first row and column of the matrix
for (let i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
for (let j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
// Populate the matrix
for (let i = 1; i <= b.length; i++) {
for (let j = 1; j <= a.length; j++) {
if (b[i - 1].toLowerCase() === a[j - 1].toLowerCase()) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(
matrix[i - 1][j - 1] + 1, // Substitution
matrix[i][j - 1] + 1, // Insertion
matrix[i - 1][j] + 1 // Deletion
);
}
}
}
return matrix[b.length][a.length];
}
/**
* Finds similar sounding patterns in a list of phonetic representations.
*
* @param phonetics An array of phonetic representations.
* @param threshold The similarity threshold for considering patterns as similar.
* @returns An array of arrays, where each inner array contains indices of similar sounding patterns.
*/
function findSimilarPatterns(phonetics: string[], threshold: number): number[][] {
const similarPatterns: number[][] = [];
const visited: boolean[] = Array(phonetics.length).fill(false);
for (let i = 0; i < phonetics.length; i++) {
if (visited[i]) continue;
const matches: number[] = [i];
visited[i] = true;
for (let j = i + 1; j < phonetics.length; j++) {
if (visited[j]) continue;
const distance = levenshteinDistance(phonetics[i], phonetics[j]);
if (distance <= threshold) {
matches.push(j);
visited[j] = true;
}
}
if (matches.length > 1) {
similarPatterns.push(matches);
}
}
return similarPatterns;
}
/**
* Type for a highlighted segment of text.
*/
type HighlightedSegment = {
text: string;
color: string;
};
/**
* Highlights similar sounding parts of the text with colors.
*
* @param text The original text.
* @param similarPatterns An array of arrays, where each inner array contains indices of similar sounding patterns.
* @returns An array of highlighted segments.
*/
function highlightSimilarParts(text: string, similarPatterns: number[][]): HighlightedSegment[] {
const words = text.split(/\s+/).map(word => word.replace(/[.,!?;:]/g, '')); // Remove punctuation
const highlighted: HighlightedSegment[] = [];
const colors = ["red", "blue", "green", "yellow", "orange", "purple", "pink"]; // Example colors
let colorIndex = 0;
const assignedColors: string[] = Array(words.length).fill("");
similarPatterns.forEach(pattern => {
const color = colors[colorIndex % colors.length];
colorIndex++;
pattern.forEach(index => {
// Assign the first available color
if (!assignedColors[index]) {
assignedColors[index] = color;
}
});
});
for (let i = 0; i < words.length; i++) {
highlighted.push({
text: words[i],
color: assignedColors[i] || "black" // Default to black if no color assigned
});
}
return highlighted;
}
/**
* Main function to process the text and highlight similar sounding parts.
*
* @param text The text to process.
* @param language The language of the text ('en' for English, 'ru' for Russian).
* @param similarityThreshold The similarity threshold for considering patterns as similar.
* @returns An array of highlighted segments.
*/
function processText(text: string, language: 'en' | 'ru', similarityThreshold: number): HighlightedSegment[] {
const phonetics = textToPhonetic(text, language);
const similarPatterns = findSimilarPatterns(phonetics, similarityThreshold);
const highlighted = highlightSimilarParts(text, similarPatterns);
return highlighted;
}
/**
* Utility function to display highlighted segments with colors in the terminal.
*
* Note: Terminal color support varies. This uses ANSI escape codes.
*
* @param highlightedSegments Array of highlighted segments.
*/
function displayHighlightedSegments(highlightedSegments: HighlightedSegment[]): void {
const colorCodes: { [key: string]: string } = {
"black": "\x1b[30m",
"red": "\x1b[31m",
"green": "\x1b[32m",
"yellow": "\x1b[33m",
"blue": "\x1b[34m",
"magenta": "\x1b[35m",
"cyan": "\x1b[36m",
"white": "\x1b[37m",
"reset": "\x1b[0m"
};
const resetCode = colorCodes["reset"];
const coloredText = highlightedSegments.map(segment => {
const colorCode = colorCodes[segment.color] || colorCodes["black"];
return `${colorCode}${segment.text}${resetCode}`;
}).join(' ');
console.log(coloredText);
}
// Example Usage
const englishText = "Hear the mellow wedding bells, Golden bells! What a world of happiness their harmony foretells!";
const russianText = "Слышишь нежные свадебные колокольчики, Золотые колокольчики! Какой мир счастья их гармонии предвещает!";
const languageEnglish: 'en' = 'en';
const languageRussian: 'ru' = 'ru';
const similarityThreshold = 2;
console.log("=== English Text Highlighting ===");
const highlightedEnglish = processText(englishText, languageEnglish, similarityThreshold);
displayHighlightedSegments(highlightedEnglish);
console.log("\n=== Russian Text Highlighting ===");
const highlightedRussian = processText(russianText, languageRussian, similarityThreshold);
displayHighlightedSegments(highlightedRussian);
Explanation of Enhancements
-
Phonetic Conversion:
- English (
englishToPhonetic): Utilizes the Metaphone algorithm from the natural library to convert English words into their phonetic representations.
- Russian (
russianToPhonetic): Uses the transliteration library to convert Cyrillic characters to Latin script. While this isn't a true phonetic representation, it offers a reasonable approximation for matching purposes.
-
Improved levenshteinDistance:
- Converts both strings to lowercase to ensure case-insensitive comparison.
-
Enhanced findSimilarPatterns:
- Introduces a
visited array to avoid reprocessing words that have already been grouped into a pattern.
- Groups words into similar patterns based on the Levenshtein distance threshold.
-
Robust highlightSimilarParts:
- Removes punctuation from words to ensure accurate indexing.
- Assigns colors systematically to avoid overlapping or conflicting color assignments.
-
Utility Function displayHighlightedSegments:
- Adds a function to display highlighted segments in the terminal using ANSI escape codes. This provides a visual representation of the highlighted words when running the script in a terminal that supports colors.
Transpiling and Running the Code
-
Ensure TypeScript Configuration:
Your tsconfig.json should have at least the following settings (adjust as needed):
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./",
"strict": true,
"esModuleInterop": true
}
}
-
Save the Code:
Save the TypeScript code in a file, e.g., phoneticHighlighter.ts.
-
Compile the TypeScript Code:
npx tsc
This will compile the .ts file into JavaScript and place it in the ./dist directory.
-
Run the Compiled Code:
node dist/phoneticHighlighter.js
You should see the highlighted English and Russian texts in the terminal with colored words indicating similar-sounding patterns.
Example Output
When you run the script, the terminal will display the original texts with certain words highlighted in different colors based on phonetic similarity.
=== English Text Highlighting ===
Hear the mellow wedding bells, Golden bells! What a world of happiness their harmony foretells!
=== Russian Text Highlighting ===
Слышишь нежные свадебные колокольчики, Золотые колокольчики! Какой мир счастья их гармонии предвещает!
Note: The actual colored output will appear in the terminal, but it's not visually represented here.
Further Enhancements
-
Advanced Russian Phonetic Conversion:
- For more accurate Russian phonetic representations, consider implementing or integrating a specialized phonetic algorithm tailored for Russian. This could involve handling soft and hard consonants, vowel reductions, and other language-specific pronunciation rules.
-
Web Integration:
- If you intend to use this functionality in a web application, modify the
HighlightedSegment type to include HTML markup with CSS classes or inline styles instead of terminal color codes.
-
Performance Optimization:
- For large texts, optimize the
levenshteinDistance function or consider using more efficient string similarity algorithms.
-
Dynamic Color Assignment:
- Enhance the color assignment logic to handle more patterns and avoid color repetition when the number of similar patterns exceeds the predefined color list.
-
User Interface:
- Develop a user-friendly interface where users can input text, select the language, adjust the similarity threshold, and view the highlighted results interactively.
Conclusion
This complete TypeScript implementation provides a solid foundation for phonetic text processing in both English and Russian. By leveraging existing libraries and implementing core functionalities, it effectively identifies and highlights similar-sounding words within a given text. Depending on your specific requirements, you can further refine and extend this implementation to suit various applications.
If you encounter any issues or need further assistance with specific parts of the code, feel free to ask!