├── .nvmrc
├── .develo
├── activate
└── server
├── .babelrc
├── .gitignore
├── src
└── cloud
│ ├── routes
│ ├── index.js
│ └── api.js
│ ├── config.js
│ ├── main.js
│ ├── app.js
│ ├── functions.js
│ └── ml_models
│ └── nsfw_model.js
├── .editorconfig
├── .env.example
├── package.json
├── index.js
├── LICENSE
└── README.md
/.nvmrc:
--------------------------------------------------------------------------------
1 | 10
2 |
--------------------------------------------------------------------------------
/.develo/activate:
--------------------------------------------------------------------------------
1 | nvm use
2 |
--------------------------------------------------------------------------------
/.develo/server:
--------------------------------------------------------------------------------
1 | npm run dev
2 |
--------------------------------------------------------------------------------
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": ["@babel/preset-env"]
3 | }
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules
3 | .cache
4 | /logs
5 | /cloud
6 | /public
7 | .env
8 |
--------------------------------------------------------------------------------
/src/cloud/routes/index.js:
--------------------------------------------------------------------------------
1 | import api from "./api";
2 |
3 | export default {
4 | api,
5 | };
6 |
--------------------------------------------------------------------------------
/src/cloud/config.js:
--------------------------------------------------------------------------------
1 | const config = {
2 | env: {
3 | nsfw_model_url: process.env.TF_MODEL_URL,
4 | nsfw_model_shape_size: process.env.TF_MODEL_INPUT_SHAPE_SIZE
5 | },
6 | }
7 |
8 | export default config;
9 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # http://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | max_line_length = off
13 | trim_trailing_whitespace = false
14 |
--------------------------------------------------------------------------------
/src/cloud/main.js:
--------------------------------------------------------------------------------
1 | import "regenerator-runtime/runtime.js";
2 |
3 | // We are using this model in lots of functions
4 | // it will be much easier that way :)
5 | import nsfwModel from "./ml_models/nsfw_model";
6 | global.nsfwModel = nsfwModel;
7 |
8 | import app from "./app";
9 |
10 | import "./functions";
11 |
12 | export { app };
13 |
--------------------------------------------------------------------------------
/src/cloud/app.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Advanced Cloud Code Example
3 | */
4 |
5 | import express from "express";
6 | import cors from "cors";
7 | import routes from "./routes";
8 | const app = express();
9 |
10 | app.use(cors());
11 | app.use(express.json()); // for parsing application/json
12 | app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
13 |
14 | // API Routes
15 | app.use("/api", routes.api);
16 |
17 | export default app;
18 |
--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------
1 | /*
2 | * Parse Server ENV variables
3 | */
4 |
5 | SERVER_URL="http://localhost:1337/1/"
6 | APP_ID="myAppId"
7 | JS_KEY="myJSKey"
8 | REST_API_KEY="myRestKey"
9 | MASTER_KEY="myMasterKey"
10 |
11 | /* Get your DB url from SashiDo Dashboard > App > App Settings > Security & Keys */
12 | DATABASE_URI=""
13 |
14 |
15 | /*
16 | * Cloud Code ENV variables
17 | */
18 |
19 | TF_MODEL_URL="https://ml.files-sashido.cloud/models/nsfw_mobilenet_v2/93/"
20 | TF_MODEL_INPUT_SHAPE_SIZE="224"
21 |
--------------------------------------------------------------------------------
/src/cloud/routes/api.js:
--------------------------------------------------------------------------------
1 | import express from "express";
2 | const router = express.Router();
3 |
4 | /* TODO
5 | * Add more classifications options
6 | * - /gif/classify
7 | * - /video/classify
8 | * - /text/classify
9 | */
10 |
11 | router.get("/image/classify", async (req, res) => {
12 | try {
13 | const { url } = req.query;
14 | const result = await nsfwModel.classify(url);
15 | res.json(result)
16 | } catch (err) {
17 | console.error(err);
18 |
19 | res.status(500).json({
20 | error: "Ups... Something went wrong! Please contact the app administrator or see at the server logs for the error."
21 | });
22 | }
23 | });
24 |
25 | export default router;
26 |
--------------------------------------------------------------------------------
/src/cloud/functions.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Simple Cloud Code Example
3 | * More information how to use it directly via the Parse SDKs or cURL
4 | * - https://docs.parseplatform.org/cloudcode/guide/#cloud-functions
5 | *
6 | * You can test this easly with the API Console in the SashiDo Dashboard
7 | *
8 | * Tutorial how:
9 | * - https://blog.sashido.io/introducing-the-api-console/#callyourcloudcodefunctions
10 | */
11 |
12 | Parse.Cloud.define("nsfwImageClassify", async (req) => {
13 | try {
14 | // url of the image we want to classify
15 | const { url } = req.params;
16 |
17 | const result = await nsfwModel.classify(url);
18 | return result;
19 | } catch (err) {
20 | console.error(err);
21 | return { error: "Something went wrong" };
22 | }
23 | });
24 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "content-moderation-image-api",
3 | "version": "0.1.0",
4 | "description": "Ready-to-use Node.JS REST API for classification of indecent images.",
5 | "main": "index.js",
6 | "repository": {
7 | "type": "git",
8 | "url": "https://github.com/SashiDo/content-moderation-image-api.git"
9 | },
10 | "license": "MIT",
11 | "engines": {
12 | "node": ">=10.2.1"
13 | },
14 | "scripts": {
15 | "start": "node index",
16 | "dev": "NODE_ENV=development npm-run-all --parallel dev:*",
17 | "dev:cloud": "parcel --no-cache ./src/cloud/main.js -t node -d cloud --no-cache",
18 | "dev:parse-server": "NODE_ENV=development nodemon index",
19 | "build": "NODE_ENV=production parcel build ./src/cloud/main.js -t node -d cloud",
20 | "postinstall": "if [ \"$install\" != \"1\" ]; then export install=\"1\" && npm run build; fi"
21 | },
22 | "dependencies": {
23 | "@babel/core": "7.9.6",
24 | "@babel/preset-env": "7.9.6",
25 | "@tensorflow/tfjs-node": "1.7.4",
26 | "axios": "0.19.2",
27 | "babel-loader": "8.1.0",
28 | "cors": "2.8.5",
29 | "nodemon": "2.0.4",
30 | "nsfwjs": "2.2.0",
31 | "parcel-bundler": "1.12.4"
32 | },
33 | "devDependencies": {
34 | "npm-run-all": "4.1.5",
35 | "parse": "2.3.0",
36 | "parse-server": "3.6.0"
37 | },
38 | "nodemonConfig": {
39 | "delay": "2000",
40 | "watch": [
41 | "./index.js",
42 | "./src/cloud"
43 | ]
44 | },
45 | "postcss": {
46 | "plugins": {
47 | "autoprefixer": true
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/cloud/ml_models/nsfw_model.js:
--------------------------------------------------------------------------------
1 | // you can use any other http client
2 | import axios from "axios";
3 |
4 | import * as tf from "@tensorflow/tfjs-node";
5 | import * as nsfw from "nsfwjs";
6 | import config from "../config";
7 |
8 | tf.enableProdMode(); // enable on production
9 |
10 | let module_vars = { model: null };
11 |
12 | const init = async () => {
13 | const model_url = config.env.nsfw_model_url;
14 | const shape_size = config.env.nsfw_model_shape_size;
15 |
16 | // Load the model in the memory only once!
17 | if (!module_vars.model) {
18 | try {
19 | module_vars.model = await nsfw.load(model_url, { size: parseInt(shape_size) });
20 | console.info("The NSFW Model was loaded successfuly!");
21 | } catch (err) {
22 | console.error(err);
23 | }
24 | }
25 | };
26 |
27 | const classify = async (url) => {
28 | let pic;
29 | let result = {};
30 |
31 | const { model } = module_vars;
32 |
33 | try {
34 | pic = await axios.get(url, {
35 | responseType: "arraybuffer",
36 | });
37 | } catch (err) {
38 | console.error("Download Image Error:", err);
39 | result.error = err;
40 | return result;
41 | }
42 |
43 | try {
44 | // Image must be in tf.tensor3d format
45 | // you can convert image to tf.tensor3d with tf.node.decodeImage(Uint8Array,channels)
46 | const image = await tf.node.decodeImage(pic.data, 3);
47 | const predictions = await model.classify(image);
48 |
49 | image.dispose(); // Tensor memory must be managed explicitly (it is not sufficient to let a tf.Tensor go out of scope for its memory to be released).
50 |
51 | result = predictions;
52 | } catch (err) {
53 | console.error("Prediction Error: ", err);
54 | result.error = "Model is not loaded yet!";
55 | return result;
56 | }
57 |
58 | return result;
59 | };
60 |
61 | // Load the model on the first require
62 | init();
63 |
64 | export default {
65 | classify
66 | }
67 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | const dotenv = require('dotenv').config();
2 |
3 | const path = require('path');
4 | const express = require('express');
5 | const { ParseServer } = require('parse-server');
6 | const databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
7 |
8 | if (!databaseUri) {
9 | console.log('DATABASE_URI not specified, falling back to localhost.');
10 | }
11 |
12 | const mountPath = process.env.PARSE_MOUNT || '/1';
13 | const port = process.env.PORT || 1337;
14 | const api = new ParseServer({
15 | databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
16 | appId: process.env.APP_ID || 'myAppId',
17 | restAPIKey: process.env.REST_API_KEY || 'myRestKey',
18 | javascriptKey: process.env.JS_KEY || 'myJSKey',
19 | masterKey: process.env.MASTER_KEY || 'myMasterKey', //Add your master key here. Keep it secret!
20 | serverURL: process.env.SERVER_URL || `http://localhost:${port}${mountPath}`,
21 |
22 | // If you change the cloud/main.js to another path
23 | // it wouldn't work on SashiDo :( ... so Don't change this.
24 | cloud: process.env.CLOUD_CODE_MAIN || 'cloud/main.js',
25 |
26 | liveQuery: {
27 | classNames: [] // List of classes to support for query subscriptions example: [ 'Posts', 'Comments' ]
28 | }
29 | });
30 |
31 | // Client-keys like the javascript key or the .NET key are not necessary with parse-server
32 | // If you wish you require them, you can set them as options in the initialization above:
33 | // javascriptKey, restAPIKey, dotNetKey, clientKey
34 |
35 | const app = express();
36 |
37 | // Serve static assets from the /public folder
38 | app.use(express.static(path.join(__dirname, '/public')));
39 |
40 | // Mount your cloud express app
41 | app.use('/', require('./cloud/main.js').app);
42 |
43 | // Serve the Parse API on the /parse URL prefix
44 | app.use(mountPath, api);
45 |
46 | const httpServer = require('http').createServer(app);
47 | httpServer.listen(port, () => {
48 | console.log(`Running on http://localhost:${port}`);
49 | });
50 |
51 | // This will enable the Live Query real-time server
52 | ParseServer.createLiveQueryServer(httpServer);
53 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Ready-to-use Node.JS REST API for classification of indecent images.
2 |
3 | Machine Learning has already matured to the point where it should be a vital part of projects of all sizes. Advances in computer processing power, storage, data tools, web, etc made machine learning technologies to become more and more affordable. This and the constant strive for innovation, led SashiDo's team to create a **fully-functional Content Moderation Service with React based Admin Panel** built with Open-Source tools and libraries only. The result is a simple and elegant product, which is easy to maintain, can be integrated into any Node.JS project and hosted anywhere. One at a time, we will share all three layers of the Content moderation service - API, Automation Engine and beautiful Admin Panel. The content moderation REST API is just the first chunk.
4 |
5 |
6 | ## Examples & Demos
7 |
8 | These are the examples and the demos of what you'll have in your tools set after you deploy and integrate this repo in your projects. We've prepared examples only for some of the classes. For the other classes we think you should experiment by yourself ... `you know what I mean ;)`.
9 |
10 |
| Image Source | 14 |Image Source | 15 |Image Source | 16 |
|---|---|---|
|
19 |
21 | |
25 |
26 |
28 | |
32 |
33 |
35 | |
39 |
| Classification Result | 42 |Classification Result | 43 |Classification Result | 44 |
47 | [{
48 | "className": "Neutral",
49 | "probability": 0.93821
50 | }, {
51 | "className": "Drawing",
52 | "probability": 0.05473
53 | }, {
54 | "className": "Sexy",
55 | "probability": 0.00532
56 | }, {
57 | "className": "Hentai",
58 | "probability": 0.00087
59 | }, {
60 | "className": "Porn",
61 | "probability": 0.00085
62 | }]
63 | |
64 |
65 | [{
66 | "className": "Sexy",
67 | "probability": 0.99394
68 | }, {
69 | "className": "Neutral",
70 | "probability": 0.00432
71 | }, {
72 | "className": "Porn",
73 | "probability": 0.00164
74 | }, {
75 | "className": "Drawing",
76 | "probability": 0.00006
77 | }, {
78 | "className": "Hentai",
79 | "probability": 0.00001
80 | }]
81 | |
82 |
83 | [{
84 | "className": "Drawing",
85 | "probability": 0.96063
86 | }, {
87 | "className": "Neutral",
88 | "probability": 0.03902
89 | }, {
90 | "className": "Hentai",
91 | "probability": 0.00032
92 | }, {
93 | "className": "Sexy",
94 | "probability": 0.00001
95 | }, {
96 | "className": "Porn",
97 | "probability": 0.00005
98 | }]
99 | |
100 |
| Neutral Demo> 103 | | 104 |Sexy Demo> 105 | | 106 |Drawing Demo> 107 | | 108 |