Example #1
0
    def __init__(self,
                 source_content_dir,
                 destination_content_dir,
                 template_dir,
                 language
                 ):
        if not source_content_dir:
            raise ValueError('source_content_dir must not be None!')
        if not destination_content_dir:
            raise ValueError('destination_content_dir must not be None!')
        if not template_dir:
            raise ValueError('template_dir must not be None!')

        self.source_content_dir = source_content_dir
        self.destination_content_dir = destination_content_dir
        self.theme_dir = os.path.join(source_content_dir, 'theme')
        self.template_dir = template_dir
        self.language = language

        print('--------- [Generator] Getting templates')
        self.templates = self.get_templates()
        print('[Generator] Acquired %s templates' % (str(len(self.templates))))

        print('--------- [Generator] Getting css styles')
        self.styles = self.get_styles()
        print('[Generator] Acquired %s css styles' % (str(len(self.styles))))

        print('--------- [Generator] Getting categories')
        self.root_category = Category(self.source_content_dir)

        print('--------- [Generator] Getting navigation')
        Navigation(self.root_category)

        print('--------- [Generator] Rendering')
        self.render()
Example #2
0
 def __init__(self):
     self.data_loaded = False
     self.category = Category()
     self.product = Product()
     self.cat_list = None
     self.categories = None
     self.product_name = None
     self.nutriscore = None
     self.stores = None
     self.url = None
Example #3
0
 def __init__(self):
     self.cls()
     self.api = OffApiData()
     self.database = DB()
     self.category = Category()
     self.product = Product()
     self.substitute = Substitute()
     self.return_menu = False
     self.keep_run = True
     self.menu_launch()
     self.dict_cat = None
     self.list_cat_nbr = None
     self.checked_input = None
     self.selected_cat = None
     self.selected_prod = None
Example #4
0
 def __init__(
     self,
     product_id=None,
     product_name=None,
     nutrition_grade=None,
     stores=None,
     url=None,
     cat_name=None,
 ):
     self.database = Database()
     self.product_id = product_id
     self.product_name = product_name
     self.nutrition_grade = nutrition_grade
     self.stores = stores
     self.url = url
     self.cat_name = cat_name
     self.category = Category()
     self.data_loaded = None
     self.checked_input = None
     self.selected_prod_id = None
     self.available_alt = None
     self.id_alternative_product = None
Example #5
0
 def __init__(self):
     self.database = Database()
     self.product = Product()
     self.category = Category()
     self.alt_saved = None
Example #6
0
class OffApiData():
    """
    This class represents the data extracted from the OFF API
    """
    def __init__(self):
        self.data_loaded = False
        self.category = Category()
        self.product = Product()
        self.cat_list = None
        self.categories = None
        self.product_name = None
        self.nutriscore = None
        self.stores = None
        self.url = None

    def get_info(self):
        """
        Get the information we need from the OFF API
        """
        self.get_categories()
        self.get_products()

    def get_categories(self):
        """
        Sends a request to the OFF API to receive a list of categories
        """
        self.cat_list = []
        url_req_categories = (
            'https://fr.openfoodfacts.org/categories.json&limit=' +
            str(CONST.NBR_CAT + 1))
        self.categories = requests.get(url_req_categories)
        categories_json = json.loads(self.categories.content.decode('utf-8'))
        for each_cat in range(0, CONST.NBR_CAT):
            print("loading CATEGORY {} ".format(each_cat + 1))
            cat_name = categories_json["tags"][each_cat]["name"]
            self.cat_list.append(cat_name)
            self.category.insert_cat(cat_name)

    def get_products(self):
        """
        Sends a request to the OFF API to receive a list of products
        within a specific category
        """
        elem = str
        for cat_name in self.cat_list:
            for prod in range(0, CONST.NBR_PROD):
                products_url = (
                    "https://fr.openfoodfacts.org/cgi/search.pl"
                    "?action=process&tagtype_0=categories&tag_contains_0"
                    "=contains&tag_0=" + cat_name + '&json=true&page_size=' +
                    str(CONST.NBR_PROD) + '&page=1')
                products = requests.get(products_url)
                p_json = json.loads(products.content.decode('utf-8'))
                self.product_name = p_json["products"][prod]["product_name_fr"]
                if "nutriscore_grade" in p_json["products"][prod]:
                    self.nutriscore = p_json["products"][prod][
                        "nutriscore_grade"]
                self.stores = p_json["products"][prod]["stores"]
                self.url = p_json["products"][prod]["url"]
                self.product.insert_product(self.product_name, self.nutriscore,
                                            self.stores, self.url, cat_name)
        self.data_loaded = True
Example #7
0
class Menu:
    """
    The menu of this program
    """
    def __init__(self):
        self.cls()
        self.api = OffApiData()
        self.database = DB()
        self.category = Category()
        self.product = Product()
        self.substitute = Substitute()
        self.return_menu = False
        self.keep_run = True
        self.menu_launch()
        self.dict_cat = None
        self.list_cat_nbr = None
        self.checked_input = None
        self.selected_cat = None
        self.selected_prod = None

    def menu_launch(self):
        """
        Initializes the menu and execute actions based on user input
        """
        print(DISCLAIMER)
        if not self.api.data_loaded:
            print(INIT_NO_LOAD)
        while self.keep_run:
            if self.return_menu:
                print(MENU_RETURN)
                input()
                self.cls()
            print(MENU)
            checked_input = check_input([1, 2, 3, 4])
            self.user_menu_choice = checked_input.validated_input
            if self.user_menu_choice == 1 and self.api.data_loaded:
                self.menu_1_alternative()
            elif self.user_menu_choice == 2 and self.api.data_loaded:
                if self.substitute.alt_saved:
                    self.menu_2_display_alt()
                else:
                    print(SAVE_ALT_FIRST)
            elif self.user_menu_choice == 3:
                self.menu_3_load_db()
            elif self.user_menu_choice == 4:
                self.keep_run = False
            else:
                print(LOAD_FIRST)
        print("Thank you, have a nice day!")
        sys.exit()

    def menu_1_alternative(self):
        """
        Menu choice 1: find an alternative with a
        better nutrition grade and save it in DB
        """
        self.category.display_categories()
        print("\nPlease choose one category of product to find a substitute")
        self.category.ask_choose_cat()
        self.category.display_prod_from_cat(self.category.selected_cat_name)
        print("Please choose one product you wish to replace.")
        self.product.ask_choose_prod(self.category.selectionnable_prod)
        self.product.find_better_nutri(self.product.selected_prod_id,
                                       self.category.selected_cat_name)
        if self.product.available_alt is not None:
            self.substitute.save_alternative(
                self.product.selected_prod_id,
                self.product.id_alternative_product)
        self.return_menu = True

    def menu_2_display_alt(self):
        """
        Menu choice 2: Display the saved alternatives
        """
        self.substitute.display_alternative()
        self.return_menu = True

    def menu_3_load_db(self):
        """
        Menu choice 3: Load or reset the database
        """
        print("\nBeginning loading data\n")
        self.database.load_sql_file()
        self.api.get_info()
        print("\nDatabase loaded\n")
        self.return_menu = True

    @staticmethod
    def cls():
        """
        Used to clear the screen of the terminal
        """
        os.system('cls' if os.name == 'nt' else 'clear')
Example #8
0
class Generator():
    """Core class that generates the cook book."""
    def __init__(self,
                 source_content_dir,
                 destination_content_dir,
                 template_dir,
                 language
                 ):
        if not source_content_dir:
            raise ValueError('source_content_dir must not be None!')
        if not destination_content_dir:
            raise ValueError('destination_content_dir must not be None!')
        if not template_dir:
            raise ValueError('template_dir must not be None!')

        self.source_content_dir = source_content_dir
        self.destination_content_dir = destination_content_dir
        self.theme_dir = os.path.join(source_content_dir, 'theme')
        self.template_dir = template_dir
        self.language = language

        print('--------- [Generator] Getting templates')
        self.templates = self.get_templates()
        print('[Generator] Acquired %s templates' % (str(len(self.templates))))

        print('--------- [Generator] Getting css styles')
        self.styles = self.get_styles()
        print('[Generator] Acquired %s css styles' % (str(len(self.styles))))

        print('--------- [Generator] Getting categories')
        self.root_category = Category(self.source_content_dir)

        print('--------- [Generator] Getting navigation')
        Navigation(self.root_category)

        print('--------- [Generator] Rendering')
        self.render()

    def get_templates(self):
        """Loads and returns the template files."""
        env = jinja2.Environment(
            loader=FileSystemLoader(self.template_dir,
                                    encoding='windows-1252'),
            # autoescape=select_autoescape(['html', 'xml']),
            trim_blocks=True,
            lstrip_blocks=True
        )
        path_base = 'template_base.html'
        path_category = 'template_category.html'
        path_recipe = 'template_recipe.html'
        path_toc = 'template_toc.html'

        templates = {}
        templates['template_base'] = env.get_template(path_base)
        templates['template_category'] = env.get_template(path_category)
        templates['template_recipe'] = env.get_template(path_recipe)
        templates['template_toc'] = env.get_template(path_toc)
        return templates

    def get_styles(self):
        """Returns a list of css style file paths."""
        styles = []
        styles_dir = os.path.join(self.source_content_dir, 'theme', 'css')

        style_files = utility.io.get_file_names(styles_dir)
        for style_file in style_files:
            file_path = os.path.join(styles_dir, style_file)
            style_asset = Asset(file_path)
            styles.append(style_asset)
        return styles

    def get_style_urls(self, obj):
        """Returns a list of styles urls for use in template rendering.
        Parameters
        ---------
        obj : Asset or Category
          The object for which to get the urls.
        """
        path = obj.path

        if isinstance(obj, Category):
            path += '/index.html'

        style_urls = []
        for style in self.styles:
            url = get_url(path, style.path)
            style_urls.append({ 'url': url })
        return style_urls

    def render(self):
        """Renders the templates."""
        categories_toc = self.root_category.get_rendered_for_toc()
        categories_toc = lxml.html.tostring(categories_toc, pretty_print=True)
        categories_toc = categories_toc.decode(sys.getdefaultencoding())

        style_urls = self.get_style_urls(self.root_category)
        title = _('Table of Contents')
        titleimage = None   # TODO
        rendered_toc = self.templates['template_toc'].render(
                                        language = self.language,
                                        styles = style_urls,
                                        title = title,
                                        titleimage = titleimage,
                                        categories_toc = categories_toc)
        utility.io.ensure_dir(self.destination_content_dir)
        rendered_path = os.path.join(self.destination_content_dir,
                                     'index.html')
        with open(rendered_path, mode='wb') as outfile:
            outfile.write(rendered_toc.encode('utf-8'))

        # Copy theme dir.
        copy_tree(os.path.join(self.source_content_dir, 'theme'),
                  os.path.join(self.destination_content_dir, 'theme'))

        # Render categories, including their children and assets.
        for category in self.root_category.children:
            category.render(self, self.destination_content_dir)