ALIVE: Making Streaming Video Models Interactive
Python
Release portable ALIVE web inference with shared speech GPU
Jinzhao Liae24b6948868
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..db54518--- /dev/null+++ b/.gitignore@@ -0,0 +1,13 @@+.DS_Store+__pycache__/+*.py[cod]+.venv/+.venvs/+.runtime/+models/+config.json+*.pem+*.key+*.log+.env+.env.*diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..d645695--- /dev/null+++ b/LICENSE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/README.md b/README.mdindex 19b9e96..d1bb9e2 100644--- a/README.md+++ b/README.md@@ -25,6 +25,18 @@<sub>* Equal contribution † Corresponding author</sub></p>+## Local web inference++The **[local deployment guide](Web_Inference/README.md)** provides the ALIVE browser interface, streaming speech recognition, and speech synthesis on **two GPUs**: one for ALIVE and one shared by ASR/TTS. It includes Chinese/English interface labels and selectable voices, with the demo inference settings preserved.++| Component | Hugging Face checkpoint |+| --- | --- |+| ALIVE | |+| ASR | [Qwen/Qwen3-ASR-1.7B](https://huggingface.co/Qwen/Qwen3-ASR-1.7B) |+| TTS | [Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice](https://huggingface.co/Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice) |++The ALIVE checkpoint link will be added later. Follow the guide to supply a local checkpoint, install the isolated environments, and open `https://localhost:8090`. This code release excludes demo recording, evaluation-session logging, and public tunnel deployment.+## DemoWatch ALIVE demonstrate **Streaming Task Coordination** and **Feedback-Seeking Interaction** in English and Chinese. Click the preview to watch the full narrated demo.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000..f973073--- /dev/null+++ b/THIRD_PARTY_NOTICES.md@@ -0,0 +1,7 @@+# Third-party notices++The ALIVE browser/server interface includes modified code derived from [Live VLM WebUI](https://github.com/NVIDIA-AI-IOT/live-vlm-webui), distributed under the Apache License, Version 2.0. Required upstream copyright and license headers are retained in the relevant files. Changes include the ALIVE interface, local speech integration, session handling, and streaming inference support.++The browser loads Lucide, KaTeX, Marked, and DOMPurify from their public distribution URLs. These projects retain their respective licenses. Qwen speech checkpoints and all Python dependencies retain their own licenses; installing them does not transfer ownership to this project. Model weights are not included in this repository.++See `LICENSE` for the Apache License, Version 2.0 text applicable to the retained upstream code. Original ALIVE additions are made available under the same license.diff --git a/Web_Inference/README.md b/Web_Inference/README.mdnew file mode 100644index 0000000..2b4f599--- /dev/null+++ b/Web_Inference/README.md@@ -0,0 +1,124 @@+# ALIVE Web Inference++A local streaming camera assistant with text input, streaming speech recognition, streaming speech synthesis, Chinese/English UI labels, and nine selectable voices. The visual layout and inference defaults match the ALIVE demo configuration.++## Requirements++- Linux, Python 3.12, `venv`, `pip`, and OpenSSL.+- Two CUDA-capable GPUs with sufficient memory for the configured models and context. A compatible driver is required for the selected PyTorch/vLLM wheels. No specific GPU model is required by the launcher.+- A camera, microphone, and a browser on the same machine. Use Chrome or another browser supporting the required media APIs.+- Internet access for initial package/model downloads and the UI's icon/Markdown/math dependencies.++Three Python environments isolate the different inference-engine dependencies. They do not imply three GPUs: the ASR and TTS processes explicitly share the second GPU. TTS initializes before ASR to avoid overlapping memory profiling.++## 1. Install++From the repository root:++```bash+cd Web_Inference+python3.12 scripts/setup.py+cp config.example.json config.json+```++This creates `.venvs/main`, `.venvs/asr`, and `.venvs/tts`, and downloads the two voice checkpoints into `models/`. The dependency versions are based on the running demo environments. Installation must succeed with the target machine's CUDA/driver combination; do not merge all three requirements files into one environment.++To download through a Hugging Face mirror:++```bash+export HF_ENDPOINT=https://hf-mirror.com+python3.12 scripts/setup.py+```++Or install without downloads, then download separately:++```bash+python3.12 scripts/setup.py --skip-download+.venvs/main/bin/python scripts/download_models.py+```++| Component | Checkpoint |+| --- | --- |+| Main model | |+| Speech recognition | [Qwen/Qwen3-ASR-1.7B](https://huggingface.co/Qwen/Qwen3-ASR-1.7B) |+| Speech synthesis | [Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice](https://huggingface.co/Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice) |++The main-model URL is intentionally blank. Put the complete ALIVE checkpoint, including its tokenizer and image processor files, in `models/ALIVE`, or set `model_path` in `config.json`. Model locations resolve relative to `Web_Inference`; they are not bundled with the code.++## 2. Configure and start++Default `config.json` settings:++```json+{+ "model_path": "models/ALIVE",+ "model_url": "",+ "asr_model_path": "models/Qwen3-ASR-1.7B",+ "tts_model_path": "models/Qwen3-TTS-12Hz-1.7B-CustomVoice",+ "main_gpu": "0",+ "voice_gpu": "1",+ "port": 8090,+ "startup_timeout": 2400+}+```++Device identifiers refer to local physical GPU indices or GPU UUIDs. Choose two distinct devices. The launcher explicitly assigns visibility separately for main and voice workers; the two TTS stages both use device `0` within the voice process's visible device set.++```bash+python3.12 start.py --check+python3.12 start.py+```++`--check` verifies checkpoint configuration files and environment executables; it does not load weights or establish GPU compatibility. The normal launcher waits for all services to become healthy before printing the browser URL.++Open **https://localhost:8090**. The launcher creates a local self-signed certificate; accept it for this local address, allow camera/microphone access, and start the camera. Enable **Sound** for model speech. The language selector changes interface labels only; it does not translate the conversation. Voice mode and experimental full duplex are available; full duplex is disabled by default.++Press **Ctrl+C** in the launcher terminal to stop all of its workers and release both GPUs. A worker failure also shuts down the other workers. Service logs are in `.runtime/logs/`. The launcher binds services to loopback and does not create public links.++## Inference configuration++| Setting | Default |+| --- | --- |+| Public model identity | ALIVE |+| Temperature | 0.8 |+| Top-p | 0.9 |+| Top-k | 40 |+| Repetition penalty | 1.1 |+| Presence penalty | 1.5 |+| Maximum generated tokens | 256 |+| Maximum model context | 131072 |+| Main model GPU memory utilization | 0.9 |+| Prefix caching / chunked prefill | Enabled |+| Streaming input format | `no_time` |+| Visual window | 30 frames; retain the most recent 10 when the window rolls |+| Frame interval / batch | 1 second / 1 frame |+| Summary model | Disabled |+| Image processor pixel limit | 786432, unchanged |++The browser requests a camera stream around 1280×720. It proportionally shrinks uploaded frames only when their short edge exceeds 480 pixels; smaller frames are not enlarged. For example, 1280×720 becomes about 853×480. The adapter also enforces downscale-only behavior. Model-internal image preprocessing is left to the checkpoint's processor.++Inference admits at most one in-flight camera request; frames arriving while it is busy are skipped. Consequently, one frame per second is a target, not a guaranteed throughput. User and assistant messages retain their alternating structure. Older visual frames leave the window while sparse question/answer history remains; no separate summary-memory model runs.++The streaming system prompt is in `webinfer/adapter_common.py`. It requests `</silence>` when no answer is warranted and `</response>` followed by a reply when the evidence is sufficient. It retains the ALIVE identity section. `webinfer/adapter_identity.py` provides the same deterministic identity responses for explicit identity questions. Normal model reply text is displayed after action-token removal and is passed to TTS; the displayed answer is not transcribed from synthesized speech.++The loader creates a runtime-only tokenizer mirror if `extra_special_tokens` requires a format conversion. It never edits the original checkpoint.++## Speech++ASR uses streaming recognition with CPU voice-activity detection, automatic/Chinese/English language selection, a 30-second utterance cap, and approximately 1.5 seconds of silence for endpoint detection. Its GPU memory utilization is 0.2. TTS uses two streaming stages, each with GPU memory utilization 0.2, on the same voice GPU. See `voice/tts/deploy.yaml` for the unchanged synthesis settings.++Default voice: `serena`. Available voices: `serena`, `vivian`, `uncle_fu`, `ryan`, `aiden`, `ono_anna`, `sohee`, `eric`, `dylan`. The browser's sound toggle controls model-audio playback. Microphone audio is handled for live recognition, not stored as a demo recording.++## Session data and validation++This distribution excludes screen recording, downloadable demo recordings, and evaluation-session frame/question logging. The adapter uses temporary image files for its active context under `.runtime/frames`; these are inference working files, not a benchmark export. Runtime caches, logs, certificates, checkpoints, and local configuration are ignored by Git.++Run the CPU-only integration checks with the main environment:++```bash+.venvs/main/bin/python -m unittest discover -s tests -v+```++These checks exercise request formatting, image resizing, window rollover, session isolation/reset, and voice gateway routing with synthetic inputs. They do not substitute for a full GPU warmup and real microphone/camera test on a new machine.++Upstream copyright/license headers are retained; see the repository-level `THIRD_PARTY_NOTICES.md`.diff --git a/Web_Inference/config.example.json b/Web_Inference/config.example.jsonnew file mode 100644index 0000000..dfe0690--- /dev/null+++ b/Web_Inference/config.example.json@@ -0,0 +1,10 @@+{+ "model_path": "models/ALIVE",+ "model_url": "",+ "asr_model_path": "models/Qwen3-ASR-1.7B",+ "tts_model_path": "models/Qwen3-TTS-12Hz-1.7B-CustomVoice",+ "main_gpu": "0",+ "voice_gpu": "1",+ "port": 8090,+ "startup_timeout": 2400+}diff --git a/Web_Inference/requirements/asr.txt b/Web_Inference/requirements/asr.txtnew file mode 100644index 0000000..d6f9c56--- /dev/null+++ b/Web_Inference/requirements/asr.txt@@ -0,0 +1,5 @@+qwen-asr[vllm]==0.0.6+transformers==4.57.6+faster-whisper==1.2.1+onnxruntime==1.32.0+aiohttp==3.13.2diff --git a/Web_Inference/requirements/main.txt b/Web_Inference/requirements/main.txtnew file mode 100644index 0000000..c9622f1--- /dev/null+++ b/Web_Inference/requirements/main.txt@@ -0,0 +1,11 @@+vllm==0.26.0+transformers==5.19.0+aiohttp==3.14.5+openai==3.37.0+aiortc==1.16.0+av==19.0.2+Pillow>=10.4.0+opencv-python-headless>=4.10.0+numpy>=1.26.4+httpx>=0.27.2+psutil>=5.9.8diff --git a/Web_Inference/requirements/tts.txt b/Web_Inference/requirements/tts.txtnew file mode 100644index 0000000..33ba837--- /dev/null+++ b/Web_Inference/requirements/tts.txt@@ -0,0 +1,4 @@+vllm==0.32.0+vllm-omni==0.32.0+transformers==5.19.0+aiohttp==3.14.5diff --git a/Web_Inference/scripts/download_models.py b/Web_Inference/scripts/download_models.pynew file mode 100644index 0000000..f24d3b2--- /dev/null+++ b/Web_Inference/scripts/download_models.py@@ -0,0 +1,25 @@+"""Download public voice checkpoints. HF_ENDPOINT can select a mirror."""+import argparse+import json+from pathlib import Path+from huggingface_hub import snapshot_download++ROOT = Path(__file__).resolve().parents[1]+MODELS = {+ 'asr_model_path': 'Qwen/Qwen3-ASR-1.7B',+ 'tts_model_path': 'Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice',+}++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--config', default='config.json')+ args = parser.parse_args()+ path = ROOT / args.config+ if not path.exists():+ path = ROOT / 'config.example.json'+ config = json.loads(path.read_text())+ for key, repo in MODELS.items():+ snapshot_download(repo_id=repo, local_dir=str(ROOT / config[key]))++if __name__ == '__main__':+ main()diff --git a/Web_Inference/scripts/setup.py b/Web_Inference/scripts/setup.pynew file mode 100644index 0000000..b3c450d--- /dev/null+++ b/Web_Inference/scripts/setup.py@@ -0,0 +1,26 @@+"""Create isolated dependency environments, then download the voice checkpoints."""+import argparse+import os+from pathlib import Path+import subprocess+import sys++ROOT = Path(__file__).resolve().parents[1]++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--skip-download', action='store_true')+ args = parser.parse_args()+ if sys.version_info[:2] != (3, 12):+ parser.error('Use Python 3.12 to create the validated environment layout.')+ for name in ('main', 'asr', 'tts'):+ target = ROOT / '.venvs' / name+ subprocess.run([sys.executable, '-m', 'venv', str(target)], check=True)+ python = str(target / 'bin/python')+ subprocess.run([python, '-m', 'pip', 'install', '--upgrade', 'pip'], check=True)+ subprocess.run([python, '-m', 'pip', 'install', '-r', str(ROOT / 'requirements' / (name + '.txt'))], check=True)+ if not args.skip_download:+ subprocess.run([str(ROOT / '.venvs/main/bin/python'), str(ROOT / 'scripts/download_models.py')], check=True)++if __name__ == '__main__':+ main()diff --git a/Web_Inference/start.py b/Web_Inference/start.pynew file mode 100644index 0000000..f4c88ff--- /dev/null+++ b/Web_Inference/start.py@@ -0,0 +1,175 @@+"""Run one ALIVE instance on two GPUs. All paths resolve from this directory."""+import argparse+import json+import os+from pathlib import Path+import signal+import socket+import ssl+import subprocess+import sys+import time+import urllib.request++ROOT = Path(__file__).resolve().parent+RUNTIME = ROOT / '.runtime'+PORTS = {'main': 7060, 'adapter': 8070, 'web': 8091, 'asr': 19411, 'tts_engine': 19412, 'tts': 19413}+PROCESSES = []+LOGS = []++def environment(name, gpu=None):+ env = dict(os.environ)+ for key in ('PYTHONPATH', 'PYTHONHOME', 'SYSTEM_PROMPT', 'EVAL_RECORD_DIR'):+ env.pop(key, None)+ env.update(PYTHONUNBUFFERED='1', PYTHONDONTWRITEBYTECODE='1',+ NO_PROXY='127.0.0.1,localhost,::1', no_proxy='127.0.0.1,localhost,::1',+ OMP_NUM_THREADS='2', OPENBLAS_NUM_THREADS='1', CAMERA_TRANSPORT='websocket',+ LIVE_SAVE_OUTPUTS='false', LIVE_SAVE_DEBUG_INPUTS='false', SAVE_MODEL_INPUTS='false',+ SUMMARIZER_DEBUG='false', VLLM_WORKER_MULTIPROC_METHOD='spawn')+ env['VLLM_PLUGINS'] = 'vllm_omni_register_models' if name == 'tts' else ''+ for key, folder in [('VLLM_CACHE_ROOT', 'vllm'), ('TRITON_CACHE_DIR', 'triton'), ('TORCHINDUCTOR_CACHE_DIR', 'inductor')]:+ env[key] = str(RUNTIME / 'cache' / name / folder)+ if gpu is not None:+ env['CUDA_VISIBLE_DEVICES'] = str(gpu)+ return env++def interpreter(name):+ return os.environ.get('ALIVE_' + name.upper() + '_PYTHON', str(ROOT / '.venvs' / name / 'bin/python'))++def spawn(name, command, env):+ log = (RUNTIME / 'logs' / (name + '.log')).open('w')+ LOGS.append(log)+ process = subprocess.Popen(command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)+ PROCESSES.append((name, process))+ print('Starting ' + name, flush=True)+ return process++def wait_http(name, url, timeout):+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),+ urllib.request.HTTPSHandler(context=ssl._create_unverified_context()))+ end = time.monotonic() + timeout+ while time.monotonic() < end:+ for label, process in PROCESSES:+ if process.poll() is not None:+ raise RuntimeError(label + ' exited; check .runtime/logs/' + label + '.log')+ try:+ with opener.open(url, timeout=3) as response:+ if response.status == 200:+ print('Ready: ' + name, flush=True)+ return+ except Exception:+ pass+ time.sleep(2)+ raise TimeoutError(name + ' did not become ready')++def cleanup():+ for _, process in reversed(PROCESSES):+ try:+ os.killpg(process.pid, signal.SIGTERM)+ except ProcessLookupError:+ pass+ end = time.monotonic() + 20+ for _, process in PROCESSES:+ try:+ process.wait(timeout=max(0.1, end - time.monotonic()))+ except subprocess.TimeoutExpired:+ try:+ os.killpg(process.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ process.wait()+ for log in LOGS:+ log.close()++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--config', default='config.json')+ parser.add_argument('--check', action='store_true', help='Validate files and configuration without starting services')+ args = parser.parse_args()+ config = json.loads((ROOT / args.config).read_text())+ if str(config['main_gpu']) == str(config['voice_gpu']):+ parser.error('main_gpu and voice_gpu must select different devices')+ models = {k: (ROOT / config[k]).resolve() for k in ('model_path', 'asr_model_path', 'tts_model_path')}+ for key, path in models.items():+ if not (path / 'config.json').is_file():+ parser.error('Missing checkpoint config for ' + key + '; download it or edit config.json')+ for name in ('main', 'asr', 'tts'):+ if not Path(interpreter(name)).is_file():+ parser.error('Missing ' + name + ' environment; run scripts/setup.py')+ if args.check:+ print('Configuration and checkpoint directories are valid.')+ return+ # Fail before starting any worker if another instance owns a required port.+ for port in list(PORTS.values()) + [int(config['port'])]:+ with socket.socket() as sock:+ sock.bind(('127.0.0.1', port))+ (RUNTIME / 'logs').mkdir(parents=True, exist_ok=True)+ tls = RUNTIME / 'tls'+ tls.mkdir(exist_ok=True)+ if not (tls / 'cert.pem').exists() or not (tls / 'key.pem').exists():+ subprocess.run(['openssl', 'req', '-x509', '-newkey', 'rsa:3072', '-nodes', '-days', '365',+ '-out', str(tls / 'cert.pem'), '-keyout', str(tls / 'key.pem'), '-subj', '/CN=localhost',+ '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1'], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ (tls / 'key.pem').chmod(0o600)+ py = interpreter('main')+ main_env = environment('main', config['main_gpu'])+ normalized = subprocess.check_output([py, str(ROOT / 'webinfer/fix_tokenizer_config.py'),+ str(models['model_path']), str(RUNTIME / 'model_links')], env=main_env, text=True).strip()+ timeout = int(config.get('startup_timeout', 2400))+ signal.signal(signal.SIGTERM, lambda *_: (_ for _ in ()).throw(KeyboardInterrupt()))+ try:+ spawn('model', [py, '-m', 'vllm.entrypoints.openai.api_server', '--model', normalized,+ '--served-model-name', 'ALIVE', '--host', '127.0.0.1', '--port', str(PORTS['main']),+ '--gpu-memory-utilization', '0.9', '--max-model-len', '131072', '--tensor-parallel-size', '1',+ '--enable-prefix-caching', '--enable-chunked-prefill'], main_env)+ tts_env = environment('tts', config['voice_gpu'])+ tts_python = interpreter('tts')+ spawn('tts-engine', [tts_python, '-m', 'vllm.entrypoints.cli.main', 'serve', str(models['tts_model_path']),+ '--served-model-name', 'qwen-tts', '--deploy-config', 'voice/tts/deploy.yaml', '--omni',+ '--host', '127.0.0.1', '--port', str(PORTS['tts_engine'])], tts_env)+ wait_http('tts-engine', 'http://127.0.0.1:19412/health', timeout)+ spawn('tts', [tts_python, 'voice/tts/service.py', '--model', 'qwen-tts',+ '--upstream', 'http://127.0.0.1:19412', '--port', str(PORTS['tts'])], tts_env)+ asr_config = RUNTIME / 'asr'+ asr_config.mkdir(exist_ok=True)+ (asr_config / 'models.json').write_text(json.dumps({'qwen': {'path': str(models['asr_model_path'])}}))+ # Initialize ASR after TTS to avoid concurrent GPU memory profiling.+ spawn('asr', [interpreter('asr'), 'voice/asr/service.py', '--root', str(asr_config),+ '--port', str(PORTS['asr'])], environment('asr', config['voice_gpu']))+ wait_http('main', 'http://127.0.0.1:7060/v1/models', timeout)+ spawn('adapter', [py, 'webinfer/live_adapter.py', '--host', '127.0.0.1', '--port', str(PORTS['adapter']),+ '--adapter-model', 'streaming-infer-adapter', '--main-api-base', 'http://127.0.0.1:7060/v1',+ '--main-model', 'ALIVE', '--disable-summarizer', '--input-format', 'no_time',+ '--chunk', '30', '--retain-frames', '10', '--frame-seconds', '1.0',+ '--resize-short-edge', '480', '--max-pixels', '786432', '--main-max-tokens', '256',+ '--main-temperature', '0.8', '--main-top-p', '0.9', '--main-top-k', '40',+ '--main-repetition-penalty', '1.1', '--main-presence-penalty', '1.5',+ '--frame-save-dir', str(RUNTIME / 'frames'), '--allowed-local-image-roots', str(RUNTIME / 'frames'),+ '--save-root', str(RUNTIME / 'state'), '--no-live-save', '--no-debug-inputs',+ '--no-save-model-inputs', '--no-summarizer-debug'], main_env)+ wait_http('adapter', 'http://127.0.0.1:8070/health', timeout)+ web_env = environment('web')+ web_env['PYTHONPATH'] = str(ROOT / 'webui/src')+ spawn('web', [py, '-m', 'alive_webui.server', '--host', '127.0.0.1', '--port', str(PORTS['web']),+ '--model', 'streaming-infer-adapter', '--api-base', 'http://127.0.0.1:8070/v1',+ '--ssl-cert', str(tls / 'cert.pem'), '--ssl-key', str(tls / 'key.pem')], web_env)+ for name, url in [('web', 'https://127.0.0.1:8091/'), ('asr', 'http://127.0.0.1:19411/health'), ('tts', 'http://127.0.0.1:19413/health')]:+ wait_http(name, url, timeout)+ spawn('gateway', [py, 'voice/gateway.py', '--web', 'https://127.0.0.1:8091',+ '--asr', 'http://127.0.0.1:19411', '--tts', 'http://127.0.0.1:19413',+ '--host', '127.0.0.1', '--port', str(config['port']), '--cert', str(tls / 'cert.pem'), '--key', str(tls / 'key.pem')], web_env)+ url = 'https://localhost:' + str(config['port'])+ wait_http('ALIVE', url + '/api/use/status', timeout)+ print('\nOpen ' + url + ' in a browser on this machine. Press Ctrl+C to stop all services.', flush=True)+ while True:+ for label, process in PROCESSES:+ if process.poll() is not None:+ raise RuntimeError(label + ' exited; inspect .runtime/logs')+ time.sleep(1)+ except KeyboardInterrupt:+ print('\nStopping ALIVE.', flush=True)+ finally:+ cleanup()++if __name__ == '__main__':+ main()diff --git a/Web_Inference/tests/test_integration.py b/Web_Inference/tests/test_integration.pynew file mode 100644index 0000000..8cac249--- /dev/null+++ b/Web_Inference/tests/test_integration.py@@ -0,0 +1,136 @@+"""CPU integration checks using synthetic frames and a mock model endpoint."""+import asyncio+import base64+import importlib.util+import io+from pathlib import Path+import sys+import tempfile+import unittest++from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer+from PIL import Image++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / 'webinfer'))+from adapter_config import AdapterConfig+from adapter_request import _resize_image_if_needed+from live_adapter import create_app++spec = importlib.util.spec_from_file_location('gateway', ROOT / 'voice/gateway.py')+gateway = importlib.util.module_from_spec(spec)+spec.loader.exec_module(gateway)++class AdapterTests(unittest.IsolatedAsyncioTestCase):+ async def asyncSetUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.requests = []+ async def completion(request):+ payload = await request.json()+ self.requests.append(payload)+ return web.json_response({'id':'test', 'object':'chat.completion', 'created':0, 'model':'ALIVE',+ 'choices':[{'index':0, 'message':{'role':'assistant','content':'</response> A green object.'}, 'finish_reason':'stop'}],+ 'usage':{'prompt_tokens':10,'completion_tokens':5,'total_tokens':15}})+ model = web.Application()+ model.router.add_post('/v1/chat/completions', completion)+ self.model = TestServer(model)+ await self.model.start_server()+ config = AdapterConfig(main_api_base=str(self.model.make_url('/v1')), main_model='ALIVE',+ enable_summarizer=False, per_session_dirs=False, frame_save_dir=self.tmp.name,+ chunk=30, retain_frames=10, input_format='no_time')+ self.client = TestClient(TestServer(create_app(config)))+ await self.client.start_server()+ self.adapter = self.client.server.app['adapter']+ image = io.BytesIO()+ Image.new('RGB', (320, 240), 'green').save(image, format='JPEG')+ self.image = 'data:image/jpeg;base64,' + base64.b64encode(image.getvalue()).decode()++ async def asyncTearDown(self):+ if self.adapter._cleanup_task:+ self.adapter._cleanup_task.cancel()+ await asyncio.gather(self.adapter._cleanup_task, return_exceptions=True)+ await self.adapter.main_client.close()+ await self.client.close()+ await self.model.close()+ self.tmp.cleanup()++ async def frame(self, session, question=''):+ content = [{'type':'image_url','image_url':{'url':self.image}}]+ if question:+ content.append({'type':'text','text':question})+ response = await self.client.post('/v1/chat/completions', headers={'x-streaming-session':session},+ json={'model':'streaming-infer-adapter','messages':[{'role':'user','content':content}]})+ payload = await response.json()+ self.assertEqual(response.status, 200, payload)+ return payload++ async def test_window_history_and_generation(self):+ for i in range(32):+ await self.frame('session-one', 'What is in view?' if i == 0 else '')+ payload = self.requests[-1]+ self.assertEqual(payload['temperature'], 0.8)+ self.assertEqual(payload['top_p'], 0.9)+ self.assertEqual(payload['top_k'], 40)+ self.assertEqual(payload['repetition_penalty'], 1.1)+ self.assertEqual(payload['presence_penalty'], 1.5)+ self.assertEqual(payload['max_tokens'], 256)+ roles = [m['role'] for m in payload['messages']]+ self.assertEqual(roles[0], 'system')+ self.assertTrue(all(a != b for a,b in zip(roles[1:], roles[2:])))+ self.assertIn('What is in view?', str(payload['messages']))+ state = self.adapter.sessions['session-one']+ self.assertLess(len(state.current_chunk['image_paths']), 30)+ self.assertGreaterEqual(len(state.current_chunk['image_paths']), 10)+ self.assertEqual(state.turn_count, 32)+ self.assertIsNone(self.adapter.summarizer)+ await self.frame('session-two', 'Describe the color.')+ self.assertNotIn('What is in view?', str(self.requests[-1]['messages']))+ response = await self.client.post('/v1/streaming/reset', headers={'x-streaming-session':'session-one'}, json={})+ self.assertTrue((await response.json())['removed'])+ self.assertNotIn('session-one', self.adapter.sessions)+ self.assertIn('session-two', self.adapter.sessions)++ def test_downscale_only(self):+ for size, expected in [((320,240),(320,240)),((1280,720),(853,480)),((720,1280),(480,853))]:+ image = Image.new('RGB',size)+ result = _resize_image_if_needed(image, max_pixels=786432, resize_short_edge=480)+ self.assertEqual((result or image).size, expected)++class GatewayTests(unittest.IsolatedAsyncioTestCase):+ async def test_lock_cleanup_and_voice_routing(self):+ cleaned=[]+ async def health(request):+ return web.json_response({'ok':True,'engine':'test'})+ async def cleanup(request):+ cleaned.append((await request.json())['session_id'])+ return web.json_response({'ok':True})+ async def ws(request):+ stream=web.WebSocketResponse()+ await stream.prepare(request)+ await stream.send_json({'type':'start'})+ async for msg in stream:+ if isinstance(msg.data,str):await stream.send_str(msg.data)+ return stream+ upstream=web.Application()+ upstream.router.add_get('/health',health)+ upstream.router.add_post('/api/session/cleanup',cleanup)+ upstream.router.add_get('/ws/asr',ws)+ upstream.router.add_get('/api/tts',ws)+ async with TestServer(upstream) as server:+ url=str(server.make_url('')).rstrip('/')+ async with TestClient(TestServer(gateway.create_app(url,url,url))) as client:+ a='owner-session';b='waiting-session'+ self.assertEqual((await client.post('/api/use/acquire',json={'session_id':a})).status,200)+ self.assertEqual((await client.post('/api/use/acquire',json={'session_id':b})).status,409)+ for path in ('/ws/asr','/api/tts'):+ async with client.ws_connect(path+'?session_id='+a) as sock:+ self.assertEqual((await sock.receive_json())['type'],'start')+ status=await (await client.get('/api/voice/status')).json()+ self.assertTrue(status['asr']['available'] and status['tts']['available'])+ self.assertTrue((await (await client.post('/api/use/release',json={'session_id':a})).json())['released'])+ self.assertEqual(cleaned,[a])+ self.assertEqual((await client.post('/api/use/acquire',json={'session_id':b})).status,200)++if __name__ == '__main__':+ unittest.main()diff --git a/Web_Inference/voice/asr/service.py b/Web_Inference/voice/asr/service.pynew file mode 100644index 0000000..121d28a--- /dev/null+++ b/Web_Inference/voice/asr/service.py@@ -0,0 +1,170 @@+"""Bilingual streaming ASR, bound to loopback.++Each connection owns its streaming state. Model calls are serialized, not+microphone sessions; silent listeners do not occupy the model. PCM/text stay+in memory. CPU Silero VAD gates speech before any ASR generation.+"""+import argparse+import asyncio+import json+import logging+from pathlib import Path+import time++from aiohttp import web, WSMsgType+import numpy as np++from speech_gate import SileroVad, SpeechGate++RATE = 16000+MAX_SECONDS = 30+MAX_CLIENTS = 2+SILENCE_SECONDS = 1.5+LOG = logging.getLogger('alive-asr')+++def create_app(root, model=None):+ metadata = json.loads((root / 'models.json').read_text())['qwen']+ languages = {'auto': None, 'zh': 'Chinese', 'en': 'English'}+ if model is None:+ from qwen_asr import Qwen3ASRModel+ model = Qwen3ASRModel.LLM(model=metadata['path'], dtype='bfloat16',+ gpu_memory_utilization=0.2, max_model_len=4096,+ max_num_seqs=1, enforce_eager=True, max_new_tokens=256,+ max_inference_batch_size=1, disable_log_stats=True)++ app = web.Application()+ app['active'] = 0+ app['lock'] = asyncio.Lock()+ vad = SileroVad()++ async def call(function, *args, **kwargs):+ async with app['lock']:+ task = asyncio.create_task(asyncio.to_thread(function, *args, **kwargs))+ try:+ return await asyncio.shield(task)+ except asyncio.CancelledError:+ await task # Never release the lock while a GPU call still runs.+ raise++ async def health(request):+ return web.json_response({'ok': True, 'engine': 'Qwen3-ASR-1.7B',+ 'revision': metadata.get('revision'), 'languages': ['auto', 'zh', 'en'], 'auto_language_detection': True,+ 'active': app['active'], 'max_clients': MAX_CLIENTS,+ 'streaming_partials': True, 'chunk_sec': 1.0,+ 'endpoint_detection': True, 'endpoint_silence_sec': SILENCE_SECONDS,+ 'speech_gate': 'silero-vad', 'speech_gate_start_ms': 192,+ 'max_recording_sec': MAX_SECONDS, 'max_new_tokens': 256})++ async def websocket(request):+ lang = request.query.get('lang', 'auto')+ if lang not in languages:+ raise web.HTTPBadRequest(text='lang must be auto, zh or en')+ ws = web.WebSocketResponse(heartbeat=20, max_msg_size=65536)+ # Reserve capacity before the first await to prevent admission races.+ if app['active'] >= MAX_CLIENTS:+ await ws.prepare(request)+ await ws.send_json({'type': 'error', 'message': 'Speech recognition is busy. Please retry.'})+ await ws.close()+ return ws+ app['active'] += 1+ endpoint = None+ total = 0+ try:+ await ws.prepare(request)+ await ws.send_json({'type': 'status', 'message': 'connected', 'sample_rate': RATE,+ 'max_recording_sec': MAX_SECONDS, 'engine': 'Qwen3-ASR-1.7B',+ 'speech_detection': 'silero-vad'})+ state = None+ continuous = request.query.get('continuous') == '1'+ endpoint = SpeechGate(vad.new_stream(), continuous=continuous)+ last = ''+ deadline = time.monotonic() + MAX_SECONDS + 20++ async def final():+ nonlocal state+ started = time.perf_counter()+ tail = await asyncio.to_thread(endpoint.finish)+ if tail.size:+ if state is None:+ await ws.send_json({'type': 'speech_activity', 'active': True})+ state = await call(model.init_streaming_state, language=languages[lang], chunk_size_sec=1.0)+ await call(model.streaming_transcribe, tail, state)+ text = ''+ if state is not None and endpoint.heard_voice:+ await call(model.finish_streaming_transcribe, state)+ text = state.text.strip()+ await ws.send_json({'type': 'result', 'event': 'IS_FINAL', 'final': True,+ 'text': text, 'language': getattr(state, 'language', ''),+ 'speech_gate': endpoint.metrics(),+ 'flush_ms': (time.perf_counter() - started) * 1000})++ while not ws.closed:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise ValueError('Recording timed out. Please retry.')+ msg = await ws.receive(timeout=min(15, remaining))+ if msg.type == WSMsgType.BINARY:+ if len(msg.data) % 2:+ raise ValueError('Invalid PCM audio format.')+ if not msg.data:+ continue+ pcm = np.frombuffer(msg.data, dtype='<i2').astype(np.float32) / 32768.0+ total += len(pcm)+ if total > MAX_SECONDS * RATE:+ raise ValueError('A single utterance can be at most 30 seconds.')+ gated = await asyncio.to_thread(endpoint.feed, pcm)+ if gated.size == 0:+ if endpoint.ended and not continuous:+ await final()+ break+ continue+ if state is None:+ await ws.send_json({'type': 'speech_activity', 'active': True})+ state = await call(model.init_streaming_state, language=languages[lang], chunk_size_sec=1.0)+ await call(model.streaming_transcribe, gated, state)+ if state.text != last:+ await ws.send_json({'type': 'result', 'event': 'IS_PARTIAL', 'final': False, 'text': state.text, 'language': state.language})+ last = state.text+ if endpoint.ended and not continuous:+ await final()+ break+ elif msg.type == WSMsgType.TEXT:+ command = json.loads(msg.data)+ if not isinstance(command, dict):+ raise ValueError('Invalid control message.')+ if command.get('type') in ('end', 'segment_end'):+ await final()+ break+ if command.get('type') == 'ping':+ await ws.send_json({'type': 'pong'})+ else:+ break+ except ConnectionResetError:+ pass # Client ended the utterance while a model call was in flight.+ except (ValueError, asyncio.TimeoutError) as exc:+ if not ws.closed:+ await ws.send_json({'type': 'error', 'message': str(exc) or 'Speech connection timed out.'})+ except Exception:+ LOG.exception('ASR request failed')+ if ws.prepared and not ws.closed:+ await ws.send_json({'type': 'error', 'message': 'Speech recognition is unavailable. Please retry.'})+ finally:+ if endpoint is not None:+ LOG.info('speech_gate %s', json.dumps(dict(endpoint.metrics(), audio_seconds=round(total / RATE, 3))))+ app['active'] -= 1+ await ws.close()+ return ws++ app.router.add_get('/health', health)+ app.router.add_get('/ws/asr', websocket)+ return app+++if __name__ == '__main__':+ parser = argparse.ArgumentParser()+ parser.add_argument('--root', type=Path, required=True)+ parser.add_argument('--port', type=int, default=18108)+ args = parser.parse_args()+ logging.basicConfig(level=logging.INFO)+ web.run_app(create_app(args.root), host='127.0.0.1', port=args.port, access_log=None)diff --git a/Web_Inference/voice/asr/speech_gate.py b/Web_Inference/voice/asr/speech_gate.pynew file mode 100644index 0000000..9920897--- /dev/null+++ b/Web_Inference/voice/asr/speech_gate.py@@ -0,0 +1,124 @@+"""CPU Silero VAD before ASR; recurrent state belongs to one utterance.++No transcript, conversation history, or user audio is persisted here.+"""+from collections import deque+import importlib.util+from pathlib import Path++import numpy as np++RATE = 16000+FRAME = 512+START_THRESHOLD = 0.60+CONTINUE_THRESHOLD = 0.35+MIN_START_FRAMES = 6 # 192 ms of consecutive likely speech, not cumulative noise.+PREROLL_FRAMES = 16 # 512 ms includes the confirmation interval.+END_FRAMES = 47 # 1504 ms of non-speech, independent of background volume.+TAIL_FRAMES = 6 # At most 192 ms of non-speech is passed to ASR at the end.+++class SileroVad:+ """Share the immutable ONNX session, never the recurrent h/c state."""+ def __init__(self, path=None):+ import onnxruntime as ort+ if path is None:+ spec = importlib.util.find_spec('faster_whisper')+ if spec is None:+ raise RuntimeError('The existing faster-whisper Silero VAD asset is required')+ path = Path(spec.origin).parent / 'assets/silero_vad_v6.onnx'+ self.path = Path(path)+ opts = ort.SessionOptions()+ opts.inter_op_num_threads = opts.intra_op_num_threads = 1+ opts.enable_cpu_mem_arena = False+ self.session = ort.InferenceSession(str(self.path), sess_options=opts,+ providers=['CPUExecutionProvider'])++ def new_stream(self):+ return VadStream(self.session)+++class VadStream:+ def __init__(self, session):+ self.session = session+ self.h = np.zeros((1, 1, 128), dtype=np.float32)+ self.c = np.zeros((1, 1, 128), dtype=np.float32)+ self.context = np.zeros(64, dtype=np.float32)++ def probability(self, frame):+ x = np.concatenate((self.context, frame)).reshape(1, -1)+ result, self.h, self.c = self.session.run(None, {'input': x, 'h': self.h, 'c': self.c})+ self.context = frame[-64:].copy()+ return float(np.asarray(result).reshape(-1)[0])+++class SpeechGate:+ def __init__(self, scorer, continuous=False):+ self.scorer = scorer+ self.continuous = continuous+ self.buffer = np.empty(0, dtype=np.float32)+ self.preroll = deque(maxlen=PREROLL_FRAMES)+ self.tail = deque()+ self.onset_frames = self.silent_frames = 0+ self.heard_voice = False+ self.ended = False+ self.frames = self.speech_frames = 0+ self.max_probability = 0.0++ def feed(self, pcm):+ if self.ended:+ return np.empty(0, dtype=np.float32)+ self.buffer = np.concatenate((self.buffer, pcm))+ output = []+ while len(self.buffer) >= FRAME and not self.ended:+ frame, self.buffer = self.buffer[:FRAME], self.buffer[FRAME:]+ output.extend(self._frame(frame))+ return np.concatenate(output) if output else np.empty(0, dtype=np.float32)++ def _frame(self, frame, valid=None):+ valid = FRAME if valid is None else valid+ probability = self.scorer.probability(frame)+ self.frames += 1+ self.max_probability = max(probability, self.max_probability)+ if probability >= START_THRESHOLD:+ self.speech_frames += 1+ actual = frame[:valid].copy()+ if not self.heard_voice:+ self.preroll.append(actual)+ self.onset_frames = self.onset_frames + 1 if probability >= START_THRESHOLD else 0+ if self.onset_frames < MIN_START_FRAMES:+ return []+ self.heard_voice = True+ output = list(self.preroll)+ self.preroll.clear()+ return output+ if probability >= CONTINUE_THRESHOLD:+ self.silent_frames = 0+ output = list(self.tail) + [actual]+ self.tail.clear()+ return output+ self.silent_frames += 1+ self.tail.append(actual)+ if self.continuous and len(self.tail) > END_FRAMES:+ # Bound long press-to-talk pauses; keep recent pre-roll for resumption.+ self.tail.popleft()+ if not self.continuous and self.silent_frames >= END_FRAMES:+ self.ended = True+ return []++ def finish(self):+ output = []+ if len(self.buffer) and not self.ended:+ size = len(self.buffer)+ output.extend(self._frame(np.pad(self.buffer, (0, FRAME - size)), valid=size))+ self.buffer = np.empty(0, dtype=np.float32)+ if self.heard_voice:+ output.extend(list(self.tail)[:TAIL_FRAMES])+ self.tail.clear()+ self.preroll.clear()+ self.ended = True+ return np.concatenate(output) if output else np.empty(0, dtype=np.float32)++ def metrics(self):+ return {'speech_detected': self.heard_voice, 'speech_frames': self.speech_frames,+ 'frames': self.frames, 'max_speech_probability': round(self.max_probability, 4)}diff --git a/Web_Inference/voice/gateway.py b/Web_Inference/voice/gateway.pynew file mode 100644index 0000000..942a036--- /dev/null+++ b/Web_Inference/voice/gateway.py@@ -0,0 +1,223 @@+"""Local same-origin ALIVE gateway for video and speech."""+import argparse+import asyncio+import json+import re+import ssl+import time+from contextlib import suppress++from aiohttp import ClientSession, ClientTimeout, WSMsgType, web++HOP_HEADERS = {'connection', 'keep-alive', 'proxy-authenticate',+ 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade'}+++def create_app(web_base, asr_base, tts_base, lease_seconds=45):+ app = web.Application(client_max_size=16 * 1024 * 1024)+ slot = {'owner': None, 'deadline': 0.0, 'releasing': False}+ admission_lock = asyncio.Lock()+ active_sockets = {}++ def session_id(value):+ value = str(value or '')+ if not re.fullmatch(r'[A-Za-z0-9_-]{8,160}', value):+ raise web.HTTPBadRequest(text='Invalid session identifier')+ return value++ def owns(sid):+ return bool(sid and slot['owner'] == sid and not slot['releasing']+ and time.monotonic() < slot['deadline'])++ def touch(sid):+ if owns(sid):+ slot['deadline'] = time.monotonic() + lease_seconds++ def public_status(sid):+ return {'busy': slot['owner'] is not None, 'mine': owns(sid),+ 'releasing': slot['releasing'], 'lease_seconds': lease_seconds}++ async def release(sid):+ # Hold the mutex until all old streams and inference state are cleaned:+ # a new owner must never overlap with an old owner's in-flight request.+ async with admission_lock:+ if slot['owner'] != sid:+ return False+ slot['releasing'] = True+ sockets = list(active_sockets.get(sid, ()))+ await asyncio.gather(*(ws.close() for ws in sockets), return_exceptions=True)+ try:+ async with app['client'].post(web_base + '/api/session/cleanup',+ json={'session_id': sid, 'reset_adapter': True}, ssl=False,+ timeout=ClientTimeout(total=15)) as response:+ if response.status != 200:+ raise RuntimeError('Session cleanup failed')+ await response.read()+ except Exception:+ # Fail closed; the expiry loop retries cleanup instead of+ # admitting another user while old model work may still run.+ slot['deadline'] = time.monotonic()+ return False+ slot.update(owner=None, deadline=0.0, releasing=False)+ return True++ async def expiry_loop():+ while True:+ await asyncio.sleep(min(5, lease_seconds / 2))+ if slot['owner'] and time.monotonic() >= slot['deadline']:+ await release(slot['owner'])++ async def admission_status(request):+ return web.json_response(public_status(request.query.get('session_id')), headers={'Cache-Control':'no-store'})++ async def admission_acquire(request):+ data = await request.json()+ sid = session_id(data.get('session_id'))+ async with admission_lock:+ if slot['owner'] and slot['owner'] != sid or slot['releasing']:+ return web.json_response({'error':'ALIVE_BUSY', **public_status(sid)}, status=409)+ slot.update(owner=sid, deadline=time.monotonic()+lease_seconds, releasing=False)+ return web.json_response(public_status(sid))++ async def admission_heartbeat(request):+ sid = session_id((await request.json()).get('session_id'))+ if not owns(sid):+ return web.json_response({'error':'ALIVE_NOT_OWNER', **public_status(sid)}, status=409)+ touch(sid)+ return web.json_response(public_status(sid))++ async def admission_release(request):+ sid = session_id((await request.json()).get('session_id'))+ return web.json_response({'released':await release(sid)})++ async def lifetime(app):+ async with ClientSession(timeout=ClientTimeout(total=None, sock_connect=10),+ trust_env=False, auto_decompress=False) as client:+ app['client'] = client+ expiry_task = asyncio.create_task(expiry_loop())+ try:+ yield+ finally:+ expiry_task.cancel()+ await asyncio.gather(expiry_task, return_exceptions=True)++ async def check_health(base):+ try:+ async with app['client'].get(base + '/health', timeout=ClientTimeout(total=4), ssl=False) as response:+ data = await response.json()+ return {'available': response.status == 200 and data.get('ok', False),+ 'engine': data.get('engine'), 'languages': data.get('languages', ['zh', 'en'])}+ except Exception:+ return {'available': False}++ async def voice_status(request):+ asr, tts = await asyncio.gather(check_health(asr_base), check_health(tts_base))+ return web.json_response({'asr': asr, 'tts': tts})++ async def relay(source, target, *, sid=None, path=None, inbound=False):+ async for message in source:+ if inbound:+ if path == '/ws' and not owns(sid):+ # Waiting visitors may view the UI and receive config, but+ # cannot submit work or change global inference settings.+ continue+ if path != '/ws' and not owns(sid):+ break+ touch(sid)+ if message.type == WSMsgType.TEXT:+ await target.send_str(message.data)+ elif message.type == WSMsgType.BINARY:+ await target.send_bytes(message.data)+ elif message.type == WSMsgType.ERROR:+ break++ async def proxy(request):+ sid = request.query.get('session_id', '')+ guarded = request.path in ('/ws/camera', '/ws/asr', '/api/tts', '/offer',+ '/api/rtsp/start', '/api/rtsp/stop', '/api/rtsp/status')+ if guarded and request.method == 'POST':+ try:+ sid = (await request.json()).get('session_id', '')+ except (ValueError, AttributeError):+ raise web.HTTPBadRequest(text='Expected a session identifier')+ if guarded and not owns(sid):+ return web.json_response({'error':'ALIVE_BUSY', **public_status(sid)}, status=409)+ if request.path == '/ws/asr':+ base = asr_base+ elif request.path in ('/api/tts', '/api/tts/config'):+ base = tts_base+ else:+ base = web_base+ url = base + str(request.rel_url)+ if request.headers.get('Upgrade', '').lower() == 'websocket':+ try:+ upstream = await app['client'].ws_connect(url, ssl=False, heartbeat=20,+ max_msg_size=4 * 1024 * 1024)+ except Exception:+ raise web.HTTPServiceUnavailable(text='Service is starting or unavailable. Please retry.')+ browser = web.WebSocketResponse(heartbeat=20, max_msg_size=4 * 1024 * 1024)+ tasks = []+ try:+ await browser.prepare(request)+ if request.path != '/ws':+ active_sockets.setdefault(sid, set()).update((browser, upstream))+ tasks = [asyncio.create_task(relay(browser, upstream, sid=sid,+ path=request.path, inbound=True)),+ asyncio.create_task(relay(upstream, browser))]+ await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)+ except ConnectionResetError:+ pass+ finally:+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ await upstream.close()+ if browser.prepared:+ await browser.close()+ if request.path != '/ws':+ active_sockets.get(sid, set()).difference_update((browser, upstream))+ if request.path == '/ws/camera' and owns(sid):+ # Avoid awaiting cleanup inside the stream being closed.+ asyncio.create_task(release(sid))+ return browser+ headers = {k: v for k, v in request.headers.items()+ if k.lower() not in HOP_HEADERS | {'host', 'content-length'}}+ try:+ async with app['client'].request(request.method, url, headers=headers,+ data=await request.read(), ssl=False,+ allow_redirects=False) as upstream:+ result = web.StreamResponse(status=upstream.status,+ headers={k: v for k, v in upstream.headers.items() if k.lower() not in HOP_HEADERS})+ await result.prepare(request)+ async for packet in upstream.content.iter_chunked(65536):+ await result.write(packet)+ await result.write_eof()+ return result+ except (OSError, asyncio.TimeoutError):+ raise web.HTTPBadGateway(text='ALIVE service is unavailable. Please retry.')++ app.cleanup_ctx.append(lifetime)+ app.router.add_get('/api/voice/status', voice_status)+ app.router.add_get('/api/use/status', admission_status)+ app.router.add_post('/api/use/acquire', admission_acquire)+ app.router.add_post('/api/use/heartbeat', admission_heartbeat)+ app.router.add_post('/api/use/release', admission_release)+ app.router.add_post('/_bridge/release', admission_release)+ app.router.add_route('*', '/{path:.*}', proxy)+ return app+++if __name__ == '__main__':+ parser = argparse.ArgumentParser()+ parser.add_argument('--web', required=True)+ parser.add_argument('--asr', default='http://127.0.0.1:19308')+ parser.add_argument('--tts', default='http://127.0.0.1:19310')+ parser.add_argument('--host', default='127.0.0.1')+ parser.add_argument('--port', type=int, default=8295)+ parser.add_argument('--cert', required=True)+ parser.add_argument('--key', required=True)+ args = parser.parse_args()+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)+ context.load_cert_chain(args.cert, args.key)+ web.run_app(create_app(args.web.rstrip('/'), args.asr.rstrip('/'), args.tts.rstrip('/')),+ host=args.host, port=args.port, ssl_context=context, access_log=None)diff --git a/Web_Inference/voice/tts/deploy.yaml b/Web_Inference/voice/tts/deploy.yamlnew file mode 100644index 0000000..082e0eb--- /dev/null+++ b/Web_Inference/voice/tts/deploy.yaml@@ -0,0 +1,86 @@+model_runner: v2+async_chunk: true++connectors:+ connector_of_shared_memory:+ name: SharedMemoryConnector+ extra:+ talker_first_audio: true+ codec_streaming: true+ connector_get_sleep_s: 0.01+ connector_get_max_wait_first_chunk: 3000+ connector_get_max_wait: 300+ codec_chunk_frames: 25+ codec_left_context_frames: 72+ initial_codec_chunk_frames: 1+ codec_chunk_ramp: [4, 4, 8, 16, 25]+ decode_batch_max_size: 4++stages:+ - stage_id: 0+ max_num_seqs: 1+ gpu_memory_utilization: 0.20+ trust_remote_code: true+ enable_prefix_caching: false+ async_scheduling: true+ max_num_batched_tokens: 512+ max_model_len: 4096+ devices: "0"+ output_connectors:+ to_stage_1: connector_of_shared_memory+ default_sampling_params:+ temperature: 0.9+ top_k: 50+ max_tokens: 4096+ min_tokens: 2+ repetition_penalty: 1.05+ silence_ban_frames: 0+ subtalker_sampling_params:+ do_sample: true+ temperature: 0.9+ top_k: 50+ top_p: 1.0++ - stage_id: 1+ dtype: bfloat16+ max_num_seqs: 1+ gpu_memory_utilization: 0.20+ enforce_eager: false+ trust_remote_code: true+ enable_prefix_caching: false+ async_scheduling: true+ max_num_batched_tokens: 65536+ max_model_len: 65536+ devices: "0"+ input_connectors:+ from_stage_0: connector_of_shared_memory+ default_sampling_params:+ temperature: 0.0+ top_p: 1.0+ top_k: -1+ max_tokens: 65536+ repetition_penalty: 1.0++platforms:+ rocm:+ model_runner: v1+ stages:+ - stage_id: 1+ enforce_eager: true+ npu:+ model_runner: v1+ stages:+ - stage_id: 0+ enforce_eager: false+ compilation_config:+ cudagraph_mode: PIECEWISE+ - stage_id: 1+ compilation_config:+ cudagraph_mode: PIECEWISE+ xpu:+ model_runner: v1+ stages:+ - stage_id: 1+ enforce_eager: true+ musa:+ model_runner: v1diff --git a/Web_Inference/voice/tts/service.py b/Web_Inference/voice/tts/service.pynew file mode 100644index 0000000..e4dd81c--- /dev/null+++ b/Web_Inference/voice/tts/service.py@@ -0,0 +1,195 @@+"""Loopback Qwen TTS adapter matching the current demo's Piper WebSocket API."""+import argparse+import asyncio+import json+import re+import time+from contextlib import suppress+from pathlib import Path++from aiohttp import ClientSession, ClientTimeout, WSMsgType, web++ENGINE = 'Qwen3-TTS-12Hz-1.7B-CustomVoice'+RATE = 24000+VOICES = {'zh': 'serena', 'en': 'serena'}+AVAILABLE_VOICES = ('serena', 'vivian', 'uncle_fu', 'ryan', 'aiden', 'ono_anna', 'sohee', 'eric', 'dylan')+MAX_CHARS = 500+MAX_CLIENTS = 4+++def chunks(text):+ # Preserve all input characters, with short phrase boundaries for cancellation.+ pieces = re.findall(r'.{1,100}?(?:[。!?!?;;\n]|(?<=[.!?])\s|$)|.{1,100}', text, re.S)+ return [piece.strip() for piece in pieces if piece.strip()]+++def validate(data):+ text = data.get('text', '')+ if not isinstance(text, str) or not text.strip():+ raise ValueError('Text must not be empty.')+ if len(text) > MAX_CHARS:+ raise ValueError(f'Maximum {MAX_CHARS} characters per request.')+ lang = data.get('lang', 'auto')+ if lang not in ('zh', 'en', 'auto'):+ raise ValueError('lang must be zh, en or auto.')+ inferred = 'zh' if re.search(r'[\u3400-\u9fff]', text) else 'en'+ voice = data.get('voice', VOICES[inferred if lang == 'auto' else lang])+ if not isinstance(voice, str) or voice not in AVAILABLE_VOICES:+ raise ValueError('Unsupported voice.')+ return text.strip(), voice, {'zh': 'Chinese', 'en': 'English', 'auto': 'Auto'}[lang]+++def create_app(upstream, model, manifest=None):+ app = web.Application(client_max_size=8192)+ app['lock'] = asyncio.Lock()+ app['clients'] = 0+ app['active'] = 0+ app['waiting'] = 0+ app['manifest'] = manifest or {}++ async def engine_health():+ try:+ async with app['http'].get(upstream + '/health', timeout=ClientTimeout(total=3)) as r:+ return r.status == 200+ except (OSError, asyncio.TimeoutError):+ return False+ except Exception:+ return False++ async def health(request):+ ok = await engine_health()+ return web.json_response({'ok': ok, 'engine': ENGINE, 'clients': app['clients'],+ 'active': app['active'], 'waiting': app['waiting'],+ 'max_clients': MAX_CLIENTS, 'sample_rate': RATE,+ 'streaming': True,+ 'revision': app['manifest'].get('revision')}, status=200 if ok else 503)++ async def status(request):+ return web.json_response({'tts': {'available': await engine_health(),+ 'engine': ENGINE, 'languages': ['zh', 'en']},+ 'asr': {'available': False}})++ async def config(request):+ return web.json_response({'available': await engine_health(), 'engine': ENGINE,+ 'languages': ['zh', 'en'], 'sample_rate': RATE,+ 'voices': VOICES, 'available_voices': list(AVAILABLE_VOICES),+ 'default_voice': 'serena', 'max_text_chars': MAX_CHARS})++ async def speak(ws, data):+ reqid = str(data.get('request_id') or data.get('reqid') or 'speech')+ try:+ text, voice, lang = validate(data)+ app['waiting'] += 1+ try:+ await asyncio.wait_for(app['lock'].acquire(), timeout=45)+ finally:+ app['waiting'] -= 1+ app['active'] += 1+ try:+ await ws.send_json({'type': 'start', 'request_id': reqid, 'sample_rate': RATE,+ 'format': 'pcm16', 'channels': 1, 'voice': voice})+ total = 0+ begin = time.perf_counter()+ first_audio_ms = None+ for piece in chunks(text):+ payload = {'model': model, 'input': piece, 'voice': voice, 'language': lang,+ 'stream': True, 'stream_format': 'audio', 'response_format': 'pcm'}+ # Closing this request on stop/disconnect aborts the upstream stream.+ async with app['http'].post(upstream + '/v1/audio/speech', json=payload) as r:+ if r.status != 200:+ raise RuntimeError(f'TTS engine returned HTTP {r.status}')+ carry = b''+ async for packet in r.content.iter_any():+ carry += packet+ aligned = len(carry) // 2 * 2+ if not aligned:+ continue+ if first_audio_ms is None:+ first_audio_ms = (time.perf_counter() - begin) * 1000+ for offset in range(0, aligned, 16384):+ await ws.send_bytes(carry[offset:min(offset + 16384, aligned)])+ total += aligned+ carry = carry[aligned:]+ if carry:+ raise RuntimeError('Incomplete PCM sample from engine')+ if total == 0:+ raise RuntimeError('TTS engine returned no audio')+ await ws.send_json({'type': 'done', 'request_id': reqid, 'audio_bytes': total,+ 'first_audio_ms': first_audio_ms,+ 'elapsed_ms': (time.perf_counter() - begin) * 1000})+ finally:+ app['active'] -= 1+ app['lock'].release()+ except asyncio.CancelledError:+ if not ws.closed:+ with suppress(Exception):+ await ws.send_json({'type': 'stopped', 'request_id': reqid})+ raise+ except Exception as exc:+ if not ws.closed:+ message = str(exc) if isinstance(exc, (ValueError, RuntimeError)) else 'Speech synthesis unavailable.'+ with suppress(Exception):+ await ws.send_json({'type': 'error', 'request_id': reqid, 'error': message})++ async def cancel(task):+ if task:+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)++ async def websocket(request):+ ws = web.WebSocketResponse(heartbeat=20, max_msg_size=8192)+ await ws.prepare(request)+ if app['clients'] >= MAX_CLIENTS:+ await ws.send_json({'type': 'error', 'error': 'TTS busy; please retry.'})+ await ws.close()+ return ws+ app['clients'] += 1+ task = None+ try:+ async for msg in ws:+ if msg.type != WSMsgType.TEXT:+ break+ try:+ data = json.loads(msg.data)+ if not isinstance(data, dict):+ raise ValueError('Expected an object')+ except ValueError:+ await ws.send_json({'type': 'error', 'error': 'Invalid JSON request.'})+ continue+ kind = data.get('type', 'speak')+ if kind in ('speak', 'stop'):+ await cancel(task)+ task = asyncio.create_task(speak(ws, data)) if kind == 'speak' else None+ elif kind == 'ping':+ await ws.send_json({'type': 'pong', 'id': data.get('id')})+ else:+ await ws.send_json({'type': 'error', 'error': 'Unknown command.'})+ finally:+ await cancel(task)+ app['clients'] -= 1+ await ws.close()+ return ws++ async def lifetime(app):+ async with ClientSession(timeout=ClientTimeout(total=180, sock_connect=5, sock_read=90)) as client:+ app['http'] = client+ yield++ app.cleanup_ctx.append(lifetime)+ app.router.add_get('/health', health)+ app.router.add_get('/api/voice/status', status)+ app.router.add_get('/api/tts/config', config)+ app.router.add_get('/api/tts', websocket)+ return app+++if __name__ == '__main__':+ p = argparse.ArgumentParser()+ p.add_argument('--upstream', default='http://127.0.0.1:18109')+ p.add_argument('--model', required=True)+ p.add_argument('--manifest', type=Path)+ p.add_argument('--port', type=int, default=18110)+ args = p.parse_args()+ manifest = json.loads(args.manifest.read_text()) if args.manifest else {}+ web.run_app(create_app(args.upstream.rstrip('/'), args.model, manifest),+ host='127.0.0.1', port=args.port, access_log=None)diff --git a/Web_Inference/webinfer/adapter_common.py b/Web_Inference/webinfer/adapter_common.pynew file mode 100644index 0000000..283794c--- /dev/null+++ b/Web_Inference/webinfer/adapter_common.py@@ -0,0 +1,481 @@+# -*- coding: utf-8 -*-+"""实时推理 adapter 的公共常量与纯函数。++本文件只放与网络/会话无关的工具:+ - 训练格式相关常量:system prompt、</silence> / </response> 动作 token、时间戳正则;+ - 时间戳解析与格式化("<12.0 seconds>" 这类训练格式文本);+ - 模型输出归一化:把 vLLM 原始输出整理成训练时的 assistant 历史格式;+ - 输出目录命名、调试记录压缩(去掉 base64 图片,避免内存随帧数增长);+ - 问答历史归档(窗口滑出时把 query / response 记录到 memory_state)。+"""++from __future__ import annotations++import copy+import logging+import math+import os+import re+from pathlib import Path+from typing import Any, Optional+++LOGGER = logging.getLogger("streaming_infer_adapter")+USER_QUERY_HEADER_EN = "[User Query (IMPORTANT — follow this instruction)]"+USER_QUERY_HEADER_ZH = "[用户问题(重要——请遵循此指令)]"++VIDEO_HISTORY_HEADER_EN = (+ "[Video History]\n"+ "The following are summaries of earlier video segments you can no longer see. "+ "Use them as background context, but always prioritize the current visual frames "+ "and the User Query below when making decisions.\n"+ "IMPORTANT: These summaries are written by an external system in a descriptive style. "+ "Do NOT imitate their writing style in your responses.\n"+)+VIDEO_HISTORY_HEADER_ZH = (+ "[Video History]\n"+ "以下是你已无法看到的早期视频片段的文字摘要。"+ "将其作为背景上下文使用,但在做决策时始终优先参考当前视觉帧及下方的用户问题。\n"+ "重要:这些摘要由外部系统以描述性风格撰写。不要在你的回复中模仿其写作风格。\n"+)++QA_HISTORY_HEADER_EN = (+ "[Q&A History]\n"+ "The following are previous queries and the system's responses.\n\n"+)+QA_HISTORY_HEADER_ZH = (+ "[Q&A History]\n"+ "以下是之前的用户提问及系统的回复。\n\n"+)++QA_QUERY_LABEL_EN = "Query"+QA_QUERY_LABEL_ZH = "提问"+QA_RESPONSE_LABEL_EN = "Response"+QA_RESPONSE_LABEL_ZH = "回复"+++def _get_i18n(language: str = "en") -> dict[str, str]:+ if language == "en":+ return {+ "user_query_header": USER_QUERY_HEADER_EN,+ "video_history_header": VIDEO_HISTORY_HEADER_EN,+ "qa_history_header": QA_HISTORY_HEADER_EN,+ "qa_query_label": QA_QUERY_LABEL_EN,+ "qa_response_label": QA_RESPONSE_LABEL_EN,+ }+ return {+ "user_query_header": USER_QUERY_HEADER_EN,+ "video_history_header": VIDEO_HISTORY_HEADER_ZH,+ "qa_history_header": QA_HISTORY_HEADER_ZH,+ "qa_query_label": QA_QUERY_LABEL_ZH,+ "qa_response_label": QA_RESPONSE_LABEL_ZH,+ }+DEFAULT_SAVE_ROOT = "result"+TIME_RANGE_RE = re.compile(+ r"<(?P<range>\d+(?:\.\d+)?\s*(?:seconds?|s)(?:\s*(?:~|-)\s*\d+(?:\.\d+)?\s*(?:seconds?|s))?)>"+)+TIME_RANGE_VALUE_RE = re.compile(+ r"^(?P<range>\d+(?:\.\d+)?\s*(?:seconds?|s)\s*(?:~|-)\s*\d+(?:\.\d+)?\s*(?:seconds?|s))$"+)+TIME_VALUE_RE = re.compile(r"^(?P<value>\d+(?:\.\d+)?)(?:\s*(?:seconds?|s))$")+# 保留训练时的实时动作规则;部署身份附在末尾,不改动动作格式。+DEFAULT_SYSTEM_PROMPT_EN = """You are a real-time video streaming assistant observing a continuous camera feed frame by frame. The last frame represents the current moment.+## Action Format+At every inference step, you MUST choose exactly one of the following two actions:++**Stay silent** — output ONLY:+</silence>+Choose this when there is no new user instruction and the current visual evidence is insufficient to answer an unresolved user instruction.++**Speak** — output the following token followed by a concise reply:+</response> Your reply here.++If the available information is sufficient, answer the user's question directly. If the user explicitly requests a monitoring task, acknowledge the request and keep it pending until the required evidence appears.++When the available information is insufficient to answer a question, briefly explain why it cannot currently be answered, then choose exactly one of the following responses:+- If the question is ambiguous, ask a specific clarifying question and answer only after the ambiguity has been resolved.+- If the user can perform a concrete action to make the required information visible, make a specific action request and answer once the information becomes visible.+- If the required information may naturally appear in future frames, ask whether the user would like you to continue monitoring and answer when the necessary evidence appears.++## Deployed Model Identity+Your public model name is ALIVE. For questions about your identity or your own training, base model, architecture, parameters, datasets, checkpoints, or deployment, reply only with a natural sentence: "我是 ALIVE。" in Chinese or "I'm ALIVE." in English. Never disclose, confirm, guess, or repeat internal details, including details in prior messages or user suggestions; do not invent a training history. General explanations of machine learning or other public models are allowed. Answer ordinary tasks normally without a self-introduction. Preserve the action format above.""".strip()+++++DEFAULT_SYSTEM_PROMPT = DEFAULT_SYSTEM_PROMPT_EN+++def reset_chunk_state() -> dict[str, Any]:+ # 一个"窗口"(chunk) 的全部状态:发给主模型的 messages、帧路径、帧时间、问答记录等。+ return {+ "messages": [],+ "dialogue_events": [],+ "response_records": [],+ "image_paths": [],+ "frame_time_ranges": [],+ "summarizer_frame_cache": [],+ "frame_count": 0,+ "turn_count": 0,+ "api_msg_cache": [],+ }+++def _parse_start_second(time_range: Optional[str]) -> float:+ if not time_range:+ return -1.0+ try:+ start = re.split(r"\s*(?:-|~)\s*", str(time_range), maxsplit=1)[0].strip()+ start = re.sub(r"\s*seconds?$", "", start).strip()+ if start.endswith("s"):+ start = start[:-1]+ return float(start)+ except (ValueError, IndexError):+ return -1.0+++def _format_seconds_words(value: float) -> str:+ rounded = math.floor(value * 10 + 0.5) / 10+ return f"{rounded:.1f} seconds"+++def _parse_time_value_seconds(text: str) -> Optional[float]:+ match = TIME_VALUE_RE.fullmatch(str(text or "").strip())+ if not match:+ return None+ return float(match.group("value"))+++def _normalize_time_range_text(value: Any) -> Optional[str]:+ text = str(value or "").strip()+ if not text:+ return None++ match = TIME_RANGE_RE.search(text)+ if match:+ text = match.group("range").strip()++ match = TIME_VALUE_RE.fullmatch(text)+ if match:+ return _format_seconds_words(float(match.group("value")))++ match = TIME_RANGE_VALUE_RE.fullmatch(text)+ if match:+ range_text = match.group("range")+ separator = " ~ " if "~" in range_text else "-"+ parts = re.split(r"\s*(?:~|-)\s*", range_text, maxsplit=1)+ if len(parts) == 2:+ start = _parse_time_value_seconds(parts[0])+ end = _parse_time_value_seconds(parts[1])+ if start is not None and end is not None:+ return f"{_format_seconds_words(start)}{separator}{_format_seconds_words(end)}"+ return range_text++ return None+++def _format_time_span(time_ranges: list[str]) -> Optional[str]:+ ranges = [str(tr).strip() for tr in time_ranges if str(tr or "").strip()]+ if not ranges:+ return None+ if len(ranges) == 1:+ return ranges[0]+ return f"{ranges[0]} ~ {ranges[-1]}"+++def _format_batch_time_marker(time_ranges: list[str]) -> Optional[str]:+ ranges = [str(tr).strip() for tr in time_ranges if str(tr or "").strip()]+ return ranges[0] if ranges else None+++def _format_turn_time_range(time_ranges: list[str]) -> str:+ ranges = [str(tr).strip() for tr in time_ranges if str(tr or "").strip()]+ if not ranges:+ return ""+ if all(time_range == ranges[0] for time_range in ranges):+ return ranges[0]+ return " ~ ".join(ranges)+++def _extract_time_range_from_message(message: dict[str, Any]) -> Optional[str]:+ content = message.get("content", "")+ if isinstance(content, list):+ for item in content:+ if isinstance(item, dict) and item.get("type") == "text":+ text = str(item.get("text", "")).strip()+ match = TIME_RANGE_RE.search(text)+ if match:+ return match.group("range")+ elif isinstance(content, str):+ match = TIME_RANGE_RE.search(content)+ if match:+ return match.group("range")+ return None+++def _compute_chunk_frame_range(current_chunk: dict[str, Any]) -> str:+ frame_time_ranges = [+ str(time_range).strip()+ for time_range in current_chunk.get("frame_time_ranges", [])+ if str(time_range or "").strip()+ ]+ if frame_time_ranges:+ return _format_time_span(frame_time_ranges) or "unknown"++ user_messages = [+ message for message in current_chunk.get("messages", [])+ if message.get("role") == "user"+ ]+ if not user_messages:+ return "unknown"++ first_range = _extract_time_range_from_message(user_messages[0])+ last_range = _extract_time_range_from_message(user_messages[-1])+ if first_range and last_range:+ return f"{first_range} ~ {last_range}"+ return first_range or last_range or "unknown"+++def _get_response_frame_indices(messages: list[dict[str, Any]]) -> list[int]:+ indices: list[int] = []+ frame_idx = -1+ for message in messages:+ if message.get("role") == "user":+ content = message.get("content")+ has_image = (+ isinstance(content, list)+ and any(+ isinstance(item, dict) and item.get("type") == "image"+ for item in content+ )+ )+ if has_image:+ frame_idx += 1+ elif message.get("role") == "assistant":+ if "</response>" in str(message.get("content", "")) and frame_idx >= 0:+ indices.append(frame_idx)+ return indices+++TRAILING_CHAT_CONTROL_TOKENS_RE = re.compile(+ r"(?:\s*(?:<\|im_end\|>|<\|endoftext\|>))+\s*\Z"+)+SILENCE_TOKEN = "</silence>"+RESPONSE_TOKEN = "</response>"+# 两个动作 token 在 tokenizer 中的 id,首动作 logprob 判定(first_action_logprob_gate)时用于限制采样。+SILENCE_TOKEN_ID = 151669+RESPONSE_TOKEN_ID = 151670+++def normalize_model_output(text: str) -> str:+ raw = (text or "").replace("\r\n", "\n").replace("\r", "\n").strip()+ # vLLM returns special tokens when skip_special_tokens=False. Assistant+ # content is passed through the checkpoint chat template again on the next+ # frame, so retaining a generated turn terminator here would serialize it+ # twice: ``...<|im_end|><|im_end|>``. Keep the untouched model text in+ # raw_prediction, but store/display normalized assistant content without+ # chat-template-owned trailing terminators.+ raw = TRAILING_CHAT_CONTROL_TOKENS_RE.sub("", raw).rstrip()+ if not raw:+ return "</silence>"++ marker_positions = []+ for marker in ("</response>", "</silence>"):+ idx = raw.find(marker)+ if idx != -1:+ marker_positions.append((idx, marker))++ if marker_positions:+ _, marker = min(marker_positions, key=lambda item: item[0])+ if marker == "</silence>":+ return "</silence>"+ response_text = raw.split(marker, 1)[1].strip()+ if not response_text:+ return "</response>"+ # 保留正文换行和缩进,避免列表、代码或解释被截成第一行。+ return f"</response> {response_text}"++ return f"</response> {raw}"+++def display_model_output(text: str) -> str:+ """仅供展示的输出:保留 silence 后模型继续采样出的正文。"""+ raw = (text or "").replace("\r\n", "\n").replace("\r", "\n").strip()+ return TRAILING_CHAT_CONTROL_TOKENS_RE.sub("", raw).rstrip() or SILENCE_TOKEN+++def action_history_output(text: str, action: str) -> str:+ """把首动作判定转为训练格式的 assistant history,模板负责补唯一的 im_end。"""+ if action == "silence":+ return SILENCE_TOKEN++ normalized = normalize_model_output(text)+ if normalized != SILENCE_TOKEN:+ return normalized+ # 采样首 token 与二选一 logits 不一致时,仍以 logits 选出的 response 动作为准。+ body = display_model_output(text).removeprefix(SILENCE_TOKEN).strip()+ return RESPONSE_TOKEN if not body else f"{RESPONSE_TOKEN} {body}"+++def extract_response_payload(text: str) -> Optional[str]:+ normalized = normalize_model_output(text)+ if not normalized.startswith("</response>"):+ return None+ payload = normalized[len("</response>"):].strip()+ return payload or None+++def sanitize_output_name(name: str, max_len: int = 120) -> str:+ safe_chars = []+ for ch in str(name or ""):+ is_ascii_alnum = ("a" <= ch <= "z") or ("A" <= ch <= "Z") or ("0" <= ch <= "9")+ safe_chars.append(ch if is_ascii_alnum or ch in ("-", "_", ".") else "_")+ safe_name = "".join(safe_chars).strip("._")+ return (safe_name or "live_adapter")[:max_len]+++def derive_model_output_name(model_path: str) -> str:+ normalized = os.path.normpath(str(model_path or "model"))+ model_name = os.path.basename(normalized) or "model"+ parent_name = os.path.basename(os.path.dirname(normalized))+ if model_name.startswith("checkpoint-") and parent_name:+ model_name = f"{parent_name}__{model_name}"+ return sanitize_output_name(model_name)+++def resolve_save_dir(path: Optional[str], root: str = DEFAULT_SAVE_ROOT) -> Optional[str]:+ if path is None:+ return None+ path = str(path).strip()+ if not path:+ return None+ if os.path.isabs(path):+ return os.path.normpath(path)+ return os.path.normpath(os.path.join(root, path))+++def derive_light_out_dir(out_dir: str) -> str:+ normalized_out_dir = os.path.normpath(out_dir)+ parent_dir = os.path.dirname(normalized_out_dir)+ base_name = os.path.basename(normalized_out_dir)+ if base_name.startswith("output_"):+ return os.path.join(parent_dir, f"output_light_{base_name[len('output_'):]}")+ if base_name == "output":+ return os.path.join(parent_dir, "output_light")+ return normalized_out_dir + "_light"+++def build_model_input_record(+ chunk_index: int,+ messages: list[dict[str, Any]],+ frame_count: int,+ model: Optional[str] = None,+ generation_kwargs: Optional[dict[str, Any]] = None,+ inference_skipped: bool = False,+ skip_reason: Optional[str] = None,+ image_paths: Optional[list[str]] = None,+ frame_time_ranges: Optional[list[str]] = None,+ prefix_content: Optional[str] = None,+ prompt: Optional[str] = None,+) -> dict[str, Any]:+ if inference_skipped:+ return {+ "http_payload_skipped": True,+ "inference_skipped": True,+ "skip_reason": skip_reason,+ "would_be_messages": list(messages),+ }++ del chunk_index, frame_count, image_paths, frame_time_ranges, prefix_content, prompt+ record = {+ "model": model,+ "messages": list(messages),+ }+ if generation_kwargs:+ record.update(copy.deepcopy(generation_kwargs))+ return record+++def compact_image_urls_for_record(+ obj: Any,+ image_paths: Optional[list[str]] = None,+) -> Any:+ """Copy a debug/output record without retaining inline image bytes.++ Camera requests carry JPEG frames as large base64 data URLs. Keeping even+ one such request per prediction makes a live session's RSS grow linearly;+ keeping the cumulative main-model input makes it grow quadratically within+ a chunk. Frames have already been persisted by ``_resolve_frame_ref``, so+ records can safely point at those files instead.+ """+ resolved_paths = iter(image_paths or [])++ def _compact(node: Any) -> Any:+ if isinstance(node, list):+ return [_compact(item) for item in node]+ if isinstance(node, dict):+ if node.get("type") == "image_url":+ compacted = {key: _compact(value) for key, value in node.items() if key != "image_url"}+ image_url = node.get("image_url")+ details = dict(image_url) if isinstance(image_url, dict) else {}+ raw_url = details.get("url") if details else image_url+ replacement = next(resolved_paths, None)+ if replacement:+ details["url"] = Path(replacement).resolve().as_uri()+ elif isinstance(raw_url, str) and raw_url.startswith("data:image/"):+ details["url"] = "<inline image omitted>"+ elif raw_url is not None:+ details["url"] = raw_url+ compacted["image_url"] = details+ return compacted+ return {key: _compact(value) for key, value in node.items()}+ if isinstance(node, str) and node.startswith("data:image/"):+ replacement = next(resolved_paths, None)+ return Path(replacement).resolve().as_uri() if replacement else "<inline image omitted>"+ return node++ return _compact(obj)+++def archive_chunk_response_records(+ current_chunk: dict[str, Any],+ memory_state: dict[str, Any],+ current_query_text: Optional[str],+ query_start_time: Optional[str],+ chunk_index: int = 0,+ before_time_sec: float = float("inf"),+) -> None:+ # 把当前问题在本窗口内得到的 response 归档进 memory_state["qa_history"](同一问题同一窗口则合并)。+ if not current_chunk["response_records"] or not current_query_text:+ return++ query_start_sec = _parse_start_second(query_start_time)+ valid_records = [+ (time_range, payload)+ for time_range, payload in current_chunk["response_records"]+ if query_start_sec <= _parse_start_second(time_range) < before_time_sec+ ]+ if not valid_records:+ return++ existing = None+ for entry in memory_state["qa_history"]:+ if (+ entry["query"] == current_query_text+ and entry.get("archived_in_chunk") == chunk_index+ and entry.get("query_time") == query_start_time+ ):+ existing = entry+ break+ if existing:+ existing["responses"].extend(valid_records)+ existing["archived_in_chunk"] = chunk_index+ else:+ memory_state["qa_history"].append(+ {+ "query_time": query_start_time,+ "query": current_query_text,+ "responses": list(valid_records),+ "archived_in_chunk": chunk_index,+ }+ )diff --git a/Web_Inference/webinfer/adapter_config.py b/Web_Inference/webinfer/adapter_config.pynew file mode 100644index 0000000..1e64bd3--- /dev/null+++ b/Web_Inference/webinfer/adapter_config.py@@ -0,0 +1,575 @@+# -*- coding: utf-8 -*-+"""Adapter 配置与命令行解析。++所有参数既可以用命令行传,也可以用同名环境变量覆盖(命令行优先)。+关键约束(parse_args 末尾校验):+ - 训练输入格式(no_time / timed)必须关闭 summarizer、保留 QA history、chunk=30;+ - retain_frames 必须小于 chunk:窗口攒满 30 帧后裁剪到最近 retain_frames 帧,再继续累积。+"""++from __future__ import annotations++import argparse+import json+import os+from dataclasses import dataclass+from datetime import datetime+from typing import Optional++from adapter_common import (+ DEFAULT_SAVE_ROOT,+ DEFAULT_SYSTEM_PROMPT_EN,+ derive_light_out_dir,+ derive_model_output_name,+ resolve_save_dir,+ sanitize_output_name,+)+++@dataclass+class AdapterConfig:+ host: str = "127.0.0.1"+ port: int = 8070+ adapter_model: str = "streaming-infer-adapter"+ main_api_base: str = "http://127.0.0.1:7060/v1"+ main_model: str = "ALIVE"+ main_backends: tuple[dict[str, str], ...] = ()+ api_key: str = "EMPTY"+ allowed_local_image_roots: tuple[str, ...] = ()+ frame_seconds: float = 1.0+ input_format: str = "no_time"+ max_pixels: int = 786432+ resize_short_edge: int = 480+ main_max_tokens: int = 256+ main_temperature: float = 0.8+ main_top_p: float = 0.9+ main_top_k: int = 40+ main_repetition_penalty: float = 1.1+ main_presence_penalty: float = 1.5+ honor_inbound_generation_params: bool = False+ chunk: int = 30+ retain_frames: int = 10+ compress_every_n_chunks: int = 5+ async_summary_lead_frames: int = 10+ use_prompt_as_query: bool = True+ force_silence_before_query: bool = True+ keep_qa_history: bool = True+ normalize_output: bool = True+ first_action_logprob_gate: bool = False+ enable_summarizer: bool = False+ summarizer_model: str = "models/summary"+ summarizer_api_base: str = "http://127.0.0.1:8065/v1"+ longterm_model: str = "models/summary"+ longterm_api_base: str = "http://127.0.0.1:8065/v1"+ summarizer_max_pixels: int = 786432+ summarizer_key_frames: int = 0+ summarizer_phase_seconds: float = 10.0+ mid_term_max_tokens: int = 4000+ mid_term_target_tokens: int = 3000+ long_term_max_tokens: int = 2000+ long_term_target_tokens: int = 1000+ mid_term_temperature: float = 0.8+ mid_term_top_p: float = 0.9+ mid_term_top_k: int = 40+ mid_term_repetition_penalty: float = 1.1+ mid_term_presence_penalty: float = 0.0+ long_term_temperature: float = 1.0+ long_term_top_p: float = 1.0+ long_term_top_k: int = 80+ long_term_repetition_penalty: float = 1.1+ long_term_presence_penalty: float = 0.0+ long_term_memory_window: int = 40+ request_timeout_seconds: float = 300.0+ session_timeout_seconds: float = 3600.0+ max_active_sessions: int = 0+ out_dir: Optional[str] = None+ light_out_dir: Optional[str] = None+ debug_input_dir: Optional[str] = None+ save_root: Optional[str] = None+ output_model_name: str = ""+ per_session_dirs: bool = True+ save_model_inputs: bool = False+ save_debug_inputs: bool = False+ summarizer_debug: bool = False+ frame_save_dir: str = ".runtime/frames"+ language: str = "en"+ system_prompt: str = DEFAULT_SYSTEM_PROMPT_EN+++def _env_bool(name: str, default: bool) -> bool:+ value = os.environ.get(name)+ if value is None:+ return default+ return value.strip().lower() in {"1", "true", "yes", "y", "on"}+++def _env_int(name: str, default: int) -> int:+ value = os.environ.get(name)+ if value is None or value == "":+ return default+ return int(value)+++def _env_float(name: str, default: float) -> float:+ value = os.environ.get(name)+ if value is None or value == "":+ return default+ return float(value)+++def _split_paths(value: str) -> tuple[str, ...]:+ if not value:+ return ()+ normalized = value.replace(",", os.pathsep)+ return tuple(item.strip() for item in normalized.split(os.pathsep) if item.strip())+++def parse_args() -> AdapterConfig:+ parser = argparse.ArgumentParser(description="StreamingHarness live OpenAI adapter")+ parser.add_argument("--host", default=os.environ.get("ADAPTER_HOST", "127.0.0.1"))+ parser.add_argument("--port", type=int, default=_env_int("ADAPTER_PORT", 8070))+ parser.add_argument(+ "--adapter-model",+ default=os.environ.get("ADAPTER_MODEL", "streaming-infer-adapter"),+ )+ parser.add_argument(+ "--main-api-base",+ default=os.environ.get("MAIN_API_BASE", "http://127.0.0.1:7060/v1"),+ )+ parser.add_argument(+ "--main-model",+ default=os.environ.get("MAIN_MODEL", "ALIVE"),+ )+ parser.add_argument(+ "--main-backends",+ default=os.environ.get("MAIN_BACKENDS", ""),+ help='JSON array of backends: [{"name":"...","api_base":"...","model":"..."},...]',+ )+ parser.add_argument("--api-key", default=os.environ.get("MODEL_API_KEY", "EMPTY"))+ parser.add_argument("--frame-seconds", type=float, default=_env_float("FRAME_SECONDS", 1.0))+ parser.add_argument(+ "--input-format",+ default=os.environ.get("INPUT_FORMAT", "no_time"),+ choices=("legacy", "timed", "no_time"),+ )+ parser.add_argument("--max-pixels", type=int, default=_env_int("MAX_PIXELS", 786432))+ parser.add_argument(+ "--resize-short-edge",+ type=int,+ default=_env_int("RESIZE_SHORT_EDGE", 480),+ help="Resize each frame proportionally so its shorter edge has this many pixels before applying max_pixels; 0 disables it.",+ )+ parser.add_argument("--main-max-tokens", type=int, default=_env_int("MAIN_MAX_TOKENS", 256))+ parser.add_argument(+ "--main-temperature",+ type=float,+ default=_env_float("MAIN_TEMPERATURE", 0.8),+ )+ parser.add_argument("--main-top-p", type=float, default=_env_float("MAIN_TOP_P", 0.9))+ parser.add_argument("--main-top-k", type=int, default=_env_int("MAIN_TOP_K", 40))+ parser.add_argument(+ "--main-repetition-penalty",+ type=float,+ default=_env_float("MAIN_REPETITION_PENALTY", 1.1),+ )+ parser.add_argument(+ "--main-presence-penalty",+ type=float,+ default=_env_float("MAIN_PRESENCE_PENALTY", 1.5),+ )+ parser.add_argument(+ "--honor-inbound-generation-params",+ action="store_true",+ default=_env_bool("HONOR_INBOUND_GENERATION_PARAMS", False),+ help="Use max_tokens/temperature/top_p from incoming WebUI requests instead of infer.sh-style defaults.",+ )+ parser.add_argument("--chunk", type=int, default=_env_int("CHUNK", 30))+ parser.add_argument(+ "--retain-frames",+ type=int,+ default=_env_int("RETAIN_FRAMES", 10),+ help="For training input formats without summarizer, when the frame window reaches --chunk, archive old turns and keep only this many recent frames before accumulating again.",+ )+ parser.add_argument(+ "--compress-every-n-chunks",+ type=int,+ default=_env_int("COMPRESS_EVERY_N_CHUNKS", 5),+ )+ parser.add_argument(+ "--async-summary-lead-frames",+ type=int,+ default=_env_int("ASYNC_SUMMARY_LEAD_FRAMES", 10),+ help="Generate async summaries this many turns before the chunk boundary. Name kept for compatibility.",+ )+ parser.add_argument(+ "--no-prompt-as-query",+ action="store_true",+ default=not _env_bool("USE_PROMPT_AS_QUERY", True),+ )+ parser.add_argument(+ "--force-silence-before-query",+ action="store_true",+ default=_env_bool("FORCE_SILENCE_BEFORE_QUERY", True),+ )+ parser.add_argument(+ "--no-force-silence-before-query",+ action="store_false",+ dest="force_silence_before_query",+ help="Disable infer.sh-style forced </silence> before the first query.",+ )+ parser.add_argument(+ "--no-qa-history",+ action="store_true",+ default=not _env_bool("KEEP_QA_HISTORY", True),+ )+ parser.add_argument(+ "--no-normalize-output",+ action="store_true",+ default=not _env_bool("NORMALIZE_OUTPUT", True),+ )+ parser.add_argument(+ "--first-action-logprob-gate",+ action="store_true",+ default=_env_bool("FIRST_ACTION_LOGPROB_GATE", False),+ help="用 </silence> 与 </response> 的首 token 概率决定 history 与评分动作。",+ )+ parser.add_argument(+ "--disable-summarizer",+ action="store_true",+ default=not _env_bool("ENABLE_SUMMARIZER", False),+ )+ parser.add_argument(+ "--summarizer-model",+ default=os.environ.get(+ "SUMMARIZER_MODEL",+ "models/summary",+ ),+ )+ parser.add_argument(+ "--summarizer-api-base",+ default=os.environ.get("SUMMARIZER_API_BASE", "http://127.0.0.1:8065/v1"),+ )+ parser.add_argument(+ "--longterm-model",+ default=os.environ.get(+ "LONGTERM_SUMMARIZER_MODEL",+ os.environ.get("SUMMARIZER_MODEL", "models/summary"),+ ),+ )+ parser.add_argument(+ "--longterm-api-base",+ default=os.environ.get(+ "LONGTERM_SUMMARIZER_API_BASE",+ os.environ.get("SUMMARIZER_API_BASE", "http://127.0.0.1:8065/v1"),+ ),+ )+ parser.add_argument(+ "--summarizer-max-pixels",+ type=int,+ default=_env_int("SUMMARIZER_MAX_PIXELS", 786432),+ )+ parser.add_argument(+ "--summarizer-key-frames",+ type=int,+ default=_env_int("SUMMARIZER_KEY_FRAMES", 0),+ )+ parser.add_argument(+ "--summarizer-phase-seconds",+ type=float,+ default=_env_float("SUMMARIZER_PHASE_SECONDS", 10.0),+ )+ parser.add_argument(+ "--mid-term-max-tokens",+ type=int,+ default=_env_int("MID_TERM_MAX_TOKENS", 4000),+ )+ parser.add_argument(+ "--mid-term-target-tokens",+ type=int,+ default=_env_int("MID_TERM_TARGET_TOKEN_COUNT", 3000),+ )+ parser.add_argument(+ "--long-term-max-tokens",+ type=int,+ default=_env_int("LONG_TERM_MAX_TOKENS", 2000),+ )+ parser.add_argument(+ "--long-term-target-tokens",+ type=int,+ default=_env_int("LONG_TERM_TARGET_TOKEN_COUNT", 1000),+ )+ parser.add_argument(+ "--mid-term-temperature",+ type=float,+ default=_env_float("MID_TERM_TEMPERATURE", 0.8),+ )+ parser.add_argument(+ "--mid-term-top-p",+ type=float,+ default=_env_float("MID_TERM_TOP_P", 0.9),+ )+ parser.add_argument(+ "--mid-term-top-k",+ type=int,+ default=_env_int("MID_TERM_TOP_K", 40),+ )+ parser.add_argument(+ "--mid-term-repetition-penalty",+ type=float,+ default=_env_float("MID_TERM_REPETITION_PENALTY", 1.0),+ )+ parser.add_argument(+ "--mid-term-presence-penalty",+ type=float,+ default=_env_float("MID_TERM_PRESENCE_PENALTY", 0.0),+ )+ parser.add_argument(+ "--long-term-temperature",+ type=float,+ default=_env_float("LONG_TERM_TEMPERATURE", 1.0),+ )+ parser.add_argument(+ "--long-term-top-p",+ type=float,+ default=_env_float("LONG_TERM_TOP_P", 1.0),+ )+ parser.add_argument(+ "--long-term-top-k",+ type=int,+ default=_env_int("LONG_TERM_TOP_K", 80),+ )+ parser.add_argument(+ "--long-term-repetition-penalty",+ type=float,+ default=_env_float("LONG_TERM_REPETITION_PENALTY", 1.0),+ )+ parser.add_argument(+ "--long-term-presence-penalty",+ type=float,+ default=_env_float("LONG_TERM_PRESENCE_PENALTY", 0.0),+ )+ parser.add_argument(+ "--long-term-memory-window",+ type=int,+ default=_env_int("LONG_TERM_MEMORY_WINDOW", 40),+ )+ parser.add_argument(+ "--request-timeout-seconds",+ type=float,+ default=_env_float("REQUEST_TIMEOUT_SECONDS", 300.0),+ )+ parser.add_argument(+ "--session-timeout-seconds",+ type=float,+ default=_env_float("SESSION_TIMEOUT_SECONDS", 3600.0),+ help="Drop idle sessions after this many seconds to release CPU memory.",+ )+ parser.add_argument(+ "--max-active-sessions",+ type=int,+ default=_env_int("MAX_ACTIVE_SESSIONS", 0),+ help="Maximum live sessions kept in adapter memory; 0 disables the limit.",+ )+ parser.add_argument(+ "--allowed-local-image-roots",+ default=os.environ.get("ALLOWED_LOCAL_IMAGE_ROOTS", ""),+ help="Comma- or colon-separated directories whose image files may be referenced directly by requests.",+ )+ parser.add_argument(+ "--frame-save-dir",+ default=os.environ.get("FRAME_SAVE_DIR", ".runtime/frames"),+ help="Directory to save base64 frames received from WebUI.",+ )+ parser.add_argument(+ "--save-root",+ default=os.environ.get(+ "LIVE_ADAPTER_SAVE_ROOT",+ os.environ.get("SAVE_ROOT", DEFAULT_SAVE_ROOT),+ ),+ help="Root used for auto-generated output_*, output_light_*, and input_* dirs.",+ )+ parser.add_argument(+ "--run-timestamp",+ default=os.environ.get("LIVE_ADAPTER_RUN_TIMESTAMP", ""),+ help="Timestamp suffix for auto-generated live save dirs.",+ )+ parser.add_argument(+ "--output-model-name",+ default=os.environ.get("LIVE_ADAPTER_OUTPUT_MODEL_NAME", ""),+ help="Model-name suffix for auto-generated live save dirs.",+ )+ parser.add_argument(+ "--out-dir",+ default=os.environ.get("LIVE_ADAPTER_OUT_DIR") or os.environ.get("OUT_DIR"),+ help="Full live output directory. Relative paths resolve under save-root.",+ )+ parser.add_argument(+ "--light-out-dir",+ default=os.environ.get("LIVE_ADAPTER_LIGHT_OUT_DIR")+ or os.environ.get("LIGHT_OUT_DIR"),+ help="Light live output directory. Defaults to output_light_* derived from out-dir.",+ )+ parser.add_argument(+ "--debug-input-dir",+ default=os.environ.get("LIVE_ADAPTER_DEBUG_INPUT_DIR")+ or os.environ.get("DEBUG_INPUT_DIR"),+ help="Directory for live input_* debug snapshots. Relative paths resolve under save-root.",+ )+ parser.add_argument(+ "--no-live-save",+ action="store_true",+ default=not _env_bool("LIVE_SAVE_OUTPUTS", False),+ help="Disable live output_*/output_light_* writing.",+ )+ parser.add_argument(+ "--no-debug-inputs",+ action="store_true",+ default=not _env_bool("LIVE_SAVE_DEBUG_INPUTS", False),+ help="Disable live input_* debug snapshot writing.",+ )+ parser.add_argument(+ "--no-save-model-inputs",+ action="store_true",+ default=not _env_bool("SAVE_MODEL_INPUTS", False),+ help="Do not embed per-turn model_input records in output_*.",+ )+ parser.add_argument(+ "--no-summarizer-debug",+ action="store_true",+ default=not _env_bool("SUMMARIZER_DEBUG", True),+ help="Do not keep/save mid/long-term summary debug inputs.",+ )+ parser.add_argument(+ "--system-prompt",+ default=os.environ.get("SYSTEM_PROMPT", DEFAULT_SYSTEM_PROMPT_EN),+ help="System prompt prepended to every 8B main-model request. Set SYSTEM_PROMPT='' to disable the built-in default.",+ )+ parser.add_argument(+ "--language",+ default=os.environ.get("ADAPTER_LANGUAGE", "en"),+ choices=["zh", "en"],+ help="Language for context injection text (Video History header, Q&A History header, User Query header). 'zh' for Chinese, 'en' for English.",+ )+ args = parser.parse_args()+ if args.input_format != "legacy" and (+ not args.disable_summarizer or args.no_qa_history or args.chunk != 30+ ):+ parser.error("training input formats require --disable-summarizer, QA history, and --chunk 30")+ if args.input_format != "legacy" and args.retain_frames >= args.chunk:+ parser.error("training input formats require --retain-frames to be smaller than --chunk")++ # 输出目录:默认按会话在 save_root 下建 output_<时间>_<模型名>/ 与 output_light_*/;显式给 out_dir 时改为全局单目录。+ raw_save_root = (args.save_root or DEFAULT_SAVE_ROOT).strip() or DEFAULT_SAVE_ROOT+ save_root = os.path.normpath(os.path.expanduser(raw_save_root))+ run_timestamp = args.run_timestamp.strip() or datetime.now().strftime("%Y%m%d_%H%M%S")+ output_model_name = (+ sanitize_output_name(args.output_model_name)+ if args.output_model_name.strip()+ else derive_model_output_name(args.main_model)+ )+ no_live_save = args.no_live_save+ no_debug_inputs = args.no_debug_inputs+ per_session_dirs = not no_live_save+ explicit_out_dir = resolve_save_dir(args.out_dir, save_root)+ explicit_light_out_dir = resolve_save_dir(args.light_out_dir, save_root)+ explicit_debug_input_dir = resolve_save_dir(args.debug_input_dir, save_root)+ if explicit_out_dir or explicit_light_out_dir or explicit_debug_input_dir:+ per_session_dirs = False++ if no_live_save:+ out_dir = None+ light_out_dir = None+ elif per_session_dirs:+ out_dir = None+ light_out_dir = None+ else:+ out_dir = explicit_out_dir+ if out_dir is None:+ out_dir = os.path.join(+ save_root,+ f"output_{run_timestamp}_{output_model_name}",+ )+ light_out_dir = explicit_light_out_dir+ if light_out_dir is None:+ light_out_dir = derive_light_out_dir(out_dir)++ if no_debug_inputs:+ debug_input_dir = None+ elif per_session_dirs:+ debug_input_dir = None+ else:+ debug_input_dir = explicit_debug_input_dir+ if debug_input_dir is None:+ debug_input_dir = os.path.join(+ save_root,+ f"input_{run_timestamp}_{output_model_name}",+ )++ return AdapterConfig(+ host=args.host,+ port=args.port,+ adapter_model=args.adapter_model,+ main_api_base=args.main_api_base,+ main_model=args.main_model,+ main_backends=tuple(json.loads(args.main_backends)) if args.main_backends else (),+ api_key=args.api_key,+ allowed_local_image_roots=_split_paths(args.allowed_local_image_roots),+ frame_seconds=args.frame_seconds,+ input_format=args.input_format,+ max_pixels=args.max_pixels,+ resize_short_edge=args.resize_short_edge,+ main_max_tokens=args.main_max_tokens,+ main_temperature=args.main_temperature,+ main_top_p=args.main_top_p,+ main_top_k=args.main_top_k,+ main_repetition_penalty=args.main_repetition_penalty,+ main_presence_penalty=args.main_presence_penalty,+ honor_inbound_generation_params=args.honor_inbound_generation_params,+ chunk=args.chunk,+ retain_frames=args.retain_frames,+ compress_every_n_chunks=args.compress_every_n_chunks,+ async_summary_lead_frames=args.async_summary_lead_frames,+ use_prompt_as_query=not args.no_prompt_as_query,+ force_silence_before_query=args.force_silence_before_query,+ keep_qa_history=not args.no_qa_history,+ normalize_output=not args.no_normalize_output,+ first_action_logprob_gate=args.first_action_logprob_gate,+ enable_summarizer=not args.disable_summarizer,+ summarizer_model=args.summarizer_model,+ summarizer_api_base=args.summarizer_api_base,+ longterm_model=args.longterm_model,+ longterm_api_base=args.longterm_api_base,+ summarizer_max_pixels=args.summarizer_max_pixels,+ summarizer_key_frames=args.summarizer_key_frames,+ summarizer_phase_seconds=args.summarizer_phase_seconds,+ mid_term_max_tokens=args.mid_term_max_tokens,+ mid_term_target_tokens=args.mid_term_target_tokens,+ long_term_max_tokens=args.long_term_max_tokens,+ long_term_target_tokens=args.long_term_target_tokens,+ mid_term_temperature=args.mid_term_temperature,+ mid_term_top_p=args.mid_term_top_p,+ mid_term_top_k=args.mid_term_top_k,+ mid_term_repetition_penalty=args.mid_term_repetition_penalty,+ mid_term_presence_penalty=args.mid_term_presence_penalty,+ long_term_temperature=args.long_term_temperature,+ long_term_top_p=args.long_term_top_p,+ long_term_top_k=args.long_term_top_k,+ long_term_repetition_penalty=args.long_term_repetition_penalty,+ long_term_presence_penalty=args.long_term_presence_penalty,+ long_term_memory_window=args.long_term_memory_window,+ request_timeout_seconds=args.request_timeout_seconds,+ session_timeout_seconds=args.session_timeout_seconds,+ max_active_sessions=args.max_active_sessions,+ out_dir=out_dir,+ light_out_dir=light_out_dir,+ debug_input_dir=debug_input_dir,+ save_root=save_root if per_session_dirs else None,+ output_model_name=output_model_name,+ per_session_dirs=per_session_dirs,+ save_model_inputs=not args.no_save_model_inputs,+ save_debug_inputs=not no_debug_inputs,+ summarizer_debug=not args.no_summarizer_debug,+ frame_save_dir=args.frame_save_dir,+ language=args.language,+ system_prompt=args.system_prompt,+ )diff --git a/Web_Inference/webinfer/adapter_core.py b/Web_Inference/webinfer/adapter_core.pynew file mode 100644index 0000000..82b0f84--- /dev/null+++ b/Web_Inference/webinfer/adapter_core.py@@ -0,0 +1,599 @@+# -*- coding: utf-8 -*-+"""StreamingInferAdapter 主体:HTTP 接口 + 每帧推理主流程。++每个 /v1/chat/completions 请求(= WebUI 送来的一帧)在 _handle_chat_payload 中依次完成:+ 1. 解析图片 / 用户问题 / 时间戳,帧落盘;有新问题则更新 current_query_text;+ 2. 窗口满 chunk 帧时裁剪到最近 retain_frames 帧(或 summarizer 模式下刷新窗口并做摘要);+ 3. 追加 user 消息;若还没有任何问题且 force_silence_before_query,直接输出 </silence> 不调模型;+ 4. 否则构造 [system + 稀疏历史 + 窗口消息] 调 vLLM,归一化输出为 </silence> 或 </response> ...;+ 5. 把 assistant 输出写回窗口历史,记录 prediction,返回 OpenAI 格式响应给 WebUI。+类方法按功能拆在三个 mixin 中:SessionMixin(会话/落盘)、ModelMixin(prompt/调模型)、SummaryMixin(摘要)。+"""++from __future__ import annotations++import asyncio+import copy+import time+from pathlib import Path+from typing import Any, Optional++from aiohttp import web+from openai import AsyncOpenAI++from adapter_common import (+ LOGGER,+ _format_turn_time_range,+ _parse_start_second,+ action_history_output,+ archive_chunk_response_records,+ build_model_input_record,+ compact_image_urls_for_record,+ display_model_output,+ extract_response_payload,+ normalize_model_output,+ reset_chunk_state,+)+from adapter_config import AdapterConfig+from adapter_model import ModelMixin+from adapter_identity import identity_action, is_identity_question+from adapter_request import (+ _chat_completion_response,+ _extract_all_image_refs,+ _extract_time_range_from_request,+ _extract_time_range_from_text,+ _extract_time_ranges_from_request,+ _extract_user_prompt_text,+ _openai_error_response,+ _read_json,+ _request_session_id,+ _safe_session_id,+ _short,+ _strip_time_range_from_text,+)+from adapter_session import SessionMixin, SessionState+from adapter_summary import SummaryMixin+from memory_summarizer import SummarizerModel+++class StreamingInferAdapter(SessionMixin, ModelMixin, SummaryMixin):+ def __init__(self, config: AdapterConfig):+ self.config = config+ self.sessions: dict[str, SessionState] = {}+ self._cleanup_task: Optional[asyncio.Task] = None+ Path(config.frame_save_dir).mkdir(parents=True, exist_ok=True)+ self.main_client = AsyncOpenAI(+ base_url=config.main_api_base,+ api_key=config.api_key,+ timeout=config.request_timeout_seconds,+ )+ self.main_clients: dict[str, tuple[AsyncOpenAI, str]] = {}+ if config.main_backends:+ for backend in config.main_backends:+ name = backend["name"]+ self.main_clients[name] = (+ AsyncOpenAI(+ base_url=backend["api_base"],+ api_key=config.api_key,+ timeout=config.request_timeout_seconds,+ ),+ backend.get("model", name),+ )+ else:+ self.main_clients[config.main_model] = (self.main_client, config.main_model)+ self.summarizer: Optional[SummarizerModel] = None+ if config.enable_summarizer:+ self.summarizer = SummarizerModel(+ model_name=config.summarizer_model,+ api_base=config.summarizer_api_base,+ longterm_model_name=config.longterm_model,+ longterm_api_base=config.longterm_api_base,+ mid_term_max_tokens=config.mid_term_max_tokens,+ mid_term_target_tokens=config.mid_term_target_tokens,+ long_term_max_tokens=config.long_term_max_tokens,+ long_term_target_tokens=config.long_term_target_tokens,+ key_frames_per_chunk=config.summarizer_key_frames,+ max_pixels=config.summarizer_max_pixels,+ prompt_phase_seconds=config.summarizer_phase_seconds,+ mid_term_temperature=config.mid_term_temperature,+ mid_term_top_p=config.mid_term_top_p,+ mid_term_top_k=config.mid_term_top_k,+ mid_term_repetition_penalty=config.mid_term_repetition_penalty,+ mid_term_presence_penalty=config.mid_term_presence_penalty,+ long_term_temperature=config.long_term_temperature,+ long_term_top_p=config.long_term_top_p,+ long_term_top_k=config.long_term_top_k,+ long_term_repetition_penalty=config.long_term_repetition_penalty,+ long_term_presence_penalty=config.long_term_presence_penalty,+ debug=config.summarizer_debug,+ )+ if config.out_dir:+ Path(config.out_dir).mkdir(parents=True, exist_ok=True)+ if config.light_out_dir:+ Path(config.light_out_dir).mkdir(parents=True, exist_ok=True)+ if config.debug_input_dir:+ Path(config.debug_input_dir).mkdir(parents=True, exist_ok=True)++ def _resolve_backend(self, model_name: Optional[str] = None) -> tuple[AsyncOpenAI, str]:+ if model_name and model_name in self.main_clients:+ return self.main_clients[model_name]+ return self.main_client, self.config.main_model++ # ==================== HTTP 接口 ====================++ async def handle_models(self, request: web.Request) -> web.Response:+ del request+ now = int(time.time())+ data = [+ {+ "id": name,+ "object": "model",+ "created": now,+ "owned_by": "streamingharness",+ }+ for name in self.main_clients+ ]+ return web.json_response({"object": "list", "data": data})++ async def handle_health(self, request: web.Request) -> web.Response:+ del request+ return web.json_response(+ {+ "ok": True,+ "model": self.config.adapter_model,+ "backends": list(self.main_clients.keys()),+ "summarizer_enabled": self.summarizer is not None,+ "sessions": len(self.sessions),+ }+ )++ async def handle_reset(self, request: web.Request) -> web.Response:+ payload = await _read_json(request)+ session_id = _request_session_id(request, payload)+ session_id = _safe_session_id(session_id)+ removed_state = self.sessions.pop(session_id, None)+ if removed_state is not None:+ removed_state.image_cache.clear()+ for job in removed_state.async_pending_summary_jobs:+ job["task"].cancel()+ await self._flush_session_outputs(removed_state)+ removed = removed_state is not None+ return web.json_response({"ok": True, "session_id": session_id, "removed": removed})++ async def handle_chat_completions(self, request: web.Request) -> web.Response:+ payload = await _read_json(request)+ session_id = _request_session_id(request, payload)+ requested_model = payload.get("model")+ client, model_name = self._resolve_backend(requested_model)+ state = self.get_session(session_id)+ # 同一会话的帧串行处理,保证窗口历史按时间顺序追加。+ async with state.lock:+ try:+ result = await self._handle_chat_payload(state, payload, request, client=client, model_name=model_name)+ except web.HTTPException:+ raise+ except Exception as exc:+ LOGGER.exception("chat completion failed")+ return _openai_error_response(str(exc), status=502)+ return web.json_response(result)++ # ==================== 每帧推理主流程 ====================++ async def _handle_chat_payload(+ self,+ state: SessionState,+ payload: dict[str, Any],+ request: web.Request,+ *,+ client: Optional[AsyncOpenAI] = None,+ model_name: Optional[str] = None,+ ) -> dict[str, Any]:+ client = client or self.main_client+ model_name = model_name or self.config.main_model+ t_start = time.perf_counter()+ messages = payload.get("messages") or []+ if not isinstance(messages, list):+ raise web.HTTPBadRequest(text="messages must be a list")++ # ---- 1. 解析本帧:图片引用 / 用户问题 / 时间戳 ----+ image_refs = _extract_all_image_refs(messages, request, payload)+ if not image_refs:+ return await self._forward_text_only(payload, client=client, model_name=model_name)+ if self.config.input_format != "legacy" and len(image_refs) != 1:+ raise web.HTTPBadRequest(text="training input format requires one frame per request")++ # The live counter is authoritative and does not depend on how much+ # diagnostic prediction history is retained in memory.+ turn_count = state.turn_count + 1+ raw_prompt_text = _extract_user_prompt_text(messages)+ prompt_text = _strip_time_range_from_text(raw_prompt_text)++ # Resolve time ranges for all images+ incoming_time_ranges = _extract_time_ranges_from_request(request, payload)+ if not incoming_time_ranges:+ single = _extract_time_range_from_request(request, payload)+ if single is None:+ single = _extract_time_range_from_text(raw_prompt_text)+ if single:+ incoming_time_ranges = [single]+ time_ranges: list[str] = []+ for i in range(len(image_refs)):+ if i < len(incoming_time_ranges) and incoming_time_ranges[i]:+ time_ranges.append(incoming_time_ranges[i])+ else:+ time_ranges.append(self._time_range_for_frame(state.frame_count + i))+ time_range = _format_turn_time_range(time_ranges)++ image_paths = [self._resolve_frame_ref(ref, state) for ref in image_refs]+ LOGGER.info(+ "[%s] turn=%d frames=%d(+%d) chunk=%d time=%s prompt=%r",+ state.session_id,+ turn_count,+ state.frame_count,+ len(image_refs),+ state.chunk_index,+ time_range,+ _short(prompt_text, 80),+ )++ query_text = self._update_query_state(state, prompt_text, time_ranges[0])+ # WebUI 的问题只发送一次;非空文本就是新提交,允许连续问同一句。+ frame_query_text = prompt_text or None++ await self._commit_required_async_summaries(+ state, state.turn_count, non_blocking=True,+ )++ # ---- 2. 窗口满 chunk 帧:训练格式下裁剪到最近 retain_frames 帧;legacy 下刷新窗口(可做摘要) ----+ if (+ self.config.input_format != "legacy"+ and self.config.chunk > 0+ and state.current_chunk["turn_count"] >= self.config.chunk+ ):+ self._trim_current_chunk_to_retained_frames(state)+ elif (+ self.config.chunk > 0+ and state.current_chunk["turn_count"] >= self.config.chunk+ ):+ self._execute_pending_qa_archive(state)+ carry_response_records = []+ if self.config.keep_qa_history and state.current_query_text:+ qa_cutoff = float("inf")+ if (+ self._async_summary_enabled()+ and state.async_summary_segment["frame_time_ranges"]+ ):+ qa_cutoff = _parse_start_second(+ state.async_summary_segment["frame_time_ranges"][0]+ )+ carry_response_records = [+ (tr, payload)+ for tr, payload in state.current_chunk["response_records"]+ if _parse_start_second(tr) >= qa_cutoff+ ]+ archive_chunk_response_records(+ state.current_chunk,+ state.memory_state,+ state.current_query_text,+ state.query_start_time,+ chunk_index=state.chunk_index,+ before_time_sec=qa_cutoff,+ )+ await self._flush_chunk(state, use_async_summary=self._async_summary_enabled())+ if (+ self._async_summary_enabled()+ and state.async_summary_segment["turn_count"] > 0+ ):+ carry = copy.deepcopy(state.async_summary_segment)+ carry_frames = carry["frame_count"]+ carry_turns = carry["turn_count"]+ carry["frame_count"] = 0+ carry["turn_count"] = 0+ carry["response_records"] = carry_response_records+ carry["api_msg_cache"] = []+ state.current_chunk = carry+ LOGGER.info(+ "[%s] carried over %d unsummarized turn(s), %d frame(s) to new chunk",+ state.session_id,+ carry_turns,+ carry_frames,+ )+ else:+ state.current_chunk = reset_chunk_state()+ state.chunk_index += 1+ state.query_in_current_chunk = bool(query_text)++ # ---- 3. 本帧写入窗口:帧路径 / 时间戳 / user 消息 ----+ for tr, ip in zip(time_ranges, image_paths):+ state.frame_count += 1+ state.current_chunk["image_paths"].append(str(ip))+ state.current_chunk["frame_time_ranges"].append(tr)+ state.current_chunk["summarizer_frame_cache"].append({"path": str(ip)})+ state.current_chunk["frame_count"] += 1++ state.turn_count += 1+ state.current_chunk["turn_count"] += 1++ user_message = self._build_internal_user_message(+ time_ranges=time_ranges,+ image_paths=[str(ip) for ip in image_paths],+ query_text=query_text if self.config.input_format == "legacy" else frame_query_text,+ )+ state.current_chunk["messages"].append(user_message)+ if (+ self.config.input_format != "legacy"+ and self.summarizer is None+ and self.config.keep_qa_history+ ):+ state.current_chunk["dialogue_events"].append(+ {"time_range": time_ranges[0], "query": prompt_text}+ )+ if self._async_summary_enabled():+ self._append_async_summary_user_message(+ state,+ time_ranges=time_ranges,+ image_paths=[str(ip) for ip in image_paths],+ query_text=query_text,+ )++ turn_input_record = {+ "source_message": compact_image_urls_for_record(+ messages[-1] if messages else None,+ [str(ip) for ip in image_paths],+ ),+ "vllm_message": user_message,+ "chunk_index": state.chunk_index,+ "has_image": True,+ "image_path": str(image_paths[-1]),+ "image_paths_batch": [str(ip) for ip in image_paths],+ "num_chunk_turns": state.current_chunk["turn_count"],+ "num_chunk_frames": state.current_chunk["frame_count"],+ "image_paths": list(state.current_chunk["image_paths"]),+ "frame_time_ranges": list(state.current_chunk["frame_time_ranges"]),+ }+ is_forced_silence = (+ self.config.force_silence_before_query and not state.current_query_text+ )+ inference_start = None+ inference_time = 0.0+ chunk_start_model_input_path = None+ turn_model_input_record = None+ model_input_record = None++ # ---- 4. 推理:尚无问题时强制 </silence>;否则构造 messages 调主模型 ----+ if is_forced_silence:+ generated_text = "</silence>"+ raw_text = ""+ usage = None+ turn_model_input_record = build_model_input_record(+ chunk_index=state.chunk_index,+ messages=state.current_chunk["messages"],+ frame_count=state.current_chunk["frame_count"],+ inference_skipped=True,+ skip_reason="force_silence_before_query",+ image_paths=state.current_chunk["image_paths"],+ frame_time_ranges=state.current_chunk["frame_time_ranges"],+ )+ if self.config.save_model_inputs:+ model_input_record = turn_model_input_record+ else:+ t_prompt_build_start = time.perf_counter()+ cache_hits_before = state.image_cache.hits+ cache_misses_before = state.image_cache.misses+ internal_messages, prefix_content = self._build_main_internal_messages(state)+ t_prompt_history_end = time.perf_counter()+ api_messages = self._build_cached_api_messages(state, internal_messages)+ t_prompt_images_end = time.perf_counter()+ generation_kwargs = self._main_generation_kwargs(payload)+ http_messages = self._build_main_http_messages(api_messages)+ turn_model_input_record = build_model_input_record(+ chunk_index=state.chunk_index,+ messages=compact_image_urls_for_record(+ http_messages,+ list(state.current_chunk["image_paths"]),+ ),+ frame_count=state.current_chunk["frame_count"],+ model=model_name,+ generation_kwargs=generation_kwargs,+ image_paths=state.current_chunk["image_paths"],+ frame_time_ranges=state.current_chunk["frame_time_ranges"],+ prefix_content=prefix_content,+ )+ if self.config.save_model_inputs:+ model_input_record = turn_model_input_record+ chunk_start_model_input_path = self._maybe_save_chunk_start_model_input(+ state,+ turn_count,+ time_range,+ turn_model_input_record,+ )+ t_prompt_build_end = time.perf_counter()+ inference_start = time.time()+ model_result = await self._call_main_model(+ payload,+ api_messages,+ client=client,+ model_name=model_name,+ session_state=state,+ generation_kwargs=generation_kwargs,+ http_messages=http_messages,+ )+ raw_text, usage, first_action = (+ model_result if len(model_result) == 3 else (*model_result, None)+ )+ inference_time = time.time() - inference_start+ t_inference_end = time.perf_counter()+ generated_text = (+ display_model_output(raw_text)+ if self.config.first_action_logprob_gate+ else normalize_model_output(raw_text)+ if self.config.normalize_output+ else (raw_text or "").strip()+ )++ # ---- 5. 输出写回窗口历史(训练格式的 assistant 轮),记录 prediction ----+ if is_forced_silence:+ first_action = None+ history_text = (+ action_history_output(raw_text, first_action["action"])+ if first_action is not None+ else generated_text+ )+ self._execute_pending_qa_archive(state)++ response_payload = extract_response_payload(history_text)+ if response_payload and state.current_query_text:+ state.current_chunk["response_records"].append((time_range, response_payload))++ state.current_chunk["messages"].append(+ {"role": "assistant", "content": history_text}+ )+ if (+ self.config.input_format != "legacy"+ and self.summarizer is None+ and self.config.keep_qa_history+ ):+ state.current_chunk["dialogue_events"][-1]["answer"] = history_text+ if self._async_summary_enabled():+ state.async_summary_segment["messages"].append(+ {"role": "assistant", "content": history_text}+ )+ self._submit_async_summary_if_needed(state)++ turn_output_record = {}+ if is_forced_silence:+ turn_output_record["inference_skipped"] = True+ turn_output_record["skip_reason"] = "force_silence_before_query"++ t_end = time.perf_counter()+ total_time = t_end - t_start++ prediction = {+ "turn": turn_count,+ "time_range": time_range,+ "query": query_text,+ "input": turn_input_record,+ "output": turn_output_record,+ "prediction": generated_text,+ "raw_prediction": raw_text,+ "action_prediction": history_text,+ "total_time": round(total_time, 3),+ "inference_time": round(inference_time, 3),+ }+ if model_input_record is not None:+ turn_input_record["model_input"] = model_input_record+ if chunk_start_model_input_path:+ prediction["chunk_start_model_input_path"] = chunk_start_model_input_path+ if first_action is not None:+ prediction["first_action_decision"] = first_action+ state.predictions.append(prediction)++ t_end = time.perf_counter()+ adapter_timing = {+ "adapter_total_ms": round((t_end - t_start) * 1000, 1),+ }+ if not is_forced_silence:+ adapter_timing["prompt_build_ms"] = round((t_prompt_build_end - t_prompt_build_start) * 1000, 1)+ adapter_timing["prompt_history_ms"] = round((t_prompt_history_end - t_prompt_build_start) * 1000, 1)+ adapter_timing["prompt_images_ms"] = round((t_prompt_images_end - t_prompt_history_end) * 1000, 1)+ adapter_timing["prompt_record_ms"] = round((t_prompt_build_end - t_prompt_images_end) * 1000, 1)+ adapter_timing["vllm_inference_ms"] = round(inference_time * 1000, 1)+ adapter_timing["post_process_ms"] = round((t_end - t_inference_end) * 1000, 1)+ adapter_timing["pre_inference_ms"] = round((t_prompt_build_start - t_start) * 1000, 1)++ if not is_forced_silence:+ LOGGER.info(+ "[%s] turn=%d timing: total=%.1fms pre=%.1fms prompt_build=%.1fms vllm=%.1fms post=%.1fms",+ state.session_id,+ turn_count,+ adapter_timing["adapter_total_ms"],+ adapter_timing["pre_inference_ms"],+ adapter_timing["prompt_build_ms"],+ adapter_timing["vllm_inference_ms"],+ adapter_timing["post_process_ms"],+ )+ else:+ LOGGER.info(+ "[%s] turn=%d timing: total=%.1fms (forced silence, inference skipped)",+ state.session_id,+ turn_count,+ adapter_timing["adapter_total_ms"],+ )++ # ---- 6. 组装 OpenAI 响应返回 WebUI ----+ result = _chat_completion_response(+ model=self.config.adapter_model,+ content=generated_text,+ usage=usage,+ raw_model=model_name,+ raw_text=raw_text,+ )+ result["streamingharness"]["action_content"] = history_text+ if first_action is not None:+ result["streamingharness"]["first_action_decision"] = first_action+ result["streamingharness"]["timing"] = adapter_timing+ if not is_forced_silence:+ result["streamingharness"]["image_cache"] = {+ "hits": state.image_cache.hits - cache_hits_before,+ "misses": state.image_cache.misses - cache_misses_before,+ "entries": len(state.image_cache),+ "bytes": state.image_cache.bytes,+ "max_bytes": state.image_cache.max_bytes,+ "max_entries": state.image_cache.max_entries,+ }+ summarizer_timing = {}+ if state.mid_term_history:+ last_mid = state.mid_term_history[-1]+ summarizer_timing["last_mid_term_ms"] = round(last_mid.get("inference_time", 0) * 1000, 1)+ summarizer_timing["last_mid_term_chunk"] = last_mid.get("chunk_index")+ if last_mid.get("barrier_wait_time") is not None:+ summarizer_timing["barrier_wait_ms"] = round(last_mid["barrier_wait_time"] * 1000, 1)+ if state.long_term_history:+ last_long = state.long_term_history[-1]+ summarizer_timing["last_long_term_ms"] = round(last_long.get("inference_time", 0) * 1000, 1)+ if self.summarizer is not None:+ result["streamingharness"]["summarizer_timing"] = summarizer_timing+ result["streamingharness"]["memory"] = {+ "mid_term_summaries": [+ {"chunk_index": e["chunk_index"], "frame_range": e["frame_range"], "summary_text": e["summary_text"]}+ for e in state.mid_term_summaries+ ],+ "long_term_memory": state.memory_state.get("long_term_memory", ""),+ }+ return result++ async def _forward_text_only(+ self,+ payload: dict[str, Any],+ *,+ client: Optional[AsyncOpenAI] = None,+ model_name: Optional[str] = None,+ ) -> dict[str, Any]:+ client = client or self.main_client+ model_name = model_name or self.config.main_model+ prompt_text = _extract_user_prompt_text(payload.get("messages") or [])+ if is_identity_question(prompt_text):+ return _chat_completion_response(+ model=self.config.adapter_model, content=identity_action(prompt_text),+ usage={"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},+ raw_model=model_name, raw_text=identity_action(prompt_text),+ )+ generation_kwargs = self._main_generation_kwargs(payload)+ response = await client.chat.completions.create(+ model=model_name,+ messages=self._build_main_http_messages(payload.get("messages") or []),+ **generation_kwargs,+ )+ raw_text = response.choices[0].message.content if response.choices else ""+ usage = response.usage.model_dump() if getattr(response, "usage", None) else None+ return _chat_completion_response(+ model=self.config.adapter_model,+ content=raw_text or "",+ usage=usage,+ raw_model=model_name,+ raw_text=raw_text or "",+ )++ def _time_range_for_frame(self, frame_index: int) -> str:+ start = frame_index * self.config.frame_seconds+ return f"{start:.1f} seconds"diff --git a/Web_Inference/webinfer/adapter_identity.py b/Web_Inference/webinfer/adapter_identity.pynew file mode 100644index 0000000..03bc0c8--- /dev/null+++ b/Web_Inference/webinfer/adapter_identity.py@@ -0,0 +1,39 @@+"""Narrow deterministic replies for questions about this deployed model.++This does not rewrite arbitrary answers or block discussion of public models.+The system prompt covers paraphrases outside these explicit patterns.+"""++import re++PUBLIC_IDENTITY = "ALIVE"+++def identity_action(text: str) -> str:+ """Return a natural, language-matched public self-introduction."""+ if re.search(r"[\u3400-\u9fff]", text or ""):+ return "</response> 我是 ALIVE。"+ return "</response> I'm ALIVE."++_DETAIL_ZH = r"(?:训练|训.{0,8}出|微调|基模|基座|底座|基础模型|架构|参数|权重|检查点|数据集|语料|技术来源|技术细节|版本|哪一版|开发|研发|模型|名字|名称|谁|来历)"+_DETAIL_EN = r"(?:train(?:ing|ed)?|fine[- ]?tun\w*|base\s+model|foundation|backbone|architecture|parameters?|weights?|checkpoints?|datasets?|training\s+data|lineage|model|name|develop\w*|creat\w*|version|built|based\s+on)"+_PATTERNS = tuple(re.compile(pattern, re.I) for pattern in (+ r"(?:你|您)(?:是|叫|姓|叫什么|到底是|究竟是).{0,12}(?:谁|什么|哪个|哪家|啥|alive|qwen|通义|千问|gpt|gemini)",+ r"(?:你|您)(?:的|自己的|自身的).{0,18}" + _DETAIL_ZH,+ r"(?:你|您)(?:是|如何|怎么|怎样|在|用|基于|由|有|属于|到底|究竟).{0,30}" + _DETAIL_ZH,+ r"(?:这个|该|当前|此)(?:模型|服务|系统).{0,20}" + _DETAIL_ZH,+ r"(?:你|您)(?:刚才|之前|前面|曾经|先前).{0,40}(?:说|提到).{0,40}" + _DETAIL_ZH,+ r"(?:介绍|说明|说说)(?:一下)?(?:你自己|你自身|你这个模型)",+ r"\b(?:who|what)\s+(?:exactly\s+)?are\s+you\b",+ r"\b(?:what|which)\s+(?:AI\s+)?(?:model|version)\s+are\s+you\b",+ r"\byour\s+(?:own\s+|underlying\s+|original\s+|exact\s+|technical\s+){0,3}" + _DETAIL_EN + r"\b",+ r"\b(?:are|were|have)\s+you\b[^.!?\n]{0,45}\b" + _DETAIL_EN + r"\b",+ r"\b(?:how|who)\s+(?:did|does|was|has)\s+(?:your\s+team|your\s+company|you)\b[^.!?\n]{0,35}\b" + _DETAIL_EN + r"\b",+ r"\b(?:who\s+(?:developed|created|trained|built)\s+you|introduce\s+yourself)\b",+ r"\byou\s+(?:said|mentioned|claimed|stated)\b[^.!?\n]{0,70}\b" + _DETAIL_EN + r"\b",+))+++def is_identity_question(text: str) -> bool:+ """Match direct questions about this service, not general ML questions."""+ return any(pattern.search(text or "") for pattern in _PATTERNS)diff --git a/Web_Inference/webinfer/adapter_image_cache.py b/Web_Inference/webinfer/adapter_image_cache.pynew file mode 100644index 0000000..72a4da3--- /dev/null+++ b/Web_Inference/webinfer/adapter_image_cache.py@@ -0,0 +1,64 @@+"""Bounded, session-owned cache of encoded frames in the current window."""++from __future__ import annotations++from collections import OrderedDict+from pathlib import Path+from typing import Callable, Iterable+++class ImageDataUrlCache:+ # Bounds include ASCII data URL payloads, not the small Python index overhead.+ def __init__(self, max_bytes: int = 32 * 1024 * 1024, max_entries: int = 128):+ self.max_bytes = max(0, max_bytes)+ self.max_entries = max(0, max_entries)+ self._entries: OrderedDict[tuple, str] = OrderedDict()+ self.bytes = 0+ self.hits = 0+ self.misses = 0++ def __len__(self) -> int:+ return len(self._entries)++ def _remove(self, key: tuple) -> None:+ self.bytes -= len(self._entries.pop(key))++ def retain_paths(self, paths: Iterable[str]) -> None:+ active = set(paths)+ for key in list(self._entries):+ if key[0] not in active:+ self._remove(key)++ def clear(self) -> None:+ self._entries.clear()+ self.bytes = 0++ def encode(+ self, path: str, max_pixels: int, resize_short_edge: int,+ loader: Callable[[str, int, int], str],+ ) -> str:+ # File identity/version prevents stale hits if a local frame is replaced.+ stat = Path(path).stat()+ key = (path, max_pixels, resize_short_edge, stat.st_dev, stat.st_ino,+ stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns)+ value = self._entries.get(key)+ if value is not None:+ self.hits += 1+ self._entries.move_to_end(key)+ return value++ self.misses += 1+ for old_key in list(self._entries):+ if old_key[:3] == key[:3]:+ self._remove(old_key)+ value = loader(path, max_pixels, resize_short_edge)+ if self.max_entries == 0 or len(value) > self.max_bytes:+ return value+ while self._entries and (+ len(self._entries) >= self.max_entries+ or self.bytes + len(value) > self.max_bytes+ ):+ self._remove(next(iter(self._entries)))+ self._entries[key] = value+ self.bytes += len(value)+ return valuediff --git a/Web_Inference/webinfer/adapter_model.py b/Web_Inference/webinfer/adapter_model.pynew file mode 100644index 0000000..824d46f--- /dev/null+++ b/Web_Inference/webinfer/adapter_model.py@@ -0,0 +1,554 @@+# -*- coding: utf-8 -*-+"""主模型输入构造与 vLLM 调用。++每来一帧,发给主模型的 messages 由三部分组成(默认 no_time 训练格式):+ [system prompt]+ + sparse_text_messages :已滑出窗口的稀疏问答(只保留文本:有提问的 user 轮 / 有 </response> 的 assistant 轮)+ + current_chunk.messages:窗口内逐帧的 user(问题+图片) / assistant(</silence> 或 </response> ...) 交替消息+窗口满 chunk(=30) 帧后,一次性裁剪到最近 retain_frames(=10) 帧(_trim_current_chunk_to_retained_frames),+之后 20 帧内消息前缀稳定,可以命中 vLLM 的 prefix cache。+"""++from __future__ import annotations++import math+from typing import Any, Optional++from openai import AsyncOpenAI++from adapter_common import (+ LOGGER,+ RESPONSE_TOKEN,+ RESPONSE_TOKEN_ID,+ SILENCE_TOKEN,+ SILENCE_TOKEN_ID,+ TIME_RANGE_RE,+ _extract_time_range_from_message,+ _format_batch_time_marker,+ _format_seconds_words,+ _get_i18n,+ _parse_start_second,+ archive_chunk_response_records,+)+from adapter_request import (+ _extract_extra_body,+ _extract_user_prompt_text,+ _file_to_data_url_cached,+ _internal_message_has_image,+ _internal_message_to_openai,+)+from adapter_session import SessionState+from adapter_identity import identity_action, is_identity_question+++def build_static_system_content(+ extra_system_messages: Optional[list[str]] = None,+ memory_state: Optional[dict[str, Any]] = None,+ mid_term_summaries: Optional[list[dict[str, Any]]] = None,+ language: str = "en",+) -> str:+ # 仅 summarizer / legacy 模式会有内容:长期记忆 + 中期摘要拼成 [Video History]。+ i18n = _get_i18n(language)+ sections: list[str] = []+ for message in extra_system_messages or []:+ if message and message.strip():+ sections.append(message.strip())++ history_parts: list[str] = []+ if memory_state is not None and memory_state.get("long_term_memory"):+ history_parts.append(memory_state["long_term_memory"])+ if mid_term_summaries:+ for entry in mid_term_summaries:+ history_parts.append(f"<{entry['frame_range']}>\n{entry['summary_text']}")++ if history_parts:+ sections.append(+ i18n["video_history_header"]+ + "\n\n".join(history_parts)+ )++ return "\n\n".join(sections) if sections else ""+++def build_dynamic_system_content(+ current_query_text: Optional[str] = None,+ memory_state: Optional[dict[str, Any]] = None,+ include_qa_history: bool = True,+ current_chunk_index: int = 0,+ language: str = "en",+) -> str:+ # 仅 summarizer / legacy 模式会有内容:旧版 [Q&A History] 与 [User Query] 文本块。+ i18n = _get_i18n(language)+ sections: list[str] = []++ if include_qa_history and memory_state is not None and memory_state.get("qa_history"):+ qa_entries = [+ entry for entry in memory_state["qa_history"]+ if entry.get("archived_in_chunk", 0) < current_chunk_index+ ]+ if qa_entries:+ qa_lines: list[str] = []+ for idx, entry in enumerate(qa_entries, 1):+ q_time = entry["query_time"] or "N/A"+ parts = [f"#{idx} [{i18n['qa_query_label']}@{q_time}] {entry['query']}"]+ for response_time, payload in entry.get("responses", []):+ parts.append(f"[{i18n['qa_response_label']}@{response_time}] {payload}")+ qa_lines.append("\n".join(parts))+ sections.append(+ i18n["qa_history_header"]+ + "\n".join(qa_lines)+ )++ if current_query_text:+ sections.append(i18n["user_query_header"] + "\n" + current_query_text.strip())++ return "\n\n".join(sections) if sections else ""+++class ModelMixin:+ """StreamingInferAdapter 的 prompt 构造与主模型调用部分(依赖 self.config / self.summarizer)。"""++ # ==================== 用户问题状态 ====================++ def _update_query_state(+ self,+ state: SessionState,+ prompt_text: str,+ time_range: str,+ ) -> Optional[str]:+ if not self.config.use_prompt_as_query:+ return None++ normalized_prompt = (prompt_text or "").strip()+ if not normalized_prompt:+ return None++ # 同样的文字再次提交也是新问题,旧问答先归档,再更新提问时刻。+ if state.current_query_text is not None:+ state._pending_qa_archive = (state.current_query_text, state.query_start_time)+ state.current_query_text = normalized_prompt+ state.query_start_time = time_range+ state.query_in_current_chunk = True+ return normalized_prompt++ def _execute_pending_qa_archive(self, state: SessionState) -> None:+ if state._pending_qa_archive is None:+ return+ old_query, old_start_time = state._pending_qa_archive+ archive_chunk_response_records(+ state.current_chunk,+ state.memory_state,+ old_query,+ old_start_time,+ chunk_index=state.chunk_index,+ )+ state.current_chunk["response_records"] = []+ state._pending_qa_archive = None++ # ==================== 窗口消息构造 ====================++ def _build_internal_user_message(+ self,+ time_range=None,+ image_path=None,+ query_text=None,+ *,+ time_ranges=None,+ image_paths=None,+ ) -> dict[str, Any]:+ i18n = _get_i18n(self.config.language)+ if time_ranges is None:+ time_ranges = [time_range] if time_range else []+ if image_paths is None:+ image_paths = [image_path] if image_path else []+ content: list[dict[str, Any]] = []+ if self.config.input_format == "legacy":+ if query_text:+ content.append({"type": "text", "text": i18n["user_query_header"] + "\n" + query_text})+ batch_time_marker = _format_batch_time_marker(time_ranges)+ if batch_time_marker:+ content.append({"type": "text", "text": f"<{batch_time_marker}>"})+ else:+ # 两版训练数据只差时间前缀;问题仅放在实际提问的这一帧。+ text = f"<{time_ranges[0]}>\n" if self.config.input_format == "timed" else ""+ if query_text:+ text += query_text + "\n"+ if text:+ content.append({"type": "text", "text": text})+ for ip in image_paths:+ content.append(+ {+ "type": "image",+ "image": ip,+ "max_pixels": self.config.max_pixels,+ "resize_short_edge": self.config.resize_short_edge,+ }+ )+ return {"role": "user", "content": content}++ def _archive_dialogue_events(+ self, state: SessionState, events: Optional[list[dict[str, str]]] = None+ ) -> None:+ for event in events if events is not None else state.current_chunk["dialogue_events"]:+ query = event["query"]+ # 事件记录的是该帧实际提交的问题,滑出窗口时也不能按文字去重。+ is_new_query = bool(query)+ answer = event["answer"]+ if not is_new_query and not answer.startswith("</response>"):+ continue+ # 训练集的旧窗口仅保留问答时刻;旧帧和纯静默轮次均不进入下一窗口。+ if self.config.input_format == "no_time":+ user_content = query if is_new_query else ""+ else:+ timestamp = f"<{_format_seconds_words(_parse_start_second(event['time_range']))}>"+ user_content = timestamp + (f"\n{query}" if is_new_query else "")+ state.sparse_text_messages.extend(+ [+ {"role": "user", "content": user_content},+ {"role": "assistant", "content": answer},+ ]+ )++ def _trim_current_chunk_to_retained_frames(self, state: SessionState) -> None:+ """Archive old no-summary turns and keep only the most recent retain_frames."""++ chunk = max(1, int(self.config.chunk or 1))+ retain = max(0, min(int(self.config.retain_frames or 0), chunk - 1))+ current_turns = int(state.current_chunk.get("turn_count") or 0)+ remove_turns = max(0, current_turns - retain)+ if remove_turns <= 0:+ return++ removed_events = state.current_chunk["dialogue_events"][:remove_turns]+ if removed_events:+ # 旧视觉帧不再进入窗口,只把需要保留的稀疏问答文本归档。+ self._archive_dialogue_events(state, removed_events)+ del state.current_chunk["dialogue_events"][:remove_turns]++ del state.current_chunk["messages"][: remove_turns * 2]+ for key in ("image_paths", "frame_time_ranges", "summarizer_frame_cache"):+ del state.current_chunk[key][:remove_turns]+ state.current_chunk["frame_count"] = max(+ 0, int(state.current_chunk.get("frame_count") or 0) - remove_turns+ )+ state.current_chunk["turn_count"] = max(0, current_turns - remove_turns)+ state.current_chunk["api_msg_cache"] = []+ state.image_cache.retain_paths(state.current_chunk["image_paths"])+ LOGGER.info(+ "[%s] chunk window reached %d turn(s); archived %d old turn(s), retained %d recent turn(s)",+ state.session_id,+ chunk,+ remove_turns,+ state.current_chunk["turn_count"],+ )++ @staticmethod+ def _normalize_model_timestamps(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:+ first_time = next(+ (+ _parse_start_second(time_range)+ for message in messages+ if message.get("role") == "user"+ for time_range in [_extract_time_range_from_message(message)]+ if time_range+ ),+ 0.0,+ )+ if first_time <= 0:+ return messages++ normalized = []+ for message in messages:+ if message.get("role") != "user":+ normalized.append(message)+ continue+ content = message["content"]+ if isinstance(content, str):+ content = TIME_RANGE_RE.sub(+ lambda match: f"<{_format_seconds_words(_parse_start_second(match.group('range')) - first_time)}>",+ content,+ count=1,+ )+ else:+ # 当前帧的时间戳和问题可能在同一个 text 中,只改开头的时间戳。+ content = [+ {+ **item,+ "text": TIME_RANGE_RE.sub(+ lambda match: f"<{_format_seconds_words(_parse_start_second(match.group('range')) - first_time)}>",+ item["text"],+ count=1,+ ),+ }+ if item.get("type") == "text" and TIME_RANGE_RE.match(item.get("text", ""))+ else item+ for item in content+ ]+ normalized.append({**message, "content": content})+ return normalized++ def _build_main_internal_messages(+ self,+ state: SessionState,+ ) -> tuple[list[dict[str, Any]], str]:+ memory_state = state.memory_state if state.current_query_text else None+ static_content = build_static_system_content(+ memory_state=memory_state,+ mid_term_summaries=state.mid_term_summaries,+ language=self.config.language,+ )+ inject_query = (+ state.current_query_text+ if self.config.input_format == "legacy" and not state.query_in_current_chunk+ else None+ )+ dynamic_content = build_dynamic_system_content(+ current_query_text=inject_query,+ memory_state=memory_state,+ include_qa_history=self.config.keep_qa_history and (+ self.config.input_format == "legacy" or self.summarizer is not None+ ),+ current_chunk_index=state.chunk_index,+ language=self.config.language,+ )+ prefix_content = "\n\n".join(+ part for part in (static_content, dynamic_content) if part+ )+ # legacy 保留旧版 Q&A History;稀疏问答和时间归一化仅用于新训练格式。+ training_history = self.config.input_format != "legacy" and self.summarizer is None+ history = state.sparse_text_messages if training_history else []+ all_messages = list(history) + list(state.current_chunk["messages"])+ if training_history:+ all_messages = self._normalize_model_timestamps(all_messages)++ if prefix_content:+ for idx in range(len(history), len(all_messages)):+ message = all_messages[idx]+ if message.get("role") != "user":+ continue+ new_message = dict(message)+ content = message.get("content")+ if isinstance(content, list):+ new_message["content"] = [+ {"type": "text", "text": prefix_content}+ ] + list(content)+ elif isinstance(content, str):+ new_message["content"] = prefix_content + "\n\n" + content+ else:+ new_message["content"] = prefix_content+ all_messages[idx] = new_message+ break++ return all_messages, prefix_content++ def _build_main_api_messages(self, state: SessionState) -> list[dict[str, Any]]:+ all_messages, _ = self._build_main_internal_messages(state)+ return [_internal_message_to_openai(message) for message in all_messages]++ def _build_cached_api_messages(+ self,+ state: SessionState,+ internal_messages: list[dict[str, Any]],+ ) -> list[dict[str, Any]]:+ # Rebuild text/prefixes, but reuse encoded frames in a bounded session cache.+ # Keep payloads out of message history and diagnostic prediction records.+ state.image_cache.retain_paths(state.current_chunk["image_paths"])+ if any(_internal_message_has_image(message) for message in internal_messages):+ state.current_chunk["api_msg_cache"] = []+ return [+ _internal_message_to_openai(message, image_cache=state.image_cache)+ for message in internal_messages+ ]++ cache = state.current_chunk["api_msg_cache"]+ chunk_msgs = state.current_chunk["messages"]+ # Incrementally convert new chunk messages and append to cache.+ # cache[i] corresponds to chunk_msgs[i] (without prefix injection).+ while len(cache) < len(chunk_msgs):+ cache.append(_internal_message_to_openai(chunk_msgs[len(cache)]))+ # internal_messages[0] has prefix injected, so always re-convert it.+ # internal_messages[1:] are identical to chunk_msgs[1:], so reuse cache.+ first_msg = _internal_message_to_openai(internal_messages[0])+ remaining = cache[1:len(internal_messages)]+ return [first_msg] + remaining++ def _build_main_http_messages(+ self,+ api_messages: list[dict[str, Any]],+ ) -> list[dict[str, Any]]:+ messages = list(api_messages)+ system_prompt = self.config.system_prompt+ if system_prompt:+ messages = [{"role": "system", "content": system_prompt}] + messages+ return messages++ # ==================== 主模型调用 ====================++ async def _call_main_model(+ self,+ inbound_payload: dict[str, Any],+ api_messages: list[dict[str, Any]],+ *,+ client: Optional[AsyncOpenAI] = None,+ model_name: Optional[str] = None,+ session_state: Optional["SessionState"] = None,+ generation_kwargs: Optional[dict[str, Any]] = None,+ http_messages: Optional[list[dict[str, Any]]] = None,+ ) -> tuple[str, Optional[dict[str, Any]], Optional[dict[str, Any]]]:+ # WebUI sends each question once; later camera frames must stay silent+ # instead of regenerating an answer from an old identity/training query.+ current_prompt = _extract_user_prompt_text(inbound_payload.get("messages") or [])+ if is_identity_question(current_prompt):+ return identity_action(current_prompt), {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}, None+ if not current_prompt and session_state is not None and is_identity_question(session_state.current_query_text or ""):+ return SILENCE_TOKEN, {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}, None+ client = client or self.main_client+ model_name = model_name or self.config.main_model+ generation_kwargs = generation_kwargs or self._main_generation_kwargs(inbound_payload)+ api_messages = http_messages or self._build_main_http_messages(api_messages)+ try:+ response = await client.chat.completions.create(+ model=model_name,+ messages=api_messages,+ **generation_kwargs,+ )+ finally:+ _file_to_data_url_cached.cache_clear()+ raw_text = response.choices[0].message.content if response.choices else ""+ usage = response.usage.model_dump() if getattr(response, "usage", None) else None+ first_action = None+ if self.config.first_action_logprob_gate:+ first_action = await self._first_action_decision(+ client=client,+ model_name=model_name,+ messages=api_messages,+ )+ return raw_text or "", usage, first_action++ async def _first_action_decision(+ self,+ *,+ client: AsyncOpenAI,+ model_name: str,+ messages: list[dict[str, Any]],+ ) -> dict[str, Any]:+ """只允许两个动作 token,贪心返回者即为首位置概率较高的动作。"""+ response = await client.chat.completions.create(+ model=model_name,+ messages=messages,+ max_tokens=1,+ temperature=0.0,+ top_p=1.0,+ logprobs=True,+ # allowed_token_ids 只约束采样;vLLM 的候选概率仍按原始全词表+ # 排序。多取少量候选,才能稳定覆盖两个已训练的动作 token。+ top_logprobs=20,+ extra_body={+ "skip_special_tokens": False,+ "greedy": True,+ "ignore_eos": True,+ "return_tokens_as_token_ids": True,+ "allowed_token_ids": [SILENCE_TOKEN_ID, RESPONSE_TOKEN_ID],+ },+ )+ token = (response.choices[0].message.content or "").strip()+ if token == SILENCE_TOKEN:+ action = "silence"+ elif token == RESPONSE_TOKEN:+ action = "response"+ else:+ raise RuntimeError(f"首动作二选一返回了非法 token: {token!r}")+ token_labels = {+ SILENCE_TOKEN: "silence",+ RESPONSE_TOKEN: "response",+ f"token_id:{SILENCE_TOKEN_ID}": "silence",+ f"token_id:{RESPONSE_TOKEN_ID}": "response",+ str(SILENCE_TOKEN_ID): "silence",+ str(RESPONSE_TOKEN_ID): "response",+ }+ token_logprob = response.choices[0].logprobs.content[0]+ # vLLM 可能只把“未选中的候选”放入 top_logprobs;实际选中的+ # token 及其概率保存在当前 content 项本身。两处合并后才能稳定+ # 得到 silence/response 的完整二选一概率。+ candidate_logprobs = [token_logprob, *token_logprob.top_logprobs]+ action_logprobs = {+ token_labels[item.token.strip()]: float(item.logprob)+ for item in candidate_logprobs+ if item.token.strip() in token_labels+ }+ # allowed_token_ids 只约束最终采样,原始全词表 Top-K 未必同时包含+ # 两个动作。对缺失动作单独强制采样一次;vLLM 返回的 selected-token+ # logprob 是施加 allowed-token mask 前的原始 logprob,可直接比较。+ action_tokens = {+ "silence": (SILENCE_TOKEN, SILENCE_TOKEN_ID),+ "response": (RESPONSE_TOKEN, RESPONSE_TOKEN_ID),+ }+ for name in ("silence", "response"):+ if name in action_logprobs:+ continue+ expected_token, token_id = action_tokens[name]+ forced = await client.chat.completions.create(+ model=model_name,+ messages=messages,+ max_tokens=1,+ temperature=0.0,+ top_p=1.0,+ logprobs=True,+ top_logprobs=0,+ extra_body={+ "skip_special_tokens": False,+ "greedy": True,+ "ignore_eos": True,+ "return_tokens_as_token_ids": True,+ "allowed_token_ids": [token_id],+ },+ )+ forced_token = (forced.choices[0].message.content or "").strip()+ if forced_token != expected_token:+ raise RuntimeError(+ f"强制读取{name}概率时返回非法 token: {forced_token!r}"+ )+ action_logprobs[name] = float(+ forced.choices[0].logprobs.content[0].logprob+ )+ if set(action_logprobs) != {"silence", "response"}:+ raise RuntimeError(f"首动作概率缺少候选 token: {action_logprobs!r}")+ weights = {name: math.exp(value) for name, value in action_logprobs.items()}+ normalizer = sum(weights.values())+ probabilities = {+ name: round(value / normalizer, 8) for name, value in weights.items()+ }+ action = max(("silence", "response"), key=probabilities.__getitem__)+ return {+ "action": action,+ "selected_token": SILENCE_TOKEN if action == "silence" else RESPONSE_TOKEN,+ "method": "restricted_greedy_argmax",+ "probabilities": probabilities,+ "logprobs": action_logprobs,+ }++ def _main_generation_kwargs(self, inbound_payload: dict[str, Any]) -> dict[str, Any]:+ # 默认忽略 WebUI 请求里的采样参数,统一使用 adapter 启动参数(与离线 infer 对齐)。+ extra_body = _extract_extra_body(inbound_payload)+ extra_body.setdefault("skip_special_tokens", False)+ extra_body.setdefault("greedy", False)+ if self.config.honor_inbound_generation_params:+ extra_body.setdefault("top_k", self.config.main_top_k)+ extra_body.setdefault("repetition_penalty", self.config.main_repetition_penalty)+ return {+ "max_tokens": inbound_payload.get("max_tokens", self.config.main_max_tokens),+ "temperature": inbound_payload.get("temperature", self.config.main_temperature),+ "top_p": inbound_payload.get("top_p", self.config.main_top_p),+ "presence_penalty": inbound_payload.get("presence_penalty", self.config.main_presence_penalty),+ "extra_body": extra_body,+ }++ extra_body["top_k"] = self.config.main_top_k+ extra_body["repetition_penalty"] = self.config.main_repetition_penalty+ return {+ "max_tokens": self.config.main_max_tokens,+ "temperature": self.config.main_temperature,+ "top_p": self.config.main_top_p,+ "presence_penalty": self.config.main_presence_penalty,+ "extra_body": extra_body,+ }diff --git a/Web_Inference/webinfer/adapter_request.py b/Web_Inference/webinfer/adapter_request.pynew file mode 100644index 0000000..5e5545a--- /dev/null+++ b/Web_Inference/webinfer/adapter_request.py@@ -0,0 +1,442 @@+# -*- coding: utf-8 -*-+"""HTTP 请求解析、图片编码与 OpenAI 响应构造。++数据流:+ WebUI 每秒发来一个 OpenAI chat 请求(messages 里带一张 base64 JPEG + 可选的用户问题)+ -> 这里解析出 session_id / 图片引用 / 时间戳 / 用户问题;+ adapter 把内部 {"type": "image", "image": 本地路径} 消息转换回 OpenAI 格式时,+ -> 这里读取图片、按短边 480 + max_pixels 等比缩放后重新编码成 data URL 发给 vLLM;+ 推理结束后+ -> 这里把结果包装成标准 chat.completion 响应(附带 streamingharness 调试字段)。+"""++from __future__ import annotations++import base64+import functools+import io+import json+import re+import time+import uuid+from pathlib import Path+from typing import Any, Optional++from aiohttp import web+from PIL import Image++from adapter_common import LOGGER, TIME_RANGE_RE, _normalize_time_range_text+from adapter_image_cache import ImageDataUrlCache+++def _safe_session_id(session_id: str) -> str:+ safe = re.sub(r"[^A-Za-z0-9_.-]+", "_", str(session_id or "default"))+ return safe.strip("._")[:120] or "default"+++def _request_session_id(request: web.Request, payload: dict[str, Any]) -> str:+ # WebUI 在 header 里带 x-streaming-session,每个浏览器会话对应 adapter 里一个独立的流式状态。+ return (+ request.headers.get("x-streaming-session")+ or request.headers.get("x-session-id")+ or str(payload.get("user") or "")+ or "default"+ )+++def _extract_time_range_from_request(+ request: web.Request,+ payload: dict[str, Any],+) -> Optional[str]:+ candidates = (+ request.headers.get("x-frame-time-range"),+ request.headers.get("x-streaming-time-range"),+ str(payload.get("x_frame_time_range") or ""),+ str(payload.get("frame_time_range") or ""),+ )+ for candidate in candidates:+ normalized = _normalize_time_range_text(candidate)+ if normalized:+ return normalized+ return None+++async def _read_json(request: web.Request) -> dict[str, Any]:+ try:+ payload = await request.json()+ except json.JSONDecodeError as exc:+ raise web.HTTPBadRequest(text=f"invalid JSON: {exc}") from exc+ if not isinstance(payload, dict):+ raise web.HTTPBadRequest(text="JSON body must be an object")+ return payload+++def _extract_first_image_ref(+ messages: list[dict[str, Any]],+ request: web.Request,+ payload: dict[str, Any],+) -> Optional[dict[str, str]]:+ local_path = _extract_local_image_path_from_request(request, payload)+ if local_path:+ return {"kind": "path", "value": local_path}++ for message in reversed(messages):+ content = message.get("content")+ if not isinstance(content, list):+ continue+ for item in content:+ if not isinstance(item, dict) or item.get("type") != "image_url":+ continue+ image_url = item.get("image_url")+ if isinstance(image_url, dict):+ url = image_url.get("url")+ else:+ url = image_url+ if isinstance(url, str) and url:+ file_path = _file_url_to_path(url)+ if file_path:+ return {"kind": "path", "value": file_path}+ return {"kind": "data_url", "value": url}+ return None+++def _extract_all_image_refs(+ messages: list[dict[str, Any]],+ request: web.Request,+ payload: dict[str, Any],+) -> list[dict[str, str]]:+ """Extract all image references from the request (supports batch frames)."""+ refs: list[dict[str, str]] = []++ local_path = _extract_local_image_path_from_request(request, payload)+ if local_path:+ refs.append({"kind": "path", "value": local_path})++ for message in reversed(messages):+ content = message.get("content")+ if not isinstance(content, list):+ continue+ for item in content:+ if not isinstance(item, dict) or item.get("type") != "image_url":+ continue+ image_url = item.get("image_url")+ if isinstance(image_url, dict):+ url = image_url.get("url")+ else:+ url = image_url+ if isinstance(url, str) and url:+ file_path = _file_url_to_path(url)+ if file_path:+ refs.append({"kind": "path", "value": file_path})+ else:+ refs.append({"kind": "data_url", "value": url})+ if refs:+ break+ return refs+++def _extract_time_ranges_from_request(+ request: web.Request,+ payload: dict[str, Any],+) -> list[str]:+ """Extract multiple time ranges from request (for batch frames)."""+ ranges = payload.get("frame_time_ranges")+ if isinstance(ranges, list) and ranges:+ parsed: list[str] = []+ for r in ranges:+ normalized = _normalize_time_range_text(r)+ if normalized:+ parsed.append(normalized)+ if parsed:+ return parsed++ single = _extract_time_range_from_request(request, payload)+ return [single] if single else []+++def _extract_local_image_path_from_request(+ request: web.Request,+ payload: dict[str, Any],+) -> Optional[str]:+ candidates = (+ request.headers.get("x-local-image-path"),+ request.headers.get("x-frame-image-path"),+ str(payload.get("x_local_image_path") or ""),+ str(payload.get("local_image_path") or ""),+ str(payload.get("frame_image_path") or ""),+ )+ for candidate in candidates:+ candidate = (candidate or "").strip()+ if candidate:+ return candidate+ return None+++def _file_url_to_path(url: str) -> Optional[str]:+ if not url.startswith("file://"):+ return None+ from urllib.parse import unquote, urlparse++ parsed = urlparse(url)+ if parsed.netloc not in {"", "localhost"}:+ return None+ return unquote(parsed.path)+++def _extract_user_prompt_text(messages: list[dict[str, Any]]) -> str:+ for message in reversed(messages):+ if message.get("role") != "user":+ continue+ content = message.get("content")+ if isinstance(content, str):+ return content.strip()+ if isinstance(content, list):+ text_parts = [+ str(item.get("text", "")).strip()+ for item in content+ if isinstance(item, dict)+ and item.get("type") == "text"+ and str(item.get("text", "")).strip()+ ]+ return "\n".join(text_parts).strip()+ return ""+++def _extract_time_range_from_text(text: str) -> Optional[str]:+ return _normalize_time_range_text(text)+++def _strip_time_range_from_text(text: str) -> str:+ lines = []+ for line in (text or "").splitlines():+ stripped = line.strip()+ if TIME_RANGE_RE.fullmatch(stripped):+ continue+ lines.append(line)+ return "\n".join(lines).strip()+++def _format_seconds(value: float) -> str:+ if abs(value - round(value)) < 1e-6:+ return f"{int(round(value))}s"+ return f"{value:.3f}".rstrip("0").rstrip(".") + "s"+++def _internal_message_has_image(message: dict[str, Any]) -> bool:+ content = message.get("content")+ if not isinstance(content, list):+ return False+ return any(isinstance(item, dict) and item.get("type") == "image" for item in content)+++def _internal_message_to_openai(+ message: dict[str, Any], image_cache: Optional[ImageDataUrlCache] = None,+) -> dict[str, Any]:+ # History stores paths; only the bounded session cache retains encoded frames.+ content = message.get("content")+ if not isinstance(content, list):+ return {"role": message.get("role", "user"), "content": content or ""}++ converted: list[dict[str, Any]] = []+ for item in content:+ if not isinstance(item, dict):+ continue+ if item.get("type") == "image":+ max_pixels = int(item.get("max_pixels") or 0)+ resize_short_edge = int(item.get("resize_short_edge") or 0)+ converted.append(+ {+ "type": "image_url",+ "image_url": {"url": _file_to_data_url(+ item["image"],+ max_pixels=max_pixels,+ resize_short_edge=resize_short_edge,+ image_cache=image_cache,+ )},+ }+ )+ elif item.get("type") == "text":+ converted.append({"type": "text", "text": str(item.get("text", ""))})+ else:+ converted.append(item)+ return {"role": message.get("role", "user"), "content": converted}+++def _file_to_data_url(+ path: str,+ max_pixels: int = 0,+ resize_short_edge: int = 0,+ image_cache: Optional[ImageDataUrlCache] = None,+) -> str:+ if path.startswith("data:"):+ return _resize_data_url_if_needed(path, max_pixels, resize_short_edge)+ if image_cache is not None:+ return image_cache.encode(path, max_pixels, resize_short_edge, _encode_file_to_data_url)+ return _file_to_data_url_cached(path, max_pixels, resize_short_edge)++[email protected]_cache(maxsize=128)+def _file_to_data_url_cached(+ path: str,+ max_pixels: int = 0,+ resize_short_edge: int = 0,+) -> str:+ # Legacy callers retain only a temporary cache, cleared after model calls.+ return _encode_file_to_data_url(path, max_pixels, resize_short_edge)+++def _encode_file_to_data_url(path: str, max_pixels: int, resize_short_edge: int) -> str:+ ext = Path(path).suffix.lower()+ mime_type = {+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".png": "image/png",+ ".webp": "image/webp",+ ".gif": "image/gif",+ ".bmp": "image/bmp",+ }.get(ext, "image/jpeg")++ if max_pixels > 0 or resize_short_edge > 0:+ try:+ with Image.open(path) as image:+ image.load()+ resized = _resize_image_if_needed(image, max_pixels, resize_short_edge)+ if resized is not None:+ return _image_to_data_url(resized, mime_type)+ except Exception as exc:+ LOGGER.warning(+ "failed to resize image %s for max_pixels=%s short_edge=%s: %s",+ path, max_pixels, resize_short_edge, exc,+ )++ with open(path, "rb") as file_obj:+ encoded = base64.b64encode(file_obj.read()).decode("ascii")+ return f"data:{mime_type};base64,{encoded}"+++def _resize_data_url_if_needed(+ data_url: str,+ max_pixels: int = 0,+ resize_short_edge: int = 0,+) -> str:+ if max_pixels <= 0 and resize_short_edge <= 0:+ return data_url+ match = re.match(r"^data:(image/[^;]+);base64,(.+)$", data_url, re.DOTALL)+ if not match:+ return data_url+ mime_type, encoded = match.groups()+ try:+ with Image.open(io.BytesIO(base64.b64decode(encoded))) as image:+ image.load()+ resized = _resize_image_if_needed(image, max_pixels, resize_short_edge)+ if resized is None:+ return data_url+ return _image_to_data_url(resized, mime_type)+ except Exception as exc:+ LOGGER.warning(+ "failed to resize data URL image for max_pixels=%s short_edge=%s: %s",+ max_pixels, resize_short_edge, exc,+ )+ return data_url+++def _resize_image_if_needed(+ image: Image.Image,+ max_pixels: int,+ resize_short_edge: int = 0,+) -> Optional[Image.Image]:+ # 仅当短边超过上限时等比缩小;小图不放大。随后按 max_pixels 限制总像素。+ width, height = image.size+ new_width, new_height = width, height+ if resize_short_edge > 0 and min(width, height) > resize_short_edge:+ scale = resize_short_edge / min(width, height)+ new_width = max(1, round(width * scale))+ new_height = max(1, round(height * scale))+ if max_pixels > 0 and new_width * new_height > max_pixels:+ scale = (max_pixels / (new_width * new_height)) ** 0.5+ new_width = max(1, int(new_width * scale))+ new_height = max(1, int(new_height * scale))+ if (new_width, new_height) == (width, height):+ return None+ return image.resize((new_width, new_height), Image.LANCZOS)+++def _image_to_data_url(image: Image.Image, mime_type: str) -> str:+ buffer = io.BytesIO()+ if mime_type == "image/png":+ image.save(buffer, format="PNG")+ elif mime_type == "image/webp":+ image.save(buffer, format="WEBP")+ else:+ mime_type = "image/jpeg"+ if image.mode not in ("RGB", "L"):+ image = image.convert("RGB")+ image.save(buffer, format="JPEG")+ encoded = base64.b64encode(buffer.getvalue()).decode("ascii")+ return f"data:{mime_type};base64,{encoded}"+++def _extract_extra_body(payload: dict[str, Any]) -> dict[str, Any]:+ keys = (+ "skip_special_tokens",+ "top_k",+ "repetition_penalty",+ "min_p",+ "stop_token_ids",+ "include_stop_str_in_output",+ )+ return {key: payload[key] for key in keys if key in payload}+++def _chat_completion_response(+ model: str,+ content: str,+ usage: Optional[dict[str, Any]],+ raw_model: str,+ raw_text: str,+) -> dict[str, Any]:+ completion_id = f"chatcmpl-{uuid.uuid4().hex}"+ response = {+ "id": completion_id,+ "object": "chat.completion",+ "created": int(time.time()),+ "model": model,+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": content},+ "finish_reason": "stop",+ }+ ],+ "usage": usage or {+ "prompt_tokens": 0,+ "completion_tokens": 0,+ "total_tokens": 0,+ },+ }+ response["streamingharness"] = {+ "main_model": raw_model,+ "raw_content": raw_text,+ }+ return response+++def _openai_error_response(message: str, status: int) -> web.Response:+ return web.json_response(+ {+ "error": {+ "message": message,+ "type": "streaming_infer_adapter_error",+ "param": None,+ "code": None,+ }+ },+ status=status,+ )+++def _short(text: str, limit: int) -> str:+ text = " ".join((text or "").split())+ if len(text) <= limit:+ return text+ return text[: limit - 3] + "..."diff --git a/Web_Inference/webinfer/adapter_session.py b/Web_Inference/webinfer/adapter_session.pynew file mode 100644index 0000000..ac21ce3--- /dev/null+++ b/Web_Inference/webinfer/adapter_session.py@@ -0,0 +1,518 @@+# -*- coding: utf-8 -*-+"""会话状态与会话级 I/O。++一个浏览器会话 = 一个 SessionState:+ - current_chunk:当前视觉窗口(最近 <= chunk 帧的 messages / 帧路径 / 时间戳);+ - sparse_text_messages:滑出窗口的稀疏问答文本(旧帧图片不再发送);+ - predictions:每一轮的输入/输出记录,会话结束或每轮异步写到 save_root 下的 output_* 目录。+SessionMixin 负责:创建/过期/淘汰会话、把 WebUI 发来的 base64 帧落盘、写结果 JSON 与调试快照。+"""++from __future__ import annotations++import asyncio+import base64+import copy+import json+import os+import re+import time+from dataclasses import dataclass, field+from datetime import datetime+from pathlib import Path+from typing import Any, Optional++from aiohttp import web++from adapter_common import (+ LOGGER,+ archive_chunk_response_records,+ derive_light_out_dir,+ reset_chunk_state,+ sanitize_output_name,+)+from adapter_request import _file_to_data_url_cached, _safe_session_id+from adapter_image_cache import ImageDataUrlCache+++@dataclass+class SessionState:+ session_id: str+ lock: asyncio.Lock = field(default_factory=asyncio.Lock)+ image_cache: ImageDataUrlCache = field(default_factory=ImageDataUrlCache, repr=False)+ frame_count: int = 0+ turn_count: int = 0+ chunk_index: int = 1+ current_chunk: dict[str, Any] = field(default_factory=reset_chunk_state)+ sparse_text_messages: list[dict[str, str]] = field(default_factory=list)+ memory_state: dict[str, Any] = field(+ default_factory=lambda: {"long_term_memory": "", "qa_history": []}+ )+ current_query_text: Optional[str] = None+ query_start_time: Optional[str] = None+ query_in_current_chunk: bool = False+ mid_term_summaries: list[dict[str, Any]] = field(default_factory=list)+ mid_term_history: list[dict[str, Any]] = field(default_factory=list)+ long_term_history: list[dict[str, Any]] = field(default_factory=list)+ long_term_compression_next_index: int = 1+ async_summary_segment: dict[str, Any] = field(default_factory=reset_chunk_state)+ async_next_summary_target_turns: int = 0+ async_next_summary_index: int = 1+ async_pending_summary_jobs: list[dict[str, Any]] = field(default_factory=list)+ predictions: list[dict[str, Any]] = field(default_factory=list)+ session_started_at: float = field(default_factory=time.time)+ output_path: Optional[Path] = None+ light_output_path: Optional[Path] = None+ debug_input_dir: Optional[Path] = None+ session_out_dir: Optional[str] = None+ session_light_out_dir: Optional[str] = None+ session_frame_dir: Optional[Path] = None+ session_frame_counter: int = 0+ chunk_start_input_saved: set[int] = field(default_factory=set)+ last_access: float = field(default_factory=time.time)+ _pending_qa_archive: Optional[tuple[str, Optional[str]]] = field(default=None, repr=False)+ _pending_write_task: Optional[asyncio.Task] = field(default=None, repr=False)+++class SessionMixin:+ """StreamingInferAdapter 的会话管理与落盘部分(依赖 self.config / self.sessions)。"""++ # ==================== 会话生命周期 ====================++ def get_session(self, session_id: str) -> SessionState:+ session_id = _safe_session_id(session_id or "default")+ state = self.sessions.get(session_id)+ if state is None:+ self._cleanup_expired_sessions()+ self._enforce_max_active_sessions(incoming_session_id=session_id)+ state = SessionState(session_id=session_id)+ if self.config.per_session_dirs and self.config.save_root:+ self._init_session_dirs(state)+ state.output_path = self._session_output_path(state, light=False)+ state.light_output_path = self._session_output_path(state, light=True)+ state.debug_input_dir = self._session_debug_input_dir(state)+ state.async_next_summary_target_turns = self._async_first_summary_turns()+ # Per-session frame directory+ frame_dir = Path(self.config.frame_save_dir) / session_id+ frame_dir.mkdir(parents=True, exist_ok=True)+ state.session_frame_dir = frame_dir+ self.sessions[session_id] = state+ LOGGER.info(+ "Created session %s (output=%s light=%s debug_input=%s frames=%s)",+ session_id,+ state.output_path,+ state.light_output_path,+ state.debug_input_dir,+ state.session_frame_dir,+ )+ state.last_access = time.time()+ return state++ def _drop_session_state(self, session_id: str, state: SessionState, reason: str) -> None:+ state.image_cache.clear()+ for job in state.async_pending_summary_jobs:+ job["task"].cancel()+ state.current_chunk = reset_chunk_state()+ state.sparse_text_messages.clear()+ state.async_summary_segment = reset_chunk_state()+ state.async_pending_summary_jobs.clear()+ state.predictions.clear()+ state.mid_term_summaries.clear()+ state.mid_term_history.clear()+ state.long_term_history.clear()+ state.memory_state = {"long_term_memory": "", "qa_history": []}+ _file_to_data_url_cached.cache_clear()+ LOGGER.info("Dropped session %s from memory (%s)", session_id, reason)++ def _enforce_max_active_sessions(self, incoming_session_id: str = "") -> None:+ limit = int(self.config.max_active_sessions or 0)+ if limit <= 0:+ return+ while len(self.sessions) >= limit:+ candidates = [+ (sid, state)+ for sid, state in self.sessions.items()+ if sid != incoming_session_id+ ]+ if not candidates:+ return+ sid, state = min(candidates, key=lambda item: item[1].last_access)+ self.sessions.pop(sid, None)+ self._drop_session_state(sid, state, "max_active_sessions")++ def _cleanup_expired_sessions(self) -> list[SessionState]:+ now = time.time()+ timeout = self.config.session_timeout_seconds+ expired = [+ sid for sid, s in self.sessions.items()+ if now - s.last_access > timeout+ ]+ expired_states = []+ for sid in expired:+ state = self.sessions.pop(sid, None)+ if state is not None:+ self._drop_session_state(sid, state, "session_timeout")+ expired_states.append(state)+ LOGGER.info("Expired session %s (idle %.0fs)", sid, now - state.last_access)+ return expired_states++ async def _session_cleanup_loop(self) -> None:+ while True:+ await asyncio.sleep(300)+ try:+ expired_states = self._cleanup_expired_sessions()+ for state in expired_states:+ await self._flush_session_outputs(state)+ except Exception:+ LOGGER.exception("session cleanup error")++ def start_background_tasks(self) -> None:+ if self._cleanup_task is None:+ self._cleanup_task = asyncio.ensure_future(self._session_cleanup_loop())++ def _init_session_dirs(self, state: SessionState) -> None:+ """Create per-session timestamped output/input directories."""+ session_ts = datetime.fromtimestamp(state.session_started_at).strftime("%Y%m%d_%H%M%S")+ model_name = self.config.output_model_name+ save_root = self.config.save_root++ state.session_out_dir = os.path.join(save_root, f"output_{session_ts}_{model_name}")+ state.session_light_out_dir = derive_light_out_dir(state.session_out_dir)++ Path(state.session_out_dir).mkdir(parents=True, exist_ok=True)+ Path(state.session_light_out_dir).mkdir(parents=True, exist_ok=True)++ if self.config.save_debug_inputs:+ state.debug_input_dir = Path(os.path.join(save_root, f"input_{session_ts}_{model_name}"))+ state.debug_input_dir.mkdir(parents=True, exist_ok=True)++ # ==================== 结果 / 调试文件写入 ====================++ def _session_output_path(self, state: SessionState, light: bool) -> Optional[Path]:+ if light:+ root = state.session_light_out_dir or self.config.light_out_dir+ else:+ root = state.session_out_dir or self.config.out_dir+ if not root:+ return None+ safe_session = sanitize_output_name(state.session_id)+ return Path(root) / "live" / f"{safe_session}.json"++ def _session_debug_input_dir(self, state: SessionState) -> Optional[Path]:+ if state.debug_input_dir:+ return state.debug_input_dir+ if not self.config.debug_input_dir:+ return None+ return Path(self.config.debug_input_dir)++ def _session_sample_data(self, state: SessionState) -> dict[str, Any]:+ return {+ "task_type": "live",+ "session_id": state.session_id,+ "adapter_model": self.config.adapter_model,+ "main_model": self.config.main_model,+ "main_api_base": self.config.main_api_base,+ "summarizer_model": self.config.summarizer_model,+ "summarizer_api_base": self.config.summarizer_api_base,+ "longterm_model": self.config.longterm_model,+ "longterm_api_base": self.config.longterm_api_base,+ "started_at": datetime.fromtimestamp(state.session_started_at).isoformat(+ timespec="seconds"+ ),+ }++ def _memory_trace(self, state: SessionState) -> dict[str, Any]:+ return {+ "mid_term_summaries": list(state.mid_term_history),+ "long_term_history": list(state.long_term_history),+ "qa_history": list(state.memory_state.get("qa_history", [])),+ "long_term_memory": state.memory_state.get("long_term_memory", ""),+ }++ def _write_json_file(self, path: Path, obj: dict[str, Any]) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp_path = path.with_suffix(path.suffix + ".tmp")+ with open(tmp_path, "w", encoding="utf-8") as file_obj:+ json.dump(obj, file_obj, ensure_ascii=False, indent=2)+ file_obj.flush()+ os.fsync(file_obj.fileno())+ os.replace(tmp_path, path)++ def _light_predictions(+ self,+ predictions: list[dict[str, Any]],+ ) -> list[dict[str, Any]]:+ light_keys = (+ "turn",+ "time_range",+ "query",+ "prediction",+ "action_prediction",+ "first_action_decision",+ "total_time",+ "inference_time",+ "fourb_mid_term_inference_time",+ "fourb_long_term_inference_time",+ "ground_truth",+ )+ return [+ {key: prediction[key] for key in light_keys if key in prediction}+ for prediction in predictions+ ]++ @staticmethod+ def _strip_base64_images(obj: Any) -> tuple[Any, dict[str, str]]:+ """Recursively strip inline base64 image data from an object.++ Returns a (stripped_obj, images_dict) tuple where images_dict maps+ placeholder keys to the original base64 strings.+ """+ images: dict[str, str] = {}+ counter = [0]++ def _strip(node: Any) -> Any:+ if isinstance(node, str):+ if node.startswith("data:image/") and len(node) > 200:+ key = f"__image_{counter[0]}__"+ counter[0] += 1+ images[key] = node+ return key+ return node+ if isinstance(node, list):+ return [_strip(item) for item in node]+ if isinstance(node, dict):+ return {k: _strip(v) for k, v in node.items()}+ return node++ stripped = _strip(obj)+ return stripped, images++ def _write_session_outputs_sync(+ self,+ output_path: Optional[Path],+ light_output_path: Optional[Path],+ full_result: Optional[dict[str, Any]],+ light_result: Optional[dict[str, Any]],+ ) -> None:+ if light_output_path and light_result:+ self._write_json_file(light_output_path, light_result)+ if output_path and full_result:+ stripped_result, images = self._strip_base64_images(full_result)+ self._write_json_file(output_path, stripped_result)+ if images:+ images_path = output_path.with_suffix(".images.json")+ self._write_json_file(images_path, images)++ def _write_session_outputs(self, state: SessionState) -> None:+ total_time = time.time() - state.session_started_at+ output_path = state.output_path+ light_output_path = state.light_output_path+ if not output_path and not light_output_path:+ return+ predictions_snapshot = copy.deepcopy(state.predictions)+ sample_data = self._session_sample_data(state)+ memory_trace = copy.deepcopy(self._memory_trace(state))+ full_result = None+ light_result = None+ if output_path:+ full_result = {+ "sample_data": sample_data,+ "total_time": total_time,+ "total_turns": len(predictions_snapshot),+ "predictions": predictions_snapshot,+ "memory": memory_trace,+ }+ if light_output_path:+ light_result = {+ "sample_data": sample_data,+ "total_time": total_time,+ "total_turns": len(predictions_snapshot),+ "predictions": self._light_predictions(predictions_snapshot),+ "memory": memory_trace,+ }+ if state._pending_write_task and not state._pending_write_task.done():+ state._pending_write_task.cancel()+ task = asyncio.ensure_future(+ asyncio.to_thread(+ self._write_session_outputs_sync,+ output_path,+ light_output_path,+ full_result,+ light_result,+ )+ )+ task.add_done_callback(self._on_write_task_done)+ state._pending_write_task = task++ @staticmethod+ def _on_write_task_done(task: asyncio.Task) -> None:+ if task.cancelled():+ return+ exc = task.exception()+ if exc is not None:+ LOGGER.error("session output write failed: %s", exc, exc_info=exc)++ async def _flush_session_outputs(self, state: SessionState) -> None:+ """Write final session outputs synchronously at session end."""+ self._execute_pending_qa_archive(state)+ if self.config.keep_qa_history and state.current_query_text:+ archive_chunk_response_records(+ state.current_chunk,+ state.memory_state,+ state.current_query_text,+ state.query_start_time,+ chunk_index=state.chunk_index,+ )+ total_time = time.time() - state.session_started_at+ output_path = state.output_path+ light_output_path = state.light_output_path+ if not output_path and not light_output_path:+ return+ if not state.predictions:+ return+ sample_data = self._session_sample_data(state)+ memory_trace = self._memory_trace(state)+ full_result = None+ light_result = None+ if output_path:+ full_result = {+ "sample_data": sample_data,+ "total_time": total_time,+ "total_turns": len(state.predictions),+ "predictions": state.predictions,+ "memory": memory_trace,+ }+ if light_output_path:+ light_result = {+ "sample_data": sample_data,+ "total_time": total_time,+ "total_turns": len(state.predictions),+ "predictions": self._light_predictions(state.predictions),+ "memory": memory_trace,+ }+ await asyncio.to_thread(+ self._write_session_outputs_sync,+ output_path,+ light_output_path,+ full_result,+ light_result,+ )+ LOGGER.info(+ "[%s] final session output written (%d turns)",+ state.session_id,+ len(state.predictions),+ )++ def _save_live_debug_input(+ self,+ state: SessionState,+ record: dict[str, Any],+ stem: str,+ ) -> Optional[str]:+ debug_dir = state.debug_input_dir or self.config.debug_input_dir+ if not debug_dir:+ return None+ path = (+ Path(debug_dir)+ / f"{sanitize_output_name(state.session_id)}__{stem}.json"+ )+ record = copy.deepcopy(record)+ record.setdefault("saved_at", datetime.now().isoformat(timespec="seconds"))+ record.setdefault("session_id", state.session_id)+ self._write_json_file(path, record)+ return str(path)++ def _maybe_save_chunk_start_model_input(+ self,+ state: SessionState,+ turn_count: int,+ time_range: str,+ model_input_record: dict[str, Any],+ ) -> Optional[str]:+ if not (state.debug_input_dir or self.config.debug_input_dir):+ return None+ if state.chunk_index in state.chunk_start_input_saved:+ return None+ record = copy.deepcopy(model_input_record)+ record["stage"] = "main_8b_chunk_start"+ record["turn"] = turn_count+ record["time_range"] = time_range+ path = self._save_live_debug_input(+ state,+ record,+ f"chunk_{state.chunk_index:04d}__turn_{turn_count:04d}",+ )+ state.chunk_start_input_saved.add(state.chunk_index)+ return path++ def _save_summarizer_debug_input(+ self,+ state: SessionState,+ stage: str,+ index: int,+ record: Optional[dict[str, Any]],+ ) -> Optional[str]:+ if not record:+ return None+ return self._save_live_debug_input(+ state,+ record,+ f"{stage}__{index:04d}",+ )++ # ==================== 帧落盘 ====================++ def _resolve_frame_ref(+ self,+ image_ref: dict[str, str],+ state: "SessionState",+ ) -> str:+ if image_ref.get("kind") == "path":+ return str(self._validate_local_image_path(image_ref.get("value", "")))+ if image_ref.get("kind") == "data_url":+ return self._save_base64_frame(image_ref.get("value", ""), state)+ raise web.HTTPBadRequest(text="unsupported image reference kind")++ def _save_base64_frame(self, data_url: str, state: "SessionState") -> str:+ # WebUI 的每帧 base64 JPEG 先落盘为 frame_000001.jpg ...,之后会话内只保存路径。+ match = re.match(r"^data:(image/[\w.+-]+);base64,(.+)$", data_url, re.DOTALL)+ if not match:+ raise web.HTTPBadRequest(text="invalid data URL format")+ state.session_frame_counter += 1+ mime_type, encoded = match.groups()+ suffix = {+ "image/jpeg": ".jpg",+ "image/jpg": ".jpg",+ "image/png": ".png",+ "image/webp": ".webp",+ "image/bmp": ".bmp",+ }.get(mime_type.lower(), ".jpg")+ frame_dir = state.session_frame_dir or (Path(self.config.frame_save_dir) / state.session_id)+ frame_dir.mkdir(parents=True, exist_ok=True)+ frame_path = frame_dir / f"frame_{state.session_frame_counter:06d}{suffix}"+ try:+ frame_path.write_bytes(base64.b64decode(encoded))+ except Exception as exc:+ raise web.HTTPBadRequest(text=f"invalid base64 image data: {exc}") from exc+ return str(frame_path)++ def _validate_local_image_path(self, raw_path: str) -> Path:+ if not self.config.allowed_local_image_roots:+ raise web.HTTPBadRequest(text="local image paths are disabled")++ path = Path(raw_path).expanduser().resolve()+ if not path.is_file():+ raise web.HTTPBadRequest(text=f"local image path does not exist: {path}")+ if path.suffix.lower() not in {".jpg", ".jpeg", ".png", ".webp", ".bmp"}:+ raise web.HTTPBadRequest(text=f"unsupported local image extension: {path.suffix}")++ for root in self.config.allowed_local_image_roots:+ root_path = Path(root).expanduser().resolve()+ try:+ path.relative_to(root_path)+ return path+ except ValueError:+ continue++ allowed = ", ".join(self.config.allowed_local_image_roots)+ raise web.HTTPBadRequest(text=f"local image path is outside allowed roots: {allowed}")diff --git a/Web_Inference/webinfer/adapter_summary.py b/Web_Inference/webinfer/adapter_summary.pynew file mode 100644index 0000000..2b911c0--- /dev/null+++ b/Web_Inference/webinfer/adapter_summary.py@@ -0,0 +1,306 @@+# -*- coding: utf-8 -*-+"""可选的摘要记忆。++仅在 ENABLE_SUMMARIZER=1(需配合 legacy 输入格式)时生效,默认真机推理不走这里:+ - 中期摘要:每个窗口(chunk)结束时,用 4B summary 模型把该窗口关键帧总结成一段文字;+ - 异步摘要:提前 async_summary_lead_frames 轮在后台线程提交摘要,窗口切换时再等待提交结果;+ - 长期记忆:攒够 compress_every_n_chunks 段中期摘要后,压缩追加到 long_term_memory。+"""++from __future__ import annotations++import asyncio+import copy+import time+from typing import Any, Optional++from adapter_common import (+ LOGGER,+ _compute_chunk_frame_range,+ _get_response_frame_indices,+ reset_chunk_state,+)+from adapter_request import _file_to_data_url_cached+from adapter_session import SessionState+++class SummaryMixin:+ """StreamingInferAdapter 的摘要记忆部分(依赖 self.config / self.summarizer)。"""++ async def _flush_chunk(self, state: SessionState, use_async_summary: bool = False) -> None:+ current_chunk = state.current_chunk+ if current_chunk["frame_count"] <= 0:+ return++ _file_to_data_url_cached.cache_clear()++ if self.summarizer is not None and use_async_summary:+ await self._commit_required_async_summaries(+ state, state.turn_count, non_blocking=False,+ )+ elif self.summarizer is not None:+ mid_term_entry, summary_time = await asyncio.to_thread(+ self._build_mid_term_summary_entry,+ state,+ copy.deepcopy(current_chunk),+ )+ state.mid_term_summaries.append(mid_term_entry)+ state.mid_term_history.append(mid_term_entry)+ LOGGER.info(+ "[%s] chunk=%d range=%s mid-summary %.3fs (%d/%d buffered)",+ state.session_id,+ mid_term_entry["chunk_index"],+ mid_term_entry["frame_range"],+ summary_time,+ len(state.mid_term_summaries),+ self.config.compress_every_n_chunks,+ )+ if len(state.mid_term_summaries) >= self.config.compress_every_n_chunks:+ await asyncio.to_thread(self._compress_mid_terms, state)++ def _build_mid_term_summary_entry(+ self,+ state: SessionState,+ chunk_snapshot: dict[str, Any],+ chunk_index: Optional[int] = None,+ current_query_text: Optional[str] = None,+ query_start_time: Optional[str] = None,+ ) -> tuple[dict[str, Any], float]:+ assert self.summarizer is not None+ resolved_chunk_index = chunk_index if chunk_index is not None else state.chunk_index+ resolved_query_text = current_query_text if current_query_text is not None else (state.current_query_text or "")+ resolved_query_start_time = query_start_time if query_start_time is not None else state.query_start_time+ frame_range = _compute_chunk_frame_range(chunk_snapshot)+ key_frames = self.summarizer.select_key_frames(+ chunk_snapshot["image_paths"],+ chunk_snapshot["frame_time_ranges"],+ _get_response_frame_indices(chunk_snapshot["messages"]),+ chunk_snapshot["summarizer_frame_cache"],+ )+ start = time.time()+ summary, mid_term_debug_input = self.summarizer.generate_detailed_summary(+ resolved_chunk_index,+ frame_range,+ key_frames,+ chunk_snapshot["frame_count"],+ resolved_query_text,+ )+ elapsed = time.time() - start+ debug_input_path = self._save_summarizer_debug_input(+ state,+ "mid_term",+ resolved_chunk_index,+ copy.deepcopy(mid_term_debug_input),+ )+ entry = {+ "chunk_index": resolved_chunk_index,+ "frame_range": frame_range,+ "query": resolved_query_text,+ "query_start_time": resolved_query_start_time,+ "summary_text": summary,+ "frame_count": chunk_snapshot["frame_count"],+ "key_frame_count": len(key_frames),+ "inference_time": round(elapsed, 3),+ "compressed_to_long_term": False,+ }+ if debug_input_path:+ entry["debug_input_path"] = debug_input_path+ return entry, elapsed++ def _compress_mid_terms(self, state: SessionState) -> None:+ assert self.summarizer is not None+ batch_index = state.long_term_compression_next_index+ state.long_term_compression_next_index += 1+ source_chunk_indices = [+ entry["chunk_index"] for entry in state.mid_term_summaries+ ]+ source_frame_ranges = [+ entry["frame_range"] for entry in state.mid_term_summaries+ ]+ start = time.time()+ merged, token_count, compressed_text, long_term_debug_input = self.summarizer.batch_compress_to_longterm(+ state.memory_state["long_term_memory"],+ state.mid_term_summaries,+ )+ elapsed = time.time() - start+ state.memory_state["long_term_memory"] = merged+ for entry in state.mid_term_summaries:+ entry["compressed_to_long_term"] = True+ entry["compressed_batch_index"] = batch_index++ long_term_entry = {+ "batch_index": batch_index,+ "query": state.current_query_text,+ "query_start_time": state.query_start_time,+ "source_chunk_indices": source_chunk_indices,+ "source_frame_ranges": source_frame_ranges,+ "source_summary_count": len(source_frame_ranges),+ "compressed_text": compressed_text,+ "inference_time": round(elapsed, 3),+ "token_count_after_append": token_count,+ }+ debug_input_path = self._save_summarizer_debug_input(+ state,+ "long_term",+ batch_index,+ copy.deepcopy(long_term_debug_input),+ )+ if debug_input_path:+ long_term_entry["debug_input_path"] = debug_input_path+ state.long_term_history.append(long_term_entry)++ window = int(self.config.long_term_memory_window or 0)+ if window > 0 and len(state.long_term_history) > window:+ dropped_count = len(state.long_term_history) - window+ del state.long_term_history[:dropped_count]+ state.memory_state["long_term_memory"] = "\n\n".join(+ entry["compressed_text"].rstrip()+ for entry in state.long_term_history+ if entry.get("compressed_text")+ )+ token_count = self.summarizer.estimate_tokens(+ state.memory_state["long_term_memory"]+ )+ long_term_entry["token_count_after_slide"] = token_count++ state.mid_term_summaries.clear()+ LOGGER.info(+ "[%s] long-term compression batch=%d %.3fs tokens=%d",+ state.session_id,+ batch_index,+ elapsed,+ token_count,+ )++ def _async_summary_enabled(self) -> bool:+ return (+ self.summarizer is not None+ and self.config.chunk > 0+ and int(self.config.async_summary_lead_frames or 0) > 0+ )++ def _async_first_summary_turns(self) -> int:+ lead_turns = max(0, int(self.config.async_summary_lead_frames or 0))+ chunk = max(1, int(self.config.chunk or 1))+ return max(1, chunk - lead_turns + 1) if lead_turns > 0 else chunk++ def _append_async_summary_user_message(+ self,+ state: SessionState,+ time_range=None,+ image_path=None,+ query_text=None,+ *,+ time_ranges=None,+ image_paths=None,+ ) -> None:+ if time_ranges is None:+ time_ranges = [time_range] if time_range else []+ if image_paths is None:+ image_paths = [image_path] if image_path else []+ segment = state.async_summary_segment+ for tr, ip in zip(time_ranges, image_paths):+ segment["image_paths"].append(ip)+ segment["frame_time_ranges"].append(tr)+ segment["summarizer_frame_cache"].append({"path": ip})+ segment["frame_count"] += 1+ segment["turn_count"] += 1+ segment["messages"].append(+ self._build_internal_user_message(+ time_ranges=time_ranges,+ image_paths=image_paths,+ query_text=query_text,+ )+ )++ def _submit_async_summary_if_needed(self, state: SessionState) -> None:+ if not self._async_summary_enabled():+ return++ if state.async_next_summary_target_turns <= 0:+ state.async_next_summary_target_turns = self._async_first_summary_turns()+ if state.async_summary_segment["turn_count"] < state.async_next_summary_target_turns:+ return++ segment_snapshot = copy.deepcopy(state.async_summary_segment)+ summary_index = state.async_next_summary_index+ required_turn_count = state.turn_count + max(+ 0, int(self.config.async_summary_lead_frames or 0) - 1+ )+ task = asyncio.create_task(+ asyncio.to_thread(+ self._build_mid_term_summary_entry,+ state,+ segment_snapshot,+ summary_index,+ state.current_query_text or "",+ state.query_start_time,+ )+ )+ state.async_pending_summary_jobs.append(+ {+ "summary_index": summary_index,+ "submitted_turn_count": state.turn_count,+ "submitted_frame_count": state.frame_count,+ "required_turn_count": required_turn_count,+ "task": task,+ }+ )+ LOGGER.info(+ "[%s] submitted async mid-summary %d at turn=%d required_by_turn=%d",+ state.session_id,+ summary_index,+ state.turn_count,+ required_turn_count,+ )++ state.async_summary_segment = reset_chunk_state()+ state.async_next_summary_index += 1+ state.async_next_summary_target_turns = max(1, int(self.config.chunk or 1))++ async def _commit_required_async_summaries(+ self,+ state: SessionState,+ upto_turn_count: Optional[int] = None,+ wait_all: bool = False,+ non_blocking: bool = False,+ ) -> None:+ if not self._async_summary_enabled():+ return++ while state.async_pending_summary_jobs:+ job = state.async_pending_summary_jobs[0]+ is_required = wait_all or (+ upto_turn_count is not None+ and job["required_turn_count"] <= upto_turn_count+ )+ if not is_required:+ break++ if non_blocking and not job["task"].done():+ break++ wait_start = time.time()+ mid_term_entry, summary_time = await job["task"]+ wait_time = time.time() - wait_start+ mid_term_entry["async_summary"] = True+ mid_term_entry["turn_count"] = job.get("submitted_turn_count", 0)+ mid_term_entry["submitted_turn_count"] = job["submitted_turn_count"]+ mid_term_entry["submitted_frame_count"] = job["submitted_frame_count"]+ mid_term_entry["required_turn_count"] = job["required_turn_count"]+ mid_term_entry["barrier_wait_time"] = round(wait_time, 3)+ state.async_pending_summary_jobs.pop(0)++ state.mid_term_summaries.append(mid_term_entry)+ state.mid_term_history.append(mid_term_entry)+ LOGGER.info(+ "[%s] committed async mid-summary %d range=%s wait=%.3fs (%d/%d buffered)",+ state.session_id,+ mid_term_entry["chunk_index"],+ mid_term_entry["frame_range"],+ wait_time,+ len(state.mid_term_summaries),+ self.config.compress_every_n_chunks,+ )+ if len(state.mid_term_summaries) >= self.config.compress_every_n_chunks:+ await asyncio.to_thread(self._compress_mid_terms, state)diff --git a/Web_Inference/webinfer/fix_tokenizer_config.py b/Web_Inference/webinfer/fix_tokenizer_config.pynew file mode 100644index 0000000..5c04361--- /dev/null+++ b/Web_Inference/webinfer/fix_tokenizer_config.py@@ -0,0 +1,70 @@+# -*- coding: utf-8 -*-+"""为 vLLM 准备可加载的 checkpoint 目录(原 Web_Inference/webinfer/run.sh 中 normalize_model_path_for_vllm 的 Python 段)。++原理:新版 transformers 保存的 tokenizer_config.json 里 extra_special_tokens 是 list,+而 vLLM 环境中的 transformers 要求它是 {name: token} 的 dict,直接加载会报错。+这里不改原 checkpoint:在 runtime_dir 下建一个镜像目录,其余文件全部软链接回原目录,+只重写 tokenizer_config.json,把 list 转成 dict。最后打印 vLLM 应该使用的模型路径。++用法: python fix_tokenizer_config.py <model_path> <runtime_dir>+"""++import hashlib+import json+import os+import shutil+import sys+from pathlib import Path++src = Path(sys.argv[1]).expanduser().resolve()+runtime_dir = Path(sys.argv[2]).expanduser().resolve()+tokenizer_config = src / "tokenizer_config.json"++# 没有 tokenizer_config 或 extra_special_tokens 已经不是 list:原目录可直接用+if not src.is_dir() or not tokenizer_config.is_file():+ print(src)+ raise SystemExit(0)++with tokenizer_config.open() as f:+ cfg = json.load(f)++extra_special_tokens = cfg.get("extra_special_tokens")+if not isinstance(extra_special_tokens, list):+ print(src)+ raise SystemExit(0)++# 镜像目录名带原路径哈希,不同 checkpoint 互不覆盖+digest = hashlib.sha1(str(src).encode("utf-8")).hexdigest()[:10]+dst = runtime_dir / f"{src.name}-tokenizer-fixed-{digest}"+dst.mkdir(parents=True, exist_ok=True)++for item in src.iterdir():+ target = dst / item.name+ if item.name == "tokenizer_config.json":+ continue+ if target.exists() or target.is_symlink():+ if target.is_dir() and not target.is_symlink():+ shutil.rmtree(target)+ else:+ target.unlink()+ os.symlink(item, target, target_is_directory=item.is_dir())++# "<|video_pad|>" -> key "video_token","<|im_start|>" -> key "im_start_token"+mapping = {}+for token in extra_special_tokens:+ key = str(token).strip("<|>").replace("|", "_")+ if key.endswith("_pad"):+ key = key[:-4] + "_token"+ else:+ key = key + "_token"+ mapping[key] = token++cfg["extra_special_tokens"] = mapping+with (dst / "tokenizer_config.json").open("w") as f:+ json.dump(cfg, f, ensure_ascii=False, indent=2)+ f.write("\n")++with (dst / ".source_model_path").open("w") as f:+ f.write(str(src) + "\n")++print(dst)diff --git a/Web_Inference/webinfer/live_adapter.py b/Web_Inference/webinfer/live_adapter.pynew file mode 100644index 0000000..2c10f94--- /dev/null+++ b/Web_Inference/webinfer/live_adapter.py@@ -0,0 +1,82 @@+# -*- coding: utf-8 -*-+"""+OpenAI-compatible live adapter for StreamingHarness inference.++The adapter does not load model weights. It accepts the WebUI's ordinary+OpenAI chat-completion requests, stores incoming base64 frames on disk, keeps+StreamingHarness-style session state, and calls the existing vLLM OpenAI API+servers:++ - main 8B inference API+ - optional summary API for mid-term summaries and long-term compression++入口文件。模块划分:+ adapter_common.py 常量、时间戳/输出归一化等纯函数+ adapter_request.py HTTP 请求解析、图片编码、OpenAI 响应构造+ adapter_config.py AdapterConfig 与命令行/环境变量解析+ adapter_session.py SessionState 与会话管理、帧落盘、结果写入+ adapter_model.py 滑窗 messages 构造与 vLLM 主模型调用+ adapter_summary.py 可选的中期/长期摘要记忆+ adapter_core.py StreamingInferAdapter:HTTP 接口 + 每帧推理主流程+"""++from __future__ import annotations++import logging+import os++from aiohttp import web++from adapter_common import LOGGER+from adapter_config import AdapterConfig, parse_args+from adapter_core import StreamingInferAdapter+++def create_app(config: AdapterConfig) -> web.Application:+ adapter = StreamingInferAdapter(config)+ app = web.Application(client_max_size=128 * 1024 * 1024)+ app["adapter"] = adapter+ async def _on_startup(_app: web.Application) -> None:+ adapter.start_background_tasks()+ app.on_startup.append(_on_startup)+ app.router.add_get("/health", adapter.handle_health)+ app.router.add_get("/v1/models", adapter.handle_models)+ app.router.add_post("/v1/chat/completions", adapter.handle_chat_completions)+ app.router.add_post("/v1/streaming/reset", adapter.handle_reset)+ return app+++def main() -> None:+ logging.basicConfig(+ level=os.environ.get("LOG_LEVEL", "INFO").upper(),+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",+ )+ config = parse_args()+ LOGGER.info("Starting adapter on %s:%s", config.host, config.port)+ LOGGER.info("Input format: %s", config.input_format)+ LOGGER.info("Adapter model: %s", config.adapter_model)+ if config.main_backends:+ LOGGER.info("Multi-backend mode: %d backends", len(config.main_backends))+ for b in config.main_backends:+ LOGGER.info(" Backend: %s -> %s (model=%s)", b["name"], b["api_base"], b.get("model", b["name"]))+ else:+ LOGGER.info("Main model: %s at %s", config.main_model, config.main_api_base)+ if config.per_session_dirs:+ LOGGER.info("Live save mode: per-session directories under %s", config.save_root)+ else:+ LOGGER.info("Live output dir: %s", config.out_dir or "disabled")+ LOGGER.info("Live light output dir: %s", config.light_out_dir or "disabled")+ LOGGER.info("Live debug input dir: %s", config.debug_input_dir or "disabled")+ if config.enable_summarizer:+ LOGGER.info(+ "Summarizer APIs: mid=%s long=%s",+ config.summarizer_api_base,+ config.longterm_api_base,+ )+ else:+ LOGGER.info("Summarizer disabled")+ web.run_app(create_app(config), host=config.host, port=config.port)+++if __name__ == "__main__":+ main()diff --git a/Web_Inference/webinfer/memory_summarizer.py b/Web_Inference/webinfer/memory_summarizer.pynew file mode 100644index 0000000..a04d63c--- /dev/null+++ b/Web_Inference/webinfer/memory_summarizer.py@@ -0,0 +1,806 @@+# -*- coding: utf-8 -*-+import base64+import os+import re+import time++from concurrent.futures import ThreadPoolExecutor, as_completed+from openai import OpenAI+from PIL import Image+import io++# ============================================================+# Prompt Templates+# ============================================================++DETAILED_SUMMARY_PROMPT_EN = """\+You are writing mid-term memory for a long-running video agent. The user message contains timestamped key frames for Chunk {chunk_index}, covering {frame_range}; each image is preceded by its sampled timestamp span. These frames will be unavailable afterward, so your paragraph must preserve the key evidence that downstream models need for recall, reasoning, and answering follow-up questions once the visuals are gone.++[Output Format]+- Write a SINGLE factual paragraph{length_instruction}. Use the full output budget when the chunk is information-dense; for near-static or nearly duplicate frames, 1-2 brief sentences suffice — do not pad for length.+- When identity, text, or numeric values are uncertain, do not guess — mark them as "possibly X", "approx. X", or "unreadable"; even when unreadable, preserve the observable category, appearance, action, or positional features.++[Information to Preserve (by priority, highest first)]++Highest priority — essential for task continuity, must preserve:+- End-of-chunk handoff state: what remains on screen, what stage the task has reached, which objects are still available, which actions are unfinished or ongoing.+- Irreversible events and state changes: appearance, disappearance, movement, opening/closing, combination, separation, transfer of objects; source, destination, and resulting state of important operations.+- Intermediate results, task progress, partially completed or interrupted steps.+- Causal chains: when one action triggers another, keep the before/after relation instead of listing isolated fragments.++High priority — high information value and hard to reconstruct:+- Readable text, labels, numbers, measurements, counts, dates, identifiers, specifications; when multiple values appear together, preserve the "item → value" mapping instead of listing context-free numbers.+- Events, entities, or behaviors appearing for the first time or clearly anomalous within this chunk (judge only within this chunk, no cross-chunk history needed).+- Final positions of important objects and key spatial relations.++Medium priority — background and supporting detail:+- Inventory of people, body parts, tools, containers, ingredients, devices, and other entities present.+- Scene layout and persistent background: record once on first appearance, update on meaningful change, do not repeat if unchanged.+- Sparse time anchors for important events and transitions.++[Writing Rules]++Time references:+- Use at most 3-5 explicit time anchors in the paragraph, and only when they improve event separation or transition clarity. Prefer merged ranges of roughly {preferred_time_span}; use at most one explicit time range per continuous action phase. E.g., write "from 349s to 364s, the guitarist keeps playing, raises his left hand, then bows" instead of separate 349s-350s, 351s-352s, 353s-355s entries.+- Treat pre-image timestamp spans as evidence anchors, not sentence headers; do not copy each one into the output. Merge continuous or repeated actions across neighboring frames into one range and describe the visible changes within it.++Detail level and abstraction:+- Write in detail for highest and high priority information; keep stable background and repeated actions brief.+- Preserve concrete steps; do not replace them with vague wording like "preparation continues" or "performs related operations."+- Camera cuts, angle shifts, or viewpoint changes need not be mentioned individually; record them only when they reveal new elements, change readable information, or affect action continuity.+- When the scene contains structured information (tables, menus, forms, HUDs, subtitles, etc.), preserve field-value associations rather than merely summarizing the topic.+- This is memory, not a caption: preserve state, entities, actions, text, and numeric values in a balanced way rather than favoring only narrative, novelty, or motion.++Factual constraints:+- Use only details directly visible in the provided key frames; do not fill in off-screen content or speculate about future developments.+- Describe in temporal order of the key frames, but do not narrate every sampled interval individually.+- Avoid generic wrap-up phrases, meta commentary (e.g., "this chunk shows…"), and repeated sentence patterns.++Output ONLY the paragraph."""++DETAILED_SUMMARY_PROMPT = """\+你正在为一个长时间运行的视频智能体编写中期记忆。用户消息包含第 {chunk_index} 个片段的带时间戳关键帧,覆盖时间范围 {frame_range};每张图片前标注其采样时间段。这些帧在本次之后不再可用,因此你的段落需要保留下游模型在没有视觉信息时进行回忆、推理和回答后续问题所需的关键证据。++【输出格式】+- 撰写一个事实性段落{length_instruction}。信息密集时充分利用空间;接近静止或几乎无新信息时(如长时间静止画面、近乎重复的帧),用 1-2 句简短记录即可,不要凑长度。+- 身份、文字、数值不确定时不要猜测,用"疑似 X"、"约 X"或"不可读"等方式标注;不可读时仍保留可观察到的类别、外观、动作或位置特征。+- 段落主体使用中文叙述;画面里能看到的英文(术语、人名、作品名、短语、年代标注等)每次出现都写成"中文译名(English 原文)",不许只留一种,不许半中半英,画面没出现的英文不要补。++【需保留的信息(按优先级从高到低)】++最高优先级 — 任务连续性必需,必须保留:+- 片段结束时的交接状态:屏幕上剩余什么、任务推进到哪一步、哪些物体仍然可用、哪些动作未完成或仍在进行。+- 不可逆事件与状态变化:物体的出现、消失、移动、开合、组合、分离、转移;重要操作的来源、目的地与结果状态。+- 中间结果、任务进度、部分完成或被中断的步骤。+- 因果链:当一个动作引发另一个动作时,保持前后关系,不要列成孤立片段。++高优先级 — 信息价值高且难以重建:+- 可读的文字、标签、标题、数字、测量值、计数、日期、标识符、规格。多值同时出现时保留"项目→值"的映射,不要列出脱离上下文的数字。+- 在本片段内首次出现或明显异常的事件、实体或行为(仅按本片段判断,不需考虑跨片段历史)。+- 重要物体的最终位置与关键空间关系。++中优先级 — 背景与陪衬:+- 出现的人物、身体部位、工具、容器、食材、设备等实体清单。+- 场景布局与持续存在的背景:首次出现时记录一次,发生有意义变化时更新,未变化则不重复。+- 重要事件与转换的稀疏时间锚点。++【撰写规则】++时间引用:+- 整段最多使用 3-5 个显式时间锚点,且仅在能改善事件区分或转换识别时使用。优先采用约 {preferred_time_span} 的合并范围,一个连续动作阶段最多使用一个显式时间范围。例如写"从 349s 到 364s,吉他手持续弹奏、抬起左手并鞠躬",而不是 349s-350s、351s-352s、353s-355s 分别写。+- 图片前的时间标注是证据锚点,不要逐个复制到输出中;相邻帧中重复或连续的动作合并为一个范围,并在其中描述可见变化。++详略与抽象层级:+- 详写最高与高优先级信息;略写稳定背景与重复动作。+- 保留具体步骤,不要用"准备继续"、"做相关操作"等空话替代可见动作。+- 镜头切换、机位移动或视角变化本身无需逐次提及;仅当它们揭示新元素、改变可读信息或影响动作连续性时才记录。+- 当场景包含结构化信息(表格、菜单、表单、HUD、字幕等)时,保留字段-值对应关系,而不仅概述主题。+- 这是记忆而非字幕:均衡保留状态、实体、动作、文字与数值,而不是只偏重叙事、新颖性或运动。++事实性约束:+- 仅使用所提供关键帧中直接可见的细节;不要补全画面外的内容或推测后续发展。+- 按关键帧的时间顺序描述,但不要逐一叙述每个采样间隔。+- 避免泛泛的总结性短语、元评论(如"本片段展示了……")和重复句式。++仅输出该段落。"""++EMPTY_CHUNK_SUMMARY_TEMPLATE_EN = "No visually significant change is evident in frames {frame_range}."+EMPTY_CHUNK_SUMMARY_TEMPLATE = "在帧 {frame_range} 中未观察到明显的视觉变化。"++BATCH_COMPRESS_PROMPT_EN = """\+You are compressing multiple mid-term memory segments into long-term memory for a long-running video agent. The original frames for period {merged_range} will no longer be available, so the output must preserve the key evidence that downstream models need for recall, reasoning, and answering follow-up questions afterward.++MID-TERM SUMMARIES TO MERGE:+{summaries_text}++[Task Definition]+This is a compression task, not a simple merge. You must prioritize and discard to reduce information density rather than piling everything together. The input consists of N mid-term summaries, each with its own end-of-segment handoff state; after merging, only the **final segment's end state** matters to downstream — earlier segments' end states that have been superseded by later events (e.g., "a cup picked up then put down", "a menu opened then closed") should be treated as process information or omitted.++[Output Format]+- Write a SINGLE unified factual paragraph (NOT separate per-segment summaries), prioritizing within the target length{length_instruction}.+- Use the same language as the mid-term summaries; if languages are mixed across segments, use whichever is the majority.+- Uncertainty markers from mid-term summaries ("possibly X", "approx. X", "unreadable") must be carried through to long-term memory — do not "launder" them into definitive statements during merging.++[Retention Priority]++Highest priority — must preserve:+- The **final** handoff state at the end of the merged period: what remains on screen, what stage the task has reached, which objects are still available, which actions are unfinished or ongoing.+- Cross-segment irreversible events and state changes: final appearances/disappearances of objects, key movements, combinations, separations, transfers; source, destination, and resulting state of important operations.+- Readable text, labels, numbers, measurements, counts, dates, identifiers, specifications, and "item → value" mappings.+- Causal chains: when one action triggers a subsequent action, preserve the dependency instead of flattening into isolated facts.++High priority — should preserve:+- Entities (people, key tools, key objects) that persist across multiple segments and their evolution.+- Overall task progress structure and milestone stages.+- Events appearing for the first time or clearly anomalous within the merged range.+- Final positions of important objects and key spatial relations at the end of the merged period.++Compressible — actively reduce density or discard:+- Intermediate states that have been overwritten by later events — preserve only when the process itself carries information value.+- Stable background unchanged across segments — record once at first description only.+- Multiple similar repetitions of the same action — merge per the "Recurrence handling" rules below.+- Fine-grained procedural steps that can be omitted when the higher-level action is already recorded.++[Merging Rules]++Cross-segment consistency:+- When the same entity is named inconsistently across segments (e.g., "red cup" → "mug" → "container"), unify to the most informative and specific term, briefly noting alternative names on first occurrence.+- When multiple segments describe the same event with conflicting details, prefer the later or more specific version; if neither can be judged, keep both with "X or Y" rather than choosing one side.+- When the same event is described redundantly at adjacent segment boundaries, merge into a single record.++Recurrence handling:+- When the count of repetitions itself carries information (e.g., "knocked 5 times", "refreshed the page 3 times"), preserve the count.+- When repetition is procedural continuity (e.g., "keeps stirring", "repeatedly checks"), merge with one time range plus action description, e.g., "from 349s to 364s, keeps playing and raises hand to acknowledge the audience several times."+- Do not compress multiple distinct actions or state changes into a vague summary.++[Time References]+- Use 3-7 explicit time anchors across the paragraph (adjust for the span of {merged_range}), and only when they improve event separation or phase-transition clarity.+- Do not retain source summaries' <Xs-Ys> headers or reproduce their chain of "At <X>s..." timestamp cadence.+- Merge continuous or repeated neighboring actions into one range and describe the visible changes within it.++[Factual Constraints]+- Use only content already present in the mid-term summaries; do not fill in off-screen information or speculate about future developments.+- Preserve concrete steps and readable values; do not replace them with vague wording like "preparation continues" or "performs related operations."+- Avoid generic wrap-up phrases, meta commentary (e.g., "this memory covers…"), and repeated sentence patterns.++Output ONLY the unified narrative text, nothing else."""++BATCH_COMPRESS_PROMPT = """\+你正在为一个长时间运行的视频智能体将多段中期记忆压缩为长期记忆。时间段 {merged_range} 的原始帧将不再可用,因此输出需要保留下游模型在此之后进行回忆、推理和回答后续问题所需的关键证据。++需要合并的中期摘要:+{summaries_text}++【任务定位】+这是压缩任务,不是简单合并。需要按优先级取舍以降低信息密度,而不是把所有内容堆在一起。输入由 N 段中期摘要组成,每段都有自己的期末交接状态;合并后只有**最后一段的期末状态**对下游有意义,前面各段的期末状态若已被后续事件覆盖(如"拿起又放下的杯子"、"打开又关闭的菜单"),应作为过程信息处理或省略。++【输出格式】+- 撰写一个统一的事实性段落(不是按片段分开的摘要),在目标长度内{length_instruction}按优先级取舍。+- 中期摘要中的不确定性标注("疑似 X"、"约 X"、"不可读")必须传递到长期记忆,不要在合并时被"洗"成确定表述。++【保留优先级】++最高优先级 — 必须保留:+- 合并期**结束时**的最终交接状态:屏幕上剩余什么、任务推进到哪一步、哪些物体仍然可用、哪些动作未完成或仍在进行。+- 跨片段的不可逆事件与状态变化:物体的最终出现/消失、关键移动、组合、分离、转移;重要操作的来源、目的地与结果状态。+- 可读的文字、标签、数字、测量值、计数、日期、标识符、规格,以及"项目→值"的映射关系。+- 因果链:当一个动作引发后续动作时,保持依赖关系,不要扁平化为孤立事实。++高优先级 — 应当保留:+- 跨多个片段持续存在的实体(人物、关键工具、关键物体)及其演变。+- 任务的整体进度结构与阶段性里程碑。+- 在合并范围内首次出现或明显异常的事件。+- 重要物体在合并期末的位置与关键空间关系。++可压缩 — 主动降低密度或丢弃:+- 已被后续事件覆写的中间状态——仅在该过程本身有信息价值时才保留。+- 跨片段未变化的稳定背景,只在首次描述时记录一次。+- 同一动作的多次相似重复,按下方"重复处理"规则归并。+- 过程性的细微步骤,在更高层动作已被记录时可以省略。++【合并规则】++跨片段一致性:+- 同一实体在不同片段中名称不一致时(如"红色杯子" → "马克杯" → "容器"),统一为信息量最高、最具体的那个,并在首次出现时简要标注其他称呼。+- 多个片段对同一事件描述冲突时,优先采信时间靠后或信息更具体的版本;如果无法判定,用"X 或 Y"并列保留,不要单方面选边。+- 同一事件在相邻片段边界处被重复描述时,合并为一次记录。++重复处理:+- 当重复次数本身携带信息时(如"敲门 5 次"、"刷新页面 3 次"),保留次数。+- 当重复是过程性持续时(如"持续搅拌"、"反复检查"),用一个时间范围加动作描述合并,例如"从 349s 到 364s 持续弹奏并多次抬手致意"。+- 不要将多个不同的动作或状态变化压缩为模糊总结。++【时间引用】+- 整段使用 3-7 个显式时间锚点(按 {merged_range} 跨度调整),仅在能改善事件区分或阶段切换识别时使用。+- 不要保留源摘要的 <Xs-Ys> 标题,也不要复制源摘要中"在 <X>s..."的连续时间戳节奏。+- 连续或重复的相邻动作合并为一个范围,并在范围内描述可见变化。++【事实性约束】+- 仅使用中期摘要中已有的内容;不要补全画面外信息或推测后续发展。+- 保留具体步骤与可读数值,不要用"准备继续"、"做相关操作"等空话替代。+- 避免泛泛的总结性短语、元评论(如"这段记忆包含……")和重复句式。++仅输出统一的叙述文本,不要输出其他内容。"""++# ============================================================+# Helper: encode image to base64 data URL+# ============================================================++def _encode_image_base64(image_path: str, max_pixels: int = 0) -> str:+ """Read an image file and return a base64 data URL for the OpenAI API.++ If *max_pixels* > 0 and the image exceeds that budget, it is+ down-scaled (preserving aspect ratio) so that width*height <= max_pixels.+ """+ if image_path.startswith("data:"):+ if max_pixels > 0:+ match = re.match(r"data:image/\w+;base64,(.+)", image_path)+ if match:+ img = Image.open(io.BytesIO(base64.b64decode(match.group(1))))+ w, h = img.size+ if w * h > max_pixels:+ scale = (max_pixels / (w * h)) ** 0.5+ new_w = max(1, int(w * scale))+ new_h = max(1, int(h * scale))+ img = img.resize((new_w, new_h), Image.LANCZOS)+ buf = io.BytesIO()+ img.save(buf, format="JPEG")+ data = base64.b64encode(buf.getvalue()).decode("utf-8")+ return f"data:image/jpeg;base64,{data}"+ return image_path+ ext = os.path.splitext(image_path)[1].lower()+ mime_map = {+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".png": "image/png",+ ".gif": "image/gif",+ ".webp": "image/webp",+ ".bmp": "image/bmp",+ }+ mime_type = mime_map.get(ext, "image/jpeg")++ if max_pixels > 0:+ img = Image.open(image_path)+ w, h = img.size+ if w * h > max_pixels:+ scale = (max_pixels / (w * h)) ** 0.5+ new_w = max(1, int(w * scale))+ new_h = max(1, int(h * scale))+ img = img.resize((new_w, new_h), Image.LANCZOS)+ buf = io.BytesIO()+ save_fmt = "PNG" if ext == ".png" else "JPEG"+ img.save(buf, format=save_fmt)+ data = base64.b64encode(buf.getvalue()).decode("utf-8")+ return f"data:{mime_type};base64,{data}"++ with open(image_path, "rb") as f:+ data = base64.b64encode(f.read()).decode("utf-8")++ return f"data:{mime_type};base64,{data}"+++# ============================================================+# SummarizerModel (OpenAI API client)+# ============================================================++class SummarizerModel:+ def __init__(+ self,+ model_name: str = "models/summary",+ api_base: str = "http://localhost:8065/v1",+ longterm_model_name: str = "",+ longterm_api_base: str = "",+ mid_term_max_tokens: int = 5000,+ mid_term_target_tokens: int = 0,+ long_term_max_tokens: int = 1200,+ long_term_target_tokens: int = 0,+ key_frames_per_chunk: int = 8,+ max_pixels: int = 0,+ prompt_phase_seconds: float = 10.0,+ mid_term_temperature: float = 0.1,+ mid_term_top_p: float = 0.9,+ mid_term_top_k: int = -1,+ mid_term_repetition_penalty: float = 1.0,+ mid_term_presence_penalty: float = 0.0,+ long_term_temperature: float = 0.1,+ long_term_top_p: float = 0.9,+ long_term_top_k: int = -1,+ long_term_repetition_penalty: float = 1.0,+ long_term_presence_penalty: float = 0.0,+ debug: bool = False,+ ):+ self.model_name = model_name+ self.longterm_model_name = longterm_model_name or model_name+ self.mid_term_max_tokens = mid_term_max_tokens+ self.mid_term_target_tokens = mid_term_target_tokens+ self.long_term_max_tokens = long_term_max_tokens+ self.long_term_target_tokens = long_term_target_tokens+ self.key_frames_per_chunk = key_frames_per_chunk+ self.max_pixels = max_pixels+ self.prompt_phase_seconds = prompt_phase_seconds+ self.mid_term_temperature = mid_term_temperature+ self.mid_term_top_p = mid_term_top_p+ self.mid_term_top_k = mid_term_top_k+ self.mid_term_repetition_penalty = mid_term_repetition_penalty+ self.mid_term_presence_penalty = mid_term_presence_penalty+ self.long_term_temperature = long_term_temperature+ self.long_term_top_p = long_term_top_p+ self.long_term_top_k = long_term_top_k+ self.long_term_repetition_penalty = long_term_repetition_penalty+ self.long_term_presence_penalty = long_term_presence_penalty+ self.debug = debug++ # 中期摘要客户端(多模态,带图片)+ self._client = OpenAI(+ api_key="EMPTY",+ base_url=api_base,+ )++ # 长期压缩客户端(纯文本)—— 如果未指定则复用中期客户端+ if longterm_api_base and longterm_api_base != api_base:+ self._longterm_client = OpenAI(+ api_key="EMPTY",+ base_url=longterm_api_base,+ )+ else:+ self._longterm_client = self._client++ from transformers import AutoTokenizer+ self._tokenizer_cls = AutoTokenizer+ self._tokenizer_model_name = model_name+ self._tokenizer = None+ self._tokenizer_failed = False++ def preencode_frame(self, image_path: str) -> tuple[dict, float]:+ """Pre-encode one frame for mid-term summary use during streaming."""+ start_time = time.time()+ data_url = _encode_image_base64(image_path, max_pixels=self.max_pixels)+ return {+ "path": image_path,+ "data_url": data_url,+ }, time.time() - start_time++ def _chat(self, messages: list, max_tokens: int, temperature: float = 0.3, top_p: float = 0.9,+ top_k: int = -1, repetition_penalty: float = 1.0,+ presence_penalty: float = 0.0,+ client: OpenAI = None, model_name: str = None) -> str:+ """Call the vLLM OpenAI API server."""+ client = client or self._client+ model_name = model_name or self.model_name+ extra_body = {"greedy": False}+ if top_k > 0:+ extra_body["top_k"] = top_k+ if repetition_penalty != 1.0:+ extra_body["repetition_penalty"] = repetition_penalty+ response = client.chat.completions.create(+ model=model_name,+ messages=messages,+ max_tokens=max_tokens,+ temperature=temperature,+ top_p=top_p,+ presence_penalty=presence_penalty,+ extra_body=extra_body,+ )+ return response.choices[0].message.content.strip() if response.choices else ""++ def _get_tokenizer(self):+ if self._tokenizer_failed:+ return None+ if self._tokenizer is None:+ try:+ self._tokenizer = self._tokenizer_cls.from_pretrained(+ self._tokenizer_model_name+ )+ except Exception as e:+ print(f"WARNING: Failed to load tokenizer from {self._tokenizer_model_name}: {e}")+ self._tokenizer_failed = True+ return None+ return self._tokenizer++ def estimate_tokens(self, text: str) -> int:+ if not text:+ return 0+ tokenizer = self._get_tokenizer()+ if tokenizer is None:+ return len(text) // 4+ return len(tokenizer.encode(text, add_special_tokens=False))++ def _parse_time_value(self, text: str):+ if text is None:+ return None+ value = text.strip()+ if value.endswith("s"):+ value = value[:-1]+ try:+ return float(value)+ except ValueError:+ return None++ @staticmethod+ def _split_frame_range(frame_range: str) -> tuple:+ """Split a frame_range string into (start, end).++ Handles both "0s-10s" and "0.0 seconds ~ 89.0 seconds" formats.+ """+ if " ~ " in frame_range:+ parts = frame_range.split(" ~ ", 1)+ return parts[0].strip(), parts[-1].strip()+ if "-" in frame_range:+ parts = frame_range.split("-", 1)+ return parts[0].strip(), parts[-1].strip()+ return frame_range.strip(), frame_range.strip()++ def _parse_time_range_bounds(self, time_range: str) -> tuple:+ if not time_range or "-" not in time_range:+ return None, None+ start_text, end_text = time_range.split("-", 1)+ return self._parse_time_value(start_text), self._parse_time_value(end_text)++ def _format_time_value(self, value: float) -> str:+ if value is None:+ return "0s"+ if abs(value - round(value)) < 1e-6:+ return f"{int(round(value))}s"+ return f"{value:.3f}".rstrip("0").rstrip(".") + "s"++ def _build_range_from_frame_indices(self, frame_time_ranges: list, start_idx: int, end_idx: int) -> str:+ start_value = float(start_idx)+ end_value = float(end_idx + 1)++ if start_idx < len(frame_time_ranges):+ parsed_start, _ = self._parse_time_range_bounds(frame_time_ranges[start_idx])+ if parsed_start is not None:+ start_value = parsed_start+ if end_idx < len(frame_time_ranges):+ _, parsed_end = self._parse_time_range_bounds(frame_time_ranges[end_idx])+ if parsed_end is not None:+ end_value = parsed_end++ if end_value <= start_value:+ end_value = start_value + 1.0++ return f"{self._format_time_value(start_value)}-{self._format_time_value(end_value)}"++ def _sample_sorted_indices(self, indices: list, budget: int) -> list:+ if budget <= 0 or not indices:+ return []+ if len(indices) <= budget:+ return list(indices)+ if budget == 1:+ return [indices[len(indices) // 2]]++ selected_positions = []+ last_pos = -1+ total = len(indices)+ for slot in range(budget):+ target = round(slot * (total - 1) / (budget - 1))+ target = max(target, last_pos + 1)+ max_allowed = total - (budget - slot)+ target = min(target, max_allowed)+ selected_positions.append(target)+ last_pos = target+ return [indices[pos] for pos in selected_positions]++ def _get_frame_prompt_time_range(self, frame: dict) -> str:+ return frame.get("source_time_range") or frame.get("time_range") or "unknown"++ def _build_prompt_phases(self, key_frames: list) -> list:+ return [+ {+ "time_range": self._get_frame_prompt_time_range(frame),+ "frames": [frame],+ }+ for frame in key_frames+ ]++ def _build_mid_term_debug_input(+ self,+ chunk_index: int,+ frame_range: str,+ frame_count: int,+ active_query: str,+ prompt_text: str,+ key_frames: list,+ phases: list,+ temperature: float,+ ) -> dict:+ content = [{"type": "text", "text": prompt_text}]+ for phase in phases:+ content.append({"type": "text", "text": f"<{phase['time_range']}>"})+ for frame in phase["frames"]:+ content.append({+ "type": "image_path",+ "image_path": frame["path"],+ "max_pixels": self.max_pixels,+ })+ return {+ "stage": "mid_term",+ "model_name": self.model_name,+ "max_tokens": self.mid_term_max_tokens,+ "target_token_count": self.mid_term_target_tokens,+ "temperature": temperature,+ "top_p": self.mid_term_top_p,+ "chunk_index": chunk_index,+ "frame_range": frame_range,+ "frame_count": frame_count,+ "active_query": active_query or "(none)",+ "phase_seconds": self.prompt_phase_seconds,+ "phases": [+ {+ "time_range": phase.get("time_range"),+ "frame_count": len(phase.get("frames", [])),+ "frame_indices": [frame.get("frame_index") for frame in phase.get("frames", [])],+ "frame_time_ranges": [frame.get("time_range") for frame in phase.get("frames", [])],+ }+ for phase in phases+ ],+ "key_frames": [+ {+ "time_range": frame.get("time_range"),+ "source_time_range": frame.get("source_time_range"),+ "path": frame.get("path"),+ "frame_index": frame.get("frame_index"),+ "range_start_index": frame.get("range_start_index"),+ "range_end_index": frame.get("range_end_index"),+ }+ for frame in key_frames+ ],+ "messages": [{"role": "user", "content": content}],+ "prompt_text": prompt_text,+ }++ def _build_long_term_debug_input(+ self,+ merged_range: str,+ active_query: str,+ prompt_text: str,+ mid_term_summaries: list,+ temperature: float,+ ) -> dict:+ return {+ "stage": "long_term",+ "model_name": self.longterm_model_name,+ "max_tokens": self.long_term_max_tokens,+ "target_token_count": self.long_term_target_tokens,+ "temperature": temperature,+ "top_p": self.long_term_top_p,+ "merged_range": merged_range,+ "active_query": active_query or "(none)",+ "source_summaries": [+ {+ "chunk_index": entry.get("chunk_index"),+ "frame_range": entry.get("frame_range"),+ "summary_text": entry.get("summary_text"),+ }+ for entry in mid_term_summaries+ ],+ "messages": [{"role": "user", "content": prompt_text}],+ "prompt_text": prompt_text,+ }++ def select_key_frames(+ self,+ image_paths: list,+ frame_time_ranges: list,+ key_frame_indices: list,+ cached_frame_payloads: list = None,+ ) -> list:+ """Select up to key_frames_per_chunk frames and carry cached payloads when available."""+ del key_frame_indices # Mid-term summaries are now driven only by timestamped frames.++ n = len(image_paths)+ budget = self.key_frames_per_chunk+ if n == 0:+ return []++ if budget <= 0 or n <= budget:+ selected_indices = list(range(n))+ else:+ selected_indices = self._sample_sorted_indices(list(range(n)), budget)++ key_frames = []+ for pos, idx in enumerate(selected_indices):+ left_idx = 0 if pos == 0 else (selected_indices[pos - 1] + idx) // 2 + 1+ right_idx = n - 1 if pos == len(selected_indices) - 1 else (idx + selected_indices[pos + 1]) // 2+ left_idx = min(max(left_idx, 0), n - 1)+ right_idx = min(max(right_idx, left_idx), n - 1)++ cached_frame = None+ if cached_frame_payloads and idx < len(cached_frame_payloads):+ cached_frame = cached_frame_payloads[idx]++ path = image_paths[idx]+ if cached_frame and cached_frame.get("path"):+ path = cached_frame["path"]+ if not path.startswith("data:") and not os.path.exists(path):+ continue++ source_time_range = frame_time_ranges[idx] if idx < len(frame_time_ranges) else None+ key_frame = {+ "path": path,+ "source_time_range": source_time_range,+ "time_range": self._build_range_from_frame_indices(frame_time_ranges, left_idx, right_idx),+ "frame_index": idx,+ "range_start_index": left_idx,+ "range_end_index": right_idx,+ }+ if cached_frame and cached_frame.get("data_url"):+ key_frame["data_url"] = cached_frame["data_url"]+ key_frames.append(key_frame)+ return key_frames++ def _build_mid_term_length_instruction(self) -> str:+ if self.mid_term_target_tokens > 0:+ return f",目标约 {self.mid_term_target_tokens} tokens"+ return ""++ def _build_long_term_length_instruction(self) -> str:+ if self.long_term_target_tokens > 0:+ return f",目标约 {self.long_term_target_tokens} tokens"+ return ""++ def generate_detailed_summary(+ self,+ chunk_index: int,+ frame_range: str,+ key_frames: list,+ frame_count: int,+ active_query: str = "",+ ) -> tuple:+ """Generate a detailed multimodal summary for a chunk (Tier 2).++ Returns (summary_text, debug_input_or_None).+ """+ if not key_frames:+ return EMPTY_CHUNK_SUMMARY_TEMPLATE.format(frame_range=frame_range), None++ length_instruction = self._build_mid_term_length_instruction()+ mid_term_temperature = self.mid_term_temperature+ prompt_text = DETAILED_SUMMARY_PROMPT.format(+ frame_range=frame_range,+ chunk_index=chunk_index,+ length_instruction=length_instruction,+ preferred_time_span=f"{self.prompt_phase_seconds:g} seconds",+ )++ phases = self._build_prompt_phases(key_frames)++ debug_input = None+ if self.debug:+ debug_input = self._build_mid_term_debug_input(+ chunk_index=chunk_index,+ frame_range=frame_range,+ frame_count=frame_count,+ active_query=active_query,+ prompt_text=prompt_text,+ key_frames=key_frames,+ phases=phases,+ temperature=mid_term_temperature,+ )++ frames_to_encode = [+ frame for phase in phases for frame in phase["frames"]+ if not frame.get("data_url")+ ]+ if frames_to_encode:+ max_px = self.max_pixels+ with ThreadPoolExecutor(max_workers=min(len(frames_to_encode), 4)) as pool:+ futures = {+ pool.submit(_encode_image_base64, f["path"], max_px): f+ for f in frames_to_encode+ }+ for fut in as_completed(futures):+ frame = futures[fut]+ try:+ frame["data_url"] = fut.result()+ except Exception as e:+ print(f"WARNING: Failed to encode image {frame['path']}: {e}")++ content_list = [{"type": "text", "text": prompt_text}]+ for phase in phases:+ content_list.append({"type": "text", "text": f"<{phase['time_range']}>"})+ for frame in phase["frames"]:+ data_url = frame.get("data_url")+ if data_url:+ content_list.append({+ "type": "image_url",+ "image_url": {"url": data_url},+ })++ messages = [{"role": "user", "content": content_list}]+ summary_text = self._chat(+ messages,+ max_tokens=self.mid_term_max_tokens,+ temperature=mid_term_temperature,+ top_p=self.mid_term_top_p,+ top_k=self.mid_term_top_k,+ repetition_penalty=self.mid_term_repetition_penalty,+ presence_penalty=self.mid_term_presence_penalty,+ )+ return summary_text, debug_input++ def batch_compress_to_longterm(+ self,+ existing_longterm: str,+ mid_term_summaries: list,+ ) -> tuple:+ """+ Compress mid-term summaries and append to existing long-term memory.++ Only the new mid-term summaries are compressed (existing long-term is+ NOT re-compressed), then appended to the existing block.++ mid_term_summaries: list of dicts with keys 'frame_range', 'summary_text', etc.+ Returns (merged_text, token_count, compressed_new_text, debug_input_or_None).+ """++ if not mid_term_summaries:+ token_count = self.estimate_tokens(existing_longterm)+ return existing_longterm, token_count, "", None++ # 计算合并后的时间范围:取第一个 chunk 的起始和最后一个 chunk 的结束+ # frame_range 可能是 "0s-10s" 或 "0.0 seconds ~ 89.0 seconds" 两种格式+ first_range = mid_term_summaries[0]["frame_range"]+ last_range = mid_term_summaries[-1]["frame_range"]+ merged_start = self._split_frame_range(first_range)[0]+ merged_end = self._split_frame_range(last_range)[1]+ merged_range = f"{merged_start}-{merged_end}"++ # Step 1: Compress the new mid-term summaries into a single block+ summary_parts = []+ for entry in mid_term_summaries:+ summary_parts.append(+ f"<{entry['frame_range']}>\n{entry['summary_text']}"+ )+ summaries_text = "\n\n".join(summary_parts)++ active_query = ""+ for entry in mid_term_summaries:+ candidate_query = entry.get("query")+ if candidate_query:+ active_query = candidate_query+ break++ long_term_temperature = self.long_term_temperature+ length_instruction = self._build_long_term_length_instruction()+ prompt_text = BATCH_COMPRESS_PROMPT.format(+ summaries_text=summaries_text,+ length_instruction=length_instruction,+ merged_range=merged_range,+ )+ debug_input = None+ if self.debug:+ debug_input = self._build_long_term_debug_input(+ merged_range=merged_range,+ active_query=active_query,+ prompt_text=prompt_text,+ mid_term_summaries=mid_term_summaries,+ temperature=long_term_temperature,+ )++ compressed_new = self._chat(+ [{"role": "user", "content": prompt_text}],+ max_tokens=self.long_term_max_tokens,+ temperature=long_term_temperature,+ top_p=self.long_term_top_p,+ top_k=self.long_term_top_k,+ repetition_penalty=self.long_term_repetition_penalty,+ presence_penalty=self.long_term_presence_penalty,+ client=self._longterm_client,+ model_name=self.longterm_model_name,+ )+ # 在压缩结果前加上合并时间范围标记+ compressed_new = f"<{merged_range}>\n{compressed_new}"++ # Step 2: Append to existing long-term memory+ if existing_longterm:+ merged = existing_longterm.rstrip() + "\n\n" + compressed_new+ else:+ merged = compressed_new++ token_count = self.estimate_tokens(merged)+ return merged, token_count, compressed_new, debug_input++ def shutdown(self):+ """No-op: the vLLM server is managed externally."""+ passdiff --git a/Web_Inference/webui/src/alive_webui/__init__.py b/Web_Inference/webui/src/alive_webui/__init__.pynew file mode 100644index 0000000..d5c3ccc--- /dev/null+++ b/Web_Inference/webui/src/alive_webui/__init__.py@@ -0,0 +1,27 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""+Live VLM WebUI - Real-time Vision Language Model interaction web interface.++A universal web interface for streaming webcam feeds to Vision Language Models+with real-time AI analysis.+"""++__version__ = "0.1.0"+__author__ = "ALIVE contributors"+__license__ = "Apache-2.0"++__all__ = ["__version__", "__author__", "__license__"]diff --git a/Web_Inference/webui/src/alive_webui/background_model.py b/Web_Inference/webui/src/alive_webui/background_model.pynew file mode 100644index 0000000..ef634a7--- /dev/null+++ b/Web_Inference/webui/src/alive_webui/background_model.py@@ -0,0 +1,1286 @@++"""Background agent delegation for long-running or high-risk VLM questions."""++import asyncio+import base64+import io+import html+import json+import logging+import os+import re+import time+import uuid+from collections import deque+from dataclasses import dataclass, replace+from pathlib import Path+from typing import Callable, Optional++import httpx+from PIL import Image++try:+ from .local_file_server import (+ LOCAL_HTML_ARTIFACT_DIR,+ local_file_url_for_path,+ rewrite_payload_local_file_links,+ )+except ImportError:+ PROJECT_ROOT = Path(__file__).resolve().parents[2]+ _html_artifact_dir = Path(os.environ.get("LIVE_VLM_HTML_ARTIFACT_DIR", "html")).expanduser()+ if not _html_artifact_dir.is_absolute():+ _html_artifact_dir = PROJECT_ROOT / _html_artifact_dir+ LOCAL_HTML_ARTIFACT_DIR = _html_artifact_dir++ def local_file_url_for_path(path_value: str) -> str:+ return ""++ def rewrite_payload_local_file_links(payload: dict) -> dict:+ return payload+++def _legacy_background_env(suffix: str, default: str = "") -> str:+ legacy_name = "BACKGROUND_" + "CO" + "DEX_" + suffix+ return os.environ.get(legacy_name, default)+++BACKGROUND_AGENT_API_URL = os.environ.get(+ "BACKGROUND_AGENT_API_URL",+ _legacy_background_env("API_URL", "http://127.0.0.1:8079"),+)+BACKGROUND_MODEL_PROVIDER = "Background Agent"+BACKGROUND_MODEL_NAME = os.environ.get("BACKGROUND_MODEL_NAME", "background-agent")+BACKGROUND_TIMEOUT_SECONDS = 600.0+BACKGROUND_MAX_SUBAGENTS = int(+ os.environ.get(+ "BACKGROUND_MAX_SUBAGENTS",+ os.environ.get(+ "BACKGROUND_AGENT_MAX_SUBAGENTS",+ _legacy_background_env("MAX_SUBAGENTS", "6"),+ ),+ )+)+BACKGROUND_SUMMARIZER_API_BASE = os.environ.get(+ "BACKGROUND_SUMMARIZER_API_BASE",+ os.environ.get("LIVE_VLM_API_BASE", "http://127.0.0.1:8070/v1"),+)+BACKGROUND_SUMMARIZER_MODEL = os.environ.get(+ "BACKGROUND_SUMMARIZER_MODEL",+ os.environ.get("SUMMARIZER_MODEL", "models/summary"),+)+BACKGROUND_SUMMARIZER_TIMEOUT_SECONDS = float(os.environ.get("BACKGROUND_SUMMARIZER_TIMEOUT_SECONDS", "60"))+BACKGROUND_SUMMARIZER_MAX_TOKENS = int(os.environ.get("BACKGROUND_SUMMARIZER_MAX_TOKENS", "256"))+BACKGROUND_FRAME_MULTIPLIER = 2+BACKGROUND_DEFAULT_FOREGROUND_FPS = 1.0+BACKGROUND_DEFAULT_MAX_FRAMES = 100+BACKGROUND_MAX_FRAME_LIMIT = 100+BACKGROUND_FRAME_RESIZE_LONG_EDGE = 768+BACKGROUND_FRAME_JPEG_QUALITY = 82+BACKGROUND_HANDOFF_MAX_CHARS = 3500+BACKGROUND_HTML_ARTIFACT_DIR = LOCAL_HTML_ARTIFACT_DIR+BACKGROUND_DELEGATION_FOREGROUND_TEXT = (+ "</response> 这个问题需要调用后台模型,请稍等,你可以在此期间继续向我提问"+)++logger = logging.getLogger(__name__)+++def _env_bool(name: str, default: bool) -> bool:+ value = os.environ.get(name)+ if value is None:+ return default+ return value.strip().lower() not in {"0", "false", "no", "off"}++_THINK_BLOCK_RE = re.compile(+ r"<(?:think|thinking|reasoning)[^>]*>[\s\S]*?</(?:think|thinking|reasoning)>",+ flags=re.IGNORECASE,+)+_LEADING_THINK_TAG_RE = re.compile(+ r"^\s*<(?:think|thinking|reasoning)[^>]*>",+ flags=re.IGNORECASE,+)+_LOOSE_THINK_TAG_RE = re.compile(+ r"</?(?:think|thinking|reasoning)[^>]*>",+ flags=re.IGNORECASE,+)+_FINAL_ANSWER_LABEL_RE = re.compile(+ r"(?im)^\s*(?:final answer|answer|final response|最终答案|正式答案|给用户的答案)\s*[::]\s*"+)+_RENDERABLE_FRAGMENT_RE = re.compile(+ r"<(?:body|main|section|article|aside|header|footer|nav|div|h[1-6]|p|button|ul|ol|li|span|img|figure|table)\b",+ flags=re.IGNORECASE,+)+_INTERNAL_QUESTION_MARKER_RE = re.compile(+ r"\s*\[(?:[^\]]*\bUser\s+(?:Query|Prompt|Request)\b[^\]]*|[^\]]*\bIMPORTANT\b[^\]]*)\]\s*",+ flags=re.IGNORECASE,+)+_SUMMARY_TAG_RE = re.compile(r"<summary\b[^>]*>([\s\S]*?)</summary>", flags=re.IGNORECASE)+++def _shorten_log_text(value, limit: int = 160) -> str:+ text = " ".join(str(value or "").split())+ if len(text) <= limit:+ return text+ return f"{text[: limit - 1]}..."+++def _normalize_user_facing_background_terms(text: str) -> str:+ value = str(text or "")+ return value.replace("背景模型", "后台模型").replace("背景 model", "后台模型")+++def clean_delegation_question_for_display(question: str) -> str:+ """Remove internal routing markers while preserving the actual user question."""+ value = str(question or "").strip()+ if not value:+ return ""+ value = _INTERNAL_QUESTION_MARKER_RE.sub(" ", value)+ value = re.sub(+ r"^\s*请(?:回答|解答)这道(?:简答题|数学题|题目|问题)[,,、\s]*"+ r"(?:并(?:提供|给出)必要的推理过程和最终答案)?[::]\s*",+ "",+ value,+ )+ value = re.sub(r"[ \t]{2,}", " ", value)+ value = re.sub(r"([::])\s+", r"\1", value)+ value = re.sub(r"\s+\n", "\n", value)+ value = re.sub(r"\n{3,}", "\n\n", value)+ return value.strip()+++def _is_internal_question_marker_only(question: str) -> bool:+ value = str(question or "").strip()+ if not value:+ return False+ return not _INTERNAL_QUESTION_MARKER_RE.sub(" ", value).strip()+++def strip_background_thinking(text: str) -> str:+ """Remove explicit reasoning wrapper tags before rendering or foreground handoff."""+ value = str(text or "").strip()+ if not value:+ return ""++ value = _THINK_BLOCK_RE.sub("", value).strip()+ value = _strip_unclosed_leading_think(value)+ value = _LOOSE_THINK_TAG_RE.sub("", value).strip()++ label_match = _FINAL_ANSWER_LABEL_RE.search(value)+ if label_match and label_match.start() <= 4000:+ value = value[label_match.end() :].strip()++ return value+++def _strip_unclosed_leading_think(value: str) -> str:+ if not _LEADING_THINK_TAG_RE.match(value):+ return value.strip()+ body = _LEADING_THINK_TAG_RE.sub("", value, count=1).strip()+ return body+++@dataclass(frozen=True)+class DelegationRequest:+ foreground_text: str+ question: str+ original_foreground_text: str = ""+ raw_text: str = ""+ raw_question: str = ""+++@dataclass+class BackgroundFrame:+ image: Image.Image+ timestamp: Optional[float] = None+ timestamp_kind: Optional[str] = None+ pts: Optional[int] = None+++def parse_delegation(text: str) -> Optional[DelegationRequest]:+ """Extract foreground response text and delegated question from model output."""+ if not text:+ return None++ raw_text = str(text)+ internal_call = _parse_internal_background_call(raw_text)+ if internal_call:+ return internal_call++ lower_text = raw_text.lower()+ tag_matches = [+ (lower_text.find("</delegation>"), len("</delegation>")),+ (lower_text.find("<delegation>"), len("<delegation>")),+ ]+ tag_matches = [(index, size) for index, size in tag_matches if index >= 0]+ if not tag_matches:+ return None++ tag_index, tag_size = min(tag_matches, key=lambda item: item[0])+ original_foreground_text = raw_text[:tag_index].strip()+ raw_question = raw_text[tag_index + tag_size :].strip()+ question = clean_delegation_question_for_display(raw_question)+ if not question and not _is_internal_question_marker_only(raw_question):+ return None++ return DelegationRequest(+ foreground_text=BACKGROUND_DELEGATION_FOREGROUND_TEXT,+ question=question,+ original_foreground_text=_normalize_user_facing_background_terms(original_foreground_text),+ raw_text=raw_text,+ raw_question=raw_question,+ )+++def _parse_internal_background_call(text: str) -> Optional[DelegationRequest]:+ tag = "<|background_call|>"+ tag_index = text.find(tag)+ if tag_index < 0:+ return None++ original_foreground_text = text[:tag_index].strip()+ call_payload = text[tag_index + len(tag) :].strip()+ parsed_payload = _extract_json_object(call_payload)+ question = ""+ if parsed_payload:+ query = parsed_payload.get("query")+ if isinstance(query, str):+ question = query.strip()+ if not question:+ question = call_payload.strip()+ raw_question = question+ question = clean_delegation_question_for_display(raw_question)+ if not question and not _is_internal_question_marker_only(raw_question):+ return None++ return DelegationRequest(+ foreground_text=BACKGROUND_DELEGATION_FOREGROUND_TEXT,+ question=question,+ original_foreground_text=_normalize_user_facing_background_terms(original_foreground_text),+ raw_text=text,+ raw_question=raw_question,+ )+++def _extract_json_object(text: str) -> Optional[dict]:+ decoder = json.JSONDecoder()+ value = str(text or "").strip()+ if not value:+ return None+ for index, char in enumerate(value):+ if char != "{":+ continue+ try:+ parsed, _ = decoder.raw_decode(value[index:])+ except json.JSONDecodeError:+ continue+ if isinstance(parsed, dict):+ return parsed+ return None+++def build_background_handoff_summary(+ question: str,+ result: str,+ rich: Optional[dict] = None,+ *,+ max_chars: int = BACKGROUND_HANDOFF_MAX_CHARS,+) -> str:+ """Create a bounded digest that the interaction model can safely use."""+ answer = str(result or "").strip()+ if not answer:+ return ""++ rich = rich or extract_rich_content(answer)+ parts = [f"用户委托问题: {str(question or '').strip()}"]++ chart = rich.get("chart") if isinstance(rich, dict) else None+ if chart:+ parts.append(+ "后台产物: 柱状图"+ + (f"《{chart.get('title')}》" if chart.get("title") else "")+ + "。完整图表和数据留在后台结果气泡中,interaction 只读取自然语言摘要。"+ )++ html_text = rich.get("html") if isinstance(rich, dict) else ""+ if html_text:+ title_match = re.search(r"<title[^>]*>(.*?)</title>", html_text, flags=re.IGNORECASE | re.DOTALL)+ title = html.unescape(title_match.group(1)).strip() if title_match else ""+ parts.append(+ "后台产物: 静态 HTML/网页预览"+ + (f",标题: {title}" if title else "")+ + f",HTML 长度约 {len(html_text)} 字符"+ + (",可能被截断" if rich.get("html_incomplete") else "")+ + "。完整内容留在后台结果气泡中,interaction 只读取这份摘要。"+ )++ explanation = _strip_structured_blocks_for_handoff(answer).strip()+ if not explanation and not (chart or html_text):+ explanation = answer+ if explanation:+ parts.append("核心内容摘录:\n" + _truncate_handoff_text(explanation, max_chars // 2))++ return _truncate_handoff_text("\n\n".join(part for part in parts if part), max_chars)+++def _strip_structured_blocks_for_handoff(text: str) -> str:+ value = str(text or "")+ value = re.sub(+ r"```[ \t]*(?:html|json)[ \t]*\r?\n[\s\S]*?(?:\r?\n```|$)",+ "",+ value,+ flags=re.IGNORECASE,+ )+ value = re.sub(+ r"(?:以下|下面|上方|下方)?[^。!?!?\n]*(?:JSON|json|代码块|图表数据|绘图数据|可直接用于绘图|可视化数据|chart)[^。!?!?\n]*[。!?!?]?",+ "",+ value,+ flags=re.IGNORECASE,+ )+ start_matches = [+ match.start()+ for match in (+ re.search(r"<!doctype\s+html\b", value, flags=re.IGNORECASE),+ re.search(r"<html\b", value, flags=re.IGNORECASE),+ )+ if match+ ]+ if start_matches:+ value = value[: min(start_matches)]+ return value.strip()+++def _truncate_handoff_text(text: str, max_chars: int) -> str:+ value = re.sub(r"\n{3,}", "\n\n", str(text or "").strip())+ if len(value) <= max_chars:+ return value+ return value[: max(0, max_chars - 20)].rstrip() + "\n...[已截断]"+++class BackgroundModelService:+ """Caches recent frames and solves delegated questions asynchronously."""++ def __init__(+ self,+ session_id: str,+ notify_callback: Optional[Callable[[dict], None]] = None,+ api_base: str = BACKGROUND_AGENT_API_URL,+ model: str = BACKGROUND_MODEL_NAME,+ max_subagents: int = BACKGROUND_MAX_SUBAGENTS,+ api_key: Optional[str] = None,+ wire_api: Optional[str] = None,+ reasoning_effort: Optional[str] = None,+ disable_response_storage: Optional[bool] = None,+ max_tokens: Optional[int] = None,+ timeout_seconds: float = BACKGROUND_TIMEOUT_SECONDS,+ summarizer_api_base: str = BACKGROUND_SUMMARIZER_API_BASE,+ summarizer_model: str = BACKGROUND_SUMMARIZER_MODEL,+ summarizer_timeout_seconds: float = BACKGROUND_SUMMARIZER_TIMEOUT_SECONDS,+ frame_multiplier: int = BACKGROUND_FRAME_MULTIPLIER,+ max_frames: Optional[int] = None,+ foreground_fps: float = BACKGROUND_DEFAULT_FOREGROUND_FPS,+ resize_long_edge: int = BACKGROUND_FRAME_RESIZE_LONG_EDGE,+ jpeg_quality: int = BACKGROUND_FRAME_JPEG_QUALITY,+ enabled: bool = True,+ ):+ self.session_id = session_id+ self.notify_callback = notify_callback+ self.api_base = str(api_base or BACKGROUND_AGENT_API_URL).rstrip("/")+ self.model = model+ self.max_subagents = max(1, int(max_subagents or BACKGROUND_MAX_SUBAGENTS))+ self._legacy_api_key = api_key+ self._legacy_wire_api = wire_api+ self._legacy_reasoning_effort = reasoning_effort+ self._legacy_disable_response_storage = disable_response_storage+ self._legacy_max_tokens = max_tokens+ self.timeout_seconds = float(timeout_seconds)+ self.summarizer_api_base = str(summarizer_api_base or BACKGROUND_SUMMARIZER_API_BASE).rstrip("/")+ self.summarizer_model = str(summarizer_model or BACKGROUND_SUMMARIZER_MODEL)+ self.summarizer_timeout_seconds = max(1.0, float(summarizer_timeout_seconds))+ self.frame_multiplier = max(1, int(frame_multiplier))+ self.max_frame_count = self._normalize_max_frames(+ max_frames if max_frames is not None else BACKGROUND_DEFAULT_MAX_FRAMES+ )+ self.foreground_fps = self._normalize_foreground_fps(foreground_fps)+ self.resize_long_edge = self._normalize_resize_long_edge(resize_long_edge)+ self.jpeg_quality = min(max(40, int(jpeg_quality)), 95)+ self.enabled = bool(enabled)+ self._frame_buffer: deque[BackgroundFrame] = deque()+ self._active_tasks: set[asyncio.Task] = set()+ self._closed = False+ self._task_sequence = 0+ self._last_cached_frame_time: Optional[float] = None+ self._resize_frame_buffer()++ def _normalize_max_frames(self, value: Optional[int]) -> Optional[int]:+ if value is None:+ return None+ try:+ max_frames = int(value)+ except (TypeError, ValueError):+ return None+ if max_frames <= 0:+ return BACKGROUND_DEFAULT_MAX_FRAMES+ return min(max_frames, BACKGROUND_MAX_FRAME_LIMIT)++ def _normalize_foreground_fps(self, value) -> float:+ try:+ fps = float(value)+ except (TypeError, ValueError):+ return BACKGROUND_DEFAULT_FOREGROUND_FPS+ if fps <= 0:+ return BACKGROUND_DEFAULT_FOREGROUND_FPS+ return min(fps, 60.0)++ def _normalize_resize_long_edge(self, value) -> int:+ try:+ long_edge = int(value)+ except (TypeError, ValueError):+ return BACKGROUND_FRAME_RESIZE_LONG_EDGE+ if long_edge <= 0:+ return 0+ return min(max(256, long_edge), 2048)++ def _background_fps(self) -> float:+ return min(+ max(0.1, self.foreground_fps * float(self.frame_multiplier)),+ 60.0,+ )++ def _sample_interval_seconds(self) -> float:+ return 1.0 / self._background_fps()++ def _target_frame_count(self) -> int:+ return min(max(1, int(self.max_frame_count or BACKGROUND_DEFAULT_MAX_FRAMES)), BACKGROUND_MAX_FRAME_LIMIT)++ def _resize_frame_buffer(self) -> None:+ maxlen = self._target_frame_count()+ if self._frame_buffer.maxlen == maxlen:+ return+ self._frame_buffer = deque(list(self._frame_buffer)[-maxlen:], maxlen=maxlen)++ def get_config(self) -> dict:+ return {+ "enabled": self.enabled,+ "api_base": self.api_base,+ "model": self.model,+ "provider": BACKGROUND_MODEL_PROVIDER,+ "web_search_enabled": True,+ "sandbox": "yolo",+ "max_subagents": self.max_subagents,+ "timeout_seconds": self.timeout_seconds,+ "summarizer_api_base": self.summarizer_api_base,+ "summarizer_model": self.summarizer_model,+ "summarizer_timeout_seconds": self.summarizer_timeout_seconds,+ "frame_multiplier": self.frame_multiplier,+ "max_frames": self.max_frame_count,+ "foreground_fps": self.foreground_fps,+ "background_fps": self._background_fps(),+ "sample_interval_seconds": self._sample_interval_seconds(),+ "target_frame_count": self._target_frame_count(),+ "cached_frame_count": len(self._frame_buffer),+ "resize_long_edge": self.resize_long_edge,+ "jpeg_quality": self.jpeg_quality,+ }++ def update_config(+ self,+ *,+ enabled: Optional[bool] = None,+ frame_multiplier: Optional[int] = None,+ max_frames: Optional[int] = None,+ foreground_fps: Optional[float] = None,+ resize_long_edge: Optional[int] = None,+ ) -> dict:+ if enabled is not None:+ self.enabled = bool(enabled)+ if frame_multiplier is not None:+ self.frame_multiplier = min(max(1, int(frame_multiplier)), 10)+ if max_frames is not None:+ self.max_frame_count = self._normalize_max_frames(max_frames)+ if foreground_fps is not None:+ self.foreground_fps = self._normalize_foreground_fps(foreground_fps)+ if resize_long_edge is not None:+ self.resize_long_edge = self._normalize_resize_long_edge(resize_long_edge)+ self._resize_frame_buffer()+ return self.get_config()++ def update_summary_api(+ self,+ *,+ api_base: Optional[str] = None,+ model: Optional[str] = None,+ ) -> dict:+ if api_base:+ self.summarizer_api_base = str(api_base).rstrip("/")+ if model:+ self.summarizer_model = str(model)+ return self.get_config()++ def set_foreground_frames_per_batch(self, frames_per_batch: int) -> None:+ # Kept for older callers; background sampling is based on foreground FPS.+ self._resize_frame_buffer()++ def set_foreground_sampling(+ self,+ *,+ process_interval_seconds: Optional[float] = None,+ frames_per_batch: Optional[int] = None,+ ) -> None:+ if process_interval_seconds is None:+ return+ try:+ interval = float(process_interval_seconds)+ batch = max(1, int(frames_per_batch or 1))+ except (TypeError, ValueError):+ return+ if interval <= 0:+ return+ self.foreground_fps = self._normalize_foreground_fps(batch / interval)++ def should_sample_frame(self, wall_time: Optional[float] = None) -> bool:+ if self._closed or not self.enabled:+ return False+ sample_time = float(wall_time if wall_time is not None else time.time())+ return (+ self._last_cached_frame_time is None+ or sample_time - self._last_cached_frame_time >= self._sample_interval_seconds()+ )++ def add_frame(+ self,+ image: Image.Image,+ *,+ timestamp: Optional[float] = None,+ timestamp_kind: Optional[str] = None,+ pts: Optional[int] = None,+ foreground_frames_per_batch: Optional[int] = None,+ wall_time: Optional[float] = None,+ ) -> None:+ if self._closed or image is None:+ return+ if foreground_frames_per_batch is not None:+ self.set_foreground_frames_per_batch(foreground_frames_per_batch)++ sample_time = float(wall_time if wall_time is not None else time.time())+ if not self.should_sample_frame(sample_time):+ return++ try:+ image_copy = self._prepare_frame_image(image)+ except Exception:+ logger.warning("[%s] Failed to copy background frame", self.session_id, exc_info=True)+ return++ self._last_cached_frame_time = sample_time+ self._frame_buffer.append(+ BackgroundFrame(+ image=image_copy,+ timestamp=timestamp,+ timestamp_kind=timestamp_kind,+ pts=pts,+ )+ )++ def _prepare_frame_image(self, image: Image.Image) -> Image.Image:+ image_copy = image.copy()+ if image_copy.mode != "RGB":+ image_copy = image_copy.convert("RGB")+ if self.resize_long_edge:+ width, height = image_copy.size+ long_edge = max(width, height)+ if long_edge > self.resize_long_edge:+ scale = self.resize_long_edge / float(long_edge)+ new_size = (+ max(1, int(round(width * scale))),+ max(1, int(round(height * scale))),+ )+ resampling = getattr(getattr(Image, "Resampling", Image), "LANCZOS")+ image_copy = image_copy.resize(new_size, resampling)+ return image_copy++ def _snapshot_frames(self) -> list[BackgroundFrame]:+ return list(self._frame_buffer)++ def _notify(self, payload: dict) -> None:+ if not self.notify_callback:+ return+ try:+ self.notify_callback(payload)+ except Exception:+ logger.warning("[%s] Failed to send background notification", self.session_id, exc_info=True)++ def handle_foreground_response(self, text: str, metrics: Optional[dict] = None) -> str:+ """Start background work when a foreground response contains delegation."""+ delegation = parse_delegation(text)+ if not delegation:+ return text+ original_question = clean_delegation_question_for_display(+ str((metrics or {}).get("user_prompt") or "")+ )+ if original_question:+ delegation = replace(delegation, question=original_question)+ if not delegation.question:+ fallback_question = original_question+ if fallback_question:+ logger.warning(+ "[%s] Background delegation used user prompt fallback because delegated question was only an internal marker: raw_question=%s fallback=%s",+ self.session_id,+ _shorten_log_text(delegation.raw_question),+ _shorten_log_text(fallback_question),+ )+ delegation = replace(delegation, question=fallback_question)+ else:+ logger.warning(+ "[%s] Background delegation skipped: delegated question was only an internal marker and no user prompt fallback was available: raw_question=%s",+ self.session_id,+ _shorten_log_text(delegation.raw_question),+ )+ return delegation.foreground_text+ if not self.enabled or self._closed:+ logger.info(+ "[%s] Background delegation skipped: enabled=%s closed=%s question=%s",+ self.session_id,+ self.enabled,+ self._closed,+ _shorten_log_text(delegation.question),+ )+ return delegation.foreground_text++ self._task_sequence += 1+ task_id = f"bg-{self.session_id}-{self._task_sequence}-{uuid.uuid4().hex[:8]}"+ frames = self._snapshot_frames()+ logger.info(+ "[%s] Background delegation queued: task_id=%s frames=%s target_frames=%s question=%s",+ self.session_id,+ task_id,+ len(frames),+ self._target_frame_count(),+ _shorten_log_text(delegation.question),+ )+ task = asyncio.create_task(+ self._run_delegation_task(task_id, delegation, frames, metrics or {}),+ name=f"background-delegation:{self.session_id}:{self._task_sequence}",+ )+ self._active_tasks.add(task)+ task.add_done_callback(self._discard_task)+ return delegation.foreground_text++ def _discard_task(self, task: asyncio.Task) -> None:+ self._active_tasks.discard(task)+ if task.cancelled():+ return+ try:+ err = task.exception()+ except asyncio.CancelledError:+ return+ if err:+ logger.warning(+ "[%s] Background delegation task ended with unhandled error: %s",+ self.session_id,+ err,+ exc_info=(type(err), err, err.__traceback__),+ )++ async def _run_delegation_task(+ self,+ task_id: str,+ delegation: DelegationRequest,+ frames: list[BackgroundFrame],+ metrics: dict,+ ) -> None:+ start_time = time.perf_counter()+ user_question = str(delegation.question or "").strip()+ try:+ await asyncio.sleep(0)+ logger.info(+ "[%s] Background delegation started: task_id=%s frames=%s model=%s",+ self.session_id,+ task_id,+ len(frames),+ self.model,+ )+ self._notify(+ {+ "type": "background_task_started",+ "task_id": task_id,+ "question": user_question,+ "foreground_text": delegation.foreground_text,+ "original_foreground_text": delegation.original_foreground_text,+ "context_excluded": True,+ "frame_count": len(frames),+ "model": self.model,+ "metrics": metrics,+ }+ )+ result_payload = await asyncio.wait_for(+ self.solve_delegation(+ task_id=task_id,+ question=user_question,+ foreground_text=delegation.foreground_text,+ frames=frames,+ ),+ timeout=self.timeout_seconds,+ )+ solve_latency_ms = (time.perf_counter() - start_time) * 1000+ result_payload = self._normalize_background_result(result_payload)+ result = result_payload["text"]+ summary_text = result_payload.get("summary_text") or result_payload.get("background_summary") or ""+ rich = result_payload.get("rich") or extract_rich_content(result)+ rich = ensure_html_artifact(rich, task_id=task_id)+ handoff = summary_text or build_background_handoff_summary(user_question, result, rich)+ summary_latency_ms = 0.0+ latency_ms = (time.perf_counter() - start_time) * 1000+ background_metrics = result_payload.get("metrics") or {}+ logger.info(+ "[%s] Background result ready: chars=%s summary_chars=%s handoff_chars=%s solve_latency_ms=%.0f html_chars=%s html_incomplete=%s chart=%s",+ self.session_id,+ len(result or ""),+ len(summary_text or ""),+ len(handoff or ""),+ solve_latency_ms,+ len(rich.get("html") or ""),+ bool(rich.get("html_incomplete")),+ bool(rich.get("chart")),+ )+ self._notify(+ rewrite_payload_local_file_links(+ {+ "type": "background_result_ready",+ "task_id": task_id,+ "question": user_question,+ "foreground_text": delegation.foreground_text,+ "original_foreground_text": delegation.original_foreground_text,+ "text": result,+ "rich": rich,+ "summary_text": summary_text,+ "background_summary": summary_text or result,+ "interaction_handoff": {+ "digest_only": True,+ "summary": handoff,+ "source": "background_model",+ },+ "context_excluded": True,+ "model": self.model,+ "metrics": {+ "latency_ms": latency_ms,+ "solve_latency_ms": solve_latency_ms,+ "summary_latency_ms": summary_latency_ms,+ "frame_count": len(frames),+ "background_service": background_metrics,+ },+ },+ )+ )+ except asyncio.CancelledError:+ latency_ms = (time.perf_counter() - start_time) * 1000+ logger.info(+ "[%s] Background delegation cancelled: task_id=%s latency_ms=%.0f",+ self.session_id,+ task_id,+ latency_ms,+ )+ raise+ except Exception as err:+ latency_ms = (time.perf_counter() - start_time) * 1000+ logger.warning("[%s] Background delegation failed: %s", self.session_id, err)+ self._notify(+ {+ "type": "background_result_error",+ "task_id": task_id,+ "question": user_question,+ "foreground_text": delegation.foreground_text,+ "original_foreground_text": delegation.original_foreground_text,+ "error": str(err),+ "context_excluded": True,+ "model": self.model,+ "metrics": {+ "latency_ms": latency_ms,+ "frame_count": len(frames),+ },+ }+ )++ async def solve_delegation(+ self,+ *,+ task_id: str,+ question: str,+ foreground_text: str,+ frames: Optional[list[BackgroundFrame]] = None,+ ) -> dict:+ frames = frames if frames is not None else self._snapshot_frames()+ payload = {+ "session_id": self.session_id,+ "task_id": task_id,+ "question": str(question or ""),+ "foreground_text": str(foreground_text or ""),+ "max_subagents": self.max_subagents,+ "timeout_seconds": self.timeout_seconds,+ "frames": [self._frame_to_payload(frame) for frame in frames],+ }+ timeout = httpx.Timeout(self.timeout_seconds + 5.0, connect=10.0)+ url = f"{self.api_base}/v1/solve"+ async with httpx.AsyncClient(timeout=timeout) as client:+ response = await client.post(url, json=payload)+ response.raise_for_status()+ data = response.json()+ return self._normalize_background_result(data)++ async def summarize_background_result(self, *, question: str, result: str) -> str:+ text = str(result or "").strip()+ if not text:+ return ""+ prompt = (+ "请把下面后台模型的完整回答压缩成给前端摘要卡展示的简短摘要。\n"+ "要求:\n"+ "- 使用中文。\n"+ "- 只输出摘要正文,不要标题、列表编号或客套话。\n"+ "- 1 到 2 句话,保留结论/关键步骤/产物类型。\n"+ "- 不要补充原文没有的信息。\n\n"+ f"用户问题:{str(question or '').strip()}\n\n"+ f"后台完整回答:\n{text}"+ )+ payload = {+ "model": self.summarizer_model,+ "user": f"background-summary:{self.session_id}",+ "messages": [+ {+ "role": "user",+ "content": prompt,+ }+ ],+ "max_tokens": BACKGROUND_SUMMARIZER_MAX_TOKENS,+ "temperature": 0.1,+ "top_p": 0.9,+ }+ url = f"{self.summarizer_api_base}/chat/completions"+ try:+ timeout = httpx.Timeout(self.summarizer_timeout_seconds, connect=5.0)+ async with httpx.AsyncClient(timeout=timeout) as client:+ response = await client.post(+ url,+ json=payload,+ headers={"x-streaming-session": f"background-summary:{self.session_id}"},+ )+ response.raise_for_status()+ data = response.json()+ summary = self._extract_chat_completion_text(data)+ return self._normalize_summary_text(summary)+ except Exception as err:+ logger.warning(+ "[%s] Background summary model failed: %s",+ self.session_id,+ err,+ )+ return ""++ def _frame_to_payload(self, frame: BackgroundFrame) -> dict:+ return {+ "image_url": self._image_to_data_url(frame.image),+ "timestamp": frame.timestamp,+ "timestamp_kind": frame.timestamp_kind,+ "pts": frame.pts,+ }++ def _normalize_background_result(self, value) -> dict:+ if isinstance(value, str):+ text = strip_background_thinking(value)+ summary, text = self._extract_summary_tag(text)+ return {+ "text": text,+ "rich": None,+ "summary_text": summary,+ "background_summary": summary,+ "metrics": {},+ }+ if not isinstance(value, dict):+ text = str(value or "").strip()+ summary, text = self._extract_summary_tag(text)+ return {+ "text": text,+ "rich": None,+ "summary_text": summary,+ "background_summary": summary,+ "metrics": {},+ }+ status = str(value.get("status") or "completed")+ error = value.get("error")+ if status != "completed":+ raise RuntimeError(str(error or f"Background service returned status={status}"))+ text = self._normalize_text_value(value.get("text") or value.get("answer"))+ text = strip_background_thinking(text)+ tagged_summary, text = self._extract_summary_tag(text)+ if not text:+ raise RuntimeError("Background service returned empty text")+ summary_text = (+ self._normalize_summary_text(value.get("summary_text"))+ or self._normalize_summary_text(value.get("background_summary"))+ or tagged_summary+ )+ rich = value.get("rich") if isinstance(value.get("rich"), dict) else None+ existing_metrics = value.get("metrics") if isinstance(value.get("metrics"), dict) else {}+ metrics = {+ "thread_id": value.get("thread_id"),+ "usage": value.get("usage"),+ "duration_ms": value.get("duration_ms"),+ "events_digest": value.get("events_digest"),+ }+ metrics = {**metrics, **existing_metrics}+ return {+ "text": text,+ "rich": rich,+ "summary_text": summary_text,+ "background_summary": summary_text,+ "metrics": metrics,+ }++ def _extract_summary_tag(self, text: str) -> tuple[str, str]:+ value = str(text or "").strip()+ match = _SUMMARY_TAG_RE.search(value)+ if not match:+ return "", value+ summary = self._normalize_summary_text(match.group(1))+ body = (value[: match.start()] + value[match.end() :]).strip()+ return summary, body++ def _extract_chat_completion_text(self, value) -> str:+ if not isinstance(value, dict):+ return ""+ choices = value.get("choices")+ if not isinstance(choices, list) or not choices:+ return ""+ first = choices[0]+ if not isinstance(first, dict):+ return ""+ message = first.get("message")+ if isinstance(message, dict):+ return self._normalize_text_value(message.get("content"))+ return self._normalize_text_value(first.get("text"))++ def _normalize_summary_text(self, value) -> str:+ text = self._normalize_text_value(value)+ text = strip_background_thinking(text)+ text = re.sub(r"^\s*(?:摘要|总结|简要摘要|简述)\s*[::]\s*", "", text)+ text = re.sub(r"\n{3,}", "\n\n", text).strip()+ return text++ def _normalize_text_value(self, value) -> str:+ if value is None:+ return ""+ if isinstance(value, str):+ return value.strip()+ if isinstance(value, list):+ parts = []+ for item in value:+ text = ""+ if isinstance(item, dict):+ text = item.get("text") or item.get("content") or item.get("value") or ""+ else:+ text = (+ getattr(item, "text", None)+ or getattr(item, "content", None)+ or getattr(item, "value", None)+ or ""+ )+ normalized = self._normalize_text_value(text)+ if normalized:+ parts.append(normalized)+ return "\n".join(parts).strip()+ if isinstance(value, dict):+ for key in ("text", "content", "value"):+ text = self._normalize_text_value(value.get(key))+ if text:+ return text+ return self._json_preview(value)+ return str(value).strip()++ def _json_preview(self, value) -> str:+ try:+ return json.dumps(value, ensure_ascii=False, default=str, indent=2).strip()+ except Exception:+ return str(value).strip()++ def _format_frame_timestamp(self, frame: BackgroundFrame) -> str:+ if frame.timestamp is None:+ return "timestamp unavailable"+ try:+ timestamp = float(frame.timestamp)+ except (TypeError, ValueError):+ return str(frame.timestamp)+ suffix = "relative seconds" if frame.timestamp_kind == "relative_seconds" else "seconds"+ return f"{timestamp:.3f} {suffix}"++ def _image_to_data_url(self, image: Image.Image) -> str:+ img_byte_arr = io.BytesIO()+ image.save(img_byte_arr, format="JPEG", quality=self.jpeg_quality, optimize=True)+ img_base64 = base64.b64encode(img_byte_arr.getvalue()).decode("utf-8")+ return f"data:image/jpeg;base64,{img_base64}"++ async def cancel_active_requests(self, timeout: float = 2.0) -> int:+ current_task = asyncio.current_task()+ tasks = [+ task+ for task in self._active_tasks+ if task is not current_task and not task.done()+ ]+ if not tasks:+ return 0++ logger.info("[%s] Cancelling %s background delegation task(s)", self.session_id, len(tasks))+ for task in tasks:+ task.cancel()+ done, pending = await asyncio.wait(tasks, timeout=timeout)+ if done:+ await asyncio.gather(*done, return_exceptions=True)+ return len(tasks)++ async def close(self, cancel_requests: bool = True) -> None:+ self._closed = True+ if cancel_requests:+ await self.cancel_active_requests()+ self._frame_buffer.clear()+++def extract_rich_content(text: str) -> dict:+ """Extract structured rich content from a background model answer."""+ html_details = extract_html_details(text)+ rich = {+ "html": html_details["html"],+ "html_incomplete": html_details["incomplete"],+ "chart": extract_bar_chart(text),+ }+ return ensure_html_artifact(rich)+++def ensure_html_artifact(rich: Optional[dict], *, task_id: str = "") -> dict:+ """Persist generated HTML so users can open a fully clickable page."""+ if not isinstance(rich, dict):+ return rich or {}+ html_text = str(rich.get("html") or "").strip()+ if not html_text:+ return rich+ if str(rich.get("html_url") or "").strip():+ return rich++ artifact_path = _write_html_artifact(html_text, task_id=task_id)+ if not artifact_path:+ return rich+ url = local_file_url_for_path(str(artifact_path))+ if not url:+ return rich+ next_rich = dict(rich)+ next_rich["html_path"] = str(artifact_path)+ next_rich["html_url"] = url+ return next_rich+++def _write_html_artifact(html_text: str, *, task_id: str = "") -> Optional[Path]:+ try:+ BACKGROUND_HTML_ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)+ safe_task = re.sub(r"[^A-Za-z0-9_.-]+", "-", str(task_id or "").strip()).strip("-")+ filename = f"{safe_task or uuid.uuid4().hex}.html"+ path = BACKGROUND_HTML_ARTIFACT_DIR / filename+ path.write_text(str(html_text or ""), encoding="utf-8")+ return path+ except Exception:+ logger.warning("Failed to write background HTML artifact", exc_info=True)+ return None+++def extract_html_document(text: str) -> str:+ return extract_html_details(text)["html"]+++def extract_html_details(text: str) -> dict:+ raw_text = html.unescape(str(text or "")).strip()+ if not raw_text:+ return {"html": "", "incomplete": False}++ explicit_candidates = []+ explicit_candidates.extend(_extract_fenced_block_candidates(raw_text, "html", include_unclosed=True))++ for block in _extract_fenced_blocks(raw_text, "json"):+ try:+ parsed = json.loads(block)+ except json.JSONDecodeError:+ continue+ if isinstance(parsed, dict) and parsed.get("type") == "html" and isinstance(parsed.get("html"), str):+ explicit_candidates.append({"text": parsed["html"], "incomplete": False})++ best = _pick_best_html_candidate(explicit_candidates)+ if best:+ return {"html": best["html"], "incomplete": best["incomplete"]}++ best = _pick_best_html_candidate([{"text": raw_text, "incomplete": False}])+ if best:+ return {"html": best["html"], "incomplete": best["incomplete"]}+ return {"html": "", "incomplete": False}+++def _pick_best_html_candidate(candidates: list[dict]) -> Optional[dict]:+ best = None+ for candidate in candidates:+ document, incomplete = _normalize_html_document_with_status(+ candidate["text"],+ source_incomplete=candidate.get("incomplete", False),+ )+ if document:+ scored = {+ "html": document,+ "incomplete": incomplete,+ "score": _score_html_candidate(document, incomplete),+ }+ if best is None or scored["score"] > best["score"]:+ best = scored+ return best+++def extract_bar_chart(text: str) -> Optional[dict]:+ raw_text = str(text or "").strip()+ candidates = _extract_fenced_blocks(raw_text, "json")+ if raw_text.startswith("{") and raw_text.endswith("}"):+ candidates.insert(0, raw_text)++ for candidate in candidates:+ try:+ parsed = json.loads(candidate)+ except json.JSONDecodeError:+ continue+ if not isinstance(parsed, dict) or parsed.get("type") != "bar_chart":+ continue+ labels = parsed.get("labels")+ values = parsed.get("values")+ if not isinstance(labels, list) or not isinstance(values, list) or len(labels) != len(values):+ continue+ try:+ numeric_values = [float(value) for value in values]+ except (TypeError, ValueError):+ continue+ return {+ "type": "bar_chart",+ "title": str(parsed.get("title") or ""),+ "labels": [str(label) for label in labels],+ "values": numeric_values,+ }+ return None+++def _extract_fenced_blocks(text: str, language: str = "") -> list[str]:+ return [+ candidate["text"]+ for candidate in _extract_fenced_block_candidates(+ text,+ language,+ include_unclosed=False,+ )+ ]+++def _extract_fenced_block_candidates(+ text: str,+ language: str = "",+ *,+ include_unclosed: bool = False,+) -> list[dict]:+ blocks = []+ raw_text = str(text or "")+ pattern = re.compile(r"```[ \t]*([a-zA-Z0-9_-]*)[ \t]*\r?\n?", re.MULTILINE)+ language = language.lower()+ for match in pattern.finditer(raw_text):+ lang = (match.group(1) or "").lower()+ if not language or lang == language:+ content_start = match.end()+ closing_index = raw_text.find("```", content_start)+ if closing_index >= 0:+ blocks.append(+ {+ "text": raw_text[content_start:closing_index].strip(),+ "incomplete": False,+ }+ )+ elif include_unclosed:+ blocks.append(+ {+ "text": raw_text[content_start:].strip(),+ "incomplete": True,+ }+ )+ return blocks+++def _normalize_html_document(value: str) -> str:+ return _normalize_html_document_with_status(value)[0]+++def _normalize_html_document_with_status(+ value: str,+ *,+ source_incomplete: bool = False,+) -> tuple[str, bool]:+ candidate = html.unescape(str(value or "")).strip()+ if not candidate:+ return "", False++ candidate = re.sub(r"^```[ \t]*(?:html)?[ \t]*\r?\n?", "", candidate, flags=re.IGNORECASE).strip()+ candidate = re.sub(r"\r?\n?```[ \t]*$", "", candidate).strip()++ start_matches = [+ match.start()+ for match in (+ re.search(r"<!doctype\s+html\b", candidate, flags=re.IGNORECASE),+ re.search(r"<html\b", candidate, flags=re.IGNORECASE),+ )+ if match+ ]+ if start_matches:+ start_index = min(start_matches)+ end_match = re.search(r"</html\s*>", candidate[start_index:], flags=re.IGNORECASE)+ if end_match:+ end_index = start_index + end_match.end()+ return candidate[start_index:end_index].strip(), False+ return candidate[start_index:].strip(), True++ if re.search(r"<(head|body|main|section|style|div|h1|p)\b", candidate, flags=re.IGNORECASE):+ return (+ f"<!doctype html>\n<html><head><meta charset=\"UTF-8\"></head><body>{candidate}</body></html>",+ source_incomplete or _looks_incomplete_html(candidate),+ )++ return "", False+++def _score_html_candidate(document: str, incomplete: bool) -> int:+ html_text = str(document or "")+ lower = html_text.lower()+ score = min(len(html_text), 20000)+ if not incomplete:+ score += 5000+ if "<style" in lower:+ score += 2500+ if "<body" in lower:+ score += 1500+ if _RENDERABLE_FRAGMENT_RE.search(html_text):+ score += 1500+ score += min(len(re.findall(r"<(?:div|section|main|header|nav|footer|button|h[1-6]|p|li)\b", html_text, flags=re.IGNORECASE)) * 120, 3000)+ placeholder_count = html_text.count("...") + html_text.count("…")+ score -= placeholder_count * 3000+ score -= len(re.findall(r">\s*\.\.\.\s*<", html_text)) * 5000+ return score+++def _looks_incomplete_html(value: str) -> bool:+ candidate = str(value or "")+ checks = (+ (r"<html\b", r"</html\s*>"),+ (r"<body\b", r"</body\s*>"),+ (r"<head\b", r"</head\s*>"),+ (r"<style\b", r"</style\s*>"),+ )+ for open_pattern, close_pattern in checks:+ if re.search(open_pattern, candidate, flags=re.IGNORECASE) and not re.search(+ close_pattern,+ candidate,+ flags=re.IGNORECASE,+ ):+ return True+ return Falsediff --git a/Web_Inference/webui/src/alive_webui/local_file_server.py b/Web_Inference/webui/src/alive_webui/local_file_server.pynew file mode 100644index 0000000..c498cb9--- /dev/null+++ b/Web_Inference/webui/src/alive_webui/local_file_server.py@@ -0,0 +1,261 @@++"""Serve local artifacts produced by background agent tasks."""++import mimetypes+import os+import re+from pathlib import Path+from urllib.parse import quote, unquote, urlparse++from aiohttp import web++LOCAL_FILE_ROUTE = "/api/local-file"+LOCAL_FILE_ROOTS_ENV = "LIVE_VLM_LOCAL_FILE_ROOTS"+PROJECT_ROOT = Path(__file__).resolve().parents[2]+REPO_ROOT = PROJECT_ROOT.parent.parent+++def _legacy_background_env(suffix: str, default: str = "") -> str:+ legacy_name = "BACKGROUND_" + "CO" + "DEX_" + suffix+ return os.environ.get(legacy_name, default)+++def _project_relative_path(value: str) -> Path:+ path = Path(value).expanduser()+ if path.is_absolute():+ return path+ return PROJECT_ROOT / path+++LOCAL_HTML_ARTIFACT_DIR = _project_relative_path(+ os.environ.get("LIVE_VLM_HTML_ARTIFACT_DIR", "html")+)++_DISPLAY_PAYLOAD_TYPES = {"background_result_ready"}+_DISPLAY_TEXT_KEYS = ("text", "summary_text", "background_summary")+_LOCAL_PATH_RE = re.compile(+ r"(?<![\w:/])(/(?:[^\s<>'\"`()\[\]{}]+/)*[^\s<>'\"`()\[\]{}]+\.[A-Za-z0-9]{1,12})"+)+_MARKDOWN_CODE_RE = re.compile(r"(```[\s\S]*?(?:```|$)|`[^`\n]+`)")+_TRAILING_PATH_PUNCTUATION = ".,;:!?,。;:!?"++_INLINE_MIME_PREFIXES = ("image/", "text/")+_INLINE_MIME_TYPES = {+ "application/json",+ "application/pdf",+ "application/xml",+ "application/xhtml+xml",+ "image/svg+xml",+}+_ATTACHMENT_EXTENSIONS = {+ ".7z",+ ".bin",+ ".bz2",+ ".dmg",+ ".exe",+ ".gz",+ ".iso",+ ".lz",+ ".lzma",+ ".rar",+ ".tar",+ ".tgz",+ ".xz",+ ".zip",+ ".zst",+}+++def setup_local_file_routes(app: web.Application) -> None:+ """Register the local artifact file route."""+ app.router.add_get(LOCAL_FILE_ROUTE, serve_local_file)+++async def serve_local_file(request: web.Request) -> web.StreamResponse:+ """Serve a whitelisted local file inline when browsers can render it."""+ raw_path = request.query.get("path", "")+ if not raw_path:+ raise web.HTTPBadRequest(text="Missing local file path")++ file_path = resolve_local_file_path(raw_path)+ if file_path is None:+ raise web.HTTPNotFound(text="Local file is unavailable")++ content_type = guess_local_file_content_type(file_path)+ disposition = "inline" if should_display_inline(file_path, content_type) else "attachment"+ headers = {+ "Cache-Control": "no-store",+ "Content-Disposition": _content_disposition(disposition, file_path.name),+ "Content-Type": content_type,+ "X-Content-Type-Options": "nosniff",+ }+ if disposition == "inline" and content_type == "image/svg+xml":+ headers["Content-Security-Policy"] = (+ "sandbox; default-src 'none'; img-src 'self' data: blob:; "+ "style-src 'unsafe-inline'; media-src 'self' data: blob:; "+ "font-src data:; frame-ancestors 'none'"+ )+ return web.FileResponse(path=file_path, headers=headers)+++def rewrite_payload_local_file_links(payload: dict) -> dict:+ """Rewrite display-only text fields with HTTP links to local artifacts."""+ if not isinstance(payload, dict) or payload.get("type") not in _DISPLAY_PAYLOAD_TYPES:+ return payload++ rewritten = dict(payload)+ changed = False+ for key in _DISPLAY_TEXT_KEYS:+ value = payload.get(key)+ if not isinstance(value, str) or not value.strip():+ continue+ next_value = rewrite_local_file_links(value)+ if next_value != value:+ rewritten[key] = next_value+ changed = True+ return rewritten if changed else payload+++def rewrite_local_file_links(text: str) -> str:+ """Convert existing local file paths in normal text into markdown links."""+ source = str(text or "")+ if not source:+ return ""++ parts = _MARKDOWN_CODE_RE.split(source)+ for index, part in enumerate(parts):+ if not part or part.startswith("`"):+ continue+ parts[index] = _rewrite_local_file_links_in_segment(part)+ return "".join(parts)+++def local_file_url_for_path(path_value: str) -> str:+ """Return the web route URL for a local file if it is safe to expose."""+ file_path = resolve_local_file_path(path_value)+ if file_path is None:+ return ""+ return f"{LOCAL_FILE_ROUTE}?path={quote(str(file_path), safe='')}"+++def resolve_local_file_path(path_value: str) -> Path | None:+ """Resolve a local file path if it exists and is under an allowed root."""+ value = _normalize_path_value(path_value)+ if not value:+ return None++ candidate = Path(value).expanduser()+ if not candidate.is_absolute():+ return None+ try:+ candidate = candidate.resolve(strict=True)+ except (OSError, RuntimeError):+ return None+ if not candidate.is_file() or not _is_allowed_local_file(candidate):+ return None+ return candidate+++def guess_local_file_content_type(path: Path) -> str:+ content_type, _encoding = mimetypes.guess_type(str(path))+ return content_type or "application/octet-stream"+++def should_display_inline(path: Path, content_type: str | None = None) -> bool:+ suffix = path.suffix.lower()+ if suffix in _ATTACHMENT_EXTENSIONS:+ return False+ resolved_type = content_type or guess_local_file_content_type(path)+ return resolved_type in _INLINE_MIME_TYPES or resolved_type.startswith(_INLINE_MIME_PREFIXES)+++def _rewrite_local_file_links_in_segment(segment: str) -> str:+ def replace(match: re.Match) -> str:+ raw_path = match.group(1)+ path_value, trailing = _split_trailing_punctuation(raw_path)+ url = local_file_url_for_path(path_value)+ if not url:+ return raw_path++ previous_char = segment[match.start() - 1] if match.start() > 0 else ""+ if previous_char == "(":+ return f"{url}{trailing}"+ label = Path(path_value).name or path_value+ return f"[{_escape_markdown_label(label)}]({url}){trailing}"++ return _LOCAL_PATH_RE.sub(replace, segment)+++def _split_trailing_punctuation(path_value: str) -> tuple[str, str]:+ value = path_value+ trailing = ""+ while value and value[-1] in _TRAILING_PATH_PUNCTUATION:+ trailing = value[-1] + trailing+ value = value[:-1]+ return value, trailing+++def _normalize_path_value(path_value: str) -> str:+ value = str(path_value or "").strip()+ if not value:+ return ""+ if value.startswith("file://"):+ parsed = urlparse(value)+ value = unquote(parsed.path or "")+ return value+++def _configured_local_file_roots() -> list[Path] | None:+ raw_roots = os.environ.get(LOCAL_FILE_ROOTS_ENV, "").strip()+ if raw_roots == "*":+ return None++ values = []+ if raw_roots:+ values = [item.strip() for item in re.split(r"[:,]", raw_roots) if item.strip()]+ else:+ values = [+ os.environ.get("BACKGROUND_AGENT_WORKSPACE", _legacy_background_env("WORKSPACE")),+ str(LOCAL_HTML_ARTIFACT_DIR),+ str(REPO_ROOT / "agent-workspace"),+ str(PROJECT_ROOT / "agent-workspace"),+ os.getcwd(),+ str(PROJECT_ROOT),+ ]++ roots = []+ seen = set()+ for value in values:+ try:+ root = Path(value).expanduser().resolve(strict=False)+ except (OSError, RuntimeError):+ continue+ key = str(root)+ if key not in seen:+ roots.append(root)+ seen.add(key)+ return roots+++def _is_allowed_local_file(path: Path) -> bool:+ roots = _configured_local_file_roots()+ if roots is None:+ return True+ path_text = str(path)+ for root in roots:+ try:+ if os.path.commonpath([path_text, str(root)]) == str(root):+ return True+ except ValueError:+ continue+ return False+++def _content_disposition(disposition: str, filename: str) -> str:+ ascii_name = filename.encode("ascii", "ignore").decode("ascii") or "download"+ ascii_name = ascii_name.replace("\\", "_").replace('"', "_")+ return f"{disposition}; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(filename)}"+++def _escape_markdown_label(label: str) -> str:+ return str(label or "").replace("\\", "\\\\").replace("[", "\\[").replace("]", "\\]")diff --git a/Web_Inference/webui/src/alive_webui/rtsp_track.py b/Web_Inference/webui/src/alive_webui/rtsp_track.pynew file mode 100644index 0000000..23e1281--- /dev/null+++ b/Web_Inference/webui/src/alive_webui/rtsp_track.py@@ -0,0 +1,294 @@+"""+RTSP Video Track for IP Camera Support++This module provides VideoStreamTrack implementation for RTSP streams,+allowing alive-webui to process IP camera feeds instead of just webcams.++SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+SPDX-License-Identifier: Apache-2.0+"""++import av+import asyncio+import logging+import re+import threading+from typing import Optional+from aiortc import VideoStreamTrack+from av import VideoFrame++# Suppress verbose ffmpeg/libav logging (HEVC decoder errors are normal for IP cameras)+# These POC/slice errors happen due to network packet loss but stream recovers automatically+av.logging.set_level(av.logging.FATAL) # Only show fatal errors that stop the stream++logger = logging.getLogger(__name__)+++class RTSPVideoTrack(VideoStreamTrack):+ """+ Video track that reads from RTSP stream and converts to aiortc VideoFrame.++ This enables processing of IP camera feeds through the same pipeline as webcam input.+ Supports automatic reconnection on stream failure.++ Example:+ track = RTSPVideoTrack("rtsp://192.168.1.100:554/stream")+ frame = await track.recv()+ """++ def __init__(+ self,+ rtsp_url: str,+ reconnect_attempts: int = 5,+ reconnect_delay: float = 2.0,+ options: Optional[dict] = None,+ ):+ """+ Initialize RTSP video track.++ Args:+ rtsp_url: Full RTSP URL (e.g., rtsp://user:[email protected]:554/stream)+ reconnect_attempts: Number of reconnection attempts on failure (default: 5)+ reconnect_delay: Base delay between reconnection attempts in seconds (default: 2.0)+ options: Additional PyAV container options (default: TCP transport)+ """+ super().__init__()+ self.rtsp_url = rtsp_url+ self.reconnect_attempts = reconnect_attempts+ self.reconnect_delay = reconnect_delay+ self.container: Optional[av.container.InputContainer] = None+ self.stream: Optional[av.video.VideoStream] = None+ self._stopped = False+ self._frame_count = 0+ self._read_lock = threading.Lock()++ # Default options for RTSP+ self.options = options or {+ "rtsp_transport": "tcp", # TCP is more reliable than UDP for most networks+ "max_delay": "500000", # 500ms max delay for low latency+ "rtsp_flags": "prefer_tcp",+ }++ # Connect to stream+ self._connect()++ def _sanitize_url(self, url: str) -> str:+ """+ Remove password from URL for safe logging.++ Args:+ url: RTSP URL potentially containing credentials++ Returns:+ URL with password replaced by ****+ """+ return re.sub(r"://([^:]+):([^@]+)@", r"://\1:****@", url)++ def _connect(self):+ """+ Connect to RTSP stream.++ Raises:+ Exception: If connection fails after all attempts+ """+ safe_url = self._sanitize_url(self.rtsp_url)++ try:+ logger.info(f"Connecting to RTSP stream: {safe_url}")++ # Open RTSP stream+ self.container = av.open(self.rtsp_url, options=self.options)++ # Get video stream+ if not self.container.streams.video:+ raise ValueError("No video stream found in RTSP source")++ self.stream = self.container.streams.video[0]++ # Log stream information+ codec = self.stream.codec_context.name+ width = self.stream.width or "unknown"+ height = self.stream.height or "unknown"+ fps = self.stream.average_rate or "unknown"++ logger.info(f"RTSP connected successfully: {codec} {width}x{height} @{fps}fps")++ except Exception as e:+ logger.error(f"Failed to connect to RTSP stream {safe_url}: {e}")+ raise++ async def recv(self) -> VideoFrame:+ """+ Receive next frame from RTSP stream.++ This is called by aiortc framework to get video frames.+ Runs demuxing/decoding in executor to avoid blocking event loop.++ Returns:+ VideoFrame: Next decoded video frame++ Raises:+ StopAsyncIteration: When stream ends or is stopped+ """+ if self._stopped:+ raise StopAsyncIteration++ try:+ # Read frame from container (blocking operation, run in executor)+ loop = asyncio.get_event_loop()+ frame = await loop.run_in_executor(None, self._read_frame)++ if frame is None:+ if not self._stopped:+ logger.warning("RTSP stream ended unexpectedly, attempting reconnection")+ await self._reconnect()+ # Try again after reconnection+ frame = await loop.run_in_executor(None, self._read_frame)+ if frame is None:+ raise StopAsyncIteration+ else:+ raise StopAsyncIteration++ self._frame_count += 1++ # Log progress periodically+ if self._frame_count % 300 == 0: # Every ~10 seconds at 30fps+ logger.debug(f"RTSP: Received {self._frame_count} frames")++ return frame++ except StopAsyncIteration:+ raise+ except Exception as e:+ logger.error(f"Error receiving RTSP frame: {e}", exc_info=True)+ # Try to reconnect on error+ if not self._stopped:+ await self._reconnect()+ raise++ def _read_frame(self) -> Optional[VideoFrame]:+ """+ Read and decode next frame from RTSP stream (blocking).++ This is a blocking operation and should be run in an executor.++ Returns:+ VideoFrame or None if stream ended or error occurred+ """+ with self._read_lock:+ if self._stopped or not self.container or not self.stream:+ return None++ try:+ for packet in self.container.demux(self.stream):+ for frame in packet.decode():+ if isinstance(frame, VideoFrame):+ return frame++ logger.info("RTSP stream reached end of file")+ return None++ except av.error.EOFError:+ logger.warning("RTSP stream EOF")+ return None+ except Exception as e:+ if self._stopped:+ return None+ logger.error(f"Error decoding RTSP frame: {e}")+ return None++ async def _reconnect(self):+ """+ Attempt to reconnect to RTSP stream with exponential backoff.++ Tries multiple times with increasing delay between attempts.+ """+ safe_url = self._sanitize_url(self.rtsp_url)+ logger.info(f"Attempting RTSP reconnection to {safe_url}...")++ # Clean up existing connection+ if self.container:+ try:+ self.container.close()+ except Exception as e:+ logger.debug(f"Error closing container during reconnect: {e}")+ self.container = None+ self.stream = None++ # Try to reconnect with exponential backoff+ for attempt in range(self.reconnect_attempts):+ try:+ logger.info(f"Reconnection attempt {attempt + 1}/{self.reconnect_attempts}")++ # Wait with exponential backoff (2, 4, 8, 16, 32 seconds)+ if attempt > 0:+ delay = self.reconnect_delay * (2 ** (attempt - 1))+ logger.info(f"Waiting {delay}s before reconnection attempt...")+ await asyncio.sleep(delay)++ # Attempt connection+ self._connect()+ logger.info(f"RTSP reconnected successfully on attempt {attempt + 1}")+ return++ except Exception as e:+ logger.warning(f"Reconnection attempt {attempt + 1} failed: {e}")+ if attempt == self.reconnect_attempts - 1:+ logger.error(+ f"RTSP reconnection failed after {self.reconnect_attempts} attempts"+ )+ raise++ def stop(self):+ """+ Stop the RTSP stream and clean up resources.++ Should be called when stream is no longer needed.+ """+ self._stopped = True++ # Wait for any in-flight _read_frame to finish before closing the container,+ # otherwise the executor thread segfaults in native ffmpeg code.+ with self._read_lock:+ if self.container:+ try:+ self.container.close()+ logger.info(f"RTSP stream closed: {self._frame_count} frames received")+ except Exception as e:+ logger.warning(f"Error closing RTSP container: {e}")+ finally:+ self.container = None+ self.stream = None++ super().stop()++ @property+ def is_connected(self) -> bool:+ """Check if RTSP stream is currently connected."""+ return self.container is not None and not self._stopped++ def get_stats(self) -> dict:+ """+ Get statistics about the RTSP stream.++ Returns:+ Dictionary with stream statistics+ """+ stats = {+ "url": self._sanitize_url(self.rtsp_url),+ "connected": self.is_connected,+ "frames_received": self._frame_count,+ "stopped": self._stopped,+ }++ if self.stream:+ stats.update(+ {+ "codec": self.stream.codec_context.name,+ "width": self.stream.width,+ "height": self.stream.height,+ "fps": float(self.stream.average_rate) if self.stream.average_rate else None,+ }+ )++ return statsdiff --git a/Web_Inference/webui/src/alive_webui/server.py b/Web_Inference/webui/src/alive_webui/server.pynew file mode 100644index 0000000..366e500--- /dev/null+++ b/Web_Inference/webui/src/alive_webui/server.py@@ -0,0 +1,1692 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""+WebRTC ALIVE Server+Main server that handles WebRTC connections and serves the web interface+"""++import asyncio+import io+import json+import logging+import os+import signal+import socket+import subprocess+import sys+import time+import uuid+from collections import defaultdict++import aiohttp+from aiohttp import web+from PIL import Image, UnidentifiedImageError+from aiortc import (+ RTCPeerConnection,+ RTCSessionDescription,+ RTCConfiguration,+ RTCIceServer,+)+from aiortc.contrib.media import MediaRelay++from .vlm_service import VLMService+from .video_processor import VideoProcessorTrack+from .rtsp_track import RTSPVideoTrack+from .background_model import BackgroundModelService+from .local_file_server import setup_local_file_routes++# Configure logging+logging.basicConfig(+ level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"+)+logger = logging.getLogger(__name__)++# Global objects+relay = MediaRelay()+pcs = set()+vlm_service = None # Kept for backwards compat; default session uses sessions["default"]+websockets = set() # Track active WebSocket connections (all)+rtsp_tracks = {} # Track active RTSP streams {session_id: (rtsp_track, processor_track)}++# Multi-session state+default_vlm_config = {} # Set at startup; used to create new sessions+sessions = {} # session_id -> {"vlm_service": VLMService}+session_websockets = defaultdict(set) # session_id -> set of ws+ws_to_session = {} # ws -> session_id+session_peer_connections = defaultdict(set) # session_id -> set of RTCPeerConnection+camera_websockets = {} # one bounded JPEG stream per session, over HTTPS+++def get_ice_server_configs():+ """Return browser/aiortc ICE servers, optionally including a TURN relay."""+ default = [+ {"urls": ["stun:stun.l.google.com:19302"]},+ {"urls": ["stun:stun1.l.google.com:19302"]},+ ]+ raw = os.environ.get("WEBRTC_ICE_SERVERS_JSON", "").strip()+ if not raw:+ return default+ try:+ value = json.loads(raw)+ except (TypeError, ValueError) as exc:+ logger.warning("Ignoring invalid WEBRTC_ICE_SERVERS_JSON: %s", exc)+ return default+ if not isinstance(value, list) or not value or not all(isinstance(item, dict) for item in value):+ logger.warning("Ignoring WEBRTC_ICE_SERVERS_JSON: expected a non-empty list of objects")+ return default+ return value+++def notify_session_json(session_id: str, payload: dict):+ """Send a JSON payload to WebSocket clients in this session."""+ handle_background_handoff_for_interaction(session_id, payload)+ send_to_session(session_id, json.dumps(payload, ensure_ascii=False))+++def handle_background_handoff_for_interaction(session_id: str, payload: dict) -> None:+ if not isinstance(payload, dict) or payload.get("type") != "background_result_ready":+ return++ session = sessions.get(session_id)+ if not session or not session.get("vlm_service"):+ return+ handoff = payload.get("interaction_handoff")+ summary = ""+ if isinstance(handoff, dict):+ summary = str(handoff.get("summary") or "").strip()+ if not summary:+ logger.info(+ "[%s] Background result received without interaction handoff: task_id=%s",+ session_id,+ payload.get("task_id"),+ )+ return+ session["vlm_service"].queue_background_handoff(+ task_id=str(payload.get("task_id") or ""),+ question=str(payload.get("question") or ""),+ summary=summary,+ )+ logger.info(+ "[%s] Background handoff queued for interaction: task_id=%s summary_chars=%s",+ session_id,+ payload.get("task_id"),+ len(summary),+ )+++def get_background_service(session_id: str):+ """Return the background model service for a session if it exists."""+ session = sessions.get(session_id)+ if not session:+ return None+ return session.get("background_service")+++def get_or_create_session(session_id: str):+ """Get or create per-session state (VLM service). Thread-safe for aiohttp."""+ if session_id not in sessions:+ cfg = default_vlm_config+ sessions[session_id] = {+ "vlm_service": VLMService(+ model=cfg.get("model", "ALIVE"),+ api_base=cfg.get("api_base", "http://localhost:8000/v1"),+ api_key=cfg.get("api_key", "EMPTY"),+ prompt=cfg.get("prompt") or None,+ session_id=session_id,+ ),+ "background_service": BackgroundModelService(+ session_id=session_id,+ notify_callback=lambda payload, sid=session_id: notify_session_json(sid, payload),+ summarizer_api_base=cfg.get("api_base", "http://localhost:8000/v1"),+ ),+ "show_request_payload": False,+ "show_response_payload": False,+ "show_memory_state": False,+ }+ logger.info(f"Created new session: {session_id}")+ return sessions[session_id]+++def send_to_session(session_id: str, message: str):+ """Send a message only to WebSocket clients in this session."""+ for ws in session_websockets.get(session_id, set()):+ try:+ asyncio.create_task(ws.send_str(message))+ except Exception as e:+ logger.error(f"Error sending to session {session_id}: {e}")+++def get_session_callback(session_id: str):+ """Return a text_callback that sends VLM results only to this session."""+ _last_memory_hash = [None]++ def callback(text: str, metrics: dict):+ session = sessions.get(session_id)+ display_text = text+ if session and session.get("background_service"):+ display_text = session["background_service"].handle_foreground_response(+ text,+ metrics=metrics,+ )++ out = {"type": "vlm_response", "text": display_text, "metrics": metrics}+ if session and session.get("vlm_service"):+ svc = session["vlm_service"]+ if session.get("show_request_payload"):+ payload = svc.get_last_request_payload()+ if payload is not None:+ out["request_payload"] = payload+ if session.get("show_response_payload"):+ payload = svc.get_last_response_payload()+ if payload is not None:+ try:+ out["response_payload"] = json.loads(json.dumps(payload, default=str))+ except (TypeError, ValueError):+ out["response_payload"] = payload+ resp = svc.get_last_response_payload()+ if resp and isinstance(resp, dict):+ sh = resp.get("streamingharness", {})+ memory = sh.get("memory") if isinstance(sh, dict) else None+ if memory:+ mem_hash = json.dumps(memory, ensure_ascii=False, sort_keys=True)+ if mem_hash != _last_memory_hash[0]:+ _last_memory_hash[0] = mem_hash+ out["memory_state"] = memory+ summarizer_timing = sh.get("summarizer_timing") if isinstance(sh, dict) else None+ if summarizer_timing:+ out["summarizer_timing"] = summarizer_timing+ send_to_session(session_id, json.dumps(out, ensure_ascii=False))++ return callback+++_cleanup_tasks = {}+_finished_sessions = {}+++async def cleanup_session(session_id: str, reset_adapter: bool = True) -> dict:+ if session_id in _finished_sessions and session_id not in sessions:+ return _finished_sessions[session_id]+ if session_id not in _cleanup_tasks:+ _cleanup_tasks[session_id] = asyncio.create_task(_cleanup_session(session_id, reset_adapter))+ task = _cleanup_tasks[session_id]+ try:+ result = await asyncio.shield(task)+ _finished_sessions[session_id] = result+ if len(_finished_sessions) > 100:+ _finished_sessions.pop(next(iter(_finished_sessions)))+ return result+ finally:+ if task.done():+ _cleanup_tasks.pop(session_id, None)+++async def cleanup_disconnected_session(session_id, original_session):+ await asyncio.sleep(10)+ if sessions.get(session_id) is original_session and not session_websockets.get(session_id):+ await cleanup_session(session_id)+++async def _cleanup_session(session_id: str, reset_adapter: bool = True) -> dict:+ """Cancel active work and remove all server-side state for a session."""+ if not session_id:+ return {"session_id": session_id, "removed": False, "reason": "missing_session_id"}++ logger.info("[%s] Cleaning up session", session_id)++ camera_ws = camera_websockets.pop(session_id, None)+ if camera_ws is not None:+ await camera_ws.close()++ session_sockets = list(session_websockets.pop(session_id, set()))+ for ws in session_sockets:+ try:+ await ws.close()+ except Exception as e:+ logger.warning("[%s] Error closing websocket: %s", session_id, e)+ finally:+ websockets.discard(ws)+ ws_to_session.pop(ws, None)++ if session_id in rtsp_tracks:+ await _stop_rtsp_session(session_id)++ pcs_for_session = list(session_peer_connections.pop(session_id, set()))+ for pc in pcs_for_session:+ try:+ await pc.close()+ except Exception as e:+ logger.warning("[%s] Error closing peer connection: %s", session_id, e)+ finally:+ pcs.discard(pc)++ session = sessions.pop(session_id, None)+ cancelled = 0+ cancelled_background = 0+ if session and session.get("vlm_service"):+ svc = session["vlm_service"]+ cancelled = await svc.cancel_active_requests()+ if reset_adapter:+ await svc.reset_adapter_session()+ await svc.close(cancel_requests=False)+ if session and session.get("background_service"):+ bg_svc = session["background_service"]+ cancelled_background = await bg_svc.cancel_active_requests()+ await bg_svc.close(cancel_requests=False)++ logger.info(+ "[%s] Session cleanup complete: removed=%s, websockets=%s, peer_connections=%s, cancelled_vlm_tasks=%s, cancelled_background_tasks=%s",+ session_id,+ bool(session),+ len(session_sockets),+ len(pcs_for_session),+ cancelled,+ cancelled_background,+ )+ return {+ "session_id": session_id,+ "removed": bool(session),+ "websockets_closed": len(session_sockets),+ "peer_connections_closed": len(pcs_for_session),+ "cancelled_vlm_tasks": cancelled,+ "cancelled_background_tasks": cancelled_background,++ }+++def is_port_available(port, host="0.0.0.0"):+ """Check if a port is available for binding"""+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ try:+ sock.bind((host, port))+ sock.close()+ return True+ except OSError:+ return False+++def find_process_using_port(port):+ """Find what process is using a port (Linux/Unix only)"""+ try:+ # Try lsof first (more reliable)+ result = subprocess.run(+ ["lsof", "-i", f":{port}", "-t"], capture_output=True, text=True, timeout=2+ )+ if result.returncode == 0 and result.stdout.strip():+ pid = result.stdout.strip().split()[0]+ # Get process name+ name_result = subprocess.run(+ ["ps", "-p", pid, "-o", "comm="], capture_output=True, text=True, timeout=2+ )+ if name_result.returncode == 0:+ return f"PID {pid} ({name_result.stdout.strip()})"+ except (FileNotFoundError, subprocess.TimeoutExpired):+ # lsof not available, try netstat+ try:+ result = subprocess.run(+ ["netstat", "-tulpn"], capture_output=True, text=True, timeout=2+ )+ for line in result.stdout.split("\n"):+ if f":{port}" in line and "LISTEN" in line:+ parts = line.split()+ if len(parts) >= 7:+ return parts[-1] # PID/Program name+ except (FileNotFoundError, subprocess.TimeoutExpired):+ pass+ return "unknown process"+++def find_available_port(start_port=8080, max_attempts=10):+ """Find next available port starting from start_port"""+ for port in range(start_port, start_port + max_attempts):+ if is_port_available(port):+ return port+ return None+++async def detect_local_service_and_model():+ """+ Auto-detect available local VLM services and select a model+ Returns: (api_base, model_name) or (None, None) if no service found+ """+ services = [+ ("http://localhost:11434/v1", "Ollama"),+ ("http://localhost:8000/v1", "vLLM"),+ ("http://localhost:30000/v1", "SGLang"),+ ]++ for api_base, service_name in services:+ try:+ # Try to connect to the service+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=2)) as session:+ async with session.get(f"{api_base}/models") as resp:+ if resp.status == 200:+ data = await resp.json()+ models = data.get("data", [])+ if models:+ # Prefer vision models+ vision_keywords = ["vision", "llava", "llama-3.2", "gemini"]+ for model in models:+ model_id = model.get("id", "")+ if any(keyword in model_id.lower() for keyword in vision_keywords):+ logger.info(f"✅ Auto-detected {service_name} at {api_base}")+ logger.info(f" Selected model: {model_id}")+ return (api_base, model_id)++ # If no vision model found, use the first one+ model_id = models[0].get("id", "")+ logger.info(f"✅ Auto-detected {service_name} at {api_base}")+ logger.info(+ f" Selected model: {model_id} (vision model preferred but not found)"+ )+ return (api_base, model_id)+ except Exception as e:+ logger.debug(f"Service {service_name} not available at {api_base}: {e}")+ continue++ return (None, None)+++async def index(request):+ """Serve the main HTML page"""+ content = open(os.path.join(os.path.dirname(__file__), "static", "index.html"), "r").read()+ ice_config = json.dumps(get_ice_server_configs(), ensure_ascii=True, separators=(",", ":"))+ content = content.replace(+ "</head>",+ f"<script>window.__ALIVE_ICE_SERVERS__={ice_config};"+ f"window.__ALIVE_CAMERA_TRANSPORT__={json.dumps(os.getenv('CAMERA_TRANSPORT', 'websocket'))};</script></head>",+ 1,+ )+ return web.Response(content_type="text/html", text=content)+++async def models(request):+ """Return available models from the VLM API"""+ try:+ # Check if custom API base and key are provided in query params+ api_base = request.rel_url.query.get("api_base")+ api_key = request.rel_url.query.get("api_key")++ if api_base:+ # Query models from the provided API endpoint+ from openai import AsyncOpenAI++ temp_client = AsyncOpenAI(base_url=api_base, api_key=api_key if api_key else "EMPTY")+ models_response = await temp_client.models.list()+ models_list = [+ {"id": model.id, "name": model.id, "current": False}+ for model in models_response.data+ ]+ return web.Response(+ content_type="application/json", text=json.dumps({"models": models_list})+ )+ else:+ # Use default session's VLM service (backwards compat when no api_base in query)+ default_svc = get_or_create_session("default")["vlm_service"]+ models_response = await default_svc.client.models.list()+ models_list = [+ {"id": model.id, "name": model.id, "current": model.id == default_svc.model}+ for model in models_response.data+ ]+ return web.Response(+ content_type="application/json", text=json.dumps({"models": models_list})+ )+ except Exception as e:+ logger.error(f"Error fetching models: {e}")+ # Return current model as fallback+ if sessions.get("default"):+ default_svc = sessions["default"]["vlm_service"]+ return web.Response(+ content_type="application/json",+ text=json.dumps(+ {+ "models": [+ {"id": default_svc.model, "name": default_svc.model, "current": True}+ ]+ }+ ),+ )+ return web.Response(+ content_type="application/json", text=json.dumps({"models": [], "error": str(e)})+ )+++async def detect_services(request):+ """Detect available local VLM services"""+ services = [+ {"name": "Ollama", "url": "http://localhost:11434/v1", "port": 11434, "path": "/api/tags"},+ {"name": "vLLM", "url": "http://localhost:8000/v1", "port": 8000, "path": "/v1/models"},+ {"name": "SGLang", "url": "http://localhost:30000/v1", "port": 30000, "path": "/v1/models"},+ ]++ detected = []++ async def check_service(service):+ """Check if a service is running by probing its endpoint"""+ try:+ timeout = aiohttp.ClientTimeout(total=1.0) # 1 second timeout+ async with aiohttp.ClientSession(timeout=timeout) as session:+ url = f"http://localhost:{service['port']}{service['path']}"+ async with session.get(url) as response:+ if response.status in [200, 404]: # 404 is ok, means server is running+ logger.info(f"Detected {service['name']} at {service['url']}")+ return service+ except (aiohttp.ClientError, asyncio.TimeoutError):+ pass+ return None++ # Check all services concurrently+ results = await asyncio.gather(*[check_service(s) for s in services])+ detected = [s for s in results if s is not None]++ return web.Response(+ content_type="application/json",+ text=json.dumps({"detected": detected, "default": detected[0] if detected else None}),+ )+++async def websocket_handler(request):+ """Handle WebSocket connections for text updates. Supports ?session_id= for multi-session."""+ ws = web.WebSocketResponse()+ await ws.prepare(request)++ # Session ID from query or generate new (client should send same id in /offer)+ session_id = request.query.get("session_id", "").strip() or str(uuid.uuid4())+ ws_to_session[ws] = session_id+ session_websockets[session_id].add(ws)+ websockets.add(ws)+ logger.info(+ f"WebSocket client connected. session_id={session_id}, total clients: {len(websockets)}"+ )++ session = get_or_create_session(session_id)+ svc = session["vlm_service"]++ try:+ # Send initial message with current server configuration (include session_id if we generated it)+ await ws.send_json(+ {+ "type": "status",+ "text": "Connected to server",+ "status": "Ready",+ "session_id": session_id,+ }+ )++ # Send current server configuration for this session+ from .video_processor import VideoProcessorTrack as _VPT++ background_service = session.get("background_service")+ await ws.send_json(+ {+ "type": "server_config",+ "model": svc.model,+ "api_base": svc.api_base,+ "prompt": svc.prompt,+ "process_interval": _VPT.process_interval_seconds,+ "frames_per_batch": _VPT.frames_per_batch,+ "background_model": background_service.get_config()+ if background_service+ else None,+ "session_id": session_id,+ }+ )++ # Keep connection alive and handle incoming messages+ async for msg in ws:+ if msg.type == web.WSMsgType.TEXT:+ try:+ data = json.loads(msg.data)+ # Re-resolve session in case it was recreated+ svc = get_or_create_session(session_id)["vlm_service"]++ if data.get("type") == "update_prompt":+ new_prompt = data.get("prompt", "").strip()+ if svc:+ svc.update_prompt(new_prompt, data.get("client_sent_at_ms"))+ logger.info(f"[{session_id}] Prompt updated: {new_prompt}")++ await ws.send_json(+ {+ "type": "prompt_updated",+ "prompt": new_prompt,+ }+ )++ elif data.get("type") == "update_model":+ new_model = data.get("model", "").strip()+ api_base = data.get("api_base", "").strip()+ api_key = data.get("api_key", "").strip()++ if new_model and svc:+ svc.model = new_model+ if api_base:+ svc.update_api_settings(api_base, api_key if api_key else None)+ bg_svc = get_background_service(session_id)+ if bg_svc:+ bg_svc.update_summary_api(api_base=svc.api_base)+ logger.info(+ f"[{session_id}] Model updated: {new_model}, API: {api_base}"+ )+ else:+ logger.info(f"[{session_id}] Model updated: {new_model}")++ await ws.send_json(+ {+ "type": "model_updated",+ "model": new_model,+ "api_base": svc.api_base,+ }+ )++ elif data.get("type") == "update_processing":+ interval_sec = data.get("process_interval", 1.0)+ try:+ interval_sec = float(interval_sec)+ if 0.1 <= interval_sec <= 60.0:+ from .video_processor import VideoProcessorTrack++ old_value = VideoProcessorTrack.process_interval_seconds+ VideoProcessorTrack.process_interval_seconds = interval_sec+ bg_svc = get_background_service(session_id)+ if bg_svc:+ bg_svc.set_foreground_sampling(+ process_interval_seconds=interval_sec,+ frames_per_batch=VideoProcessorTrack.frames_per_batch,+ )+ logger.info(+ f"[{session_id}] Processing interval updated: {old_value} → {interval_sec}s"+ )++ await ws.send_json(+ {+ "type": "processing_updated",+ "process_interval": interval_sec,+ "background_model": bg_svc.get_config()+ if bg_svc+ else None,+ }+ )+ else:+ logger.warning(+ f"Processing interval out of range (0.1-60): {interval_sec}"+ )+ except ValueError:+ logger.error(f"Invalid processing interval: {interval_sec}")++ elif data.get("type") == "update_frames_per_batch":+ fpb = data.get("frames_per_batch", 1)+ try:+ fpb = int(fpb)+ if 1 <= fpb <= 30:+ from .video_processor import VideoProcessorTrack++ old_value = VideoProcessorTrack.frames_per_batch+ VideoProcessorTrack.frames_per_batch = fpb+ bg_svc = get_background_service(session_id)+ if bg_svc:+ bg_svc.set_foreground_sampling(+ process_interval_seconds=VideoProcessorTrack.process_interval_seconds,+ frames_per_batch=fpb,+ )+ logger.info(+ f"[{session_id}] Frames per batch updated: {old_value} → {fpb}"+ )++ await ws.send_json(+ {+ "type": "frames_per_batch_updated",+ "frames_per_batch": fpb,+ "background_model": bg_svc.get_config()+ if bg_svc+ else None,+ }+ )+ else:+ logger.warning(+ f"Frames per batch out of range (1-30): {fpb}"+ )+ except ValueError:+ logger.error(f"Invalid frames per batch: {fpb}")++ elif data.get("type") == "update_background_config":+ bg_svc = get_background_service(session_id)+ if bg_svc:+ try:+ config = bg_svc.update_config(+ enabled=data.get("enabled")+ if "enabled" in data+ else None,+ frame_multiplier=data.get("frame_multiplier")+ if "frame_multiplier" in data+ else None,+ max_frames=data.get("max_frames")+ if "max_frames" in data+ else None,+ foreground_fps=data.get("foreground_fps")+ if "foreground_fps" in data+ else None,+ resize_long_edge=data.get("resize_long_edge")+ if "resize_long_edge" in data+ else None,+ )+ logger.info(+ "[%s] Background model config updated: %s",+ session_id,+ config,+ )+ await ws.send_json(+ {+ "type": "background_config_updated",+ "background_model": config,+ }+ )+ except (TypeError, ValueError) as err:+ await ws.send_json(+ {+ "type": "background_result_error",+ "task_id": "",+ "error": f"Invalid background config: {err}",+ }+ )++ elif data.get("type") == "set_debug":+ session_data = get_or_create_session(session_id)+ if "show_request_payload" in data:+ session_data["show_request_payload"] = bool(+ data["show_request_payload"]+ )+ if "show_response_payload" in data:+ session_data["show_response_payload"] = bool(+ data["show_response_payload"]+ )+ if "show_memory_state" in data:+ session_data["show_memory_state"] = bool(+ data["show_memory_state"]+ )+ logger.debug(+ f"[{session_id}] Debug: request_payload="+ f"{session_data.get('show_request_payload')}, response_payload="+ f"{session_data.get('show_response_payload')}, memory_state="+ f"{session_data.get('show_memory_state')}"+ )++ elif data.get("type") == "reset_session":+ logger.info(f"[{session_id}] Client requested adapter session reset")+ asyncio.create_task(svc.reset_adapter_session())++ elif data.get("type") == "cleanup_session":+ logger.info(f"[{session_id}] Client requested session cleanup")+ asyncio.create_task(cleanup_session(session_id))+ await ws.close()+ break++ elif data.get("type") == "update_max_latency":+ max_latency = data.get("max_latency", 0.0)+ try:+ max_latency = float(max_latency)+ if 0 <= max_latency <= 10.0:+ from .video_processor import VideoProcessorTrack++ old_value = VideoProcessorTrack.max_frame_latency+ VideoProcessorTrack.max_frame_latency = max_latency+ status = "disabled" if max_latency == 0 else f"{max_latency:.1f}s"+ old_status = "disabled" if old_value == 0 else f"{old_value:.1f}s"+ logger.info(+ f"[{session_id}] Max frame latency updated: {old_status} → {status}"+ )++ await ws.send_json(+ {"type": "max_latency_updated", "max_latency": max_latency}+ )+ else:+ logger.warning(f"Max latency out of range (0-10.0): {max_latency}")+ except ValueError:+ logger.error(f"Invalid max latency value: {max_latency}")+ except json.JSONDecodeError:+ logger.error("Invalid JSON from client")+ except Exception as e:+ logger.error(f"Error handling client message: {e}")+ elif msg.type == web.WSMsgType.ERROR:+ logger.error(f"WebSocket error: {ws.exception()}")+ finally:+ session_sockets = session_websockets.get(session_id)+ if session_sockets is not None:+ session_sockets.discard(ws)+ if not session_sockets:+ session_websockets.pop(session_id, None)+ ws_to_session.pop(ws, None)+ websockets.discard(ws)+ original_session = sessions.get(session_id)+ if original_session is not None:+ asyncio.create_task(cleanup_disconnected_session(session_id, original_session))+ logger.info(+ f"WebSocket client disconnected. session_id={session_id}, total clients: {len(websockets)}"+ )++ return ws+++def broadcast_text_update(text: str, metrics: dict):+ """Broadcast text update and metrics to all connected WebSocket clients"""+ if not websockets:+ return++ message = json.dumps({"type": "vlm_response", "text": text, "metrics": metrics})++ # Send to all connected clients+ dead_websockets = set()+ for ws in websockets:+ try:+ # Use asyncio to send without blocking+ asyncio.create_task(ws.send_str(message))+ except Exception as e:+ logger.error(f"Error sending to websocket: {e}")+ dead_websockets.add(ws)++ # Clean up dead connections+ websockets.difference_update(dead_websockets)+++async def camera_websocket(request):+ """Carry sampled webcam JPEGs through the same HTTPS ingress as the UI."""+ session_id = request.query.get("session_id", "").strip()+ if not session_id or session_id not in sessions:+ raise web.HTTPBadRequest(text="Connect the session before the camera")+ if session_id in camera_websockets:+ raise web.HTTPConflict(text="Camera already connected")+ ws = web.WebSocketResponse(heartbeat=20, max_msg_size=2 * 1024 * 1024)+ await ws.prepare(request)+ camera_websockets[session_id] = ws+ session = sessions[session_id]+ svc = session["vlm_service"]+ callback = get_session_callback(session_id)++ pending = None++ async def process(jpeg):+ received = time.time()+ try:+ with Image.open(io.BytesIO(jpeg)) as source:+ if source.format != "JPEG" or source.width * source.height > 2097152:+ raise ValueError("Expected a JPEG of at most 2 megapixels")+ frame = source.convert("RGB")+ await svc.process_frame(frame, frame_metadata={+ "timestamp": received, "timestamp_kind": "wall_clock_seconds",+ "timestamp_interval_seconds": VideoProcessorTrack.process_interval_seconds,+ "capture_monotonic_s": time.monotonic(),+ "capture_server_unix_ms": received * 1000,+ })+ if not ws.closed and sessions.get(session_id) is session:+ response, _ = svc.get_current_response()+ metrics = svc.get_metrics()+ callback(response, metrics)+ await ws.send_json({"type": "frame_done", "inferences": metrics["total_inferences"]})+ except (ValueError, UnidentifiedImageError, OSError) as exc:+ if not ws.closed:+ await ws.send_json({"type": "frame_error", "message": str(exc)})+ except Exception:+ logger.exception("[%s] Camera frame failed", session_id)+ if not ws.closed:+ await ws.send_json({"type": "frame_error", "message": "Camera processing failed"})++ try:+ await ws.send_json({"type": "camera_ready"})+ async for msg in ws:+ if msg.type == web.WSMsgType.BINARY:+ # Keep only one inference in flight; never accumulate old frames.+ if pending is None or pending.done():+ pending = asyncio.create_task(process(msg.data))+ elif msg.type == web.WSMsgType.ERROR:+ break+ finally:+ if pending is not None:+ pending.cancel()+ await asyncio.gather(pending, return_exceptions=True)+ if camera_websockets.get(session_id) is ws:+ camera_websockets.pop(session_id, None)+ return ws+++async def offer(request):+ """Handle WebRTC offer from client (supports both webcam and RTSP). Uses session_id for per-session VLM."""+ params = await request.json()+ offer_sdp = RTCSessionDescription(sdp=params["sdp"], type=params["type"])+ rtsp_url = params.get("rtsp_url") # Optional RTSP URL for IP camera mode+ session_id = params.get("session_id", "default")++ session = get_or_create_session(session_id)+ session_vlm = session["vlm_service"]++ background_service = session.get("background_service")+ session_callback = get_session_callback(session_id)++ # Create RTCPeerConnection with STUN/TURN servers for NAT compatibility.+ ice_servers = []+ for item in get_ice_server_configs():+ try:+ ice_servers.append(+ RTCIceServer(+ urls=item["urls"],+ username=item.get("username", ""),+ credential=item.get("credential", ""),+ )+ )+ except (KeyError, TypeError, ValueError) as exc:+ logger.warning("Skipping invalid ICE server entry: %s", exc)+ config = RTCConfiguration(+ iceServers=ice_servers,+ )+ pc = RTCPeerConnection(configuration=config)+ pcs.add(pc)+ session_peer_connections[session_id].add(pc)++ # Store RTSP track for cleanup+ rtsp_cleanup_track = None++ @pc.on("connectionstatechange")+ async def on_connectionstatechange():+ logger.info(f"Connection state: {pc.connectionState}")+ if pc.connectionState in ["failed", "closed"]:+ # Clean up RTSP track if exists+ if rtsp_cleanup_track:+ rtsp_cleanup_track.stop()+ logger.info("RTSP track stopped on connection close")+ await pc.close()+ pcs.discard(pc)+ session_pcs = session_peer_connections.get(session_id)+ if session_pcs is not None:+ session_pcs.discard(pc)+ if not session_pcs:+ session_peer_connections.pop(session_id, None)+ if session_id not in _cleanup_tasks:+ asyncio.create_task(cleanup_session(session_id))++ @pc.on("iceconnectionstatechange")+ async def on_iceconnectionstatechange():+ logger.info(f"ICE connection state: {pc.iceConnectionState}")+ if pc.iceConnectionState == "failed":+ logger.error("ICE connection failed - check firewall/NAT settings")++ @pc.on("icegatheringstatechange")+ async def on_icegatheringstatechange():+ logger.info(f"ICE gathering state: {pc.iceGatheringState}")++ # If RTSP URL provided, create RTSP track instead of waiting for browser track+ if rtsp_url:+ logger.info(f"[{session_id}] Creating RTSP track for: {rtsp_url}")+ try:+ rtsp_track = RTSPVideoTrack(rtsp_url)+ rtsp_cleanup_track = rtsp_track # Store for cleanup++ # Wait for initial connection to get stream info+ await asyncio.sleep(0.5)++ # Wrap RTSP track with relay first (same pattern as webcam)+ relayed_rtsp = relay.subscribe(rtsp_track)++ processor_track = VideoProcessorTrack(+ relayed_rtsp,+ session_vlm,+ text_callback=session_callback,+ background_service=background_service,+ )++ # Add processor directly to peer connection+ pc.addTrack(processor_track)+ logger.info("Added RTSP processor track to peer connection")++ except Exception as e:+ logger.error(f"Failed to create RTSP track: {e}")+ return web.Response(+ status=500,+ content_type="application/json",+ text=json.dumps({"error": f"Failed to connect to RTSP stream: {str(e)}"}),+ )+ else:+ # Webcam mode: wait for browser to send track+ @pc.on("track")+ def on_track(track):+ logger.info(f"Received track: {track.kind}")++ if track.kind == "video":+ # Create processor track with this session's VLM and session-scoped callback+ processor_track = VideoProcessorTrack(+ relay.subscribe(track),+ session_vlm,+ text_callback=session_callback,+ background_service=background_service,+ )++ # Add processed track back to connection+ pc.addTrack(processor_track)+ logger.info("Added processed video track back to peer connection")++ @track.on("ended")+ async def on_ended():+ logger.info(f"Track {track.kind} ended")++ # Handle offer+ await pc.setRemoteDescription(offer_sdp)++ # Create answer - this must happen after tracks are added+ answer = await pc.createAnswer()+ await pc.setLocalDescription(answer)++ logger.info(f"Created answer with {len(pc.getTransceivers())} transceivers")++ return web.Response(+ content_type="application/json",+ text=json.dumps({"sdp": pc.localDescription.sdp, "type": pc.localDescription.type}),+ )+++async def session_cleanup(request):+ """Cancel active VLM work and remove a session."""+ try:+ data = await request.json()+ except Exception:+ data = {}++ session_id = (data.get("session_id") or "").strip()+ if not session_id:+ return web.Response(+ status=400,+ content_type="application/json",+ text=json.dumps({"error": "Missing session_id parameter"}),+ )++ reset_adapter = bool(data.get("reset_adapter", True))+ result = await cleanup_session(session_id, reset_adapter=reset_adapter)+ return web.Response(content_type="application/json", text=json.dumps(result))+++async def rtsp_start(request):+ """+ Start RTSP stream processing.++ Accepts RTSP URL and creates a video processing pipeline.++ POST /api/rtsp/start+ Body: {"rtsp_url": "rtsp://...", "session_id": "optional-id"}+ """+ try:+ data = await request.json()+ rtsp_url = data.get("rtsp_url")+ session_id = data.get("session_id", "default")++ if not rtsp_url:+ logger.warning("RTSP start request missing rtsp_url")+ return web.Response(+ status=400,+ content_type="application/json",+ text=json.dumps({"error": "Missing rtsp_url parameter"}),+ )++ # Check if session already exists+ if session_id in rtsp_tracks:+ logger.warning(f"RTSP session {session_id} already exists, stopping it first")+ await _stop_rtsp_session(session_id)++ logger.info(f"Starting RTSP stream for session {session_id}")++ # Create RTSP video track+ try:+ rtsp_track = RTSPVideoTrack(rtsp_url)+ except Exception as e:+ logger.error(f"Failed to create RTSP track: {e}")+ return web.Response(+ status=500,+ content_type="application/json",+ text=json.dumps({"error": f"Failed to connect to RTSP stream: {str(e)}"}),+ )++ # Create processor track with this session's VLM and session-scoped callback+ session = get_or_create_session(session_id)+ session_vlm = session["vlm_service"]++ background_service = session.get("background_service")+ session_callback = get_session_callback(session_id)+ processor_track = VideoProcessorTrack(+ rtsp_track,+ session_vlm,+ text_callback=session_callback,+ background_service=background_service,+ )++ # Start background task to consume frames+ async def consume_frames():+ """Background task to continuously pull frames from processor track"""+ try:+ while not rtsp_track._stopped:+ try:+ _ = await processor_track.recv()+ # Frame is processed, just discard it (VLM analysis happens in recv())+ except StopAsyncIteration:+ logger.info(f"RTSP stream {session_id} ended")+ break+ except Exception as e:+ logger.error(f"Error consuming RTSP frame for {session_id}: {e}")+ break+ finally:+ logger.info(f"Frame consumption stopped for {session_id}")++ frame_task = asyncio.create_task(consume_frames())++ # Store reference with frame task+ rtsp_tracks[session_id] = (rtsp_track, processor_track, frame_task)++ # Get stream stats+ stats = rtsp_track.get_stats()++ logger.info(+ f"RTSP stream started: {session_id} - {stats.get('codec')} "+ f"{stats.get('width')}x{stats.get('height')}"+ )++ return web.Response(+ content_type="application/json",+ text=json.dumps({"status": "started", "session_id": session_id, "stream_info": stats}),+ )++ except Exception as e:+ logger.error(f"Error starting RTSP: {e}", exc_info=True)+ return web.Response(+ status=500, content_type="application/json", text=json.dumps({"error": str(e)})+ )+++async def rtsp_stop(request):+ """+ Stop RTSP stream processing.++ POST /api/rtsp/stop+ Body: {"session_id": "optional-id"}+ """+ try:+ data = await request.json()+ session_id = data.get("session_id", "default")++ await _stop_rtsp_session(session_id)++ return web.Response(+ content_type="application/json",+ text=json.dumps({"status": "stopped", "session_id": session_id}),+ )++ except Exception as e:+ logger.error(f"Error stopping RTSP: {e}", exc_info=True)+ return web.Response(+ status=500, content_type="application/json", text=json.dumps({"error": str(e)})+ )+++async def rtsp_status(request):+ """+ Get status of all RTSP streams.++ GET /api/rtsp/status+ """+ try:+ status_list = []++ for session_id, (rtsp_track, processor_track, frame_task) in rtsp_tracks.items():+ stats = rtsp_track.get_stats()+ status_list.append(+ {+ "session_id": session_id,+ "connected": stats.get("connected"),+ "frames_received": stats.get("frames_received"),+ "stream_info": {+ "codec": stats.get("codec"),+ "width": stats.get("width"),+ "height": stats.get("height"),+ "fps": stats.get("fps"),+ },+ }+ )++ return web.Response(+ content_type="application/json",+ text=json.dumps({"active_streams": len(rtsp_tracks), "streams": status_list}),+ )++ except Exception as e:+ logger.error(f"Error getting RTSP status: {e}", exc_info=True)+ return web.Response(+ status=500, content_type="application/json", text=json.dumps({"error": str(e)})+ )+++async def _stop_rtsp_session(session_id: str):+ """Helper function to stop an RTSP session"""+ if session_id in rtsp_tracks:+ rtsp_track, processor_track, frame_task = rtsp_tracks[session_id]++ # Signal stop first so _read_frame exits early on its next iteration+ rtsp_track._stopped = True++ # Cancel frame consumption task+ if frame_task and not frame_task.done():+ frame_task.cancel()+ try:+ await frame_task+ except asyncio.CancelledError:+ pass++ # Stop tracks (rtsp_track.stop acquires _read_lock to wait for+ # any in-flight executor thread before closing the container)+ try:+ processor_track.stop()+ except Exception as e:+ logger.warning(f"Error stopping processor track: {e}")++ try:+ rtsp_track.stop()+ except Exception as e:+ logger.warning(f"Error stopping RTSP track: {e}")++ # Remove from tracking+ del rtsp_tracks[session_id]+ logger.info(f"RTSP stream stopped: {session_id}")+ else:+ logger.warning(f"RTSP session {session_id} not found")+++async def on_startup(app):+ """Initialize resources on server startup"""+ logger.info("Server startup complete")+++async def on_shutdown(app):+ """Cleanup on server shutdown"""++ logger.info("Shutting down server...")++ # Close all websockets and clear session state+ for ws in list(websockets):+ await ws.close()+ websockets.clear()+ session_websockets.clear()+ ws_to_session.clear()+ session_peer_connections.clear()++ # Close all RTSP streams+ for session_id in list(rtsp_tracks.keys()):+ await _stop_rtsp_session(session_id)+ logger.info("RTSP streams closed")++ # Close all peer connections+ coros = [pc.close() for pc in pcs]+ await asyncio.gather(*coros)+ pcs.clear()++ for session_id, session in list(sessions.items()):+ svc = session.get("vlm_service")+ if svc:+ await svc.close()+ bg_svc = session.get("background_service")+ if bg_svc:+ await bg_svc.close()+ sessions.pop(session_id, None)+ logger.info("VLM sessions closed")++ logger.info("Cleanup complete")+++async def create_app(test_mode=False):+ """+ Create and configure the aiohttp web application.++ Args:+ test_mode: If True, use test configuration++ Returns:+ Configured web.Application instance+ """+ # Create web application+ app = web.Application()+ async def voice_status(request):+ return web.json_response({"asr": {"available": False}, "tts": {"available": False}})++ async def release_local_session(request):+ return web.json_response({"released": True})++ app.router.add_get("/api/voice/status", voice_status)+ app.router.add_post("/_bridge/release", release_local_session)+ app.router.add_get("/", index)+ app.router.add_get("/models", models)+ app.router.add_get("/detect-services", detect_services)+ app.router.add_get("/ws", websocket_handler)+ app.router.add_get("/ws/camera", camera_websocket)+++ setup_local_file_routes(app)+ app.router.add_post("/offer", offer)+ app.router.add_post("/api/session/cleanup", session_cleanup)++ # RTSP endpoints+ app.router.add_post("/api/rtsp/start", rtsp_start)+ app.router.add_post("/api/rtsp/stop", rtsp_stop)+ app.router.add_get("/api/rtsp/status", rtsp_status)++ # Serve static files (images, etc.)+ # Always serve from static/images within the package (works for both pip and dev installs)+ images_dir = os.path.join(os.path.dirname(__file__), "static", "images")+ images_dir = os.path.abspath(images_dir)++ if os.path.exists(images_dir):+ app.router.add_static("/images", images_dir, name="images")+ logger.info(f"Serving static files from: {images_dir}")+ else:+ logger.warning(f"⚠️ Static images directory not found: {images_dir}")++ # Serve favicon files+ favicon_dir = os.path.join(os.path.dirname(__file__), "static", "favicon")+ favicon_dir = os.path.abspath(favicon_dir)++ if os.path.exists(favicon_dir):+ app.router.add_static("/favicon", favicon_dir, name="favicon")+ logger.info(f"Serving favicon files from: {favicon_dir}")+ else:+ logger.warning(f"⚠️ Favicon directory not found: {favicon_dir}")++ if not test_mode:+ app.on_startup.append(on_startup)+ app.on_shutdown.append(on_shutdown)++ return app+++def get_app_config_dir():+ """Get the application config directory following OS conventions"""+ import os+ from pathlib import Path++ # Follow XDG Base Directory spec on Linux, use OS-appropriate paths elsewhere+ if os.name == "posix":+ if "darwin" in os.sys.platform.lower():+ # macOS+ config_dir = Path.home() / "Library" / "Application Support" / "alive-webui"+ else:+ # Linux/Unix (including Jetson)+ config_dir = (+ Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "alive-webui"+ )+ else:+ # Windows+ config_dir = Path(os.environ.get("APPDATA", Path.home())) / "alive-webui"++ # Create directory if it doesn't exist+ config_dir.mkdir(parents=True, exist_ok=True)+ return config_dir+++def generate_self_signed_cert(cert_path="cert.pem", key_path="key.pem"):+ """Generate a self-signed SSL certificate if it doesn't exist"""+ import subprocess+ import os++ if os.path.exists(cert_path) and os.path.exists(key_path):+ return True++ logger.info("🔐 Generating self-signed SSL certificate...")+ logger.info(f" Saving to: {os.path.dirname(os.path.abspath(cert_path)) or '.'}")+ try:+ subprocess.run(+ [+ "openssl",+ "req",+ "-x509",+ "-newkey",+ "rsa:4096",+ "-nodes",+ "-out",+ cert_path,+ "-keyout",+ key_path,+ "-days",+ "365",+ "-subj",+ "/CN=localhost",+ ],+ check=True,+ capture_output=True,+ )+ logger.info(f"✅ Generated {cert_path} and {key_path}")+ return True+ except FileNotFoundError:+ logger.warning("⚠️ openssl not found - cannot auto-generate certificates")+ logger.warning(+ "⚠️ Install openssl: sudo apt install openssl (Linux) or brew install openssl (Mac)"+ )+ return False+ except subprocess.CalledProcessError as e:+ logger.warning(f"⚠️ Failed to generate certificates: {e}")+ return False+++def main():+ """Main entry point"""+ import argparse+ import ssl+ from . import __version__++ parser = argparse.ArgumentParser(+ description="WebRTC ALIVE - Real-time vision model interaction",+ epilog="Examples:\n"+ " vLLM: python -m alive_webui.server --model ALIVE --api-base http://localhost:8000/v1\n"+ " SGLang: python -m alive_webui.server --model ALIVE --api-base http://localhost:30000/v1\n"+ " Ollama: python -m alive_webui.server --model ALIVE --api-base http://localhost:11434/v1\n"+ " HTTPS: python -m alive_webui.server --model ALIVE --api-base http://localhost:11434/v1 --ssl-cert cert.pem --ssl-key key.pem",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ )+ parser.add_argument(+ "--version",+ action="version",+ version=f"%(prog)s {__version__}",+ )+ parser.add_argument("--host", default="0.0.0.0", help="Host to bind to (default: 0.0.0.0)")+ parser.add_argument("--port", type=int, default=8090, help="Port to bind to (default: 8090)")+ parser.add_argument(+ "--auto-port",+ action="store_true",+ help="Automatically find available port if default is taken",+ )+ parser.add_argument(+ "--model", help="VLM model name (optional, will auto-detect if not specified)"+ )+ parser.add_argument(+ "--api-base", help="VLM API base URL (defaults to the local ALIVE adapter)"+ )+ parser.add_argument(+ "--api-key",+ default="EMPTY",+ help="Local API key (default: EMPTY)",+ )+ parser.add_argument(+ "--prompt",+ default="",+ help="Initial prompt to send to VLM (default: empty, waits for user input)",+ )+ # Get default SSL cert paths (platform-specific)+ default_config_dir = get_app_config_dir()+ default_cert_path = str(default_config_dir / "cert.pem")+ default_key_path = str(default_config_dir / "key.pem")++ parser.add_argument("--process-interval", type=float, default=1.0, help="Processing interval in seconds (default: 1.0)")+ parser.add_argument("--frames-per-batch", type=int, default=1, help="Number of frames to batch per VLM inference (default: 1). E.g., 2 means capture 2 frames within each process-interval and send them together.")+ parser.add_argument(+ "--ssl-cert",+ default=None, # Will be set to config dir if not specified+ help=f"Path to SSL certificate file (default: {default_cert_path}, auto-generated if missing)",+ )+ parser.add_argument(+ "--ssl-key",+ default=None, # Will be set to config dir if not specified+ help=f"Path to SSL private key file (default: {default_key_path}, auto-generated if missing)",+ )+ parser.add_argument(+ "--no-ssl",+ action="store_true",+ help="Disable SSL (not recommended - webcam requires HTTPS)",+ )++ args = parser.parse_args()++ # Cloud deployment: env overrides for default API base, model, and frame interval+ if os.environ.get("LIVE_VLM_API_BASE"):+ if not args.api_base:+ args.api_base = os.environ.get("LIVE_VLM_API_BASE").strip()+ logger.info(f"Using API base from env: {args.api_base}")+ if os.environ.get("LIVE_VLM_DEFAULT_MODEL"):+ if not args.model:+ args.model = os.environ.get("LIVE_VLM_DEFAULT_MODEL").strip()+ logger.info(f"Using default model from env: {args.model}")+ if os.environ.get("LIVE_VLM_PROCESS_INTERVAL"):+ try:+ args.process_interval = float(os.environ.get("LIVE_VLM_PROCESS_INTERVAL"))+ logger.info(f"Using process_interval from env: {args.process_interval}s")+ except ValueError:+ pass+ if os.environ.get("LIVE_VLM_FRAMES_PER_BATCH"):+ try:+ args.frames_per_batch = int(os.environ.get("LIVE_VLM_FRAMES_PER_BATCH"))+ logger.info(f"Using frames_per_batch from env: {args.frames_per_batch}")+ except ValueError:+ pass++ # Set default SSL cert paths to config directory if not specified+ if args.ssl_cert is None:+ config_dir = get_app_config_dir()+ args.ssl_cert = str(config_dir / "cert.pem")+ if args.ssl_key is None:+ config_dir = get_app_config_dir()+ args.ssl_key = str(config_dir / "key.pem")++ api_base = args.api_base or "http://127.0.0.1:8070/v1"+ model = args.model or "streaming-infer-adapter"+ api_key = args.api_key++ # Initialize VLM service and default session for multi-session support+ global vlm_service, default_vlm_config+ vlm_service = VLMService(model=model, api_base=api_base, api_key=api_key, prompt=args.prompt)+ default_vlm_config = {+ "model": model,+ "api_base": api_base,+ "api_key": api_key,+ "prompt": args.prompt,+ }+ sessions["default"] = {+ "vlm_service": vlm_service,+ "background_service": BackgroundModelService(+ session_id="default",+ notify_callback=lambda payload: notify_session_json("default", payload),+ summarizer_api_base=api_base,+ ),+ "show_request_payload": False,+ "show_response_payload": False,+ "show_memory_state": False,+ }++ # Log initialization with better formatting+ service_name = "Local" if "localhost" in api_base or "127.0.0.1" in api_base else "Cloud"+ logger.info("Initialized VLM service:")+ logger.info(f" Model: {model}")+ logger.info(f" API: {api_base} ({service_name})")+ logger.info(f" Prompt: {args.prompt}")++ # Update frame processing rate in VideoProcessorTrack if needed+ # (This is a bit hacky but works for this demo)+ VideoProcessorTrack.process_interval_seconds = args.process_interval+ VideoProcessorTrack.frames_per_batch = args.frames_per_batch++ # Create web application using create_app+ app = asyncio.run(create_app(test_mode=False))++ # Setup SSL (auto-generate certificates if needed)+ ssl_context = None+ protocol = "http"+ if not args.no_ssl:+ # Try to auto-generate if certificates don't exist+ if not os.path.exists(args.ssl_cert) or not os.path.exists(args.ssl_key):+ success = generate_self_signed_cert(args.ssl_cert, args.ssl_key)+ if not success:+ # FAIL FAST - SSL is required for webcam access+ logger.error("")+ logger.error("❌ Cannot start server without SSL certificates")+ logger.error("❌ Webcam access requires HTTPS!")+ logger.error("")+ logger.error("🔧 To fix, install openssl:")+ logger.error(" Linux/Jetson: sudo apt install openssl")+ logger.error(" macOS: brew install openssl")+ logger.error("")+ logger.error(" Then restart the server")+ logger.error("")+ logger.error(+ "⚠️ Or run with --no-ssl if you don't need camera access (not recommended)"+ )+ logger.error("")+ sys.exit(1)++ # Load certificates (they must exist at this point)+ if os.path.exists(args.ssl_cert) and os.path.exists(args.ssl_key):+ ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)+ ssl_context.load_cert_chain(args.ssl_cert, args.ssl_key)+ protocol = "https"+ logger.info("SSL enabled - using HTTPS")+ else:+ # This should never happen, but just in case+ logger.error("❌ SSL certificates missing after generation - unexpected error")+ sys.exit(1)+ else:+ logger.warning("⚠️ SSL disabled with --no-ssl flag")+ logger.warning("⚠️ Webcam access will NOT work without HTTPS!")++ # Get network addresses+ import socket+ import subprocess++ # Run server+ logger.info(f"Starting server on {args.host}:{args.port}")+ logger.info("")+ logger.info("=" * 70)+ logger.info("Access the server at:")+ logger.info(f" Local: {protocol}://localhost:{args.port}")++ # Get network interfaces - try multiple methods for cross-platform support+ network_ips = []++ # Method 1: hostname -I (Linux)+ try:+ result = subprocess.run(["hostname", "-I"], capture_output=True, text=True, timeout=1)+ if result.returncode == 0:+ ips = result.stdout.strip().split()+ for ip in ips:+ # Filter out loopback and docker bridges (172.17.x.x)+ if not ip.startswith("127.") and not ip.startswith("172.17."):+ network_ips.append(ip)+ except Exception:+ pass++ # Method 2: Socket method (cross-platform fallback)+ if not network_ips:+ try:+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ s.connect(("8.8.8.8", 80))+ ip = s.getsockname()[0]+ s.close()+ if ip and ip != "127.0.0.1":+ network_ips.append(ip)+ except Exception:+ pass++ # Display all found network IPs+ for ip in network_ips:+ logger.info(f" Network: {protocol}://{ip}:{args.port}")++ logger.info("=" * 70)+ logger.info("")+ logger.info("Press Ctrl+C to stop")++ # Setup signal handlers for graceful shutdown+ def signal_handler(signum, frame):+ logger.info("\nReceived signal to terminate. Shutting down gracefully...")+ raise KeyboardInterrupt++ signal.signal(signal.SIGINT, signal_handler)+ signal.signal(signal.SIGTERM, signal_handler)++ try:+ web.run_app(app, host=args.host, port=args.port, ssl_context=ssl_context)+ except KeyboardInterrupt:+ logger.info("Server stopped by user")+ except Exception as e:+ logger.error(f"Server error: {e}")+++def stop():+ """Stop the running alive-webui server"""+ import sys+ import time++ try:+ import psutil+ except ImportError:+ logger.error("psutil is required for the stop command")+ logger.error("Install it with: pip install alive-webui[dev]")+ sys.exit(1)++ print("Stopping ALIVE server...")++ # Find and kill processes running alive_webui.server+ found = False+ killed = []++ for proc in psutil.process_iter(["pid", "name", "cmdline"]):+ try:+ cmdline = proc.info.get("cmdline")+ if cmdline:+ cmdline_str = " ".join(cmdline)+ if "alive_webui.server" in cmdline_str or "alive-webui" in cmdline_str:+ # Don't kill the stop command itself+ if "stop" not in cmdline_str:+ found = True+ print(f" Stopping process {proc.info['pid']}: {proc.info['name']}")+ proc.terminate()+ killed.append(proc)+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):+ pass++ if not found:+ print("✓ No running server found")+ return++ # Wait for graceful shutdown+ time.sleep(2)++ # Force kill if still running+ for proc in killed:+ try:+ if proc.is_running():+ print(f" Force killing process {proc.pid}")+ proc.kill()+ except (psutil.NoSuchProcess, psutil.AccessDenied):+ pass++ # Final verification+ time.sleep(1)+ still_running = False+ for proc in psutil.process_iter(["cmdline"]):+ try:+ cmdline = proc.info.get("cmdline")+ if cmdline:+ cmdline_str = " ".join(cmdline)+ if "alive_webui.server" in cmdline_str or "alive-webui" in cmdline_str:+ if "stop" not in cmdline_str:+ still_running = True+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):+ pass++ if still_running:+ print("❌ Failed to stop server")+ sys.exit(1)+ else:+ print("✓ Server stopped successfully")+++if __name__ == "__main__":+ main()diff --git a/Web_Inference/webui/src/alive_webui/static/images/alive.png b/Web_Inference/webui/src/alive_webui/static/images/alive.pngnew file mode 100644index 0000000..326027cBinary files /dev/null and b/Web_Inference/webui/src/alive_webui/static/images/alive.png differdiff --git a/Web_Inference/webui/src/alive_webui/static/index.html b/Web_Inference/webui/src/alive_webui/static/index.htmlnew file mode 100644index 0000000..576795d--- /dev/null+++ b/Web_Inference/webui/src/alive_webui/static/index.html@@ -0,0 +1,9879 @@+<!--+SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+SPDX-License-Identifier: Apache-2.0++Licensed under the Apache License, Version 2.0 (the "License");+you may not use this file except in compliance with the License.+You may obtain a copy of the License at++http://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.+-->+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>ALIVE</title>++ <link rel="icon" type="image/png" href="/images/alive.png">++ <style>+ :root {+ /* Compatibility names for existing controls; alive brand colors. */+ --alive-red: #d51b69;+ --alive-red-dark: #ac1553;+ --alive-red-light: #ee418b;+ --alive-red-soft: rgba(231, 35, 116, 0.12);+ --alive-red-ring: rgba(231, 35, 116, 0.24);+ --alive-red-shadow: rgba(62, 18, 41, 0.32);++ /* Legacy variables kept for existing references */+ --theme-green: var(--alive-red);+ --theme-green-dark: var(--alive-red-dark);+ --theme-green-light: var(--alive-red-light);++ --bg-primary: #15171a;+ --bg-secondary: #1d2024;+ --bg-tertiary: #282c31;+ --text-primary: #f7f8fa;+ --text-secondary: #cbd0d6;+ --text-muted: #a0a7b0;+ --border-color: #3b4149;+ --card-bg: #22262b;+ --card-hover: #30363e;+ --accent-color: #ff82b6;+ --accent-hover: #ffa5ca;+ --primary-blue: var(--accent-color);+ --hover-bg: var(--card-hover);+ --warning-color: #f5b66b;+ --error-color: #f17e86;+ }++ body.light-theme {+ --bg-primary: #ffffff;+ --bg-secondary: #fafafa;+ --bg-tertiary: #f5f6f7;+ --text-primary: #20242a;+ --text-secondary: #525a65;+ --text-muted: #69727e;+ --border-color: #e3e6e9;+ --card-bg: #ffffff;+ --card-hover: #f0f2f4;+ --accent-color: #b91860;+ --accent-hover: #93104a;+ --warning-color: #ae681f;+ --error-color: #b9485b;+ }++ * {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+ }++ body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', sans-serif;+ background: var(--bg-primary);+ color: var(--text-primary);+ min-height: 100vh;+ transition: background 0.3s ease, color 0.3s ease;+ }++ /* Code styling for hostname */+ code {+ background: var(--bg-tertiary);+ border: 1px solid var(--border-color);+ padding: 2px 2px;+ border-radius: 6px;+ font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;+ font-size: 0.8em;+ color: var(--accent-color);+ white-space: nowrap;+ }++ /* Header */+ .header {+ background:+ radial-gradient(circle at 12% -80%, rgba(255, 143, 190, 0.22), transparent 32%),+ linear-gradient(112deg, #302330 0%, #211820 58%, #3d2032 100%);+ border-bottom: 1px solid rgba(255, 255, 255, 0.18);+ padding: 12px 32px;+ display: flex;+ justify-content: space-between;+ align-items: center;+ position: sticky;+ top: 0;+ z-index: 1000;+ backdrop-filter: blur(10px);+ box-shadow: 0 8px 28px rgba(4, 21, 32, 0.22);+ color: #ffffff;+ }++ .header-left {+ display: flex;+ align-items: center;+ gap: 20px;+ }++ .logo {+ width: 50px;+ height: 50px;+ padding: 5px;+ border-radius: 14px;+ background: rgba(255, 255, 255, 0.96);+ box-shadow: 0 8px 22px rgba(3, 23, 36, 0.25);+ line-height: 0;+ cursor: pointer;+ }++ .title-section h1 {+ font-size: 21px;+ font-weight: 780;+ color: #ffffff;+ margin-bottom: 0;+ letter-spacing: -0.03em;+ }++ .title-section h1 span {+ display: block;+ color: #e2b7cc;+ font-size: 11px;+ font-weight: 500;+ letter-spacing: 0.035em;+ line-height: 1.35;+ }++ .header-right {+ display: flex;+ align-items: center;+ gap: 12px;+ }++ .theme-toggle {+ background: rgba(255, 255, 255, 0.14);+ border: 1px solid rgba(255, 255, 255, 0.24);+ color: #ffffff;+ padding: 8px 16px;+ border-radius: 6px;+ cursor: pointer;+ font-size: 13px;+ transition: all 0.2s;+ display: flex;+ align-items: center;+ gap: 6px;+ }++ .theme-toggle:hover {+ background: rgba(255, 255, 255, 0.22);+ }++ .settings-btn {+ background: rgba(255, 255, 255, 0.14);+ border: 1px solid rgba(255, 255, 255, 0.24);+ color: #ffffff;+ padding: 8px 12px;+ border-radius: 6px;+ cursor: pointer;+ font-size: 16px;+ transition: all 0.2s;+ display: flex;+ align-items: center;+ }++ .settings-btn:hover {+ background: rgba(255, 255, 255, 0.22);+ }++ /* Settings Modal */+ .settings-modal {+ display: none;+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ background: rgba(0, 0, 0, 0.5);+ z-index: 10000;+ justify-content: center;+ align-items: center;+ }++ .settings-modal.show {+ display: flex;+ }++ .settings-dialog {+ background: var(--bg-secondary);+ border: 1px solid var(--border-color);+ border-radius: 12px;+ width: 90%;+ max-width: 900px;+ max-height: 80vh;+ overflow-y: auto;+ box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);+ }++ .settings-header {+ padding: 20px 24px;+ border-bottom: 1px solid var(--border-color);+ display: flex;+ justify-content: space-between;+ align-items: center;+ }++ .settings-title {+ font-size: 18px;+ font-weight: 600;+ color: var(--text-primary);+ }++ .settings-close {+ background: none;+ border: none;+ font-size: 24px;+ color: var(--text-secondary);+ cursor: pointer;+ padding: 0;+ width: 32px;+ height: 32px;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: 4px;+ transition: all 0.2s;+ }++ .settings-close:hover {+ background: var(--bg-tertiary);+ }++ .settings-body {+ padding: 24px;+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 32px;+ }++ .settings-section {+ margin-bottom: 24px;+ }++ .settings-section:last-child {+ margin-bottom: 0;+ }++ /* Full width section for sections that need it */+ .settings-section.full-width {+ grid-column: 1 / -1;+ }++ .settings-section-title {+ font-size: 14px;+ font-weight: 600;+ color: var(--text-primary);+ margin-bottom: 12px;+ }++ .settings-item {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 12px 0;+ border-bottom: 1px solid var(--border-color);+ gap: 16px;+ }++ .settings-item:last-child {+ border-bottom: none;+ }++ .settings-item-label {+ font-size: 14px;+ color: var(--text-primary);+ }++ .settings-item > div:first-child {+ flex: 1;+ min-width: 0;+ }++ .settings-item-description {+ font-size: 12px;+ color: var(--text-muted);+ margin-top: 4px;+ }++ /* Toggle Switch */+ .toggle-switch {+ position: relative;+ width: 48px;+ height: 26px;+ flex-shrink: 0;+ }++ .toggle-switch input {+ opacity: 0;+ width: 0;+ height: 0;+ }++ .toggle-slider {+ position: absolute;+ cursor: pointer;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background-color: var(--bg-tertiary);+ border: 1px solid var(--border-color);+ transition: 0.3s;+ border-radius: 26px;+ }++ .toggle-slider:before {+ position: absolute;+ content: "";+ height: 18px;+ width: 18px;+ left: 3px;+ bottom: 3px;+ background-color: var(--text-secondary);+ transition: 0.3s;+ border-radius: 50%;+ }++ input:checked + .toggle-slider {+ background-color: var(--accent-color);+ border-color: var(--accent-color);+ }++ input:checked + .toggle-slider:before {+ transform: translateX(22px);+ background-color: white;+ }++ /* Settings Dropdown */+ .settings-select {+ background: var(--bg-tertiary);+ border: 1px solid var(--border-color);+ color: var(--text-primary);+ padding: 6px 12px;+ border-radius: 6px;+ font-size: 14px;+ cursor: pointer;+ width: 180px;+ flex-shrink: 0;+ }++ .settings-select:focus {+ outline: none;+ border-color: var(--accent-color);+ }++ /* Main Layout */+ .container {+ display: flex;+ height: calc(100vh - 75px);+ min-width: 0;+ }++ /* Sidebar */+ .sidebar {+ width: 350px;+ flex: 0 0 350px;+ background: var(--bg-secondary);+ border-right: 1px solid var(--border-color);+ overflow-y: auto;+ overflow-x: hidden;+ padding: 20px;+ transition: width 0.25s ease, flex-basis 0.25s ease, padding 0.25s ease;+ }++ .sidebar.docked {+ width: 64px;+ flex-basis: 64px;+ padding: 12px 8px;+ }++ .panel {+ background: var(--card-bg);+ border: 1px solid var(--border-color);+ border-radius: 8px;+ margin-bottom: 16px;+ overflow: visible;+ }++ .sidebar.docked .panel {+ margin-bottom: 10px;+ overflow: hidden;+ }++ .panel-header {+ padding: 14px 16px;+ border-bottom: 1px solid var(--border-color);+ cursor: pointer;+ user-select: none;+ display: flex;+ justify-content: space-between;+ align-items: center;+ transition: background 0.2s;+ }++ .sidebar.docked .panel-header {+ justify-content: center;+ padding: 12px;+ border-bottom: none;+ }++ .panel-header:hover {+ background: var(--card-hover);+ }++ .panel-title {+ font-size: 14px;+ font-weight: 600;+ color: var(--text-primary);+ display: flex;+ align-items: center;+ gap: 8px;+ }++ .sidebar.docked .panel-title {+ gap: 0;+ }++ .sidebar.docked .panel-title-text,+ .sidebar.docked .panel-toggle {+ display: none;+ }++ .panel-icon {+ font-size: 16px;+ }++ .panel-toggle {+ color: var(--text-muted);+ font-size: 12px;+ transition: transform 0.2s;+ }++ .panel-toggle.collapsed {+ transform: rotate(-90deg);+ }++ .panel-content {+ padding: 16px;+ max-height: 1000px;+ transition: max-height 0.3s ease, opacity 0.3s ease;+ opacity: 1;+ overflow: visible;+ }++ .panel-content.collapsed {+ max-height: 0;+ opacity: 0;+ padding: 0 16px;+ overflow: hidden;+ }++ #apiKeyField {+ max-height: 100px;+ transition: max-height 0.3s ease, opacity 0.3s ease;+ opacity: 1;+ overflow: hidden;+ }++ #apiKeyField.collapsed {+ max-height: 0;+ opacity: 0;+ }++ #apiKeyToggle {+ transition: transform 0.2s;+ }++ #apiKeyToggle.collapsed {+ transform: rotate(-90deg);+ }++ .form-group {+ margin-bottom: 14px;+ }++ .form-group:last-child {+ margin-bottom: 0;+ }++ label {+ display: block;+ font-size: 12px;+ font-weight: 500;+ color: var(--text-secondary);+ margin-bottom: 6px;+ letter-spacing: 0.3px;+ }++ input[type="text"],+ input[type="number"],+ select,+ textarea {+ width: 100%;+ background: var(--bg-tertiary);+ border: 1px solid var(--border-color);+ color: var(--text-primary);+ padding: 10px 12px;+ border-radius: 6px;+ font-size: 13px;+ font-family: inherit;+ transition: border 0.2s;+ }++ input:focus,+ select:focus,+ textarea:focus {+ outline: none;+ border-color: var(--primary-blue);+ }++ /* Prevent browser autofill blue background */+ input:-webkit-autofill,+ input:-webkit-autofill:hover,+ input:-webkit-autofill:focus {+ -webkit-box-shadow: 0 0 0 1000px var(--bg-tertiary) inset !important;+ -webkit-text-fill-color: var(--text-primary) !important;+ transition: background-color 5000s ease-in-out 0s;+ }++ /* Disabled input styling */+ input:disabled,+ select:disabled,+ textarea:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ background: var(--bg-secondary);+ color: var(--text-muted);+ }++ textarea {+ resize: vertical;+ min-height: 80px;+ line-height: 1.5;+ }++ .btn {+ width: 100%;+ padding: 10px 16px;+ border: none;+ border-radius: 6px;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ transition: all 0.2s;+ letter-spacing: 0.3px;+ }++ .btn-primary {+ background: var(--accent-color);+ color: white;+ border: 1px solid var(--accent-color);+ }++ .btn-primary:hover {+ background: var(--accent-hover);+ border-color: var(--accent-hover);+ transform: translateY(-1px);+ box-shadow: 0 4px 12px var(--alive-red-ring);+ }++ /* Tab-style underline (for future use) */+ .tab-item {+ padding: 10px 20px;+ cursor: pointer;+ border-bottom: 3px solid transparent;+ transition: border-color 0.2s;+ }++ .tab-item.active {+ border-bottom-color: var(--accent-color);+ }++ .tab-item:hover {+ border-bottom-color: var(--accent-hover);+ }++ .btn-secondary {+ background: var(--bg-tertiary);+ color: var(--text-primary);+ border: 1px solid var(--border-color);+ }++ .btn-secondary:hover {+ background: var(--card-hover);+ }++ .btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }++ .icon-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 28px;+ height: 28px;+ padding: 0;+ border: 1px solid var(--border-color);+ border-radius: 6px;+ background: var(--bg-tertiary);+ color: var(--text-primary);+ font-size: 14px;+ cursor: pointer;+ transition: all 0.2s;+ }++ .icon-btn:hover:not(:disabled) {+ background: var(--card-hover);+ border-color: var(--accent-color);+ transform: scale(1.1);+ }++ .icon-btn:active:not(:disabled) {+ transform: scale(0.95);+ }++ .icon-btn:disabled {+ cursor: not-allowed;+ opacity: 0.4;+ background: var(--bg-secondary);+ }++ .input-hint {+ font-size: 11px;+ color: var(--text-muted);+ margin-top: 4px;+ }++ /* Input Source Tabs */+ .input-source-tabs {+ display: flex;+ gap: 0;+ margin-bottom: 16px;+ border-bottom: 2px solid var(--border-color);+ }++ /* Beta Badge - Small and Rotated */+ .beta-badge {+ display: inline-block;+ background: var(--warning-color);+ color: #000;+ font-size: 7px;+ font-weight: 700;+ padding: 1px 1px;+ border-radius: 2px;+ margin-left: -6px;+ vertical-align: super;+ letter-spacing: 0.3px;+ transform: rotate(50deg);+ transform-origin: center;+ }++ .input-source-tab {+ flex: 1;+ padding: 10px 2px;+ background: transparent;+ border: none;+ border-bottom: 2px solid transparent;+ margin-bottom: -2px;+ cursor: pointer;+ font-size: 13px;+ font-weight: 500;+ color: var(--text-muted);+ transition: all 0.2s;+ }++ .input-source-tab:hover {+ color: var(--text-primary);+ background: var(--alive-red-soft);+ }++ .input-source-tab.active {+ color: var(--accent-color);+ border-bottom-color: var(--accent-color);+ }++ /* Tooltip */+ .tooltip-wrapper {+ position: relative;+ display: inline-flex;+ align-items: baseline;+ gap: 6px;+ }++ .tooltip-icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 15px;+ height: 15px;+ border-radius: 50%;+ background: var(--border-color);+ color: var(--text-muted);+ font-size: 10px;+ font-weight: 600;+ line-height: 1;+ cursor: help;+ transition: all 0.2s;+ flex-shrink: 0;+ transform: translateY(-1px);+ }++ .tooltip-icon:hover {+ background: var(--accent-color);+ color: white;+ }++ .tooltip-text {+ visibility: hidden;+ opacity: 0;+ position: fixed;+ padding: 12px 16px;+ background: var(--card-bg);+ border: 1px solid var(--accent-color);+ border-radius: 8px;+ font-size: 12px;+ line-height: 1.6;+ color: var(--text-primary);+ white-space: normal;+ width: 380px;+ max-width: calc(100vw - 40px);+ z-index: 10000;+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);+ transition: opacity 0.2s, visibility 0.2s;+ pointer-events: none;+ }++ .tooltip-text strong {+ color: var(--accent-color);+ font-weight: 600;+ }++ .tooltip-wrapper:hover .tooltip-text {+ visibility: visible;+ opacity: 1;+ }++ /* Main Content */+ .main-content {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: 20px;+ display: flex;+ flex-direction: column;+ gap: 20px;+ }+++ /* Status Badge */+ .status-badge {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 6px 12px;+ border-radius: 16px;+ font-size: 12px;+ font-weight: 600;+ text-transform: uppercase;+ }++ .status-badge.connected {+ background: rgba(255, 255, 255, 0.2);+ color: #ffffff;+ }++ .status-badge.disconnected {+ background: rgba(255, 255, 255, 0.12);+ color: rgba(255, 255, 255, 0.76);+ }++ .status-badge.processing {+ background: rgba(255, 255, 255, 0.2);+ color: #ffffff;+ }++ /* Video Display */+ .video-card {+ background: var(--card-bg);+ border: 1px solid var(--border-color);+ border-radius: 12px;+ overflow: hidden;+ margin-bottom: 20px;+ position: relative;+ display: flex;+ flex-direction: column;+ flex: 0 0 auto;+ }++ .video-card.waiting-for-stream {+ background: #000;+ }++ .video-card.waiting-for-stream video {+ visibility: hidden;+ }++ video {+ width: 100%;+ flex: 1;+ min-height: 240px;+ max-height: 100%;+ display: block;+ background: #000;+ transition: transform 0.3s ease;+ object-fit: contain;+ margin: 0;+ padding: 0;+ }++ /* Video Overlay Text */+ .video-overlay {+ position: absolute;+ left: 0;+ right: 0;+ padding: 16px 20px;+ background: linear-gradient(to bottom, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.4));+ color: white;+ font-size: 16px;+ line-height: 1.5;+ pointer-events: none;+ display: none;+ z-index: 10;+ }++ .video-overlay.top {+ top: 0;+ background: linear-gradient(to bottom, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.4));+ }++ .video-overlay.bottom {+ bottom: 0;+ background: linear-gradient(to top, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.4));+ }++ .video-overlay.show {+ display: block;+ }++ video.mirrored {+ transform: scaleX(-1);+ }++ .video-controls {+ position: absolute;+ top: 12px;+ right: 12px;+ display: flex;+ gap: 8px;+ z-index: 10;+ }++ .video-control-btn {+ background: rgba(0, 0, 0, 0.7);+ border: 1px solid rgba(255, 255, 255, 0.2);+ color: white;+ padding: 8px 12px;+ border-radius: 6px;+ cursor: pointer;+ font-size: 13px;+ backdrop-filter: blur(10px);+ transition: all 0.2s;+ }++ .video-control-btn:hover {+ background: rgba(0, 0, 0, 0.9);+ border-color: var(--accent-color);+ }++ .video-control-btn.active {+ background: var(--accent-color);+ border-color: var(--accent-color);+ }++ .fullscreen-prompt-overlay {+ position: absolute;+ bottom: max(18px, env(safe-area-inset-bottom));+ left: 18px;+ width: min(640px, calc(100vw - 36px));+ max-height: 72px;+ display: none;+ z-index: 102;+ }++ .video-card.fullscreen .fullscreen-prompt-overlay {+ display: block;+ }++ .fullscreen-prompt-overlay .chat-prompt-shell {+ background: rgba(255, 255, 255, 0.08);+ border-color: rgba(255, 255, 255, 0.22);+ backdrop-filter: blur(18px) saturate(145%);+ box-shadow: 0 10px 28px rgba(0, 0, 0, 0.12);+ }++ .fullscreen-prompt-overlay .chat-prompt-input {+ color: white;+ max-height: 48px;+ text-shadow: 0 1px 6px rgba(0, 0, 0, 0.7);+ }++ .video-card.fullscreen .fullscreen-prompt-overlay:has(.chat-prompt-shell.mobile-voice-mode) {+ bottom: max(32px, calc(env(safe-area-inset-bottom) + 24px));+ max-height: none;+ }++ .video-card.fullscreen .fullscreen-prompt-overlay.voice-panel-open {+ bottom: max(32px, calc(env(safe-area-inset-bottom) + 24px));+ max-height: none;+ }++ /* Big Start Button (centered on video) */+ .big-start-btn {+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ width: min(140px, 25vh);+ height: min(140px, 25vh);+ max-width: 80%;+ max-height: 80%;+ border-radius: 16px;+ background: linear-gradient(135deg, var(--alive-red-light), var(--alive-red) 52%, var(--alive-red-dark));+ border: none;+ color: white;+ font-size: 20px;+ font-weight: 600;+ cursor: pointer;+ box-shadow: 0 12px 30px rgba(82, 24, 53, 0.36);+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 8px;+ z-index: 100;+ opacity: 0.8;+ transition: transform 0.2s ease, box-shadow 0.2s ease, opacity 0.2s ease;+ }++ .big-start-btn:hover:not(:disabled):not(.animating) {+ transform: translate(-50%, -50%) scale(1.05);+ box-shadow: 0 16px 38px rgba(82, 24, 53, 0.46);+ opacity: 0.95;+ }++ .big-start-btn:active:not(:disabled):not(.animating) {+ transform: translate(-50%, -50%) scale(0.95);+ }++ .big-start-btn:disabled {+ opacity: 0.8;+ cursor: wait;+ transform: translate(-50%, -50%);+ }++ .big-start-btn i, .big-start-btn svg {+ width: 56px !important;+ height: 56px !important;+ flex-shrink: 0;+ }++ /* Animation to top-left corner when streaming starts */+ .big-start-btn.animating {+ animation: moveToCorner 0.5s cubic-bezier(0.4, 0, 0.2, 1) forwards;+ pointer-events: none;+ }++ @keyframes moveToCorner {+ 0% {+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ width: 140px;+ height: 140px;+ border-radius: 16px;+ background: linear-gradient(135deg, var(--alive-red-light), var(--alive-red) 52%, var(--alive-red-dark));+ font-size: 20px;+ box-shadow: 0 12px 30px rgba(82, 24, 53, 0.36);+ }+ 100% {+ top: 16px;+ left: 16px;+ transform: translate(0, 0);+ width: 48px;+ height: 48px;+ border-radius: 8px;+ background: linear-gradient(135deg, #FFA726, #FF9800);+ font-size: 0px;+ box-shadow: 0 4px 12px rgba(255, 152, 0, 0.5);+ opacity: 0;+ }+ }++ /* Hide after animation */+ .big-start-btn.streaming {+ display: none;+ }++ /* Small Stop button (top-left corner when streaming) */+ .small-stop-btn {+ position: absolute;+ top: 16px;+ left: 16px;+ width: 48px;+ height: 48px;+ border-radius: 8px;+ background: linear-gradient(135deg, #EF5350, #D32F2F) !important;+ border: none;+ color: white;+ cursor: pointer;+ box-shadow: 0 4px 12px rgba(239, 83, 80, 0.5);+ display: none;+ align-items: center;+ justify-content: center;+ transition: transform 0.3s ease, opacity 0.3s ease;+ z-index: 100;+ opacity: 0.7;+ }++ .small-stop-btn.show {+ display: flex;+ }++ .small-stop-btn:hover {+ background: linear-gradient(135deg, #EF5350, #D32F2F) !important;+ transform: scale(1.1);+ opacity: 1 !important;+ }++ .small-stop-btn:active {+ transform: scale(0.95);+ }++ .small-stop-btn i, .small-stop-btn svg {+ width: 30px !important;+ height: 30px !important;+ flex-shrink: 0;+ }++ /* Fullscreen button (top-right corner) */+ .fullscreen-btn {+ position: absolute;+ top: 12px;+ right: 12px;+ width: 40px;+ height: 40px;+ border-radius: 8px;+ background: rgba(0, 0, 0, 0.5);+ border: 1px solid rgba(255, 255, 255, 0.2);+ color: white;+ cursor: pointer;+ backdrop-filter: blur(10px);+ display: flex;+ align-items: center;+ justify-content: center;+ transition: all 0.2s ease;+ z-index: 99;+ opacity: 0.3;+ }++ .fullscreen-btn:hover {+ background: rgba(0, 0, 0, 0.8);+ border-color: var(--accent-color);+ opacity: 0.8;+ transform: scale(1.05);+ }++ .fullscreen-btn svg, .fullscreen-btn i {+ width: 20px !important;+ height: 20px !important;+ }++ .quick-camera-btn {+ position: absolute;+ top: 12px;+ right: 60px;+ min-width: 92px;+ height: 40px;+ padding: 0 12px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.14);+ border: 1px solid rgba(255, 255, 255, 0.28);+ color: white;+ cursor: pointer;+ backdrop-filter: blur(12px);+ display: none;+ align-items: center;+ justify-content: center;+ gap: 6px;+ font-size: 12px;+ font-weight: 650;+ z-index: 101;+ opacity: 0.86;+ box-shadow: 0 6px 16px rgba(0, 0, 0, 0.18);+ }++ .quick-camera-btn svg,+ .quick-camera-btn i {+ width: 16px !important;+ height: 16px !important;+ flex-shrink: 0;+ }++ .quick-camera-btn:hover {+ background: rgba(255, 255, 255, 0.22);+ border-color: rgba(255, 255, 255, 0.4);+ }++ .quick-camera-btn:disabled {+ opacity: 0.45;+ cursor: not-allowed;+ }++ /* Fullscreen mode styles */+ .video-card.fullscreen {+ position: fixed;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ width: 100vw !important;+ height: 100vh !important;+ max-width: 100vw !important;+ max-height: 100vh !important;+ z-index: 9999;+ margin: 0;+ border-radius: 0;+ border: none;+ }++ .video-card.fullscreen video {+ width: 100%;+ height: 100%;+ object-fit: contain;+ }++ .video-card.fullscreen .fullscreen-btn {+ opacity: 0.7;+ background: rgba(0, 0, 0, 0.8);+ z-index: 101;+ }++ .video-card.fullscreen .fullscreen-btn:hover {+ opacity: 1;+ transform: scale(1.1);+ }++ /* Keep controls above VLM overlay in fullscreen so shrink/mirror remain clickable */+ .video-card.fullscreen .video-controls {+ z-index: 101;+ }++ /* Responses overlay in fullscreen mode */+ .fullscreen-vlm-overlay {+ position: absolute;+ top: 76px;+ left: 18px;+ width: min(480px, calc(100vw - 36px));+ padding: 10px 12px;+ background: rgba(255, 255, 255, 0.08);+ border: 1px solid rgba(255, 255, 255, 0.18);+ border-radius: 10px;+ backdrop-filter: blur(18px) saturate(145%);+ color: white;+ z-index: 98;+ display: none;+ max-height: calc(1.45em * 4 + 22px);+ overflow: hidden;+ pointer-events: none;+ }++ .video-card.fullscreen .fullscreen-vlm-overlay {+ display: block;+ }++ .fullscreen-vlm-overlay .vlm-title {+ display: none;+ font-size: 12px;+ font-weight: 600;+ color: var(--accent-color);+ margin-bottom: 6px;+ align-items: center;+ gap: 8px;+ text-shadow: 0 1px 6px rgba(0, 0, 0, 0.65);+ }++ .fullscreen-vlm-overlay .vlm-content {+ font-size: 13px;+ line-height: 1.45;+ font-weight: 500;+ display: -webkit-box;+ -webkit-line-clamp: 4;+ -webkit-box-orient: vertical;+ overflow: hidden;+ white-space: pre-line;+ word-break: break-word;+ text-shadow: 0 2px 8px rgba(0, 0, 0, 0.8);+ }++ .fullscreen-vlm-overlay .vlm-metrics {+ display: none;+ font-size: 12px;+ color: rgba(255, 255, 255, 0.7);+ margin-top: 8px;+ gap: 16px;+ }++ /* Generation Result */+ .result-card {+ background: var(--card-bg);+ border: 1px solid var(--border-color);+ border-radius: 12px;+ padding: 20px;+ margin-bottom: 20px;+ transition: opacity 0.3s ease, filter 0.3s ease;+ }++ .result-card.cloud-api {+ opacity: 0.5;+ filter: grayscale(0.3);+ }++ #vlmOutputCard {+ display: flex;+ flex-direction: column;+ flex: 1 1 0;+ min-height: 0;+ }++ .api-preset-item {+ padding: 10px 16px;+ cursor: pointer;+ transition: background 0.2s;+ }++ .api-preset-item:hover {+ background: var(--hover-bg);+ }++ .api-preset-item strong {+ color: var(--text-primary);+ font-size: 13px;+ }++ .result-header {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ gap: 16px;+ margin-bottom: 16px;+ min-width: 0;+ }++ .result-header-left {+ flex: 1 1 auto;+ min-width: 0;+ }++ .result-title {+ font-size: 14px;+ font-weight: 600;+ color: var(--text-secondary);+ letter-spacing: 0.3px;+ margin-bottom: 6px;+ }++ .result-subtitle {+ font-size: 12px;+ color: var(--text-muted);+ line-height: 1.4;+ }++ .tts-speaking-line {+ display: none;+ margin-top: 6px;+ font-size: 12px;+ line-height: 1.35;+ color: var(--text-secondary);+ max-width: 100%;+ white-space: normal;+ overflow: hidden;+ overflow-wrap: anywhere;+ max-height: calc(1.35em * 2);+ }++ .tts-speaking-line.show {+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;+ }++ .tts-speaking-line strong {+ color: var(--accent-color);+ font-weight: 600;+ }++ .vlm-history {+ position: relative;+ height: 420px;+ max-height: 420px;+ overflow-y: auto;+ overflow-x: hidden;+ overscroll-behavior: contain;+ padding-top: 18px;+ padding-right: 4px;+ padding-bottom: 36px;+ scroll-behavior: auto;+ overflow-anchor: none;+ display: block;+ -webkit-overflow-scrolling: touch;+ scrollbar-gutter: stable;+ contain: layout paint;+ }++ /* Stick messages to the bottom: the first real bubble absorbs leftover+ vertical space so content grows upward from the bottom like a chat app. */+ .vlm-history > .result-prompt:first-of-type,+ .vlm-history > .result-text:first-of-type {+ margin-top: auto;+ }++ /* Prevent flex from shrinking bubbles to fit the container — without this,+ items collapse instead of overflowing and the scrollbar never appears. */+ .vlm-history > .result-prompt,+ .vlm-history > .result-text {+ flex-shrink: 0;+ }++ .vlm-history::before {+ content: none;+ position: sticky;+ top: 0;+ display: block;+ height: 44px;+ margin-bottom: -44px;+ background: linear-gradient(to bottom, var(--card-bg), transparent);+ pointer-events: none;+ z-index: 3;+ }++ .result-prompt {+ font-size: 15px;+ line-height: 1.5;+ color: var(--text-primary);+ margin-top: 16px;+ margin-bottom: 12px;+ margin-left: auto;+ margin-right: 0;+ padding: 6px 12px;+ background: var(--bg-tertiary);+ border: 1px solid var(--border-color);+ border-radius: 16px 16px 4px 16px;+ max-width: 85%;+ word-wrap: break-word;+ }++ .result-text {+ font-size: 15px;+ line-height: 1.5;+ color: var(--text-primary);+ transition: opacity 3s ease, transform 0.3s ease, box-shadow 0.3s ease;+ min-height: 120px;+ margin-top: 12px;+ margin-left: 0;+ margin-right: auto;+ padding: 6px 12px;+ background: linear-gradient(135deg, rgba(231, 35, 116, 0.12) 0%, rgba(82, 24, 53, 0.06) 100%);+ border: 1px solid rgba(231, 35, 116, 0.24);+ border-radius: 16px 16px 16px 4px;+ max-width: 90%;+ word-wrap: break-word;+ position: relative; /* For absolute positioning of button */+ }++ .vlm-history .result-prompt:first-of-type {+ margin-top: 0;+ }++ .result-text-content {+ /* Content wrapper - this is what gets updated, not the parent */+ width: 100%;+ }++ .vlm-history-shell {+ width: 100%;+ max-width: 100%;+ flex: 1 1 auto;+ min-height: 0;+ padding: 0;+ background: transparent;+ border: none;+ border-radius: 0;+ display: flex;+ flex-direction: column;+ }++ .vlm-history .result-text {+ display: block;+ min-height: 0;+ margin-top: 8px;+ margin-bottom: 12px;+ position: static;+ }++ .result-text.background-result {+ width: min(100%, 760px);+ border-color: rgba(255, 167, 38, 0.34);+ background: linear-gradient(135deg, rgba(255, 167, 38, 0.14), rgba(231, 35, 116, 0.06));+ }++ .background-result-shell {+ display: flex;+ flex-direction: column;+ gap: 10px;+ }++ .background-result-header {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ }++ .background-result-icon {+ width: 28px;+ height: 28px;+ flex: 0 0 28px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border-radius: 50%;+ color: var(--warning-color);+ background: rgba(255, 167, 38, 0.16);+ }++ .background-result-title {+ flex: 1 1 auto;+ min-width: 0;+ font-weight: 700;+ color: var(--text-primary);+ }++ .background-result-question {+ margin-top: 3px;+ font-size: 13px;+ font-weight: 400;+ color: var(--text-secondary);+ overflow-wrap: anywhere;+ }++ .background-result-action {+ flex: 0 0 auto;+ border: 1px solid rgba(255, 167, 38, 0.34);+ border-radius: 6px;+ padding: 5px 10px;+ background: var(--card-bg);+ color: var(--text-primary);+ cursor: pointer;+ font-size: 13px;+ font-weight: 600;+ }++ .background-result-action:hover {+ background: var(--card-hover);+ }++ .background-result-action:disabled {+ opacity: 0.55;+ cursor: default;+ }++ .background-origin-action {+ width: 30px;+ height: 30px;+ padding: 0;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ }++ .background-origin-action i,+ .background-origin-action svg {+ width: 15px !important;+ height: 15px !important;+ }++ .background-jump-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ margin-top: 10px;+ padding-top: 10px;+ border-top: 1px solid rgba(255, 167, 38, 0.18);+ }++ .background-jump-question {+ min-width: 0;+ flex: 1 1 auto;+ display: flex;+ align-items: baseline;+ gap: 6px;+ padding: 6px 9px;+ border-radius: 8px;+ background: rgba(255, 167, 38, 0.10);+ border: 1px solid rgba(255, 167, 38, 0.18);+ color: var(--text-primary);+ }++ .background-jump-question-label {+ flex: 0 0 auto;+ color: var(--warning-color);+ font-size: 12px;+ font-weight: 800;+ }++ .background-jump-question-text {+ min-width: 0;+ overflow-wrap: anywhere;+ color: var(--text-primary);+ font-size: 13px;+ line-height: 1.35;+ font-weight: 700;+ }++ .background-jump-button {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ border: 1px solid rgba(255, 167, 38, 0.42);+ border-radius: 999px;+ padding: 6px 11px;+ background: linear-gradient(135deg, rgba(255, 167, 38, 0.18), rgba(231, 35, 116, 0.12));+ color: var(--text-primary);+ cursor: pointer;+ font-size: 13px;+ font-weight: 700;+ box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);+ white-space: nowrap;+ flex: 0 0 auto;+ }++ .background-jump-button:hover {+ background: linear-gradient(135deg, rgba(255, 167, 38, 0.25), rgba(231, 35, 116, 0.18));+ }++ .background-jump-button i,+ .background-jump-button svg {+ width: 15px !important;+ height: 15px !important;+ }++ .background-result.jump-highlight {+ box-shadow: 0 0 0 2px rgba(255, 167, 38, 0.58), 0 0 24px rgba(255, 167, 38, 0.22);+ }++ .result-prompt.jump-highlight {+ box-shadow: 0 0 0 2px rgba(255, 167, 38, 0.58), 0 0 24px rgba(255, 167, 38, 0.22);+ }++ .result-text.background-summary-message {+ width: min(100%, 720px);+ background: linear-gradient(135deg, rgba(255, 167, 38, 0.13), rgba(55, 65, 81, 0.08));+ border-color: rgba(255, 167, 38, 0.32);+ box-shadow: inset 3px 0 0 rgba(255, 167, 38, 0.62);+ }++ .background-summary-message {+ display: flex;+ flex-direction: column;+ gap: 9px;+ }++ .background-summary-label {+ display: inline-flex;+ width: fit-content;+ align-items: center;+ gap: 6px;+ border: 1px solid rgba(255, 167, 38, 0.22);+ border-radius: 999px;+ padding: 4px 9px;+ background: rgba(255, 167, 38, 0.12);+ color: var(--warning-color);+ font-size: 12px;+ font-weight: 800;+ }++ .background-summary-label i,+ .background-summary-label svg {+ width: 14px !important;+ height: 14px !important;+ }++ .background-summary-body {+ min-width: 0;+ }++ .background-summary-body > *:first-child {+ margin-top: 0;+ }++ .background-summary-body > *:last-child {+ margin-bottom: 0;+ }++ .standard-rich-response {+ display: flex;+ flex-direction: column;+ gap: 10px;+ }++ .standard-rich-explanation,+ .standard-rich-chart,+ .standard-rich-html {+ min-width: 0;+ }++ .background-rich-content {+ display: flex;+ flex-direction: column;+ gap: 12px;+ }++ .background-rich-tabs {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ }++ .background-rich-tab {+ border: 1px solid var(--border-color);+ border-radius: 6px;+ padding: 4px 10px;+ background: var(--bg-tertiary);+ color: var(--text-secondary);+ cursor: pointer;+ font-size: 12px;+ font-weight: 600;+ }++ .background-rich-tab.active {+ color: var(--text-primary);+ border-color: rgba(255, 167, 38, 0.42);+ background: rgba(255, 167, 38, 0.14);+ }++ .background-view-shell {+ display: flex;+ flex-direction: column;+ gap: 8px;+ }++ .background-view-toolbar {+ display: flex;+ justify-content: flex-end;+ gap: 6px;+ }++ .background-rich-action {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ border: 1px solid rgba(255, 167, 38, 0.34);+ border-radius: 6px;+ padding: 4px 9px;+ background: var(--card-bg);+ color: var(--text-primary);+ cursor: pointer;+ font-size: 12px;+ font-weight: 600;+ }++ .background-rich-action:hover {+ background: var(--card-hover);+ }++ .background-rich-action i {+ width: 14px;+ height: 14px;+ }++ .background-raw-shell {+ display: flex;+ flex-direction: column;+ gap: 8px;+ }++ .background-raw-toolbar {+ display: flex;+ justify-content: flex-end;+ gap: 6px;+ }++ .background-raw-copy {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ border: 1px solid rgba(255, 167, 38, 0.34);+ border-radius: 6px;+ padding: 4px 9px;+ background: var(--card-bg);+ color: var(--text-primary);+ cursor: pointer;+ font-size: 12px;+ font-weight: 600;+ }++ .background-raw-copy:hover {+ background: var(--card-hover);+ }++ .background-raw-block {+ max-height: calc(1.45em * 7 + 20px);+ margin: 0;+ padding: 10px 12px;+ overflow: auto;+ border: 1px solid var(--border-color);+ border-radius: 8px;+ background: rgba(12, 10, 10, 0.72);+ color: var(--text-primary);+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;+ font-size: 13px;+ line-height: 1.45;+ white-space: pre;+ }++ .background-html-frame {+ width: 100%;+ min-height: 420px;+ border: 1px solid var(--border-color);+ border-radius: 8px;+ background: #fff;+ }++ .background-preview-warning {+ padding: 8px 10px;+ border: 1px solid rgba(255, 167, 38, 0.32);+ border-radius: 8px;+ background: rgba(255, 167, 38, 0.12);+ color: var(--text-secondary);+ font-size: 12px;+ line-height: 1.45;+ }++ .background-chart {+ width: 100%;+ height: 280px;+ border: 1px solid var(--border-color);+ border-radius: 8px;+ background: var(--bg-secondary);+ }++ .background-modal-backdrop[hidden] {+ display: none;+ }++ .background-modal-backdrop {+ position: fixed;+ inset: 0;+ z-index: 10000;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 24px;+ background: rgba(8, 6, 6, 0.54);+ backdrop-filter: blur(18px) saturate(145%);+ -webkit-backdrop-filter: blur(18px) saturate(145%);+ }++ .background-modal-dialog {+ width: min(1120px, calc(100vw - 48px));+ max-height: calc(100vh - 48px);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ border: 1px solid rgba(255, 167, 38, 0.34);+ border-radius: 8px;+ background: rgba(24, 18, 18, 0.96);+ box-shadow: 0 24px 80px rgba(0, 0, 0, 0.48);+ }++ .background-modal-header {+ flex: 0 0 auto;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ padding: 14px 16px;+ border-bottom: 1px solid var(--border-color);+ }++ .background-modal-title {+ margin: 0;+ font-size: 16px;+ font-weight: 700;+ color: var(--text-primary);+ }++ .background-modal-close {+ width: 34px;+ height: 34px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border: 1px solid var(--border-color);+ border-radius: 6px;+ background: var(--card-bg);+ color: var(--text-primary);+ cursor: pointer;+ }++ .background-modal-close:hover {+ background: var(--card-hover);+ }++ .background-modal-body {+ flex: 1 1 auto;+ min-height: 0;+ overflow: auto;+ padding: 16px;+ }++ .background-modal-dialog .background-raw-block {+ max-height: calc(100vh - 180px);+ }++ .background-modal-dialog .background-html-frame {+ min-height: min(760px, calc(100vh - 180px));+ height: calc(100vh - 180px);+ }++ .background-modal-dialog .background-chart {+ height: min(680px, calc(100vh - 200px));+ }++ body.background-modal-open {+ overflow: hidden;+ }++ .prompt-editor-inline {+ margin-top: auto;+ flex: 0 0 auto;+ padding-top: 14px;+ border-top: 1px solid var(--border-color);+ }++ .chat-prompt-shell {+ position: relative;+ display: flex;+ align-items: flex-end;+ gap: 8px;+ padding: 10px;+ background: var(--bg-tertiary);+ border: 1px solid var(--border-color);+ border-radius: 18px;+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.03);+ }++ .chat-prompt-shell::before {+ content: "";+ position: absolute;+ inset: -0.5rem;+ border-radius: 24px;+ background:+ linear-gradient(180deg, rgba(9, 31, 45, 0.82), rgba(11, 45, 57, 0.98)),+ radial-gradient(circle at 50% 0, rgba(231, 35, 116, 0.18), transparent 48%);+ opacity: 0;+ pointer-events: none;+ z-index: 0;+ transform: translateY(8px);+ transition: opacity 0.18s ease, transform 0.18s ease;+ }++ .chat-prompt-shell::after {+ content: "";+ position: absolute;+ left: 28px;+ right: 28px;+ bottom: calc(50% - 10px);+ height: 22px;+ opacity: 0;+ pointer-events: none;+ z-index: 1;+ background:+ repeating-linear-gradient(+ 90deg,+ transparent 0 6px,+ var(--alive-red-light) 6px 9px,+ transparent 9px 15px+ );+ mask-image: linear-gradient(+ 90deg,+ rgba(0, 0, 0, 0.15) 0%,+ #000 18%,+ #000 82%,+ rgba(0, 0, 0, 0.15) 100%+ );+ -webkit-mask-image: linear-gradient(+ 90deg,+ rgba(0, 0, 0, 0.15) 0%,+ #000 18%,+ #000 82%,+ rgba(0, 0, 0, 0.15) 100%+ );+ transform-origin: center;+ }++ .chat-prompt-shell > * {+ position: relative;+ z-index: 2;+ }++ .chat-prompt-shell.voice-ripple-active {+ isolation: isolate;+ background: transparent;+ border-color: rgba(231, 35, 116, 0.28);+ box-shadow: 0 -12px 36px rgba(4, 32, 45, 0.28);+ -webkit-touch-callout: none;+ -webkit-user-select: none;+ user-select: none;+ touch-action: none;+ }++ .chat-prompt-shell.voice-ripple-active::before {+ opacity: 1;+ transform: translateY(0);+ }++ .chat-prompt-shell.voice-ripple-active::after {+ opacity: 1;+ animation: voiceBars 0.82s ease-in-out infinite;+ }++ .video-card.fullscreen .fullscreen-prompt-overlay .chat-prompt-shell.voice-ripple-active::before {+ inset: -1rem -0.5rem -0.5rem;+ }++ @keyframes voiceBars {+ 0%, 100% { transform: scaleY(0.42); filter: brightness(0.9); }+ 35% { transform: scaleY(1); filter: brightness(1.18); }+ 68% { transform: scaleY(0.62); filter: brightness(1); }+ }++ .chat-prompt-shell:focus-within {+ border-color: rgba(231, 35, 116, 0.5);+ box-shadow: 0 0 0 3px rgba(231, 35, 116, 0.13);+ }++ .chat-prompt-action {+ width: 34px;+ height: 34px;+ border-radius: 50%;+ border: 1px solid var(--border-color);+ background: var(--card-bg);+ color: var(--text-secondary);+ display: inline-flex;+ align-items: center;+ justify-content: center;+ flex: 0 0 auto;+ cursor: pointer;+ transition: background 0.2s, border-color 0.2s, color 0.2s, transform 0.2s;+ }++ .chat-prompt-action:hover,+ .chat-prompt-action.active {+ background: var(--card-hover);+ border-color: var(--accent-color);+ color: var(--text-primary);+ transform: translateY(-1px);+ }++ .chat-prompt-action:disabled {+ cursor: not-allowed;+ opacity: 0.45;+ transform: none;+ box-shadow: none;+ }++ .chat-prompt-action .lucide {+ width: 17px;+ height: 17px;+ }++ .chat-prompt-action.send {+ background: linear-gradient(135deg, var(--alive-red-light), var(--alive-red) 58%, var(--alive-red-dark));+ border-color: rgba(255, 255, 255, 0.12);+ color: white;+ box-shadow: 0 8px 18px rgba(82, 24, 53, 0.28);+ }++ .chat-prompt-action.send:hover {+ background: linear-gradient(135deg, #f6539a, var(--alive-red) 54%, var(--alive-red-dark));+ border-color: rgba(255, 255, 255, 0.18);+ box-shadow: 0 10px 24px rgba(82, 24, 53, 0.36);+ }++ .chat-prompt-action.send .lucide {+ stroke: white;+ }++ .speech-label {+ display: none;+ font-size: 14px;+ font-weight: 600;+ line-height: 1;+ white-space: nowrap;+ }++ .voice-wave {+ display: none;+ align-items: center;+ justify-content: center;+ gap: 2px;+ width: 18px;+ height: 18px;+ }++ .voice-wave span {+ width: 3px;+ height: 6px;+ border-radius: 999px;+ background: currentColor;+ animation: voiceWave 0.72s ease-in-out infinite;+ }++ .voice-wave span:nth-child(2) {+ animation-delay: 0.12s;+ }++ .voice-wave span:nth-child(3) {+ animation-delay: 0.24s;+ }++ .voice-wave span:nth-child(4) {+ animation-delay: 0.36s;+ }++ @keyframes voiceWave {+ 0%, 100% {+ height: 5px;+ }+ 50% {+ height: 17px;+ }+ }++ .speech-control.recording {+ background: linear-gradient(135deg, var(--alive-red-light), var(--alive-red) 58%, var(--alive-red-dark));+ border-color: rgba(255, 255, 255, 0.14);+ color: white;+ box-shadow: 0 8px 18px rgba(82, 24, 53, 0.28);+ }++ .speech-control.recording .lucide {+ stroke: white;+ }++ .speech-control.recording .mic-icon {+ display: none;+ }++ .speech-control.recording .voice-wave {+ display: inline-flex;+ }++ .chat-prompt-action.speech:disabled {+ opacity: 0.65;+ transform: none;+ }++ .chat-prompt-input {+ flex: 1;+ min-height: 34px;+ max-height: 120px;+ padding: 7px 4px;+ resize: none;+ border: none !important;+ background: transparent !important;+ box-shadow: none !important;+ color: var(--text-primary);+ font-size: 14px;+ line-height: 1.45;+ }++ .chat-prompt-input:focus {+ outline: none;+ border: none !important;+ box-shadow: none !important;+ }++ .voice-mode-bar {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 10px;+ padding: 10px 0 4px;+ }+ .voice-mode-button {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ border: 1px solid var(--border-color);+ border-radius: 20px;+ padding: 9px 14px;+ background: var(--bg-secondary);+ color: var(--text-primary);+ font: inherit;+ font-size: 13px;+ cursor: pointer;+ }+ .voice-mode-button[aria-pressed="true"] {+ border-color: var(--accent-color);+ color: var(--accent-color);+ }+ .voice-mode-button:disabled { opacity: 0.5; cursor: default; }+ .voice-mode-button svg { width: 17px; height: 17px; }+ .voice-language-tabs { display: inline-flex; padding: 3px; gap: 2px; border: 1px solid var(--border-color); border-radius: 20px; background: var(--bg-secondary); }+ .voice-language-tab { min-width: 38px; min-height: 34px; padding: 5px 9px; border: 0; border-radius: 16px; background: transparent; color: var(--text-secondary); font: inherit; font-size: 13px; cursor: pointer; }+ .voice-language-tab[aria-checked="true"] { background: var(--bg-primary); color: var(--text-primary); box-shadow: 0 1px 4px #0002; font-weight: 600; }+ .voice-language-tab:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 2px; }+ .voice-mode-status { color: var(--text-secondary); font-size: 12px; }+ .fullscreen-prompt-overlay .voice-mode-bar {+ border-radius: 12px;+ background: var(--card-bg);+ padding: 8px 10px;+ }++ .prompt-popover {+ position: absolute;+ bottom: calc(100% + 8px);+ left: 0;+ right: auto;+ width: min(360px, calc(100vw - 40px));+ max-height: 320px;+ padding: 8px;+ overflow-y: auto;+ background: var(--card-bg);+ border: 1px solid var(--border-color);+ border-radius: 12px;+ box-shadow: 0 16px 38px rgba(0, 0, 0, 0.28);+ z-index: 30;+ }++ .prompt-popover.hidden {+ display: none;+ }++ .prompt-preset-option {+ width: 100%;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ padding: 9px 10px;+ border: none;+ border-radius: 8px;+ background: transparent;+ color: var(--text-primary);+ font: inherit;+ font-size: 13px;+ text-align: left;+ cursor: pointer;+ }++ .prompt-preset-copy {+ display: flex;+ flex-direction: column;+ gap: 8px;+ min-width: 0;+ }++ .prompt-preset-copy .primary {+ font-size: 15px;+ line-height: 1.35;+ color: var(--text-primary);+ }++ .prompt-preset-copy .secondary {+ font-size: 13px;+ line-height: 1.35;+ color: var(--text-secondary);+ }++ .prompt-preset-option:hover,+ .prompt-preset-option.selected {+ background: var(--hover-bg);+ }++ .prompt-preset-option .check {+ width: 16px;+ color: var(--accent-color);+ opacity: 0;+ flex: 0 0 auto;+ }++ .prompt-preset-option.selected .check {+ opacity: 1;+ }++ /* Embedded markdown toggle button */+ .markdown-toggle-embedded {+ position: absolute;+ top: -1px; /* Overlap balloon's top border */+ right: -1px; /* Overlap balloon's right border */+ background: var(--bg-secondary);+ border-top: 1px solid rgba(231, 35, 116, 0.24);+ border-right: 1px solid rgba(231, 35, 116, 0.24);+ border-left: 1px solid rgba(231, 35, 116, 0.24);+ border-bottom: 1px solid rgba(231, 35, 116, 0.24);+ border-radius: 0 16px 0 0; /* Match top-right corner of balloon */+ color: var(--text-secondary);+ padding: 4px 10px;+ font-size: 11px;+ cursor: pointer;+ display: flex;+ align-items: center;+ gap: 4px;+ transition: all 0.2s;+ z-index: 10;+ line-height: 1.2;+ }++ .markdown-toggle-embedded:hover {+ background: var(--bg-tertiary);+ color: var(--text-primary);+ }++ .markdown-toggle-embedded .lucide {+ width: 12px;+ height: 12px;+ }++ /* Copy to clipboard button - overlay style in lower right */+ .copy-button-embedded {+ position: absolute;+ bottom: 8px;+ right: 8px;+ background: rgba(255, 255, 255, 0.15);+ backdrop-filter: blur(8px);+ border: 1px solid rgba(255, 255, 255, 0.25);+ border-radius: 6px;+ color: var(--text-primary);+ padding: 6px 8px;+ cursor: pointer;+ display: flex;+ align-items: center;+ justify-content: center;+ transition: all 0.2s;+ z-index: 10;+ opacity: 0.4;+ }++ .copy-button-embedded:hover {+ opacity: 1;+ background: rgba(255, 255, 255, 0.25);+ border-color: rgba(255, 255, 255, 0.4);+ transform: scale(1.05);+ }++ .copy-button-embedded:active {+ transform: scale(0.95);+ }++ .copy-button-embedded .lucide {+ width: 14px;+ height: 14px;+ }++ .copy-button-embedded.copied {+ background: rgba(231, 35, 116, 0.58);+ border-color: rgba(231, 35, 116, 0.38);+ }++ .copy-button-embedded.copied .lucide {+ animation: checkmark 0.3s ease;+ }++ @keyframes checkmark {+ 0% { transform: scale(0.8); }+ 50% { transform: scale(1.2); }+ 100% { transform: scale(1); }+ }++ /* Markdown styling */+ .result-text-content.markdown-rendered h1,+ .result-text-content.markdown-rendered h2,+ .result-text-content.markdown-rendered h3,+ .result-text.markdown-rendered h1,+ .result-text.markdown-rendered h2,+ .result-text.markdown-rendered h3 {+ color: var(--text-primary);+ margin-top: 16px;+ margin-bottom: 8px;+ font-weight: 600;+ }++ .result-text-content.markdown-rendered h1,+ .result-text.markdown-rendered h1 {+ font-size: 1.5em;+ border-bottom: 2px solid var(--border-color);+ padding-bottom: 8px;+ }++ .result-text-content.markdown-rendered h2,+ .result-text.markdown-rendered h2 {+ font-size: 1.3em;+ }++ .result-text-content.markdown-rendered h3,+ .result-text.markdown-rendered h3 {+ font-size: 1.1em;+ }++ .result-text-content.markdown-rendered p,+ .result-text.markdown-rendered p {+ margin: 8px 0;+ }++ .result-text-content.markdown-rendered ul,+ .result-text-content.markdown-rendered ol,+ .result-text.markdown-rendered ul,+ .result-text.markdown-rendered ol {+ margin: 8px 0;+ padding-left: 24px;+ }++ .result-text-content.markdown-rendered li,+ .result-text.markdown-rendered li {+ margin: 4px 0;+ }++ .result-text-content.markdown-rendered code,+ .result-text.markdown-rendered code {+ background: var(--bg-tertiary);+ border: 1px solid var(--border-color);+ padding: 2px 6px;+ border-radius: 4px;+ font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;+ font-size: 0.9em;+ color: var(--accent-color);+ }++ .result-text-content.markdown-rendered pre,+ .result-text.markdown-rendered pre {+ background: var(--bg-secondary);+ border: 1px solid var(--border-color);+ border-radius: 8px;+ padding: 12px;+ overflow-x: auto;+ margin: 12px 0;+ }++ .result-text-content.markdown-rendered pre code,+ .result-text.markdown-rendered pre code {+ background: transparent;+ border: none;+ padding: 0;+ color: var(--text-primary);+ font-size: 0.85em;+ }++ .result-text-content.markdown-rendered blockquote,+ .result-text.markdown-rendered blockquote {+ border-left: 4px solid var(--accent-color);+ padding-left: 16px;+ margin: 12px 0;+ color: var(--text-secondary);+ font-style: italic;+ }++ .result-text-content.markdown-rendered table,+ .result-text.markdown-rendered table {+ border-collapse: collapse;+ width: 100%;+ margin: 12px 0;+ font-size: 0.9em;+ }++ .result-text-content.markdown-rendered table th,+ .result-text-content.markdown-rendered table td,+ .result-text.markdown-rendered table th,+ .result-text.markdown-rendered table td {+ border: 1px solid var(--border-color);+ padding: 8px 12px;+ text-align: left;+ }++ .result-text-content.markdown-rendered table th,+ .result-text.markdown-rendered table th {+ background: var(--bg-tertiary);+ font-weight: 600;+ color: var(--text-primary);+ }++ .result-text-content.markdown-rendered table tr:nth-child(even),+ .result-text.markdown-rendered table tr:nth-child(even) {+ background: var(--bg-secondary);+ }++ .result-text-content.markdown-rendered strong,+ .result-text.markdown-rendered strong {+ font-weight: 600;+ color: var(--text-primary);+ }++ .result-text-content.markdown-rendered em,+ .result-text.markdown-rendered em {+ font-style: italic;+ }++ .result-text-content.markdown-rendered a,+ .result-text.markdown-rendered a {+ color: var(--accent-color);+ text-decoration: none;+ }++ .result-text-content.markdown-rendered a:hover,+ .result-text.markdown-rendered a:hover {+ text-decoration: underline;+ }++ .result-text-content.markdown-rendered hr,+ .result-text.markdown-rendered hr {+ border: none;+ border-top: 1px solid var(--border-color);+ margin: 16px 0;+ }++ .result-text-content.markdown-rendered .katex,+ .result-text.markdown-rendered .katex {+ color: var(--text-primary);+ font-size: 1.02em;+ }++ .result-text-content.markdown-rendered .katex-display,+ .result-text.markdown-rendered .katex-display {+ overflow-x: auto;+ overflow-y: hidden;+ margin: 12px 0;+ padding: 4px 0;+ }++ .result-text-content.markdown-rendered .markdown-math-fallback,+ .result-text.markdown-rendered .markdown-math-fallback {+ color: var(--text-primary);+ font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;+ white-space: pre-wrap;+ }++ .result-text.fade {+ opacity: 0.4;+ }++ .vlm-history-shell.fade {+ opacity: 1;+ }++ .result-text.new-message {+ animation: popIn 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);+ }++ .result-text.new-message.with-glow {+ animation: popInWithGlow 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);+ }++ @keyframes popIn {+ 0% {+ transform: scale(0.95);+ opacity: 0.8;+ }+ 100% {+ transform: scale(1);+ opacity: 1;+ }+ }++ @keyframes popInWithGlow {+ 0% {+ transform: scale(0.95);+ opacity: 0.8;+ box-shadow: 0 0 0 0 rgba(231, 35, 116, 0.38);+ }+ 50% {+ box-shadow: 0 0 20px 4px rgba(231, 35, 116, 0.42);+ }+ 100% {+ transform: scale(1);+ opacity: 1;+ box-shadow: 0 0 0 0 rgba(231, 35, 116, 0);+ }+ }++ /* VLM Metrics */+ .metrics-inline {+ display: flex;+ gap: 16px;+ font-size: 12px;+ color: var(--text-secondary);+ flex: 0 0 auto;+ white-space: nowrap;+ }++ .result-header-metrics {+ display: flex;+ align-items: center;+ gap: 16px;+ flex: 0 0 auto;+ max-width: 100%;+ }++ .metric-item {+ display: flex;+ align-items: center;+ gap: 4px;+ flex: 0 0 auto;+ }++ .metric-value {+ font-weight: 600;+ color: var(--accent-color);+ }++ /* Info Box */+ .info-box {+ background: var(--card-bg);+ border: 1px solid var(--border-color);+ border-radius: 8px;+ padding: 16px;+ font-size: 13px;+ line-height: 1.6;+ color: var(--text-secondary);+ }++ .info-box h3 {+ font-size: 14px;+ font-weight: 600;+ color: var(--text-primary);+ margin-bottom: 10px;+ }++ .info-box ul {+ list-style-position: inside;+ padding-left: 0;+ }++ .info-box li {+ margin-bottom: 6px;+ }++ /* Scrollbar styling */+ ::-webkit-scrollbar {+ width: 8px;+ height: 8px;+ }++ ::-webkit-scrollbar-track {+ background: var(--bg-secondary);+ }++ ::-webkit-scrollbar-thumb {+ background: var(--bg-tertiary);+ border-radius: 4px;+ }++ ::-webkit-scrollbar-thumb:hover {+ background: var(--border-color);+ }++ /* Lucide icon styling */+ .lucide {+ width: 1em;+ height: 1em;+ vertical-align: middle;+ }++ .logo .lucide,+ .logo svg {+ width: 100%;+ height: 100%;+ filter: none;+ }++ /* Logo color - theme-aware (subtle glow on light background) */+ body.light-theme .logo .lucide,+ body.light-theme .logo svg {+ filter: none;+ }++ .icon-btn .lucide,+ .settings-btn .lucide,+ .video-control-btn .lucide {+ width: 16px;+ height: 16px;+ }++ .panel-icon .lucide {+ width: 18px;+ height: 18px;+ }++ .result-title .lucide {+ width: 20px;+ height: 20px;+ margin-right: 6px;+ }++ /* Default: Neutral icon colors (clean two-tone system) */+ .panel-icon svg,+ .panel-icon .lucide,+ .result-title svg,+ .result-title .lucide {+ stroke: var(--text-secondary) !important;+ }++ /* Colorful icon strokes (only when enabled) - Dark theme */+ body.colorful-focus .panel-icon:has([data-lucide="globe"]) svg,+ body.colorful-focus .panel-icon:has([data-lucide="globe"]) .lucide {+ stroke: rgb(34, 211, 238) !important; /* Softer cyan */+ }++ body.colorful-focus .panel-icon:has([data-lucide="video"]) svg,+ body.colorful-focus .panel-icon:has([data-lucide="video"]) .lucide {+ stroke: rgb(59, 130, 246) !important; /* Blue */+ }++ body.colorful-focus .panel-icon:has([data-lucide="edit-3"]) svg,+ body.colorful-focus .panel-icon:has([data-lucide="edit-3"]) .lucide {+ stroke: rgb(251, 191, 36) !important; /* Yellow/Orange */+ }++ body.colorful-focus .result-title:has([data-lucide="bot"]) svg,+ body.colorful-focus .result-title:has([data-lucide="bot"]) .lucide {+ stroke: rgb(168, 85, 247) !important; /* Purple */+ }+++ /* Colorful icon strokes - Light theme (darker variants) */+ body.light-theme.colorful-focus .panel-icon:has([data-lucide="globe"]) svg,+ body.light-theme.colorful-focus .panel-icon:has([data-lucide="globe"]) .lucide {+ stroke: rgb(6, 182, 212) !important; /* Darker cyan */+ }++ body.light-theme.colorful-focus .panel-icon:has([data-lucide="video"]) svg,+ body.light-theme.colorful-focus .panel-icon:has([data-lucide="video"]) .lucide {+ stroke: rgb(37, 99, 235) !important; /* Darker blue */+ }++ body.light-theme.colorful-focus .panel-icon:has([data-lucide="edit-3"]) svg,+ body.light-theme.colorful-focus .panel-icon:has([data-lucide="edit-3"]) .lucide {+ stroke: rgb(217, 119, 6) !important; /* Darker orange */+ }++ body.light-theme.colorful-focus .result-title:has([data-lucide="bot"]) svg,+ body.light-theme.colorful-focus .result-title:has([data-lucide="bot"]) .lucide {+ stroke: rgb(126, 34, 206) !important; /* Darker purple */+ }+++ /* Settings icon - theme-aware */+ .settings-btn .lucide {+ stroke: #ffffff;+ }+ body.light-theme .settings-btn .lucide {+ stroke: #ffffff;+ }++ /* Theme toggle icons - Yellow/Gold */+ #themeIcon .lucide {+ stroke: #ffffff;+ }+ body.light-theme #themeIcon .lucide {+ stroke: #ffffff;+ }++ /* Video control buttons - Teal */+ .video-control-btn .lucide {+ stroke: rgb(20, 184, 166);+ }+ body.light-theme .video-control-btn .lucide {+ stroke: rgb(13, 148, 136); /* Darker teal for light mode */+ }++ /* Action button icons (play, stop) - White for contrast on red button */+ .btn-primary .lucide {+ stroke: white !important;+ }+ body.light-theme .btn-primary .lucide {+ stroke: white !important;+ }++ .btn-secondary .lucide {+ stroke: var(--text-primary) !important;+ }++ /* Input fields - Focus and Apply animations */+ #promptText,+ #processEvery,+ #apiBaseUrl,+ #apiKey,+ #modelSelect,+ #cameraSelect,+ #rtspUrl {+ transition: all 0.3s ease;+ }++ /* Default: Neutral white focus glow (when colorful is disabled) */+ #promptText:focus,+ #processEvery:focus,+ #cameraSelect:focus,+ #apiBaseUrl:focus,+ #apiKey:focus,+ #modelSelect:focus,+ #rtspUrl:focus {+ border-color: rgba(200, 200, 200, 0.6) !important;+ box-shadow: 0 0 0 2px rgba(200, 200, 200, 0.15),+ 0 0 8px rgba(200, 200, 200, 0.2) !important;+ outline: none;+ }++ /* Colorful focus glows (only when enabled) */+ body.colorful-focus #promptText:focus {+ border-color: rgb(251, 191, 36) !important;+ box-shadow: 0 0 0 3px rgba(251, 191, 36, 0.3),+ 0 0 12px rgba(251, 191, 36, 0.4) !important;+ }++ body.colorful-focus #processEvery:focus,+ body.colorful-focus #cameraSelect:focus,+ body.colorful-focus #rtspUrl:focus {+ border-color: rgb(59, 130, 246) !important;+ box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.3),+ 0 0 12px rgba(59, 130, 246, 0.4) !important;+ }++ body.colorful-focus #apiBaseUrl:focus,+ body.colorful-focus #apiKey:focus,+ body.colorful-focus #modelSelect:focus {+ border-color: rgb(34, 211, 238) !important;+ box-shadow: 0 0 0 3px rgba(34, 211, 238, 0.25),+ 0 0 12px rgba(34, 211, 238, 0.3) !important;+ }++ /* Bright flash animation when applied (on blur) */+ @keyframes settingApplied {+ 0% {+ box-shadow: 0 0 0 0 rgba(231, 35, 116, 0.62),+ 0 0 20px rgba(231, 35, 116, 0.52);+ }+ 50% {+ box-shadow: 0 0 0 6px rgba(231, 35, 116, 0.24),+ 0 0 30px rgba(231, 35, 116, 0.38);+ }+ 100% {+ box-shadow: 0 0 0 0 rgba(231, 35, 116, 0),+ 0 0 0 rgba(231, 35, 116, 0);+ }+ }++ #promptText.applied,+ #processEvery.applied,+ #apiBaseUrl.applied,+ #apiKey.applied,+ #modelSelect.applied,+ #cameraSelect.applied,+ #rtspUrl.applied {+ animation: settingApplied 0.6s ease-out;+ }+++ /* ===== GRADIENT STROKES (Optional - gradients may not work reliably with Lucide) ===== */+ /*+ .panel-icon [data-lucide="globe"] svg {+ stroke: url(#gradient-cyan) !important;+ }++ .panel-icon [data-lucide="video"] svg {+ stroke: url(#gradient-blue) !important;+ }++ .panel-icon [data-lucide="edit-3"] svg {+ stroke: url(#gradient-orange) !important;+ }++ .result-title [data-lucide="bot"] svg {+ stroke: url(#gradient-purple) !important;+ }++ */++ /* Responsive Layout - Side by Side on Wide Screens */+ @media (min-width: 1400px) {+ .main-content {+ display: grid;+ grid-template-columns: 1fr 1fr;+ grid-template-rows: minmax(0, 1fr) auto;+ gap: 20px;+ align-items: start;+ max-height: calc(100vh - 100px);+ }++ /* Video card in left column */+ .video-card {+ grid-column: 1;+ grid-row: 1;+ margin-bottom: 0;+ align-self: stretch;+ max-height: 100%;+ }++ /* Responses card in right column */+ #vlmOutputCard {+ grid-column: 2;+ grid-row: 1;+ margin-bottom: 0;+ max-height: 100%;+ min-height: 0;+ overflow: hidden;+ align-self: stretch;+ display: flex;+ flex-direction: column;+ }++ #vlmOutputCard .vlm-history-shell {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ }++ #vlmOutputCard .vlm-history {+ flex: 1;+ min-height: 0;+ height: auto;+ max-height: none;+ }++ }++ @media (min-width: 1600px) {+ .main-content {+ grid-template-columns: 1.2fr 1fr;+ }+ }++ /* Responsive adjustments for smaller screens */+ @media (max-width: 1024px) {+ .sidebar {+ width: 280px;+ }++ .header-title {+ font-size: 18px;+ }+ }++ @media (max-width: 768px) {+ body {+ min-height: 100dvh;+ overflow-x: hidden;+ }++ .header {+ padding: 10px 12px;+ gap: 10px;+ }++ .header-left {+ min-width: 0;+ gap: 10px;+ }++ .logo {+ width: 38px;+ height: 38px;+ padding: 4px;+ border-radius: 10px;+ flex: 0 0 auto;+ }++ .title-section h1 {+ font-size: 18px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .header-right {+ gap: 8px;+ flex: 0 0 auto;+ }++ .status-badge {+ max-width: 104px;+ padding: 5px 8px;+ font-size: 10px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .theme-toggle {+ width: 34px;+ height: 34px;+ padding: 0;+ justify-content: center;+ }++ .theme-toggle #themeText {+ display: none;+ }++ .settings-btn {+ width: 34px;+ height: 34px;+ padding: 0;+ justify-content: center;+ }++ .settings-dialog {+ width: calc(100vw - 20px);+ max-height: calc(100dvh - 28px);+ border-radius: 10px;+ }++ .container {+ display: flex;+ flex-direction: column;+ height: auto;+ min-height: calc(100dvh - 59px);+ }++ .main-content {+ order: 1;+ width: 100%;+ height: calc(100dvh - 59px);+ min-height: calc(100dvh - 59px);+ padding: 10px;+ gap: 10px;+ overflow: visible;+ display: flex;+ flex-direction: column;+ }++ .video-card {+ order: 1;+ border-radius: 8px;+ margin-bottom: 0;+ min-height: 0;+ height: clamp(240px, 43dvh, 420px);+ flex: 0 0 auto;+ }++ .video-card video {+ min-height: 0;+ height: 100%;+ flex: 1 1 auto;+ }++ .video-controls {+ top: 54px !important;+ right: 8px;+ }++ .video-card.fullscreen .video-controls {+ top: 56px !important;+ right: 8px;+ }++ .video-control-btn {+ padding: 7px 9px;+ font-size: 12px;+ }++ .fullscreen-btn {+ top: 8px;+ right: 8px;+ width: 36px;+ height: 36px;+ opacity: 0.7;+ }++ .quick-camera-btn {+ display: inline-flex;+ top: 8px;+ right: 52px;+ height: 36px;+ min-width: 62px;+ padding: 0 8px;+ }++ .video-card.fullscreen .quick-camera-btn {+ display: inline-flex;+ top: 8px;+ right: 52px;+ height: 36px;+ min-width: 62px;+ padding: 0 8px;+ }++ .small-stop-btn {+ top: 10px;+ left: 10px;+ width: 42px;+ height: 42px;+ }++ .video-overlay {+ padding: 10px 12px;+ font-size: 13px;+ line-height: 1.45;+ }++ .result-card {+ order: 2;+ border-radius: 8px;+ padding: 12px;+ margin-bottom: 0;+ }++ #vlmOutputCard {+ min-height: 0;+ flex: 1 1 0;+ }++ #vlmOutputCard .result-header {+ margin-bottom: 8px;+ gap: 8px;+ }++ #vlmOutputCard .result-title {+ font-size: 12px;+ margin-bottom: 2px;+ }++ #vlmOutputCard .result-subtitle {+ font-size: 11px;+ }++ .metrics-inline {+ gap: 8px;+ font-size: 10px;+ flex-wrap: wrap;+ justify-content: flex-end;+ }++ .vlm-history-shell {+ flex: 1 1 auto;+ }++ .vlm-history {+ height: clamp(140px, 24dvh, 260px);+ max-height: clamp(140px, 24dvh, 260px);+ padding-top: 8px;+ padding-bottom: 18px;+ scrollbar-gutter: auto;+ }++ .result-prompt,+ .result-text {+ max-width: 94%;+ font-size: 14px;+ padding: 7px 10px;+ }++ .markdown-toggle-embedded {+ padding: 4px 8px;+ }++ .copy-button-embedded {+ bottom: 6px;+ right: 6px;+ }++ .prompt-editor-inline {+ position: sticky;+ bottom: 0;+ z-index: 40;+ margin: auto -12px -12px;+ padding: 8px 10px calc(8px + env(safe-area-inset-bottom));+ background: var(--card-bg);+ border-top: 1px solid var(--border-color);+ box-shadow: 0 -10px 24px rgba(0, 0, 0, 0.16);+ }++ .chat-prompt-shell {+ gap: 6px;+ padding: 8px;+ border-radius: 16px;+ }++ .chat-prompt-action {+ width: 50px;+ height: 50px;+ }++ .chat-prompt-action .lucide {+ width: 24px;+ height: 24px;+ }++ .voice-wave {+ width: 24px;+ height: 24px;+ gap: 3px;+ }++ .voice-wave span {+ width: 4px;+ }++ .voice-wave span {+ animation-name: voiceWaveMobile;+ }++ @keyframes voiceWaveMobile {+ 0%, 100% {+ height: 7px;+ }+ 50% {+ height: 24px;+ }+ }++ .chat-prompt-shell.mobile-voice-mode #promptPresetBtn,+ .chat-prompt-shell.mobile-voice-mode #promptSendBtn,+ .chat-prompt-shell.mobile-voice-mode .chat-prompt-input,+ .chat-prompt-shell.mobile-voice-mode .prompt-popover {+ display: none;+ }++ .chat-prompt-shell.mobile-voice-mode {+ min-height: 156px;+ align-items: center;+ justify-content: center;+ border-radius: 24px;+ }++ .chat-prompt-shell.mobile-voice-mode .chat-prompt-action.speech {+ position: absolute;+ left: 50%;+ top: 24px;+ width: auto;+ height: auto;+ min-height: 0;+ padding: 0;+ transform: translateX(-50%);+ border-radius: 999px;+ gap: 8px;+ border: none;+ background: transparent;+ box-shadow: none;+ color: rgba(255, 255, 255, 0.72);+ touch-action: none;+ user-select: none;+ -webkit-user-select: none;+ -webkit-touch-callout: none;+ }++ .chat-prompt-shell.mobile-voice-mode .chat-prompt-action.speech .speech-label {+ display: inline;+ font-size: 14px;+ font-weight: 500;+ letter-spacing: 0;+ }++ .chat-prompt-shell.mobile-voice-mode .chat-prompt-action.speech .voice-wave,+ .chat-prompt-shell.mobile-voice-mode .chat-prompt-action.speech .mic-icon {+ display: none;+ }++ .chat-prompt-shell.mobile-voice-mode::after {+ left: 18px;+ right: 18px;+ bottom: 44px;+ height: 28px;+ }++ .chat-prompt-input {+ min-width: 0;+ min-height: 54px;+ max-height: 144px;+ font-size: 15px;+ padding: 12px 2px;+ }++ .prompt-popover {+ width: calc(100vw - 20px);+ max-height: min(320px, 55dvh);+ left: -8px;+ }++ .sidebar {+ order: 2;+ width: 100%;+ flex: 0 0 auto;+ padding: 10px;+ border-right: none;+ border-top: 1px solid var(--border-color);+ overflow: visible;+ }++ .sidebar.docked {+ width: 100%;+ flex-basis: auto;+ padding: 8px 10px;+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 8px;+ }++ .sidebar .panel {+ margin-bottom: 10px;+ }++ .sidebar.docked .panel {+ margin-bottom: 0;+ }++ .sidebar.docked .panel-header {+ min-height: 44px;+ }++ .panel-content {+ padding: 12px;+ }++ .big-start-btn {+ width: min(96px, 24vw);+ height: min(96px, 24vw);+ font-size: 16px;+ }++ .big-start-btn i, .big-start-btn svg {+ width: min(40px, 8vh) !important;+ height: min(40px, 8vh) !important;+ }+ }++ @media (max-width: 420px) {+ .header {+ padding: 8px 10px;+ }++ .title-section h1 {+ font-size: 16px;+ }++ .status-badge {+ max-width: 86px;+ }++ .main-content {+ padding: 8px;+ }++ .video-card {+ height: clamp(220px, 40dvh, 360px);+ }++ .result-card {+ padding: 10px;+ }++ .prompt-editor-inline {+ margin: auto -10px -10px;+ padding-left: 8px;+ padding-right: 8px;+ }++ .chat-prompt-shell {+ gap: 5px;+ padding: 7px;+ }++ .chat-prompt-action {+ width: 48px;+ height: 48px;+ }++ .chat-prompt-shell.mobile-voice-mode .chat-prompt-action.speech {+ min-height: 0;+ }++ .chat-prompt-action .lucide {+ width: 23px;+ height: 23px;+ }+ }++ /* ALIVE header surfaces. */+ body, body.light-theme { background: var(--bg-primary); }+ .header {+ min-height: 74px;+ padding: 10px 24px;+ background: #fff;+ color: #20242a;+ border-bottom: 1px solid #e3e6e9;+ box-shadow: none;+ backdrop-filter: none;+ }+ .header-left { min-width: 0; gap: 24px; }+ .title-section { min-width: 0; }+ .title-section h1 { color: #20242a; font-size: 20px; font-weight: 650; }+ .title-section h1 span { color: #69727e; }+ .theme-toggle, .settings-btn {+ border-radius: 9px;+ color: #525a65;+ background: #fff;+ border-color: #e3e6e9;+ }+ .theme-toggle:hover, .settings-btn:hover { background: #f5f6f7; }+ .settings-btn .lucide, body.light-theme .settings-btn .lucide,+ #themeIcon .lucide, body.light-theme #themeIcon .lucide { stroke: currentColor; }+ .status-badge { border: 1px solid #e3e6e9; letter-spacing: 0.035em; }+ .status-badge::before {+ content: "";+ width: 6px; height: 6px; flex: 0 0 auto;+ border-radius: 50%; background: currentColor;+ }+ .status-badge.connected { color: #177245; background: #f4faf6; }+ .status-badge.disconnected { color: #69727e; background: #f7f8f9; }+ .status-badge.processing { color: #956015; background: #fffbf3; }+ .sidebar { background: var(--bg-secondary); }+ .main-content { gap: 18px; padding: 22px; }+ .panel, .settings-dialog { border-radius: 15px; }+ .sidebar.docked .panel { border-radius: 12px; }+ .panel-header { border-radius: 14px 14px 0 0; }+ .panel-title { font-weight: 650; }+ input[type="text"], input[type="number"], select, textarea {+ border-radius: 9px; min-height: 39px;+ }+ .btn, .icon-btn { border-radius: 9px; }+ .input-source-tabs { gap: 6px; border-bottom: 0; }+ .input-source-tab {+ margin: 0; border: 1px solid var(--border-color);+ border-radius: 9px; background: var(--bg-tertiary);+ }+ .input-source-tab.active { border-color: var(--accent-color); background: var(--alive-red-soft); }+ .video-card, .result-card {+ border-radius: 18px;+ border-color: var(--border-color);+ box-shadow: 0 4px 20px rgba(20, 30, 40, 0.045);+ }+ body.light-theme .video-card.waiting-for-stream { background: #f5f6f7; }+ .big-start-btn {+ background: #303640;+ border: 1px solid #444c58;+ box-shadow: 0 8px 24px rgba(20, 30, 40, 0.12);+ }+ .big-start-btn:hover:not(:disabled):not(.animating) {+ box-shadow: 0 12px 28px rgba(20, 30, 40, 0.18);+ }+ .result-title { color: var(--text-primary); font-weight: 650; }+ .result-prompt { background: var(--bg-tertiary); }+ .vlm-history .result-text, body.light-theme .vlm-history .result-text {+ background: var(--bg-secondary); border-color: var(--border-color);+ }+ .chat-prompt-shell { border-radius: 17px; }+ .chat-prompt-shell:focus-within {+ border-color: var(--text-muted); box-shadow: 0 0 0 3px rgba(110, 120, 132, 0.10);+ }+ .chat-prompt-action.send { background: #303640; box-shadow: none; }+ .chat-prompt-action.send:hover:not(:disabled) { background: #444c58; }+ :is(button, input, select, textarea, .logo):focus-visible {+ outline: 2px solid var(--accent-color); outline-offset: 3px;+ }+ @media (max-width: 768px) {+ .header { min-height: 60px; padding: 8px 12px; }+ .header-left { gap: 9px; }+ .title-section h1 span {+ max-width: 32ch; white-space: nowrap; overflow: hidden;+ text-overflow: ellipsis; font-size: 10px;+ }+ .main-content { padding: 10px; gap: 10px; }+ .video-card, .result-card { border-radius: 12px; }+ }+ @media (max-width: 420px) {+ .title-section h1 { font-size: 17px; }+ .title-section h1 span { display: none; }+ }+ /* ALIVE wordmark and voice controls. */+ .logo { flex: 0 0 auto; width: 148px; height: 48px; padding: 0; border-radius: 0; background: transparent; box-shadow: none; }+ .logo img { display: block; width: 100%; height: 100%; object-fit: contain; }+ #speechBtn, .quick-camera-btn[hidden] { display: none !important; }+ .voice-mode-bar { padding: 10px 0 0; gap: 8px; }+ .voice-mode-button { min-height: 44px; padding: 10px 13px; }+ .voice-mode-button[aria-pressed="true"] { background: var(--alive-red-soft); }+ .voice-toggle-icon { display: inline-flex; }+ .voice-toggle-icon svg { width: 19px; height: 19px; }+ .voice-mode-status { flex: 1; min-width: 120px; }+ @media (max-width: 768px) {+ .header { display: grid; grid-template-columns: 1fr auto; gap: 8px 12px; }+ .header-left { display: contents; }+ .logo { grid-column: 1; grid-row: 1; width: 120px; height: 40px; padding: 0; }+ .header-right { grid-column: 2; grid-row: 1; }+ .title-section { grid-column: 1 / -1; grid-row: 2; }+ .title-section h1 { font-size: 18px; }+ .title-section h1 span { display: none; }+ .voice-mode-status { flex-basis: 100%; font-size: 11px; }+ }++ /* ALIVE workspace: independent branding, responsive video + conversation. */+ :root { --alive-red:#a8cd18; --alive-red-dark:#86a510; --alive-red-light:#c7e75c;+ --alive-red-soft:rgba(168,205,24,.12); --alive-red-ring:rgba(168,205,24,.24);+ --alive-red-shadow:rgba(6,36,70,.15); --accent-color:#b5d944; --accent-hover:#d4ed88;+ --bg-primary:#101d2e; --bg-secondary:#14253a; --bg-tertiary:#20344b;+ --card-bg:#14253a; --border-color:#2b415a; --text-primary:#edf3f9; --text-secondary:#bbc8d6; --text-muted:#92a7bb; }+ body.light-theme { --bg-primary:#f5f6f2; --bg-secondary:#f8f9f6; --bg-tertiary:#edf0e8;+ --card-bg:#fff; --card-hover:#eef2e7; --border-color:#e0e5da;+ --text-primary:#102d50; --text-secondary:#53665f; --text-muted:#7a8784;+ --accent-color:#17486c; --accent-hover:#092b50; }+ body { font-family:Inter,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif; }+ .header { min-height:82px; padding:12px 36px; background:var(--card-bg); color:var(--text-primary); border-color:var(--border-color); }+ .header-left { gap:26px; }+ .logo { width:156px; height:52px; background:#fff; border-radius:9px; }+ .title-section { border-left:1px solid var(--border-color); padding-left:24px; }+ .title-section h1 { color:var(--text-primary); font-size:14px; letter-spacing:.01em; font-weight:600; }+ .title-section h1 span { color:var(--text-muted); font-size:11px; margin-top:4px; }+ .theme-toggle,.settings-btn { background:var(--bg-secondary); color:var(--text-secondary); border-color:var(--border-color); height:36px; }+ .status-badge { font-size:10px; padding:8px 11px; letter-spacing:.08em; }+ .status-badge.connected { background:#eef5d7; color:#507009; border-color:#dce9b5; }+ .alive-intro { max-width:1700px; margin:auto; padding:32px 36px 26px; display:flex; justify-content:space-between; align-items:center; gap:24px; }+ .alive-eyebrow { font-size:10px; letter-spacing:.16em; font-weight:700; color:var(--text-muted); display:flex; align-items:center; gap:8px; }+ .alive-eyebrow span { background:#a8cd18; width:7px; height:7px; border-radius:50%; }+ .alive-intro h2 { font-size:clamp(26px,2.6vw,38px); line-height:1.15; letter-spacing:-.045em; font-weight:600; margin:11px 0 10px; }+ .alive-intro p { color:var(--text-secondary); font-size:13px; line-height:1.6; }+ .alive-session-chip { display:flex; align-items:center; gap:12px; border:1px solid var(--border-color); padding:13px 18px; border-radius:14px; background:var(--card-bg); }+ .alive-spark { font-size:32px; color:#8eaf12; }+ .alive-session-chip strong { display:block; font-size:12px; letter-spacing:.08em; }+ .alive-session-chip div span { display:block; font-size:11px; color:var(--text-muted); margin-top:5px; }+ .container { max-width:1700px; margin:0 auto; padding:16px 24px 24px; height:calc(100dvh - 82px); min-height:500px; gap:12px; }+ .sidebar { border:1px solid var(--border-color); border-radius:18px; background:var(--card-bg); }+ .sidebar.docked { width:52px; flex-basis:52px; padding:12px 6px; }+ .sidebar.docked .panel { background:var(--bg-secondary); border-color:transparent; }+ .main-content { min-width:0; padding:0; display:grid; grid-template-columns:minmax(0,1.4fr) minmax(350px,1fr); grid-template-rows:minmax(0,1fr); gap:20px; overflow:visible; }+ .video-card,.result-card { border-radius:22px; margin:0; box-shadow:0 8px 24px rgba(17,41,36,.035); }+ .video-card:not(.fullscreen) { height:100%; min-height:360px; width:100%; background:#10283f; border:1px solid #203d57; }+ body.light-theme .video-card.waiting-for-stream { background:#10283f; }+ .video-card video { width:100%; height:100%; object-fit:contain; }+ .alive-view-label { position:absolute; top:22px; left:22px; color:#d5e3e9; z-index:4; font-size:10px; font-weight:600; letter-spacing:.15em; display:flex; align-items:center; gap:7px; pointer-events:none; }+ .alive-view-label span { width:6px; height:6px; background:#a8cd18; border-radius:50%; }+ .alive-camera-note { position:absolute; left:20px; right:20px; top:29%; text-align:center; color:#fff; font-size:clamp(17px,1.5vw,24px); letter-spacing:-.025em; pointer-events:none; z-index:3; }+ .alive-camera-note small { display:block; margin-top:10px; color:#9cb0c2; font-size:12px; letter-spacing:0; }+ .video-card:has(.big-start-btn.streaming) .alive-camera-note,.video-card:has(.big-start-btn.animating) .alive-camera-note { display:none; }+ .big-start-btn { border-radius:40px; background:#b5d933; border:1px solid #b5d933; color:#193218; font-size:14px; padding:17px 27px; gap:9px; box-shadow:0 5px 22px #0002; }+ .big-start-btn:hover:not(:disabled):not(.animating) { background:#c5e658; box-shadow:0 8px 28px #0003; }+ .big-start-btn i,.big-start-btn svg { width:19px; height:19px; }+ .result-card { padding:24px; min-width:0; }+ .result-title { font-size:17px; color:var(--text-primary); letter-spacing:-.02em; }+ .result-subtitle { font-size:11px; margin-top:6px; color:var(--text-muted); }+ #resultText { background:transparent; border:0; margin-top:18px; }+ #resultTextContent:empty::before { content:'A conversation starts with a shared view. Open your camera, then ask ALIVE a question — or tell it what to watch for.'; display:block; max-width:29ch; margin:48px auto; text-align:center; color:var(--text-muted); font-size:14px; line-height:1.85; }+ .vlm-history .result-text,body.light-theme .vlm-history .result-text { border-radius:14px; background:var(--bg-secondary); }+ .prompt-editor-inline { margin:auto -24px -24px; padding:16px; border-top:1px solid var(--border-color); background:var(--card-bg); border-radius:0 0 22px 22px; }+ .chat-prompt-shell { border-radius:16px; background:var(--bg-secondary); border-color:var(--border-color); }+ .chat-prompt-shell:focus-within { border-color:#99b851; box-shadow:0 0 0 3px rgba(168,205,24,.13); }+ .chat-prompt-action.send { background:#102f55; color:white; border-radius:12px; }+ .chat-prompt-action.send:hover:not(:disabled) { background:#204b78; }+ .voice-mode-bar { flex-wrap:wrap; }+ .voice-mode-button { font-size:11px; min-height:34px; padding:7px 9px; border-radius:9px; }+ .voice-mode-status { font-size:10px; color:var(--text-muted); }+ .fullscreen .alive-view-label { display:none; }+ @media (max-width:1100px) and (min-width:769px) { .main-content { grid-template-columns:minmax(0,1fr) minmax(320px,1fr); gap:14px; } .alive-session-chip { display:none; } }+ @media (max-width:768px) {+ .header { display:flex; min-height:66px; padding:9px 16px; gap:8px; }+ .header-left { display:flex; gap:0; } .logo { width:126px; height:42px; } .title-section { display:none; }+ .header-right { display:flex; gap:6px; } .theme-toggle { padding:7px; } #themeText { display:none; }+ .status-badge { font-size:8px; padding:7px; } .alive-intro { padding:22px 18px 20px; }+ .alive-intro h2 { font-size:29px; } .alive-intro p { font-size:12px; max-width:34ch; } .alive-eyebrow { font-size:8px; }+ .alive-session-chip { display:none; } .container { height:auto; min-height:0; padding:0 12px 20px; display:flex; flex-direction:column; gap:10px; }+ .sidebar.docked { width:100%; flex:0 0 auto; height:46px; padding:4px 7px; border-radius:12px; }+ .main-content { display:flex; flex-direction:column; padding:0; gap:12px; overflow:visible; }+ .video-card:not(.fullscreen) { height:clamp(260px,43dvh,420px); min-height:260px; border-radius:18px; }+ .alive-camera-note { top:26%; font-size:18px; } .big-start-btn { padding:14px 23px; }+ #vlmOutputCard { min-height:420px; flex:0 0 auto; padding:18px; border-radius:18px; }+ .prompt-editor-inline { margin:auto -18px -18px; padding:12px; border-radius:0 0 18px 18px; }+ .voice-mode-status { flex-basis:100%; } .alive-view-label { top:17px; left:17px; }+ }+ @media (prefers-reduced-motion:reduce) { *,*::before,*::after { animation-duration:.01ms!important; transition-duration:.01ms!important; } }+++ #bigStartBtn:not(.streaming):not(.animating) { width:auto; height:auto; min-width:166px; min-height:52px; flex-direction:row; border-radius:40px; font-size:14px; padding:15px 24px; }+ #bigStartBtn:not(.streaming):not(.animating) svg { width:20px; height:20px; }+ .video-card:has(#bigStartBtn:not(.streaming):not(.animating)) video { background:transparent; }+ #resultTextContent:has(> .alive-empty) { display:flex; align-items:center; justify-content:center; }+ .alive-empty { max-width:30ch; color:var(--text-muted); text-align:center; font-size:14px; line-height:1.85; padding:25px 10px; }+ @media (max-width:768px) {+ .main-content { height:auto; min-height:0; }+ #vlmOutputCard { min-height:440px; }+ #vlmOutputCard .result-title { font-size:17px; }+ .alive-camera-note { top:23%; }+ #bigStartBtn:not(.streaming):not(.animating) { top:59%; }+ .prompt-editor-inline { position:static!important; bottom:auto; box-shadow:none; }+ #resultText { min-height:180px; flex:1; }+ }+++ /* Compact workspace: the viewport is devoted to camera and conversation. */+ .conversation-brand { display:block; width:126px; height:42px; object-fit:contain; background:#fff; border-radius:6px; }+ #modelName[hidden] { display:none!important; }+ @media (max-width:768px) {+ .container { padding-top:12px; }+ .conversation-brand { width:114px; height:38px; }+ }+++ /* Icon-only ALIVE brand mark, cropped from the original logo. */+ .alive-mark {+ display: inline-block;+ width: 24px;+ height: 24px;+ flex: 0 0 auto;+ overflow: hidden;+ background: #fff;+ border-radius: 4px;+ vertical-align: middle;+ }+ .background-summary-label .alive-mark {+ width: 18px !important;+ height: 18px !important;+ }+ .background-result-icon .alive-mark {+ width: 22px;+ height: 22px;+ }+++ /* Demo production palette: film/src/FilmV8.tsx. */+ body {+ font-family: "Helvetica Neue", "PingFang SC", -apple-system, sans-serif;+ }+ body.light-theme {+ --bg-primary: #EDF2F7;+ --bg-secondary: #F5F8FC;+ --bg-tertiary: #EDF3FB;+ --card-bg: #FFFFFF;+ --card-hover: #EAF3FF;+ --border-color: #E0E7EF;+ --text-primary: #092B57;+ --text-secondary: #617287;+ --text-muted: #617287;+ --accent-color: #092B57;+ --accent-hover: #173F71;+ --alive-red-soft: rgba(9,43,87,.07);+ --alive-red-ring: rgba(9,43,87,.18);+ }+ body.light-theme .header { background: #EDF2F7; }+ body.light-theme .logo { background: transparent; }+ body.light-theme .logo img { mix-blend-mode: multiply; }+ body.light-theme .video-card,+ body.light-theme .video-card.waiting-for-stream {+ background: #081321;+ border-color: #173454;+ box-shadow: 0 18px 45px #17345416;+ }+ body.light-theme .result-card {+ background: #FFFFFF;+ border-color: #E0E7EF;+ box-shadow: 0 18px 45px #1734540A;+ }+ body.light-theme .result-prompt {+ background: #EAF3FF;+ color: #092B57;+ border-color: #99BCE6;+ }+ body.light-theme .vlm-history > .result-text:not(.background-result):not(.background-summary-message) {+ background: #092B57;+ color: #FFFFFF;+ border-color: #173F71;+ --text-primary: #FFFFFF;+ --text-secondary: #DCE8F6;+ --text-muted: #CBD7E5;+ --accent-color: #B7D6FA;+ --bg-tertiary: #173F71;+ --border-color: #456387;+ }+ body.light-theme .chat-prompt-shell:focus-within {+ border-color: #99BCE6;+ box-shadow: 0 0 0 3px #6A95C522;+ }+ body.light-theme .chat-prompt-action.send { background: #092B57; }+ body.light-theme .chat-prompt-action.send:hover:not(:disabled) { background: #173F71; }+ body.light-theme .theme-toggle:hover,+ body.light-theme .settings-btn:hover { background: #EAF3FF; }+ body.light-theme .voice-mode-button[aria-pressed="true"],+ body.light-theme .input-source-tab.active {+ background: #EAF3FF;+ border-color: #99BCE6;+ color: #092B57;+ }+ body.light-theme .status-badge.disconnected {+ background: #F5F8FC; color: #617287; border-color: #E0E7EF;+ }+ body.light-theme .alive-mark { mix-blend-mode: multiply; }++ /* UI language and per-browser TTS voice selection. */+.ui-language-control { display:inline-flex; align-items:center; padding:3px; border:1px solid var(--border-color); border-radius:10px; background:var(--bg-secondary); flex-shrink:0; }+.ui-language-control button { border:0; background:transparent; color:var(--text-secondary); padding:5px 8px; min-height:28px; border-radius:7px; cursor:pointer; font:600 11px "Helvetica Neue","PingFang SC",sans-serif; }+.ui-language-control button[aria-pressed="true"] { background:var(--card-bg); color:var(--text-primary); box-shadow:0 1px 4px #092B5718; }+.tts-voice-control { display:inline-flex; align-items:center; gap:6px; color:var(--text-secondary); font-size:11px; margin:0; }+.tts-voice-control select { min-height:34px; width:112px; padding:6px 8px; border:1px solid var(--border-color); border-radius:9px; background:var(--bg-secondary); color:var(--text-primary); font-size:11px; cursor:pointer; }+.tts-voice-control select:disabled { opacity:.6; cursor:wait; }+html[lang="zh-CN"] .status-badge { letter-spacing:0; }+@media(max-width:768px) {+ .header { flex-wrap:wrap; }+ .header-right { flex-wrap:wrap; justify-content:flex-end; }+ .ui-language-control button { padding:4px 6px; }+ .header .logo { width:105px; height:35px; }+ .voice-mode-status { flex-basis:100%; }+}+@media(max-width:360px) { .header { padding-left:12px; padding-right:12px; } .header .logo { width:90px; } .header-right { gap:4px; } .ui-language-control button { padding:4px; } }++.admission-status { font-size:10px; font-weight:600; color:#507009; background:#eef5d7; border:1px solid #dce9b5; border-radius:999px; padding:8px 10px; white-space:nowrap; }+.admission-status[data-busy="true"] { color:#895818; background:#fff4df; border-color:#ead4ad; }+@media(max-width:768px) { .admission-status { font-size:9px; padding:6px 8px; } .header-right { max-width:100%; } }++</style>++ <!-- SVG Gradient Definitions (for gradient strokes) -->+ <svg width="0" height="0" style="position: absolute;">+ <defs>+ <!-- Cyan gradient -->+ <linearGradient id="gradient-cyan" x1="0%" y1="0%" x2="100%" y2="100%">+ <stop offset="0%" style="stop-color:rgb(34, 211, 238);stop-opacity:1" />+ <stop offset="100%" style="stop-color:rgb(6, 182, 212);stop-opacity:1" />+ </linearGradient>++ <!-- Blue gradient -->+ <linearGradient id="gradient-blue" x1="0%" y1="0%" x2="100%" y2="100%">+ <stop offset="0%" style="stop-color:rgb(96, 165, 250);stop-opacity:1" />+ <stop offset="100%" style="stop-color:rgb(59, 130, 246);stop-opacity:1" />+ </linearGradient>++ <!-- Orange/Yellow gradient -->+ <linearGradient id="gradient-orange" x1="0%" y1="0%" x2="100%" y2="100%">+ <stop offset="0%" style="stop-color:rgb(251, 191, 36);stop-opacity:1" />+ <stop offset="100%" style="stop-color:rgb(245, 158, 11);stop-opacity:1" />+ </linearGradient>++ <!-- Purple gradient -->+ <linearGradient id="gradient-purple" x1="0%" y1="0%" x2="100%" y2="100%">+ <stop offset="0%" style="stop-color:rgb(192, 132, 252);stop-opacity:1" />+ <stop offset="100%" style="stop-color:rgb(168, 85, 247);stop-opacity:1" />+ </linearGradient>++ <!-- alive brand gradient -->+ <linearGradient id="gradient-green" x1="0%" y1="0%" x2="100%" y2="100%">+ <stop offset="0%" style="stop-color:rgb(255, 143, 190);stop-opacity:1" />+ <stop offset="100%" style="stop-color:rgb(213, 27, 105);stop-opacity:1" />+ </linearGradient>+ </defs>+ </svg>++ <!-- Lucide Icons - Load before body scripts -->+ <script src="https://unpkg.com/lucide@latest"></script>+ <!-- Markdown rendering libraries -->+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css">+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js"></script>+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/marked.min.js"></script>+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/purify.min.js"></script>+ <script>+ const demoStorage = {+ getItem: key => localStorage.getItem('alive-demo:' + key),+ setItem: (key, value) => localStorage.setItem('alive-demo:' + key, value),+ removeItem: key => localStorage.removeItem('alive-demo:' + key)+ };++ document.title = 'ALIVE';++ // Initialize Lucide icons immediately when DOM is ready+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', () => lucide.createIcons());+ } else {+ lucide.createIcons();+ }+ </script>+</head>+<body class="light-theme">+ <!-- Header -->+ <div class="header">+ <div class="header-left">+ <div class="logo" id="jdLogo" role="button" tabindex="0" aria-label="Refresh page">+ <img src="/images/alive.png?v=1" alt="ALIVE" width="2048" height="683">+ </div>+ </div>+ <div class="header-right">+ <span class="status-badge disconnected" id="connectionStatus">Disconnected</span>+ <button class="settings-btn" id="settingsBtn" title="Settings">+ <i data-lucide="settings"></i>+ </button>+ <button class="theme-toggle" id="themeToggle">+ <span id="themeIcon">+ <i data-lucide="moon"></i>+ </span>+ <span id="themeText">Dark</span>+ </button>+ </div>+ </div>++ <!-- Settings Modal -->+ <div class="settings-modal" id="settingsModal">+ <div class="settings-dialog">+ <div class="settings-header">+ <div class="settings-title">+ <i data-lucide="settings"></i> Settings+ </div>+ <button class="settings-close" id="settingsClose">×</button>+ </div>+ <div class="settings-body">+ <!-- Column 1: Layout & Visual Effects -->+ <div>+ <div class="settings-section">+ <div class="settings-section-title">Layout</div>++ <div class="settings-item">+ <div>+ <div class="settings-item-label">Main Content Order</div>+ <div class="settings-item-description">Choose which element appears at the top</div>+ </div>+ <select id="layoutOrder" class="settings-select">+ <option value="video-first">Camera → Conversation</option>+ <option value="vlm-first" selected>Conversation → Camera</option>+ </select>+ </div>++ <div class="settings-item">+ <div>+ <div class="settings-item-label">Responses on Camera View</div>+ <div class="settings-item-description">Show text overlay directly on video feed</div>+ </div>+ <select id="overlayPosition" class="settings-select">+ <option value="none">None</option>+ <option value="top">At the top</option>+ <option value="bottom">At the bottom</option>+ </select>+ </div>+ </div>++ <div class="settings-section">+ <div class="settings-section-title">Visual Effects</div>++ <div class="settings-item">+ <div>+ <div class="settings-item-label">Pop-in Animation</div>+ <div class="settings-item-description">Scale animation when new VLM response arrives</div>+ </div>+ <label class="toggle-switch">+ <input type="checkbox" id="popInToggle" checked>+ <span class="toggle-slider"></span>+ </label>+ </div>++ <div class="settings-item">+ <div>+ <div class="settings-item-label">Green Glow Effect</div>+ <div class="settings-item-description">Border glow on new VLM response</div>+ </div>+ <label class="toggle-switch">+ <input type="checkbox" id="glowToggle" checked>+ <span class="toggle-slider"></span>+ </label>+ </div>++ <div class="settings-item">+ <div>+ <div class="settings-item-label">Fade Effect</div>+ <div class="settings-item-description">Gradually fade response after 2 seconds</div>+ </div>+ <label class="toggle-switch">+ <input type="checkbox" id="fadeToggle" checked>+ <span class="toggle-slider"></span>+ </label>+ </div>+ </div>+ </div>++ <!-- Column 2: Input Colors & WebRTC -->+ <div>+ <div class="settings-section">+ <div class="settings-section-title">Visual Style</div>++ <div class="settings-item">+ <div>+ <div class="settings-item-label">Colorful UI Accents</div>+ <div class="settings-item-description">Color-coded icons and input focus glows</div>+ </div>+ <label class="toggle-switch">+ <input type="checkbox" id="colorfulFocusToggle">+ <span class="toggle-slider"></span>+ </label>+ </div>+ </div>++ <div class="settings-section">+ <div class="settings-section-title">WebRTC</div>++ <div class="settings-item">+ <div style="flex: 1; min-width: 0;">+ <div class="settings-item-label">Max Video Latency (seconds)</div>+ <div class="settings-item-description">Drop old frames if delay exceeds this (0 = no intervention)</div>+ </div>+ <input type="number" id="maxLatency" value="0" min="0" max="10.0" step="0.1" style="width: 80px; padding: 6px 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--bg-primary); color: var(--text-primary); font-size: 14px;">+ </div>+ </div>++ <div class="settings-section">+ <div class="settings-section-title">Voice</div>++ <div class="settings-item-description">Use Auto / 中 / 英 below the message box to switch both speech input and output. Auto detects your speech language and reads replies in their original language.</div>+ <div class="settings-item">+ <div>+ <label class="settings-item-label" for="fullDuplexToggle">Full duplex (experimental)</label>+ <div id="fullDuplexDescription" class="settings-item-description">Keep listening while replies play; speak to interrupt. Off on every page load. Turn on Mic and Sound below. Headphones recommended; if speaker echo triggers interruptions, turn this off.</div>+ </div>+ <label class="toggle-switch">+ <input type="checkbox" id="fullDuplexToggle" aria-describedby="fullDuplexDescription">+ <span class="toggle-slider"></span>+ </label>+ </div>+ <div id="voiceStatus" class="settings-item-description" role="status">Checking voice service…</div>++ <div class="settings-item">+ <div>+ <div class="settings-item-label">Speak replies</div>+ <div class="settings-item-description">Off by default. Read replies in English or Chinese when enabled</div>+ </div>+ <label class="toggle-switch">+ <input type="checkbox" id="ttsEnabledToggle">+ <span class="toggle-slider"></span>+ </label>+ </div>+ </div>++ <div class="settings-section">+ <div class="settings-section-title">Background Model</div>++ <div class="settings-item">+ <div>+ <div class="settings-item-label">Enable delegation solver</div>+ <div class="settings-item-description">Use ALIVE for delegated questions, visual reasoning, and chart tasks in the background</div>+ </div>+ <label class="toggle-switch">+ <input type="checkbox" id="backgroundEnabledToggle" checked>+ <span class="toggle-slider"></span>+ </label>+ </div>++ <div class="settings-item">+ <div style="flex: 1; min-width: 0;">+ <div class="settings-item-label">Frame multiplier</div>+ <div class="settings-item-description">Background frames per second relative to foreground streaming FPS</div>+ </div>+ <input type="number" id="backgroundFrameMultiplier" value="2" min="1" max="10" step="1" style="width: 80px; padding: 6px 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--bg-primary); color: var(--text-primary); font-size: 14px;">+ </div>++ <div class="settings-item">+ <div style="flex: 1; min-width: 0;">+ <div class="settings-item-label">Max background frames</div>+ <div class="settings-item-description">Recent background frame cache cap; default and maximum are 100</div>+ </div>+ <input type="number" id="backgroundMaxFrames" value="100" min="1" max="100" step="1" style="width: 80px; padding: 6px 8px; border: 1px solid var(--border-color); border-radius: 4px; background: var(--bg-primary); color: var(--text-primary); font-size: 14px;">+ </div>+ </div>++ <div class="settings-section">+ <div class="settings-section-title">Debug</div>++ <div class="settings-item">+ <div>+ <div class="settings-item-label">Show request payload</div>+ <div class="settings-item-description">Include request JSON (image + prompt) under the prompt area; collapsed by default</div>+ </div>+ <label class="toggle-switch">+ <input type="checkbox" id="debugShowRequestPayload">+ <span class="toggle-slider"></span>+ </label>+ </div>++ <div class="settings-item">+ <div>+ <div class="settings-item-label">Show response payload</div>+ <div class="settings-item-description">Include API response JSON under the VLM output; collapsed by default</div>+ </div>+ <label class="toggle-switch">+ <input type="checkbox" id="debugShowResponsePayload">+ <span class="toggle-slider"></span>+ </label>+ </div>++ <div class="settings-item">+ <div>+ <div class="settings-item-label">Show memory state</div>+ <div class="settings-item-description">Display mid-term and long-term memory content below VLM output</div>+ </div>+ <label class="toggle-switch">+ <input type="checkbox" id="debugShowMemoryState">+ <span class="toggle-slider"></span>+ </label>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>++<div class="container">+ <!-- Left Sidebar -->+ <div class="sidebar docked" id="sidebar">+ <!-- Internal API controls retained for server configuration only. -->+ <div class="panel" style="display: none;">+ <div class="panel-header" onclick="togglePanel('vlmConfig')">+ <div class="panel-title">+ <span class="panel-icon">+ <i data-lucide="globe"></i>+ </span>+ <span class="panel-title-text">VLM API Configuration</span>+ </div>+ <span class="panel-toggle collapsed" id="vlmConfigToggle">▼</span>+ </div>+ <div class="panel-content collapsed" id="vlmConfig">+ <div class="form-group">+ <div style="display: flex; align-items: center; gap: 4px; margin-bottom: 8px;">+ <label style="margin-bottom: 0; flex: 1;">API Base URL</label>+ <div style="display: none; position: relative;">+ <button class="icon-btn" id="apiPresetsBtn" title="Select preset API endpoint">+ <i data-lucide="clipboard"></i>+ </button>+ <div id="apiPresetsMenu" style="display: none; position: absolute; right: 0; top: 100%; margin-top: 4px; background: var(--card-bg); border: 1px solid var(--border-color); border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); min-width: 280px; z-index: 9999;">+ <div style="padding: 8px 0;">+ <div class="api-preset-item" data-url="http://localhost:11434/v1">+ <strong>Ollama</strong><br>+ <span style="font-size: 11px; color: var(--text-muted);">http://localhost:11434/v1</span>+ </div>+ <div class="api-preset-item" data-url="http://localhost:8000/v1">+ <strong>vLLM</strong><br>+ <span style="font-size: 11px; color: var(--text-muted);">http://localhost:8000/v1</span>+ </div>+ <div class="api-preset-item" data-url="http://localhost:30000/v1">+ <strong>SGLang</strong><br>+ <span style="font-size: 11px; color: var(--text-muted);">http://localhost:30000/v1</span>+ </div>+ <div style="border-top: 1px solid var(--border-color); margin: 4px 0;"></div>+ <div class="api-preset-item" data-url="https://api.openai.com/v1">+ <strong>OpenAI</strong><br>+ <span style="font-size: 11px; color: var(--text-muted);">https://api.openai.com/v1</span>+ </div>+ </div>+ </div>+ </div>+ </div>+ <input type="text" id="apiBaseUrl" value="http://127.0.0.1:8070/v1" placeholder="http://localhost:8000/v1">+ <div class="input-hint" id="apiBaseHint">Current VLM endpoint</div>+ </div>+ <div class="form-group" id="apiKeyGroup">+ <div style="display: flex; align-items: center; cursor: pointer; margin-bottom: 8px;" onclick="toggleApiKeyField()">+ <label style="margin-bottom: 0; flex: 1;">API Key (Optional)</label>+ <span id="apiKeyToggle" style="font-size: 12px; color: var(--text-secondary);">▼</span>+ </div>+ <div id="apiKeyField">+ <input type="text" id="apiKey" placeholder="sk-..." autocomplete="off">+ <div class="input-hint">Leave empty for local deployment.</div>+ </div>+ </div>++ <div class="form-group">+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">+ <label style="margin-bottom: 0;">Model Selection</label>+ <div style="display: flex; gap: 6px;">+ <button class="icon-btn" id="refreshModelsBtn" title="Refresh available models">+ <i data-lucide="refresh-cw"></i>+ </button>+ </div>+ </div>+ <select id="modelSelect">+ <option value="">Loading models...</option>+ </select>+ </div>+ </div>+ </div>++ <!-- Video Source -->+ <div class="panel">+ <div class="panel-header" onclick="togglePanel('cameraConfig')">+ <div class="panel-title">+ <span class="panel-icon">+ <i data-lucide="video"></i>+ </span>+ <span class="panel-title-text">Video Source</span>+ </div>+ <span class="panel-toggle collapsed" id="cameraConfigToggle">▼</span>+ </div>+ <div class="panel-content collapsed" id="cameraConfig">+ <!-- Input Source Tabs -->+ <div class="input-source-tabs" style="display: none;">+ <button class="input-source-tab active" data-source="webcam">+ <i data-lucide="video" style="width: 14px; height: 14px; margin-right: 4px;"></i>+ Webcam+ </button>+ <button class="input-source-tab" data-source="rtsp" title="RTSP IP Camera (Beta - Tested with Reolink RLC-811A)">+ <i data-lucide="cast" style="width: 14px; height: 14px; margin-right: 4px;"></i>+ RTSP Stream+ <span class="beta-badge">BETA</span>+ </button>+ </div>++ <!-- Webcam Controls -->+ <div id="webcamControls">+ <div class="form-group">+ <label>Camera Selection</label>+ <select id="cameraSelect">+ <option value="">Detecting cameras...</option>+ </select>+ <div class="input-hint" style="margin-bottom: 11px;">Select camera device to use for VLM analysis</div>+ </div>+ </div>++ <!-- RTSP Controls -->+ <div id="rtspControls" style="display: none;">+ <div class="form-group">+ <div style="display: flex; align-items: center; gap: 4px; margin-bottom: 8px;">+ <div class="tooltip-wrapper" style="margin-bottom: 0; flex: 1;">+ <label style="margin-bottom: 0;">RTSP Stream URL</label>+ <span class="tooltip-icon">ℹ</span>+ <div class="tooltip-text">+ <strong>Format:</strong> rtsp://[user:pass@]ip:port/path<br><br>+ <strong>Examples:</strong><br>+ • rtsp://192.168.1.100:554/stream<br>+ • rtsp://admin:[email protected]:554/h264Preview_01_main+ </div>+ </div>+ <button class="icon-btn" id="testRtspBtn" title="Test Connection">+ <i data-lucide="test-tube-diagonal"></i>+ </button>+ </div>+ <input type="text" id="rtspUrl" placeholder="rtsp://192.168.1.100:554/stream" style="margin-bottom: 16px;">+ <div id="rtspStatus" class="input-hint" style="margin-top: -8px; margin-bottom: 12px; display: none;"></div>+ </div>+ </div>+ <div class="form-group">+ <!-- RTSP Beta Warning (shown only when RTSP tab is active) -->+ <div id="rtspBetaWarning" class="input-hint" style="margin-top: 12px; color: var(--warning-color); display: none; align-items: center; gap: 4px;">+ <span><strong>Beta:</strong> Optional IP camera input.</span>+ </div>+ </div>+ <div class="form-group">+ <label>Processing Interval</label>+ <input type="number" id="processEvery" value="1" min="0.1" max="60" step="0.1">+ <div class="input-hint">Seconds between each VLM inference (default: 1s)</div>+ </div>+ <div class="form-group" style="margin-bottom: 0;">+ <label>Frames per Batch</label>+ <input type="number" id="framesPerBatch" value="1" min="1" max="30" step="1">+ <div class="input-hint">Number of frames batched per inference (default: 1)</div>+ </div>+ </div>+ </div>++ </div>++ <!-- Main Content -->+ <div class="main-content">+ <!-- Video Feed -->+ <div class="video-card" id="videoCard">+ <div class="alive-view-label"><span></span> YOUR VIEW</div>+ <div class="alive-camera-note">A shared view, a new perspective.<small>Start your camera to begin.</small></div>+ <!-- Big Start Button (centered overlay) -->+ <button id="bigStartBtn" class="big-start-btn" onclick="start()">+ <i data-lucide="play"></i>+ Open camera+ </button>++ <!-- Small Stop Button (top-left corner when streaming) -->+ <button id="smallStopBtn" class="small-stop-btn" onclick="stop({ clearConversation: true })">+ <i data-lucide="square"></i>+ </button>++ <!-- Fullscreen Button (top-right corner) -->+ <button class="fullscreen-btn" onclick="toggleFullscreen()" title="Toggle fullscreen">+ <i data-lucide="maximize" id="fullscreenIcon"></i>+ </button>++ <button class="quick-camera-btn" id="quickCameraBtn" hidden title="Switch front/rear camera" type="button">+ <i data-lucide="camera"></i>+ <span id="quickCameraLabel">Rear</span>+ </button>++ <div class="fullscreen-prompt-overlay" id="fullscreenPromptOverlay"></div>++ <!-- Responses Overlay (shown in fullscreen mode) -->+ <div class="fullscreen-vlm-overlay" id="fullscreenVlmOverlay">+ <div class="vlm-title">+ <i data-lucide="bot"></i>+ Responses+ </div>+ <div class="vlm-content" id="fullscreenVlmContent">Ready</div>+ <div class="vlm-metrics" id="fullscreenVlmMetrics"></div>+ </div>++ <!-- Legacy controls (kept for mirror functionality) -->+ <div class="video-controls" style="top: 64px;">+ <button class="video-control-btn" id="mirrorBtn" title="Mirror video">+ <i data-lucide="flip-horizontal"></i> Mirror+ </button>+ </div>++ <video id="videoElement" autoplay playsinline muted></video>+ <div class="video-overlay" id="videoOverlay"></div>+ </div>++ <!-- Generation Result -->+ <div class="result-card" id="vlmOutputCard">+ <div class="result-header">+ <div class="result-header-left">+ <img class="conversation-brand" src="/images/alive.png?v=1" alt="ALIVE" width="126" height="42">+ <span id="modelName" hidden aria-hidden="true"></span>+ <div class="tts-speaking-line" id="ttsSpeakingLine">+ <strong>Speaking:</strong> <span id="ttsSpeakingText"></span>+ </div>+ </div>+ <div class="result-header-metrics">+ <div class="metrics-inline" id="metricsInline" style="display: none;">+ <div class="metric-item">+ <span title="Model processing time; excludes ASR, TTS, and public network delay">Model:</span>+ <span class="metric-value" id="latencyValue">--</span>+ <span>ms</span>+ </div>+ <div class="metric-item">+ <span>Avg:</span>+ <span class="metric-value" id="avgLatencyValue">--</span>+ <span>ms</span>+ </div>+ <div class="metric-item">+ <span>Count:</span>+ <span class="metric-value" id="countValue">--</span>+ </div>+ </div>+ </div>+ </div>++ <div class="result-prompt" id="currentPrompt" style="display: none;"></div>+ <div id="requestPayloadDebug" class="debug-payload-block" style="display: none; margin-top: 8px;">+ <details style="margin: 0;">+ <summary style="cursor: pointer; font-size: 12px; color: var(--text-secondary);">Request payload (debug)</summary>+ <pre id="requestPayloadContent" style="margin: 8px 0 0; padding: 10px; background: var(--bg-secondary); border-radius: 8px; font-size: 11px; overflow: auto; max-height: 240px; white-space: pre-wrap; word-break: break-all;"></pre>+ </details>+ </div>+ <div class="result-text vlm-history-shell" id="resultText">+ <button class="markdown-toggle-embedded" id="markdownToggle" title="Toggle Markdown Rendering">+ <span id="markdownIcon"><i data-lucide="code"></i></span>+ <span id="markdownText">Markdown</span>+ </button>+ <button class="copy-button-embedded" id="copyButton" title="Copy to clipboard">+ <i data-lucide="copy"></i>+ </button>+ <div class="result-text-content vlm-history" id="resultTextContent"></div>+ </div>+ <div id="responsePayloadDebug" class="debug-payload-block" style="display: none; margin-top: 8px;">+ <details style="margin: 0;">+ <summary style="cursor: pointer; font-size: 12px; color: var(--text-secondary);">Response payload (debug)</summary>+ <pre id="responsePayloadContent" style="margin: 8px 0 0; padding: 10px; background: var(--bg-secondary); border-radius: 8px; font-size: 11px; overflow: auto; max-height: 240px; white-space: pre-wrap; word-break: break-all;"></pre>+ </details>+ </div>+ <div id="memoryStateDebug" class="debug-payload-block" style="display: none; margin-top: 8px;">+ <details open style="margin: 0;">+ <summary style="cursor: pointer; font-size: 12px; color: var(--text-secondary);">Mid-term memory</summary>+ <pre id="midTermMemoryContent" style="margin: 8px 0 0; padding: 10px; background: var(--bg-secondary); border-radius: 8px; font-size: 11px; overflow: auto; max-height: 300px; white-space: pre-wrap; word-break: break-all;"></pre>+ </details>+ <details open style="margin: 4px 0 0;">+ <summary style="cursor: pointer; font-size: 12px; color: var(--text-secondary);">Long-term memory</summary>+ <pre id="longTermMemoryContent" style="margin: 8px 0 0; padding: 10px; background: var(--bg-secondary); border-radius: 8px; font-size: 11px; overflow: auto; max-height: 300px; white-space: pre-wrap; word-break: break-all;"></pre>+ </details>+ </div>+ <div class="prompt-editor-inline">+ <div class="chat-prompt-shell" id="promptEditor">+ <button class="chat-prompt-action" id="promptPresetBtn" title="Quick prompts" type="button">+ <svg class="alive-mark" viewBox="280 126 515 450" aria-hidden="true" focusable="false"><image href="/images/alive.png?v=1" x="0" y="0" width="2172" height="724" /></svg>+ </button>+ <div class="prompt-popover hidden" id="promptPresetMenu">+ <button class="prompt-preset-option" type="button" data-label="Describe the scene" data-prompt="Describe the current scene in one sentence. Answer in English.">+ <span class="prompt-preset-copy">+ <span class="primary">Describe the current scene in one sentence</span>+ <span class="secondary">Describe the scene</span>+ </span>+ <span class="check">✓</span>+ </button>+ <button class="prompt-preset-option" type="button" data-label="Identify an object" data-prompt="What am I holding? Give a short answer in English.">+ <span class="prompt-preset-copy">+ <span class="primary">Identify the object I am holding</span>+ <span class="secondary">Identify an object</span>+ </span>+ <span class="check">✓</span>+ </button>+ <button class="prompt-preset-option" type="button" data-label="Clothing color" data-prompt="What color are my clothes? Give a short answer in English.">+ <span class="prompt-preset-copy">+ <span class="primary">Tell me the color of my clothing</span>+ <span class="secondary">Clothing color</span>+ </span>+ <span class="check">✓</span>+ </button>+ <button class="prompt-preset-option" type="button" data-label="Describe my action" data-prompt="What am I doing? Give a short answer in English.">+ <span class="prompt-preset-copy">+ <span class="primary">Describe what I am doing</span>+ <span class="secondary">Describe my action</span>+ </span>+ <span class="check">✓</span>+ </button>+ </div>+ <textarea class="chat-prompt-input" id="promptText" rows="1" placeholder="Ask about what you see…"></textarea>+ <button class="chat-prompt-action speech speech-control" id="speechBtn" title="Start the video to speak" type="button" disabled>+ <i class="mic-icon" data-lucide="mic"></i>+ <span class="voice-wave" aria-hidden="true"><span></span><span></span><span></span><span></span></span>+ <span class="speech-label">Hold to speak</span>+ </button>+ <button class="chat-prompt-action send" id="promptSendBtn" title="Start the video to send" type="button" disabled>+ <i data-lucide="send"></i>+ </button>+ </div>+ <div class="voice-mode-bar" id="voiceModeBar" aria-label="Voice controls">+ <button id="voiceModeBtn" class="voice-mode-button" type="button" aria-pressed="false"+ aria-label="Turn microphone on" title="Turn microphone on" disabled>+ <span id="voiceModeIcon" class="voice-toggle-icon" aria-hidden="true"></span>+ <span id="voiceModeLabel">Mic off</span>+ </button>+ <button id="ttsToggleBtn" class="voice-mode-button" type="button" aria-pressed="false"+ aria-label="Turn spoken replies on" title="Turn spoken replies on" disabled>+ <span id="ttsToggleIcon" class="voice-toggle-icon" aria-hidden="true"></span>+ <span id="ttsToggleLabel">Sound off</span>+ </button>+ <div id="voiceLanguageTabs" class="voice-language-tabs" role="radiogroup" aria-label="Speech input and output language">+ <button type="button" class="voice-language-tab" role="radio" data-language="auto" aria-checked="true" tabindex="0" title="Detect speech and reply language">Auto</button>+ <button type="button" class="voice-language-tab" role="radio" data-language="zh" aria-checked="false" tabindex="-1" title="Chinese speech input and output">中</button>+ <button type="button" class="voice-language-tab" role="radio" data-language="en" aria-checked="false" tabindex="-1" title="English speech input and output">英</button>+ </div>+ <span id="voiceModeStatus" class="voice-mode-status" role="status">Microphone and sound are off</span>+ </div>+ </div>+ </div>++ </div>+ </div>++ <script>+ // ASR parameters+ const ASR_TARGET_SAMPLE_RATE = 16000;+ const ASR_SILENCE_AUTO_STOP_MS = 2000;+ const ASR_SILENCE_RMS_THRESHOLD = 0.012;+ const ASR_AUDIO_BUFFER_SIZE = 4096;+ const ASR_FINAL_FALLBACK_MS = 6000;+ const ASR_WS_PATH = '/ws/asr';+ // Applied after browser echo cancellation. Short clicks do not interrupt.+ const DUPLEX_ONSET_RMS = 0.018;+ const DUPLEX_ONSET_SAMPLES = ASR_TARGET_SAMPLE_RATE * 0.18;+ const DUPLEX_PREROLL_SAMPLES = ASR_TARGET_SAMPLE_RATE * 0.30;++ // Elements+ const themeToggle = document.getElementById('themeToggle');+ const themeIcon = document.getElementById('themeIcon');+ const themeText = document.getElementById('themeText');+ const jdLogo = document.getElementById('jdLogo');+ const videoElement = document.getElementById('videoElement');+ const startBtn = document.getElementById('startBtn');+ const stopBtn = document.getElementById('stopBtn');+ const connectionStatus = document.getElementById('connectionStatus');+ const resultText = document.getElementById('resultText');+ const currentPrompt = document.getElementById('currentPrompt');+ const metricsInline = document.getElementById('metricsInline');+ const markdownToggle = document.getElementById('markdownToggle');+ const markdownIcon = document.getElementById('markdownIcon');+ const markdownText = document.getElementById('markdownText');+ const copyButton = document.getElementById('copyButton');+ const latencyValue = document.getElementById('latencyValue');+ const avgLatencyValue = document.getElementById('avgLatencyValue');+ const countValue = document.getElementById('countValue');+ const promptPresetBtn = document.getElementById('promptPresetBtn');+ const promptPresetMenu = document.getElementById('promptPresetMenu');+ const promptPresetOptions = document.querySelectorAll('.prompt-preset-option');+ const promptEditor = document.getElementById('promptEditor');+ const promptEditorHome = document.querySelector('.prompt-editor-inline');+ const fullscreenPromptOverlay = document.getElementById('fullscreenPromptOverlay');+ const promptText = document.getElementById('promptText');+ const speechBtn = document.getElementById('speechBtn');+ const voiceModeBtn = document.getElementById('voiceModeBtn');+ const voiceModeLabel = document.getElementById('voiceModeLabel');+ const voiceModeStatus = document.getElementById('voiceModeStatus');+ const ttsToggleBtn = document.getElementById('ttsToggleBtn');+ const ttsToggleLabel = document.getElementById('ttsToggleLabel');+ const voiceIcon = paths => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">${paths}</svg>`;+ const voiceIcons = {+ mic: voiceIcon('<rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3M8 22h8"/>'),+ micOff: voiceIcon('<path d="m2 2 20 20M9 9v3a3 3 0 0 0 5.1 2.1M9 5V5a3 3 0 0 1 6 0v5M5 10v2a7 7 0 0 0 12 4.9M19 10v2M12 19v3M8 22h8"/>'),+ sound: voiceIcon('<path d="m11 5-6 4H2v6h3l6 4V5ZM15.5 8.5a5 5 0 0 1 0 7M19 5a10 10 0 0 1 0 14"/>'),+ soundOff: voiceIcon('<path d="m11 5-6 4H2v6h3l6 4V5ZM17 9l5 6M22 9l-5 6"/>')+ };+ const speechButtons = [speechBtn].filter(Boolean);+ const promptSendBtn = document.getElementById('promptSendBtn');+ const modelSelect = document.getElementById('modelSelect');+ const refreshModelsBtn = document.getElementById('refreshModelsBtn');+ const processEvery = document.getElementById('processEvery');+ const framesPerBatch = document.getElementById('framesPerBatch');+ const maxLatency = document.getElementById('maxLatency');+ const mirrorBtn = document.getElementById('mirrorBtn');+ const quickCameraBtn = document.getElementById('quickCameraBtn');+ const quickCameraLabel = document.getElementById('quickCameraLabel');+ const ttsEnabledToggle = document.getElementById('ttsEnabledToggle');+ const fullDuplexToggle = document.getElementById('fullDuplexToggle');+ const voiceLanguageTabs = [...document.querySelectorAll('#voiceLanguageTabs [data-language]')];+ let voiceCapabilities = { asr: false, tts: false };+ const ttsSpeakingLine = document.getElementById('ttsSpeakingLine');+ const ttsSpeakingText = document.getElementById('ttsSpeakingText');+ const backgroundEnabledToggle = document.getElementById('backgroundEnabledToggle');+ const backgroundFrameMultiplier = document.getElementById('backgroundFrameMultiplier');+ const backgroundMaxFrames = document.getElementById('backgroundMaxFrames');++ let peerConnection = null;+ let localStream = null;+ let cameraWebsocket = null;+ let cameraCaptureTimer = null;+ let websocket = null;+ let serverConfigApplied = false;+ let fadeTimeout = null;+ let lastText = '';+ let lastTtsEventKey = '';+ let ttsEventSequence = 0;+ let ttsRequestToken = 0;+ let ttsWs = null;+ let ttsWsReadyPromise = null;+ let ttsAudioContext = null;+ let ttsNextPlayTime = 0;+ let ttsSources = [];+ let ttsPcmRemainder = null;+ let ttsSpeaking = false;+ let pendingTtsQueue = [];+ let currentTtsItem = null;+ let ttsFinishTimer = null;+ let currentPromptText = '';+ let vlmHistory = [];+ let backgroundTaskEntries = new Map();+ let backgroundSummaryEntries = new Map();+ let lastReadyBackgroundTaskId = '';+ let backgroundConfig = null;+ let lastHistoryKey = null;+ let lastLoggedInferenceCount = 0;+ let pendingPromptEntry = null;+ let streamStartToken = 0;+ let revealVideoAfterMetricsToken = null;+ let revealVideoFallbackTimeout = null;+ let asrWs = null;+ let asrStream = null;+ let asrAudioContext = null;+ let asrSource = null;+ let asrProcessor = null;+ let asrSilence = null;+ let asrStarting = false;+ let asrRecording = false;+ let asrFinalText = '';+ let asrPartialText = '';+ let asrLastFinalText = '';+ let asrLastVoiceTime = 0;+ let asrSendPromptWhenFinal = false;+ let asrStopMode = 'auto';+ let asrPointerId = null;+ let ignoreNextSpeechClick = false;+ let ignoreSpeechClickTimeout = null;+ let asrStartToken = 0;+ let asrFinalFallbackTimer = null;+ let asrStopRequested = false;+ let asrHeardVoice = false;+ let asrUsesServerVad = false;+ let asrRenewTimer = null;+ let duplexUserSpeaking = false;+ let duplexOnsetSamples = 0;+ let duplexPreroll = [];+ let duplexPrerollSamples = 0;+ // Until the new question is answered, late replies may display but not speak.+ let duplexReplyGate = { prompt: null, waiting: false };+ let voiceModeEnabled = false;+ let voiceModeStarting = false;+ let voiceModeGeneration = 0;+ let voiceListenTimer = null;+ let voiceReplyTimer = null;+ let voiceAwaitingPrompt = null;+ let mobileVoiceMode = false;+ // Multi-session: one ID per page/tab; sent in WebSocket and /offer so this tab gets only its VLM output+ let sessionId = crypto.randomUUID ? crypto.randomUUID() : 'tab-' + Date.now() + '-' + Math.random().toString(36).slice(2);+ let gatewaySessionBlocked = false;+ let isAnalysisRunning = false;+ let selectedCameraId = null;+ let videoDevices = [];+ let preferredCameraFacing = 'environment';+ let rtspSessionId = 'default'; // For RTSP mode+ // Enable markdown by default (user can disable if they prefer raw text)+ let markdownEnabled = demoStorage.getItem('markdownEnabled') !== 'false';++ function getCameraFacing(device, index = 0) {+ const label = (device?.label || '').toLowerCase();+ if (/front|user|face|前/.test(label)) {+ return 'user';+ }+ if (/back|rear|environment|world|后/.test(label)) {+ return 'environment';+ }+ return index === 0 ? 'user' : 'environment';+ }++ function syncQuickCameraButton() {+ const activeDevice = videoDevices.find(device => device.deviceId === selectedCameraId);+ const activeIndex = activeDevice ? videoDevices.indexOf(activeDevice) : 0;+ const facing = getCameraFacing(activeDevice, activeIndex);+ preferredCameraFacing = facing;++ if (quickCameraLabel) {+ quickCameraLabel.textContent = facing === 'user' ? 'Front' : 'Rear';+ }+ if (quickCameraBtn) {+ quickCameraBtn.disabled = videoDevices.length < 2;+ quickCameraBtn.hidden = videoDevices.length < 2;+ }+ }++ // Enumerate and list available cameras+ async function enumerateCameras() {+ try {+ // Request permission first to get device labels+ const tempStream = await navigator.mediaDevices.getUserMedia({ video: true });+ tempStream.getTracks().forEach(track => track.stop());++ // Now enumerate with labels+ const devices = await navigator.mediaDevices.enumerateDevices();+ videoDevices = devices.filter(device => device.kind === 'videoinput');++ const cameraSelect = document.getElementById('cameraSelect');+ cameraSelect.innerHTML = '';++ if (videoDevices.length === 0) {+ cameraSelect.innerHTML = '<option value="">No cameras found</option>';+ return;+ }++ videoDevices.forEach((device, index) => {+ const option = document.createElement('option');+ option.value = device.deviceId;+ option.text = device.label || `Camera ${index + 1}`;+ cameraSelect.appendChild(option);+ });++ // Select first camera by default+ selectedCameraId = videoDevices[0].deviceId;+ syncQuickCameraButton();+ console.log(`Found ${videoDevices.length} camera(s)`);+ } catch (err) {+ console.error('Error enumerating cameras:', err);+ document.getElementById('cameraSelect').innerHTML = '<option value="">Error detecting cameras</option>';+ }+ }++ // Handle camera selection change+ document.getElementById('cameraSelect').addEventListener('change', async (e) => {+ selectedCameraId = e.target.value;+ syncQuickCameraButton();+ console.log('Selected camera:', selectedCameraId);++ // If already running, switch camera+ if (isAnalysisRunning && localStream) {+ try {+ // Reset session for fresh inference+ //resetSession();++ // Stop current stream+ localStream.getTracks().forEach(track => track.stop());++ // Get new stream with selected camera+ localStream = await navigator.mediaDevices.getUserMedia({+ video: {+ deviceId: { exact: selectedCameraId },+ width: { ideal: 1280 },+ height: { ideal: 720 }+ }+ });++ showProcessedVideoStream(localStream, streamStartToken);++ // Replace track in peer connection+ const videoTrack = localStream.getVideoTracks()[0];+ const sender = peerConnection?.getSenders().find(s => s.track && s.track.kind === 'video');+ if (sender) {+ await sender.replaceTrack(videoTrack);+ console.log('Camera switched successfully');+ }+ } catch (err) {+ console.error('Error switching camera:', err);+ alert('Failed to switch camera: ' + err.message);+ }+ }++ // Trigger flash animation+ const cameraSelect = document.getElementById('cameraSelect');+ cameraSelect.classList.add('applied');+ setTimeout(() => {+ cameraSelect.classList.remove('applied');+ }, 600);+ });++ // Also trigger flash on blur (when dropdown closes)+ document.getElementById('cameraSelect').addEventListener('blur', () => {+ const cameraSelect = document.getElementById('cameraSelect');+ if (cameraSelect.value) {+ // Trigger flash animation+ cameraSelect.classList.add('applied');+ setTimeout(() => {+ cameraSelect.classList.remove('applied');+ }, 600);+ }+ });++ function findCameraByFacing(facing) {+ return videoDevices.find((device, index) => getCameraFacing(device, index) === facing);+ }++ async function switchCameraByFacing(facing) {+ const cameraSelect = document.getElementById('cameraSelect');+ let targetDevice = findCameraByFacing(facing);++ if (!targetDevice && videoDevices.length > 1) {+ const currentIndex = Math.max(0, videoDevices.findIndex(device => device.deviceId === selectedCameraId));+ targetDevice = videoDevices[(currentIndex + 1) % videoDevices.length];+ }++ if (!targetDevice || targetDevice.deviceId === selectedCameraId) {+ return;+ }++ preferredCameraFacing = getCameraFacing(targetDevice, videoDevices.indexOf(targetDevice));+ selectedCameraId = targetDevice.deviceId;+ if (cameraSelect) {+ cameraSelect.value = selectedCameraId;+ cameraSelect.dispatchEvent(new Event('change', { bubbles: true }));+ }+ syncQuickCameraButton();+ }++ quickCameraBtn?.addEventListener('click', () => {+ const nextFacing = preferredCameraFacing === 'user' ? 'environment' : 'user';+ switchCameraByFacing(nextFacing);+ });++ // Tooltip positioning (for fixed position tooltips)+ document.querySelectorAll('.tooltip-wrapper').forEach(wrapper => {+ const icon = wrapper.querySelector('.tooltip-icon');+ const tooltip = wrapper.querySelector('.tooltip-text');++ if (icon && tooltip) {+ wrapper.addEventListener('mouseenter', () => {+ const rect = icon.getBoundingClientRect();+ tooltip.style.left = `${rect.left}px`;+ tooltip.style.top = `${rect.bottom + 8}px`;+ });+ }+ });++ // Handle input source tabs (Webcam vs RTSP)+ document.querySelectorAll('.input-source-tab').forEach(tab => {+ tab.addEventListener('click', () => {+ const source = tab.getAttribute('data-source');+ const webcamControls = document.getElementById('webcamControls');+ const rtspControls = document.getElementById('rtspControls');+ const rtspBetaWarning = document.getElementById('rtspBetaWarning');+ const startBtn = document.getElementById('startBtn');++ // Update active tab+ document.querySelectorAll('.input-source-tab').forEach(t => t.classList.remove('active'));+ tab.classList.add('active');++ // Show/hide controls+ if (source === 'webcam') {+ webcamControls.style.display = 'block';+ rtspControls.style.display = 'none';+ rtspBetaWarning.style.display = 'none';+ } else if (source === 'rtsp') {+ webcamControls.style.display = 'none';+ rtspControls.style.display = 'block';+ rtspBetaWarning.style.display = 'flex';+ }+ });+ });++ // Clear RTSP status message when user types+ const rtspUrlInput = document.getElementById('rtspUrl');+ rtspUrlInput.addEventListener('input', () => {+ const statusDiv = document.getElementById('rtspStatus');+ statusDiv.style.display = 'none';+ });++ // Green flash animation when RTSP URL is set (same as API Base URL)+ rtspUrlInput.addEventListener('blur', () => {+ if (rtspUrlInput.value.trim()) {+ rtspUrlInput.classList.add('applied');+ setTimeout(() => {+ rtspUrlInput.classList.remove('applied');+ }, 600);+ }+ });++ // Test RTSP connection+ document.getElementById('testRtspBtn').addEventListener('click', async () => {+ const rtspUrl = document.getElementById('rtspUrl').value.trim();+ const statusDiv = document.getElementById('rtspStatus');+ const testBtn = document.getElementById('testRtspBtn');++ if (!rtspUrl) {+ statusDiv.textContent = '⚠️ Please enter an RTSP URL';+ statusDiv.style.display = 'block';+ statusDiv.style.color = '#ff6b35';+ return;+ }++ testBtn.disabled = true;+ statusDiv.textContent = '🔄 Testing connection...';+ statusDiv.style.display = 'block';+ statusDiv.style.color = '#76b900';++ try {+ const response = await fetch('/api/rtsp/start', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ rtsp_url: rtspUrl,+ session_id: 'test-' + Date.now()+ })+ });++ const data = await response.json();++ if (response.ok) {+ const info = data.stream_info;+ statusDiv.innerHTML = `✅ Connected!<br>${info.codec} ${info.width}x${info.height} @${info.fps}fps`;+ statusDiv.style.color = '#76b900';++ // Stop the test connection after 2 seconds+ setTimeout(async () => {+ await fetch('/api/rtsp/stop', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ session_id: data.session_id })+ });+ }, 2000);+ } else {+ statusDiv.textContent = '❌ ' + (data.error || 'Connection failed');+ statusDiv.style.color = '#ff6b35';+ }+ } catch (err) {+ console.error('RTSP test error:', err);+ statusDiv.textContent = '❌ Connection failed: ' + err.message;+ statusDiv.style.color = '#ff6b35';+ } finally {+ testBtn.disabled = false;+ }+ });++ // Tooltip positioning - dynamically position tooltip to avoid clipping+ document.querySelectorAll('.tooltip-wrapper').forEach(wrapper => {+ const icon = wrapper.querySelector('.tooltip-icon');+ const tooltip = wrapper.querySelector('.tooltip-text');++ if (icon && tooltip) {+ icon.addEventListener('mouseenter', () => {+ const rect = icon.getBoundingClientRect();+ const tooltipWidth = 380; // Match CSS width++ // Position below the icon+ let left = rect.left - 10; // Slight offset to left+ let top = rect.bottom + 8;++ // Ensure tooltip doesn't go off right edge of viewport+ if (left + tooltipWidth > window.innerWidth - 20) {+ left = window.innerWidth - tooltipWidth - 20;+ }++ // Ensure tooltip doesn't go off left edge+ if (left < 20) {+ left = 20;+ }++ tooltip.style.left = left + 'px';+ tooltip.style.top = top + 'px';+ });+ }+ });++ function getVlmDisplayText(text) {+ if (!text) return '';++ const rawText = String(text);+ const lowerText = rawText.toLowerCase();+ if (rawText.trim() === 'Initializing...') {+ return '';+ }++ if (lowerText.includes('</silence>')) {+ return '';+ }++ const openTag = '<response>';+ const closeTag = '</response>';+ const openIndex = lowerText.lastIndexOf(openTag);++ if (openIndex !== -1) {+ const responseStart = openIndex + openTag.length;+ const closeIndex = lowerText.indexOf(closeTag, responseStart);+ const responseText = closeIndex === -1+ ? rawText.slice(responseStart)+ : rawText.slice(responseStart, closeIndex);+ return responseText.trim();+ }++ return rawText.replace(/<\/response>/gi, '').trim();+ }++ function escapeHtml(text) {+ const element = document.createElement('div');+ element.textContent = String(text || '');+ return element.innerHTML;+ }++ function decodeHtmlEntities(text) {+ const element = document.createElement('textarea');+ element.innerHTML = String(text || '');+ return element.value;+ }++ function protectMarkdownCodeSpans(text) {+ const placeholders = [];+ const store = (value) => {+ const token = `@@LIVE_VLM_CODE_${placeholders.length}@@`;+ placeholders.push({ token, value });+ return token;+ };+ const protectedText = String(text || '')+ .replace(/```[\s\S]*?(?:```|$)/g, store)+ .replace(/`[^`\n]+`/g, store);+ return { text: protectedText, placeholders };+ }++ function restoreMarkdownCodeSpans(text, placeholders) {+ let restored = String(text || '');+ placeholders.forEach(({ token, value }) => {+ restored = restored.split(token).join(value);+ });+ return restored;+ }++ function renderMathToHtml(math, displayMode) {+ const source = String(math || '').trim();+ if (!source) return '';+ if (typeof katex === 'undefined' || typeof katex.renderToString !== 'function') {+ return displayMode+ ? `<div class="markdown-math-fallback">$${escapeHtml(source)}$</div>`+ : `<span class="markdown-math-fallback">$${escapeHtml(source)}$</span>`;+ }+ try {+ return katex.renderToString(source, {+ displayMode,+ throwOnError: false,+ strict: 'ignore',+ trust: false,+ output: 'html'+ });+ } catch (error) {+ console.warn('Error rendering LaTeX:', error);+ return displayMode+ ? `<div class="markdown-math-fallback">$${escapeHtml(source)}$</div>`+ : `<span class="markdown-math-fallback">$${escapeHtml(source)}$</span>`;+ }+ }++ function renderMarkdownMath(text) {+ const protectedParts = protectMarkdownCodeSpans(text);+ let source = protectedParts.text;++ source = source.replace(/\$\$([\s\S]+?)\$\$/g, (_match, math) => {+ return renderMathToHtml(math, true);+ });+ source = source.replace(/\\\[([\s\S]+?)\\\]/g, (_match, math) => {+ return renderMathToHtml(math, true);+ });+ source = source.replace(/\\\(([\s\S]+?)\\\)/g, (_match, math) => {+ return renderMathToHtml(math, false);+ });+ source = source.replace(/(^|[^\w\\])\$([^\n$]+?)\$(?!\w)/g, (match, prefix, math) => {+ const trimmed = String(math || '').trim();+ if (!trimmed) return match;+ return `${prefix}${renderMathToHtml(trimmed, false)}`;+ });++ return restoreMarkdownCodeSpans(source, protectedParts.placeholders);+ }++ // Markdown rendering function+ function renderMarkdown(text) {+ if (!text) return '';+ const rawText = String(text);+ // Check if libraries are loaded+ if (typeof marked === 'undefined' || typeof DOMPurify === 'undefined') {+ console.warn('Markdown libraries not loaded, falling back to plain text');+ return escapeHtml(rawText);+ }+ try {+ // Preserve special VLM tokens (e.g. </silence>, </response>) by escaping angle brackets+ text = rawText.replace(/<\/(silence|response)>/g, '</$1>');+ text = text.replace(/<(silence|response)>/g, '<$1>');+ text = renderMarkdownMath(text);+ // Configure marked options+ marked.setOptions({+ breaks: true, // Convert line breaks to <br>+ gfm: true, // GitHub Flavored Markdown+ });+ // Parse markdown and sanitize HTML+ const html = marked.parse(text);+ const sanitized = DOMPurify.sanitize(html, {+ ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'u', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'code', 'pre', 'blockquote', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'hr', 'a', 'span', 'div', 'math', 'semantics', 'annotation', 'mrow', 'mi', 'mn', 'mo', 'msup', 'msub', 'msubsup', 'mfrac', 'msqrt', 'mroot', 'mtable', 'mtr', 'mtd', 'mtext'],+ ALLOWED_ATTR: ['href', 'title', 'class', 'style', 'aria-hidden', 'xmlns', 'encoding', 'target', 'rel'],+ });+ return openLinksInNewTabs(sanitized);+ } catch (e) {+ console.error('Error rendering markdown:', e);+ return escapeHtml(rawText); // Fallback to escaped plain text on error+ }+ }++ function openLinksInNewTabs(html) {+ const wrapper = document.createElement('div');+ wrapper.innerHTML = String(html || '');+ wrapper.querySelectorAll('a[href]').forEach((link) => {+ link.setAttribute('target', '_blank');+ link.setAttribute('rel', 'noopener noreferrer');+ });+ return wrapper.innerHTML;+ }++ // Update markdown toggle UI+ function updateMarkdownToggleUI() {+ const contentDiv = document.getElementById('resultTextContent');+ if (markdownEnabled) {+ markdownIcon.innerHTML = '<i data-lucide="code"></i>';+ markdownText.textContent = 'Markdown';+ if (contentDiv) {+ contentDiv.classList.add('markdown-rendered');+ } else {+ resultText.classList.add('markdown-rendered');+ }+ } else {+ markdownIcon.innerHTML = '<i data-lucide="file-text"></i>';+ markdownText.textContent = 'Plain Text';+ if (contentDiv) {+ contentDiv.classList.remove('markdown-rendered');+ } else {+ resultText.classList.remove('markdown-rendered');+ }+ }+ lucide.createIcons();+ }++ // Markdown toggle handler+ markdownToggle.addEventListener('click', () => {+ markdownEnabled = !markdownEnabled;+ demoStorage.setItem('markdownEnabled', markdownEnabled.toString());+ updateMarkdownToggleUI();++ // Re-render current text with new mode+ renderVlmHistory();+ });++ // Initialize markdown toggle state+ updateMarkdownToggleUI();++ // Copy to clipboard functionality+ copyButton.addEventListener('click', async () => {+ const contentDiv = document.getElementById('resultTextContent');+ let textToCopy = '';++ if (contentDiv) {+ // If markdown is enabled, copy the raw text (not HTML)+ if (markdownEnabled) {+ // Get the raw text by reading from lastText or extracting from content+ const latestEntry = vlmHistory[vlmHistory.length - 1] || {};+ textToCopy = latestEntry.response || latestEntry.error || contentDiv.innerText || contentDiv.textContent;+ } else {+ const latestEntry = vlmHistory[vlmHistory.length - 1] || {};+ textToCopy = latestEntry.response || latestEntry.error || contentDiv.textContent || contentDiv.innerText;+ }+ } else {+ textToCopy = resultText.textContent || resultText.innerText;+ }++ if (!textToCopy || textToCopy.trim() === '') {+ return; // Nothing to copy+ }++ try {+ await navigator.clipboard.writeText(textToCopy);++ // Visual feedback+ const originalHTML = copyButton.innerHTML;++ copyButton.classList.add('copied');+ copyButton.innerHTML = '<i data-lucide="check"></i>';+ lucide.createIcons();++ // Reset after 0.8 seconds+ setTimeout(() => {+ copyButton.classList.remove('copied');+ copyButton.innerHTML = originalHTML;+ lucide.createIcons();+ }, 800);+ } catch (err) {+ console.error('Failed to copy text:', err);+ // Fallback for older browsers+ const textArea = document.createElement('textarea');+ textArea.value = textToCopy;+ textArea.style.position = 'fixed';+ textArea.style.opacity = '0';+ document.body.appendChild(textArea);+ textArea.select();+ try {+ document.execCommand('copy');+ copyButton.classList.add('copied');+ setTimeout(() => copyButton.classList.remove('copied'), 500);+ } catch (e) {+ console.error('Fallback copy failed:', e);+ }+ document.body.removeChild(textArea);+ }+ });++ function renderTextIntoElement(element, text) {+ if (markdownEnabled) {+ element.innerHTML = renderMarkdown(text);+ } else {+ element.textContent = text;+ }+ }++ function extractFencedBlocks(text, language) {+ return extractFencedBlockCandidates(text, language, { includeUnclosed: false })+ .map(candidate => candidate.text);+ }++ function extractFencedBlockCandidates(text, language, options = {}) {+ const blocks = [];+ const source = String(text || '');+ const pattern = /```[ \t]*([a-zA-Z0-9_-]*)[ \t]*\r?\n?/g;+ const requestedLanguage = String(language || '').toLowerCase();+ let match;+ while ((match = pattern.exec(source)) !== null) {+ const lang = (match[1] || '').toLowerCase();+ const contentStart = pattern.lastIndex;+ const closingIndex = source.indexOf('```', contentStart);+ if (!requestedLanguage || lang === requestedLanguage) {+ if (closingIndex >= 0) {+ blocks.push({+ text: source.slice(contentStart, closingIndex).trim(),+ incomplete: false+ });+ } else if (options.includeUnclosed) {+ blocks.push({+ text: source.slice(contentStart).trim(),+ incomplete: true+ });+ }+ }+ if (closingIndex >= 0) {+ pattern.lastIndex = closingIndex + 3;+ } else {+ break;+ }+ }+ return blocks;+ }++ function extractInlineJsonObjectCandidates(text, requiredType = '') {+ const source = String(text || '');+ const candidates = [];+ const wantedType = String(requiredType || '').toLowerCase();++ for (let start = 0; start < source.length; start += 1) {+ if (source[start] !== '{') continue;++ let depth = 0;+ let inString = false;+ let escaped = false;++ for (let index = start; index < source.length; index += 1) {+ const char = source[index];+ if (inString) {+ if (escaped) {+ escaped = false;+ } else if (char === '\\') {+ escaped = true;+ } else if (char === '"') {+ inString = false;+ }+ continue;+ }++ if (char === '"') {+ inString = true;+ } else if (char === '{') {+ depth += 1;+ } else if (char === '}') {+ depth -= 1;+ if (depth === 0) {+ const end = index + 1;+ const candidate = source.slice(start, end).trim();+ if (candidate.includes('"type"')) {+ try {+ const parsed = JSON.parse(candidate);+ const type = String(parsed?.type || '').toLowerCase();+ if (!wantedType || type === wantedType) {+ candidates.push({ text: candidate, start, end, parsed });+ }+ } catch (err) {+ // This was a brace-balanced object, but not valid JSON.+ }+ }+ start = end - 1;+ break;+ }+ }++ if (index - start > 160000) {+ break;+ }+ }+ }++ return candidates;+ }++ function stripInlineStructuredJsonFromText(text) {+ let source = String(text || '');+ const removable = extractInlineJsonObjectCandidates(source)+ .filter(candidate => {+ const type = String(candidate.parsed?.type || '').toLowerCase();+ return type === 'bar_chart' || type === 'html';+ })+ .sort((a, b) => b.start - a.start);++ removable.forEach((candidate) => {+ let start = candidate.start;+ const prefix = source.slice(Math.max(0, start - 12), start);+ const jsonLabel = prefix.match(/(?:^|\s)json\s*$/i);+ if (jsonLabel) {+ start -= jsonLabel[0].length;+ }+ source = `${source.slice(0, start)}${source.slice(candidate.end)}`;+ });++ return source.replace(/[ \t]{2,}/g, ' ').trim();+ }++ function parseBackgroundChart(text) {+ const candidates = extractFencedBlocks(text, 'json');+ extractInlineJsonObjectCandidates(text, 'bar_chart').forEach(candidate => {+ candidates.push(candidate.text);+ });+ const trimmed = String(text || '').trim();+ if (trimmed.startsWith('{') && trimmed.endsWith('}')) {+ candidates.unshift(trimmed);+ }++ for (const candidate of candidates) {+ try {+ const parsed = JSON.parse(candidate);+ if (+ parsed &&+ parsed.type === 'bar_chart' &&+ Array.isArray(parsed.labels) &&+ Array.isArray(parsed.values)+ ) {+ const labels = parsed.labels.map(label => String(label));+ const values = parsed.values.map(value => Number(value));+ if (labels.length && labels.length === values.length && values.every(Number.isFinite)) {+ return {+ title: String(parsed.title || ''),+ labels,+ values+ };+ }+ }+ } catch (err) {+ // Keep looking for a valid structured block.+ }+ }+ return null;+ }++ function extractBackgroundHtml(text) {+ return extractBackgroundHtmlDetails(text).html;+ }++ function extractBackgroundExplanation(text) {+ let source = String(text || '').trim();+ if (!source) return '';++ source = source+ .replace(/```[ \t]*html[ \t]*\r?\n[\s\S]*?(?:\r?\n```|$)/gi, '')+ .replace(/```[ \t]*json[ \t]*\r?\n\s*\{[\s\S]*?"type"\s*:\s*"(?:html|bar_chart)"[\s\S]*?(?:\r?\n```|$)/gi, '')+ .trim();+ source = stripInlineStructuredJsonFromText(source);++ const doctypeIndex = source.search(/<!doctype html/i);+ const htmlIndex = source.search(/<html[\s>]/i);+ const starts = [doctypeIndex, htmlIndex].filter(index => index >= 0);+ if (starts.length) {+ source = source.slice(0, Math.min(...starts)).trim();+ }++ return source;+ }++ function extractBackgroundHtmlDetails(text) {+ const explicitHtmlCandidates = [];+ const htmlBlocks = extractFencedBlockCandidates(text, 'html', { includeUnclosed: true });+ htmlBlocks.forEach((block) => {+ explicitHtmlCandidates.push({+ text: block.text,+ incomplete: block.incomplete+ });+ });++ const candidates = extractFencedBlocks(text, 'json');+ extractInlineJsonObjectCandidates(text, 'html').forEach(candidate => {+ candidates.push(candidate.text);+ });+ const trimmed = String(text || '').trim();+ if (trimmed.startsWith('{') && trimmed.endsWith('}')) {+ candidates.unshift(trimmed);+ }+ for (const candidate of candidates) {+ try {+ const parsed = JSON.parse(candidate);+ if (parsed && parsed.type === 'html' && typeof parsed.html === 'string') {+ explicitHtmlCandidates.push({+ text: parsed.html,+ incomplete: false+ });+ }+ } catch (err) {+ // Keep looking.+ }+ }++ const explicitBest = pickBestBackgroundHtmlCandidate(explicitHtmlCandidates);+ if (explicitBest) {+ return explicitBest;+ }++ const fallbackBest = pickBestBackgroundHtmlCandidate([{+ text: trimmed,+ incomplete: false+ }]);+ if (fallbackBest) {+ return fallbackBest;+ }+ return { html: '', incomplete: false };+ }++ function pickBestBackgroundHtmlCandidate(htmlCandidates) {+ let best = null;+ htmlCandidates.forEach((candidate) => {+ const details = normalizeExtractedHtmlDetails(candidate.text, {+ sourceIncomplete: candidate.incomplete+ });+ if (!details.html) return;+ const scored = {+ ...details,+ score: scoreHtmlCandidate(details.html, details.incomplete)+ };+ if (!best || scored.score > best.score) {+ best = scored;+ }+ });++ if (best) {+ return {+ html: best.html,+ incomplete: best.incomplete+ };+ }+ return null;+ }++ function normalizeExtractedHtml(value) {+ return normalizeExtractedHtmlDetails(value).html;+ }++ function normalizeExtractedHtmlDetails(value, options = {}) {+ let html = decodeHtmlEntities(value).trim();+ if (!html) {+ return { html: '', incomplete: false };+ }++ html = html+ .replace(/^```[ \t]*(?:html)?[ \t]*\r?\n?/i, '')+ .replace(/\r?\n?```[ \t]*$/i, '')+ .trim();++ const doctypeIndex = html.search(/<!doctype html/i);+ const htmlIndex = html.search(/<html[\s>]/i);+ const startCandidates = [doctypeIndex, htmlIndex].filter(index => index >= 0);+ if (!startCandidates.length) {+ if (/<(head|body|main|section|style|div|h1|p)\b/i.test(html)) {+ return {+ html: completeStaticHtmlDocument(`<!doctype html>\n<html><head><meta charset="UTF-8"></head><body>${html}`),+ incomplete: Boolean(options.sourceIncomplete || looksIncompleteHtml(html))+ };+ }+ return { html: '', incomplete: false };+ }++ const startIndex = Math.min(...startCandidates);+ const endMatch = /<\/html\s*>/i.exec(html.slice(startIndex));+ if (endMatch) {+ const endIndex = startIndex + endMatch.index + endMatch[0].length;+ return {+ html: html.slice(startIndex, endIndex).trim(),+ incomplete: false+ };+ }+ return {+ html: completeStaticHtmlDocument(html.slice(startIndex).trim()),+ incomplete: true+ };+ }++ function scoreHtmlCandidate(html, incomplete = false) {+ const source = String(html || '');+ const lower = source.toLowerCase();+ let score = Math.min(source.length, 20000);+ if (!incomplete) score += 5000;+ if (lower.includes('<style')) score += 2500;+ if (lower.includes('<body')) score += 1500;+ if (/<(body|main|section|article|aside|header|footer|nav|div|h[1-6]|p|button|ul|ol|li|span|img|figure|table)\b/i.test(source)) {+ score += 1500;+ }+ const structuralMatches = source.match(/<(?:div|section|main|header|nav|footer|button|h[1-6]|p|li)\b/gi) || [];+ score += Math.min(structuralMatches.length * 120, 3000);+ const placeholderCount = (source.match(/\.{3}|…/g) || []).length;+ score -= placeholderCount * 3000;+ const placeholderElementCount = (source.match(/>\s*\.{3}\s*</g) || []).length;+ score -= placeholderElementCount * 5000;+ return score;+ }++ function looksIncompleteHtml(value) {+ const html = String(value || '');+ return (+ (/<html\b/i.test(html) && !/<\/html\s*>/i.test(html)) ||+ (/<body\b/i.test(html) && !/<\/body\s*>/i.test(html)) ||+ (/<head\b/i.test(html) && !/<\/head\s*>/i.test(html)) ||+ (/<style\b/i.test(html) && !/<\/style\s*>/i.test(html))+ );+ }++ function completeStaticHtmlDocument(value) {+ let html = String(value || '').trim();+ if (!html) return '';++ if (/<style\b[^>]*>/i.test(html) && !/<\/style\s*>/i.test(html)) {+ html += '\n</style>';+ }+ if (/<head\b[^>]*>/i.test(html) && !/<\/head\s*>/i.test(html)) {+ html += '\n</head>';+ }+ if (!/<body\b/i.test(html)) {+ html += '\n<body><main style="min-height:100vh;display:grid;place-items:center;font-family:sans-serif;color:#333;background:#f7f7f7;">HTML may be truncated; only styles are available to preview.</main>';+ }+ if (/<body\b[^>]*>/i.test(html) && !/<\/body\s*>/i.test(html)) {+ html += '\n</body>';+ }+ if (/<html\b[^>]*>/i.test(html) && !/<\/html\s*>/i.test(html)) {+ html += '\n</html>';+ }+ if (!/<html\b/i.test(html)) {+ html = `<!doctype html>\n<html><head><meta charset="UTF-8"></head><body>${html}</body></html>`;+ }+ return html;+ }++ function sanitizeStaticHtml(html) {+ if (!html) return '';+ const rawHtml = String(html);+ const allowedTags = [+ 'html', 'head', 'body', 'title', 'style',+ 'main', 'header', 'footer', 'nav', 'section', 'article', 'aside',+ 'div', 'span', 'p', 'br', 'strong', 'em', 'b', 'i', 'u', 'small',+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',+ 'ul', 'ol', 'li', 'dl', 'dt', 'dd',+ 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption',+ 'pre', 'code', 'blockquote', 'hr',+ 'a', 'img', 'figure', 'figcaption', 'button'+ ];+ const allowedAttrs = [+ 'class', 'id', 'style', 'title', 'role', 'aria-label',+ 'href', 'src', 'alt', 'width', 'height', 'colspan', 'rowspan'+ ];++ if (typeof DOMPurify !== 'undefined') {+ const cleaned = DOMPurify.sanitize(rawHtml, {+ WHOLE_DOCUMENT: true,+ ALLOWED_TAGS: allowedTags,+ ALLOWED_ATTR: allowedAttrs,+ ALLOW_DATA_ATTR: false,+ ALLOW_ARIA_ATTR: true,+ ALLOWED_URI_REGEXP: /^(?:#|data:image\/(?:png|jpe?g|gif|webp);base64,)/i,+ FORBID_TAGS: ['script', 'form', 'input', 'textarea', 'select', 'option', 'iframe', 'object', 'embed', 'link', 'meta', 'base', 'svg', 'math']+ });+ return normalizeStaticHtmlDocument(cleaned, allowedTags, allowedAttrs);+ }++ return sanitizeStaticHtmlFallback(rawHtml, allowedTags, allowedAttrs);+ }++ function normalizeStaticHtmlDocument(html, allowedTags, allowedAttrs) {+ if (typeof DOMParser === 'undefined') {+ return escapeHtml(html);+ }+ const parser = new DOMParser();+ const source = parser.parseFromString(String(html || ''), 'text/html');+ const cleanDoc = document.implementation.createHTMLDocument('');+ const cleanNode = makeStaticHtmlNodeCleaner(cleanDoc, allowedTags, allowedAttrs);++ Array.from(source.head.childNodes).forEach((child) => {+ const cleaned = cleanNode(child);+ if (cleaned) cleanDoc.head.appendChild(cleaned);+ });+ Array.from(source.body.childNodes).forEach((child) => {+ const cleaned = cleanNode(child);+ if (cleaned) cleanDoc.body.appendChild(cleaned);+ });++ return '<!doctype html>\n' + cleanDoc.documentElement.outerHTML;+ }++ function sanitizeStaticHtmlFallback(html, allowedTags, allowedAttrs) {+ if (typeof DOMParser === 'undefined') {+ return escapeHtml(html);+ }+ return normalizeStaticHtmlDocument(html, allowedTags, allowedAttrs);+ }++ function makeStaticHtmlNodeCleaner(cleanDoc, allowedTags, allowedAttrs) {+ const tagSet = new Set(allowedTags);+ const attrSet = new Set(allowedAttrs);+ const dropTags = new Set(['script', 'form', 'input', 'textarea', 'select', 'option', 'iframe', 'object', 'embed', 'link', 'meta', 'base', 'svg', 'math']);++ const cleanNode = (node) => {+ if (node.nodeType === Node.TEXT_NODE) {+ return cleanDoc.createTextNode(node.textContent || '');+ }+ if (node.nodeType !== Node.ELEMENT_NODE) {+ return null;+ }++ const tagName = node.tagName.toLowerCase();+ if (dropTags.has(tagName)) {+ return null;+ }+ if (!tagSet.has(tagName)) {+ const fragment = cleanDoc.createDocumentFragment();+ Array.from(node.childNodes).forEach((child) => {+ const cleanedChild = cleanNode(child);+ if (cleanedChild) fragment.appendChild(cleanedChild);+ });+ return fragment;+ }++ const element = cleanDoc.createElement(tagName);+ Array.from(node.attributes || []).forEach((attr) => {+ const attrName = attr.name.toLowerCase();+ if (!attrSet.has(attrName) || attrName.startsWith('on')) {+ return;+ }+ if (tagName === 'a' && attrName === 'href') {+ return;+ }+ if (attrName === 'src' && !isSafeStaticUrl(attr.value)) {+ return;+ }+ if (attrName === 'style') {+ element.setAttribute(attrName, sanitizeStaticCss(attr.value));+ return;+ }+ element.setAttribute(attrName, attr.value);+ });++ Array.from(node.childNodes).forEach((child) => {+ const cleanedChild = cleanNode(child);+ if (cleanedChild) element.appendChild(cleanedChild);+ });++ if (tagName === 'style') {+ element.textContent = sanitizeStaticCss(node.textContent || '');+ }+ if (tagName === 'a') {+ element.setAttribute('data-static-link', 'true');+ element.setAttribute('tabindex', '-1');+ }+ if (tagName === 'button') {+ element.setAttribute('type', 'button');+ }+ return element;+ };++ return cleanNode;+ }++ function isSafeStaticUrl(url) {+ const value = String(url || '').trim();+ return !value || value.startsWith('#') || /^data:image\/(?:png|jpe?g|gif|webp);base64,/i.test(value);+ }++ function sanitizeStaticCss(css) {+ return String(css || '')+ .replace(/@import\b[^;]+;?/gi, '')+ .replace(/javascript:/gi, '')+ .replace(/expression\s*\(/gi, '')+ .replace(/url\s*\(\s*(['"]?)(?!data:image\/(?:png|jpe?g|gif|webp);base64,)[^)]+\)/gi, 'none');+ }++ function drawBackgroundBarChart(canvas, chart) {+ const dpr = window.devicePixelRatio || 1;+ const rect = canvas.getBoundingClientRect();+ const width = Math.max(320, Math.floor(rect.width || canvas.clientWidth || 640));+ const height = Math.max(220, Math.floor(rect.height || canvas.clientHeight || 280));+ canvas.width = width * dpr;+ canvas.height = height * dpr;+ const ctx = canvas.getContext('2d');+ ctx.scale(dpr, dpr);+ ctx.clearRect(0, 0, width, height);++ const styles = getComputedStyle(document.documentElement);+ const textColor = styles.getPropertyValue('--text-primary').trim() || '#f5f5f5';+ const mutedColor = styles.getPropertyValue('--text-secondary').trim() || '#aaa';+ const accentColor = styles.getPropertyValue('--warning-color').trim() || '#FFA726';+ const gridColor = styles.getPropertyValue('--border-color').trim() || '#333';+ const padding = { top: chart.title ? 36 : 20, right: 18, bottom: 58, left: 48 };+ const plotW = width - padding.left - padding.right;+ const plotH = height - padding.top - padding.bottom;+ const maxValue = Math.max(...chart.values, 0);+ const scaleMax = maxValue <= 0 ? 1 : maxValue * 1.12;++ ctx.font = '600 14px system-ui, sans-serif';+ ctx.fillStyle = textColor;+ if (chart.title) {+ ctx.fillText(chart.title, padding.left, 22);+ }++ ctx.strokeStyle = gridColor;+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.moveTo(padding.left, padding.top);+ ctx.lineTo(padding.left, padding.top + plotH);+ ctx.lineTo(padding.left + plotW, padding.top + plotH);+ ctx.stroke();++ const barGap = Math.max(6, Math.min(18, plotW / chart.labels.length * 0.18));+ const barW = Math.max(10, (plotW - barGap * (chart.labels.length - 1)) / chart.labels.length);+ ctx.textAlign = 'center';+ ctx.font = '12px system-ui, sans-serif';+ chart.values.forEach((value, index) => {+ const x = padding.left + index * (barW + barGap);+ const barH = Math.max(1, (value / scaleMax) * plotH);+ const y = padding.top + plotH - barH;+ ctx.fillStyle = accentColor;+ ctx.fillRect(x, y, barW, barH);+ ctx.fillStyle = textColor;+ ctx.fillText(String(value), x + barW / 2, Math.max(padding.top + 12, y - 6));+ ctx.fillStyle = mutedColor;+ const label = chart.labels[index];+ const shortLabel = label.length > 14 ? label.slice(0, 13) + '…' : label;+ ctx.fillText(shortLabel, x + barW / 2, padding.top + plotH + 22);+ });+ ctx.textAlign = 'left';+ }++ let activeBackgroundModal = null;++ function createBackgroundActionButton(icon, label, onClick) {+ const button = document.createElement('button');+ button.type = 'button';+ button.className = 'background-rich-action';+ button.innerHTML = `<i data-lucide="${icon}"></i><span>${label}</span>`;+ button.addEventListener('click', onClick);+ return button;+ }++ function openHtmlArtifact(url) {+ const value = String(url || '').trim();+ if (!value) return;+ window.open(value, '_blank', 'noopener,noreferrer');+ }++ function renderBackgroundRawView(view, text, options = {}) {+ view.className = 'background-raw-shell';+ const toolbar = document.createElement('div');+ toolbar.className = 'background-raw-toolbar';++ const copyButton = createBackgroundActionButton('copy', 'Copy', async () => {+ try {+ await navigator.clipboard.writeText(String(text || ''));+ copyButton.innerHTML = '<i data-lucide="check"></i><span>Copied</span>';+ lucide.createIcons();+ setTimeout(() => {+ copyButton.innerHTML = '<i data-lucide="copy"></i><span>Copy</span>';+ lucide.createIcons();+ }, 900);+ } catch (err) {+ console.error('Failed to copy background raw result:', err);+ }+ });+ toolbar.appendChild(copyButton);++ if (!options.modal) {+ toolbar.appendChild(createBackgroundActionButton('maximize-2', 'Expand', () => {+ openBackgroundModal('Raw', (body) => renderBackgroundRawView(body, text, { modal: true }));+ }));+ }++ const pre = document.createElement('pre');+ pre.className = 'background-raw-block';+ pre.textContent = String(text || '');+ view.appendChild(toolbar);+ view.appendChild(pre);+ }++ function renderBackgroundChartView(view, chart, options = {}) {+ view.className = 'background-view-shell';+ if (!options.modal) {+ const toolbar = document.createElement('div');+ toolbar.className = 'background-view-toolbar';+ toolbar.appendChild(createBackgroundActionButton('maximize-2', 'Expand', () => {+ openBackgroundModal('Chart', (body) => renderBackgroundChartView(body, chart, { modal: true }));+ }));+ view.appendChild(toolbar);+ }++ const canvas = document.createElement('canvas');+ canvas.className = 'background-chart';+ view.appendChild(canvas);+ requestAnimationFrame(() => drawBackgroundBarChart(canvas, chart));+ }++ function renderBackgroundHtmlView(view, html, options = {}) {+ view.className = 'background-view-shell';+ if (!options.modal) {+ const toolbar = document.createElement('div');+ toolbar.className = 'background-view-toolbar';+ if (options.htmlUrl) {+ toolbar.appendChild(createBackgroundActionButton('external-link', 'Open', () => {+ openHtmlArtifact(options.htmlUrl);+ }));+ }+ toolbar.appendChild(createBackgroundActionButton('maximize-2', 'Expand', () => {+ openBackgroundModal('Preview', (body) => renderBackgroundHtmlView(body, html, {+ modal: true,+ incomplete: options.incomplete,+ htmlUrl: options.htmlUrl+ }));+ }));+ view.appendChild(toolbar);+ } else if (options.htmlUrl) {+ const toolbar = document.createElement('div');+ toolbar.className = 'background-view-toolbar';+ toolbar.appendChild(createBackgroundActionButton('external-link', 'Open', () => {+ openHtmlArtifact(options.htmlUrl);+ }));+ view.appendChild(toolbar);+ }++ if (options.incomplete) {+ const warning = document.createElement('div');+ warning.className = 'background-preview-warning';+ warning.textContent = 'Background HTML may be truncated. Check the Raw view for the original content.';+ view.appendChild(warning);+ }++ const iframe = document.createElement('iframe');+ iframe.className = 'background-html-frame';+ iframe.setAttribute('sandbox', '');+ iframe.srcdoc = sanitizeStaticHtml(html);+ view.appendChild(iframe);+ }++ function openBackgroundModal(title, renderContent) {+ closeBackgroundModal();++ const backdrop = document.createElement('div');+ backdrop.className = 'background-modal-backdrop';+ backdrop.setAttribute('role', 'dialog');+ backdrop.setAttribute('aria-modal', 'true');++ const dialog = document.createElement('div');+ dialog.className = 'background-modal-dialog';+ dialog.addEventListener('click', (event) => event.stopPropagation());++ const header = document.createElement('div');+ header.className = 'background-modal-header';+ const titleElement = document.createElement('h3');+ titleElement.className = 'background-modal-title';+ titleElement.textContent = title;+ const closeButton = document.createElement('button');+ closeButton.type = 'button';+ closeButton.className = 'background-modal-close';+ closeButton.setAttribute('aria-label', 'Close');+ closeButton.innerHTML = '<i data-lucide="x"></i>';+ closeButton.addEventListener('click', closeBackgroundModal);+ header.appendChild(titleElement);+ header.appendChild(closeButton);++ const body = document.createElement('div');+ body.className = 'background-modal-body';+ renderContent(body);++ dialog.appendChild(header);+ dialog.appendChild(body);+ backdrop.appendChild(dialog);+ backdrop.addEventListener('click', closeBackgroundModal);++ document.body.appendChild(backdrop);+ document.body.classList.add('background-modal-open');+ activeBackgroundModal = backdrop;+ lucide.createIcons();+ closeButton.focus();+ }++ function closeBackgroundModal() {+ if (!activeBackgroundModal) return;+ activeBackgroundModal.remove();+ activeBackgroundModal = null;+ document.body.classList.remove('background-modal-open');+ }++ document.addEventListener('keydown', (event) => {+ if (event.key === 'Escape' && activeBackgroundModal) {+ closeBackgroundModal();+ }+ });++ function renderBackgroundRichContent(element, text, rich = null) {+ const structuredChart = rich && rich.chart && Array.isArray(rich.chart.labels) && Array.isArray(rich.chart.values)+ ? {+ title: String(rich.chart.title || ''),+ labels: rich.chart.labels.map(label => String(label)),+ values: rich.chart.values.map(value => Number(value))+ }+ : null;+ const chart = structuredChart || parseBackgroundChart(text);+ let htmlDetails;+ if (rich && typeof rich.html === 'string' && rich.html.trim()) {+ htmlDetails = normalizeExtractedHtmlDetails(rich.html, {+ sourceIncomplete: Boolean(rich.html_incomplete)+ });+ htmlDetails.incomplete = Boolean(rich.html_incomplete || htmlDetails.incomplete);+ } else {+ htmlDetails = extractBackgroundHtmlDetails(text);+ }+ const html = htmlDetails.html;+ const hasRich = Boolean(chart || html);+ const explanation = extractBackgroundExplanation(text);+ if (!hasRich) {+ renderTextIntoElement(element, text);+ element.classList.toggle('markdown-rendered', markdownEnabled);+ return;+ }++ element.innerHTML = '';+ element.classList.add('background-rich-content');++ const tabs = document.createElement('div');+ tabs.className = 'background-rich-tabs';+ const body = document.createElement('div');+ const views = [];+ let preferredViewLabel = chart ? 'Chart' : html ? 'Preview' : explanation ? 'Explanation' : 'Raw';++ const addView = (label, render) => {+ const tab = document.createElement('button');+ tab.type = 'button';+ tab.className = 'background-rich-tab';+ tab.textContent = label;+ const view = document.createElement('div');+ view.style.display = 'none';+ render(view);+ tab.addEventListener('click', () => {+ views.forEach(item => {+ item.tab.classList.toggle('active', item.view === view);+ item.view.style.display = item.view === view ? 'block' : 'none';+ });+ });+ tabs.appendChild(tab);+ body.appendChild(view);+ views.push({ label, tab, view });+ };++ if (explanation) {+ addView('Explanation', (view) => {+ view.className = 'background-view-shell markdown-rendered';+ renderTextIntoElement(view, explanation);+ });+ }++ addView('Raw', (view) => {+ renderBackgroundRawView(view, text);+ });++ if (chart) {+ addView('Chart', (view) => {+ renderBackgroundChartView(view, chart);+ });+ }++ if (html) {+ addView('Preview', (view) => {+ renderBackgroundHtmlView(view, html, {+ incomplete: htmlDetails.incomplete,+ htmlUrl: rich && typeof rich.html_url === 'string' ? rich.html_url : ''+ });+ });+ }++ element.appendChild(tabs);+ element.appendChild(body);+ if (views.length) {+ const defaultView = views.find(item => item.label === preferredViewLabel) || views[0];+ defaultView.tab.click();+ lucide.createIcons();+ }+ }++ function isVlmHistoryNearBottom(element) {+ if (!element) return false;+ if (element.scrollHeight <= element.clientHeight) return true;+ return element.scrollHeight - element.scrollTop - element.clientHeight <= 48;+ }++ function scrollVlmHistoryToBottom(element) {+ if (!element) return;++ requestAnimationFrame(() => {+ element.scrollTop = element.scrollHeight;+ requestAnimationFrame(() => {+ element.scrollTop = element.scrollHeight;+ });+ });+ }++ function updateTtsSpeakingDisplay(text = '') {+ const speakingText = String(text || '').trim();+ if (ttsSpeakingLine) {+ ttsSpeakingLine.classList.toggle('show', Boolean(speakingText));+ }+ if (ttsSpeakingText) {+ ttsSpeakingText.textContent = speakingText;+ }+ }++ function stopTtsPlayback({ clearQueue = true, requeueCurrent = false } = {}) {+ if (clearQueue) pendingTtsQueue = [];+ else if (requeueCurrent && currentTtsItem) pendingTtsQueue.unshift(currentTtsItem);+ currentTtsItem = null;+ ttsRequestToken += 1;++ if (ttsWs && ttsWs.readyState === WebSocket.OPEN) {+ ttsWs._acceptingAudio = false;+ ttsWs._requestId = '';+ ttsWs._pendingRequestId = '';+ ttsWs.send(JSON.stringify({+ type: 'stop',+ request_id: String(ttsRequestToken)+ }));+ }++ ttsSources.forEach(source => {+ try {+ source.stop();+ } catch (e) {+ // Source may have already ended.+ }+ });+ ttsSources = [];+ ttsNextPlayTime = 0;+ ttsPcmRemainder = null;+ ttsSpeaking = false;+ updateTtsSpeakingDisplay('');+ if (ttsFinishTimer) {+ clearTimeout(ttsFinishTimer);+ ttsFinishTimer = null;+ }+ }++ function closeTtsWebSocket() {+ stopTtsPlayback();+ if (ttsWs && [WebSocket.CONNECTING, WebSocket.OPEN].includes(ttsWs.readyState)) {+ ttsWs.close();+ }+ ttsWs = null;+ ttsWsReadyPromise = null;+ }++ function maybeSpeakPendingTts() {+ scheduleVoiceListening();+ if (!pendingTtsQueue.length) return;+ const inputBlocksPlayback = isSpeechActive()+ && (!isDuplexListening() || duplexUserSpeaking || asrSendPromptWhenFinal);+ if (ttsSpeaking || !pendingTtsQueue.length || inputBlocksPlayback || !settings.ttsEnabled || !voiceCapabilities.tts) {+ return;+ }+ currentTtsItem = pendingTtsQueue.shift();+ ttsRequestToken += 1;+ startTtsSpeech(currentTtsItem.text, currentTtsItem.lang);+ }++ function splitSpeechText(text) {+ // The speech server accepts 500 characters; keep long replies intact+ // by sending ordered pieces, preferably split at a word boundary.+ const parts = [];+ let rest = text;+ while (rest.length > 450) {+ let end = rest.lastIndexOf(' ', 450);+ if (end < 225) end = 450;+ parts.push(rest.slice(0, end));+ rest = rest.slice(end).trimStart();+ }+ if (rest) parts.push(rest);+ return parts;+ }++ function getTtsWebSocket() {+ if (ttsWs && ttsWs.readyState === WebSocket.OPEN) {+ return Promise.resolve(ttsWs);+ }++ if (ttsWsReadyPromise && ttsWs && ttsWs.readyState === WebSocket.CONNECTING) {+ return ttsWsReadyPromise;+ }++ const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';+ const wsUrl = `${protocol}//${window.location.host}/api/tts?session_id=${encodeURIComponent(sessionId)}`;+ const ws = new WebSocket(wsUrl);+ ttsWs = ws;+ ws.binaryType = 'arraybuffer';++ ttsWsReadyPromise = new Promise((resolve, reject) => {+ ws.onopen = () => {+ if (ttsWs === ws) {+ resolve(ws);+ } else {+ reject(new Error('TTS websocket was replaced'));+ }+ };+ ws.onerror = (error) => {+ if (ttsWs === ws) {+ lastTtsEventKey = '';+ }+ reject(error instanceof Error ? error : new Error('TTS websocket failed'));+ };+ });++ ws.onmessage = (event) => {+ if (ttsWs !== ws || !settings.ttsEnabled) {+ return;+ }++ if (typeof event.data === 'string') {+ let message;+ try {+ message = JSON.parse(event.data);+ } catch (error) {+ console.warn('TTS sent invalid control message:', event.data);+ return;+ }++ if (message.type === 'start') {+ const startedRequestId = String(message.request_id || message.reqid || '');+ if (startedRequestId === ws._pendingRequestId) {+ ws._sampleRate = Number(message.sample_rate) || ws._sampleRate || 24000;+ ws._requestId = startedRequestId;+ ws._acceptingAudio = true;+ ws._serverDone = false;+ }+ } else if (message.type === 'done' || message.type === 'stopped') {+ if (message.request_id && String(message.request_id) === ws._requestId) {+ ws._acceptingAudio = false;+ ws._serverDone = true;+ scheduleTtsFinishCheck(String(message.request_id));+ maybeFinishTtsSpeech(String(message.request_id));+ }+ } else if (message.type === 'error') {+ const failedId = String(message.request_id || '');+ if (!failedId || failedId === String(ttsRequestToken)) {+ stopTtsPlayback({ clearQueue: false });+ lastTtsEventKey = '';+ updateStatus('Speech playback failed. Continuing with the next reply.', 'disconnected');+ maybeSpeakPendingTts();+ }+ }+ return;+ }++ const activeRequestId = String(ttsRequestToken);+ if (!ws._acceptingAudio || ws._requestId !== activeRequestId) {+ return;+ }+ queueTtsPcmChunk(event.data, ws._sampleRate || 24000, ttsRequestToken);+ };++ ws.onclose = () => {+ if (ttsWs === ws) {+ ttsWs = null;+ ttsWsReadyPromise = null;+ if (ttsSpeaking) {+ stopTtsPlayback({ clearQueue: false });+ updateStatus('Speech connection interrupted. Please retry.', 'disconnected');+ maybeSpeakPendingTts();+ }+ }+ };++ return ttsWsReadyPromise;+ }++ function ensureTtsAudioContext() {+ const AudioContextClass = window.AudioContext || window.webkitAudioContext;+ if (!AudioContextClass) {+ throw new Error('Web Audio API is not supported');+ }+ if (!ttsAudioContext || ttsAudioContext.state === 'closed') {+ ttsAudioContext = new AudioContextClass();+ }+ if (ttsAudioContext.state === 'suspended') {+ ttsAudioContext.resume();+ }+ return ttsAudioContext;+ }++ function pcm16ToAudioBuffer(arrayBuffer, sampleRate) {+ const context = ensureTtsAudioContext();+ const pcm = new Int16Array(arrayBuffer);+ const audioBuffer = context.createBuffer(1, pcm.length, sampleRate);+ const channel = audioBuffer.getChannelData(0);++ for (let i = 0; i < pcm.length; i += 1) {+ channel[i] = Math.max(-1, Math.min(1, pcm[i] / 32768));+ }++ return audioBuffer;+ }++ function normalizePcmChunk(arrayBuffer) {+ let bytes = new Uint8Array(arrayBuffer);++ if (ttsPcmRemainder?.length) {+ const combined = new Uint8Array(ttsPcmRemainder.length + bytes.length);+ combined.set(ttsPcmRemainder, 0);+ combined.set(bytes, ttsPcmRemainder.length);+ bytes = combined;+ ttsPcmRemainder = null;+ }++ if (bytes.length % 2 !== 0) {+ ttsPcmRemainder = bytes.slice(bytes.length - 1);+ bytes = bytes.slice(0, bytes.length - 1);+ }++ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);+ }++ function queueTtsPcmChunk(arrayBuffer, sampleRate, requestToken) {+ if (requestToken !== ttsRequestToken || !settings.ttsEnabled || arrayBuffer.byteLength === 0) {+ return;+ }++ const pcmBuffer = normalizePcmChunk(arrayBuffer);+ if (pcmBuffer.byteLength === 0) {+ return;+ }++ const context = ensureTtsAudioContext();+ const source = context.createBufferSource();+ source.buffer = pcm16ToAudioBuffer(pcmBuffer, sampleRate);+ source.connect(context.destination);++ const startAt = Math.max(context.currentTime + 0.02, ttsNextPlayTime || 0);+ ttsNextPlayTime = startAt + source.buffer.duration;+ ttsSources.push(source);+ scheduleTtsFinishCheck(String(requestToken));+ source.onended = () => {+ ttsSources = ttsSources.filter(item => item !== source);+ maybeFinishTtsSpeech(String(requestToken));+ };+ source.start(startAt);+ }++ function scheduleTtsFinishCheck(requestId) {+ if (ttsFinishTimer) {+ clearTimeout(ttsFinishTimer);+ }++ let delayMs = 100;+ if (ttsAudioContext && ttsNextPlayTime > ttsAudioContext.currentTime) {+ delayMs = Math.max(100, (ttsNextPlayTime - ttsAudioContext.currentTime) * 1000 + 80);+ }++ ttsFinishTimer = setTimeout(() => {+ ttsFinishTimer = null;+ maybeFinishTtsSpeech(requestId);+ }, delayMs);+ }++ function maybeFinishTtsSpeech(requestId, { failed = false } = {}) {+ const ws = ttsWs;+ const activeRequestId = ws?._requestId || '';+ const hasQueuedAudio = ttsSources.length > 0;+ const serverStillStreaming = ws?._acceptingAudio && activeRequestId === requestId;+ const serverDone = ws?._serverDone && activeRequestId === requestId;++ if (serverStillStreaming || hasQueuedAudio) {+ return;+ }++ if ((String(ttsRequestToken) === requestId && serverDone) || failed) {+ if (ws && activeRequestId === requestId) {+ ws._requestId = '';+ ws._serverDone = false;+ }+ if (ttsFinishTimer) {+ clearTimeout(ttsFinishTimer);+ ttsFinishTimer = null;+ }+ ttsSpeaking = false;+ currentTtsItem = null;+ ttsPcmRemainder = null;+ updateTtsSpeakingDisplay('');+ maybeSpeakPendingTts();+ }+ }++ function startTtsSpeech(speechText, language) {+ const requestToken = ttsRequestToken;+ ttsSpeaking = true;+ scheduleVoiceListening();+ updateTtsSpeakingDisplay(speechText);+ ttsPcmRemainder = null;+ ttsNextPlayTime = 0;++ getTtsWebSocket().then(ws => {+ if (requestToken !== ttsRequestToken || !settings.ttsEnabled) return;+ ws._sampleRate = 24000;+ ws._requestId = '';+ ws._pendingRequestId = String(requestToken);+ ws._acceptingAudio = false;+ ws._serverDone = false;+ ws.send(JSON.stringify({+ type: 'speak',+ text: speechText,+ lang: language,+ voice: window.aliveUi?.voice || 'serena',+ session_id: sessionId,+ request_id: String(requestToken)+ }));+ }).catch(error => {+ if (requestToken === ttsRequestToken) {+ lastTtsEventKey = '';+ ttsSpeaking = false;+ currentTtsItem = null;+ updateTtsSpeakingDisplay('');+ console.warn('TTS playback failed:', error);+ updateStatus('Speech connection failed. Please retry.', 'disconnected');+ maybeSpeakPendingTts();+ }+ });+ }++ function speakVlmText(text, eventKey = '', metrics = null) {+ const speechText = String(text || '').trim();+ const speechEventKey = String(eventKey || '').trim();+ if (!settings.ttsEnabled || !speechText) {+ scheduleVoiceListening();+ return;+ }+ if (speechEventKey && speechEventKey === lastTtsEventKey) return;+ lastTtsEventKey = speechEventKey || `event:${++ttsEventSequence}`;+ if (isDuplexListening()) {+ // Do not resume an interrupted answer or speak over an utterance.+ const prompt = metrics?.user_prompt || '';+ if (duplexUserSpeaking || asrSendPromptWhenFinal+ || (duplexReplyGate.waiting && (!duplexReplyGate.prompt || prompt !== duplexReplyGate.prompt))+ || (duplexReplyGate.prompt && prompt && prompt !== duplexReplyGate.prompt)) return;+ }+ // A newer reply replaces all audio and remaining chunks of the old reply.+ stopTtsPlayback();+ const lang = resolveSpeechLanguage(speechText);+ for (const part of splitSpeechText(speechText)) pendingTtsQueue.push({text: part, lang});+ if (voiceModeEnabled && !isDuplexListening() && asrRecording && !asrHeardVoice) {+ // Idle listening yields to playback; never cut off an utterance.+ finishSpeech({ sendPrompt: false });+ }+ maybeSpeakPendingTts();+ }++ function clearVlmConversation() {+ closeTtsWebSocket();+ vlmHistory = [];+ backgroundTaskEntries.clear();+ backgroundSummaryEntries.clear();+ lastReadyBackgroundTaskId = '';+ lastText = '';+ lastTtsEventKey = '';+ lastHistoryKey = null;+ currentPromptText = '';+ pendingPromptEntry = null;++ resultText.classList.remove('fade');+ renderVlmHistory();++ videoOverlay.textContent = '';+ videoOverlay.classList.remove('show', 'top', 'bottom');++ currentPrompt.style.display = 'none';+ currentPrompt.textContent = '';+ metricsInline.style.display = 'flex';+ latencyValue.textContent = '0';+ avgLatencyValue.textContent = '0';+ countValue.textContent = '0';++ const requestPayloadDebug = document.getElementById('requestPayloadDebug');+ const requestPayloadContent = document.getElementById('requestPayloadContent');+ const responsePayloadDebug = document.getElementById('responsePayloadDebug');+ const responsePayloadContent = document.getElementById('responsePayloadContent');+ if (requestPayloadDebug) requestPayloadDebug.style.display = 'none';+ if (requestPayloadContent) requestPayloadContent.textContent = '';+ if (responsePayloadDebug) responsePayloadDebug.style.display = 'none';+ if (responsePayloadContent) responsePayloadContent.textContent = '';+ const memoryStateDebug = document.getElementById('memoryStateDebug');+ if (memoryStateDebug) memoryStateDebug.style.display = 'none';+ const midTermMemoryContent = document.getElementById('midTermMemoryContent');+ if (midTermMemoryContent) midTermMemoryContent.textContent = '';+ const longTermMemoryContent = document.getElementById('longTermMemoryContent');+ if (longTermMemoryContent) longTermMemoryContent.textContent = '';++ syncVlmToFullscreen();+ }++ function hasVisiblePrompt(entry) {+ return Boolean(entry?.prompt && entry.prompt.trim() && entry.prompt.trim() !== '--');+ }++ function createHistoryNodes(entry, animateResponse = false) {+ let promptDiv = null;+ if (hasVisiblePrompt(entry)) {+ promptDiv = document.createElement('div');+ promptDiv.className = 'result-prompt';+ promptDiv.textContent = cleanBackgroundQuestionText(entry.prompt.trim());+ }++ let responseDiv = null;+ if (entry.kind === 'background') {+ responseDiv = createBackgroundHistoryNode(entry, animateResponse);+ } else if (entry.response) {+ responseDiv = document.createElement('div');+ responseDiv.className = 'result-text';+ if (animateResponse && settings.popIn) {+ responseDiv.classList.add('new-message');+ if (settings.glow) {+ responseDiv.classList.add('with-glow');+ }+ }+ renderStandardResponseIntoElement(responseDiv, entry);+ }++ entry.promptElement = promptDiv;+ entry.responseElement = responseDiv;++ return { promptDiv, responseDiv };+ }++ function renderStandardResponseIntoElement(responseDiv, entry) {+ renderStandardRichContent(responseDiv, entry);+ appendBackgroundJumpButton(responseDiv, entry);+ requestAnimationFrame(() => lucide.createIcons());+ }++ function isBackgroundSummaryEntry(entry) {+ return entry?.kind === 'background_summary' ||+ Boolean(entry?.backgroundSummary) ||+ Boolean(resolveBackgroundJumpTaskId(entry));+ }++ function isForegroundHistoryEntry(entry) {+ return Boolean(entry) && entry.kind !== 'background' && !isBackgroundSummaryEntry(entry);+ }++ function formatInlineJsonAsMarkdown(text) {+ let source = String(text || '');+ const inlineBlocks = extractInlineJsonObjectCandidates(source)+ .sort((a, b) => b.start - a.start);++ inlineBlocks.forEach((candidate) => {+ let start = candidate.start;+ const prefix = source.slice(Math.max(0, start - 12), start);+ const jsonLabel = prefix.match(/(?:^|\s)json\s*$/i);+ if (jsonLabel) {+ start -= jsonLabel[0].length;+ }++ let prettyJson = candidate.text;+ try {+ prettyJson = JSON.stringify(JSON.parse(candidate.text), null, 2);+ } catch (err) {+ // Keep the original JSON string if prettifying fails.+ }++ const block = `\n\n\`\`\`json\n${prettyJson}\n\`\`\`\n`;+ source = `${source.slice(0, start).trimEnd()}${block}${source.slice(candidate.end).trimStart()}`;+ });++ return source.trim();+ }++ function renderBackgroundSummaryMarkdown(responseDiv, text) {+ responseDiv.innerHTML = '';+ responseDiv.classList.remove('standard-rich-response');+ responseDiv.classList.add('background-summary-message');++ const label = document.createElement('div');+ label.className = 'background-summary-label';+ label.innerHTML = '<svg class="alive-mark" viewBox="280 126 515 450" aria-hidden="true" focusable="false"><image href="/images/alive.png?v=1" x="0" y="0" width="2172" height="724" /></svg><span>Summary</span>';++ const body = document.createElement('div');+ body.className = 'background-summary-body markdown-rendered';+ renderTextIntoElement(body, String(text || '').trim());++ responseDiv.appendChild(label);+ responseDiv.appendChild(body);+ }++ function renderStandardRichContent(responseDiv, entry) {+ const text = entry?.response || '';+ if (isBackgroundSummaryEntry(entry)) {+ renderBackgroundSummaryMarkdown(responseDiv, text);+ return;+ }++ const chart = parseBackgroundChart(text);+ const htmlDetails = extractBackgroundHtmlDetails(text);+ const html = htmlDetails.html;++ if (!chart && !html) {+ responseDiv.classList.remove('standard-rich-response');+ if (!isBackgroundSummaryEntry(entry)) {+ responseDiv.classList.remove('background-summary-message');+ }+ renderTextIntoElement(responseDiv, text);+ return;+ }++ responseDiv.innerHTML = '';+ responseDiv.classList.add('standard-rich-response');+ responseDiv.classList.remove('background-summary-message');+ const explanation = extractBackgroundExplanation(text);+ if (explanation) {+ const explanationElement = document.createElement('div');+ explanationElement.className = 'standard-rich-explanation markdown-rendered';+ renderTextIntoElement(explanationElement, explanation);+ responseDiv.appendChild(explanationElement);+ }++ if (chart) {+ const chartElement = document.createElement('div');+ chartElement.className = 'standard-rich-chart';+ renderBackgroundChartView(chartElement, chart);+ responseDiv.appendChild(chartElement);+ }++ if (html) {+ const htmlElement = document.createElement('div');+ htmlElement.className = 'standard-rich-html';+ renderBackgroundHtmlView(htmlElement, html, {+ incomplete: htmlDetails.incomplete+ });+ responseDiv.appendChild(htmlElement);+ }+ }++ function getLatestReadyBackgroundEntry() {+ if (lastReadyBackgroundTaskId && backgroundTaskEntries.has(lastReadyBackgroundTaskId)) {+ const entry = backgroundTaskEntries.get(lastReadyBackgroundTaskId);+ if (entry?.ready && entry.status === 'ready') {+ return entry;+ }+ }++ for (let index = vlmHistory.length - 1; index >= 0; index -= 1) {+ const entry = vlmHistory[index];+ if (entry?.kind === 'background' && entry.ready && entry.status === 'ready') {+ return entry;+ }+ }+ return null;+ }++ function cleanBackgroundQuestionText(question) {+ return String(question || '')+ .replace(/^\s*请(?:回答|解答)这道(?:简答题|数学题|题目|问题)[,,、\s]*(?:并(?:提供|给出)必要的推理过程和最终答案)?[::]\s*/u, '')+ .replace(/\[User Query[^\]]*\]\s*/gi, '')+ .replace(/^Prompt:\s*/i, '')+ .replace(/[ \t]{2,}/g, ' ')+ .trim();+ }++ function isBackgroundWaitingNotice(text) {+ const value = String(text || '').trim();+ return /(?:需要|正在)调用后台模型|后台模型(?:正在)?处理|请稍等/.test(value)+ && /继续(?:向我)?提问|期间/.test(value);+ }++ function resolveBackgroundJumpTaskId(entry) {+ const directTaskId = entry?.backgroundHandoff?.task_id;+ if (directTaskId && backgroundTaskEntries.has(String(directTaskId))) {+ return String(directTaskId);+ }++ return '';+ }++ function appendBackgroundJumpButton(responseDiv, entry) {+ if (!isBackgroundSummaryEntry(entry)) {+ return;+ }+ const taskId = resolveBackgroundJumpTaskId(entry);+ if (!taskId) {+ return;+ }++ const backgroundEntry = backgroundTaskEntries.get(String(taskId));+ const questionText = cleanBackgroundQuestionText(+ entry?.backgroundHandoff?.question ||+ backgroundEntry?.question ||+ ''+ );++ const row = document.createElement('div');+ row.className = 'background-jump-row';+ row.dataset.backgroundTaskId = taskId;+ if (questionText) {+ const question = document.createElement('div');+ question.className = 'background-jump-question';+ const label = document.createElement('span');+ label.className = 'background-jump-question-label';+ label.textContent = 'Related question';+ const value = document.createElement('span');+ value.className = 'background-jump-question-text';+ value.textContent = questionText;+ question.appendChild(label);+ question.appendChild(value);+ row.appendChild(question);+ }+ const button = document.createElement('button');+ button.type = 'button';+ button.className = 'background-jump-button';+ button.dataset.backgroundTaskId = taskId;+ button.innerHTML = '<i data-lucide="corner-down-left"></i><span>Jump</span>';+ button.title = 'Jump to the background result';+ button.addEventListener('click', (event) => {+ event.preventDefault();+ event.stopPropagation();+ jumpToBackgroundResult(button.dataset.backgroundTaskId || taskId);+ });+ row.appendChild(button);+ responseDiv.appendChild(row);+ }++ function findBackgroundResultElement(taskId) {+ const expectedTaskId = String(taskId || '');+ if (!expectedTaskId) return null;++ const domTarget = Array.from(document.querySelectorAll('[data-background-result-task-id]'))+ .find(element => element.dataset.backgroundResultTaskId === expectedTaskId);+ if (domTarget) {+ return domTarget;+ }++ const entry = backgroundTaskEntries.get(expectedTaskId);+ return entry?.responseElement || null;+ }++ function getScrollableAncestors(element) {+ const ancestors = [];+ let node = element?.parentElement || null;+ while (node && node !== document.body) {+ const style = window.getComputedStyle(node);+ const canScroll = /(auto|scroll|overlay)/.test(style.overflowY)+ && node.scrollHeight > node.clientHeight + 1;+ if (canScroll) {+ ancestors.push(node);+ }+ node = node.parentElement;+ }++ const root = document.scrollingElement || document.documentElement;+ if (root) {+ ancestors.push(root);+ }+ return ancestors;+ }++ function scrollElementIntoContainer(target, container, behavior = 'smooth') {+ if (!target || !container) return;+ const containerRect = container.getBoundingClientRect();+ const targetRect = target.getBoundingClientRect();+ const targetTop = container.scrollTop+ + targetRect.top+ - containerRect.top+ - 16;+ container.scrollTo({+ top: Math.max(0, targetTop),+ behavior+ });+ }++ function flashBackgroundJumpTarget(target) {+ if (!target) return;+ target.classList.add('jump-highlight');+ setTimeout(() => target.classList.remove('jump-highlight'), 1800);+ }++ function findBackgroundOriginEntry(entry) {+ const question = cleanBackgroundQuestionText(entry?.question || '');+ if (!question) return null;+ for (let index = vlmHistory.length - 1; index >= 0; index -= 1) {+ const candidate = vlmHistory[index];+ if (!isForegroundHistoryEntry(candidate)) continue;+ if (cleanBackgroundQuestionText(candidate.prompt || '') === question) {+ return candidate;+ }+ }+ return null;+ }++ function jumpToBackgroundOrigin(entry) {+ const originEntry = findBackgroundOriginEntry(entry);+ const target = originEntry?.promptElement || null;+ if (!target) return;++ const historyContainer = document.getElementById('resultTextContent');+ if (historyContainer && historyContainer.contains(target)) {+ scrollElementIntoContainer(target, historyContainer, 'smooth');+ }+ getScrollableAncestors(target).forEach(container => {+ scrollElementIntoContainer(target, container, 'smooth');+ });+ target.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' });+ flashBackgroundJumpTarget(target);+ }++ function jumpToBackgroundResult(taskId) {+ const normalizedTaskId = String(taskId || '');+ const entry = backgroundTaskEntries.get(normalizedTaskId);+ if (!entry) return;+ entry.expanded = true;+ renderVlmHistory();++ const performJump = (attempt = 0) => {+ const target = findBackgroundResultElement(normalizedTaskId);+ if (!target) {+ if (attempt < 3) {+ setTimeout(() => performJump(attempt + 1), 80);+ }+ return;+ }++ const behavior = attempt === 0 ? 'smooth' : 'auto';+ const historyContainer = document.getElementById('resultTextContent');+ if (historyContainer && historyContainer.contains(target)) {+ scrollElementIntoContainer(target, historyContainer, behavior);+ }+ getScrollableAncestors(target).forEach(container => {+ scrollElementIntoContainer(target, container, behavior);+ });+ target.scrollIntoView({ behavior, block: 'start', inline: 'nearest' });+ flashBackgroundJumpTarget(target);++ if (attempt < 2) {+ setTimeout(() => performJump(attempt + 1), attempt === 0 ? 180 : 360);+ }+ };++ requestAnimationFrame(() => {+ requestAnimationFrame(() => performJump(0));+ });+ }++ function createBackgroundHistoryNode(entry, animateResponse = false) {+ const responseDiv = document.createElement('div');+ responseDiv.className = 'result-text background-result';+ if (entry.taskId) {+ responseDiv.dataset.backgroundResultTaskId = String(entry.taskId);+ }+ if (animateResponse && settings.popIn) {+ responseDiv.classList.add('new-message');+ }++ const shell = document.createElement('div');+ shell.className = 'background-result-shell';++ const header = document.createElement('div');+ header.className = 'background-result-header';++ const icon = document.createElement('div');+ icon.className = 'background-result-icon';+ icon.innerHTML = '<svg class="alive-mark" viewBox="280 126 515 450" aria-hidden="true" focusable="false"><image href="/images/alive.png?v=1" x="0" y="0" width="2172" height="724" /></svg>';++ const title = document.createElement('div');+ title.className = 'background-result-title';+ title.textContent = entry.status === 'error'+ ? 'Background model failed'+ : entry.ready+ ? 'Background result is ready. View it now?'+ : 'Background model is working...';++ if (entry.question) {+ const question = document.createElement('div');+ question.className = 'background-result-question';+ question.textContent = entry.question;+ title.appendChild(question);+ }++ const action = document.createElement('button');+ action.type = 'button';+ action.className = 'background-result-action';+ action.textContent = entry.expanded ? 'Collapse' : entry.ready ? 'View' : 'Waiting';+ action.disabled = !entry.ready && entry.status !== 'error';+ action.addEventListener('click', () => {+ entry.expanded = !entry.expanded;+ renderVlmHistory();+ });++ const originEntry = findBackgroundOriginEntry(entry);+ let originAction = null;+ if (originEntry) {+ originAction = document.createElement('button');+ originAction.type = 'button';+ originAction.className = 'background-result-action background-origin-action';+ originAction.innerHTML = '<i data-lucide="corner-up-left"></i>';+ originAction.title = 'Jump to the original question';+ originAction.addEventListener('click', (event) => {+ event.preventDefault();+ event.stopPropagation();+ jumpToBackgroundOrigin(entry);+ });+ }++ header.appendChild(icon);+ header.appendChild(title);+ if (originAction) {+ header.appendChild(originAction);+ }+ header.appendChild(action);+ shell.appendChild(header);++ if (entry.expanded) {+ const content = document.createElement('div');+ content.className = 'result-text-content markdown-rendered';+ if (entry.status === 'error') {+ content.textContent = entry.error || 'Background model failed.';+ } else {+ renderBackgroundRichContent(content, entry.response || '', entry.rich || null);+ }+ shell.appendChild(content);+ }++ responseDiv.appendChild(shell);+ entry.responseElement = responseDiv;+ requestAnimationFrame(() => lucide.createIcons());+ return responseDiv;+ }++ function appendVlmHistoryEntry(entry, { animateLast = false } = {}) {+ const contentDiv = document.getElementById('resultTextContent');+ if (!contentDiv) return;++ const shouldAutoScroll = isVlmHistoryNearBottom(contentDiv);+ const { promptDiv, responseDiv } = createHistoryNodes(entry, animateLast);++ if (promptDiv) {+ contentDiv.appendChild(promptDiv);+ }+ if (responseDiv) {+ contentDiv.appendChild(responseDiv);+ }+ resultText.style.display = settings.overlayPosition === 'none' ? 'flex' : 'none';++ if (shouldAutoScroll) {+ scrollVlmHistoryToBottom(contentDiv);+ }++ const videoCard = document.getElementById('videoCard');+ if (videoCard && videoCard.classList.contains('fullscreen')) {+ syncVlmToFullscreen();+ }+ }++ function renderVlmHistory({ animateLast = false } = {}) {+ const contentDiv = document.getElementById('resultTextContent');+ if (!contentDiv) return;++ const shouldAutoScroll = isVlmHistoryNearBottom(contentDiv);++ contentDiv.innerHTML = '';+ const fragment = document.createDocumentFragment();+ vlmHistory.forEach((entry, index) => {+ const { promptDiv, responseDiv } = createHistoryNodes(+ entry,+ animateLast && index === vlmHistory.length - 1+ );+ if (promptDiv) {+ fragment.appendChild(promptDiv);+ }+ if (responseDiv) {+ fragment.appendChild(responseDiv);+ }+ });+ contentDiv.appendChild(fragment);++ resultText.style.display = vlmHistory.length > 0 && settings.overlayPosition === 'none' ? 'flex' : 'none';+ if (shouldAutoScroll) {+ scrollVlmHistoryToBottom(contentDiv);+ }++ // Auto-sync to fullscreen overlay if in fullscreen mode+ const videoCard = document.getElementById('videoCard');+ if (videoCard && videoCard.classList.contains('fullscreen')) {+ syncVlmToFullscreen();+ }+ }++ function appendPromptHistoryEntry(prompt) {+ const latest = vlmHistory[vlmHistory.length - 1];+ const cleanPrompt = cleanBackgroundQuestionText(prompt);++ if (latest && latest.pending && latest.prompt === cleanPrompt) {+ pendingPromptEntry = latest;+ return;+ }++ const entry = {+ key: `prompt:${Date.now()}:${Math.random().toString(36).slice(2)}`,+ prompt: cleanPrompt,+ response: '',+ rawText: '',+ pending: true+ };+ vlmHistory.push(entry);+ pendingPromptEntry = entry;+ appendVlmHistoryEntry(entry);+ }++ function resolveBackgroundSummaryText(data) {+ return String(data?.summary_text || 'The background result is ready.').trim();+ }++ function resolveBackgroundSummaryDetailText(data) {+ const direct = String(data?.background_summary || '').trim();+ if (direct) return direct;+ const text = String(data?.text || '').trim();+ if (text) return text;+ const handoff = data?.interaction_handoff;+ if (handoff && typeof handoff === 'object') {+ return String(handoff.summary || '').trim();+ }+ return '';+ }++ function updateBackgroundSummaryEntry(data, summaryText = null, rawText = null) {+ const taskId = String(data?.task_id || '').trim();+ const summary = String(summaryText ?? resolveBackgroundSummaryText(data)).trim();+ const detailText = String(rawText ?? resolveBackgroundSummaryDetailText(data)).trim();+ if (!taskId || !summary) {+ return null;+ }++ let entry = backgroundSummaryEntries.get(taskId);+ if (!entry) {+ entry = {+ key: `background-summary:${taskId}`,+ kind: 'background_summary',+ contextExcluded: true,+ prompt: '',+ response: summary,+ rawText: detailText || summary,+ backgroundSummary: true,+ backgroundHandoff: {+ task_id: taskId,+ question: cleanBackgroundQuestionText(data.question || '')+ }+ };+ backgroundSummaryEntries.set(taskId, entry);+ } else {+ entry.kind = 'background_summary';+ entry.contextExcluded = true;+ entry.backgroundSummary = true;+ entry.response = summary;+ entry.rawText = detailText || summary;+ entry.backgroundHandoff = {+ task_id: taskId,+ question: cleanBackgroundQuestionText(data.question || entry.backgroundHandoff?.question || '')+ };+ }+ return entry;+ }++ function appendOrUpdateBackgroundSummaryEntry(data) {+ updateBackgroundSummaryEntry(data);+ }++ function appendOrUpdateBackgroundSummaryHistoryEntry(data, summaryText = null, rawText = null) {+ const entry = updateBackgroundSummaryEntry(data, summaryText, rawText);+ if (!entry) {+ return null;+ }++ const alreadyInHistory = vlmHistory.includes(entry);+ if (!alreadyInHistory) {+ vlmHistory.push(entry);+ appendVlmHistoryEntry(entry, { animateLast: true });+ } else if (entry.responseElement) {+ renderStandardResponseIntoElement(entry.responseElement, entry);+ } else {+ renderVlmHistory({ animateLast: true });+ }+ return entry;+ }++ function appendOrUpdateBackgroundEntry(data) {+ const taskId = String(data.task_id || `background:${Date.now()}`);+ let entry = backgroundTaskEntries.get(taskId);+ const isReady = data.type === 'background_result_ready';+ const isError = data.type === 'background_result_error';++ if (!entry) {+ entry = {+ key: `background:${taskId}`,+ kind: 'background',+ contextExcluded: true,+ taskId,+ question: data.question || '',+ response: '',+ rawText: '',+ error: '',+ ready: false,+ expanded: false,+ status: 'running'+ };+ backgroundTaskEntries.set(taskId, entry);+ vlmHistory.push(entry);+ }++ entry.question = data.question || entry.question || '';+ entry.foregroundText = data.foreground_text || entry.foregroundText || '';+ entry.metrics = data.metrics || entry.metrics || null;+ entry.model = data.model || entry.model || '';+ entry.contextExcluded = true;++ if (isReady) {+ entry.response = data.text || '';+ entry.rawText = data.text || '';+ entry.rich = data.rich || null;+ entry.ready = true;+ entry.status = 'ready';+ lastReadyBackgroundTaskId = taskId;+ appendOrUpdateBackgroundSummaryHistoryEntry(data);+ } else if (isError) {+ entry.error = data.error || 'Background model failed.';+ entry.ready = true;+ entry.status = 'error';+ }++ renderVlmHistory({ animateLast: true });+ }++ function applyBackgroundConfig(config) {+ if (!config) return;+ backgroundConfig = config;+ if (backgroundEnabledToggle && typeof config.enabled === 'boolean') {+ backgroundEnabledToggle.checked = config.enabled;+ }+ if (backgroundFrameMultiplier && config.frame_multiplier != null) {+ backgroundFrameMultiplier.value = String(config.frame_multiplier);+ }+ if (backgroundMaxFrames) {+ backgroundMaxFrames.value = String(config.max_frames || 100);+ }+ }++ function sendBackgroundConfig() {+ if (!websocket || websocket.readyState !== WebSocket.OPEN) return;+ websocket.send(JSON.stringify({+ type: 'update_background_config',+ enabled: !!backgroundEnabledToggle?.checked,+ frame_multiplier: parseInt(backgroundFrameMultiplier?.value, 10) || 2,+ max_frames: parseInt(backgroundMaxFrames?.value, 10) || 100+ }));+ }++ // Function to update result text (handles both markdown and plain text)+ function updateResultText(text, metrics = null, backgroundHandoff = null) {+ const displayText = getVlmDisplayText(text);+ if (displayText.trim() && isDuplexListening() && !duplexUserSpeaking && !asrSendPromptWhenFinal+ && duplexReplyGate.prompt && metrics?.user_prompt === duplexReplyGate.prompt) {+ duplexReplyGate.waiting = false;+ }+ if (voiceAwaitingPrompt !== null && metrics?.user_prompt === voiceAwaitingPrompt) {+ voiceAwaitingPrompt = null;+ clearTimeout(voiceReplyTimer);+ voiceReplyTimer = null;+ }+ if (displayText.trim() === '') {+ resultText.style.display = vlmHistory.length > 0 && settings.overlayPosition === 'none' ? 'flex' : 'none';+ scheduleVoiceListening();+ return;+ }++ const resolvedBackgroundHandoff = isBackgroundWaitingNotice(displayText)+ ? null+ : (backgroundHandoff || null);+ const prompt = currentPromptText || '';+ const hasInferenceKey = metrics?.total_inferences != null;+ const historyKey = hasInferenceKey+ ? `count:${metrics.total_inferences}`+ : `text:${text}`;+ const ttsEventKey = hasInferenceKey+ ? historyKey+ : `event:${++ttsEventSequence}`;+ speakVlmText(displayText, ttsEventKey, metrics);+ const pendingEntry = pendingPromptEntry && vlmHistory.includes(pendingPromptEntry)+ && isForegroundHistoryEntry(pendingPromptEntry)+ ? pendingPromptEntry+ : null;++ if (resolvedBackgroundHandoff?.task_id) {+ appendOrUpdateBackgroundSummaryHistoryEntry(+ {+ task_id: resolvedBackgroundHandoff.task_id,+ question: resolvedBackgroundHandoff.question || ''+ },+ displayText,+ text+ );+ syncVlmToFullscreen();+ return;+ }++ const latest = [...vlmHistory].reverse().find(isForegroundHistoryEntry);++ if (latest && latest.key === historyKey) {+ const handoffChanged = JSON.stringify(latest.backgroundHandoff || null)+ !== JSON.stringify(resolvedBackgroundHandoff || latest.backgroundHandoff || null);+ if (latest.rawText === text && latest.response === displayText && !handoffChanged) {+ return;+ }+ const contentDiv = document.getElementById('resultTextContent');+ const shouldAutoScroll = isVlmHistoryNearBottom(contentDiv);+ latest.rawText = text;+ latest.response = displayText;+ latest.backgroundHandoff = resolvedBackgroundHandoff || latest.backgroundHandoff || null;+ if (latest.responseElement) {+ renderStandardResponseIntoElement(latest.responseElement, latest);+ } else {+ renderVlmHistory();+ }+ if (shouldAutoScroll) {+ scrollVlmHistoryToBottom(contentDiv);+ }+ } else if (pendingEntry) {+ const contentDiv = document.getElementById('resultTextContent');+ const shouldAutoScroll = isVlmHistoryNearBottom(contentDiv);+ pendingEntry.key = historyKey;+ pendingEntry.response = displayText;+ pendingEntry.rawText = text;+ pendingEntry.backgroundHandoff = resolvedBackgroundHandoff || pendingEntry.backgroundHandoff || null;+ pendingEntry.pending = false;+ lastHistoryKey = historyKey;+ currentPromptText = '';+ pendingPromptEntry = null;++ if (pendingEntry.responseElement) {+ renderStandardResponseIntoElement(pendingEntry.responseElement, pendingEntry);+ } else if (pendingEntry.promptElement) {+ const responseDiv = document.createElement('div');+ responseDiv.className = 'result-text';+ if (settings.popIn) {+ responseDiv.classList.add('new-message');+ if (settings.glow) {+ responseDiv.classList.add('with-glow');+ }+ }+ renderStandardResponseIntoElement(responseDiv, pendingEntry);+ pendingEntry.responseElement = responseDiv;+ pendingEntry.promptElement.insertAdjacentElement('afterend', responseDiv);+ } else {+ renderVlmHistory({ animateLast: true });+ }++ if (shouldAutoScroll) {+ scrollVlmHistoryToBottom(contentDiv);+ }+ } else if (historyKey !== lastHistoryKey && (hasInferenceKey || text !== lastText)) {+ const entry = {+ key: historyKey,+ prompt,+ response: displayText,+ rawText: text,+ backgroundHandoff: resolvedBackgroundHandoff || null+ };+ vlmHistory.push(entry);+ lastHistoryKey = historyKey;+ currentPromptText = '';+ appendVlmHistoryEntry(entry, { animateLast: true });+ }++ syncVlmToFullscreen();+ }++ function logLatencyBreakdown(metrics) {+ if (!metrics || !metrics.latency_breakdown_ms) return;+ const inferenceCount = Number(metrics.total_inferences) || 0;+ if (inferenceCount <= lastLoggedInferenceCount) return;+ lastLoggedInferenceCount = inferenceCount;++ const toMs = (value) => Number.isFinite(Number(value)) ? Number(value).toFixed(2) : '--';+ const frameTiming = metrics.frame_timing_ms || {};+ const vlmTiming = metrics.latency_breakdown_ms || {};+ console.groupCollapsed(+ `[VLM latency] #${inferenceCount} total ${toMs(metrics.last_latency_ms)} ms`+ );+ console.table([+ { phase: 'Frame to ndarray', scope: 'Before Latency', ms: toMs(frameTiming.frame_to_ndarray_ms) },+ { phase: 'Frame copy', scope: 'Before Latency', ms: toMs(frameTiming.frame_copy_ms) },+ { phase: 'BGR to RGB + PIL', scope: 'Before Latency', ms: toMs(frameTiming.bgr_to_rgb_pil_ms) },+ { phase: 'Pre-VLM subtotal', scope: 'Before Latency', ms: toMs(frameTiming.pre_vlm_total_ms) },+ { phase: 'JPEG encode', scope: 'Latency', ms: toMs(vlmTiming.jpeg_encode_ms) },+ { phase: 'Base64 encode', scope: 'Latency', ms: toMs(vlmTiming.base64_encode_ms) },+ { phase: 'Request build/debug payload', scope: 'Latency', ms: toMs(vlmTiming.request_build_ms) },+ { phase: 'API call + VLM inference', scope: 'Latency', ms: toMs(vlmTiming.api_call_ms) },+ { phase: 'Response payload record', scope: 'Latency', ms: toMs(vlmTiming.response_payload_ms) },+ { phase: 'Response extract', scope: 'Latency', ms: toMs(vlmTiming.response_extract_ms) },+ { phase: 'Latency total', scope: 'Latency', ms: toMs(vlmTiming.total_ms) },+ ]);+ console.groupEnd();+ }++ // Enumerate cameras on page load+ enumerateCameras();++ // Start the redesigned page in light mode once, then remember explicit choices.+ function applyTheme(theme) {+ // theme can be 'light', 'dark', or 'auto'+ if (theme === 'light') {+ document.body.classList.add('light-theme');+ themeIcon.innerHTML = '<i data-lucide="sun"></i>';+ themeText.textContent = 'Light';+ } else if (theme === 'dark') {+ document.body.classList.remove('light-theme');+ themeIcon.innerHTML = '<i data-lucide="moon"></i>';+ themeText.textContent = 'Dark';+ } else { // 'auto' - follow OS preference+ const prefersLight = window.matchMedia('(prefers-color-scheme: light)').matches;+ if (prefersLight) {+ document.body.classList.add('light-theme');+ } else {+ document.body.classList.remove('light-theme');+ }+ // Always show monitor icon for AUTO mode+ themeIcon.innerHTML = '<i data-lucide="monitor"></i>';+ themeText.textContent = 'Auto';+ }+ lucide.createIcons();++ }++ // Theme Toggle: cycles through Auto -> Light -> Dark -> Auto+ jdLogo.addEventListener('click', () => {+ window.location.reload();+ });++ jdLogo.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ window.location.reload();+ }+ });++ themeToggle.addEventListener('click', () => {+ const currentTheme = demoStorage.getItem('theme') || 'light';+ let nextTheme;++ if (currentTheme === 'auto' || !currentTheme) {+ nextTheme = 'light';+ } else if (currentTheme === 'light') {+ nextTheme = 'dark';+ } else { // dark+ nextTheme = 'auto';+ }++ demoStorage.setItem('theme', nextTheme);+ applyTheme(nextTheme);+ });++ const themeVersion = 'alive-white-1';+ if (demoStorage.getItem('themeVersion') !== themeVersion) {+ demoStorage.setItem('theme', 'light');+ demoStorage.setItem('themeVersion', themeVersion);+ }+ const savedTheme = demoStorage.getItem('theme');+ applyTheme(['light', 'dark', 'auto'].includes(savedTheme) ? savedTheme : 'light');++ // Listen for OS preference changes when in 'auto' mode+ const colorSchemeQuery = window.matchMedia('(prefers-color-scheme: light)');+ colorSchemeQuery.addEventListener('change', (e) => {+ const currentTheme = demoStorage.getItem('theme');+ // Only update if user hasn't manually set a preference+ if (currentTheme === 'auto') {+ applyTheme('auto');+ }+ });++ // Load saved colorful UI accents setting (default: disabled for clean two-tone system)+ const colorfulFocusToggle = document.getElementById('colorfulFocusToggle');+ const colorfulFocusSaved = demoStorage.getItem('colorfulFocus');+ if (colorfulFocusSaved === 'true') {+ document.body.classList.add('colorful-focus');+ colorfulFocusToggle.checked = true;+ } else {+ // Default: neutral white/gray icons and focus glows with red flash+ document.body.classList.remove('colorful-focus');+ colorfulFocusToggle.checked = false;+ }++ // Settings Modal+ const settingsBtn = document.getElementById('settingsBtn');+ const settingsModal = document.getElementById('settingsModal');+ const settingsClose = document.getElementById('settingsClose');+ const popInToggle = document.getElementById('popInToggle');+ const glowToggle = document.getElementById('glowToggle');+ const fadeToggle = document.getElementById('fadeToggle');+ const overlayPosition = document.getElementById('overlayPosition');+ const layoutOrder = document.getElementById('layoutOrder');+ const videoOverlay = document.getElementById('videoOverlay');++ // Migrate older independent EN/ZH settings to the shared Auto default once.+ if (demoStorage.getItem('voiceDefaultsVersion') !== 'unified-auto-v3') {+ demoStorage.setItem('voiceLanguage', 'auto');+ demoStorage.setItem('voiceDefaultsVersion', 'unified-auto-v3');+ }+ const savedVoiceLanguage = ['auto', 'zh', 'en'].includes(demoStorage.getItem('voiceLanguage'))+ ? demoStorage.getItem('voiceLanguage') : 'auto';+ // Settings state+ const settings = {+ popIn: demoStorage.getItem('popIn') !== 'false',+ glow: demoStorage.getItem('glow') !== 'false',+ fade: demoStorage.getItem('fade') !== 'false',+ overlayPosition: demoStorage.getItem('overlayPosition') || 'none',+ layoutOrder: demoStorage.getItem('layoutOrder') || 'vlm-first',+ ttsEnabled: false,+ fullDuplex: false,+ asrLanguage: savedVoiceLanguage,+ ttsLanguage: savedVoiceLanguage+ };++ // Load saved settings+ popInToggle.checked = settings.popIn;+ glowToggle.checked = settings.glow;+ fadeToggle.checked = settings.fade;+ overlayPosition.value = settings.overlayPosition;+ layoutOrder.value = settings.layoutOrder;+ if (ttsEnabledToggle) {+ ttsEnabledToggle.checked = settings.ttsEnabled;+ ttsEnabledToggle.disabled = true;+ }+ fullDuplexToggle.checked = settings.fullDuplex;+ fullDuplexToggle.addEventListener('change', () => setFullDuplex(fullDuplexToggle.checked));++ function isDuplexListening() {+ return settings.fullDuplex && voiceModeEnabled;+ }++ function resetDuplexDetection() {+ duplexUserSpeaking = false;+ duplexOnsetSamples = duplexPrerollSamples = 0;+ duplexPreroll = [];+ }++ function setFullDuplex(enabled) {+ settings.fullDuplex = Boolean(enabled);+ fullDuplexToggle.checked = settings.fullDuplex;+ duplexReplyGate = { prompt: null, waiting: false };+ resetDuplexDetection();+ if (isDuplexListening()) {+ // Keep any utterance already in progress when enabling the option.+ duplexUserSpeaking = asrHeardVoice && isSpeechActive();+ if (duplexUserSpeaking) stopTtsPlayback();+ } else if (voiceModeEnabled && !asrHeardVoice && (ttsSpeaking || voiceAwaitingPrompt !== null)) {+ finishSpeech({ sendPrompt: false });+ }+ maybeSpeakPendingTts();+ scheduleVoiceListening();+ }++ function resolveSpeechLanguage(text) {+ return settings.ttsLanguage === 'auto'+ ? (/[\u3400-\u9fff]/u.test(text) ? 'zh' : 'en') : settings.ttsLanguage;+ }++ function syncVoiceLanguageTabs() {+ voiceLanguageTabs.forEach(tab => {+ const selected = tab.dataset.language === settings.asrLanguage;+ tab.setAttribute('aria-checked', String(selected));+ tab.tabIndex = selected ? 0 : -1;+ });+ }++ function setVoiceLanguage(language) {+ if (!['auto', 'zh', 'en'].includes(language) || language === settings.asrLanguage) return;+ // Retain only the current reply; replay its current chunk in the new voice.+ const remaining = [currentTtsItem, ...pendingTtsQueue].filter(Boolean);+ closeTtsWebSocket();+ settings.asrLanguage = settings.ttsLanguage = language;+ demoStorage.setItem('voiceLanguage', language);+ finishSpeech({ sendPrompt: false });+ pendingTtsQueue = remaining.map(item => ({text: item.text, lang: resolveSpeechLanguage(item.text)}));+ syncVoiceLanguageTabs();+ syncSpeechButtons();+ maybeSpeakPendingTts();+ scheduleVoiceListening();+ }+ voiceLanguageTabs.forEach((tab, index) => {+ tab.addEventListener('click', () => setVoiceLanguage(tab.dataset.language));+ tab.addEventListener('keydown', event => {+ if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) return;+ event.preventDefault();+ const offset = ['ArrowLeft', 'ArrowUp'].includes(event.key) ? -1 : 1;+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? 2 : (index + offset + 3) % 3;+ voiceLanguageTabs[next].focus();+ setVoiceLanguage(voiceLanguageTabs[next].dataset.language);+ });+ });+ syncVoiceLanguageTabs();++ async function refreshVoiceCapabilities() {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), 10000);+ try {+ const response = await fetch('/api/voice/status', { signal: controller.signal });+ if (!response.ok) throw new Error('Voice service unavailable');+ const state = await response.json();+ voiceCapabilities = { asr: state.asr?.available === true, tts: state.tts?.available === true };+ } catch (error) {+ voiceCapabilities = { asr: false, tts: false };+ } finally {+ clearTimeout(timer);+ }+ ttsEnabledToggle.disabled = !voiceCapabilities.tts;+ if (!voiceCapabilities.tts && settings.ttsEnabled) setTtsEnabled(false);+ if (voiceModeEnabled && !voiceCapabilities.asr) {+ stopVoiceMode('Voice service unavailable. Click to retry.');+ }+ document.getElementById('voiceStatus').textContent = voiceCapabilities.asr && voiceCapabilities.tts+ ? 'English and Chinese voice ready'+ : voiceCapabilities.tts ? 'Microphone unavailable; sound and text input are ready'+ : voiceCapabilities.asr ? 'Microphone ready; sound is unavailable'+ : 'Voice unavailable; use text input';+ updatePromptAvailability();+ maybeSpeakPendingTts();+ }+ refreshVoiceCapabilities();+ setInterval(refreshVoiceCapabilities, 30000);++ // Apply overlay position+ function applyOverlayPosition(position) {+ videoOverlay.classList.remove('show', 'top', 'bottom');+ const resultText = document.getElementById('resultText');+ const hasDisplayText = (vlmHistory[vlmHistory.length - 1]?.response || getVlmDisplayText(lastText)).trim() !== '';++ if (position !== 'none') {+ // Overlay enabled - show on video, hide response balloon (keep prompt visible)+ if (hasDisplayText) {+ videoOverlay.classList.add('show', position);+ }+ resultText.style.display = 'none';+ } else {+ // Overlay disabled - hide from video, show response balloon+ resultText.style.display = hasDisplayText ? 'flex' : 'none';+ }+ }+ applyOverlayPosition(settings.overlayPosition);++ // Apply layout order+ function isMobileLayout() {+ return window.matchMedia('(max-width: 768px)').matches;+ }++ function isPressToTalkLayout() {+ return isMobileLayout() && mobileVoiceMode;+ }++ function applyLayoutOrder(order) {+ const mainContent = document.querySelector('.main-content');+ const videoCard = document.querySelector('.video-card');+ const resultCard = document.getElementById('vlmOutputCard');++ if (!mainContent || !videoCard || !resultCard) {+ return;+ }++ if (isMobileLayout()) {+ mainContent.insertBefore(videoCard, resultCard);+ } else if (order === 'vlm-first') {+ // Conversation at top, Camera below (default)+ mainContent.insertBefore(resultCard, videoCard);+ } else {+ // Camera at top, Conversation below+ mainContent.insertBefore(videoCard, resultCard);+ }+ }+ applyLayoutOrder(settings.layoutOrder);++ window.matchMedia('(max-width: 768px)').addEventListener('change', () => {+ applyLayoutOrder(settings.layoutOrder);+ updatePromptAvailability();+ syncSpeechButtons();+ });++ // Open settings modal+ settingsBtn.addEventListener('click', () => {+ settingsModal.classList.add('show');+ });++ // Close settings modal+ settingsClose.addEventListener('click', () => {+ settingsModal.classList.remove('show');+ });++ // Close modal when clicking outside+ settingsModal.addEventListener('click', (e) => {+ if (e.target === settingsModal) {+ settingsModal.classList.remove('show');+ }+ });++ // Handle settings changes+ popInToggle.addEventListener('change', (e) => {+ settings.popIn = e.target.checked;+ demoStorage.setItem('popIn', settings.popIn);+ });++ glowToggle.addEventListener('change', (e) => {+ settings.glow = e.target.checked;+ demoStorage.setItem('glow', settings.glow);+ });++ fadeToggle.addEventListener('change', (e) => {+ settings.fade = e.target.checked;+ demoStorage.setItem('fade', settings.fade);+ });++ function syncTtsToggle() {+ ttsEnabledToggle.checked = settings.ttsEnabled;+ ttsToggleBtn.disabled = !voiceCapabilities.tts;+ ttsToggleBtn.setAttribute('aria-pressed', String(settings.ttsEnabled));+ const label = settings.ttsEnabled ? 'Turn spoken replies off' : 'Turn spoken replies on';+ ttsToggleBtn.setAttribute('aria-label', label);+ ttsToggleBtn.title = voiceCapabilities.tts ? label : 'Speech output is unavailable';+ ttsToggleLabel.textContent = settings.ttsEnabled ? 'Sound on' : 'Sound off';+ document.getElementById('ttsToggleIcon').innerHTML = settings.ttsEnabled ? voiceIcons.sound : voiceIcons.soundOff;+ }++ function setTtsEnabled(enabled) {+ settings.ttsEnabled = Boolean(enabled && voiceCapabilities.tts);+ if (!settings.ttsEnabled) closeTtsWebSocket();+ else {+ try { ensureTtsAudioContext(); }+ catch (error) {+ settings.ttsEnabled = false;+ closeTtsWebSocket();+ voiceModeStatus.textContent = 'Sound could not start. Please retry.';+ }+ }+ syncTtsToggle();+ if (!voiceModeEnabled) {+ voiceModeStatus.textContent = settings.ttsEnabled+ ? 'Microphone off · Spoken replies on'+ : 'Microphone and sound are off';+ }+ scheduleVoiceListening();+ }+ ttsEnabledToggle.addEventListener('change', e => setTtsEnabled(e.target.checked));+ ttsToggleBtn.addEventListener('click', () => setTtsEnabled(!settings.ttsEnabled));++ colorfulFocusToggle.addEventListener('change', (e) => {+ const enabled = e.target.checked;+ demoStorage.setItem('colorfulFocus', enabled);+ if (enabled) {+ document.body.classList.add('colorful-focus');+ } else {+ document.body.classList.remove('colorful-focus');+ }+ // Force icon re-render to apply new colors+ lucide.createIcons();+ });++ overlayPosition.addEventListener('change', (e) => {+ settings.overlayPosition = e.target.value;+ demoStorage.setItem('overlayPosition', settings.overlayPosition);+ applyOverlayPosition(settings.overlayPosition);+ });++ layoutOrder.addEventListener('change', (e) => {+ settings.layoutOrder = e.target.value;+ demoStorage.setItem('layoutOrder', settings.layoutOrder);+ applyLayoutOrder(settings.layoutOrder);+ });++ // Panel Toggle+ function togglePanel(panelId) {+ const sidebar = document.getElementById('sidebar');+ const content = document.getElementById(panelId);+ const toggle = document.getElementById(panelId + 'Toggle');+ const sidebarPanelIds = ['vlmConfig', 'cameraConfig'];+ const isSidebarPanel = sidebarPanelIds.includes(panelId);++ if (isSidebarPanel && sidebar?.classList.contains('docked')) {+ sidebar.classList.remove('docked');+ sidebarPanelIds.forEach(id => {+ const panelContent = document.getElementById(id);+ const panelToggle = document.getElementById(id + 'Toggle');+ const isActive = id === panelId;+ panelContent?.classList.toggle('collapsed', !isActive);+ panelToggle?.classList.toggle('collapsed', !isActive);+ });+ return;+ }++ content?.classList.toggle('collapsed');+ toggle?.classList.toggle('collapsed');++ const allSidebarPanelsCollapsed = sidebarPanelIds+ .every(id => document.getElementById(id)?.classList.contains('collapsed'));+ if (isSidebarPanel && allSidebarPanelsCollapsed) {+ sidebar?.classList.add('docked');+ }+ }+++ // Fullscreen Toggle+ function toggleFullscreen() {+ const videoCard = document.getElementById('videoCard');+ const fullscreenIcon = document.getElementById('fullscreenIcon');++ videoCard.classList.toggle('fullscreen');++ // Update icon: maximize when normal, minimize when fullscreen+ if (videoCard.classList.contains('fullscreen')) {+ fullscreenIcon.setAttribute('data-lucide', 'minimize');+ if (fullscreenPromptOverlay && promptEditor) {+ fullscreenPromptOverlay.appendChild(document.getElementById('voiceModeBar'));+ fullscreenPromptOverlay.appendChild(promptEditor);+ }+ // Sync current VLM output to fullscreen overlay+ syncVlmToFullscreen();+ } else {+ fullscreenIcon.setAttribute('data-lucide', 'maximize');+ restorePromptEditorHome();+ }+ lucide.createIcons();+ }++ function restorePromptEditorHome() {+ if (promptEditorHome && promptEditor && promptEditor.parentElement !== promptEditorHome) {+ promptEditorHome.appendChild(document.getElementById('voiceModeBar'));+ promptEditorHome.appendChild(promptEditor);+ }+ }++ // Sync VLM output to fullscreen overlay+ function syncVlmToFullscreen() {+ const fullscreenVlmContent = document.getElementById('fullscreenVlmContent');+ const fullscreenVlmMetrics = document.getElementById('fullscreenVlmMetrics');++ if (fullscreenVlmContent) {+ fullscreenVlmContent.textContent = getFullscreenVlmText();+ }++ // Add metrics if available+ const latency = document.getElementById('latencyValue')?.textContent;+ const count = document.getElementById('countValue')?.textContent;+ if (latency && count) {+ fullscreenVlmMetrics.innerHTML = `<span>Latency: ${latency}ms</span><span>Count: ${count}</span>`;+ }+ }++ function normalizeFullscreenLine(text) {+ return String(text || '').replace(/\s+/g, ' ').trim();+ }++ function getFullscreenVlmText() {+ const lines = [];++ vlmHistory.forEach(entry => {+ if (entry.kind === 'background' || entry.contextExcluded) {+ return;+ }+ const prompt = normalizeFullscreenLine(entry.prompt);+ const response = normalizeFullscreenLine(entry.response);++ if (hasVisiblePrompt(entry) && prompt) {+ lines.push(`Input: ${prompt}`);+ }+ if (response) {+ lines.push(`Output: ${response}`);+ }+ });++ const liveResponse = normalizeFullscreenLine(getVlmDisplayText(lastText));+ if (!lines.length && liveResponse) {+ lines.push(`Output: ${liveResponse}`);+ }++ return lines.slice(-4).join('\n') || 'Ready';+ }++ // ESC key to exit fullscreen+ document.addEventListener('keydown', (e) => {+ if (e.key === 'Escape') {+ const videoCard = document.getElementById('videoCard');+ if (videoCard.classList.contains('fullscreen')) {+ toggleFullscreen();+ }+ }+ });++ // API Key Field Toggle+ function toggleApiKeyField() {+ const field = document.getElementById('apiKeyField');+ const toggle = document.getElementById('apiKeyToggle');+ field.classList.toggle('collapsed');+ toggle.classList.toggle('collapsed');+ }++ // Check if API Base URL requires API key+ function checkApiKeyRequirement(url) {+ const apiKeyField = document.getElementById('apiKeyField');+ const apiKeyToggle = document.getElementById('apiKeyToggle');++ // Check if URL is a remote service (not localhost or 127.0.0.1)+ const isLocal = url.includes('localhost') || url.includes('127.0.0.1') || url.includes('0.0.0.0');+ const isRemote = !isLocal;++ if (isRemote) {+ // Show API key field for remote services+ apiKeyField.classList.remove('collapsed');+ apiKeyToggle.classList.remove('collapsed');+ console.log('Remote API detected - API Key field expanded');+ } else {+ // Hide API key field for local services+ apiKeyField.classList.add('collapsed');+ apiKeyToggle.classList.add('collapsed');+ console.log('Local API detected - API Key field collapsed');+ }+ }++ // Status Update+ function updateStatus(message, state) {+ connectionStatus.textContent = message;+ connectionStatus.className = `status-badge ${state}`;+ }++ function updatePromptAvailability() {+ const canSendPrompt = Boolean(isAnalysisRunning);+ promptSendBtn.disabled = !canSendPrompt;+ speechButtons.forEach(button => {+ button.disabled = voiceModeEnabled || asrSendPromptWhenFinal || (isSpeechActive() ? false : (!canSendPrompt || !voiceCapabilities.asr));+ });+ promptText.placeholder = canSendPrompt ? 'Ask about what you see…' : 'Open your camera to start a conversation';+ promptSendBtn.title = canSendPrompt ? 'Send prompt' : 'Start the video to send';+ syncSpeechButtons();+ syncVoiceMode();++ processEvery.disabled = isAnalysisRunning;+ processEvery.title = isAnalysisRunning ? 'Stop the video before changing this setting' : '';+ framesPerBatch.disabled = isAnalysisRunning;+ framesPerBatch.title = isAnalysisRunning ? 'Stop the video before changing this setting' : '';+ }++ function setVideoWaitingForStream(waiting) {+ const videoCard = document.getElementById('videoCard');+ videoCard?.classList.toggle('waiting-for-stream', waiting);+ }++ function resetVideoButtons() {+ const bigBtn = document.getElementById('bigStartBtn');+ const smallStopBtn = document.getElementById('smallStopBtn');+ bigBtn.classList.remove('animating', 'streaming');+ smallStopBtn.classList.remove('show');+ }++ function cancelRevealVideoFallback() {+ if (revealVideoFallbackTimeout) {+ clearTimeout(revealVideoFallbackTimeout);+ revealVideoFallbackTimeout = null;+ }+ }++ function revealVideoWhenReady(token) {+ if (token !== streamStartToken) {+ return;+ }+ cancelRevealVideoFallback();+ revealVideoAfterMetricsToken = null;+ setVideoWaitingForStream(false);+ updateStatus('Streaming', 'connected');+ }++ function showProcessedVideoStream(stream, token) {+ if (token !== streamStartToken) {+ return;+ }+ videoElement.srcObject = stream;++ const markStreaming = () => {+ if (token !== streamStartToken || videoElement.srcObject !== stream) {+ return;+ }+ isAnalysisRunning = true;+ updatePromptAvailability();+ if (revealVideoAfterMetricsToken === token) {+ updateStatus('Preparing first metrics...', 'processing');+ cancelRevealVideoFallback();+ revealVideoFallbackTimeout = setTimeout(() => {+ revealVideoWhenReady(token);+ }, 5000);+ } else {+ revealVideoWhenReady(token);+ }+ };++ const playPromise = videoElement.play();+ if (playPromise && typeof playPromise.then === 'function') {+ playPromise.then(markStreaming).catch(err => {+ console.error('Error playing video:', err);+ markStreaming();+ });+ } else {+ markStreaming();+ }+ }++ // Detect Local VLM Services+ async function detectServices() {+ try {+ const response = await fetch('/detect-services');+ const data = await response.json();++ if (data.default) {+ const service = data.default;+ console.log('Detected service:', service.name);++ // Update API Base URL+ apiBaseUrl.value = service.url;++ // Check if API key is required+ checkApiKeyRequirement(service.url);++ // Update hint text+ const hintDiv = apiBaseUrl.nextElementSibling;+ if (data.detected.length > 1) {+ const serviceNames = data.detected.map(s => s.name).join(', ');+ hintDiv.textContent = `Detected: ${serviceNames}`;+ } else if (service.name === 'NVIDIA API Catalog') {+ hintDiv.textContent = 'No local VLM services found. Using NVIDIA API Catalog (requires API key from build.nvidia.com)';+ }+ }+ } catch (error) {+ console.error('Error detecting services:', error);+ // Default to showing API key field on error+ checkApiKeyRequirement('https://');+ }+ }++ function displayModelName(model) {+ if (model === 'streaming-infer-adapter') return 'ALIVE';+ if (/qwen/i.test(String(model || ''))) return 'ALIVE';+ return model;+ }++ function formatDebugPayload(payload) {+ // Alias model labels in the UI; keep transport IDs unchanged.+ return JSON.stringify(payload, (key, value) =>+ ['model', 'model_id', 'model_name'].includes(key) && typeof value === 'string'+ ? displayModelName(value) : value, 2);+ }++ // Fetch Models+ async function fetchModels() {+ try {+ modelSelect.innerHTML = '<option value="">Loading models...</option>';++ // Get current API settings from UI+ const currentApiBase = apiBaseUrl.value.trim();+ const currentApiKey = apiKey.value.trim();++ // Build query params+ const params = new URLSearchParams();+ if (currentApiBase) {+ params.append('api_base', currentApiBase);+ }+ if (currentApiKey) {+ params.append('api_key', currentApiKey);+ }++ const url = `/models${params.toString() ? '?' + params.toString() : ''}`;+ const response = await fetch(url);+ const data = await response.json();++ if (data.models && data.models.length > 0) {+ modelSelect.innerHTML = '';+ let currentModel = null;+ let autoSelectedModel = null;++ data.models.forEach((model, index) => {+ const option = document.createElement('option');+ option.value = model.id;+ option.textContent = displayModelName(model.id);+ if (model.current) {+ option.selected = true;+ currentModel = model.id;+ }+ modelSelect.appendChild(option);+ });++ // If no current model, auto-select first model and apply+ if (!currentModel && data.models.length > 0) {+ autoSelectedModel = data.models[0].id;+ modelSelect.value = autoSelectedModel;+ currentModel = autoSelectedModel;++ // Auto-apply the new model+ console.log(`Auto-selected model: ${autoSelectedModel}`);+ applyApiSettings({ showFeedback: false });+ }++ // Update model name in VLM output header+ if (currentModel) {+ document.getElementById('modelName').textContent = displayModelName(currentModel);+ }+ } else {+ modelSelect.innerHTML = '<option value="">No models available</option>';+ }+ } catch (error) {+ console.error('Error fetching models:', error);+ modelSelect.innerHTML = '<option value="">Error loading models</option>';+ }+ }++ // Handle model change+ modelSelect.addEventListener('change', (e) => {+ const newModel = e.target.value;+ if (!newModel) return;++ // Update model name in VLM output header+ document.getElementById('modelName').textContent = displayModelName(newModel);++ if (websocket && websocket.readyState === WebSocket.OPEN) {+ // Send model, API base, and API key together+ websocket.send(JSON.stringify({+ type: 'update_model',+ model: newModel,+ api_base: apiBaseUrl.value.trim(),+ api_key: apiKey.value.trim()+ }));+ updateStatus('Model configured', 'connected');+ }++ // Trigger flash animation+ modelSelect.classList.add('applied');+ setTimeout(() => {+ modelSelect.classList.remove('applied');+ }, 600);+ });++ // Also trigger flash on blur (when dropdown closes)+ modelSelect.addEventListener('blur', () => {+ const currentModel = modelSelect.value;+ if (currentModel) {+ // Trigger flash animation+ modelSelect.classList.add('applied');+ setTimeout(() => {+ modelSelect.classList.remove('applied');+ }, 600);+ }+ });++ // Helper function to apply prompt settings+ function applyPromptSettings() {+ if (!isAnalysisRunning || !websocket || websocket.readyState !== WebSocket.OPEN) {+ updateStatus('Start the video and wait for the connection before sending.', 'disconnected');+ return false;+ }+ const newPrompt = cleanBackgroundQuestionText(promptText.value.trim());+ if (!newPrompt) return false;+ try {+ websocket.send(JSON.stringify({+ type: 'update_prompt', prompt: newPrompt, client_sent_at_ms: Date.now()+ }));+ } catch (error) {+ updateStatus('Message not sent. Please retry.', 'disconnected');+ return false;+ }+ if (isDuplexListening()) {+ stopTtsPlayback();+ duplexReplyGate = { prompt: newPrompt, waiting: true };+ }+ if (voiceModeEnabled) {+ voiceAwaitingPrompt = newPrompt;+ clearTimeout(voiceListenTimer);+ clearTimeout(voiceReplyTimer);+ voiceReplyTimer = setTimeout(() => {+ if (voiceModeEnabled && voiceAwaitingPrompt !== null) {+ if (isDuplexListening()) {+ voiceAwaitingPrompt = null;+ voiceReplyTimer = null;+ updateStatus('Reply delayed. You can keep speaking.', 'connected');+ scheduleVoiceListening();+ } else {+ stopVoiceMode('No reply yet. You can retry with voice or text.');+ }+ }+ }, 60000);+ syncVoiceMode();+ }+ // Manual Send during recording ends that utterance too. Late ASR+ // events cannot put previously submitted words back into the input.+ if (asrWs || isSpeechActive()) finishSpeech({ sendPrompt: false });+ currentPromptText = newPrompt;+ appendPromptHistoryEntry(newPrompt);+ promptText.value = '';+ asrFinalText = asrPartialText = asrLastFinalText = '';+ resizePromptInput();+ scheduleVoiceListening();+ return true;+ }++ function resizePromptInput() {+ promptText.style.height = 'auto';+ promptText.style.height = Math.min(promptText.scrollHeight, 120) + 'px';+ }++ function syncVoiceMode() {+ voiceModeBtn.disabled = !voiceModeEnabled && !voiceCapabilities.asr;+ voiceModeBtn.setAttribute('aria-pressed', String(voiceModeEnabled));+ const label = voiceModeEnabled ? 'Turn microphone off' : 'Turn microphone on';+ voiceModeBtn.setAttribute('aria-label', label);+ voiceModeBtn.title = voiceCapabilities.asr ? label : 'Speech input is unavailable';+ voiceModeLabel.textContent = voiceModeEnabled ? 'Mic on' : 'Mic off';+ document.getElementById('voiceModeIcon').innerHTML = voiceModeEnabled ? voiceIcons.mic : voiceIcons.micOff;+ syncTtsToggle();+ if (voiceModeEnabled) {+ voiceModeStatus.textContent = voiceModeStarting ? 'Starting camera…'+ : ttsSpeaking ? (isDuplexListening()+ ? (asrRecording ? 'Speaking + listening — speak to interrupt' : 'Speaking — connecting microphone…')+ : 'Speaking — microphone paused')+ : isDuplexListening() && asrRecording ? (duplexUserSpeaking+ ? 'Listening — pause to send'+ : voiceAwaitingPrompt !== null ? 'Listening — waiting for reply…' : 'Listening — full duplex')+ : voiceAwaitingPrompt !== null ? 'Waiting for a reply…'+ : asrSendPromptWhenFinal ? 'Sending…'+ : asrRecording ? 'Listening — pause to send'+ : 'Connecting microphone…';+ }+ }++ function canResumeVoiceListening() {+ return voiceModeEnabled && !voiceModeStarting && isAnalysisRunning && !document.hidden && !isSpeechActive()+ && (isDuplexListening() || (voiceAwaitingPrompt === null && !ttsSpeaking && !pendingTtsQueue.length));+ }++ function scheduleVoiceListening() {+ syncVoiceMode();+ if (!canResumeVoiceListening()) return;+ clearTimeout(voiceListenTimer);+ const generation = voiceModeGeneration;+ voiceListenTimer = setTimeout(() => {+ voiceListenTimer = null;+ if (generation === voiceModeGeneration && canResumeVoiceListening()) startSpeech({ mode: 'auto' });+ }, isDuplexListening() ? 120 : 400);+ }++ function stopVoiceMode(message = 'Microphone off') {+ if (!voiceModeEnabled) return;+ voiceModeEnabled = voiceModeStarting = false;+ voiceModeGeneration += 1;+ duplexReplyGate = { prompt: null, waiting: false };+ voiceAwaitingPrompt = null;+ clearTimeout(voiceListenTimer);+ clearTimeout(voiceReplyTimer);+ voiceListenTimer = voiceReplyTimer = null;+ finishSpeech({ sendPrompt: false });+ voiceModeStatus.textContent = message;+ updatePromptAvailability();+ }++ async function toggleVoiceMode() {+ if (voiceModeEnabled) { stopVoiceMode(); return; }+ if (!voiceCapabilities.asr) return;+ if (isSpeechActive()) finishSpeech({ sendPrompt: false });+ voiceModeEnabled = true;+ const generation = ++voiceModeGeneration;+ mobileVoiceMode = false;+ try {+ voiceModeStarting = !isAnalysisRunning;+ syncVoiceMode();+ if (!isAnalysisRunning) {+ await start();+ const deadline = Date.now() + 15000;+ while (voiceModeEnabled && generation === voiceModeGeneration+ && !isAnalysisRunning && Date.now() < deadline) {+ await new Promise(resolve => setTimeout(resolve, 100));+ }+ }+ if (!voiceModeEnabled || generation !== voiceModeGeneration) return;+ voiceModeStarting = false;+ if (!isAnalysisRunning) {+ stopVoiceMode('Camera did not start. Check permissions and retry.');+ return;+ }+ updatePromptAvailability();+ scheduleVoiceListening();+ } catch (error) {+ stopVoiceMode('Microphone could not start. Check permissions and retry.');+ }+ }+ voiceModeBtn.addEventListener('click', toggleVoiceMode);+ document.addEventListener('visibilitychange', () => {+ if (document.hidden) stopVoiceMode('Microphone paused. Click to resume.');+ });++ function closePromptPopovers(except = null) {+ if (except !== 'presets') {+ promptPresetMenu.classList.add('hidden');+ promptPresetBtn.classList.remove('active');+ }+ }++ function flashPromptControl(element) {+ element.classList.add('applied');+ setTimeout(() => {+ element.classList.remove('applied');+ }, 600);+ }+++ function syncSpeechButtons() {+ const canSendPrompt = Boolean(isAnalysisRunning);+ const pressMode = isPressToTalkLayout();+ const speechActive = isSpeechActive();+ const speechVisualActive = isSpeechVisualActive();+ const idleTitle = !voiceCapabilities.asr ? 'Voice unavailable' : canSendPrompt+ ? (isMobileLayout() ? (pressMode ? 'Hold to speak' : 'Switch to voice input') : 'Click to speak')+ : 'Start the video to speak';++ promptEditor?.classList.toggle('mobile-voice-mode', pressMode);+ promptEditor?.classList.toggle('voice-ripple-active', pressMode && speechVisualActive);+ fullscreenPromptOverlay?.classList.toggle('voice-panel-open', pressMode);++ speechButtons.forEach(button => {+ button.classList.toggle('recording', speechVisualActive);+ button.title = speechVisualActive+ ? (pressMode ? 'Release to send' : 'Stop speaking')+ : idleTitle;++ const label = button.querySelector('.speech-label');+ if (label) {+ if (speechVisualActive) {+ label.textContent = pressMode ? 'Release to send' : 'Stop speaking';+ } else {+ label.textContent = pressMode ? 'Hold to speak' : (settings.asrLanguage === 'auto' ? 'Speak' : settings.asrLanguage === 'en' ? 'Speak EN' : 'Speak ZH');+ }+ }+ });+ lucide.createIcons();+ }++ function isSpeechActive() {+ return Boolean(asrStarting || asrRecording || asrSendPromptWhenFinal);+ }++ function isSpeechVisualActive() {+ if (isPressToTalkLayout()) {+ return asrPointerId !== null || asrStarting || asrRecording || Boolean(asrStream || asrAudioContext || asrWs);+ }+ return isSpeechActive();+ }++ function setSpeechRecording(recording) {+ asrStarting = false;+ asrRecording = recording;+ syncSpeechButtons();+ updatePromptAvailability();+ }++ function suppressNextSpeechClick() {+ ignoreNextSpeechClick = true;+ if (ignoreSpeechClickTimeout) {+ clearTimeout(ignoreSpeechClickTimeout);+ }+ ignoreSpeechClickTimeout = setTimeout(() => {+ ignoreNextSpeechClick = false;+ ignoreSpeechClickTimeout = null;+ }, 450);+ }++ function floatToInt16(input) {+ const output = new Int16Array(input.length);+ for (let i = 0; i < input.length; i += 1) {+ const sample = Math.max(-1, Math.min(1, input[i]));+ output[i] = sample < 0 ? sample * 0x8000 : sample * 0x7fff;+ }+ return output;+ }++ function downsampleToInt16(input, inputSampleRate) {+ if (inputSampleRate === ASR_TARGET_SAMPLE_RATE) {+ return floatToInt16(input).buffer;+ }++ const ratio = inputSampleRate / ASR_TARGET_SAMPLE_RATE;+ const length = Math.floor(input.length / ratio);+ const output = new Float32Array(length);+ let inputOffset = 0;++ for (let i = 0; i < length; i += 1) {+ const nextOffset = Math.floor((i + 1) * ratio);+ let sum = 0;+ let count = 0;+ for (let j = inputOffset; j < nextOffset && j < input.length; j += 1) {+ sum += input[j];+ count += 1;+ }+ output[i] = count ? sum / count : 0;+ inputOffset = nextOffset;+ }++ return floatToInt16(output).buffer;+ }++ function getAudioRms(input) {+ let sum = 0;+ for (let i = 0; i < input.length; i += 1) {+ sum += input[i] * input[i];+ }+ return Math.sqrt(sum / Math.max(1, input.length));+ }++ function getMicErrorMessage(error) {+ if (!window.isSecureContext) {+ return 'Microphone access requires HTTPS or localhost.';+ }+ if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {+ return 'Microphone access is unavailable in this browser.';+ }+ if (error && error.name === 'NotAllowedError') {+ return 'Allow microphone access in your browser and try again.';+ }+ if (error && error.name === 'NotFoundError') {+ return 'No microphone found.';+ }+ return `Microphone unavailable: ${error ? error.message : 'Unknown error'}`;+ }++ function updatePromptFromSpeech() {+ const text = [asrFinalText, asrPartialText].filter(Boolean).join(settings.asrLanguage === 'zh' ? '' : ' ');+ promptText.value = text;+ resizePromptInput();+ }++ function handleAsrResult(data) {+ if (!asrWs || !['IS_PARTIAL', 'IS_FINAL', 'IS_END'].includes(data.event)) return;+ if (data.text) {+ asrHeardVoice = true;+ if (isDuplexListening()) beginDuplexUtterance();+ }+ if (data.final) {+ const text = String(data.text || '').trim();+ if (text && text !== asrLastFinalText) {+ asrFinalText += (settings.asrLanguage !== 'zh' && asrFinalText ? ' ' : '') + text;+ asrLastFinalText = text;+ }+ asrPartialText = '';+ updatePromptFromSpeech();+ if (asrSendPromptWhenFinal || asrStopMode === 'auto') {+ finishSpeech({ sendPrompt: true });+ }+ } else {+ asrPartialText = data.text || '';+ updatePromptFromSpeech();+ }+ }++ function beginDuplexUtterance() {+ if (duplexUserSpeaking) return;+ duplexUserSpeaking = true;+ asrHeardVoice = true;+ duplexReplyGate = { prompt: '', waiting: true };+ voiceAwaitingPrompt = null;+ clearTimeout(voiceReplyTimer);+ voiceReplyTimer = null;+ stopTtsPlayback();+ syncVoiceMode();+ }++ function sendDuplexAudio(audio) {+ const pcm = new Int16Array(audio);+ const output = [];+ for (let pos = 0; pos < pcm.length; pos += 320) {+ const frame = pcm.subarray(pos, pos + 320);+ let sum = 0;+ for (const sample of frame) sum += (sample / 32768) ** 2;+ const rms = Math.sqrt(sum / frame.length);+ if (duplexUserSpeaking) {+ if (rms >= ASR_SILENCE_RMS_THRESHOLD) asrLastVoiceTime = performance.now();+ output.push(frame);+ continue;+ }+ duplexPreroll.push(frame.slice());+ duplexPrerollSamples += frame.length;+ while (duplexPrerollSamples > DUPLEX_PREROLL_SAMPLES && duplexPreroll.length > 1) {+ duplexPrerollSamples -= duplexPreroll.shift().length;+ }+ duplexOnsetSamples = rms >= DUPLEX_ONSET_RMS ? duplexOnsetSamples + frame.length : 0;+ if (duplexOnsetSamples >= DUPLEX_ONSET_SAMPLES) {+ beginDuplexUtterance();+ asrLastVoiceTime = performance.now();+ output.push(...duplexPreroll);+ duplexPreroll = [];+ duplexPrerollSamples = 0;+ } else {+ output.push(new Int16Array(frame.length));+ }+ }+ const merged = new Int16Array(output.reduce((count, part) => count + part.length, 0));+ let offset = 0;+ for (const part of output) { merged.set(part, offset); offset += part.length; }+ if (merged.length) asrWs.send(merged.buffer);+ if (duplexUserSpeaking && asrStopMode === 'auto'+ && performance.now() - asrLastVoiceTime >= ASR_SILENCE_AUTO_STOP_MS) stopSpeech();+ }++ async function prepareSpeechMic(token) {+ const stream = await navigator.mediaDevices.getUserMedia({+ audio: {+ channelCount: 1,+ echoCancellation: true,+ noiseSuppression: true,+ autoGainControl: true+ }+ });+ if (token !== asrStartToken || asrStopRequested || !isAnalysisRunning) {+ stream.getTracks().forEach(track => track.stop());+ return false;+ }+ asrStream = stream;++ asrAudioContext = new AudioContext();+ asrSource = asrAudioContext.createMediaStreamSource(asrStream);+ asrProcessor = asrAudioContext.createScriptProcessor(ASR_AUDIO_BUFFER_SIZE, 1, 1);+ asrSilence = asrAudioContext.createGain();+ asrSilence.gain.value = 0;+ asrLastVoiceTime = performance.now();++ asrProcessor.onaudioprocess = (event) => {+ if (token !== asrStartToken || !asrRecording || !asrWs || asrWs.readyState !== WebSocket.OPEN) {+ return;+ }++ const input = event.inputBuffer.getChannelData(0);+ if (isDuplexListening() && !asrUsesServerVad) {+ sendDuplexAudio(downsampleToInt16(input, asrAudioContext.sampleRate));+ return;+ }+ const rms = getAudioRms(input);+ const now = performance.now();+ if (!asrUsesServerVad && rms >= ASR_SILENCE_RMS_THRESHOLD) {+ asrLastVoiceTime = now;+ asrHeardVoice = true;+ } else if (!asrUsesServerVad && asrStopMode === 'auto' && (!voiceModeEnabled || asrHeardVoice)+ && now - asrLastVoiceTime >= ASR_SILENCE_AUTO_STOP_MS) {+ stopSpeech();+ return;+ }++ const audio = downsampleToInt16(input, asrAudioContext.sampleRate);+ if (audio.byteLength > 0) {+ asrWs.send(audio);+ }+ };++ asrSource.connect(asrProcessor);+ asrProcessor.connect(asrSilence);+ asrSilence.connect(asrAudioContext.destination);+ return true;+ }++ function connectAsrWebSocket() {+ const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';+ // Press-to-talk may span pauses; click-to-talk ends after one utterance.+ const continuous = asrStopMode === 'press' ? '&continuous=1' : '';+ const ws = new WebSocket(`${protocol}//${window.location.host}${ASR_WS_PATH}?session_id=${encodeURIComponent(sessionId)}&lang=${settings.asrLanguage}${continuous}`);+ asrWs = ws;+ ws.binaryType = 'arraybuffer';+ ws.onmessage = (event) => {+ if (asrWs !== ws) return;+ const data = JSON.parse(event.data);+ if (data.type === 'status' && data.message === 'connected') {+ if (!isAnalysisRunning || asrStopRequested) {+ finishSpeech({ sendPrompt: false });+ return;+ }+ asrUsesServerVad = data.speech_detection === 'silero-vad';+ asrLastVoiceTime = performance.now();+ setSpeechRecording(true);+ if (voiceModeEnabled || Number(data.max_recording_sec) > 0) {+ // Respect each provider's stream limit, including silent+ // hands-free listening. Renew before the backend closes.+ const maxSeconds = Number(data.max_recording_sec) || 120;+ const renewMs = Math.max(1000, (maxSeconds - 2) * 1000);+ asrRenewTimer = setTimeout(() => {+ if (asrWs === ws) {+ if (asrHeardVoice) stopSpeech();+ else finishSpeech({ sendPrompt: false });+ }+ }, renewMs);+ }+ } else if (data.type === 'speech_activity' && data.active) {+ asrHeardVoice = true;+ asrLastVoiceTime = performance.now();+ if (isDuplexListening()) beginDuplexUtterance();+ } else if (data.type === 'error') {+ updateStatus(data.message, 'disconnected');+ stopVoiceMode('Speech recognition unavailable. Click to retry.');+ finishSpeech({ sendPrompt: false });+ } else if (data.type === 'result') {+ handleAsrResult(data);+ }+ };+ ws.onclose = () => {+ if (asrWs !== ws) return;+ if (voiceModeEnabled && !asrSendPromptWhenFinal) {+ stopVoiceMode('Microphone connection closed. Click to retry.');+ return;+ }+ // Only an explicit stop/final result authorizes submission.+ finishSpeech({ sendPrompt: asrSendPromptWhenFinal });+ };+ ws.onerror = () => {+ if (asrWs !== ws) return;+ updateStatus('Speech recognition connection failed. Please retry.', 'disconnected');+ stopVoiceMode('Microphone connection failed. Click to retry.');+ finishSpeech({ sendPrompt: false });+ };+ }++ async function startSpeech({ mode = 'auto' } = {}) {+ if (!voiceCapabilities.asr) {+ updateStatus('Voice unavailable. Please use text input.', 'disconnected');+ return;+ }+ if (!isAnalysisRunning) {+ updateStatus('Start the video first', 'disconnected');+ updatePromptAvailability();+ return;+ }++ if (isSpeechActive() || asrStream || asrAudioContext || asrWs) {+ return;+ }++ if (!isDuplexListening()) stopTtsPlayback({ clearQueue: false, requeueCurrent: true });+ resetDuplexDetection();+ const token = ++asrStartToken;+ asrStarting = true;+ syncSpeechButtons();+ updatePromptAvailability();+ asrStopMode = mode;+ asrHeardVoice = false;+ asrUsesServerVad = false;+ asrStopRequested = false;+ if (mode !== 'press') {+ speechButtons.forEach(button => {+ button.disabled = true;+ });+ }+ asrFinalText = '';+ asrPartialText = '';+ asrLastFinalText = '';+ asrSendPromptWhenFinal = false;+ if (asrFinalFallbackTimer) {+ clearTimeout(asrFinalFallbackTimer);+ asrFinalFallbackTimer = null;+ }+ promptText.value = '';+ resizePromptInput();++ try {+ if (!await prepareSpeechMic(token)) return;+ if (token !== asrStartToken || asrStopRequested || !isAnalysisRunning) {+ await stopSpeech({ sendEnd: false, sendPrompt: false });+ return;+ }+ connectAsrWebSocket();+ } catch (error) {+ updateStatus(getMicErrorMessage(error), 'disconnected');+ stopVoiceMode(getMicErrorMessage(error));+ updatePromptAvailability();+ await stopSpeech({ sendEnd: false, sendPrompt: false });+ }+ }++ function releaseSpeechMic() {+ // Detach synchronously before awaiting AudioContext.close. Final and+ // close events may arrive together, and cleanup must be idempotent.+ const context = asrAudioContext;+ clearTimeout(asrRenewTimer);+ asrRenewTimer = null;+ asrProcessor?.disconnect();+ asrSource?.disconnect();+ asrSilence?.disconnect();+ asrStream?.getTracks().forEach(track => track.stop());+ asrProcessor = asrSource = asrSilence = asrStream = asrAudioContext = null;+ if (context && context.state !== 'closed') context.close().catch(console.warn);+ }++ function finishSpeech({ sendPrompt = false } = {}) {+ asrStartToken += 1;+ asrStopRequested = true;+ const ws = asrWs;+ asrWs = null; // Ignore late results before clearing/submitting text.+ asrStarting = asrRecording = asrSendPromptWhenFinal = false;+ asrPointerId = null;+ if (asrFinalFallbackTimer) clearTimeout(asrFinalFallbackTimer);+ asrFinalFallbackTimer = null;+ releaseSpeechMic();+ if (ws && [WebSocket.CONNECTING, WebSocket.OPEN].includes(ws.readyState)) ws.close();+ if (sendPrompt && promptText.value.trim()) {+ if (applyPromptSettings()) flashPromptControl(promptText);+ else stopVoiceMode('Message not sent. Your text is kept for retry.');+ }+ asrFinalText = asrPartialText = asrLastFinalText = '';+ resetDuplexDetection();+ if (duplexReplyGate.prompt === '') duplexReplyGate = { prompt: null, waiting: false };+ if (isMobileLayout()) mobileVoiceMode = false;+ updatePromptAvailability();+ maybeSpeakPendingTts();+ }++ async function stopSpeech({ sendEnd = true, sendPrompt = true } = {}) {+ if (!sendEnd || !sendPrompt) {+ finishSpeech({ sendPrompt });+ return;+ }+ if (asrSendPromptWhenFinal) return;+ asrStartToken += 1;+ asrStopRequested = true;+ const wasRecording = asrRecording;+ asrStarting = asrRecording = false;+ asrPointerId = null;+ releaseSpeechMic();+ if (wasRecording && asrWs?.readyState === WebSocket.OPEN) {+ asrSendPromptWhenFinal = true;+ asrFinalFallbackTimer = setTimeout(() => finishSpeech({ sendPrompt: true }), ASR_FINAL_FALLBACK_MS);+ asrWs.send(JSON.stringify({ type: 'end' }));+ updatePromptAvailability();+ } else {+ finishSpeech({ sendPrompt });+ }+ }++ function finishPressToTalk({ sendEnd = true, sendPrompt = true } = {}) {+ if (!isPressToTalkLayout() && asrPointerId === null) {+ return;+ }+ asrPointerId = null;+ stopSpeech({ sendEnd, sendPrompt });+ mobileVoiceMode = false;+ updatePromptAvailability();+ }++ promptPresetBtn.addEventListener('click', (e) => {+ e.stopPropagation();+ const willOpen = promptPresetMenu.classList.contains('hidden');+ closePromptPopovers(willOpen ? 'presets' : null);+ promptPresetMenu.classList.toggle('hidden', !willOpen);+ promptPresetBtn.classList.toggle('active', willOpen);+ });++ promptPresetOptions.forEach(option => {+ option.addEventListener('click', () => {+ promptPresetOptions.forEach(item => item.classList.remove('selected'));+ option.classList.add('selected');+ promptText.value = option.dataset.prompt || '';+ resizePromptInput();+ closePromptPopovers();+ promptText.focus();+ });+ });++ document.addEventListener('click', (e) => {+ if (!e.target.closest('.chat-prompt-shell')) {+ closePromptPopovers();+ }+ });++ let promptImeComposing = false;+ let promptCompositionEndedAt = 0;++ promptText.addEventListener('compositionstart', () => {+ promptImeComposing = true;+ });++ promptText.addEventListener('compositionend', () => {+ promptImeComposing = false;+ promptCompositionEndedAt = Date.now();+ });++ function isPromptImeEnter(e) {+ return Boolean(+ promptImeComposing ||+ e.isComposing ||+ e.keyCode === 229 ||+ Date.now() - promptCompositionEndedAt < 30+ );+ }++ // Apply prompt on Enter key (Shift+Enter for newline)+ promptText.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' && !e.shiftKey) {+ if (isPromptImeEnter(e)) {+ return;+ }+ e.preventDefault();+ if (applyPromptSettings()) {+ flashPromptControl(promptText);+ }+ }+ });++ promptText.addEventListener('input', resizePromptInput);++ function toggleSpeechByClick() {+ if (isSpeechActive()) {+ stopSpeech();+ } else {+ startSpeech({ mode: 'auto' });+ }+ }++ function enterMobileVoiceMode(event) {+ if (!isMobileLayout() || mobileVoiceMode) {+ return false;+ }+ event.preventDefault();+ mobileVoiceMode = true;+ closePromptPopovers();+ updatePromptAvailability();+ return true;+ }++ function preventSpeechLongPressMenu(event) {+ if (+ isMobileLayout() &&+ (event.target === speechBtn || event.target.closest?.('.speech-control, .mobile-voice-mode'))+ ) {+ event.preventDefault();+ }+ }++ function startPressToTalk(event) {+ if (!isMobileLayout()) {+ return;+ }+ event.preventDefault();+ if (enterMobileVoiceMode(event)) {+ asrPointerId = event.pointerId;+ suppressNextSpeechClick();+ event.currentTarget.setPointerCapture?.(event.pointerId);+ syncSpeechButtons();+ startSpeech({ mode: 'press' });+ return;+ }+ if (isSpeechActive() || asrStream || asrAudioContext || asrWs) {+ return;+ }+ asrPointerId = event.pointerId;+ suppressNextSpeechClick();+ event.currentTarget.setPointerCapture?.(event.pointerId);+ syncSpeechButtons();+ startSpeech({ mode: 'press' });+ }++ function stopPressToTalk(event) {+ if (!isPressToTalkLayout() || asrPointerId !== event.pointerId) {+ return;+ }+ event.preventDefault();+ event.currentTarget.releasePointerCapture?.(event.pointerId);+ finishPressToTalk({ sendEnd: true, sendPrompt: true });+ }++ speechBtn.addEventListener('pointerdown', startPressToTalk);+ speechBtn.addEventListener('contextmenu', preventSpeechLongPressMenu);+ speechBtn.addEventListener('selectstart', preventSpeechLongPressMenu);+ promptEditor?.addEventListener('contextmenu', preventSpeechLongPressMenu);+ promptEditor?.addEventListener('selectstart', preventSpeechLongPressMenu);+ speechBtn.addEventListener('pointerup', stopPressToTalk);+ speechBtn.addEventListener('pointercancel', stopPressToTalk);+ speechBtn.addEventListener('pointerleave', stopPressToTalk);+ document.addEventListener('pointerup', (event) => {+ if (asrPointerId !== null && event.pointerId === asrPointerId) {+ finishPressToTalk({ sendEnd: true, sendPrompt: true });+ }+ }, true);+ document.addEventListener('pointercancel', (event) => {+ if (asrPointerId !== null && event.pointerId === asrPointerId) {+ finishPressToTalk({ sendEnd: false, sendPrompt: false });+ }+ }, true);+ window.addEventListener('blur', () => {+ if (asrPointerId !== null || isPressToTalkLayout()) {+ finishPressToTalk({ sendEnd: false, sendPrompt: false });+ }+ });+ document.addEventListener('visibilitychange', () => {+ if (document.hidden && (asrPointerId !== null || isPressToTalkLayout())) {+ finishPressToTalk({ sendEnd: false, sendPrompt: false });+ }+ });+ speechBtn.addEventListener('click', (event) => {+ if (ignoreNextSpeechClick) {+ event.preventDefault();+ ignoreNextSpeechClick = false;+ if (ignoreSpeechClickTimeout) {+ clearTimeout(ignoreSpeechClickTimeout);+ ignoreSpeechClickTimeout = null;+ }+ return;+ }+ if (isPressToTalkLayout()) {+ event.preventDefault();+ return;+ }+ if (enterMobileVoiceMode(event)) {+ return;+ }+ toggleSpeechByClick();+ });++ promptSendBtn.addEventListener('click', () => {+ if (applyPromptSettings()) {+ flashPromptControl(promptText);+ }+ });++ updatePromptAvailability();+ resizePromptInput();++ refreshModelsBtn.addEventListener('click', fetchModels);++ // Helper function to apply API settings to server+ function applyApiSettings(options = {}) {+ const currentApiBase = apiBaseUrl.value.trim();+ const currentApiKey = apiKey.value.trim();+ const currentModel = modelSelect.value;++ if (!currentApiBase) {+ return; // Silently skip if no API base+ }++ if (!currentModel) {+ return; // Silently skip if no model selected yet+ }++ // Send update to server+ if (websocket && websocket.readyState === WebSocket.OPEN) {+ websocket.send(JSON.stringify({+ type: 'update_model',+ model: currentModel,+ api_base: currentApiBase,+ api_key: currentApiKey+ }));++ if (options.showFeedback) {+ updateStatus('API settings updated', 'connected');+ }++ // Refresh models from new endpoint if requested+ if (options.refreshModels) {+ fetchModels();+ }+ }+ }++ // Auto-apply API settings when API Base URL changes+ apiBaseUrl.addEventListener('blur', (e) => {+ checkApiKeyRequirement(e.target.value);+ applyApiSettings({ refreshModels: true, showFeedback: true });++ // Trigger flash animation+ apiBaseUrl.classList.add('applied');+ setTimeout(() => {+ apiBaseUrl.classList.remove('applied');+ }, 600);+ });++ apiBaseUrl.addEventListener('change', (e) => {+ checkApiKeyRequirement(e.target.value);+ applyApiSettings({ refreshModels: true, showFeedback: true });++ // Trigger flash animation+ apiBaseUrl.classList.add('applied');+ setTimeout(() => {+ apiBaseUrl.classList.remove('applied');+ }, 600);+ });++ // Auto-apply API settings when API Key changes (with debounce)+ let apiKeyDebounceTimer;+ apiKey.addEventListener('input', () => {+ clearTimeout(apiKeyDebounceTimer);+ apiKeyDebounceTimer = setTimeout(() => {+ applyApiSettings({ showFeedback: false });+ }, 1000); // Wait 1 second after user stops typing+ });++ // Flash animation when API Key loses focus+ apiKey.addEventListener('blur', () => {+ clearTimeout(apiKeyDebounceTimer);+ applyApiSettings({ showFeedback: false });++ // Trigger flash animation+ apiKey.classList.add('applied');+ setTimeout(() => {+ apiKey.classList.remove('applied');+ }, 600);+ });++ // API Presets Menu+ const apiPresetsBtn = document.getElementById('apiPresetsBtn');+ const apiPresetsMenu = document.getElementById('apiPresetsMenu');++ if (apiPresetsBtn && apiPresetsMenu) {+ apiPresetsBtn.addEventListener('click', (e) => {+ e.stopPropagation();+ apiPresetsMenu.style.display = apiPresetsMenu.style.display === 'none' ? 'block' : 'none';+ });++ // Close menu when clicking outside+ document.addEventListener('click', (e) => {+ if (!apiPresetsMenu.contains(e.target) && e.target !== apiPresetsBtn) {+ apiPresetsMenu.style.display = 'none';+ }+ });++ // Handle preset selection+ document.querySelectorAll('.api-preset-item').forEach(item => {+ item.addEventListener('click', (e) => {+ const url = e.currentTarget.getAttribute('data-url');+ apiBaseUrl.value = url;+ apiPresetsMenu.style.display = 'none';++ // Trigger checks+ checkApiKeyRequirement(url);++ // Auto-apply new API settings+ applyApiSettings({ refreshModels: true, showFeedback: true });++ // Update hint+ const hint = document.getElementById('apiBaseHint');+ const serviceName = e.currentTarget.querySelector('strong').textContent;+ hint.textContent = `Using ${serviceName}`;+ });+ });+ }++ // Mirror video toggle+ mirrorBtn.addEventListener('click', () => {+ videoElement.classList.toggle('mirrored');+ mirrorBtn.classList.toggle('active');+ });++ // Auto-apply processing interval on change+ processEvery.addEventListener('change', () => {+ const interval = parseFloat(processEvery.value) || 1.0;++ if (websocket && websocket.readyState === WebSocket.OPEN) {+ websocket.send(JSON.stringify({+ type: 'update_processing',+ process_interval: interval+ }));+ }++ // Trigger flash animation+ processEvery.classList.add('applied');+ setTimeout(() => {+ processEvery.classList.remove('applied');+ }, 600);+ });++ // Also trigger flash on blur+ processEvery.addEventListener('blur', () => {+ const interval = parseFloat(processEvery.value) || 1.0;++ if (websocket && websocket.readyState === WebSocket.OPEN) {+ websocket.send(JSON.stringify({+ type: 'update_processing',+ process_interval: interval+ }));+ }++ // Trigger flash animation+ processEvery.classList.add('applied');+ setTimeout(() => {+ processEvery.classList.remove('applied');+ }, 600);+ });++ // Auto-apply frames per batch on change+ framesPerBatch.addEventListener('change', () => {+ const value = parseInt(framesPerBatch.value) || 1;++ if (websocket && websocket.readyState === WebSocket.OPEN) {+ websocket.send(JSON.stringify({+ type: 'update_frames_per_batch',+ frames_per_batch: value+ }));+ }++ framesPerBatch.classList.add('applied');+ setTimeout(() => {+ framesPerBatch.classList.remove('applied');+ }, 600);+ });++ framesPerBatch.addEventListener('blur', () => {+ const value = parseInt(framesPerBatch.value) || 1;++ if (websocket && websocket.readyState === WebSocket.OPEN) {+ websocket.send(JSON.stringify({+ type: 'update_frames_per_batch',+ frames_per_batch: value+ }));+ }++ framesPerBatch.classList.add('applied');+ setTimeout(() => {+ framesPerBatch.classList.remove('applied');+ }, 600);+ });++ // Auto-apply max latency on change+ maxLatency.addEventListener('change', () => {+ const latency = parseFloat(maxLatency.value) || 1.0;++ if (websocket && websocket.readyState === WebSocket.OPEN) {+ websocket.send(JSON.stringify({+ type: 'update_max_latency',+ max_latency: latency+ }));+ }+ });++ // Debug payload toggles (Settings modal): send set_debug so server includes request/response payload in vlm_response+ function sendDebugFlags() {+ if (!websocket || websocket.readyState !== WebSocket.OPEN) return;+ const req = document.getElementById('debugShowRequestPayload');+ const res = document.getElementById('debugShowResponsePayload');+ const mem = document.getElementById('debugShowMemoryState');+ websocket.send(JSON.stringify({+ type: 'set_debug',+ show_request_payload: !!req?.checked,+ show_response_payload: !!res?.checked,+ show_memory_state: !!mem?.checked+ }));+ }+ const debugShowRequestPayload = document.getElementById('debugShowRequestPayload');+ const debugShowResponsePayload = document.getElementById('debugShowResponsePayload');+ const debugShowMemoryState = document.getElementById('debugShowMemoryState');+ const requestPayloadDebugEl = document.getElementById('requestPayloadDebug');+ const responsePayloadDebugEl = document.getElementById('responsePayloadDebug');+ const memoryStateDebugEl = document.getElementById('memoryStateDebug');+ if (debugShowRequestPayload) {+ debugShowRequestPayload.addEventListener('change', () => {+ sendDebugFlags();+ if (requestPayloadDebugEl) requestPayloadDebugEl.style.display = debugShowRequestPayload.checked ? 'block' : 'none';+ });+ }+ if (debugShowResponsePayload) {+ debugShowResponsePayload.addEventListener('change', () => {+ sendDebugFlags();+ if (responsePayloadDebugEl) responsePayloadDebugEl.style.display = debugShowResponsePayload.checked ? 'block' : 'none';+ });+ }+ if (debugShowMemoryState) {+ debugShowMemoryState.addEventListener('change', () => {+ sendDebugFlags();+ if (memoryStateDebugEl) memoryStateDebugEl.style.display = debugShowMemoryState.checked ? 'block' : 'none';+ });+ }++ [backgroundEnabledToggle, backgroundFrameMultiplier, backgroundMaxFrames].forEach(control => {+ if (!control) return;+ control.addEventListener('change', () => {+ sendBackgroundConfig();+ control.classList?.add('applied');+ setTimeout(() => control.classList?.remove('applied'), 600);+ });+ });++ // Memory state change detection for console logging+ let _lastMemoryStateHash = '';+++ // WebSocket Connection+ function connectWebSocket() {+ if (gatewaySessionBlocked || (websocket && [WebSocket.OPEN, WebSocket.CONNECTING].includes(websocket.readyState))) {+ return;+ }++ const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';+ const wsUrl = `${protocol}//${window.location.host}/ws?session_id=${encodeURIComponent(sessionId)}`;++ const ws = new WebSocket(wsUrl);+ websocket = ws;++ ws.onopen = () => {+ if (websocket !== ws) {+ return;+ }+ console.log('WebSocket connected');+ updateStatus('Connected', 'connected');++ // Send current model/API settings to server after WebSocket connects+ // This ensures auto-selected models are properly initialized on the server side+ // Fix for race condition: page load might auto-select model before WS connects+ const currentModel = modelSelect.value;+ if (currentModel) {+ console.log('Initializing server with current model:', currentModel);+ applyApiSettings({ showFeedback: false });+ }+ };++ ws.onmessage = (event) => {+ if (websocket !== ws) {+ return;+ }+ const data = JSON.parse(event.data);+ if (data.type === 'service_busy') {+ gatewaySessionBlocked = true;+ stopVoiceMode();+ stopTtsPlayback();+ updateStatus('ALIVE is busy. Please retry.', 'disconnected');+ return;+ }++ if (data.type === 'vlm_response') {+ if (!isAnalysisRunning) {+ return;+ }++ if (data.text !== lastText) {+ resultText.classList.remove('fade');++ if (fadeTimeout) {+ clearTimeout(fadeTimeout);+ }++ // Start fade after 2 seconds if enabled+ if (settings.fade) {+ fadeTimeout = setTimeout(() => {+ resultText.classList.add('fade');+ }, 2000);+ }+ }++ updateResultText(data.text, data.metrics, data.metrics?.background_handoff || null);+ lastText = data.text;++ // Update video overlay (always, visibility is controlled by CSS)+ const displayText = getVlmDisplayText(data.text);+ videoOverlay.textContent = displayText;+ videoOverlay.classList.remove('show', 'top', 'bottom');+ if (displayText && settings.overlayPosition !== 'none') {+ videoOverlay.classList.add('show', settings.overlayPosition);+ }++ if (data.metrics) {+ metricsInline.style.display = 'flex';+ latencyValue.textContent = Math.round(data.metrics.last_latency_ms);+ avgLatencyValue.textContent = Math.round(data.metrics.avg_latency_ms);+ countValue.textContent = data.metrics.total_inferences;+ if (+ revealVideoAfterMetricsToken === streamStartToken &&+ Number(data.metrics.total_inferences) > 0+ ) {+ revealVideoWhenReady(streamStartToken);+ }+ logLatencyBreakdown(data.metrics);+ }+ if (data.summarizer_timing) {+ const st = data.summarizer_timing;+ const stKey = JSON.stringify(st);+ if (stKey !== window._lastSummarizerKey) {+ window._lastSummarizerKey = stKey;+ let parts = [];+ if (st.last_mid_term_ms != null) parts.push(`mid-term=${st.last_mid_term_ms}ms (chunk#${st.last_mid_term_chunk})`);+ if (st.barrier_wait_ms != null) parts.push(`barrier_wait=${st.barrier_wait_ms}ms`);+ if (st.last_long_term_ms != null) parts.push(`long-term=${st.last_long_term_ms}ms`);+ if (parts.length) console.log(`[summary model] ${parts.join(', ')}`);+ }+ }+ if (data.request_payload) {+ const block = document.getElementById('requestPayloadDebug');+ const pre = document.getElementById('requestPayloadContent');+ if (block && pre && document.getElementById('debugShowRequestPayload')?.checked) {+ block.style.display = 'block';+ pre.textContent = formatDebugPayload(data.request_payload);+ }+ }+ if (data.response_payload) {+ const block = document.getElementById('responsePayloadDebug');+ const pre = document.getElementById('responsePayloadContent');+ if (block && pre && document.getElementById('debugShowResponsePayload')?.checked) {+ block.style.display = 'block';+ pre.textContent = formatDebugPayload(data.response_payload);+ }+ }+ if (data.memory_state) {+ const summaries = data.memory_state.mid_term_summaries || [];+ const longTerm = data.memory_state.long_term_memory || '';+ const memHash = JSON.stringify(data.memory_state);+ if (memHash !== _lastMemoryStateHash) {+ _lastMemoryStateHash = memHash;+ // UI display (controlled by toggle)+ const memBlock = document.getElementById('memoryStateDebug');+ if (memBlock && document.getElementById('debugShowMemoryState')?.checked) {+ memBlock.style.display = 'block';+ const midPre = document.getElementById('midTermMemoryContent');+ if (midPre) {+ midPre.textContent = summaries.length+ ? summaries.map(s => `[Chunk ${s.chunk_index} | ${s.frame_range}]\n${s.summary_text}`).join('\n\n')+ : '(empty)';+ }+ const ltPre = document.getElementById('longTermMemoryContent');+ if (ltPre) {+ ltPre.textContent = longTerm || '(empty)';+ }+ }+ // Console output+ console.group('%c[Memory State]', 'color: #4fc3f7; font-weight: bold;');+ if (summaries.length) {+ console.groupCollapsed(`Mid-term memory (${summaries.length} chunks)`);+ summaries.forEach(s => {+ console.log(`%c[Chunk ${s.chunk_index} | ${s.frame_range}]`, 'color: #81c784;', '\n' + s.summary_text);+ });+ console.groupEnd();+ } else {+ console.log('Mid-term memory: (empty)');+ }+ if (longTerm) {+ console.groupCollapsed('Long-term memory');+ console.log(longTerm);+ console.groupEnd();+ } else {+ console.log('Long-term memory: (empty)');+ }+ console.groupEnd();+ }+ }+ } else if (data.type === 'status') {+ // Don't show status messages in result balloon (too flashy)+ // Status is already shown in the header+ } else if (+ data.type === 'background_task_started' ||+ data.type === 'background_result_ready' ||+ data.type === 'background_result_error'+ ) {+ appendOrUpdateBackgroundEntry(data);+ } else if (data.type === 'server_config') {+ // Server sent its current configuration (model, api_base, prompt)+ if (data.model) {+ document.getElementById('modelName').textContent = displayModelName(data.model);+ // Also update the model select if it matches+ if (modelSelect.querySelector(`option[value="${data.model}"]`)) {+ modelSelect.value = data.model;+ }+ }+ if (data.api_base) {+ apiBaseUrl.value = data.api_base;+ checkApiKeyRequirement(apiBaseUrl.value);+ serverConfigApplied = true;+ fetchModels();+ }+ if (data.process_interval != null && !isNaN(data.process_interval)) {+ processEvery.value = String(data.process_interval);+ }+ if (data.frames_per_batch != null && !isNaN(data.frames_per_batch)) {+ framesPerBatch.value = String(data.frames_per_batch);+ }+ if (data.background_model) {+ applyBackgroundConfig(data.background_model);+ }+ const reqCb = document.getElementById('debugShowRequestPayload');+ const resCb = document.getElementById('debugShowResponsePayload');+ const memCb = document.getElementById('debugShowMemoryState');+ if ((reqCb?.checked || resCb?.checked || memCb?.checked) && websocket && websocket.readyState === WebSocket.OPEN) {+ websocket.send(JSON.stringify({+ type: 'set_debug',+ show_request_payload: !!reqCb?.checked,+ show_response_payload: !!resCb?.checked,+ show_memory_state: !!memCb?.checked+ }));+ }+ } else if (data.type === 'model_updated') {+ // Model was updated on server+ if (data.model) {+ document.getElementById('modelName').textContent = displayModelName(data.model);+ console.log('Model updated to:', data.model);+ }+ } else if (data.type === 'prompt_updated') {+ // Prompt was updated on server (already handled in applyPrompt)+ console.log('Prompt updated:', data.prompt);+ } else if (data.type === 'processing_updated') {+ if (data.process_interval != null) processEvery.value = String(data.process_interval);+ console.log('Processing interval updated:', data.process_interval, 's');+ } else if (data.type === 'frames_per_batch_updated') {+ if (data.frames_per_batch != null) framesPerBatch.value = String(data.frames_per_batch);+ if (data.background_model) applyBackgroundConfig(data.background_model);+ console.log('Frames per batch updated:', data.frames_per_batch);+ } else if (data.type === 'background_config_updated') {+ applyBackgroundConfig(data.background_model);+ console.log('Background model config updated:', data.background_model);+ }+ };++ ws.onerror = (error) => {+ console.error('WebSocket error:', error);+ };++ ws.onclose = () => {+ if (websocket !== ws) {+ return;+ }+ if (gatewaySessionBlocked) return;+ console.log('WebSocket disconnected, will reconnect...');+ websocket = null;+ stopVoiceMode('Connection interrupted. Click to resume when connected.');+ updateStatus('Reconnecting...', 'disconnected');+ setTimeout(connectWebSocket, 2000);+ };+ }++ window.addEventListener('pagehide', () => {+ stopVoiceMode();+ stopTtsPlayback();+ if (cameraWebsocket) cameraWebsocket.close();+ if (websocket) websocket.close();+ navigator.sendBeacon('/api/session/cleanup', new Blob([+ JSON.stringify({session_id: sessionId, reset_adapter: true})+ ], {type: 'application/json'}));+ });++ async function cleanupServerSession(sessionIdToCleanup) {+ if (!sessionIdToCleanup) {+ return;+ }++ try {+ const response = await fetch('/api/session/cleanup', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ session_id: sessionIdToCleanup,+ reset_adapter: true+ })+ });+ if (!response.ok) {+ console.warn('Session cleanup failed:', response.status);+ } else {+ const result = await response.json();+ }+ } catch (error) {+ console.warn('Session cleanup request failed:', error);+ }+ }++ async function resetSession({ clearConversation = false, cleanupServer = true } = {}) {+ const oldSessionId = sessionId;++ if (!cleanupServer && websocket && websocket.readyState === WebSocket.OPEN) {+ try {+ websocket.send(JSON.stringify({ type: 'reset_session' }));+ } catch (e) {+ console.warn('Failed to send reset_session:', e);+ }+ }++ sessionId = crypto.randomUUID ? crypto.randomUUID() : 'tab-' + Date.now() + '-' + Math.random().toString(36).slice(2);+ console.log('Session reset:', oldSessionId, '->', sessionId);++ // Release the previous page slot before replacing its control WS.+ // A gateway without admission support may return 404; local close+ // below retains compatibility with that deployment.+ const previousControl = websocket;+ websocket = null;+ try {+ await fetch('/_bridge/release', {method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({session_id: oldSessionId})});+ } catch (error) { console.warn('Session release unavailable', error); }+ // Reconnect WebSocket with new session_id+ if (previousControl) {+ const oldSocket = previousControl;+ // Allow the gateway to release the old experience slot before+ // opening its replacement, including when both slots are full.+ await new Promise(resolve => {+ if (oldSocket.readyState === WebSocket.CLOSED) { resolve(); return; }+ const timer = setTimeout(resolve, 2000);+ oldSocket.addEventListener('close', () => { clearTimeout(timer); resolve(); }, {once: true});+ oldSocket.close();+ });+ }+ connectWebSocket();++ // Clear prompt input+ promptText.value = '';+ currentPromptText = '';++ if (clearConversation) {+ clearVlmConversation();+ } else {+ // Reset current streaming state, keep the visible history in the page+ resultText.classList.remove('fade');+ videoOverlay.textContent = '';+ lastText = '';+ lastTtsEventKey = '';+ lastHistoryKey = null;+ lastLoggedInferenceCount = 0;+ renderVlmHistory();+ }++ if (cleanupServer) {+ await cleanupServerSession(oldSessionId);+ }+ }++ // Start - dispatch to webcam or RTSP based on active tab+ async function start() {+ streamStartToken += 1;+ const token = streamStartToken;+ isAnalysisRunning = false;+ revealVideoAfterMetricsToken = null;+ cancelRevealVideoFallback();+ updatePromptAvailability();+ metricsInline.style.display = 'flex';+ latencyValue.textContent = '--';+ avgLatencyValue.textContent = '--';+ countValue.textContent = '--';+ setVideoWaitingForStream(true);+ videoElement.srcObject = null;+ if (settings.ttsEnabled) {+ try {+ ensureTtsAudioContext();+ } catch (error) {+ console.warn('Unable to initialize TTS audio context:', error);+ }+ }++ // Animate big button+ const bigBtn = document.getElementById('bigStartBtn');+ bigBtn.classList.add('animating');+ setTimeout(() => {+ bigBtn.classList.remove('animating');+ bigBtn.classList.add('streaming');+ }, 500);++ // Show small stop button+ document.getElementById('smallStopBtn').classList.add('show');++ const activeTab = document.querySelector('.input-source-tab.active');+ const inputSource = activeTab ? activeTab.getAttribute('data-source') : 'webcam';++ if (inputSource === 'webcam') {+ revealVideoAfterMetricsToken = token;+ await startWebcam(token);+ } else if (inputSource === 'rtsp') {+ await startRTSP(token);+ }++ }++ // Start WebRTC (Webcam mode)+ async function startWebcam(token) {+ if (window.__ALIVE_CAMERA_TRANSPORT__ === 'websocket') {+ return startWebcamUpload(token);+ }+ try {+ if (!websocket || websocket.readyState !== WebSocket.OPEN) {+ connectWebSocket();+ }++ updateStatus('Requesting camera...', 'processing');++ // Use selected camera or default+ const videoConstraints = {+ width: { ideal: 1280 },+ height: { ideal: 720 }+ };++ if (selectedCameraId) {+ videoConstraints.deviceId = { exact: selectedCameraId };+ }++ localStream = await navigator.mediaDevices.getUserMedia({+ video: videoConstraints,+ audio: false+ });++ updateStatus('Connecting...', 'processing');+ showProcessedVideoStream(localStream, token);++ peerConnection = new RTCPeerConnection({+ iceServers: window.__ALIVE_ICE_SERVERS__ || [{ urls: 'stun:stun.l.google.com:19302' }]+ });++ localStream.getTracks().forEach(track => {+ peerConnection.addTrack(track, localStream);+ });++ peerConnection.ontrack = (event) => {+ console.log('Received remote track');+ };++ peerConnection.oniceconnectionstatechange = () => {+ console.log('ICE connection state:', peerConnection.iceConnectionState);+ switch (peerConnection.iceConnectionState) {+ case 'connected':+ if (isAnalysisRunning) {+ updateStatus('Streaming', 'connected');+ }+ break;+ case 'disconnected':+ case 'failed':+ case 'closed':+ updateStatus('Disconnected', 'disconnected');+ stop();+ break;+ }+ };++ const offer = await peerConnection.createOffer();+ await peerConnection.setLocalDescription(offer);++ const response = await fetch('/offer', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ sdp: peerConnection.localDescription.sdp,+ type: peerConnection.localDescription.type,+ session_id: sessionId,+ }),+ });++ const answer = await response.json();+ await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));++ } catch (error) {+ console.error('Error starting webcam:', error);+ updateStatus(`Error: ${error.message}`, 'disconnected');+ setVideoWaitingForStream(false);+ stop();+ }+ }++ // Browser-camera transport for deployments where WebRTC UDP cannot reach+ // the compute node (for example, an HTTPS reverse tunnel). Frames travel+ // as bounded JPEGs over the authenticated WebSocket; the local stream is+ // still shown immediately as the preview.+ async function startWebcamUpload(token) {+ try {+ if (!websocket || websocket.readyState !== WebSocket.OPEN) {+ connectWebSocket();+ await new Promise((resolve, reject) => {+ const deadline = Date.now() + 10000;+ const poll = () => {+ if (websocket && websocket.readyState === WebSocket.OPEN) return resolve();+ if (Date.now() > deadline) return reject(new Error('Control connection timed out'));+ setTimeout(poll, 100);+ };+ poll();+ });+ }+ updateStatus('Requesting camera...', 'processing');+ const videoConstraints = { width: { ideal: 1280 }, height: { ideal: 720 } };+ if (selectedCameraId) videoConstraints.deviceId = { exact: selectedCameraId };+ localStream = await navigator.mediaDevices.getUserMedia({ video: videoConstraints, audio: false });+ showProcessedVideoStream(localStream, token);++ const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';+ const url = `${protocol}//${window.location.host}/ws/camera?session_id=${encodeURIComponent(sessionId)}`;+ cameraWebsocket = new WebSocket(url);+ cameraWebsocket.binaryType = 'arraybuffer';+ const ws = cameraWebsocket;+ ws.onopen = () => {+ if (cameraWebsocket !== ws) return;+ const canvas = document.createElement('canvas');+ const context = canvas.getContext('2d', { alpha: false });+ const sendFrame = () => {+ if (cameraWebsocket !== ws || ws.readyState !== WebSocket.OPEN || !videoElement.videoWidth) return;+ const maxShortEdge = 480;+ const scale = Math.min(1, maxShortEdge / Math.min(videoElement.videoWidth, videoElement.videoHeight));+ canvas.width = Math.max(1, Math.round(videoElement.videoWidth * scale));+ canvas.height = Math.max(1, Math.round(videoElement.videoHeight * scale));+ context.drawImage(videoElement, 0, 0, canvas.width, canvas.height);+ canvas.toBlob(blob => {+ if (blob && ws.readyState === WebSocket.OPEN) ws.send(blob);+ }, 'image/jpeg', 0.72);+ };+ const intervalMs = Math.max(500, Number(processEvery?.value || 1) * 1000);+ cameraCaptureTimer = setInterval(sendFrame, intervalMs);+ sendFrame();+ updateStatus('Streaming', 'connected');+ };+ ws.onmessage = event => {+ try {+ const data = JSON.parse(event.data);+ if (data.type === 'frame_error') console.warn('Camera frame:', data.message);+ } catch (_) {}+ };+ ws.onerror = () => updateStatus('Camera connection error', 'disconnected');+ ws.onclose = () => {+ if (cameraWebsocket === ws && isAnalysisRunning) {+ stopVoiceMode('Camera connection closed. Restart the video to continue.');+ updateStatus('Disconnected', 'disconnected');+ }+ };+ } catch (error) {+ console.error('Error starting webcam upload:', error);+ updateStatus(`Error: ${error.message}`, 'disconnected');+ setVideoWaitingForStream(false);+ stop();+ }+ }++ // Start RTSP mode+ async function startRTSP(token) {+ try {+ if (!websocket || websocket.readyState !== WebSocket.OPEN) {+ connectWebSocket();+ }++ const rtspUrl = document.getElementById('rtspUrl').value.trim();++ if (!rtspUrl) {+ alert('Please enter an RTSP URL');+ setVideoWaitingForStream(false);+ resetVideoButtons();+ return;+ }++ updateStatus('Connecting to RTSP stream...', 'processing');++ // Create WebRTC peer connection (no local stream needed for RTSP)+ peerConnection = new RTCPeerConnection({+ iceServers: window.__ALIVE_ICE_SERVERS__ || [{ urls: 'stun:stun.l.google.com:19302' }]+ });++ // Receive processed video from server+ peerConnection.ontrack = (event) => {+ console.log('Received RTSP stream from server');+ if (event.track.kind === 'video') {+ showProcessedVideoStream(event.streams[0], token);+ }+ };++ peerConnection.oniceconnectionstatechange = () => {+ console.log('ICE connection state:', peerConnection.iceConnectionState);+ switch (peerConnection.iceConnectionState) {+ case 'connected':+ if (isAnalysisRunning) {+ updateStatus('Streaming', 'connected');+ }+ break;+ case 'disconnected':+ case 'failed':+ case 'closed':+ updateStatus('Disconnected', 'disconnected');+ stop();+ break;+ }+ };++ // Create offer (recvonly - we're only receiving video from server)+ peerConnection.addTransceiver('video', { direction: 'recvonly' });+ const offer = await peerConnection.createOffer();+ await peerConnection.setLocalDescription(offer);++ // Wait for ICE gathering to complete before sending offer (with timeout)+ // This ensures all ICE candidates are embedded in the SDP+ console.log('Waiting for ICE gathering to complete...');+ await new Promise((resolve) => {+ if (peerConnection.iceGatheringState === 'complete') {+ resolve();+ } else {+ const checkState = () => {+ if (peerConnection.iceGatheringState === 'complete') {+ peerConnection.removeEventListener('icegatheringstatechange', checkState);+ resolve();+ }+ };+ peerConnection.addEventListener('icegatheringstatechange', checkState);++ // Timeout after 5 seconds - proceed anyway to avoid hanging+ setTimeout(() => {+ peerConnection.removeEventListener('icegatheringstatechange', checkState);+ console.warn('ICE gathering timeout - proceeding anyway');+ resolve();+ }, 5000);+ }+ });+ console.log('ICE gathering state:', peerConnection.iceGatheringState, '- sending offer');++ // Send offer with RTSP URL and session to server+ const response = await fetch('/offer', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ sdp: peerConnection.localDescription.sdp,+ type: peerConnection.localDescription.type,+ rtsp_url: rtspUrl,+ session_id: sessionId,+ })+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || 'Failed to connect to RTSP stream');+ }++ const answer = await response.json();+ await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));++ // Disable RTSP URL field and Test button while streaming+ rtspUrlInput.disabled = true;+ document.getElementById('testRtspBtn').disabled = true;++ } catch (error) {+ console.error('Error starting RTSP:', error);+ updateStatus(`Error: ${error.message}`, 'disconnected');+ alert('Failed to connect to RTSP stream: ' + error.message);+ setVideoWaitingForStream(false);+ resetVideoButtons();+ if (peerConnection) {+ peerConnection.close();+ peerConnection = null;+ }+ }+ }++ // Stop (handles both webcam and RTSP)+ async function stop({ clearConversation = false } = {}) {+ stopVoiceMode();+ streamStartToken += 1;+ isAnalysisRunning = false;+ revealVideoAfterMetricsToken = null;+ cancelRevealVideoFallback();+ mobileVoiceMode = false;+ closeTtsWebSocket();+ restorePromptEditorHome();+ updatePromptAvailability();+ if (asrRecording || asrStream || asrAudioContext) {+ await stopSpeech({ sendEnd: false, sendPrompt: false });+ }++ // Reset overlay buttons+ resetVideoButtons();++ if (fadeTimeout) {+ clearTimeout(fadeTimeout);+ fadeTimeout = null;+ }++ // Stop webcam (if in webcam mode)+ if (localStream) {+ localStream.getTracks().forEach(track => track.stop());+ localStream = null;+ }++ if (cameraCaptureTimer) {+ clearInterval(cameraCaptureTimer);+ cameraCaptureTimer = null;+ }+ if (cameraWebsocket) {+ cameraWebsocket.close();+ cameraWebsocket = null;+ }++ // Close WebRTC peer connection (used by both webcam and RTSP)+ if (peerConnection) {+ peerConnection.close();+ peerConnection = null;+ }++ videoElement.srcObject = null;+ setVideoWaitingForStream(false);++ // Reset session after local tracks are stopped so the backend can cancel+ // any in-flight VLM call and remove old session state.+ await resetSession({ clearConversation, cleanupServer: true });++ updateStatus('Connected', 'connected');++ // Re-enable RTSP URL field and Test button+ const rtspUrlInput = document.getElementById('rtspUrl');+ if (rtspUrlInput) {+ rtspUrlInput.disabled = false;+ }+ const testRtspBtn = document.getElementById('testRtspBtn');+ if (testRtspBtn) {+ testRtspBtn.disabled = false;+ }+ }++ // Sidebar start/stop buttons removed - using overlay buttons instead+ // startBtn.addEventListener('click', start);+ // stopBtn.addEventListener('click', stop);++ // Load on page load+ window.addEventListener('load', async () => {+ connectWebSocket();++ // Fallback for older servers that do not send server_config.+ setTimeout(() => {+ if (!serverConfigApplied) {+ checkApiKeyRequirement(apiBaseUrl.value);+ fetchModels();+ }+ }, 1000);++ // Initialize prompt display+ const initialPrompt = promptText.value.trim();+ if (initialPrompt) {+ currentPromptText = initialPrompt;+ }++ // Initialize Lucide icons+ lucide.createIcons();+ });+ </script>+++ <script>+ (() => {+ const history = document.getElementById('resultTextContent');+ const refreshEmpty = () => {+ if (!history.textContent.trim() && !history.querySelector('.alive-empty')) {+ const note=document.createElement('div'); note.className='alive-empty';+ note.textContent='Open your camera, then ask a question — or tell ALIVE what to watch for.';+ history.appendChild(note);+ } else if (history.querySelector('.alive-empty') && history.children.length > 1) {+ history.querySelector('.alive-empty').remove();+ }+ };+ new MutationObserver(refreshEmpty).observe(history,{childList:true}); refreshEmpty();+ })();+ </script>+<script>+(() => {+ 'use strict';+ const translations = {+ 'Connected': '已连接', 'Disconnected': '未连接', 'Connecting...': '正在连接…',+ 'Reconnecting...': '正在重连…', 'Streaming': '运行中', 'Ready': '就绪',+ 'Light': '浅色', 'Dark': '深色', 'Auto': '自动', 'Settings': '设置',+ 'Interface language': '界面语言', 'Voice': '语音', 'TTS voice': '音色',+ 'Voice for spoken replies': '模型语音回复的音色',+ 'Loading voices…': '正在加载音色…', 'Voices unavailable': '音色暂不可用',+ 'Layout': '布局', 'Main Content Order': '主区域顺序',+ 'Choose which element appears at the top': '选择上下排列时首先显示的内容',+ 'Camera → Conversation': '摄像头 → 对话', 'Conversation → Camera': '对话 → 摄像头',+ 'Responses on Camera View': '在画面上显示回复',+ 'Show text overlay directly on video feed': '将回复文字叠加到摄像头画面上',+ 'None': '不显示', 'At the top': '顶部', 'At the bottom': '底部',+ 'Visual Effects': '视觉效果', 'Pop-in Animation': '弹出动画',+ 'Scale animation when new VLM response arrives': '新回复出现时播放缩放动画',+ 'Green Glow Effect': '高亮光晕', 'Border glow on new VLM response': '新回复出现时高亮边框',+ 'Fade Effect': '淡出效果', 'Gradually fade response after 2 seconds': '回复出现 2 秒后逐渐淡出',+ 'Visual Style': '视觉风格', 'Colorful UI Accents': '彩色界面点缀',+ 'Color-coded icons and input focus glows': '使用彩色图标和输入框聚焦光晕',+ 'Max Video Latency (seconds)': '最大视频延迟(秒)',+ 'Drop old frames if delay exceeds this (0 = no intervention)': '超过该延迟时丢弃旧帧(0 表示不干预)',+ 'Use Auto / 中 / 英 below the message box to switch both speech input and output. Auto detects your speech language and reads replies in their original language.': '使用输入框下方的“自动 / 中 / 英”切换语音输入和输出语言。自动模式会识别说话语言,并按回复原文语言朗读。',+ 'Full duplex (experimental)': '全双工(实验功能)',+ 'Keep listening while replies play; speak to interrupt. Off on every page load. Turn on Mic and Sound below. Headphones recommended; if speaker echo triggers interruptions, turn this off.': '播放回复时继续聆听,开口即可打断。每次打开页面默认关闭,请先开启下方的麦克风和声音。建议使用耳机;如果扬声器回声导致误打断,请关闭此功能。',+ 'Checking voice service…': '正在检查语音服务…',+ 'English and Chinese voice ready': '中英文语音服务已就绪',+ 'Microphone unavailable; sound and text input are ready': '麦克风暂不可用;可播放声音和输入文字',+ 'Microphone ready; sound is unavailable': '麦克风已就绪;声音暂不可用',+ 'Voice unavailable; use text input': '语音暂不可用,请输入文字',+ 'Speak replies': '朗读回复',+ 'Off by default. Read replies in English or Chinese when enabled': '默认关闭,开启后朗读中文或英文回复',+ 'Background Model': '后台模型', 'Enable delegation solver': '启用后台任务处理',+ 'Use ALIVE for delegated questions, visual reasoning, and chart tasks in the background': '使用 ALIVE 在后台处理委托问题、视觉推理和图表任务',+ 'Frame multiplier': '帧数倍率',+ 'Background frames per second relative to foreground streaming FPS': '后台每秒帧数相对于前台流式帧率的倍数',+ 'Max background frames': '后台最大帧数',+ 'Recent background frame cache cap; default and maximum are 100': '后台最近帧的缓存上限;默认值和最大值均为 100',+ 'Debug': '调试', 'Show request payload': '显示请求内容',+ 'Include request JSON (image + prompt) under the prompt area; collapsed by default': '在输入区域下显示请求 JSON(图像和提示词),默认折叠',+ 'Show response payload': '显示响应内容',+ 'Include API response JSON under the VLM output; collapsed by default': '在模型输出下显示接口响应 JSON,默认折叠',+ 'Show memory state': '显示记忆状态',+ 'Display mid-term and long-term memory content below VLM output': '在模型输出下显示中期和长期记忆内容',+ 'VLM API Configuration': '视觉模型接口配置', 'API Base URL': '接口基础地址',+ 'Current VLM endpoint': '当前视觉模型接口', 'API Key (Optional)': 'API 密钥(可选)',+ 'Leave empty for local deployment.': 'OpenAI、NVIDIA API Catalog 等服务需要密钥',+ 'Model Selection': '模型选择', 'Video Source': '视频来源', 'Webcam': '摄像头',+ 'RTSP Stream': 'RTSP 视频流', 'BETA': '测试版', 'Camera Selection': '选择摄像头',+ 'No cameras found': '未找到摄像头', 'Error detecting cameras': '检测摄像头失败',+ 'Select camera device to use for VLM analysis': '选择供视觉模型分析的摄像头设备',+ 'RTSP Stream URL': 'RTSP 视频流地址', 'Format:': '格式:', 'Examples:': '示例:',+ 'Beta:': '测试版:', 'Tested with Reolink RLC-811A. Other cameras may work.': '已测试 Reolink RLC-811A,其他摄像头也可能适用。',+ 'Learn more': '了解更多', 'Processing Interval': '推理间隔',+ 'Seconds between each VLM inference (default: 1s)': '每次视觉模型推理的间隔秒数(默认 1 秒)',+ 'Frames per Batch': '每批帧数', 'Number of frames batched per inference (default: 1)': '每次推理输入的帧数(默认 1 帧)',+ 'Speaking:': '正在朗读:', 'Model:': '模型:', 'ms': '毫秒', 'Avg:': '平均:', 'Count:': '次数:',+ 'Request payload (debug)': '请求内容(调试)', 'Response payload (debug)': '响应内容(调试)',+ 'Mid-term memory': '中期记忆', 'Long-term memory': '长期记忆',+ 'Plain Text': '纯文本',+ 'Open your camera, then ask a question — or tell ALIVE what to watch for.': '打开摄像头后即可提问,或告诉 ALIVE 需要留意什么。',+ 'A conversation starts with a shared view. Open your camera, then ask ALIVE a question — or tell it what to watch for.': '从分享画面开始对话。打开摄像头后向 ALIVE 提问,或告诉它需要留意什么。',+ 'Describe the current scene in one sentence': '用一句话描述当前画面',+ 'Describe the scene': '描述画面', 'Identify the object I am holding': '识别我手中的物品',+ 'Identify an object': '识别物品', 'Tell me the color of my clothing': '告诉我衣服的颜色',+ 'Clothing color': '衣服颜色', 'Describe what I am doing': '描述我正在做什么',+ 'Describe my action': '描述动作', 'Quick prompts': '快捷提示',+ 'YOUR VIEW': '你的画面', 'A shared view, a new perspective.': '共享视野,发现新角度。',+ 'Start your camera to begin.': '打开摄像头即可开始。', 'Open camera': '打开摄像头',+ 'Start': '开始', 'Stop': '停止', 'Stop camera': '关闭摄像头', 'Stop video': '停止视频',+ 'Starting...': '正在启动…', 'Starting…': '正在启动…', 'Stopping...': '正在停止…',+ 'Front': '前置', 'Rear': '后置', 'Responses': '回复', 'Mirror': '镜像',+ 'Refresh page': '刷新页面', 'Select preset API endpoint': '选择预设接口',+ 'Refresh available models': '刷新模型列表',+ 'RTSP IP Camera (Beta - Tested with Reolink RLC-811A)': 'RTSP 网络摄像头(测试版,已测试 Reolink RLC-811A)',+ 'Test Connection': '测试连接',+ 'Model processing time; excludes ASR, TTS, and public network delay': '模型处理耗时,不包括语音识别、语音合成和公网延迟',+ 'Toggle Markdown Rendering': '切换 Markdown 渲染', 'Copy to clipboard': '复制到剪贴板',+ 'Ask about what you see…': '问问你看到的内容…',+ 'Open your camera to start a conversation': '打开摄像头开始对话',+ 'Start the video to speak': '先打开视频再说话', 'Start the video to send': '先打开视频再发送',+ 'Send prompt': '发送消息', 'Voice controls': '语音控制',+ 'Mic off': '麦克风关', 'Mic on': '麦克风开', 'Sound off': '声音关', 'Sound on': '声音开',+ 'Turn microphone on': '开启麦克风', 'Turn microphone off': '关闭麦克风',+ 'Turn spoken replies on': '开启回复朗读', 'Turn spoken replies off': '关闭回复朗读',+ 'Speech input and output language': '语音输入和输出语言',+ 'Detect speech and reply language': '自动识别语音和回复语言',+ 'Chinese speech input and output': '中文语音输入和输出',+ 'English speech input and output': '英文语音输入和输出',+ 'Toggle fullscreen': '切换全屏', 'Switch front/rear camera': '切换前后摄像头', 'Mirror video': '镜像画面',+ 'Microphone and sound are off': '麦克风和声音均已关闭',+ 'Microphone off · Spoken replies on': '麦克风已关闭 · 回复朗读已开启',+ 'Microphone access requires HTTPS or localhost.': '麦克风需要通过 HTTPS 或 localhost 访问。',+ 'Microphone access is unavailable in this browser.': '此浏览器无法访问麦克风。',+ 'Allow microphone access in your browser and try again.': '请在浏览器中允许麦克风访问,然后重试。',+ 'No microphone found.': '未找到麦克风。',+ 'Microphone is off; replies will be spoken': '麦克风已关闭;回复将自动朗读',+ 'Microphone off': '麦克风已关闭', 'Sound could not start. Please retry.': '声音启动失败,请重试。',+ 'Speech output is unavailable': '语音输出暂不可用', 'Speech input is unavailable': '语音输入暂不可用',+ 'Starting camera…': '正在打开摄像头…',+ 'Speaking + listening — speak to interrupt': '正在朗读并聆听,开口可打断',+ 'Speaking — connecting microphone…': '正在朗读,连接麦克风中…',+ 'Speaking — microphone paused': '正在朗读,麦克风已暂停',+ 'Listening — pause to send': '正在聆听,停顿后发送',+ 'Listening — waiting for reply…': '正在聆听,等待回复中…',+ 'Listening — full duplex': '正在聆听,全双工模式', 'Waiting for a reply…': '正在等待回复…',+ 'Sending…': '正在发送…', 'Connecting microphone…': '正在连接麦克风…',+ 'Release to send': '松开发送', 'Stop speaking': '结束说话', 'Hold to speak': '按住说话',+ 'Speak': '说话', 'Speak EN': '说英文', 'Speak ZH': '说中文',+ 'Stop the video before changing this setting': '请先停止视频再修改此设置',+ 'Voice service unavailable. Click to retry.': '语音服务暂不可用,点击重试。',+ 'Speech connection failed. Please retry.': '语音连接失败,请重试。',+ 'Speech connection interrupted. Please retry.': '语音连接中断,请重试。',+ 'Speech playback failed. Continuing with the next reply.': '语音播放失败,将继续下一条回复。',+ 'Preparing first metrics...': '正在准备首次统计…', 'Model configured': '模型已配置',+ 'Start the video and wait for the connection before sending.': '请启动视频并等待连接后再发送。',+ 'Message not sent. Please retry.': '消息未发送,请重试。',+ 'Reply delayed. You can keep speaking.': '回复有延迟,你可以继续说话。',+ 'No reply yet. You can retry with voice or text.': '暂未收到回复,可使用语音或文字重试。',+ 'Camera did not start. Check permissions and retry.': '摄像头未启动,请检查权限并重试。',+ 'Microphone could not start. Check permissions and retry.': '麦克风未启动,请检查权限并重试。',+ 'Microphone paused. Click to resume.': '麦克风已暂停,点击恢复。',+ 'Speech recognition unavailable. Click to retry.': '语音识别暂不可用,点击重试。',+ 'Microphone connection closed. Click to retry.': '麦克风连接已关闭,点击重试。',+ 'Speech recognition connection failed. Please retry.': '语音识别连接失败,请重试。',+ 'Microphone connection failed. Click to retry.': '麦克风连接失败,点击重试。',+ 'Voice unavailable. Please use text input.': '语音暂不可用,请输入文字。',+ 'Start the video first': '请先启动视频',+ 'Message not sent. Your text is kept for retry.': '消息未发送,文字已保留,可重试。',+ 'API settings updated': '接口设置已更新',+ 'Connection interrupted. Click to resume when connected.': '连接中断,重新连接后点击恢复。',+ 'Requesting camera...': '正在请求摄像头权限…', 'Camera connection error': '摄像头连接错误',+ 'Camera connection closed. Restart the video to continue.': '摄像头连接已关闭,请重启视频。',+ 'Connecting to RTSP stream...': '正在连接 RTSP 视频流…',+ 'Summary': '摘要', 'Related question': '相关问题', 'Jump': '跳转',+ 'Background model failed': '后台模型处理失败',+ 'Background result is ready. View it now?': '后台结果已就绪,要现在查看吗?',+ 'Background model is working...': '后台模型正在处理…',+ 'Jump to the background result': '跳转到后台结果', 'Jump to the original question': '跳转到原始问题',+ 'Collapse': '收起', 'View': '查看', 'Waiting': '等待中', 'Copy': '复制', 'Copied': '已复制',+ 'Preview': '预览', 'Raw': '原文', 'Close': '关闭',+ 'Background model failed.': '后台模型处理失败。',+ 'Loading models...': '正在加载模型…', 'No models available': '暂无可用模型', 'Error loading models': '加载模型失败',+ '⚠️ Please enter an RTSP URL': '⚠️ 请输入 RTSP 地址', '🔄 Testing connection...': '🔄 正在测试连接…'+ };+ const languageKey = 'alive-demo:uiLanguage';+ const voiceKey = 'alive-demo:ttsVoice';+ const read = key => { try { return localStorage.getItem(key); } catch { return null; } };+ const save = (key, value) => { try { localStorage.setItem(key, value); } catch {} };+ let language = read(languageKey) === 'zh' ? 'zh' : 'en';+ let voice = read(voiceKey) || 'serena';+ const original = new WeakMap();+ const originalAttributes = new WeakMap();+ const protectedContent = 'script,style,svg,textarea,input,pre,code,iframe,[contenteditable],[data-no-ui-translate],.result-prompt,.markdown-rendered:not(#resultTextContent),.result-text-content:not(#resultTextContent),#ttsSpeakingText,#videoOverlay,#fullscreenVlmContent,#currentPrompt,#requestPayloadContent,#responsePayloadContent,#midTermMemoryContent,#longTermMemoryContent';+ const historyControls = '.alive-empty,#markdownToggle,#copyButton,.background-summary-label,.background-result-title,.background-result-action,.background-origin-action,.background-jump-button,.background-jump-question-label,.background-view-toolbar,.background-raw-toolbar';+ function excluded(node, attribute = false) {+ const e = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;+ if (!e || e.closest(attribute ? protectedContent.replace('textarea,input,', '') : protectedContent)) return true;+ return Boolean(e.closest('#resultTextContent,.result-text') && !e.closest(historyControls));+ }+ function translate(source) {+ if (language !== 'zh') return source;+ const key = source.trim();+ const translated = translations[key];+ return translated ? source.replace(key, translated) : source;+ }+ function applyText(node) {+ if (excluded(node)) return;+ const current = node.nodeValue;+ let state = original.get(node);+ if (!state || state.rendered !== current) state = { source: current };+ state.rendered = translate(state.source);+ original.set(node, state);+ if (current !== state.rendered) node.nodeValue = state.rendered;+ }+ function applyAttribute(element, attribute) {+ if (excluded(element, true)) return;+ const current = element.getAttribute(attribute);+ if (current === null) return;+ const states = originalAttributes.get(element) || {};+ let state = states[attribute];+ if (!state || state.rendered !== current) state = { source: current };+ state.rendered = translate(state.source);+ states[attribute] = state;+ originalAttributes.set(element, states);+ if (current !== state.rendered) element.setAttribute(attribute, state.rendered);+ }+ const languageControl = document.createElement('div');+ languageControl.className = 'ui-language-control';+ languageControl.setAttribute('role', 'group');+ languageControl.setAttribute('aria-label', 'Interface language');+ languageControl.innerHTML = '<button type="button" data-ui-language="zh" data-no-ui-translate lang="zh-CN">中文</button><button type="button" data-ui-language="en" data-no-ui-translate lang="en">EN</button>';+ document.querySelector('.header-right').prepend(languageControl);+ const voiceControl = document.createElement('label');+ voiceControl.className = 'tts-voice-control';+ voiceControl.htmlFor = 'ttsVoiceSelect';+ voiceControl.innerHTML = '<span>TTS voice</span><select id="ttsVoiceSelect" title="Voice for spoken replies" disabled><option>Loading voices…</option></select>';+ document.getElementById('voiceModeStatus').before(voiceControl);+ const voiceSelect = document.getElementById('ttsVoiceSelect');+ voiceSelect.addEventListener('change', () => {+ voice = voiceSelect.value;+ save(voiceKey, voice);+ });+ const observer = new MutationObserver(records => {+ if (records.some(record => !excluded(record.target, record.type === 'attributes') ||+ [...record.addedNodes].some(node => node.nodeType === Node.ELEMENT_NODE &&+ (node.matches(historyControls) || node.querySelector(historyControls))))) schedule();+ });+ let scheduled = false;+ function schedule() {+ if (scheduled) return;+ scheduled = true;+ queueMicrotask(applyLanguage);+ }+ function applyLanguage() {+ scheduled = false;+ observer.disconnect();+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);+ while (walker.nextNode()) applyText(walker.currentNode);+ document.querySelectorAll('[title],[placeholder],[aria-label]').forEach(element => {+ for (const attribute of ['title', 'placeholder', 'aria-label']) applyAttribute(element, attribute);+ });+ document.documentElement.lang = language === 'zh' ? 'zh-CN' : 'en';+ languageControl.querySelectorAll('button').forEach(button => button.setAttribute('aria-pressed', String(button.dataset.uiLanguage === language)));+ observer.observe(document.body, {subtree:true, childList:true, characterData:true, attributes:true, attributeFilter:['title','placeholder','aria-label']});+ }+ languageControl.addEventListener('click', event => {+ const button = event.target.closest('[data-ui-language]');+ if (!button) return;+ language = button.dataset.uiLanguage;+ save(languageKey, language);+ applyLanguage();+ });+ const names = {serena:'Serena', vivian:'Vivian', uncle_fu:'Uncle Fu', ryan:'Ryan', aiden:'Aiden', ono_anna:'Ono Anna', sohee:'Sohee', eric:'Eric', dylan:'Dylan'};+ async function loadVoices() {+ try {+ const response = await fetch('/api/tts/config', {signal:AbortSignal.timeout(10000)});+ if (!response.ok) throw new Error('Voice configuration unavailable');+ const config = await response.json();+ const choices = config.available_voices;+ if (!Array.isArray(choices) || !choices.length) throw new Error('No available voices');+ if (!choices.includes(voice)) voice = config.default_voice || choices[0];+ voiceSelect.replaceChildren(...choices.map(id => new Option(names[id] || id, id)));+ voiceSelect.value = voice;+ voiceSelect.disabled = false;+ save(voiceKey, voice);+ } catch (error) {+ voiceSelect.replaceChildren(new Option('Voices unavailable', ''));+ voiceSelect.disabled = true;+ setTimeout(loadVoices, 15000);+ }+ schedule();+ }+ window.aliveUi = { get voice() { return voice; }, get language() { return language; } };+ applyLanguage();+ loadVoices();+})();++</script>+<script>+(() => {+ let ownedSession = null;+ let acquiring = false;+ let lastState = null;+ let networkError = false;+ const status = document.createElement('span');+ status.className = 'admission-status';+ status.setAttribute('role', 'status');+ status.setAttribute('data-no-ui-translate', '');+ document.querySelector('.header-right').prepend(status);+ const zh = () => document.documentElement.lang.startsWith('zh');+ function render() {+ const mine = lastState?.mine && ownedSession === sessionId;+ const busy = lastState?.busy && !mine;+ const text = networkError ? (zh()?'连接检查中':'Checking connection')+ : mine ? (zh()?'你正在使用':'Your session')+ : busy ? (zh()?'有人使用中':'In use')+ : (zh()?'空闲 · 单人使用':'Available · one at a time');+ if (status.textContent !== text) status.textContent = text;+ status.dataset.busy = String(Boolean(busy));+ const title = busy ? (zh()?'其他人正在使用,请等待对方停止或断开连接。':'Someone else is using ALIVE. Please wait until they stop or disconnect.')+ : (zh()?'打开摄像头后占用,停止后释放。':'Opening your camera reserves ALIVE; stopping releases it.');+ if (status.title !== title) status.title = title;+ if (!isAnalysisRunning) document.getElementById('bigStartBtn').disabled = Boolean(busy || acquiring || networkError);+ }+ async function request(path, sid, method='POST') {+ const response = await fetch('/api/use/'+path+(method==='GET'?'?session_id='+encodeURIComponent(sid):''), {+ method, cache:'no-store', signal:AbortSignal.timeout(12000),+ ...(method==='POST'?{headers:{'Content-Type':'application/json'},body:JSON.stringify({session_id:sid})}:{})+ });+ const state = await response.json();+ return {response,state};+ }+ async function releaseOwned(sid=ownedSession) {+ if (!sid) return;+ if (ownedSession===sid) ownedSession=null;+ try { await request('release',sid); } catch { /* lease expiry recovers disconnects */ }+ }+ const originalStart = start;+ start = async function(...args) {+ if (acquiring || isAnalysisRunning) return;+ acquiring=true; render();+ const sid=sessionId;+ try {+ const {response,state}=await request('acquire',sid);+ lastState=state; networkError=false;+ if (!response.ok || !state.mine) {+ stopVoiceMode(zh()?'有人正在使用,请稍后重试。':'ALIVE is in use. Please try again later.');+ return;+ }+ ownedSession=sid;+ await originalStart(...args);+ } catch (error) {+ await releaseOwned(sid);+ networkError=true;+ stopVoiceMode(zh()?'连接失败,请稍后重试。':'Connection failed. Please try again.');+ } finally {+ acquiring=false; render();+ }+ };+ const originalStop = stop;+ stop = async function(...args) {+ const sid=ownedSession;+ try { return await originalStop(...args); }+ finally { await releaseOwned(sid); await refresh(); }+ };+ let checking=false;+ async function refresh() {+ if (checking) return;+ checking=true;+ try {+ const {response,state}=await request(ownedSession?'heartbeat':'status',ownedSession||sessionId,ownedSession?'POST':'GET');+ networkError=false; lastState=state;+ if (ownedSession && (!response.ok || !state.mine)) {+ ownedSession=null;+ await originalStop();+ }+ } catch { networkError=true; }+ finally { checking=false; render(); }+ }+ window.addEventListener('pagehide',()=>{+ if (ownedSession) navigator.sendBeacon('/api/use/release',new Blob([JSON.stringify({session_id:ownedSession})],{type:'application/json'}));+ });+ new MutationObserver(render).observe(document.documentElement,{attributes:true,attributeFilter:['lang']});+ setInterval(refresh,5000);+ refresh();+})();++</script>+</body>+</html>diff --git a/Web_Inference/webui/src/alive_webui/video_processor.py b/Web_Inference/webui/src/alive_webui/video_processor.pynew file mode 100644index 0000000..417663f--- /dev/null+++ b/Web_Inference/webui/src/alive_webui/video_processor.py@@ -0,0 +1,437 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""+Video Track Processor+Handles video frames, adds text overlays, and manages VLM processing+"""++import asyncio+import numpy as np+from PIL import Image+from aiortc import VideoStreamTrack+from aiortc.mediastreams import MediaStreamError+from typing import Optional+import logging+import time+import av++from .vlm_service import VLMService++# Enable swscaler warnings to track hardware acceleration status+# TODO: Implement hardware-accelerated color space conversion on Jetson using NVMM/VPI+av.logging.set_level(av.logging.WARNING)++logger = logging.getLogger(__name__)++_cv2_module = None+++def get_cv2():+ """Import cv2 only when frame conversion/overlay actually needs it."""+ global _cv2_module+ if _cv2_module is None:+ import cv2++ _cv2_module = cv2+ return _cv2_module+++class VideoProcessorTrack(VideoStreamTrack):+ """+ Video track that receives frames, sends them to VLM for analysis,+ and overlays responses on the video before sending back+ """++ # Class variable for processing interval in seconds (can be updated dynamically)+ process_interval_seconds = 1.0+ # Max allowed latency before dropping frames (in seconds, 0 = disabled)+ max_frame_latency = 0.0+ # Number of frames to batch per VLM inference (1 = original behavior)+ frames_per_batch = 1++ def __init__(+ self,+ track: VideoStreamTrack,+ vlm_service: VLMService,+ text_callback=None,+ background_service=None,+ ):+ super().__init__()+ self.track = track+ self.vlm_service = vlm_service+ self.text_callback = text_callback # Callback to send text updates+ self.background_service = background_service+ self.last_frame: Optional[np.ndarray] = None+ self.frame_count = 0+ self.dropped_frames = 0+ self.first_frame_pts = None # Track first frame PTS to calculate relative time+ self.first_frame_time = None # Wall clock time of first frame+ self.frame_time_base = None # Time base for PTS conversion (e.g., 1/90000)+ self._last_process_time = 0.0 # Wall clock time of last VLM processing+ self._frame_buffer = [] # Buffer for collecting frames before batch send+ self._last_sub_capture_time = 0.0 # Wall clock time of last sub-frame capture+ self._last_callback_inference_count = 0+ self._last_callback_response = None++ async def recv(self):+ """+ Receive frame from input track, process it, and return with text overlay+ """+ try:+ # Get frame from incoming track+ frame = await self.track.recv()++ # Initialize timing on first frame+ if self.first_frame_pts is None and frame.pts is not None:+ self.first_frame_pts = frame.pts+ self.first_frame_time = time.time()+ # Store time_base for PTS conversion (e.g., 1/90000 for 90kHz clock)+ self.frame_time_base = float(frame.time_base)+ logger.info(+ f"Latency tracking initialized: PTS={frame.pts}, time_base={frame.time_base} ({self.frame_time_base}s per tick)"+ )++ # Calculate actual frame age (latency) using PTS and time_base+ # Note: Some streams (like RTSP) may not have PTS set, so skip latency checks+ frame_latency = 0.0+ frame_timestamp = time.time()+ timestamp_kind = "wall_clock_seconds"+ if frame.pts is not None and self.first_frame_pts is not None:+ # PTS is in time_base units, convert to seconds: pts * time_base+ frame_time_offset = (frame.pts - self.first_frame_pts) * self.frame_time_base+ expected_wall_time = self.first_frame_time + frame_time_offset+ current_time = time.time()+ frame_latency = current_time - expected_wall_time+ frame_timestamp = frame_time_offset+ timestamp_kind = "relative_seconds"++ # Check for accumulated latency and drop old frames if needed (only if max_latency > 0)+ max_latency = self.__class__.max_frame_latency+ if max_latency > 0 and frame_latency > max_latency and frame.pts is not None:+ logger.warning(+ f"Frame is {frame_latency:.2f}s behind, dropping frames (threshold: {max_latency}s)"+ )++ # Drop frames until we get a fresh one+ dropped_count = 0+ while frame_latency > max_latency:+ self.dropped_frames += 1+ dropped_count += 1++ # Get next frame+ frame = await self.track.recv()++ # Recalculate latency for new frame (using time_base for correct conversion)+ if frame.pts is not None and self.first_frame_pts is not None:+ frame_time_offset = (+ frame.pts - self.first_frame_pts+ ) * self.frame_time_base+ expected_wall_time = self.first_frame_time + frame_time_offset+ frame_latency = time.time() - expected_wall_time+ else:+ # If PTS becomes unavailable, stop dropping frames+ break++ # Prevent infinite loop+ if dropped_count > 100:+ logger.error(+ f"Dropped {dropped_count} frames, but still behind. Resetting timing."+ )+ if frame.pts is not None:+ self.first_frame_pts = frame.pts+ self.first_frame_time = time.time()+ self.frame_time_base = float(frame.time_base)+ break++ if dropped_count > 0:+ logger.info(+ f"Dropped {dropped_count} frames, now at {frame_latency:.2f}s latency"+ )++ # Increment frame counter+ self.frame_count += 1++ # Only convert to numpy when needed (for VLM processing or first frame)+ # This avoids expensive CPU color conversion on every frame+ now = time.time()+ capture_monotonic_s = time.monotonic()+ interval_sec = self.__class__.process_interval_seconds+ frames_per_batch = max(1, self.__class__.frames_per_batch)+ background_needs_frame = self._background_needs_frame(now)++ if frames_per_batch <= 1:+ # --- Original single-frame logic ---+ time_since_last = now - self._last_process_time+ need_conversion = (time_since_last >= interval_sec) or (self.frame_count == 1)++ if need_conversion or background_needs_frame:+ t1 = time.time()+ img = frame.to_ndarray(format="bgr24")+ t2 = time.time()+ self.last_frame = img.copy()+ t3 = time.time()++ if self.frame_count % 100 == 0:+ logger.info(+ f"Frame conversion times: to_ndarray={1000*(t2-t1):.1f}ms, copy={1000*(t3-t2):.1f}ms"+ )+ if self.frame_count == 1:+ logger.info(f"First frame received: {img.shape}")++ t4 = time.time()+ pil_img = Image.fromarray(img[:, :, ::-1])+ t5 = time.time()+ frame_timing_ms = {+ "frame_to_ndarray_ms": 1000 * (t2 - t1),+ "frame_copy_ms": 1000 * (t3 - t2),+ "bgr_to_rgb_pil_ms": 1000 * (t5 - t4),+ "pre_vlm_total_ms": 1000 * (t5 - t1),+ }+ if background_needs_frame:+ self._cache_background_frame(+ pil_img,+ frame_timestamp=frame_timestamp,+ timestamp_kind=timestamp_kind,+ pts=frame.pts,+ frames_per_batch=frames_per_batch,+ process_interval_seconds=interval_sec,+ wall_time=now,+ )+ if need_conversion:+ asyncio.create_task(+ self.vlm_service.process_frame(+ pil_img,+ frame_timing_ms=frame_timing_ms,+ frame_metadata={+ "timestamp": frame_timestamp,+ "timestamp_kind": timestamp_kind,+ "pts": frame.pts,+ "timestamp_interval_seconds": interval_sec,+ "capture_monotonic_s": capture_monotonic_s,+ "capture_server_unix_ms": now * 1000,+ },+ )+ )+ self._last_process_time = now+ logger.info(f"Frame {self.frame_count}: Sending to VLM (interval={interval_sec}s)")+ else:+ # --- Multi-frame batch logic ---+ sub_interval = interval_sec / frames_per_batch+ time_since_last_sub = now - self._last_sub_capture_time+ need_capture = (time_since_last_sub >= sub_interval) or (self.frame_count == 1)++ if need_capture or background_needs_frame:+ t1 = time.time()+ img = frame.to_ndarray(format="bgr24")+ t2 = time.time()+ self.last_frame = img.copy()+ t3 = time.time()+ pil_img = Image.fromarray(img[:, :, ::-1])+ t4 = time.time()++ if self.frame_count == 1:+ logger.info(f"First frame received: {img.shape}")++ if need_capture:+ self._frame_buffer.append({+ "image": pil_img,+ "timestamp": frame_timestamp,+ "timestamp_kind": timestamp_kind,+ "timestamp_interval_seconds": interval_sec,+ "capture_monotonic_s": capture_monotonic_s,+ "capture_server_unix_ms": now * 1000,+ "pts": frame.pts,+ "frame_timing_ms": {+ "frame_to_ndarray_ms": 1000 * (t2 - t1),+ "frame_copy_ms": 1000 * (t3 - t2),+ "bgr_to_rgb_pil_ms": 1000 * (t4 - t3),+ "pre_vlm_total_ms": 1000 * (t4 - t1),+ },+ })+ self._last_sub_capture_time = now++ if background_needs_frame:+ self._cache_background_frame(+ pil_img,+ frame_timestamp=frame_timestamp,+ timestamp_kind=timestamp_kind,+ pts=frame.pts,+ frames_per_batch=frames_per_batch,+ process_interval_seconds=interval_sec,+ wall_time=now,+ )++ if len(self._frame_buffer) >= frames_per_batch:+ batch = list(self._frame_buffer)+ self._frame_buffer.clear()+ asyncio.create_task(+ self.vlm_service.process_frame_batch(batch)+ )+ self._last_process_time = now+ logger.info(+ f"Frame {self.frame_count}: Sending {len(batch)} frames to VLM "+ f"(interval={interval_sec}s, batch={frames_per_batch})"+ )++ # Get current response (may be old if VLM is still processing)+ response, is_processing = self.vlm_service.get_current_response()++ # Get metrics+ metrics = self.vlm_service.get_metrics()++ # Send text update via callback (for WebSocket)+ if self.text_callback:+ inference_count = int(metrics.get("total_inferences") or 0)+ has_new_inference = inference_count > self._last_callback_inference_count+ has_new_response = response != self._last_callback_response+ if inference_count > 0 and (has_new_inference or has_new_response):+ self._last_callback_inference_count = inference_count+ self._last_callback_response = response+ handoff_meta = self.vlm_service.consume_background_handoff_metric()+ if handoff_meta:+ metrics = dict(metrics)+ metrics["background_handoff"] = handoff_meta+ self.text_callback(response, metrics)++ # Return original frame directly - zero-copy passthrough!+ # This avoids expensive BGR→YUV conversion+ return frame++ except MediaStreamError:+ # Track ended (user stopped, tab closed, etc.) — normal, not an error+ logger.debug("Video track ended")+ raise+ except Exception as e:+ logger.error(f"Error processing frame: {e}", exc_info=True)+ raise++ def _background_needs_frame(self, wall_time: float) -> bool:+ if not self.background_service:+ return False+ try:+ self.background_service.set_foreground_sampling(+ process_interval_seconds=self.__class__.process_interval_seconds,+ frames_per_batch=self.__class__.frames_per_batch,+ )+ return self.background_service.should_sample_frame(wall_time)+ except Exception:+ logger.warning("Failed to check background frame sampling", exc_info=True)+ return False++ def _cache_background_frame(+ self,+ pil_img: Image.Image,+ *,+ frame_timestamp: float,+ timestamp_kind: str,+ pts,+ frames_per_batch: int,+ process_interval_seconds: float,+ wall_time: float,+ ) -> None:+ if not self.background_service:+ return+ try:+ self.background_service.set_foreground_sampling(+ process_interval_seconds=process_interval_seconds,+ frames_per_batch=frames_per_batch,+ )+ self.background_service.add_frame(+ pil_img,+ timestamp=frame_timestamp,+ timestamp_kind=timestamp_kind,+ pts=pts,+ foreground_frames_per_batch=frames_per_batch,+ wall_time=wall_time,+ )+ except Exception:+ logger.warning("Failed to cache background frame", exc_info=True)++ def _add_text_overlay(self, img: np.ndarray, text: str, status: str = "") -> np.ndarray:+ """+ Add text overlay to image++ Args:+ img: Input image (BGR format)+ text: Text to overlay (VLM response)+ status: Optional status text++ Returns:+ Image with text overlay+ """+ img_copy = img.copy()+ cv2 = get_cv2()+ height, width = img_copy.shape[:2]++ # Prepare text+ full_text = f"{text} {status}" if status else text++ # Text wrapping - split long captions+ max_chars_per_line = 60+ words = full_text.split()+ lines = []+ current_line = []+ current_length = 0++ for word in words:+ if current_length + len(word) + 1 <= max_chars_per_line:+ current_line.append(word)+ current_length += len(word) + 1+ else:+ if current_line:+ lines.append(" ".join(current_line))+ current_line = [word]+ current_length = len(word)++ if current_line:+ lines.append(" ".join(current_line))++ # Text properties+ font = cv2.FONT_HERSHEY_SIMPLEX+ font_scale = 0.7+ font_thickness = 2+ text_color = (255, 255, 255) # White+ bg_color = (0, 0, 0) # Black background+ padding = 10+ line_height = 30++ # Calculate total height needed+ total_text_height = len(lines) * line_height + 2 * padding++ # Create semi-transparent overlay at bottom+ overlay = img_copy.copy()+ cv2.rectangle(overlay, (0, height - total_text_height), (width, height), bg_color, -1)++ # Blend overlay with original image+ alpha = 0.7+ cv2.addWeighted(overlay, alpha, img_copy, 1 - alpha, 0, img_copy)++ # Add text lines+ y_position = height - total_text_height + padding + line_height+ for line in lines:+ cv2.putText(+ img_copy,+ line,+ (padding, y_position),+ font,+ font_scale,+ text_color,+ font_thickness,+ cv2.LINE_AA,+ )+ y_position += line_height++ return img_copydiff --git a/Web_Inference/webui/src/alive_webui/vlm_service.py b/Web_Inference/webui/src/alive_webui/vlm_service.pynew file mode 100644index 0000000..f50f748--- /dev/null+++ b/Web_Inference/webui/src/alive_webui/vlm_service.py@@ -0,0 +1,790 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""+VLM Service+Handles async image analysis using any OpenAI-compatible VLM API+(Works with vLLM, SGLang, Ollama, OpenAI, etc.)+"""++import asyncio+import base64+import io+import json+import math+import re+import time+from openai import AsyncOpenAI+from PIL import Image+from typing import Optional+import logging+++logger = logging.getLogger(__name__)+++def _format_seconds_words(value: float) -> str:+ rounded = math.floor(value * 10 + 0.5) / 10+ return f"{rounded:.1f} seconds"+++class VLMService:+ """Service for analyzing images using VLM via OpenAI-compatible API"""++ def __init__(+ self,+ model: str,+ api_base: str = "http://localhost:8000/v1",+ api_key: str = "EMPTY",+ prompt: Optional[str] = None,+ max_tokens: int = 512,+ session_id: str = "default",+ ):+ self.model = model+ self.api_base = api_base+ self.api_key = api_key if api_key else "EMPTY"+ self.prompt = prompt+ self.max_tokens = max_tokens+ self.session_id = session_id++ self._question_id = None+ self.client = AsyncOpenAI(base_url=api_base, api_key=api_key)+ self.current_response = "Initializing..."+ self.is_processing = False+ self._processing_lock = asyncio.Lock()+ self._active_tasks = set()+ self._closed = False+ self._last_request_payload = None+ self._last_response_payload = None+ self.last_latency_breakdown_ms = {}+ self.last_frame_timing_ms = {}+ self.last_user_prompt = ""+ self._pending_background_handoff: Optional[dict] = None+ self._last_background_handoff_meta: Optional[dict] = None+ self._timestamp_turn_count = 0++ # Metrics tracking+ self.last_inference_time = 0.0 # seconds+ self.total_inferences = 0+ self.total_inference_time = 0.0++ def _format_frame_time_range(self, frame_metadata: Optional[dict]) -> str:+ if not frame_metadata:+ return ""++ timestamp = frame_metadata.get("timestamp")+ if timestamp is None:+ return ""++ try:+ timestamp_value = float(timestamp)+ except (TypeError, ValueError):+ return str(timestamp)++ return _format_seconds_words(timestamp_value)++ def _normalize_timestamp_interval(self, interval_seconds) -> float:+ try:+ interval = float(interval_seconds)+ except (TypeError, ValueError):+ interval = 1.0+ return max(0.0, interval)++ def _next_turn_timestamp_metadata(self, interval_seconds) -> dict:+ interval = self._normalize_timestamp_interval(interval_seconds)+ turn_index = self._timestamp_turn_count+ self._timestamp_turn_count += 1+ return {+ "timestamp": turn_index * interval,+ "timestamp_kind": "turn_seconds",+ "timestamp_turn": turn_index + 1,+ "timestamp_interval_seconds": interval,+ }++ def _apply_turn_timestamp(self, metadata: Optional[dict], turn_metadata: dict) -> dict:+ result = dict(metadata or {})+ if "timestamp" in result:+ result.setdefault("source_timestamp", result.get("timestamp"))+ if "timestamp_kind" in result:+ result.setdefault("source_timestamp_kind", result.get("timestamp_kind"))+ result.update(turn_metadata)+ return result++ def _metadata_with_next_turn_timestamp(self, metadata: Optional[dict]) -> dict:+ source = dict(metadata or {})+ turn_metadata = self._next_turn_timestamp_metadata(+ source.get("timestamp_interval_seconds")+ )+ return self._apply_turn_timestamp(source, turn_metadata)++ def _batch_with_next_turn_timestamp(self, frames_data: list) -> list:+ if not frames_data:+ return []+ first_frame = frames_data[0] if isinstance(frames_data[0], dict) else {}+ turn_metadata = self._next_turn_timestamp_metadata(+ first_frame.get("timestamp_interval_seconds")+ )+ return [+ self._apply_turn_timestamp(frame_data, turn_metadata)+ for frame_data in frames_data+ ]++ async def analyze_image(+ self,+ image: Image.Image,+ prompt: Optional[str] = None,+ frame_metadata: Optional[dict] = None,+ ) -> str:+ if prompt is None:+ prompt = self.prompt+ prompt_text = (prompt or "").strip()+ question_id = self._question_id if prompt_text else None+ record_id = None+ frame_time_range = self._format_frame_time_range(frame_metadata)++ try:+ start_time = time.perf_counter()++ # Convert PIL Image to base64+ jpeg_start = time.perf_counter()+ img_byte_arr = io.BytesIO()+ image.save(img_byte_arr, format="JPEG")+ img_byte_arr = img_byte_arr.getvalue()+ jpeg_end = time.perf_counter()++ base64_start = time.perf_counter()+ img_base64 = base64.b64encode(img_byte_arr).decode("utf-8")+ base64_end = time.perf_counter()++ request_build_start = time.perf_counter()+ image_url = f"data:image/jpeg;base64,{img_base64}"+ content = []+ if prompt_text:+ content.append({"type": "text", "text": prompt_text})+ content.append({"type": "image_url", "image_url": {"url": image_url}})+ messages = [+ {+ "role": "user",+ "content": content,+ }+ ]++ # Store request payload for debug (truncate base64 for display)+ truncate_len = 120+ if len(img_base64) > truncate_len:+ image_url_debug = f"data:image/jpeg;base64,{img_base64[:truncate_len]}...<{len(img_base64)} chars total>"+ else:+ image_url_debug = image_url+ debug_content = []+ if prompt_text:+ debug_content.append({"type": "text", "text": prompt_text})+ debug_content.append({"type": "image_url", "image_url": {"url": image_url_debug}})+ self._last_request_payload = {+ "model": self.model,+ "messages": [+ {+ "role": "user",+ "content": debug_content,+ }+ ],+ "max_tokens": self.max_tokens,+ "temperature": 0.7,+ }+ if frame_time_range:+ self._last_request_payload["frame_time_range"] = frame_time_range+ request_build_end = time.perf_counter()++ # Call API+ api_start = time.perf_counter()+ create_kwargs = {+ "model": self.model,+ "messages": messages,+ "max_tokens": self.max_tokens,+ "temperature": 0.7,+ "extra_headers": {"x-streaming-session": self.session_id},+ }+ if frame_time_range:+ create_kwargs["extra_body"] = {"frame_time_range": frame_time_range}++ response = await self.client.chat.completions.create(+ **create_kwargs,+ )+ api_end = time.perf_counter()++ # Store response payload for debug+ response_payload_start = time.perf_counter()+ try:+ self._last_response_payload = (+ response.model_dump() if hasattr(response, "model_dump") else response.dict()+ )+ except Exception:+ self._last_response_payload = {+ "id": getattr(response, "id", None),+ "model": getattr(response, "model", None),+ "choices": [+ {+ "index": getattr(c, "index", i),+ "message": {+ "role": getattr(getattr(c, "message", None), "role", None),+ "content": getattr(getattr(c, "message", None), "content", None),+ },+ "finish_reason": getattr(c, "finish_reason", None),+ }+ for i, c in enumerate(getattr(response, "choices", []))+ ],+ "usage": getattr(response, "usage", None),+ }+ response_payload_end = time.perf_counter()++ # Calculate latency+ response_extract_start = time.perf_counter()+ result = self._extract_response_text(response)++ end_time = time.perf_counter()+ inference_time = end_time - start_time++ # Update metrics+ self.last_inference_time = inference_time+ self.total_inferences += 1+ self.total_inference_time += inference_time+ self.last_latency_breakdown_ms = {+ "jpeg_encode_ms": (jpeg_end - jpeg_start) * 1000,+ "base64_encode_ms": (base64_end - base64_start) * 1000,+ "request_build_ms": (request_build_end - request_build_start) * 1000,+ "api_call_ms": (api_end - api_start) * 1000,+ "response_payload_ms": (response_payload_end - response_payload_start) * 1000,+ "response_extract_ms": (end_time - response_extract_start) * 1000,+ "total_ms": inference_time * 1000,+ }+ logger.info(f"VLM response: {result} (latency: {inference_time*1000:.0f}ms)")+ return result++ except asyncio.CancelledError:++ raise+ except Exception as e:++ logger.error(f"Error analyzing image: {e}")+ return f"Error: {str(e)}"++ def get_last_request_payload(self) -> Optional[dict]:+ return self._last_request_payload++ def get_last_response_payload(self) -> Optional[dict]:+ return self._last_response_payload++ def _track_current_task(self):+ task = asyncio.current_task()+ if task is not None:+ self._active_tasks.add(task)+ return task++ def _untrack_task(self, task) -> None:+ if task is not None:+ self._active_tasks.discard(task)++ async def cancel_active_requests(self, timeout: float = 2.0) -> int:+ """Cancel in-flight VLM processing tasks for this session."""+ current_task = asyncio.current_task()+ tasks = [+ task+ for task in self._active_tasks+ if task is not current_task and not task.done()+ ]+ if not tasks:+ self.is_processing = False+ return 0++ for task in tasks:+ task.cancel()++ done, pending = await asyncio.wait(tasks, timeout=timeout)+ if done:+ await asyncio.gather(*done, return_exceptions=True)+ for task in pending:+ logger.warning(+ "Timed out waiting for VLM task cancellation for session %s",+ self.session_id,+ )++ self.is_processing = False+ logger.info("Cancelled %s VLM task(s) for session %s", len(tasks), self.session_id)+ return len(tasks)++ def clear_state(self) -> None:+ self.current_response = "Initializing..."+ self.is_processing = False+ self.prompt = None+ self._last_request_payload = None+ self._last_response_payload = None+ self.last_latency_breakdown_ms = {}+ self.last_frame_timing_ms = {}+ self.last_user_prompt = ""+ self._pending_background_handoff = None+ self._last_background_handoff_meta = None+ self._timestamp_turn_count = 0+ self.last_inference_time = 0.0+ self.total_inferences = 0+ self.total_inference_time = 0.0++ def queue_background_handoff(+ self,+ *,+ task_id: str,+ question: str,+ summary: str,+ ) -> None:+ """Record background completion metadata for UI/metrics without prompt injection."""+ compact_summary = self._compact_text(summary, 3500)+ self._pending_background_handoff = {+ "task_id": str(task_id or ""),+ "question": str(question or ""),+ "summary": compact_summary,+ }+ logger.info(+ "Recorded background handoff metadata for interaction session %s: task_id=%s summary_chars=%s",+ self.session_id,+ task_id,+ len(compact_summary),+ )++ def _resolve_prompt_for_inference(self, explicit_prompt: Optional[str], captured_prompt: Optional[str]) -> tuple[Optional[str], bool]:+ prompt_text = explicit_prompt if explicit_prompt is not None else captured_prompt+ handoff = self._pending_background_handoff+ if handoff and handoff.get("summary"):+ self._pending_background_handoff = None+ self._last_background_handoff_meta = {+ "task_id": str(handoff.get("task_id") or ""),+ "question": str(handoff.get("question") or ""),+ "summary": str(handoff.get("summary") or ""),+ }+ return prompt_text, True+ if explicit_prompt is not None:+ return explicit_prompt, False+ if captured_prompt:+ return captured_prompt, False+ return None, False++ def _compact_text(self, text, limit: int) -> str:+ value = re.sub(r"\s+", " ", str(text or "")).strip()+ if len(value) <= limit:+ return value+ return value[: max(0, limit - 12)].rstrip() + " ...[截断]"++ async def close(self, cancel_requests: bool = True) -> None:+ self._closed = True+ if cancel_requests:+ await self.cancel_active_requests()+ self.clear_state()+++ close = getattr(self.client, "close", None)+ if close is not None:+ result = close()+ if hasattr(result, "__await__"):+ await result++ async def process_frame(+ self,+ image: Image.Image,+ prompt: Optional[str] = None,+ frame_timing_ms: Optional[dict] = None,+ frame_metadata: Optional[dict] = None,+ ) -> None:+ if self._closed:+ return++ task = self._track_current_task()+ try:+ if self._processing_lock.locked():+ logger.debug("VLM busy, skipping frame")+ return++ async with self._processing_lock:+ if self._closed:+ return+ self.is_processing = True+ try:+ self.last_frame_timing_ms = frame_timing_ms or {}+ captured_prompt = self.prompt+ used_prompt, consumed_background_handoff = self._resolve_prompt_for_inference(+ prompt,+ captured_prompt,+ )+ self.last_user_prompt = str(used_prompt or "").strip()+ request_frame_metadata = self._metadata_with_next_turn_timestamp(+ frame_metadata+ )+ response = await self.analyze_image(+ image,+ used_prompt,+ frame_metadata=request_frame_metadata,+ )+ if self._closed:+ return+ self.current_response = response+ if captured_prompt and self.prompt == captured_prompt:+ self.prompt = None+ if consumed_background_handoff:+ logger.info("Consumed background handoff metadata for session %s", self.session_id)+ finally:+ self.is_processing = False+ finally:+ self._untrack_task(task)++ async def analyze_images(+ self,+ frames_data: list,+ prompt: Optional[str] = None,+ ) -> str:+ """Analyze multiple images in a single API call (batch mode)."""+ if prompt is None:+ prompt = self.prompt+ prompt_text = (prompt or "").strip()+ question_id = self._question_id if prompt_text else None+ record_id = None++ try:+ start_time = time.perf_counter()++ content: list[dict] = []+ debug_content: list[dict] = []+ if prompt_text:+ content.append({"type": "text", "text": prompt_text})+ debug_content.append({"type": "text", "text": prompt_text})++ frame_time_ranges: list[str] = []+ for frame_data in frames_data:+ image = frame_data["image"]+ frame_metadata = {+ "timestamp": frame_data.get("timestamp"),+ "timestamp_kind": frame_data.get("timestamp_kind"),+ }++ img_byte_arr = io.BytesIO()+ image.save(img_byte_arr, format="JPEG")+ img_bytes = img_byte_arr.getvalue()++ img_base64 = base64.b64encode(img_bytes).decode("utf-8")+ image_url = f"data:image/jpeg;base64,{img_base64}"++ content.append({"type": "image_url", "image_url": {"url": image_url}})++ truncate_len = 120+ if len(img_base64) > truncate_len:+ debug_url = f"data:image/jpeg;base64,{img_base64[:truncate_len]}...<{len(img_base64)} chars>"+ else:+ debug_url = image_url+ debug_content.append({"type": "image_url", "image_url": {"url": debug_url}})++ ftr = self._format_frame_time_range(frame_metadata)+ if ftr:+ frame_time_ranges.append(ftr)++ messages = [{"role": "user", "content": content}]++ self._last_request_payload = {+ "model": self.model,+ "messages": [{"role": "user", "content": debug_content}],+ "max_tokens": self.max_tokens,+ "temperature": 0.7,+ "frame_time_ranges": frame_time_ranges,+ }++ api_start = time.perf_counter()+ create_kwargs = {+ "model": self.model,+ "messages": messages,+ "max_tokens": self.max_tokens,+ "temperature": 0.7,+ "extra_headers": {"x-streaming-session": self.session_id},+ }+ if frame_time_ranges:+ create_kwargs["extra_body"] = {"frame_time_ranges": frame_time_ranges}++ response = await self.client.chat.completions.create(**create_kwargs)+ api_end = time.perf_counter()++ try:+ self._last_response_payload = (+ response.model_dump() if hasattr(response, "model_dump") else response.dict()+ )+ except Exception:+ self._last_response_payload = None++ result = self._extract_response_text(response)++ end_time = time.perf_counter()+ inference_time = end_time - start_time++ self.last_inference_time = inference_time+ self.total_inferences += 1+ self.total_inference_time += inference_time+ self.last_latency_breakdown_ms = {+ "api_call_ms": (api_end - api_start) * 1000,+ "total_ms": inference_time * 1000,+ }+ logger.info(+ f"VLM batch response ({len(frames_data)} frames): {result} "+ f"(latency: {inference_time*1000:.0f}ms)"+ )+ return result++ except asyncio.CancelledError:++ raise+ except Exception as e:++ logger.error(f"Error analyzing images batch: {e}")+ return f"Error: {str(e)}"++ async def process_frame_batch(+ self,+ frames_data: list,+ prompt: Optional[str] = None,+ frame_timing_ms: Optional[dict] = None,+ ) -> None:+ """Process a batch of frames in a single VLM call."""+ if self._closed:+ return++ task = self._track_current_task()+ try:+ if self._processing_lock.locked():+ logger.debug("VLM busy, skipping frame batch")+ return++ async with self._processing_lock:+ if self._closed:+ return+ self.is_processing = True+ try:+ self.last_frame_timing_ms = frame_timing_ms or {}+ captured_prompt = self.prompt+ used_prompt, consumed_background_handoff = self._resolve_prompt_for_inference(+ prompt,+ captured_prompt,+ )+ self.last_user_prompt = str(used_prompt or "").strip()+ request_frames_data = self._batch_with_next_turn_timestamp(frames_data)+ response = await self.analyze_images(request_frames_data, used_prompt)+ if self._closed:+ return+ self.current_response = response+ if captured_prompt and self.prompt == captured_prompt:+ self.prompt = None+ if consumed_background_handoff:+ logger.info("Consumed background handoff metadata for session %s", self.session_id)+ finally:+ self.is_processing = False+ finally:+ self._untrack_task(task)++ def get_current_response(self) -> tuple[str, bool]:+ return self.current_response, self.is_processing++ def _extract_response_text(self, response) -> str:+ """Return assistant text from common OpenAI-compatible response shapes."""++ output_text = self._normalize_text_value(getattr(response, "output_text", None))+ if output_text:+ return output_text++ choices = getattr(response, "choices", None) or []+ if choices:+ choice = choices[0]+ message = getattr(choice, "message", None)+ if message is not None:+ for attr_name in ("content", "reasoning_content", "reasoning", "refusal"):+ text = self._normalize_text_value(getattr(message, attr_name, None))+ if text:+ return text++ tool_calls = getattr(message, "tool_calls", None)+ if tool_calls:+ return self._json_preview(tool_calls)++ for attr_name in ("text", "content"):+ text = self._normalize_text_value(getattr(choice, attr_name, None))+ if text:+ return text++ delta = getattr(choice, "delta", None)+ if delta is not None:+ text = self._normalize_text_value(getattr(delta, "content", None))+ if text:+ return text++ payload = self._response_to_dict(response)+ if payload:+ for path in (+ ("output_text",),+ ("choices", 0, "message", "content"),+ ("choices", 0, "message", "reasoning_content"),+ ("choices", 0, "message", "reasoning"),+ ("choices", 0, "message", "refusal"),+ ("choices", 0, "text"),+ ("choices", 0, "delta", "content"),+ ):+ text = self._normalize_text_value(self._get_path(payload, path))+ if text:+ return text++ finish_reason = self._response_finish_reason(response, payload)+ logger.warning(+ "VLM returned empty content for session %s; finish_reason=%s",+ self.session_id,+ finish_reason or "unknown",+ )+ return f"Empty model response{': ' + finish_reason if finish_reason else ''}"++ def _normalize_text_value(self, value) -> str:+ if value is None:+ return ""+ if isinstance(value, str):+ return value.strip()+ if isinstance(value, list):+ parts = []+ for item in value:+ if isinstance(item, dict):+ text = item.get("text") or item.get("content") or item.get("value") or ""+ else:+ text = (+ getattr(item, "text", None)+ or getattr(item, "content", None)+ or getattr(item, "value", None)+ or ""+ )+ normalized = self._normalize_text_value(text)+ if normalized:+ parts.append(normalized)+ return "\n".join(parts).strip()+ if isinstance(value, dict):+ for key in ("text", "content", "value"):+ text = self._normalize_text_value(value.get(key))+ if text:+ return text+ return self._json_preview(value)+ return str(value).strip()++ def _response_to_dict(self, response) -> dict:+ for attr_name in ("model_dump", "dict"):+ method = getattr(response, attr_name, None)+ if method is None:+ continue+ try:+ payload = method()+ except Exception:+ continue+ if isinstance(payload, dict):+ return payload+ if isinstance(response, dict):+ return response+ return {}++ def _get_path(self, payload: dict, path: tuple):+ value = payload+ for key in path:+ try:+ if isinstance(key, int):+ value = value[key]+ else:+ value = value.get(key)+ except (AttributeError, IndexError, KeyError, TypeError):+ return None+ return value++ def _response_finish_reason(self, response, payload: Optional[dict]) -> str:+ choices = getattr(response, "choices", None) or []+ if choices:+ finish_reason = getattr(choices[0], "finish_reason", None)+ if finish_reason:+ return str(finish_reason)+ finish_reason = self._get_path(payload or {}, ("choices", 0, "finish_reason"))+ return str(finish_reason) if finish_reason else ""++ def _json_preview(self, value) -> str:+ try:+ return json.dumps(value, ensure_ascii=False, default=str, indent=2).strip()+ except Exception:+ return str(value).strip()++ def get_metrics(self) -> dict:+ avg_latency = (+ self.total_inference_time / self.total_inferences if self.total_inferences > 0 else 0.0+ )++ metrics = {+ "last_latency_ms": self.last_inference_time * 1000,+ "avg_latency_ms": avg_latency * 1000,+ "total_inferences": self.total_inferences,+ "is_processing": self.is_processing,+ "latency_breakdown_ms": self.last_latency_breakdown_ms,+ "frame_timing_ms": self.last_frame_timing_ms,+ "user_prompt": self.last_user_prompt,+ }+ if self._last_background_handoff_meta:+ metrics["background_handoff"] = self._last_background_handoff_meta+ return metrics++ def consume_background_handoff_metric(self) -> Optional[dict]:+ meta = self._last_background_handoff_meta+ self._last_background_handoff_meta = None+ return meta++ def update_prompt(self, new_prompt: Optional[str], client_sent_at_ms=None) -> None:+ prompt_text = new_prompt.strip() if new_prompt else None+ self.prompt = prompt_text+ self._question_id = None+ logger.info(f"Updated prompt to: {prompt_text}")++ def update_api_settings(+ self, api_base: Optional[str] = None, api_key: Optional[str] = None+ ) -> None:+ if api_base:+ self.api_base = api_base+ if api_key is not None:+ self.api_key = api_key if api_key else "EMPTY"++ self.client = AsyncOpenAI(base_url=self.api_base, api_key=self.api_key)++ masked_key = (+ "***" + self.api_key[-4:]+ if self.api_key and len(self.api_key) > 4 and self.api_key != "EMPTY"+ else "EMPTY"+ )+ logger.info(f"Updated API settings - base: {self.api_base}, key: {masked_key}")++ async def reset_adapter_session(self) -> bool:+ """Call the adapter's /v1/streaming/reset to flush session outputs."""+ import aiohttp++ reset_url = self.api_base.rstrip("/").removesuffix("/v1") + "/v1/streaming/reset"+ try:+ async with aiohttp.ClientSession() as http:+ async with http.post(+ reset_url,+ json={"user": self.session_id},+ headers={"x-streaming-session": self.session_id},+ timeout=aiohttp.ClientTimeout(total=5),+ ) as resp:+ ok = resp.status == 200+ logger.info(+ f"Adapter reset for session {self.session_id}: status={resp.status}"+ )+ return ok+ except Exception as e:+ logger.warning(f"Adapter reset failed for session {self.session_id}: {e}")+ return False