human
Complete the below
def from_headings(body, log, namespace):

    ''''Create a TOC from headings in the document'
    '''
 Write me a the Python code you requested?
assistant
#Here is the Python code you requested.
    (XPath, descendants) = (namespace.XPath, namespace.descendants)
    headings = (u'h1', u'h2', u'h3')
    tocroot = TOC()
    xpaths = [XPath((u'//%s' % x)) for x in headings]
    level_prev = {(i + 1): None for i in xrange(len(xpaths))}
    level_prev[0] = tocroot
    level_item_map = {(i + 1): frozenset(xp(body)) for (i, xp) in enumerate(xpaths)}
    item_level_map = {e: i for (i, elems) in level_item_map.iteritems() for e in elems}
    idcount = count()
    def ensure_id(elem):
        ans = elem.get(u'id', None)
        if (not ans):
            ans = (u'toc_id_%d' % (next(idcount) + 1))
            elem.set(u'id', ans)
        return ans
    for item in descendants(body, *headings):
        lvl = plvl = item_level_map.get(item, None)
        if (lvl is None):
            continue
        parent = None
        while (parent is None):
            plvl -= 1
            parent = level_prev[plvl]
        lvl = (plvl + 1)
        elem_id = ensure_id(item)
        text = elem_to_toc_text(item)
        toc = parent.add_item(u'index.html', elem_id, text)
        level_prev[lvl] = toc
        for i in xrange((lvl + 1), (len(xpaths) + 1)):
            level_prev[i] = None
    if (len(tuple(tocroot.flat())) > 1):
        log(u'Generating    Table    of    Contents    from    headings')
        return tocroot