This is a great request for implementing a language detection system using n-gram frequency profiling. Let me create a comprehensive implementation that:
- Creates n-gram frequency profiles from Wikipedia dumps
- Implements cosine similarity calculation
- Detects language of new sentences
- Includes training and testing functionality
I'll create a complete solution with:
- N-gram extraction
- Frequency profiling
- Cosine similarity
- Language detection
- Model persistence
- Evaluation metrics
Let me write a production-quality implementation.
Language Detection Using N-gram Frequency Profiling
Here's a complete implementation with training, evaluation, and visualization:
import numpy as np
from collections import defaultdict, Counter
from typing import Dict, List, Tuple, Set
import json
import os
from pathlib import Path
import pickle
import math
from dataclasses import dataclass
from enum import Enum
import matplotlib.pyplot as plt
import seaborn as sns
from urllib.request import urlopen
import gzip
import io
# ============================================================================
# Data Structures and Enums
# ============================================================================
class LanguageProfile(Enum):
"""Available language profiles"""
ENGLISH = "English"
SPANISH = "Spanish"
FRENCH = "French"
GERMAN = "German"
ITALIAN = "Italian"
@dataclass
class DetectionResult:
"""Result of language detection"""
detected_language: str
confidence: float
scores: Dict[str, float]
n_gram_vector: Dict[str, float]
def __str__(self) -> str:
return (
f"Language: {self.detected_language} "
f"(Confidence: {self.confidence:.2%})\n"
f"Scores: {', '.join(f'{lang}: {score:.4f}' for lang, score in sorted(self.scores.items(), key=lambda x: x[1], reverse=True))}"
)
# ============================================================================
# N-gram Profile Builder
# ============================================================================
class NGramProfiler:
"""Build and manage n-gram frequency profiles for languages"""
def __init__(self, n: int = 3, top_k: int = 300):
"""
Args:
n: Size of n-grams (typically 2-4)
top_k: Number of most frequent n-grams to keep
"""
self.n = n
self.top_k = top_k
self.profiles: Dict[str, Dict[str, float]] = {}
self.n_gram_counts: Dict[str, Counter] = {}
def _extract_ngrams(self, text: str) -> List[str]:
"""Extract n-grams from text"""
# Normalize text
text = text.lower()
text = ''.join(c if c.isalpha() or c.isspace() else '' for c in text)
ngrams = []
for word in text.split():
# Add word boundaries
padded_word = f"_{word}_"
for i in range(len(padded_word) - self.n + 1):
ngrams.append(padded_word[i:i + self.n])
return ngrams
def _normalize_profile(self, ngram_counts: Counter) -> Dict[str, float]:
"""Convert n-gram counts to normalized frequency profile"""
if not ngram_counts:
return {}
# Get top k n-grams
total = sum(ngram_counts.values())
top_ngrams = dict(ngram_counts.most_common(self.top_k))
# Normalize by total occurrences
profile = {
ngram: count / total
for ngram, count in top_ngrams.items()
}
return profile
def train_from_text(self, language: str, text: str) -> Dict[str, float]:
"""Train profile from raw text"""
ngrams = self._extract_ngrams(text)
self.n_gram_counts[language] = Counter(ngrams)
self.profiles[language] = self._normalize_profile(self.n_gram_counts[language])
return self.profiles[language]
def add_to_training(self, language: str, text: str) -> None:
"""Add more text to existing training"""
ngrams = self._extract_ngrams(text)
if language not in self.n_gram_counts:
self.n_gram_counts[language] = Counter(ngrams)
else:
self.n_gram_counts[language].update(ngrams)
self.profiles[language] = self._normalize_profile(
self.n_gram_counts[language]
)
def get_profile(self, language: str) -> Dict[str, float]:
"""Get normalized profile for a language"""
return self.profiles.get(language, {})
def save_profiles(self, filepath: str) -> None:
"""Save profiles to disk"""
Path(filepath).parent.mkdir(parents=True, exist_ok=True)
with open(filepath, 'wb') as f:
pickle.dump({
'profiles': self.profiles,
'n_gram_counts': self.n_gram_counts,
'n': self.n,
'top_k': self.top_k
}, f)
print(f"Profiles saved to {filepath}")
def load_profiles(self, filepath: str) -> None:
"""Load profiles from disk"""
with open(filepath, 'rb') as f:
data = pickle.load(f)
self.profiles = data['profiles']
self.n_gram_counts = data['n_gram_counts']
self.n = data['n']
self.top_k = data['top_k']
print(f"Profiles loaded from {filepath}")
def get_statistics(self) -> Dict[str, Dict]:
"""Get statistics about profiles"""
stats = {}
for language, profile in self.profiles.items():
stats[language] = {
'n_grams': len(profile),
'total_count': sum(self.n_gram_counts[language].values()),
'unique_n_grams': len(self.n_gram_counts[language]),
'avg_frequency': np.mean(list(profile.values())),
'max_frequency': max(profile.values()) if profile else 0
}
return stats
# ============================================================================
# Language Detector
# ============================================================================
class LanguageDetector:
"""Detect language using cosine similarity"""
def __init__(self, profiler: NGramProfiler):
self.profiler = profiler
self.n = profiler.n
def _get_text_vector(self, text: str) -> Dict[str, float]:
"""Convert text to n-gram frequency vector"""
ngrams = self.profiler._extract_ngrams(text)
ngram_counts = Counter(ngrams)
if not ngram_counts:
return {}
total = sum(ngram_counts.values())
vector = {
ngram: count / total
for ngram, count in ngram_counts.items()
}
return vector
@staticmethod
def cosine_similarity(vec1: Dict[str, float], vec2: Dict[str, float]) -> float:
"""Calculate cosine similarity between two vectors"""
if not vec1 or not vec2:
return 0.0
# Get common keys
common_keys = set(vec1.keys()) & set(vec2.keys())
if not common_keys:
return 0.0
# Calculate dot product
dot_product = sum(vec1[key] * vec2[key] for key in common_keys)
# Calculate magnitudes
magnitude1 = math.sqrt(sum(v**2 for v in vec1.values()))
magnitude2 = math.sqrt(sum(v**2 for v in vec2.values()))
if magnitude1 == 0 or magnitude2 == 0:
return 0.0
return dot_product / (magnitude1 * magnitude2)
def detect(self, text: str) -> DetectionResult:
"""Detect language of text"""
text_vector = self._get_text_vector(text)
scores = {}
for language, profile in self.profiler.profiles.items():
similarity = self.cosine_similarity(text_vector, profile)
scores[language] = similarity
if not scores:
return DetectionResult(
detected_language="Unknown",
confidence=0.0,
scores=scores,
n_gram_vector=text_vector
)
detected_language = max(scores, key=scores.get)
max_score = scores[detected_language]
# Calculate confidence as proportion of top score
total_score = sum(scores.values())
confidence = max_score / total_score if total_score > 0 else 0.0
return DetectionResult(
detected_language=detected_language,
confidence=confidence,
scores=scores,
n_gram_vector=text_vector
)
def detect_batch(self, texts: List[str]) -> List[DetectionResult]:
"""Detect language for multiple texts"""
return [self.detect(text) for text in texts]
# ============================================================================
# Training Data Manager
# ============================================================================
class TrainingDataManager:
"""Manage training data from various sources"""
# Sample texts for demonstration (in production, use Wikipedia dumps)
SAMPLE_TEXTS = {
LanguageProfile.ENGLISH.value: [
"""The English language is a West Germanic language that was first spoken
in early medieval England. It is named after the Angles, one of the Germanic
tribes that migrated to the area of Great Britain. English is an Indo-European
language and belongs to the West Germanic branch of the Indo-European language family.""",
"""Machine learning is a subset of artificial intelligence that provides
systems the ability to automatically learn and improve from experience without
being explicitly programmed. Machine learning focuses on the development of
computer programs that can access data and use it to learn for themselves.""",
],
LanguageProfile.SPANISH.value: [
"""El idioma español es una lengua romance procedente del latín hablado.
Tiene raíces que se remontan a la época del Imperio Romano y la subsecuente
romanización durante la Edad Media. El español se hablaba en la península
ibérica y se expandió a través del imperio español a Asia, América y África.""",
"""La inteligencia artificial es la rama de la informática que se ocupa de
crear máquinas inteligentes que puedan realizar tareas que típicamente requieren
inteligencia humana. Los sistemas de inteligencia artificial utilizan algoritmos
y modelos matemáticos para procesar datos y tomar decisiones.""",
],
LanguageProfile.FRENCH.value: [
"""La langue française est une langue romane parlée dans plusieurs pays.
Elle descend du latin et s'est développée en France au cours du Moyen Age.
Le français est l'une des langues les plus parlées dans le monde et est
une langue officielle dans de nombreux pays et organisations internationales.""",
"""L'apprentissage automatique est un domaine de l'intelligence artificielle
qui se concentre sur le développement de systèmes informatiques capables
d'apprendre et de s'améliorer à partir de l'expérience sans être explicitement programmés.
C'est une approche puissante pour résoudre des problèmes complexes.""",
],
LanguageProfile.GERMAN.value: [
"""Die deutsche Sprache ist eine westgermanische Sprache, die heute vor allem
in Deutschland, Österreich und der Schweiz gesprochen wird. Sie hat ihre Wurzeln
in den germanischen Stämmen und entwickelte sich während des Mittelalters
zu einer eigenständigen Sprache. Das Deutsche ist eine wichtige Sprache in Europa.""",
"""Maschinelles Lernen ist ein Bereich der künstlichen Intelligenz, der sich
mit der Entwicklung von Computersystemen befasst, die aus Daten lernen können.
Diese Systeme verwenden mathematische Modelle und Algorithmen, um Muster in
Daten zu erkennen und Vorhersagen zu treffen.""",
],
LanguageProfile.ITALIAN.value: [
"""La lingua italiana è una lingua romanza parlata principalmente in Italia.
Deriva dal latino e si è evoluta durante il Medioevo. L'italiano è la lingua
ufficiale dell'Italia e è parlato anche in Svizzera, San Marino e Città del Vaticano.
È una delle lingue europee più importanti con una ricca tradizione culturale.""",
"""L'apprendimento automatico è un campo dell'intelligenza artificiale che
si concentra sullo sviluppo di sistemi informatici in grado di imparare
dall'esperienza. Questi sistemi utilizzano algoritmi e modelli matematici
per analizzare dati e fare previsioni intelligenti.""",
],
}
@staticmethod
def get_sample_texts() -> Dict[str, List[str]]:
"""Get sample training texts"""
return TrainingDataManager.SAMPLE_TEXTS
@staticmethod
def download_wikipedia_sample(language_code: str, num_articles: int = 5) -> List[str]:
"""
Download sample texts from Wikipedia (simplified version)
In production, use proper Wikipedia dump processing
"""
print(f"Note: Downloading from Wikipedia for {language_code} is simplified.")
print("For production, use Wikipedia dump files processed with dedicated tools.")
return []
# ============================================================================
# Model Evaluator
# ============================================================================
class LanguageDetectorEvaluator:
"""Evaluate language detection performance"""
def __init__(self, detector: LanguageDetector):
self.detector = detector
self.results = []
def evaluate(self, test_texts: Dict[str, List[str]]) -> Dict:
"""Evaluate detector on test texts"""
self.results = []
confusion_matrix = defaultdict(lambda: defaultdict(int))
all_predictions = []
all_true_labels = []
for true_language, texts in test_texts.items():
for text in texts:
result = self.detector.detect(text)
predicted_language = result.detected_language
self.results.append({
'true': true_language,
'predicted': predicted_language,
'confidence': result.confidence,
'text': text[:50] + "..."
})
confusion_matrix[true_language][predicted_language] += 1
all_predictions.append(predicted_language)
all_true_labels.append(true_language)
# Calculate metrics
accuracy = self._calculate_accuracy(all_true_labels, all_predictions)
precision = self._calculate_precision(all_true_labels, all_predictions)
recall = self._calculate_recall(all_true_labels, all_predictions)
f1 = self._calculate_f1(precision, recall)
return {
'accuracy': accuracy,
'precision': precision,
'recall': recall,
'f1': f1,
'confusion_matrix': dict(confusion_matrix),
'total_samples': len(self.results),
'results': self.results
}
@staticmethod
def _calculate_accuracy(true_labels: List[str], predictions: List[str]) -> float:
"""Calculate accuracy"""
if not true_labels:
return 0.0
return sum(1 for t, p in zip(true_labels, predictions) if t == p) / len(true_labels)
@staticmethod
def _calculate_precision(true_labels: List[str], predictions: List[str]) -> Dict[str, float]:
"""Calculate precision per language"""
precision = {}
languages = set(true_labels + predictions)
for lang in languages:
tp = sum(1 for t, p in zip(true_labels, predictions) if p == lang and t == lang)
fp = sum(1 for t, p in zip(true_labels, predictions) if p == lang and t != lang)
precision[lang] = tp / (tp + fp) if (tp + fp) > 0 else 0.0
return precision
@staticmethod
def _calculate_recall(true_labels: List[str], predictions: List[str]) -> Dict[str, float]:
"""Calculate recall per language"""
recall = {}
languages = set(true_labels + predictions)
for lang in languages:
tp = sum(1 for t, p in zip(true_labels, predictions) if t == lang and p == lang)
fn = sum(1 for t, p in zip(true_labels, predictions) if t == lang and p != lang)
recall[lang] = tp / (tp + fn) if (tp + fn) > 0 else 0.0
return recall
@staticmethod
def _calculate_f1(precision: Dict[str, float], recall: Dict[str, float]) -> Dict[str, float]:
"""Calculate F1 score"""
f1 = {}
for lang in precision:
p = precision.get(lang, 0)
r = recall.get(lang, 0)
f1[lang] = 2 * (p * r) / (p + r) if (p + r) > 0 else 0.0
return f1
def print_evaluation_report(self, metrics: Dict) -> None:
"""Print evaluation report"""
print("\n" + "="*60)
print("LANGUAGE DETECTION EVALUATION REPORT")
print("="*60)
print(f"\nOverall Accuracy: {metrics['accuracy']:.2%}")
print(f"Total Samples: {metrics['total_samples']}")
print("\nPer-Language Metrics:")
print("-" * 60)
print(f"{'Language':<15} {'Precision':<12} {'Recall':<12} {'F1-Score':<12}")
print("-" * 60)
for lang in sorted(metrics['precision'].keys()):
p = metrics['precision'].get(lang, 0)
r = metrics['recall'].get(lang, 0)
f1 = metrics['f1'].get(lang, 0)
print(f"{lang:<15} {p:<12.2%} {r:<12.2%} {f1:<12.2%}")
print("\nConfusion Matrix:")
print("-" * 60)
languages = sorted(set(sum(metrics['confusion_matrix'].values(), [])))
print(f"{'True \\ Pred':<15}", end="")
for lang in languages:
print(f"{lang:<12}", end="")
print()
print("-" * 60)
for true_lang in languages:
print(f"{true_lang:<15}", end="")
for pred_lang in languages:
count = metrics['confusion_matrix'].get(true_lang, {}).get(pred_lang, 0)
print(f"{count:<12}", end="")
print()
print("="*60 + "\n")
# ============================================================================
# Visualization
# ============================================================================
class LanguageDetectionVisualizer:
"""Visualize language detection results"""
@staticmethod
def plot_confusion_matrix(confusion_matrix: Dict, save_path: str = None) -> None:
"""Plot confusion matrix"""
# Convert to numpy array
languages = sorted(set(
list(confusion_matrix.keys()) +
[k for v in confusion_matrix.values() for k in v.keys()]
))
n = len(languages)
matrix = np.zeros((n, n))
for i, true_lang in enumerate(languages):
for j, pred_lang in enumerate(languages):
matrix[i, j] = confusion_matrix.get(true_lang, {}).get(pred_lang, 0)
plt.figure(figsize=(10, 8))
sns.heatmap(matrix, annot=True, fmt='d', cmap='Blues',
xticklabels=languages, yticklabels=languages,
cbar_kws={'label': 'Count'})
plt.xlabel('Predicted Language')
plt.ylabel('True Language')
plt.title('Language Detection Confusion Matrix')
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Confusion matrix saved to {save_path}")
plt.show()
@staticmethod
def plot_profile_comparison(profiler: NGramProfiler, save_path: str = None) -> None:
"""Plot n-gram frequency distributions"""
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
axes = axes.flatten()
for idx, (language, profile) in enumerate(profiler.profiles.items()):
if idx >= len(axes):
break
# Get top 15 n-grams
top_ngrams = sorted(profile.items(), key=lambda x: x[1], reverse=True)[:15]
ngrams, frequencies = zip(*top_ngrams)
axes[idx].barh(range(len(ngrams)), frequencies, color='steelblue')
axes[idx].set_yticks(range(len(ngrams)))
axes[idx].set_yticklabels(ngrams)
axes[idx].set_xlabel('Frequency')
axes[idx].set_title(f'{language} - Top 15 N-grams')
axes[idx].invert_yaxis()
# Hide unused subplots
for idx in range(len(profiler.profiles), len(axes)):
axes[idx].set_visible(False)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Profile comparison saved to {save_path}")
plt.show()
@staticmethod
def plot_confidence_distribution(results: List[Dict], save_path: str = None) -> None:
"""Plot confidence score distribution"""
confidences = [r['confidence'] for r in results]
plt.figure(figsize=(10, 6))
plt.hist(confidences, bins=20, color='steelblue', edgecolor='black', alpha=0.7)
plt.xlabel('Confidence Score')
plt.ylabel('Frequency')
plt.title('Language Detection Confidence Distribution')
plt.axvline(np.mean(confidences), color='red', linestyle='--', label=f'Mean: {np.mean(confidences):.2f}')
plt.axvline(np.median(confidences), color='green', linestyle='--', label=f'Median: {np.median(confidences):.2f}')
plt.legend()
plt.grid(axis='y', alpha=0.3)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Confidence distribution saved to {save_path}")
plt.show()
@staticmethod
def plot_scores_distribution(eval_results: List[DetectionResult],
save_path: str = None) -> None:
"""Plot score distributions by language"""
scores_by_lang = defaultdict(list)
for result in eval_results:
for lang, score in result['scores'].items():
scores_by_lang[lang].append(score)
fig, ax = plt.subplots(figsize=(12, 6))
positions = range(len(scores_by_lang))
bp = ax.boxplot([scores_by_lang[lang] for lang in sorted(scores_by_lang.keys())],
labels=sorted(scores_by_lang.keys()),
patch_artist=True)
for patch in bp['boxes']:
patch.set_facecolor('lightblue')
ax.set_ylabel('Cosine Similarity Score')
ax.set_title('Score Distribution for Each Language Profile')
ax.grid(axis='y', alpha=0.3)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300, bbox_inches='tight')
print(f"Scores distribution saved to {save_path}")
plt.show()
# ============================================================================
# Main Demo
# ============================================================================
def main():
"""Complete demonstration of language detection system"""
print("\n" + "="*70)
print("LANGUAGE DETECTION USING N-GRAM FREQUENCY PROFILING")
print("="*70)
# ========================================================================
# 1. Initialize and Train
# ========================================================================
print("\n[1] Initializing N-gram Profiler...")
profiler = NGramProfiler(n=3, top_k=300)
print("[2] Loading training data...")
training_data = TrainingDataManager.get_sample_texts()
print("[3] Training language profiles...")
for language, texts in training_data.items():
for i, text in enumerate(texts):
if i == 0:
profiler.train_from_text(language, text)
else:
profiler.add_to_training(language, text)
print(f" ✓ {language}: {len(texts)} training texts")
# Print profile statistics
print("\n[4] Profile Statistics:")
stats = profiler.get_statistics()
for language, stat in stats.items():
print(f"\n {language}:")
print(f" N-grams in profile: {stat['n_grams']}")
print(f" Total occurrences: {stat['total_count']}")
print(f" Average frequency: {stat['avg_frequency']:.6f}")
print(f" Max frequency: {stat['max_frequency']:.6f}")
# ========================================================================
# 2. Initialize Detector
# ========================================================================
print("\n[5] Initializing Language Detector...")
detector = LanguageDetector(profiler)
print(" ✓ Detector ready")
# ========================================================================
# 3. Test Detection on Sample Sentences
# ========================================================================
print("\n" + "="*70)
print("LANGUAGE DETECTION DEMONSTRATIONS")
print("="*70)
test_sentences = {
LanguageProfile.ENGLISH.value: [
"The quick brown fox jumps over the lazy dog.",
"Python is a powerful programming language.",
"Artificial intelligence is transforming the world."
],
LanguageProfile.SPANISH.value: [
"El gato negro salta sobre la valla.",
"La inteligencia artificial es muy importante.",
"Mexico es un país muy hermoso."
],
LanguageProfile.FRENCH.value: [
"Le chat noir saute par-dessus la clôture.",
"La technologie change notre vie quotidienne.",
"Paris est la capitale de la France."
],
LanguageProfile.GERMAN.value: [
"Die schwarze Katze springt über den Zaun.",
"Deutschland ist ein schönes Land.",
"Technologie verändert unsere Welt."
],
LanguageProfile.ITALIAN.value: [
"Il gatto nero salta oltre la recinzione.",
"Roma è la capitale dell'Italia.",
"L'Italia ha una ricca storia culturale."
]
}
all_test_results = []
for language, sentences in test_sentences.items():
print(f"\n{language}:")
print("-" * 70)
for sentence in sentences:
result = detector.detect(sentence)
all_test_results.append({
'true': language,
'detected': result.detected_language,
'scores': result.scores,
'confidence': result.confidence
})
print(f"\nText: {sentence}")
print(f"Detection: {result.detected_language}")
print(f"Confidence: {result.confidence:.2%}")
print(f"Scores: {', '.join(f'{lang}: {score:.4f}' for lang, score in sorted(result.scores.items(), key=lambda x: x[1], reverse=True))}")
# ========================================================================
# 4. Evaluation
# ========================================================================
print("\n" + "="*70)
print("EVALUATION")
print("="*70)
evaluator = LanguageDetectorEvaluator(detector)
metrics = evaluator.evaluate(test_sentences)
evaluator.print_evaluation_report(metrics)
# ========================================================================
# 5. Extended Tests with Mixed Content
# ========================================================================
print("\n" + "="*70)
print("CHALLENGING TEST CASES")
print("="*70)
challenging_texts = [
("Code snippet", "def hello_world(): print('Hello, World!')"),
("Numbers and symbols", "123 456 789 !@#$%^&*()"),
("Mixed English-Spanish", "Hello amigo, como estás today?"),
("Short text", "Bonjour"),
("Email address", "user@example.com"),
("Long English text",
"Machine learning is a subset of artificial intelligence that enables systems to learn "
"and improve from experience without being explicitly programmed. It focuses on developing "
"computer programs that can access data and learn from it automatically."),
]
for test_type, text in challenging_texts:
result = detector.detect(text)
print(f"\n[{test_type}]")
print(f"Text: {text[:60]}{'...' if len(text) > 60 else ''}")
print(f"Detection: {result.detected_language} (Confidence: {result.confidence:.2%})")
# ========================================================================
# 6. Batch Processing
# ========================================================================
print("\n" + "="*70)
print("BATCH PROCESSING")
print("="*70)
batch_texts = [
"The weather is beautiful today.",
"Hace mucho calor hoy en Madrid.",
"Il pleut beaucoup à Paris.",
"Es regnet in Berlin.",
"Piove a Roma."
]
print(f"\nProcessing {len(batch_texts)} texts...")
batch_results = detector.detect_batch(batch_texts)
for i, (text, result) in enumerate(zip(batch_texts, batch_results), 1):
print(f"\n{i}. {text}")
print(f" → {result.detected_language} ({result.confidence:.2%})")
# ========================================================================
# 7. N-gram Analysis
# ========================================================================
print("\n" + "="*70)
print("N-GRAM ANALYSIS")
print("="*70)
analysis_text = "The quick brown fox"
print(f"\nAnalyzing: '{analysis_text}'")
ngrams = profiler._extract_ngrams(analysis_text)
print(f"Extracted n-grams (n=3): {ngrams}")
# Show overlaps with profiles
text_vector = detector._get_text_vector(analysis_text)
print(f"\nN-gram vector ({len(text_vector)} unique n-grams):")
for ngram, freq in sorted(text_vector.items(), key=lambda x: x[1], reverse=True):
print(f" '{ngram}': {freq:.4f}")
# ========================================================================
# 8. Save Models
# ========================================================================
print("\n" + "="*70)
print("MODEL PERSISTENCE")
print("="*70)
model_path = "language_profiles.pkl"
profiler.save_profiles(model_path)
# Demonstrate loading
new_profiler = NGramProfiler(n=3, top_k=300)
new_profiler.load_profiles(model_path)
new_detector = LanguageDetector(new_profiler)
test_text = "Hello, how are you today?"
result_original = detector.detect(test_text)
result_loaded = new_detector.detect(test_text)
print(f"\nVerification test:")
print(f"Original detector: {result_original.detected_language}")
print(f"Loaded detector: {result_loaded.detected_language}")
print(f"Results match: {result_original.detected_language == result_loaded.detected_language}")
# ========================================================================
# 9. Visualizations
# ========================================================================
print("\n" + "="*70)
print("GENERATING VISUALIZATIONS")
print("="*70)
visualizer = LanguageDetectionVisualizer()
print("\n[1] Generating confusion matrix...")
visualizer.plot_confusion_matrix(metrics['confusion_matrix'],
save_path='confusion_matrix.png')
print("[2] Generating profile comparison...")
visualizer.plot_profile_comparison(profiler,
save_path='profile_comparison.png')
print("[3] Generating confidence distribution...")
visualizer.plot_confidence_distribution(metrics['results'],
save_path='confidence_dist.png')
print("[4] Generating scores distribution...")
visualizer.plot_scores_distribution(all_test_results,
save_path='scores_dist.png')
# ========================================================================
# 10. Summary
# ========================================================================
print("\n" + "="*70)
print("SUMMARY")
print("="*70)
print(f"\n✓ System trained on {len(training_data)} languages")
print(f"✓ Each profile contains top {profiler.top_k} n-grams")
print(f"✓ N-gram size: {profiler.n}")
print(f"✓ Total test sentences: {metrics['total_samples']}")
print(f"✓ Overall accuracy: {metrics['accuracy']:.2%}")
print(f"✓ Models saved to: {model_path}")
print(f"✓ Visualizations generated")
print("\n" + "="*70 + "\n")
# ============================================================================
# Advanced Usage Examples
# ============================================================================
def advanced_examples():
"""Advanced usage examples"""
print("\n" + "="*70)
print("ADVANCED USAGE EXAMPLES")
print("="*70)
# Example 1: Custom n-gram size
print("\n[Example 1] Different n-gram sizes")
for n in [2, 3, 4]:
profiler = NGramProfiler(n=n, top_k=200)
text = "Hello world"
ngrams = profiler._extract_ngrams(text)
print(f"n={n}: {ngrams}")
# Example 2: Fine-tuning confidence threshold
print("\n[Example 2] Confidence-based filtering")
profiler = NGramProfiler(n=3, top_k=300)
detector = LanguageDetector(profiler)
for language, texts in TrainingDataManager.get_sample_texts().items():
for text in texts:
profiler.train_from_text(language, text)
low_confidence_text = "123 456" # Likely to have low confidence
result = detector.detect(low_confidence_text)
if result.confidence < 0.5:
print(f"Low confidence detection: {result.confidence:.2%}")
print(f"Recommendation: Require more text or mark as uncertain")
# Example 3: Language similarity analysis
print("\n[Example 3] Language similarity matrix")
# Create a similarity matrix between language profiles
profiler = NGramProfiler(n=3, top_k=300)
training_data = TrainingDataManager.get_sample_texts()
for language, texts in training_data.items():
for text in texts:
profiler.train_from_text(language, text)
detector = LanguageDetector(profiler)
languages = list(profiler.profiles.keys())
print("\nLanguage Similarity Matrix:")
print("-" * 50)
print(f"{'Lang':<12}", end="")
for lang in languages:
print(f"{lang:<12}", end="")
print()
print("-" * 50)
for lang1 in languages:
print(f"{lang1:<12}", end="")
for lang2 in languages:
profile1 = profiler.profiles[lang1]
profile2 = profiler.profiles[lang2]
sim = detector.cosine_similarity(profile1, profile2)
print(f"{sim:<12.4f}", end="")
print()
if __name__ == "__main__":
main()
advanced_examples()
This comprehensive implementation includes:
Key Features:
-
N-gram Extraction
- Configurable n-gram size (typically 2-4)
- Word boundary markers (_)
- Text normalization
-
Profile Building
- Frequency-based profiles
- Top-K n-gram selection
- Profile persistence (save/load)
-
Language Detection
- Cosine similarity calculation
- Confidence scoring
- Batch processing
-
Evaluation Metrics
- Accuracy, Precision, Recall, F1
- Confusion matrix
- Per-language statistics
-
Visualizations
- Confusion matrix heatmap
- N-gram frequency distributions
- Confidence distributions
- Score box plots
-
Advanced Features
- Sample handling of mixed languages
- Short text detection
- Model persistence
- Batch operations
Usage:
python solution.py
The system trains on 5 languages, evaluates performance, and provides comprehensive visualizations and metrics!