Beispiel #1
0
def main():
  logger = logging.getLogger('clarifai')
  logger.handlers = []
  logger.addHandler(logging.StreamHandler())
  logger.setLevel(logging.INFO)

  app = ClarifaiApp()

  delete_all_inputs(app, logger)
  app.models.delete_all()

  app.wait_until_inputs_delete_finish()
  app.wait_until_models_delete_finish()

  app.inputs.create_image_from_url(
      urls[0], concepts=['train', 'railway'], allow_duplicate_url=True)
  app.inputs.create_image_from_url(urls[3], concepts=['dog', 'animal'], allow_duplicate_url=True)

  model_id = uuid.uuid4().hex

  model1 = app.models.create(model_id=model_id, concepts=['train', 'railway', 'dog', 'animal'])
  model = model1.train(timeout=240)

  if model.model_status_code != 21100:
    logger.error('Model not trained in 240 seconds with 2 inputs. Test could not continue.')
    exit(2)
Beispiel #2
0
        python clarifai_run_on_folder.py --input_image_folder images/negative --class_type negative
        python clarifai_run_on_folder.py --input_image_folder images/nudity --class_type nudity
        python clarifai_run_on_folder.py --input_image_folder images/violence --class_type violence
    """

    parser = argparse.ArgumentParser()
    parser.add_argument("--input_image_folder", default="", help="")
    parser.add_argument("--class_type", default="", help="")
    args = parser.parse_args()

    print(args)

    with open('api_keys.json') as f:
        api_keys = json.load(f)

    app = ClarifaiApp(api_key=api_keys['CLARIFAI_API_KEY'])

    # get the general model
    model = app.models.get("general-v1.3")

    all_violence_files = glob.glob('{}/*'.format(args.input_image_folder))
    print(all_violence_files)

    #result = predict_with_local_file('images/Man-holding-a-knife-via-Shutterstock.jpg')
    for fp in all_violence_files:
        file_name = fp.split('\\')[1]
        output_json_path = 'results/{}_image_results/{}.json'.format(args.class_type, file_name)

        if os.path.exists(output_json_path):
            print('Path exists: {}'.format(output_json_path))
            continue
Beispiel #3
0
from clarifai import rest
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage
import json
import requests

app = ClarifaiApp(api_key='ec6402c259dc42a5a0d8d48b1e121cad')

model = app.models.get('nsfw-v1.0')
image = ClImage(url='https://pbs.twimg.com/media/BFG-BCSCMAA7sF9.jpg')
response = model.predict([image])

concepts = response['outputs'][0]['data']['concepts']
for concept in concepts:
    if concept["name"] == "sfw":
        sfw_val = concept["value"]
    if concept["name"] == "nsfw":
        nsfw_val = concept["value"]
#print(concept['name'], concept['value'])

print("sfw: ", sfw_val)
print("nsfw: ", nsfw_val)
data = {
    "type":
    "bulk",
    "args": [{
        "type": "delete",
        "args": {
            "table": "clarifai_nsfw",
            "where": {}
        }
Beispiel #4
0
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage
from clarifai.client import ClarifaiApi
import os
import json
import argparse
from key import *

app = ClarifaiApp(CLIENT_KEY, CLIENT_SECRET)
clarifai_api = ClarifaiApi(CLIENT_KEY, CLIENT_SECRET)

# get the general model
model = app.models.get("general-v1.3")


def classify_images(folder):
    images = []
    image_prefix = folder + "/{0}"
    for frame in os.listdir(folder):
        if ".jpg" in frame:
            img = ClImage(file_obj=open(image_prefix.format(frame), 'rb'))
            images.append(img)
    response = model.predict(images)
    return extract_result(response)


def extract_result(response):
    data = response["outputs"][0]["data"]["concepts"]
    result = list()
    # a list of tuples in the form (name, probability)
    for datum in data:
Beispiel #5
0
from flask import Flask, render_template, request
from werkzeug import secure_filename
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage

app = ClarifaiApp(api_key='ed78ccc5e8764fee8fc8c750ef421de2')
appF = Flask(__name__)


@appF.route('/upload')
def upload_file2():
    return render_template('upload.html')


@appF.route('/uploader', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['file']
        f.save(secure_filename(f.filename))
        #return determine(f.filename)
        return render_template('afterUpload.html',
                               answer=determine(f.filename))
        #return 'file uploaded successfully'


def determine(image):

    # get the general model
    #model = app.models.get("general-v1.3")
    model = app.models.get("Ocean Cleanup")
    image = ClImage(file_obj=open(image, 'rb'))
Beispiel #6
0
 def setUpClass(cls):
     cls.api = ApiClient(log_level=logging.WARN)
     cls.app = ClarifaiApp(log_level=logging.WARN)
Beispiel #7
0
#nltk.download('twitter_samples')
nltk.download('brown')
from nltk.corpus import brown
for category in brown.categories():
    words = brown.words(categories=category)
    text = " ".join(words)
    filename = 'data-markovify/' + category + '.txt'
    outfile = open(filename, 'w')
    outfile.write(text)
    outfile.close()

import inflect
import markovify

app = ClarifaiApp(api_key='1f2c93de75074a088597cd7791491b5a')
model = app.public_models.general_model
'''
Lazytag Bot
1. Generate list of keywords from Clarifai model
2. Filter the keywords
3. Recieve most search words from each sub-reddit from the worddit api
4. Compare the keywords with most search word
5. Find the subreddit that has the highest probability of producing an acurate comment
6. Generate comment with comments produced from the subreddit
'''

## Inputs ##
# an image url
sample_img = "https://images.unsplash.com/photo-1518791841217-8f162f1e1131?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2850&q=80"
if len(sys.argv) > 1:
Beispiel #8
0
from clarifai.rest import ClarifaiApp
from food import search_food

import json
import urllib2

url = 'https://api.nal.usda.gov/ndb/search/?format=json&api_key=fsH5vnlqW2BI46MwQCEvrmw2nAJjb0QyOjWbIoaS&q=beer, coke, soda&ds=Standard Reference'

app = ClarifaiApp(api_key='4ca3a32fd0fc40eeb9bb314978689e3a')


def get_relevant_tags(image_url):
    response_data = app.tag_urls(urls=[image_url],
                                 model_id='bd367be194cf45149e75f01d59f77ba7')

    tag_urls = []
    for concept in response_data['outputs'][0]['data']['concepts']:
        tag_urls.append(concept['name'])
    str = "Hello from RowdyHacks\n"
    #return str + ' \n'.join(tag_urls[0:3])
    return tag_urls[0:3]


#print get_relevant_tags('https://brendid.com/wp-content/uploads/2015/10/Pear-Recipes-7.jpg')
#print get_food_nut()
Beispiel #9
0
def test_add_concepts(mock_http_client):  # type: (mock.Mock) -> None
    mock_execute_request = mock_request(
        mock_http_client, """
{
    "status": {
        "code": 10000,
        "description": "Ok"
    },
    "inputs": [{
        "id": "@inputID",
        "data": {
            "image": {
                "url": "@imageURL"
            },
            "concepts": [
                {
                  "id": "@positiveConcept1",
                  "value": 1
                },
                {
                  "id": "@positiveConcept2",
                  "value": 1
                },
                {
                  "id": "@negativeConcept1",
                  "name": "@negativeConceptName1",
                  "value": 0
                },
                {
                  "id": "@negativeConcept2",
                  "value": 0
                }
            ]
        },
        "created_at": "2017-10-13T20:53:00.253139Z",
        "modified_at": "2017-10-13T20:53:00.868659782Z",
        "status": {
            "code": 30200,
            "description": "Input image modification success"
        }
    }]
}
""")

    app = ClarifaiApp()
    image = app.inputs.add_concepts('@inputID', ['@positiveConcept1'],
                                    ['@negativeConcept1'])

    assert image.input_id == '@inputID'
    assert image.url == '@imageURL'

    assert_request(
        mock_execute_request, 'PATCH', '/v2/inputs', """
  {
    "inputs": [
      {
        "id": "@inputID",
        "data": {
          "concepts": [
            {
              "id": "@positiveConcept1",
              "value": 1
            },
            {
              "id": "@negativeConcept1",
              "value": 0
            }
          ]
        }
      }
    ],
    "action":"merge"
  }
          """)
Beispiel #10
0
def test_get_all(mock_http_client):  # type: (mock.Mock) -> None
    mock_execute_request = mock_request(mock_http_client,
                                        json_responses=[
                                            """
{
  "status": {
    "code": 10000,
    "description": "Ok"
  },
  "inputs": [
    {
      "id": "@inputID1",
      "data": {
        "image": {
          "url": "https://some.image.url1"
        },
        "geo": {
          "geo_point": {
            "longitude": 55,
            "latitude": 66
          }
        }
      },
      "created_at": "2019-01-17T14:02:21.216473Z",
      "modified_at": "2019-01-17T14:02:21.800792Z",
      "status": {
        "code": 30000,
        "description": "Download complete"
      }
    },
    {
      "id": "@inputID2",
      "data": {
        "image": {
          "url": "https://some.image.url2"
        }
      },
      "created_at": "2019-01-17T14:02:21.216473Z",
      "modified_at": "2019-01-17T14:02:21.800792Z",
      "status": {
        "code": 30000,
        "description": "Download complete"
      }
    }
  ]
}
""", """
{
  "status": {
    "code": 10000,
      "description": "Ok"
    },
  "inputs": []
}
"""
                                        ])

    app = ClarifaiApp()
    images = list(app.inputs.get_all())

    assert images[0].input_id == '@inputID1'
    assert images[0].url == 'https://some.image.url1'
    assert images[0].geo.geo_point.longitude == 55
    assert images[0].geo.geo_point.latitude == 66

    assert images[1].input_id == '@inputID2'
    assert images[1].url == 'https://some.image.url2'

    assert_requests(mock_execute_request,
                    requests=[('GET', '/v2/inputs', """
{"page": 1, "per_page": 20}
    """), ('GET', '/v2/inputs', """
{"page": 2, "per_page": 20}
    """)])
Beispiel #11
0
def test_bulk_update_with_metadata(
        mock_http_client):  # type: (mock.Mock) -> None
    mock_execute_request = mock_request(
        mock_http_client, """
{
    "status": {
        "code": 10000,
        "description": "Ok"
    },
    "inputs": [{
        "id": "@inputID",
        "data": {
            "image": {
                "url": "@imageURL"
            },
            "concepts": [{
                "id": "concept1",
                "name": "concept1",
                "value": 1,
                "app_id": "@appID"
            }],
            "metadata": {
                "@key1": "@value1",
                "@key2": "@value2"
            }
        },
        "created_at": "2017-11-02T15:08:22.005157Z",
        "modified_at": "2017-11-02T15:08:23.071624222Z",
        "status": {
            "code": 30200,
            "description": "Input image modification success"
        }
    }]
}
""")

    app = ClarifaiApp()
    images = app.inputs.bulk_update([
        Image(image_id='@inputID',
              metadata={
                  '@key1': '@value1',
                  '@key2': '@value2',
              })
    ],
                                    action='overwrite')

    assert images[0].input_id == '@inputID'
    assert images[0].url == '@imageURL'
    assert images[0].status.code == 30200
    assert images[0].metadata == {'@key1': '@value1', '@key2': '@value2'}

    assert_request(
        mock_execute_request, 'PATCH', '/v2/inputs', """
{
    "inputs": [
      {
        "id": "@inputID",
        "data": {
          "metadata": {
            "@key1": "@value1",
            "@key2": "@value2"
          }
        }
      }
    ],
    "action":"overwrite"
}
        """)
Beispiel #12
0
def test_bulk_update_with_regions(
        mock_http_client):  # type: (mock.Mock) -> None
    mock_execute_request = mock_request(
        mock_http_client, """
{
  "status": {
    "code": 10000,
    "description": "Ok"
  },
  "inputs": [
    {
      "id": "@inputID",
      "data": {
        "image": {
          "url": "@imageURL"
        },
        "concepts": [
          {
            "id": "@concept1",
            "name": "@concept1",
            "value": 1,
            "app_id": "@appID"
          },
          {
            "id": "@concept2",
            "name": "@concept2",
            "value": 0,
            "app_id": "@appID"
          }
        ]
      },
      "created_at": "2019-01-29T15:23:21.188492Z",
      "modified_at": "2019-01-29T15:23:21.575667Z",
      "status": {
        "code": 30200,
        "description": "Input image modification success"
      }
    }
  ]
}
""")

    app = ClarifaiApp()
    images = app.inputs.bulk_update([
        Image(image_id='@inputID',
              regions=[
                  Region(region_info=RegionInfo(
                      bbox=BoundingBox(0.5, 0.5, 1.0, 1.0),
                      feedback_type=FeedbackType.misplaced),
                         concepts=[
                             Concept(concept_id='@concept1', value=True),
                             Concept(concept_id='@concept2', value=False)
                         ],
                         region_id='@regionID',
                         face=Face(identity=FaceIdentity(concepts=[
                             Concept(concept_id='@faceConcept1', value=True),
                             Concept(concept_id='@faceConcept2', value=False),
                         ])))
              ])
    ],
                                    action='overwrite')

    assert images[0].input_id == '@inputID'
    assert images[0].url == '@imageURL'
    assert images[0].status.code == 30200

    assert_request(
        mock_execute_request, 'PATCH', '/v2/inputs', """
{
  "inputs": [
    {
      "id": "@inputID",
      "data": {
        "regions": [
          {
            "id": "@regionID",
            "region_info": {
              "bounding_box": {
                "top_row": 0.5,
                "left_col": 0.5,
                "bottom_row": 1,
                "right_col": 1
              },
              "feedback": "misplaced"
            },
            "data": {
              "concepts": [
                {
                  "id": "@concept1",
                  "value": 1
                },
                {
                  "id": "@concept2",
                  "value": 0
                }
              ],
              "face": {
                "identity": {
                  "concepts": [
                    {
                      "id": "@faceConcept1",
                      "value": 1
                    },
                    {
                      "id": "@faceConcept2",
                      "value": 0
                    }
                  ]
                }
              }
            }
          }
        ]
      }
    }
  ],
  "action": "overwrite"
}
        """)
Beispiel #13
0
def test_bulk_create_image(mock_http_client):  # type: (mock.Mock) -> None
    mock_execute_request = mock_request(
        mock_http_client, """
{
  "status": {
    "code": 10000,
    "description": "Ok"
  },
  "inputs": [
    {
      "id": "@inputID1",
      "data": {
        "image": {
          "url": "https://some.image.url1"
        },
        "geo": {
          "geo_point": {
            "longitude": 55,
            "latitude": 66
          }
        }
      },
      "created_at": "2019-01-17T12:43:04.895006174Z",
      "modified_at": "2019-01-17T12:43:04.895006174Z",
      "status": {
        "code": 30001,
        "description": "Download pending"
      }
    },
    {
      "id": "@inputID2",
      "data": {
        "image": {
          "url": "https://some.image.url2"
        }
      },
      "created_at": "2019-01-17T12:43:04.895006174Z",
      "modified_at": "2019-01-17T12:43:04.895006174Z",
      "status": {
        "code": 30001,
        "description": "Download pending"
      }
    }
  ]
}
""")

    app = ClarifaiApp()
    images = app.inputs.bulk_create_images([
        Image(url='https://some.image.url1',
              image_id='@inputID1',
              allow_dup_url=True,
              geo=Geo(geo_point=GeoPoint(55, 66))),
        Image(url='https://some.image.url2',
              image_id='@inputID2',
              allow_dup_url=True),
    ])

    assert images[0].input_id == '@inputID1'
    assert images[0].url == 'https://some.image.url1'
    assert images[0].geo.geo_point.longitude == 55
    assert images[0].geo.geo_point.latitude == 66
    assert images[0].status.code == 30001

    assert images[1].input_id == '@inputID2'
    assert images[1].url == 'https://some.image.url2'
    assert not images[1].geo
    assert images[1].status.code == 30001

    assert_request(
        mock_execute_request, 'POST', '/v2/inputs', """
{
  "inputs": [
    {
      "id": "@inputID1",
      "data": {
        "image": {
          "url": "https://some.image.url1",
          "allow_duplicate_url": true
        },
        "geo": {
          "geo_point": {
            "longitude": 55,
            "latitude": 66
          }
        }
      }
    },
    {
      "id": "@inputID2",
      "data": {
        "image": {
          "url": "https://some.image.url2",
          "allow_duplicate_url": true
        }
      }
    }
  ]
}
        """)
Beispiel #14
0
from clarifai.rest import ClarifaiApp
from pprint import pprint

client_id = "TMWN2VTpC-gVCqsQM8etnUXRoEYJwFdeK7R0L589"
client_secret = "XgqM1Hle2TY7NEZ0PPKS3op02X2RkCrbfegbr3vS"
StyAiconcepts = ['arty','business','casual','chic','elegant','female','goth','preppy','streetwear']

app = ClarifaiApp(client_id, client_secret)

query = app.inputs.search_by_predicted_concepts(concepts=['men','streetwear'])


print len(query)

for q in query:
    model = app.models.get("general-v1.3")
    # pprint(model.predict([q]))
    # raw_input()

def test_search_concepts_with_language(
        mock_http_client):  # type: (mock.Mock) -> None
    mock_execute_request = mock_request(mock_http_client,
                                        json_responses=[
                                            """
{
  "status": {
    "code": 10000,
    "description": "Ok"
  },
  "concepts": [
    {
      "id": "@conceptID1",
      "name": "狗",
      "value": 1,
      "created_at": "2016-03-17T11:43:01.223962Z",
      "language": "zh",
      "app_id": "main"
    },
    {
      "id": "@conceptID2",
      "name": "狗仔队",
      "value": 1,
      "created_at": "2016-03-17T11:43:01.223962Z",
      "language": "zh",
      "app_id": "main"
    }
  ]
}
""", """
{
  "status": {
    "code": 10000,
    "description": "Ok"
  },
  "concepts": []
}
"""
                                        ])

    app = ClarifaiApp()
    concepts = list(app.concepts.search('狗*', lang='zh'))

    assert concepts[0].concept_id == '@conceptID1'
    assert concepts[0].concept_name == u'狗'

    assert concepts[1].concept_id == '@conceptID2'
    assert concepts[1].concept_name == u'狗仔队'

    assert_requests(mock_execute_request,
                    requests=[('POST', '/v2/concepts/searches', """
{
  "concept_query": {
    "name": "狗*",
    "language": "zh"
  },
  "pagination": {
    "per_page": 20,
    "page": 1
  }
}
  """),
                              ('POST', '/v2/concepts/searches', """
{
  "concept_query": {
    "name": "狗*",
    "language": "zh"
  },
  "pagination": {
    "per_page": 20,
    "page": 2
  }
}
  """)])
Beispiel #16
0
def main():
    app = ClarifaiApp()
    model = app.models.get('general-v1.3')

    bytes = raw_input("base64: ")
    print model.predict_by_base64(bytes)['outputs'][0]['data']['concepts']
Beispiel #17
0
    def __init__(self, api_key, api_id):

        self.api_key = api_key
        self.api_id = api_id
        self.app = ClarifaiApp(api_key=self.api_key)
        self.client = wolframalpha.Client(self.api_id)
Beispiel #18
0
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage
import os

APP = ClarifaiApp(api_key="a11ec80513f94400a2caf2867db4bca6")

# APP.inputs.delete_all()

# app.inputs.delete_all()


def sendData(letter):

    FOLDER_PATH = "/Users/singhdas/Downloads/asl-alphabet/asl_alphabet_train/" + letter.upper(
    ) + "/"
    alphabets = "abc"
    count = 0
    lst = []
    #
    for filename in os.listdir(FOLDER_PATH):
        if (filename >= "C1550.jpg" and count < 128):
            count += 1
            not_concepts = list(alphabets.replace(letter.lower(), ""))
            lst.append(
                ClImage(filename=FOLDER_PATH + filename,
                        concepts=[letter.lower()],
                        not_concepts=not_concepts))
            # break
    # print(lst)
    APP.inputs.bulk_create_images(lst)
    print("Done")
Beispiel #19
0
 def __init__(self, toml_file=None):
     super().__init__(toml_file)
     self.app = ClarifaiApp(api_key=Bundle.API_KEY)
     self.set_bundle(Bundle)
     self.set_ready()
Beispiel #20
0
from django.shortcuts import render, redirect
from .models import Clothing
from .forms import ClothingForm
from clarifai import rest
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage
#Jason's Clarifai Client ID, Client Secret
app = ClarifaiApp("wPXX8nSrRj_A25bqQAdAurGdZdbxzhJWELL9aaQ2",
                  "SRRlIyrXfV7bJkNE7R3naCBPkxw3J-UwqVgcxJhJ")
#Model for Apparel Prediction
model = app.models.get('e0be3b9d6a454f0493ac3a30784001ff')


#Takes a URL in text, returns the response as a string
#This function is the main part of this code, use it to format any clarifai API response
def clarify(urlstr):
    x = app.inputs.create_image_from_filename(urlstr)

    predictions = str(model.predict([x]))

    #Outputing the response string to a file and formatting it
    fil = open('output.txt', 'w')
    for i in predictions:
        if i == '}':
            fil.write('}\n')
        else:
            fil.write(i)

    #Takes the highest confidence line
    fil = open('output.txt', 'r')
    for line in fil:
Beispiel #21
0
 def setUpClass(cls):
     cls.app = ClarifaiApp(log_level=logging.WARN)
# -*- coding: utf-8 -*-

from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage
import pandas as pd
import csv

app = ClarifaiApp(api_key='211d6ec030764627b5b07984b4881cda')
#paintings = pd.read_csv('../dados/paintings.csv') #read data and name columns
paintings = pd.read_csv('../dados/treino.csv', sep=';', encoding='latin-1')

all_concepts = []
todos_autores = []
todas_escolas = []
todas_tecnicas = []
i = 0
for index, row in paintings.iterrows():
    if i < 1000:
        tecnica = row['TECHNIQUE'].split(',')[0]
        autor = row['AUTHOR']
        escola = row['SCHOOL']
        all_concepts = all_concepts + [tecnica, autor, escola]
        todos_autores.append(autor)
        todas_escolas.append(escola)
        todas_tecnicas.append(tecnica)

        i = i + 1

all_concepts = list(set(all_concepts))
todas_escolas = list(set(todas_escolas))
todos_autores = list(set(todos_autores))
Beispiel #23
0
from clarifai.rest import ClarifaiApp

app = ClarifaiApp("ixACIQvGqKKcJCGLT_xnEh4_jlG7dRKXuzF4jam3",
                  "-XQ5gLtB0ZljTUEmoaqV4LI8UXdlwZNEvLTkSXt-")

model = app.models.get('general-v1.3')

response = model.predict_by_url(
    url='https://avatars1.githubusercontent.com/u/3252741?v=3&s=400')

for tag in response["outputs"][0]["data"]["concepts"]:
    print(tag["name"])
os.system("sudo google_speech 'capture complete. uploading file '")

destination_blob_name = name
source_file_name = name

blob = bucket.blob(destination_blob_name)

blob.upload_from_filename(source_file_name)
blob.make_public()

print('File {} uploaded to {}.'.format(source_file_name,
                                       destination_blob_name))

imageurl = 'https://storage.googleapis.com/melanomadetector/candidate.jpg'

app = ClarifaiApp(api_key=api_key)

model = app.models.get('melanomadetector')
model.model_version = 'd472e3e2fab84c698de67c47dfeb1123'

image = ClImage(url=imageurl)

os.system("sudo google_speech 'upload complete. analyzing '")

output = model.predict([image])

print(output)

print('----------')

##jsonres = json.loads(output)
Beispiel #25
0
import random


def scrambled(orig):  ##shuffling a list of image locations
    dest = orig[:]
    random.shuffle(dest)
    return dest


def batch(iterable, n=128):
    l = len(iterable)
    for ndx in range(0, l, n):
        yield iterable[ndx:min(ndx + n, l)]


app = ClarifaiApp(api_key='REDACTED')

img_locs = scrambled(
    glob(".//persons_cropped//*.jpg"))  #all photos in the 'no' set, shuffled
no_train = img_locs[:401]  #select the training data for 'no'

yes_train = glob(".//yes//*.jpg")[:401]  #same for 'yes'

no_val = img_locs[401:]
yes_val = img_locs[401:]

yes_img_list = [
    ClImage(filename=image, concepts=["yes"]) for image in yes_train
]  #creating lists of Clarifai data points and labels
no_img_list = [ClImage(filename=image, concepts=["no"]) for image in no_train]
test_nos = [ClImage(filename=image) for image in no_val]
Beispiel #26
0
import imutils
import cv2
from googletrans import Translator

app = Flask(__name__)
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage

APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT, 'images/')
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
sess = Session()
application = ClarifaiApp(api_key='eb7f93f1cce54defb92e276ab515d948')

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def get_ext(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower()

app.add_url_rule('/images/<filename>', 'uploaded_file', build_only=True)
app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
    '/images':  app.config['UPLOAD_FOLDER']
})

@app.route('/images/predict', methods=['GET','POST'])
parser.add_argument("--num_iter",
                    type=int,
                    default=5,
                    help="number of iterations to run")
parser.add_argument("--group_size",
                    type=int,
                    default=10000,
                    help="Number of features to group together")
parser.add_argument("--delta",
                    type=float,
                    default=1.0,
                    help="local perturbation")

args = parser.parse_args()

app = ClarifaiApp()

model = app.models.get(args.target_model)

time1 = time.time()
success = 0
avg_l2_perturb = 0
curr_image = args.target_image_name + '.jpg'
curr_sample = np.array(mpimg.imread(curr_image), dtype=float)
array_shape = curr_sample.shape
if len(curr_sample.shape) > 2:
    curr_sample = curr_sample[:, :, :3]
else:
    curr_sample = curr_sample.reshape((array_shape[0], array_shape[1], 1))

BATCH_SIZE = 1
Beispiel #28
0
 def __init__(self, api_key: str = None, logger=None):
     self.app = ClarifaiApp(api_key=api_key)
     self.model = self.app.public_models.general_model
     self.logger = logger
import requests
import csv
import os
import json
import argparse
import requests
import random
import re
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage

app = ClarifaiApp(api_key='')
model = app.models.get('demographics')
collected = 0

#------------------------------
count1 = 0
count2 = 0
for jsonfile in os.listdir('real'):
    print(count1, " files collected")
    print(count2, " files skipped")
    if os.path.exists("real_demographic_response" + os.sep + jsonfile):
        count1 += 1
        print("Already got data for ", jsonfile)
        continue

    print("Working on real user: ", jsonfile)
    try:
        current = json.load(open('real' + os.sep + jsonfile, 'r'))
        img_list = current['images']
        img_paths = []
Beispiel #30
0
def test_get_all_models(mock_http_client):  # type: (mock.Mock) -> None
    mock_execute_request = mock_request(mock_http_client,
                                        json_responses=[
                                            """
{
  "status": {
    "code": 10000,
      "description": "Ok"
    },
  "models": [
    {
      "id": "@modelID1",
      "name": "@modelName1",
      "created_at": "2019-01-16T23:33:46.605294Z",
      "app_id": "main",
      "output_info": {
        "message": "Show output_info with: GET /models/{model_id}/output_info",
        "type": "facedetect",
        "type_ext": "facedetect"
      },
      "model_version": {
        "id": "28b2ff6148684aa2b18a34cd004b4fac",
        "created_at": "2019-01-16T23:33:46.605294Z",
        "status": {
          "code": 21100,
          "description": "Model trained successfully"
        },
        "train_stats": {}
      },
      "display_name": "Face Detection"
    },
    {
      "id": "@modelID2",
      "name": "@modelName2",
      "created_at": "2019-01-16T23:33:46.605294Z",
      "app_id": "main",
      "output_info": {
        "message": "Show output_info with: GET /models/{model_id}/output_info",
        "type": "embed",
        "type_ext": "detect-embed"
      },
      "model_version": {
        "id": "fc6999e5eb274dfdba826f6b1c7ffdab",
        "created_at": "2019-01-16T23:33:46.605294Z",
        "status": {
          "code": 21100,
          "description": "Model trained successfully"
        },
        "train_stats": {}
      },
      "display_name": "Face Embedding"
    }
  ]
}
""", """
{
  "status": {
    "code": 10000,
      "description": "Ok"
    },
  "models": []
}
      """
                                        ])

    app = ClarifaiApp()
    models = list(app.models.get_all())

    assert models[0].model_id == '@modelID1'
    assert models[0].model_name == '@modelName1'
    assert models[0].output_info['type_ext'] == 'facedetect'

    assert models[1].model_id == '@modelID2'
    assert models[1].model_name == '@modelName2'
    assert models[1].output_info['type_ext'] == 'detect-embed'

    assert_requests(mock_execute_request, [
        ('GET', '/v2/models', '{"per_page": 20, "page": 1}'),
        ('GET', '/v2/models', '{"per_page": 20, "page": 2}'),
    ])
Beispiel #31
0
from clarifai.rest import ClarifaiApp
myApi = '937179c1c41f4378b15017c3bc501ce4'
app = ClarifaiApp(api_key=myApi)


def predict(imageLink, myApi):
    app = ClarifaiApp(api_key=myApi)

    model = app.public_models.general_model

    response = model.predict_by_filename(imageLink)

    concepts = response['outputs'][0]['data']['concepts']
    results = []

    for concept in concepts:
        results.append((concept['name']))

    return results