当前位置: 首页>>代码示例>>Python>>正文


Python client.ClarifaiApi类代码示例

本文整理汇总了Python中clarifai.client.ClarifaiApi的典型用法代码示例。如果您正苦于以下问题:Python ClarifaiApi类的具体用法?Python ClarifaiApi怎么用?Python ClarifaiApi使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ClarifaiApi类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getTags

def getTags(item):
	clarifai_api = ClarifaiApi() # assumes environment variables are set.
	result = clarifai_api.tag_image_urls(item.imgURL)

	result = result["results"][0]["result"]["tag"]["classes"]
	for i in result:
		Tag(tagText=i, item=item).save()
开发者ID:hennersz,项目名称:Lost-and-Found,代码行数:7,代码来源:views.py

示例2: tags

def tags():
    url = request.args["url"] 
    clarifai_api = ClarifaiApi()  # assumes environment variables are set.
    result = clarifai_api.tag_image_urls(url)
    results = result['results'][0]["result"]["tag"]["classes"]#[:3]

    client = foursquare.Foursquare(client_id='JEK02X44TGMNJSE0VC1UBEB4FRNNW3UMFQ4IQOPI4BAR2GXA', \
                                    client_secret='A2Z50VTUHHXEUYJBHCQKB1LXTNVVBYBQR4SDASVTXTWUMWXS') #foursquare shit

    address = request.args["address"] #address is currently a string
    geolocator = Nominatim()
    location = geolocator.geocode(address)
    newLocation = str(location.latitude) + str(", ") + str(location.longitude)
    
    
    # foursquare_dictionary = client.venues.explore(params={'ll': '40.7, -74', 'v': '20160402', 'query': results[0] + ',' + results[1] + ',' + results[2]})

    foursquare_dictionary = client.venues.explore(params={'ll': newLocation, 'v': '20160402', 'query': results[0] + ',' + results[1] + ',' + results[2]})

    #first place to eat
    # status1 = foursquare_dictionary['groups'][0]['items'][0]['venue']['hours']['status']
    address1 = foursquare_dictionary['groups'][0]['items'][0]['venue']['location']['formattedAddress']
    name = foursquare_dictionary['groups'][0]['items'][0]['venue']['name']

    #second place to eat
    address2 = foursquare_dictionary['groups'][0]['items'][1]['venue']['location']['formattedAddress']
   # status2 = foursquare_dictionary['groups'][0]['items'][1]['venue']['hours']['status']
    name1 = foursquare_dictionary['groups'][0]['items'][1]['venue']['name']

    return render_template('tags.html',\
                           newAddress1 = newAddress(address1), name = name,\
                           newAddress2 = newAddress(address2), name1 = name1,\
                           newLocation = newLocation)
开发者ID:jchen2186,项目名称:Foodifai,代码行数:33,代码来源:__init__.py

示例3: send_message

def send_message():
	image = Images.query.filter_by(is_sent=0).first()

	if image == None:
		imgur_client = ImgurClient(os.environ.get('IMGUR_CLIENT_ID'), os.environ.get('IMGUR_CLIENT_SECRET'))
		clarifai_api = ClarifaiApi()

		images = imgur_client.subreddit_gallery(subreddit='aww', page=0)

		for image in images:
			if image.is_album == False and ('jpeg' in image.type):
				try:
					result = clarifai_api.tag_image_urls(image.link)
					total_result = result['results'][0]['result']['tag']['classes']
					if len(set(total_result).intersection(['dog', 'puppy', 'cat', 'kitten', 'bird'])) > 0:
						db.session.add(Images(image.link))
						db.session.commit()
				except:
					pass

		image = Images.query.filter_by(is_sent=0).first()

	users = Users.query.filter_by(active=1).all()

	for user in users:
		try:
			client = TwilioRestClient(os.environ.get('TWILIO_ACCOUNT_SID'), os.environ.get('TWILIO_AUTH_TOKEN'))
			message  = client.messages.create(to=user.number, from_="+19733214779", media_url=[image.link])
		except:
			pass
		
	image.is_sent = 1
	db.session.commit()
开发者ID:jayrav13,项目名称:cat-tax,代码行数:33,代码来源:imgur.py

示例4: send_image

def send_image():
	image = Images.query.filter_by(is_sent=0).first()

	if image == None:
		parameters = {
			"format" : "xml",
			"results_per_page" : "100"
		}
		result = requests.get('http://thecatapi.com/api/images/get', params=parameters)
		tree = html.document_fromstring(result.text)

		clarifai_api = ClarifaiApi()

		for val in tree.xpath('//images'):
			for elem in val:
				try:
					result = clarifai_api.tag_image_urls(elem.xpath('url')[0].text)
					total_results = result['results'][0]['result']['tag']['classes']
					if 'cat' in total_results or 'kitten' in total_results:
						db.session.add(Images(elem.xpath('url')[0].text, elem.xpath('id')[0].text, elem.xpath('source_url')[0].text, 0))
						db.session.commit()
				except:
					pass

		image = Images.query.filter_by(is_sent=0).first()

	users = Users.query.filter_by(active=1).all()

	for elem in users:
		client = TwilioRestClient(os.environ.get('TWILIO_ACCOUNT_SID'), os.environ.get('TWILIO_AUTH_TOKEN'))
		message = client.messages.create(to=elem.number, from_="+19733214779", media_url=[image.url])

	image.is_sent = 1
	db.session.commit()
开发者ID:jayrav13,项目名称:cat-tax,代码行数:34,代码来源:images.py

示例5: getImage

def getImage():
	image = request.args.get('urlname')
	if image:
		clarifai_api = ClarifaiApi(CLARIFAI_APP_ID, CLARIFAI_APP_SECRET)
		try:
			response = clarifai_api.tag_image_urls('%s' %(str(image)))
			tags = response['results'][0]['result']['tag']['classes']
			for tag in tags:
				joke = searchForJoke(jokes, tag)
				if joke != "No joke with keyword found!":
					break
			try:
				page = wikipedia.page(tags[0])
			except wikipedia.exceptions.DisambiguationError as e:
				page = e.options[0]		
			return jsonify(result=str(tags).strip("[").strip("]"), 
						   joke="Possibly inappro Chuck Norris Joke: " + joke, 
						   wiki="Fun fact: " + page.summary + "...",
						   readMore="Read more here: " + page.url)
		except:
			return jsonify(result="API keys failed!",
				           joke="No image!",
				           wiki="No image!",
				           readMore="No image!")
	return jsonify(result="No input or failed to locate image!",
		           joke="No image!",
		           wiki="No image!",
		           readMore="No image!")
开发者ID:bryanyan,项目名称:clarifai-champs,代码行数:28,代码来源:views.py

示例6: clarifai

def clarifai():
    if request_format_okay(request):
        s3_base_url = 'https://make-or-break.s3.amazonaws.com/'
        data = request.get_json()
        request_obj = Request.query.get(data["request_id"])
        image_url = str(data["image_encoded"] + "")
        file_type = data["file_type"] if data["file_type"] else ".png"

        fileName = id_generator() + "." + file_type
        fh = open(fileName, "wb")
        fh.write(base64.b64decode(image_url))
        fh.close()

        aws_key = os.environ.get('AWS_KEY')
        aws_secret = os.environ.get('AWS_SECRET')
        conn = tinys3.Connection(aws_key, aws_secret, tls=True)
        f = open(fileName, 'rb')
        conn.upload(fileName, f, 'make-or-break')
        f.close()

        s3_url = s3_base_url + fileName

        request_obj.image_url = s3_url
        db.session.commit()

        os.remove(fileName)

        clarifai_api = ClarifaiApi() # assumes environment variables are set
        result = clarifai_api.tag_image_urls(s3_url)
        return jsonify(result)
    else:
        return abort(415)
开发者ID:neil1023,项目名称:makeorbreak-backend,代码行数:32,代码来源:routes.py

示例7: get_words_url

def get_words_url(url):
    clarifai_api = ClarifaiApi() # assumes environment variables are set.
    result = clarifai_api.tag_image_urls(url)

    tags=result['results'][0]['result']['tag']['classes']
    probs=result['results'][0]['result']['tag']['probs']
    return { tags[i] : probs[i] for i in range(len(tags)) }
开发者ID:dhlanm,项目名称:dubhacksfilter,代码行数:7,代码来源:application.py

示例8: test_unicode_urls

    def test_unicode_urls(self):
        image_url = u"http://www.alvaronoboa.com/wp-content/uploads/2013/02/Álvaro-Noboa-y-Annabella-Azín-Votaciones-41-1024x682.jpg"

        api = ClarifaiApi()
        response = api.tag_image_urls(image_url)
        self.assertTrue(response)
        self.assertTrue(response["results"][0]["url"] == image_url)
开发者ID:yatingupta10,项目名称:clarifai-python,代码行数:7,代码来源:test_client.py

示例9: process_data

    def process_data(self, url):
        url = url.decode('utf-8')
        annotations_filename = self.get_model_filename(url)
        model_filename = get_cache_filename(url)
        pdf_filename = model_filename + '.data'
        images_dir = pdf_filename + '-images/'

        clarifai_api = ClarifaiApi()

        annotations = self.get_new_model()

        for file in os.listdir(images_dir):
            if file.endswith(".png"):
                response = clarifai_api.tag_images(open(images_dir + file, 'rb'))
                result = response['results'][0]['result']['tag']
                for tag, prob in zip(result['classes'], result['probs']):
                    print('Tag: ' + tag + ' Prob: ' + str(prob))
                    annotation = create_annotation(
                                                (namespaces.oa.confidence, Literal(prob, datatype=XSD.decimal)),
                                                target=URIRef(url) + '#image' + file,
                                                body=Literal(tag, datatype=XSD.string),
                                                annotator=Literal('Clarif.ai', datatype=XSD.string))

                annotations += annotation
        self.write_and_merge_model(annotations, annotations_filename)
开发者ID:querenker,项目名称:COAL,代码行数:25,代码来源:clarifai_worker.py

示例10: getTags

def getTags(file):
    # assumes environment variables are set.
    clarifai_api = ClarifaiApi() 
    result = clarifai_api.tag_images(file)
    #parsing Json
    res = []
    return result['results'][0]['result']['tag']['classes']
开发者ID:J-Miao,项目名称:search-video-by-sketch,代码行数:7,代码来源:loadImages.py

示例11: get_tags

def get_tags():
	#TODO: Error checking
#       global d 
#       d = {}

	clarifai_api = ClarifaiApi()
	blob_service = BlobService('calhacks', 'mm7EmY+T+MGahePBDSDU5LHpZR5tRXuh4MSco4jFrzHovOPEf06e18c89pxtPIo4NDVhhjSeaQY/FQmKNxjjyA==')      

	blob_name = request.form['blob_id']
#       blob_name = blob_name.decode('utf-8')
	blob_service.get_blob_to_path('imagestore', blob_name, 'out.png')       
	print("checkpoint 1")
	i = open ('out.png', 'r')
	strd = ""
	for line in i:
		strd += line.strip()
	fname = 'img.png'
	with open (fname, 'wb') as f:
		f.write (base64.b64decode(strd))
		f.close()

	f = open (fname, 'rb')
	result = clarifai_api.tag_images(f)
	st = result['results'][0]['result']['tag']['classes'][0:6]
	print(st)

	for i in []:#['food', 'nobody', 'still life', 'meal', 'dish', 'plate', 'delicious', 'isolated', 'cutout', 'unhealthy', 'one', 'background']: 
		while i in st:
			st.remove(i)
	js = json.dumps(search_terms(st))
	print(js)
	return js
开发者ID:Hersh500,项目名称:pie-piper,代码行数:32,代码来源:server_without_timeout.py

示例12: main

def main(argv):
  if len(argv) > 1:
    imageurl = argv[1]
  else:
    imageurl = 'http://clarifai-img.s3.amazonaws.com/test/toddler-flowers.jpeg'
    print("We will be using the default since you provided no local directories")

  api = ClarifaiApi()

  if imageurl.startswith('http'):
    response = api.tag_image_urls(imageurl)

  elif os.path.isdir(imageurl):
    tags_list = tag_images_in_directory(imageurl, api)


    # this is a list of lists
    # you get simply something like ['hot', 'girl', 'model', 'young', 'brunette']
    # so take that, join it as one string with _ between each word 
    # and rename each file accordingly. 

    response = rename_images_in_directory_with_tags(format_tags_with_filenames(tags_list, images), imageurl)


  elif os.path.isfile(imageurl):
    with open(imageurl,'rb') as image_file:
      response = api.tag_images(image_file)

  else:
    raise Exception("Must input url, directory path, or file path")
开发者ID:yjkimjunior,项目名称:nostradamus,代码行数:30,代码来源:nostradamus-main.py

示例13: get_the_fucking_tags

def get_the_fucking_tags(image):
    """Uses clarifai api to get image tags."""
    clarifai_api = ClarifaiApi() # assumes environment variables are set.
    result = clarifai_api.tag_images(open(image))
    data = json.dumps(result)
    jdata = json.loads(data)
    jresults = jdata['results'][0]['result']['tag']['classes'][0]
    return jresults
开发者ID:Thefroshow,项目名称:UGAHacks,代码行数:8,代码来源:get_image_tags.py

示例14: test_tag_one_video_from_localfs

 def test_tag_one_video_from_localfs(self):
     # video source: http://techslides.com/demos/sample-videos/small.mp4
     video_file = "tests/data/small.mp4"
     api = ClarifaiApi()
     if os.path.exists(video_file):
         with open(video_file, "rb") as fb:
             response = api.tag_images(fb)
             self.assertTrue(response)
开发者ID:yatingupta10,项目名称:clarifai-python,代码行数:8,代码来源:test_client.py

示例15: test_tag_one_video

    def test_tag_one_video(self):
        # video source: http://techslides.com/demos/sample-videos/small.mp4
        video_url = "http://techslides.com/demos/sample-videos/small.mp4"

        api = ClarifaiApi()
        response = api.tag_image_urls(video_url)
        self.assertTrue(response)
        self.assertTrue(response["results"][0]["url"] == video_url)
开发者ID:yatingupta10,项目名称:clarifai-python,代码行数:8,代码来源:test_client.py


注:本文中的clarifai.client.ClarifaiApi类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。