本文整理汇总了Python中clarifai.client.ClarifaiApi.tag_image_urls方法的典型用法代码示例。如果您正苦于以下问题:Python ClarifaiApi.tag_image_urls方法的具体用法?Python ClarifaiApi.tag_image_urls怎么用?Python ClarifaiApi.tag_image_urls使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类clarifai.client.ClarifaiApi
的用法示例。
在下文中一共展示了ClarifaiApi.tag_image_urls方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getTags
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
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()
示例2: tags
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
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)
示例3: send_message
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
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()
示例4: send_image
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
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()
示例5: getImage
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
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!")
示例6: test_unicode_urls
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
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)
示例7: __init__
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
class ClarifaiParse:
def __init__(self, app_id=None, app_secret=None):
self.api = ClarifaiApi(app_id, app_secret)
def parse(self, url):
try:
api_result = self.api.tag_image_urls(url)
if api_result["status_code"] == "OK":
matches = []
for r in api_result['results']:
tag = r["result"]["tag"]
number_results = len(tag["classes"])
for i in range(number_results):
data = {"tag": tag["classes"][i], "probs": tag["probs"][i], "id": tag["concept_ids"][i]}
matches.append(data)
return matches
else:
print(api_result["status_code"])
print(api_result["status_msg"])
return []
except IOError:
print("can't open", filename)
return []
except Exception as e:
print(e)
return []
示例8: clarifai
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
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)
示例9: main
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
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")
示例10: get_words_url
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
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)) }
示例11: test_tag_one_video
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
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)
示例12: get_tags_and_probs
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
def get_tags_and_probs(url):
clarifai_api = ClarifaiApi()
result = clarifai_api.tag_image_urls(url)
tags = result['results'][0]['result']['tag']['classes']
probs = result['results'][0]['result']['tag']['probs']
#print tags
#print probs
return tags, probs
示例13: getTagsFromImages
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
def getTagsFromImages(images):
clarifai_api = ClarifaiApi() # assumes environment variables are set.
ans = []
y = clarifai_api.tag_image_urls(images)
ans = {}
for x in y["results"]:
for i in range(len(x["result"]["tag"]["classes"])):
ans[x["result"]["tag"]["classes"][i]] = x["result"]["tag"]["probs"][i]/3
return ans
示例14: CoverMaker
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
class CoverMaker(object):
def __init__(self, tags, band, album):
self._tags, self.tags = tags, tags
self.band = band
self.album = album
self.available_fonts = [font for font in os.listdir('./fonts') if font.lower().endswith('ttf')]
self.flickr = FlickrAPI(FLICKR_API_KEY, FLICKR_API_SECRET)
self.clarifai = ClarifaiApi(CLARIFAI_API_KEY, CLARIFAI_API_SECRET)
def make_cover(self):
# Generate random images
img1 = self._get_random_photo()
img2 = self._get_random_photo()
# Blend images, with a level between 0.25 and 0.75 to make sure both can be seen
cover = Image.blend(img1, img2, random.uniform(LOW_BLEND, HIGH_BLEND))
# Add band name and title
band_position = (random.choice(MARGINS), random.choice(MARGINS))
band_font = self._get_random_font(TITLE_SIZE)
ImageDraw.Draw(cover).text(band_position, self.band, font=band_font)
album_position = (random.choice(MARGINS), TOP_ALBUM+random.choice(MARGINS))
album_font = self._get_random_font(ALBUM_SIZE)
ImageDraw.Draw(cover).text(album_position, self.album, font=album_font)
# Return cover
return cover
def _get_random_font(self, size):
return ImageFont.truetype("./fonts/{font}".format(**{
'font' : random.choice(self.available_fonts)
}), size)
def _check_with_clarifai(self, url, tag):
data = self.clarifai.tag_image_urls(url)['results'][0]['result']['tag']
classes, probs = data['classes'], data['probs']
tags = [class_ for (i, class_) in enumerate(classes) if probs[i] > LOW_PROB]
return tag in tags
def _get_random_photo(self, size=IMG_SIZE):
"""
Get a random photo from Flickr and returns as a PIL image of a given size.
"""
tag = random.choice(tags)
data = self.flickr.photos.search(text=tag, per_page='500', content_type=1, sort='relevance', format="json")
photos = json.loads(data).get('photos').get('photo')
photo = random.choice(photos)
url = "https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg".format(**{
'farm-id' : photo.get('farm', ''),
'server-id' : photo.get('server', ''),
'id' : photo.get('id', ''),
'secret' : photo.get('secret', ''),
})
if self._check_with_clarifai(url, tag):
self.tags.remove(tag)
file = StringIO(urlopen(url).read())
return Image.open(file).resize(size)
else:
return self._get_random_photo()
示例15: process_image
# 需要导入模块: from clarifai.client import ClarifaiApi [as 别名]
# 或者: from clarifai.client.ClarifaiApi import tag_image_urls [as 别名]
def process_image(urls):
tags = dict()
api = ClarifaiApi("KuQ2EWXhdosMQyktSI1tw6Z3be7c677oA11p1g9o","Kt84XYqK7nVnx3f05_B8pe2biv9bBlGZAHjFvEwF")
for u in urls:
response = api.tag_image_urls(u)
tags[u] = response['results'][0]['result']['tag']['classes']
return tags