<commit_before><commit_msg>Add first cut at model loader<commit_after>package org.krugler.yalder;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.krugler.yalder.hash.HashLanguageModel;
import org.krugler.yalder.text.TextLanguageModel;

public class ModelLoader {

    public static Collection<BaseLanguageModel> loadModelsFromResources() {
        // TODO use language-detector code to find/load resources
        return null;
    }
    
    public static Collection<BaseLanguageModel> loadModelsFromDirectory(File dirFile, boolean isBinary) throws IOException {
        Set<BaseLanguageModel> result = new HashSet<>();
        
        String modelSuffix = isBinary ? "bin" : "txt";
        for (File file : FileUtils.listFiles(dirFile, new String[]{modelSuffix}, true)) {
            String filename = file.getName();
            Pattern p = Pattern.compile(String.format("yalder_model_(.+).%s", modelSuffix));
            Matcher m = p.matcher(filename);
            if (!m.matches()) {
                continue;
            }

            // Verify that language is valid
            LanguageLocale.fromString(m.group(1));
            
            if (isBinary) {
                try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
                    HashLanguageModel binaryModel = new HashLanguageModel();
                    binaryModel.readAsBinary(dis);
                    result.add(binaryModel);
                } 
            } else {
                try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8")) {
                    TextLanguageModel textModel = new TextLanguageModel();
                    textModel.readAsText(isr);
                    result.add(textModel);
                }
            }
        }

        return result;
    }
}
{'fraction_non_alphanumeric': 0.09663666508763619, 'fraction_numerical': 0.0009474182851729038, 'mean_word_length': 2.310344827586207, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, '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': '4259915', 'n_tokens_mistral': 553, 'n_tokens_neox': 540, 'n_words': 123}