oralsite.new
clone your own copy | download snapshot

Snapshots | iceberg

Inside this repository

__init__.py
text/x-python

Download raw (4.6 KB)

from pelican import signals
from itertools import repeat
import os.path
import math
from collections import namedtuple

class Cluster (object):
  def __init__ (self, title=''):
    self.title = title
    self.articles = []
    self.page = None
    self.audiolength = {}

def index_in_tuple_list(needle, haystack):
  if not haystack:
    return None
    
  keys, entries = zip(*haystack)

  try:
    return keys.index(needle)
  except ValueError:
    return None
  
def in_tuple_list (needle, haystack):
  return (index_in_tuple_list(needle, haystack) is not None)

def find_in_tuple_list (needle, haystack, key=1):
    index = index_in_tuple_list(needle, haystack)
    if index is not None:
      return haystack[index][key]
    return None

def getFactoredLength (length):
  length = float(length)
  remaining = length
  hours = math.floor(remaining / 3600)
  remaining -= hours * 3600
  minutes = math.floor(remaining / 60)
  remaining -= minutes * 60
  seconds = round(remaining)
  return hours, minutes, seconds

def makeTimelabel (hours=0, minutes=0, seconds=0):
  return ('{}h '.format(hours) if hours else '') + '{:0>2}\' {:0>2}"'.format(str(minutes), str(seconds))


##
## Reorganize articles over chapters and clusters 
## Chapter is a property that is set on both an article and a page
## Clusters are defined on the page file
## An article is inserted into a cluster through 
def make_clusters (generator):
  pages = generator.context.get('pages', [])
  articles = generator.context.get('articles', [])
  chapters = []

  chapter_pages = []
  cluster_pages = []

  # Construct a chapter list.
  # Based on what is found in the pages
  for page in pages:
    # basename = os.path.basename(page.source_path)

    if hasattr(page, 'chapter') and not hasattr(page, 'cluster'):
      chapter_pages.append(page)
    elif hasattr(page, 'cluster'):
      cluster_pages.append(page)


  for page in chapter_pages:
    if hasattr(page, 'chapter') \
      and page.chapter != 'pages' \
      and not in_tuple_list(page.chapter, chapters):
      
      if hasattr(page, 'clusters'):
        page.clusters = [(name, Cluster(title=name)) for name in page.clusters]
        
      page.articles = []
      chapters.append((page.chapter, page))

  cluster_pages = sorted(cluster_pages, key=lambda p: int(p.order) if hasattr(p, 'order') else 9999)

  for page in cluster_pages:
    chapter = find_in_tuple_list(page.chapter, chapters)
    
    if not hasattr(chapter, 'clusters'):
      chapter.clusters = []
    
    page.chapter = chapter
    page.articles = []

    page_cluster_index = index_in_tuple_list(page.cluster, chapter.clusters)
    if page_cluster_index is not None:
      chapter.clusters[page_cluster_index] = (page.cluster, page)
    else:
      chapter.clusters.append((page.cluster, page))

  articles = sorted(articles, key=lambda a: int(a.order) if hasattr(a, 'order') else 9999)

  for article in articles: 
    #print(article, article.title)
    if hasattr(article, 'chapter'):
      chapter = find_in_tuple_list(article.chapter, chapters)
      
      if hasattr(article, 'cluster') and hasattr(chapter, 'clusters'):
        cluster = find_in_tuple_list(article.cluster, chapter.clusters)
        cluster.articles.append(article)
        article.cluster = cluster
        
      chapter.articles.append(article)
      article.chapter = chapter

      # if cluster = article.cluster
      
      # if cluster not in chapters[chapter]['clusters']:
      #   chapters[chapter]['clusters'][cluster] = []

      # chapters[chapter]['clusters'][cluster].append(article)

  for _, chapter in chapters:
    if hasattr(chapter, 'clusters'):
      for _, cluster in chapter.clusters:
        cluster_length = 0

        for article in cluster.articles:
          if hasattr(article, 'audiolength') and article.audiolength:
            cluster_length += article.audiolength['raw']

        if cluster_length > 0:
          cluster.audiolength = {
            'raw': cluster_length,
            'factored': getFactoredLength(cluster_length),
            'formatted': makeTimelabel(*getFactoredLength(cluster_length))
          }

    chapter_length = 0

    for article in chapter.articles:
      if hasattr(article, 'audiolength') and article.audiolength:
        chapter_length += article.audiolength['raw']

    if chapter_length > 0:
      chapter.audiolength = {
        'raw': chapter_length,
        'factored': getFactoredLength(chapter_length),
        'formatted': makeTimelabel(*getFactoredLength(chapter_length))
      }
    

  generator.context['chapters'] = chapters
  

def register():
  # signals.article_generator_finalized.connect(set_category_order)
  signals.page_generator_finalized.connect(make_clusters)