3 * Part of Text_LanguageDetect
8 * @package Text_LanguageDetect
9 * @author Nicholas Pisarro <infinityminusnine+pear@gmail.com>
10 * @copyright 2005-2006 Nicholas Pisarro
11 * @license BSD http://www.opensource.org/licenses/bsd-license.php
12 * @link http://pear.php.net/package/Text_LanguageDetect/
15 require_once 'Text/LanguageDetect/Exception.php';
16 require_once 'Text/LanguageDetect/Parser.php';
17 require_once 'Text/LanguageDetect/ISO639.php';
20 * Detects the language of a given piece of text.
22 * Attempts to detect the language of a sample of text by correlating ranked
23 * 3-gram frequencies to a table of 3-gram frequencies of known languages.
25 * Implements a version of a technique originally proposed by Cavnar & Trenkle
26 * (1994): "N-Gram-Based Text Categorization"
28 * Requires the language model database (lang.dat) that should have
29 * accompanied this class definition in order to be instantiated.
34 * require_once 'Text/LanguageDetect.php';
36 * $l = new Text_LanguageDetect;
38 * $stdin = fopen('php://stdin', 'r');
40 * echo "Supported languages:\n";
43 * $langs = $l->getLanguages();
44 * } catch (Text_LanguageDetect_Exception $e) {
45 * die($e->getMessage());
49 * echo join(', ', $langs);
51 * while ($line = fgets($stdin)) {
52 * print_r($l->detect($line, 4));
57 * @package Text_LanguageDetect
58 * @author Nicholas Pisarro <infinityminusnine+pear@gmail.com>
59 * @copyright 2005 Nicholas Pisarro
60 * @license BSD http://www.opensource.org/licenses/bsd-license.php
61 * @version Release: @package_version@
62 * @link http://pear.php.net/package/Text_LanguageDetect/
64 class Text_LanguageDetect
67 * The filename that stores the trigram data for the detector
69 * If this value starts with a slash (/) or a dot (.) the value of
70 * $this->_data_dir will be ignored
74 protected $_db_filename = 'lang.dat';
77 * The filename that stores the unicode block definitions
79 * If this value starts with a slash (/) or a dot (.) the value of
80 * $this->_data_dir will be ignored
84 protected $_unicode_db_filename = 'unicode_blocks.dat';
89 * Should be set by PEAR installer
93 protected $_data_dir = '@data_dir@';
96 * The trigram data for comparison
98 * Will be loaded on start from $this->_db_filename
102 protected $_lang_db = array();
105 * Stores the map of the trigram data to unicode characters
109 protected $_unicode_map;
112 * The size of the trigram data arrays
116 protected $_threshold = 300;
119 * The maximum possible score.
121 * Needed for score normalization. Different depending on the
122 * perl compatibility setting
125 * @see setPerlCompatible()
127 protected $_max_score = 0;
130 * Whether or not to simulate perl's Language::Guess exactly
133 * @see setPerlCompatible()
135 protected $_perl_compatible = false;
138 * Whether to use the unicode block detection to speed up processing
142 protected $_use_unicode_narrowing = true;
145 * Stores the result of the clustering operation
148 * @see clusterLanguages()
150 protected $_clusters;
153 * Which type of "language names" are accepted and returned:
155 * 0 - language name ("english")
156 * 2 - 2-letter ISO 639-1 code ("en")
157 * 3 - 3-letter ISO 639-2 code ("eng")
159 protected $_name_mode = 0;
164 * Will attempt to load the language database. If it fails, you will get
167 public function __construct()
169 $data = $this->_readdb($this->_db_filename);
170 $this->_checkTrigram($data['trigram']);
171 $this->_lang_db = $data['trigram'];
173 if (isset($data['trigram-unicodemap'])) {
174 $this->_unicode_map = $data['trigram-unicodemap'];
177 // Not yet implemented:
178 if (isset($data['trigram-clusters'])) {
179 $this->_clusters = $data['trigram-clusters'];
184 * Returns the path to the location of the database
186 * @param string $fname File name to load
188 * @return string expected path to the language model database
190 protected function _get_data_loc($fname)
192 if ($fname{0} == '/' || $fname{0} == '.') {
193 // if filename starts with a slash, assume it's an absolute pathname
194 // and skip whatever is in $this->_data_dir
197 } elseif ($this->_data_dir != '@' . 'data_dir' . '@') {
198 // if the data dir was set by the PEAR installer, use that
199 return $this->_data_dir . '/Text_LanguageDetect/' . $fname;
202 // assume this was just unpacked somewhere
203 // try the local working directory if otherwise
204 return __DIR__ . '/../data/' . $fname;
209 * Loads the language trigram database from filename
211 * Trigram datbase should be a serialize()'d array
213 * @param string $fname the filename where the data is stored
215 * @return array the language model data
216 * @throws Text_LanguageDetect_Exception
218 protected function _readdb($fname)
220 // finds the correct data dir
221 $fname = $this->_get_data_loc($fname);
224 if (!file_exists($fname)) {
225 throw new Text_LanguageDetect_Exception(
226 'Language database does not exist: ' . $fname,
227 Text_LanguageDetect_Exception::DB_NOT_FOUND
229 } elseif (!is_readable($fname)) {
230 throw new Text_LanguageDetect_Exception(
231 'Language database is not readable: ' . $fname,
232 Text_LanguageDetect_Exception::DB_NOT_READABLE
236 return unserialize(file_get_contents($fname));
241 * Checks if this object is ready to detect languages
243 * @param array $trigram Trigram data from database
247 protected function _checkTrigram($trigram)
249 if (!is_array($trigram)) {
250 if (ini_get('magic_quotes_runtime')) {
251 throw new Text_LanguageDetect_Exception(
252 'Error loading database. Try turning magic_quotes_runtime off.',
253 Text_LanguageDetect_Exception::MAGIC_QUOTES
256 throw new Text_LanguageDetect_Exception(
257 'Language database is not an array.',
258 Text_LanguageDetect_Exception::DB_NOT_ARRAY
260 } elseif (empty($trigram)) {
261 throw new Text_LanguageDetect_Exception(
262 'Language database has no elements.',
263 Text_LanguageDetect_Exception::DB_EMPTY
271 * Pass this function the name of or an array of names of
272 * languages that you don't want considered
274 * If you're only expecting a limited set of languages, this can greatly
275 * speed up processing
277 * @param mixed $omit_list language name or array of names to omit
278 * @param bool $include_only if true will include (rather than
279 * exclude) only those in the list
281 * @return int number of languages successfully deleted
282 * @throws Text_LanguageDetect_Exception
284 public function omitLanguages($omit_list, $include_only = false)
288 $omit_list = $this->_convertFromNameMode($omit_list);
290 if (!$include_only) {
291 // deleting the given languages
292 if (!is_array($omit_list)) {
293 $omit_list = strtolower($omit_list); // case desensitize
294 if (isset($this->_lang_db[$omit_list])) {
295 unset($this->_lang_db[$omit_list]);
299 foreach ($omit_list as $omit_lang) {
300 if (isset($this->_lang_db[$omit_lang])) {
301 unset($this->_lang_db[$omit_lang]);
308 // deleting all except the given languages
309 if (!is_array($omit_list)) {
310 $omit_list = array($omit_list);
314 foreach ($omit_list as $key => $omit_lang) {
315 $omit_list[$key] = strtolower($omit_lang);
318 foreach (array_keys($this->_lang_db) as $lang) {
319 if (!in_array($lang, $omit_list)) {
320 unset($this->_lang_db[$lang]);
326 // reset the cluster cache if the number of languages changes
327 // this will then have to be recalculated
328 if (isset($this->_clusters) && $deleted > 0) {
329 $this->_clusters = null;
337 * Returns the number of languages that this object can detect
339 * @return int the number of languages
340 * @throws Text_LanguageDetect_Exception
342 public function getLanguageCount()
344 return count($this->_lang_db);
348 * Checks if the language with the given name exists in the database
350 * @param mixed $lang Language name or array of language names
352 * @return bool true if language model exists
354 public function languageExists($lang)
356 $lang = $this->_convertFromNameMode($lang);
358 if (is_string($lang)) {
359 return isset($this->_lang_db[strtolower($lang)]);
361 } elseif (is_array($lang)) {
362 foreach ($lang as $test_lang) {
363 if (!isset($this->_lang_db[strtolower($test_lang)])) {
370 throw new Text_LanguageDetect_Exception(
371 'Unsupported parameter type passed to languageExists()',
372 Text_LanguageDetect_Exception::PARAM_TYPE
378 * Returns the list of detectable languages
380 * @return array the names of the languages known to this object<<<<<<<
381 * @throws Text_LanguageDetect_Exception
383 public function getLanguages()
385 return $this->_convertToNameMode(
386 array_keys($this->_lang_db)
391 * Make this object behave like Language::Guess
393 * @param bool $setting false to turn off perl compatibility
397 public function setPerlCompatible($setting = true)
399 if (is_bool($setting)) { // input check
400 $this->_perl_compatible = $setting;
402 if ($setting == true) {
403 $this->_max_score = $this->_threshold;
405 $this->_max_score = 0;
412 * Sets the way how language names are accepted and returned.
414 * @param integer $name_mode One of the following modes:
415 * 0 - language name ("english")
416 * 2 - 2-letter ISO 639-1 code ("en")
417 * 3 - 3-letter ISO 639-2 code ("eng")
421 public function setNameMode($name_mode)
423 $this->_name_mode = $name_mode;
427 * Whether to use unicode block ranges in detection
429 * Should speed up most detections if turned on (detault is on). In some
430 * circumstances it may be slower, such as for large text samples (> 10K)
431 * in languages that use latin scripts. In other cases it should speed up
432 * detection noticeably.
434 * @param bool $setting false to turn off
438 public function useUnicodeBlocks($setting = true)
440 if (is_bool($setting)) {
441 $this->_use_unicode_narrowing = $setting;
446 * Converts a piece of text into trigrams
448 * @param string $text text to convert
450 * @return array array of trigram frequencies
451 * @deprecated Superceded by the Text_LanguageDetect_Parser class
453 protected function _trigram($text)
455 $s = new Text_LanguageDetect_Parser($text);
456 $s->prepareTrigram();
457 $s->prepareUnicode(false);
458 $s->setPadStart(!$this->_perl_compatible);
460 return $s->getTrigramFreqs();
464 * Converts a set of trigrams from frequencies to ranks
466 * Thresholds (cuts off) the list at $this->_threshold
468 * @param array $arr array of trigram
470 * @return array ranks of trigrams
472 protected function _arr_rank($arr)
475 // sorts alphabetically first as a standard way of breaking rank ties
476 $this->_bub_sort($arr);
478 // below might also work, but seemed to introduce errors in testing
485 foreach ($arr as $key => $value) {
488 // cut off at a standard threshold
489 if ($i >= $this->_threshold) {
498 * Sorts an array by value breaking ties alphabetically
500 * @param array $arr the array to sort
504 protected function _bub_sort(&$arr)
506 // should do the same as this perl statement:
507 // sort { $trigrams{$b} == $trigrams{$a}
508 // ? $a cmp $b : $trigrams{$b} <=> $trigrams{$a} }
510 // needs to sort by both key and value at once
511 // using the key to break ties for the value
513 // converts array into an array of arrays of each key and value
514 // may be a better way of doing this
517 foreach ($arr as $key => $value) {
518 $combined[] = array($key, $value);
521 usort($combined, array($this, '_sort_func'));
523 $replacement = array();
524 foreach ($combined as $key => $value) {
525 list($new_key, $new_value) = $value;
526 $replacement[$new_key] = $new_value;
533 * Sort function used by bubble sort
535 * Callback function for usort().
537 * @param array $a first param passed by usort()
538 * @param array $b second param passed by usort()
540 * @return int 1 if $a is greater, -1 if not
543 protected function _sort_func($a, $b)
545 // each is actually a key/value pair, so that it can compare using both
546 list($a_key, $a_value) = $a;
547 list($b_key, $b_value) = $b;
549 if ($a_value == $b_value) {
550 // if the values are the same, break ties using the key
551 return strcmp($a_key, $b_key);
554 // if not, just sort normally
555 if ($a_value > $b_value) {
562 // 0 should not be possible because keys must be unique
566 * Calculates a linear rank-order distance statistic between two sets of
569 * Sums the differences in rank for each trigram. If the trigram does not
570 * appear in both, consider it a difference of $this->_threshold.
572 * This distance measure was proposed by Cavnar & Trenkle (1994). Despite
573 * its simplicity it has been shown to be highly accurate for language
574 * identification tasks.
576 * @param array $arr1 the reference set of trigram ranks
577 * @param array $arr2 the target set of trigram ranks
579 * @return int the sum of the differences between the ranks of
580 * the two trigram sets
582 protected function _distance($arr1, $arr2)
586 foreach ($arr2 as $key => $value) {
587 if (isset($arr1[$key])) {
588 $distance = abs($value - $arr1[$key]);
590 // $this->_threshold sets the maximum possible distance value
591 // for any one pair of trigrams
592 $distance = $this->_threshold;
594 $sumdist += $distance;
599 // todo: there are other distance statistics to try, e.g. relative
600 // entropy, but they're probably more costly to compute
604 * Normalizes the score returned by _distance()
606 * Different if perl compatible or not
608 * @param int $score the score from _distance()
609 * @param int $base_count the number of trigrams being considered
611 * @return float the normalized score
614 protected function _normalize_score($score, $base_count = null)
616 if ($base_count === null) {
617 $base_count = $this->_threshold;
620 if (!$this->_perl_compatible) {
621 return 1 - ($score / $base_count / $this->_threshold);
623 return floor($score / $base_count);
629 * Detects the closeness of a sample of text to the known languages
631 * Calculates the statistical difference between the text and
632 * the trigrams for each language, normalizes the score then
633 * returns results for all languages in sorted order
635 * If perl compatible, the score is 300-0, 0 being most similar.
636 * Otherwise, it's 0-1 with 1 being most similar.
638 * The $sample text should be at least a few sentences in length;
639 * should be ascii-7 or utf8 encoded, if another and the mbstring extension
640 * is present it will try to detect and convert. However, experience has
641 * shown that mb_detect_encoding() *does not work very well* with at least
642 * some types of encoding.
644 * @param string $sample a sample of text to compare.
645 * @param int $limit if specified, return an array of the most likely
646 * $limit languages and their scores.
648 * @return mixed sorted array of language scores, blank array if no
649 * useable text was found
651 * @throws Text_LanguageDetect_Exception
653 public function detect($sample, $limit = 0)
656 if (!Text_LanguageDetect_Parser::validateString($sample)) {
660 // check char encoding
661 // (only if mbstring extension is compiled and PHP > 4.0.6)
662 if (function_exists('mb_detect_encoding')
663 && function_exists('mb_convert_encoding')
665 // mb_detect_encoding isn't very reliable, to say the least
666 // detection should still work with a sufficient sample
667 // of ascii characters
668 $encoding = mb_detect_encoding($sample);
670 // mb_detect_encoding() will return FALSE if detection fails
671 // don't attempt conversion if that's the case
672 if ($encoding != 'ASCII' && $encoding != 'UTF-8'
673 && $encoding !== false
675 // verify the encoding exists in mb_list_encodings
676 if (in_array($encoding, mb_list_encodings())) {
677 $sample = mb_convert_encoding($sample, 'UTF-8', $encoding);
682 $sample_obj = new Text_LanguageDetect_Parser($sample);
683 $sample_obj->prepareTrigram();
684 if ($this->_use_unicode_narrowing) {
685 $sample_obj->prepareUnicode();
687 $sample_obj->setPadStart(!$this->_perl_compatible);
688 $sample_obj->analyze();
690 $trigram_freqs = $sample_obj->getTrigramRanks();
691 $trigram_count = count($trigram_freqs);
693 if ($trigram_count == 0) {
699 // use unicode block detection to narrow down the possibilities
700 if ($this->_use_unicode_narrowing) {
701 $blocks = $sample_obj->getUnicodeBlocks();
703 if (is_array($blocks)) {
704 $present_blocks = array_keys($blocks);
706 throw new Text_LanguageDetect_Exception(
707 'Error during block detection',
708 Text_LanguageDetect_Exception::BLOCK_DETECTION
712 $possible_langs = array();
714 foreach ($present_blocks as $blockname) {
715 if (isset($this->_unicode_map[$blockname])) {
717 $possible_langs = array_merge(
719 array_keys($this->_unicode_map[$blockname])
722 // todo: faster way to do this?
726 // could also try an intersect operation rather than a union
727 // in other words, choose languages whose trigrams contain
728 // ALL of the unicode blocks found in this sample
729 // would improve speed but would be completely thrown off by an
730 // unexpected character, like an umlaut appearing in english text
732 $possible_langs = array_intersect(
733 array_keys($this->_lang_db),
734 array_unique($possible_langs)
737 // needs to intersect it with the keys of _lang_db in case
738 // languages have been omitted
741 // or just try 'em all
742 $possible_langs = array_keys($this->_lang_db);
746 foreach ($possible_langs as $lang) {
747 $scores[$lang] = $this->_normalize_score(
748 $this->_distance($this->_lang_db[$lang], $trigram_freqs),
755 if ($this->_perl_compatible) {
761 // todo: drop languages with a score of $this->_max_score?
763 // limit the number of returned scores
764 if ($limit && is_numeric($limit)) {
765 $limited_scores = array();
768 foreach ($scores as $key => $value) {
769 if ($i++ >= $limit) {
773 $limited_scores[$key] = $value;
776 return $this->_convertToNameMode($limited_scores, true);
778 return $this->_convertToNameMode($scores, true);
783 * Returns only the most similar language to the text sample
785 * Calls $this->detect() and returns only the top result
787 * @param string $sample text to detect the language of
789 * @return string the name of the most likely language
790 * or null if no language is similar
792 * @throws Text_LanguageDetect_Exception
794 public function detectSimple($sample)
796 $scores = $this->detect($sample, 1);
798 // if top language has the maximum possible score,
799 // then the top score will have been picked at random
800 if (!is_array($scores) || empty($scores)
801 || current($scores) == $this->_max_score
810 * Returns an array containing the most similar language and a confidence
813 * Confidence is a simple measure calculated from the similarity score
814 * minus the similarity score from the next most similar language
815 * divided by the highest possible score. Languages that have closely
816 * related cousins (e.g. Norwegian and Danish) should generally have lower
819 * The similarity score answers the question "How likely is the text the
820 * returned language regardless of the other languages considered?" The
821 * confidence score is one way of answering the question "how likely is the
822 * text the detected language relative to the rest of the language model
825 * To see how similar languages are a priori, see languageSimilarity()
827 * @param string $sample text for which language will be detected
829 * @return array most similar language, score and confidence rating
830 * or null if no language is similar
832 * @throws Text_LanguageDetect_Exception
834 public function detectConfidence($sample)
836 $scores = $this->detect($sample, 2);
838 // if most similar language has the max score, it
839 // will have been picked at random
840 if (!is_array($scores) || empty($scores)
841 || current($scores) == $this->_max_score
846 $arr['language'] = key($scores);
847 $arr['similarity'] = current($scores);
848 if (next($scores) !== false) { // if false then no next element
849 // the goal is to return a higher value if the distance between
850 // the similarity of the first score and the second score is high
852 if ($this->_perl_compatible) {
853 $arr['confidence'] = (current($scores) - $arr['similarity'])
857 $arr['confidence'] = $arr['similarity'] - current($scores);
862 $arr['confidence'] = null;
869 * Returns the distribution of unicode blocks in a given utf8 string
871 * For the block name of a single char, use unicodeBlockName()
873 * @param string $str input string. Must be ascii or utf8
874 * @param bool $skip_symbols if true, skip ascii digits, symbols and
875 * non-printing characters. Includes spaces,
876 * newlines and common punctutation characters.
879 * @throws Text_LanguageDetect_Exception
881 public function detectUnicodeBlocks($str, $skip_symbols)
883 $skip_symbols = (bool)$skip_symbols;
886 $sample_obj = new Text_LanguageDetect_Parser($str);
887 $sample_obj->prepareUnicode();
888 $sample_obj->prepareTrigram(false);
889 $sample_obj->setUnicodeSkipSymbols($skip_symbols);
890 $sample_obj->analyze();
891 $blocks = $sample_obj->getUnicodeBlocks();
897 * Returns the block name for a given unicode value
899 * If passed a string, will assume it is being passed a UTF8-formatted
900 * character and will automatically convert. Otherwise it will assume it
901 * is being passed a numeric unicode value.
903 * Make sure input is of the correct type!
905 * @param mixed $unicode unicode value or utf8 char
907 * @return mixed the block name string or false if not found
908 * @throws Text_LanguageDetect_Exception
910 public function unicodeBlockName($unicode)
912 if (is_string($unicode)) {
913 // assume it is being passed a utf8 char, so convert it
914 if (self::utf8strlen($unicode) > 1) {
915 throw new Text_LanguageDetect_Exception(
916 'Pass a single char only to this method',
917 Text_LanguageDetect_Exception::PARAM_TYPE
920 $unicode = $this->_utf8char2unicode($unicode);
922 } elseif (!is_int($unicode)) {
923 throw new Text_LanguageDetect_Exception(
924 'Input must be of type string or int.',
925 Text_LanguageDetect_Exception::PARAM_TYPE
929 $blocks = $this->_read_unicode_block_db();
931 $result = $this->_unicode_block_name($unicode, $blocks);
941 * Searches the unicode block database
943 * Returns the block name for a given unicode value. unicodeBlockName() is
944 * the public interface for this function, which does input checks which
945 * this function omits for speed.
947 * @param int $unicode the unicode value
948 * @param array $blocks the block database
949 * @param int $block_count the number of defined blocks in the database
951 * @return mixed Block name, -1 if it failed
952 * @see unicodeBlockName()
954 protected function _unicode_block_name($unicode, $blocks, $block_count = -1)
956 // for a reference, see
957 // http://www.unicode.org/Public/UNIDATA/Blocks.txt
959 // assume that ascii characters are the most common
960 // so try it first for efficiency
961 if ($unicode <= $blocks[0][1]) {
965 // the optional $block_count param is for efficiency
966 // so we this function doesn't have to run count() every time
967 if ($block_count != -1) {
968 $high = $block_count - 1;
970 $high = count($blocks) - 1;
973 $low = 1; // start with 1 because ascii was 0
975 // your average binary search algorithm
976 while ($low <= $high) {
977 $mid = floor(($low + $high) / 2);
979 if ($unicode < $blocks[$mid][0]) {
980 // if it's lower than the lower bound
983 } elseif ($unicode > $blocks[$mid][1]) {
984 // if it's higher than the upper bound
989 return $blocks[$mid];
993 // failed to find the block
996 // todo: differentiate when it's out of range or when it falls
997 // into an unassigned range?
1001 * Brings up the unicode block database
1003 * @return array the database of unicode block definitions
1004 * @throws Text_LanguageDetect_Exception
1006 protected function _read_unicode_block_db()
1008 // since the unicode definitions are always going to be the same,
1009 // might as well share the memory for the db with all other instances
1013 if (!isset($data)) {
1014 $data = $this->_readdb($this->_unicode_db_filename);
1021 * Calculate the similarities between the language models
1023 * Use this function to see how similar languages are to each other.
1025 * If passed 2 language names, will return just those languages compared.
1026 * If passed 1 language name, will return that language compared to
1028 * If passed none, will return an array of every language model compared
1029 * to every other one.
1031 * @param string $lang1 the name of the first language to be compared
1032 * @param string $lang2 the name of the second language to be compared
1034 * @return array scores of every language compared
1035 * or the score of just the provided languages
1036 * or null if one of the supplied languages does not exist
1037 * @throws Text_LanguageDetect_Exception
1039 public function languageSimilarity($lang1 = null, $lang2 = null)
1041 $lang1 = $this->_convertFromNameMode($lang1);
1042 $lang2 = $this->_convertFromNameMode($lang2);
1043 if ($lang1 != null) {
1044 $lang1 = strtolower($lang1);
1046 // check if language model exists
1047 if (!isset($this->_lang_db[$lang1])) {
1051 if ($lang2 != null) {
1052 if (!isset($this->_lang_db[$lang2])) {
1053 // check if language model exists
1057 $lang2 = strtolower($lang2);
1059 // compare just these two languages
1060 return $this->_normalize_score(
1062 $this->_lang_db[$lang1],
1063 $this->_lang_db[$lang2]
1068 // compare just $lang1 to all languages
1069 $return_arr = array();
1070 foreach ($this->_lang_db as $key => $value) {
1071 if ($key != $lang1) {
1072 // don't compare a language to itself
1073 $return_arr[$key] = $this->_normalize_score(
1074 $this->_distance($this->_lang_db[$lang1], $value)
1085 // compare all languages to each other
1086 $return_arr = array();
1087 foreach (array_keys($this->_lang_db) as $lang1) {
1088 foreach (array_keys($this->_lang_db) as $lang2) {
1089 // skip comparing languages to themselves
1090 if ($lang1 != $lang2) {
1092 if (isset($return_arr[$lang2][$lang1])) {
1093 // don't re-calculate what's already been done
1094 $return_arr[$lang1][$lang2]
1095 = $return_arr[$lang2][$lang1];
1099 $return_arr[$lang1][$lang2]
1100 = $this->_normalize_score(
1102 $this->_lang_db[$lang1],
1103 $this->_lang_db[$lang2]
1116 * Cluster known languages according to languageSimilarity()
1118 * WARNING: this method is EXPERIMENTAL. It is not recommended for common
1119 * use, and it may disappear or its functionality may change in future
1120 * releases without notice.
1122 * Uses a nearest neighbor technique to generate the maximum possible
1123 * number of dendograms from the similarity data.
1125 * @return array language cluster data
1126 * @throws Text_LanguageDetect_Exception
1127 * @see languageSimilarity()
1128 * @deprecated this function will eventually be removed and placed into
1129 * the model generation class
1131 public function clusterLanguages()
1133 // todo: set the maximum number of clusters
1134 // return cached result, if any
1135 if (isset($this->_clusters)) {
1136 return $this->_clusters;
1139 $langs = array_keys($this->_lang_db);
1141 $arr = $this->languageSimilarity();
1145 foreach ($langs as $lang) {
1146 if (!isset($this->_lang_db[$lang])) {
1147 throw new Text_LanguageDetect_Exception(
1149 Text_LanguageDetect_Exception::UNKNOWN_LANGUAGE
1154 // http://www.psychstat.missouristate.edu/multibook/mlt04m.html
1155 foreach ($langs as $old_key => $lang1) {
1156 $langs[$lang1] = $lang1;
1157 unset($langs[$old_key]);
1160 $result_data = $really_map = array();
1163 while (count($langs) > 2 && $i++ < 200) {
1164 $highest_score = -1;
1167 foreach ($langs as $lang1) {
1168 foreach ($langs as $lang2) {
1169 if ($lang1 != $lang2
1170 && $arr[$lang1][$lang2] > $highest_score
1172 $highest_score = $arr[$lang1][$lang2];
1173 $highest_key1 = $lang1;
1174 $highest_key2 = $lang2;
1179 if (!$highest_key1) {
1180 // should not ever happen
1181 throw new Text_LanguageDetect_Exception(
1182 "no highest key? (step: $i)",
1183 Text_LanguageDetect_Exception::NO_HIGHEST_KEY
1187 if ($highest_score == 0) {
1188 // languages are perfectly dissimilar
1192 // $highest_key1 and $highest_key2 are most similar
1193 $sum1 = array_sum($arr[$highest_key1]);
1194 $sum2 = array_sum($arr[$highest_key2]);
1196 // use the score for the one that is most similar to the rest of
1197 // the field as the score for the group
1198 // todo: could try averaging or "centroid" method instead
1199 // seems like that might make more sense
1200 // actually nearest neighbor may be better for binary searching
1203 // for "Complete Linkage"/"furthest neighbor"
1205 // for "Single Linkage"/"nearest neighbor" method
1206 // should should be >
1207 // results seem to be pretty much the same with either method
1209 // figure out which to delete and which to replace
1210 if ($sum1 > $sum2) {
1211 $replaceme = $highest_key1;
1212 $deleteme = $highest_key2;
1214 $replaceme = $highest_key2;
1215 $deleteme = $highest_key1;
1218 $newkey = $replaceme . ':' . $deleteme;
1220 // $replaceme is most similar to remaining languages
1221 // replace $replaceme with '$newkey', deleting $deleteme
1223 // keep a record of which fork is really which language
1224 $really_lang = $replaceme;
1225 while (isset($really_map[$really_lang])) {
1226 $really_lang = $really_map[$really_lang];
1228 $really_map[$newkey] = $really_lang;
1231 // replace the best fitting key, delete the other
1232 foreach ($arr as $key1 => $arr2) {
1233 foreach ($arr2 as $key2 => $value2) {
1234 if ($key2 == $replaceme) {
1235 $arr[$key1][$newkey] = $arr[$key1][$key2];
1236 unset($arr[$key1][$key2]);
1237 // replacing $arr[$key1][$key2] with $arr[$key1][$newkey]
1240 if ($key1 == $replaceme) {
1241 $arr[$newkey][$key2] = $arr[$key1][$key2];
1242 unset($arr[$key1][$key2]);
1243 // replacing $arr[$key1][$key2] with $arr[$newkey][$key2]
1246 if ($key1 == $deleteme || $key2 == $deleteme) {
1247 // deleting $arr[$key1][$key2]
1248 unset($arr[$key1][$key2]);
1254 unset($langs[$highest_key1]);
1255 unset($langs[$highest_key2]);
1256 $langs[$newkey] = $newkey;
1259 // some of these may be overkill
1260 $result_data[$newkey] = array(
1261 'newkey' => $newkey,
1263 'diff' => abs($sum1 - $sum2),
1264 'score' => $highest_score,
1265 'bestfit' => $replaceme,
1266 'otherfit' => $deleteme,
1267 'really' => $really_lang,
1271 $return_val = array(
1272 'open_forks' => $langs,
1273 // the top level of clusters
1274 // clusters that are mutually exclusive
1275 // or specified by a specific maximum
1277 'fork_data' => $result_data,
1278 // data for each split
1280 'name_map' => $really_map,
1281 // which cluster is really which language
1282 // using the nearest neighbor technique, the cluster
1283 // inherits all of the properties of its most-similar member
1288 // saves the result in the object
1289 $this->_clusters = $return_val;
1296 * Perform an intelligent detection based on clusterLanguages()
1298 * WARNING: this method is EXPERIMENTAL. It is not recommended for common
1299 * use, and it may disappear or its functionality may change in future
1300 * releases without notice.
1302 * This compares the sample text to top the top level of clusters. If the
1303 * sample is similar to the cluster it will drop down and compare it to the
1304 * languages in the cluster, and so on until it hits a leaf node.
1306 * this should find the language in considerably fewer compares
1307 * (the equivalent of a binary search), however clusterLanguages() is costly
1308 * and the loss of accuracy from this technique is significant.
1310 * This method may need to be 'fuzzier' in order to become more accurate.
1312 * This function could be more useful if the universe of possible languages
1313 * was very large, however in such cases some method of Bayesian inference
1314 * might be more helpful.
1316 * @param string $str input string
1318 * @return array language scores (only those compared)
1319 * @throws Text_LanguageDetect_Exception
1320 * @see clusterLanguages()
1322 public function clusteredSearch($str)
1325 if (!Text_LanguageDetect_Parser::validateString($str)) {
1329 // clusterLanguages() will return a cached result if possible
1330 // so it's safe to call it every time
1331 $result = $this->clusterLanguages();
1333 $dendogram_start = $result['open_forks'];
1334 $dendogram_data = $result['fork_data'];
1335 $dendogram_alias = $result['name_map'];
1337 $sample_obj = new Text_LanguageDetect_Parser($str);
1338 $sample_obj->prepareTrigram();
1339 $sample_obj->setPadStart(!$this->_perl_compatible);
1340 $sample_obj->analyze();
1341 $sample_result = $sample_obj->getTrigramRanks();
1342 $sample_count = count($sample_result);
1345 if ($sample_count == 0) {
1349 $i = 0; // counts the number of steps
1351 foreach ($dendogram_start as $lang) {
1352 if (isset($dendogram_alias[$lang])) {
1353 $lang_key = $dendogram_alias[$lang];
1358 $scores[$lang] = $this->_normalize_score(
1359 $this->_distance($this->_lang_db[$lang_key], $sample_result),
1366 if ($this->_perl_compatible) {
1372 $top_score = current($scores);
1373 $top_key = key($scores);
1375 // of starting forks, $top_key is the most similar to the sample
1377 $cur_key = $top_key;
1378 while (isset($dendogram_data[$cur_key])) {
1379 $lang1 = $dendogram_data[$cur_key]['bestfit'];
1380 $lang2 = $dendogram_data[$cur_key]['otherfit'];
1381 foreach (array($lang1, $lang2) as $lang) {
1382 if (isset($dendogram_alias[$lang])) {
1383 $lang_key = $dendogram_alias[$lang];
1388 $scores[$lang] = $this->_normalize_score(
1389 $this->_distance($this->_lang_db[$lang_key], $sample_result),
1393 //todo: does not need to do same comparison again
1398 if ($scores[$lang1] > $scores[$lang2]) {
1400 $loser_key = $lang2;
1403 $loser_key = $lang1;
1406 $diff = $scores[$cur_key] - $scores[$loser_key];
1408 // $cur_key ({$dendogram_alias[$cur_key]}) wins
1409 // over $loser_key ({$dendogram_alias[$loser_key]})
1410 // with a difference of $diff
1413 // found result in $i compares
1415 // rather than sorting the result, preserve it so that you can see
1416 // which paths the algorithm decided to take along the tree
1418 // but sometimes the last item is only the second highest
1419 if (($this->_perl_compatible && (end($scores) > prev($scores)))
1420 || (!$this->_perl_compatible && (end($scores) < prev($scores)))
1422 $real_last_score = current($scores);
1423 $real_last_key = key($scores);
1425 // swaps the 2nd-to-last item for the last item
1426 unset($scores[$real_last_key]);
1427 $scores[$real_last_key] = $real_last_score;
1431 if (!$this->_perl_compatible) {
1432 $scores = array_reverse($scores, true);
1433 // second param requires php > 4.0.3
1440 * UTF8-safe strlen()
1442 * Returns the numbers of characters (not bytes) in a utf8 string
1444 * @param string $str string to get the length of
1446 * @return int number of chars
1448 public static function utf8strlen($str)
1450 // utf8_decode() will convert unknown chars to '?', which is actually
1451 // ideal for counting.
1453 return strlen(utf8_decode($str));
1455 // idea stolen from dokuwiki
1459 * Returns the unicode value of a utf8 char
1461 * @param string $char a utf8 (possibly multi-byte) char
1463 * @return int unicode value
1464 * @link http://en.wikipedia.org/wiki/UTF-8
1466 protected function _utf8char2unicode($char)
1468 // strlen() here will actually get the binary length of a single char
1469 switch (strlen($char)) {
1471 // normal ASCII-7 byte
1472 // 0xxxxxxx --> 0xxxxxxx
1473 return ord($char{0});
1477 // 110zzzzx 10xxxxxx --> 00000zzz zxxxxxxx
1478 $z = (ord($char{0}) & 0x000001F) << 6;
1479 $x = (ord($char{1}) & 0x0000003F);
1484 // 1110zzzz 10zxxxxx 10xxxxxx --> zzzzzxxx xxxxxxxx
1485 $z = (ord($char{0}) & 0x0000000F) << 12;
1486 $x1 = (ord($char{1}) & 0x0000003F) << 6;
1487 $x2 = (ord($char{2}) & 0x0000003F);
1488 return ($z | $x1 | $x2);
1492 // 11110zzz 10zzxxxx 10xxxxxx 10xxxxxx -->
1493 // 000zzzzz xxxxxxxx xxxxxxxx
1494 $z1 = (ord($char{0}) & 0x00000007) << 18;
1495 $z2 = (ord($char{1}) & 0x0000003F) << 12;
1496 $x1 = (ord($char{2}) & 0x0000003F) << 6;
1497 $x2 = (ord($char{3}) & 0x0000003F);
1498 return ($z1 | $z2 | $x1 | $x2);
1503 * UTF8-safe fast character iterator
1505 * Will get the next character starting from $counter, which will then be
1506 * incremented. If a multi-byte char the bytes will be concatenated and
1507 * $counter will be incremeted by the number of bytes in the char.
1509 * @param string $str the string being iterated over
1510 * @param int $counter the iterator, will increment by reference
1511 * @param bool $special_convert whether to do special conversions
1513 * @return char the next (possibly multi-byte) char from $counter
1515 protected static function _next_char($str, &$counter, $special_convert = false)
1517 $char = $str{$counter++};
1520 // for a description of the utf8 system see
1521 // http://www.phpclasses.org/browse/file/5131.html
1523 // normal ascii one byte char
1525 // special conversions needed for this package
1526 // (that only apply to regular ascii characters)
1527 // lower case, and convert all non-alphanumeric characters
1528 // other than "'" to space
1529 if ($special_convert && $char != ' ' && $char != "'") {
1530 if ($ord >= 65 && $ord <= 90) { // A-Z
1531 $char = chr($ord + 32); // lower case
1532 } elseif ($ord < 97 || $ord > 122) { // NOT a-z
1533 $char = ' '; // convert to space
1539 } elseif ($ord >> 5 == 6) { // two-byte char
1541 $nextchar = $str{$counter++}; // get next byte
1543 // lower-casing of non-ascii characters is still incomplete
1545 if ($special_convert) {
1546 // lower case latin accented characters
1548 $nextord = ord($nextchar);
1549 $nextord_adj = $nextord + 64;
1550 // for a reference, see
1551 // http://www.ramsch.org/martin/uni/fmi-hp/iso8859-1.html
1553 // À - Þ but not ×
1554 if ($nextord_adj >= 192
1555 && $nextord_adj <= 222
1556 && $nextord_adj != 215
1558 $nextchar = chr($nextord + 32);
1561 } elseif ($ord == 208) {
1562 // lower case cyrillic alphabet
1563 $nextord = ord($nextchar);
1565 if ($nextord >= 144 && $nextord <= 159) {
1567 $nextchar = chr($nextord + 32);
1569 } elseif ($nextord >= 160 && $nextord <= 175) {
1572 $char = chr(209); // == $ord++
1573 $nextchar = chr($nextord - 32);
1579 return $char . $nextchar;
1580 } elseif ($ord >> 4 == 14) { // three-byte char
1582 // tag on next 2 bytes
1583 return $char . $str{$counter++} . $str{$counter++};
1585 } elseif ($ord >> 3 == 30) { // four-byte char
1587 // tag on next 3 bytes
1588 return $char . $str{$counter++} . $str{$counter++} . $str{$counter++};
1596 * Converts an $language input parameter from the configured mode
1597 * to the language name that is used internally.
1599 * Works for strings and arrays.
1601 * @param string|array $lang A language description ("english"/"en"/"eng")
1602 * @param boolean $convertKey If $lang is an array, setting $key
1603 * converts the keys to the language name.
1605 * @return string|array Language name
1607 protected function _convertFromNameMode($lang, $convertKey = false)
1609 if ($this->_name_mode == 0) {
1613 if ($this->_name_mode == 2) {
1614 $method = 'code2ToName';
1616 $method = 'code3ToName';
1619 if (is_string($lang)) {
1620 return (string)Text_LanguageDetect_ISO639::$method($lang);
1624 foreach ($lang as $key => $val) {
1626 $newkey = (string)Text_LanguageDetect_ISO639::$method($key);
1627 $newlang[$newkey] = $val;
1629 $newlang[$key] = (string)Text_LanguageDetect_ISO639::$method($val);
1636 * Converts an $language output parameter from the language name that is
1637 * used internally to the configured mode.
1639 * Works for strings and arrays.
1641 * @param string|array $lang A language description ("english"/"en"/"eng")
1642 * @param boolean $convertKey If $lang is an array, setting $key
1643 * converts the keys to the language name.
1645 * @return string|array Language name
1647 protected function _convertToNameMode($lang, $convertKey = false)
1649 if ($this->_name_mode == 0) {
1653 if ($this->_name_mode == 2) {
1654 $method = 'nameToCode2';
1656 $method = 'nameToCode3';
1659 if (is_string($lang)) {
1660 return Text_LanguageDetect_ISO639::$method($lang);
1664 foreach ($lang as $key => $val) {
1666 $newkey = Text_LanguageDetect_ISO639::$method($key);
1667 $newlang[$newkey] = $val;
1669 $newlang[$key] = Text_LanguageDetect_ISO639::$method($val);
1676 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */