Skip to content

Commit e197224

Browse files
SamSam
Sam
authored and
Sam
committed
use a different face recognition api , old one depreciated
1 parent 33ab340 commit e197224

File tree

3 files changed

+22
-141
lines changed

3 files changed

+22
-141
lines changed

faceSquares.py

+9-8
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from PIL import Image , ImageDraw , ImageFilter
22
import faceapi, urllib2
33
from StringIO import StringIO
4-
4+
import pprint
55
#had to make this method because PIL wont let me draw a rectangle properly
66
def drawRect(img,top_left,bottom_right, width , color):
77
draw = ImageDraw.Draw(img)
@@ -36,7 +36,6 @@ def drawRect(img,top_left,bottom_right, width , color):
3636
draw.line(l4, fill=color, width=width)
3737

3838
def getImageFromUrl(url):
39-
print url
4039
opener1 = urllib2.build_opener()
4140
page1 = opener1.open(url)
4241
data = StringIO(page1.read())
@@ -46,20 +45,22 @@ def getImageFromUrl(url):
4645
def drawTags(tags,imgurl):
4746
image = getImageFromUrl(imgurl).convert('RGB').filter(ImageFilter.FIND_EDGES)
4847
for tag in tags:
48+
pprint.pprint(tag)
4949
if tag.has_key('attributes'):
50-
if tag['attributes'].has_key('gender'):
51-
gender = tag['attributes']['gender']['value']
50+
if tag['attributes'][0].has_key('gender'):
51+
gender = tag['attributes'][0]['gender']
5252
center = int(tag['center']['x']) , int(tag['center']['y'])
5353
height = int(tag['height'])
5454
width = int(tag['width'])
55+
print gender,center,width,height,image
5556
drawTag(gender,center,width,height,image)
5657
return image
5758

5859
def drawTag(gender,center,width,height,im):
59-
c1 = (center[0] - (width/2)) * im.size[0]/100 , (center[1] - (height/2)) * im.size[1]/100
60-
c3 = (center[0] + (width/2)) * im.size[0]/100 , (center[1] + (height/2)) * im.size[1]/100
61-
c2 = (center[0] + (width/2)) * im.size[0]/100 , (center[1] - (height/2)) * im.size[1]/100
62-
c4 = (center[0] - (width/2)) * im.size[0]/100 , (center[1] + (height/2)) * im.size[1]/100
60+
c1 = (center[0] - (width/2)) , (center[1] - (height/2))
61+
c3 = (center[0] + (width/2)) , (center[1] + (height/2))
62+
c2 = (center[0] + (width/2)) , (center[1] - (height/2))
63+
c4 = (center[0] - (width/2)) , (center[1] + (height/2))
6364
if gender == 'female':
6465
drawRect(im,c1,c3,width=4,color='blue')
6566
elif gender == 'male':

faceapi.py

+12-127
Original file line numberDiff line numberDiff line change
@@ -4,48 +4,14 @@
44
from botmily.db import db
55
import pprint
66

7-
def Detect(imageUrl):
8-
httpcnx = httplib.HTTPSConnection('api.face.com' , strict = True)
9-
params = {'api_key' : '2fffccb658f4e2b092bc2360e3a6ea27' , 'api_secret' : 'ecf5262853523b43625a5c384977e259' , 'urls' : imageUrl ,'detector' : 'Aggressive' ,'attributes' : 'all'}
10-
url = "/faces/detect.json"
11-
url = url + "?" + urllib.urlencode( params )
12-
httpcnx.request('GET' , url )
13-
response = httpcnx.getresponse()
14-
return json.loads(response.read())
15-
16-
def Recognize(imageUrl):
17-
httpcnx = httplib.HTTPSConnection('api.face.com' , strict = True)
18-
params = {'api_key' : '2fffccb658f4e2b092bc2360e3a6ea27' , 'api_secret' : 'ecf5262853523b43625a5c384977e259' , 'urls' : imageUrl ,'uids' : '[email protected]' ,'detector' : 'Aggressive'}
19-
url = "/faces/recognize.json"
20-
url = url + "?" + urllib.urlencode( params )
21-
httpcnx.request('GET' , url )
22-
response = httpcnx.getresponse()
23-
return json.loads(response.read())
24-
25-
def SaveTag(tid,userid):
26-
httpcnx = httplib.HTTPSConnection('api.face.com' , strict = True)
27-
params = {'api_key' : '2fffccb658f4e2b092bc2360e3a6ea27' , 'api_secret' : 'ecf5262853523b43625a5c384977e259' , 'tids' : tid ,'uid' : userid + '@shughes.uk' }
28-
url = "/tags/save.json"
29-
url = url + "?" + urllib.urlencode( params )
30-
httpcnx.request('GET' , url )
31-
response = httpcnx.getresponse()
32-
return json.loads(response.read())
7+
MASHAPE_AUTH = {'X-Mashape-Authorization': 'dWNwZDBxdnF1bjhjdnlveWdtZnNtdTBpdXhodWFrOmNlOGZiMGVlM2JkZTAzMTk0YmI2ZWNhZDBjNzMwOTFhYzQ2NzUyMTI='}
338

34-
def RemoveTag(tid):
35-
httpcnx = httplib.HTTPSConnection('api.face.com' , strict = True)
36-
params = {'api_key' : '2fffccb658f4e2b092bc2360e3a6ea27' , 'api_secret' : 'ecf5262853523b43625a5c384977e259' , 'tids' : tid }
37-
url = "/tags/remove.json"
38-
url = url + "?" + urllib.urlencode( params )
39-
httpcnx.request('GET' , url )
40-
response = httpcnx.getresponse()
41-
return json.loads(response.read())
42-
43-
def Train(userid):
44-
httpcnx = httplib.HTTPSConnection('api.face.com' , strict = True)
45-
params = {'api_key' : '2fffccb658f4e2b092bc2360e3a6ea27' , 'api_secret' : 'ecf5262853523b43625a5c384977e259' , 'uids' : userid + '@shughes.uk' }
46-
url = "/faces/train.json"
9+
def Detect(imageUrl):
10+
httpcnx = httplib.HTTPSConnection('lambda-face-detection-and-recognition.p.mashape.com' , strict = True)
11+
params = {'images':imageUrl}
12+
url = "/detect"
4713
url = url + "?" + urllib.urlencode( params )
48-
httpcnx.request('GET' , url )
14+
httpcnx.request('GET' , url , None , MASHAPE_AUTH)
4915
response = httpcnx.getresponse()
5016
return json.loads(response.read())
5117

@@ -57,13 +23,13 @@ def makeBlurb(face):
5723
if photo.has_key('tags'):
5824
facecount = 0
5925
for tag in photo['tags']:
60-
if len(tag['attributes'].keys()) > 1:
26+
if len(tag['attributes'][0].keys()) > 1:
6127
facecount += 1
6228
if facecount > 1:
6329
blurb = '%s faces in this photo, ' %facecount
6430
faceNum = 1
6531
for tag in photo['tags']:
66-
if len(tag['attributes'].keys()) > 1:
32+
if len(tag['attributes'][0].keys()) > 1:
6733
blurb = blurb +' Face %i: ' %faceNum + getTagBlurb(tag)
6834
faceNum += 1
6935
elif facecount == 1:
@@ -88,7 +54,7 @@ def cleanTags(tags):
8854
for tag in photo['tags']:
8955
if tids.has_key(tag['tid']):
9056
toPurge.append(tag)
91-
elif len(tag['attributes'].keys()) < 2:
57+
elif len(tag['attributes'][0].keys()) < 2:
9258
toPurge.append(tag)
9359
else:
9460
tids[tag['tid']] = True
@@ -103,42 +69,16 @@ def cleanTags(tags):
10369
return tags
10470

10571
def getTagBlurb(tag):
106-
print 'blargh'
10772
stringDict = {'gender' : '' , 'age' : '' , 'face' : '','glasses':'' , 'smiling':'' , 'lips':'' , 'mood': ''}
10873
attributes = tag['attributes']
10974
for attribute in attributes:
110-
if attribute == 'gender':
111-
stringDict['gender'] = "\u0002%s\u000f(%s%%) " %(attributes[attribute]['value'],attributes[attribute]['confidence'])
112-
113-
if attribute == 'age_est':
114-
stringDict['age'] = "\u0002Age\u000f: %s(%s%%) " %(attributes[attribute]['value'],attributes[attribute]['confidence'])
75+
if attribute.has_key('gender'):
76+
stringDict['gender'] = "\u0002%s\u000f(%s%%) " %(attribute['gender'],attribute['confidence'])
11577

116-
if attribute == 'mood':
117-
stringDict['mood'] = "\u0002%s\u000f(%s%%) "%(attributes[attribute]['value'],attributes[attribute]['confidence'])
11878
blurb = stringDict['gender'] + stringDict['age'] + stringDict['mood']
11979
return blurb
12080

121-
def getPeopleBlurb(tags):
122-
blurb = ''
123-
users =[]
124-
try:
125-
if len(tags['photos']) == 1:
126-
photo = tags['photos'][0]
127-
if photo.has_key('tags'):
128-
for tag in photo['tags']:
129-
if len(tag['uids']) > 0:
130-
users.append(tag['uids'][0]['uid'].rstrip('@shughes.uk'))
131-
if len(users) > 0:
132-
for user in users:
133-
blurb = blurb + '%s,' %user
134-
return blurb + ' could be in this photo'
135-
else:
136-
return None
137-
except Exception , e:
138-
print e
139-
print '\nFace Json :'
140-
print tags
141-
return None
81+
14282

14383
def getTag(face):
14484
if len(face['photos']) == 1:
@@ -147,58 +87,3 @@ def getTag(face):
14787
if len(photo['tags']) == 1:
14888
return photo['tags'][0]
14989
return None
150-
151-
def trainFace(imageUrl,nick):
152-
detectResult = Detect(imageUrl)
153-
tag = getTag(detectResult)
154-
if tag:
155-
tid = tag['tid']
156-
savedTIDS = getSavedTIDS(nick)
157-
for s_tid in savedTIDS:
158-
tid = tid + ',' + s_tid
159-
x = SaveTag(tid,nick)
160-
saved_tags = x['saved_tags']
161-
for tag in saved_tags:
162-
saveTID(nick,tag['tid'])
163-
result = Train(nick)
164-
if result.has_key('updated'):
165-
return "I now have %s picture's of %s maybe ill get good at recognizing them" %(result['updated'][0]['training_set_size'], nick)
166-
elif result.has_key('unchanged'):
167-
return 'I think I already had that picture , nothing changed'
168-
else:
169-
return "Multiple faces or I coulndt find any at all"
170-
171-
def removeMe(nick):
172-
tids = getSavedTIDS(nick)
173-
tid = ''
174-
for result in tids:
175-
tid += result
176-
RemoveTag(tid)
177-
db.execute("delete from face where nick='%s'" %nick)
178-
db.commit()
179-
return 'Done'
180-
181-
182-
183-
def getSavedTIDS(nick):
184-
cur = db.execute("select * from face where nick='%s'" %nick)
185-
result = cur.fetchall()
186-
results = []
187-
if len(result) > 0:
188-
for row in result:
189-
results.append(row[1])
190-
return results
191-
elif len(result) == 0:
192-
return []
193-
194-
def saveTID(nick , tid):
195-
cur = db.execute("select * from face where nick='%s' and tid='%s'" %(nick,tid))
196-
result = cur.fetchall()
197-
if len(result) == 1:
198-
print 'TID already exists for nick'
199-
elif len(result) > 1:
200-
print 'porblem'
201-
elif len(result) == 0:
202-
print 'Saving Tag %s' %tid
203-
db.execute("insert into face(nick, tid) values('%s', '%s')" %(nick,tid))
204-
db.commit()

plugins/face.py

+1-6
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,9 @@ def face(message_data, bot):
3535
img = faceSquares.drawTags(result['photos'][0]['tags'],imgurl)
3636
img.save('temp.png', 'PNG')
3737
postedUrl = imgur.postToImgur(str('temp.png'))
38-
result = faceapi.Recognize(imgurl)
39-
who = faceapi.getPeopleBlurb(result)
40-
if who and characteristics:
41-
return characteristics + who + ', what I saw %s' %postedUrl
42-
elif characteristics:
4338
return characteristics + ', what I saw %s' %postedUrl
4439
else:
45-
return "Couldn't find a face :("
40+
return "Couldn't find a face, you are too ugly maybe :("
4641

4742
commands = {"face": face, "passmeter": face}
4843
triggers = []

0 commit comments

Comments
 (0)