Skip to content
This repository has been archived by the owner on Apr 18, 2022. It is now read-only.

Commit

Permalink
python: fix image encoding for Python 3.
Browse files Browse the repository at this point in the history
Fixes face detection, text detection, Twilio, utils, and awwvision for
Python 3. The label detection was already fixed by an external PR.
  • Loading branch information
tswast committed Mar 24, 2016
1 parent 6e068d3 commit 255b2a1
Show file tree
Hide file tree
Showing 7 changed files with 26 additions and 24 deletions.
2 changes: 1 addition & 1 deletion python/awwvision/worker/src/vision.py
Expand Up @@ -39,7 +39,7 @@ def detect_labels(self, images, max_results=2, num_retries=3):
for image in images:
batch_request.append({
'image': {
'content': base64.b64encode(image)
'content': base64.b64encode(image).decode('UTF-8')
},
'features': [{
'type': 'LABEL_DETECTION',
Expand Down
2 changes: 1 addition & 1 deletion python/face_detection/faces.py
Expand Up @@ -51,7 +51,7 @@ def detect_face(face_file, max_results=4):
image_content = face_file.read()
batch_request = [{
'image': {
'content': base64.b64encode(image_content)
'content': base64.b64encode(image_content).decode('UTF-8')
},
'features': [{
'type': 'FACE_DETECTION',
Expand Down
11 changes: 6 additions & 5 deletions python/text/README.md
Expand Up @@ -61,7 +61,7 @@ Either method will include the desired subdirectory
The rest of the tutorial assumes this as your working directory.


This example has been tested with Python 2.7.
This example has been tested with Python 2.7 and 3.4.

### Install the Libraries Used by the Example

Expand Down Expand Up @@ -215,7 +215,8 @@ class VisionApi:
for filename in images:
batch_request.append({
'image': {
'content': base64.b64encode(images[filename])
'content': base64.b64encode(
images[filename]).decode('UTF-8')
},
'features': [{
'type': 'TEXT_DETECTION',
Expand Down Expand Up @@ -243,9 +244,9 @@ class VisionApi:
else:
text_response[filename] = []
return text_response
except errors.HttpError, e:
except errors.HttpError as e:
print("Http Error for %s: %s" % (filename, e))
except KeyError, e2:
except KeyError as e2:
print("Key error: %s" % e2)
```

Expand Down Expand Up @@ -281,7 +282,7 @@ def extract_description(texts):
for text in texts:
try:
document += text['description']
except KeyError, e:
except KeyError as e:
print('KeyError: %s\n%s' % (e, text))
return document

Expand Down
9 changes: 5 additions & 4 deletions python/text/textindex.py
Expand Up @@ -85,7 +85,8 @@ def detect_text(self, input_filenames, num_retries=3, max_results=6):
for filename in images:
batch_request.append({
'image': {
'content': base64.b64encode(images[filename])
'content': base64.b64encode(
images[filename]).decode('UTF-8')
},
'features': [{
'type': 'TEXT_DETECTION',
Expand Down Expand Up @@ -113,9 +114,9 @@ def detect_text(self, input_filenames, num_retries=3, max_results=6):
else:
text_response[filename] = []
return text_response
except errors.HttpError, e:
except errors.HttpError as e:
print("Http Error for %s: %s" % (filename, e))
except KeyError, e2:
except KeyError as e2:
print("Key error: %s" % e2)
# [END detect_text]

Expand Down Expand Up @@ -231,7 +232,7 @@ def extract_description(texts):
for text in texts:
try:
document += text['description']
except KeyError, e:
except KeyError as e:
print('KeyError: %s\n%s' % (e, text))
return document

Expand Down
2 changes: 1 addition & 1 deletion python/twilio-labels/whats_that.py
Expand Up @@ -106,7 +106,7 @@ def get_labels(image, num_retries=3, max_results=3):
discoveryServiceUrl=DISCOVERY_URL)

# Prepare the image for the API
image_content = base64.b64encode(image)
image_content = base64.b64encode(image).decode('UTF-8')

# Construct the request
service_request = service.images().annotate(
Expand Down
4 changes: 2 additions & 2 deletions python/utils/generatejson.py
Expand Up @@ -64,7 +64,7 @@ def main(input_file, output_filename):
# First, get the image data
with open(image_filename, 'rb') as image_file:
content_json_obj = {
'content': base64.b64encode(image_file.read())
'content': base64.b64encode(image_file.read()).decode('UTF-8')
}

# Then parse out all the features we want to compute on this image
Expand Down Expand Up @@ -145,5 +145,5 @@ def get_detection_type(detect_num):
try:
with open(args.input_file, 'r') as input_file:
main(input_file, args.output_file)
except ValueError, e:
except ValueError as e:
sys.exit('Invalid input file format.\n' + FILE_FORMAT_DESCRIPTION)
20 changes: 10 additions & 10 deletions python/utils/generatejson_test.py
Expand Up @@ -14,46 +14,46 @@

import json
import os
import StringIO
import shutil
import tempfile
import unittest
from io import StringIO

from .generatejson import main
from generatejson import main


class TestGenerateJson(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.image_name = os.path.join(
os.path.dirname(__file__), 'generatejson_test_fake.jpg')
os.path.dirname(__file__), u'generatejson_test_fake.jpg')

def tearDown(self):
shutil.rmtree(self.temp_dir)

def test_no_features(self):
input_file = StringIO.StringIO(self.image_name)
input_file = StringIO(self.image_name)
output_filename = os.path.join(self.temp_dir, 'empty_file.json')
with self.assertRaises(ValueError):
main(input_file, output_filename)
self.assertFalse(os.path.exists(output_filename))

def test_no_image(self):
input_file = StringIO.StringIO('doesnotexist.jpg 1:1')
input_file = StringIO(u'doesnotexist.jpg 1:1')
output_filename = os.path.join(self.temp_dir, 'empty_file.json')
with self.assertRaises(IOError):
main(input_file, output_filename)
self.assertFalse(os.path.exists(output_filename))

def test_no_max(self):
input_file = StringIO.StringIO(self.image_name + ' 1')
input_file = StringIO(self.image_name + ' 1')
output_filename = os.path.join(self.temp_dir, 'empty_file.json')
with self.assertRaises(ValueError):
main(input_file, output_filename)
self.assertFalse(os.path.exists(output_filename))

def test_one_detection(self):
input_file = StringIO.StringIO(self.image_name + ' 1:1')
input_file = StringIO(self.image_name + ' 1:1')
output_filename = os.path.join(self.temp_dir, 'empty_file.json')
main(input_file, output_filename)
self.assertTrue(os.path.exists(output_filename))
Expand All @@ -70,7 +70,7 @@ def test_one_detection(self):
1, obj['requests'][0]['features'][0]['maxResults'])

def test_multiple_detections(self):
input_file = StringIO.StringIO(self.image_name + ' 1:1 2:3')
input_file = StringIO(self.image_name + ' 1:1 2:3')
output_filename = os.path.join(self.temp_dir, 'empty_file.json')
main(input_file, output_filename)
self.assertTrue(os.path.exists(output_filename))
Expand All @@ -91,7 +91,7 @@ def test_multiple_detections(self):
3, obj['requests'][0]['features'][1]['maxResults'])

def test_multiple_lines(self):
input_file = StringIO.StringIO(
input_file = StringIO(
'%s 1:2\n%s 2:1' % ((self.image_name,) * 2))
output_filename = os.path.join(self.temp_dir, 'empty_file.json')
main(input_file, output_filename)
Expand All @@ -106,7 +106,7 @@ def test_multiple_lines(self):
self.assertIn('content', obj['requests'][i]['image'])

def test_bad_detection_type(self):
input_file = StringIO.StringIO(self.image_name + ' 125:1')
input_file = StringIO(self.image_name + ' 125:1')
output_filename = os.path.join(self.temp_dir, 'empty_file.json')
main(input_file, output_filename)
self.assertTrue(os.path.exists(output_filename))
Expand Down

0 comments on commit 255b2a1

Please sign in to comment.