0x0/nsfw_detect.py

53 lines
1.5 KiB
Python
Raw Normal View History

2017-10-27 05:22:11 +02:00
#!/usr/bin/env python3
2020-11-03 04:01:30 +01:00
"""
2024-09-25 18:12:39 +02:00
Copyright © 2024 Mia Herkt
2020-11-03 04:01:30 +01:00
Licensed under the EUPL, Version 1.2 or - as soon as approved
by the European Commission - subsequent versions of the EUPL
(the "License");
You may not use this work except in compliance with the License.
You may obtain a copy of the license at:
https://joinup.ec.europa.eu/software/page/eupl
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.
"""
2017-10-27 05:22:11 +02:00
import os
import sys
from pathlib import Path
2017-10-27 05:22:11 +02:00
import av
2024-09-25 18:12:39 +02:00
from transformers import pipeline
2017-10-27 05:22:11 +02:00
class NSFWDetector:
def __init__(self):
2024-09-25 18:12:39 +02:00
self.classifier = pipeline("image-classification", model="giacomoarienti/nsfw-classifier")
2017-10-27 05:22:11 +02:00
def detect(self, fpath):
try:
with av.open(fpath) as container:
try: container.seek(int(container.duration / 2))
except: container.seek(0)
frame = next(container.decode(video=0))
2024-09-25 18:12:39 +02:00
img = frame.to_image()
res = self.classifier(img)
2024-09-25 18:12:39 +02:00
return max([x["score"] for x in res if x["label"] not in ["neutral", "drawings"]])
except: pass
2017-10-27 05:22:11 +02:00
2024-09-25 18:12:39 +02:00
return -1.0
2017-10-27 05:22:11 +02:00
if __name__ == "__main__":
n = NSFWDetector()
for inf in sys.argv[1:]:
score = n.detect(inf)
print(inf, score)