def clarifai(): clarifai = ClarifaiCustomModel() concept_name = 'piyali' PIYALI_POSITIVES = [ 'http://anshulkgupta.com/hackmit/piyali1.png', 'http://anshulkgupta.com/hackmit/piyali2.png', 'http://anshulkgupta.com/hackmit/piyali3.png', 'http://anshulkgupta.com/hackmit/piyali4.png' ] for positive_example in PIYALI_POSITIVES: clarifai.positive(positive_example, concept_name) PIYALI_NEGATIVES = [ 'http://anshulkgupta.com/hackmit/anshul1.png', 'http://anshulkgupta.com/hackmit/anshul2.png', 'http://anshulkgupta.com/hackmit/annie1.png', 'http://anshulkgupta.com/hackmit/annie2.png' ] for negative_example in PIYALI_NEGATIVES: clarifai.negative(negative_example, concept_name) clarifai.train(concept_name) PIYALI_TEST = [ 'http://anshulkgupta.com/hackmit/piyali-test1.png' ] NOT_PIYALI = [ 'http://anshulkgupta.com/hackmit/annie-test1.png', 'http://anshulkgupta.com/hackmit/anshul-test1.png', 'http://anshulkgupta.com/hackmit/anshul-test2.png' ] data = [] for test in PIYALI_TEST + NOT_PIYALI: result = clarifai.predict(test, concept_name) data.append([result['status']['message'], result['urls'][0]['score'], result['urls'][0]['url']]) return render_template('clarifai.html', data=data)
def classify(url): concept = ClarifaiCustomModel() highscore = 0 classification = None for d in data: score = concept.predict(url, d["alias"])["urls"][0]["score"] if score > 0.9: return d if score > highscore and score > 0.5: classification = d highscore = score print classification["alias"] print score return classification
def trainTextbook(textbook, textbooks): clarifai = ClarifaiCustomModel() concept_name = encode.NumericToAlpha(textbook.isbn[1:]) PHISH_POSITIVES = [ textbook.imgURL #pilexample.filterBlur(textbook.imgURL) ] for positive_example in PHISH_POSITIVES: clarifai.positive(positive_example, concept_name) PHISH_NEGATIVES = [] for t in textbooks: if t != textbook: PHISH_NEGATIVES.append(t.imgURL) for negative_example in PHISH_NEGATIVES: clarifai.negative(negative_example, concept_name) clarifai.train(concept_name) result = clarifai.predict(textbook.imgURL, concept_name) print result['status']['message'], "%0.3f" % result['urls'][0]['score'], result['urls'][0]['url'] print concept_name print decode.alphaToNumeric(concept_name)
def build(self): # instantiate clarifai client clarifai = ClarifaiCustomModel(app_id, app_secret) concept_name = 'phish' # find some positive and negative examples PHISH_POSITIVES = [ 'http://clarifai-test.s3.amazonaws.com/phish/positive/3652848536_c72244dc88_o.jpg', 'http://clarifai-test.s3.amazonaws.com/phish/positive/4840976460_8463f9f319_b.jpg', 'http://clarifai-test.s3.amazonaws.com/phish/positive/4904257471_20c0ff714f_b.jpg', 'http://clarifai-test.s3.amazonaws.com/phish/positive/4904842036_6806f5fd25_b.jpg', 'http://clarifai-test.s3.amazonaws.com/phish/positive/4904845798_aaf3392666_b.jpg', 'http://clarifai-test.s3.amazonaws.com/phish/positive/6030148539_5d6da277c0_b.jpg', 'http://clarifai-test.s3.amazonaws.com/phish/positive/9381652037_7e5e7665ab_k.jpg' ] # add the positive example images to the model for positive_example in PHISH_POSITIVES: clarifai.positive(positive_example, concept_name) # negatives are not required but will help if you want to discriminate between similar concepts PHISH_NEGATIVES = [ 'http://clarifai-test.s3.amazonaws.com/phish/negative/5587410471_cf932bf9fa_o.jpg', 'http://clarifai-test.s3.amazonaws.com/phish/negative/7367377586_f5e7c59ef8_k.jpg', 'http://clarifai-test.s3.amazonaws.com/phish/negative/8422034157_1fbe437d3a_b.jpg', 'http://clarifai-test.s3.amazonaws.com/phish/negative/8464327405_5eaf39e6e2_o.jpg', 'http://clarifai-test.s3.amazonaws.com/phish/negative/8804958484_9dcba3da19_k.jpg', 'http://clarifai-test.s3.amazonaws.com/phish/negative/8805067594_f2abc5c751_k.jpg', 'http://clarifai-test.s3.amazonaws.com/phish/negative/9583629691_a1594637a9_k.jpg' ] # add the negative example images to the model for negative_example in PHISH_NEGATIVES: clarifai.negative(negative_example, concept_name) # train the model clarifai.train(concept_name) PHISH_EXAMPLES = [ 'https://clarifai-test.s3.amazonaws.com/photo-1-11-e1342391144673.jpg', 'https://clarifai-test.s3.amazonaws.com/DSC01226-e1311293061704.jpg' ] NOT_PHISH = [ 'https://clarifai-test.s3.amazonaws.com/2141620332_2b741028b3.jpg', 'https://clarifai-test.s3.amazonaws.com/grateful_dead230582_15-52.jpg' ] # If everything works correctly, the confidence that true positive images are of Phish should be # significantly greater than 0.5, which is the same as choosing at random. The confidence that true # negative images are Phish should be significantly less than 0.5. # use the model to predict whether the test images are Phish or not for test in PHISH_EXAMPLES + NOT_PHISH: result = clarifai.predict(test, concept_name) print result['status']['message'], "%0.3f" % result['urls'][0]['score'], result['urls'][0]['url'] return Label(text='xxx')
def predict(url): concept = ClarifaiCustomModel() max_confidence = 0.0 classification = None for word in language.keys(): #print word result = concept.predict(url, word) confidence = result['urls'][0]['score'] print word, confidence if confidence > max_confidence: max_confidence = confidence classification = word if classification == None: return None else: return (classification, max_confidence)
def goToBookScouterURL(url_in): clarifai = ClarifaiCustomModel() probMax = 0 maxScoreISBN = "" print "Searching textbooks...." for isbn in isbnList.getISBNList(): result = clarifai.predict(url_in, encode.NumericToAlpha(isbn)) data = json.dumps(result) jdata = json.loads(data) jresults = jdata['urls'][0]['score'] #print str(jresults) + ":" + encode.NumericToAlpha(isbn) if result['urls'][0]['score'] > probMax: probMax = result['urls'][0]['score'] maxScoreISBN = isbn isbn = maxScoreISBN home = "http://bookscouter.com" ext1 = "/prices.php?isbn=" ext2 = "&searchbutton=Sell" url = home + ext1 + isbn + ext2 print "Found Textbook" print "ISBN-10 "+isbn+" with probablity: "+"%0.3f" % probMax webbrowser.open_new(url) #go to bookscouter.com
class Trainer(object): def __init__(self, jfp): self.clarifai = ClarifaiCustomModel(app_id, app_secret) self.jdata = getAllJSONData() def train(self, negatives_threshold=1.0, dist=2): for concept in self.jdata: for url in self.jdata[concept]["resources"]: print(concept + " positive: " + url) self.clarifai.positive(url, concept) filtered = getConceptsByGPS( latitude=self.jdata[concept]["latitude"], longitude=self.jdata[concept]["longitude"], jdata=self.jdata, distance=dist) for cid, _ in filtered: for url in self.jdata[cid]["resources"]: if random() <= negatives_threshold: print(concept + " negative: " + url) self.clarifai.negative(url, cid) self.clarifai.train(concept)
import sys from clarifai_basic import ClarifaiCustomModel good = False concept = ClarifaiCustomModel() filename = sys.argv[1] g = sys.argv[2] tagArray = ['HeavyMetal','Rap', 'Alternative','Pop','Country','Classical','Electronic'] file = open('ElecExcel.txt','w') file.write('{url, genre, HeavyMetal, Rap, Alternative, Pop, Country, Classical, Electronic}\n') with open(filename) as f: for line in f: good = False line = line.rstrip() try: for genre in tagArray: result = concept.predict(line,genre) good = True except: good = False if(good is True): print line file.write('{') file.write(line) file.write(', ') file.write(g) for genre in tagArray: file.write(', ') result = concept.predict(line,genre) confidence = float(result['urls'][0]['score']) file.write(repr(confidence)) file.write('}\n')
#!/usr/bin/env python from json import load from pprint import pprint from clarifai_basic import ClarifaiCustomModel from token import app_id, app_secret from random import random jdata = load(open("example-data.json"))["concepts"] clarifai = ClarifaiCustomModel(app_id, app_secret) allurls = [] for concept in jdata: allurls += jdata[concept]["resources"] LEARN = False # Percentage of negative pictures that are used for training # set to 1 for 100% NEGATIVEPERCENTAGE = 0.1 if LEARN: for concept in jdata: for url in allurls: if url in jdata[concept]["resources"]: print(concept + " positive: " + url) clarifai.positive(url, concept) else: if random() <= NEGATIVEPERCENTAGE:
from clarifai_basic import ClarifaiCustomModel import sys if len(sys.argv) < 2: print("please provide a valid URL or File Path") print("syntax: python .\predict.py [URL|File]") exit() # assumes environment variables are set. clarifai_api = ClarifaiCustomModel( "Qu6z2uKlfDgqa7Atn1HlOBa3pakRBQHflQicLNr_", "8WgQ8D4Dp9IW1JilxEfjXjgg1geq1zpaeT3P7Rk3") url = sys.argv[1] result = clarifai_api.predict(url, 'perfect') perfect = result["urls"][0]["score"] result = clarifai_api.predict(url, 'dent') dent = result["urls"][0]["score"] output = { "url": url, "state": "undef", "score": 0 } if dent > perfect:
import sys from clarifai_basic import ClarifaiCustomModel concept = ClarifaiCustomModel() url = sys.argv[1] max = 0 prediction = '' tagArray = ['HeavyMetal','Rap', 'Alternative','Pop','Country','Classical','Electronic'] for genre in tagArray: #print genre result = concept.predict(url,genre) confidence = float(result['urls'][0]['score']) #if confidence > max: #max = confidence #prediction = genre print genre, 'Confidence rate: ', confidence #print prediction
import os import sys from clarifai_basic import ClarifaiCustomModel concept = ClarifaiCustomModel() filename = sys.argv[1] tag = sys.argv[2] tagArray = ['HeavyMetal','Rap', 'Alternative','Pop','Country','Classical','Electronic'] with open(filename) as f: for line in f: line = line.rstrip() print line for genre in tagArray: try: if genre == tag: print 'Yes' concept.positive(line,tag) #else: #concept.negative(line,tag) #pass except: print 'Fail' , line pass concept.train(tag)
from clarifai_basic import ClarifaiCustomModel import sys if len(sys.argv) < 2: print("please provide a valid URL or File Path") print("syntax: python .\predict.py [URL|File]") exit() # assumes environment variables are set. clarifai_api = ClarifaiCustomModel("Qu6z2uKlfDgqa7Atn1HlOBa3pakRBQHflQicLNr_", "8WgQ8D4Dp9IW1JilxEfjXjgg1geq1zpaeT3P7Rk3") url = sys.argv[1] result = clarifai_api.predict(url, 'perfect') perfect = result["urls"][0]["score"] result = clarifai_api.predict(url, 'dent') dent = result["urls"][0]["score"] output = {"url": url, "state": "undef", "score": 0} if dent > perfect: output["state"] = "dent" output["score"] = dent else: output["state"] = "perfect" output["score"] = perfect
from clarifai_basic import ClarifaiCustomModel import os import urllib2, socket # instantiate clarifai client clarifai = ClarifaiCustomModel() p=os.getcwd() p=p.replace('\\','/') #XXXXXXXXXXXXXXXXXXX CAR XXXXXXXXXXXXXXXXXXXXXXXXXXXXX POSITIVES = [] pos=p+"/images/cars.txt" with open(pos) as f: POSITIVES = [x.strip('\n') for x in f.readlines()] NEGATIVES = [] neg=p+"/images/bikes.txt" with open(neg) as f: NEGATIVES.extend([x.strip('\n') for x in f.readlines()]) neg=p+"/images/buses.txt" with open(neg) as f: NEGATIVES.extend([x.strip('\n') for x in f.readlines()]) neg=p+"/images/motorbikes.txt" with open(neg) as f: NEGATIVES.extend([x.strip('\n') for x in f.readlines()]) for i in POSITIVES: try: urllib2.urlopen(i)
for d in data: # ignore non-food data if d['parents'][0] not in MAIN_GROUPS and d['alias'] not in EXCEPTIONS: continue # add 'food' to restaurants for better search optimization if d['parents'][0] in MAIN_GROUPS[0]: d['title'] = str(d['title']) + ' Food' categories.append({ 'alias': str(d['alias']), 'title': str(d['title']) }) # pprint.pprint(categories) concept = ClarifaiCustomModel() # train model for each category for cat in categories: print cat['alias'] if cat['alias'] in DONE: continue # get images to train with images = bing.image_search(query=cat['title']) for image in images: print image print images.index(image) concept.positive(image, cat['alias']) # choose random food
from clarifai_basic import ClarifaiCustomModel from json import dumps from classifications import language concept = ClarifaiCustomModel() image_url = 'http://i.imgur.com/m4yadmu.jpg' model = 'letter_o' concept.positive(image_url, model) concept.train(model) for word in language: if word != model: print word concept.negative(image_url, word) concept.train(word) print concept.predict(image_url, model)
class Client(object): def __init__(self): self.clarifai = ClarifaiCustomModel(app_id, app_secret) self.jdata = getAllJSONData() def processImage(self, latitude, longitude, url, homelat, homelong): concept = self.__processImage(latitude, longitude, url) if concept is None: return None return self.__getInfos(concept, homelat, homelong) def __processImage(self, latitude, longitude, url): filtered = getConceptsByGPS(latitude, longitude, self.jdata, 1) results = [] for concept, _ in filtered: result = self.clarifai.predict(url, concept) results.append([concept, result["urls"][0]["score"]]) results = sorted(results, key=lambda pair: pair[1], reverse=True) if len(results) == 0: return None result = results[0] if result[1] < 0.5: return None return result[0] def processImageDebug(self, url): print("Start recognizing...") filtered = getConceptsByGPS(0, 0, self.jdata, 40000) results = [] count = len(filtered) for concept, _ in filtered: result = self.clarifai.predict(url, concept) results.append([concept, result["urls"][0]["score"]]) results = sorted(results, key=lambda pair: pair[1], reverse=True) if len(results) == 0: return None result = results[0] if result[1] < 0.5: return None return result[0] def getInfos(self, concept): target = self.jdata[concept] name = target["name"] city = target["city"] return (name, city) def __getInfos(self, concept, homelat, homelong): target = self.jdata[concept] name = target["name"] city = "NiHier" # target["city"] tlong = target["longitude"] tlat = target["latitude"] distance = distance_on_unit_sphere(homelat, homelong, tlat, tlong) return (name, distance, city)
from clarifai_basic import ClarifaiCustomModel import os os.environ["CLARIFAI_APP_ID"]="f_LGpdh9gta77vih9bOl-96qNU4Nbn5_x6j412N_" os.environ["CLARIFAI_APP_SECRET"]="_daBl2t7eC9nAGb-IBOdYLfm1uqoCQH6MPlvAJR1" concept = ClarifaiCustomModel() concept.positive('https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/BMW_E90_Kirrinsannassa_2.jpg/280px-BMW_E90_Kirrinsannassa_2.jpg', 'car') concept.train('car')
#author Aditya Vishwanath #created for HackMIT 2015 # """ # THE FOLLOWING COMMENT IS REDUNDANT. # Concepts: # 1. Grains. # 2. Vegetables. # 3. Fruits. # 4. Milk. # 5. Meat and Beans. # """ from clarifai_basic import ClarifaiCustomModel testConcept = ClarifaiCustomModel() TEST_TAG = 'cocacola' def conceptTrainer(): # grainsConcept = ClarifaiCustomModel() # vegetablesConcept = ClarifaiCustomModel() # fruitsConcept = ClarifaiCustomModel() # milkConcept = ClarifaiCustomModel() # meatandbeansConcept = ClarifaiCustomModel() #TEST: To learn the coca-cola tag, and differentiate between Coca-Cola and Pepsi. #Should be optimized to pull data from an Image Search API and run multiple positive and negative tests. #Positives testConcept.positive('http://www.coca-cola.com/global/images/coke_disc.png', TEST_TAG) testConcept.positive('http://img3.wikia.nocookie.net/__cb20150801090518/logopedia/images/5/59/Coca-Cola_logo_2007.jpg', TEST_TAG)
import sys # ARGS need to be 'MODEL' 'POSITIVE IMAGE LIST.txt' 'NEGATIVE IMAGE LIST.txt' Model_name = str(sys.argv[1]) Positive_File = str(sys.argv[2]) Negative_File = str(sys.argv[3]) print "Start" # instantiate clarifai client clarifai = ClarifaiCustomModel() #[line.strip() for line in open("C:/name/MyDocuments/numbers", 'r')] # add the positive example images to the model print "Positive" for positive_example in [ line.strip() for line in (open(Positive_File)).readlines() ]: try: clarifai.positive(positive_example, Model_name) except: print "oops" print str(positive_example) # negatives are not required but will help if you want to discriminate between similar concepts print "Negative Examples"
#instantiate a new Clarifai object from clarifai_basic import ClarifaiCustomModel clarifai = ClarifaiCustomModel() # Give a few positive examples and a name for the custom concept. clarifai.positive('https://upload.wikimedia.org/wikipedia/commons/0/02/Durian.jpg', 'durian') clarifai.positive('https://www.organicfacts.net/wp-content/uploads/2013/05/Banana21.jpg', 'banana') clarifai.positive('http://thumbs.dreamstime.com/z/sweet-sop-2898990.jpg', 'sweetsop') clarifai.positive('http://www.centraliowaminiclub.org/wp-content/uploads/2015/08/pie.jpg', 'pie') clarifai.positive('http://media.mercola.com/assets/images/food-facts/lychee-nutrition-facts.jpg', 'lychee') # Give a few negative examples and a name for the custom concept. clarifai.negative('https://www.organicfacts.net/wp-content/uploads/2013/05/Banana21.jpg', 'durian') clarifai.negative('https://upload.wikimedia.org/wikipedia/commons/0/02/Durian.jpg', 'banana') clarifai.negative('http://dreamatico.com/data_images/apple/apple-7.jpg', 'sweetsop') clarifai.negative('https://upload.wikimedia.org/wikipedia/commons/8/8f/NYC-Diner-Bacon-Cheeseburger.jpg', 'pie') clarifai.negative('http://www.newhealthguide.org/images/10415496/image001.jpg', 'lychee') # Train the platform to learn your custom concept. clarifai.train('durian') clarifai.train('pie') clarifai.train('banana') clarifai.train('sweetsop') clarifai.train('lychee')
__author__ = 'montanawong' from clarifai.client import ClarifaiApi from clarifai_basic import ClarifaiCustomModel concept = ClarifaiCustomModel() clarifai_api = ClarifaiApi() # assumes environment variables are set. url = "http://cdn.hitfix.com/photos/5621843/Grumpy-Cat.jpg" concept.positive(url, "nelly") concept.train('nelly') #result = #concept.predict('https://pbs.twimg.com/profile_images/616542814319415296/#McCTpH_E.jpg', 'nelly') #confidence = result['urls'][0]['score'] #print confidence #result = clarifai_api.tag_images(open('images/cat.jpg')) result = clarifai_api.tag_image_urls(url) print result
from clarifai_basic import ClarifaiCustomModel import sys clarifai = ClarifaiCustomModel() result = clarifai.predict('http://comps.canstockphoto.com/can-stock-photo_csp10316699.jpg', 'test5') print result "http://pad2.whstatic.com/images/thumb/b/bb/Get-Rid-of-Skin-Moles-Step-2-Version-3.jpg/670px-Get-Rid-of-Skin-Moles-Step-2-Version-3.jpg" result = clarifai.predict("http://pad2.whstatic.com/images/thumb/b/bb/Get-Rid-of-Skin-Moles-Step-2-Version-3.jpg/670px-Get-Rid-of-Skin-Moles-Step-2-Version-3.jpg", 'test5') print result result = clarifai.predict("http://cancerousmolepictures.com/large/6/Cancerous-Mole-Pictures-1.jpg" , 'test5') print result
# BOOK TRAINER # #import all the stuffs from clarifai_basic import ClarifaiCustomModel concept = ClarifaiCustomModel() #assign the stuffs image_url = "" tag = "" ISBN_DICT = {tag:image_url} #Provide some positive example images for concept concept.positive(image_url, tag );
from clarifai_basic import ClarifaiCustomModel from json import dumps from classifications import language concept = ClarifaiCustomModel() for model in language.keys(): print "current model to train: " + model for url in language[model]: concept.positive(url, model) #print "training url:%s on model %s" % (url, model) for key, value in language.iteritems(): if key != model: for neg_url in value: print neg_url concept.negative(neg_url, model) concept.train(model) #print "making url:%s from model: %s a negative case." %(neg_url, key) ''' for url in language['letter_c']: concept.positive(url, "letter_c") for neg_url in language['letter_a']: concept.negative(neg_url, "letter_c") for neg_url in language['letter_b']: concept.negative(neg_url, "letter_c") for neg_url in language['applause']:
from clarifai_basic import ClarifaiCustomModel clarifai = ClarifaiCustomModel() def train(ImgURL, name): # Positive data source clarifai.positive(ImgURL, name) negative_source = [ "https://ollienollie.files.wordpress.com/2009/10/untitled-181.jpg", "https://c2.staticflickr.com/4/3500/3895160739_51bd7a644a.jpg", "http://www.facesmainst.com/manager/profile/pix/photo252-20091124013740.jpg", "http://static1.squarespace.com/static/5577b787e4b02cd823df9127/5578c73be4b0b454e5bdce91/5578c785e4b007898ac4a747/1433978757441/face32.jpg", "http://www.funnyfacespictures.net/pictures/funny-faces-crazy_eyes.jpg", "https://c2.staticflickr.com/6/5190/5580706695_cc7cf9d96c_b.jpg", "http://farm8.staticflickr.com/7005/6404355801_e90c7fe1ff_z.jpg", "http://www.lahiguera.net/cinemania/actores/julian_villagran/fotos/2551/julian_villagran.jpg", "http://www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=92080475" "http://img2-3.timeinc.net/people/i/2010/news/100719/lindsay-lohan-1-240.jpg", "http://4.bp.blogspot.com/_cG2SV6Pnny4/SVEMe3VpLEI/AAAAAAAABic/tysh9iiyGuQ/s400/12_b.jpg", "http://www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=116178971" ] # Negative data source for negative in negative_source: clarifai.negative(negative, name) # train the model clarifai.train(name)
#!/usr/bin/env python # I pity the fool who forgets to set his environment variables! from clarifai_basic import ClarifaiCustomModel from token import * clarifai = ClarifaiCustomModel(app_id, app_secret) concept_name = 'cologne_dome' COLOGNE_POSITIVES = [ 'http://www.pcgames.de/screenshots/original/2012/01/Koelner_Dom.jpg', 'http://www.stadt-touristen.de/wp-content/uploads/2014/05/K%C3%B6ln-K%C3%B6lner-Dom.jpg', 'https://thejarrells.files.wordpress.com/2011/06/img_2440_2.jpg', 'https://upload.wikimedia.org/wikipedia/commons/5/55/Dmthoth_Koelner_dom_001.JPG' ] COLOGNE_NEGATIVES = [ 'http://www.dresden.citysam.de/fotos-dresden-p/tagesausfluege/meissen-2.jpg', 'http://rotary1880.de/bayreuth_eremitage/bilder/Meissen5.JPG', 'http://sachsen-blogger.de/wp-content/uploads/2013/07/DSCF4292.jpg' ] for pos in COLOGNE_POSITIVES: clarifai.positive(pos, concept_name) for neg in COLOGNE_NEGATIVES: clarifai.negative(neg, concept_name)
from clarifai_basic import ClarifaiCustomModel # assumes environment variables are set. clarifai_api = ClarifaiCustomModel( "Qu6z2uKlfDgqa7Atn1HlOBa3pakRBQHflQicLNr_", "8WgQ8D4Dp9IW1JilxEfjXjgg1geq1zpaeT3P7Rk3") result = clarifai_api.predict('http://www.bodyshopzone.com/archives/collision/side_impact_1/cxeqia01apr_Equinox_tbone.jpg', 'dent') print("Dent: ") print(result) #TGhikOhhzTI/AAAAAAAAAPo/nYmF9hULrCU/s1600/IMG_1437.JPG', 'scratch') #print("Scratch: ") #print(result) result = clarifai_api.predict('http://www.bodyshopzone.com/archives/collision/side_impact_1/cxeqia01apr_Equinox_tbone.jpg', 'perfect') print("Perfect: ") print(result)
def __init__(self, jfp): self.clarifai = ClarifaiCustomModel(app_id, app_secret) self.jdata = getAllJSONData()
from clarifai_basic import ClarifaiCustomModel # assumes environment variables are set. clarifai_api = ClarifaiCustomModel( "Qu6z2uKlfDgqa7Atn1HlOBa3pakRBQHflQicLNr_", "8WgQ8D4Dp9IW1JilxEfjXjgg1geq1zpaeT3P7Rk3") files = ["dent", "perfect"] for fileName in files: f = open("images/" + fileName + ".txt") urls = [url.strip() for url in f.readlines()] for url in urls: print("Training positive " + fileName +": " + url) clarifai_api.positive(url, fileName) f.close() for other in files: if other != fileName: f = open("images/" + fileName + ".txt") urls = [url.strip() for url in f.readlines()] for url in urls: print("Training negative " + other +": " + url) clarifai_api.positive(url, fileName) f.close() clarifai_api.train(fileName) print("Trained: " + fileName)
import urllib2 import json import cStringIO from league_names import champ_list_maker, weird_names from clarifai_basic import ClarifaiCustomModel, ApiError concept = ClarifaiCustomModel("7aHTExCPi2drd-DX2dJjyQNu7elDvMXxvTo8KHgu", "rTSOazFe9NFcpVkSn-_TDWc13wSsyBNKPlMh5dES") fetcher = urllib2.build_opener() champion_list = champ_list_maker() weird_name_list = weird_names() space_names = ["MasterYi", "TwistedFate", "Cho'Gath", "Kha'Zix", "Kog'Maw", "Rek'Sai"] for champion in space_names: searchTerm = champion googleimages = [] for sI in xrange(2): startIndex = 4 * sI searchUrl = ( "http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" + searchTerm + "+lol&start=" + str(startIndex) ) f = fetcher.open(searchUrl) deserialized_output = json.load(f) for i in xrange(min(len(deserialized_output["responseData"]["results"]), 10)): imageUrl = deserialized_output["responseData"]["results"][i]["unescapedUrl"] googleimages.append(imageUrl)
from clarifai_basic import ClarifaiCustomModel import sys if len(sys.argv) < 4: print( "syntax: python .\predict.py [URL|File] [Result State] [Good|Bad] [if Bad: expected State") exit() # assumes environment variables are set. clarifai_api = ClarifaiCustomModel( "Qu6z2uKlfDgqa7Atn1HlOBa3pakRBQHflQicLNr_", "8WgQ8D4Dp9IW1JilxEfjXjgg1geq1zpaeT3P7Rk3") possibleStates=["dent", "perfect"] url = sys.argv[1] state = sys.argv[2].lower predictResult = sys.argv[3].lower() if predictResult == "good": clarifai_api.positive(url, state) for s in possibleStates: if s != state: clarifai_api.negative(url, s) clarifai_api.train(state) if predictResult == "bad": expectedState = sys.argv[4].lower() clarifai_api.positive(url, expectedState) for s in possibleStates: if s != expectedState: clarifai_api.negative(url, s)