Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix export issues #1018

Merged
merged 2 commits into from
Jan 30, 2025
Merged
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
45 changes: 39 additions & 6 deletions lumen/ai/export.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import base64
import datetime as dt
import json
import os

from io import BytesIO
from textwrap import dedent
from typing import Any

import nbformat

from panel import Column
from panel.chat import ChatMessage, ChatStep
from panel.pane.image import ImageBase

from lumen.ai.views import LumenOutput
from lumen.config import config
Expand Down Expand Up @@ -35,12 +39,41 @@ def make_preamble(preamble: str, extensions: list[str]):
imports = nbformat.v4.new_code_cell(source=source)
return [header, imports]

def format_markdown(msg: ChatMessage):
if msg.avatar.startswith('https://'):
avatar = f'<img src="{msg.avatar}" width=45 height=45></img>'

def serialize_avatar(avatar: str | BytesIO, size: int = 45) -> str:
"""
Process different types of avatar inputs into HTML img tag or text span.

Args:
avatar: Avatar source (URL, BytesIO, PIL Image, or text)
size: Desired width and height of the avatar in pixels

Returns:
HTML string representing the avatar
"""
if isinstance(avatar, ImageBase):
avatar = avatar.object
if isinstance(avatar, BytesIO):
avatar = avatar.getvalue()

if isinstance(avatar, str):
if avatar.startswith(('http://', 'https://')):
return f'<img src="{avatar}" width={size} height={size} alt="avatar" style="border-radius: 50%;"></img>'
elif os.path.exists(avatar):
avatar_path = os.path.abspath(avatar)
return f'<img src="{avatar_path}" width={size} height={size} alt="avatar" style="border-radius: 50%;"></img>'
else:
return f'<span class="text-avatar" style="width: {size}px; height: {size}px; display: inline-flex; align-items: center; justify-content: center; background-color: #f0f0f0; border-radius: 50%;">{avatar[:2].upper()}</span>'
elif isinstance(avatar, bytes):
img_data = base64.b64encode(avatar).decode()
return f'<img src="data:image/png;base64,{img_data}" width={size} height={size} alt="avatar" style="border-radius: 50%;"></img>'
else:
avatar = f'<span>{msg.avatar}</span>'
header = f'<div style="display: flex; flex-direction: row; font-weight: bold; font-size: 2em;">{avatar}<span style="margin-left: 0.5em">{msg.user}</span></div>'
return f'<span class="text-avatar" style="width: {size}px; height: {size}px; display: inline-flex; align-items: center; justify-content: center; background-color: #f0f0f0; border-radius: 50%;">{str(avatar)[:2].upper()}</span>'


def format_markdown(msg: ChatMessage):
avatar_html = serialize_avatar(msg.avatar)
header = f'<div style="display: flex; flex-direction: row; font-weight: bold; font-size: 2em;">{avatar_html}<span style="margin-left: 0.5em">{msg.user}</span></div>'
prefix = '\n' if msg.user == 'User' else '\n> '
content = prefix.join(msg.serialize().split('\n'))
return [nbformat.v4.new_markdown_cell(source=f'{header}\n{prefix}{content}')]
Expand All @@ -67,7 +100,7 @@ def format_output(msg: ChatMessage):
def render_cells(messages: list[ChatMessage]) -> tuple[Any, list[str]]:
cells, extensions = [], []
for msg in messages:
if msg.user == 'Help':
if msg.user in ("Help", " "):
continue
elif isinstance(msg.object, str):
cells += format_markdown(msg)
Expand Down
2 changes: 1 addition & 1 deletion lumen/ai/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ class UI(Viewer):
llm = param.ClassSelector(class_=Llm, default=OpenAI(), doc="""
The LLM provider to be used by default""")

log_level = param.ObjectSelector(default='DEBUG', objects=['DEBUG', 'INFO', 'WARNING', 'ERROR'], doc="""
log_level = param.ObjectSelector(default='INFO', objects=['DEBUG', 'INFO', 'WARNING', 'ERROR'], doc="""
The log level to use.""")

logs_db_path = param.String(default=None, doc="""
Expand Down
6 changes: 5 additions & 1 deletion lumen/sources/duckdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,10 @@ def _serialize_tables(self):
tables[t] = serializer.serialize(tdf)
return tables

def _process_sql_paths(self, sql_expr: str) -> str:
def _process_sql_paths(self, sql_expr: dict | str) -> str:
if isinstance(sql_expr, dict):
return {self._process_sql_paths(k): v for k, v in sql_expr.items()}

# Look for read_* patterns like read_parquet, read_csv etc.
matches = re.finditer(r"read_\w+\('([^']+)'\)", sql_expr)
processed_sql = sql_expr
Expand Down Expand Up @@ -209,6 +212,7 @@ def from_spec(cls, spec: dict[str, Any] | str) -> Source:
spec['tables'] = {}
else:
ephemeral_tables = {}

source = super().from_spec(spec)
if not ephemeral_tables:
return source
Expand Down
Loading