Exemplo n.º 1
0
def Caption(image_name, passs):
    auth = CV.SimpleAuth(passs)
    conn = CV.API(auth)
    Filter_chocolate = ['chocolate', 'pizza']
    filter_phone = [
        'smartphone', 'phone', 'mobile', 'Smartphone', 'Phone', 'Mobile'
    ]
    with open(image_name, 'rb') as f:
        response = conn.image_request(f, image_name, {
            'image_request[locale]': 'en-US',
        })
    status = conn.wait(response['token'], timeout=30)
    status = conn.image_response(response['token'])
    if status['status'] != cloudsight.STATUS_NOT_COMPLETED:
        try:
            caption = status['name']
            for content in Filter_chocolate:
                if content in caption:
                    print("Warning: Eating %s is injurious to Health.." %
                          content)
                    GV.speak(
                        'Warning: Eating Cholocate is injurious to Health.... Image Content'
                    )
                    break
            for content in filter_phone:
                if content in caption:
                    caption = "Alert: %s Detected.. Filtered Content.." % content

            GV.speak(caption)
            return (caption)
        except:
            print('Cannot Process this image')
    else:
        print('Cannot Process Image')
Exemplo n.º 2
0
    def testGetCompletedResponse(self):
        auth = cloudsight.SimpleAuth('test-token')
        api = cloudsight.API(auth)

        response = api.image_response('BjMGgyIZQt7QNPNZKmzq2A')

        assert response['status'] == 'completed'
        assert response['token']  == 'BjMGgyIZQt7QNPNZKmzq2A'
        assert response['name']   == 'Apple logo'
Exemplo n.º 3
0
    def testSendRequest(self):
        auth = cloudsight.SimpleAuth('test-token')
        api = cloudsight.API(auth)
        response = api.remote_image_request('https://storage.googleapis.com/iex/api/logos/AAPL.png', {
            'image_request[locale]': 'en-US',
        })

        assert response['status'] == 'not completed'
        assert response['token']  == 'BjMGgyIZQt7QNPNZKmzq2A'
Exemplo n.º 4
0
def call_vision_api(image_filename, api_keys):
    api_key = api_keys['cloudsight']['api_key']

    # Via example found here:
    # https://github.com/cloudsight/cloudsight-python

    auth = cloudsight.SimpleAuth(api_key)
    api = cloudsight.API(auth)

    with open(image_filename, 'rb') as image_file:
        response = api.image_request(image_file, image_filename)

    response = api.wait(response['token'], timeout=60)

    return response
def Caption(image_name, passs):
    auth = CS.SimpleAuth(passs)
    conn = CS.API(auth)
    Filter_chocolate = ['chocolate', 'pizza']
    filter_phone = [
        'smartphone', 'phone', 'mobile', 'Smartphone', 'Phone', 'Mobile'
    ]
    filter_cigarette = ['cigarette', 'cigarettes', 'smoking', 'smoke']
    with open(image_name, 'rb') as f:
        response = conn.image_request(f, image_name, {
            'image_request[locale]': 'en-US',
        })
    status = conn.wait(response['token'], timeout=30)
    status = conn.image_response(response['token'])
    if status['status'] != CS.STATUS_NOT_COMPLETED:
        try:
            caption = status['name']
            for content in Filter_chocolate:
                if content in caption:
                    message = "Warning: Eating %s is injurious to Health...Image Content" % content
                    #GV.speak('Warning: Eating Cholocate is injurious to Health.... Image Content\n')
                    message = message + caption
                    caption = message
                    break
            for content in filter_cigarette:
                if content in caption:
                    message = "Warning: Smoking %s is injurious to Health...Image Content. " % content
                    #GV.speak('Warning: Smoking %s is injurious to Health.... Image Content. \n' %content)
                    message = message + caption
                    caption = message
                    break
            for content in filter_phone:
                if content in caption:
                    caption = "Alert: %s Detected.. Filtered Content.." % content

            person = DT.Recognise_Face(image_name)
            if person != 0:
                message = 'You are looking at %s. ' % person
                message = message + caption
                caption = message
            GV.speak(caption)
            return (caption)
        except:
            print('Cannot Process this image')
    else:
        print('Cannot Process Image')
Exemplo n.º 6
0
 def fetch_labels(self, image_data, image_extension):
     try:
         auth = cloudsight.SimpleAuth(self._api_key)
         api = cloudsight.API(auth)
         response = api.image_request(image_data,
                                      'image.{}'.format(image_extension),
                                      {'image_request[locale]': 'en-US'})
         api.wait(response['token'], timeout=30)
         response = api.image_response(response['token'])
         status = response['status']
         if status == cloudsight.STATUS_COMPLETED:
             return [ImageLabel(label=response['name'], rank=1)]
         elif status == cloudsight.STATUS_SKIPPED:
             raise ImageRecognitionException(response['reason'])
         else:
             raise ImageRecognitionException('Service unavailable')
     except APIError:
         raise ImageRecognitionException('Service unavailable')
Exemplo n.º 7
0
 def post(self, request):
     # add a new image into database
     if request.POST.get("image"):
         image_feedback = request.POST.get("image")
         format, imgstr = image_feedback.split(';base64,')
         ext = format.split('/')[-1]
         data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext)
         auth = cloudsight.SimpleAuth('1bRy8uWYdSP9iErp-lImYg')
         api = cloudsight.API(auth)
         response = api.image_request(data, 'temp.' + ext, {
             'image_request[locale]': 'en-US',
         })
         print "wait"
         status = api.wait(response['token'], timeout=30)
         print "get image response"
         status = api.image_response(response['token'])
         if status['status'] != cloudsight.STATUS_NOT_COMPLETED:
             # Done!
             print "inside completed"
             print status
             category = status['name']
             score_dict = general_operations._get_priority_score_dict(
                 category, datetime.datetime.now())
             priority = general_operations._get_priority_score(score_dict)
             image = ImageFeedback(image=data,
                                   category=category,
                                   date_created=timezone.now(),
                                   priority=priority)
             image.save()
             # category = general_operations.get_image_classification(data)
             # image_name = category
             # score_dict = general_operations._get_priority_score_dict(category, datetime.datetime.now())
             # priority = general_operations._get_priority_score(score_dict)
             # image = ImageFeedback(image=data, category=category, date_created=timezone.now(), priority=priority)
             # image.save()
             return JsonResponse({"success": True}, status=200)
         print "end"
         print "error with api"
         return HttpResponse(status=404)
     print "error with image form"
     return HttpResponse(status=404)
Exemplo n.º 8
0
 def post(self, request):
     img = request.FILES.get('img')
     if img is None:
         return HttpResponse('You need upload a picture!')
     auth = cloudsight.SimpleAuth('bbzL7Oh6D2L1krnQZ5OfKg')
     api = cloudsight.API(auth)
     InputFile = img.name
     print(InputFile)
     response = api.image_request(img, InputFile, {
         'image_request[locale]': 'zh-CN',
         'image_request[language]': 'zh-CN'
     })
     print(response)
     status = api.wait(response['token'], timeout=30)
     data = {
         'name': status['name'],
         'url': status['url'],
         'code': 200,
     }
     return HttpResponse(json.dumps(data),
                         content_type='application/json;charset=utf-8')
Exemplo n.º 9
0
def take_picture():
    camera = camera_factory()

    snap = camera.snapshot()
    print "Picture Taken"
    path = "img/snap%d.jpg" % time.time()
    with open(path, "w") as outfile:
        outfile.write(snap)

    auth = cloudsight.SimpleAuth('0XG_2yQHzZgMHyjVVVskNQ')
    api = cloudsight.API(auth)
    with open(path, 'rb') as f:
        response = api.image_request(f, path, {
            'image_request[locale]': 'en-US',
        })
    status = api.wait(response['token'], timeout=30)
    name = str(status["name"])
    print name
    engine = pyttsx.init()
    engine.setProperty('rate', 140)
    engine.say(name)
    engine.runAndWait()
Exemplo n.º 10
0
def main() :

    # Make API call for authentication with API key
    auth = cloudsight.SimpleAuth('OMITTED')

    api = cloudsight.API(auth)

    # Iterate through the number of images the user would like described
    for x in range(numImages):
        string = str(x)
        # Files must be called from 0.jpg onwards so it knows how many to iterate
        file = string + '.jpg'
        # If the file doesn't exist, inform the user and exit the for loop
        if os.path.exists(file) == False:
            print("The file " + file + " does not exist. Please check the filenames are correctly formatted. \n")
            print("Now exiting the loop. Please rerun the program. \n")
            break
        # Open the image and downsize the file so it is easier and faster to upload
        im = Image.open(file)
        im.thumbnail((600, 600))
        # Save the smaller image so we can upload to the API
        im.save(string + 'cloudsight.jpg')
        # Open the image and make the request to the API
        with open(string + 'cloudsight.jpg', 'rb') as f:
            response = api.image_request(f, string + 'cloudsight.jpg', {'image_request[locale]': 'en-US', })
            # Maximum waiting time of 30 seconds - just in case
            status = api.wait(response['token'], timeout=30)

        # Print out the caption returned
        output = status['name']
        print(output)
        print("Preparing text to speech. \n")
        # Call the text to speech function with caption as parameter
        textSpeech("The image can be described as " + output)
        # Wait so the text to speech can finish before starting to say the joke
        wait()
        # Call the joke function with the caption as a parameter
        dadJoke(output)
Exemplo n.º 11
0
 def post(self, request):
     img = request.FILES.get('picture')
     if img is None:
         return HttpResponse('You need upload a picture!')
     auth = cloudsight.SimpleAuth('wslbEXDJIZNwAWW3BOP0g')
     api = cloudsight.API(auth)
     InputFile = img.name
     response = api.image_request(img, InputFile, {
         'image_request[locale]': 'zh-CN',
         'image_request[language]': 'zh-CN'
     })
     status = api.wait(response['token'], timeout=30)
     userImg = UserImg(
         name=status['name'],
         url=status['url'],
     )
     data = {
         'name': status['name'],
         'url': status['url'],
         'code': 200,
     }
     userImg.save()
     return HttpResponse(json.dumps(data),
                         content_type="application/json;charset=utf-8")
Exemplo n.º 12
0
import cloudsight
import sys
import pyttsx

auth = cloudsight.SimpleAuth('0XG_2yQHzZgMHyjVVVskNQ')
api = cloudsight.API(auth)
with open(sys.argv[1], 'rb') as f:
    response = api.image_request(f, sys.argv[1], {
        'image_request[locale]': 'en-US',
    })
status = api.wait(response['token'], timeout=30)
name = str(status["name"])
print name
engine = pyttsx.init()
engine.setProperty('rate', 140)
engine.say(name)
engine.runAndWait()
Exemplo n.º 13
0
import sys
import re
import subprocess

from googlesearch import *

print("Welcome to the simple book-review tool")
print("--------------------------------------------")
print("Authentication for cloud services in progress")
gc = client.GoodreadsClient('YZGDbGQrMRAAygCAr8Z8tw',
                            'iH9xo6jhIkNEEHQ9a0nJopDPNEL0TLfq3Z2E2ZNgBDc')
result = requests.get(
    "https://firebasestorage.googleapis.com/v0/b/book-finder-1f3de.appspot.com/o/image_0?alt=media&token=61ce6b03-fead-45fb-b875-71e869c3015c"
)

auth = cloudsight.SimpleAuth('nHo9nAczgUTzB6pLiCv1UA')
api = cloudsight.API(auth)
print("Authentication complete!!")

print("Your book is being recognised..")
response = api.remote_image_request(
    'https://firebasestorage.googleapis.com/v0/b/book-finder-1f3de.appspot.com/o/image_0?alt=media&token=48e00dec-ffc4-494b-aa4c-5424cca5b9cc',
    {
        'image_request[locale]': 'en-US',
    })

status = api.image_response(response['token'])
if status['status'] != cloudsight.STATUS_NOT_COMPLETED:
    # Done!
    pass
Exemplo n.º 14
0
    def testNewApi(self):
        auth = cloudsight.SimpleAuth('your-api-key')
        api = cloudsight.API(auth)

        assert api.auth == auth
Exemplo n.º 15
0
    def testAuth(self):
        auth = cloudsight.SimpleAuth('your-api-key')

        assert auth.key == 'your-api-key'
Exemplo n.º 16
0
import cloudsight

auth = cloudsight.SimpleAuth('EUVIyy2Rp_OGH7pm8z9oxA')
api = cloudsight.API(auth)
auth = cloudsight.OAuth('EUVIyy2Rp_OGH7pm8z9oxA', 'xqgUfGKc4SfKUW9CSeZeXw')
api = cloudsight.API(auth)

with open('sun.jpg', 'rb') as f:
    response = api.image_request(f, 'sun.jpg', {
        'image_request[locale]': 'en-US',
    })

'''
response = api.remote_image_request('http://www.example.com/image.jpg', {
    'image_request[locale]': 'en-US',
})
'''

status = api.image_response(response['token'])
if status['status'] != cloudsight.STATUS_NOT_COMPLETED:
    # Done!
    pass
    
status = api.wait(response['token'], timeout=30)
Exemplo n.º 17
0
from flask import Flask, jsonify, request
import cloudsight
import httplib, urllib, base64, json

app = Flask(__name__)

auth = cloudsight.SimpleAuth('kZH5jI5q2CSUD5Ofrsd8Dg')
api = cloudsight.API(auth)

MS_VISION_KEY = '6c8fa85edf7c47488eae0f1a6827b72c'


@app.route('/cloudsight/v1.0/image/', methods=['GET'])
def index():
    url = request.args.get('url')
    response = api.remote_image_request(url, {
        'image_request[locale]': 'en-US',
    })
    status = api.wait(response['token'], timeout=30)
    return jsonify(status)


@app.route('/ms/describe/', methods=['GET'])
def describe_image():
    url = request.args.get('url')
    headers = {
        # Request headers
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key': MS_VISION_KEY,
    }
Exemplo n.º 18
0
import json
from nutritionix import Nutritionix

from werkzeug import secure_filename

import cloudsight

from parse_rest.connection import register, SessionToken
from parse_rest.datatypes import Object
from parse_rest.user import User

register('O6H2V7pJzoOWntRT9hFqpxxHHdJTCLtA7xmnhHZ5',
         'olPs7M45S8mx7RpdSOSbAqfZbfBKjLzDzqISSivP',
         master_key='ZSpZtkfRzOziXOOJEy9kGjaTDVaju64YQcbLeBRH')

auth = cloudsight.SimpleAuth('qAd-COIpRxvKVaNUKrJMMQ')
api = cloudsight.API(auth)

nix = Nutritionix(app_id="76986486",
                  api_key="28882f3d105c4c9e3222a05eeafd049a")

UPLOAD_FOLDER = 'tmp'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
FACEBOOK_APP_ID = os.environ['FACEBOOK_APP_ID']
FACEBOOK_APP_SECRET = os.environ['FACEBOOK_APP_SECRET']

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
CORS(app)
app.secret_key = 'development'
Exemplo n.º 19
0
import sys
import subprocess
import requests
from requests.utils import quote
import sqlite3
import cloudsight
import json

# sets up API
db = None
auth = cloudsight.SimpleAuth('E_Q05SUR2NPl-PTTOr-crg')
api = cloudsight.API(auth)

subprocess.call(['aplay', 'sound/please_wait.wav'])

with open('item.jpg', 'rb') as f:
    response = api.image_request(f, 'your-file.jpg', {
        'image_request[locale]': 'en-US',
    })

status = api.image_response(response['token'])
if status['status'] != cloudsight.STATUS_NOT_COMPLETED:
    # Done!
    print("Shit messed up")
    pass

status = api.wait(response['token'], timeout=30)

item_name = status['name']

phrase = 'identified item, ' + item_name