/
mbrecognition.py
128 lines (92 loc) · 3.67 KB
/
mbrecognition.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
from mbclient import mb
import urllib
import urllib2
import traceback
import re
import json
nsfw="^(?:n?sfw\s*(?P<url>.+\.(?:jpeg|jpg|png).*)?)|((?:is|was)\s+(?:that\s+(?:link|picture|image|pic)|it|that)\s+(?:safe|sfw|nsfw))\s*$"
tags="^(?:tags*\s+(?P<url>.+\.(?:jpeg|jpg|png).*)?)|(tags*(?:\s+on)?(?:\s+(?:that|this|it))?\s*(?:pic|picture|link|image)?)\s*$"
emotion="emotions?\s+(?P<url>.+)"
def auth():
client_id = mb.data["passwords"]["clarifai"]["client_id"]
client_secret = mb.data["passwords"]["clarifai"]["client_secret"]
data = urllib.urlencode({"client_id": client_id, "client_secret": client_secret, "grant_type":"client_credentials"}).encode("utf-8")
req = urllib2.Request("https://api.clarifai.com/v1/token",data = data)
try:
response = json.loads(urllib2.urlopen(req).read().decode("utf-8"))
except:
traceback.print_exc()
return ""
return response["access_token"]
def nsfw_func(nick,match,target):
link=match.group("url")
if not link:
link = mb.data["stuff"]["last_picture"]
url=urllib.urlencode({"url":link})
access_token = auth()
if access_token=="":
mb.tell(nick+": nope. fucking OAuth",target)
return
req = urllib2.Request("https://api.clarifai.com/v1/tag?model=nsfw-v1.0&{}".format(url));
req.add_header("Authorization","Bearer "+access_token);
try:
response = json.loads(urllib2.urlopen(req).read().decode("utf-8"));
except:
mb.tell(nick+": something aint right",target)
traceback.print_exc()
return
res=response["results"][0]["result"]["tag"];
mb.tell(nick+": "+res["classes"][0]+": "+"{0:.3f}".format(res["probs"][0])+", "+res["classes"][1]+": "+"{0:.3f}".format(res["probs"][1]),target)
def tags_func(nick,match,target):
link=match.group("url")
if not link:
link = mb.data["stuff"]["last_picture"]
url = urllib.urlencode({"url":link})
access_token = auth()
if access_token=="":
mb.tell(nick+": nope. fucking OAuth",target)
return
req = urllib2.Request("https://api.clarifai.com/v1/tag?{}".format(url));
req.add_header("Authorization","Bearer "+access_token);
try:
response = json.loads(urllib2.urlopen(req).read().decode("utf-8"));
except:
mb.tell(nick+": something aint right",target)
traceback.print_exc()
return
res=", ".join(response["results"][0]["result"]["tag"]["classes"])
mb.tell(nick+": "+res,target)
return
def emotion_func(nick,match,target):
url=json.dumps({"url":match.group("url")}).encode("utf-8")
req = urllib2.Request("https://api.projectoxford.ai/emotion/v1.0/recognize",data=url);
req.add_header("Ocp-Apim-Subscription-Key","f40e7a9a0e944f22b1bf91175c0d7e9d");
req.add_header('Content-Type', 'application/json')
try:
response = json.loads(urllib2.urlopen(req).read().decode("utf-8"));
except:
mb.tell(nick+": something aint right",target)
traceback.print_exc()
return
if response ==[]:
mb.tell(nick+": no faces on that",target)
return
faces=[]
for result in response:
emotion_list = [{"emotion":emotion,"score":score} for emotion,score in result["scores"].items()]
emotion_list = sorted(emotion_list, key = lambda k: k["score"])
scores = [entry["emotion"] for entry in emotion_list][-2:]
face = {"emotion": " and ".join(scores), "left": result["faceRectangle"]["left"]}
faces.append(face)
faces_ordered = sorted(faces, key = lambda k: k["left"])
emotions= [face["emotion"] for face in faces_ordered]
answer = nick+": "
if len(response)>1:
answer+="from left to right: "
mb.tell(answer+", ".join(emotions),target)
return
mb.add_command(emotion,emotion_func)
mb.add_command(nsfw,nsfw_func)
mb.add_command(tags,tags_func)
mb.help['recognition']="mb tags <picture url>, mb nsfw <picture url>, mb emotion <picture url>"
print('loaded recognition')