├── .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 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 25 | 32 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 64 | 82 | 100 | 101 | 102 | 104 | 106 | 108 | 109 | 110 |
Image SourceImage SourceImage Source
19 | 21 | 23 | 24 | 26 | 28 | 30 | 31 | 33 | 35 | 37 | 38 |
Classification ResultClassification ResultClassification Result
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 |
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 |
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 |
Neutral Demo 103 | Sexy Demo 105 | Drawing Demo 107 |
111 |
112 | 113 | ## How it works 114 | This REST API is built in Node.JS with Mongo DB and Parse Server. Classifying images may be invoked from an Express route or a Cloud Code function ( Parse Server lovers, you're welcome :) ) 115 | 116 | We have implemented [NSFW.JS](https://github.com/infinitered/nsfwjs) classification, which uses [TensorFlowJS](https://www.tensorflow.org/js) pretrained models. 117 | 118 | ## Classification map 119 | 120 | Pass the API an image and receive a JSON response, which holds the predictions on how likely this image falls into each of the following classes: 121 | 122 | *Drawing* - Harmless art, or picture of art
123 | *Hentai* - Pornographic art, unsuitable for most work environments
124 | *Neutral* - General, inoffensive content
125 | *Porn* - Indecent content and actions, often involving genitalia
126 | *Sexy* - Unseemly provocative content, can include nipples
127 | 128 | 129 | # File Structure 130 | 131 | The REST API is built on top of Parse Server. You can use it in a standard Express app, but keep in mind that the file structure of the repo is Parse specific. The code is organized in a ```src``` folder and ```src/cloud/main.js``` is the root file for the service. For more information about how the project is building on the Local env and in Production, take a look at the [package.json](https://github.com/SashiDo/content-moderation-image-api/blob/master/package.json#L14-L20) 132 | 133 | # Installation & Configuration 134 | 135 | ### Requirements: 136 | 137 | - Node.JS >= 10.2.1 138 | 139 | - Mongo DB 140 | 141 | ### Download the project 142 | 143 | Clone the repo: 144 | 145 | ``` 146 | git clone https://github.com/SashiDo/content-moderation-image-api.git 147 | cd content-moderation-image-api 148 | ``` 149 | 150 | ### Set Environment Variables 151 | 152 | Copy the env.example to .env file and set the environment variables for your local environment with your favorite editor: 153 | 154 | ``` 155 | cp env.example .env 156 | ``` 157 | 158 | Place your MongoDB URI. If your app is hosted at SashiDo, you can use the database URI of your SashiDo project. Find the connection string from the app's `Dashboard -> App -> App Settings -> Security & Keys` 159 | 160 | ### Install Dependencies 161 | 162 | As this is a full-featured example, all dependencies are present to the packege.json. You only need to run: 163 | ``` 164 | npm install 165 | ``` 166 | 167 | ### Start the project 168 | 169 | ``` 170 | npm run dev 171 | ``` 172 | 173 | **If everything is okay you should see an output similar to this one**: 174 | 175 | ``` 176 | [nodemon] 2.0.4 177 | ... 178 | [nodemon] starting `node index index.js` 179 | ✨ Built in 2.55s. 180 | node-pre-gyp ... 181 | ... 182 | Running on http://localhost:1337 183 | ⠙ Building index.js...The NSFW Model was loaded successfuly! 184 | ✨ Built in 16.41s. 185 | ``` 186 | 187 | If you see the output above, you are ready to play with the API :) 188 | 189 | # API Usage Examples 190 | 191 | The project contains two approaches for classifying images - for direct communication through the Parse SDK using Cloud Code and from an Express route. 192 | 193 | ## Classify from the Express endpoint 194 | 195 | ```bash 196 | curl http://localhost:1337/api/image/classify?url=https://nsfw-demo.sashido.io/sexy.png 197 | ``` 198 | 199 | ## Classify from a Cloud Code function via Parse SDKs 200 | 201 | You can invoke the **nsfwImageClassify function** from the client-side or using the Parse Server REST API: 202 | 203 | ### Android SDK Example 204 | 205 | ```Java 206 | HashMap params = new HashMap(); 207 | params.put("url", "https://nsfw-demo.sashido.io/sexy.png"); 208 | ParseCloud.callFunctionInBackground("nsfwImageClassify", params, new FunctionCallback() { 209 | void done(Object predictions, ParseException e) { 210 | if (e == null) { 211 | // prediction 212 | } 213 | } 214 | }); 215 | ``` 216 | 217 | More information about how to work with the Android SDK can be found in the [official docs](https://docs.parseplatform.org/android/guide/#use-cloud-code). 218 | 219 | 220 | 221 | ### iOS SDK Example 222 | 223 | ```Swift 224 | PFCloud.callFunctionInBackground("nsfwImageClassify", withParameters: ["url":"https://nsfw-demo.sashido.io/sexy.png"]) { 225 | (predictions, error) in 226 | if !error { 227 | // prediction 228 | } 229 | } 230 | ``` 231 | 232 | More information about how to work with the Parse iOS SDK can be found in the [official docs](https://docs.parseplatform.org/ios/guide/#use-cloud-code). 233 | 234 | 235 | ### REST API Example 236 | 237 | ``` 238 | curl -X POST \ 239 | -H "X-Parse-Application-Id: myAppId" \ 240 | -H "X-Parse-REST-API-Key: myRestKey" \ 241 | -H "Content-Type: application/json" \ 242 | -d '{ "url": "https://nsfw-demo.sashido.io/sexy.png" }' \ 243 | http://localhost:1337/1/functions/nsfwImageClassify 244 | ``` 245 | 246 | More information about how to work with the Parse REST API can be found in the [official docs](http://docs.parseplatform.org/rest/guide/#cloud-code). 247 | 248 | 249 | SashiDo users can test all Cloud Code functions from our super-friendly [API Console](https://blog.sashido.io/introducing-the-api-console/) that’s built in the Dashboard. Moreover, it gives you the option to export ay request to cURL. 250 | 251 | 252 | # Deployment on Production 253 | 254 | ## 1. Environment Variables Setup 255 | 256 | For production, you need to set the **NSFW model URL** and the **NSFW Model Shape size**. SashiDo stores three NSFW models, each one you can set easily using the following URLs: 257 | 258 | 259 | | Model URL | Size | Shape Size | Accuracy | 260 | | :---------------------------------------------------------- | :----: | :--------: | :------: | 261 | | https://ml.files-sashido.cloud/models/nsfw_inception_v3/ | Huge | 299 | 93% | 262 | | https://ml.files-sashido.cloud/models/nsfw_mobilenet_v2/90/ | 2.6 MB | 224 | 90% | 263 | | https://ml.files-sashido.cloud/models/nsfw_mobilenet_v2/93/ | 4.2 MB | 224 | 93% | 264 | 265 | **Please note** *the Inception_v3 model used for this projects has high RAM/CPU consumption. While the two mobilenet models are far more lightweight.* 266 | 267 | ### Choose the model and set the following environment variables for your live server: 268 | 269 | ```sh 270 | TF_MODEL_URL = MODEL_URL 271 | TF_MODEL_INPUT_SHAPE_SIZE = MODEL_SHAPE_SIZE 272 | 273 | # Example 274 | TF_MODEL_URL="https://ml.files-sashido.cloud/models/nsfw_mobilenet_v2/93/" 275 | TF_MODEL_INPUT_SHAPE_SIZE=224 276 | ``` 277 | 278 | ## 2. Code Deployment 279 | 280 | ### Deployment on SashiDo 281 | 282 | This is probably the simplest way to deploy the code in production. At SashiDo we have implemented an automatic git deployment process following the [The Twelve Factor App](https://12factor.net/) principle. 283 | 284 | Connect your SashiDo app with GitHub, check [here](https://blog.sashido.io/how-to-start-using-github-with-sashido-for-beginners/) for more details how to start using GitHub with SashiDo. 285 | 286 | Next, the code can be easily deployed with two simple commands for adding a remote branch and pushing the code. 287 | 288 | ```sh 289 | git remote add production git@github.com:parsegroundapps/.git 290 | git push -f production master 291 | ``` 292 | 293 | ### Deployment on other providers 294 | 295 | Basically, you need to follow the same steps as for SashiDo Deployment. Simply follow the requirements of your hosting provider when setting environment variables for production and deploying the code. 296 | 297 | # What's next? 298 | 299 | To get a further insight into the project and what inspired us to build this service, check out our blog post on the topic here. 300 | 301 | The REST API is a part of the Content Moderation service, which also offers: 302 | 303 | - [**Automation Engine**](https://github.com/SashiDo/content-moderation-automations) that will automatically delete inappropriate images. Set the params and reduce manual work to the bare minimum. - Coming Soon! 304 | 305 | - [**Admin Panel**](https://github.com/SashiDo/content-moderation-application) where all images in need of moderation are stacked up in a beautiful interface, which allows you to make decisions with just a click. - Coming Soon! 306 | # Contribution 307 | 308 | Thanks for looking at this section. We’re open to any cool ideas, so if you have one and are willing to share - fork the repo, apply changes and open a pull request. :) 309 | 310 | # License 311 | 312 | Copyright © 2020, CloudStrap AD. See [LICENSE](https://github.com/SashiDo/content-moderation-image-api/blob/master/LICENSE) for further details. 313 | --------------------------------------------------------------------------------