Esempio n. 1
0
def Upload(img_path, img_name):
    cred = credentials.Certificate(certificate_path)
    firebase_admin.initialize_app(
        cred, {'storageBucket': 'facerecognizationdata.appspot.com'})
    bucket = storage.bucket()

    with open(img_path, "rb") as image_file:
        image_data = base64.b64encode(image_file.read())
        bucket = storage.bucket()
        blob = bucket.blob(img_name + '.jpg')
        blob.upload_from_filename(img_path, content_type='image/jpg')
        print(blob.public_url)


##        blob = bucket.blob(img_name + '.jpg')
##        blob.upload_from_filename(
##            image_data,
##            content_type='image/jpg'
##        )
##        print(blob.public_url)

##if __name__ == '__main__':
##
##
##    img_path = '/'.join(os.path.realpath(__file__).replace('\\', '/').split('/')[:-1]) + '/2018_student.jpg'
##
##
##    img_name = '2018_student'
##
##    ImageUploading.Upload(img_path, img_name)
Esempio n. 2
0
def deleteVideo():
    data = request.get_json()
    video_id = data['video_id']
    token = data['idToken']
    decoded_token = auth.verify_id_token(token)
    user_uid = decoded_token['uid']
    print(video_id, user_uid)
    doc_ref = db.collection("users").document(user_uid).collection(
        "videos").document(video_id).get()
    print(doc_ref.to_dict())
    if doc_ref.exists:
        doc_ref = doc_ref.to_dict()
        imageExtension = doc_ref["thumbnail_type"]
        videoExtension = doc_ref['type']
        bucket = storage.bucket()
        blob = bucket.blob('images/' + video_id + imageExtension)
        blob.delete()
        bucket2 = storage.bucket()
        blob2 = bucket2.blob('videos/' + video_id + videoExtension)
        blob2.delete()
        db.collection("users").document(user_uid).collection(
            "videos").document(video_id).delete()
        return Response("OK", status=200, mimetype='application/json')
    else:
        print(doc_ref.id)
        print("!exists")
Esempio n. 3
0
def downloadFile(filename):
    print 'Downloading Video to temp file...'

    tempName = 'temporaryVideo.mp4'

    storage.bucket('mta-bus-view-originals').blob(
        filename).download_to_filename(tempName,
                                       client=None,
                                       start=None,
                                       end=None)

    print 'Download complete!'
    return tempName
Esempio n. 4
0
def route_upload_user_image(user_id: str, index: int):
    """Endpoint for uploading profile images."""
    user = User.objects.get_or_404(id=user_id)
    user.identify(request)

    image_file = request.files["user_image"]

    if not re.match(IMAGE_MIMETYPE_REGEX, image_file.mimetype):
        raise ValueError("The file is not an image type.")

    bucket = storage.bucket()
    file_name_to_save = "{0}_{1}_{2}".format(user.uid, index, uuid.uuid1())
    blob = bucket.blob("{0}/{1}/{2}".format(USER_IMAGE_FOLDER, user.uid, file_name_to_save))
    blob.upload_from_file(image_file)

    user_images_temp = user.user_images_temp
    current_image_at_index = next((x for x in user_images_temp if x.index == index), None)

    if not current_image_at_index:  # create new one
        user.user_images_temp.append(UserImage(index=index, url=blob.public_url))
    else:  # update existing one
        current_image_at_index.url = blob.public_url
        user.user_images_temp = sorted(user_images_temp, key=lambda x: x.index)
    user.status = User.Status.OPENED
    user.save()

    updated_image = next((x for x in user_images_temp if x.index == index), None)

    response = encode(updated_image.to_mongo())
    return Response(response, mimetype="application/json")
def download_blob(download=False):
    bucket = storage.bucket()
    blob = bucket.get_blob('surgery1.mp4')
    if download:
        with open("blob.mp4", "wb") as file_obj:
            blob.download_to_file(file_obj)
    return blob
Esempio n. 6
0
def create_blob(file_path):
    # Connect to bucket
    bucket = storage.bucket()

    # Create blob
    blob = bucket.blob(file_path)
    return blob
Esempio n. 7
0
    def _remove_image(self, filename):
        bucket = storage.bucket(app=self.app)
        blob = bucket.get_blob(filename)
        if blob is None:
            raise NotFoundError("Photo")

        blob.delete()
Esempio n. 8
0
    def downloadFileFromRepository(self, filename):
        bucket = storage.bucket("hyperledger-jte.appspot.com")

        blob = bucket.get_blob(filename)
        local_filename = filename.split(".")[0] + f"_{self.analyst_name}.txt"
        blob.download_to_filename(local_filename)
        os.rename(os.path.join(os.getcwd(), local_filename), os.path.join(self.analyst_path, filename))
def extract_features(args):
    model = load_model(args)
    model = model.cuda() if torch.cuda.is_available() else model
    model.eval()

    if not firebase_admin._apps:
        print('Initializing firebase app')
        cred = credentials.Certificate('firebase_key.json')
        firebase_admin.initialize_app(cred)
    bucket = storage.bucket('ssnap-411f1.appspot.com')

    blobs = []
    for i, blob in enumerate(bucket.list_blobs()):
        if 'Grade' in blob.path or '%EC%9D%BC%EB%B0%98' in blob.path:
            blobs.append(blob)

    wf = open(args.csv_path, 'w')
    with torch.no_grad():
        for i, blob in tqdm(enumerate(blobs), total=len(blobs)):
            try:
                blob.download_to_filename('./fb_extract_temp.jpg')
                image = read_image('./fb_extract_temp.jpg')
                image = image.cuda(non_blocking=True) if torch.cuda.is_available() else image

                _, features = model(image)

                wf.write('{},{}\n'.format(blob.id, ','.join([str(x) for x in features[0].cpu().data.numpy()])))
            except:
                print('Error [{}] {}'.format(i, blob))
                continue

    os.remove('./fb_extract_temp.jpg')
    wf.close()
Esempio n. 10
0
def homepage():
    if not checkLoggedIn():
        return redirect(url_for('login'))
    try:
        bucket = storage.bucket()
        blob = bucket.blob('hello.txt')
        outfile='./hello.txt'
        blob.upload_from_filename(outfile)
    except:
        print("ok")
    def displayAllData():
        user_refs = db.collection("available options")
        docs = user_refs.stream()
        options = [doc.to_dict() for doc in docs]
        ret_dict = {}

        for option in options:
            product = option['item']
            price = option['cash_price']
            place = option["\ufeffname"]
            popularity = option["popularity"]
            if place in ret_dict:
                ret_dict[place].append({product: [price, popularity]})
            else:
                ret_dict[place] = [{product: [price, popularity]}]
        return ret_dict
    display_dict = displayAllData()


    return render_template("buyer.html", options=display_dict)
Esempio n. 11
0
def verify(job: dict):

    '''
    Get the job, from the app id, download the user image and passport
    compare this information and make sure that they match for facial rec.
    Then, we need to check mrz and get info off of it. date of birth, 
    the expiry and stuff...............
    '''
    # Convert the byte strings to images


    bucket = storage.bucket(app=app)

    default_bucket = "userinf/{}/".format(job['AppID'])
    passport_image_blob = default_bucket + "passport"
    user_image_blob = default_bucket + "profile_picture"
    passport_image_blob = bucket.blob(passport_image_blob)
    user_image_blob = bucket.blob(user_image_blob)

    passport_bytes = passport_image_blob.download_as_string()
    profile_picture_bytes = user_image_blob.download_as_string()

    passport_image = Image.open(io.BytesIO(passport_bytes))
    user_image = Image.open(io.BytesIO(profile_picture_bytes))

    check_face_result = __check_face(passport_image, user_image)

    if(check_face_result[0]):
        # Passed the first check, verify the user's face matches their
        # passport now to verify date of biheaders = {'content-type': 'application/json'}rth and driving license number.
        return __verify_age(io.BytesIO(passport_bytes), job)            
    else:
        return check_face_result
Esempio n. 12
0
def deleteFile(blob_path):
    bucket = storage.bucket()
    fileDeleteBlob = bucket.blob(blob_path)
    try:
        fileDeleteBlob.delete()
    except Exception as e:
        print(e)
Esempio n. 13
0
    def fetch_channels(self):
        config = Config.get()
        bucket = storage.bucket("yada-comp451.appspot.com")

        channel_path = Path(channel_module_directory)
        if not channel_path.exists():
            channel_path.mkdir()

        for key in filter(lambda section: section.startswith("channel/"),
                          config.sections()):
            config.remove_section(key)

        for root, dirs, files in os.walk(channel_module_directory):
            for file in files:
                os.remove(os.path.join(root, file))

        template = self.template_snapshot.to_dict()
        for channel_name, filename in template["channels"].items():
            blob = bucket.blob(f"{PREFIX}{filename['script']}")
            blob.download_to_filename(
                f"{channel_module_directory}{channel_name}.py")

            config[f"channel/{channel_name}"] = {
                "module": filename['script'].replace(".py", "")
            }

        config["config"]["template_modified_date"] = template["modified"]
Esempio n. 14
0
    def __init__(self, private_key: str = "./certs/admin-key.json",
                 firebase_url: str = "https://spirobot-d9387.firebaseio.com/",
                 storage_bucket_url: str = "spirobot-d9387.appspot.com"):
        """
        Constructor for Firebase communications
        :param private_key: Private Key JSON file for Firebase
        :param firebase_url: URL of Firebase Instance
        :param storage_bucket_url: URL of Google Cloud Storage Instance.
        """

        firebase_admin.initialize_app(credentials.Certificate(private_key), {
            "databaseURL": firebase_url,
            "storageBucket": storage_bucket_url
        })
        self.root = db.reference("/")
        self.__verify_control_details()
        sleep(1)  # Allows Live DB to be refreshed and stops old commands from being loaded.
        self.__controls = db.reference("controls")
        self.__events = db.reference("events")
        self.__status = db.reference("status")
        self.__images = db.reference("images")
        self.__custom_moves = db.reference("custom_moves")
        self.__motion_data = db.reference("motion_data")
        self.__proximity_data = db.reference("proximity_data")
        self.__message_token = db.reference("token")
        self.__video_state = None
        self.communication_controls = {}
        self.__storage_bucket = storage.bucket()
Esempio n. 15
0
 def __init__(self):
     try:
         self.app = firebase_admin.initialize_app(Firebase_module.cred)
     except:
         pass
     self.db = firestore.client()
     self.bucket = storage.bucket('homefood-b7713.appspot.com')
    def __init__(self):
        try:
            cred_json = json.loads(os.getenv('FIREBASE_CREDENTIALS', None))
            cred_json['private_key'] = cred_json['private_key'].replace(
                '\\n', '\n')
            credential = credentials.Certificate(cred_json)
            app = firebase_admin.initialize_app(
                credential, {
                    'projectId': 'colorfightai-firebase',
                    'storageBucket': 'colorfightai-firebase.appspot.com',
                    'databaseURL':
                    'https://colorfightai-firebase.firebaseio.com'
                })

            self.executor = concurrent.futures.ThreadPoolExecutor(
                max_workers=15)

            self.bucket = storage.bucket()
            self.firestore = firestore.client()
            self.db = db

            self.leaderboard_duration = 7 * 24 * 3600
            self.valid = True

            self.timezone = datetime.timezone(datetime.timedelta(-1, 61200))

            schedule.every().hour.at(":00").do(
                self.sync_backup_leaderboard,
                tag="leaderboard_" + datetime.datetime.now(
                    tz=self.timezone).strftime("%y%m%d_%H%M"))
        except Exception as e:
            self.valid = False
            print(e)
            print(
                "Could not connect to firebase, other stuff should work fine")
Esempio n. 17
0
def upload():
    #initialize files
    outfile = None
    blob = None
    bucket = storage.bucket()

    #Name file by current time
    name = str(dt.datetime.now())

    #Picture to be sent to Firebase
    outfile = '/home/pi/Desktop/CameraSoftware/WhoDat.jpg'
    print("Sending Image to Firestore...")
    #Upload image blob
    blob = bucket.blob(settings.userID + '/images/' + name + '.jpg')
    blob.upload_from_filename(outfile)
    print("Image was uploaded to firestore!")

    #Video to be Sent to Firebase
    outfile = '/home/pi/Desktop/CameraSoftware/video.mp4'
    print("Sending Video to Firestore...")
    #Upload video blob
    blob = bucket.blob(settings.userID + '/videos/' + name + '.mp4')
    blob.upload_from_filename(outfile)
    print("Video was uploaded to firestore!")

    #Signal Database
    fireapp = firebase.FirebaseApplication('https://mspi-a4b75.firebaseio.com',
                                           None)
    fireapp.post('/signal', {'signal': 'Charrrrrlie'})
    print('DB has been signaled...')
Esempio n. 18
0
def generate_song():
    song_length = 100
    pitches, velocities = _get_sequence(song_length)
    _song_to_txt([pitches, velocities], song_length)
    _txt_to_mid()

    # Init firebase with your credentials
    file_name = newMidi_dir + song_id + '.mid'
    bucket = storage.bucket()
    blob = bucket.blob(file_name)
    blob.upload_from_filename(file_name)

    blob.make_public()

    song_obj = {
        'name': "Temporary name",
        'duration': str(song_length * .07),
        'song_id': song_id,
        'genres': "Classical"
    }
    url = 'Library/' + song_id
    res = fb.patch(url, song_obj)
    print(res)

    return song_id
Esempio n. 19
0
 def uploadima(self):
     from connection_status import connect
     if connect():
         from firebase_admin import credentials, initialize_app, storage
         import firebase_admin
         import pathlib
         if not firebase_admin._apps:
             cred = credentials.Certificate(
                 "farmzon-abdcb-c4c57249e43b.json")
             initialize_app(cred,
                            {'storageBucket': 'farmzon-abdcb.appspot.com'})
             # print(uploadima_app.name)
             list_food = [
                 "avocado.png", "pea.png", "carrot.png", "cucumber.png",
                 "capsicum.png", "onion.png", "clove.png"
             ]
             for i in range(list_food.__len__()):
                 fileName = "farmzon database/herbs/herbs/" + list_food[i]
                 bucket = storage.bucket()
                 suf = pathlib.Path(list_food[i]).suffix
                 name = self.rchop(list_food[i], ".png")
                 blob = bucket.blob("Categories_url/herbs/" + name.lower())
                 blob.upload_from_filename(fileName)
                 blob.make_public()
                 self.url = blob.public_url
                 print("your file url", self.url)
                 self.product_image = self.url
                 self.put_in_database(self.url, name.lower())
Esempio n. 20
0
    def addPictureToStorage(self, image):
        bucket = storage.bucket()
        blob = bucket.blob("Repairs/Test.png")
        blob.upload_from_string(image, content_type='image/png')
        blob.make_public()

        print(blob.public_url)
Esempio n. 21
0
def get_url(imagePath):
    bucket = storage.bucket()
    blob = bucket.blob(imagePath)
    blob.upload_from_filename(imagePath)
    blob.make_public()

    return blob.public_url
Esempio n. 22
0
def db_storage(ringsData, imgDirPath):
    cred = firebase_admin.credentials.Certificate("./firebase_key.json")
    firebase_admin.initialize_app(
        cred, {
            "databaseURL": "https://engagementringwebapp.firebaseio.com/",
            "storageBucket": "engagementringwebapp.appspot.com"
        })

    # to access the root level of the collection node
    root = db.reference()
    # delete "shops" node to wipe all previous data
    # shops might sell different rings already so better to wipe all old data
    root.child("shops").delete()
    # push new data obtained after recently web scrapping
    root.child("shops").push(ringsData)

    # upload all images to firebase storage
    bucket = storage.bucket()
    # delete all images in the firebase storage
    # shops might sell different rings already so better to wipe all old data
    bucket.delete_blobs(bucket.list_blobs())
    # get each image and upload it
    for file in os.listdir(imgDirPath):
        # set the destination name
        blob = bucket.blob(file)
        # set the source path
        blob.upload_from_filename(imgDirPath + "/" + file)
        # to make it available to annoymous users so our website can access without authentication
        blob.make_public()
        # e.g. https://storage.googleapis.com/engagementringwebapp.appspot.com/86.jpg
        # print(blob.public_url)

    print("Finished uploadeding to database...")
Esempio n. 23
0
    def upload(self, caminho, arquivo):
        try:
            ''' 
            screenshot = 'minha-colecao-a01d5.appspot.com'
            banco='minha-colecao-a01d5.appspot.com/Y2hyaXN0aWFuLmNvbGl2ZWlyYUBnbWFpbC5jb20=/bancodados'
            '''
            # Init firebase with your credentials
            try:
                cred = credentials.Certificate(
                    "minha-colecao-a01d5-firebase-adminsdk-ehm8b-b1a0aed377.json"
                )
                initialize_app(cred, {'storageBucket': caminho})
            except:
                pass

            # upload image
            fileName = arquivo
            bucket = storage.bucket()
            blob = bucket.blob(fileName)
            blob.upload_from_filename(fileName)

            # Opt : if you want to make public access from the URL
            blob.make_public()

            print("your file url", blob.public_url)

            # /Y2hyaXN0aWFuLmNvbGl2ZWlyYUBnbWFpbC5jb20=/bancodados
        except Exception as e:
            print(e)
Esempio n. 24
0
    def upload_image(self, image, image_cat):

        assert image_cat in ["profile_picture", "floor_plan"]
        if not allowed_file(image.filename, image_cat):
            return ("danger", "Error!", "file must have one of the following extensions: {}".format(", ".join(
                config.Config.ALLOWED_EXTENSIONS[image_cat])))
        if not allowed_image_filesize(request.cookies[image_cat + "_filesize"]):
            return ("danger", "Error!", "file size has exceeded maximum limit of 1Mb")

        filename = secure_filename(image.filename)

        bucket = storage.bucket("clamber-7fb70.appspot.com")
        firestore_file_name = f"{self.uid}_{image_cat}.{filename.rsplit('.')[-1].upper()}"
        blob = bucket.blob(firestore_file_name)
        temp = tempfile.NamedTemporaryFile(delete=False)
        image.save(temp.name)

        t = threading.Thread(target=lambda blob, r: blob.upload_from_file(r), name=firestore_file_name, args=(blob, temp))
        t.start()
        t.join()

        self.update_user({image_cat: firestore_file_name})
        # Clean-up temp images
        temp.close()
        os.remove(temp.name)

        return ("success", "Success!", "Profile picture has been successfully uploaded")
Esempio n. 25
0
def pictureFunc():

    GPIO.output(36, GPIO.LOW)
    time.sleep(0.3)
    GPIO.output(36, GPIO.HIGH)

    value = randint(0, 10000)

    vs.camera.capture('/home/pi/Desktop/randomCaptures_001/picture%s.jpg' %
                      value)

    #os.system("aplay /home/pi/Desktop/test.wav")

    # Put your local file path
    fileName = ('/home/pi/Desktop/randomCaptures_001/picture%s.jpg' % value)
    bucket = storage.bucket()
    blob = bucket.blob(fileName)
    blob.upload_from_filename(fileName)

    # Opt : if you want to make public access from the URL
    blob.make_public()

    #Adding data to firebase
    doc_ref = db.collection('testEntry').document('testDocument')

    doc_ref.set({'Datetime': today, 'ImageUrl1': blob.public_url})

    print("your file url", blob.public_url)
    print("Datetime: ", today)
Esempio n. 26
0
def success(): 
    path = "images/original/" 
    if request.method == 'POST':  
        f = request.files['file']
        ps = path+f.filename
        f.save(ps)
        fileName = f.filename
        bucket = storage.bucket()
        blob1 = bucket.blob(fileName)
        blob1.upload_from_filename(ps)
        blob1.make_public()
        l1 = blob1.public_url
        img = Image.open(ps)    
        
        # Compressing the image
        compname = "/compressed_"+f.filename
        blob2 = bucket.blob(compname)
        
        if(request.form['comp']==''):
            img.save('images/compressed'+compname,optimize=True,quality=30)
            blob2.upload_from_filename('images/compressed'+compname)
            blob2.make_public()
        else:
            img.save('images/compressed'+compname,optimize=True,quality=int(request.form['comp']))
            blob2.upload_from_filename('images/compressed'+compname)
            blob2.make_public()
        
        # Setting the links in firebase
        ref.set({"out_link":blob2.public_url,
                 "out_file_size":os.path.getsize('images/compressed'+compname),
                 "original_link":blob1.public_url,
                 "original_file_size":os.path.getsize(ps)}) 

        return redirect(blob2.public_url)  
Esempio n. 27
0
 def upload(self, model):
     bucket = storage.bucket()
     blob = bucket.blob('bus/' + str(model['timestamp']) + '.jpg')
     blob.upload_from_string(model['image'])
     blob.make_public()
     print(blob.public_url)
     return blob.public_url
Esempio n. 28
0
    def read_from_storage(self):

        print('pulling from store')
        bucket = storage.bucket()

        for blob in bucket.list_blobs():
            blob.download_to_filename(blob.name)
Esempio n. 29
0
def upload():
    if request.method == 'POST':
        db = MySQLdb.connect("伺服器", "帳號", "密碼", "schema", charset='utf8')
        cursor = db.cursor()
        psort = request.form.get('psort')
        pname = request.form.get('pname')
        pmoney = request.form.get('pmoney')
        file = request.files['pimg']
        filename = file.filename     # 圖片檔名
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        # 圖片上傳到 firebase Storage:先去firebase建立anysell資料夾
        bucket = storage.bucket(app=app01)
        blob = bucket.blob('anysell/'+filename)
        blob.upload_from_filename(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        blob.make_public()
        fbimg = blob.public_url
        pstorage = fbimg
        sql = 'INSERT INTO product(psort, pname, pmoney, pimg, pstorage) VALUES ("%s", "%s", "%s", "%s", "%s")' % (psort, pname, pmoney, filename, pstorage)
        try:
            cursor.execute(sql)
            db.commit()
        except:
            db.rollback()
        db.close()                       
        return render_template('upload.html', okk='thanks')
    else:
        return render_template('upload.html')
Esempio n. 30
0
def send_json_to_database(filename):
    cred = credentials.Certificate(
        '/root/mycovidtracker/mycovidtracker/service.json')
    initialized = firebase_admin._apps

    if not initialized:
        initialize_app(cred,
                       {'storageBucket': 'mycovidtracker-5e186.appspot.com'})

    bucket = storage.bucket('mycovidtracker-5e186.appspot.com'
                            ) if initialized else storage.bucket()
    blob = bucket.blob(filename)
    blob.upload_from_filename(filename)
    blob.make_public()

    return