示例#1
0
def wrap_with_abbreviation(abbr, text, syntax='html', profile='plain'):
    """
	Wraps passed text with abbreviation. Text will be placed inside last
	expanded element
	@param abbr: Abbreviation
	@type abbr: str
	
	@param text: Text to wrap
	@type text: str
	
	@param syntax: Document type (html, xml, etc.)
	@type syntax: str
	
	@param profile: Output profile's name.
	@type profile: str
	@return {String}
	"""
    tree_root = utils.parse_into_tree(abbr, syntax)
    pasted = False

    if tree_root:
        if tree_root.multiply_elem:
            # we have a repeating element, put content in
            tree_root.multiply_elem.set_paste_content(text)
            tree_root.multiply_elem.repeat_by_lines = pasted = True

        tree = utils.rollout_tree(tree_root)

        if not pasted:
            tree.paste_content(text)

        utils.apply_filters(tree, syntax, profile, tree_root.filters)
        return utils.replace_variables(tree.to_string())

    return None
示例#2
0
def wrap_with_abbreviation(abbr, text, syntax="html", profile="plain"):
    """
	Wraps passed text with abbreviation. Text will be placed inside last
	expanded element
	@param abbr: Abbreviation
	@type abbr: str
	
	@param text: Text to wrap
	@type text: str
	
	@param syntax: Document type (html, xml, etc.)
	@type syntax: str
	
	@param profile: Output profile's name.
	@type profile: str
	@return {String}
	"""
    tree_root = utils.parse_into_tree(abbr, syntax)
    pasted = False

    if tree_root:
        if tree_root.multiply_elem:
            # we have a repeating element, put content in
            tree_root.multiply_elem.set_paste_content(text)
            tree_root.multiply_elem.repeat_by_lines = pasted = True

        tree = utils.rollout_tree(tree_root)

        if not pasted:
            tree.paste_content(text)

        utils.apply_filters(tree, syntax, profile, tree_root.filters)
        return utils.replace_variables(tree.to_string())

    return None
示例#3
0
def apply_actions_on_image(session_id, action_stack, filename,
                           image_signature):
    action_stack = deepcopy(action_stack)

    # If we have arrived to the original image
    if len(action_stack) == 0:
        return im_pil0

    # Pop out the last action
    last_action = action_stack.pop()

    # Apply all the previous action_stack, and gets the image PIL
    im_pil = apply_actions_on_image(session_id, action_stack, filename,
                                    image_signature)
    im_size = im_pil.size

    # Apply the rest of the action_stack
    operation = last_action['operation']
    selectedData = last_action['selectedData']
    type = last_action['type']

    # Select using Lasso
    if selectedData and 'lassoPoints' in selectedData:
        selection_mode = 'lasso'
        selection_zone = generate_lasso_mask(im_pil, selectedData)
    # Select using rectangular box
    elif selectedData and 'range' in selectedData:
        selection_mode = 'select'
        lower, upper = map(int, selectedData['range']['y'])
        left, right = map(int, selectedData['range']['x'])
        # Adjust height difference
        height = im_size[1]
        upper = height - upper
        lower = height - lower
        selection_zone = (left, upper, right, lower)
    # Select the whole image
    else:
        selection_mode = 'select'
        selection_zone = (0, 0) + im_size

    # Apply the filters
    if type == 'filter':
        apply_filters(image=im_pil,
                      zone=selection_zone,
                      filter=operation,
                      mode=selection_mode)
    elif type == 'enhance':
        enhancement = operation['enhancement']
        factor = operation['enhancement_factor']

        apply_enhancements(image=im_pil,
                           zone=selection_zone,
                           enhancement=enhancement,
                           enhancement_factor=factor,
                           mode=selection_mode)

    return im_pil
示例#4
0
def expand_abbreviation(abbr, syntax='html', profile_name='plain'):
	"""
	Expands abbreviation into a XHTML tag string
	@type abbr: str
	@return: str
	"""
	tree_root = utils.parse_into_tree(abbr, syntax)
	if tree_root:
		tree = utils.rollout_tree(tree_root)
		utils.apply_filters(tree, syntax, profile_name, tree_root.filters)
		return utils.replace_variables(tree.to_string())
	
	return ''
示例#5
0
def expand_abbreviation(abbr, syntax='html', profile_name='plain'):
	"""
	Expands abbreviation into a XHTML tag string
	@type abbr: str
	@return: str
	"""
	tree_root = utils.parse_into_tree(abbr, syntax)
	if tree_root:
		tree = utils.rollout_tree(tree_root)
		utils.apply_filters(tree, syntax, profile_name, tree_root.filters)
		return utils.replace_variables(tree.to_string())
	
	return ''
示例#6
0
    def generic_post_list_renderer(self, lang, posts, output_name,
                                   template_name, filters, extra_context):
        """Renders pages with lists of posts."""

        deps = self.template_system.template_deps(template_name)
        for post in posts:
            deps += post.deps(lang)
        context = {}
        context["posts"] = posts
        context["title"] = self.config['BLOG_TITLE']
        context["description"] = self.config['BLOG_DESCRIPTION']
        context["lang"] = lang
        context["prevlink"] = None
        context["nextlink"] = None
        context.update(extra_context)
        deps_context = copy(context)
        deps_context["posts"] = [(p.titles[lang], p.permalink(lang))
                                 for p in posts]
        deps_context["global"] = self.config['GLOBAL_CONTEXT']
        task = {
            'name':
            output_name.encode('utf8'),
            'targets': [output_name],
            'file_dep':
            deps,
            'actions':
            [(self.render_template, [template_name, output_name, context])],
            'clean':
            True,
            'uptodate': [config_changed(deps_context)]
        }

        yield utils.apply_filters(task, filters)
示例#7
0
文件: nikola.py 项目: Bluerise/nikola
    def generic_post_list_renderer(self, lang, posts,
        output_name, template_name, filters, extra_context):
        """Renders pages with lists of posts."""

        deps = self.template_system.template_deps(template_name)
        for post in posts:
            deps += post.deps(lang)
        context = {}
        context["posts"] = posts
        context["title"] = self.config['BLOG_TITLE']
        context["description"] = self.config['BLOG_DESCRIPTION']
        context["lang"] = lang
        context["prevlink"] = None
        context["nextlink"] = None
        context.update(extra_context)
        deps_context = copy(context)
        deps_context["posts"] = [(p.titles[lang], p.permalink(lang))
            for p in posts]
        task = {
            'name': output_name.encode('utf8'),
            'targets': [output_name],
            'file_dep': deps,
            'actions': [(self.render_template,
                [template_name, output_name, context])],
            'clean': True,
            'uptodate': [config_changed(deps_context)]
        }

        yield utils.apply_filters(task, filters)
示例#8
0
    def generic_page_renderer(self, lang, wildcard, template_name, destination,
                              filters):
        """Render post fragments to final HTML pages."""
        for post in glob.glob(wildcard):
            post_name = os.path.splitext(post)[0]
            context = {}
            post = self.global_data[post_name]
            deps = post.deps(lang) + \
                self.template_system.template_deps(template_name)
            context['post'] = post
            context['lang'] = lang
            context['title'] = post.title(lang)
            context['description'] = post.description(lang)
            context['permalink'] = post.permalink(lang)
            context['page_list'] = self.pages
            output_name = os.path.join(self.config['OUTPUT_FOLDER'],
                                       self.config['TRANSLATIONS'][lang],
                                       destination,
                                       post.pagenames[lang] + ".html")
            deps_dict = copy(context)
            deps_dict.pop('post')
            if post.prev_post:
                deps_dict['PREV_LINK'] = [post.prev_post.permalink(lang)]
            if post.next_post:
                deps_dict['NEXT_LINK'] = [post.next_post.permalink(lang)]
            deps_dict['OUTPUT_FOLDER'] = self.config['OUTPUT_FOLDER']
            deps_dict['TRANSLATIONS'] = self.config['TRANSLATIONS']
            deps_dict['global'] = self.config['GLOBAL_CONTEXT']

            task = {
                'name':
                output_name.encode('utf-8'),
                'file_dep':
                deps,
                'targets': [output_name],
                'actions':
                [(self.render_template, [template_name, output_name,
                                         context])],
                'clean':
                True,
                'uptodate': [config_changed(deps_dict)],
            }

            yield utils.apply_filters(task, filters)
示例#9
0
    def generic_page_renderer(self, lang, wildcard,
        template_name, destination, filters):
        """Render post fragments to final HTML pages."""
        for post in glob.glob(wildcard):
            post_name = os.path.splitext(post)[0]
            context = {}
            post = self.global_data[post_name]
            deps = post.deps(lang) + \
                self.template_system.template_deps(template_name)
            context['post'] = post
            context['lang'] = lang
            context['title'] = post.title(lang)
            context['description'] = post.description(lang)
            context['permalink'] = post.permalink(lang)
            context['page_list'] = self.pages
            output_name = os.path.join(
                self.config['OUTPUT_FOLDER'],
                self.config['TRANSLATIONS'][lang],
                destination,
                post.pagenames[lang] + ".html")
            deps_dict = copy(context)
            deps_dict.pop('post')
            if post.prev_post:
                deps_dict['PREV_LINK'] = [post.prev_post.permalink(lang)]
            if post.next_post:
                deps_dict['NEXT_LINK'] = [post.next_post.permalink(lang)]
            deps_dict['OUTPUT_FOLDER'] = self.config['OUTPUT_FOLDER']
            deps_dict['TRANSLATIONS'] = self.config['TRANSLATIONS']
            deps_dict['global'] = self.config['GLOBAL_CONTEXT']

            task = {
                'name': output_name.encode('utf-8'),
                'file_dep': deps,
                'targets': [output_name],
                'actions': [(self.render_template,
                    [template_name, output_name, context])],
                'clean': True,
                'uptodate': [config_changed(deps_dict)],
            }

            yield utils.apply_filters(task, filters)
示例#10
0
文件: nikola.py 项目: sureshvv/nikola
    def generic_page_renderer(self, lang, wildcard, template_name, destination, filters):
        """Render post fragments to final HTML pages."""
        for post in glob.glob(wildcard):
            post_name = os.path.splitext(post)[0]
            context = {}
            post = self.global_data[post_name]
            deps = post.deps(lang) + self.template_system.template_deps(template_name)
            context["post"] = post
            context["lang"] = lang
            context["title"] = post.title(lang)
            context["description"] = post.description(lang)
            context["permalink"] = post.permalink(lang)
            context["page_list"] = self.pages
            output_name = os.path.join(
                self.config["OUTPUT_FOLDER"],
                self.config["TRANSLATIONS"][lang],
                destination,
                post.pagenames[lang] + ".html",
            )
            deps_dict = copy(context)
            deps_dict.pop("post")
            if post.prev_post:
                deps_dict["PREV_LINK"] = [post.prev_post.permalink(lang)]
            if post.next_post:
                deps_dict["NEXT_LINK"] = [post.next_post.permalink(lang)]
            deps_dict["OUTPUT_FOLDER"] = self.config["OUTPUT_FOLDER"]
            deps_dict["TRANSLATIONS"] = self.config["TRANSLATIONS"]

            task = {
                "name": output_name.encode("utf-8"),
                "file_dep": deps,
                "targets": [output_name],
                "actions": [(self.render_template, [template_name, output_name, context])],
                "clean": True,
                "uptodate": [config_changed(deps_dict)],
            }

            yield utils.apply_filters(task, filters)
def apply_actions_on_image(session_id, action_stack, filename,
                           image_signature):
    action_stack = deepcopy(action_stack)

    # If we have arrived to the original image
    if len(action_stack) == 0 and LOCAL:
        with open("image_string.csv", mode="r") as image_file:
            image_reader = csv.DictReader(image_file)
            for row in image_reader:
                im_pil = drc.b64_to_pil(row["image"])
                return im_pil

    if len(action_stack) == 0 and not LOCAL:
        # Retrieve the url in which the image string is stored inside s3,
        # using the session ID

        url = s3.generate_presigned_url(ClientMethod="get_object",
                                        Params={
                                            "Bucket": bucket_name,
                                            "Key": session_id
                                        })

        # A key replacement is required for URL pre-sign in gcp

        url = url.replace("AWSAccessKeyId", "GoogleAccessId")

        response = requests.get(url)
        if DEBUG:
            print("IMAGE STRING LENGTH: " + str(len(response.text)))
        im_pil = drc.b64_to_pil(response.text)
        return im_pil

    # Pop out the last action
    last_action = action_stack.pop()
    # Apply all the previous action_stack recursively, and gets the image PIL
    im_pil = apply_actions_on_image(session_id, action_stack, filename,
                                    image_signature)
    im_size = im_pil.size

    # Apply the rest of the action_stack
    operation = last_action["operation"]
    selected_data = last_action["selectedData"]
    action_type = last_action["type"]

    # Select using Lasso
    if selected_data and "lassoPoints" in selected_data:
        selection_mode = "lasso"
        selection_zone = utils.generate_lasso_mask(im_pil, selected_data)
    # Select using rectangular box
    elif selected_data and "range" in selected_data:
        selection_mode = "select"
        lower, upper = map(int, selected_data["range"]["y"])
        left, right = map(int, selected_data["range"]["x"])
        # Adjust height difference
        height = im_size[1]
        upper = height - upper
        lower = height - lower
        selection_zone = (left, upper, right, lower)
    # Select the whole image
    else:
        selection_mode = "select"
        selection_zone = (0, 0) + im_size

    # Apply the filters
    if action_type == "filter":
        utils.apply_filters(image=im_pil,
                            zone=selection_zone,
                            filter=operation,
                            mode=selection_mode)
    elif action_type == "enhance":
        enhancement = operation["enhancement"]
        factor = operation["enhancement_factor"]

        utils.apply_enhancements(
            image=im_pil,
            zone=selection_zone,
            enhancement=enhancement,
            enhancement_factor=factor,
            mode=selection_mode,
        )

    return im_pil
示例#12
0
def apply_actions_on_image(session_id,
                           action_stack,
                           filename,
                           image_signature):
    action_stack = deepcopy(action_stack)

    # If we have arrived to the original image
    if len(action_stack) == 0:
        # Retrieve the url in which the image string is stored inside s3,
        # using the session ID

        url = s3.generate_presigned_url(
            ClientMethod='get_object',
            Params={
                'Bucket': bucket_name,
                'Key': session_id
            }
        )

        # A key replacement is required for URL pre-sign in gcp

        url = url.replace('AWSAccessKeyId', 'GoogleAccessId')

        response = requests.get(url)
        print(len(response.text))
        im_pil = drc.b64_to_pil(response.text)
        return im_pil

    # Pop out the last action
    last_action = action_stack.pop()
    # Apply all the previous action_stack, and gets the image PIL
    im_pil = apply_actions_on_image(
        session_id,
        action_stack,
        filename,
        image_signature
    )
    im_size = im_pil.size

    # Apply the rest of the action_stack
    operation = last_action['operation']
    selectedData = last_action['selectedData']
    type = last_action['type']

    # Select using Lasso
    if selectedData and 'lassoPoints' in selectedData:
        selection_mode = 'lasso'
        selection_zone = generate_lasso_mask(im_pil, selectedData)
    # Select using rectangular box
    elif selectedData and 'range' in selectedData:
        selection_mode = 'select'
        lower, upper = map(int, selectedData['range']['y'])
        left, right = map(int, selectedData['range']['x'])
        # Adjust height difference
        height = im_size[1]
        upper = height - upper
        lower = height - lower
        selection_zone = (left, upper, right, lower)
    # Select the whole image
    else:
        selection_mode = 'select'
        selection_zone = (0, 0) + im_size

    # Apply the filters
    if type == 'filter':
        apply_filters(
            image=im_pil,
            zone=selection_zone,
            filter=operation,
            mode=selection_mode
        )
    elif type == 'enhance':
        enhancement = operation['enhancement']
        factor = operation['enhancement_factor']

        apply_enhancements(
            image=im_pil,
            zone=selection_zone,
            enhancement=enhancement,
            enhancement_factor=factor,
            mode=selection_mode
        )

    return im_pil
def apply_actions_on_image(session_id, action_stack, filename,
                           image_signature):
    action_stack = deepcopy(action_stack)

    # If we have arrived to the original image
    if len(action_stack) == 0 and LOCAL:
        with open("image_string.csv", mode="r") as image_file:
            image_reader = csv.DictReader(image_file)
            for row in image_reader:
                im_pil = drc.b64_to_pil(row["image"])
                return im_pil

    if len(action_stack) == 0 and not LOCAL:
        pass

    # Pop out the last action
    last_action = action_stack.pop()
    # Apply all the previous action_stack recursively, and gets the image PIL
    im_pil = apply_actions_on_image(session_id, action_stack, filename,
                                    image_signature)
    im_size = im_pil.size

    # Apply the rest of the action_stack
    operation = last_action["operation"]
    selected_data = last_action["selectedData"]
    action_type = last_action["type"]

    # Select using Lasso
    if selected_data and "lassoPoints" in selected_data:
        selection_mode = "lasso"
        selection_zone = utils.generate_lasso_mask(im_pil, selected_data)
    # Select using rectangular box
    elif selected_data and "range" in selected_data:
        selection_mode = "select"
        lower, upper = map(int, selected_data["range"]["y"])
        left, right = map(int, selected_data["range"]["x"])
        # Adjust height difference
        height = im_size[1]
        upper = height - upper
        lower = height - lower
        selection_zone = (left, upper, right, lower)
    # Select the whole image
    else:
        selection_mode = "select"
        selection_zone = (0, 0) + im_size

    # Apply the filters
    if action_type == "filter":
        utils.apply_filters(image=im_pil,
                            zone=selection_zone,
                            filter=operation,
                            mode=selection_mode)
    elif action_type == "enhance":
        enhancement = operation["enhancement"]
        factor = operation["enhancement_factor"]

        utils.apply_enhancements(
            image=im_pil,
            zone=selection_zone,
            enhancement=enhancement,
            enhancement_factor=factor,
            mode=selection_mode,
        )

    return im_pil
示例#14
0
def update_graph_interactive_image(content, n_clicks, figure, selectedData,
                                   filters, enhance, enhancement_factor,
                                   new_filename, dragmode, enc_format,
                                   storage):
    t1 = time.time()

    # Retrieve metadata stored in the storage
    filename = storage

    # If the file has changed (when a file is uploaded)
    if new_filename and new_filename != filename:
        if DEBUG:
            print(filename, "replaced by", new_filename)

        string = content.split(';base64,')[-1]
        im_pil = drc.b64_to_pil(string)

    # If the file HAS NOT changed (which means an operation was applied)
    else:
        # Retrieve the image stored inside the figure
        enc_str = figure['layout']['images'][0]['source'].split(';base64,')[-1]
        # Creates the PIL Image object from the b64 png encoding
        im_pil = drc.b64_to_pil(string=enc_str)
        im_size = im_pil.size

        # Select using Lasso
        if selectedData and 'lassoPoints' in selectedData:
            selection_mode = 'lasso'
            selection_zone = generate_lasso_mask(im_pil, selectedData)
        # Select using rectangular box
        elif selectedData and 'range' in selectedData:
            selection_mode = 'select'
            lower, upper = map(int, selectedData['range']['y'])
            left, right = map(int, selectedData['range']['x'])
            # Adjust height difference
            height = im_size[1]
            upper = height - upper
            lower = height - lower
            selection_zone = (left, upper, right, lower)
        # Select the whole image
        else:
            selection_mode = 'select'
            selection_zone = (0, 0) + im_size

        # If the filter dropdown was chosen, apply the filter selected by the user
        if filters:
            apply_filters(image=im_pil,
                          zone=selection_zone,
                          filter=filters,
                          mode=selection_mode)

        if enhance:
            apply_enhancements(image=im_pil,
                               zone=selection_zone,
                               enhancement=enhance,
                               enhancement_factor=enhancement_factor,
                               mode=selection_mode)

    t2 = time.time()
    if DEBUG:
        print(f"Updated Image Storage in {t2-t1:.3f} sec")

    return [
        drc.InteractiveImagePIL(image_id='interactive-image',
                                image=im_pil,
                                enc_format=enc_format,
                                display_mode='fixed',
                                dragmode=dragmode,
                                verbose=DEBUG),
        html.Div(id='div-filename-image',
                 children=new_filename,
                 style={'display': 'none'})
    ]
示例#15
0
st.title("Film Recommender System")
cast_options, director_options, genres_options = get_filter_values(
    filtered_films)
cast_default, director_default, genres_default = get_filter_values(data)
cast_filter, director_filter, genre_filter = st.columns(3)
cast = cast_filter.multiselect("Filter by cast", cast_options)
director = director_filter.multiselect("Filter by director", director_options)
genres = genre_filter.multiselect("Filter by genre", genres_options)
cast = cast_default if not cast else cast
director = director_default if not director else director
genres = genres_default if not genres else genres

if option == "Top Films":
    filtered_films = apply_filters(data=data,
                                   cast=cast,
                                   director=director,
                                   genres=genres,
                                   sort_column="imdb_score")
    filtered_films = filtered_films.loc[
        filtered_films["vote_count"] >= config.m]
    display_film_posters(
        streamlit=st,
        data=filtered_films,
        num_rows=config.NUM_POSTER_ROWS,
        posters_per_row=config.POSTERS_PER_ROW,
    )

elif option == "Personal Recommendations":
    if len(liked_films) == 0:
        st.sidebar.write(
            "Please select at least one film for recommendations.")