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

Pr for arbitrary html header injection for chainlit pai 362 #1

17 changes: 11 additions & 6 deletions backend/chainlit/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,10 @@
# custom_font = "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&display=swap"

# Specify a custom meta image url.
# custom_meta_image_url = "https://chainlit-cloud.s3.eu-west-3.amazonaws.com/logo/chainlit_banner.png"
# custom_og_image_url = "https://chainlit-cloud.s3.eu-west-3.amazonaws.com/logo/chainlit_banner.png"

# Specify a custom meta url.
# custom_url = ""

# Specify a custom build directory for the frontend.
# This can be used to customize the frontend code.
Expand Down Expand Up @@ -240,7 +243,7 @@ class FeaturesSettings(DataClassJsonMixin):
latex: bool = False
unsafe_allow_html: bool = False
auto_tag_thread: bool = True
edit_message:bool = True
edit_message: bool = True


@dataclass()
Expand All @@ -257,7 +260,9 @@ class UISettings(DataClassJsonMixin):
custom_js: Optional[str] = None
custom_font: Optional[str] = None
# Optional custom meta tag for image preview
custom_meta_image_url: Optional[str] = None
custom_og_image_url: Optional[str] = None
# Optional custom meta url
custom_url: Optional[str] = None
# Optional custom build directory for the frontend
custom_build: Optional[str] = None

Expand Down Expand Up @@ -285,9 +290,9 @@ class CodeSettings:

author_rename: Optional[Callable[[str], str]] = None
on_settings_update: Optional[Callable[[Dict[str, Any]], Any]] = None
set_chat_profiles: Optional[Callable[[Optional["User"]], List["ChatProfile"]]] = (
None
)
set_chat_profiles: Optional[
Callable[[Optional["User"]], List["ChatProfile"]]
] = None
set_starters: Optional[Callable[[Optional["User"]], List["Starter"]]] = None


Expand Down
74 changes: 21 additions & 53 deletions backend/chainlit/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse
from fastapi.security import OAuth2PasswordRequestForm
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.datastructures import URL
from starlette.middleware.cors import CORSMiddleware
from typing_extensions import Annotated
Expand Down Expand Up @@ -171,6 +172,8 @@ def get_build_dir(local_target: str, packaged_target: str):

app = FastAPI(lifespan=lifespan)

templates = Jinja2Templates(directory=build_dir)

sio = socketio.AsyncServer(
cors_allowed_origins=[] if IS_SUBMOUNT else "*", async_mode="asgi"
)
Expand Down Expand Up @@ -255,61 +258,29 @@ def replace_between_tags(text: str, start_tag: str, end_tag: str, replacement: s
return re.sub(pattern, start_tag + replacement + end_tag, text, flags=re.DOTALL)


def get_html_template():
PLACEHOLDER = "<!-- TAG INJECTION PLACEHOLDER -->"
JS_PLACEHOLDER = "<!-- JS INJECTION PLACEHOLDER -->"
CSS_PLACEHOLDER = "<!-- CSS INJECTION PLACEHOLDER -->"

def get_html_template(request: Request):
default_url = "https://github.com/Chainlit/chainlit"
default_meta_image_url = (
default_og_image_url = (
"https://chainlit-cloud.s3.eu-west-3.amazonaws.com/logo/chainlit_banner.png"
)
url = config.ui.github or default_url
meta_image_url = config.ui.custom_meta_image_url or default_meta_image_url
og_image_url = config.ui.custom_og_image_url or default_og_image_url
favicon_path = ROOT_PATH + "/favicon" if ROOT_PATH else "/favicon"

tags = f"""<title>{config.ui.name}</title>
<link rel="icon" href="{favicon_path}" />
<meta name="description" content="{config.ui.description}">
<meta property="og:type" content="website">
<meta property="og:title" content="{config.ui.name}">
<meta property="og:description" content="{config.ui.description}">
<meta property="og:image" content="{meta_image_url}">
dhruvsyos marked this conversation as resolved.
Show resolved Hide resolved
<meta property="og:url" content="{url}">
<meta property="og:root_path" content="{ROOT_PATH}">"""

js = f"""<script>{f"window.theme = {json.dumps(config.ui.theme.to_dict())}; " if config.ui.theme else ""}</script>"""

css = None
if config.ui.custom_css:
css = (
f"""<link rel="stylesheet" type="text/css" href="{config.ui.custom_css}">"""
)
context = {
"request": request,
"favicon_path": favicon_path,
"name": config.ui.name,
"description": config.ui.description,
"custom_font": config.ui.custom_font,
"custom_css": config.ui.custom_css,
"custom_js": config.ui.custom_js,
"theme": config.ui.theme.to_dict() if config.ui.theme else None,
"github": url,
"og_image_url": og_image_url,
}

if config.ui.custom_js:
js += f"""<script src="{config.ui.custom_js}" defer></script>"""

font = None
if config.ui.custom_font:
font = f"""<link rel="stylesheet" href="{config.ui.custom_font}">"""

index_html_file_path = os.path.join(build_dir, "index.html")

with open(index_html_file_path, "r", encoding="utf-8") as f:
content = f.read()
content = content.replace(PLACEHOLDER, tags)
if js:
content = content.replace(JS_PLACEHOLDER, js)
if css:
content = content.replace(CSS_PLACEHOLDER, css)
if font:
content = replace_between_tags(
content, "<!-- FONT START -->", "<!-- FONT END -->", font
)
if ROOT_PATH:
content = content.replace('href="/', f'href="{ROOT_PATH}/')
content = content.replace('src="/', f'src="{ROOT_PATH}/')
return content
return templates.TemplateResponse("index.html", context)


def get_user_facing_url(url: URL):
Expand Down Expand Up @@ -935,12 +906,9 @@ def status_check():


@router.get("/{full_path:path}")
async def serve():
html_template = get_html_template()
async def serve(request: Request):
"""Serve the UI files."""
response = HTMLResponse(content=html_template, status_code=200)

return response
return get_html_template(request)


app.include_router(router)
Expand Down
2 changes: 2 additions & 0 deletions backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ numpy = [
{ version = "^1.26", python = ">=3.9" },
{ version = "^1.24.4", python = "<3.9" },
]
jinja2 = "^3.1.4"

[tool.poetry.group.tests]
optional = true
Expand Down Expand Up @@ -106,6 +107,7 @@ module = [
]
ignore_missing_imports = true


[tool.poetry.group.custom-data]
optional = true

Expand Down
53 changes: 37 additions & 16 deletions frontend/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,45 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- TAG INJECTION PLACEHOLDER -->
<title>{{ name }}</title>
<link rel="icon" href="{{ favicon_path }}" />
<meta name="description" content="{{ description }}">
<meta property="og:type" content="website">
<meta property="og:title" content="{{ name }}">
<meta property="og:description" content="{{ description }}">
<meta property="og:image" content="{{ og_image_url }}">
<meta property="og:url" content="{{ github }}">

<!-- Preconnect for performance -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<!-- FONT START -->
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&display=swap"
rel="stylesheet"
/>
<!-- FONT END -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"
/>
<!-- JS INJECTION PLACEHOLDER -->
<!-- CSS INJECTION PLACEHOLDER -->
<script>
const global = globalThis;
</script>

<!-- Conditionally include custom font or default Inter font -->
{% if custom_font %}
<link rel="stylesheet" href="{{ custom_font }}">
{% else %}
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&display=swap" rel="stylesheet" />
{% endif %}

<!-- Include KaTeX CSS if needed -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" />

<!-- Conditionally include custom CSS -->
{% if custom_css %}
<link rel="stylesheet" type="text/css" href="{{ custom_css }}">
{% endif %}

<!-- Theme Configuration Script -->
{% if theme %}
<script id="theme-data" type="application/json">
window.theme = {{ theme | tojson | safe }};
</script>
{% endif %}

<!-- Conditionally include custom JS -->
{% if custom_js %}
<script src="{{ custom_js }}" defer></script>
{% endif %}
dhruvsyos marked this conversation as resolved.
Show resolved Hide resolved
</head>
<body>
<div id="root"></div>
dhruvsyos marked this conversation as resolved.
Show resolved Hide resolved
Expand Down