encoding_estimator 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: f22f57e18e9e57c37d777061d7b644f1b44acf71
4
+ data.tar.gz: e27edfa36627f76644d9238c1177853f70a2d238
5
+ SHA512:
6
+ metadata.gz: f4621f23022e68f1fa8298f56e3aba0ffac23bc086a71187b45e89ff0d19a0dbbb59c1f16c72f83b021a217c5120d1056c4a3c527005b1132df51d877187e3ec
7
+ data.tar.gz: f2ef8383cb065d1b2402fd5418ee17305ba29aedc44aa8172d2fa1306e3144aa95e790aebb7d34f0ab2ba021789cb767cdb0fd03da92a6adc8c05e695ba21a1b
data/.gitignore ADDED
@@ -0,0 +1,2 @@
1
+ Gemfile.lock
2
+ .idea
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at kirmis@st.ovgu.de. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in encoding_estimator.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Oskar Kirmis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,121 @@
1
+ # EncodingEstimator: Detect encoding of strings
2
+
3
+ This gem allows you to detect the encoding of a string based on their content. It uses character distribution statistics to check which encoding is the one that gives you the best results.
4
+
5
+ ## Usage in Ruby Code
6
+
7
+ The gem has two major high level methods. The first one can be used when you want to know, how a string is encoded:
8
+
9
+ ```ruby
10
+ detection = EncodingEstimator.detect( File.read( 'foo.txt' ), languages: [ :en, :de ] )
11
+ puts "Encoding: #{detection.result.encoding}"
12
+ ```
13
+
14
+ The second one is a shortcut you can use in case you just want to be sure to get a string of an unknown encoding as a UTF-8 encoded string (should be the ruby default):
15
+
16
+ ```ruby
17
+ utf8_txt = EncodingEstimator.ensure_utf8( File.read( 'foo.txt' ), languages: [ :en, :de ] )
18
+ ```
19
+
20
+ If you need more control over the operations to perform, just have a look at `EncodingEstimator::Detector` and `EncodingEstimator::Conversion`.
21
+
22
+
23
+ ## Installation
24
+
25
+ Add this line to your application's Gemfile:
26
+
27
+ ```ruby
28
+ gem 'encoding_estimator'
29
+ ```
30
+
31
+ And then execute:
32
+
33
+ $ bundle
34
+
35
+ Or install it yourself as:
36
+
37
+ $ gem install encoding_estimator
38
+
39
+ Note: if you want to use the multithreaded versions of the algorithms, please install `parallel` and `ruby-progressbar` gem.
40
+
41
+ ## Command line utilities
42
+
43
+ This gem provides two command line utilities: `encest-detect` and `encest-gen`.
44
+
45
+ ### encest-detect
46
+
47
+ This tool can detect the encoding of files. Therefore, it has some command line options you should use whenever you know more about a file (e.g. which languages it could be written in or which encodings it could have).
48
+
49
+ ```
50
+ usage: encest-detect [options]
51
+ --encodings, -e Encodings to test (default: iso-8859-1,utf-16le,windows-1251)
52
+ --operations, -o Operations (enc/dec) to test (default: dec)
53
+ --languages, -l Language profiles to apply (default: en,de)
54
+ --threads, -t Number of threads to use (0 to disable multithreading, default)
55
+ --help, -h Display help
56
+ other arguments: files to parse
57
+ ```
58
+
59
+ Please note that the `-l` argument accepts the short two-letter-codes for the included language profiles as well as paths to language model files. These can be generated by using `encest-gen`.
60
+
61
+ The output might look like this:
62
+
63
+ ```
64
+ $ encest-detect -l en,de,fr */*.txt
65
+ de/iso-8859-1.txt: dec_iso-8859-1
66
+ keep_utf-8: 0.9983638601518013
67
+ dec_iso-8859-1: 1.0
68
+ dec_utf-16le: 0.0
69
+ dec_windows-1251: 0.9984215377764598
70
+ en/utf-16le.txt: dec_utf-16le
71
+ keep_utf-8: 0.0
72
+ dec_iso-8859-1: 0.3981167811176304
73
+ dec_utf-16le: 1.0
74
+ dec_windows-1251: 0.005410547626031029
75
+ fr/utf-8.txt: keep_utf-8
76
+ keep_utf-8: 1.0
77
+ dec_iso-8859-1: 0.9957726010451553
78
+ dec_utf-16le: 0.0
79
+ dec_windows-1251: 0.9957810888135232
80
+ ```
81
+
82
+ ### encest-gen
83
+
84
+ This tool is can generate the language models the `encest-detect` tool uses (or the other classes in this gem). The language models are *very simple* JSON files, looking somewhat like that:
85
+
86
+ `{"W":0.222539,"ä":0.288427,"-":0.513657,"Z":0.118473 ... }`
87
+
88
+ The `encest-gen` command generates these scores based on a lot of input text. To generate the language models this gem provides by default, I used dumps of the Wikipedia, but you can use any (UTF-8-encoded) text files you like. Just put them in one directory, let's call it *pt* (for Portuguese) and extract the files you want to learn the language model from to that directory (e.g. the Wikipedia dump). Please split large files into smaller chunks of text (max ~20MiB) because ruby otherwise will crash with NoMemoryError and you don't see a progressbar.
89
+
90
+ Usage of `encest-gen` is quite simple:
91
+ ```
92
+ usage: encest-gen [options]
93
+ --threshold, -t Minimum character count threshold to include a char in the model (default: 0.00001)
94
+ --threads, -n Number of threads used to process the files (default: 4)
95
+ --silent, -s Disable progressbars and other outputs
96
+ --help, -h Display help
97
+ other arguments: lang1=directory1 ... langN=directoryN
98
+ ```
99
+
100
+ So for our Portuguese language model on a 8 core machine we call:
101
+
102
+ `encest-gen -n 8 pt=/path/to/the/directory/with/text`
103
+
104
+ The command will produce a file called `pt.json` which is you new language model.
105
+
106
+ ## How it works
107
+
108
+ This gem uses a statistical approach to determine the encoding of an input string. Therefore, it interprets the input as different encodings (all encodings to test) and compares the character distribution against one or multiple language models. The detector then returns the likelihood of every encoding.
109
+
110
+ ## Supported languages
111
+
112
+ Currently, the gem has support for 5 languages: English, German, French, Spanish and Russian. The language profiles were generated from Wikipedia dumps. You can generate your own language profiles using the `encest-gen` tool. For more information on this tool, see above.
113
+
114
+ ## Supported encodings
115
+
116
+ The gem supports all encodings your ruby implementation supports. But note that including more encodings in the list of encodings you want to test slows down the detection process.
117
+
118
+ ## License
119
+
120
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
121
+
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require 'bundler/gem_tasks'
2
+ task :default => :spec
data/bin/encest-detect ADDED
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'json'
4
+ require 'slop'
5
+
6
+ # Get environment: development or production? -> Installed gem or current source dir
7
+ if ENV.key?( 'ENCEST_ENV' ) and ENV[ 'ENCEST_ENV' ] == 'development'
8
+ require_relative '../lib/encoding_estimator'
9
+ else
10
+ require 'encoding_estimator'
11
+ end
12
+
13
+
14
+ opts = Slop.parse do |o|
15
+ o.array(
16
+ '--encodings', '-e', 'Encodings to test (default: iso-8859-1,utf-16le,windows-1251)', default: %w(iso-8859-1 utf-16le windows-1251)
17
+ )
18
+ o.array(
19
+ '--operations', '-o', 'Operations (enc/dec) to test (default: dec)',
20
+ default: [EncodingEstimator::Conversion::Operation::DECODE]
21
+ )
22
+ o.array(
23
+ '--languages', '-l', 'Language models to apply (default: en,de)', default: ['de', 'en']
24
+ )
25
+ o.integer(
26
+ '--threads', '-t', 'Number of threads to use (0 to disable multithreading, default)', default: 0
27
+ )
28
+ o.bool(
29
+ '--help', '-h', 'Display help'
30
+ )
31
+ end
32
+
33
+ if opts[:help]
34
+ puts opts
35
+ puts (' ' * 4) + 'other arguments: files to parse'
36
+ exit! 0
37
+ end
38
+
39
+ opts.arguments.each do |file|
40
+ unless File.file? file
41
+ puts "No such file: #{file}"
42
+ exit! 1
43
+ end
44
+ end
45
+
46
+ # Internal vs. external profiles
47
+ opts[:languages] = opts[:languages].map { |l| l.size == 2 ? l.to_sym : l }
48
+
49
+ # Multithreading: nil for 0
50
+ opts[:threads] = opts[:threads] == 0 ? nil : opts[:threads]
51
+
52
+ # Process every file
53
+ opts.arguments.each do |file|
54
+ detection = EncodingEstimator.detect File.read(file ), {
55
+ languages: opts[:languages], encodings: opts[:encodings],
56
+ operations: opts[:operations], include_default: true,
57
+ num_cores: opts[:threads]
58
+ }
59
+
60
+ puts "#{file}: #{detection.result.key}"
61
+ detection.results.each { |r| puts " #{r[:conversion].key}: #{r[:score]}" }
62
+ end
data/bin/encest-gen ADDED
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ # This tool can be used to generate language profiles from directories containing
4
+ # a lot plaintext. It can process multiple languages and directories at once.
5
+ # The models created will be written to the working directory as "two-letter-lang-code.json".
6
+
7
+ require 'json'
8
+ require 'slop'
9
+
10
+ # Get environment: development or production? -> Installed gem or current source dir
11
+ if ENV.key?( 'ENCEST_ENV' ) and ENV[ 'ENCEST_ENV' ] == 'development'
12
+ require_relative '../lib/encoding_estimator'
13
+ else
14
+ require 'encoding_estimator'
15
+ end
16
+
17
+ # Represents a task as specified as command line argument to build a language model for a given
18
+ # language using the files from a given directory.
19
+ class ModelBuildTask
20
+ attr_reader :directory, :language
21
+
22
+ # New model build task representing a directory and a language code
23
+ def initialize( directory, language )
24
+ @directory = directory
25
+ @language = language
26
+ end
27
+
28
+ # Validate the object for correct directory name and language code. Exits the program on error.
29
+ def validate!
30
+ errors = [ validate_directory, validate_language ].reject { |e| e.nil? }
31
+ print_errors errors if errors.any?
32
+ end
33
+
34
+ # Create a ModelBuildTask from a given command line argument of the form
35
+ # "two-letter-code=directory". Quits the program on parsing errors.
36
+ #
37
+ # @param [String] string Command line argument to parse
38
+ # @return [ModelBuildTask] ModelBuildTask representing the command line argument (language and directory)
39
+ def self.parse( string )
40
+ tokens = string.split '='
41
+ if tokens.size == 2
42
+ ModelBuildTask.new(tokens[1], tokens[0])
43
+ else
44
+ print_errors [ "Invalid argument: '#{string}'" ]
45
+ end
46
+ end
47
+
48
+ private
49
+
50
+ # Print a list of errors to standard error
51
+ def self.print_errors( errors )
52
+ STDERR.write "#{errors.join "\n"}"
53
+ exit! 1
54
+ end
55
+
56
+ # Create directory validation error message. nil if everything is fine.
57
+ def validate_directory
58
+ "Not a directory: '#{@directory}'." unless File.directory? @directory
59
+ end
60
+
61
+ # Create two-letter-language-code error message. nil if no error
62
+ def validate_language
63
+ "Invalid language name (no two-letter-code): '#{@directory}'." unless @language.size == 2
64
+ end
65
+ end
66
+
67
+ # Specify/parse the command line arguments.
68
+ opts = Slop.parse do |o|
69
+ o.float(
70
+ '--threshold', '-t', 'Minimum character count threshold to include a char in the model (default: 0.00001)', default: 0.00001
71
+ )
72
+ o.integer(
73
+ '--threads', '-n', 'Number of threads used to process the files (default: 4)', default: 4
74
+ )
75
+ o.bool(
76
+ '--silent', '-s', 'Disable progressbars and other outputs'
77
+ )
78
+ o.bool(
79
+ '--help', '-h', 'Display help'
80
+ )
81
+ end
82
+
83
+ # Help requested?
84
+ if ARGV.include?( '-h' ) || ARGV.include?( '--help' )
85
+ puts opts
86
+ puts ( ' ' * 4 ) + 'other arguments: lang1=directory1 ... langN=directoryN'
87
+ exit! 0
88
+ end
89
+
90
+ silent = opts[:silent]
91
+
92
+ # Parse all arguments of the form two-letter-language-code=directory-to-process-files-from
93
+ configurations = opts.arguments.map { |arg| ModelBuildTask.parse(arg) }
94
+
95
+ # Process every language with its associated directory
96
+ configurations.each do |config|
97
+ puts "Creating language file for #{config.language} from #{config.directory}..." unless silent
98
+
99
+ # Create the model from the directory
100
+ runner = EncodingEstimator::ParallelModelBuilder.new( config.directory, opts[:threshold] )
101
+ runner.execute!( opts[:threads], !silent )
102
+
103
+ # Save the model as json
104
+ File.open("#{config.language}.json", 'w') { |f| f.write JSON.unparse(runner.results) }
105
+ end
@@ -0,0 +1,31 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'encoding_estimator/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'encoding_estimator'
8
+ spec.version = EncodingEstimator::VERSION
9
+ spec.authors = ['Oskar Kirmis']
10
+ spec.email = ['kirmis@st.ovgu.de']
11
+
12
+ spec.summary = %q{Detect encoding of an input string using character count statistics.}
13
+ spec.description = %q{This gem allows you to detect the encoding of a string based on their content. It uses character distribution statistics to check which encoding is the one that gives you the best results.}
14
+ spec.homepage = 'https://git.iftrue.de/okirmis/encoding_estimator'
15
+ spec.license = 'MIT'
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+
21
+ spec.bindir = 'bin'
22
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
23
+ spec.require_paths = ['lib']
24
+
25
+ spec.add_development_dependency 'bundler', '~> 1.13'
26
+ spec.add_development_dependency 'rake', '~> 10.0'
27
+
28
+ spec.add_dependency 'htmlentities', '~> 4.3'
29
+ spec.add_dependency 'json', '~> 2.0'
30
+ spec.add_dependency 'slop', '~> 4.4'
31
+ end
@@ -0,0 +1,70 @@
1
+ require 'htmlentities'
2
+
3
+ module EncodingEstimator
4
+
5
+ # Class which allows building language models (character count statistics) from a single file
6
+ class ModelBuilder
7
+ attr_reader :filename
8
+
9
+ # Create a new object for a given file
10
+ #
11
+ # @param [String] filename Path to the file to learn statistics from
12
+ def initialize( filename )
13
+ @filename = filename
14
+ end
15
+
16
+ # Count all characters in the file
17
+ #
18
+ # @return [Hash] Hash mapping each character found in the file to the number of occurrences
19
+ def execute
20
+ content = load_content
21
+
22
+ stats = {}
23
+ content.each_char { |c| stats[c] = stats.fetch(c, 0) + 1 }
24
+
25
+ stats
26
+ end
27
+
28
+ # Combine multiple character count statistics to one single table. Also, characters
29
+ # occurring less often then a threshold are ignored. The final table is scaled
30
+ # linear (and mapped to a score of 1 to 10)
31
+ #
32
+ # @param [Array<Hash>] stats_collection Array of character count statistics as returned by ModelBuilder.encode
33
+ # @param [Float] min_char_threshold Threshold used to decide, which characters to include
34
+ # (include a char if count/max_count >= threshold)
35
+ # @return [Hash] Character count statistics, in linear scale, score from 1 to 10
36
+ def self.join_and_postprocess( stats_collection, min_char_threshold = 0.0001 )
37
+ stats = {}
38
+ log_stats = {}
39
+
40
+ # Join all stats
41
+ stats_collection.each do |stat|
42
+ stat.each { |char, count| stats[char] = stats.fetch(char, 0) + count }
43
+ end
44
+
45
+ max_count = stats.values.max
46
+ stats.each do |char, count|
47
+ next if count < max_count * min_char_threshold
48
+
49
+ log_stats[ char ] = ( 10.0 * count / max_count ).round( 6 )
50
+ end
51
+
52
+ log_stats
53
+ end
54
+
55
+ private
56
+
57
+ # Load the content from the file specified in the constructor. HTML entities are decoded because of large
58
+ # collections of natural language from the internet are used (e.g. Wikipedia).
59
+ #
60
+ # @return [String] Content of the file without whitespaces
61
+ def load_content
62
+ raw = File.read( @filename ).encode('UTF-16be', invalid: :replace, replace: '').encode('UTF-8')
63
+ decoder = HTMLEntities.new
64
+ plaintext = decoder.decode raw
65
+
66
+ plaintext.gsub! /\s/, ''
67
+ plaintext
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,45 @@
1
+ require_relative '../parallel_support'
2
+ require_relative 'model_builder'
3
+
4
+ module EncodingEstimator
5
+
6
+ # Class used to build language models from multiple files
7
+ class ParallelModelBuilder
8
+
9
+ attr_reader :files
10
+ attr_reader :results
11
+
12
+ # Create a new builder object from all files of a given directory.
13
+ #
14
+ # @param [String] directory Path to the directory to load files from
15
+ # @param [Float] min_char_threshold Minimum threshold specifying which characters to include in the final model
16
+ # (see ModelBuilder.join_and_postprocess for more information)
17
+ def initialize( directory, min_char_threshold = 0.00001 )
18
+ @files = Dir.new( directory ).entries.map { |p| "#{directory}/#{p}" }.select { |p| File.file?( p ) }
19
+ @results = nil
20
+ @threshold = min_char_threshold
21
+ end
22
+
23
+ # Load and process all files from the directory. If the parallel gem is installed, this is done in
24
+ # multiple processes and therefore truly concurrent. If the ruby-progressbar gem is installed and
25
+ # the show_progress parameter is set to true, a progressbar will be shown.
26
+ #
27
+ # @param [Integer] max_processes Maximum number of processes to spawn for processing the files
28
+ # @param [Boolean] show_progress if set to true and the ruby-progressbar gem is installed, show a progressbar
29
+ # @return [Hash] Character count statistics combined from all files of the directory, scaled linear
30
+ def execute!( max_processes = 4, show_progress = true )
31
+ if EncodingEstimator::ParallelSupport.supported?
32
+ opts = {
33
+ in_processes: max_processes,
34
+ progress: ( show_progress && EncodingEstimator::ParallelSupport.progress? ) ? 'Analyzing' : nil
35
+ }
36
+
37
+ result_list = Parallel.map( files, opts ) { |f| EncodingEstimator::ModelBuilder.new( f ).execute }
38
+ else
39
+ result_list = files.map { |f| EncodingEstimator::ModelBuilder.new( f ).execute }
40
+ end
41
+
42
+ @results = EncodingEstimator::ModelBuilder.join_and_postprocess(result_list, @threshold )
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,108 @@
1
+ module EncodingEstimator
2
+
3
+ # Class that represents the conversion of a string to or from an other encoding
4
+ class Conversion
5
+ DEFAULT_TARGET_ENCODING = :'utf-8'
6
+
7
+ # Ways of conversion: convert from an encoding to the target, to an encoding or don't change anything
8
+ module Operation
9
+ ENCODE = :enc
10
+ DECODE = :dec
11
+ KEEP = :keep
12
+ end
13
+
14
+ attr_reader :operation
15
+ attr_reader :encoding
16
+
17
+ # Initialize a new conversion object from an encoding and tell it whether to convert from it or to it
18
+ #
19
+ # @param [String] encoding Encoding to convert to/from
20
+ # @param [Symbol] operation Whether to convert from that encoding or to it
21
+ def initialize( encoding = DEFAULT_TARGET_ENCODING, operation = Operation::KEEP )
22
+ @encoding = encoding
23
+ @operation = operation
24
+ end
25
+
26
+ # Check if two conversions are representing the same operation.
27
+ #
28
+ # @param [EncodingEstimator::Conversion] other Conversion to compare this instance to
29
+ # @return [Boolean] True if equal, false if not
30
+ def equals?( other )
31
+
32
+ # Not the same encoding? Cannot be equal
33
+ return false if other.encoding.to_s != self.encoding.to_s
34
+
35
+ # If the default and the target encoding is the same, the operation doesn't matter
36
+ # as the conversion does nothing at all
37
+ return true if self.encoding.to_s == DEFAULT_TARGET_ENCODING.to_s
38
+
39
+ # Not the default encoding, so check if the operation is the same
40
+ self.operation == other.operation
41
+ end
42
+
43
+ # Perform the conversion with the current settings on a given string
44
+ #
45
+ # @param [String] data String to encode/decode
46
+ # @return [String] The encoded/decoded string
47
+ def perform( data )
48
+ return encode( data, encoding ) if operation == Operation::ENCODE
49
+ return decode( data, encoding ) if operation == Operation::DECODE
50
+ data
51
+ end
52
+
53
+ # Get the internal name (unique key) for this conversion. Useful when storing/referencing conversions
54
+ # in hashes.
55
+ #
56
+ # @return [String] Unique key of this conversion
57
+ def key
58
+ @key ||= "#{operation}_#{encoding}"
59
+ end
60
+
61
+ # Generate all conversions of for given encodings and operations. Note: this will produce
62
+ # #encodings * #operations conversions if default is not included and #encoding * #operations + 1
63
+ # if the default is included.
64
+ #
65
+ # @param [Array<String>] encodings Names of the encodings to generate conversions for
66
+ # @param [Array<Symbol>] operations Operations describing which conversions (encode/decode/keep) to include
67
+ # @param [Boolean] include_no_change Include the default conversion (keep UTF-8) in the list
68
+ # @return [Array<Conversion>] List of conversions generated from the encodings and operations
69
+ def self.generate(
70
+ encodings = %w(utf-8 iso-8859-1 Windows-1251),
71
+ operations = [Operation::ENCODE, Operation::DECODE ],
72
+ include_no_change = true
73
+ )
74
+
75
+ conversions = include_no_change ? [ Conversion.new ] : []
76
+
77
+ encodings.each do |encoding|
78
+ conversions = conversions + operations.map { |operation| Conversion.new( encoding, operation ) }
79
+ end
80
+
81
+ conversions
82
+ end
83
+
84
+ private
85
+
86
+ # Encode a given string from the default (UTF-8) to a given encoding.
87
+ #
88
+ # @param [String] str String to encode
89
+ # @param [String] encoding Name of the encoding used to encode the string
90
+ # @return [String] The encoded string
91
+ def encode( str, encoding )
92
+ str.clone.force_encoding( DEFAULT_TARGET_ENCODING.to_s ).encode(
93
+ encoding, invalid: :replace, undef: :replace, replace: ''
94
+ ).force_encoding( DEFAULT_TARGET_ENCODING.to_s )
95
+ end
96
+
97
+ # Decode a given string from a given encoding to the default (UTF-8).
98
+ #
99
+ # @param [String] str String to decode
100
+ # @param [String] encoding Name of the encoding used to decode the string
101
+ # @return [String] The decoded string
102
+ def decode( str, encoding )
103
+ str.clone.force_encoding( encoding ).encode(
104
+ DEFAULT_TARGET_ENCODING.to_s, invalid: :replace, undef: :replace, replace: ''
105
+ )
106
+ end
107
+ end
108
+ end