-
Notifications
You must be signed in to change notification settings - Fork 64
Support more content types for the NSFWProtector #594
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Half-Shot
wants to merge
10
commits into
main
Choose a base branch
from
hs/nsfw-handle-more-filetypes
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
16091ea
Add support for thumbnailing via ffmpeg.
Half-Shot c65930a
Fixup NSFW thumbnailer.
Half-Shot 61b0b1b
Include ffmpeg in docker container
Half-Shot dd4fde8
Update some deps.
Half-Shot c94c19c
Merge branch 'main' into hs/nsfw-handle-more-filetypes
Half-Shot b2137c6
More tweaks
Half-Shot 6c05bb9
fix model name
Half-Shot 6a96dc7
fix type
Half-Shot 805ec8e
drop a couple of lines
Half-Shot c1bffde
add a break
Half-Shot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,20 +17,113 @@ limitations under the License. | |
| import { Protection } from "./IProtection"; | ||
| import { Mjolnir } from "../Mjolnir"; | ||
| import * as nsfw from "nsfwjs"; | ||
| import { LogLevel, LogService } from "@vector-im/matrix-bot-sdk"; | ||
| import { node } from "@tensorflow/tfjs-node"; | ||
| import { LogLevel, LogService, MXCUrl } from "@vector-im/matrix-bot-sdk"; | ||
| import { node, Tensor3D } from "@tensorflow/tfjs-node"; | ||
| import { spawn } from "node:child_process"; | ||
| import { ReadableStream } from "node:stream/web"; | ||
|
|
||
| const TENSOR_SUPPORTED_TYPES = [ | ||
| "image/png", | ||
| "image/apng", | ||
| "image/bmp", | ||
| "image/x-bmp", | ||
| "image/gif", | ||
| "image/jpeg", | ||
| "image/jp2", | ||
| "image/jpx", | ||
| "image/jpm", | ||
| ]; | ||
|
|
||
| const FFMPEG_SUPPORTED_TYPES = ["video/", "image/"]; | ||
|
|
||
| const FFMPEG_EXTRA_ARGS: Record<string, string[]> = { | ||
| // Extra params needed to extract svg thumbnails. | ||
| "image/svg+xml": ["-f", "svg_pipe", "-frame_size", "10000", "-video_size", "512x512"], | ||
| }; | ||
|
|
||
| export class NsfwProtection extends Protection { | ||
| settings = {}; | ||
| // @ts-ignore | ||
| private model: any; | ||
| private model: nsfw.NSFWJS; | ||
|
|
||
| private classificationCache = new Map<string, boolean>(); | ||
|
|
||
| /** | ||
| * Extract the first frame from a video or image source. | ||
| * @param ffmpegPath The path to the `ffmpeg` binary. | ||
| * @param stream The stream containing the source. | ||
| * @param mimetype The mimetype provided by the source. | ||
| * | ||
| * @returns A byte array containing the thumbnail in JPEG format. | ||
| */ | ||
| static async extractFrame( | ||
| ffmpegPath: string, | ||
| stream: ReadableStream<Uint8Array>, | ||
| mimetype: string, | ||
| ): Promise<Uint8Array> { | ||
| const errData: Buffer[] = []; | ||
| const imageData: Buffer[] = []; | ||
| const extraArgs = FFMPEG_EXTRA_ARGS[mimetype] ?? []; | ||
| const cmd = spawn(ffmpegPath, [ | ||
| ...extraArgs, | ||
| "-i", | ||
| "-", | ||
| "-update", | ||
| "true", | ||
| "-frames:v", | ||
| "1", | ||
| "-f", | ||
| "image2", | ||
| "-", | ||
| ]); | ||
| let stdinErrorFinished!: Promise<void>; | ||
| const p = new Promise<Uint8Array>((resolve, reject) => { | ||
| cmd.once("exit", (code) => { | ||
| if (code !== 0) { | ||
| reject(new Error(`FFMPEG failed to run: ${code}, ${Buffer.concat(errData).toString()}`)); | ||
| } else { | ||
| resolve(Buffer.concat(imageData)); | ||
| } | ||
| }); | ||
| cmd.stderr.on("data", (b) => { | ||
| errData.push(b); | ||
| }); | ||
| cmd.stdout.on("data", (b) => { | ||
| imageData.push(b); | ||
| }); | ||
| // EPIPE is "normal" for ffmpeg to emit after it's finished processing an input. | ||
| stdinErrorFinished = new Promise((res, rej) => { | ||
| cmd.stdin.once("error", (e: { code: string }) => { | ||
| if (e.code !== "EPIPE") { | ||
| LogService.debug("NsfwProtection", "Unexpected error from ffmpeg", e); | ||
| rej(e); | ||
| } | ||
| res(); | ||
| }); | ||
| }); | ||
| }); | ||
| for await (const element of stream) { | ||
| if (cmd.stdin.write(element) === false) { | ||
| // Wait for either a drain, or the whole stream to complete | ||
| await Promise.race([stdinErrorFinished, new Promise((r) => cmd.stdin.once("drain", r))]); | ||
| } | ||
| } | ||
| if (!cmd.stdin.writableEnded) { | ||
| cmd.stdin.end(); | ||
| } | ||
| try { | ||
| return await p; | ||
| } finally { | ||
| LogService.debug("NsfwProtection", `Generated thumbnail`); | ||
| } | ||
| } | ||
|
|
||
| constructor() { | ||
| super(); | ||
| } | ||
|
|
||
| async initialize() { | ||
| this.model = await nsfw.load(); | ||
| async initialize(modelName: string) { | ||
| this.model = await nsfw.load(modelName); | ||
| } | ||
|
|
||
| public get name(): string { | ||
|
|
@@ -44,6 +137,57 @@ export class NsfwProtection extends Protection { | |
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Given a MXC URL, attempt to extract a image supported by our NSFW model. | ||
| * @param mjolnir The mjolnir instance. | ||
| * @param mxc The MXC url. | ||
| * @returns Bytes of an image processable by the model. | ||
| */ | ||
| private async determineImageFromMedia(mjolnir: Mjolnir, mxc: MXCUrl): Promise<Uint8Array | null> { | ||
| const res = await fetch( | ||
| `${mjolnir.client.homeserverUrl}/_matrix/client/v1/media/download/${encodeURIComponent(mxc.domain)}/${encodeURIComponent(mxc.mediaId)}`, | ||
| { | ||
| headers: { | ||
| Authorization: `Bearer ${mjolnir.client.accessToken}`, | ||
| }, | ||
| }, | ||
| ); | ||
| if (!res.body || res.status !== 200) { | ||
| LogService.error("NsfwProtection", `Could not fetch mxc ${mxc}: ${res.status}`); | ||
| return null; | ||
| } | ||
| const contentType = res.headers.get("content-type")?.split(";")[0]; | ||
| if (!contentType) { | ||
| LogService.warn("NsfwProtection", `No content type header specified`); | ||
| return null; | ||
| } | ||
| console.log(contentType); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Wondering if this is a stray from debugging :) |
||
| if (TENSOR_SUPPORTED_TYPES.includes(contentType)) { | ||
| return new Uint8Array(await res.arrayBuffer()); | ||
| } | ||
| // Why do we do this? | ||
| // - We don't want to trust client thumbnails, which might not match the content. Or they might | ||
| // not exist at all (which forces clients to generate their own) | ||
| // - We also don't want to make our homeserver generate thumbnails of potentially | ||
| // harmful images, so this locally generates a thumbnail of a range of types in memory. | ||
| if (mjolnir.config.ffmpegPath && FFMPEG_SUPPORTED_TYPES.some((mt) => contentType.startsWith(mt))) { | ||
| const stream = res.body as ReadableStream<Uint8Array>; | ||
| try { | ||
| LogService.debug( | ||
| "NsfwProtection", | ||
| `Image type ${contentType} is unsupported by model, attempting to generate thumbnail`, | ||
| ); | ||
| return await NsfwProtection.extractFrame(mjolnir.config.ffmpegPath, stream, contentType); | ||
| } catch (ex) { | ||
| LogService.warn("NsfwProtection", "Could not extract thumbnail from image", ex); | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| LogService.debug("NsfwProtection", `Unsupported file type ${contentType}`); | ||
| return null; | ||
| } | ||
|
|
||
| public async handleEvent(mjolnir: Mjolnir, roomId: string, event: any): Promise<any> { | ||
| if (event.type !== "m.room.message" && event.type !== "m.sticker") { | ||
| return; | ||
|
|
@@ -66,27 +210,46 @@ export class NsfwProtection extends Protection { | |
| } | ||
|
|
||
| for (const mxc of mxcs) { | ||
| const image = await mjolnir.client.downloadContent(mxc); | ||
| // If we've already scanned this media, return early. | ||
| if (this.classificationCache.has(mxc)) { | ||
| if (this.classificationCache.get(mxc)) { | ||
| await this.redactEvent(mjolnir, roomId, event, room); | ||
| break; | ||
| } | ||
| continue; | ||
| } | ||
|
|
||
| let decodedImage; | ||
| const data = await this.determineImageFromMedia(mjolnir, MXCUrl.parse(mxc)); | ||
| if (!data) { | ||
| // Couldn't extract an image, skip. | ||
| continue; | ||
| } else { | ||
| LogService.debug("NsfwProtection", `Thumbnail generated for ${mxc}`); | ||
| } | ||
| let decodedImage: Tensor3D | undefined; | ||
| try { | ||
| decodedImage = await node.decodeImage(image.data, 3); | ||
| decodedImage = (await node.decodeImage(data, 3)) as Tensor3D; | ||
| const predictions = await this.model.classify(decodedImage); | ||
| LogService.debug("NsfwProtection", `Classified ${mxc} as`, predictions); | ||
| const isNsfw = predictions.some( | ||
| (prediction) => | ||
| ["Hentai", "Porn"].includes(prediction.className) && | ||
| prediction.probability > mjolnir.config.nsfwSensitivity, | ||
| ); | ||
| this.classificationCache.set(mxc, isNsfw); | ||
| if (isNsfw) { | ||
| await this.redactEvent(mjolnir, roomId, event, room); | ||
| // Stop scanning media once we've redacted. | ||
| break; | ||
| } | ||
| } catch (e) { | ||
| LogService.error("NsfwProtection", `There was an error processing an image: ${e}`); | ||
| continue; | ||
| } | ||
|
|
||
| const predictions = await this.model.classify(decodedImage); | ||
|
|
||
| for (const prediction of predictions) { | ||
| if (["Hentai", "Porn"].includes(prediction["className"])) { | ||
| if (prediction["probability"] > mjolnir.config.nsfwSensitivity) { | ||
| await this.redactEvent(mjolnir, roomId, event, room); | ||
| break; | ||
| } | ||
| } finally { | ||
| if (decodedImage) { | ||
| decodedImage.dispose(); | ||
| } | ||
| } | ||
| decodedImage.dispose(); | ||
| } | ||
| } | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should it pull from somewhere in the first third-middle? Just wondering if always pulling from first frame will be easily evaded.