def instantiate_objects():
    """After connection has been made, instatiate the various robot objects
    """

    global perm_dir_path
    global dir_path

    logger.debug('instantiate_objects called')
    #get default json file
    def_start_protocol = FileIO.get_dict_from_json(
        os.path.join(dir_path, 'data/default_startup_protocol.json'))
    #FileIO.get_dict_from_json('/home/pi/PythonProject/default_startup_protocol.json')

    #instantiate the head
    head = Head(def_start_protocol['head'], publisher, perm_dir_path)
    logger.debug('head string: ')
    logger.debug(str(head))
    logger.debug('head representation: ')
    logger.debug(repr(head))
    #use the head data to configure the head
    head_data = {}
    head_data = prot_dict['head']  #extract the head section from prot_dict

    logger.debug("Head configured!")

    #instantiate the script keeper (sk)

    #instantiate the deck
    deck = Deck(def_start_protocol['deck'], publisher, perm_dir_path)
    logger.debug('deck string: ')
    logger.debug(str(deck))
    logger.debug('deck representation: ')
    logger.debug(repr(deck))

    runner = ProtocolRunner(head, publisher)

    #use the deck data to configure the deck
    deck_data = {}
    deck_data = prot_dict['deck']  #extract the deck section from prot_dict
    #    deck = RobotLib.Deck({})        #instantiate an empty deck
    deck.configure_deck(deck_data)  #configure the deck from prot_dict data
    logger.debug("Deck configured!")

    #do something with the Ingredient data
    ingr_data = {}
    ingr_data = prot_dict[
        'ingredients']  #extract the ingredient section from prot_dict
    ingr = Ingredients({})

    ingr.configure_ingredients(
        ingr_data)  #configure the ingredienets from prot_dict data
    logger.debug('Ingredients imported!')

    publisher.set_head(head)
    publisher.set_runner(runner)
    subscriber.set_deck(deck)
    subscriber.set_head(head)
    subscriber.set_runner(runner)
def delete_ingredient():
    if request.method == 'POST':
        name = request.form['ingredient-name']

        ingredients_instance = Ingredients()
        ingredients_instance.delete_ingredient(name)
        return redirect('/ingredients')
    else:
        return render_template('delete_ingredient.html')
def instantiate_objects():
    """After connection has been made, instatiate the various robot objects
    """

    global perm_dir_path
    global dir_path

    #get default json file
    def_start_protocol = FileIO.get_dict_from_json(os.path.join(dir_path,'data/default_startup_protocol.json'))
    #FileIO.get_dict_from_json('/home/pi/PythonProject/default_startup_protocol.json')


    #instantiate the head
    head = Head(def_start_protocol['head'], publisher, perm_dir_path)
    #use the head data to configure the head
    head_data = {}
    head_data = prot_dict['head']   #extract the head section from prot_dict


    #instantiate the script keeper (sk)


    #instantiate the deck
    deck = Deck(def_start_protocol['deck'], publisher, perm_dir_path)


    runner = ProtocolRunner(head, publisher)


    #use the deck data to configure the deck
    deck_data = {}
    deck_data = prot_dict['deck']   #extract the deck section from prot_dict
    #    deck = RobotLib.Deck({})        #instantiate an empty deck
    deck.configure_deck(deck_data)  #configure the deck from prot_dict data


    #do something with the Ingredient data
    ingr_data = {}
    ingr_data = prot_dict['ingredients'] #extract the ingredient section from prot_dict
    ingr = Ingredients({})

    ingr.configure_ingredients(ingr_data) #configure the ingredienets from prot_dict data


    publisher.set_head(head)
    publisher.set_runner(runner)
    subscriber.set_deck(deck)
    subscriber.set_head(head)
    subscriber.set_runner(runner)
Beispiel #4
0
    def __init__(self, pizza_lines):
        self.ingredients = Ingredients(pizza_lines)

        self.r, self.c = self.ingredients.shape

        self._dict = {}
        self._map = np.full((self.r, self.c), -1)
        self._map_can_increase = np.full((self.r, self.c, 4), False)
        self._map_can_increase[:, :-1, Direction.right.value] = True
        self._map_can_increase[:-1, :, Direction.down.value] = True
        self._map_can_increase[:, 1:, Direction.left.value] = True
        self._map_can_increase[1:, :, Direction.up.value] = True

        self.huge_slice = Slice(0, 0, self.r - 1, self.c - 1)
Beispiel #5
0
def instantiate_objects():
    """After connection has been made, instatiate the various robot objects
    """
    FileIO.log('instantiate_objects called')
    #get default json file
    def_start_protocol = FileIO.get_dict_from_json(os.path.join(dir_path,'data/default_startup_protocol.json'))
    #FileIO.get_dict_from_json('/home/pi/PythonProject/default_startup_protocol.json')


    #instantiate the head 
    head = Head(def_start_protocol['head'], publisher)
    if debug == True:
        FileIO.log('head string: ', str(head))
        FileIO.log('head representation: ', repr(head))
    #use the head data to configure the head
    head_data = {}
    head_data = prot_dict['head']   #extract the head section from prot_dict
    #    head = RobotLib.Head({})        #instantiate an empty head
    #head.configure_head(head_data)  #configure the head from prot_dict data
    if debug == True:
        FileIO.log ("Head configured!")


    #instantiate the script keeper (sk)
    the_sk = ScriptKeeper(publisher)


    #instantiate the deck
    deck = Deck(def_start_protocol['deck'], publisher)
    if debug == True:
        FileIO.log('deck string: ', str(deck))
        FileIO.log('deck representation: ', repr(deck))


    runner = ProtocolRunner(head, publisher)

    
    #use the deck data to configure the deck
    deck_data = {}
    deck_data = prot_dict['deck']   #extract the deck section from prot_dict
    #    deck = RobotLib.Deck({})        #instantiate an empty deck
    deck.configure_deck(deck_data)  #configure the deck from prot_dict data
    if debug == True:
        FileIO.log ("Deck configured!")


    #do something with the Ingredient data
    ingr_data = {}
    ingr_data = prot_dict['ingredients'] #extract the ingredient section from prot_dict
    ingr = Ingredients({}) 
    
    ingr.configure_ingredients(ingr_data) #configure the ingredienets from prot_dict data
    if debug == True:
        FileIO.log('Ingredients imported!')
        FileIO.log('this is a test') 


    publisher.set_head(head)
    publisher.set_runner(runner)
    subscriber.set_deck(deck)
    subscriber.set_head(head)
    subscriber.set_runner(runner)


    @asyncio.coroutine
    def periodically_send_ip_addresses():
        """Coroutine that periodically sends information to browser
        """
        if debug == True and verbose == True: FileIO.log('periodically_send_ip_addresses called')
        while True:
            if debug == True and verbose == True: FileIO.log('periodically_send_ip_addresses again...')
            yield from asyncio.sleep(2)
            stuff = yield from sk.per_data()
            session_factory._myAppSession.publish('com.opentrons.robot_to_browser_ctrl',json.dumps(stuff,sort_keys=True,indent=4,separators=(',',': ')))


    asyncio.Task(periodically_send_ip_addresses())
Beispiel #6
0
    def find(self, key):
        if key in self.s:
            return self.s[key]
        else:
            return key


with open('gamefiles/GameDataClient.json') as f:
    gdc = json.loads(f.read())
with open('gamefiles/GameDataWrapper.json') as f:
    gdw = json.loads(f.read())
with open('gamefiles/strings.json') as f:
    s = Strings(json.loads(f.read()))

print('===== Spells =====')
spells = Spells(gdc, gdw, s)
spells.extract()
print('\n\n\n===== Foundables =====')
foundables = Foundables(gdc, gdw, s)
print('\n\n\n===== Potions =====')
potions = Potions(gdc, gdw, s)
print('\n\n\n===== Runestones =====')
runestones = Runestones(gdc, gdw, s)
print('\n\n\n===== Ingredients =====')
ingredients = Ingredients(gdc, gdw, s)
print('\n\n\n===== Encounters =====')
encounters = Encounters(gdc, gdw, s)

# TODO: proto_vaultcategory_food
# TODO: proto_vaultcategory_selfieavatar
def ingredients():
    ingredients_instance = Ingredients()
    data = ingredients_instance.get_ingredients()
    return render_template('ingredients.html', ingredients=data)
Beispiel #8
0
class Recipe:
    def __init__(self, recipe_lines, id, collection):
        # Print to console if we see this
        if len(recipe_lines) < 2:
            print(recipe_lines)
            return None

        # Parse out the recipe title
        self.title = string.capwords(recipe_lines[0].strip())
        self.slug = slug(self.title)
        self.id = id
        self.recipe_id = f"RECIPE#{id}"
        recipe_lines.pop(0)

        self.collection = collection
        if self.collection is not None:
            self.collection_to_recipe_mapping, self.recipe_to_collection_mapping = collection.add_recipe(
                self)
        else:
            print(f"recipe {self.title} has no collection")

        # Parse out the recipe author if present
        if recipe_lines[0].strip() != "":
            self.author = recipe_lines[0].strip()
            recipe_lines.pop(0)
        else:
            self.author = None

        # initialize our content
        self.ingredients_class = None
        self.instructions_class = None
        self.summary = ""

        # Label lines based on the content they contain
        raw_content = []
        for line in recipe_lines:
            line = line.strip()

            if line == "":
                raw_content.append(("BLANK", line))
            elif re.search("^[*]", line):
                raw_content.append(("INGREDIENT", line.lstrip("*").strip()))
            elif re.search("^\d", line):
                raw_content.append(
                    ("STEP", line.lstrip("0123456789.").strip()))
            else:
                raw_content.append(("TEXT", line))

        # Add extra value to array so that we capture all elements of the list and at least have one element
        raw_content.insert(0, ("BLANK", ""))
        raw_content.append(("BLANK", ""))

        # Save the contents of each line to the proper variable
        prev_type, prev_content = None, None

        try:
            for curr_type, curr_content in raw_content:
                # If there was a subsection header on the ingredient block, add it to the list
                if prev_type == "TEXT" and curr_type == "INGREDIENT":
                    if self.ingredients_class is None:
                        self.ingredients_class = SplitIngredients()
                    self.ingredients_class.set_section_title(
                        string.capwords(prev_content).strip(":"))

                # Add ingredient to the list
                if curr_type == "INGREDIENT":
                    if self.ingredients_class is None:
                        self.ingredients_class = Ingredients()
                    self.ingredients_class.add_ingredient(
                        format_ingredient(curr_content))

                # If there was a subsection header on the steps block, add it to the list
                if prev_type == "TEXT" and curr_type == "STEP":
                    if self.instructions_class is None:
                        self.instructions_class = SplitSteps()
                    self.instructions_class.set_section_title(
                        string.capwords(prev_content).strip(":"))

                # Add step to the list
                if curr_type == "STEP":
                    if self.instructions_class is None:
                        self.instructions_class = Steps()
                    self.instructions_class.add_instruction(curr_content)

                # Adding text to the summary
                if prev_type == "TEXT" and (curr_type != "INGREDIENT"
                                            and curr_type != "STEP"):
                    self.summary = self.summary + prev_content

                # Setting the values for the next run through the loop
                prev_type, prev_content = curr_type, curr_content
        except AttributeError as err:
            print(f"Error parsing recipe: {err}")
            print(recipe_lines)
            raise

        self.dynamo_dict = {
            "PutRequest": {
                "Item": {
                    "PK": {
                        "S": self.recipe_id
                    },
                    "SK": {
                        "S": self.recipe_id
                    },
                    "id": {
                        "N": self.id
                    },
                    "name": {
                        "S": self.title
                    },
                    "slug": {
                        "S": self.slug
                    },
                    "author": {
                        "M": {
                            "name": {
                                "S": self.author
                            }
                        }
                    },
                    "description": {
                        "S": self.summary
                    },
                    "ingredients":
                    self.ingredients_class.get_json()
                    if self.ingredients_class is not None else None,
                    "instructions":
                    self.instructions_class.get_json()
                    if self.instructions_class is not None else None
                }
            }
        }

    def get_dynamo_dictionaries(self):
        return [
            self.dynamo_dict, self.collection_to_recipe_mapping,
            self.recipe_to_collection_mapping
        ]
Beispiel #9
0
def get_recipe(url, use_filter):
    # target Binging with Babish video
    transcript = YouTubeTranscriptApi.get_transcript(url)

    # Get verbs from db
    verbs = []
    with open("../../datasets/cooking_verbs.txt", 'r') as verb_file:
        verbs = verb_file.readlines()

    # ingredient extraction ============================
    db = Ingredients()
    ingreds = set([])
    actual_ingredients = []
    res = {}
    i = 0
    print('>>> Getting ingredients')
    for subtitle in transcript:
        i += 1
        text = subtitle['text']
        cur_ingredients = db.parse_ingredients(text)
        measurements = db.parse_measurements(text)
        if len(cur_ingredients) > 0:
            print('>>> Ingredients from line ' + str(i) + ': ')
            print(cur_ingredients)
        ingreds |= set(cur_ingredients)
        actual_ingredients += get_actual_ingredients(cur_ingredients,
                                                     measurements)

    print('>>> Ingredients detected: ')
    print(actual_ingredients)
    res['ingredients'] = actual_ingredients
    # ==================================================
    video_file = download_video(url)

    # steps extraction =================================
    times = ['seconds', 'minutes', 'hours', 'second', 'minute', 'hour']
    instructions = []
    pictures = []
    if use_filter:
        print('>>> Generating steps')
        i = 0
        for subtitle in transcript:
            text = subtitle['text']

            # Write all lines
            # with open('before_filter.txt', 'a') as before_file:
            #     before_file.write(text + '\n')

            # Remove lines without an ingredient, cooking verb, or time measurement
            for target in (list(ingreds) + verbs):
                if (target in text or len([t for t in times if (t in text)])):
                    instructions.append({'step': text})
                    if i % PICTURE_FREQUENCY == 0:
                        pictures.append(subtitle['start'])
                    print('>>> KEEPING LINE: ' + text)
                    # with open('after_filter.txt', 'a') as after_file:
                    #     after_file.write(text + '\n')
                    #     break
                    i += 1
                    break
    res['instructions'] = instructions
    print('>>> Steps Generation Complete')
    # ==================================================

    # frames extraction ================================
    print('>>> Extracting Frames...')
    file_names = extract_frames(video_file, pictures)
    i = 0
    for file_name in file_names:
        res['instructions'][i]['image'] = file_name
        i += PICTURE_FREQUENCY
    if os.path.exists(video_file):
        os.remove(video_file)
    # ==================================================
    print('>>> finished. result: ')
    print(res)
    return res