Implement language detection using character n-gram frequency profiling. Train profiles on Wikipedia dumps for 5 languages and detect new sentences by calculating cosine similarity between their n-gram vectors and language profiles.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The plan details implementing a Python solution that trains character n-gram frequency profiles for five languages using Wikipedia page content fetched via the wikipedia library, then detects languages of new sentences by cosine similarity of these profiles. The code will include training, profile normalization, similarity calculation, and demonstration with example inputs.
Below is a self‑contained Python example that builds character n‑gram frequency profiles for five languages using Wikipedia text, and then detects the language of new sentences by computing cosine similarity between their n‑gram vectors and the precomputed profiles.
python
# pip install wikipedia # if not already installed
import math
import re
from collections import Counter, defaultdict
import wikipedia
class NGramLanguageProfiler:
def __init__(self, n=3):
self.n = n
self.profiles = {} # language_code -> {ngram: frequency}
@staticmethod
def _normalize_text(text):
# Lowercase and strip out non-letter/space characters for simplicity
return re.sub(r'[^a-záàâäãåæçéèêëíìîïñóòôöõúùûüýÿœæßğčšžćđłńąćęłńśżź ]+', ' ',
text.lower())
def _extract_ngrams(self, text):
"""
Given a piece of text, return a Counter of character n-grams.
Uses spaces too; you can tweak normalization as needed.
"""
text = self._normalize_text(text)
ngrams = Counter()
# Pad with start/end markers if desired; here we don't pad
for i in range(len(text) - self.n + 1):
ng = text[i:i+self.n]
ngrams[ng] += 1
return ngrams
def _counter_to_freqs(self, counter):
"""
Convert a Counter of n-gram counts to normalized frequencies.
"""
total = sum(counter.values())
if total == 0:
return {}
return {ng: count / total for ng, count in counter.items()}
def build_profile_for_language(self, lang_code, pages=None, max_chars=100000):
"""
Fetch text from one or more Wikipedia pages in the given language
and build a normalized n-gram frequency profile.
"""
wikipedia.set_lang(lang_code)
if pages is None:
# Some default pages per language; you can choose any topics.
pages = ['Wikipedia', 'Language', 'Mathematics', 'Science', 'History']
aggregated_text = ""
for title in pages:
try:
page = wikipedia.page(title)
aggregated_text += page.content + " "
if len(aggregated_text) >= max_chars:
break
except Exception as e:
# If the page isn't found in this language, skip it
print(f"[{lang_code}] Could not fetch page '{title}': {e}")
continue
# Trim to max_chars to keep things lightweight
aggregated_text = aggregated_text[:max_chars]
counts = self._extract_ngrams(aggregated_text)
freqs = self._counter_to_freqs(counts)
self.profiles[lang_code] = freqs
print(f"Built profile for '{lang_code}' with {len(freqs)} unique n-grams.")
def train(self, languages):
"""
Build profiles for all specified languages.
'languages' should be a dict: lang_code -> list_of_page_titles_or_None
"""
for lang_code, pages in languages.items():
self.build_profile_for_language(lang_code, pages)
@staticmethod
def cosine_similarity(profile_a, profile_b):
"""
Compute cosine similarity between two sparse frequency vectors (dicts).
"""
# Intersection of n-grams present in both
common = set(profile_a.keys()) & set(profile_b.keys())
dot_product = sum(profile_a[ng] * profile_b[ng] for ng in common)
norm_a = math.sqrt(sum(v * v for v in profile_a.values()))
norm_b = math.sqrt(sum(v * v for v in profile_b.values()))
if norm_a == 0 or norm_b == 0:
return 0.0
return dot_product / (norm_a * norm_b)
def detect_language(self, text):
"""
Given input text, compute its n-gram profile and find the best matching
language by cosine similarity.
"""
text_counts = self._extract_ngrams(text)
text_freqs = self._counter_to_freqs(text_counts)
best_lang = None
best_score = -1.0
for lang, profile in self.profiles.items():
score = self.cosine_similarity(text_freqs, profile)
if score > best_score:
best_score = score
best_lang = lang
return best_lang, best_score
if __name__ == "__main__":
# Define which languages to train on and (optionally) which pages to use
# Language codes are ISO 639-1: en=English, es=Spanish, fr=French, de=German, it=Italian
languages_to_train = {
'en': ['Mathematics', 'Science', 'Language', 'History'],
'es': ['Matemáticas', 'Ciencia', 'Idioma', 'Historia'],
'fr': ['Mathématiques', 'Science', 'Langue', 'Histoire'],
'de': ['Mathematik', 'Wissenschaft', 'Sprache', 'Geschichte'],
'it': ['Matematica', 'Scienza', 'Lingua', 'Storia'],
}
detector = NGramLanguageProfiler(n=3)
detector.train(languages_to_train)
# Test sentences
samples = [
"This is an English sentence about science and history.",
"Este es un texto en español sobre matemáticas y ciencia.",
"Ceci est une phrase française parlant de mathématiques et d'histoire.",
"Das ist ein deutscher Beispielsatz über Wissenschaft.",
"Questa è una frase italiana riguardante la scienza e la matematica."
]
for s in samples:
lang, score = detector.detect_language(s)
print(f"Input: {s}")
print(f"Detected language: {lang} (similarity {score:.3f})")
print("-" * 60)
How it works
The NGramLanguageProfiler builds character n‑gram (default n = 3) frequency profiles for each language from Wikipedia content. You can control which pages and how much text to fetch via parameters.
Text is lowercased and stripped of non‑letter characters; you can adjust _normalize_text to include punctuation or other characters if desired.
Frequencies are normalized to form a vector, and cosine similarity is used to compare the input text’s vector with each language profile.
The detect_language method returns the language code with the highest cosine similarity.
Note: Fetching Wikipedia pages requires internet access, and the quality of the profiles improves with more text/pages. For production use, you would typically parse full Wikipedia dumps; the above demonstrates the same technique on smaller samples.