class InternalCitationLayer():
    shorthand = 'internal'

    def __init__(self, layer):
        self.layer = layer
        self.sectional = False
        self.version = None
        self.rev_urls = SectionUrl()
        self.rendered = {}

    def render_url(
        self, label, text,
            template_name='regulations/layers/internal_citation.html'):

        key = (tuple(label), text, template_name)
        if key not in self.rendered:
            url = self.rev_urls.fetch(label, self.version, self.sectional)
            c = Context({'citation': {
                'url': url, 'label': text,
                'label_id': self.rev_urls.view_label_id(label, self.version)}})
            template = loader.get_template(template_name)
            self.rendered[key] = template.render(c).strip('\n')
        return self.rendered[key]

    def apply_layer(self, text, text_index):
        if text_index in self.layer:
            layer_elements = self.layer[text_index]

            layer_pairs = []
            for layer_element in layer_elements:
                for start, end in layer_element['offsets']:
                    ot = text[int(start):int(end)]
                    rt = self.render_url(layer_element['citation'], ot)
                    layer_pairs.append((ot, rt, (start, end)))
            return layer_pairs
class InternalCitationLayer(InlineLayer):
    shorthand = 'internal'
    data_source = 'internal-citations'

    def __init__(self, layer):
        self.layer = layer
        self.sectional = False
        self.version = None
        self.rev_urls = SectionUrl()
        self.rendered = {}

    def render_url(self,
                   label,
                   text,
                   template_name='regulations/layers/internal_citation.html'):

        key = (tuple(label), text, template_name)
        if key not in self.rendered:
            url = self.rev_urls.fetch(label, self.version, self.sectional)
            c = Context({
                'citation': {
                    'url': url,
                    'label': text,
                    'label_id':
                    self.rev_urls.view_label_id(label, self.version)
                }
            })
            template = loader.get_template(template_name)
            self.rendered[key] = template.render(c).strip('\n')
        return self.rendered[key]

    def replacement_for(self, original, data):
        return self.render_url(data['citation'], original)
class InternalCitationLayer(InlineLayer):
    shorthand = 'internal'
    data_source = 'internal-citations'

    def __init__(self, layer):
        self.layer = layer
        self.sectional = False
        self.version = None
        self.rev_urls = SectionUrl()
        self.rendered = {}

    def render_url(self, label, text,
                   template_name='regulations/layers/internal_citation.html'):

        key = (tuple(label), text, template_name)
        if key not in self.rendered:
            url = self.rev_urls.fetch(label, self.version, self.sectional)
            c = Context({'citation': {
                'url': url, 'label': text,
                'label_id': self.rev_urls.view_label_id(label, self.version)}})
            template = loader.get_template(template_name)
            self.rendered[key] = template.render(c).strip('\n')
        return self.rendered[key]

    def replacement_for(self, original, data):
        return self.render_url(data['citation'], original)
class InternalCitationLayer():
    shorthand = 'internal'

    def __init__(self, layer):
        self.layer = layer
        self.sectional = False
        self.version = None
        self.rev_urls = SectionUrl()
        self.rendered = {}

    def render_url(
        self, label, text,
            template_name='regulations/layers/internal_citation.html'):

        key = (tuple(label), text, template_name)
        if key not in self.rendered:
            url = self.rev_urls.fetch(label, self.version, self.sectional)
            c = Context({'citation': {'url': url, 'label': text,
                'label_id': self.rev_urls.view_label_id(label, self.version)}})
            template = loader.get_template(template_name)
            self.rendered[key] = template.render(c).strip('\n')
        return self.rendered[key]

    def apply_layer(self, text, text_index):
        if text_index in self.layer:
            layer_elements = self.layer[text_index]

            layer_pairs = []
            for layer_element in layer_elements:
                for start, end in layer_element['offsets']:
                    ot = text[int(start):int(end)]
                    rt = self.render_url(layer_element['citation'], ot)
                    layer_pairs.append((ot, rt, (start, end)))
            return layer_pairs
Пример #5
0
    def get_context_data(self, **kwargs):
        # We don't want to run the content data of PartialView -- it assumes
        # we will be applying layers
        context = super(PartialView, self).get_context_data(**kwargs)

        context['q'] = self.request.GET.get('q')
        context['version'] = self.request.GET.get('version')

        context['regulation'] = context['label_id'].split('-')[0]

        try:
            page = int(self.request.GET.get('page', '0'))
        except ValueError:
            page = 0

        api_page = page // (API_PAGE_SIZE / PAGE_SIZE)

        context['warnings'] = []
        if not context['q']:
            context['warnings'].append('Please provide a query.')
        if not context['version']:
            context['warnings'].append('Please provide a version.')

        if context['warnings']:
            results = {'results': [], 'total_hits': 0}
        else:
            results = api_reader.ApiReader().search(context['q'],
                                                    context['version'],
                                                    context['regulation'],
                                                    api_page)

        self.reduce_results(results, page)
        section_url = SectionUrl()

        for result in results['results']:
            result['header'] = node_types.label_to_text(result['label'])
            if 'title' in result:
                result['header'] += ' ' + title(result['title'])
            result['section_id'] = section_url.view_label_id(
                result['label'], context['version'])
            result['url'] = section_url.fetch(result['label'],
                                              context['version'],
                                              sectional=True)
        context['results'] = results

        for version in fetch_grouped_history(context['regulation']):
            for notice in version['notices']:
                if notice['document_number'] == context['version']:
                    context['version_by_date'] = notice['effective_on']

        self.add_prev_next(page, context)
        self.final_context = context

        return context
Пример #6
0
def process_cfr_results(results, version):
    """Modify the results of a search over the CFR by adding a human-readable
    label, appropriate links, and version information"""
    section_url = SectionUrl()
    results = deepcopy(results)
    for result in results["results"]:
        result["header"] = node_types.label_to_text(result["label"])
        if "title" in result:
            result["header"] += " " + title(result["title"])
        result["section_id"] = section_url.view_label_id(result["label"], version)
        result["url"] = section_url.fetch(result["label"], version, sectional=True)
    return results
Пример #7
0
def process_cfr_results(results, version):
    """Modify the results of a search over the CFR by adding a human-readable
    label, appropriate links, and version information"""
    section_url = SectionUrl()
    results = deepcopy(results)
    for result in results['results']:
        add_cfr_headers(result)
        result['section_id'] = section_url.view_label_id(
            result['label'], version)
        result['url'] = section_url.fetch(
            result['label'], version, sectional=True)
    return results
Пример #8
0
    def get_context_data(self, **kwargs):
        # We don't want to run the content data of PartialView -- it assumes
        # we will be applying layers
        context = super(PartialView, self).get_context_data(**kwargs)

        context['q'] = self.request.GET.get('q')
        context['version'] = self.request.GET.get('version')

        context['regulation'] = context['label_id'].split('-')[0]

        try:
            page = int(self.request.GET.get('page', '0'))
        except ValueError:
            page = 0

        api_page = page // (API_PAGE_SIZE / PAGE_SIZE)

        context['warnings'] = []
        if not context['q']:
            context['warnings'].append('Please provide a query.')
        if not context['version']:
            context['warnings'].append('Please provide a version.')

        if context['warnings']:
            results = {'results': [], 'total_hits': 0}
        else:
            results = api_reader.ApiReader().search(
                context['q'], context['version'], context['regulation'],
                api_page)

        self.reduce_results(results, page)
        section_url = SectionUrl()

        for result in results['results']:
            result['header'] = node_types.label_to_text(result['label'])
            if 'title' in result:
                result['header'] += ' ' + title(result['title'])
            result['section_id'] = section_url.view_label_id(
                result['label'], context['version'])
            result['url'] = section_url.fetch(
                result['label'], context['version'], sectional=True)
        context['results'] = results

        for version in fetch_grouped_history(context['regulation']):
            for notice in version['notices']:
                if notice['document_number'] == context['version']:
                    context['version_by_date'] = notice['effective_on']

        self.add_prev_next(page, context)
        self.final_context = context

        return context
    def get_context_data(self, **kwargs):
        # We don't want to run the content data of PartialView -- it assumes
        # we will be applying layers
        context = super(PartialView, self).get_context_data(**kwargs)
        context['regulation'] = context['label_id'].split('-')[0]

        try:
            page = int(self.request.GET.get('page', '0'))
        except ValueError:
            page = 0

        # API page size is API_PAGE_SIZE, but we show only PAGE_SIZE
        api_page = page // (API_PAGE_SIZE / PAGE_SIZE)
        page_idx = (page % (API_PAGE_SIZE / PAGE_SIZE)) * PAGE_SIZE

        results = api_reader.ApiReader().search(context['q'],
                                                context['version'],
                                                context['regulation'],
                                                api_page)

        # Ignore results found in the root (i.e. not a section), adjust
        # the number of results accordingly.
        original_count = len(results['results'])
        results['results'] = [
            r for r in results['results'] if len(r['label']) > 1
        ]
        num_results_ignored = original_count - len(results['results'])
        results['total_hits'] -= num_results_ignored
        results['results'] = results['results'][page_idx:page_idx + PAGE_SIZE]

        section_url = SectionUrl()

        for result in results['results']:
            result['header'] = label_to_text(result['label'])
            if 'title' in result:
                result['header'] += ' ' + title(result['title'])
            result['section_id'] = section_url.view_label_id(
                result['label'], context['version'])
            result['url'] = section_url.fetch(result['label'],
                                              context['version'],
                                              sectional=True)
        context['results'] = results

        for version in fetch_grouped_history(context['regulation']):
            for notice in version['notices']:
                if notice['document_number'] == context['version']:
                    context['version_by_date'] = notice['effective_on']

        self.add_prev_next(page, context)
        self.final_context = context

        return context
def process_cfr_results(results, version):
    """Modify the results of a search over the CFR by adding a human-readable
    label, appropriate links, and version information"""
    section_url = SectionUrl()
    results = deepcopy(results)
    for result in results['results']:
        add_cfr_headers(result)
        result['section_id'] = section_url.view_label_id(
            result['label'], version)
        result['url'] = section_url.fetch(result['label'],
                                          version,
                                          sectional=True)
    return results
def process_cfr_results(results, version):
    """Modify the results of a search over the CFR by adding a human-readable
    label, appropriate links, and version information"""
    section_url = SectionUrl()
    results = deepcopy(results)
    for result in results['results']:
        result['header'] = node_types.label_to_text(result['label'])
        if 'title' in result:
            result['header'] += ' ' + title(result['title'])
        result['section_id'] = section_url.view_label_id(
            result['label'], version)
        result['url'] = section_url.fetch(result['label'],
                                          version,
                                          sectional=True)
    return results