Lilly-api / app /web /index.html
Safak11's picture
Lilly: Bosnian to English, typed, spoken or photographed
1e8d185 verified
Raw History Blame Contribute Delete
82.1 kB
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"> <meta name="color-scheme" content="light"> <meta name="theme-color" content="#f7f4f0"> <meta name="description" content="Lilly translates Bosnian and English — typed, spoken, or photographed."> <title>Lilly</title> <style> /* --------------------------------------------------------------- Sarajevo in daylight, uncovered, behind one viewport of clear glass. One deep teal accent; the photograph does the rest. --------------------------------------------------------------- */ :root { --bg-0: #f7f4f0; --ink: #14181a; --ink-2: rgba(20, 24, 26, 0.84); --ink-3: rgba(20, 24, 26, 0.74); --ink-quiet: rgba(20, 24, 26, 0.72); /* Clear glass: the photograph stays readable through every panel. */ --glass: rgba(255, 255, 255, 0.15); --glass-edge: rgba(255, 255, 255, 0.45); --glass-lift: rgba(255, 255, 255, 0.16); --glass-blur: blur(6px); --hair: rgba(20, 24, 26, 0.1); --sheen: rgba(255, 255, 255, 0.7); /* No veil over the photo, so text carries its own light edge instead. */ --lift: 0 0 6px rgba(255, 255, 255, 0.8), 0 0 16px rgba(255, 255, 255, 0.55); --accent: #0f8a7c; --accent-hi: #0b6b60; --accent-ink: #ffffff; --rec: #c2483e; --shadow: 0 1px 2px rgba(20, 20, 24, 0.05), 0 18px 40px -18px rgba(20, 20, 24, 0.16); --r-lg: 24px; --r-md: 16px; --r-sm: 12px; --font-sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, sans-serif; --font-serif: ui-serif, Georgia, "Iowan Old Style", "Palatino Linotype", "Times New Roman", serif; --ease: cubic-bezier(0.32, 0.72, 0, 1); --t-fast: 0.16s; --t-base: 0.3s; --t-slow: 0.46s; } * { margin: 0; padding: 0; box-sizing: border-box; } html { -webkit-text-size-adjust: 100%; } html, body { height: 100%; overflow: hidden; } body { font-family: var(--font-sans); color: var(--ink); background: #b9cfdc; height: 100vh; height: 100dvh; display: flex; flex-direction: column; padding-top: env(safe-area-inset-top); padding-bottom: env(safe-area-inset-bottom); -webkit-font-smoothing: antialiased; } ::selection { background: rgba(15, 138, 124, 0.22); } /* --- Sarajevo, fixed behind the page, nothing laid over it ---------- */ /* Julian Nyča, Wikimedia Commons, CC BY-SA 4.0, at its full 2800 px so a Retina screen or a tall phone is not upscaling it. Served beside the page (app/server.py), not inlined, so the page paints before the photo has arrived; until then a 48 px copy of the same frame holds its place. */ .bg-photo { position: fixed; inset: 0; z-index: -2; background-image: url("sarajevo-2800.jpg"), url("data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/2wBDAQoLCw4NDhwQEBw7KCIoOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozv/wAARCAAdADADASIAAhEBAxEB/8QAGAAAAwEBAAAAAAAAAAAAAAAAAwQFBgL/xAAsEAACAgEDAgQFBQEAAAAAAAABAgMRBAAhMQUSQVFhcQYTFCKBFSQykaHw/8QAFwEAAwEAAAAAAAAAAAAAAAAAAQIDBP/EABwRAAICAwEBAAAAAAAAAAAAAAABAhEDEhMhQf/aAAwDAQACEQMRAD8AuQ/EOJK5XdKHLUAdOx58TiwwPsQdYP6GSKJ3hl+4HaJ7tvbRcMZocu+PK4Ve7Y1x68Hy1bsiDxOzfLlRkeJ9tdrkIeQdZCDrHZ8wyQGFY6Dsp7rZj/ED/q1Qlz1SNJktkC9xZ3o8cVoPMhliLz5Ceg/OgtlxLzIov11FXNxpAxWa2YiyWofd4X56UlyImjcwtJOyGlEW9EHexz/eh3Q3FknP6gIsgio3pQSe6u0ElSa8tJ9L6xk5B+jhyZYQkeyCNTe9Uo21Txfh8ZKGSSdAKMR7IaLL4gmzt6aQ6nhR9E6ljjHAfvSlZxuhvwP+fnWJSWyizTPatvgfBkbF+J5MdgRCYvmyKBydiOfHn/dONJ3TdkU6CYkhUZqvmuPfSP6p2/upYFkkV1S9hW3INWPbVeLpeNnwPNMCZewBGoDss3wAPPbTzTFg6XhBm6hlNkqhmYSdrOWjpRY23J20fH6tgRCaZHYl3uSmu2u6FVeuGxx0/DnzFdpJFoL3ed1Z8+NQjL82Uyuqli3gKAvfYald+gc3A//Z"); background-size: cover; background-position: center 30%; background-repeat: no-repeat; } /* --- Masthead ------------------------------------------------------- */ header { text-align: center; margin: auto 0 clamp(14px, 2.6vh, 26px); } h1 { font-family: var(--font-serif); color: var(--ink); font-size: clamp(36px, 9vw, 46px); font-weight: 600; letter-spacing: -0.015em; text-wrap: balance; text-shadow: var(--lift); } .tagline { margin-top: 9px; display: flex; justify-content: center; } .swap { font: inherit; font-size: 11.5px; font-weight: 500; letter-spacing: 0.16em; text-transform: uppercase; color: var(--ink); background: var(--glass); backdrop-filter: var(--glass-blur); -webkit-backdrop-filter: var(--glass-blur); border: 1px solid var(--glass-edge); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 10px; min-height: 44px; padding: 0 14px; border-radius: 999px; -webkit-tap-highlight-color: transparent; transition: color var(--t-base) var(--ease), background var(--t-base) var(--ease), border-color var(--t-base) var(--ease), transform var(--t-fast) var(--ease); } .swap:hover { background: rgba(255, 255, 255, 0.26); } .swap:active { transform: scale(0.965); } .swap svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; } main { width: 100%; max-width: 580px; display: flex; flex-direction: column; gap: 12px; margin-bottom: auto; } /* --- The glass ------------------------------------------------------ */ .glass { position: relative; background: var(--glass); backdrop-filter: var(--glass-blur); -webkit-backdrop-filter: var(--glass-blur); border: 1px solid var(--glass-edge); border-radius: var(--r-lg); text-shadow: var(--lift); } .composer { padding: 4px 4px 4px; } textarea#input { width: 100%; min-height: 108px; max-height: 42vh; resize: none; background: transparent; border: none; outline: none; color: var(--ink); font: inherit; font-size: 17.5px; line-height: 1.52; padding: 16px 18px 8px; caret-color: var(--accent); } textarea#input::placeholder { color: var(--ink-3); } .composer-foot { display: flex; gap: 8px; align-items: center; padding: 4px 8px 8px; } .composer-foot .spacer { flex: 1; } /* --- Controls ------------------------------------------------------- */ .btn { position: relative; font: inherit; font-size: 15px; color: var(--ink); text-decoration: none; cursor: pointer; border: 1px solid var(--glass-edge); background: var(--glass-lift); border-radius: 14px; min-height: 44px; padding: 0 17px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; -webkit-tap-highlight-color: transparent; transition: transform var(--t-fast) var(--ease), background var(--t-base) var(--ease), border-color var(--t-base) var(--ease), opacity var(--t-base) var(--ease); } .btn:hover { background: rgba(255, 255, 255, 0.3); } .btn:active { transform: scale(0.965); } .btn:disabled { opacity: 0.38; cursor: default; transform: none; } .btn.primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; font-weight: 600; padding: 0 22px; text-shadow: none; } .btn.primary:hover { background: var(--accent-hi); } .btn.icon { width: 44px; padding: 0; } .btn.ghost { background: transparent; border-color: transparent; color: var(--ink-quiet); } .btn.ghost:hover { background: rgba(255, 255, 255, 0.2); color: var(--ink); } .btn svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; transition: opacity var(--t-fast) var(--ease); } .btn .lbl { transition: opacity var(--t-fast) var(--ease); } .btn.busy { pointer-events: none; } .btn.busy .lbl, .btn.busy svg { opacity: 0; } .btn.busy::after { content: ""; position: absolute; left: 50%; top: 50%; width: 17px; height: 17px; margin: -8.5px 0 0 -8.5px; border-radius: 50%; border: 2px solid currentColor; border-right-color: transparent; opacity: 0.8; animation: spin 0.68s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } :focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } /* The microphone hears you: a halo that breathes with your voice. */ #micBtn .halo { position: absolute; inset: -5px; border-radius: 18px; border: 1px solid var(--rec); opacity: 0; transform: scale(0.92); pointer-events: none; transition: opacity 90ms linear, transform 90ms linear; } #micBtn.recording { background: rgba(194, 72, 62, 0.14); border-color: rgba(194, 72, 62, 0.45); color: #8a2c23; } #micBtn.recording .halo { opacity: calc(0.22 + var(--level, 0) * 0.6); transform: scale(calc(1 + var(--level, 0) * 0.13)); } #clearBtn { opacity: 0; transform: scale(0.9); pointer-events: none; transition: opacity var(--t-base) var(--ease), transform var(--t-base) var(--ease); } body.has-text #clearBtn { opacity: 1; transform: none; pointer-events: auto; } /* --- Hint ----------------------------------------------------------- */ .hint { text-align: center; font-size: 13.5px; color: var(--ink-2); text-shadow: var(--lift); padding: 6px 4px 2px; transition: opacity var(--t-base) var(--ease); } .hint:empty { display: none; } body.has-result .hint { opacity: 0; height: 0; padding: 0; overflow: hidden; } /* --- Result --------------------------------------------------------- */ .result { display: none; flex-direction: column; gap: 16px; padding: 20px 22px 16px; } .result-langs { display: flex; flex-direction: column; gap: 16px; } body.en-bs .result-langs { flex-direction: column-reverse; } .result.visible { display: flex; animation: rise var(--t-slow) var(--ease) both; } @keyframes rise { from { opacity: 0; transform: translateY(10px) scale(0.985); } to { opacity: 1; transform: none; } } @keyframes swap { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } } .result.swap .block { animation: swap var(--t-base) var(--ease) both; } .result.swap .block:nth-child(2) { animation-delay: 0.04s; } .label { font-size: 10.5px; font-weight: 600; letter-spacing: 0.15em; text-transform: uppercase; color: var(--ink-3); margin-bottom: 7px; } .source-row { display: flex; gap: 12px; align-items: flex-start; } #srcThumb { width: 54px; height: 54px; border-radius: 10px; object-fit: cover; border: 1px solid var(--hair); flex: none; } .bosnian { font-size: 15px; color: var(--ink-2); line-height: 1.55; overflow-wrap: anywhere; } .english { font-size: 21px; line-height: 1.42; font-weight: 500; letter-spacing: -0.005em; text-wrap: pretty; overflow-wrap: anywhere; } /* Reverse: Bosnian is the answer, English is what was typed. */ body.en-bs .bosnian { font-size: 21px; line-height: 1.42; font-weight: 500; letter-spacing: -0.005em; color: var(--ink); text-wrap: pretty; overflow-wrap: anywhere; } body.en-bs .english { font-size: 15px; line-height: 1.55; font-weight: 400; letter-spacing: 0; color: var(--ink-2); } .result-actions { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; padding-top: 2px; border-top: 1px solid rgba(20, 24, 26, 0.08); margin-top: 2px; } .result-actions .btn { font-size: 13.5px; padding: 0 13px; min-height: 44px; } .result-actions .spacer { flex: 1; } /* --- Toast ---------------------------------------------------------- */ .toast { position: fixed; left: 50%; bottom: calc(20px + env(safe-area-inset-bottom)); z-index: 20; max-width: min(88vw, 460px); padding: 11px 18px; border-radius: 999px; font-size: 14px; line-height: 1.35; text-align: center; color: var(--ink); background: rgba(255, 253, 250, 0.86); backdrop-filter: blur(24px) saturate(180%); -webkit-backdrop-filter: blur(24px) saturate(180%); border: 1px solid var(--hair); box-shadow: var(--shadow), inset 0 1px 0 var(--sheen); opacity: 0; transform: translate(-50%, 14px) scale(0.97); pointer-events: none; transition: opacity var(--t-base) var(--ease), transform var(--t-base) var(--ease); } .toast.on { opacity: 1; transform: translate(-50%, 0) scale(1); } /* --- Correction sheet ----------------------------------------------- */ dialog { margin: auto; width: min(92vw, 480px); padding: 0; border: none; background: transparent; overflow: visible; color: var(--ink); } dialog::backdrop { background: rgba(3, 10, 14, 0.5); backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px); } .sheet { padding: 24px; border-radius: var(--r-lg); background: linear-gradient(180deg, rgba(255, 253, 250, 0.97), rgba(250, 247, 242, 0.97)); backdrop-filter: blur(34px) saturate(180%); -webkit-backdrop-filter: blur(34px) saturate(180%); border: 1px solid var(--hair); box-shadow: 0 32px 70px -20px rgba(20, 20, 24, 0.35), inset 0 1px 0 var(--sheen); } dialog[open] { animation: sheetIn 0.34s var(--ease) both; } dialog[open]::backdrop { animation: fadeIn 0.34s var(--ease) both; } dialog.closing { animation: sheetOut 0.2s var(--ease) both; } dialog.closing::backdrop { animation: fadeOut 0.2s var(--ease) both; } @keyframes sheetIn { from { opacity: 0; transform: translateY(12px) scale(0.97); } to { opacity: 1; transform: none; } } @keyframes sheetOut { to { opacity: 0; transform: translateY(8px) scale(0.98); } } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @keyframes fadeOut { to { opacity: 0; } } .sheet h2 { font-size: 19px; font-weight: 600; letter-spacing: -0.01em; } .sheet .sub { margin-top: 6px; font-size: 13.5px; color: var(--ink-3); line-height: 1.5; } .quote { margin: 16px 0 4px; padding: 12px 14px; border-radius: var(--r-sm); background: rgba(20, 24, 26, 0.035); border: 1px solid rgba(20, 24, 26, 0.08); font-size: 13.5px; line-height: 1.5; max-height: 132px; overflow: auto; } .quote .q-bs { color: var(--ink-3); } .quote .q-en { color: var(--ink-2); margin-top: 5px; } .sheet label { display: block; font-size: 12.5px; color: var(--ink-3); margin: 15px 0 7px; } .sheet textarea { width: 100%; min-height: 62px; resize: vertical; border: 1px solid var(--hair); border-radius: var(--r-sm); background: rgba(20, 24, 26, 0.035); color: var(--ink); font: inherit; font-size: 15px; line-height: 1.5; padding: 11px 13px; outline: none; transition: border-color var(--t-base) var(--ease), background var(--t-base) var(--ease); } .sheet textarea:focus { border-color: rgba(15, 138, 124, 0.5); background: rgba(20, 24, 26, 0.055); } .sheet .row { display: flex; gap: 8px; justify-content: flex-end; margin-top: 20px; } /* The sheet is a modal, and a modal paints over everything — including the toast, which sits at the bottom of the page under the backdrop. A failure here has to be answered inside the sheet or the reader never sees it. */ .sheet-note { margin-top: 16px; font-size: 13.5px; line-height: 1.45; color: var(--rec); } /* --- Drop target ---------------------------------------------------- */ .dropveil { position: fixed; inset: 0; z-index: 30; display: grid; place-items: center; background: rgba(7, 18, 25, 0.55); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); opacity: 0; pointer-events: none; transition: opacity var(--t-base) var(--ease); } body.dropping .dropveil { opacity: 1; } .dropveil span { padding: 14px 22px; border-radius: 999px; border: 1px dashed rgba(122, 211, 189, 0.6); color: rgba(238, 244, 246, 0.85); font-size: 15px; } /* The only page there is: the tool, centred in one viewport. It scrolls inside itself if a result and the camera outgrow a short screen; the page never does. */ .stage { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; align-items: center; padding: clamp(16px, 3.5vh, 48px) 16px clamp(12px, 2vh, 24px); } .credit { flex: none; padding: 0 16px 10px; text-align: center; font-size: 11px; color: rgba(255, 255, 255, 0.92); text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); } .credit a { color: inherit; } /* --- Detect & conversation pills ------------------------------------ */ .tagline { gap: 10px; flex-wrap: wrap; } .pill { font: inherit; font-size: 11.5px; font-weight: 500; letter-spacing: 0.12em; text-transform: uppercase; color: var(--ink); background: var(--glass); backdrop-filter: var(--glass-blur); -webkit-backdrop-filter: var(--glass-blur); border: 1px solid var(--glass-edge); cursor: pointer; display: inline-flex; align-items: center; gap: 7px; min-height: 36px; padding: 0 13px; border-radius: 999px; -webkit-tap-highlight-color: transparent; transition: color var(--t-base) var(--ease), background var(--t-base) var(--ease), border-color var(--t-base) var(--ease); } .pill:hover { background: rgba(255, 255, 255, 0.26); } .pill[aria-pressed="true"] { color: #ffffff; border-color: transparent; background: var(--accent); } /* --- Character counter ----------------------------------------------- */ .composer-foot { flex-wrap: wrap; } .counter { font-size: 12px; font-variant-numeric: tabular-nums; color: var(--ink-3); padding: 0 2px; white-space: nowrap; } .counter.over { color: var(--rec); } /* The conversation mode's microphone is the one button that changed meaning, so it wears the accent while the mode is on. */ body.convo #micBtn { border-color: rgba(15, 138, 124, 0.55); color: var(--accent-hi); } /* --- Camera: live viewfinder and its overlays ------------------------ */ .camera { padding: 12px; } .cam-stage { position: relative; border-radius: var(--r-md); overflow: hidden; background: rgba(20, 24, 26, 0.92); border: 1px solid var(--hair); aspect-ratio: 4 / 3; } .cam-stage video, .cam-stage img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; display: block; } /* display:block above would quietly defeat the [hidden] attributes these two start and end their lives with — said explicitly instead. */ .cam-stage video[hidden], .cam-stage img[hidden] { display: none; } .cam-overlay { position: absolute; inset: 0; pointer-events: none; } /* One chip per detected region, drawn over the words it translates. The chips are positioned in percentages of the frame, so they stay on their region however the stage is displayed. */ .cam-chip { position: absolute; background: rgba(11, 107, 96, 0.92); color: #ffffff; font-size: 12.5px; line-height: 1.35; padding: 3px 6px; border-radius: 6px; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.25); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .cam-note { margin: 12px 4px 0; font-size: 13.5px; line-height: 1.5; color: var(--ink-2); } .cam-note a { color: var(--accent-hi); font-weight: 600; } .cam-actions { display: flex; gap: 8px; align-items: center; margin-top: 12px; flex-wrap: wrap; } .cam-actions .spacer { flex: 1; } /* --- History & phrasebook --------------------------------------------- */ .library { padding: 12px 14px 14px; } .library-tabs { display: flex; gap: 6px; } .lib-tab { font: inherit; font-size: 12px; font-weight: 600; letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-3); background: transparent; border: 1px solid transparent; cursor: pointer; padding: 8px 12px; border-radius: 999px; -webkit-tap-highlight-color: transparent; transition: color var(--t-base) var(--ease), background var(--t-base) var(--ease); } .lib-tab.on { color: var(--accent-hi); background: rgba(255, 255, 255, 0.3); } .lib-list { list-style: none; margin-top: 6px; max-height: clamp(96px, 20vh, 220px); overflow: auto; } .lib-empty { font-size: 13.5px; color: var(--ink-3); padding: 14px 4px 6px; line-height: 1.5; } .lib-item { display: flex; align-items: center; gap: 8px; border-top: 1px solid rgba(20, 24, 26, 0.07); } .lib-item:first-child { border-top: none; } .lib-row { flex: 1; min-width: 0; font: inherit; text-align: left; color: var(--ink); background: transparent; border: none; cursor: pointer; padding: 10px 4px; border-radius: var(--r-sm); -webkit-tap-highlight-color: transparent; } .lib-row:hover { background: rgba(255, 255, 255, 0.22); } .lib-row .dir { display: block; font-size: 10px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--ink-3); } .lib-row .src { display: block; font-size: 14.5px; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .lib-row .dst { display: block; font-size: 12.5px; color: var(--ink-3); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .lib-x { flex: none; font: inherit; font-size: 15px; line-height: 1; color: var(--ink-3); background: transparent; border: 1px solid transparent; border-radius: 999px; width: 30px; height: 30px; cursor: pointer; -webkit-tap-highlight-color: transparent; } .lib-x:hover { color: var(--rec); background: rgba(194, 72, 62, 0.08); } .library-foot { display: flex; justify-content: flex-end; margin-top: 6px; } .library-foot .btn { font-size: 12.5px; min-height: 36px; } /* --- Handwriting pad ---------------------------------------------------- */ .write-pad { width: 100%; height: 240px; border: 1px solid var(--hair); border-radius: var(--r-sm); background: rgba(255, 255, 255, 0.78); touch-action: none; display: block; margin-top: 14px; cursor: crosshair; } @media (max-width: 420px) { .result { padding: 18px 18px 14px; } .english { font-size: 19.5px; } body.en-bs .bosnian { font-size: 19.5px; } body.en-bs .english { font-size: 15px; } .result-actions .btn { flex: 1 1 auto; } } @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: 0.001ms !important; animation-iteration-count: 1 !important; transition-duration: 0.001ms !important; } .btn.busy::after { animation: none; opacity: 0.5; } } </style> </head> <body id="top"> <!-- Sarajevo, the real skyline, fixed behind everything the page shows. --> <div class="bg-photo" aria-hidden="true"></div> <section class="stage"> <header> <h1>Lilly</h1> <p class="tagline"> <button type="button" class="swap" id="swapBtn" aria-pressed="false" aria-label="Swap to English then Bosnian"> <span id="fromLang">Bosnian</span> <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 8h11M15 5l3 3-3 3"/><path d="M17 16H6M9 13l-3 3 3 3"/></svg> <span id="toLang">English</span> </button> <button type="button" class="pill" id="convoBtn" aria-pressed="false">Conversation</button> </p> </header> <main> <section class="glass composer"> <textarea id="input" lang="bs" rows="3" spellcheck="false" autocorrect="off" placeholder="Upi&#353;ite bosanski tekst&#8230;" aria-label="Bosnian text"></textarea> <div class="composer-foot"> <button type="button" class="btn icon" id="micBtn" title="Speak Bosnian" aria-label="Record speech"> <span class="halo" aria-hidden="true"></span> <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5 11a7 7 0 0 0 14 0"/><path d="M12 18v3"/></svg> </button> <button type="button" class="btn icon" id="photoBtn" title="Translate a photo" aria-label="Choose a photo"> <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="6" width="18" height="14" rx="3"/><circle cx="12" cy="13" r="4"/><path d="M9 6l1.5-2h3L15 6"/></svg> </button> <button type="button" class="btn icon" id="camBtn" title="Live camera" aria-label="Open the live camera"> <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 8a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><path d="M16 11l5-3v8l-5-3"/></svg> </button> <button type="button" class="btn icon" id="writeBtn" title="Write by hand" aria-label="Open the handwriting pad"> <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 20l1-4L16.5 4.5a2.1 2.1 0 0 1 3 3L8 19z"/><path d="M14.5 6.5l3 3"/></svg> </button> <button type="button" class="btn icon" id="docBtn" title="Translate a document" aria-label="Choose a document"> <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4"/><path d="M9 12h6M9 16h6"/></svg> </button> <input type="file" id="photoInput" accept="image/*" hidden> <input type="file" id="docInput" accept=".docx,.pdf" hidden> <span class="counter" id="counter" aria-hidden="true">0 / 5000</span> <span class="spacer"></span> <button type="button" class="btn icon ghost" id="clearBtn" title="Clear" aria-label="Clear the text"> <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg> </button> <button type="button" class="btn primary" id="translateBtn"><span class="lbl">Translate</span></button> </div> </section> <section class="glass camera" id="cameraPanel" hidden> <div class="cam-stage" id="camStage"> <video id="camVideo" autoplay playsinline muted hidden></video> <img id="camStill" alt="" hidden> <div class="cam-overlay" id="camOverlay" aria-live="polite"></div> </div> <p class="cam-note" id="camNote" hidden></p> <p class="cam-note" id="camEscape" hidden> <a id="camOpenTab" target="_blank" rel="noopener">Open Lilly in its own tab</a> </p> <div class="cam-actions"> <button type="button" class="btn ghost" id="camClose"><span class="lbl">Close</span></button> <span class="spacer"></span> <button type="button" class="btn" id="camTakeShot" hidden><span class="lbl">Take a photo</span></button> <button type="button" class="btn primary" id="camCapture" disabled><span class="lbl">Capture</span></button> </div> <input type="file" id="camShotInput" accept="image/*" capture="environment" hidden> </section> <p class="hint" id="hint"></p> <section class="glass result" id="result" aria-live="polite"> <div class="result-langs"> <div class="block"> <div class="label">Bosnian</div> <div class="source-row"> <img id="srcThumb" alt="" hidden> <div class="bosnian" id="outBosnian" lang="bs"></div> </div> </div> <div class="block"> <div class="label">English</div> <div class="source-row"> <div class="english" id="outEnglish"></div> </div> </div> </div> <div class="result-actions"> <button type="button" class="btn" id="playBtn"> <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9v6h4l5 4V5L8 9H4z"/><path d="M17 9.5a4 4 0 0 1 0 5"/><path d="M19.5 7a7.5 7.5 0 0 1 0 10"/></svg> <span class="lbl">Play voice</span> </button> <button type="button" class="btn" id="copyBtn"> <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="11" height="11" rx="2.5"/><path d="M15 6.5V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h.5"/></svg> <span class="lbl">Copy</span> </button> <button type="button" class="btn" id="saveBtn"> <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4l2.4 4.9 5.6.8-4 3.9.9 5.4-4.9-2.6-4.9 2.6.9-5.4-4-3.9 5.6-.8z"/></svg> <span class="lbl">Save</span> </button> <button type="button" class="btn" id="shareBtn"> <svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="6" cy="12" r="2.5"/><circle cx="18" cy="6" r="2.5"/><circle cx="18" cy="18" r="2.5"/><path d="M8.3 10.8l7.4-3.6M8.3 13.2l7.4 3.6"/></svg> <span class="lbl">Share</span> </button> <span class="spacer"></span> <button type="button" class="btn ghost" id="wrongBtn"><span class="lbl">This translation is wrong</span></button> </div> </section> <section class="glass library" id="library"> <div class="library-tabs"> <button type="button" class="lib-tab on" id="histTab" aria-selected="true">History</button> <button type="button" class="lib-tab" id="savedTab" aria-selected="false">Saved</button> </div> <ul class="lib-list" id="histList"></ul> <ul class="lib-list" id="savedList" hidden></ul> <div class="library-foot"> <button type="button" class="btn ghost" id="histClear">Clear history</button> </div> </section> </main> </section> <p class="credit">Sarajevo by <a href="https://commons.wikimedia.org/wiki/File:Sarajevo_City_Panorama.JPG" target="_blank" rel="noopener">Julian Nyča</a>, CC BY-SA 4.0 · <a href="https://github.com/ssaaffaakk/Lilly" target="_blank" rel="noopener">GitHub</a></p> <div class="toast" id="toast" role="status" aria-live="polite"></div> <div class="dropveil" aria-hidden="true"><span>Drop the photo to read it</span></div> <dialog id="feedbackDialog" aria-labelledby="fbTitle"> <div class="sheet"> <h2 id="fbTitle">Help Lilly improve</h2> <p class="sub">Corrections are kept for review. Approved ones become training material.</p> <div class="quote"> <div class="q-bs" id="fbQuoteBs" lang="bs"></div> <div class="q-en" id="fbQuoteEn"></div> </div> <label for="fbWhat">What is wrong with this translation?</label> <textarea id="fbWhat"></textarea> <label for="fbSuggest">What should it say? (optional)</label> <textarea id="fbSuggest"></textarea> <p class="sheet-note" id="fbNote" role="status" aria-live="polite" hidden></p> <div class="row"> <button type="button" class="btn ghost" id="fbCancel"><span class="lbl">Cancel</span></button> <button type="button" class="btn primary" id="fbSend"><span class="lbl">Send</span></button> </div> </div> </dialog> <dialog id="writeDialog" aria-labelledby="writeTitle"> <div class="sheet"> <h2 id="writeTitle">Write it by hand</h2> <p class="sub">Draw the words with your finger or a mouse. Lilly reads the pad as a photograph.</p> <canvas class="write-pad" id="writePad" width="560" height="240"></canvas> <p class="sheet-note" id="writeNote" role="status" aria-live="polite" hidden></p> <div class="row"> <button type="button" class="btn ghost" id="writeCancel"><span class="lbl">Cancel</span></button> <button type="button" class="btn ghost" id="writeClear"><span class="lbl">Clear</span></button> <button type="button" class="btn primary" id="writeSend"><span class="lbl">Read it</span></button> </div> </div> </dialog> <script> const $ = id => document.getElementById(id); const state = { bosnian: "", english: "", audioUrl: null, audioLang: "" }; const calm = window.matchMedia("(prefers-reduced-motion: reduce)").matches; function isReply() { return document.body.classList.contains("en-bs"); } function isConvo() { return document.body.classList.contains("convo"); } function applyDirection(reply) { document.body.classList.toggle("en-bs", reply); $("fromLang").textContent = reply ? "English" : "Bosnian"; $("toLang").textContent = reply ? "Bosnian" : "English"; $("swapBtn").setAttribute("aria-pressed", reply ? "true" : "false"); $("swapBtn").setAttribute("aria-label", reply ? "Swap to Bosnian then English" : "Swap to English then Bosnian"); const input = $("input"); input.lang = reply ? "en" : "bs"; input.setAttribute("aria-label", (reply ? "English" : "Bosnian") + " text"); input.placeholder = reply ? "Type English\u2026" : "Upi\u0161ite bosanski tekst\u2026"; $("micBtn").title = reply ? "Speak English" : "Speak Bosnian"; updateHint(); } /* The hint under the composer says what this mode hears; conversation mode says its own thing whichever way the arrow points. */ function updateHint() { $("hint").textContent = isConvo() ? "Tap the microphone, say either language. Lilly answers aloud, then listens again." : ""; } /* The direction the server is asked for, and which side of its answer is the input: every ability runs both ways, so a recording or a photo goes out with the direction the arrow shows rather than flipping it back. */ function direction() { return isReply() ? "en-bs" : "bs-en"; } function sourceOf(data) { return isReply() ? data.english : data.bosnian; } /* ---- messages ---------------------------------------------------- */ let toastTimer = 0; function setStatus(msg, sticky, ms) { const el = $("toast"); clearTimeout(toastTimer); if (!msg) { el.classList.remove("on"); return; } el.textContent = msg; el.classList.add("on"); if (!sticky) toastTimer = setTimeout(() => el.classList.remove("on"), ms || 3200); } /* A failure asks the reader to do something, so it stays up more than twice as long as a confirmation: three seconds is not enough to read a sentence and act on it. */ function fail(msg) { setStatus(msg, false, 7500); } /* ---- what went wrong, and what to do about it ----------------------- Every sentence below answers both halves. The server states the first half plainly and with the real limit inside it — "that file is over 12 MB", "that image is 8000x7000" — so its words are kept and the instruction is added here, where the page knows which button was pressed. Provoked against a running server, this is everything it sends back: 413 too big — an oversized upload, an empty one, an image with more pixels than we decode, or more text than one translation may do 400 a file we cannot open: not an image, not audio 422 the request never reached the model — a field past its limit, or a body the server could not read. These carry no "error" field, so the page has to speak for itself 500 our side. The reason goes to the server's log, not to the reply and a failed fetch, which is no answer at all. */ const NEXT = { // what pressing on again means, per place translate: "press Translate again", photo: "try the photo again", speech: "record again", speak: "press Play voice again", document: "try the document again", feedback: "send it again" }; const TOO_MUCH_TEXT = "That is more text than Lilly translates in one go. " + "Send it a few paragraphs at a time."; const cap = s => s.charAt(0).toUpperCase() + s.slice(1); /* The server's own sentence, made into a sentence: capital, no full stop. */ function said(err) { const t = String((err && err.serverText) || "").trim().replace(/[.\s]+$/, ""); return t ? cap(t) : ""; } function describe(err, where) { const next = NEXT[where] || "try again"; const text = said(err); if (err && err.timeout) { if (where === "photo") return "Lilly is still reading that photograph, and this page stopped " + "waiting. On Hugging Face the first photo after sleep can take " + "longer than the connection lasts — wait until the Space says " + "Running, then try a smaller, sharper photo."; if (where === "speech") return "Lilly is still listening, and this page stopped waiting. The " + "large ear on two CPU cores can take a minute for a short clip " + "— record something shorter, then " + next + "."; return "Lilly is still working, and this page stopped waiting. " + cap(next) + "."; } // Nothing answered: fetch rejects with a TypeError before there is a status. // Hugging Face's proxy does this to a photograph that is still being read. if (err instanceof TypeError) { if (where === "photo") return "The connection dropped while Lilly was still reading. On Hugging " + "Face that happens when the photograph takes longer than the page " + "is allowed to wait. Refresh, wait until Running, and try a " + "smaller photo."; return "Lilly is not answering — the server stopped or the connection " + "dropped. Check it is running, then " + next + "."; } switch (err && err.status) { case 413: if (where === "translate") return TOO_MUCH_TEXT; if (!text) return "That is too big for Lilly to take. Try again with something smaller."; if (/empty/.test(text)) return text + " — nothing came through. " + cap(next) + "."; if (where === "speech") return text + ". Record a shorter clip."; if (where === "document") return text + ". Send a smaller file, or export the document without its pictures."; return text + ". Pick a smaller photo, or take the picture again at a lower resolution."; case 400: if (!text) return "Lilly could not use what was sent. " + cap(next) + "."; if (where === "speech") return text + ". Record again — press the microphone to start, and again to stop."; if (where === "photo") return text + ". It may be damaged — try another photo."; return text + ". " + cap(next) + "."; case 422: if (err.tooLong && where === "speak") return "That translation is too long to read aloud. Translate it in " + "smaller pieces to hear them."; if (err.tooLong && where === "feedback") return "That note is longer than the box takes. Shorten it, then send it again."; if (err.tooLong) return TOO_MUCH_TEXT; return "Lilly could not read that request. Reload the page, then " + next + "."; case 503: return (text || "That model is not on this machine") + ". " + cap(next) + "."; } if (err && err.status >= 500) return (text || "Something went wrong on our side") + ". " + cap(next) + " — if it keeps happening, the server's log says what broke."; return "Lilly could not do that just now. Reload the page, then " + next + "."; } function busy(btn, on) { btn.classList.toggle("busy", on); } /* ---- result ------------------------------------------------------- */ let thumbUrl = null; function setThumb(file) { if (thumbUrl) { URL.revokeObjectURL(thumbUrl); thumbUrl = null; } const el = $("srcThumb"); // The thumbnail belongs beside what was photographed, whichever side that is. (isReply() ? $("outEnglish") : $("outBosnian")).parentElement.prepend(el); if (file) { thumbUrl = URL.createObjectURL(file); el.src = thumbUrl; el.hidden = false; } else { el.removeAttribute("src"); el.hidden = true; } } function showResult(bosnian, english, file) { state.bosnian = bosnian; state.english = english; state.audioUrl = null; $("outBosnian").textContent = bosnian; $("outEnglish").textContent = english; setThumb(file || null); const card = $("result"); const already = card.classList.contains("visible"); card.classList.add("visible"); document.body.classList.add("has-result"); if (already && !calm) { // replacing an answer: cross-fade the words card.classList.remove("swap"); void card.offsetWidth; card.classList.add("swap"); } setStatus(""); remember(bosnian, english); // every successful result is history } /* The server explains itself in JSON: {"error": "..."} for the failures it knows about, and a {"detail": [...]} list when a request never got as far as the model. Carry the status and the sentence out together — the status alone cannot say which file, and the sentence alone cannot say what to do. */ function httpError(res, data) { const err = new Error("HTTP " + res.status); err.status = res.status; err.serverText = (data && typeof data.error === "string") ? data.error : ""; const detail = (data && data.detail) || []; err.tooLong = Array.isArray(detail) && detail.some(d => d && typeof d.type === "string" && d.type.indexOf("too_long") >= 0); return err; } async function apiJson(path, options) { options = options || {}; const timeoutMs = options.timeoutMs || 0; const fetchOpts = Object.assign({}, options); delete fetchOpts.timeoutMs; let timer = 0; if (timeoutMs) { const ctrl = new AbortController(); if (fetchOpts.signal) { fetchOpts.signal.addEventListener("abort", () => ctrl.abort(), { once: true }); } fetchOpts.signal = ctrl.signal; timer = setTimeout(() => ctrl.abort(), timeoutMs); } try { const res = await fetch(path, fetchOpts); const data = await res.json().catch(() => null); if (!res.ok) throw httpError(res, data); return data; } catch (e) { if (e && e.name === "AbortError" && timeoutMs) throw Object.assign(new Error("timeout"), { timeout: true }); throw e; } finally { if (timer) clearTimeout(timer); } } /* ---- text --------------------------------------------------------- */ /* One translation request at a time, the newest wins. A slow answer to what was typed three keystrokes ago must never land after the answer to what is in the box now, so every new run aborts the in-flight one. */ let liveCtrl = null, liveTimer = 0; function abortLive() { if (liveCtrl) { liveCtrl.abort(); liveCtrl = null; } } /* The one path a typed text travels: straight to the direction the arrow shows, Bosnian → English or English → Bosnian. */ async function translateText(text, signal) { const json = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text }), signal }; return apiJson(isReply() ? "/api/reply" : "/api/translate", json); } /* Translate-as-you-type: 300 ms after the last keystroke the settled text is translated, and the next keystroke cancels the run in flight. */ function scheduleLive() { clearTimeout(liveTimer); liveTimer = setTimeout(liveTranslate, 300); } async function liveTranslate() { const text = $("input").value.trim(); abortLive(); if (!text) return; const ctrl = liveCtrl = new AbortController(); try { const data = await translateText(text, ctrl.signal); showResult(data.bosnian, data.english); } catch (e) { if (e && e.name === "AbortError") return; // replaced by a newer request fail(describe(e, "translate")); } finally { if (liveCtrl === ctrl) liveCtrl = null; // never clear a newer run's controller } } $("translateBtn").addEventListener("click", async () => { const text = $("input").value.trim(); if (!text) { $("input").focus(); return; } clearTimeout(liveTimer); abortLive(); busy($("translateBtn"), true); setStatus("Translating…", true); try { const data = await translateText(text); showResult(data.bosnian, data.english); } catch (e) { fail(describe(e, "translate")); } finally { busy($("translateBtn"), false); } }); $("swapBtn").addEventListener("click", () => { abortLive(); const goingReply = !isReply(); if (state.bosnian || state.english) { $("input").value = goingReply ? (state.english || "") : (state.bosnian || ""); document.body.classList.toggle("has-text", $("input").value.trim().length > 0); } applyDirection(goingReply); if ($("input").value.trim()) $("translateBtn").click(); }); $("input").addEventListener("keydown", e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); $("translateBtn").click(); } }); /* The character counter is a guide, not a gate: the server holds the real limits (12,000 characters, then tokens) and answers past-them inputs with its own sentence. Five thousand is the point where the counter turns red and asks the reader to think about splitting the text up. */ const COUNTER_MAX = 5000; function updateCounter() { const n = $("input").value.length; $("counter").textContent = n + " / " + COUNTER_MAX; $("counter").classList.toggle("over", n > COUNTER_MAX); } $("input").addEventListener("input", () => { document.body.classList.toggle("has-text", $("input").value.trim().length > 0); updateCounter(); scheduleLive(); // translate as you type }); $("clearBtn").addEventListener("click", () => { $("input").value = ""; document.body.classList.remove("has-text"); updateCounter(); abortLive(); // no answer may land for text that is gone $("input").focus(); }); /* ---- microphone ---------------------------------------------------- */ /* Conversation mode: the microphone becomes a two-sided tap-to-talk loop. Everything else about the page stays as it is; only the direction the clip travels with and what happens after the answer change. */ $("convoBtn").addEventListener("click", () => { const on = !isConvo(); document.body.classList.toggle("convo", on); $("convoBtn").setAttribute("aria-pressed", on ? "true" : "false"); updateHint(); setStatus(on ? "Conversation on — tap the microphone and say either language." : "Conversation off."); }); let recorder = null, chunks = []; let audioCtx = null, srcNode = null, levelRaf = 0; function startLevel(stream) { if (calm) return; try { const Ctx = window.AudioContext || window.webkitAudioContext; if (!Ctx) return; audioCtx = new Ctx(); srcNode = audioCtx.createMediaStreamSource(stream); const analyser = audioCtx.createAnalyser(); analyser.fftSize = 512; analyser.smoothingTimeConstant = 0.82; srcNode.connect(analyser); const buf = new Uint8Array(analyser.fftSize); const tick = () => { analyser.getByteTimeDomainData(buf); let sum = 0; for (let i = 0; i < buf.length; i++) { const v = (buf[i] - 128) / 128; sum += v * v; } const level = Math.min(1, Math.sqrt(sum / buf.length) * 4.5); $("micBtn").style.setProperty("--level", level.toFixed(3)); levelRaf = requestAnimationFrame(tick); }; tick(); } catch (e) { /* the meter is a courtesy; recording does not depend on it */ } } function stopLevel() { if (levelRaf) { cancelAnimationFrame(levelRaf); levelRaf = 0; } try { if (srcNode) srcNode.disconnect(); } catch (e) {} try { if (audioCtx) audioCtx.close(); } catch (e) {} srcNode = null; audioCtx = null; $("micBtn").style.setProperty("--level", "0"); } $("micBtn").addEventListener("click", async () => { if (recorder && recorder.state === "recording") { recorder.stop(); return; } // Browsers hand out getUserMedia only on a secure origin, and localhost // counts as one. Reached over plain http from a phone on the same wifi — // which is how the README says to try Lilly on a phone — the whole // mediaDevices object is missing, so the call throws before any permission // prompt exists. Left to the catch below it reads as "allow it in the // browser": an instruction with no button behind it, since there is nothing // to allow and pressing again cannot help. if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { fail(window.isSecureContext ? "This browser will not give Lilly a microphone. Type the Bosnian " + "instead, or open Lilly in a different browser." : "Browsers only allow recording over https, and Lilly is open over " + "http. Type the Bosnian instead, or open Lilly at " + "http://localhost:8000 on the machine running it."); return; } try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); chunks = []; recorder = new MediaRecorder(stream); recorder.ondataavailable = e => chunks.push(e.data); recorder.onstop = async () => { stopLevel(); stream.getTracks().forEach(t => t.stop()); $("micBtn").classList.remove("recording"); busy($("micBtn"), true); setStatus("Listening to what you said…", true); const blob = new Blob(chunks, { type: recorder.mimeType }); const form = new FormData(); form.append("file", blob, "speech.webm"); form.append("direction", isConvo() ? "auto" : direction()); try { const data = await apiJson("/api/speech", { method: "POST", body: form, timeoutMs: SPEECH_WAIT_MS }); // Conversation mode: the server heard whatever language it heard and // said which. The arrow follows the heard side, the answer is read // aloud, and the microphone is left armed for the next utterance — // the loop is tap, speak, listen, tap again. if (isConvo()) { const heardText = data.heard === "en" ? data.english : data.bosnian; if (!heardText) { fail("Lilly did not catch any words. Record again, closer to the microphone."); return; } applyDirection(data.heard === "en"); $("input").value = heardText; document.body.classList.add("has-text"); updateCounter(); showResult(data.bosnian, data.english); setStatus("Conversation — tap the microphone for the next one.", true); playAnswer(); return; } const heard = sourceOf(data); if (!heard) { fail("Lilly did not catch any words. Record again, closer to the microphone."); return; } $("input").value = heard; document.body.classList.add("has-text"); updateCounter(); showResult(data.bosnian, data.english); playAnswer(); // speak the answer back automatically } catch (e) { fail(describe(e, "speech")); } finally { busy($("micBtn"), false); } }; recorder.start(); $("micBtn").classList.add("recording"); startLevel(stream); setStatus("Recording — press again to stop", true); } catch (e) { fail(e && e.name === "NotFoundError" ? "No microphone found. Connect one, then press the microphone again." : e && e.name === "NotReadableError" ? "Another program is using the microphone. Close it, then press the " + "microphone again." : e && e.name === "NotAllowedError" ? "Lilly needs permission to use the microphone. Allow it in the browser, " + "then press the microphone again." // Anything else is not a permission problem, and sending someone to grant // permission they were never refused sends them hunting for a setting // that is not there. : "Lilly could not start recording. Type the Bosnian instead, or press " + "the microphone again in a moment."); } }); /* ---- photo --------------------------------------------------------- */ /* A phone photograph is often 12 MP HEIC. The reader already shrinks to 2 MP (app/ocr.py MAX_WORKING_PIXELS) and measured no gain above that, so sending the original only costs upload time and first-decode on the Space's two CPUs. 1600 on the long side is about that working size, and drawing through a canvas turns HEIC into JPEG the reader can open. */ const PHOTO_MAX_SIDE = 1600; const PHOTO_WAIT_MS = 90000; const SPEECH_WAIT_MS = 120000; function blobToJpeg(source, maxSide) { const w0 = source.videoWidth || source.naturalWidth || source.width; const h0 = source.videoHeight || source.naturalHeight || source.height; if (!w0) return Promise.resolve(null); let w = w0, h = h0; if (Math.max(w, h) > maxSide) { const s = maxSide / Math.max(w, h); w = Math.round(w * s); h = Math.round(h * s); } const canvas = document.createElement("canvas"); canvas.width = w; canvas.height = h; canvas.getContext("2d").drawImage(source, 0, 0, w, h); return new Promise(res => canvas.toBlob(res, "image/jpeg", 0.85)); } async function jpegForReader(file) { if (typeof createImageBitmap !== "function") return file; try { const bitmap = await createImageBitmap(file); const blob = await blobToJpeg(bitmap, PHOTO_MAX_SIDE); bitmap.close(); return blob || file; } catch (e) { return file; } } async function readPhoto(file) { if (!file) return; busy($("photoBtn"), true); setStatus("Reading the photo…", true); const body = await jpegForReader(file); const form = new FormData(); form.append("file", body, "photo.jpg"); form.append("direction", direction()); try { const data = await apiJson("/api/photo", { method: "POST", body: form, timeoutMs: PHOTO_WAIT_MS }); const seen = sourceOf(data); if (!seen) { fail("No text found in that photo. Take it again straight on, with the words filling the frame."); return; } $("input").value = seen; document.body.classList.add("has-text"); updateCounter(); showResult(data.bosnian, data.english, body); } catch (e) { fail(describe(e, "photo")); } finally { busy($("photoBtn"), false); } } $("photoBtn").addEventListener("click", () => $("photoInput").click()); $("photoInput").addEventListener("change", async () => { const file = $("photoInput").files[0]; $("photoInput").value = ""; await readPhoto(file); }); /* A photo dropped on the window, or pasted, is the same request. */ let dragDepth = 0; const hasImage = dt => dt && Array.from(dt.types || []).includes("Files"); window.addEventListener("dragenter", e => { if (!hasImage(e.dataTransfer)) return; e.preventDefault(); dragDepth++; document.body.classList.add("dropping"); }); window.addEventListener("dragover", e => { if (hasImage(e.dataTransfer)) e.preventDefault(); }); window.addEventListener("dragleave", e => { if (!hasImage(e.dataTransfer)) return; dragDepth = Math.max(0, dragDepth - 1); if (!dragDepth) document.body.classList.remove("dropping"); }); window.addEventListener("drop", e => { if (!hasImage(e.dataTransfer)) return; e.preventDefault(); dragDepth = 0; document.body.classList.remove("dropping"); const file = Array.from(e.dataTransfer.files).find(f => f.type.startsWith("image/")); if (file) readPhoto(file); else fail("That is not an image. Drop a photo file instead — a JPEG or a PNG."); }); window.addEventListener("paste", e => { const file = Array.from((e.clipboardData && e.clipboardData.files) || []) .find(f => f.type.startsWith("image/")); if (file) { e.preventDefault(); readPhoto(file); } }); /* ---- voice out ----------------------------------------------------- */ /* The answer, read aloud: the English when Bosnian came in, the Bosnian when English did. The audio is kept per answer and per language, so a swap after the fact fetches the other side rather than replaying this one. */ async function playAnswer() { const lang = isReply() ? "bs" : "en"; const text = lang === "bs" ? state.bosnian : state.english; if (!text) return; const btn = $("playBtn"); btn.disabled = true; busy(btn, true); try { if (!state.audioUrl || state.audioLang !== lang) { const res = await fetch("/api/speak", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text, language: lang }) }); if (!res.ok) throw httpError(res, await res.json().catch(() => null)); state.audioUrl = URL.createObjectURL(await res.blob()); state.audioLang = lang; } await new Audio(state.audioUrl).play(); } catch (e) { // The voice plays by itself straight after a recording, and a browser may // refuse to start audio nobody asked for. Nothing is broken, so say the // one thing that fixes it rather than blaming the server. fail(e && e.name === "NotAllowedError" ? "The browser blocked the sound. Press Play voice to hear it." : describe(e, "speak")); } finally { busy(btn, false); btn.disabled = false; } } $("playBtn").addEventListener("click", playAnswer); /* Copying has to survive three worlds: a secure origin where the async clipboard API works, a plain-http origin (a phone on the local network) where `navigator.clipboard` does not exist at all, and an embedded browser that reports success while writing nothing. So the fallback selects the English on the page rather than a hidden field: if the write silently does not take, the words are sitting there highlighted and the reader's own shortcut finishes the job. */ function selectAnswer() { const node = isReply() ? $("outBosnian") : $("outEnglish"); const sel = window.getSelection(); const range = document.createRange(); range.selectNodeContents(node); sel.removeAllRanges(); sel.addRange(range); try { return document.execCommand("copy"); } catch (e) { return false; } } const COPY_KEY = /Mac|iPhone|iPad/.test(navigator.platform || "") ? "\u2318C" : "Ctrl+C"; function copyAnswer() { const text = isReply() ? state.bosnian : state.english; if (!text) return; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(text) .then(() => setStatus("Copied")) .catch(() => setStatus(selectAnswer() ? "Copied" : "Press " + COPY_KEY + " — the translation is selected.")); return; } setStatus(selectAnswer() ? "Copied" : "Press " + COPY_KEY + " — the translation is selected."); } $("copyBtn").addEventListener("click", copyAnswer); /* Share where the platform has it; everywhere else, the copy routine above is the fallback — the answer is selected on the page, so the reader's own shortcut finishes the job even where a silent write fails. */ $("shareBtn").addEventListener("click", async () => { const text = isReply() ? state.bosnian : state.english; if (!text) return; if (navigator.share) { try { await navigator.share({ text }); return; } catch (e) { if (e && e.name === "AbortError") return; } // dismissed: not a failure } copyAnswer(); }); /* ---- correction loop ------------------------------------------------ */ const dlg = $("feedbackDialog"); function noteFeedback(msg) { $("fbNote").textContent = msg || ""; $("fbNote").hidden = !msg; } function closeFeedback() { if (!dlg.open) return; dlg.classList.add("closing"); setTimeout(() => { dlg.classList.remove("closing"); dlg.close(); }, calm ? 0 : 200); } $("wrongBtn").addEventListener("click", () => { noteFeedback(""); $("fbQuoteBs").textContent = state.bosnian; $("fbQuoteEn").textContent = state.english; dlg.showModal(); $("fbWhat").focus(); }); $("fbCancel").addEventListener("click", closeFeedback); dlg.addEventListener("cancel", e => { e.preventDefault(); closeFeedback(); }); dlg.addEventListener("click", e => { if (e.target === dlg) closeFeedback(); }); $("fbSend").addEventListener("click", async () => { busy($("fbSend"), true); try { await apiJson("/api/feedback", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ source_text: isReply() ? state.english : state.bosnian, model_output: isReply() ? state.bosnian : state.english, user_complaint: $("fbWhat").value.trim(), suggested_translation: $("fbSuggest").value.trim(), direction: isReply() ? "en-bs" : "bs-en" }) }); closeFeedback(); $("fbWhat").value = ""; $("fbSuggest").value = ""; noteFeedback(""); setStatus("Thank you — your correction was saved for review."); } catch (e) { // Not the toast: it would be behind the open sheet. Answer where the // reader is looking, and leave what they wrote where they left it. noteFeedback(describe(e, "feedback")); } finally { busy($("fbSend"), false); } }); /* ---- history & phrasebook ------------------------------------------- Both live in localStorage, so they survive a reload and cost the server nothing. The lists are capped: a long evening of translations cannot grow the store without bound, and a full or blocked store degrades the feature rather than the translation. */ const HIST_KEY = "lilly.history.v1", SAVED_KEY = "lilly.saved.v1"; const HIST_CAP = 50, SAVED_CAP = 200; function loadList(key) { try { const v = JSON.parse(localStorage.getItem(key) || "[]"); return Array.isArray(v) ? v : []; } catch (e) { return []; } } function saveList(key, list) { try { localStorage.setItem(key, JSON.stringify(list)); } catch (e) { /* storage unavailable — history is a courtesy, translation is not */ } } /* Every successful result is remembered, live typing included; a pair already in the list is moved back to the top rather than stacked — the same translation made again, or restored from the list, is one entry. The direction is whichever the arrow showed when the result landed, so a click can put the pair back exactly the way it was made. */ function remember(bosnian, english) { if (!bosnian && !english) return; const direction = isReply() ? "en-bs" : "bs-en"; const entry = { bosnian, english, direction, ts: Date.now() }; const list = loadList(HIST_KEY); const i = list.findIndex(e => e.bosnian === bosnian && e.english === english && e.direction === entry.direction); if (i === 0) { list[0].ts = entry.ts; } else { if (i > 0) list.splice(i, 1); /* Translate-as-you-type makes a result out of every pause, and the exact-match check above cannot see that. Measured in a browser before this line existed: one sentence typed with three natural pauses left three entries, two of them half-words -- "Gdje je na", "Gdje je najbliza a", "Gdje je najbliza apoteka?". At a 50-entry cap a few minutes of typing would evict every real translation in favour of fragments of the newest one. A run of typing is one thought, so when the newest entry's source text and this one are prefixes of each other -- still typing, or backspacing over a mistake -- the run collapses onto its latest state instead of stacking. Two genuinely different texts are never prefixes of each other, so history a person actually made is untouched. The source side is whichever one was typed, which is what the direction records. */ const sourceOf = e => (e.direction === "en-bs" ? e.english : e.bosnian) || ""; const head = list[0]; const typed = sourceOf(entry), earlier = head ? sourceOf(head) : ""; if (head && head.direction === direction && typed && earlier && (typed.startsWith(earlier) || earlier.startsWith(typed))) { list.shift(); } list.unshift(entry); if (list.length > HIST_CAP) list.length = HIST_CAP; } saveList(HIST_KEY, list); renderHistory(); } function pairRow(entry, onRemove) { const li = document.createElement("li"); li.className = "lib-item"; const btn = document.createElement("button"); btn.type = "button"; btn.className = "lib-row"; const dir = document.createElement("span"); dir.className = "dir"; dir.textContent = entry.direction === "en-bs" ? "English \u2192 Bosnian" : "Bosnian \u2192 English"; const src = document.createElement("span"); src.className = "src"; src.textContent = entry.direction === "en-bs" ? entry.english : entry.bosnian; const dst = document.createElement("span"); dst.className = "dst"; dst.textContent = entry.direction === "en-bs" ? entry.bosnian : entry.english; btn.append(dir, src, dst); btn.addEventListener("click", () => restorePair(entry)); li.appendChild(btn); if (onRemove) { const x = document.createElement("button"); x.type = "button"; x.className = "lib-x"; x.setAttribute("aria-label", "Remove this pair"); x.textContent = "\u00d7"; x.addEventListener("click", onRemove); li.appendChild(x); } return li; } function renderList(key, listEl, removable) { const list = loadList(key); listEl.innerHTML = ""; if (!list.length) { const empty = document.createElement("li"); empty.className = "lib-empty"; empty.textContent = key === HIST_KEY ? "Nothing yet." : "Nothing saved."; listEl.appendChild(empty); return; } for (const entry of list) { listEl.appendChild(pairRow(entry, removable && (() => { saveList(key, loadList(key).filter(e => e !== entry)); renderList(key, listEl, removable); }))); } } function renderHistory() { renderList(HIST_KEY, $("histList"), false); } function renderSaved() { renderList(SAVED_KEY, $("savedList"), true); } /* A click puts the pair back exactly as it was made: the arrow, the input and the result, straight from the stored answer — no network round trip. */ function restorePair(entry) { clearTimeout(liveTimer); abortLive(); applyDirection(entry.direction === "en-bs"); $("input").value = entry.direction === "en-bs" ? entry.english : entry.bosnian; document.body.classList.add("has-text"); updateCounter(); showResult(entry.bosnian, entry.english); setStatus(""); } function selectTab(hist) { $("histTab").classList.toggle("on", hist); $("savedTab").classList.toggle("on", !hist); $("histTab").setAttribute("aria-selected", hist ? "true" : "false"); $("savedTab").setAttribute("aria-selected", hist ? "false" : "true"); $("histList").hidden = !hist; $("savedList").hidden = hist; $("histClear").hidden = !hist; renderHistory(); renderSaved(); } $("histTab").addEventListener("click", () => selectTab(true)); $("savedTab").addEventListener("click", () => selectTab(false)); $("histClear").addEventListener("click", () => { saveList(HIST_KEY, []); renderHistory(); setStatus("History cleared."); }); $("saveBtn").addEventListener("click", () => { const pair = { bosnian: state.bosnian, english: state.english, direction: isReply() ? "en-bs" : "bs-en", ts: Date.now() }; if (!pair.bosnian && !pair.english) { fail("There is no translation to save yet — translate something first."); return; } const list = loadList(SAVED_KEY); const already = list.some(e => e.bosnian === pair.bosnian && e.english === pair.english && e.direction === pair.direction); if (already) { setStatus("Already in your phrasebook."); return; } list.unshift(pair); if (list.length > SAVED_CAP) list.length = SAVED_CAP; saveList(SAVED_KEY, list); renderSaved(); setStatus("Saved to your phrasebook."); }); /* ---- live camera ------------------------------------------------------ The viewfinder is getUserMedia; the frame then travels to /api/photo-boxes the same way a photo upload would. Hugging Face shows this page inside another page (huggingface.co embedding *.hf.space). A phone will not give a camera to that inner page: getUserMedia fails with NotAllowedError and never shows a prompt. The panel then offers the Space in its own tab (where the same button gets a real viewfinder) and a capture=environment file input, which is the native camera and does work inside the iframe. facingMode "environment" as a required constraint also fails on a laptop with only a face camera, so the second try is any video. */ let camStream = null, camStillUrl = null; function pageIsFramed() { try { return window.self !== window.top; } catch (e) { return true; } } async function requestCameraStream() { const tries = [ { video: { facingMode: { ideal: "environment" } }, audio: false }, { video: true, audio: false } ]; let last = null; for (const constraints of tries) { try { return await navigator.mediaDevices.getUserMedia(constraints); } catch (e) { last = e; } } throw last; } function hideCameraHelp() { $("camNote").hidden = true; $("camEscape").hidden = true; $("camTakeShot").hidden = true; } function showCameraHelp(err) { const framed = pageIsFramed(); const denied = err && err.name === "NotAllowedError"; let msg; if (framed) { msg = "Hugging Face shows Lilly inside another page, and this phone will " + "not give that page a live camera. Open Lilly in its own tab, then " + "press the camera button again — or take a photo with the phone " + "camera below."; } else if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { msg = window.isSecureContext ? "This browser will not give Lilly a live camera. Take a photo with " + "the phone camera below, or use the photo button." : "Browsers only allow the camera over https, and Lilly is open over " + "http. Open it at http://localhost:8000 on this machine, or take " + "a photo with the phone camera below."; } else if (denied) { msg = "Lilly needs permission to use the camera. Allow it in the browser, " + "then press the camera button again — or take a photo with the " + "phone camera below."; } else { msg = "Lilly could not start the live camera. Take a photo with the " + "phone camera below, or use the photo button."; } $("camCapture").disabled = true; $("camNote").textContent = msg; $("camNote").hidden = false; $("camOpenTab").href = location.href; $("camEscape").hidden = !framed; $("camTakeShot").hidden = false; } async function openCamera() { const panel = $("cameraPanel"); if (!panel.hidden) { closeCamera(); return; } panel.hidden = false; hideCameraHelp(); $("camCapture").querySelector(".lbl").textContent = "Capture"; $("camCapture").disabled = true; panel.scrollIntoView({ block: "nearest" }); if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { showCameraHelp(null); return; } try { camStream = await requestCameraStream(); const video = $("camVideo"); video.setAttribute("playsinline", ""); video.playsInline = true; video.muted = true; video.srcObject = camStream; video.hidden = false; try { await video.play(); } catch (e) {} $("camCapture").disabled = false; } catch (e) { showCameraHelp(e); } } function closeCamera() { if (camStream) { camStream.getTracks().forEach(t => t.stop()); camStream = null; } if (camStillUrl) { URL.revokeObjectURL(camStillUrl); camStillUrl = null; } $("camVideo").srcObject = null; $("camVideo").hidden = true; $("camStill").hidden = true; $("camOverlay").innerHTML = ""; $("camStage").classList.remove("still"); $("camStage").style.aspectRatio = ""; hideCameraHelp(); $("cameraPanel").hidden = true; } $("camClose").addEventListener("click", closeCamera); $("camBtn").addEventListener("click", openCamera); $("camTakeShot").addEventListener("click", () => $("camShotInput").click()); $("camShotInput").addEventListener("change", async () => { const file = $("camShotInput").files[0]; $("camShotInput").value = ""; if (!file) return; const blob = await jpegForReader(file); await sendCameraFrame(blob); }); async function sendCameraFrame(blob) { if (!blob) { fail("The camera frame could not be read. Try the capture again."); return; } $("camVideo").hidden = true; if (camStillUrl) URL.revokeObjectURL(camStillUrl); camStillUrl = URL.createObjectURL(blob); $("camStill").src = camStillUrl; $("camStill").hidden = false; $("camStage").classList.add("still"); busy($("camCapture"), true); busy($("camTakeShot"), true); setStatus("Reading the photo…", true); const form = new FormData(); form.append("file", blob, "frame.jpg"); form.append("direction", direction()); try { const data = await apiJson("/api/photo-boxes", { method: "POST", body: form, timeoutMs: PHOTO_WAIT_MS }); drawCameraOverlay(blob, data); const seen = sourceOf(data); if (seen) { $("input").value = seen; document.body.classList.add("has-text"); updateCounter(); } showResult(data.bosnian, data.english, blob); } catch (e) { fail(describe(e, "photo")); } finally { busy($("camCapture"), false); busy($("camTakeShot"), false); } } $("camCapture").addEventListener("click", async () => { // After a capture the stage shows the still; the same button returns to // the live view for another shot. if ($("camStage").classList.contains("still")) { $("camStill").hidden = true; $("camOverlay").innerHTML = ""; $("camStage").classList.remove("still"); $("camVideo").hidden = false; $("camCapture").querySelector(".lbl").textContent = "Capture"; return; } const blob = await blobToJpeg($("camVideo"), PHOTO_MAX_SIDE); await sendCameraFrame(blob); }); /* The frame is drawn over by each region's translation, placed where the words were found. Boxes arrive in the frame's own pixels, so they are mapped to percentages of the still's natural size and the stage is set to the frame's aspect — overlay and picture then move together at any display size. The still decodes asynchronously, so the placement runs once it has its real size (onload), and again straight away in case it decoded before the handler could attach. */ function drawCameraOverlay(blob, data) { $("camVideo").hidden = true; const stage = $("camStage"); stage.classList.add("still"); if (camStillUrl) URL.revokeObjectURL(camStillUrl); camStillUrl = URL.createObjectURL(blob); const still = $("camStill"); still.src = camStillUrl; still.hidden = false; $("camCapture").querySelector(".lbl").textContent = camStream ? "Live view" : "Capture"; $("camCapture").disabled = !camStream; const place = () => { if (!still.naturalWidth) return; stage.style.aspectRatio = still.naturalWidth + " / " + still.naturalHeight; const overlay = $("camOverlay"); overlay.innerHTML = ""; for (const region of data.regions || []) { if (!region.translated || !region.box || region.box.length < 2) continue; const xs = region.box.map(p => p[0]), ys = region.box.map(p => p[1]); const x0 = Math.min(...xs), y0 = Math.min(...ys); const x1 = Math.max(...xs), y1 = Math.max(...ys); const chip = document.createElement("span"); chip.className = "cam-chip"; chip.textContent = region.translated; chip.style.left = (x0 / still.naturalWidth * 100) + "%"; chip.style.top = (y0 / still.naturalHeight * 100) + "%"; chip.style.width = Math.max(4, (x1 - x0) / still.naturalWidth * 100) + "%"; overlay.appendChild(chip); } }; still.onload = place; place(); } /* ---- handwriting ------------------------------------------------------ A canvas pad, exported as a PNG and sent to the same /api/photo the camera and the file picker use. The reader cannot tell a drawn page from a photographed one, so no new server path is needed. */ const writeDlg = $("writeDialog"); let drawing = false; function sizePad() { const pad = $("writePad"); const width = Math.min(pad.parentElement.clientWidth, 560); const scale = Math.max(window.devicePixelRatio || 1, 1); // Crisp strokes on a retina screen: the bitmap is dpr times the CSS size // and the context scaled back, so one logical pixel is one logical pixel. pad.style.width = width + "px"; pad.style.height = "240px"; pad.width = Math.round(width * scale); pad.height = Math.round(240 * scale); const ctx = pad.getContext("2d"); ctx.scale(scale, scale); ctx.lineWidth = 3; ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.strokeStyle = "#14181a"; } $("writeBtn").addEventListener("click", () => { sizePad(); // resizing clears the pad: only on open $("writeNote").hidden = true; writeDlg.showModal(); }); function padPoint(e) { const rect = $("writePad").getBoundingClientRect(); return [e.clientX - rect.left, e.clientY - rect.top]; } $("writePad").addEventListener("pointerdown", e => { drawing = true; $("writePad").setPointerCapture(e.pointerId); const [x, y] = padPoint(e); const ctx = $("writePad").getContext("2d"); ctx.beginPath(); ctx.moveTo(x, y); }); $("writePad").addEventListener("pointermove", e => { if (!drawing) return; const [x, y] = padPoint(e); const ctx = $("writePad").getContext("2d"); ctx.lineTo(x, y); ctx.stroke(); }); $("writePad").addEventListener("pointerup", () => { drawing = false; }); $("writePad").addEventListener("pointercancel", () => { drawing = false; }); $("writeClear").addEventListener("click", () => { const pad = $("writePad"); pad.getContext("2d").clearRect(0, 0, pad.width, pad.height); }); $("writeCancel").addEventListener("click", () => writeDlg.close()); $("writeSend").addEventListener("click", async () => { busy($("writeSend"), true); $("writeNote").hidden = true; try { const blob = await new Promise(res => $("writePad").toBlob(res, "image/png")); if (!blob) throw new Error("empty pad export"); const form = new FormData(); form.append("file", blob, "handwriting.png"); form.append("direction", direction()); const data = await apiJson("/api/photo", { method: "POST", body: form }); const seen = sourceOf(data); if (!seen) { $("writeNote").textContent = "Lilly could not read the pad. Write larger, " + "with clear letters, then press Read it again."; $("writeNote").hidden = false; return; } writeDlg.close(); $("input").value = seen; document.body.classList.add("has-text"); updateCounter(); showResult(data.bosnian, data.english); } catch (e) { // Inside the modal the toast sits behind the backdrop: answer where the // reader is looking, the way the correction sheet does. $("writeNote").textContent = describe(e, "photo"); $("writeNote").hidden = false; } finally { busy($("writeSend"), false); } }); /* ---- document ---------------------------------------------------------- A .docx or .pdf travels to /api/document; its text comes back as `original` and drops into the box the way a photograph's text does, with the usual bosnian/english pair beside it. */ $("docBtn").addEventListener("click", () => $("docInput").click()); $("docInput").addEventListener("change", async () => { const file = $("docInput").files[0]; $("docInput").value = ""; if (!file) return; busy($("docBtn"), true); setStatus("Reading the document…", true); const form = new FormData(); form.append("file", file, file.name || "document.pdf"); form.append("direction", direction()); try { const data = await apiJson("/api/document", { method: "POST", body: form }); $("input").value = data.original || ""; document.body.classList.add("has-text"); updateCounter(); showResult(data.bosnian, data.english); } catch (e) { fail(describe(e, "document")); } finally { busy($("docBtn"), false); } }); /* ---- start ---------------------------------------------------------- */ applyDirection(false); // Bosnian → English is the default; the arrow flips it updateCounter(); renderHistory(); renderSaved(); </script> </body> </html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="light">
<meta name="theme-color" content="#f7f4f0">
<meta name="description" content="Lilly translates Bosnian and English — typed, spoken, or photographed.">
<title>Lilly</title>
<style>
/* ---------------------------------------------------------------
Sarajevo in daylight, uncovered, behind one viewport of clear
glass. One deep teal accent; the photograph does the rest.
--------------------------------------------------------------- */
:root {
--bg-0: #f7f4f0;
--ink: #14181a;
--ink-2: rgba(20, 24, 26, 0.84);
--ink-3: rgba(20, 24, 26, 0.74);
--ink-quiet: rgba(20, 24, 26, 0.72);
/* Clear glass: the photograph stays readable through every panel. */
--glass: rgba(255, 255, 255, 0.15);
--glass-edge: rgba(255, 255, 255, 0.45);
--glass-lift: rgba(255, 255, 255, 0.16);
--glass-blur: blur(6px);
--hair: rgba(20, 24, 26, 0.1);
--sheen: rgba(255, 255, 255, 0.7);
/* No veil over the photo, so text carries its own light edge instead. */
--lift: 0 0 6px rgba(255, 255, 255, 0.8), 0 0 16px rgba(255, 255, 255, 0.55);
--accent: #0f8a7c;
--accent-hi: #0b6b60;
--accent-ink: #ffffff;
--rec: #c2483e;
--shadow: 0 1px 2px rgba(20, 20, 24, 0.05), 0 18px 40px -18px rgba(20, 20, 24, 0.16);
--r-lg: 24px;
--r-md: 16px;
--r-sm: 12px;
--font-sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, sans-serif;
--font-serif: ui-serif, Georgia, "Iowan Old Style", "Palatino Linotype", "Times New Roman", serif;
--ease: cubic-bezier(0.32, 0.72, 0, 1);
--t-fast: 0.16s;
--t-base: 0.3s;
--t-slow: 0.46s;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
html, body { height: 100%; overflow: hidden; }
body {
font-family: var(--font-sans);
color: var(--ink);
background: #b9cfdc;
height: 100vh;
height: 100dvh;
display: flex;
flex-direction: column;
padding-top: env(safe-area-inset-top);
padding-bottom: env(safe-area-inset-bottom);
-webkit-font-smoothing: antialiased;
}
::selection { background: rgba(15, 138, 124, 0.22); }
/* --- Sarajevo, fixed behind the page, nothing laid over it ---------- */
/* Julian Nyča, Wikimedia Commons, CC BY-SA 4.0, at its full 2800 px so a
Retina screen or a tall phone is not upscaling it. Served beside the
page (app/server.py), not inlined, so the page paints before the photo
has arrived; until then a 48 px copy of the same frame holds its place. */
.bg-photo {
position: fixed;
inset: 0;
z-index: -2;
background-image:
url("sarajevo-2800.jpg"),
url("data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/2wBDAQoLCw4NDhwQEBw7KCIoOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozv/wAARCAAdADADASIAAhEBAxEB/8QAGAAAAwEBAAAAAAAAAAAAAAAAAwQFBgL/xAAsEAACAgEDAgQFBQEAAAAAAAABAgMRBAAhMQUSQVFhcQYTFCKBFSQykaHw/8QAFwEAAwEAAAAAAAAAAAAAAAAAAQIDBP/EABwRAAICAwEBAAAAAAAAAAAAAAABAhEDEhMhQf/aAAwDAQACEQMRAD8AuQ/EOJK5XdKHLUAdOx58TiwwPsQdYP6GSKJ3hl+4HaJ7tvbRcMZocu+PK4Ve7Y1x68Hy1bsiDxOzfLlRkeJ9tdrkIeQdZCDrHZ8wyQGFY6Dsp7rZj/ED/q1Qlz1SNJktkC9xZ3o8cVoPMhliLz5Ceg/OgtlxLzIov11FXNxpAxWa2YiyWofd4X56UlyImjcwtJOyGlEW9EHexz/eh3Q3FknP6gIsgio3pQSe6u0ElSa8tJ9L6xk5B+jhyZYQkeyCNTe9Uo21Txfh8ZKGSSdAKMR7IaLL4gmzt6aQ6nhR9E6ljjHAfvSlZxuhvwP+fnWJSWyizTPatvgfBkbF+J5MdgRCYvmyKBydiOfHn/dONJ3TdkU6CYkhUZqvmuPfSP6p2/upYFkkV1S9hW3INWPbVeLpeNnwPNMCZewBGoDss3wAPPbTzTFg6XhBm6hlNkqhmYSdrOWjpRY23J20fH6tgRCaZHYl3uSmu2u6FVeuGxx0/DnzFdpJFoL3ed1Z8+NQjL82Uyuqli3gKAvfYald+gc3A//Z");
background-size: cover;
background-position: center 30%;
background-repeat: no-repeat;
}
/* --- Masthead ------------------------------------------------------- */
header {
text-align: center;
margin: auto 0 clamp(14px, 2.6vh, 26px);
}
h1 {
font-family: var(--font-serif);
color: var(--ink);
font-size: clamp(36px, 9vw, 46px);
font-weight: 600;
letter-spacing: -0.015em;
text-wrap: balance;
text-shadow: var(--lift);