code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
|---|---|---|---|---|---|
load_metafile.cache_clear()
meta = load_metafile(fullpath)
if not meta:
return True
# update the category meta file mapping
category = meta.get('Category', utils.get_category(relpath))
values = {
'category': category,
'file_path': fullpath,
'sort_name': meta.get('Sort-Name', '')
}
logger.debug("setting category %s to metafile %s", category, fullpath)
record = model.Category.get(category=category)
if record:
record.set(**values)
else:
record = model.Category(**values)
# update other relationships to the index
path_alias.remove_aliases(record)
for alias in meta.get_all('Path-Alias', []):
path_alias.set_alias(alias, category=record)
orm.commit()
return record
|
def scan_file(fullpath, relpath)
|
scan a file and put it into the index
| 5.438581
| 5.34481
| 1.017544
|
if self._meta and self._meta.get('name'):
# get it from the meta file
return self._meta.get('name')
# infer it from the basename
return self.basename.replace('_', ' ').title()
|
def name(self)
|
Get the display name of the category
| 5.247737
| 4.882192
| 1.074873
|
if self._meta and self._meta.get_payload():
return utils.TrueCallableProxy(self._description)
return utils.CallableProxy(None)
|
def description(self)
|
Get the textual description of the category
| 19.434856
| 21.027372
| 0.924265
|
ret = []
here = self
while here:
ret.append(here)
here = here.parent
return list(reversed(ret))
|
def breadcrumb(self)
|
Get the category hierarchy leading up to this category, including
root and self.
For example, path/to/long/category will return a list containing
Category('path'), Category('path/to'), and Category('path/to/long').
| 4.254313
| 4.041191
| 1.052737
|
if self._record and self._record.sort_name:
return self._record.sort_name
return self.name
|
def sort_name(self)
|
Get the sorting name of this category
| 4.965058
| 4.588916
| 1.081967
|
if self.path:
return Category(os.path.dirname(self.path))
return None
|
def parent(self)
|
Get the parent category
| 7.432991
| 4.557339
| 1.630993
|
if recurse:
# No need to filter
return sorted([Category(e) for e in self._subcats_recursive],
key=lambda c: c.sort_breadcrumb)
# get all the subcategories, with only the first subdir added
# number of path components to ingest
parts = len(self.path.split('/')) + 1 if self.path else 1
# convert the subcategories into separated pathlists with only 'parts'
# parts
subcats = [c.split('/')[:parts] for c in self._subcats_recursive]
# join them back into a path, and make unique
subcats = {'/'.join(c) for c in subcats}
# convert to a bunch of Category objects
return sorted([Category(c) for c in subcats], key=lambda c: c.sort_name or c.name)
|
def _get_subcats(self, recurse=False)
|
Get the subcategories of this category
recurse -- whether to include their subcategories as well
| 6.362339
| 6.266622
| 1.015274
|
for record in self._entries(spec).order_by(model.Entry.local_date,
model.Entry.id)[:1]:
return entry.Entry(record)
return None
|
def _first(self, **spec)
|
Get the earliest entry in this category, optionally including subcategories
| 9.539699
| 8.647634
| 1.103157
|
for record in self._entries(spec).order_by(orm.desc(model.Entry.local_date),
orm.desc(model.Entry.id))[:1]:
return entry.Entry(record)
return None
|
def _last(self, **spec)
|
Get the latest entry in this category, optionally including subcategories
| 8.913107
| 7.485998
| 1.190637
|
match = re.match(
r'([0-9]{4})(-?([0-9]{1,2}))?(-?([0-9]{1,2}))?(_w)?$', datestr)
if not match:
return (arrow.get(datestr,
tzinfo=config.timezone).replace(tzinfo=config.timezone),
'day', 'YYYY-MM-DD')
year, month, day, week = match.group(1, 3, 5, 6)
start = arrow.Arrow(year=int(year), month=int(
month or 1), day=int(day or 1), tzinfo=config.timezone)
if week:
return start.span('week')[0], 'week', WEEK_FORMAT
if day:
return start, 'day', DAY_FORMAT
if month:
return start, 'month', MONTH_FORMAT
if year:
return start, 'year', YEAR_FORMAT
raise ValueError("Could not parse date: {}".format(datestr))
|
def parse_date(datestr)
|
Parse a date expression into a tuple of:
(start_date, span_type, span_format)
Arguments:
datestr -- A date specification, in the format of YYYY-MM-DD (dashes optional)
| 2.655708
| 2.573483
| 1.031951
|
if isinstance(search_path, str):
search_path = [search_path]
for relative in search_path:
candidate = os.path.normpath(os.path.join(relative, path))
if os.path.isfile(candidate):
return candidate
return None
|
def find_file(path, search_path)
|
Find a file by relative path. Arguments:
path -- the image's filename
search_path -- a list of directories to check in
Returns: the resolved file path
| 2.205405
| 2.439989
| 0.903858
|
from . import entry # pylint:disable=cyclic-import
try:
entry_id = int(rel_path)
record = model.Entry.get(id=entry_id)
if record:
return entry.Entry(record)
except ValueError:
pass
if rel_path.startswith('/'):
search_path = [config.content_folder]
rel_path = '.' + rel_path
for where in search_path:
abspath = os.path.normpath(os.path.join(where, rel_path))
record = model.Entry.get(file_path=abspath)
if record:
return entry.Entry(record)
return None
|
def find_entry(rel_path, search_path)
|
Find an entry by relative path. Arguments:
path -- the entry's filename (or entry ID)
search_path -- a list of directories to check in
Returns: the resolved Entry object
| 3.021336
| 3.116727
| 0.969394
|
if os.sep != '/':
path = '/'.join(path.split(os.sep))
return flask.url_for('static', filename=path, _external=absolute)
|
def static_url(path, absolute=False)
|
Shorthand for returning a URL for the requested static file.
Arguments:
path -- the path to the file (relative to the static files directory)
absolute -- whether the link should be absolute or relative
| 3.490587
| 3.991074
| 0.874598
|
text = '<' + name
if isinstance(attrs, dict):
attr_list = attrs.items()
elif isinstance(attrs, list):
attr_list = attrs
elif attrs is not None:
raise TypeError("Unhandled attrs type " + str(type(attrs)))
for key, val in attr_list:
if val is not None:
escaped = html.escape(str(val), False).replace('"', '"')
text += ' {}="{}"'.format(key, escaped)
if start_end:
text += ' /'
text += '>'
return flask.Markup(text)
|
def make_tag(name, attrs, start_end=False)
|
Build an HTML tag from the given name and attributes.
Arguments:
name -- the name of the tag (p, div, etc.)
attrs -- a dict of attributes to apply to the tag
start_end -- whether this tag should be self-closing
| 2.522475
| 2.85035
| 0.88497
|
stat = os.stat(fullpath)
return ','.join([str(value) for value in [stat.st_ino, stat.st_mtime, stat.st_size] if value])
|
def file_fingerprint(fullpath)
|
Get a metadata fingerprint for a file
| 2.844978
| 2.92775
| 0.971728
|
out_args = input_args
for dest_key, src_keys in remap.items():
remap_value = None
if isinstance(src_keys, str):
src_keys = [src_keys]
for key in src_keys:
if key in input_args:
remap_value = input_args[key]
break
if remap_value is not None:
if out_args is input_args:
out_args = {**input_args}
out_args[dest_key] = remap_value
return out_args
|
def remap_args(input_args, remap)
|
Generate a new argument list by remapping keys. The 'remap'
dict maps from destination key -> priority list of source keys
| 2.037552
| 2.071954
| 0.983396
|
if path.startswith('@'):
# static resource
return static_url(path[1:], absolute=absolute)
if absolute:
# absolute-ify whatever the URL is
return urllib.parse.urljoin(flask.request.url, path)
return path
|
def remap_link_target(path, absolute=False)
|
remap a link target to a static URL if it's prefixed with @
| 6.277899
| 4.895337
| 1.282424
|
return '/'.join(os.path.dirname(filename).split(os.sep))
|
def get_category(filename)
|
Get a default category name from a filename in a cross-platform manner
| 4.831346
| 4.088248
| 1.181764
|
if self._default_args:
return self._func(
*self._default_args,
**self._default_kwargs)
return self._func(**self._default_kwargs)
|
def _default(self)
|
Get the default function return
| 4.313456
| 3.684484
| 1.170708
|
try:
db.bind(**config.database_config)
except OSError:
# Attempted to connect to a file-based database where the file didn't
# exist
db.bind(**config.database_config, create_db=True)
rebuild = True
try:
db.generate_mapping(create_tables=True)
with orm.db_session:
version = GlobalConfig.get(key='schema_version')
if version and version.int_value != SCHEMA_VERSION:
logger.info("Existing database has schema version %d",
version.int_value)
else:
rebuild = False
except: # pylint:disable=bare-except
logger.exception("Error mapping schema")
if rebuild:
logger.info("Rebuilding schema")
try:
db.drop_all_tables(with_all_data=True)
db.create_tables()
except:
raise RuntimeError("Unable to upgrade schema automatically; please " +
"delete the existing database and try again.")
with orm.db_session:
if not GlobalConfig.get(key='schema_version'):
logger.info("setting schema version to %d", SCHEMA_VERSION)
GlobalConfig(key='schema_version',
int_value=SCHEMA_VERSION)
orm.commit()
|
def setup()
|
Set up the database
| 3.432004
| 3.349288
| 1.024697
|
return self.status not in (PublishStatus.DRAFT.value,
PublishStatus.GONE.value)
|
def visible(self)
|
Returns true if the entry should be viewable
| 11.777036
| 11.563465
| 1.018469
|
card = CardData()
parser = CardParser(card, config, image_search_path)
misaka.Markdown(parser, extensions=markdown.ENABLED_EXTENSIONS)(text)
return card
|
def extract_card(text, config, image_search_path)
|
Extract card data based on the provided texts.
| 8.441181
| 8.160661
| 1.034375
|
if not self._out.description:
self._out.description = content
return ' '
|
def paragraph(self, content)
|
Turn the first paragraph of text into the summary text
| 12.739316
| 10.483274
| 1.215204
|
''' extract the images '''
max_images = self._config.get('count')
if max_images is not None and len(self._out.images) >= max_images:
# We already have enough images, so bail out
return ' '
image_specs = raw_url
if title:
image_specs += ' "{}"'.format(title)
alt, container_args = image.parse_alt_text(alt)
spec_list, _ = image.get_spec_list(image_specs, container_args)
for spec in spec_list:
if not spec:
continue
self._out.images.append(self._render_image(spec, alt))
if max_images is not None and len(self._out.images) >= max_images:
break
return ' '
|
def image(self, raw_url, title='', alt='')
|
extract the images
| 4.189163
| 4.112405
| 1.018665
|
# pylint: disable=unused-argument
try:
path, image_args, _ = image.parse_image_spec(spec)
except Exception as err: # pylint: disable=broad-except
# we tried™
logger.exception("Got error on spec %s: %s", spec, err)
return None
img = image.get_image(path, self._image_search_path)
if img:
image_config = {**image_args, **self._config, 'absolute': True}
return img.get_rendition(1, **image_config)[0]
return None
|
def _render_image(self, spec, alt='')
|
Given an image spec, try to turn it into a card image per the configuration
| 5.690741
| 5.381779
| 1.057409
|
config.setup(cfg)
app = _PublApp(name,
template_folder=config.template_folder,
static_folder=config.static_folder,
static_url_path=config.static_url_path)
for route in [
'/',
'/<path:category>/',
'/<template>',
'/<path:category>/<template>',
]:
app.add_url_rule(route, 'category', rendering.render_category)
for route in [
'/<int:entry_id>',
'/<int:entry_id>-',
'/<int:entry_id>-<slug_text>',
'/<path:category>/<int:entry_id>',
'/<path:category>/<int:entry_id>-',
'/<path:category>/<int:entry_id>-<slug_text>',
]:
app.add_url_rule(route, 'entry', rendering.render_entry)
app.add_url_rule('/<path:path>.PUBL_PATHALIAS',
'path_alias', rendering.render_path_alias)
app.add_url_rule('/_async/<path:filename>',
'async', image.get_async)
app.add_url_rule('/_', 'chit', rendering.render_transparent_chit)
app.add_url_rule('/_file/<path:filename>',
'asset', rendering.retrieve_asset)
app.config['TRAP_HTTP_EXCEPTIONS'] = True
app.register_error_handler(
werkzeug.exceptions.HTTPException, rendering.render_exception)
app.jinja_env.globals.update( # pylint: disable=no-member
get_view=view.get_view,
arrow=arrow,
static=utils.static_url,
get_template=rendering.get_template
)
caching.init_app(app)
maint = maintenance.Maintenance()
if config.index_rescan_interval:
maint.register(functools.partial(index.scan_index,
config.content_folder),
config.index_rescan_interval)
if config.image_cache_interval and config.image_cache_age:
maint.register(functools.partial(image.clean_cache,
config.image_cache_age),
config.image_cache_interval)
app.before_request(maint.run)
if 'CACHE_THRESHOLD' in config.cache:
app.after_request(set_cache_expiry)
if app.debug:
# We're in debug mode so we don't want to scan until everything's up
# and running
app.before_first_request(startup)
else:
# In production, register the exception handler and scan the index
# immediately
app.register_error_handler(Exception, rendering.render_exception)
startup()
return app
|
def publ(name, cfg)
|
Create a Flask app and configure it for use with Publ
| 3.230716
| 3.184153
| 1.014623
|
model.setup()
index.scan_index(config.content_folder)
index.background_scan(config.content_folder)
|
def startup()
|
Startup routine for initiating the content indexer
| 13.774597
| 9.787046
| 1.407431
|
if response.cache_control.max_age is None and 'CACHE_DEFAULT_TIMEOUT' in config.cache:
response.cache_control.max_age = config.cache['CACHE_DEFAULT_TIMEOUT']
return response
|
def set_cache_expiry(response)
|
Set the cache control headers
| 3.247879
| 3.432724
| 0.946152
|
def decorator(func):
self.add_path_regex(regex, func)
return decorator
|
def path_alias_regex(self, regex)
|
A decorator that adds a path-alias regular expression; calls
add_path_regex
| 8.827519
| 6.771262
| 1.303674
|
for regex, func in self._regex_map:
match = re.match(regex, path)
if match:
return func(match)
return None, None
|
def get_path_regex(self, path)
|
Evaluate the registered path-alias regular expressions
| 3.74201
| 3.779603
| 0.990054
|
base, _ = os.path.splitext(basename)
return re.sub(r'[ _-]+', r' ', base).title()
|
def guess_title(basename)
|
Attempt to guess the title from the filename
| 5.125504
| 4.200027
| 1.22035
|
warn_duplicate = False
if 'Entry-ID' in entry:
entry_id = int(entry['Entry-ID'])
else:
entry_id = None
# See if we've inadvertently duplicated an entry ID
if entry_id:
try:
other_entry = model.Entry.get(id=entry_id)
if (other_entry
and os.path.isfile(other_entry.file_path)
and not os.path.samefile(other_entry.file_path, fullpath)):
warn_duplicate = entry_id
entry_id = None
except FileNotFoundError:
# the other file doesn't exist, so just let it go
pass
# Do we need to assign a new ID?
if not entry_id and not assign_id:
# We're not assigning IDs yet
return None
if not entry_id:
# See if we already have an entry with this file path
by_filepath = model.Entry.get(file_path=fullpath)
if by_filepath:
entry_id = by_filepath.id
if not entry_id:
# We still don't have an ID; generate one pseudo-randomly, based on the
# entry file path. This approach averages around 0.25 collisions per ID
# generated while keeping the entry ID reasonably short. In general,
# count*N averages 1/(N-1) collisions per ID.
limit = max(10, orm.get(orm.count(e) for e in model.Entry) * 5)
attempt = 0
while not entry_id or model.Entry.get(id=entry_id):
# Stably generate a quasi-random entry ID from the file path
md5 = hashlib.md5()
md5.update("{} {}".format(fullpath, attempt).encode('utf-8'))
entry_id = int.from_bytes(md5.digest(), byteorder='big') % limit
attempt = attempt + 1
if warn_duplicate is not False:
logger.warning("Entry '%s' had ID %d, which belongs to '%s'. Reassigned to %d",
fullpath, warn_duplicate, other_entry.file_path, entry_id)
return entry_id
|
def get_entry_id(entry, fullpath, assign_id)
|
Get or generate an entry ID for an entry
| 3.958309
| 3.942154
| 1.004098
|
with tempfile.NamedTemporaryFile('w', delete=False) as file:
tmpfile = file.name
# we can't just use file.write(str(entry)) because otherwise the
# headers "helpfully" do MIME encoding normalization.
# str(val) is necessary to get around email.header's encoding
# shenanigans
for key, val in entry.items():
print('{}: {}'.format(key, str(val)), file=file)
print('', file=file)
file.write(entry.get_payload())
shutil.move(tmpfile, fullpath)
|
def save_file(fullpath, entry)
|
Save a message file out, without mangling the headers
| 5.732183
| 5.551924
| 1.032468
|
# pylint: disable=too-many-branches,too-many-statements,too-many-locals
# Since a file has changed, the lrucache is invalid.
load_message.cache_clear()
try:
entry = load_message(fullpath)
except FileNotFoundError:
# The file doesn't exist, so remove it from the index
record = model.Entry.get(file_path=fullpath)
if record:
expire_record(record)
return True
entry_id = get_entry_id(entry, fullpath, assign_id)
if entry_id is None:
return False
fixup_needed = False
basename = os.path.basename(relpath)
title = entry['title'] or guess_title(basename)
values = {
'file_path': fullpath,
'category': entry.get('Category', utils.get_category(relpath)),
'status': model.PublishStatus[entry.get('Status', 'SCHEDULED').upper()].value,
'entry_type': entry.get('Entry-Type', ''),
'slug_text': make_slug(entry.get('Slug-Text', title)),
'redirect_url': entry.get('Redirect-To', ''),
'title': title,
'sort_title': entry.get('Sort-Title', title),
'entry_template': entry.get('Entry-Template', '')
}
entry_date = None
if 'Date' in entry:
try:
entry_date = arrow.get(entry['Date'], tzinfo=config.timezone)
except arrow.parser.ParserError:
entry_date = None
if entry_date is None:
del entry['Date']
entry_date = arrow.get(
os.stat(fullpath).st_ctime).to(config.timezone)
entry['Date'] = entry_date.format()
fixup_needed = True
if 'Last-Modified' in entry:
last_modified_str = entry['Last-Modified']
try:
last_modified = arrow.get(
last_modified_str, tzinfo=config.timezone)
except arrow.parser.ParserError:
last_modified = arrow.get()
del entry['Last-Modified']
entry['Last-Modified'] = last_modified.format()
fixup_needed = True
values['display_date'] = entry_date.isoformat()
values['utc_date'] = entry_date.to('utc').datetime
values['local_date'] = entry_date.naive
logger.debug("getting entry %s with id %d", fullpath, entry_id)
record = model.Entry.get(id=entry_id)
if record:
logger.debug("Reusing existing entry %d", record.id)
record.set(**values)
else:
record = model.Entry(id=entry_id, **values)
# Update the entry ID
if str(record.id) != entry['Entry-ID']:
del entry['Entry-ID']
entry['Entry-ID'] = str(record.id)
fixup_needed = True
if 'UUID' not in entry:
entry['UUID'] = str(uuid.uuid5(
uuid.NAMESPACE_URL, 'file://' + fullpath))
fixup_needed = True
# add other relationships to the index
path_alias.remove_aliases(record)
if record.visible:
for alias in entry.get_all('Path-Alias', []):
path_alias.set_alias(alias, entry=record)
with orm.db_session:
set_tags = {
t.lower()
for t in entry.get_all('Tag', [])
+ entry.get_all('Hidden-Tag', [])
}
for tag in record.tags:
if tag.key in set_tags:
set_tags.remove(tag.key)
else:
tag.delete()
for tag in set_tags:
model.EntryTag(entry=record, key=tag)
orm.commit()
if record.status == model.PublishStatus.DRAFT.value:
logger.info("Not touching draft entry %s", fullpath)
elif fixup_needed:
logger.info("Fixing up entry %s", fullpath)
save_file(fullpath, entry)
return record
|
def scan_file(fullpath, relpath, assign_id)
|
scan a file and put it into the index
| 2.923084
| 2.905848
| 1.005931
|
load_message.cache_clear()
orm.delete(pa for pa in model.PathAlias if pa.entry.file_path == filepath)
orm.delete(item for item in model.Entry if item.file_path == filepath)
orm.commit()
|
def expire_file(filepath)
|
Expire a record for a missing file
| 7.902005
| 7.446463
| 1.061176
|
load_message.cache_clear()
# This entry no longer exists so delete it, and anything that references it
# SQLite doesn't support cascading deletes so let's just clean up
# manually
orm.delete(pa for pa in model.PathAlias if pa.entry == record)
record.delete()
orm.commit()
|
def expire_record(record)
|
Expire a record for a missing entry
| 15.259574
| 14.974792
| 1.019017
|
if self._record.redirect_url:
return links.resolve(self._record.redirect_url,
self.search_path, kwargs.get('absolute'))
return self._permalink(*args, **kwargs)
|
def _link(self, *args, **kwargs)
|
Returns a link, potentially pre-redirected
| 12.146531
| 9.36412
| 1.297135
|
return flask.url_for('entry',
entry_id=self._record.id,
category=self._record.category if expand else None,
slug_text=self._record.slug_text if expand else None,
_external=absolute,
**kwargs)
|
def _permalink(self, absolute=False, expand=True, **kwargs)
|
Returns a canonical URL for the item
| 4.469878
| 4.444495
| 1.005711
|
return [os.path.dirname(self._record.file_path)] + self.category.search_path
|
def search_path(self)
|
The relative image search path for this entry
| 10.801685
| 9.411337
| 1.147731
|
filepath = self._record.file_path
try:
return load_message(filepath)
except FileNotFoundError:
expire_file(filepath)
empty = email.message.Message()
empty.set_payload('')
return empty
|
def _message(self)
|
get the message payload
| 8.860682
| 7.82729
| 1.132024
|
body, _, is_markdown = self._entry_content
return TrueCallableProxy(
self._get_markup,
body,
is_markdown) if body else CallableProxy(None)
|
def body(self)
|
Get the above-the-fold entry body text
| 24.526352
| 18.885723
| 1.298672
|
_, more, is_markdown = self._entry_content
return TrueCallableProxy(
self._get_markup,
more,
is_markdown) if more else CallableProxy(None)
|
def more(self)
|
Get the below-the-fold entry body text
| 28.002586
| 21.4079
| 1.308049
|
body, more, is_markdown = self._entry_content
return TrueCallableProxy(
self._get_card,
body or more) if is_markdown else CallableProxy(None)
|
def card(self)
|
Get the entry's OpenGraph card
| 35.734249
| 25.834452
| 1.383201
|
if self.get('Summary'):
return self.get('Summary')
body, more, is_markdown = self._entry_content
return TrueCallableProxy(
self._get_summary,
body or more) if is_markdown else CallableProxy(None)
|
def summary(self)
|
Get the entry's summary text
| 18.921902
| 15.839801
| 1.19458
|
if self.get('Last-Modified'):
return arrow.get(self.get('Last-Modified'))
return self.date
|
def last_modified(self)
|
Get the date of last file modification
| 5.026493
| 4.953694
| 1.014696
|
if is_markdown:
return markdown.to_html(
text,
config=kwargs,
search_path=self.search_path)
return html_entry.process(
text,
config=kwargs,
search_path=self.search_path)
|
def _get_markup(self, text, is_markdown, **kwargs)
|
get the rendered markup for an entry
is_markdown -- whether the entry is formatted as Markdown
kwargs -- parameters to pass to the Markdown processor
| 5.435977
| 5.334385
| 1.019045
|
def og_tag(key, val):
return utils.make_tag('meta', {'property': key, 'content': val}, start_end=True)
tags = og_tag('og:title', self.title(markup=False))
tags += og_tag('og:url', self.link(absolute=True))
card = cards.extract_card(text, kwargs, self.search_path)
for image in card.images:
tags += og_tag('og:image', image)
if card.description:
tags += og_tag('og:description',
self.get('Summary', card.description))
return flask.Markup(tags)
|
def _get_card(self, text, **kwargs)
|
Render out the tags for a Twitter/OpenGraph card for this entry.
| 5.312647
| 4.978813
| 1.067051
|
card = cards.extract_card(text, kwargs, self.search_path)
return flask.Markup((card.description or '').strip())
|
def _get_summary(self, text, **kwargs)
|
Render out just the summary
| 22.024195
| 19.004595
| 1.158888
|
spec = self._pagination_default_spec(kwargs)
spec.update(kwargs)
query = queries.build_query(spec)
query = queries.where_before_entry(query, self._record)
for record in query.order_by(orm.desc(model.Entry.local_date),
orm.desc(model.Entry.id))[:1]:
return Entry(record)
return None
|
def _previous(self, **kwargs)
|
Get the previous item in any particular category
| 7.364116
| 6.693603
| 1.100172
|
spec = self._pagination_default_spec(kwargs)
spec.update(kwargs)
query = queries.build_query(spec)
query = queries.where_after_entry(query, self._record)
for record in query.order_by(model.Entry.local_date,
model.Entry.id)[:1]:
return Entry(record)
return None
|
def _next(self, **kwargs)
|
Get the next item in any particular category
| 8.34673
| 7.608843
| 1.096978
|
# copy the necessary configuration values over
this_module = sys.modules[__name__]
for name, value in cfg.items():
if hasattr(this_module, name):
setattr(this_module, name, value)
|
def setup(cfg)
|
set up the global configuration from an object
| 3.659656
| 3.595054
| 1.017969
|
_, ext = os.path.splitext(template.filename)
return EXTENSION_MAP.get(ext, 'text/html; charset=utf-8')
|
def mime_type(template)
|
infer the content-type from the extension
| 3.882891
| 3.741551
| 1.037776
|
if isinstance(template_list, str):
template_list = [template_list]
for template in template_list:
path = os.path.normpath(category)
while path is not None:
for extension in ['', '.html', '.htm', '.xml', '.json']:
candidate = os.path.join(path, template + extension)
file_path = os.path.join(config.template_folder, candidate)
if os.path.isfile(file_path):
return Template(template, candidate, file_path)
parent = os.path.dirname(path)
if parent != path:
path = parent
else:
path = None
|
def map_template(category, template_list)
|
Given a file path and an acceptable list of templates, return the
best-matching template's path relative to the configured template
directory.
Arguments:
category -- The path to map
template_list -- A template to look up (as a string), or a list of templates.
| 2.631252
| 2.526916
| 1.04129
|
if isinstance(relation, Entry):
path = relation.category.path
elif isinstance(relation, Category):
path = relation.path
else:
path = relation
tmpl = map_template(path, template)
return tmpl.filename if tmpl else None
|
def get_template(template, relation)
|
Given an entry or a category, return the path to a related template
| 4.900012
| 3.677231
| 1.332528
|
path = []
if entry is not None:
path += entry.search_path
if category is not None:
# Since the category might be different than the entry's category we add
# this too
path += category.search_path
if template is not None:
path.append(os.path.join(
config.content_folder,
os.path.dirname(template.filename)))
return lambda filename: image.get_image(filename, path)
|
def image_function(template=None, entry=None, category=None)
|
Get a function that gets an image
| 4.86854
| 4.66468
| 1.043703
|
text = render_template(
template.filename,
template=template,
image=image_function(
template=template,
category=kwargs.get('category'),
entry=kwargs.get('entry')),
**kwargs
)
return text, caching.get_etag(text)
|
def render_publ_template(template, **kwargs)
|
Render out a template, providing the image function based on the args.
Returns tuple of (rendered text, etag)
| 6.476563
| 5.652702
| 1.145746
|
if isinstance(error_codes, int):
error_codes = [error_codes]
error_code = error_codes[0]
template_list = [str(code) for code in error_codes]
template_list.append(str(int(error_code / 100) * 100))
template_list.append('error')
template = map_template(category, template_list)
if template:
return render_publ_template(
template,
_url_root=request.url_root,
category=Category(category),
error={'code': error_code, 'message': error_message},
exception=exception)[0], error_code
# no template found, so fall back to default Flask handler
return flask.abort(error_code)
|
def render_error(category, error_message, error_codes, exception=None)
|
Render an error page.
Arguments:
category -- The category of the request
error_message -- The message to provide to the error template
error_codes -- The applicable HTTP error code(s). Will usually be an
integer or a list of integers; the HTTP error response will always
be the first error code in the list, and the others are alternates
for looking up the error template to use.
exception -- Any exception that led to this error page
| 3.804646
| 3.770544
| 1.009044
|
_, _, category = str.partition(request.path, '/')
qsize = index.queue_length()
if isinstance(error, http_error.NotFound) and qsize:
response = flask.make_response(render_error(
category, "Site reindex in progress (qs={})".format(qsize), 503))
response.headers['Retry-After'] = qsize
response.headers['Refresh'] = max(5, qsize / 5)
return response, 503
if isinstance(error, http_error.HTTPException):
return render_error(category, error.name, error.code, exception={
'type': type(error).__name__,
'str': error.description,
'args': error.args
})
return render_error(category, "Exception occurred", 500, exception={
'type': type(error).__name__,
'str': str(error),
'args': error.args
})
|
def render_exception(error)
|
Catch-all renderer for the top-level exception handler
| 3.931853
| 3.906155
| 1.006579
|
redir = path_alias.get_redirect('/' + path)
if not redir:
raise http_error.NotFound("Path redirection not found")
return redir
|
def render_path_alias(path)
|
Render a known path-alias (used primarily for forced .php redirects)
| 8.898857
| 7.765512
| 1.145946
|
# pylint:disable=too-many-return-statements
# See if this is an aliased path
redir = get_redirect()
if redir:
return redir
# Forbidden template types
if template and template.startswith('_'):
raise http_error.Forbidden("Template is private")
if template in ['entry', 'error']:
raise http_error.BadRequest("Invalid view requested")
if category:
# See if there's any entries for the view...
if not orm.select(e for e in model.Entry if e.category == category or
e.category.startswith(category + '/')):
raise http_error.NotFound("No such category")
if not template:
template = Category(category).get('Index-Template') or 'index'
tmpl = map_template(category, template)
if not tmpl:
# this might actually be a malformed category URL
test_path = '/'.join((category, template)) if category else template
logger.debug("Checking for malformed category %s", test_path)
record = orm.select(
e for e in model.Entry if e.category == test_path).exists()
if record:
return redirect(url_for('category', category=test_path, **request.args))
# nope, we just don't know what this is
raise http_error.NotFound("No such view")
view_spec = view.parse_view_spec(request.args)
view_spec['category'] = category
view_obj = view.View(view_spec)
rendered, etag = render_publ_template(
tmpl,
_url_root=request.url_root,
category=Category(category),
view=view_obj)
if request.if_none_match.contains(etag):
return 'Not modified', 304
return rendered, {'Content-Type': mime_type(tmpl),
'ETag': etag}
|
def render_category(category='', template=None)
|
Render a category page.
Arguments:
category -- The category to render
template -- The template to render it with
| 4.891937
| 5.029342
| 0.972679
|
# pylint: disable=too-many-return-statements
# check if it's a valid entry
record = model.Entry.get(id=entry_id)
if not record:
# It's not a valid entry, so see if it's a redirection
path_redirect = get_redirect()
if path_redirect:
return path_redirect
logger.info("Attempted to retrieve nonexistent entry %d", entry_id)
raise http_error.NotFound("No such entry")
# see if the file still exists
if not os.path.isfile(record.file_path):
expire_record(record)
# See if there's a redirection
path_redirect = get_redirect()
if path_redirect:
return path_redirect
raise http_error.NotFound("No such entry")
# Show an access denied error if the entry has been set to draft mode
if record.status == model.PublishStatus.DRAFT.value:
raise http_error.Forbidden("Entry not available")
# Show a gone error if the entry has been deleted
if record.status == model.PublishStatus.GONE.value:
raise http_error.Gone()
# check if the canonical URL matches
if record.category != category or record.slug_text != slug_text:
# This could still be a redirected path...
path_redirect = get_redirect()
if path_redirect:
return path_redirect
# Redirect to the canonical URL
return redirect(url_for('entry',
entry_id=entry_id,
category=record.category,
slug_text=record.slug_text))
# if the entry canonically redirects, do that now
entry_redirect = record.redirect_url
if entry_redirect:
return redirect(entry_redirect)
entry_template = (record.entry_template
or Category(category).get('Entry-Template')
or 'entry')
tmpl = map_template(category, entry_template)
if not tmpl:
raise http_error.BadRequest("Missing entry template")
# Get the viewable entry
entry_obj = Entry(record)
# does the entry-id header mismatch? If so the old one is invalid
if int(entry_obj.get('Entry-ID')) != record.id:
expire_record(record)
return redirect(url_for('entry', entry_id=int(entry_obj.get('Entry-Id'))))
rendered, etag = render_publ_template(
tmpl,
_url_root=request.url_root,
entry=entry_obj,
category=Category(category))
if request.if_none_match.contains(etag):
return 'Not modified', 304
return rendered, {'Content-Type': mime_type(tmpl),
'ETag': etag}
|
def render_entry(entry_id, slug_text='', category='')
|
Render an entry page.
Arguments:
entry_id -- The numeric ID of the entry to render
slug_text -- The expected URL slug text
category -- The expected category
| 3.706204
| 3.693904
| 1.00333
|
if request.if_none_match.contains('chit') or request.if_modified_since:
return 'Not modified', 304
out_bytes = base64.b64decode(
"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
return out_bytes, {'Content-Type': 'image/gif', 'ETag': 'chit',
'Last-Modified': 'Tue, 31 Jul 1990 08:00:00 -0000'}
|
def render_transparent_chit()
|
Render a transparent chit for external, sized images
| 3.271289
| 3.139154
| 1.042092
|
record = model.Image.get(asset_name=filename)
if not record:
raise http_error.NotFound("File not found")
if not record.is_asset:
raise http_error.Forbidden()
return flask.send_file(record.file_path, conditional=True)
|
def retrieve_asset(filename)
|
Retrieves a non-image asset associated with an entry
| 4.728022
| 4.851857
| 0.974477
|
now = time.time()
for func, spec in self.tasks.items():
if force or now >= spec.get('next_run', 0):
func()
spec['next_run'] = now + spec['interval']
|
def run(self, force=False)
|
Run all pending tasks; 'force' will run all tasks whether they're
pending or not.
| 3.635842
| 3.499752
| 1.038886
|
record = model.Image.get(file_path=file_path)
fingerprint = ','.join((utils.file_fingerprint(file_path),
str(RENDITION_VERSION)))
if not record or record.fingerprint != fingerprint:
# Reindex the file
logger.info("Updating image %s -> %s", file_path, fingerprint)
# compute the md5sum; from https://stackoverflow.com/a/3431838/318857
md5 = hashlib.md5()
md5.update(bytes(RENDITION_VERSION))
with open(file_path, 'rb') as file:
for chunk in iter(lambda: file.read(16384), b""):
md5.update(chunk)
values = {
'file_path': file_path,
'checksum': md5.hexdigest(),
'fingerprint': fingerprint,
}
try:
image = PIL.Image.open(file_path)
image = fix_orientation(image)
except IOError:
image = None
if image:
values['width'] = image.width
values['height'] = image.height
values['transparent'] = image.mode in ('RGBA', 'P')
values['is_asset'] = False
else:
# PIL could not figure out what file type this is, so treat it as
# an asset
values['is_asset'] = True
values['asset_name'] = os.path.join(values['checksum'][:5],
os.path.basename(file_path))
record = model.Image.get(file_path=file_path)
if record:
record.set(**values)
else:
record = model.Image(**values)
orm.commit()
return record
|
def _get_asset(file_path)
|
Get the database record for an asset file
| 3.069978
| 2.981515
| 1.029671
|
if path.startswith('@'):
return StaticImage(path[1:], search_path)
if path.startswith('//') or '://' in path:
return RemoteImage(path, search_path)
if os.path.isabs(path):
file_path = utils.find_file(os.path.relpath(
path, '/'), config.content_folder)
else:
file_path = utils.find_file(path, search_path)
if not file_path:
return ImageNotFound(path, search_path)
record = _get_asset(file_path)
if record.is_asset:
return FileAsset(record, search_path)
return LocalImage(record, search_path)
|
def get_image(path, search_path)
|
Get an Image object. If the path is given as absolute, it will be
relative to the content directory; otherwise it will be relative to the
search path.
path -- the image's filename
search_path -- a search path for the image (string or list of strings)
| 3.151083
| 3.113281
| 1.012142
|
# per https://stackoverflow.com/a/49723227/318857
args = 'f({})'.format(args)
tree = ast.parse(args)
funccall = tree.body[0].value
args = [ast.literal_eval(arg) for arg in funccall.args]
kwargs = {arg.arg: ast.literal_eval(arg.value)
for arg in funccall.keywords}
if len(args) > 2:
raise TypeError(
"Expected at most 2 positional args but {} were given".format(len(args)))
if len(args) >= 1:
kwargs['width'] = int(args[0])
if len(args) >= 2:
kwargs['height'] = int(args[1])
return kwargs
|
def parse_arglist(args)
|
Parses an arglist into arguments for Image, as a kwargs dict
| 2.993383
| 2.773637
| 1.079227
|
match = re.match(r'([^\{]*)(\{(.*)\})$', alt)
if match:
alt = match.group(1)
args = parse_arglist(match.group(3))
else:
args = {}
return alt, args
|
def parse_alt_text(alt)
|
Parses the arguments out from a Publ-Markdown alt text into a tuple of text, args
| 3.511517
| 3.357727
| 1.045802
|
# I was having trouble coming up with a single RE that did it right,
# so let's just break it down into sub-problems. First, parse out the
# alt text...
match = re.match(r'(.+)\s+\"(.*)\"\s*$', spec)
if match:
spec, title = match.group(1, 2)
else:
title = None
# and now parse out the arglist
match = re.match(r'([^\{]*)(\{(.*)\})\s*$', spec)
if match:
spec = match.group(1)
args = parse_arglist(match.group(3))
else:
args = {}
return spec, args, (title and html.unescape(title))
|
def parse_image_spec(spec)
|
Parses out a Publ-Markdown image spec into a tuple of path, args, title
| 4.899119
| 4.49414
| 1.090113
|
spec_list = [spec.strip() for spec in image_specs.split('|')]
original_count = len(spec_list)
if 'count' in container_args:
if 'count_offset' in container_args:
spec_list = spec_list[container_args['count_offset']:]
spec_list = spec_list[:container_args['count']]
return spec_list, original_count
|
def get_spec_list(image_specs, container_args)
|
Given a list of specs and a set of container args, return a tuple of
the final container argument list and the original list size
| 2.695432
| 2.590846
| 1.040368
|
if os.path.isfile(os.path.join(config.static_folder, filename)):
return flask.redirect(flask.url_for('static', filename=filename))
retry_count = int(flask.request.args.get('retry_count', 0))
if retry_count < 10:
time.sleep(0.25) # ghastly hack to get the client to backoff a bit
return flask.redirect(flask.url_for('async',
filename=filename,
cb=random.randint(0, 2**48),
retry_count=retry_count + 1))
# the image isn't available yet; generate a placeholder and let the
# client attempt to re-fetch periodically, maybe
vals = [int(b) for b in hashlib.md5(
filename.encode('utf-8')).digest()[0:12]]
placeholder = PIL.Image.new('RGB', (2, 2))
placeholder.putdata(list(zip(vals[0::3], vals[1::3], vals[2::3])))
outbytes = io.BytesIO()
placeholder.save(outbytes, "PNG")
outbytes.seek(0)
response = flask.make_response(
flask.send_file(outbytes, mimetype='image/png'))
response.headers['Refresh'] = 5
return response
|
def get_async(filename)
|
Asynchronously fetch an image
| 3.328413
| 3.230788
| 1.030217
|
add = {}
if 'prefix' in kwargs:
attr_prefixes = kwargs.get('prefix')
if isinstance(kwargs['prefix'], str):
attr_prefixes = [attr_prefixes]
for prefix in attr_prefixes:
for k, val in kwargs.items():
if k.startswith(prefix):
add[k[len(prefix):]] = val
return self._get_img_attrs(style, {**kwargs, **add})
|
def get_img_attrs(self, style=None, **kwargs)
|
Get an attribute list (src, srcset, style, et al) for the image.
style -- an optional list of CSS style fragments
Returns: a dict of attributes e.g. {'src':'foo.jpg','srcset':'foo.jpg 1x, bar.jpg 2x']
| 3.174178
| 3.431723
| 0.924952
|
try:
style = []
for key in ('img_style', 'style'):
if key in kwargs:
if isinstance(kwargs[key], (list, tuple, set)):
style += list(kwargs[key])
else:
style.append(kwargs[key])
if 'shape' in kwargs:
shape = self._get_shape_style(**kwargs)
if shape:
style.append("shape-outside: url('{}')".format(shape))
attrs = {
'alt': alt_text,
'title': title,
**self.get_img_attrs(style, **kwargs)
}
return flask.Markup(
self._wrap_link_target(
kwargs,
utils.make_tag(
'img', attrs, start_end=kwargs.get('xhtml')),
title))
except FileNotFoundError as error:
text = '<span class="error">Image not found: <code>{}</code>'.format(
html.escape(error.filename))
if ' ' in error.filename:
text += ' (Did you forget a <code>|</code>?)'
text += '</span>'
return flask.Markup(text)
|
def get_img_tag(self, title='', alt_text='', **kwargs)
|
Build a <img> tag for the image with the specified options.
Returns: an HTML fragment.
| 4.09026
| 4.172644
| 0.980256
|
text = self._css_background(**kwargs)
if uncomment:
text = ' */ {} /* '.format(text)
return text
|
def get_css_background(self, uncomment=False, **kwargs)
|
Get the CSS background attributes for an element.
Additional arguments:
uncomment -- surround the attributes with `*/` and `/*` so that the
template tag can be kept inside a comment block, to keep syntax
highlighters happy
| 8.364498
| 8.789392
| 0.951658
|
fullsize_args = {}
if 'absolute' in kwargs:
fullsize_args['absolute'] = kwargs['absolute']
for key in ('width', 'height', 'quality', 'format', 'background', 'crop'):
fsk = 'fullsize_' + key
if fsk in kwargs:
fullsize_args[key] = kwargs[fsk]
img_fullsize, _ = self.get_rendition(1, **fullsize_args)
return img_fullsize
|
def get_fullsize(self, kwargs)
|
Get the fullsize rendition URL
| 3.240235
| 3.024881
| 1.071194
|
return utils.make_tag('a', {
'href': self.get_fullsize(kwargs),
'data-lightbox': kwargs['gallery_id'],
'title': title
})
|
def _fullsize_link_tag(self, kwargs, title)
|
Render a <a href> that points to the fullsize rendition specified
| 5.172065
| 5.555357
| 0.931005
|
spec = alias.split()
path = spec[0]
values = {**kwargs, 'path': path}
if len(spec) > 1:
values['template'] = spec[1]
record = model.PathAlias.get(path=path)
if record:
record.set(**values)
else:
record = model.PathAlias(**values)
orm.commit()
return record
|
def set_alias(alias, **kwargs)
|
Set a path alias.
Arguments:
alias -- The alias specification
entry -- The entry to alias it to
category -- The category to alias it to
url -- The external URL to alias it to
| 4.355869
| 4.356818
| 0.999782
|
orm.delete(p for p in model.PathAlias if p.path == path)
orm.commit()
|
def remove_alias(path)
|
Remove a path alias.
Arguments:
path -- the path to remove the alias of
| 10.083405
| 13.047295
| 0.772835
|
if isinstance(target, model.Entry):
orm.delete(p for p in model.PathAlias if p.entry == target)
elif isinstance(target, model.Category):
orm.delete(p for p in model.PathAlias if p.category == target)
else:
raise TypeError("Unknown type {}".format(type(target)))
orm.commit()
|
def remove_aliases(target)
|
Remove all aliases to a destination
| 3.596749
| 3.5352
| 1.01741
|
# pylint:disable=too-many-return-statements
record = model.PathAlias.get(path=path)
if not record:
return None, None
template = record.template if record.template != 'index' else None
if record.entry and record.entry.visible:
if record.template:
# a template was requested, so we go to the category page
category = (record.category.category
if record.category else record.entry.category)
return url_for('category',
start=record.entry.id,
template=template,
category=category), True
from . import entry # pylint:disable=cyclic-import
outbound = entry.Entry(record.entry).get('Redirect-To')
if outbound:
# The entry has a Redirect-To (soft redirect) header
return outbound, False
return url_for('entry',
entry_id=record.entry.id,
category=record.entry.category,
slug_text=record.entry.slug_text), True
if record.category:
return url_for('category',
category=record.category.category,
template=template), True
if record.url:
# This is an outbound URL that might be changed by the user, so
# we don't do a 301 Permanently moved
return record.url, False
return None, None
|
def get_alias(path)
|
Get a path alias for a single path
Returns a tuple of (url,is_permanent)
| 4.702373
| 4.630721
| 1.015473
|
if isinstance(paths, str):
paths = [paths]
for path in paths:
url, permanent = get_alias(path)
if url:
return redirect(url, 301 if permanent else 302)
url, permanent = current_app.get_path_regex(path)
if url:
return redirect(url, 301 if permanent else 302)
return None
|
def get_redirect(paths)
|
Get a redirect from a path or list of paths
Arguments:
paths -- either a single path string, or a list of paths to check
Returns: a flask.redirect() result
| 2.995183
| 2.781077
| 1.076987
|
exif_orientation_tag = 0x0112
exif_transpose_sequences = [
[],
[],
[PIL.Image.FLIP_LEFT_RIGHT],
[PIL.Image.ROTATE_180],
[PIL.Image.FLIP_TOP_BOTTOM],
[PIL.Image.FLIP_LEFT_RIGHT, PIL.Image.ROTATE_90],
[PIL.Image.ROTATE_270],
[PIL.Image.FLIP_TOP_BOTTOM, PIL.Image.ROTATE_90],
[PIL.Image.ROTATE_90],
]
try:
# pylint:disable=protected-access
orientation = image._getexif()[exif_orientation_tag]
sequence = exif_transpose_sequences[orientation]
return functools.reduce(type(image).transpose, sequence, image)
except (TypeError, AttributeError, KeyError):
# either no EXIF tags or no orientation tag
pass
return image
|
def fix_orientation(image)
|
adapted from https://stackoverflow.com/a/30462851/318857
Apply Image.transpose to ensure 0th row of pixels is at the visual
top of the image, and 0th column is the visual left-hand side.
Return the original image if unable to determine the orientation.
As per CIPA DC-008-2012, the orientation field contains an integer,
1 through 8. Other values are reserved.
| 1.946969
| 1.957872
| 0.994431
|
if not LocalImage._thread_pool:
logger.info("Starting LocalImage threadpool")
LocalImage._thread_pool = concurrent.futures.ThreadPoolExecutor(
thread_name_prefix="Renderer")
return LocalImage._thread_pool
|
def thread_pool()
|
Get the rendition threadpool
| 5.591059
| 4.567025
| 1.224224
|
# pylint:disable=too-many-locals
basename, ext = os.path.splitext(
os.path.basename(self._record.file_path))
basename = utils.make_slug(basename)
if kwargs.get('format'):
ext = '.' + kwargs['format']
# The spec for building the output filename
out_spec = [basename, self._record.checksum[-10:]]
out_args = {}
if ext in ['.png', '.jpg', '.jpeg']:
out_args['optimize'] = True
crop = self._parse_tuple_string(kwargs.get('crop'))
size, box = self.get_rendition_size(kwargs, output_scale, crop)
box = self._adjust_crop_box(box, crop)
if size and (size[0] < self._record.width or size[1] < self._record.height):
out_spec.append('x'.join([str(v) for v in size]))
if box:
# pylint:disable=not-an-iterable
out_spec.append('-'.join([str(v) for v in box]))
# Set RGBA flattening options
flatten = self._record.transparent and ext not in ['.png', '.gif']
if flatten and 'background' in kwargs:
bg_color = kwargs['background']
if isinstance(bg_color, (tuple, list)):
out_spec.append('b' + '-'.join([str(a) for a in bg_color]))
else:
out_spec.append('b' + str(bg_color))
# Set JPEG quality
if ext in ('.jpg', '.jpeg') and kwargs.get('quality'):
out_spec.append('q' + str(kwargs['quality']))
out_args['quality'] = kwargs['quality']
if ext in ('.jpg', '.jpeg'):
out_args['optimize'] = True
# Build the output filename
out_basename = '_'.join([str(s) for s in out_spec]) + ext
out_rel_path = os.path.join(
config.image_output_subdir,
self._record.checksum[0:2],
self._record.checksum[2:6],
out_basename)
out_fullpath = os.path.join(config.static_folder, out_rel_path)
if os.path.isfile(out_fullpath):
os.utime(out_fullpath)
return utils.static_url(out_rel_path, kwargs.get('absolute')), size
LocalImage.thread_pool().submit(
self._render, out_fullpath, size, box, flatten, kwargs, out_args)
return flask.url_for('async', filename=out_rel_path, _external=kwargs.get('absolute')), size
|
def get_rendition(self, output_scale=1, **kwargs)
|
Get the rendition for this image, generating it if necessary.
Returns a tuple of `(relative_path, width, height)`, where relative_path
is relative to the static file directory (i.e. what one would pass into
`get_static()`)
output_scale -- the upsample factor for the requested rendition
Keyword arguments:
scale -- the downsample factor for the base rendition
scale_min_width -- the minimum width after downsampling
scale_min_height -- the minimum height after downsampling
crop -- box to crop the original image into (left, top, right, bottom)
width -- the width to target
height -- the height to target
max_width -- the maximum width
max_height -- the maximum height
resize -- how to fit the width and height; "fit", "fill", or "stretch"
fill_crop_x -- horizontal offset fraction for resize="fill"
fill_crop_y -- vertical offset fraction for resize="fill"
format -- output format
background -- background color when converting transparent to opaque
quality -- the JPEG quality to save the image as
quantize -- how large a palette to use for GIF or PNG images
| 3.186717
| 3.185968
| 1.000235
|
if crop and box:
# Both boxes are the same size; just line them up.
return (box[0] + crop[0], box[1] + crop[1],
box[2] + crop[0], box[3] + crop[1])
if crop:
# We don't have a fit box, so just convert the crop box
return (crop[0], crop[1], crop[0] + crop[2], crop[1] + crop[3])
# We don't have a crop box, so return the fit box (even if it's None)
return box
|
def _adjust_crop_box(box, crop)
|
Given a fit box and a crop box, adjust one to the other
| 3.621979
| 3.004794
| 1.2054
|
if isinstance(argument, str):
return tuple(int(p.strip()) for p in argument.split(','))
return argument
|
def _parse_tuple_string(argument)
|
Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d)
| 3.96669
| 3.223782
| 1.230446
|
if crop:
# Use the cropping rectangle size
_, _, width, height = crop
else:
# Use the original image size
width = self._record.width
height = self._record.height
mode = spec.get('resize', 'fit')
if mode == 'fit':
return self.get_rendition_fit_size(spec, width, height, output_scale)
if mode == 'fill':
return self.get_rendition_fill_size(spec, width, height, output_scale)
if mode == 'stretch':
return self.get_rendition_stretch_size(spec, width, height, output_scale)
raise ValueError("Unknown resize mode {}".format(mode))
|
def get_rendition_size(self, spec, output_scale, crop)
|
Wrapper to determine the overall rendition size and cropping box
Returns tuple of (size,box)
| 2.494316
| 2.54691
| 0.97935
|
width = input_w
height = input_h
scale = spec.get('scale')
if scale:
width = width / scale
height = height / scale
min_width = spec.get('scale_min_width')
if min_width and width < min_width:
height = height * min_width / width
width = min_width
min_height = spec.get('scale_min_height')
if min_height and height < min_height:
width = width * min_height / height
height = min_height
tgt_width, tgt_height = spec.get('width'), spec.get('height')
if tgt_width and width > tgt_width:
height = height * tgt_width / width
width = tgt_width
if tgt_height and height > tgt_height:
width = width * tgt_height / height
height = tgt_height
tgt_width, tgt_height = spec.get('max_width'), spec.get('max_height')
if tgt_width and width > tgt_width:
height = height * tgt_width / width
width = tgt_width
if tgt_height and height > tgt_height:
width = width * tgt_height / height
height = tgt_height
width = width * output_scale
height = height * output_scale
# Never scale to larger than the base rendition
width = min(round(width), input_w)
height = min(round(height), input_h)
return (width, height), None
|
def get_rendition_fit_size(spec, input_w, input_h, output_scale)
|
Determine the scaled size based on the provided spec
| 1.676542
| 1.668312
| 1.004933
|
width = input_w
height = input_h
scale = spec.get('scale')
if scale:
width = width / scale
height = height / scale
if spec.get('scale_min_width'):
width = max(width, spec['spec_min_width'])
if spec.get('scale_min_height'):
height = max(height, spec['scale_min_height'])
if spec.get('width'):
width = min(width, spec['width'])
if spec.get('max_width'):
width = min(width, spec['max_width'])
if spec.get('height'):
height = min(height, spec['height'])
if spec.get('max_height'):
height = min(height, spec['max_height'])
width = width * output_scale
height = height * output_scale
# Never scale to larger than the base rendition (but keep the output
# aspect)
if width > input_w:
height = height * input_w / width
width = input_w
if height > input_h:
width = width * input_h / height
height = input_h
# Determine the box size
box_w = min(input_w, round(width * input_h / height))
box_h = min(input_h, round(height * input_w / width))
# Box offset
box_x = round((input_w - box_w) * spec.get('fill_crop_x', 0.5))
box_y = round((input_h - box_h) * spec.get('fill_crop_y', 0.5))
return (round(width), round(height)), (box_x, box_y, box_x + box_w, box_y + box_h)
|
def get_rendition_fill_size(spec, input_w, input_h, output_scale)
|
Determine the scale-crop size given the provided spec
| 1.988589
| 1.970222
| 1.009322
|
width = input_w
height = input_h
scale = spec.get('scale')
if scale:
width = width / scale
height = height / scale
min_width = spec.get('scale_min_width')
if min_width and width < min_width:
width = min_width
min_height = spec.get('scale_min_height')
if min_height and height < min_height:
height = min_height
tgt_width, tgt_height = spec.get('width'), spec.get('height')
if tgt_width and width > tgt_width:
width = tgt_width
tgt_height = spec.get('height')
if tgt_height and height > tgt_height:
height = tgt_height
tgt_width, tgt_height = spec.get('max_width'), spec.get('max_height')
if tgt_width and width > tgt_width:
width = tgt_width
tgt_height = spec.get('height')
if tgt_height and height > tgt_height:
height = tgt_height
width = width * output_scale
height = height * output_scale
return (round(width), round(height)), None
|
def get_rendition_stretch_size(spec, input_w, input_h, output_scale)
|
Determine the scale-crop size given the provided spec
| 1.723435
| 1.680101
| 1.025793
|
if bgcolor:
background = PIL.Image.new('RGB', image.size, bgcolor)
background.paste(image, mask=image.split()[3])
return background
return image.convert('RGB')
|
def flatten(image, bgcolor=None)
|
Flatten an image, with an optional background color
| 2.461809
| 2.484261
| 0.990962
|
img_1x, size = self.get_rendition(
1, **utils.remap_args(kwargs, {"quality": "quality_ldpi"}))
img_2x, _ = self.get_rendition(
2, **utils.remap_args(kwargs, {"quality": "quality_hdpi"}))
return (img_1x, img_2x, size)
|
def _get_renditions(self, kwargs)
|
Get a bunch of renditions; returns a tuple of 1x, 2x, size
| 4.126805
| 3.493809
| 1.181177
|
# Get the 1x and 2x renditions
img_1x, img_2x, size = self._get_renditions(kwargs)
return {
'src': img_1x,
'width': size[0],
'height': size[1],
'srcset': "{} 1x, {} 2x".format(img_1x, img_2x) if img_1x != img_2x else None,
'style': ';'.join(style) if style else None,
'class': kwargs.get('class', kwargs.get('img_class')),
'id': kwargs.get('img_id')
}
|
def _get_img_attrs(self, style, kwargs)
|
Get the attributes of an an <img> tag for this image, hidpi-aware
| 2.97117
| 2.842361
| 1.045318
|
# Get the 1x and 2x renditions
img_1x, img_2x, _ = self._get_renditions(kwargs)
tmpl = 'background-image: url("{s1x}");'
if img_1x != img_2x:
image_set = 'image-set(url("{s1x}") 1x, url("{s2x}") 2x)'
tmpl += 'background-image: {ss};background-image: -webkit-{ss};'.format(
ss=image_set)
return tmpl.format(s1x=img_1x, s2x=img_2x)
|
def _css_background(self, **kwargs)
|
Get the CSS specifiers for this as a hidpi-capable background image
| 3.629845
| 3.298181
| 1.10056
|
processor = HTMLEntry(config, search_path)
processor.feed(text)
text = processor.get_data()
if not config.get('no_smartquotes'):
text = misaka.smartypants(text)
return flask.Markup(text)
|
def process(text, config, search_path)
|
Process an HTML entry's HTML
| 5.992612
| 5.296183
| 1.131496
|
if tag.lower() == 'img':
attrs = self._image_attrs(attrs)
# Remap the attributes
out_attrs = []
for key, val in attrs:
if (key.lower() == 'href'
or (key.lower() == 'src' and not tag.lower() == 'img')):
out_attrs.append((key, links.resolve(
val, self._search_path, self._config.get('absolute'))))
else:
out_attrs.append((key, val))
self.append(
utils.make_tag(
tag,
out_attrs,
self_closing))
|
def _handle_tag(self, tag, attrs, self_closing)
|
Handle a tag.
attrs -- the attributes of the tag
self_closing -- whether this is self-closing
| 3.781597
| 3.692881
| 1.024024
|
path = None
config = {**self._config}
for key, val in attrs:
if key.lower() == 'width' or key.lower() == 'height':
try:
config[key.lower()] = int(val)
except ValueError:
pass
elif key.lower() == 'src':
path = val
img_path, img_args, _ = image.parse_image_spec(path)
img = image.get_image(img_path, self._search_path)
for key, val in img_args.items():
if val and key not in config:
config[key] = val
try:
img_attrs = img.get_img_attrs(**config)
except FileNotFoundError as error:
return [('data-publ-error', 'file not found: {}'.format(error.filename))]
# return the original attr list with the computed overrides in place
return [(key, val) for key, val in attrs
if key.lower() not in img_attrs] + list(img_attrs.items())
|
def _image_attrs(self, attrs)
|
Rewrite the SRC attribute on an <img> tag, possibly adding a SRCSET.
| 3.81367
| 3.604005
| 1.058175
|
files = model.FileFingerprint.select().order_by(
orm.desc(model.FileFingerprint.file_mtime))
for file in files:
return file.file_mtime, file.file_path
return None, None
|
def last_modified()
|
information about the most recently modified file
| 5.053577
| 4.89566
| 1.032257
|
logger.debug("Scanning file: %s (%s) %s", fullpath, relpath, assign_id)
def do_scan():
_, ext = os.path.splitext(fullpath)
try:
if ext in ENTRY_TYPES:
logger.info("Scanning entry: %s", fullpath)
return entry.scan_file(fullpath, relpath, assign_id)
if ext in CATEGORY_TYPES:
logger.info("Scanning meta info: %s", fullpath)
return category.scan_file(fullpath, relpath)
return None
except: # pylint: disable=bare-except
logger.exception("Got error parsing %s", fullpath)
return False
result = do_scan()
if result is False and not assign_id:
logger.info("Scheduling fixup for %s", fullpath)
THREAD_POOL.submit(scan_file, fullpath, relpath, True)
else:
logger.debug("%s complete", fullpath)
if result:
set_fingerprint(fullpath)
SCHEDULED_FILES.remove(fullpath)
|
def scan_file(fullpath, relpath, assign_id)
|
Scan a file for the index
fullpath -- The full path to the file
relpath -- The path to the file, relative to its base directory
assign_id -- Whether to assign an ID to the file if not yet assigned
This calls into various modules' scanner functions; the expectation is that
the scan_file function will return a truthy value if it was scanned
successfully, False if it failed, and None if there is nothing to scan.
| 3.127666
| 3.166724
| 0.987666
|
record = model.FileFingerprint.get(file_path=fullpath)
if record:
return record.fingerprint
return None
|
def get_last_fingerprint(fullpath)
|
Get the last known modification time for a file
| 5.745906
| 5.780246
| 0.994059
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.