Esempio n. 1
0
def add_category(
    post
):  #this function is used to show the category of the images using clarifai api
    app = ClarifaiApp(api_key=API_KEY)
    model = app.models.get("general-v1.3")
    response = model.predict_by_url(url=post.image_url)

    if response["status"]["code"] == 10000:
        if response["outputs"]:
            if response["outputs"][0]["data"]:
                if response["outputs"][0]["data"]["concepts"]:
                    for index in range(
                            0,
                            len(response["outputs"][0]["data"]["concepts"])):
                        category = CategoryModel(
                            post=post,
                            category_text=response["outputs"][0]["data"]
                            ["concepts"][index]["name"])
                        category.save()
                else:
                    print "No Concepts List Error"
            else:
                print "No Data List Error"
        else:
            print "No Outputs List Error"
    else:
        print "Response Code Error"
Esempio n. 2
0
 def __init__(self):
     """ Initialize """
     # initialize the treeview
     CommonTreeView.__init__(self)
     # setup the column
     self.cat_column = gtk.TreeViewColumn(_("Categories"),
                                          gtk.CellRendererText(),
                                          markup=C_ITEM["short_name"])
     self.append_column(self.cat_column)
     self.cat_column.set_visible(True)
     self.cat_column.set_expand(True)
     self.count_column = gtk.TreeViewColumn(_("# pkgs"),
                                            gtk.CellRendererText(),
                                            markup=C_ITEM["count"])
     self.append_column(self.count_column)
     self.count_column.set_visible(True)
     self.count_column.set_expand(False)
     # setup the model
     self.model = CategoryModel()
     self.set_model(self.model)
     # connect to clicked event
     self.last_category = None
     self.connect("cursor-changed", self._clicked)
     # register default callback
     self.register_callback()
     self.search_cat = False
     debug.dprint("VIEWS: Category view initialized")
Esempio n. 3
0
    def add_category(self, category: Category) -> Category:
        """
        Add new category
        :param category: Category(dataclass)
        :return: new category
        """
        category.name = category.name.lower()
        if category.parent_id is not None and self.__get_category_model_by_id(
                category.parent_id) is None:
            raise CategoryIdDoesNotExist()

        if self.__get_category_model_by_name(category.name) is not None:
            raise CategoryAlredyExist()

        new_category = CategoryModel(name=category.name, user_id=self.user_id)
        self.session.add(new_category)
        self.session.commit()

        new_level_category = LevelCategoryModel(parent_id=category.parent_id,
                                                children_id=new_category.id)
        self.session.add(new_level_category)
        self.session.commit()
        return Category(id=new_category.id,
                        name=new_category.name,
                        parent_id=category.parent_id)
Esempio n. 4
0
def add_category(post):
    app = ClarifaiApp(api_key=CLARIFAI_API_KEY)

    # Logo model

    model = app.models.get('logo')
    response = model.predict_by_url(url=post.image_url)

    if response["status"]["code"] == 10000:

        if response["outputs"]:

            if response["outputs"][0]["data"]:

                if response["outputs"][0]["data"]["regions"]:

                    if response["outputs"][0]["data"]["regions"][0]["data"]:

                        for index in range(
                                0,
                                len(response["outputs"][0]["data"]["regions"]
                                    [0]["data"]["concepts"])):
                            category = CategoryModel(
                                post=post,
                                category_text=response["outputs"][0]["data"]
                                ["regions"][0]["data"]["concepts"][index]
                                ["name"])
                            category.save()

                    else:
                        print "No concepts list error."

                else:
                    print "No concepts list error."

            else:
                print "No data list error."

        else:
            print "No output lists error."

    else:
        print "Response code error."
Esempio n. 5
0
def add_category(post):
    app = ClarifaiApp(api_key='c0d6dcc72a5f490b8a1f0df33bf2f272')
    model = app.models.get("general-v1.3")
    response = model.predict_by_url(url=post.image_url)
    if response["status"]["code"] == 10000:
        if response["outputs"]:
            if response["output"][0]["data"]:
                if response["output"][0]["data"]["concepts"]:
                    for index in range(
                            0,
                            len(response["outputs"][0]["data"]["concepts"])):
                        category = CategoryModel(
                            post=post,
                            category_text=response['outputs'][0]['data']
                            ['concepts'][index]['name'])
                        category.save()
                else:
                    print 'no concepts error'
            else:
                print 'no data list error'
        else:
            print 'no outtput list error'
    else:
        print 'response code error'
Esempio n. 6
0
def category_view(post):
    app = ClarifaiApp(api_key=clarify_api_key)
    model = app.models.get("General-v1.3")
    response = model.predict_by_url(url=post.image_url)
    if response["status"]["code"] == 10000:
        if response["outputs"]:
            if response["outputs"][0]["data"]:
                if response["outputs"][0]["data"]["concepts"]:
                    for index in range(
                            0,
                            len(response["outputs"][0]["data"]["concepts"])):
                        category = CategoryModel(
                            post=post,
                            category=response["outputs"][0]["data"]["concepts"]
                            [0]["name"])
                        category.save()
                else:
                    print "No concepts List Error"
            else:
                print "No Data List Error"
        else:
            print "No Outputs List Error"
    else:
        print "Response Code Error"
Esempio n. 7
0
    def mutate(root, info, id, title, content, category, tags, excerpt):
        """
        Create the new post
        :param root: the root information
        :param info: information about the request
        :param id: the id corresponds to the post
        :param title: title of the post
        :param content: content of the post (in Markdown format)
        :param category: category of the post
        :param tags: a list of tags of the post
        :param excerpt: brief description about the post.
        :return: the new post, or None
        """
        viewer = root.get("viewer")
        if not viewer or not viewer.isAdmin:
            raise GraphQLError("Permission denied")
        else:
            if id is None:
                post = PostModel()
            else:
                print("id", relay.Node.get_node_from_global_id(info, id))
                post = relay.Node.get_node_from_global_id(info, id)

            tags = set(tags)  # remove duplicate tags
            if title == "" or content == "" or category == "" or "" in tags:
                raise GraphQLError("Missing required fields")
            post.category = Category.get_query(info).filter_by(
                name=category).first() or CategoryModel(name=category)
            post.tags = [
                Tag.get_query(info).filter_by(name=tag).first()
                or TagModel(name=tag) for tag in tags
            ]
            post.title = title
            post.content = content
            post.publishDate = post.publishDate or datetime.datetime.utcnow()
            post.lastUpdateDate = datetime.datetime.utcnow()
            post.author = viewer
            post.excerpt = excerpt

            db_session.add(post)
            db_session.commit()
            return SetPost(post=post)
Esempio n. 8
0
 def mutate(cls, _, args, context, info):
     category = CategoryModel(name=args.get('name'))
     db_session.add(category)
     db_session.commit()
     ok = True
     return createCategory(category=category, ok=ok)
Esempio n. 9
0
class CategoryView(CommonTreeView):
    """ Self contained treeview to hold categories """
    def __init__(self):
        """ Initialize """
        # initialize the treeview
        CommonTreeView.__init__(self)
        # setup the column
        self.cat_column = gtk.TreeViewColumn(_("Categories"),
                                             gtk.CellRendererText(),
                                             markup=C_ITEM["short_name"])
        self.append_column(self.cat_column)
        self.cat_column.set_visible(True)
        self.cat_column.set_expand(True)
        self.count_column = gtk.TreeViewColumn(_("# pkgs"),
                                               gtk.CellRendererText(),
                                               markup=C_ITEM["count"])
        self.append_column(self.count_column)
        self.count_column.set_visible(True)
        self.count_column.set_expand(False)
        # setup the model
        self.model = CategoryModel()
        self.set_model(self.model)
        # connect to clicked event
        self.last_category = None
        self.connect("cursor-changed", self._clicked)
        # register default callback
        self.register_callback()
        self.search_cat = False
        debug.dprint("VIEWS: Category view initialized")

    def set_search(self, option):
        self.search_cat = option
        if option == True:
            self.cat_column.set_title(_("Search History"))
        elif option == False:
            self.cat_column.set_title(_("Categories"))

    def register_callback(self, category_changed=None):
        """ Register callbacks for events """
        self._category_changed = category_changed

    def _clicked(self, treeview, *args):
        """ Handle treeview clicks """
        model, iter = treeview.get_selection().get_selected()
        if iter: category = model.get_value(iter, C_ITEM["full_name"])
        else: category = self.last_category
        # has the selection really changed?
        if category != self.last_category:
            debug.dprint("VIEWS: category change detected")
            # then call the callback if it exists!
            if self._category_changed:
                self.last_category = category
                self._category_changed(category)
        # save current selection as last selected
        self.last_category = category

    def populate(self, categories, _sort=True, counts=None):
        """Fill the category tree."""
        self.clear()
        #debug.dprint("VIEWS: Populating category view; categories: " + str(categories))
        last_full_names = []
        if _sort:
            categories.sort()
            #debug.dprint("VIEWS: Sorted categories: " + str(categories))
        if self.search_cat == True:
            self.populate_search(categories, counts)
            return
        #set parent_iter to top level
        parent_iter = [None]
        for cat in categories:
            #debug.dprint(" VIEWS: CategoryView.populate():107 cat: %s" %cat)
            if cat:  # != 'virtual':
                cat_split = cat.split("-")
                max_level = len(cat_split) - 1
                for i in range(len(cat_split)):
                    #debug.dprint(" VIEWS: CategoryView.populate():112 i = " + str(i) + ' ' + str(range(len(cat_split))))
                    # determine the full_name to this level, default to minimum first part of possible split
                    full_name = '-'.join(cat_split[:i + 1] or cat_split[0])
                    if i < max_level:
                        # add parent/subparent row
                        len_full_names = len(last_full_names)
                        #debug.dprint(" VIEWS: CategoryView.populate():i<max_level 117 i = " +str(i) +" new full_name = " + full_name +' >> ' + str(last_full_names) + str(len_full_names))
                        if len_full_names > i and last_full_names[
                                i] == full_name:
                            #debug.dprint(" VIEWS: CategoryView.populate():i<max_level 119 matching full_name...continuing")
                            continue  # skip to the next level
                        # delete any previous deeper levels
                        if i > 0:
                            #debug.dprint(" VIEWS: CategoryView.populate():i>0:123 new parent/sub-parent... truncating parent_iter and flast_full_names")
                            parent_iter = parent_iter[:i + 1]
                            last_full_names = last_full_names[:i]
                            #debug.dprint(" VIEWS: CategoryView.populate():i>0:126 full_name, >> = " + full_name +' >> ' + str(last_full_names[i]))
                        else:
                            #debug.dprint(" VIEWS: CategoryView.populate() i=0:128:resetting parent_iter and last_full_names from: " + str(last_full_names))
                            parent_iter = [None]
                            last_full_names = []
                            #debug.dprint(" VIEWS: CategoryView.populate()i=0:131 reset last_full_names from: " + str(last_full_names))
                        #debug.dprint(" VIEWS: CategoryView.populate(): 132 adding parent/subparent category: " + cat_split[i])
                        last_full_names.append(full_name)
                        #debug.dprint(" VIEWS: CategoryView.populate():134 parent_iter = " +str(parent_iter))
                        parent_iter.append(
                            self.model.insert_before(parent_iter[i], None))
                        #debug.dprint(" VIEWS: CategoryView.populate():136 new parent_iter = " +str(parent_iter))
                        #debug.dprint(" VIEWS: CategoryView.populate(): 137 added parent category, path = " +str(
                        #                                self.model.get_path(parent_iter[i+1])))
                        self.model.set_value(parent_iter[i + 1],
                                             C_ITEM["short_name"],
                                             cat_split[i])
                        self.model.set_value(
                            parent_iter[i + 1], C_ITEM["full_name"],
                            None)  #last_full_names[i]) # needed?
                        #debug.dprint(" VIEWS: CategoryView.populate(): 141 added parent to last_full_names: " + str(last_full_names))
                        self.model.set_value(parent_iter[i + 1],
                                             C_ITEM["count"], str(0))
                    else:  # last one, short_name, i == max_level
                        # child row
                        #debug.dprint(" VIEWS: CategoryView.populate(): i = " + str(i) + " 161 end child row '"+ cat_split[i] + "' for: " + full_name)
                        #debug.dprint(" VIEWS: CategoryView.populate():162 parent_iter = " +str(parent_iter))
                        parent_iter = parent_iter[:i + 1]
                        last_full_names.append(full_name)
                        parent_iter.append(
                            self.model.insert_before(parent_iter[i], None))
                        #debug.dprint(" VIEWS: CategoryView.populate():166 added end child category path = " +str(
                        #                               self.model.get_path(parent_iter[i+1])))
                        #debug.dprint(" VIEWS: CategoryView.populate():168 parent_iter = " +str(parent_iter))
                        self.model.set_value(parent_iter[i + 1],
                                             C_ITEM["short_name"],
                                             cat_split[i])
                        self.model.set_value(parent_iter[i + 1],
                                             C_ITEM["full_name"], full_name)
                        if counts != None:  # and counts[cat] != 0:
                            #debug.dprint("VIEWS: Counts: %s = %s" %(cat, str(counts[cat])))
                            self.model.set_value(parent_iter[i + 1],
                                                 C_ITEM["count"],
                                                 str(counts[cat]))
                            path = self.model.get_path(parent_iter[i + 1])
                            p = i
                            while p > 0:
                                path = path[:p]
                                #debug.dprint(" VIEWS: CategoryView.populate(): 178 update parent counts path = "+str(path))
                                iter = self.model.get_iter(path)
                                prev_count = self.model.get_value(
                                    iter, C_ITEM["count"])
                                #debug.dprint(" VIEWS: CategoryView.populate(): 181 p = "+str(p)+" prev_count = "+str(prev_count)+" new count = " + str(counts[cat]) +" new parent total = " +str(counts[cat]+int(prev_count)))
                                self.model.set_value(
                                    iter, C_ITEM["count"],
                                    str(counts[cat] + int(prev_count)))
                                p -= 1

    def populate_search(self, categories, counts):
        debug.dprint("VIEWS: populating category view with search history")
        for string in categories:
            iter = self.model.insert_before(None, None)
            self.model.set_value(iter, C_ITEM["short_name"], string)
            self.model.set_value(iter, C_ITEM["full_name"], string)
            if counts != None:  # and counts[string] != 0:
                #debug.dprint("VIEWS: Counts: %s = %s" %(cat, str(counts[string])))
                self.model.set_value(iter, C_ITEM["count"],
                                     str(counts[string]))
Esempio n. 10
0
         'title': 'Рис с овощами, свининой и шампиньонами с соусом удон',
         'price': '320',
         'description': 'Рис, морковь, цукини, перец болгарский, китайская капуста, шампиньоны, свинина, кунжут, соус удон',
         'picture': 'dish24.jpeg',
         'category_id': '5'},
        {'id': '25',
         'title': 'Пицца Четыре сыра классическая',
         'price': '559',
         'description': 'Моцарелла, Сливочный пицца-соус, Сыр Дор Блю, Сыр пармезан, Сыр Чеддер',
         'picture': 'dish25.jpeg',
         'category_id': '3'}]

cat = {'1': 'Суши/роллы', '2': 'Стрит фуд', '3': 'Пица', '4': 'Паста', '5': 'Новинки'}

for index, value in cat.items():
    cat = CategoryModel()
    cat.id = index
    cat.title = value
    db.session.add(cat)
db.session.commit()

for m in data:
    meal = MealModel()
    meal.title = m['title']
    meal.price = m['price']
    meal.description = m['description']
    meal.picture = 'pictures/' + m['picture']
    meal.category = db.session.query(CategoryModel).get(m['category_id'])
    db.session.add(meal)
    db.session.commit()