def get_food_listings(): if request.method == "POST": if request.form["business-type"] == "Soup Kitchen": business_type = "soup_kitchen" elif request.form["business-type"] == "Food bank": business_type = "food_banks" else: business_type = "individuals" cred = credentials.ApplicationDefault() try: firebase_admin.get_app() print('firebase already intialized.') except ValueError as e: print('firebase not initialized. initialize.') firebase_admin.initialize_app(cred) db = firestore.client() doc_ref = db.collection(business_type) north_point = firestore.GeoPoint( float(request.form["latval"])+5, float(request.form["lngval"])+5) south_point = firestore.GeoPoint( float(request.form["latval"])-5, float(request.form["lngval"])-5) docs = doc_ref.where( 'location', '<=', north_point).where('location', '>=', south_point).where('available', '==', "True").stream() results = {} for doc in docs: print('{}=>{}'.format(doc.id, doc.to_dict())) docdata = doc.to_dict() results[str(doc.id)] = dict() for key, val in docdata.items(): if isinstance(docdata[key], firebase_admin.firestore.GeoPoint): results[str(doc.id) ]["latitude"] = docdata["location"].latitude results[str(doc.id) ]["longitude"] = docdata["location"].longitude else: results[str(doc.id)][key] = docdata[key] if results: print("sending results") print(results) return jsonify({'success': results}) else: print("sending error") return jsonify({'error': "No food items found"})
def main(): key_json = os.path.expanduser("~/.config/serviceAccountKey.json") cred = credentials.Certificate(key_json) firebase_admin.initialize_app(cred) with open('data.json', 'r') as f: items = json.load(f) db = firestore.client() coll = db.collection('places') ids = [] docs = coll.get() for doc in docs: ids.append(doc.id) for item in items: if item['id'] in ids: continue doc = coll.document(item['id']) doc.set({ 'name': item['name'], 'position': firestore.GeoPoint(item['position']['lat'], item['position']['lng']) }) print(item)
def set_wp(self, coords): nav = [] for cord in coords: coord = utils.to_wgs84(cord) nav.append(firestore.GeoPoint(coord.y, coord.x)) self.mission.document("routes").update({u'nav': nav}) self.status.document("nav").update({"mode": "STOP"})
def store_food_item_db(event, context): """Triggered from a message on a Cloud Pub/Sub topic. Args: event (dict): Event payload. context (google.cloud.functions.Context): Metadata for the event. """ pubsub_message = base64.b64decode(event['data']).decode('utf-8') food_item = json.loads(pubsub_message) print(food_item["category"]) cred = credentials.ApplicationDefault() try: firebase_admin.get_app() print('firebase already intialized.') except ValueError as e: print('firebase not initialized. initialize.') firebase_admin.initialize_app(cred) db = firestore.client() collection_id = "default" document_id = str(food_item["food_item_id"]) if food_item["category"] == "cooked_food": collection_id = 'soup_kitchen' elif food_item["category"] == "produce": collection_id = 'individuals' elif food_item["category"] == "packed_food" or food_item[ "category"] == "house_supply": collection_id = 'food_banks' else: collection_id = 'default' doc_ref = db.collection(collection_id).document(document_id) doc_ref.set({ 'food_item_id': food_item["food_item_id"], 'image': food_item["image"], 'title': food_item["title"], 'pickup': food_item["pickup"], 'description': food_item["description"], 'category': food_item["category"], 'location': firestore.GeoPoint(float(food_item["lat"]), float(food_item["long"])), 'address': food_item["address"], 'available': food_item["available"], 'date': food_item["date"], 'collection_id': collection_id }) print("data uploaded")
def journeyTaskVariables(request): # get variables common to all journey tasks from json request userId = request.json["userId"] taskType = request.json["taskType"] journeyType = request.json["journeyType"] taskId = request.json["taskId"] originString = request.json["origin"] regex = re.search('.*\((.*),(.*)\)', originString) origin = firestore.GeoPoint(float(regex.group(1)), float(regex.group(2))) destinationString = request.json["destination"] regex = re.search('.*\((.*),(.*)\)', destinationString) destination = firestore.GeoPoint(float(regex.group(1)), float(regex.group(2))) distance = float(request.json["distance"]) return userId, taskId, taskType, journeyType, origin, destination, distance
def sendData(driveTime, driver, lat, lon, speed, limit, deltaSpeed): #client = firestore.client() print("data send") if deltaSpeed < 0: GPIO.output(40, 0) else: GPIO.output(40, 1) location=firestore.GeoPoint(lat, lon) timestamp = firestore.SERVER_TIMESTAMP doc_ref = db.collection(u'events').document() doc_ref.set({ u'Battery': 100, u'Driver': driver, u'Location': location, u'RealData': reatData, u'Speed': speed, u'SpeedLimit': limit, u'SpeedStatus': deltaSpeed, u'StatusCode': "", u'Time': timestamp })
def parse_data(data_list, count, docName): ### Initialize firebase cred = credentials.Certificate('./ServiceAccountKey.json') default_app = firebase_admin.initialize_app(cred) db = firestore.client() counter = 0 while counter < count: d = data_list[counter] counter = counter + 1 # attribution and target set to 'unknown'' by default attribution = 'unknown' target = 'unknown' if d['actor1'] is not "": attribution = d['actor1'] if d['actor2'] is not "": target = d['actor2'] # severity guaged by casualties severity = 1 if int(d['fatalities']) > 0: if int(d['fatalities']) > 5: severity = 3 else: severity = 2 description = d['notes'] primaryEventType = "" eventType = {} # eventType (can be multiple) read from description and primaryEventType set # by following order of importance (defaults to assault) if (d['event_type'] == 'Riots/Protests'): primaryEventType = u"riot" eventType['riot'] = True if ("militants" in description) or ("militia" in description) or ( "army" in description) or ("armed group" in description): primaryEventType = u"armed group" eventType['armed group'] = True if ("theft" in description) or ("stole" in description) or ("loot" in description): primaryEventType = u"theft" eventType['theft'] = True if ("shoot" in description) or ("shot" in description) or ( "gunfire" in description) or ("gunmen" in description) or ( "sniping" in description) or ("snipe" in description): primaryEventType = u"shooting" eventType['shooting'] = True if ("kidnap" in description): primaryEventType = u"kidnapping" eventType['kidnapping'] = True if ("explosive" in description) or ("explosion" in description) or ( "exploded" in description) or ("bomb" in description) or ("IED" in description): primaryEventType = u"explosives" eventType['explosives'] = True if len(eventType) == 0: primaryEventType = u"assault" eventType['assault'] = True # Create and add new doc to input region's intelReports sub-collection db.collection('regions').document(docName).collection( 'intelReports').add({ 'operator': d['source'], 'timestamp': datetime.now(), 'location': { 'type': u'address', 'address': [(d['location']), (d['admin2'] + ", " + d['admin1'] + ", " + d['country'])], 'coordinates': firestore.GeoPoint(float(d['latitude']), float(d['longitude'])) }, 'timeOfEvent': datetime.strptime(d['event_date'] + ' 04:00', '%Y-%m-%d %H:%M'), 'eventType': eventType, 'primaryEventType': primaryEventType, 'numberInvolved': 1, 'casualties': int(d['fatalities']), 'attribution': attribution, 'target': target, 'description': d['notes'], 'severity': severity, # 'verification': {...} }) print "Parsed " + str( counter ) + " incidents into /regions/" + docName + "/intelReports . . . "
data = [] headers = [] with open(file_path) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: for header in row: headers.append(header) line_count += 1 else: obj = {} for idx, item in enumerate(row): obj[headers[idx]] = item obj['location'] = firestore.GeoPoint(float( obj['lat']), float(obj['long'])) #geopoint transformation obj['redemptionLimit'] = int(obj['redemptionLimit']) #str to int obj.pop('lat') obj.pop('long') obj.pop('geopy') #obj['expiryDate'] = json.dumps(dt(obj['expiryDate']).isoformat()) data.append(obj) line_count += 1 print(f'Processed {line_count} lines.') for batched_data in batch_data(data, 499): batch = store.batch() for data_item in batched_data: doc_ref = store.collection(collection_name).document() batch.set(doc_ref, data_item) batch.commit()
def parse(self): return firestore.GeoPoint(self.latitude, self.longitude)
def test_geo_point(self): geo_point = firestore.GeoPoint(10, 20) # pylint: disable=no-member assert geo_point.latitude == 10 assert geo_point.longitude == 20
def set_limit(self, coords): nav = [] for cord in coords: nav.append(firestore.GeoPoint(cord.y, cord.x)) self.mission.document("routes").update({u'limit': nav}) self.status.document("nav").update({"mode": "STOP"})
def save_petition(data_json, num_of_department): #--------------------object data----------------------# #datetimeObj=data_json['datetime'] messageObj = data_json['messageObj'] location = data_json['location'] #--------------------object data----------------------# doc_result = db.collection('User').where('userID_from_line', '==', data_json['userid']).stream() is_std = True for sub_doc in doc_result: is_std = False if is_std: doc_query_result = db.collection('Student').where( 'userID_from_line', '==', data_json['userid']).stream() doc = list(doc_query_result)[0] #doc = doc.to_dict() doc_ref = db.collection('Student').document(doc.id) doc = doc_ref.get() data_dict = doc.to_dict() std_id = data_dict['User_ID'] num_of_petition = data_dict['nPetition'] pet_id = std_id + str(num_of_petition) image_dict = getImage_todic(messageObj) path = std_id + '/' + pet_id + '/' imgPath_dict = {} for x, y in image_dict.items(): imgPath_dict[x] = path + x + '.jpg' blob = bucket.blob(path + x + '.jpg') blob.upload_from_string(y, content_type='image/jpeg') userid = data_json['userid'] data_pet = { 'ID': pet_id, 'Detail': data_json['detail'], 'Topic': data_json['topic'], 'User_ID': std_id, 'userType': True, 'Date_time': firestore.SERVER_TIMESTAMP, 'location': firestore.GeoPoint(location['latitude'], location['longitude']), 'Image': imgPath_dict, 'Department': num_of_department, 'currentStatus': 0 } doc_pet = db.collection('Petition').document(pet_id) doc_std = db.collection('Student').document(doc.id) batch.update(doc_std, {'nPetition': increment}) batch.set(doc_pet, data_pet) batch.commit() doc_to_listenning = db.collection('Petition').document(pet_id) doc_listenner_dict[pet_id] = doc_to_listenning.on_snapshot(on_snapshot) else: doc_ref = db.collection('User').document(data_json['userid']) doc = doc_ref.get() data_dict = doc.to_dict() use_id = data_dict['User_ID'] num_of_petition = data_dict['nPetition'] userid = data_json['userid'] pet_id = use_id + str(num_of_petition) image_dict = getImage_todic(messageObj) path = use_id + '/' + pet_id + '/' imgPath_dict = {} for x, y in image_dict.items(): imgPath_dict[x] = path + x + '.jpg' blob = bucket.blob(path + x + '.jpg') blob.upload_from_string(y, content_type='image/jpeg') data_pet = { 'ID': pet_id, 'Detail': data_json['detail'], 'Topic': data_json['topic'], 'User_ID': use_id, 'userType': False, 'Date_time': firestore.SERVER_TIMESTAMP, 'location': firestore.GeoPoint(location['latitude'], location['longitude']), 'Image': imgPath_dict, 'Department': num_of_department, 'currentStatus': 0 } doc_pet = db.collection('Petition').document(pet_id) doc_use = db.collection('User').document(userid) batch.update(doc_use, {'nPetition': increment}) batch.set(doc_pet, data_pet) batch.commit() doc_to_listenning = db.collection('Petition').document(pet_id) doc_listenner_dict[pet_id] = doc_to_listenning.on_snapshot(on_snapshot) #----------------------gen pet id--------------------# return pet_id
def predict(): to_predict = [] X_tr = [] usedImages = [] num_frames = 16 img_rows, img_cols = 128, 128 classes = 'System Start, Collecting Frames' payload = request.form.to_dict(flat=False) im_b64 = payload['image'] for i in range(len(im_b64)): im_binary = base64.b64decode(im_b64[i]) buf = io.BytesIO(im_binary) img = Image.open(buf) to_predict.append(np.array(img)) if len(to_predict) == num_frames: for frameData in to_predict: frame1 = cv2.cvtColor(frameData, cv2.COLOR_BGR2RGB) frame1 = cv2.resize(frame1, (img_rows, img_cols), interpolation=cv2.INTER_AREA) gray = cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB) usedImages.append(gray) input_img = np.array(usedImages) ipt = np.rollaxis(np.rollaxis(input_img, 2, 0), 2, 0) ipt = np.rollaxis(ipt, 2, 0) X_tr.append(ipt) X_tr_array = np.array(X_tr) test_pred = model1.predict(X_tr_array) result = np.argmax(test_pred, axis=1) print(test_pred) if result[0] == 0: classes = 'Non Violence' else: classes = 'Violence' todo_ref.add({ 'address': 'TEST', 'camera_name': 'dulgimo', 'coordinate': firestore.GeoPoint(-7.285113, 112.796504), 'created_at': time.time(), 'photo': im_b64[8], 'resolved': False, 'resolved_by': '', 'updated_at': None, 'user': '******', 'phone': '087899998888' }) result = push_service.notify_topic_subscribers( message_title="Jaga Bersama", topic_name="violence", message_body="Kasus Kekerasan Baru Terdeteksi") return jsonify({'msg': 'success', 'classes': classes}), 200
def to_dict_firebase(self): return { u'owner': self.owner, u'hours_active_weekly': self.hours_active_weekly, u'points': [firestore.GeoPoint(p[0], p[1]) for p in self.points] }
def set_a(self, coord): coord2 = firestore.GeoPoint(coord.y, coord.x) self.client.set('a_lat', str(coord.y)) self.client.set('a_lon', str(coord.x)) self.mission.document("routes").update({u'a': coord2}) self.status.document("nav").update({"mode": "STOP"})
def create_locations(db): ''' Create location collection with the 3 local gyms :param db: firestore database :return: Dict of location references :rtype: dict of ref ''' try: # Basic Location information locations = [{ 'name': 'Altitude Kanata', 'address': '0E5, 501 Palladium Dr, Kanata, ON K2V 0E5', 'city': 'Ottawa', 'province': 'Ontario', 'country': 'Canada', 'postal': 'K2V 0E5', 'location': firestore.GeoPoint(45.297970, -75.911150), 'grading_scale': [ 'VB/V0', 'V0/V1', 'V1/V2', 'V2/V3', 'V3/V4', 'V4/V5', 'V5/V6', 'V6/V7', 'V7/V8', 'V8/V9', 'V9+', 'Kids - VB/V0', 'Kids - V0/V1', 'Kids - V1/V2', 'Kids - V2/V3', 'Kids - V3/V4', 'Kids - V4/V5', 'Kids - V5/V6', 'Kids - V6/V7', 'Kids - V7/V8', 'Kids - V8/V9', 'Kids - V9+', 'competition', 'routesetting-squad' ], 'capacity': 50, }, { 'name': 'Altitude Gatineau', 'address': '35 Boulevard Saint-Raymond, Gatineau, QC J8Y 1R5', 'city': 'Gatineau', 'province': 'Quebec', 'country': 'Canada', 'postal': 'J8Y 1R5', 'location': firestore.GeoPoint(45.446861, -75.736801), 'grading_scale': [ 'VB/V0', 'V0/V1', 'V1/V2', 'V2/V3', 'V3/V4', 'V4/V5', 'V5/V6', 'V6/V7', 'V7/V8', 'V8/V9', 'V9+', 'competition', 'routesetting-squad' ], 'capacity': 75, }, { 'name': 'Coyote Rock Gym', 'address': '1737B St Laurent Blvd, Ottawa, ON K1G 3V4', 'city': 'Ottawa', 'province': 'Ontario', 'country': 'Canada', 'postal': 'K1G 3V4', 'location': firestore.GeoPoint(45.406130, -75.625500), 'grading_scale': [ 'White', 'Orange', 'Red', 'Blue', 'Green', 'Purple', 'Black', 'Ungraded' ], 'capacity': 50, }] # Loop through locations and create a new document in firestore location_dict = {} for location in locations: doc_ref = db.collection('locations').document() location_dict[location['name']] = doc_ref doc_ref.set(location) print( f"[Document ID: {doc_ref.id}] {location['name']}'s location data has been added to the db " ) return location_dict except Exception as ex: raise ex
def set_b(self, coord): coord2 = firestore.GeoPoint(coord.y, coord.x) self.client.set('b_lat', str(coord.y)) self.client.set('b_lon', str(coord.x)) self.mission.document("routes").update({u'b': coord2}) self.status.document("nav").update({"mode": "CREAR RUTA"})
def getdata(phnumber, update_probability=False): privatekey = db.collection(u'Profile').document( u'' + phnumber).get().to_dict()['PrivateKey'] rsakey = RSA.importKey(base64.b64decode(privatekey)) # rsakey = PKCS1_OAEP.new(rsakey, hashAlgo=SHA256, mgfunc=lambda x,y: pss.MGF1(x,y, SHA256)) rsakey = PKCS1_OAEP.new(rsakey, SHA512) def decrypt_location(loc, rsakey): # global rsakey b64_decoded_message = base64.b64decode(loc) decrypted = rsakey.decrypt(b64_decoded_message) return decrypted # #temorary # #3decimal places taken # lat=round(locx[0],3) # long=round(locx[1],3) # return(str(lat)+','+str(long)) # #temp ends # #decrypt and send # #return(list(map(float,loc.split(',')))) def rev_cipher(num): # add code here return num users_ref = db.collection(u'Profile').document(u'' + phnumber).collection( 'TimeStamps') docs = users_ref.stream() blth = {} loc = {} for doc in docs: bdic = doc.to_dict() time = bdic['TimeStamps'] if (bdic['Activity'] == "STILL"): loci = bdic['Location'] # print(loci) loci = decrypt_location(loci, rsakey) if loci in loc: loc[loci]["time"] += 2 loc[loci]["last"] = time else: loc[loci] = {"time": 2, "last": time} if 'MacAddress' in bdic: for bl in bdic['MacAddress']: bl1 = rev_cipher(bl) if bl1 in blth: blth[bl1]["time"] += 2 blth[bl1]["last"] = time else: blth[bl1] = {"time": 2, "last": time} blth2 = {} for i in blth: number = db.collection(u'Identify').document( u'' + i).get().to_dict()['Number'] blth2[number] = {"time": blth[i]["time"], "last": blth[i]["last"]} def update_prob(blth): for i in blth: prob = db.collection(u'Profile').document( u'' + i).get().to_dict()['Probability'] if blth[i]['time'] > 15: prob += 0.7 elif blth[i]['time'] > 5: prob += 0.4 else: prob += 0.2 prob = min(prob, 1) * 100 pth = db.collection(u'Profile').document(u'' + i).update( {u'Probability': prob}) data = {u'time spent': blth[i]['time'], u'last': blth[i]['last']} db.collection(u'Profile').document(u'' + i).collection( u'contact').document().set(data, merge=True) if update_probability == True: update_prob(blth2) ## to conver to list loc2 = [] for i in loc: loc2 += [{ 'geo': i.decode("utf-8"), 'last': loc[i]['last'], 'time': loc[i]['time'] }] if update_probability: for i in loc2: locx = i['geo'] locx = list(map(float, locx.split(','))) doc_ref = db.collection(u'HighRiskPlaces').document() doc_ref.set({ u'name': i['geo'], u'location': firestore.GeoPoint(locx[0], locx[1]) }) return ({"devices": blth2, "location": loc2})
with open('./assets/seller_sections_fake_data_foobarify.json') as json_file: fake_sections = json.load(json_file) batch = db.batch() for index, section in enumerate(fake_sections): docRef = db.collection( f'sellers/{section["seller_id"]}/sections').document() delivery_location = { 'address': section['delivery_location']['address'], 'address_zh': section['delivery_location']['address_zh'], 'geopoint': firestore.GeoPoint( section['delivery_location']['geopoint']['lat'], section['delivery_location']['geopoint']['long']) } now_time = datetime.now( pytz.timezone('Asia/Hong_Kong')) + timedelta(days=index) cutoff_time = datetime.strptime(section["cutoff_time"], '%H:%M') delivery_time = datetime.strptime(section["delivery_time"], '%H:%M') new_cutoff_time = now_time.replace(hour=cutoff_time.hour, minute=cutoff_time.minute) new_delivery_time = now_time.replace(hour=delivery_time.hour, minute=delivery_time.minute) batch.set( docRef, {
from firebase_admin import firestore from config import db # Insert into 'sellers' with open('./assets/sellers_fake_data.json') as json_file: fake_sellers = json.load(json_file) batch = db.batch() for seller in fake_sellers: docRef = db.document(f'sellers/{seller["id"]}') location = { 'address': seller['location']['address'], 'address_zh': seller['location']['address_zh'], 'geopoint': firestore.GeoPoint( seller['location']['geopoint']['lat'], seller['location']['geopoint']['long'] ) } batch.set(docRef, { 'id': seller['id'], 'name': seller['name'], 'name_zh': seller.get('name_zh', None), 'description': seller.get('description', None), 'description_zh': seller.get('description_zh', None), 'website': seller.get('website', None), 'phone_num': seller['phone_num'], 'location': location, 'image_url': seller.get('image_url', None), 'min_spend': seller['min_spend'], 'order_rating': seller['order_rating'],
def store_data_in_firebase(input_data): countries_data = input_data.copy() collection = firestore_init() ref = collection.stream() for firebase_data in ref: info = firebase_data.to_dict() id_ = firebase_data.id if info != {}: courser = info['cityName'] if courser in countries_data: if info['cases'] != countries_data[courser]['cases'] or info['death'] != countries_data[courser]['deaths'] or info['treated'] != countries_data[courser]['recovered']: latitude = countries_data[courser]['latitude'] longitude = countries_data[courser]['longitude'] try: collection.document(id_).update({ u'cityName': courser, u'countryName_KU': countries_data[courser]['countryKurdishName'], u'cases': countries_data[courser]['cases'], u'death': countries_data[courser]['deaths'], u'treated': countries_data[courser]['recovered'], u'todayCases': countries_data[courser]['todayCases'], u'todayDeaths': countries_data[courser]['todayDeaths'], u'critical': countries_data[courser]['critical'], u'bearing': countries_data[courser]['bearing'], u'latLong': firestore.GeoPoint(latitude, longitude), u'priority': countries_data[courser]['priority'], u'zoom': countries_data[courser]['zoom'], u'updated': datetime.fromtimestamp(countries_data[courser]['updated']/1000), u'continent': countries_data[courser]['continent'], }) except: print(u'We have some problem!') else: print(u"{}DATA UPDATED ----->>> {}{} >> {}. ######".format( C.WARNING, C.ENDC, courser, info )) del countries_data[courser] for new_country in countries_data: print(u"{}NEW COUNTRY ADDED ---->>>{} {} >> {}. *****".format( C.FAIL, C.ENDC, new_country, countries_data[new_country] )) latitude = countries_data[new_country]['latitude'] longitude = countries_data[new_country]['longitude'] collection.add({ u'cityName': new_country, u'cases': countries_data[new_country]['cases'], u'death': countries_data[new_country]['deaths'], u'treated': countries_data[new_country]['recovered'], u'countryName_KU': countries_data[new_country]['countryKurdishName'], u'critical': countries_data[new_country]['critical'], u'todayCases': countries_data[new_country]['todayCases'], u'todayDeaths': countries_data[new_country]['todayDeaths'], u'bearing': countries_data[new_country]['bearing'], u'latLong': firestore.GeoPoint(latitude, longitude), u'priority': countries_data[new_country]['priority'], u'zoom': countries_data[new_country]['zoom'], u'updated': datetime.fromtimestamp(countries_data[new_country]['updated']/1000), u'continent': countries_data[new_country]['continent'], }) return True