Test_AI_writing / tools_common.py
unknown
Claude Opus 5.5
Formatter and Finder tabs: download buttons that carry the file
ee3bfc0
Raw History Blame Contribute Delete
1.41 kB
"""Shared by the Journal Formatter and Journal Finder tabs."""
import base64
import html
from pathlib import Path
_MIME = {".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".pdf": "application/pdf",
".zip": "application/zip", ".csv": "text/csv", ".md": "text/markdown", ".txt": "text/plain"}
def download_link(path, label=None):
"""A download button that carries the file itself (a data link), like the other tabs' buttons. Gradio's own
file box links to the server, and that link is blocked when the app is shown on a custom domain or inside a
frame; a button that already holds the file always works. '' when there is no file."""
if not path or not Path(path).exists():
return ""
p = Path(path)
data = base64.b64encode(p.read_bytes()).decode("ascii")
mime = _MIME.get(p.suffix.lower(), "application/octet-stream")
text = html.escape(label or f"Download {p.name}")
return (f'<a class="cs-dl" download="{html.escape(p.name, quote=True)}" href="data:{mime};base64,{data}">'
f'⬇️ {text}</a>')
def download_row(*items):
"""Several buttons side by side; items are (path, label)."""
links = [download_link(p, lab) for p, lab in items]
links = [x for x in links if x]
return ('<div style="display:flex;flex-wrap:wrap;gap:8px;margin:6px 0">' + "".join(links) + "</div>") if links else ""