Skip to content

Commit

Permalink
update web page
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasxlu committed Mar 21, 2019
1 parent 606c72b commit 89569be
Show file tree
Hide file tree
Showing 9 changed files with 205 additions and 3 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ nlp/__pycache__/
__pycache__/
pyWeb/
research/imgcensor/model/
cv/model/
cv/model/
cv/static/ImgCensorUpload/
cv/static/SkinUpload/
117 changes: 117 additions & 0 deletions cv/controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,73 @@ def infer_from_img(self, img):
}


class NSFWEstimator:
"""
NSFW Estimator Class Wrapper
"""

def __init__(self, pretrained_model_path="cv/model/DenseNet121_NSFW.pth", num_cls=5):
self.num_cls = num_cls
model = models.densenet121(pretrained=True)
num_ftrs = model.classifier.in_features
model.classifier = nn.Linear(num_ftrs, self.num_cls)

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

model.load_state_dict(torch.load(pretrained_model_path))

model.to(device)
model.eval()

self.device = device
self.model = model
self.topK = 5
self.mapping = {
0: 'drawings',
1: 'hentai',
2: 'neutral',
3: 'porn',
4: 'sexy'
}

def infer(self, img_file):
img = Image.open(img_file)

preprocess = transforms.Compose([
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])

img = preprocess(img)
img.unsqueeze_(0)

img = img.to(self.device)

outputs = self.model(img)
outputs = F.softmax(outputs, dim=1)

topK_prob, topK_label = torch.topk(outputs, self.topK)
prob = topK_prob.to("cpu").detach().numpy().tolist()

_, predicted = torch.max(outputs.data, 1)

return {
"status": 0,
"message": "success",
"results": [
{
"prob": round(prob[0][i], 4),
"type": self.mapping[int(topK_label[0][i].to("cpu"))],
} for i in range(self.topK)
]
}


beauty_recognizer = BeautyRecognizer()
skin_disease_recognizer = SkinDiseaseRecognizer(num_cls=198)
nsfw_estimator = NSFWEstimator(num_cls=5)


def upload_and_rec_beauty(request):
Expand Down Expand Up @@ -334,3 +399,55 @@ def upload_and_rec_skin_disease(request):
json_result = json.dumps(result, ensure_ascii=False)

return HttpResponse(json_result)


def upload_and_rec_porn(request):
"""
upload and recognize porn image
:param request:
:return:
"""
image_dir = 'cv/static/ImgCensorUpload'
if not os.path.exists(image_dir):
os.makedirs(image_dir)

result = {}

if request.method == "POST":
image = request.FILES.get("image", None)
if not image:
result['code'] = 3
result['msg'] = 'Invalid Path for Image'
result['results'] = None

json_result = json.dumps(result, ensure_ascii=False)

return HttpResponse(json_result)
else:
destination = open(os.path.join(image_dir, image.name), 'wb+')
for chunk in image.chunks():
destination.write(chunk)
destination.close()

tik = time.time()
imagepath = URL_PORT + '/static/ImgCensorUpload/' + image.name

nswf_result = nsfw_estimator.infer(os.path.join(image_dir, image.name))

result['code'] = 0
result['msg'] = 'success'
result['imgpath'] = imagepath
result['results'] = nswf_result['results']
result['elapse'] = round(time.time() - tik, 2)

json_str = json.dumps(result, ensure_ascii=False)

return HttpResponse(json_str)
else:
result['code'] = 3
result['msg'] = 'Invalid HTTP Method'
result['data'] = None

json_result = json.dumps(result, ensure_ascii=False)

return HttpResponse(json_result)
Binary file modified cv/static/img/portfolio-1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified cv/static/img/portfolio-3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion cv/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ <h2>Research Achievements</h2>
<div class="row">
<div class="col-md-6">
<div class="portfolio-item">
<a href="#">
<a href="nsfwview" target="_blank">
<img class="img-portfolio img-responsive"
src="/static/img/portfolio-1.png">
</a>
Expand Down
3 changes: 2 additions & 1 deletion cv/templates/mcloud.html
Original file line number Diff line number Diff line change
Expand Up @@ -541,8 +541,9 @@ <h5>We're on social networks</h5>
<div class="col-md-12">
<p>Copyright &copy; LucasX. All rights reserved.</p>
<div class="credits">
Designed by LucasX.
Designed by <a href="https://www.zhihu.com/people/xulu-0620">LucasX</a>.
</div>
<p>Powered by <a href="index">XCloud</a></p>
</div>
</div>
</div>
Expand Down
71 changes: 71 additions & 0 deletions cv/templates/nsfw.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Porn Image Recognition</title>
{# {% load static %}#}
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<link rel="stylesheet"
href="http://cdn.amazeui.org/amazeui/2.7.2/css/amazeui.min.css">
<link rel="icon" type="image/png" sizes="192x192" href="/static/favicon.ico">
<script src="http://cdn.amazeui.org/amazeui/2.7.2/js/amazeui.min.js"></script>
<script src="http://cdn.amazeui.org/amazeui/2.7.2/js/amazeui.ie8polyfill.min.js"></script>
<script src="http://cdn.amazeui.org/amazeui/2.7.2/js/amazeui.widgets.helper.min.js"></script>
</head>
<body>
<h2 align="center">Porn Image Recognition</h2>
<div align="center">
<form enctype="multipart/form-data">{% csrf_token %}
<div class="am-form-group am-form-file">
<button type="button" class="am-btn am-btn-danger am-btn-sm">
<i class="am-icon-cloud-upload"></i> Choose Image
<input type="file" placeholder="upload image" name="image">
{# <input id="doc-form-file" type="file" multiple>#}
</button>
</div>
<input type="button" value="detect" id='upload-btn'
class="am-btn am-btn-success" onclick="upload()">
</form>
<img class="am-img-responsive" alt="" src="" style="max-height: 320px;
margin-top: 5px"/>
</div>
<div align="center">
<p>The image is <span id="desc" style="color:
red"></span>, AI takes
<span id="time" style="color: red">0</span> seconds!
</p>
</div>

<footer style="text-align: center">
Powered by <a href="http://www.lucasx.top:8001/cv/mcloud" target="_blank">MCloud</a>
Supported by <a href="https://www.zhihu.com/people/xulu-0620/activities"
target="_blank">LucasX</a>
</footer>

<script>
function upload() {
var src = $("input[name='image']").val();
var imgName = src.split("\\")[src.split('\\').length - 1];
var data = new FormData($('form').get(0));

$.ajax({
url: 'nsfw',
type: 'POST',
data: data,
cache: false,
processData: false,
contentType: false,
success: function (data) {
console.log('success');
var result = eval('(' + data + ')');
$('#desc').text(result.results[0].type);
$('#time').text(result.elapse);
$('img').attr('src', '../../../static/ImgCensorUpload/' + imgName);
}
});

return false;
}
</script>
</body>
</html>
2 changes: 2 additions & 0 deletions cv/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
# path('sdr', views.sdr, name='sdr'),
url('fbpview', views.fbp_view, name='fbpview'),
url('fbp', views.fbp, name='fbp'),
url('nsfwview', views.nsfw_view, name='nsfwview'),
url('nsfw', views.nsfw, name='nsfw'),
url('skinview', views.skin_view, name='skinview'),
url('mcloud/skin', views.rec_skin, name='recskin'),
url('detectface', views.detect_face, name='detectface'),
Expand Down
9 changes: 9 additions & 0 deletions cv/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ def skin_view(request):
return render(request, 'skin.html')


def nsfw_view(request):
return render(request, 'nsfw.html')


def nsfw(request):
from cv import controllers
return controllers.upload_and_rec_porn(request)


def detect_face(request):
"""
face detection
Expand Down

0 comments on commit 89569be

Please sign in to comment.