Exemplo n.º 1
0
def handle_images():
        body = request.json
        # image = CloudinaryImage("https://res.cloudinary.com/cormineco/image/upload/v1618091325/cormineco/residuos_waru5q.jpg").image(type="fetch")
        
        if body is None:
            return jsonify({
                "result" : "missing request body"

            }), 400

        if "folder" not in body:
            return jsonify({
                "result": "missing fields in request body"
            }), 400

        if "folder" in body:
            if body["folder"] == "inicio":
                result = cloudinary.Search().expression('folder:"inicio"').max_results('10').execute()
                resources = result["resources"]
                response = []
                for image in resources:
                    response.append({"image_url": image["url"], "name": image["filename"]})
                    
                return jsonify(response), 200
            if body["folder"] == "cormineco":
                result = cloudinary.Search().expression('folder:"cormineco"').max_results('10').execute()
                resources = result["resources"]
                response = []
                for image in resources:
                    response.append({"image_url": image["url"], "name": image["filename"]})
                    
                return jsonify(response), 200
            if body["folder"] == "compromiso":
                result = cloudinary.Search().expression('folder:"compromiso"').max_results('10').execute()
                resources = result["resources"]
                response = []
                for image in resources:
                    response.append({"image_url": image["url"], "name": image["filename"]})
                    
                return jsonify(response), 200
            if body["folder"] == "alcance":
                result = cloudinary.Search().expression('folder:"alcance"').max_results('10').execute()
                resources = result["resources"]
                response = []
                for image in resources:
                    response.append({"image_url": image["url"], "name": image["filename"]})
                    
                return jsonify(response), 200
            if body["folder"] == "contacto":
                result = cloudinary.Search().expression('folder:"contacto"').max_results('10').execute()
                resources = result["resources"]
                response = []
                for image in resources:
                    response.append({"image_url": image["url"], "name": image["filename"]})
                    
                return jsonify(response), 200
        return jsonify({
            "result" : "missing fields in request body folder"
        }), 400
Exemplo n.º 2
0
def tag_search(request):
    context = {}
    if request.method == 'POST':
        search_query = request.POST["tagsearch"]
        search = 'resource_type:image AND tags=' + search_query

        result = cloudinary.Search() \
                .expression(search) \
                .with_field('tags') \
                .max_results('10') \
                .execute()

        images = []

        if result and 'resources' in result:
            for img in result["resources"]:
                images.append(img["url"])

        context['search_query'] = search_query
        context['images'] = images
        context['search_result'] = result

        return render(request, 'tagged_pictures.html', context)

    return render(request, 'tagsearch.html')
Exemplo n.º 3
0
def upload_image_to_cloudinary(file, tags):
    file.seek(0)

    result = cloudinary.uploader.upload(file,
                                        use_filename=True,
                                        tags=tags,
                                        folder=settings.UPLOAD_FOLDER)

    #etag is unique identifier for picture
    etag = result.get('etag', None)
    try:
        # if it is the first time we uploaded image onto database, then we will rename public_ic with etag
        result = cloudinary.uploader.rename(result.get('public_id'), etag)
    except:
        # Exception will occur when same image is posted twice
        # Thus we will delete the uploaded image in the database
        cloudinary.api.delete_resources([result.get('public_id', None)])

    query = 'resource_type:image AND public_id='
    # We need to ensure that the database gets populated with the original photo, not the photo that was originally posted
    # This is because photo originally posted was deleted
    search_query = cloudinary.Search() \
            .expression(query + etag) \
            .execute()
    if (len(search_query["resources"]) > 0):
        search_query['url'] = search_query["resources"][0]['url']
        search_query['public_id'] = search_query["resources"][0]['public_id']
        search_query['etag'] = result['etag']
        return search_query
    else:
        return result
Exemplo n.º 4
0
def pliki():
    images = []
    try:
        result = cloudinary.Search().expression('folder:twojkomputerowiec AND resource_type:image').with_field('context').execute()
    except:
        result = None
    if result:
        for resource in result['resources']:
            url = resource.get("url")
            id = resource.get("public_id")
            id = id.replace(Konfiguracja.STORAGE_FOLDER + '/', '')
            title = None
            if resource.get("context"):
                title = resource.get("context").get('caption')
            images.append({'url': url, 'title': title, 'id': id})
    videos = []
    try:
        result = cloudinary.Search().expression('folder:twojkomputerowiec AND resource_type:video').with_field('context').execute()
    except:
        result = None
    if result:
        for resource in result['resources']:
            url = resource.get("url")
            id = resource.get("public_id")
            id = id.replace(Konfiguracja.STORAGE_FOLDER + '/', '')
            title = None
            if resource.get("context"):
                title = resource.get("context").get('caption')
            videos.append({'url': url, 'title': title, 'id': id})
    files = []
    try:
        result = cloudinary.Search().expression('folder:twojkomputerowiec AND resource_type:raw').with_field('context').execute()
    except:
        result = None
    if result:
        for resource in result['resources']:
            url = resource.get("url")
            id = resource.get("public_id")
            id = id.replace(Konfiguracja.STORAGE_FOLDER + '/', '')
            title = None
            if resource.get("context"):
                title = resource.get("context").get('caption')
            files.append({'url': url, 'title': title, 'id': id})
    return render_template('pliki.html', images=images, videos=videos, files=files, admin=Konfiguracja.MAIL_USERNAME)
Exemplo n.º 5
0
 def test_post_same_image_with_different_name(self):
     client = Client()
     with open(TEST_IMAGES_DIR + "/image5.jpg",
               "rb") as file1, open(TEST_IMAGES_DIR + "/same_as_image5.jpg",
                                    "rb") as file2:
         response = client.post(reverse('classify'),
                                {'file': [file1, file2]})
     query = 'resource_type:image AND public_id=' + 'a2324d47504d07607aaae43d7be708c0'
     search_query_result = cloudinary.Search().expression(query).execute()
     print(search_query_result["total_count"])
     self.assertEqual(search_query_result["total_count"], 1)
Exemplo n.º 6
0
def helper_search_cld_type(key, resource_type, cld_public_id):
    """
    Calculate mandatory cld properties that identifies the object mapping
    """
    cld_type = "upload"
    file_not_found = True
    result = cloudinary.Search().expression(
        "resource_type:" + resource_type + " AND public_id=" + cld_public_id) \
        .max_results('1') \
        .execute()
    file_not_found = True
    if "resources" in result and len(result['resources']) == 1 and result['resources'][0]['public_id'] == cld_public_id:
            cld_type = result["resources"][0]["type"]
            file_not_found = False
    return cld_type, file_not_found
def inbound_parse_manifest():
    payload = request.json
    #reset metadata_string
    metadata_list = []
    metadata_string = ''
    metadata_tree = cloudinary.api.list_metadata_fields()
    if (payload['public_id'].split('.')[1]).lower() == 'csv':
        payload['action'] = 'incoming hook for csv parsing'
        print(json.dumps(request.json))
        #get the file
        with requests.Session() as s:
            download = s.get(payload['secure_url'])
            decoded_content = download.content.decode('utf-8')
            cr = csv.DictReader(decoded_content.splitlines(), delimiter=',')

            #parse the file and make the cahnges by each line of it
            #header format should be as following
            #FILENAME,FIELD_EXT_ID1,FIELD_EXT_ID2
            #file.jpg,field_value1,field_value2

            for row in cr:
                metadata_list = []
                for k, v in row.items():
                    if k != 'FILENAME':
                        metadata_item = ''
                        metadata_item = generate_meta_string(
                            k, v, metadata_tree)
                        if metadata_item:
                            metadata_list.append(metadata_item)
                metadata_string = '|'.join(metadata_list)

                #search for the assets to get it's public_id
                search_results = cloudinary.Search().expression(
                    'filename=' + Path(str(row['FILENAME'])).stem +
                    '*').execute()

                #call upon a function to update the metadata
                meta_result = cloudinary.uploader.update_metadata(
                    metadata_string,
                    search_results['resources'][0]['public_id'])
                meta_result['action'] = 'metadata update by csv'
                meta_result['metadata_string'] = metadata_string
                meta_result['metadata_list'] = metadata_list
                meta_result['search_results'] = search_results
                print(json.dumps(meta_result))
        return "OK"
    else:
        return "OK"
                      api_key="311767175853995",
                      api_secret="M_ApqE5rBoqTHpY94c9exAVmn0M")

#uploading files
"""
import cloudinary.uploader
result = cloudinary.uploader.upload("./cloudinaryClient.py", folder="twojkomputerowiec", resource_type="raw",
                                    context="alt=my description|caption=my title")
print(result.get("url"))
print("#######################")
"""

#listing files
try:
    result = cloudinary.Search().expression(
        'folder:twojkomputerowiec AND resource_type:raw').with_field(
            'context').execute()
except:
    result = None
if result:
    for resource in result['resources']:
        print(resource.get("url"))
        if resource.get("context"):
            title = resource.get("context").get('caption')
            print(title)
        print("=======================")
print("#######################")

#listing images
try:
    result = cloudinary.Search().expression(
Exemplo n.º 9
0
def converter(request):           
    result = cloudinary.Search().expression('resource_type:video').sort_by('public_id','desc').execute()    
    file_list=[]
    for x in result["resources"]:        
        if x["filename"]==gma():
            file_list.append(x["url"])                     
                    
    # check file                
    exte_str=file_list[0][-3]+file_list[0][-2]+file_list[0][-1]
    
    if exte_str=="mp3":        
        url_file=file_list[0]        
        path_file="./speech.mp3"    

        response = requests.get(url_file)     # get the response of the url
        with open(path_file, 'wb') as file:   # create the file
            file.write(response.content) # write response contents to the file

        str_url = str(path_file)

        file_x_mp3=str_url
        sound_x_mp3 = AudioSegment.from_mp3(file_x_mp3)
        cut_name1=str_url[0:(len(str_url)-4)]
        sound_x_mp3.export(cut_name1+".wav", format="wav")

        sound_mp3=cut_name1+".wav"

        # listening to audio
        ls_mp3=sr.Recognizer()

        client_id=settings.CLIENT_ID
        client_key=settings.CLIENT_KEY

        with sr.AudioFile(sound_mp3) as source:
            ls_mp3.adjust_for_ambient_noise(source)                      
            audio_mp3 = ls_mp3.record(source)          
            try:
                text_mp3=ls_mp3.recognize_houndify((audio_mp3),client_id,client_key)                                                    
            except Exception:
                messages.info(request,"Could Not Read You File!")
                return redirect("home")                
        
        messages.info(request, 'Successfully did magic for you. Scroll down to see it!')        
        return render(request,'index.html',{"text":text_mp3})           

    elif exte_str=="wav":
        url_file_x=file_list[0]        
        path_file_x="./speech.wav"    

        response = requests.get(url_file_x)     # get the response of the url
        with open(path_file_x, 'wb') as file:   # create the file
            file.write(response.content) # write response contents to the file

        str_url_x = str(path_file_x)

        file_wav=str_url_x
        sound_x_wav = AudioSegment.from_wav(file_wav)
        sound_x_wav = sound_x_wav.set_channels(1)
        sound_x_wav.export(file_wav, format="wav")            
        sound_wav=str_url_x
        
        # listening to audio
        ls_wav=sr.Recognizer()

        with sr.AudioFile(sound_wav) as source_wav:
            ls_wav.adjust_for_ambient_noise(source_wav)
                
            audio_wav = ls_wav.record(source_wav)          
            try:                    
                text_wav=ls_wav.recognize_google(audio_wav)                    
            except Exception:
                messages.info(request,"Could Not Read You File!")
                return redirect("home")                

        messages.info(request, 'Successfully did magic for you. Scroll down to see it!')                                    
        return render(request,'index.html',{"text":text_wav})                   
        
    else:            
        messages.info(request, 'Bad News! We only accept audio files!.')
        return redirect("home")         
Exemplo n.º 10
0
def last_handler(event):
    line_bot_api.reply_message(event.reply_token, [
        TextSendMessage(
            text='Pesanan kamu sudah di konfirmasi dan akan segera kami proses'
        ),
        TextSendMessage(
            text=
            'kamu akan mendapat konfirmasi maksimal 1x24 jam dari email yang kamu cantumkan'
        ),
        StickerSendMessage(package_id=11537, sticker_id=52002759)
    ])

    ext = 'jpg'
    message_content = line_bot_api.get_message_content(event.message.id)
    with tempfile.NamedTemporaryFile(dir=static_tmp_path,
                                     prefix=ext + '-',
                                     delete=False) as tf:
        for chunk in message_content.iter_content():
            tf.write(chunk)
        tempfile_path = tf.name

    dist_path = tempfile_path + '.' + ext
    dist_name = os.path.basename(dist_path)
    os.rename(tempfile_path, dist_path)

    cloudinary.uploader.upload(request.host_url +
                               os.path.join('static', 'tmp', dist_name),
                               public_id=dist_name[4:])
    search_ord = 'public_id=' + dist_name[4:]
    search_cloud = cloudinary.Search().expression(search_ord).execute()
    print(search_cloud)
    json_tmp = json.dumps(search_cloud)
    print(json_tmp)
    json_tmp1 = json_tmp.split(",")
    print(json_tmp1)
    json_tmp2 = json_tmp1[18]
    print(json_tmp2)
    json_tmp3 = json_tmp2[16:-1]
    print(json_tmp3)

    # print(json_response)
    # print(json_response['resources'][0])

    # resources = json_response['resources'][0]

    nata_id = event.source.user_id
    profile = line_bot_api.get_profile(nata_id)
    tmp_user = user_generator(nata_id, profile.display_name)
    tmp_arr = []
    for i in tmp_user.user_events:
        tmp_arr.append(i)
    new_cart = cart(cart_id=str(nata_id),
                    cart_name=tmp_user.user_name,
                    cart_email=tmp_user.user_email,
                    cart_date=tmp_user.user_date,
                    cart_events=tmp_arr,
                    cart_image_link=json_tmp3)

    tmp_user.user_name = ""
    tmp_user.user_email = ""
    tmp_user.user_date = ""
    tmp_user.user_events = []
    tmp_user.cart_image_link = ""

    db.session.add(new_cart)
    db.session.commit()
Exemplo n.º 11
0
def search_file(expr):
    return cloudinary.Search().expression(expr).sort_by('public_id',
                                                        'desc').execute()
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 29 00:05:37 2019
@author: anubhav singh
Get urls of images inside a folder in cloudinary storage
"""

import urllib.request as req
import cloudinary
import cv2

cloudinary.config(cloud_name='YOUR-CLOUD-NAME',
                  api_key='YOUR-CLOUDINARY-API-KEY',
                  api_secret='YOUR-CLOUDINARY-API-SECRET-KEY')

for i in cloudinary.Search().expression(
        "folder:your_folder_name").execute()['resources']:
    image_url = cloudinary.CloudinaryImage(i['url']).build_url()
    image_ext = image_url.split('/')[8].split('.')[1]
    req.urlretrieve(image_url, "filename" + image_ext)
    img = cv2.imread('filename.jpg')
    # other logics for image manifpulation