models.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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 ? process.argv[2].split('*') : ['', ''];
  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 url = new URL(location);
  312. const protocol = url.protocol === 'https:' ? require('https') : require('http');
  313. const request = protocol.request(location, {});
  314. return new Promise((resolve, reject) => {
  315. if (cookie && cookie.length > 0) {
  316. request.setHeader('Cookie', cookie);
  317. }
  318. request.on('response', (response) => {
  319. resolve(response);
  320. });
  321. request.on('error', (error) => {
  322. reject(error);
  323. });
  324. request.end();
  325. });
  326. };
  327. const downloadFile = (location, cookie) => {
  328. return request(location, cookie).then((response) => {
  329. const url = new URL(location);
  330. if (response.statusCode == 200 &&
  331. url.hostname == 'drive.google.com' &&
  332. response.headers['set-cookie'].some((cookie) => cookie.startsWith('download_warning_'))) {
  333. cookie = response.headers['set-cookie'];
  334. const download = cookie.filter((cookie) => cookie.startsWith('download_warning_')).shift();
  335. const confirm = download.split(';').shift().split('=').pop();
  336. location = location + '&confirm=' + confirm;
  337. return downloadFile(location, cookie);
  338. }
  339. if (response.statusCode == 301 || response.statusCode == 302) {
  340. if (response.headers.location.startsWith('http://') || response.headers.location.startsWith('https://')) {
  341. location = response.headers.location;
  342. }
  343. else {
  344. location = url.protocol + '//' + url.hostname + response.headers.location;
  345. }
  346. return downloadFile(location, cookie);
  347. }
  348. if (response.statusCode != 200) {
  349. throw new Error(response.statusCode.toString() + ' ' + location);
  350. }
  351. return new Promise((resolve, reject) => {
  352. let position = 0;
  353. const data = [];
  354. const length = response.headers['content-length'] ? Number(response.headers['content-length']) : -1;
  355. response.on('data', (chunk) => {
  356. position += chunk.length;
  357. if (length >= 0) {
  358. const label = location.length > 70 ? location.substring(0, 66) + '...' : location;
  359. process.stdout.write(' (' + (' ' + Math.floor(100 * (position / length))).slice(-3) + '%) ' + label + '\r');
  360. }
  361. else {
  362. process.stdout.write(' ' + position + ' bytes\r');
  363. }
  364. data.push(chunk);
  365. });
  366. response.on('end', () => {
  367. resolve(Buffer.concat(data));
  368. });
  369. response.on('error', (error) => {
  370. reject(error);
  371. });
  372. });
  373. });
  374. };
  375. const download = (folder, targets, sources) => {
  376. if (targets.every((file) => fs.existsSync(folder + '/' + file))) {
  377. return Promise.resolve();
  378. }
  379. if (!sources) {
  380. return Promise.reject(new Error('Download source not specified.'));
  381. }
  382. let source = '';
  383. let sourceFiles = [];
  384. const startIndex = sources.indexOf('[');
  385. const endIndex = sources.indexOf(']');
  386. if (startIndex != -1 && endIndex != -1 && endIndex > startIndex) {
  387. sourceFiles = sources.substring(startIndex + 1, endIndex).split(',').map((sourceFile) => sourceFile.trim());
  388. source = sources.substring(0, startIndex);
  389. sources = sources.substring(endIndex + 1);
  390. if (sources.startsWith(',')) {
  391. sources = sources.substring(1);
  392. }
  393. }
  394. else {
  395. const commaIndex = sources.indexOf(',');
  396. if (commaIndex != -1) {
  397. source = sources.substring(0, commaIndex);
  398. sources = sources.substring(commaIndex + 1);
  399. }
  400. else {
  401. source = sources;
  402. sources = '';
  403. }
  404. }
  405. for (const target of targets) {
  406. const dir = path.dirname(folder + '/' + target);
  407. fs.existsSync(dir) || fs.mkdirSync(dir, { recursive: true });
  408. }
  409. return downloadFile(source).then((data) => {
  410. if (sourceFiles.length > 0) {
  411. clearLine();
  412. process.stdout.write(' decompress...\r');
  413. const archive = decompress(data, source.split('?').shift().split('/').pop());
  414. clearLine();
  415. for (const name of sourceFiles) {
  416. process.stdout.write(' write ' + name + '\r');
  417. if (name !== '.') {
  418. const stream = archive.entries.get(name);
  419. if (!stream) {
  420. throw new Error("Entry not found '" + name + '. Archive contains entries: ' + JSON.stringify(Array.from(archive.entries.keys())) + " .");
  421. }
  422. const target = targets.shift();
  423. const buffer = stream.peek();
  424. const file = path.join(folder, target);
  425. fs.writeFileSync(file, buffer, null);
  426. }
  427. else {
  428. const target = targets.shift();
  429. const dir = path.join(folder, target);
  430. if (!fs.existsSync(dir)) {
  431. fs.mkdirSync(dir);
  432. }
  433. }
  434. clearLine();
  435. }
  436. }
  437. else {
  438. const target = targets.shift();
  439. clearLine();
  440. process.stdout.write(' write ' + target + '\r');
  441. fs.writeFileSync(folder + '/' + target, data, null);
  442. }
  443. clearLine();
  444. if (sources.length > 0) {
  445. return download(folder, targets, sources);
  446. }
  447. return null;
  448. });
  449. };
  450. const loadModel = (target, item) => {
  451. const host = new TestHost();
  452. const exceptions = [];
  453. host.on('exception', (_, data) => {
  454. exceptions.push(data.exception);
  455. });
  456. const identifier = path.basename(target);
  457. const stat = fs.statSync(target);
  458. let context = null;
  459. if (stat.isFile()) {
  460. const buffer = fs.readFileSync(target, null);
  461. const reader = new TestBinaryStream(buffer);
  462. const dirname = path.dirname(target);
  463. context = new TestContext(host, dirname, identifier, reader);
  464. }
  465. else if (stat.isDirectory()) {
  466. const entries = new Map();
  467. const walk = (dir) => {
  468. for (const item of fs.readdirSync(dir)) {
  469. const pathname = path.join(dir, item);
  470. const stat = fs.statSync(pathname);
  471. if (stat.isDirectory()) {
  472. walk(pathname);
  473. }
  474. else if (stat.isFile()) {
  475. const buffer = fs.readFileSync(pathname, null);
  476. const stream = new TestBinaryStream(buffer);
  477. const name = pathname.split(path.sep).join(path.posix.sep);
  478. entries.set(name, stream);
  479. }
  480. }
  481. };
  482. walk(target);
  483. context = new TestContext(host, target, identifier, null, entries);
  484. }
  485. const modelFactoryService = new view.ModelFactoryService(host);
  486. let opened = false;
  487. return modelFactoryService.open(context).then((model) => {
  488. if (opened) {
  489. throw new Error("Model opened more than once '" + target + "'.");
  490. }
  491. opened = true;
  492. if (!model.format || (item.format && model.format != item.format)) {
  493. throw new Error("Invalid model format '" + model.format + "'.");
  494. }
  495. if (item.producer && model.producer != item.producer) {
  496. throw new Error("Invalid producer '" + model.producer + "'.");
  497. }
  498. if (item.runtime && model.runtime != item.runtime) {
  499. throw new Error("Invalid runtime '" + model.runtime + "'.");
  500. }
  501. if (item.assert) {
  502. for (const assert of item.assert) {
  503. const parts = assert.split('=').map((item) => item.trim());
  504. const properties = parts[0].split('.');
  505. const value = parts[1];
  506. let context = { model: model };
  507. while (properties.length) {
  508. const property = properties.shift();
  509. if (context[property] !== undefined) {
  510. context = context[property];
  511. continue;
  512. }
  513. const match = /(.*)\[(.*)\]/.exec(property);
  514. if (match.length === 3 && context[match[1]] !== undefined) {
  515. const array = context[match[1]];
  516. const index = parseInt(match[2], 10);
  517. if (array[index] !== undefined) {
  518. context = array[index];
  519. continue;
  520. }
  521. }
  522. throw new Error("Invalid property path: '" + parts[0]);
  523. }
  524. if (context !== value.toString()) {
  525. throw new Error("Invalid '" + value.toString() + "' != '" + assert + "'.");
  526. }
  527. }
  528. }
  529. model.version;
  530. model.description;
  531. model.author;
  532. model.license;
  533. for (const graph of model.graphs) {
  534. for (const input of graph.inputs) {
  535. input.name.toString();
  536. input.name.length;
  537. for (const argument of input.arguments) {
  538. argument.name.toString();
  539. argument.name.length;
  540. if (argument.type) {
  541. argument.type.toString();
  542. }
  543. argument.quantization;
  544. argument.initializer;
  545. }
  546. }
  547. for (const output of graph.outputs) {
  548. output.name.toString();
  549. output.name.length;
  550. for (const argument of output.arguments) {
  551. argument.name.toString();
  552. argument.name.length;
  553. if (argument.type) {
  554. argument.type.toString();
  555. }
  556. }
  557. }
  558. for (const node of graph.nodes) {
  559. node.type.toString();
  560. node.type.length;
  561. if (!node.type || typeof node.type.name != 'string') {
  562. throw new Error("Invalid node type '" + JSON.stringify(node.type) + "'.");
  563. }
  564. sidebar.DocumentationSidebar.formatDocumentation(node.type);
  565. node.name.toString();
  566. node.name.length;
  567. node.description;
  568. node.attributes.slice();
  569. for (const attribute of node.attributes) {
  570. attribute.name.toString();
  571. attribute.name.length;
  572. let value = new sidebar.Formatter(attribute.value, attribute.type).toString();
  573. if (value && value.length > 1000) {
  574. value = value.substring(0, 1000) + '...';
  575. }
  576. value = value.split('<');
  577. }
  578. for (const input of node.inputs) {
  579. input.name.toString();
  580. input.name.length;
  581. for (const argument of input.arguments) {
  582. argument.name.toString();
  583. argument.name.length;
  584. argument.description;
  585. if (argument.type) {
  586. argument.type.toString();
  587. }
  588. if (argument.initializer) {
  589. argument.initializer.toString();
  590. argument.initializer.type.toString();
  591. /*
  592. const python = require('../source/python');
  593. const tensor = argument.initializer;
  594. if (tensor.type && tensor.type.dataType !== '?') {
  595. let data_type = tensor.type.dataType;
  596. switch (data_type) {
  597. case 'boolean': data_type = 'bool'; break;
  598. }
  599. const execution = new python.Execution(null);
  600. const bytes = execution.invoke('io.BytesIO', []);
  601. const dtype = execution.invoke('numpy.dtype', [ data_type ]);
  602. const array = execution.invoke('numpy.asarray', [ tensor.value, dtype ]);
  603. execution.invoke('numpy.save', [ bytes, array ]);
  604. }
  605. */
  606. }
  607. }
  608. }
  609. for (const output of node.outputs) {
  610. output.name.toString();
  611. output.name.length;
  612. for (const argument of output.arguments) {
  613. argument.name.toString();
  614. argument.name.length;
  615. if (argument.type) {
  616. argument.type.toString();
  617. }
  618. }
  619. }
  620. if (node.chain) {
  621. for (const chain of node.chain) {
  622. chain.name.toString();
  623. chain.name.length;
  624. }
  625. }
  626. // new sidebar.NodeSidebar(host, node);
  627. }
  628. }
  629. if (exceptions.length > 0) {
  630. throw exceptions[0];
  631. }
  632. return model;
  633. });
  634. };
  635. const renderModel = (model, item) => {
  636. if (item.actions.has('skip-render')) {
  637. return Promise.resolve();
  638. }
  639. try {
  640. const host = new TestHost();
  641. const currentView = new view.View(host);
  642. currentView.options.attributes = true;
  643. currentView.options.initializers = true;
  644. return currentView.renderGraph(model, model.graphs[0]);
  645. }
  646. catch (error) {
  647. return Promise.reject(error);
  648. }
  649. };
  650. const next = () => {
  651. if (items.length == 0) {
  652. return;
  653. }
  654. const item = items.shift();
  655. if (!item.type) {
  656. console.error("Property 'type' is required for item '" + JSON.stringify(item) + "'.");
  657. return;
  658. }
  659. const targets = item.target.split(',');
  660. const target = targets[0];
  661. const folder = dataFolder + '/' + item.type;
  662. const name = item.type + '/' + target;
  663. if ((filter[0] && !name.startsWith(filter[0])) || (filter[1] && !name.endsWith(filter[1]))) {
  664. next();
  665. return;
  666. }
  667. process.stdout.write(item.type + '/' + target + '\n');
  668. item.actions = new Set((item.action || '').split(';'));
  669. if (item.actions.has('skip')) {
  670. next();
  671. return;
  672. }
  673. clearLine();
  674. const sources = item.source;
  675. download(folder, targets, sources).then(() => {
  676. return loadModel(folder + '/' + target, item).then((model) => {
  677. return renderModel(model, item).then(() => {
  678. if (!item.error) {
  679. next();
  680. return;
  681. }
  682. console.error('Expected error.');
  683. });
  684. });
  685. }).catch((error) => {
  686. if (item.error && item.error == error.message) {
  687. next();
  688. return;
  689. }
  690. console.error(error.message);
  691. });
  692. };
  693. next();