Exemplo n.º 1
0
def test_bulk_update_with_metadata(
        mock_http_client):  # type: (mock.Mock) -> None
    mock_execute_request = mock_request(mock_http_client,
                                        json_responses=[
                                            """
{
    "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_inputs([
        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"
}
        """)
Exemplo n.º 2
0
#need to install clarify (pip)
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage
import pprint
app = ClarifaiApp(api_key='e5af645934f34cee8ec140028c1fff12')

def fooditem(new_image):
    model = app.models.get('food-items-v1.0')
    image = ClImage(file_obj=open(new_image, 'rb'))
    r =  model.predict([image])
    food_items = dict()
    #pprint.pprint(model.predict([image]))
    food_items = [r['outputs'][0]['data']['concepts'][0]['name'], \
                 r['outputs'][0]['data']['concepts'][1]['name'], \
                 r['outputs'][0]['data']['concepts'][2]['name'], \
                 r['outputs'][0]['data']['concepts'][3]['name'], \
                 r['outputs'][0]['data']['concepts'][4]['name']]
    return food_items
    #print r['outputs'][0]['data']['concepts'][0]['name'] #Option 1
    #print r['outputs'][0]['data']['concepts'][1]['name'] #Option 2
    #print r['outputs'][0]['data']['concepts'][2]['name'] #Option 3
    #print r['outputs'][0]['data']['concepts'][3]['name'] #Option 4
    #print r['outputs'][0]['data']['concepts'][4]['name'] #Option 5
Exemplo n.º 3
0
# clarifai: an image analysis api
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage

# requests: a library to make http requests
import requests

# lxml: a library to parse html documents
from lxml import html, etree

# PyMongo schemas
from schema import *

# API KEY: dbe3f2920953470199637703b6566c31

app = ClarifaiApp(api_key='dbe3f2920953470199637703b6566c31'
                  )  # TODO: hide this key in an environment variable.


def clarifai_clear_images():
    app.inputs.delete_all()  # TODO: this might be asynchronous :/


def clarifai_upload_images(
    image_urls,
    batch_size=30
):  # uploads images in batches. why? because the tutorial said so.
    image_list = []
    image_counter = 0
    for image_url in image_urls:
        image_list.append(ClImage(url=image_url))
        image_counter += 1
Exemplo n.º 4
0
# Create your views here.
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

# import key from project settings.py
from imagely.settings import CLARIFAI_API_KEY

# import python ClarifaiApp
from clarifai.rest import ClarifaiApp
cf_app = ClarifaiApp(api_key=CLARIFAI_API_KEY)

# View Functions for /image routes

# csrf added to handle POST request not related to FE Form


@csrf_exempt
def images(request):
    """
    Handles all requests for /image route, methods: GET, POST
    """
    if request.method == 'POST':

        # get encoded base64 pic from post request
        encodedpic = request.POST.get('encodedpic')

        # set clarifai model to use
        # model = cf_app.public_models.general_model
        model = cf_app.models.get('food-items-v1.0')

        # get dict from clarifai
Exemplo n.º 5
0
    def __init__(self,
                 cb_get_frame,
                 min_object_area=200,
                 object_movement_threshold=10,
                 archive_folder="/tmp/",
                 do_recognize=False,
                 clarifai_client_id=None,
                 clarifai_client_secret=None):
        """ Constructeur dans lequel on va initialiser les variables.
            Paramètres : 
            @cb_get_frame : callback vers la fonction qui récupère la frame courante du flux vidéo.
            @min_object_area : aire minimale en pixels des objets détectés dans l'image.
            @object_movement_threshold : seuil de tolérance pour le mouvement des objets .
            @archive_folder : dossier qui sera utilisé pour stocker des images sous forme de fichiers.
            @do_recognize : True/False : activer (True) ou non l'identification des objets détectés avec Clarifai.
            @clarifai_client_id : client id pour utiliser l'API de Clarifai.
            @clarifai_client_secret : clé du client pour utiliser l'API de Clarifai.
        """

        # On affecte les valeurs des paramètres à des variables de la classe
        self.get_frame = cb_get_frame
        self.min_object_area = min_object_area
        self.object_movement_threshold = object_movement_threshold
        self.archive_folder = archive_folder
        self.do_recognize = do_recognize
        self.clarifai_client_id = clarifai_client_id
        self.clarifai_client_secret = clarifai_client_secret

        # On initialise la frame pour l'affichage de l'image
        self.frame = None

        # On initialise une frame 'outil' pour afficher les objets détectés hors de l'image.
        # La taille de cette frame (500px de haut pour 1500px de large) sera à adapter en fonction de l'usage.
        # Dans le cadre de cet article, elle permet d'afficher une dizaine d'objets détectés.
        self.frame_found_objects = np.zeros((500, 1500, 3), np.uint8)

        # On intialise la liste des objets détectés.
        # Elle contiendra cette structure :
        #   { "id1" :
        #       {
        #          "x" : coordonnées
        #          "y" : coordonnées
        #          "w" : coordonnées
        #          "h" : coordonnées
        #          "img" : l'image de l'objet lors de sa première apparition
        #          "recognition" : une liste de tags qui décrivent l'objet
        #          "first_seen" : le moment où a été vu l'objet la première fois
        #          "last_seen" : le dernier moment où a été vu l'objet
        #       },
        #     "id2" :
        #       { ... },
        #     ...
        #  }
        self.objects = {}

        # On initialise un compteur qui contient l'id du dernier objet trouvé.
        # Il sera incrémenté au prochain objet trouvé.
        self.last_object_id = 0

        # Si on souhaite activer l'identification des objets
        if self.do_recognize:
            # Initialisation de Clarifai avec l'identifiant et sa clé.
            app = ClarifaiApp(self.clarifai_client_id,
                              self.clarifai_client_secret)
            # Création du model Clarifai. Ici on utilise le modèle général.
            self.model = app.models.get("general-v1.3")
Exemplo n.º 6
0
from core import *

from nltk.tag.perceptron import PerceptronTagger

from nltk.corpus import brown

from nltk import tokenize

import numpy as np

from scipy.sparse import csc_matrix

app = Flask(__name__)
CORS(app)

clarifai = ClarifaiApp(app_id='VWLdaFkl56G5o81k54s-ZI6se11adzKSFnVQ_Ggg',
                       app_secret='QnVFC6wRIWDplb3SZBVX5iMLje_tA9oWtyj8WpcH')

clarifai_model = clarifai.models.get('general-v1.3')

tagger = PerceptronTagger()

total_word_counts = {}

for s in brown.sents():
    s = map(lambda k: k.lower(), s)
    for w in set(s):
        if w not in total_word_counts:
            total_word_counts[w] = 0
        total_word_counts[w] += 1

brown_sent_count = len(brown.sents())
Exemplo n.º 7
0
from clarifai import rest
from clarifai.rest import ClarifaiApp

app = ClarifaiApp("M0ytZ-ulTpWGpY9zCtZHea-VPJQRe4I4onV_5tAe", "WVDAYcncI5DozDkEJUiMFgNRoFgaWjQyJqrCS1wm")

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

model.predict_by_url(url='http://www.so-rummet.se/sites/default/files/nu_och_da/nazisternas-hakkors.gif')
Exemplo n.º 8
0
def get_clarifai_api():
    return ClarifaiApp(CLIENT_ID, CLIENT_SECRET)
Exemplo n.º 9
0
	def __init__(self):
		app = ClarifaiApp(api_key='KEY')
		self.model = app.models.get('apparel')
		self.concepts = []
Exemplo n.º 10
0
time.sleep(.1)

while True:
    print(sensor1.distance * 100)
    time.sleep(0.1)
    if sensor1.distance * 100 < 20:
        print("hit")
        time.sleep(0.5)
        stream1 = os.popen('fswebcam /home/pi/test/Images/image.jpg')
        output1 = stream1.read()
        my_string1 = ""
        
        with open("/home/pi/test/Images/image.jpg", "rb") as img_file1:
            my_string1 = base64.b64encode(img_file1.read())
            
        app = ClarifaiApp(api_key='71a594e3144a4ca89c761a6a5504c4a8')

        model = app.public_models.general_model
        response = model.predict_by_filename('Images/image.jpg')

        recycle = False
        for x in response['outputs'][0]['data']['concepts']:
            if x['name'] == "recycling" or x['name'] == "plastic":
                print(x['name'])
                recycle = True

        if recycle:
            SetAngle(175)
            time.sleep(2)
            SetAngle(100)
        else:
Exemplo n.º 11
0
from clarifai import rest
from clarifai.rest import ClarifaiApp
#from clarifai.rest import Image as ClImage

UPLOAD_TO_WIN=ClarifaiApp()
app.inputs.create_image_from_filename('/home/vishwarupa/Pictures', concepts=['boy'])
Exemplo n.º 12
0
from __future__ import print_function  # In python 2.7
import os
import json
from clarifai import rest
from clarifai.rest import ClarifaiApp
app1 = ClarifaiApp("fXY39wieIcnVwRxNlu4d2HbKGupLzHXrvF1rYPMZ",
                   "y6-0qljij7SOOVC1FuRylVhKh7lgeLDu-TIbfkCW")
from clarifai.rest import Image as CImage
import csv

# We'll render HTML templates and access data sent by POST
# using the request object from flask. Redirect and url_for
# will be used to redirect the user once the upload is done
# and send_from_directory will help us to send/show on the
# browser the file that the user just uploaded
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from werkzeug import secure_filename

import sys

# Initialize the Flask application
app = Flask(__name__)

# This is the path to the upload directory
app.config['UPLOAD_FOLDER'] = 'uploads/'
# These are the extension that we are accepting to be uploaded
app.config['ALLOWED_EXTENSIONS'] = set(
    ['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])


# For a given file, return whether it's an allowed type or not
Exemplo n.º 13
0
def test_add_concepts(mock_http_client):  # type: (mock.Mock) -> None
    mock_execute_request = mock_request(mock_http_client,
                                        json_responses=[
                                            """
{
    "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"
  }
          """)
Exemplo n.º 14
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}
    """)])

    # An empty list should be returned in the case of an emtpy JSON
    mock_request(mock_http_client,
                 json_responses=[
                     """
{
  "status": {
    "code": 10000,
      "description": "Ok"
    },
  "inputs": []
}
"""
                 ])
    images = list(app.inputs.get_all())
    assert not images
Exemplo n.º 15
0
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage
import constants
import os

app = ClarifaiApp(api_key=constants.CLARIFAI_API)

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

add cardboard
cardboard files
cardboard_imgs = os.listdir('data/train/cardboard')
cardboard_imgs = list(chunks(cardboard_imgs, 128))
for split_cardboard_imgs in cardboard_imgs:
	imgs = []
	for img_name in split_cardboard_imgs:
		print(img_name)
		if img_name == ".DS_Store":
			continue
		img = ClImage(filename=f"data/train/cardboard/{img_name}", concepts=["cardboard"], not_concepts=["glass", "metal", "plastic", "trash"])
		imgs.append(img)
	app.inputs.bulk_create_images(imgs)

glass_imgs = os.listdir('data/train/glass')
glass_imgs = list(chunks(glass_imgs, 128))
for split_glass_imgs in glass_imgs:
	imgs = []
	for img_name in split_glass_imgs:
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage
import os
import csv
from datetime import datetime

CHICAGO_DB_PATH = "/Users/samuilstoychev/Desktop/researchproject/api_processing/Datasets/CFD/Images"
API_KEY = '<Insert-API-Key-here>'
OUTPUT_FILE = 'clarifai_output.csv'
app = ClarifaiApp(api_key=API_KEY)


def collect_images():
    """ Collect images from the Chicago Database and extract in a list. """
    # Get the contents of the current directory
    folders = os.listdir(CHICAGO_DB_PATH)
    # Filter only folders
    folders = list(
        filter(lambda x: os.path.isdir("/".join([CHICAGO_DB_PATH, x])),
               folders))
    # Sanity check
    assert len(folders) == 597
    all_images = []
    for folder in folders:
        images = os.listdir("/".join([CHICAGO_DB_PATH, folder]))
        images = filter(lambda x: x[-3:] == "jpg", images)
        images = list(
            map(lambda x: "/".join([CHICAGO_DB_PATH, folder, x]), images))
        assert (len(images) > 0 and len(images) < 6)
        all_images += images
Exemplo n.º 17
0
from clarifai import rest
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage
import tempfile
from werkzeug.utils import secure_filename
import json
import boto3
import rules
import forecastio
import smtplib

app = Flask(__name__)
import models
s3 = boto3.resource('s3')
dark_sky_key = os.getenv("DARK_SKY_KEY")
appClar = ClarifaiApp(os.getenv("clarifai_client_id"),
                      os.getenv("clarifai_client_secret"))


###################################Clarifai methods#############################
#returns an an array of  possible apparel
#attr
#name-apparelName
#value-confidence
def possibleApparel(appCont, name):
    model = appCont.models.get('e0be3b9d6a454f0493ac3a30784001ff')
    image = ClImage(file_obj=open(name, 'rb'))
    response = model.predict([image])
    response = response["outputs"][0]["data"]["concepts"]
    item = response
    items = []
    items.append(item[0])
from clarifai import rest
from clarifai.rest import ClarifaiApp

app = ClarifaiApp('client id', 'client secret')
model = app.models.get("general-v1.3")

# predict with the model
print model.predict_by_url(url='https://samples.clarifai.com/metro-north.jpg')
Exemplo n.º 19
0
from flask import Flask, render_template, request
# https://docs.clarifai.com/api-guide/train#train
from clarifai.rest import ClarifaiApp
from clarifai.rest import Image as ClImage

key = 'd8c6adff128c41d8a95a375cea3357dc'
app = ClarifaiApp(api_key=key)


def get_photo_tags(link):
    model = app.models.get('general-v1.3')
    image = ClImage(url=link)
    u = model.predict([image])
    concepts = u['outputs'][0]['data']['concepts']
    tags = []
    for tag in concepts:
        tags.append(tag['name'])
    return tags


my_app = Flask(__name__)


@my_app.route("/", methods=["GET"])
def index():
    return render_template('index.html')


if __name__ == '__main__':
    my_app.run(debug=True)
Exemplo n.º 20
0
 def predict(self, imageURL):
     app = ClarifaiApp(api_key='b7d9cb0c34b04b898f54a281ed9a68a4')
     model = app.models.get('e9576d86d2004ed1a38ba0cf39ecb4b1')
     image = ClImage(url=imageURL)
     jsonoutput = model.predict([image])
     return jsonoutput['outputs'][0]['data']['concepts'][1]['value']
Exemplo n.º 21
0
from clarifai.rest import ClarifaiApp
import os, glob
wordbank = {}
app = ClarifaiApp('3sV5ZqH5HPz-obqWgk8m7iBHHf41IDhHHr_wUGaT', '91Mg1OCiSKYMemuJWt5GBWmK-FKmxOQ3DJmarLuY')

model = app.models.get('aaa03c23b3724a16a56b629203edc62c')

newest = min(glob.iglob('*.jpg'), key=os.path.getctime)

result = model.predict_by_filename(newest)

print(result.get("outputs")[0].get("data").get("concepts")[0])
wordbank.update(result.get("outputs")[0].get("data").get("concepts"))
print(wordbank)
Exemplo n.º 22
0
def get_food_results(path, local_file=True):
    ################ clarifai API
    # can check https://www.clarifai.com/models/ai-food-recognition
    results = ' '
    app = ClarifaiApp(api_key='keyname')
    model = app.models.get('food-items-v1.0')
    if local_file:
        response = model.predict_by_filename(path)
    else:
        response = model.predict_by_url(path)
    # print('results: %s' % results)

#Code for reading json(result from clarifai) to array in python
    crawl = []
    for each in response['outputs'][0]['data']['concepts']:
        print(each['name'], ' ', each['value'])
        #filtering probability higher than 0.7
        if (each['value'] >= 0.74):
            taken = each['name']
        else:
            continue
        crawl.append(taken)
        results = results + taken + ','

    #print(results)
    print(crawl)
    ########## Calories Crawler
    food_calorie = ''
    total_calories = 0
    for i in range(len(crawl)):
        # Google 搜尋 URL
        google_url = "https://www.google.com.tw/search"

        # 查詢參數
        foods_name = crawl[i] + " calories"
        my_params = {"q": foods_name}

        # 設定 User-Agent (UA) 來假裝是透過瀏覽器做請求
        user_agent = {
            'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
        }

        # 下載 Google 搜尋結果
        html = requests.get(google_url, params=my_params, headers=user_agent)

        # 確認是否下載成功
        if html.status_code == requests.codes.ok:
            # 以 BeautifulSoup 解析 HTML 原始碼
            soup = BeautifulSoup(html.text, "html.parser")
            item = soup.find("div", {"class": "Z0LcW"})
            if item is None:
                item = random.randint(30, 100)
            else:
                item = soup.find("div", {"class": "Z0LcW"}).text.split(' ')[0]

            print(foods_name)
            print("calorie: " + str(item) + " kcal")
            food_calorie = food_calorie + foods_name + ' ' + str(
                item) + ' kcal \n'
            total_calories = total_calories + float(item)


#####################################################################################################
    print(total_calories)
    final_result = 'i see....\n' + 'Approx. total calories : ' + str(
        total_calories) + ' kcal'
    print(final_result)
    return total_calories
Exemplo n.º 23
0
 def setUpClass(cls):
     cls.app = ClarifaiApp(log_level=logging.WARN)
Exemplo n.º 24
0
def handle_message(event):
    if isinstance(event.message, TextMessage):
        Msg = event.message.text
        print('GotMsg:{}'.format(Msg))
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="你說了: " + event.message.text))

    elif isinstance(event.message, StickerMessage):
        line_bot_api.reply_message(
            event.reply_token, StickerSendMessage(package_id=1, sticker_id=1))

    elif isinstance(event.message, ImageMessage):
        message_content = line_bot_api.get_message_content(event.message.id)
        with open(
                r'C:\Users\Nico\Desktop\大二下\IOT\Final Project\bot_final\dd.jpg',
                'wb') as fd:
            for chunk in message_content.iter_content():
                fd.write(chunk)
        try:
            client = authenticate()
            image = upload_image(client)

            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="上傳成功,圖片網址:{0}".format(
                    image['link']))  #result in here 
            )

        except:
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text='上傳失敗'))

#####################################################################################################

    userId = event.source.user_id
    if not userId in user_id_set:
        user_id_set.add(userId)
        saveUserId(userId)

    DAN.push('msg-i', image['link'])
    time.sleep(1)
    value1 = DAN.pull('msg-o')
    if value1 != None:
        print(value1[0])

    try:
        line_bot_api.push_message(
            userId,
            TextSendMessage(text='Thanks, I will process it. Please Wait ^^'))
        line_bot_api.push_message(
            userId, StickerSendMessage(package_id='1', sticker_id='2'))
        time.sleep(2)
        #######################################################################################  clarifai API
        results = ' '
        app = ClarifaiApp(api_key='48fb3f463538454eba3f2cf2ae281bde')
        model = app.models.get('food-items-v1.0')
        image = ClImage(url=value1[0])
        result = model.predict([image])
        #######################################################################################

        #Code for reading json(result from clarifai) to array in python
        crawl = []
        for each in result['outputs'][0]['data']['concepts']:
            print(each['name'], ' ', each['value'])
            #filtering probability higher than 0.7
            if (each['value'] >= 0.7):
                taken = each['name']
                DAN.push('taken-i', taken)
                time.sleep(1)
            else:
                continue
            value2 = DAN.pull('taken-o')
            crawl.append(value2[0])
            results = results + taken + ','
        print(results)

        ######################################Calories Crawler#############################################
        food_calorie = ''
        total_calories = 0
        for i in range(len(crawl)):
            # Google 搜尋 URL
            google_url = "https://www.google.com.tw/search"

            # 查詢參數
            foods_name = crawl[i] + " calories"
            my_params = {"q": foods_name}

            # 設定 User-Agent (UA) 來假裝是透過瀏覽器做請求
            user_agent = {
                'User-Agent':
                'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
            }

            # 下載 Google 搜尋結果
            html = requests.get(google_url,
                                params=my_params,
                                headers=user_agent)

            # 確認是否下載成功
            if html.status_code == requests.codes.ok:
                # 以 BeautifulSoup 解析 HTML 原始碼
                soup = BeautifulSoup(html.text, "html.parser")
                item = soup.find("div", {"class": "Z0LcW"})
                if item is None:
                    item = random.randint(30, 100)
                else:
                    item = soup.find("div", {
                        "class": "Z0LcW"
                    }).text.split(' ')[0]

                print(foods_name)
                print("熱量: " + str(item) + " kcal")
                food_calorie = food_calorie + foods_name + ' ' + str(
                    item) + ' kcal \n'
                total_calories = total_calories + float(item)


#####################################################################################################

        DAN.push('calorie-i', food_calorie)
        time.sleep(1)
        value3 = DAN.pull('calorie-o')

        print(total_calories)
        final_result = 'i see....\n' + value3[
            0] + 'Approx. total calories : ' + str(total_calories) + ' kcal'
        line_bot_api.push_message(userId, TextSendMessage(text=final_result))
        #line_bot_api.push_message(userId, TextSendMessage(text='All calories are for every 100g, hope you enjoy :D'))
        line_bot_api.push_message(
            userId, StickerSendMessage(package_id='1', sticker_id='132'))

    except:
        print('not an image url!!!!')
        line_bot_api.push_message(
            userId, TextSendMessage(text='You do not send me URL!'))
        #line_bot_api.push_message(userId, StickerSendMessage(package_id='1', sticker_id='7'))
        pass
Exemplo n.º 25
0
        return jsonify(json_to_return)
        #return jsonify(list(probas[0]))
    else:
        return '' #jsonify({'No results'})

    #return json.dumps(input_json)

if __name__ == '__main__':
    count = 0

    different_classes = ['violence', 'gambling', 'drugs', 'nudity', 'negative']

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

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

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

    model_obj = load_model('latest_model_obj.pkl')
    clf = model_obj['clf']
    vocab = model_obj['vocabulary']
    
    print('Vocab length: {}'.format(len(vocab)))
    
    model_obj_multi_clf = load_model('latest_model_obj_5_clfs.pkl')
    
    clf_violence = model_obj_multi_clf['violence']
    clf_gambling = model_obj_multi_clf['gambling']
    clf_drugs = model_obj_multi_clf['drugs']
Exemplo n.º 26
0
import urllib3
import shutil
import os
import instapy_cli
import sys
import subprocess
import string
import random
import glob
import clarifai
from instapy_cli import client
from random import randint
from clarifai import rest
from clarifai.rest import ClarifaiApp

app = ClarifaiApp(api_key='e59b78f56ed64e12b496009fdbbe5fd0')
model = app.public_models.general_model
urllib3.disable_warnings()
url = 'https://old.reddit.com/r/ANYSUBREDDIT/random.json'
http = urllib3.PoolManager()
username1 = 'YOURLOGIN'
password1 = 'YOURPASS'
suffix = ['.jpg', '.mp4', '.png']
mogrify = 'mogrify -resize 1080\\> data/rand'
pngtojpg = 'convert data/rand -background white -alpha remove data/rand.jpg && mv data/rand.jpg data/rand'
# If you need to translate
translat = 'trans -b -i data/linkdesc :ja > data/description'
clearr = 'sed -i \':a;N;$!ba;s/\\n/ /g\' data/description'
fileplace = 'data/rand'
path = os.path.dirname(os.path.abspath(__file__))
os.chdir(path)
from clarifai.rest import ClarifaiApp

65d4e71d02134ee38e1fbf37919bde33

app = ClarifaiApp()

app.inputs.create_image_from_url(url='https://samples.clarifai.com/puppy.jpeg', concepts=['my puppy'])
app.inputs.create_image_from_url(url='https://samples.clarifai.com/wedding.jpg', not_concepts=['my puppy'])
Exemplo n.º 28
0
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from clarifai.rest import ClarifaiApp
from pprint import pprint
from random import shuffle

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

app = ClarifaiApp(client_id, client_secret)

# Create your views here.

def hexColorDelta(hex1,hex2):
    r1 = int(hex1[1:3],16)
    g1 = int(hex1[3:5],16)
    b1 = int(hex1[5:7],16)

    r2 = int(hex2[1:3],16)
    g2 = int(hex2[3:5],16)
    b2 = int(hex2[5:7],16)

    r = 255 - math.abs(r1-r2)
    g = 255 - math.abs(g1-g2)
    b = 255 - math.abs(b1-b2)

    r /= 255
    g /= 255
    b /= 255
Exemplo n.º 29
0
def check_image(
    browser,
    clarifai_api_key,
    img_tags,
    img_tags_skip_if_contain,
    logger,
    clarifai_models,
    workflow,
    probability,
    full_match=False,
    check_video=False,
    proxy=None,
    picture_url=None,
):
    try:
        """Uses the link to the image to check for invalid content in the
        image.
        If a workflow has been selected, get list of tags from Clarifai API
        by checking link against models included in the workflow. If a workflow
        hasn't been provided, InstaPy will check images against given model(
        s)"""
        clarifai_api = ClarifaiApp(api_key=clarifai_api_key)
        clarifai_tags = []

        if proxy is not None:
            clarifai_api.api.session.proxies = {"https": proxy}
        # Set req image or video source URL to given one or get it from
        # current page
        if picture_url is None:
            source_link = get_source_link(browser)
        else:
            source_link = [picture_url]

        # No image in page
        if not source_link:
            return True, [], []

        # Check image using workflow if provided. If no workflow,
        # check image using model(s)
        if workflow:
            clarifai_workflow = Workflow(clarifai_api.api, workflow_id=workflow[0])
            # If source is video, checks keyframe against models as video
            # inputs not supported when using workflows
            if source_link[0].endswith("mp4"):
                clarifai_response = clarifai_workflow.predict_by_url(source_link[1])
            else:
                clarifai_response = clarifai_workflow.predict_by_url(source_link[0])

            for response in clarifai_response["results"][0]["outputs"]:
                results = get_clarifai_tags(response, probability)
                clarifai_tags.extend(results)
        else:
            for model in clarifai_models:
                clarifai_response = get_clarifai_response(
                    clarifai_api, model, source_link, check_video
                )
                results = get_clarifai_tags(
                    clarifai_response["outputs"][0], probability
                )
                clarifai_tags.extend(results)

        logger.info(
            "source_link {} got predicted result(s):\n{}".format(
                source_link, clarifai_tags
            )
        )

        # Will not comment on an image if any of the tags in
        # img_tags_skip_if_contain are matched
        if given_tags_in_result(img_tags_skip_if_contain, clarifai_tags):
            logger.info(
                'Not Commenting, image contains concept(s): "{}".'.format(
                    ", ".join(list(set(clarifai_tags) & set(img_tags_skip_if_contain)))
                )
            )
            return False, [], clarifai_tags

        for (tags, should_comment, comments) in img_tags:
            if should_comment and given_tags_in_result(tags, clarifai_tags, full_match):
                return True, comments, clarifai_tags
            elif given_tags_in_result(tags, clarifai_tags, full_match):
                logger.info(
                    'Not Commenting, image contains concept(s): "{}".'.format(
                        ", ".join(list(set(clarifai_tags) & set(tags)))
                    )
                )
                return False, [], clarifai_tags

        return True, [], clarifai_tags

    except Exception as err:
        logger.error("Image check error: {}".format(err))
Exemplo n.º 30
0
def test_bulk_create_image(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-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()

    # UserError should be thrown if a batch exceds 128 inputs
    large_set = [Image(image_id='@inputID1')] * 129
    with pytest.raises(UserError):
        app.inputs.bulk_create_images(large_set)

    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
        }
      }
    }
  ]
}
        """)