<commit_before>require 'csv'

class SuppliersPlugin::Import

  def self.to_utf8 string
    if string.encoding == Encoding::ASCII_8BIT
      string.force_encoding 'utf-8'
    else
      string.encode!('utf-8')
    end
    string
  end

  def self.products consumer, csv
    #i = Iconv.new 'UTF-8//IGNORE', 'UTF-8'
    product_category = consumer.environment.product_categories.find_by_name 'Produtos'

    data = {}
    header = []
    rows = []
    [",", ";", "\t"].each do |sep|
      rows = CSV.parse csv, :col_sep => sep
      header = rows.shift
      break if header.size == 4
    end
    raise 'invalid number of columns' unless header.size == 4

    rows.each do |row|
      supplier_name = to_utf8 row[0].to_s.squish
      product_name = to_utf8 row[1].to_s.squish
      product_unit = to_utf8 row[2].to_s.squish
      product_price = to_utf8 row[3].to_s.squish
<commit_msg>suppliers: convert encoding on import<commit_after>require 'csv'
require 'charlock_holmes'

class SuppliersPlugin::Import

  def self.to_utf8 string
    if string.encoding == Encoding::ASCII_8BIT
      string.force_encoding 'utf-8'
    else
      string.encode!('utf-8')
    end
    string
  end

  def self.products consumer, csv
    product_category = consumer.environment.product_categories.find_by_name 'Produtos'

    detection = CharlockHolmes::EncodingDetector.detect(csv)
    csv = CharlockHolmes::Converter.convert csv, detection[:encoding], 'UTF-8'
    data = {}
    header = []
    rows = []
    [",", ";", "\t"].each do |sep|
      rows = CSV.parse csv, :col_sep => sep
      header = rows.shift
      break if header.size == 4
    end
    raise 'invalid number of columns' unless header.size == 4

    rows.each do |row|
      supplier_name = to_utf8 row[0].to_s.squish
      product_name = to_utf8 row[1].to_s.squish
      product_unit = to_utf8 row[2].to_s.squish
      product_price = to_utf8 row[3].to_s.squish

{'fraction_non_alphanumeric': 0.11780104712041885, 'fraction_numerical': 0.016230366492146597, 'mean_word_length': 2.9402061855670105, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2883504', 'n_tokens_mistral': 673, 'n_tokens_neox': 645, 'n_words': 147}