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

Jinja2 index template #1196

Closed
wants to merge 3 commits into from
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
70 changes: 19 additions & 51 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=[], async_mode="asgi"
)
Expand Down Expand Up @@ -258,11 +261,7 @@ 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 = (
"https://chainlit-cloud.s3.eu-west-3.amazonaws.com/logo/chainlit_banner.png"
Expand All @@ -271,48 +270,20 @@ def get_html_template():
meta_image_url = config.ui.custom_meta_image_url or default_meta_image_url
favicon_path = "/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}">
<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,
"meta_image_url": meta_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 @@ -938,12 +909,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
90 changes: 88 additions & 2 deletions backend/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ packaging = "^23.1"
python-multipart = "^0.0.9"
pyjwt = "^2.8.0"
numpy = "^1.26"
jinja2 = "^3.1.4"

[tool.poetry.group.tests]
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="{{ meta_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 %}
</head>
<body>
<div id="root"></div>
Expand Down
Loading