models.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. #!/usr/bin/env node
  2. /* eslint "no-console": off */
  3. const fs = require('fs');
  4. const path = require('path');
  5. const process = require('process');
  6. const util = require('util');
  7. // const json = require('../source/json');
  8. const protobuf = require('../source/protobuf');
  9. const flatbuffers = require('../source/flatbuffers');
  10. const sidebar = require('../source/view-sidebar.js');
  11. const view = require('../source/view.js');
  12. const zip = require('../source/zip');
  13. const gzip = require('../source/gzip');
  14. const tar = require('../source/tar');
  15. const base = require('../source/base');
  16. global.Int64 = base.Int64;
  17. global.Uint64 = base.Uint64;
  18. // global.json = json;
  19. global.protobuf = protobuf;
  20. global.flatbuffers = flatbuffers;
  21. global.TextDecoder = class {
  22. constructor(encoding) {
  23. if (encoding !== 'ascii') {
  24. this._decoder = new util.TextDecoder(encoding);
  25. }
  26. }
  27. decode(data) {
  28. if (this._decoder) {
  29. return this._decoder.decode(data);
  30. }
  31. if (data.length < 32) {
  32. return String.fromCharCode.apply(null, data);
  33. }
  34. const buffer = [];
  35. let start = 0;
  36. do {
  37. let end = start + 32;
  38. if (end > data.length) {
  39. end = data.length;
  40. }
  41. buffer.push(String.fromCharCode.apply(null, data.subarray(start, end)));
  42. start = end;
  43. }
  44. while (start < data.length);
  45. return buffer.join('');
  46. }
  47. };
  48. const filter = process.argv.length > 2 ? new RegExp('^' + process.argv[2].replace(/\./, '\\.').replace(/\*/, '.*')) : null;
  49. const dataFolder = path.normalize(__dirname + '/../third_party/test');
  50. const items = JSON.parse(fs.readFileSync(__dirname + '/models.json', 'utf-8'));
  51. class TestHost {
  52. constructor() {
  53. this._document = new HTMLDocument();
  54. }
  55. get document() {
  56. return this._document;
  57. }
  58. initialize(/* view */) {
  59. return Promise.resolve();
  60. }
  61. start() {
  62. }
  63. environment(name) {
  64. if (name == 'zoom') {
  65. return 'none';
  66. }
  67. return null;
  68. }
  69. screen(/* name */) {
  70. }
  71. require(id) {
  72. try {
  73. const file = path.join(path.join(__dirname, '../source'), id + '.js');
  74. return Promise.resolve(require(file));
  75. }
  76. catch (error) {
  77. return Promise.reject(error);
  78. }
  79. }
  80. request(file, encoding, base) {
  81. const pathname = path.join(base || path.join(__dirname, '../source'), file);
  82. if (!fs.existsSync(pathname)) {
  83. return Promise.reject(new Error("The file '" + file + "' does not exist."));
  84. }
  85. if (encoding) {
  86. const content = fs.readFileSync(pathname, encoding);
  87. return Promise.resolve(content);
  88. }
  89. const buffer = fs.readFileSync(pathname, null);
  90. const stream = new TestBinaryStream(buffer);
  91. return Promise.resolve(stream);
  92. }
  93. event(/* category, action, label, value */) {
  94. }
  95. exception(err /*, fatal */) {
  96. this._raise('exception', { exception: err });
  97. }
  98. on(event, callback) {
  99. this._events = this._events || {};
  100. this._events[event] = this._events[event] || [];
  101. this._events[event].push(callback);
  102. }
  103. _raise(event, data) {
  104. if (this._events && this._events[event]) {
  105. for (const callback of this._events[event]) {
  106. callback(this, data);
  107. }
  108. }
  109. }
  110. }
  111. class TestBinaryStream {
  112. constructor(buffer) {
  113. this._buffer = buffer;
  114. this._length = buffer.length;
  115. this._position = 0;
  116. }
  117. get position() {
  118. return this._position;
  119. }
  120. get length() {
  121. return this._length;
  122. }
  123. stream(length) {
  124. const buffer = this.read(length);
  125. return new TestBinaryStream(buffer.slice(0));
  126. }
  127. seek(position) {
  128. this._position = position >= 0 ? position : this._length + position;
  129. if (this._position > this._buffer.length) {
  130. throw new Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  131. }
  132. }
  133. skip(offset) {
  134. this._position += offset;
  135. if (this._position > this._buffer.length) {
  136. throw new Error('Expected ' + (this._position - this._buffer.length) + ' more bytes. The file might be corrupted. Unexpected end of file.');
  137. }
  138. }
  139. peek(length) {
  140. if (this._position === 0 && length === undefined) {
  141. return this._buffer;
  142. }
  143. const position = this._position;
  144. this.skip(length !== undefined ? length : this._length - this._position);
  145. const end = this._position;
  146. this.seek(position);
  147. return this._buffer.subarray(position, end);
  148. }
  149. read(length) {
  150. if (this._position === 0 && length === undefined) {
  151. this._position = this._length;
  152. return this._buffer;
  153. }
  154. const position = this._position;
  155. this.skip(length !== undefined ? length : this._length - this._position);
  156. return this._buffer.subarray(position, this._position);
  157. }
  158. byte() {
  159. const position = this._position;
  160. this.skip(1);
  161. return this._buffer[position];
  162. }
  163. }
  164. class TestContext {
  165. constructor(host, folder, identifier, stream, entries) {
  166. this._host = host;
  167. this._folder = folder;
  168. this._identifier = identifier;
  169. this._stream = stream;
  170. this._entries = entries;
  171. }
  172. get identifier() {
  173. return this._identifier;
  174. }
  175. get stream() {
  176. return this._stream;
  177. }
  178. get entries() {
  179. return this._entries;
  180. }
  181. request(file, encoding, base) {
  182. return this._host.request(file, encoding, base === undefined ? this._folder : base);
  183. }
  184. require(id) {
  185. return this._host.require(id);
  186. }
  187. exception(error, fatal) {
  188. this._host.exception(error, fatal);
  189. }
  190. }
  191. class HTMLDocument {
  192. constructor() {
  193. this._elements = {};
  194. this.documentElement = new HTMLHtmlElement();
  195. this.body = new HTMLBodyElement();
  196. }
  197. createElement(/* name */) {
  198. return new HTMLElement();
  199. }
  200. createElementNS(/* namespace, name */) {
  201. return new HTMLElement();
  202. }
  203. createTextNode(/* text */) {
  204. return new HTMLElement();
  205. }
  206. getElementById(id) {
  207. let element = this._elements[id];
  208. if (!element) {
  209. element = new HTMLElement();
  210. this._elements[id] = element;
  211. }
  212. return element;
  213. }
  214. addEventListener(/* event, callback */) {
  215. }
  216. removeEventListener(/* event, callback */) {
  217. }
  218. }
  219. class HTMLElement {
  220. constructor() {
  221. this._childNodes = [];
  222. this._attributes = new Map();
  223. this._style = new CSSStyleDeclaration();
  224. }
  225. get style() {
  226. return this._style;
  227. }
  228. appendChild(node) {
  229. this._childNodes.push(node);
  230. }
  231. setAttribute(name, value) {
  232. this._attributes.set(name, value);
  233. }
  234. hasAttribute(name) {
  235. return this._attributes.has(name);
  236. }
  237. getAttribute(name) {
  238. return this._attributes.get(name);
  239. }
  240. getElementsByClassName(name) {
  241. const elements = [];
  242. for (const node of this._childNodes) {
  243. if (node instanceof HTMLElement) {
  244. elements.push(...node.getElementsByClassName(name));
  245. if (node.hasAttribute('class') &&
  246. node.getAttribute('class').split(' ').find((text) => text === name)) {
  247. elements.push(node);
  248. }
  249. }
  250. }
  251. return elements;
  252. }
  253. addEventListener(/* event, callback */) {
  254. }
  255. removeEventListener(/* event, callback */) {
  256. }
  257. get classList() {
  258. return new DOMTokenList(this);
  259. }
  260. getBBox() {
  261. return { x: 0, y: 0, width: 10, height: 10 };
  262. }
  263. getBoundingClientRect() {
  264. return { left: 0, top: 0, wigth: 0, height: 0 };
  265. }
  266. scrollTo() {
  267. }
  268. focus() {
  269. }
  270. }
  271. class HTMLHtmlElement extends HTMLElement {
  272. }
  273. class HTMLBodyElement extends HTMLElement{
  274. }
  275. class CSSStyleDeclaration {
  276. constructor() {
  277. this._properties = new Map();
  278. }
  279. setProperty(name, value) {
  280. this._properties.set(name, value);
  281. }
  282. }
  283. class DOMTokenList {
  284. add(/* token */) {
  285. }
  286. }
  287. const clearLine = () => {
  288. if (process.stdout.clearLine) {
  289. process.stdout.clearLine();
  290. }
  291. };
  292. const decompress = (buffer) => {
  293. let archive = null;
  294. if (buffer.length >= 18 && buffer[0] === 0x1f && buffer[1] === 0x8b) {
  295. archive = gzip.Archive.open(buffer);
  296. if (archive.entries.size == 1) {
  297. const stream = archive.entries.values().next().value;
  298. buffer = stream.peek();
  299. }
  300. }
  301. const formats = [ zip, tar ];
  302. for (const module of formats) {
  303. archive = module.Archive.open(buffer);
  304. if (archive) {
  305. break;
  306. }
  307. }
  308. return archive;
  309. };
  310. const request = (location, cookie) => {
  311. const options = { rejectUnauthorized: false };
  312. const url = new URL(location);
  313. const protocol = url.protocol === 'https:' ? require('https') : require('http');
  314. const request = protocol.request(location, options);
  315. return new Promise((resolve, reject) => {
  316. if (cookie && cookie.length > 0) {
  317. request.setHeader('Cookie', cookie);
  318. }
  319. request.on('response', (response) => {
  320. resolve(response);
  321. });
  322. request.on('error', (error) => {
  323. reject(error);
  324. });
  325. request.end();
  326. });
  327. };
  328. const downloadFile = (location, cookie) => {
  329. return request(location, cookie).then((response) => {
  330. const url = new URL(location);
  331. if (response.statusCode == 200 &&
  332. url.hostname == 'drive.google.com' &&
  333. response.headers['set-cookie'].some((cookie) => cookie.startsWith('download_warning_'))) {
  334. cookie = response.headers['set-cookie'];
  335. const download = cookie.filter((cookie) => cookie.startsWith('download_warning_')).shift();
  336. const confirm = download.split(';').shift().split('=').pop();
  337. location = location + '&confirm=' + confirm;
  338. return downloadFile(location, cookie);
  339. }
  340. if (response.statusCode == 301 || response.statusCode == 302) {
  341. if (response.headers.location.startsWith('http://') || response.headers.location.startsWith('https://')) {
  342. location = response.headers.location;
  343. }
  344. else {
  345. location = url.protocol + '//' + url.hostname + response.headers.location;
  346. }
  347. return downloadFile(location, cookie);
  348. }
  349. if (response.statusCode != 200) {
  350. throw new Error(response.statusCode.toString() + ' ' + location);
  351. }
  352. return new Promise((resolve, reject) => {
  353. let position = 0;
  354. const data = [];
  355. const length = response.headers['content-length'] ? Number(response.headers['content-length']) : -1;
  356. response.on('data', (chunk) => {
  357. position += chunk.length;
  358. if (length >= 0) {
  359. const label = location.length > 70 ? location.substring(0, 66) + '...' : location;
  360. process.stdout.write(' (' + (' ' + Math.floor(100 * (position / length))).slice(-3) + '%) ' + label + '\r');
  361. }
  362. else {
  363. process.stdout.write(' ' + position + ' bytes\r');
  364. }
  365. data.push(chunk);
  366. });
  367. response.on('end', () => {
  368. resolve(Buffer.concat(data));
  369. });
  370. response.on('error', (error) => {
  371. reject(error);
  372. });
  373. });
  374. });
  375. };
  376. const download = (folder, targets, sources) => {
  377. if (targets.every((file) => fs.existsSync(folder + '/' + file))) {
  378. return Promise.resolve();
  379. }
  380. if (!sources) {
  381. return Promise.reject(new Error('Download source not specified.'));
  382. }
  383. let source = '';
  384. let sourceFiles = [];
  385. const startIndex = sources.indexOf('[');
  386. const endIndex = sources.indexOf(']');
  387. if (startIndex != -1 && endIndex != -1 && endIndex > startIndex) {
  388. sourceFiles = sources.substring(startIndex + 1, endIndex).split(',').map((sourceFile) => sourceFile.trim());
  389. source = sources.substring(0, startIndex);
  390. sources = sources.substring(endIndex + 1);
  391. if (sources.startsWith(',')) {
  392. sources = sources.substring(1);
  393. }
  394. }
  395. else {
  396. const commaIndex = sources.indexOf(',');
  397. if (commaIndex != -1) {
  398. source = sources.substring(0, commaIndex);
  399. sources = sources.substring(commaIndex + 1);
  400. }
  401. else {
  402. source = sources;
  403. sources = '';
  404. }
  405. }
  406. for (const target of targets) {
  407. const dir = path.dirname(folder + '/' + target);
  408. fs.existsSync(dir) || fs.mkdirSync(dir, { recursive: true });
  409. }
  410. return downloadFile(source).then((data) => {
  411. if (sourceFiles.length > 0) {
  412. clearLine();
  413. process.stdout.write(' decompress...\r');
  414. const archive = decompress(data, source.split('?').shift().split('/').pop());
  415. clearLine();
  416. for (const name of sourceFiles) {
  417. process.stdout.write(' write ' + name + '\r');
  418. if (name !== '.') {
  419. const stream = archive.entries.get(name);
  420. if (!stream) {
  421. throw new Error("Entry not found '" + name + '. Archive contains entries: ' + JSON.stringify(Array.from(archive.entries.keys())) + " .");
  422. }
  423. const target = targets.shift();
  424. const buffer = stream.peek();
  425. const file = path.join(folder, target);
  426. fs.writeFileSync(file, buffer, null);
  427. }
  428. else {
  429. const target = targets.shift();
  430. const dir = path.join(folder, target);
  431. if (!fs.existsSync(dir)) {
  432. fs.mkdirSync(dir);
  433. }
  434. }
  435. clearLine();
  436. }
  437. }
  438. else {
  439. const target = targets.shift();
  440. clearLine();
  441. process.stdout.write(' write ' + target + '\r');
  442. fs.writeFileSync(folder + '/' + target, data, null);
  443. }
  444. clearLine();
  445. if (sources.length > 0) {
  446. return download(folder, targets, sources);
  447. }
  448. return;
  449. });
  450. };
  451. const loadModel = (target, item) => {
  452. const host = new TestHost();
  453. const exceptions = [];
  454. host.on('exception', (_, data) => {
  455. exceptions.push(data.exception);
  456. });
  457. const identifier = path.basename(target);
  458. const stat = fs.statSync(target);
  459. let context = null;
  460. if (stat.isFile()) {
  461. const buffer = fs.readFileSync(target, null);
  462. const reader = new TestBinaryStream(buffer);
  463. const dirname = path.dirname(target);
  464. context = new TestContext(host, dirname, identifier, reader);
  465. }
  466. else if (stat.isDirectory()) {
  467. const entries = new Map();
  468. const walk = (dir) => {
  469. for (const item of fs.readdirSync(dir)) {
  470. const pathname = path.join(dir, item);
  471. const stat = fs.statSync(pathname);
  472. if (stat.isDirectory()) {
  473. walk(pathname);
  474. }
  475. else if (stat.isFile()) {
  476. const buffer = fs.readFileSync(pathname, null);
  477. const stream = new TestBinaryStream(buffer);
  478. const name = pathname.split(path.sep).join(path.posix.sep);
  479. entries.set(name, stream);
  480. }
  481. }
  482. };
  483. walk(target);
  484. context = new TestContext(host, target, identifier, null, entries);
  485. }
  486. const modelFactoryService = new view.ModelFactoryService(host);
  487. let opened = false;
  488. return modelFactoryService.open(context).then((model) => {
  489. if (opened) {
  490. throw new Error("Model opened more than once '" + target + "'.");
  491. }
  492. opened = true;
  493. if (!model.format || (item.format && model.format != item.format)) {
  494. throw new Error("Invalid model format '" + model.format + "'.");
  495. }
  496. if (item.producer && model.producer != item.producer) {
  497. throw new Error("Invalid producer '" + model.producer + "'.");
  498. }
  499. if (item.runtime && model.runtime != item.runtime) {
  500. throw new Error("Invalid runtime '" + model.runtime + "'.");
  501. }
  502. if (item.assert) {
  503. for (const assert of item.assert) {
  504. const parts = assert.split('=').map((item) => item.trim());
  505. const properties = parts[0].split('.');
  506. const value = parts[1];
  507. let context = { model: model };
  508. while (properties.length) {
  509. const property = properties.shift();
  510. if (context[property] !== undefined) {
  511. context = context[property];
  512. continue;
  513. }
  514. const match = /(.*)\[(.*)\]/.exec(property);
  515. if (match.length === 3 && context[match[1]] !== undefined) {
  516. const array = context[match[1]];
  517. const index = parseInt(match[2], 10);
  518. if (array[index] !== undefined) {
  519. context = array[index];
  520. continue;
  521. }
  522. }
  523. throw new Error("Invalid property path: '" + parts[0]);
  524. }
  525. if (context !== value.toString()) {
  526. throw new Error("Invalid '" + value.toString() + "' != '" + assert + "'.");
  527. }
  528. }
  529. }
  530. model.version;
  531. model.description;
  532. model.author;
  533. model.license;
  534. for (const graph of model.graphs) {
  535. for (const input of graph.inputs) {
  536. input.name.toString();
  537. input.name.length;
  538. for (const argument of input.arguments) {
  539. argument.name.toString();
  540. argument.name.length;
  541. if (argument.type) {
  542. argument.type.toString();
  543. }
  544. argument.quantization;
  545. argument.initializer;
  546. }
  547. }
  548. for (const output of graph.outputs) {
  549. output.name.toString();
  550. output.name.length;
  551. for (const argument of output.arguments) {
  552. argument.name.toString();
  553. argument.name.length;
  554. if (argument.type) {
  555. argument.type.toString();
  556. }
  557. }
  558. }
  559. for (const node of graph.nodes) {
  560. node.type.toString();
  561. node.type.length;
  562. if (!node.type || typeof node.type.name != 'string') {
  563. throw new Error("Invalid node type '" + JSON.stringify(node.type) + "'.");
  564. }
  565. sidebar.DocumentationSidebar.formatDocumentation(node.type);
  566. node.name.toString();
  567. node.name.length;
  568. node.description;
  569. node.attributes.slice();
  570. for (const attribute of node.attributes) {
  571. attribute.name.toString();
  572. attribute.name.length;
  573. let value = sidebar.NodeSidebar.formatAttributeValue(attribute.value, attribute.type);
  574. if (value && value.length > 1000) {
  575. value = value.substring(0, 1000) + '...';
  576. }
  577. value = value.split('<');
  578. }
  579. for (const input of node.inputs) {
  580. input.name.toString();
  581. input.name.length;
  582. for (const argument of input.arguments) {
  583. argument.name.toString();
  584. argument.name.length;
  585. argument.description;
  586. if (argument.type) {
  587. argument.type.toString();
  588. }
  589. if (argument.initializer) {
  590. argument.initializer.toString();
  591. argument.initializer.type.toString();
  592. /*
  593. const python = require('../source/python');
  594. const tensor = argument.initializer;
  595. if (tensor.type && tensor.type.dataType !== '?') {
  596. let data_type = tensor.type.dataType;
  597. switch (data_type) {
  598. case 'boolean': data_type = 'bool'; break;
  599. }
  600. const execution = new python.Execution(null);
  601. const bytes = execution.invoke('io.BytesIO', []);
  602. const dtype = execution.invoke('numpy.dtype', [ data_type ]);
  603. const array = execution.invoke('numpy.asarray', [ tensor.value, dtype ]);
  604. execution.invoke('numpy.save', [ bytes, array ]);
  605. }
  606. */
  607. }
  608. }
  609. }
  610. for (const output of node.outputs) {
  611. output.name.toString();
  612. output.name.length;
  613. for (const argument of output.arguments) {
  614. argument.name.toString();
  615. argument.name.length;
  616. if (argument.type) {
  617. argument.type.toString();
  618. }
  619. }
  620. }
  621. if (node.chain) {
  622. for (const chain of node.chain) {
  623. chain.name.toString();
  624. chain.name.length;
  625. }
  626. }
  627. // new sidebar.NodeSidebar(host, node);
  628. }
  629. }
  630. if (exceptions.length > 0) {
  631. throw exceptions[0];
  632. }
  633. return model;
  634. });
  635. };
  636. const renderModel = (model, item) => {
  637. if (item.actions.has('skip-render')) {
  638. return Promise.resolve();
  639. }
  640. try {
  641. const host = new TestHost();
  642. const currentView = new view.View(host);
  643. currentView.options.attributes = true;
  644. currentView.options.initializers = true;
  645. return currentView.renderGraph(model, model.graphs[0]);
  646. }
  647. catch (error) {
  648. return Promise.reject(error);
  649. }
  650. };
  651. const next = () => {
  652. if (items.length == 0) {
  653. return;
  654. }
  655. const item = items.shift();
  656. if (!item.type) {
  657. console.error("Property 'type' is required for item '" + JSON.stringify(item) + "'.");
  658. return;
  659. }
  660. const targets = item.target.split(',');
  661. const target = targets[0];
  662. const folder = dataFolder + '/' + item.type;
  663. const name = item.type + '/' + target;
  664. if (filter && !filter.test(name)) {
  665. next();
  666. return;
  667. }
  668. process.stdout.write(item.type + '/' + target + '\n');
  669. item.actions = new Set((item.action || '').split(';'));
  670. if (item.actions.has('skip')) {
  671. next();
  672. return;
  673. }
  674. clearLine();
  675. const sources = item.source;
  676. return download(folder, targets, sources).then(() => {
  677. return loadModel(folder + '/' + target, item).then((model) => {
  678. return renderModel(model, item).then(() => {
  679. if (item.error) {
  680. console.error('Expected error.');
  681. }
  682. else {
  683. return next();
  684. }
  685. });
  686. });
  687. }).catch((error) => {
  688. if (!item.error || item.error != error.message) {
  689. console.error(error.message);
  690. }
  691. else {
  692. return next();
  693. }
  694. });
  695. };
  696. next();