Initial commit

This commit is contained in:
talksik
2021-12-29 01:57:42 -08:00
commit ce39a60b42
4634 changed files with 997667 additions and 0 deletions
+52
View File
@@ -0,0 +1,52 @@
/*! firebase-admin v10.0.1 */
/*!
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Firebase Machine Learning.
*
* @packageDocumentation
*/
import { App } from '../app';
import { MachineLearning } from './machine-learning';
export { MachineLearning, ListModelsResult, Model, TFLiteModel, } from './machine-learning';
export { AutoMLTfliteModelOptions, GcsTfliteModelOptions, ListModelsOptions, ModelOptions, ModelOptionsBase, } from './machine-learning-api-client';
/**
* Gets the {@link MachineLearning} service for the default app or a given app.
*
* `getMachineLearning()` can be called with no arguments to access the
* default app's `MachineLearning` service or as `getMachineLearning(app)` to access
* the `MachineLearning` service associated with a specific app.
*
* @example
* ```javascript
* // Get the MachineLearning service for the default app
* const defaultMachineLearning = getMachineLearning();
* ```
*
* @example
* ```javascript
* // Get the MachineLearning service for a given app
* const otherMachineLearning = getMachineLearning(otherApp);
* ```
*
* @param app - Optional app whose `MachineLearning` service to
* return. If not provided, the default `MachineLearning` service
* will be returned.
*
* @returns The default `MachineLearning` service if no app is provided or the
* `MachineLearning` service associated with the provided app.
*/
export declare function getMachineLearning(app?: App): MachineLearning;
+63
View File
@@ -0,0 +1,63 @@
/*! firebase-admin v10.0.1 */
"use strict";
/*!
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMachineLearning = void 0;
/**
* Firebase Machine Learning.
*
* @packageDocumentation
*/
var app_1 = require("../app");
var machine_learning_1 = require("./machine-learning");
var machine_learning_2 = require("./machine-learning");
Object.defineProperty(exports, "MachineLearning", { enumerable: true, get: function () { return machine_learning_2.MachineLearning; } });
Object.defineProperty(exports, "Model", { enumerable: true, get: function () { return machine_learning_2.Model; } });
/**
* Gets the {@link MachineLearning} service for the default app or a given app.
*
* `getMachineLearning()` can be called with no arguments to access the
* default app's `MachineLearning` service or as `getMachineLearning(app)` to access
* the `MachineLearning` service associated with a specific app.
*
* @example
* ```javascript
* // Get the MachineLearning service for the default app
* const defaultMachineLearning = getMachineLearning();
* ```
*
* @example
* ```javascript
* // Get the MachineLearning service for a given app
* const otherMachineLearning = getMachineLearning(otherApp);
* ```
*
* @param app - Optional app whose `MachineLearning` service to
* return. If not provided, the default `MachineLearning` service
* will be returned.
*
* @returns The default `MachineLearning` service if no app is provided or the
* `MachineLearning` service associated with the provided app.
*/
function getMachineLearning(app) {
if (typeof app === 'undefined') {
app = app_1.getApp();
}
var firebaseApp = app;
return firebaseApp.getOrInitService('machineLearning', function (app) { return new machine_learning_1.MachineLearning(app); });
}
exports.getMachineLearning = getMachineLearning;
@@ -0,0 +1,102 @@
/*! firebase-admin v10.0.1 */
/*!
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Firebase ML Model input objects
*/
export interface ModelOptionsBase {
displayName?: string;
tags?: string[];
}
export interface GcsTfliteModelOptions extends ModelOptionsBase {
tfliteModel: {
gcsTfliteUri: string;
};
}
export interface AutoMLTfliteModelOptions extends ModelOptionsBase {
tfliteModel: {
automlModel: string;
};
}
export declare type ModelOptions = ModelOptionsBase | GcsTfliteModelOptions | AutoMLTfliteModelOptions;
/**
* Interface representing options for listing Models.
*/
export interface ListModelsOptions {
/**
* An expression that specifies how to filter the results.
*
* Examples:
*
* ```
* display_name = your_model
* display_name : experimental_*
* tags: face_detector AND tags: experimental
* state.published = true
* ```
*
* See https://firebase.google.com/docs/ml/manage-hosted-models#list_your_projects_models
*/
filter?: string;
/** The number of results to return in each page. */
pageSize?: number;
/** A token that specifies the result page to return. */
pageToken?: string;
}
export interface StatusErrorResponse {
readonly code: number;
readonly message: string;
}
export declare type ModelUpdateOptions = ModelOptions & {
state?: {
published?: boolean;
};
};
export declare function isGcsTfliteModelOptions(options: ModelOptions): options is GcsTfliteModelOptions;
export interface ModelContent {
readonly displayName?: string;
readonly tags?: string[];
readonly state?: {
readonly validationError?: StatusErrorResponse;
readonly published?: boolean;
};
readonly tfliteModel?: {
readonly gcsTfliteUri?: string;
readonly automlModel?: string;
readonly sizeBytes: number;
};
}
export interface ModelResponse extends ModelContent {
readonly name: string;
readonly createTime: string;
readonly updateTime: string;
readonly etag: string;
readonly modelHash?: string;
readonly activeOperations?: OperationResponse[];
}
export interface ListModelsResponse {
readonly models?: ModelResponse[];
readonly nextPageToken?: string;
}
export interface OperationResponse {
readonly name?: string;
readonly metadata?: {
[key: string]: any;
};
readonly done: boolean;
readonly error?: StatusErrorResponse;
readonly response?: ModelResponse;
}
@@ -0,0 +1,304 @@
/*! firebase-admin v10.0.1 */
"use strict";
/*!
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.MachineLearningApiClient = exports.isGcsTfliteModelOptions = void 0;
var api_request_1 = require("../utils/api-request");
var error_1 = require("../utils/error");
var utils = require("../utils/index");
var validator = require("../utils/validator");
var machine_learning_utils_1 = require("./machine-learning-utils");
var ML_V1BETA2_API = 'https://firebaseml.googleapis.com/v1beta2';
var FIREBASE_VERSION_HEADER = {
'X-Firebase-Client': "fire-admin-node/" + utils.getSdkVersion(),
};
// Operation polling defaults
var POLL_DEFAULT_MAX_TIME_MILLISECONDS = 120000; // Maximum overall 2 minutes
var POLL_BASE_WAIT_TIME_MILLISECONDS = 3000; // Start with 3 second delay
var POLL_MAX_WAIT_TIME_MILLISECONDS = 30000; // Maximum 30 second delay
function isGcsTfliteModelOptions(options) {
var _a, _b;
var gcsUri = (_b = (_a = options) === null || _a === void 0 ? void 0 : _a.tfliteModel) === null || _b === void 0 ? void 0 : _b.gcsTfliteUri;
return typeof gcsUri !== 'undefined';
}
exports.isGcsTfliteModelOptions = isGcsTfliteModelOptions;
/**
* Class that facilitates sending requests to the Firebase ML backend API.
*
* @internal
*/
var MachineLearningApiClient = /** @class */ (function () {
function MachineLearningApiClient(app) {
this.app = app;
if (!validator.isNonNullObject(app) || !('options' in app)) {
throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'First argument passed to admin.machineLearning() must be a valid '
+ 'Firebase app instance.');
}
this.httpClient = new api_request_1.AuthorizedHttpClient(app);
}
MachineLearningApiClient.prototype.createModel = function (model) {
var _this = this;
if (!validator.isNonNullObject(model) ||
!validator.isNonEmptyString(model.displayName)) {
var err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid model content.');
return Promise.reject(err);
}
return this.getProjectUrl()
.then(function (url) {
var request = {
method: 'POST',
url: url + "/models",
data: model,
};
return _this.sendRequest(request);
});
};
MachineLearningApiClient.prototype.updateModel = function (modelId, model, updateMask) {
var _this = this;
if (!validator.isNonEmptyString(modelId) ||
!validator.isNonNullObject(model) ||
!validator.isNonEmptyArray(updateMask)) {
var err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid model or mask content.');
return Promise.reject(err);
}
return this.getProjectUrl()
.then(function (url) {
var request = {
method: 'PATCH',
url: url + "/models/" + modelId + "?updateMask=" + updateMask.join(),
data: model,
};
return _this.sendRequest(request);
});
};
MachineLearningApiClient.prototype.getModel = function (modelId) {
var _this = this;
return Promise.resolve()
.then(function () {
return _this.getModelName(modelId);
})
.then(function (modelName) {
return _this.getResourceWithShortName(modelName);
});
};
MachineLearningApiClient.prototype.getOperation = function (operationName) {
var _this = this;
return Promise.resolve()
.then(function () {
return _this.getResourceWithFullName(operationName);
});
};
MachineLearningApiClient.prototype.listModels = function (options) {
var _this = this;
if (options === void 0) { options = {}; }
if (!validator.isNonNullObject(options)) {
var err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid ListModelsOptions');
return Promise.reject(err);
}
if (typeof options.filter !== 'undefined' && !validator.isNonEmptyString(options.filter)) {
var err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid list filter.');
return Promise.reject(err);
}
if (typeof options.pageSize !== 'undefined') {
if (!validator.isNumber(options.pageSize)) {
var err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Invalid page size.');
return Promise.reject(err);
}
if (options.pageSize < 1 || options.pageSize > 100) {
var err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Page size must be between 1 and 100.');
return Promise.reject(err);
}
}
if (typeof options.pageToken !== 'undefined' && !validator.isNonEmptyString(options.pageToken)) {
var err = new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Next page token must be a non-empty string.');
return Promise.reject(err);
}
return this.getProjectUrl()
.then(function (url) {
var request = {
method: 'GET',
url: url + "/models",
data: options,
};
return _this.sendRequest(request);
});
};
MachineLearningApiClient.prototype.deleteModel = function (modelId) {
var _this = this;
return this.getProjectUrl()
.then(function (url) {
var modelName = _this.getModelName(modelId);
var request = {
method: 'DELETE',
url: url + "/" + modelName,
};
return _this.sendRequest(request);
});
};
/**
* Handles a Long Running Operation coming back from the server.
*
* @param op - The operation to handle
* @param options - The options for polling
*/
MachineLearningApiClient.prototype.handleOperation = function (op, options) {
if (op.done) {
if (op.response) {
return Promise.resolve(op.response);
}
else if (op.error) {
var err = machine_learning_utils_1.FirebaseMachineLearningError.fromOperationError(op.error.code, op.error.message);
return Promise.reject(err);
}
// Done operations must have either a response or an error.
throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-server-response', 'Invalid operation response.');
}
// Operation is not done
if (options === null || options === void 0 ? void 0 : options.wait) {
return this.pollOperationWithExponentialBackoff(op.name, options);
}
var metadata = op.metadata || {};
var metadataType = metadata['@type'] || '';
if (!metadataType.includes('ModelOperationMetadata')) {
throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-server-response', "Unknown Metadata type: " + JSON.stringify(metadata));
}
return this.getModel(extractModelId(metadata.name));
};
// baseWaitMillis and maxWaitMillis should only ever be modified by unit tests to run faster.
MachineLearningApiClient.prototype.pollOperationWithExponentialBackoff = function (opName, options) {
var _this = this;
var _a, _b, _c;
var maxTimeMilliseconds = (_a = options === null || options === void 0 ? void 0 : options.maxTimeMillis) !== null && _a !== void 0 ? _a : POLL_DEFAULT_MAX_TIME_MILLISECONDS;
var baseWaitMillis = (_b = options === null || options === void 0 ? void 0 : options.baseWaitMillis) !== null && _b !== void 0 ? _b : POLL_BASE_WAIT_TIME_MILLISECONDS;
var maxWaitMillis = (_c = options === null || options === void 0 ? void 0 : options.maxWaitMillis) !== null && _c !== void 0 ? _c : POLL_MAX_WAIT_TIME_MILLISECONDS;
var poller = new api_request_1.ExponentialBackoffPoller(baseWaitMillis, maxWaitMillis, maxTimeMilliseconds);
return poller.poll(function () {
return _this.getOperation(opName)
.then(function (responseData) {
if (!responseData.done) {
return null;
}
if (responseData.error) {
var err = machine_learning_utils_1.FirebaseMachineLearningError.fromOperationError(responseData.error.code, responseData.error.message);
throw err;
}
return responseData.response;
});
});
};
/**
* Gets the specified resource from the ML API. Resource names must be the short names without project
* ID prefix (e.g. `models/123456789`).
*
* @param {string} name Short name of the resource to get. e.g. 'models/12345'
* @returns {Promise<T>} A promise that fulfills with the resource.
*/
MachineLearningApiClient.prototype.getResourceWithShortName = function (name) {
var _this = this;
return this.getProjectUrl()
.then(function (url) {
var request = {
method: 'GET',
url: url + "/" + name,
};
return _this.sendRequest(request);
});
};
/**
* Gets the specified resource from the ML API. Resource names must be the full names including project
* number prefix.
* @param fullName - Full resource name of the resource to get. e.g. projects/123465/operations/987654
* @returns {Promise<T>} A promise that fulfulls with the resource.
*/
MachineLearningApiClient.prototype.getResourceWithFullName = function (fullName) {
var request = {
method: 'GET',
url: ML_V1BETA2_API + "/" + fullName
};
return this.sendRequest(request);
};
MachineLearningApiClient.prototype.sendRequest = function (request) {
var _this = this;
request.headers = FIREBASE_VERSION_HEADER;
return this.httpClient.send(request)
.then(function (resp) {
return resp.data;
})
.catch(function (err) {
throw _this.toFirebaseError(err);
});
};
MachineLearningApiClient.prototype.toFirebaseError = function (err) {
if (err instanceof error_1.PrefixedFirebaseError) {
return err;
}
var response = err.response;
if (!response.isJson()) {
return new machine_learning_utils_1.FirebaseMachineLearningError('unknown-error', "Unexpected response with status: " + response.status + " and body: " + response.text);
}
var error = response.data.error || {};
var code = 'unknown-error';
if (error.status && error.status in ERROR_CODE_MAPPING) {
code = ERROR_CODE_MAPPING[error.status];
}
var message = error.message || "Unknown server error: " + response.text;
return new machine_learning_utils_1.FirebaseMachineLearningError(code, message);
};
MachineLearningApiClient.prototype.getProjectUrl = function () {
return this.getProjectIdPrefix()
.then(function (projectIdPrefix) {
return ML_V1BETA2_API + "/" + projectIdPrefix;
});
};
MachineLearningApiClient.prototype.getProjectIdPrefix = function () {
var _this = this;
if (this.projectIdPrefix) {
return Promise.resolve(this.projectIdPrefix);
}
return utils.findProjectId(this.app)
.then(function (projectId) {
if (!validator.isNonEmptyString(projectId)) {
throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Failed to determine project ID. Initialize the SDK with service account credentials, or '
+ 'set project ID as an app option. Alternatively, set the GOOGLE_CLOUD_PROJECT '
+ 'environment variable.');
}
_this.projectIdPrefix = "projects/" + projectId;
return _this.projectIdPrefix;
});
};
MachineLearningApiClient.prototype.getModelName = function (modelId) {
if (!validator.isNonEmptyString(modelId)) {
throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Model ID must be a non-empty string.');
}
if (modelId.indexOf('/') !== -1) {
throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', 'Model ID must not contain any "/" characters.');
}
return "models/" + modelId;
};
return MachineLearningApiClient;
}());
exports.MachineLearningApiClient = MachineLearningApiClient;
var ERROR_CODE_MAPPING = {
INVALID_ARGUMENT: 'invalid-argument',
NOT_FOUND: 'not-found',
RESOURCE_EXHAUSTED: 'resource-exhausted',
UNAUTHENTICATED: 'authentication-error',
UNKNOWN: 'unknown-error',
};
function extractModelId(resourceName) {
return resourceName.split('/').pop();
}
@@ -0,0 +1,85 @@
/*! firebase-admin v10.0.1 */
/*!
* Copyright 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { App } from '../app';
import { ListModelsResult as TListModelsResult, MachineLearning as TMachineLearning, Model as TModel, TFLiteModel as TTFLiteModel } from './machine-learning';
import { AutoMLTfliteModelOptions as TAutoMLTfliteModelOptions, GcsTfliteModelOptions as TGcsTfliteModelOptions, ListModelsOptions as TListModelsOptions, ModelOptions as TModelOptions, ModelOptionsBase as TModelOptionsBase } from './machine-learning-api-client';
/**
* Gets the {@link firebase-admin.machine-learning#MachineLearning} service for the
* default app or a given app.
*
* `admin.machineLearning()` can be called with no arguments to access the
* default app's `MachineLearning` service or as `admin.machineLearning(app)` to access
* the `MachineLearning` service associated with a specific app.
*
* @example
* ```javascript
* // Get the MachineLearning service for the default app
* var defaultMachineLearning = admin.machineLearning();
* ```
*
* @example
* ```javascript
* // Get the MachineLearning service for a given app
* var otherMachineLearning = admin.machineLearning(otherApp);
* ```
*
* @param app - Optional app whose `MachineLearning` service to
* return. If not provided, the default `MachineLearning` service
* will be returned.
*
* @returns The default `MachineLearning` service if no app is provided or the
* `MachineLearning` service associated with the provided app.
*/
export declare function machineLearning(app?: App): machineLearning.MachineLearning;
export declare namespace machineLearning {
/**
* Type alias to {@link firebase-admin.machine-learning#ListModelsResult}.
*/
type ListModelsResult = TListModelsResult;
/**
* Type alias to {@link firebase-admin.machine-learning#MachineLearning}.
*/
type MachineLearning = TMachineLearning;
/**
* Type alias to {@link firebase-admin.machine-learning#Model}.
*/
type Model = TModel;
/**
* Type alias to {@link firebase-admin.machine-learning#TFLiteModel}.
*/
type TFLiteModel = TTFLiteModel;
/**
* Type alias to {@link firebase-admin.machine-learning#AutoMLTfliteModelOptions}.
*/
type AutoMLTfliteModelOptions = TAutoMLTfliteModelOptions;
/**
* Type alias to {@link firebase-admin.machine-learning#GcsTfliteModelOptions}.
*/
type GcsTfliteModelOptions = TGcsTfliteModelOptions;
/**
* Type alias to {@link firebase-admin.machine-learning#ListModelsOptions}.
*/
type ListModelsOptions = TListModelsOptions;
/**
* Type alias to {@link firebase-admin.machine-learning#ModelOptions}.
*/
type ModelOptions = TModelOptions;
/**
* Type alias to {@link firebase-admin.machine-learning#ModelOptionsBase}.
*/
type ModelOptionsBase = TModelOptionsBase;
}
@@ -0,0 +1,18 @@
/*! firebase-admin v10.0.1 */
"use strict";
/*!
* Copyright 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,22 @@
/*! firebase-admin v10.0.1 */
/*!
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { PrefixedFirebaseError } from '../utils/error';
export declare type MachineLearningErrorCode = 'already-exists' | 'authentication-error' | 'internal-error' | 'invalid-argument' | 'invalid-server-response' | 'not-found' | 'resource-exhausted' | 'service-unavailable' | 'unknown-error' | 'cancelled' | 'deadline-exceeded' | 'permission-denied' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'data-loss' | 'unauthenticated';
export declare class FirebaseMachineLearningError extends PrefixedFirebaseError {
static fromOperationError(code: number, message: string): FirebaseMachineLearningError;
constructor(code: MachineLearningErrorCode, message: string);
}
@@ -0,0 +1,62 @@
/*! firebase-admin v10.0.1 */
"use strict";
/*!
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.FirebaseMachineLearningError = void 0;
var error_1 = require("../utils/error");
var FirebaseMachineLearningError = /** @class */ (function (_super) {
__extends(FirebaseMachineLearningError, _super);
function FirebaseMachineLearningError(code, message) {
return _super.call(this, 'machine-learning', code, message) || this;
}
FirebaseMachineLearningError.fromOperationError = function (code, message) {
switch (code) {
case 1: return new FirebaseMachineLearningError('cancelled', message);
case 2: return new FirebaseMachineLearningError('unknown-error', message);
case 3: return new FirebaseMachineLearningError('invalid-argument', message);
case 4: return new FirebaseMachineLearningError('deadline-exceeded', message);
case 5: return new FirebaseMachineLearningError('not-found', message);
case 6: return new FirebaseMachineLearningError('already-exists', message);
case 7: return new FirebaseMachineLearningError('permission-denied', message);
case 8: return new FirebaseMachineLearningError('resource-exhausted', message);
case 9: return new FirebaseMachineLearningError('failed-precondition', message);
case 10: return new FirebaseMachineLearningError('aborted', message);
case 11: return new FirebaseMachineLearningError('out-of-range', message);
case 13: return new FirebaseMachineLearningError('internal-error', message);
case 14: return new FirebaseMachineLearningError('service-unavailable', message);
case 15: return new FirebaseMachineLearningError('data-loss', message);
case 16: return new FirebaseMachineLearningError('unauthenticated', message);
default:
return new FirebaseMachineLearningError('unknown-error', message);
}
};
return FirebaseMachineLearningError;
}(error_1.PrefixedFirebaseError));
exports.FirebaseMachineLearningError = FirebaseMachineLearningError;
+181
View File
@@ -0,0 +1,181 @@
/*! firebase-admin v10.0.1 */
/*!
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { App } from '../app';
import { ListModelsOptions, ModelOptions } from './machine-learning-api-client';
/** Response object for a listModels operation. */
export interface ListModelsResult {
/** A list of models in your project. */
readonly models: Model[];
/**
* A token you can use to retrieve the next page of results. If null, the
* current page is the final page.
*/
readonly pageToken?: string;
}
/**
* A TensorFlow Lite Model output object
*
* One of either the `gcsTfliteUri` or `automlModel` properties will be
* defined.
*/
export interface TFLiteModel {
/** The size of the model. */
readonly sizeBytes: number;
/** The URI from which the model was originally provided to Firebase. */
readonly gcsTfliteUri?: string;
/**
* The AutoML model reference from which the model was originally provided
* to Firebase.
*/
readonly automlModel?: string;
}
/**
* The Firebase `MachineLearning` service interface.
*/
export declare class MachineLearning {
private readonly client;
private readonly appInternal;
/**
* The {@link firebase-admin.app#App} associated with the current `MachineLearning`
* service instance.
*/
get app(): App;
/**
* Creates a model in the current Firebase project.
*
* @param model - The model to create.
*
* @returns A Promise fulfilled with the created model.
*/
createModel(model: ModelOptions): Promise<Model>;
/**
* Updates a model's metadata or model file.
*
* @param modelId - The ID of the model to update.
* @param model - The model fields to update.
*
* @returns A Promise fulfilled with the updated model.
*/
updateModel(modelId: string, model: ModelOptions): Promise<Model>;
/**
* Publishes a Firebase ML model.
*
* A published model can be downloaded to client apps.
*
* @param modelId - The ID of the model to publish.
*
* @returns A Promise fulfilled with the published model.
*/
publishModel(modelId: string): Promise<Model>;
/**
* Unpublishes a Firebase ML model.
*
* @param modelId - The ID of the model to unpublish.
*
* @returns A Promise fulfilled with the unpublished model.
*/
unpublishModel(modelId: string): Promise<Model>;
/**
* Gets the model specified by the given ID.
*
* @param modelId - The ID of the model to get.
*
* @returns A Promise fulfilled with the model object.
*/
getModel(modelId: string): Promise<Model>;
/**
* Lists the current project's models.
*
* @param options - The listing options.
*
* @returns A promise that
* resolves with the current (filtered) list of models and the next page
* token. For the last page, an empty list of models and no page token
* are returned.
*/
listModels(options?: ListModelsOptions): Promise<ListModelsResult>;
/**
* Deletes a model from the current project.
*
* @param modelId - The ID of the model to delete.
*/
deleteModel(modelId: string): Promise<void>;
private setPublishStatus;
private signUrlIfPresent;
private signUrl;
}
/**
* A Firebase ML Model output object.
*/
export declare class Model {
private model;
private readonly client?;
/** The ID of the model. */
get modelId(): string;
/**
* The model's name. This is the name you use from your app to load the
* model.
*/
get displayName(): string;
/**
* The model's tags, which can be used to group or filter models in list
* operations.
*/
get tags(): string[];
/** The timestamp of the model's creation. */
get createTime(): string;
/** The timestamp of the model's most recent update. */
get updateTime(): string;
/** Error message when model validation fails. */
get validationError(): string | undefined;
/** True if the model is published. */
get published(): boolean;
/**
* The ETag identifier of the current version of the model. This value
* changes whenever you update any of the model's properties.
*/
get etag(): string;
/**
* The hash of the model's `tflite` file. This value changes only when
* you upload a new TensorFlow Lite model.
*/
get modelHash(): string | undefined;
/** Metadata about the model's TensorFlow Lite model file. */
get tfliteModel(): TFLiteModel | undefined;
/**
* True if the model is locked by a server-side operation. You can't make
* changes to a locked model. See {@link Model.waitForUnlocked}.
*/
get locked(): boolean;
/**
* Return the model as a JSON object.
*/
toJSON(): {
[key: string]: any;
};
/**
* Wait for the model to be unlocked.
*
* @param maxTimeMillis - The maximum time in milliseconds to wait.
* If not specified, a default maximum of 2 minutes is used.
*
* @returns A promise that resolves when the model is unlocked
* or the maximum wait time has passed.
*/
waitForUnlocked(maxTimeMillis?: number): Promise<void>;
private static validateAndClone;
}
+399
View File
@@ -0,0 +1,399 @@
/*! firebase-admin v10.0.1 */
"use strict";
/*!
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Model = exports.MachineLearning = void 0;
var index_1 = require("../storage/index");
var error_1 = require("../utils/error");
var validator = require("../utils/validator");
var deep_copy_1 = require("../utils/deep-copy");
var utils = require("../utils");
var machine_learning_api_client_1 = require("./machine-learning-api-client");
var machine_learning_utils_1 = require("./machine-learning-utils");
/**
* The Firebase `MachineLearning` service interface.
*/
var MachineLearning = /** @class */ (function () {
/**
* @param app - The app for this ML service.
* @constructor
* @internal
*/
function MachineLearning(app) {
if (!validator.isNonNullObject(app) || !('options' in app)) {
throw new error_1.FirebaseError({
code: 'machine-learning/invalid-argument',
message: 'First argument passed to admin.machineLearning() must be a ' +
'valid Firebase app instance.',
});
}
this.appInternal = app;
this.client = new machine_learning_api_client_1.MachineLearningApiClient(app);
}
Object.defineProperty(MachineLearning.prototype, "app", {
/**
* The {@link firebase-admin.app#App} associated with the current `MachineLearning`
* service instance.
*/
get: function () {
return this.appInternal;
},
enumerable: false,
configurable: true
});
/**
* Creates a model in the current Firebase project.
*
* @param model - The model to create.
*
* @returns A Promise fulfilled with the created model.
*/
MachineLearning.prototype.createModel = function (model) {
var _this = this;
return this.signUrlIfPresent(model)
.then(function (modelContent) { return _this.client.createModel(modelContent); })
.then(function (operation) { return _this.client.handleOperation(operation); })
.then(function (modelResponse) { return new Model(modelResponse, _this.client); });
};
/**
* Updates a model's metadata or model file.
*
* @param modelId - The ID of the model to update.
* @param model - The model fields to update.
*
* @returns A Promise fulfilled with the updated model.
*/
MachineLearning.prototype.updateModel = function (modelId, model) {
var _this = this;
var updateMask = utils.generateUpdateMask(model);
return this.signUrlIfPresent(model)
.then(function (modelContent) { return _this.client.updateModel(modelId, modelContent, updateMask); })
.then(function (operation) { return _this.client.handleOperation(operation); })
.then(function (modelResponse) { return new Model(modelResponse, _this.client); });
};
/**
* Publishes a Firebase ML model.
*
* A published model can be downloaded to client apps.
*
* @param modelId - The ID of the model to publish.
*
* @returns A Promise fulfilled with the published model.
*/
MachineLearning.prototype.publishModel = function (modelId) {
return this.setPublishStatus(modelId, true);
};
/**
* Unpublishes a Firebase ML model.
*
* @param modelId - The ID of the model to unpublish.
*
* @returns A Promise fulfilled with the unpublished model.
*/
MachineLearning.prototype.unpublishModel = function (modelId) {
return this.setPublishStatus(modelId, false);
};
/**
* Gets the model specified by the given ID.
*
* @param modelId - The ID of the model to get.
*
* @returns A Promise fulfilled with the model object.
*/
MachineLearning.prototype.getModel = function (modelId) {
var _this = this;
return this.client.getModel(modelId)
.then(function (modelResponse) { return new Model(modelResponse, _this.client); });
};
/**
* Lists the current project's models.
*
* @param options - The listing options.
*
* @returns A promise that
* resolves with the current (filtered) list of models and the next page
* token. For the last page, an empty list of models and no page token
* are returned.
*/
MachineLearning.prototype.listModels = function (options) {
var _this = this;
if (options === void 0) { options = {}; }
return this.client.listModels(options)
.then(function (resp) {
if (!validator.isNonNullObject(resp)) {
throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', "Invalid ListModels response: " + JSON.stringify(resp));
}
var models = [];
if (resp.models) {
models = resp.models.map(function (rs) { return new Model(rs, _this.client); });
}
var result = { models: models };
if (resp.nextPageToken) {
result.pageToken = resp.nextPageToken;
}
return result;
});
};
/**
* Deletes a model from the current project.
*
* @param modelId - The ID of the model to delete.
*/
MachineLearning.prototype.deleteModel = function (modelId) {
return this.client.deleteModel(modelId);
};
MachineLearning.prototype.setPublishStatus = function (modelId, publish) {
var _this = this;
var updateMask = ['state.published'];
var options = { state: { published: publish } };
return this.client.updateModel(modelId, options, updateMask)
.then(function (operation) { return _this.client.handleOperation(operation); })
.then(function (modelResponse) { return new Model(modelResponse, _this.client); });
};
MachineLearning.prototype.signUrlIfPresent = function (options) {
var modelOptions = deep_copy_1.deepCopy(options);
if (machine_learning_api_client_1.isGcsTfliteModelOptions(modelOptions)) {
return this.signUrl(modelOptions.tfliteModel.gcsTfliteUri)
.then(function (uri) {
modelOptions.tfliteModel.gcsTfliteUri = uri;
return modelOptions;
})
.catch(function (err) {
throw new machine_learning_utils_1.FirebaseMachineLearningError('internal-error', "Error during signing upload url: " + err.message);
});
}
return Promise.resolve(modelOptions);
};
MachineLearning.prototype.signUrl = function (unsignedUrl) {
var MINUTES_IN_MILLIS = 60 * 1000;
var URL_VALID_DURATION = 10 * MINUTES_IN_MILLIS;
var gcsRegex = /^gs:\/\/([a-z0-9_.-]{3,63})\/(.+)$/;
var matches = gcsRegex.exec(unsignedUrl);
if (!matches) {
throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-argument', "Invalid unsigned url: " + unsignedUrl);
}
var bucketName = matches[1];
var blobName = matches[2];
var bucket = index_1.getStorage(this.app).bucket(bucketName);
var blob = bucket.file(blobName);
return blob.getSignedUrl({
action: 'read',
expires: Date.now() + URL_VALID_DURATION,
}).then(function (signUrl) { return signUrl[0]; });
};
return MachineLearning;
}());
exports.MachineLearning = MachineLearning;
/**
* A Firebase ML Model output object.
*/
var Model = /** @class */ (function () {
/**
* @internal
*/
function Model(model, client) {
this.model = Model.validateAndClone(model);
this.client = client;
}
Object.defineProperty(Model.prototype, "modelId", {
/** The ID of the model. */
get: function () {
return extractModelId(this.model.name);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Model.prototype, "displayName", {
/**
* The model's name. This is the name you use from your app to load the
* model.
*/
get: function () {
return this.model.displayName;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Model.prototype, "tags", {
/**
* The model's tags, which can be used to group or filter models in list
* operations.
*/
get: function () {
return this.model.tags || [];
},
enumerable: false,
configurable: true
});
Object.defineProperty(Model.prototype, "createTime", {
/** The timestamp of the model's creation. */
get: function () {
return new Date(this.model.createTime).toUTCString();
},
enumerable: false,
configurable: true
});
Object.defineProperty(Model.prototype, "updateTime", {
/** The timestamp of the model's most recent update. */
get: function () {
return new Date(this.model.updateTime).toUTCString();
},
enumerable: false,
configurable: true
});
Object.defineProperty(Model.prototype, "validationError", {
/** Error message when model validation fails. */
get: function () {
var _a, _b;
return (_b = (_a = this.model.state) === null || _a === void 0 ? void 0 : _a.validationError) === null || _b === void 0 ? void 0 : _b.message;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Model.prototype, "published", {
/** True if the model is published. */
get: function () {
var _a;
return ((_a = this.model.state) === null || _a === void 0 ? void 0 : _a.published) || false;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Model.prototype, "etag", {
/**
* The ETag identifier of the current version of the model. This value
* changes whenever you update any of the model's properties.
*/
get: function () {
return this.model.etag;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Model.prototype, "modelHash", {
/**
* The hash of the model's `tflite` file. This value changes only when
* you upload a new TensorFlow Lite model.
*/
get: function () {
return this.model.modelHash;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Model.prototype, "tfliteModel", {
/** Metadata about the model's TensorFlow Lite model file. */
get: function () {
// Make a copy so people can't directly modify the private this.model object.
return deep_copy_1.deepCopy(this.model.tfliteModel);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Model.prototype, "locked", {
/**
* True if the model is locked by a server-side operation. You can't make
* changes to a locked model. See {@link Model.waitForUnlocked}.
*/
get: function () {
var _a, _b;
return ((_b = (_a = this.model.activeOperations) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0;
},
enumerable: false,
configurable: true
});
/**
* Return the model as a JSON object.
*/
Model.prototype.toJSON = function () {
// We can't just return this.model because it has extra fields and
// different formats etc. So we build the expected model object.
var jsonModel = {
modelId: this.modelId,
displayName: this.displayName,
tags: this.tags,
createTime: this.createTime,
updateTime: this.updateTime,
published: this.published,
etag: this.etag,
locked: this.locked,
};
// Also add possibly undefined fields if they exist.
if (this.validationError) {
jsonModel['validationError'] = this.validationError;
}
if (this.modelHash) {
jsonModel['modelHash'] = this.modelHash;
}
if (this.tfliteModel) {
jsonModel['tfliteModel'] = this.tfliteModel;
}
return jsonModel;
};
/**
* Wait for the model to be unlocked.
*
* @param maxTimeMillis - The maximum time in milliseconds to wait.
* If not specified, a default maximum of 2 minutes is used.
*
* @returns A promise that resolves when the model is unlocked
* or the maximum wait time has passed.
*/
Model.prototype.waitForUnlocked = function (maxTimeMillis) {
var _this = this;
var _a, _b;
if (((_b = (_a = this.model.activeOperations) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0) {
// The client will always be defined on Models that have activeOperations
// because models with active operations came back from the server and
// were constructed with a non-empty client.
return this.client.handleOperation(this.model.activeOperations[0], { wait: true, maxTimeMillis: maxTimeMillis })
.then(function (modelResponse) {
_this.model = Model.validateAndClone(modelResponse);
});
}
return Promise.resolve();
};
Model.validateAndClone = function (model) {
if (!validator.isNonNullObject(model) ||
!validator.isNonEmptyString(model.name) ||
!validator.isNonEmptyString(model.createTime) ||
!validator.isNonEmptyString(model.updateTime) ||
!validator.isNonEmptyString(model.displayName) ||
!validator.isNonEmptyString(model.etag)) {
throw new machine_learning_utils_1.FirebaseMachineLearningError('invalid-server-response', "Invalid Model response: " + JSON.stringify(model));
}
var tmpModel = deep_copy_1.deepCopy(model);
// If tflite Model is specified, it must have a source consisting of
// oneof {gcsTfliteUri, automlModel}
if (model.tfliteModel &&
!validator.isNonEmptyString(model.tfliteModel.gcsTfliteUri) &&
!validator.isNonEmptyString(model.tfliteModel.automlModel)) {
// If we have some other source, ignore the whole tfliteModel.
delete tmpModel.tfliteModel;
}
// Remove '@type' field. We don't need it.
if (tmpModel['@type']) {
delete tmpModel['@type'];
}
return tmpModel;
};
return Model;
}());
exports.Model = Model;
function extractModelId(resourceName) {
return resourceName.split('/').pop();
}