aboutsummaryrefslogtreecommitdiffstats
path: root/model-integration/src/main/java/ai/vespa/rankingexpression/importer/configmodelview/ImportedMlModels.java
blob: c97e47818891fb5d2233d5ae9f8897e620768ce1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.rankingexpression.importer.configmodelview;

import com.yahoo.path.Path;
import com.yahoo.yolean.Exceptions;

import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.regex.Pattern;

/**
 * All models imported from the models/ directory in the application package.
 * If this is empty it may be due to either not having any models in the application package,
 * or this being created for a ZooKeeper application package, which does not have imported models.
 *
 * @author bratseth
 */
public class ImportedMlModels {

    /** All imported models, indexed by their names */
    private final Map<String, ImportedMlModel> importedModels;

    /** Models that were not imported due to some error */
    private final Map<String, String> skippedModels = new ConcurrentHashMap<>();

    /** Create a null imported models */
    public ImportedMlModels() {
        importedModels = Collections.emptyMap();
    }

    public ImportedMlModels(File modelsDirectory, ExecutorService executor, Collection<MlModelImporter> importers) {
        Map<String, Future<ImportedMlModel>> futureModels = new HashMap<>();

        // Find all subdirectories recursively which contains a model we can read
        importRecursively(modelsDirectory, executor, futureModels, importers, skippedModels);
        Map<String, ImportedMlModel> models = new HashMap<>();
        futureModels.forEach((name, future) -> {
            try {
                ImportedMlModel model = future.get();
                if (model != null) {
                    models.put(name, model);
                }
            } catch (InterruptedException | ExecutionException e) {
                skippedModels.put(name, Exceptions.toMessageString(e));
            }
        });
        importedModels = Collections.unmodifiableMap(models);
    }

    /**
     * Returns the model at the given location in the application package.
     *
     * @param modelPath the path to this model (file or directory, depending on model type)
     *                  under the application package, both from the root or relative to the
     *                  models directory works
     * @return the model at this path or null if none
     */
    public ImportedMlModel get(File modelPath) {
        return importedModels.get(toName(modelPath));
    }

    /** Returns an immutable collection of all the imported models */
    public Collection<ImportedMlModel> all() {
        return importedModels.values();
    }

    public Map<String, String> getSkippedModels() {
        return skippedModels;
    }

    private static void importRecursively(File dir,
                                          ExecutorService executor,
                                          Map<String, Future<ImportedMlModel>> models,
                                          Collection<MlModelImporter> importers,
                                          Map<String, String> skippedModels) {
        if ( ! dir.isDirectory()) return;

        Arrays.stream(dir.listFiles()).sorted().forEach(child -> {
            Optional<MlModelImporter> importer = findImporterOf(child, importers);
            if (importer.isPresent()) {
                validateModelPath(child);
                String name = toName(child);
                Future<ImportedMlModel> existing = models.get(name);
                if (existing != null) {
                    try {
                        throw new IllegalArgumentException("The models in " + child + " and " + existing.get().source() +
                                                           " both resolve to the model name '" + name + "'");
                    } catch (InterruptedException | ExecutionException e) {}
                }

                Future<ImportedMlModel> future = executor.submit(() -> {
                    try {
                        return importer.get().importModel(name, child);
                    } catch (RuntimeException e) {
                        skippedModels.put(name, e.getMessage());
                    }
                    return null;
                });
                models.put(name, future);
            }
            else {
                importRecursively(child, executor, models, importers, skippedModels);
            }
        });
    }

    private static Optional<MlModelImporter> findImporterOf(File path, Collection<MlModelImporter> importers) {
        return importers.stream().filter(item -> item.canImport(path.toString())).findFirst();
    }

    private static String toName(File modelFile) {
        Path modelPath = Path.fromString(modelFile.toString());
        if (modelFile.isFile())
            modelPath = stripFileEnding(modelPath);
        String localPath = concatenateAfterModelsDirectory(modelPath);
        return localPath.replace('.', '_');
    }

    private static Path stripFileEnding(Path path) {
        int dotIndex = path.last().lastIndexOf(".");
        if (dotIndex <= 0) return path;
        return path.withLast(path.last().substring(0, dotIndex));
    }

    private static String concatenateAfterModelsDirectory(Path path) {
        boolean afterModels = false;
        StringBuilder result = new StringBuilder();
        for (String element : path.elements()) {
            if (afterModels) result.append(element).append("_");
            if (element.equals("models")) afterModels = true;
        }
        return result.substring(0, result.length()-1);
    }

    private static void validateModelPath(File modelFile) {
        Pattern nameRegexp = Pattern.compile("[A-Za-z0-9_.]*");

        Path path = Path.fromString(modelFile.toString());
        if (modelFile.isFile())
            path = stripFileEnding(path);

        boolean afterModels = false;
        for (String element : path.elements()) {
            if (afterModels) {
                if ( ! nameRegexp.matcher(element).matches()) {
                    throw new IllegalArgumentException("When Vespa imports a model from the 'models' directory, it " +
                                                       "uses the directory structure under 'models' to determine the " +
                                                       "name of the model. The directory or file name '" + element + "' " +
                                                       "is not valid. Please rename this to only contain letters, " +
                                                       "numbers or underscores.");
                }
            } else if (element.equals("models")) {
                afterModels = true;
            }
        }
    }

}