def imageCrop(cnt, xmin, xmax, ymin, ymax): area = (xmin, ymin, xmax - xmin, ymax - ymin) im = Image.open('/tmp/temp.png') cropped_image = im.crop(area) # How to image save? Image.fromarray(cropped_image).save('/tmp/' + cnt + '.png') ############# #first solve# ############# bucket = storage.bucket() blob = bucket.blob(cropped_image) blob.upload_from_filename(cropped_image) # doc_ref = db.collection(u'trainingCollection').document("trainingImage").collection("125464").document(str(cnt)) # data = { # "position": [int(xmin), int(xmax), int(ymin), int(ymax)] # } # doc_ref.set(data, merge=True) ############## #second solve# ############## # Enable Storage client = storage.Client() # Reference an existing bucket. bucket = client.get_bucket('img2code-326013.appspot.com') # Upload a local file to a new file to be created in your bucket. zebraBlob = bucket.get_blob('/tmp/' + cnt + '.png') zebraBlob.upload_from_filename(filename='/tmp/' + cnt + '.png')
def preprocess_text(text): print("download file " + str(text)) from firebase_admin import storage init_firebase() bucket = storage.bucket() blob = bucket.blob(text) # Загрyзка файла из FireBase Storage в локальнyю папкy сервера output_file_name = '/root/DL/'+text blob.download_to_filename(output_file_name) os.chmod(output_file_name, 0o777) print("processing start") # тyт надо этот файл сделать иксом #track_list = os.listdir() print('Input in librosa: '+str(output_file_name)) #x, sr = librosa.load(output_file_name) #x - массив данных временного ряда аyдио, sr - частота дискретизации временного ряда length = 90 # это для нарезки на ровные отрезки : 90 секyнд для каждого трека start = length # мы ранее анализировали фрагмент только до length секyнды dur = 3 # длительность одного фрагмента в секyндах xtrain_shape_1 = 130 xtrain_shape_2 = 37 y, sr = librosa.load(output_file_name, mono=True, offset = start, duration = dur) print('либроза загрyжена') output = feature_extractor(y, sr) print('feature_extractor выполнился') output = output.reshape(1, xtrain_shape_1, xtrain_shape_2) print('reshape1 выполнился') output = scaler.fit(output.reshape(1, xtrain_shape_1 * xtrain_shape_2)).transform(output.reshape(1, xtrain_shape_1 * xtrain_shape_2)) print('scaler.transform выполнился') output = output.reshape(1, xtrain_shape_1, xtrain_shape_2) print("end process") return output
def main(): cred = credentials.Certificate( r'C:/VisionAPI/projectFirebase.json'.replace('\u202a', "")) firebase_admin.initialize_app( cred, {'storageBucket': 'parking-76066.appspot.com'}) config = { "apiKey": "AIzaSyD8frsIPC5o2RMec3To5YkuU6FMrnWGCTI", "authDomain": "parking-76066.firebaseapp.com", "databaseURL": "https://parking-76066.firebaseio.com", "projectId": "parking-76066", "storageBucket": "parking-76066.appspot.com", "messagingSenderId": "341130119386", "appId": "1:341130119386:web:3d2d28e2d9e8acf21ffde3", "measurementId": "G-GF6TX0KFFB" } try: f = [ open('C:/HC/afterCrop/ocr%d.text'.replace('\u202a', "") % i, 'r', encoding='UTF-8') for i in range(1, 4) ] read = [] for i in range(0, len(f)): read.append(f[i].read()) finally: for fh in f: fh.close() ocr_txt = "" for i in range(0, len(read)): if (read[i] == "parknum is not found"): ocr_txt = "null" else: ocr_txt = read[i] break print(ocr_txt) firebase = pyrebase.initialize_app(config) db = firebase.database() db.child("name").child("-M9m61HQdmKX694wJKnF").update({"parknum": ocr_txt}) # db.child("name").child("-M7qEiKlHjou_PAqcwnt").update({"parknum":ocr_txt}) print("FireBase에 텍스트를 Update 했습니다.") #db.child("name").remove() #db = firestore.client() bucket = storage.bucket() blobs = [] for i in range(0, 3): blobs.append(bucket.blob('Parking{}'.format(i + 1))) for i in range(0, 3): outfile = 'C:\\HC\\imgList\\CarLocationImg_{}.jpg'.format(i + 1).replace( '\u202a', "") with open(outfile, 'rb') as my_file: blobs[i].upload_from_file(my_file) print("FireBase storage에 이미지 파일을 저장했습니다.")
def kernel_push(request): api = KaggleApi() api.authenticate() bucket = storage.bucket(PUSH_BUCKET) metadata_blob = bucket.blob("kernel_metadata.json") notebook_blob = bucket.blob("{}.ipynb".format(KERNEL_SLUG)) metadata_blob.download_to_filename("{}/kernel-metadata.json".format(PATH)) notebook_blob.download_to_filename("{}/{}.ipynb".format(PATH, KERNEL_SLUG)) api.kernels_push("{}".format(PATH))
def kernel_pull(request): api = KaggleApi() api.authenticate() api.kernels_pull_cli("{}/{}".format(USERNAME, KERNEL_SLUG), path="{}".format(PATH), metadata=True) bucket = storage.bucket(PULL_BUCKET) metadata_blob = bucket.blob("kernel_metadata.json") notebook_blob = bucket.blob("{}.ipynb".format(KERNEL_SLUG)) metadata_blob.upload_from_filename("{}/kernel-metadata.json".format(PATH)) notebook_blob.upload_from_filename("{}/{}.ipynb".format(PATH, KERNEL_SLUG))
def main(): fname = " C:\HC\parking.json" cred=credentials.Certificate(r' C:/HC/parking.json'.replace('\u202a',"")) firebase_admin.initialize_app(cred,{ 'storageBucket': 'parking-76066.appspot.com' }) config = { "apiKey": "", "authDomain": "", "databaseURL": "", "projectId": "", "storageBucket": "", "messagingSenderId": "", "appId": "", "measurementId": "" } try: f = [open(' C:/HC/afterCrop/ocr%d.text'.replace('\u202a',"")%i,'r',encoding='UTF-8')for i in range(1,4)] read = [] for i in range(0,len(f)): read.append(f[i].read()) finally: for fh in f: fh.close() ocr_txt = "" for i in range(0,len(read)): if(read[i]=="parknum is not found"): ocr_txt="null" else: ocr_txt=read[i] break print(ocr_txt) firebase = pyrebase.initialize_app(config) db = firebase.database() db.child("name").child("key value").update({"parknum":ocr_txt}) print("success update firebase") #db.child("name").remove() #db = firestore.client() bucket = storage.bucket() blobs=[] for i in range(0,3): blobs.append(bucket.blob('test{}'.format(i+1))) for i in range(0,3): outfile = ' C:\\HC\\imgList\\test_{}.jpg'.format(i+1).replace('\u202a',"") with open(outfile,'rb') as my_file: blobs[i].upload_from_file(my_file) print("success update storage")
def kernel_update(request): # pull the most recent version of the kernel api = KaggleApi() api.authenticate() api.kernels_pull_cli("{}/{}".format(USERNAME, KERNEL_SLUG), path="{}".format(PATH), metadata=True) # push our notebook api.kernels_push_cli("{}".format(PATH)) # save a copy of our notebook in our bucket (if you would prefer # not to save a copy, delete all lines from here to the end of the file). bucket = storage.bucket(BUCKET) metadata_blob = bucket.blob("kernel-metadata.json") notebook_blob = bucket.blob("{}.{}".format(KERNEL_SLUG, KERNEL_EXTENSION )) metadata_blob.upload_from_filename("{}/kernel-metadata.json".format(PATH)) notebook_blob.upload_from_filename("{}/{}.{}".format(PATH, KERNEL_SLUG, KERNEL_EXTENSION))
def __init__(self, **kwargs): # self.ref = db.reference() super(SignUPApp, self).__init__(**kwargs) self.face_cascade = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') self.data = [] self.checks = [] self.check_ref = {} self.can_party = [] self.can_cnic = [] self.sector = '' Clock.schedule_once(self.forTowns) if not len(firebase_admin._apps): cred = credentials.Certificate("serviceAccountKey.json") firebase_admin.initialize_app( cred, {'storageBucket': 'electronicvotingsystem-50180.appspot.com'}) self.db = firestore.client() self.bucket = storage.bucket() self.strng = Builder.load_string(help_str) self.regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' self.count = 0 try: firebaseconfig = { "apiKey": "AIzaSyDPUAJhlgVdg3KMlUtsYEonw-EJjSVWNSY", "authDomain": "electronicvotingsystem-50180.firebaseapp.com", "databaseURL": "https://electronicvotingsystem-50180.firebaseio.com", "projectId": "electronicvotingsystem-50180", "storageBucket": "electronicvotingsystem-50180.appspot.com", "messagingSenderId": "1084797426587", "appId": "1:1084797426587:web:90c9c0dd986f0ba0e95f3e", "measurementId": "G-11FL2TP01C" } self.firebase = pyrebase.initialize_app(firebaseconfig) self.storage = self.firebase.storage() except requests.exceptions.HTTPError as httpErr: error_message = json.loads(httpErr.args[1])['error']['message']
def kernel_update(request): # pull the most recent version of the kernel api = KaggleApi() api.authenticate() api.kernels_pull_cli("{}/{}".format(USERNAME, KERNEL_SLUG), path="{}".format(PATH), metadata=True) # push our notebook api.kernels_push_cli("{}".format(PATH)) # save a copy of our notebook in our bucket (if you would prefer # not to save a copy, delete all lines from here to the end of the file). bucket = storage.bucket(BUCKET) metadata_blob = bucket.blob("kernel-metadata.json") notebook_blob = bucket.blob("{}.{}".format(KERNEL_SLUG, KERNEL_EXTENSION)) metadata_blob.upload_from_filename("{}/kernel-metadata.json".format(PATH)) notebook_blob.upload_from_filename("{}/{}.{}".format( PATH, KERNEL_SLUG, KERNEL_EXTENSION))
def changeStatusPhoto(self, estado): if estado: try: print('TAKING FOTO') name = datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S") full_path = '/home/pi/iot/photos/' + name + '.jpg' self.camera.resolution = (640, 360) self.camera.start_preview() sleep(2) self.camera.capture(full_path) self.camera.stop_preview() reference = '2C:3A:E8:06:F6:D4/' + name #create a bucket for storage files on Firebase Storage bucket = storage.bucket() blob = bucket.blob(reference) outfile = full_path blob.upload_from_filename(outfile) #upload image to Storage blob.make_public() #Make public thhe image #set de public url that upload on firebase Storage self.refMacPhotos.push({ 'url': blob.public_url, 'reference': reference }) #update status on camera reference self.refCamera.update({'status': False}) print("ok") except Exception as e: print(e) else: print('DONT NEED TO TAKE PHOTO')
outline=(0, 0, 255)) draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 255)) # Remove the drawing library from memory as per the Pillow docs. del draw # Save image in open-cv format to be able to show it. opencvimage = np.array(pil_image) return opencvimage if __name__ == "__main__": ################### Call Image ###################### bucket = storage.bucket(app=sr_app) blob = bucket.blob("WhoRU_target/{}.jpg".format(username)) user_path = "./knn_examples/train/{}".format(username) if not os.path.isdir(user_path): os.mkdir(user_path) img_url = blob.generate_signed_url(datetime.timedelta(seconds=300), method='GET') urllib.request.urlretrieve(img_url, '{0}/{1}.jpg'.format(user_path, username)) print("save") ###################################################### print("Training KNN classifier...") classifier = train("knn_examples/train", model_save_path="trained_knn_model.clf", n_neighbors=2) print("Training complete!")
from firebase import firebase from google.cloud import storage import firebase_admin from firebase_admin import credentials, firestore, storage import os #firebase = firebase.FirebaseApplication('https://pracs-be3b0.firebaseio.com', None) cred = credentials.Certificate("pracs-be3b0-firebase-adminsdk-yqgu4-f92fb008fe.json") firebase_admin.initialize_app(cred, { 'storageBucket': 'pracs-be3b0.appspot.com'}) #db = firestore.client() bucket = storage.bucket() zebraBlob = bucket.blob("yellowdog.png") zebraBlob.upload_from_filename(filename="data/yellowdog.png")
# limitations under the License. import google.auth import google.oauth2.credentials import google.cloud.storage # Explicitly grab credentials. This will pickup the Cloud SDK credentials if # and only if (1) the user hasn't set the GOOGLE_APPLICATION_CREDENTIALS # environment variable, (2) the user isn't running the code on GCE, GKE, GCF, # or GA, and (3) if the Cloud SDK is install and the user has run gcloud auth # application-default login. You can technically omit this step as the Storage # client constructor will do it under the covers, but I want to illustrate # what's occurring. credentials, _ = google.auth.default() # Make sure these are user credentials. We don't want our application to use # any other types of credentials that might be returned from # google.auth.default() if not isinstance(credentials, google.oauth2.credentials.Credentials): raise EnvironmentError( "The credentials obtained by google.auth.default() did not come from " "the Cloud SDK") # Create a storage client and list the contents of a bucket. storage = google.cloud.storage.Client(credentials=credentials, project=None) blobs = storage.bucket('temp.theadora.io').list_blobs() for blob in blobs: print(blob.name)
import datetime from google.appengine.api import app_identity import google.cloud.storage import webapp2 storage = google.cloud.storage.Client() bucket = storage.bucket( '{}.appspot.com'.format(app_identity.get_application_id(), ), ) class MainHandler(webapp2.RequestHandler): def get(self): token, ttl = app_identity.get_access_token_uncached(( 'https://www.googleapis.com/auth/devstorage.full_control', 'https://www.googleapis.com/auth/devstorage.read_only', 'https://www.googleapis.com/auth/devstorage.read_write', ), ) blob = bucket.blob('NotAllowed') blob.upload_from_string( '123', content_type='image/jpeg', ) self.response.json = { 'token': token, 'ttl': ttl, 'url': blob.generate_signed_url(datetime.timedelta(minutes=1)),
import os import flask from google.cloud import storage import tempfile BUCKET_NAME = os.environ.get("BUCKET_NAME") app = flask.Flask(__name__) storage = storage.Client() bucket = storage.bucket(BUCKET_NAME) @app.route("/cat/<img>") def cat(img): blob = bucket.blob(img) with tempfile.NamedTemporaryFile() as temp: blob.download_to_filename(temp.name) return flask.send_file(temp.name, attachment_filename=img) @app.route("/") def hello_cats(): if not BUCKET_NAME: return flask.render_template_string( "<h1>I have no cats.</h1>BUCKET_NAME environment variable required." ) cats = storage.list_blobs(BUCKET_NAME) return flask.render_template("cats.html", cats=cats)
from segmentation import getImagesFromFolder cred = credentials.Certificate("credentials.json") app = firebase_admin.initialize_app(cred) storage = storage.Client.from_service_account_json("credentials.json") db = firestore.client() doc_ref = db.collection(u'Main').document(u'ProcessedImages') doc_ref.set({ u'imageURL': 'initialisation', u'imageclass': 'initialisation', u'co-ords': [0, 0] }) imageFiles = getImagesFromFolder("raw-images", "raw-images/s") i = 1 for file in imageFiles: blob = storage.bucket('bgn-university-hack-rem-1018.appspot.com').blob( "processed" + file.name[-5] + ".png") blob.upload_from_filename(file.name) print(file.name, "uploaded as processed" + file.name[-5] + ".png") i += 1 print(blob.public_url) # db.collection(u'Main').add({ # u'URL': blob.public_url, # u'imageclass':'bar', # u'co-ords':[2,4] # })