loader.es6 7.3 KB
Newer Older
W
wangqun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* eslint-disable */
/**
 * @file loader,model加载器
 * @author wangqun@baidu.com
 */

export default class Loader  {
    constructor(modelGonfig, options) {
        this.version  = '0.0.1';
        this.data = {};
        this.modelGonfig = modelGonfig;
        this.options = options;
        this.multipart = false;
        this.test = false;
15
        this.chunkNum = 0;
W
wangqun 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
        // fetch xhr jsonp
        this.params = {type: 'fetch'};
        // 设置分片加载model
        if (this.options) {
            this.multipart = this.options.multipart;
            if (options.dataType === 'binary') {
                this.binaryOption = options.options;
                this.dataType = options.dataType;
            }
            if (options.test) {
                this.test = true;
            }
        }

        if (!this.loadOptions) {
            this.loadOptions = {};
        }
W
wangqun 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
        else {
            // this.fetchJson(this.modelGonfig.dir + 'x.json').then(data => {
            //     const [b, c, h, w] = [1, 3, 320, 320];
            //     const size = data.length;
            //     const total = 3 * 320 * 320;
            //     this.testData = new Float32Array(total);
            //     for (let i = 0; i < size; i++) {
            //         let j = i / (c * w) | 0;
            //         let k = i % (c * w);
            //         let b1 = j / h | 0;
            //         let h1 = j % h;
            //         let c1 = k % c;
            //         let w1 = k / c | 0;
            //         let l = b1 * (c * h * w) + c1 * (h * w) + h1 * (w) + w1;
            //         this.testData[i] = data[l];
            //     }
            // });
        }
W
wangqun 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    }

    fetchOneChunk(path) {
        return this.fetch(path).then(request => {
            return request.arrayBuffer();
        })
    }

    fetchJson(path) {
        return this.fetch(path).then(request => {
            return request.json();
        })
    }

    fetchChunks() {
66
        let counts = this.chunkNum || this.binaryOption.fileCount;
W
wangqun 已提交
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
        let chunkArray = [];
        for (let i = 1; i <= counts; i++) {
            chunkArray.push(
                this.fetchOneChunk(this.modelGonfig.dir + this.binaryOption.getFileName(i))
            );
        }
        // console.time('加载时间');
        return Promise.all(chunkArray).then(chunks => {
            // console.timeEnd('加载时间');
            let chunksLength = 0;
            let f32Array = [];
            let float32Chunk;
            chunks.forEach(i => {
                float32Chunk = new Float32Array(i);
                f32Array.push(float32Chunk);
                chunksLength += float32Chunk.length;
            });
            this.allData = new Float32Array(chunksLength);
            let offset = 0;
            f32Array.forEach(i => {
                i.forEach(num => {
                    this.allData[offset] = num;
                    offset += 1;
                })
            });
        });
    }

    fetchData(name) {
        const path = this.modelGonfig.dir + name + '.json';
        let load = new Promise((resolve, reject) => {
            fetch(path, {
                method: 'get', mode: 'cors', credentials: "include",
                headers: { 'Content-Type': 'application/json;charset=utf-8'}})
                .then(response => response.json())
                .then(responseData => resolve(responseData))
                .then(err => reject(err))
        })
        return load;
    }

108
    async fetchAllData (arr) {
W
wangqun 已提交
109 110 111 112
        const TMP_SCHEME_REGEX = /\.tmp/;
        const TMP_REGEX = /\-/;
        let requesterArr = arr.map(item => {
            if (item.name
113 114 115
                // && item.name.match(TMP_SCHEME_REGEX) === null
                // && item.name.match(TMP_REGEX) === null
                ) {
W
wangqun 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128
                return this.fetchData(item.name).then(data => item.data = data);
            }
            return Promise.resolve();
        });
        return Promise.all(requesterArr);
    }

    traverse (arr) {
        const TMP_SCHEME_REGEX = /\.tmp/;
        const TMP_REGEX = /\-/;
        let marker = 0; // 读到哪个位置了
        let len; // 当前op长度
        arr.filter(item => {
129 130 131
            return item.name;
                // && item.name.match(TMP_SCHEME_REGEX) === null
                // && item.name.match(TMP_REGEX) === null;
W
wangqun 已提交
132
            })
W
wangqun 已提交
133 134 135 136 137 138 139 140 141
            // .sort((a, b) => {
            //     if (a.name > b.name) {
            //         return 1;
            //     }
            //     if (a.name < b.name) {
            //         return -1;
            //     }
            //     return 0;
            // }) // 按字母顺序排列 在model.json里
W
wangqun 已提交
142 143
            .forEach(item => {
                len = item.shape.reduce((a, b) => a * b); // 长度为shape的乘积
W
wangqun 已提交
144 145 146 147 148
                // 为了减少模型体积,模型转换工具不会导出非persistable的数据,这里只需要读取persistable的数据
                if (item.persistable) {
                    item.data = this.allData.slice(marker, marker + len);
                    marker += len;
                }
W
wangqun 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
            });
    }

    fetch(path, params) {
        params = params || this.params;
        let method = params.method || 'get';
        let mode = params.mode || 'no-cors';
        let myHeaders = new Headers();
        return fetch(path, {
            method: method,
            // mode: mode,
            // credentials: 'include',
            headers: myHeaders
        });
    }

    fetchModel(params) {
        params = params || this.params;
        const path = this.modelGonfig.dir + this.modelGonfig.main;
        let load = null;
        // jsonp请求方式
        if (params && params.type === 'jsonp') {
            let json;
            let s = document.createElement('script');
            s.src = path + '&jsonpCallback=fn';
            window.fn = function(data) {
                json = data;
                // console.log(json);
            };
            //当script被插入文档中时,src中的资源就会开始加载
            document.body.appendChild(s);
            load = new Promise((resolve, reject) => {
                s.onload = function(e) {
                    resolve(json);
                }
                s.onerror = function() {
                    reject(json);
                }
            });
            this.data = load;
        }
        // 原生fetch
        else if (params.type === 'fetch') {
            load = new Promise((resolve, reject) => {
                this.fetch(path, params)
                .then(response => response.json())
                .then(responseData => resolve(responseData))
                .then(err => reject(err))
            });
            this.data = load;
        }
        // ajax
        else if (params.type === 'xhr') {
            this.data = load;
        }
        return load;
    }

    async load() {
        let that = this;
        const artifacts = this.data = await this.fetchModel();
210
        this.chunkNum =  artifacts.chunkNum;
W
wangqun 已提交
211 212 213 214 215 216
        if (this.multipart === true) {
            if (this.dataType === 'binary') {
                await this.fetchChunks()
                    .then(() => this.traverse(artifacts.vars));
            }
            else {
217
                await that.fetchAllData(artifacts.vars);
W
wangqun 已提交
218 219 220 221 222 223 224
            }
        }
        return artifacts;
    }

}
/* eslint-enable */