Exemplo n.º 1
0
    def find_meme(self, meme):
        sightclient = SightengineClient("1347331372", "BhoFasNuF3zAGp8XSRXi")

        try:
            height = int(meme)
            # meme represents height
            rawdata_meme = getJSON("%s/getmemedatabyheight/%s" %
                                   (self.api_root, meme))['result']
            result = dict(rawdata_meme, **{'meme_identifier': height})

        except ValueError as e:
            # meme represents ipfsid
            rawdata_meme = getJSON("%s/getmemedatabyhash/%s" %
                                   (self.api_root, meme))['result']
            result = dict(rawdata_meme,
                          **{'meme_identifier': rawdata_meme['hashlink']})

        try:
            sight_output = sightclient.check('nudity').set_url(
                'https://ipfs.io/ipfs/%s' % rawdata_meme['ipfs_id'])

            if sight_output['nudity']['safe'] > 0.5:
                return result
            else:
                return None

        except KeyError as e:
            return result
Exemplo n.º 2
0
def getOutput(my_url_list):
    global client, all_creds, current_cred
    output_list = []
    for my_url in my_url_list:
        if current_cred >= len(all_creds):
            current_cred = 0
            raise Exception(
                'You have reached the daily limit of 1500 requests!')
            break
        result = client.check('wad').set_url(my_url)
        while result['status'] != 'success':
            if current_cred >= len(all_creds):  # if last credential reached
                current_cred = 0
                raise Exception('API keys exhausted.')
                break
            current_cred += 1
            client = SightengineClient(all_creds[current_cred][0],
                                       all_creds[current_cred][1])
            result = client.check('wad').set_url(my_url)
            print('Using credentials ' + all_creds[current_cred][0] + ', ' +
                  all_creds[current_cred][1])
            print(result)
        print(result)
        output_list.append(result)
    for output in output_list:
        print(output)
    return output_list
Exemplo n.º 3
0
 def check_safety(input_url):
     client = SightengineClient('265033791', 'E8KsSkGNjT4Em8aaCUpF')
     checkNudity = client.check('nudity')
     output1 = checkNudity.set_url(input_url)
     safety_level = output1['nudity']['safe']
     if safety_level < 0.5:
         return 1
     else:
         return 0
Exemplo n.º 4
0
def process_file():

    if not current_user.is_authenticated:
        flash('Only authenticated users can upload or delete images')
        return redirect(url_for('images'))

    if len(list(request.form.keys())) > 0 and request.form["delete"]:
        output = delete_file_from_s3(app.config["S3_BUCKET"],
                                     request.form["delete"])
        models.Appimage.query.filter_by(URL=request.form["delete"]).delete()
        db.session.commit()
        return redirect(url_for('images'))

    file = request.files["user_file"]

    if file.filename and allowed_file(file.filename):
        file.filename = secure_filename(file.filename)
        output = upload_file_to_s3(file, app.config["S3_BUCKET"])

        client = SightengineClient('1959849289', 'Wm9a6r2E8SnF7oBfNJUW')
        output2 = client.check('nudity', 'wad', 'celebrities',
                               'scam').set_url(app.config["S3_LOCATION"] +
                                               '/' + file.filename)

        #Get the probability that the face belongs to said celebrity
        celeProb = 0
        for face in output2["faces"]:
            celebrities = face.get("celebrity")

            for cele in celebrities:
                if (celeProb < cele.get("prob")):
                    celeProb = cele.get("prob")

        #Nudity check: probability that the image does not contain nudity
        #Celebrity check: Probability that the face belongs to said celebrity
        #Weapon check: Probability that the image contains weapons
        #Scammer check: Probability that there is a scammer on the image
        if (float(output2["nudity"]["safe"]) < 0.5 or celeProb > 0.8
                or float(output2["weapon"]) > 0.4
                or float(output2["scam"]["prob"]) > 0.3):
            delete_file_from_s3(app.config["S3_BUCKET"], file.filename)
            flash('Image denied')
            #flash(float(output2["nudity"]["safe"]))
            #flash(celeProb)
            #flash(float(output2["weapon"]))
            #flash(float(output2["scam"]["prob"]))
        else:
            user = models.Appuser.query.filter_by(
                email=current_user.get_id()).first()
            i = models.Appimage(appuser_id=user.get_id(), URL=file.filename)
            db.session.add(i)
            db.session.commit()

        return redirect(url_for('images'))

    else:
        return redirect(url_for('images'))
Exemplo n.º 5
0
def get_celebs(url):
    client = SightengineClient(local_settings.SIGHTENGINE_USER, local_settings.SIGHTENGINE_KEY)
    output = client.check('celebrities').set_url({url})
    # Returns names and probabilities
    results = output["faces"][0]["celebrity"]

    return results

    # for celeb in results:
    #     return ("Name:", celeb["name"], "Probability:", celeb["prob"])
Exemplo n.º 6
0
class SightEngineParser():
    def load_apis(self):
        with open('api_keys.json') as f:
            self.api_keys = json.load(f)

    def initialize_client(self):
        self.load_apis()
        self.client = SightengineClient(self.api_keys['SIGHTENGINE_API_ID'], self.api_keys['SIGHTENGINE_API_KEY'])

    def fetch_results(self, filepath):
        try:
            return self.client.check('nudity', 'type', 'properties', 'wad', 'face').set_file(filepath)
        except:
            return None
Exemplo n.º 7
0
def upload_file():
    file = flask.request.files['image']
    fpath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
    ext = file.filename.split('.')[-1]

    file_read = file.read()

    if ext in ALLOWED_EXT:
        try:
            sightclient = SightengineClient("1347331372",
                                            "BhoFasNuF3zAGp8XSRXi")

            sight_output = sightclient.check('nudity').set_bytes(file_read)

            if sight_output['nudity']['safe'] > 0.5:
                if ext == 'jpg':
                    ext = 'jpeg'
                headers = {'Content-Type': 'image/%s' % ext.lower()}

                req = requests.post("http://95.179.132.93:1337/api/addmeme",
                                    data=file_read,
                                    stream=True,
                                    headers=headers)
                json_response = req.json()

                try:
                    if json_response['success'] == True:
                        return flask.render_template('upload-success.html')

                except KeyError as e:
                    error_msg = json_response['description']
                    return flask.render_template('upload-failed.html',
                                                 error_msg=error_msg)

            else:
                error_msg = "Meme image has not passed profanity filter. Please do not upload offensive materials."
                return flask.render_template('upload-failed.html',
                                             error_msg=error_msg)

        except KeyError as e:
            error_msg = "Profanity filter max API call limit reached."
            return flask.render_template('upload-failed.html',
                                         error_msg=error_msg)

    else:
        error_msg = "Meme file extension not supported."
        return flask.render_template('upload-failed.html', error_msg=error_msg)
Exemplo n.º 8
0
def check_sightengine_properties(path):
    """
    Check some image properties offered by the sigthengine API
    (https://sightengine.com/) including:
    - Nudity Detection
    - Weapons, Alcohol, Drug detection
    - Offensive Signs an Gesture detection
    - Minors detection
    - Image Quality detection
    - Sunglasses detection
    """

    #client = SightengineClient('1519637001','knEJCk3vyKorBydqMPek')
    client = SightengineClient('250594697', '54GphLZgSBoenkVfXMPX')
    output = client.check('nudity', 'wad', 'properties', 'offensive', 'scam',
                          'text-content', 'face-attributes',
                          'text').set_file(os.path.abspath(path))

    # Adjust the dictionary to our requirements
    del output['status']
    del output['request']
    del output['colors']
    del output['media']
    del output['text']

    # 0 = Low, 1 = High
    output['scam'] = 1 if output['scam']['prob'] > 0.75 else 0
    print(output["nudity"])
    output['nudity'] = 1 if output['nudity']['partial'] > 0.85 else 0
    output[
        'minor'] = 1 if output['faces'][0]['attributes']['minor'] > 0.75 else 0
    output['sunglasses'] = 1 if output['faces'][0]['attributes'][
        'sunglasses'] > 0.75 else 0
    output['offensive'] = 1 if output['offensive']['prob'] > 0.75 else 0
    output['sharpness'] = 1 if output['sharpness'] > 0.75 else 0
    output['weapon'] = 1 if output['weapon'] > 0.75 else 0
    output['alcohol'] = 1 if output['alcohol'] > 0.75 else 0
    output['drugs'] = 1 if output['drugs'] > 0.75 else 0

    # 0 = OK, 1 = High, 2 = Low
    output['contrast'] = 1 if output[
        'contrast'] > 0.85 else 2 if output['contrast'] < 0.15 else 0
    output['brightness'] = 1 if output[
        'brightness'] > 0.85 else 2 if output['brightness'] < 0.15 else 0
    del output['faces']

    return output
Exemplo n.º 9
0
    def test_nudityModel(self):
        client = SightengineClient('1234', 'test')
        checkNudity = client.check('nudity')

        image = os.path.join(os.path.dirname(__file__), 'assets', 'image.jpg')

        output = checkNudity.set_url('https://sightengine.com/assets/img/examples/example5.jpg')
        self.assertEqual('success', output['status'])

        output2 = checkNudity.set_file(image)
        self.assertEqual('success', output2['status'])

        with open(image, mode='rb') as img:
            binary_image = img.read()

        output3 = checkNudity.set_bytes(binary_image)
        self.assertEqual('success', output3['status'])
Exemplo n.º 10
0
def check_image(pic):
    pic = os.path.join(current_app.root_path, 'static/profile_pics', pic)
    picsamp = pic.replace('\\', '/')
    client = SightengineClient('82714170', 'RT4oo9fZFDbNsrvV6VSp')

    output = client.check('nudity', 'wad', 'celebrities', 'scam',
                          'face-attributes').set_file(picsamp)
    invalidImage = False
    # contains nudity
    if output['nudity']['safe'] <= output['nudity']['partial'] and output[
            'nudity']['safe'] <= output['nudity']['raw']:
        invalidImage = True

    n = Nude(picsamp)
    n.parse()

    print(n.result, n.message)

    return invalidImage
    def get_frame(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        # instead.
        
        
        self.video = cv2.VideoCapture(0)

        img_counter = 0
        
        while True:
            ret, frame = self.video.read()
            #cv2.imshow("test", frame)
            if not ret:
                break
            k = cv2.waitKey(1)
    
            if k%256 == 27:
        # ESC pressed
                print("Escape hit, closing...")
                break
            elif keyboard.is_pressed('space'):
        # SPACE pressed
                img_name = "opencv_frame_{}.png".format(img_counter)
                cv2.imwrite(img_name, frame)
                print("{} written!".format(img_name))

                client = SightengineClient('523702522', 'SoMh4T2mBCTB848RmhqS')
                output = client.check('celebrities').set_file('/Users/jeffrosal1/Desktop/NUhomework/project3/combined/flasktest/opencv_frame_0.png')
                print(output)
                set_api_key("i0bqh0wRTlMqHMTHXZPxXFumRAcETw698GaIqBN9vuM")

# when sending a image file

                path = "/Users/jeffrosal1/Desktop/NUhomework/project3/combined/flasktest/opencv_frame_0.png"
                emoout = paralleldots.facial_emotion(path)         
                print(emoout)
            rete, jpeg = cv2.imencode('.jpg', frame)
            return jpeg.tobytes()
Exemplo n.º 12
0
 def main():
     # 我使用的是 SightengineApi(“用戶api”,“秘密api”):
     client = SightengineClient('1069852127', 'tLNDZxAArCRND5p8qt7A')
     # 特別整數:
     theSpecialInteger = 18
     # 獲取用戶輸入:
     dataLocation = input("Please input the data:  \n")
     # 打開用戶輸入數據
     __image = Image.open(dataLocation)
     # 使用 Numpy 將圖像轉換為數組
     np__image = np.array(__image)
     # 打印出數組的結果
     print("Converted Image to Array ", np__image)
     # 得到十八和以前結果的差別
     np__image = np__image - theSpecialInteger
     # 從數組創建新圖像
     new_image = Image.fromarray(np__image)
     # 保存圖片
     #new_image.save("output.png")
     # 聲明 SightengineApi 檢測功能
     output = client.check("nudity", "wad", "offensive", "faces",
                           "face-attributes",
                           "celebrities").set_file(dataLocation)
     # 將輸出和結果打印為 <<json>> 格式
     print(json.dumps(output, indent=6, sort_keys=True))
     # 基於操作系統打開圖像或視頻
     computer_platform = p.system()
     if computer_platform == "Windows":
         __image.show()
         print("以下图像是明确的并且不合适的")
     elif computer_platform == "Darwin":
         __image.show()
         print("以下图像是明确的并且不合适的")
     elif computer_platform == "Linux":
         __image.show()
         print("以下图像是明确的并且不合适的")
     else:
         print("can't open image")
Exemplo n.º 13
0
def process_image():
    """Convert and analyze image, add to DB"""
    privacy = request.form["privacy"]
    img = request.files["img_file"]

    # Define path and save image to local directory
    img_path = UPLOAD_FOLDER + img.filename
    img.save(img_path)

    #SightEngine check image for nudity/weapons/drugs
    client = SightengineClient('860162422', 'eFiRDeywSC9mCCjXse5q')
    output = client.check('nudity','wad').set_file(img_path)
    print(output)
    if output['weapon'] > 0.8:
        message = "Weapons detected, please upload a different image."
        print("NO WEAPONS")
        return jsonify({'error_message': message})

    elif output['alcohol'] > 0.8:
        message = "Drugs or alcohol detected, please upload a different image."
        print("NO ALCOHOLS")
        return jsonify({'error_message': message})

    elif output['nudity']['raw'] > 0.5:
        message = "Nudity detected, please upload a different image."
        print("NO NAKEY PICS")
        return jsonify({'error_message': message})

    else:
        # Convert image and analyze, redirect to homepage
        upload = convert_resize_image(img_path, privacy)
        img_id = upload.img_id
        img_url = upload.img_url
        results = {"id": img_id, "url": img_url}
        pillow_analyze_image(img_path)
        # Return results
        return jsonify(results)
Exemplo n.º 14
0
    def find(self, limit=100, start=0, memechain_height=0):
        sightclient = SightengineClient("1347331372", "BhoFasNuF3zAGp8XSRXi")
        timeline = []

        for ident in range(start, start + limit):
            meme_height = memechain_height - ident
            rawdata_meme = getJSON("%s/getmemedatabyheight/%s" %
                                   (self.api_root, str(meme_height)))['result']

            sight_output = sightclient.check('nudity').set_url(
                'https://ipfs.io/ipfs/%s' % rawdata_meme['ipfs_id'])

            try:
                if sight_output['nudity']['safe'] > 0.5:
                    timeline.append(
                        dict(rawdata_meme, **{'meme_height': meme_height}))
                else:
                    pass

            except KeyError as e:
                timeline.append(
                    dict(rawdata_meme, **{'meme_height': meme_height}))

        return timeline