Example #1
0
def draw(identifier):
    # get game doc from db
    game_doc = db.collection('games').document(identifier)

    # load data
    game = game_doc.get().to_dict()

    # ensure game is in progress
    if game['status'] != 'in progress':
        return ({'message': 'This game is not in progress!'}), 403

    # check for correct turn
    device_uuid = request.headers.get('device', 'unknown')
    if game['sequence'][game['turn']] != device_uuid:
        return jsonify({'message': 'It is not your turn!'}), 403

    # get card and end game if deck finished
    card = game['deck'][game['position']]
    if game['position'] + 1 >= len(game['deck']):
        game['status'] = 'complete'

    turn_rollback = False
    if game['turn'] >= len(game['sequence']) - 1:
        turn_rollback = True

    # update db
    game_doc.update({
        'turn': 0 if turn_rollback else firestore.Increment(1),
        'position': firestore.Increment(1)
    })

    return jsonify({'card': card})
Example #2
0
def update_like(post_id):
    """likes the post for the current user or unlikes it if they have already liked the post."""

    if 'username' not in flask.session:
        return flask.jsonify(
            **{
                'message': 'must be logged in to like a post',
                'url': flask.request.path
            }), 401

    username = flask.session['username']

    # check if the specified post exists in our database
    post_doc = post_ref.document(post_id)
    if not post_doc.get().exists:
        return flask.jsonify(
            **{
                'message': 'specified post id {} not found'.format(post_id),
                'url': flask.request.path
            }), 404

    # look for an existing like in the post's subcollection
    existing_like = post_doc.collection('likes').document(username).get()
    # like does not exist so we add a document with id username to subcollection and increment count
    if not existing_like.exists:
        post_doc.collection('likes').document(username).set({})
        post_doc.get().reference.update({'num_likes': firestore.Increment(1)})
    # like does exist so we want to remove that document from the subcollection and decrement count
    else:
        existing_like.reference.delete()
        post_doc.get().reference.update({'num_likes': firestore.Increment(-1)})

    liked = not existing_like.exists
    # returns true if like action occurred and false if unlike action occurred
    return flask.jsonify(**{'url': flask.request.path, 'liked': liked}), 200
Example #3
0
def update_firestore(user_id, db, food_nutrition):

    current_date = datetime.today().strftime('%d-%m-%Y')

    user_doc_ref = db.collection('users').document(user_id)
    doc = user_doc_ref.get()
    if doc.exists:
        user_doc_ref.update({
            current_date: {
                "foods": firestore.ArrayUnion([food_nutrition['food_name']]),
                "total_nutrition": {
                    "calories":
                    firestore.Increment(food_nutrition['calories']),
                    "fat_g": firestore.Increment(food_nutrition['fat_g']),
                    "sodium_mg":
                    firestore.Increment(food_nutrition['sodium_mg']),
                    "protein_g":
                    firestore.Increment(food_nutrition['protein_g'])
                }
            }
        })
    else:
        user_doc_ref.set({
            current_date: {
                "foods": [food_nutrition['food_name']],
                "total_nutrition": {
                    "calories": food_nutrition['calories'],
                    "fat_g": food_nutrition['fat_g'],
                    "sodium_mg": food_nutrition['sodium_mg'],
                    "protein_g": food_nutrition['protein_g']
                }
            }
        })
Example #4
0
def customerAnalysis(adType, adAge):
    print(adType)
    print(adAge)
    if adType == 'male':
        if adAge == '(25,32)':
            customer_ref.update({u'male_25to32': firestore.Increment(1)})
    elif adType == 'female':
        if adAge == '(25,32)':
            customer_ref.update({u'female_25to32': firestore.Increment(1)})
Example #5
0
 def increment_num_attempts(self, player_id, mock_id):
     match_ref = self._db.document(f"users/{player_id}/matches/{mock_id}")
     try:
         match_ref.update({'numAttempts': firestore.Increment(1)})
     except:
         match = match_ref.get()
         if match.exists:
             match_ref.update({'numAttempts': firestore.Increment(1)})
         else:
             match_ref.set({'numAttempts': 1})
     self._db.document(f"users/{player_id}").update(
         {'numTotalAttempts': firestore.Increment(1)})
def update_stock_for_user():
    stocks_ref = db.collection("stocks")
    # Create stock query to query by userId and stock ticker
    query = stocks_ref.where(u'userId', '==',
                             request.args.get('userId')).where(
                                 u'stockTicker', '==',
                                 request.args.get('ticker'))
    try:
        doc_ref = query.get()
        for doc in doc_ref:
            doc_update = stocks_ref.document(doc.id)
            doc_update.update({
                'balance':
                firestore.Increment(int(request.args.get('amount'))),
                'initialBalance':
                firestore.Increment(int(request.args.get('amount'))),
                'minBalance':
                request.args.get('minBalance'),
            })
    except google.cloud.exceptions.NotFound:
        print(u'No such documents!')
        return jsonify({'success': False})
    return jsonify({'success': True})
Example #7
0
def update_follow(target_user):
    """Follows/Unfollows the specified user for the current user."""

    if 'username' not in flask.session:
        return flask.jsonify(**{'message': 'Cannot follow/unfollow user, not logged in', 'url': flask.request.path}), 401

    username = flask.session['username']
    target_entry = list(user_ref.where('username', '==', target_user).stream())
    user_entry = list(user_ref.where('username', '==', username).stream())

    # Make sure current user and target user exist
    if (len(target_entry) == 0):
        return flask.jsonify(** {'message': 'no target user {} found'.format(target_user), 'url': flask.request.path}), 404
    
    if (len(user_entry) == 0):
        return flask.jsonify(** {'message': 'no current user {} found'.format(username), 'url': flask.request.path}), 401

    # Check if the follow relationship already exists
    follow_check = list(follow_ref.where('follower', '==', username).where('followed', '==', target_user).stream())
    #if follow relationship does not exist, then follow the user
    if (len(follow_check) == 0):
        data = {
            'follower': username,
            'followed': target_user
        }
        follow_ref.document(username + '_' + target_user).set(data)
        user_entry[0].reference.update({'num_following': firestore.Increment(1)})
        target_entry[0].reference.update({'num_followers': firestore.Increment(1)})
    # if follow relationship does exist, then unfollow the user
    else:
        follow_check[0].reference.delete()
        user_entry[0].reference.update({'num_following': firestore.Increment(-1)})
        target_entry[0].reference.update({'num_followers': firestore.Increment(-1)})
    #Create database entry for following relationship and increment profile counts
    followed = (len(follow_check) == 0)
    # returns true if a follow occurred/false if an unfollow occurred
    return flask.jsonify(**{'url': flask.request.path, 'followed': followed}), 200
Example #8
0
def update_fidelity_increment(userId = None):
	if request.method == 'PATCH':
		userId = userId
		data = list()

		users_ref = db.collection(u'users').stream()

		for doc in users_ref:
			if doc.to_dict()['userId'] == userId:
				users_ref = db.collection(u'users').document(userId)
				users_ref.update({'fidelity': firestore.Increment(1)})
				response = build_response(200, 'Success', data)

				return jsonify(response)

		response = build_response(400, 'userId not found', data)
		return jsonify(response)
Example #9
0
def profile():
    print("in profile")
    uID = request.headers['uid']
    print(uID)
    current_user = auth.get_user(uID, default_app)
    accID = get_user_info(current_user)['email']
    if request.method == 'POST':
        try:
            # Check if ID was passed to URL query
            #accID = get_user_info(current_user)['email']
            #print(request.json)
            #accID = '*****@*****.**'

            profileCount = accounts.document(
                accID).get().to_dict()["profile_count"]
            profileID = genProfileID(accID, profileCount)
            print(profileID)
            profileDict = {}
            profileDict[profileID] = request.json

            # print(json.dumps(profileDict))
            accounts.document(accID).update(
                {u"profiles": firestore.ArrayUnion([profileDict])})

            accounts.document(accID).update(
                {"profile_count": firestore.Increment(1)})

            return jsonify({"success": True}), 200
        except Exception as e:
            print("ERRORR!!")
            print(e)
            return jsonify({"success": False}), 500
            return

    if request.method == "GET":
        try:
            accountDetails = accounts.document(accID).get().to_dict()
            # print(accountDetails["profiles"])
            return jsonify(accountDetails["profiles"]), 200

        except Exception as e:
            return f"An Error Occured: {e}"
Example #10
0
def deploy(image, detections):
    logger.debug('Deploying to firebase...')
    # Convert to blob
    retval, blob = cv2.imencode('.jpg', image)
    now = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
    # Add entry
    frames_ref.add({
        'image': base64.b64encode(blob),
        'created_at': now,
        'classes': list(map(lambda d: d['name'], detections)),
        'classes_detailed': detections
    })
    # Update stats for today
    today = now[:10]
    if len(detections) > 0:
        stats_ref.document(today).update(
            dict(
                zip(list(map(lambda d: d['name'], detections)),
                    [firestore.Increment(1)] * len(detections))))
    logger.debug('Deployed to firebase')
Example #11
0
def addLike():
    global read
    key = request.args['key']
    read.collection(u'Brands').document(u'H&M').collection(u'Products').document(key).update(
        {"likes": firestore.Increment(1)})
    return 'Sucessful'
Example #12
0
    async def rps(self, ctx, member: discord.Member = None):
        p1 = ctx.message.author
        p2 = member

        def check1(m):
            return m.author == p1 and m.channel != ctx.message.channel

        def check2(m):
            return m.author == p2 and m.channel != ctx.message.channel

        def checkopt(m):
            return m.author == p2 and m.channel == ctx.channel

        if member is None:
            await ctx.channel.send(
                "{0.mention} Please mention a user to play against!".format(p1)
            )
        elif p1 == p2:
            await ctx.channel.send(
                "Smh are you really going to play with yourself? 🤮 ")
        else:

            await ctx.channel.send(
                "{0.mention} Do you accept the challenge? (Y/N)".format(p2))
            choice = ""

            try:
                choice = await self.bot.wait_for('message',
                                                 timeout=60.0,
                                                 check=checkopt)
            except asyncio.TimeoutError:
                await ctx.message.channel.send(
                    'Event cancelled as no response recieved')
            else:
                if (choice.content.upper() == "Y"):
                    await ctx.channel.send("**Respond in your DM**")
                    await p1.send(
                        "**Choose between rock, paper and scissor(R/P/S)**")
                    await p2.send(f"*{p1} is choosing. please wait...*")

                    move1 = ""
                    move2 = ""
                    winner = p1
                    fail = ""
                    m1 = ""
                    m2 = ""
                    try:
                        move1 = await self.bot.wait_for('message',
                                                        timeout=30.0,
                                                        check=check1)
                    except asyncio.TimeoutError:
                        await p1.send("No response recieved")
                        fail = "y"
                    else:
                        move1 = move1.content.lower()

                    await p2.send(
                        "**Choose between rock, paper and scissor(R/P/S)**")

                    try:
                        move2 = await self.bot.wait_for('message',
                                                        timeout=30.0,
                                                        check=check2)
                    except asyncio.TimeoutError:
                        await p2.send("No response recieved")
                        fail = "y"
                    else:
                        move2 = move2.content.lower()

                    if (move1 == "" or move2 == ""):
                        fail = "y"

                    elif (move1 == "r" and move2 == "s"):
                        winner = p1
                    elif (move1 == "r" and move2 == "p"):
                        winner = p2
                    elif (move1 == "s" and move2 == "p"):
                        winner = p1
                    elif (move1 == "s" and move2 == "r"):
                        winner = p2
                    elif (move1 == "p" and move2 == "r"):
                        winner = p1
                    elif (move1 == "p" and move2 == "s"):
                        winner = p2
                    elif (move1 == move2):
                        winner = "tie"
                    else:
                        fail = "y"

                    if fail != "y":
                        if move1 == "r":
                            m1 = "rock"
                        elif move1 == "s":
                            m1 = "scissor"
                        elif move1 == "p":
                            m1 = "paper"

                        if move2 == "r":
                            m2 = "rock"
                        elif move2 == "s":
                            m2 = "scissor"
                        elif move2 == "p":
                            m2 = "paper"

                        desc = "{0.mention} won the game! What a pr0h 😩 ".format(
                            winner
                        ) if winner != "tie" else "{0.mention} and {1.mention} have tied with each other".format(
                            p1, p2)
                        desc = desc + "\n\n**Moves made:**\n{0.mention} picked `{1}`\n{2.mention} picked `{3}`".format(
                            p1, m1, p2, m2)

                        print(
                            '```p1:{}\np2:{}\nmove1:{}\nmove2:{}\nm1string:{}\nm2string{}\nwinner:{}```'
                            .format(p1, p2, move1, move2, m1, m2, winner))

                        embed = discord.Embed(
                            title="Rock,Paper,Scissors game result!",
                            description=desc,
                            color=0x00ff00)
                        if (winner != "tie"):
                            embed.set_thumbnail(url=winner.avatar_url)

                            doc_ref = db.collection(u'rps').document(
                                str(winner.id))
                            doc = doc_ref.get()

                            print(winner)

                            if doc.exists:
                                print(doc.to_dict())
                                doc_ref.update(
                                    {'points': firestore.Increment(1)})
                            else:
                                print(doc.to_dict())
                                doc_ref.set({
                                    u'points': 1,
                                    'name': winner.name
                                })

                        await ctx.channel.send(embed=embed)
                    else:
                        print(
                            '```p1:{}\np2:{}\nmove1:{}\nmove2:{}\nm1string:{}\nm2string{}\nwinner:{}```'
                            .format(p1, p2, move1, move2, m1, m2, winner))
                        await ctx.channel.send(
                            "**Challenge declined due to invalid responses/no responses**"
                        )

                elif (choice.content.upper() == "N"):
                    await ctx.channel.send("**Challenge has been declined!**")
                else:
                    await ctx.channel.send(
                        "**Challenge declined due to invalid input**")
Example #13
0
 def addPlay(self,tid):
     self.db.collection('tracks').document(tid).update({'plays':firestore.Increment(1)})
Example #14
0
 def increment_num_mock_tests(self, increment_value):
     self._db.document(f'metaData/mockTests').update(
         {'numMockTests': firestore.Increment(increment_value)})
     if increment_value > 0:
         self._db.document(f'metaData/mockTests').update(
             {'largestMockTestIndex': firestore.Increment(increment_value)})
Example #15
0
def deduct_fare(id):
    db.collection('facePay').document(id).update(
        {'walletBalance': firestore.Increment(-fare)})
Example #16
0
 def update(self):
     activities_ref = db.collection(u'activities').document(self.uid)
     activiti_ref = activities_ref.collection(self.uid).document(
         self.window_title)
     activiti_ref.update({'delta': firestore.Increment(self.diff)})
     print(f"[FB][+]{self.window_title} - {self.diff} updated.")
Example #17
0
    async def img(self, ctx, *msg):
        query = ' '.join(msg)
        img = ""
        if query == "":
            await ctx.send("What image do u want tho?")
            return

        if query.lower() == "arcadia":
            img = "https://images-ext-1.discordapp.net/external/sc3p-qOYB1jWwkFDfd4i6W7_r-lQP7o9rShmSlNT3zM/%3Fsize%3D256/https/cdn.discordapp.com/avatars/650969739107237900/8aa95ac0cf6413decdfd6c76e9c30f6e.png"
        else:
            key = GOOGLE_API_KEY
            cx = SEARCH_ENGINE_ID

            search_url = f"https://www.googleapis.com/customsearch/v1?key={key}&q={query}&cx={cx}&searchType=image&num=2"

            response = requests.get(search_url)
            data = response.json()

            print(data)

        try:
            if query.lower() == "arcadia":
                pass
            else:
                if data["items"][0]["link"].startswith(
                        "https://lookaside"
                ) or "svg" in data["items"][0]["link"]:
                    img = data["items"][1]["link"]
                else:
                    img = data["items"][0]["link"]
        except KeyError:
            try:
                if data["error"]["code"] == 429:
                    url = "https://bing-image-search1.p.rapidapi.com/images/search"
                    querystring = {"count": "1", "q": query}
                    headers = {
                        'x-rapidapi-host': "bing-image-search1.p.rapidapi.com",
                        'x-rapidapi-key': BING_API_KEY
                    }

                    response = requests.request("GET",
                                                url,
                                                headers=headers,
                                                params=querystring)

                    res = json.loads(response.text)
                    print(res)
                    try:
                        img = res["value"][0]["contentUrl"]
                    except KeyError:
                        await ctx.send(f"**No images found for {query}**")
                    else:
                        embed = discord.Embed(
                            title=f"Image result for {query}", color=0x1FEAEA)
                        embed.set_image(url=img)

                        await ctx.send(embed=embed)
            except KeyError:
                await ctx.send(f"**No images found for {query}**")
                return
            else:
                print(img)
        else:
            print(img)
            embed = discord.Embed(title=f"Image result for {query}",
                                  color=0x1FEAEA)
            embed.set_image(url=img)

            await ctx.send(embed=embed)
        
        doc_ref = db.collection(u'img-stats').document(str(ctx.message.author.name))

        if not(doc_ref.get().exists):
            doc_ref.set({u'uses':1})
        else:
            doc_ref.update({u'uses': firestore.Increment(1)})
Example #18
0
pre = pretext.pretextprocessing()
embed = hub.load("/home/thanaphat_phetkrow/API/model3")

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from firebase_admin import storage

cred = credentials.Certificate(
    '/home/thanaphat_phetkrow/API/serviceAccountKey.json')
firebase_admin.initialize_app(cred, {'storageBucket': 'fir-c1ec0.appspot.com'})
db = firestore.client()
bucket = storage.bucket()
batch = db.batch()
increment = firestore.Increment(1)

from linebot import LineBotApi
from linebot.models import TextSendMessage
from linebot.exceptions import LineBotApiError

line_bot_api = LineBotApi(
    'D0swFcBPAYfgPimK1O9LuyDhDGUUTkMAAPEgpCGB3gdS89Nl4tJpq8FfaVJFpf4dftTky5mCm5LYkbwSquGKZLWr3ye417GRKFvrXYgQPUWHAiocqCPcKT1i+hIRfHF73FxmmWWGyQpUt+YtQl+fAQdB04t89/1O/w1cDnyilFU='
)


def getImage_todic(messageIDList):

    disImage = {}

    for index in range(len(messageIDList)):
Example #19
0
def update_user(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    is_staff = request.user2['is_staff']

    try:
        if is_staff is None:
            return HttpResponse(
                {'error': 'Please verify weather user is Buyer or Seller'},
                statusx=400)
        if not is_staff:
            print(request.data)
            obj = Buyer.objects.get(id=request.user2['id'])

            serializer = BuyerUpdateSerializer(obj, request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                data = serializer.data
                profile_pic = data.get('profile_pic', None)
                if not profile_pic:
                    profile_pic = ''
                doc_ref = db.collection(u'chat_users').where(
                    'ids', 'array_contains', data.get('id')).get()
                for doc in doc_ref:
                    db.collection(u'chat_users').document(
                        u'' + str(doc.id)).update({
                            u'' + str(data.get('id')): {
                                u'name':
                                u'' + data.get('first_name', '') + ' ' +
                                data.get('last_name', ''),
                                u'avatar':
                                u'' + profile_pic,
                                u'unread':
                                firestore.Increment(50)
                            }
                        })
                data.pop('password', None)
                return tokenize(data, ip)
            return HttpResponse(serializer.errors, status=400)
        elif is_staff:
            obj = Seller.objects.get(id=request.user2['id'])
            serializer = SellerUpdateSerializer(obj,
                                                request.data,
                                                partial=True)
            print('Data')
            print(serializer.initial_data)

            if serializer.is_valid():
                serializer.save()
                data = serializer.data
                profile_pic = data.get('profile_pic', None)
                if not profile_pic:
                    profile_pic = ''
                doc_ref = db.collection(u'chat_users').where(
                    'ids', 'array_contains', data.get('id')).get()
                for doc in doc_ref:
                    db.collection(u'chat_users').document(
                        u'' + str(doc.id)).update({
                            u'' + str(data.get('id')): {
                                u'name':
                                u'' + data.get('first_name', '') + ' ' +
                                data.get('last_name', ''),
                                u'avatar':
                                u'' + profile_pic,
                                u'unread':
                                firestore.Increment(0)
                            }
                        })
                data.pop('password', None)
                return tokenize(data, ip)
            print(serializer.errors)
            return HttpResponse(serializer.errors, status=400)
    except Exception as e:
        print(e)
Example #20
0
 def increment_mock_num_questions(self, mock_id, increment_value):
     self._db.document(f'mockTests/{mock_id}').update(
         {'numQuestions': firestore.Increment(increment_value)})
     if increment_value > 0:
         self._db.document(f'mockTests/{mock_id}').update(
             {'largestQuestionIndex': firestore.Increment(1)})
def visualize_boxes_and_labels_on_image_array(current_frame_number,
                                              image,
                                              boxes,
                                              classes,
                                              scores,
                                              category_index,
                                              instance_masks=None,
                                              keypoints=None,
                                              use_normalized_coordinates=False,
                                              max_boxes_to_draw=20,
                                              min_score_thresh=.5,
                                              agnostic_mode=False,
                                              line_thickness=4):
    """Overlay labeled boxes on an image with formatted scores and label names.

  This function groups boxes that correspond to the same location
  and creates a display string for each detection and overlays these
  on the image. Note that this function modifies the image in place, and returns
  that same image.

  Args:
    image: uint8 numpy array with shape (img_height, img_width, 3)
    boxes: a numpy array of shape [N, 4]
    classes: a numpy array of shape [N]. Note that class indices are 1-based,
      and match the keys in the label map.
    scores: a numpy array of shape [N] or None.  If scores=None, then
      this function assumes that the boxes to be plotted are groundtruth
      boxes and plot all boxes as black with no classes or scores.
    category_index: a dict containing category dictionaries (each holding
      category index `id` and category name `name`) keyed by category indices.
    instance_masks: a numpy array of shape [N, image_height, image_width], can
      be None
    keypoints: a numpy array of shape [N, num_keypoints, 2], can
      be None
    use_normalized_coordinates: whether boxes is to be interpreted as
      normalized coordinates or not.
    max_boxes_to_draw: maximum number of boxes to visualize.  If None, draw
      all boxes.
    min_score_thresh: minimum score threshold for a box to be visualized
    agnostic_mode: boolean (default: False) controlling whether to evaluate in
      class-agnostic mode or not.  This mode will display scores but ignore
      classes.
    line_thickness: integer (default: 4) controlling line width of the boxes.

  Returns:
    uint8 numpy array with shape (img_height, img_width, 3) with overlaid boxes.
  """
    # Create a display string (and color) for every box location, group any boxes
    # that correspond to the same location.
    cred = credentials.Certificate('firebase-sdk-key.json')
    if not firebase_admin._apps:
        firebase_admin.initialize_app(
            cred,
            {'databaseURL': 'https://summer-project-f7b40.firebaseio.com/'})
    db = firestore.client()
    doc_ref = db.collection('Parkings').document('AgeN47dUopUxcOjzrq6k')
    csv_line_util = "not_available"
    is_full = 0
    counter = 0
    firebase_counter = 0
    is_vehicle_detected = []
    box_to_display_str_map = collections.defaultdict(list)
    box_to_color_map = collections.defaultdict(str)
    box_to_instance_masks_map = {}
    box_to_keypoints_map = collections.defaultdict(list)
    if not max_boxes_to_draw:
        max_boxes_to_draw = boxes.shape[0]
    for i in range(min(max_boxes_to_draw, boxes.shape[0])):
        if scores is None or scores[i] > min_score_thresh:
            box = tuple(boxes[i].tolist())
            if instance_masks is not None:
                box_to_instance_masks_map[box] = instance_masks[i]
            if keypoints is not None:
                box_to_keypoints_map[box].extend(keypoints[i])
            if scores is None:
                box_to_color_map[box] = 'black'
            else:
                if not agnostic_mode:
                    if classes[i] in category_index.keys():
                        class_name = category_index[classes[i]]['name']
                    else:
                        class_name = 'N/A'
                    display_str = '{}: {}%'.format(class_name,
                                                   int(100 * scores[i]))
                else:
                    display_str = 'score: {}%'.format(int(100 * scores[i]))

                box_to_display_str_map[box].append(display_str)
                if agnostic_mode:
                    box_to_color_map[box] = 'DarkOrange'
                else:
                    box_to_color_map[box] = STANDARD_COLORS[
                        classes[i] % len(STANDARD_COLORS)]

    # Draw all boxes onto image.
    for box, color in box_to_color_map.items():
        ymin, xmin, ymax, xmax = box
        if instance_masks is not None:
            draw_mask_on_image_array(image,
                                     box_to_instance_masks_map[box],
                                     color=color)

        display_str_list = box_to_display_str_map[box]
        # we are interested just vehicles (i.e. cars and trucks)
        if (("car" in display_str_list[0]) or ("truck" in display_str_list[0])
                or ("bus" in display_str_list[0])):
            is_vehicle_detected, csv_line, update_csv = draw_bounding_box_on_image_array(
                current_frame_number,
                image,
                ymin,
                xmin,
                ymax,
                xmax,
                color=color,
                thickness=line_thickness,
                display_str_list=box_to_display_str_map[box],
                use_normalized_coordinates=use_normalized_coordinates)

            if keypoints is not None:
                draw_keypoints_on_image_array(
                    image,
                    box_to_keypoints_map[box],
                    color=color,
                    radius=line_thickness / 2,
                    use_normalized_coordinates=use_normalized_coordinates)

    if (1 in is_vehicle_detected):
        counter = 1

        doc = doc_ref.get(field_paths={'Aquired'}).to_dict().get('Aquired')
        doc_ref.update({'Aquired': firestore.Increment(1)})

        del is_vehicle_detected[:]
        is_vehicle_detected = []
        if (class_name == "boat"):
            class_name = "truck"
        csv_line_util = class_name + "," + csv_line

    doc = doc_ref.get(field_paths={'Aquired'}).to_dict().get('Aquired')
    doc1 = doc_ref.get(field_paths={'Quantity'}).to_dict().get('Quantity')

    if doc >= doc1:
        is_full = 1
    else:
        is_full = 0

    return is_full, counter, csv_line_util
Example #22
0
def main():

    global mode
    global users_docID
    global users_data
    global roles

    print("Mode before processing input")
    print(mode)

    if(len(sys.argv) != 2):
        print("Please use -D to indicate a dry-run of the program and -M for the actual run which will modify the database.")
        return
    elif (sys.argv[1] == "-D"):
        print("Executing program in dry-run mode. Database will not be modified.")
        mode = DRY_RUN
    elif (sys.argv[1] == "-M"):
        print("Executing program in modify mode. Database will be modified.")
        mode = MODIFY
    else:
        print("Please use -D to indicate a dry-run of the program and -M for the actual run which will modify the database.")
        return

    print("Mode after processing input")
    print(mode)
    # return
    # get the google sheet service
    service = get_service()
    # get all the values into a 2d array 
    values_mentor = get_sheet(service, mentor_sheet_id, mentor_range)
    values_event = get_sheet(service, event_sheet_id, event_range)

    # start firebase and get access to the databse
    firebase_admin.initialize_app()
    db = firestore.client()  
    
    roles = getEnumMap("roles", db)

    print(roles)
    return
    print(event_start)
    print(mentor_start)

    processed_mentor_pts = 0
    processed_events_pts = 0

    ## ISSUE: Change update_** method calls to store retunred row value and write that down in the config file.

    print("\n\nWORKING WITH MENTOR POINTS SHEET\n\n")
    # if(len(values_mentor) > 0 and not populate_users_mentor(values_mentor, db)):
    if(len(values_mentor) > 0 and not populate_users("mentor", values_mentor, mentor_start, 1, 2, 3, db) and not populate_users("mentor", values_mentor, mentor_start, 4, 5, 6, db)):
        print("\n\nPROCESSING MENTOR POINTS SHEET\n\n")
        processed_mentor_pts = update_mentor_event(values_mentor, db)
    
    
    print("\n\nWORKING WITH EVENT POINTS SHEET\n\n")
    # if(len(values_event) > 0 and not populate_users_event(values_event, db)):
    if(len(values_event) > 0 and not populate_users("event", values_event, event_start, 3, 1, 2, db)):
        print("\n\nPROCESSING EVENT POINTS SHEET\n\n")
        processed_events_pts = update_event(values_event, db)
    

    for key, value in users_data.items():
        value['induction_points'] = firestore.Increment(value['induction_points'])
        value['officer_signs'] = firestore.ArrayUnion(list(value['officer_signs']))
        if mode == MODIFY:
            db.collection(u'users').document(key).update(value)
        elif mode == DRY_RUN:
            print("\nUpdating document with id " + key + " with following data:")
            print(value)

    # This is the only crazy and stupid way I can think of to rewrite the env file
    # If you found any other way please use them.
    # This way works if you have exactly these 5 fields.
    starting_index = event_range.replace('Sheet1!A','')
    starting_index = starting_index.replace(':K', '')
    starting_index_mentor = mentor_range.replace('Sheet1!A','')
    starting_index_mentor = starting_index_mentor.replace(':G', '')

    ## ISSUE: Update range value that gets written down to config file.
    lines = ['EVENT_SHEET_ID="'+event_sheet_id+'"\n', 'MENTOR_SHEET_ID="'+mentor_sheet_id+'"\n',
            'GOOGLE_APPLICATION_CREDENTIALS="'+cred+'"\n', 
            'EVENT_RANGE="Sheet1!A'+str(processed_events_pts+int(event_start))+':L"\n', 
            'MENTOR_RANGE="Sheet1!A'+str(processed_mentor_pts+int(mentor_start))+':I"\n']
    with open('config.env', 'w') as f:
        f.writelines(lines)