Spaces:
Runtime error
Runtime error
Dockerize better
Browse files- .dockerignore +24 -0
- .gitignore +3 -0
- Dockerfile +55 -32
- README.md +123 -33
- backend/app.py +49 -20
- backend/config.py +21 -5
- backend/helpers/transcript.py +9 -2
- backend/ollama.py +10 -4
- backend/schemas.py +4 -1
- backend/youtube.py +8 -2
- docker-compose.override.yml +37 -0
- docker-compose.yml +66 -0
- environment.yml +23 -0
- frontend/index.html +1 -1
- frontend/public/logo.svg +42 -0
- frontend/{src/assets/logo.svg → public/old_logo.svg} +0 -0
- frontend/public/vite.svg +0 -1
- frontend/src/App.jsx +1 -1
- frontend/src/config.js +15 -14
- frontend/vite.config.js +18 -0
- scripts/train.py +12 -5
.dockerignore
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.git
|
| 2 |
+
.gitignore
|
| 3 |
+
notes
|
| 4 |
+
plans
|
| 5 |
+
data
|
| 6 |
+
*.csv
|
| 7 |
+
*.jsonl
|
| 8 |
+
*.json
|
| 9 |
+
__pycache__
|
| 10 |
+
*.pyc
|
| 11 |
+
*.pyo
|
| 12 |
+
.venv
|
| 13 |
+
*.venv
|
| 14 |
+
node_modules
|
| 15 |
+
frontend/node_modules
|
| 16 |
+
frontend/dist
|
| 17 |
+
dist
|
| 18 |
+
.env
|
| 19 |
+
.env.*
|
| 20 |
+
!.env.example
|
| 21 |
+
.DS_Store
|
| 22 |
+
.cache
|
| 23 |
+
*.ipynb
|
| 24 |
+
temp.py
|
.gitignore
CHANGED
|
@@ -19,3 +19,6 @@ notes/
|
|
| 19 |
# Front end
|
| 20 |
node_modules
|
| 21 |
package-lock.json
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
# Front end
|
| 20 |
node_modules
|
| 21 |
package-lock.json
|
| 22 |
+
|
| 23 |
+
# Personal
|
| 24 |
+
plans/
|
Dockerfile
CHANGED
|
@@ -1,43 +1,66 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
# Set environment variables
|
| 4 |
ENV PYTHONUNBUFFERED=1 \
|
| 5 |
PYTHONDONTWRITEBYTECODE=1 \
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
RUN apt-get update && apt-get install -y \
|
| 10 |
-
python3.11 \
|
| 11 |
-
python3.11-venv \
|
| 12 |
-
python3-pip \
|
| 13 |
-
nodejs \
|
| 14 |
-
npm \
|
| 15 |
-
git \
|
| 16 |
-
curl \
|
| 17 |
-
&& rm -rf /var/lib/apt/lists/*
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
RUN
|
| 21 |
-
|
| 22 |
|
| 23 |
WORKDIR /app
|
| 24 |
|
| 25 |
-
#
|
| 26 |
-
|
| 27 |
-
|
|
|
|
| 28 |
|
| 29 |
-
#
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
|
| 42 |
-
#
|
| 43 |
-
CMD ["
|
|
|
|
| 1 |
+
# syntax=docker/dockerfile:1
|
| 2 |
+
|
| 3 |
+
# ── Stage 1: Build frontend ──────────────────────────────────────────────
|
| 4 |
+
FROM node:20-alpine AS frontend-builder
|
| 5 |
+
WORKDIR /app/frontend
|
| 6 |
+
COPY frontend/package.json frontend/package-lock.json* ./
|
| 7 |
+
RUN npm ci || npm install
|
| 8 |
+
COPY frontend ./
|
| 9 |
+
# Build-time env: API_BASE empty = same origin (FastAPI serves frontend)
|
| 10 |
+
ARG VITE_API_BASE_URL=""
|
| 11 |
+
ARG PRECIS_API_KEY=""
|
| 12 |
+
ARG VITE_API_KEY=""
|
| 13 |
+
ENV VITE_API_BASE_URL=${VITE_API_BASE_URL}
|
| 14 |
+
ENV PRECIS_API_KEY=${PRECIS_API_KEY}
|
| 15 |
+
ENV VITE_API_KEY=${VITE_API_KEY}
|
| 16 |
+
RUN npm run build
|
| 17 |
+
|
| 18 |
+
# ── Stage 2: Python runtime via conda env `precis` ──────────────────────
|
| 19 |
+
FROM continuumio/miniconda3:latest
|
| 20 |
|
|
|
|
| 21 |
ENV PYTHONUNBUFFERED=1 \
|
| 22 |
PYTHONDONTWRITEBYTECODE=1 \
|
| 23 |
+
PIP_NO_CACHE_DIR=1 \
|
| 24 |
+
NODE_ENV=production \
|
| 25 |
+
CONDA_AUTO_UPDATE_CONDA=false
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
# curl for healthchecks
|
| 28 |
+
RUN apt-get update && apt-get install -y --no-install-recommends curl \
|
| 29 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 30 |
|
| 31 |
WORKDIR /app
|
| 32 |
|
| 33 |
+
# Create the `precis` env exactly as you do locally:
|
| 34 |
+
# conda env create -f environment.yml (or `conda create -n precis python=3.11 && pip install -r requirements.txt`)
|
| 35 |
+
COPY environment.yml requirements.txt ./
|
| 36 |
+
RUN conda env create -f environment.yml && conda clean -afy
|
| 37 |
|
| 38 |
+
# Make `precis` the default Python for all subsequent layers + runtime
|
| 39 |
+
ENV CONDA_DEFAULT_ENV=precis
|
| 40 |
+
ENV CONDA_PREFIX=/opt/conda/envs/precis
|
| 41 |
+
ENV PATH=/opt/conda/envs/precis/bin:$PATH
|
| 42 |
|
| 43 |
+
# Verify the env (fails fast if not created)
|
| 44 |
+
RUN which python && python --version && conda run -n precis python -c "import fastapi, httpx; print('precis env ready')"
|
| 45 |
+
|
| 46 |
+
# Copy backend flattened to /app so `from config import ...` works with `uvicorn app:app`
|
| 47 |
+
COPY backend ./
|
| 48 |
+
|
| 49 |
+
# Bring built frontend to where app.py expects it: /app/frontend/dist
|
| 50 |
+
COPY --from=frontend-builder /app/frontend/dist ./frontend/dist
|
| 51 |
+
|
| 52 |
+
# HF Spaces expects 7860, local dev uses 8000 — expose both.
|
| 53 |
+
# At runtime HF sets $PORT=7860; locally defaults to 8000 via ENV PORT.
|
| 54 |
+
EXPOSE 8000 7860
|
| 55 |
+
|
| 56 |
+
ENV PORT=8000 \
|
| 57 |
+
OLLAMA_BASE_URL=http://ollama:11434 \
|
| 58 |
+
DEFAULT_MODEL=phi4-mini:latest \
|
| 59 |
+
AVAILABLE_MODELS=phi4-mini:latest \
|
| 60 |
+
PRECIS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:8000,http://localhost:7860,https://*.hf.space,https://*.huggingface.co
|
| 61 |
|
| 62 |
+
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
| 63 |
+
CMD curl -fsS http://localhost:${PORT:-8000}/health || curl -fsS http://localhost:8000/health || curl -fsS http://localhost:7860/health || exit 1
|
| 64 |
|
| 65 |
+
# Uses precis env via PATH; shell form expands $PORT (HF sets 7860, local uses 8000)
|
| 66 |
+
CMD ["sh", "-c", "uvicorn app:app --host 0.0.0.0 --port ${PORT:-8000}"]
|
README.md
CHANGED
|
@@ -10,17 +10,8 @@ app_file: app.py
|
|
| 10 |
pinned: false
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
<h1 align="center">Précis</h1>
|
| 16 |
|
| 17 |
-
<p align="center">
|
| 18 |
-
<img src="https://img.shields.io/badge/python-3.11-blue?style=flat-square&logo=python" alt="Python 3.11">
|
| 19 |
-
<img src="https://img.shields.io/badge/node-18+-green?style=flat-square&logo=nodedotjs" alt="Node 18+">
|
| 20 |
-
<img src="https://img.shields.io/badge/ollama-required-orange?style=flat-square&logo=ollama" alt="Ollama">
|
| 21 |
-
<img src="https://img.shields.io/badge/license-GPL--3.0-brightgreen?style=flat-square" alt="License">
|
| 22 |
-
</p>
|
| 23 |
-
|
| 24 |
<p align="center">
|
| 25 |
<em>Compress long-form content into clear, structured summaries.</em>
|
| 26 |
</p>
|
|
@@ -55,55 +46,154 @@ pinned: false
|
|
| 55 |
| `POST` | `/summarize/youtube` | YouTube video by URL |
|
| 56 |
| `POST` | `/summarize/file` | `.txt` file summary |
|
| 57 |
|
| 58 |
-
All `/summarize/*` endpoints accept an optional `model` field to override the default.
|
| 59 |
|
| 60 |
---
|
| 61 |
|
| 62 |
-
##
|
| 63 |
|
| 64 |
-
|
| 65 |
|
| 66 |
-
|
| 67 |
-
- **Node.js** 18+ (or an equivalent alternative)
|
| 68 |
-
- **Ollama** (`ollama serve` to run)
|
| 69 |
-
- At least one model pulled, e.g. `ollama pull phi4-mini:latest`
|
| 70 |
|
| 71 |
-
|
| 72 |
|
| 73 |
-
|
|
|
|
| 74 |
|
| 75 |
-
|
| 76 |
|
| 77 |
```bash
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
| 80 |
```
|
| 81 |
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
|
| 85 |
|
| 86 |
-
|
| 87 |
|
| 88 |
```bash
|
| 89 |
-
|
| 90 |
```
|
| 91 |
|
| 92 |
-
---
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
-
|
| 95 |
|
| 96 |
```bash
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
| 100 |
```
|
| 101 |
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
---
|
| 105 |
|
| 106 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
```bash
|
| 109 |
cd frontend
|
|
@@ -113,7 +203,7 @@ npm run dev
|
|
| 113 |
|
| 114 |
Served at **`http://localhost:5173`**.
|
| 115 |
|
| 116 |
-
|
| 117 |
|
| 118 |
---
|
| 119 |
|
|
|
|
| 10 |
pinned: false
|
| 11 |
---
|
| 12 |
|
|
|
|
|
|
|
| 13 |
<h1 align="center">Précis</h1>
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
<p align="center">
|
| 16 |
<em>Compress long-form content into clear, structured summaries.</em>
|
| 17 |
</p>
|
|
|
|
| 46 |
| `POST` | `/summarize/youtube` | YouTube video by URL |
|
| 47 |
| `POST` | `/summarize/file` | `.txt` file summary |
|
| 48 |
|
| 49 |
+
All `/summarize/*` endpoints accept an optional `model` field to override the default and require `X-API-Key` header (`PRECIS_API_KEY`).
|
| 50 |
|
| 51 |
---
|
| 52 |
|
| 53 |
+
## Quick Start (Docker)
|
| 54 |
|
| 55 |
+
**One command** to build and run the whole stack (API + frontend + Ollama). This is the main way to run Précis — no manual `ollama serve`/`uvicorn`/`vite` needed.
|
| 56 |
|
| 57 |
+
> **Python runs inside the `precis` conda environment** — same as your local setup. The `Dockerfile` uses `continuumio/miniconda3` + `environment.yml` to create `conda env precis` (Python 3.11) and installs all deps there; the container's `PATH` points to `/opt/conda/envs/precis/bin`, so `uvicorn` runs from `precis`.
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
+
### 1. Prerequisites
|
| 60 |
|
| 61 |
+
- **Docker** + **Docker Compose** ([Install Docker Desktop](https://docs.docker.com/get-docker/))
|
| 62 |
+
- That's it. Python (via `precis` conda env), Node, and Ollama are all inside the containers. No local conda/Python/Node needed.
|
| 63 |
|
| 64 |
+
### 2. Configure
|
| 65 |
|
| 66 |
```bash
|
| 67 |
+
# from repo root
|
| 68 |
+
cp .env.example .env
|
| 69 |
+
# edit .env — set a strong secret:
|
| 70 |
+
# PRECIS_API_KEY=openssl rand -hex 32 (or any long random string)
|
| 71 |
+
# VITE_API_KEY must match PRECIS_API_KEY so the baked frontend can auth
|
| 72 |
```
|
| 73 |
|
| 74 |
+
> **`.env.example` defaults for Docker:**
|
| 75 |
+
> ```ini
|
| 76 |
+
> OLLAMA_BASE_URL=http://127.0.0.1:11434 # compose overrides to http://ollama:11434
|
| 77 |
+
> DEFAULT_MODEL=phi4-mini:latest
|
| 78 |
+
> AVAILABLE_MODELS=phi4-mini:latest
|
| 79 |
+
> PRECIS_API_KEY=replace-with-a-long-random-secret
|
| 80 |
+
> VITE_API_KEY=replace-with-a-long-random-secret
|
| 81 |
+
> PRECIS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:5555
|
| 82 |
+
> VITE_API_BASE_URL= # empty = same origin (correct for Docker)
|
| 83 |
+
> ```
|
| 84 |
|
| 85 |
+
Manually update `.env.example` to match the block above if your copy is older.
|
| 86 |
|
| 87 |
+
### 3. Run
|
| 88 |
|
| 89 |
```bash
|
| 90 |
+
docker compose up --build
|
| 91 |
```
|
| 92 |
|
| 93 |
+
- First build takes ~4-6 min (multi-stage: Node build + `conda env create -f environment.yml` for `precis` — cached after first build).
|
| 94 |
+
- Opens: **http://localhost:5555** — single origin serves both API (`/docs`, `/health`) and the frontend.
|
| 95 |
+
- Compose healthchecks wait for Ollama (`/api/tags`) before starting the API (which runs as `conda run -n precis uvicorn`).
|
| 96 |
+
|
| 97 |
+
#### Pull a model (inside Ollama container)
|
| 98 |
|
| 99 |
+
The API will 503 until a model is installed. In a **second terminal**:
|
| 100 |
|
| 101 |
```bash
|
| 102 |
+
docker exec -it precis-ollama ollama pull phi4-mini:latest
|
| 103 |
+
# optional extras:
|
| 104 |
+
docker exec -it precis-ollama ollama pull llama3.1:latest
|
| 105 |
+
docker exec -it precis-ollama ollama pull qwen3:4b
|
| 106 |
+
docker exec -it precis-ollama ollama list
|
| 107 |
```
|
| 108 |
|
| 109 |
+
Then refresh http://localhost:5555 — the model selector populates automatically (`GET /models`).
|
| 110 |
+
|
| 111 |
+
#### Useful commands
|
| 112 |
+
|
| 113 |
+
```bash
|
| 114 |
+
docker compose up --build -d # detached
|
| 115 |
+
docker compose logs -f api # tail API logs
|
| 116 |
+
docker compose logs -f ollama
|
| 117 |
+
docker compose down # stop
|
| 118 |
+
docker compose down -v # stop + wipe Ollama model cache (ollama_data volume)
|
| 119 |
+
docker compose ps
|
| 120 |
+
curl http://localhost:5555/health
|
| 121 |
+
curl http://localhost:5555/status
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
#### Single-image run (without compose / without Ollama sidecar)
|
| 125 |
+
|
| 126 |
+
If you just want the API image and already run Ollama natively (`ollama serve` on host):
|
| 127 |
+
|
| 128 |
+
```bash
|
| 129 |
+
docker build -t precis .
|
| 130 |
+
docker run --rm -p 5555:5555 --env-file .env \
|
| 131 |
+
-e OLLAMA_BASE_URL=http://host.docker.internal:11434 \
|
| 132 |
+
precis
|
| 133 |
+
# Windows/Mac: host.docker.internal resolves to host. Linux: add --add-host=host.docker.internal:host-gateway
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
#### Hugging Face Spaces
|
| 137 |
+
|
| 138 |
+
`sdk: docker` with `EXPOSE 5555 7860` + `ENV PORT=5555` + `CMD sh -c "uvicorn ... --port ${PORT:-5555}"` means the same image works everywhere: locally `http://localhost:5555` (compose sets `PORT=5555`), on HF Spaces Hugging Face sets `PORT=7860` automatically and the container listens on `7860` with no extra config.
|
| 139 |
|
| 140 |
---
|
| 141 |
|
| 142 |
+
## Manual Development
|
| 143 |
+
|
| 144 |
+
Use this if you want hot-reload for the frontend/backend separately. Docker remains the reproducible path.
|
| 145 |
+
|
| 146 |
+
### Prerequisites
|
| 147 |
+
|
| 148 |
+
- **Conda** (Miniconda/Anaconda/Mamba) with env **`precis`** (`conda env create -f environment.yml` / `conda activate precis`) — Python 3.11, same env the Docker image uses
|
| 149 |
+
- Alternative without conda: **Python** 3.11+ + `pip install -r requirements.txt`
|
| 150 |
+
- **Node.js** 18+
|
| 151 |
+
- **Ollama** (`ollama serve` to run) + at least one model: `ollama pull phi4-mini:latest`
|
| 152 |
+
|
| 153 |
+
### 1. Environment
|
| 154 |
+
|
| 155 |
+
```bash
|
| 156 |
+
cp .env.example .env
|
| 157 |
+
# set PRECIS_API_KEY, VITE_API_KEY (same value), and for local:
|
| 158 |
+
# OLLAMA_BASE_URL=http://127.0.0.1:11434
|
| 159 |
+
# VITE_API_BASE_URL=http://localhost:5555 # or leave empty and rely on Vite proxy
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
### 2. Run the Fine-Tuning (optional)
|
| 163 |
+
|
| 164 |
+
Scripts live in `scripts/`. Tested primarily with **phi4-mini** (Microsoft) and **Qwen 3-4b** (Alibaba).
|
| 165 |
+
|
| 166 |
+
```bash
|
| 167 |
+
ollama pull phi4-mini:latest
|
| 168 |
+
ollama pull llama3.1:latest
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
### 3. Test Fine-Tuning Quality
|
| 172 |
+
|
| 173 |
+
To evaluate summarization accuracy, run the script below against the `test` split. It uses **BERTScore** (0 to 1.0, higher is better), comparing semantic similarity between generated summaries and references.
|
| 174 |
+
|
| 175 |
+
```bash
|
| 176 |
+
python -m scripts.test --model phi4-mini:latest
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
### 4. Start the Backend
|
| 180 |
+
|
| 181 |
+
```bash
|
| 182 |
+
# With conda (recommended — mirrors Docker):
|
| 183 |
+
conda env create -f environment.yml # once
|
| 184 |
+
conda activate precis
|
| 185 |
+
pip install -r requirements.txt # keep in sync if you edit requirements.txt
|
| 186 |
+
uvicorn backend.app:app --reload --port 5555
|
| 187 |
+
# or: cd backend && uvicorn app:app --reload --port 5555
|
| 188 |
+
|
| 189 |
+
# Without conda:
|
| 190 |
+
# pip install -r requirements.txt
|
| 191 |
+
# uvicorn backend.app:app --reload --port 5555
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
Served at **`http://localhost:5555`** with interactive docs at `/docs`.
|
| 195 |
+
|
| 196 |
+
### 5. Run the Frontend
|
| 197 |
|
| 198 |
```bash
|
| 199 |
cd frontend
|
|
|
|
| 203 |
|
| 204 |
Served at **`http://localhost:5173`**.
|
| 205 |
|
| 206 |
+
`vite.config.js` proxies `/health`, `/status`, `/models`, `/summarize`, `/warmup`, `/unload` to `http://localhost:5555`, so you only need to visit `http://localhost:5173` — no manual `VITE_API_BASE_URL` required. For custom backend ports, set `VITE_API_BASE_URL` in `.env`.
|
| 207 |
|
| 208 |
---
|
| 209 |
|
backend/app.py
CHANGED
|
@@ -7,17 +7,30 @@ from fastapi import FastAPI, HTTPException, UploadFile, File, Header, Request
|
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
from fastapi.staticfiles import StaticFiles
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
from
|
| 20 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
app = FastAPI(
|
| 23 |
title="Précis API",
|
|
@@ -33,17 +46,14 @@ app.add_middleware(
|
|
| 33 |
allow_headers=["Content-Type", "X-API-Key"],
|
| 34 |
)
|
| 35 |
|
| 36 |
-
# Only mount frontend in production when dist/ exists
|
| 37 |
-
if os.path.isdir("frontend/dist"):
|
| 38 |
-
app.mount("/", StaticFiles(directory="frontend/dist", html=True), name="static")
|
| 39 |
-
|
| 40 |
def verify_api_key(x_api_key: Optional[str] = Header(default=None, alias="X-API-Key")):
|
| 41 |
if not API_KEY:
|
| 42 |
raise HTTPException(
|
| 43 |
status_code=500,
|
| 44 |
detail="Server misconfigured: PRECIS_API_KEY must be set.",
|
| 45 |
)
|
| 46 |
-
|
|
|
|
| 47 |
raise HTTPException(status_code=401, detail="Invalid API key.")
|
| 48 |
|
| 49 |
|
|
@@ -223,13 +233,16 @@ async def summarize_file(
|
|
| 223 |
):
|
| 224 |
verify_api_key(x_api_key)
|
| 225 |
content_length = req.headers.get("content-length")
|
| 226 |
-
|
| 227 |
-
|
|
|
|
|
|
|
|
|
|
| 228 |
|
| 229 |
-
if not file.filename.endswith(".txt"):
|
| 230 |
raise HTTPException(status_code=400, detail="Only .txt files are supported.")
|
| 231 |
|
| 232 |
-
content = await file.read()
|
| 233 |
if len(content) > MAX_UPLOAD_BYTES:
|
| 234 |
raise HTTPException(status_code=413, detail="Uploaded file is too large.")
|
| 235 |
|
|
@@ -243,6 +256,22 @@ async def summarize_file(
|
|
| 243 |
return await stream_summary(text, title=file.filename, model=model)
|
| 244 |
|
| 245 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
if __name__ == "__main__":
|
| 247 |
import uvicorn
|
| 248 |
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
from fastapi.staticfiles import StaticFiles
|
| 9 |
|
| 10 |
+
try: # Docker flattened: /app/config.py | Local: backend/config.py
|
| 11 |
+
from config import ( # type: ignore
|
| 12 |
+
OLLAMA_BASE_URL,
|
| 13 |
+
DEFAULT_MODEL,
|
| 14 |
+
AVAILABLE_MODELS,
|
| 15 |
+
ALLOWED_ORIGINS,
|
| 16 |
+
API_KEY,
|
| 17 |
+
MAX_UPLOAD_BYTES,
|
| 18 |
+
)
|
| 19 |
+
from schemas import TranscriptRequest, YouTubeRequest, UnloadRequest # type: ignore
|
| 20 |
+
from ollama import stream_summary # type: ignore
|
| 21 |
+
from helpers.transcript import transcript as fetch_yt_transcript # type: ignore
|
| 22 |
+
except ImportError: # Running as `backend.app` package
|
| 23 |
+
from backend.config import ( # type: ignore
|
| 24 |
+
OLLAMA_BASE_URL,
|
| 25 |
+
DEFAULT_MODEL,
|
| 26 |
+
AVAILABLE_MODELS,
|
| 27 |
+
ALLOWED_ORIGINS,
|
| 28 |
+
API_KEY,
|
| 29 |
+
MAX_UPLOAD_BYTES,
|
| 30 |
+
)
|
| 31 |
+
from backend.schemas import TranscriptRequest, YouTubeRequest, UnloadRequest # type: ignore
|
| 32 |
+
from backend.ollama import stream_summary # type: ignore
|
| 33 |
+
from backend.helpers.transcript import transcript as fetch_yt_transcript # type: ignore
|
| 34 |
|
| 35 |
app = FastAPI(
|
| 36 |
title="Précis API",
|
|
|
|
| 46 |
allow_headers=["Content-Type", "X-API-Key"],
|
| 47 |
)
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
def verify_api_key(x_api_key: Optional[str] = Header(default=None, alias="X-API-Key")):
|
| 50 |
if not API_KEY:
|
| 51 |
raise HTTPException(
|
| 52 |
status_code=500,
|
| 53 |
detail="Server misconfigured: PRECIS_API_KEY must be set.",
|
| 54 |
)
|
| 55 |
+
import secrets as _secrets
|
| 56 |
+
if not _secrets.compare_digest(x_api_key or "", API_KEY):
|
| 57 |
raise HTTPException(status_code=401, detail="Invalid API key.")
|
| 58 |
|
| 59 |
|
|
|
|
| 233 |
):
|
| 234 |
verify_api_key(x_api_key)
|
| 235 |
content_length = req.headers.get("content-length")
|
| 236 |
+
try:
|
| 237 |
+
if content_length and int(content_length) > MAX_UPLOAD_BYTES:
|
| 238 |
+
raise HTTPException(status_code=413, detail="Uploaded file is too large.")
|
| 239 |
+
except ValueError:
|
| 240 |
+
pass
|
| 241 |
|
| 242 |
+
if not file.filename or not file.filename.endswith(".txt"):
|
| 243 |
raise HTTPException(status_code=400, detail="Only .txt files are supported.")
|
| 244 |
|
| 245 |
+
content = await file.read(MAX_UPLOAD_BYTES + 1)
|
| 246 |
if len(content) > MAX_UPLOAD_BYTES:
|
| 247 |
raise HTTPException(status_code=413, detail="Uploaded file is too large.")
|
| 248 |
|
|
|
|
| 256 |
return await stream_summary(text, title=file.filename, model=model)
|
| 257 |
|
| 258 |
|
| 259 |
+
# ── Mount frontend LAST so /health, /models, /docs etc. are not shadowed ──
|
| 260 |
+
# Starlette matches mounts in order — "/" mounted first would swallow /health.
|
| 261 |
+
from pathlib import Path as _Path
|
| 262 |
+
|
| 263 |
+
_frontend_candidates = [
|
| 264 |
+
_Path(__file__).resolve().parent.parent / "frontend" / "dist",
|
| 265 |
+
_Path(__file__).resolve().parent / "frontend" / "dist",
|
| 266 |
+
_Path.cwd() / "frontend" / "dist",
|
| 267 |
+
]
|
| 268 |
+
_frontend_dist = next((str(p) for p in _frontend_candidates if p.is_dir()), None)
|
| 269 |
+
if _frontend_dist:
|
| 270 |
+
try:
|
| 271 |
+
app.mount("/", StaticFiles(directory=_frontend_dist, html=True), name="static")
|
| 272 |
+
except Exception:
|
| 273 |
+
pass
|
| 274 |
+
|
| 275 |
if __name__ == "__main__":
|
| 276 |
import uvicorn
|
| 277 |
uvicorn.run(app, host="0.0.0.0", port=8000)
|
backend/config.py
CHANGED
|
@@ -4,8 +4,21 @@ from pathlib import Path
|
|
| 4 |
from dotenv import load_dotenv
|
| 5 |
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
|
| 11 |
def _csv_env(name: str, default: list[str]) -> list[str]:
|
|
@@ -23,13 +36,16 @@ def _required_env(name: str) -> str:
|
|
| 23 |
return value
|
| 24 |
|
| 25 |
|
| 26 |
-
OLLAMA_BASE_URL =
|
| 27 |
-
DEFAULT_MODEL =
|
| 28 |
AVAILABLE_MODELS = _csv_env("AVAILABLE_MODELS", [DEFAULT_MODEL])
|
| 29 |
if DEFAULT_MODEL not in AVAILABLE_MODELS:
|
| 30 |
AVAILABLE_MODELS = [DEFAULT_MODEL, *AVAILABLE_MODELS]
|
| 31 |
|
| 32 |
-
ALLOWED_ORIGINS = _csv_env(
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
API_KEY = os.getenv("PRECIS_API_KEY") or None
|
| 35 |
|
|
|
|
| 4 |
from dotenv import load_dotenv
|
| 5 |
|
| 6 |
|
| 7 |
+
# Load .env robustly for both local dev and Docker flattened layout.
|
| 8 |
+
# Local: backend/config.py -> parents[1] = repo root / .env
|
| 9 |
+
# Docker: /app/config.py (flattened) or /app/backend/config.py (package) -> CWD = /app
|
| 10 |
+
for _candidate in [
|
| 11 |
+
Path(__file__).resolve().parents[1] / ".env", # repo root when running locally
|
| 12 |
+
Path.cwd() / ".env", # Docker WORKDIR /app
|
| 13 |
+
Path(__file__).resolve().parent / ".env", # adjacent to config.py
|
| 14 |
+
Path(__file__).resolve().parents[0] / ".env",
|
| 15 |
+
]:
|
| 16 |
+
if _candidate.is_file():
|
| 17 |
+
load_dotenv(_candidate, override=False)
|
| 18 |
+
break
|
| 19 |
+
else:
|
| 20 |
+
# Still call load_dotenv to pick up env vars injected by Docker/compose
|
| 21 |
+
load_dotenv(override=False)
|
| 22 |
|
| 23 |
|
| 24 |
def _csv_env(name: str, default: list[str]) -> list[str]:
|
|
|
|
| 36 |
return value
|
| 37 |
|
| 38 |
|
| 39 |
+
OLLAMA_BASE_URL = (os.getenv("OLLAMA_BASE_URL") or "").strip() or "http://127.0.0.1:11434"
|
| 40 |
+
DEFAULT_MODEL = (os.getenv("DEFAULT_MODEL") or "").strip() or "phi4-mini:latest"
|
| 41 |
AVAILABLE_MODELS = _csv_env("AVAILABLE_MODELS", [DEFAULT_MODEL])
|
| 42 |
if DEFAULT_MODEL not in AVAILABLE_MODELS:
|
| 43 |
AVAILABLE_MODELS = [DEFAULT_MODEL, *AVAILABLE_MODELS]
|
| 44 |
|
| 45 |
+
ALLOWED_ORIGINS = _csv_env(
|
| 46 |
+
"PRECIS_ALLOWED_ORIGINS",
|
| 47 |
+
["http://localhost:5173", "http://localhost:5555", "http://localhost:7860"],
|
| 48 |
+
)
|
| 49 |
|
| 50 |
API_KEY = os.getenv("PRECIS_API_KEY") or None
|
| 51 |
|
backend/helpers/transcript.py
CHANGED
|
@@ -57,9 +57,16 @@ def _extract_video_id(url: str) -> str:
|
|
| 57 |
|
| 58 |
def _fetch_transcript_sync(video_id: str) -> str:
|
| 59 |
"""Blocking transcript fetch. Always call via ``asyncio.to_thread``."""
|
| 60 |
-
ytt = YouTubeTranscriptApi()
|
| 61 |
try:
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
except TranscriptsDisabled:
|
| 64 |
raise HTTPException(
|
| 65 |
status_code=422,
|
|
|
|
| 57 |
|
| 58 |
def _fetch_transcript_sync(video_id: str) -> str:
|
| 59 |
"""Blocking transcript fetch. Always call via ``asyncio.to_thread``."""
|
|
|
|
| 60 |
try:
|
| 61 |
+
ytt = YouTubeTranscriptApi()
|
| 62 |
+
fetch = getattr(ytt, "fetch", None) or getattr(YouTubeTranscriptApi, "get_transcript", None)
|
| 63 |
+
if fetch is None:
|
| 64 |
+
raise AttributeError("No transcript fetch method")
|
| 65 |
+
# instance fetch vs static get_transcript have different signatures
|
| 66 |
+
try:
|
| 67 |
+
t = fetch(video_id, languages=_LANG_PREFS) if fetch is getattr(ytt, "fetch", None) else fetch(video_id, languages=_LANG_PREFS)
|
| 68 |
+
except TypeError:
|
| 69 |
+
t = fetch(video_id)
|
| 70 |
except TranscriptsDisabled:
|
| 71 |
raise HTTPException(
|
| 72 |
status_code=422,
|
backend/ollama.py
CHANGED
|
@@ -6,10 +6,16 @@ import httpx
|
|
| 6 |
from fastapi import HTTPException
|
| 7 |
from fastapi.responses import StreamingResponse
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
def build_prompt(title: Optional[str], text: str) -> str:
|
|
|
|
| 6 |
from fastapi import HTTPException
|
| 7 |
from fastapi.responses import StreamingResponse
|
| 8 |
|
| 9 |
+
try:
|
| 10 |
+
from config import ( # type: ignore
|
| 11 |
+
OLLAMA_BASE_URL, DEFAULT_MODEL, AVAILABLE_MODELS,
|
| 12 |
+
MAX_SUMMARY_TOKENS, TEMPERATURE,
|
| 13 |
+
)
|
| 14 |
+
except ImportError:
|
| 15 |
+
from backend.config import ( # type: ignore
|
| 16 |
+
OLLAMA_BASE_URL, DEFAULT_MODEL, AVAILABLE_MODELS,
|
| 17 |
+
MAX_SUMMARY_TOKENS, TEMPERATURE,
|
| 18 |
+
)
|
| 19 |
|
| 20 |
|
| 21 |
def build_prompt(title: Optional[str], text: str) -> str:
|
backend/schemas.py
CHANGED
|
@@ -1,7 +1,10 @@
|
|
| 1 |
from typing import Optional
|
| 2 |
from pydantic import BaseModel, Field
|
| 3 |
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
|
| 7 |
class YouTubeRequest(BaseModel):
|
|
|
|
| 1 |
from typing import Optional
|
| 2 |
from pydantic import BaseModel, Field
|
| 3 |
|
| 4 |
+
try:
|
| 5 |
+
from config import MAX_TRANSCRIPT_CHARS # type: ignore
|
| 6 |
+
except ImportError:
|
| 7 |
+
from backend.config import MAX_TRANSCRIPT_CHARS # type: ignore
|
| 8 |
|
| 9 |
|
| 10 |
class YouTubeRequest(BaseModel):
|
backend/youtube.py
CHANGED
|
@@ -24,9 +24,15 @@ def extract_video_id(url: str) -> str:
|
|
| 24 |
|
| 25 |
def fetch_transcript(video_id: str) -> str:
|
| 26 |
"""Synchronous transcript fetch. Call via asyncio.to_thread."""
|
| 27 |
-
ytt = YouTubeTranscriptApi()
|
| 28 |
try:
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
except TranscriptsDisabled:
|
| 31 |
raise HTTPException(status_code=422, detail="This video has transcripts disabled.")
|
| 32 |
except NoTranscriptFound:
|
|
|
|
| 24 |
|
| 25 |
def fetch_transcript(video_id: str) -> str:
|
| 26 |
"""Synchronous transcript fetch. Call via asyncio.to_thread."""
|
|
|
|
| 27 |
try:
|
| 28 |
+
ytt = YouTubeTranscriptApi()
|
| 29 |
+
fetch = getattr(ytt, "fetch", None) or getattr(YouTubeTranscriptApi, "get_transcript", None)
|
| 30 |
+
if fetch is None:
|
| 31 |
+
raise AttributeError("No transcript fetch method")
|
| 32 |
+
try:
|
| 33 |
+
transcript = fetch(video_id, languages=["en", "en-US", "en-GB"]) if fetch is getattr(ytt, "fetch", None) else fetch(video_id, languages=["en", "en-US", "en-GB"])
|
| 34 |
+
except TypeError:
|
| 35 |
+
transcript = fetch(video_id)
|
| 36 |
except TranscriptsDisabled:
|
| 37 |
raise HTTPException(status_code=422, detail="This video has transcripts disabled.")
|
| 38 |
except NoTranscriptFound:
|
docker-compose.override.yml
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dev override — auto-merged by `docker compose up`
|
| 2 |
+
# Gives you the same hot-reload you get manually:
|
| 3 |
+
# - backend: uvicorn --reload via host mount
|
| 4 |
+
# - frontend: vite dev server with HMR on :5173
|
| 5 |
+
# To run production (no reload): `docker compose -f docker-compose.yml up --build`
|
| 6 |
+
|
| 7 |
+
services:
|
| 8 |
+
api:
|
| 9 |
+
# Mount host backend over image copy for live reload.
|
| 10 |
+
# Host ./backend -> /app/backend, run as `backend.app` (package layout).
|
| 11 |
+
volumes:
|
| 12 |
+
- ./backend:/app/backend
|
| 13 |
+
- ./.env:/app/.env:ro
|
| 14 |
+
# Keep frontend/dist from image (don't hide with host mount)
|
| 15 |
+
command: sh -c "uvicorn backend.app:app --host 0.0.0.0 --port 8000 --reload --reload-dir /app/backend --reload-dir /app"
|
| 16 |
+
environment:
|
| 17 |
+
# Ensure vite proxy / same-origin still works in dev
|
| 18 |
+
PRECIS_ALLOWED_ORIGINS: http://localhost:5173,http://localhost:8000,http://localhost:7860
|
| 19 |
+
|
| 20 |
+
frontend:
|
| 21 |
+
image: node:20-alpine
|
| 22 |
+
working_dir: /app/frontend
|
| 23 |
+
command: sh -c "npm ci --silent || npm install --silent; npm run dev -- --host 0.0.0.0 --port 5173"
|
| 24 |
+
ports:
|
| 25 |
+
- "5173:5173"
|
| 26 |
+
volumes:
|
| 27 |
+
- ./frontend:/app/frontend
|
| 28 |
+
- /app/frontend/node_modules
|
| 29 |
+
env_file:
|
| 30 |
+
- .env
|
| 31 |
+
environment:
|
| 32 |
+
VITE_API_BASE_URL: "" # uses vite proxy
|
| 33 |
+
VITE_PROXY_TARGET: http://api:8000
|
| 34 |
+
DOCKER: "1"
|
| 35 |
+
depends_on:
|
| 36 |
+
api:
|
| 37 |
+
condition: service_healthy
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
ollama:
|
| 3 |
+
image: ollama/ollama:latest
|
| 4 |
+
container_name: precis-ollama
|
| 5 |
+
ports:
|
| 6 |
+
- "11434:11434"
|
| 7 |
+
volumes:
|
| 8 |
+
# Reuse host's Ollama models (~/.ollama) so you don't keep 2 copies.
|
| 9 |
+
# On Windows: C:\Users\varak\.ollama -> /root/.ollama in container.
|
| 10 |
+
# Set OLLAMA_HOST_DIR in .env if your host path differs.
|
| 11 |
+
# NOTE: You can't run host `ollama serve` + this container at same time on 11434 — stop one first.
|
| 12 |
+
- type: bind
|
| 13 |
+
source: ${OLLAMA_HOST_DIR:-C:/Users/varak/.ollama}
|
| 14 |
+
target: /root/.ollama
|
| 15 |
+
restart: unless-stopped
|
| 16 |
+
healthcheck:
|
| 17 |
+
test: ["CMD-SHELL", "ollama list >/dev/null 2>&1 || wget -qO- http://localhost:11434/api/tags >/dev/null 2>&1 || curl -fsS http://localhost:11434/api/tags >/dev/null 2>&1"]
|
| 18 |
+
interval: 10s
|
| 19 |
+
timeout: 5s
|
| 20 |
+
retries: 10
|
| 21 |
+
start_period: 15s
|
| 22 |
+
start_interval: 2s
|
| 23 |
+
|
| 24 |
+
api:
|
| 25 |
+
build:
|
| 26 |
+
context: .
|
| 27 |
+
dockerfile: Dockerfile
|
| 28 |
+
args:
|
| 29 |
+
# Baked into frontend at `npm run build` time (Vite inlines env).
|
| 30 |
+
# api still reads PRECIS_API_KEY at runtime via env_file / environment.
|
| 31 |
+
VITE_API_BASE_URL: "" # same-origin in Docker (frontend served by FastAPI)
|
| 32 |
+
PRECIS_API_KEY: ${PRECIS_API_KEY:-}
|
| 33 |
+
VITE_API_KEY: ${VITE_API_KEY:-${PRECIS_API_KEY:-}}
|
| 34 |
+
container_name: precis-api
|
| 35 |
+
ports:
|
| 36 |
+
- "8000:8000"
|
| 37 |
+
env_file:
|
| 38 |
+
- .env
|
| 39 |
+
environment:
|
| 40 |
+
# Docker defaults — overridden by .env if set
|
| 41 |
+
PORT: 8000
|
| 42 |
+
OLLAMA_BASE_URL: http://ollama:11434
|
| 43 |
+
# Keep in sync with .env.example if you change defaults
|
| 44 |
+
DEFAULT_MODEL: ${DEFAULT_MODEL:-phi4-mini:latest}
|
| 45 |
+
AVAILABLE_MODELS: ${AVAILABLE_MODELS:-phi4-mini:latest}
|
| 46 |
+
PRECIS_ALLOWED_ORIGINS: ${PRECIS_ALLOWED_ORIGINS:-http://localhost:5173,http://localhost:8000,http://localhost:7860,https://*.hf.space,https://*.huggingface.co}
|
| 47 |
+
PRECIS_API_KEY: ${PRECIS_API_KEY:?PRECIS_API_KEY must be set in .env}
|
| 48 |
+
OLLAMA_KEEP_ALIVE: ${OLLAMA_KEEP_ALIVE:-30m}
|
| 49 |
+
depends_on:
|
| 50 |
+
ollama:
|
| 51 |
+
condition: service_healthy
|
| 52 |
+
volumes:
|
| 53 |
+
# Mount .env read-only so config.py hot-reload isn't needed — container restarts pick up changes
|
| 54 |
+
- type: bind
|
| 55 |
+
source: ./.env
|
| 56 |
+
target: /app/.env
|
| 57 |
+
read_only: true
|
| 58 |
+
restart: unless-stopped
|
| 59 |
+
healthcheck:
|
| 60 |
+
test: ["CMD", "curl", "-fsS", "http://localhost:8000/health"]
|
| 61 |
+
interval: 15s
|
| 62 |
+
timeout: 5s
|
| 63 |
+
retries: 5
|
| 64 |
+
start_period: 20s
|
| 65 |
+
|
| 66 |
+
volumes: {}
|
environment.yml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: precis
|
| 2 |
+
channels:
|
| 3 |
+
- conda-forge
|
| 4 |
+
- defaults
|
| 5 |
+
dependencies:
|
| 6 |
+
- python=3.11
|
| 7 |
+
- pip
|
| 8 |
+
- pip:
|
| 9 |
+
# ── API (runtime) ────────────────────────────────────────────────
|
| 10 |
+
- fastapi
|
| 11 |
+
- uvicorn[standard]
|
| 12 |
+
- httpx
|
| 13 |
+
- python-multipart
|
| 14 |
+
- python-dotenv
|
| 15 |
+
- youtube-transcript-api
|
| 16 |
+
# ── Training / eval (optional — keep parity with requirements.txt) ─
|
| 17 |
+
- torch
|
| 18 |
+
- transformers
|
| 19 |
+
- accelerate
|
| 20 |
+
- bitsandbytes
|
| 21 |
+
- peft
|
| 22 |
+
- datasets
|
| 23 |
+
- sentencepiece
|
frontend/index.html
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
|
| 4 |
<head>
|
| 5 |
<meta charset="UTF-8" />
|
| 6 |
-
<link rel="icon" type="image/svg+xml" href="/
|
| 7 |
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 8 |
<meta name="description"
|
| 9 |
content="Summarize YouTube videos, articles, and text files with local AI models." />
|
|
|
|
| 3 |
|
| 4 |
<head>
|
| 5 |
<meta charset="UTF-8" />
|
| 6 |
+
<link rel="icon" type="image/svg+xml" href="/logo.svg" />
|
| 7 |
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 8 |
<meta name="description"
|
| 9 |
content="Summarize YouTube videos, articles, and text files with local AI models." />
|
frontend/public/logo.svg
ADDED
|
|
frontend/{src/assets/logo.svg → public/old_logo.svg}
RENAMED
|
File without changes
|
frontend/public/vite.svg
DELETED
frontend/src/App.jsx
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
import { useEffect, useState, useRef } from 'react'
|
| 2 |
import InlineResult from './components/InlineResult'
|
| 3 |
import { useStreaming } from './hooks/useStreaming'
|
| 4 |
-
import logoSvg from './assets/logo.svg'
|
| 5 |
import { API_BASE } from './config'
|
|
|
|
| 6 |
import './App.css'
|
| 7 |
|
| 8 |
function App() {
|
|
|
|
| 1 |
import { useEffect, useState, useRef } from 'react'
|
| 2 |
import InlineResult from './components/InlineResult'
|
| 3 |
import { useStreaming } from './hooks/useStreaming'
|
|
|
|
| 4 |
import { API_BASE } from './config'
|
| 5 |
+
const logoSvg = '/logo.svg'
|
| 6 |
import './App.css'
|
| 7 |
|
| 8 |
function App() {
|
frontend/src/config.js
CHANGED
|
@@ -1,22 +1,23 @@
|
|
| 1 |
-
const
|
| 2 |
const list = Array.isArray(names) ? names : [names]
|
| 3 |
for (const name of list) {
|
| 4 |
const value = import.meta.env[name]
|
| 5 |
if (value && String(value).trim()) return String(value).trim()
|
| 6 |
}
|
| 7 |
-
|
| 8 |
}
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
]
|
| 15 |
-
|
| 16 |
-
'PRECIS_API_KEY',
|
| 17 |
-
'VITE_API_KEY',
|
| 18 |
-
])
|
| 19 |
-
|
| 20 |
-
export const authHeaders = (headers = {}) => (
|
| 21 |
-
API_KEY ? { ...headers, 'X-API-Key': API_KEY } : headers
|
| 22 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const optionalEnv = (names, fallback = '') => {
|
| 2 |
const list = Array.isArray(names) ? names : [names]
|
| 3 |
for (const name of list) {
|
| 4 |
const value = import.meta.env[name]
|
| 5 |
if (value && String(value).trim()) return String(value).trim()
|
| 6 |
}
|
| 7 |
+
return fallback
|
| 8 |
}
|
| 9 |
|
| 10 |
+
// In Docker/production the frontend is served from the same origin as the API
|
| 11 |
+
// (FastAPI StaticFiles at /), so empty string means "same origin" -> fetch("/models").
|
| 12 |
+
// In local dev, set VITE_API_BASE_URL=http://localhost:8000 in .env or rely on Vite proxy.
|
| 13 |
+
export const API_BASE = optionalEnv(
|
| 14 |
+
['API_BASE_URL', 'VITE_API_BASE_URL', 'PRECIS_API_BASE_URL'],
|
| 15 |
+
'',
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
)
|
| 17 |
+
|
| 18 |
+
// API key is baked at `npm run build` time. For Docker, pass --build-arg PRECIS_API_KEY
|
| 19 |
+
// or VITE_API_KEY (docker-compose does this from .env). Falls back to empty so the
|
| 20 |
+
// production image can still build; backend will 401 until a real key is set.
|
| 21 |
+
export const API_KEY = optionalEnv(['PRECIS_API_KEY', 'VITE_API_KEY', 'VITE_PRECIS_API_KEY'], '')
|
| 22 |
+
|
| 23 |
+
export const authHeaders = (headers = {}) => (API_KEY ? { ...headers, 'X-API-Key': API_KEY } : headers)
|
frontend/vite.config.js
CHANGED
|
@@ -6,4 +6,22 @@ export default defineConfig({
|
|
| 6 |
envDir: '..',
|
| 7 |
envPrefix: ['VITE_', 'PRECIS_', 'API_', 'DEFAULT_', 'AVAILABLE_'],
|
| 8 |
plugins: [react()],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
})
|
|
|
|
| 6 |
envDir: '..',
|
| 7 |
envPrefix: ['VITE_', 'PRECIS_', 'API_', 'DEFAULT_', 'AVAILABLE_'],
|
| 8 |
plugins: [react()],
|
| 9 |
+
server: {
|
| 10 |
+
host: '0.0.0.0',
|
| 11 |
+
port: 5173,
|
| 12 |
+
// `npm run dev` on host -> localhost:5555, `docker compose up` frontend -> api:5555
|
| 13 |
+
proxy: (() => {
|
| 14 |
+
const target = process.env.VITE_PROXY_TARGET || (process.env.DOCKER ? 'http://api:5555' : 'http://localhost:5555')
|
| 15 |
+
return {
|
| 16 |
+
'/health': target,
|
| 17 |
+
'/status': target,
|
| 18 |
+
'/models': target,
|
| 19 |
+
'/warmup': target,
|
| 20 |
+
'/unload': target,
|
| 21 |
+
'/summarize': target,
|
| 22 |
+
'/docs': target,
|
| 23 |
+
'/openapi.json': target,
|
| 24 |
+
}
|
| 25 |
+
})(),
|
| 26 |
+
},
|
| 27 |
})
|
scripts/train.py
CHANGED
|
@@ -9,11 +9,18 @@ from pathlib import Path
|
|
| 9 |
# Add project root to path
|
| 10 |
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 11 |
|
| 12 |
-
|
| 13 |
-
from src.
|
| 14 |
-
from src.
|
| 15 |
-
from src.tuning.
|
| 16 |
-
from src.tuning.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
| 19 |
logger = logging.getLogger(__name__)
|
|
|
|
| 9 |
# Add project root to path
|
| 10 |
sys.path.insert(0, str(Path(__file__).parent.parent))
|
| 11 |
|
| 12 |
+
try:
|
| 13 |
+
from src.config import ModelConfig, TrainingConfig, DataConfig
|
| 14 |
+
from src.model import load_model, load_tokenizer, prepare_for_training
|
| 15 |
+
from src.tuning.lora import apply_lora
|
| 16 |
+
from src.tuning.data import create_dummy_data, prepare_dataset
|
| 17 |
+
from src.tuning.trainer import PrecisTrainer
|
| 18 |
+
except ImportError:
|
| 19 |
+
from init.config import ModelConfig, TrainingConfig, DataConfig
|
| 20 |
+
from init.model import load_model, load_tokenizer, prepare_for_training
|
| 21 |
+
from init.tuning.lora import apply_lora
|
| 22 |
+
from init.tuning.data import create_dummy_data, prepare_dataset
|
| 23 |
+
from init.tuning.trainer import PrecisTrainer
|
| 24 |
|
| 25 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
| 26 |
logger = logging.getLogger(__name__)
|