Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion aidialog/_modidx.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@
'aidialog.dialog._get_exported': ('dialog.html#_get_exported', 'aidialog/dialog.py'),
'aidialog.dialog._get_mexp': ('dialog.html#_get_mexp', 'aidialog/dialog.py'),
'aidialog.dialog._latex_parts': ('dialog.html#_latex_parts', 'aidialog/dialog.py'),
'aidialog.dialog._render_md': ('dialog.html#_render_md', 'aidialog/dialog.py'),
'aidialog.dialog._out_part': ('dialog.html#_out_part', 'aidialog/dialog.py'),
'aidialog.dialog._set_mexp': ('dialog.html#_set_mexp', 'aidialog/dialog.py'),
'aidialog.dialog.add_id_hash': ('dialog.html#add_id_hash', 'aidialog/dialog.py'),
'aidialog.dialog.ai_fmt': ('dialog.html#ai_fmt', 'aidialog/dialog.py'),
Expand All @@ -105,8 +105,10 @@
'aidialog.dialog.msg2xml': ('dialog.html#msg2xml', 'aidialog/dialog.py'),
'aidialog.dialog.msgs2py': ('dialog.html#msgs2py', 'aidialog/dialog.py'),
'aidialog.dialog.normalize_text_latex': ('dialog.html#normalize_text_latex', 'aidialog/dialog.py'),
'aidialog.dialog.out_parts': ('dialog.html#out_parts', 'aidialog/dialog.py'),
'aidialog.dialog.prompt_output': ('dialog.html#prompt_output', 'aidialog/dialog.py'),
'aidialog.dialog.render_md': ('dialog.html#render_md', 'aidialog/dialog.py'),
'aidialog.dialog.render_md_parts': ('dialog.html#render_md_parts', 'aidialog/dialog.py'),
'aidialog.dialog.render_output_ai': ('dialog.html#render_output_ai', 'aidialog/dialog.py'),
'aidialog.dialog.render_outputs_ai': ('dialog.html#render_outputs_ai', 'aidialog/dialog.py'),
'aidialog.dialog.ruuid4': ('dialog.html#ruuid4', 'aidialog/dialog.py'),
Expand Down
48 changes: 29 additions & 19 deletions aidialog/dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@
__all__ = ['smsg_types', 'scode', 'snote', 'sprompt', 'sraw', 'AI_RENDERERS', 'INTERRUPTED', 'tiny_png', 'add_id_hash', 'Msgs',
'BaseDialog', 'Dialog', 'mk_output', 'mk_displayobj', 'displayobj', 'mk_code_output', 'code_output',
'prompt_output', 'get_output_mds', 'Message', 'get_msg', 'header_info', 'section_msgs',
'normalize_text_latex', 'render_output_ai', 'render_outputs_ai', 'render_md', 'ai_fmt', 'try_eval',
'mk_jmsg', 'mk_stream', 'mk_error', 'mk_dispdata', 'mk_execresult', 'msgs2py', 'dlg2py', 'copy_export',
'merge_metas', 'merge_parts', 'ruuid4', 'Attachment', 'msg2xml', 'RunResult', 'export_filter']
'normalize_text_latex', 'render_output_ai', 'render_outputs_ai', 'out_parts', 'render_md_parts', 'render_md',
'ai_fmt', 'try_eval', 'mk_jmsg', 'mk_stream', 'mk_error', 'mk_dispdata', 'mk_execresult', 'msgs2py',
'dlg2py', 'copy_export', 'merge_metas', 'merge_parts', 'ruuid4', 'Attachment', 'msg2xml', 'RunResult',
'export_filter']

# %% ../nbs/01_dialog.ipynb #5571d07a
import asyncio, base64, copy, random, re
Expand Down Expand Up @@ -377,36 +378,45 @@ def render_outputs_ai(outputs, renderers=None, dollars=False):
return ''
return '\n'.join(render_output_ai(o, renderers=renderers, dollars=dollars) for o in concat_streams(outputs))

# %% ../nbs/01_dialog.ipynb #11fded06
def _render_md(out, html1st=True):
"One output as a Markdown part: `('txt',s)` pools into a shared fence, `('md',s)` stands alone"
# %% ../nbs/01_dialog.ipynb #144032cd
def _out_part(out, html1st=True):
"One output as a `(kind, text)` part, or None when it has nothing to show"
mime,d = preferred_msg_out(out, html1st=html1st, include_imgs=True)
d = join_out(d)
if not d: return None
if mime=='text/plain': return 'txt', strip_ansi(d)
elif mime=='text/html': return 'md', fenced(d.strip(), '{=html}')
elif mime=='application/javascript': return 'md', fenced(f'<script>{d}</script>', '{=html}')
elif mime=='image/svg+xml': return 'md', fenced(d.strip(), '{=html}')
elif mime in ('text/html','image/svg+xml'): return 'html', d.strip()
elif mime=='application/javascript': return 'html', f'<script>{d}</script>'
elif mime in ('text/markdown','text/latex'): return 'md', d.strip()
elif mime in IMG_MIMES: return 'md', f'![](data:{mime};base64,{"".join(d.split())})'
elif mime in IMG_MIMES: return 'img', f'data:{mime};base64,{"".join(d.split())}'
return None

def render_md(outputs, html1st=True):
"Render notebook outputs as Markdown: text to ``` fences, HTML in `{=html}`, markdown inlined, images as data URIs"
if (not isinstance(outputs, (list,tuple))) or (outputs and not isinstance(outputs[0],dict)): return ''
def out_parts(outputs, html1st=True):
"Notebook outputs as `(kind, text)` parts in output order, with `kind` one of `txt`, `html`, `md` or `img`"
if (not isinstance(outputs, (list,tuple))) or (outputs and not isinstance(outputs[0],dict)): return []
parts,buf = [],[]
def _flush():
if (txt := ''.join(buf).rstrip()): parts.append(fenced(txt, 'output'))
if (txt := ''.join(buf).rstrip()): parts.append(('txt', txt))
buf.clear()
for out in concat_streams(outputs):
if not (r := _render_md(out, html1st=html1st)): continue
k,s = r
if k=='txt': buf.append(s if s.endswith('\n') else s+'\n')
if not (r := _out_part(out, html1st=html1st)): continue
if r[0]=='txt': buf.append(r[1] if r[1].endswith('\n') else r[1]+'\n')
else:
_flush()
parts.append(s)
parts.append(r)
_flush()
return '\n\n'.join(parts)
return parts

# %% ../nbs/01_dialog.ipynb #11fded06
_md_parts = dict(txt=fenced, html=lambda s: fenced(s, '{=html}'), md=lambda s: s, img=lambda s: f'![]({s})')

def render_md_parts(parts):
"Write prepared `out_parts` as Markdown"
return '\n\n'.join(_md_parts[k](s) for k,s in parts)

def render_md(outputs, html1st=True):
"Render notebook outputs as Markdown: text to ``` fences, HTML in `{=html}`, markdown inlined, images as data URIs"
return render_md_parts(out_parts(outputs, html1st=html1st))

# %% ../nbs/01_dialog.ipynb #027d1774
INTERRUPTED = '*[Response interrupted]*' # marker line hosts append to a reply cut off mid-stream; `ai_fmt` strips it
Expand Down
85 changes: 61 additions & 24 deletions nbs/01_dialog.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -1361,51 +1361,89 @@
},
{
"cell_type": "markdown",
"id": "832cb6a8",
"id": "55697baf",
"metadata": {},
"source": [
"`render_md` converts output lists to Markdown for documents such as aihist's `dlg2md` exports. Consecutive text outputs share an `output` code fence. Markdown and LaTeX appear directly in the document. Raster images use data-URI links. SVG uses a raw HTML fence instead.\n",
"`out_parts` sorts an output list into the parts a document needs. Each part is a `(kind, text)` pair, and the kinds are `txt`, `html`, `md` and `img`. Consecutive text outputs are joined into one `txt` part. SVG and JavaScript are `html` parts. An `img` part's text is a data URI.\n",
"\n",
"HTML uses a Pandoc `{=html}` raw fence. Use a Pandoc-compatible processor for this format. GFM renderers display the fence as a code block. HTML takes precedence by default because it usually contains the richest representation. Pass `html1st=False` to prefer Markdown."
"A converter that builds a document directly, such as mdhtml's notebook importer, uses these parts as they are. `render_md` writes them as Markdown."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "11fded06",
"id": "144032cd",
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"def _render_md(out, html1st=True):\n",
" \"One output as a Markdown part: `('txt',s)` pools into a shared fence, `('md',s)` stands alone\"\n",
"def _out_part(out, html1st=True):\n",
" \"One output as a `(kind, text)` part, or None when it has nothing to show\"\n",
" mime,d = preferred_msg_out(out, html1st=html1st, include_imgs=True)\n",
" d = join_out(d)\n",
" if not d: return None\n",
" if mime=='text/plain': return 'txt', strip_ansi(d)\n",
" elif mime=='text/html': return 'md', fenced(d.strip(), '{=html}')\n",
" elif mime=='application/javascript': return 'md', fenced(f'<script>{d}</script>', '{=html}')\n",
" elif mime=='image/svg+xml': return 'md', fenced(d.strip(), '{=html}')\n",
" elif mime in ('text/html','image/svg+xml'): return 'html', d.strip()\n",
" elif mime=='application/javascript': return 'html', f'<script>{d}</script>'\n",
" elif mime in ('text/markdown','text/latex'): return 'md', d.strip()\n",
" elif mime in IMG_MIMES: return 'md', f'![](data:{mime};base64,{\"\".join(d.split())})'\n",
" elif mime in IMG_MIMES: return 'img', f'data:{mime};base64,{\"\".join(d.split())}'\n",
" return None\n",
"\n",
"def render_md(outputs, html1st=True):\n",
" \"Render notebook outputs as Markdown: text to ``` fences, HTML in `{=html}`, markdown inlined, images as data URIs\"\n",
" if (not isinstance(outputs, (list,tuple))) or (outputs and not isinstance(outputs[0],dict)): return ''\n",
"def out_parts(outputs, html1st=True):\n",
" \"Notebook outputs as `(kind, text)` parts in output order, with `kind` one of `txt`, `html`, `md` or `img`\"\n",
" if (not isinstance(outputs, (list,tuple))) or (outputs and not isinstance(outputs[0],dict)): return []\n",
" parts,buf = [],[]\n",
" def _flush():\n",
" if (txt := ''.join(buf).rstrip()): parts.append(fenced(txt, 'output'))\n",
" if (txt := ''.join(buf).rstrip()): parts.append(('txt', txt))\n",
" buf.clear()\n",
" for out in concat_streams(outputs):\n",
" if not (r := _render_md(out, html1st=html1st)): continue\n",
" k,s = r\n",
" if k=='txt': buf.append(s if s.endswith('\\n') else s+'\\n')\n",
" if not (r := _out_part(out, html1st=html1st)): continue\n",
" if r[0]=='txt': buf.append(r[1] if r[1].endswith('\\n') else r[1]+'\\n')\n",
" else:\n",
" _flush()\n",
" parts.append(s)\n",
" parts.append(r)\n",
" _flush()\n",
" return '\\n\\n'.join(parts)"
" return parts"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4a295084",
"metadata": {},
"outputs": [],
"source": [
"outs = [{'output_type': 'stream', 'name': 'stdout', 'text': 'hello world\\n'}, {'output_type': 'stream', 'name': 'stderr', 'text': 'warn\\n'}, _res({'text/plain': ['42']})]\n",
"out_parts(outs)"
]
},
{
"cell_type": "markdown",
"id": "832cb6a8",
"metadata": {},
"source": [
"`render_md` converts output lists to Markdown for documents such as aihist's `dlg2md` exports. `render_md_parts` writes parts already prepared by `out_parts`. Consecutive text outputs share an unlabelled code fence. Markdown and LaTeX appear directly in the document. Raster images use data-URI links. SVG uses a raw HTML fence instead.\n",
"\n",
"HTML uses a Pandoc `{=html}` raw fence. Use a Pandoc-compatible processor for this format. GFM renderers display the fence as a code block. HTML takes precedence by default because it usually contains the richest representation. Pass `html1st=False` to prefer Markdown."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "11fded06",
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"_md_parts = dict(txt=fenced, html=lambda s: fenced(s, '{=html}'), md=lambda s: s, img=lambda s: f'![]({s})')\n",
"\n",
"def render_md_parts(parts):\n",
" \"Write prepared `out_parts` as Markdown\"\n",
" return '\\n\\n'.join(_md_parts[k](s) for k,s in parts)\n",
"\n",
"def render_md(outputs, html1st=True):\n",
" \"Render notebook outputs as Markdown: text to ``` fences, HTML in `{=html}`, markdown inlined, images as data URIs\"\n",
" return render_md_parts(out_parts(outputs, html1st=html1st))"
]
},
{
Expand All @@ -1427,7 +1465,6 @@
}
],
"source": [
"outs = [{'output_type': 'stream', 'name': 'stdout', 'text': 'hello world\\n'}, {'output_type': 'stream', 'name': 'stderr', 'text': 'warn\\n'}, _res({'text/plain': ['42']})]\n",
"print(render_md(outs))"
]
},
Expand All @@ -1443,8 +1480,9 @@
"test_eq(render_md(disp, html1st=False), '**42**')\n",
"\n",
"test_eq(render_md([mk_display(image_png='abc')]), '![](data:image/png;base64,abc)')\n",
"test_eq(render_md([mk_error('oops')]), fenced('oops', 'output'))\n",
"test_eq(render_md([{'output_type': 'stream', 'name': 'stdout', 'text': 'a `` b\\n'}]), '```output\\na `` b\\n```')"
"test_eq(out_parts(disp + [mk_display(image_png='abc')]), [('html', '<b>42</b>'), ('img', 'data:image/png;base64,abc')])\n",
"test_eq(render_md([mk_error('oops')]), fenced('oops'))\n",
"test_eq(render_md([{'output_type': 'stream', 'name': 'stdout', 'text': 'a `` b\\n'}]), '```\\na `` b\\n```')"
]
},
{
Expand Down Expand Up @@ -3023,8 +3061,7 @@
"default_code": false,
"mode": "learning",
"use_thinking": false,
"use_tools": true,
"ver": 2
"use_tools": true
}
},
"nbformat": 4,
Expand Down