# via007/bilibili-rag architecture

> Architecture diagram of the GitHub repository via007/bilibili-rag, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-10). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/via007/bilibili-rag
- Repository: https://github.com/via007/bilibili-rag

## Overview

##### 项目类型与目的（先在图上用一句话定调）
这是一个 **全栈 RAG 应用**：把用户的 **B 站收藏夹视频**拉取下来，进行 **音频获取 → ASR 转写 → 切分/向量化 → 存入向量库**，最终在 Web 前端提供 **可追溯来源的对话问答**。

图上建议在标题旁标注关键链路：**Bilibili → Fetch/ASR → Embeddings/Chroma → RAG Chat (LLM)**，并强调本地存储是 **SQLite + ChromaDB**，LLM/Embedding/ASR 走 **DashScope**。

##### 从文件树提取“必须画出来”的模块边界
按目录拆解组件（画图时每个组件尽量对应一个目录/文件群）：

##### 后端（FastAPI）
- `app/main.py`：FastAPI 启动入口、路由挂载（在图里是 **API Gateway/Backend**）
- `app/routers/`：对外 API 边界（画成 Backend 内部的“Controller/Route 层”）
- `auth.py`：B 站扫码登录 / Cookie/Token（对接 Bilibili）
- `knowledge.py`：知识库构建/同步（收藏夹 → 文档/向量）
- `chat.py`：对话接口（RAG 检索 + LLM 生成）
- `favorites.py`：收藏夹读取/列表
- `app/services/`：核心业务能力（画成 Backend 内部的“Service 层”）
- `bilibili.py` + `wbi.py`：B 站接口调用、签名/鉴权（外部依赖：Bilibili）
- `content_fetcher.py`：拉取视频信息/音频 URL/下载（含 Cookie 兜底）
- `asr.py`：ASR 流程（ffmpeg 转码 + DashScope 识别）
- `rag.py`：RAG 主流程（切分、Embedding、向量检索、拼 prompt、调用 LLM）
- `app/database.py` + `app/models.py`：SQLite 的 ORM/数据模型（持久化：收藏夹、视频、转写、元数据、可能的索引状态等）
- `app/config.py`：环境变量与配置（.env 里的 DashScope Key 等）

##### 前端（Next.js + Tailwind）
- `frontend/app/page.tsx` 等：页面入口（画成 **Web UI**）
- `frontend/components/*`：
- `ChatPanel.tsx`：对话 UI（对接 `/chat`）
- `LoginModal.tsx`：扫码登录 UI（对接 `/auth`）
- `SourcesPanel.tsx`：来源/引用展示（强烈建议在图上体现“可追溯来源”能力）
- `frontend/lib/api.ts`：前端到后端的 API client（图里是前端到后端的 HTTPS 调用）

##### 测试/诊断脚本（可选：放在“运维/开发工具”泳道）
- `test/debug_asr_single.py`：验证音频与 ASR 链路
- `test/diagnose_rag.py`：验证召回质量
- `test/sync_cache_vectors.py`：SQLite 缓存与向量库同步（这说明系统存在“结构化库 vs 向量库”双存储一致性问题，建议图上标注）

##### 需要在架构图中明确的外部依赖与运行时
从 README 与结构可以确定这些外部/运行时节点必须画出来：

- **Bilibili 平台**（外部）：登录、收藏夹、视频/音频资源
- **DashScope**（外部 AI 平台）：至少包含三类能力
- ASR（语音识别）
- Embedding（向量化）
- LLM Chat Completion（生成回答）
- **ffmpeg**（本机依赖）：ASR 兜底流程关键环节（“转码 16k 单声道”）
- **本地存储**（通常在 `data/` 下，README 提到）
- SQLite（结构化元数据、缓存、状态）
- ChromaDB（向量库/索引）

##### 推荐你画的“最准确”的 3 张图（从宏观到细节）
为了“既全面又准确”，建议拆成三层：Context → Container → Sequence/Dataflow。每张图都能从文件树精确映射到代码归属。

##### 图 A：系统上下文图（C4 - Context）
目标：让人一眼知道系统在生态中的位置。
组件：
- 用户（Browser）
- Web UI（Next.js）
- Backend API（FastAPI）
- 外部：Bilibili、DashScope
- 本地：SQLite、ChromaDB、ffmpeg（可作为 backend 所在 host 的依赖）

箭头（务必带动词）：
- Browser → Next.js：访问页面
- Next.js → FastAPI：REST 调用（登录/收藏夹/构建知识库/聊天）
- FastAPI ↔ Bilibili：扫码登录、拉取收藏夹、获取媒体信息、下载音频（Cookie）
- FastAPI ↔ DashScope：ASR / Embedding / LLM
- FastAPI ↔ SQLite：元数据/缓存/状态
- FastAPI ↔ ChromaDB：upsert embeddings、query 相似片段
- FastAPI → ffmpeg：本地转码（process call）

##### 图 B：容器/组件图（C4 - Container/Component）
目标：体现后端内部边界（routers vs services vs storage），以及前端关键 UI 组件。
建议画法：
- 一个大框 “Backend (FastAPI)” 内分三层：
1) Routers：`auth/chat/knowledge/favorites`
2) Services：`bilibili/wbi/content_fetcher/asr/rag`
3) Persistence：`database/models`（SQLite）、Chroma client
- 一个框 “Frontend (Next.js)” 内标出：
- Pages（`app/page.tsx`）
- Components（ChatPanel/LoginModal/SourcesPanel）
- API client（`lib/api.ts`）

关键关系：
- Routers → Services（控制层调用业务层）
- `knowledge` router → `content_fetcher` + `asr` + `rag`（构建知识库管线）
- `chat` router → `rag`（检索+生成）
- `auth` router → `bilibili/wbi`（登录鉴权）
- Services → SQLite/Chroma/DashScope/Bilibili/ffmpeg

##### 图 C：核心时序/数据流图（Sequence / Pipeline）
目标：把 README 的“工作流程”落到真实实现组件（最能体现准确性）。
至少画两条主链路：

##### 知识库构建（Favorites → KB）
- User 在 UI 选择收藏夹
- Frontend 调 `POST /knowledge/build`（或相近接口，按实际路由命名）
- Backend:
- `favorites`/`knowledge` → `bilibili` 拉取视频列表与元信息
- `content_fetcher` 获取音频 URL；如 403：
- 用 Cookie 下载 → ffmpeg 转码 → 上传 DashScope ASR
- `asr` 产出 transcript
- `rag` 做切分、调用 DashScope Embedding
- 写入：
- SQLite：视频、转写文本、分段元数据、来源信息、处理状态
- ChromaDB：向量 + metadata（video_id、timestamp、title、source_url 等）

##### 对话问答（Chat with citations）
- User 在 ChatPanel 提问
- Frontend 调 `POST /chat`
- Backend:
- `rag`：query embedding → Chroma similarity search → top-k chunks
- `rag`：组装 prompt（含引用信息/来源链接/时间戳）
- 调 DashScope LLM
- 返回 answer + sources
- Frontend：SourcesPanel 展示引用来源

> 这张图要特别强调“来源可追溯”：检索返回的 chunk metadata 如何回到 UI 的引用展示。

##### 你在图里必须“画细”的点（体现架构质量）
结合 README 的“音频不可达兜底”和双存储：

##### ASR 兜底分支
- “音频 URL 直链可达” vs “403 不可达”两个分支
- 不可达分支包含：下载（带 Cookie）→ ffmpeg 转码 → 上传 → ASR
- 这是项目差异化能力，建议用红色或注释框标出来

##### 双存储一致性（SQLite + ChromaDB）
- SQLite 存结构化状态；Chroma 存向量索引
- `test/sync_cache_vectors.py` 暗示存在“从缓存同步到向量库”的流程
- 在图上标注“可能的重建/同步任务”，避免别人误解为单一存储

##### DashScope 的三种调用
- ASR、Embedding、LLM 是不同 API/模型计费与 SLA
- 在图上分成三个子块（即使都属于 DashScope），便于讨论成本与瓶颈

- **组件命名**：尽量用 “职责 + 技术” 双标签
- 例：`RAG Service (LangChain + DashScope)`、`Vector Store (ChromaDB)`、`Metadata DB (SQLite)`
- **箭头必须带动词**：Fetch / Download / Transcode / Transcribe / Embed / Upsert / Query / Generate
- **颜色/形状约定**（建议固定一套）：
- 蓝色：你的服务（Frontend/Backend）
- 灰色：数据存储（SQLite/Chroma）
- 橙色：外部依赖（Bilibili、DashScope）
- 虚线：异步/批处理/可选路径（如 sync_cache_vectors、ASR 兜底）
- **标注协议/接口**（简写即可）：
- Frontend → Backend：HTTPS/JSON
- Backend → DashScope：HTTP API
- Backend → ffmpeg：local process call
- Backend → SQLite/Chroma：local file/db client

##### 针对本项目的“不要漏画清单”
- Next.js 前端与 FastAPI 后端分离（两个独立进程：3000/8000）
- B 站扫码登录（auth）与 Cookie 在后端使用
- 音频获取的 403 分支 + ffmpeg 转码
- DashScope 的 ASR/Embedding/LLM 三段式
- SQLite + ChromaDB 双持久化
- 引用来源展示（SourcesPanel）与 metadata 流向

##### 可直接复用的图结构（建议你照这个拆）
- 一张 **Context**（1 屏）
- 一张 **Container/Component**（1-2 屏，精细到 routers/services）
- 两张 **Sequence**（Build KB / Chat）
- （可选）一张 **Data model / Storage**：SQLite 表（videos, transcripts, chunks, favorites, jobs）+ Chroma collection 与 metadata 字段（video_id, ts, url, title）

只要按上述拆法画，基本能做到“最大程度贴合代码结构”，同时满足系统设计评审对边界、依赖、数据流、异常分支（403 兜底）和存储一致性的关注点。

## Diagram (Mermaid)

```mermaid
flowchart TD
  %% =========================
  %% Title / Context tagline
  %% =========================
  T["Full-stack RAG: Bilibili → Fetch/ASR → Embeddings/Chroma → RAG Chat (LLM)\nLocal: SQLite + ChromaDB | AI: DashScope (ASR/Embedding/LLM)"]:::title

  %% =========================
  %% External Actors / Systems
  %% =========================
  U["User (Browser)"]:::external
  BILI["Bilibili Platform\n(Login/Favorites/Media)"]:::external
  subgraph "DashScope AI Platform (External)"
    direction TB
    DS_ASR["DashScope ASR API"]:::externalAI
    DS_EMB["DashScope Embedding API"]:::externalAI
    DS_LLM["DashScope LLM Chat API"]:::externalAI
  end
  FFMPEG["ffmpeg (local process)\nTranscode 16k mono"]:::infra

  %% =========================
  %% Local Storage
  %% =========================
  subgraph "Local Storage (data/)"
    direction TB
    SQLITE[("Metadata DB (SQLite)\nVideos/Transcripts/Chunks/Jobs/Status")]:::storage
    CHROMA[("Vector Store (ChromaDB)\nEmbeddings + metadata")]:::storage
  end

  %% =========================
  %% Frontend (Next.js)
  %% =========================
  subgraph "Frontend (Next.js + Tailwind)"
    direction TB
    FE_APP["Web UI App (Next.js)"]:::frontend
    FE_PAGE["Main Page (app/page.tsx)"]:::frontend
    FE_LAYOUT["Layout (app/layout.tsx)"]:::frontend
    FE_GLOBALS["Globals (Tailwind/CSS)"]:::frontend

    subgraph "UI Components"
      direction TB
      FE_LOGIN["LoginModal\n(Bilibili QR login)"]:::frontend
      FE_CHAT["ChatPanel\n(Chat UX)"]:::frontend
      FE_SOURCES["SourcesPanel\n(Traceable citations)"]:::frontend
    end

    FE_API["API Client (frontend/lib/api.ts)\nHTTPS/JSON"]:::frontend
  end

  %% =========================
  %% Backend (FastAPI)
  %% =========================
  subgraph "Backend (FastAPI)"
    direction TB
    BE_MAIN["API Gateway / App Entrypoint (FastAPI)"]:::backend
    BE_CONFIG["Config (.env / DashScope keys)"]:::backend

    subgraph "Routers (API Boundary)"
      direction TB
      R_AUTH["Auth Router\n/ auth (QR login, cookie/token)"]:::backend
      R_FAV["Favorites Router\n/ favorites (list/read)"]:::backend
      R_KNOW["Knowledge Router\n/ knowledge (build/sync KB)"]:::backend
      R_CHAT["Chat Router\n/ chat (RAG chat)"]:::backend
    end

    subgraph "Services (Business Logic)"
      direction TB
      S_BILI["Bilibili Client Service\n(API calls)"]:::service
      S_WBI["WBI Sign/Auth Helper\n(signature, auth)"]:::service
      S_FETCH["Content Fetcher\n(video info, audio URL, download w cookie)"]:::service
      S_ASR["ASR Pipeline\n(ffmpeg + DashScope ASR)"]:::service
      S_RAG["RAG Pipeline\n(chunking, embed, vector search, prompt, LLM)"]:::service
    end

    subgraph "Persistence (Structured)"
      direction TB
      DB_LAYER["DB Session/Engine"]:::storageLayer
      DB_MODELS["ORM Models\n(videos/transcripts/chunks/...)"]:::storageLayer
    end
  end

  %% =========================
  %% Dev / Ops Tools
  %% =========================
  subgraph "Dev / Diagnostics Tools (optional)"
    direction TB
    TEST_ASR["debug_asr_single.py\n(ASR validation)"]:::devtool
    TEST_RAG["diagnose_rag.py\n(recall quality)"]:::devtool
    TEST_SYNC["sync_cache_vectors.py\n(SQLite ↔ Chroma consistency)"]:::devtool
    ASSETS["Demo / Assets\n(screenshots/video)"]:::devtool
  end

  %% =========================
  %% High-level context links
  %% =========================
  T --> U
  U -->|"Visit"| FE_APP
  FE_APP --> FE_PAGE
  FE_APP --> FE_LAYOUT
  FE_APP --> FE_GLOBALS
  FE_PAGE --> FE_LOGIN
  FE_PAGE --> FE_CHAT
  FE_CHAT --> FE_SOURCES
  FE_APP -->|"Calls"| FE_API

  FE_API -->|"HTTPS/JSON"| BE_MAIN
  BE_MAIN --> BE_CONFIG

  %% Router mounting
  BE_MAIN -->|"Mount"| R_AUTH
  BE_MAIN -->|"Mount"| R_FAV
  BE_MAIN -->|"Mount"| R_KNOW
  BE_MAIN -->|"Mount"| R_CHAT

  %% Routers -> Services
  R_AUTH -->|"Authenticate"| S_BILI
  R_AUTH -->|"Sign/Verify"| S_WBI
  R_FAV -->|"FetchFavorites"| S_BILI
  R_KNOW -->|"BuildKB"| S_FETCH
  R_KNOW -->|"Transcribe"| S_ASR
  R_KNOW -->|"Chunk/Embed/Upsert"| S_RAG
  R_CHAT -->|"Retrieve+Generate"| S_RAG

  %% Services -> external deps
  S_BILI <-->|"Login/Fetch/MediaMeta"| BILI
  S_WBI -->|"WBI signature"| BILI
  S_FETCH <-->|"FetchVideoInfo/AudioURL"| BILI

  %% ASR pipeline + fallback emphasis
  S_ASR -->|"Transcribe (HTTP API)"| DS_ASR
  S_ASR -->|"Transcode (local process)"| FFMPEG
  S_FETCH -.->|"403 fallback: download w cookie"| S_ASR
  S_FETCH -->|"AudioURL (direct)"| S_ASR

  %% RAG pipeline external calls + stores
  S_RAG -->|"Embed (HTTP API)"| DS_EMB
  S_RAG -->|"Generate (HTTP API)"| DS_LLM
  S_RAG -->|"Upsert vectors"| CHROMA
  S_RAG -->|"Query top-k"| CHROMA

  %% Backend persistence (SQLite)
  BE_MAIN --> DB_LAYER
  DB_LAYER --> SQLITE
  DB_MODELS --> SQLITE
  R_KNOW -->|"Write metadata/status"| DB_LAYER
  S_ASR -->|"Store transcript"| DB_LAYER
  S_FETCH -->|"Store video/meta"| DB_LAYER
  S_RAG -->|"Store chunks+sources"| DB_LAYER

  %% Traceable sources to UI
  CHROMA -->|"Chunk metadata (url/title/ts/video_id)"| S_RAG
  S_RAG -->|"Answer + sources[]"| R_CHAT
  R_CHAT -->|"JSON: answer + citations"| FE_API
  FE_API -->|"Render citations"| FE_SOURCES

  %% Sync / consistency (dashed batch)
  TEST_SYNC -.->|"Reconcile/Sync"| SQLITE
  TEST_SYNC -.->|"Reconcile/Sync"| CHROMA

  %% Diagnostics scripts
  TEST_ASR -.->|"Test audio→ASR chain"| S_ASR
  TEST_RAG -.->|"Evaluate retrieval"| S_RAG

  %% Assets
  ASSETS -.->|"Docs/demo material"| FE_APP

  %% =========================
  %% Click events (component_mapping)
  %% =========================
  click BE_MAIN "https://github.com/via007/bilibili-rag/blob/main/app/main.py"
  click BE_CONFIG "https://github.com/via007/bilibili-rag/blob/main/app/config.py"
  click DB_LAYER "https://github.com/via007/bilibili-rag/blob/main/app/database.py"
  click DB_MODELS "https://github.com/via007/bilibili-rag/blob/main/app/models.py"

  click R_AUTH "https://github.com/via007/bilibili-rag/blob/main/app/routers/auth.py"
  click R_FAV "https://github.com/via007/bilibili-rag/blob/main/app/routers/favorites.py"
  click R_KNOW "https://github.com/via007/bilibili-rag/blob/main/app/routers/knowledge.py"
  click R_CHAT "https://github.com/via007/bilibili-rag/blob/main/app/routers/chat.py"

  click S_BILI "https://github.com/via007/bilibili-rag/blob/main/app/services/bilibili.py"
  click S_WBI "https://github.com/via007/bilibili-rag/blob/main/app/services/wbi.py"
  click S_FETCH "https://github.com/via007/bilibili-rag/blob/main/app/services/content_fetcher.py"
  click S_ASR "https://github.com/via007/bilibili-rag/blob/main/app/services/asr.py"
  click S_RAG "https://github.com/via007/bilibili-rag/blob/main/app/services/rag.py"

  click FE_APP "https://github.com/via007/bilibili-rag/tree/main/frontend/app/"
  click FE_PAGE "https://github.com/via007/bilibili-rag/blob/main/frontend/app/page.tsx"
  click FE_LAYOUT "https://github.com/via007/bilibili-rag/blob/main/frontend/app/layout.tsx"
  click FE_GLOBALS "https://github.com/via007/bilibili-rag/blob/main/frontend/app/globals.css"

  click FE_CHAT "https://github.com/via007/bilibili-rag/blob/main/frontend/components/ChatPanel.tsx"
  click FE_LOGIN "https://github.com/via007/bilibili-rag/blob/main/frontend/components/LoginModal.tsx"
  click FE_SOURCES "https://github.com/via007/bilibili-rag/blob/main/frontend/components/SourcesPanel.tsx"
  click FE_API "https://github.com/via007/bilibili-rag/blob/main/frontend/lib/api.ts"

  click TEST_ASR "https://github.com/via007/bilibili-rag/blob/main/test/debug_asr_single.py"
  click TEST_RAG "https://github.com/via007/bilibili-rag/blob/main/test/diagnose_rag.py"
  click TEST_SYNC "https://github.com/via007/bilibili-rag/blob/main/test/sync_cache_vectors.py"

  click ASSETS "https://github.com/via007/bilibili-rag/tree/main/assets/demo/"

  %% =========================
  %% Styles
  %% =========================
  classDef title fill:#111827,stroke:#111827,color:#F9FAFB,stroke-width:2px
  classDef external fill:#F59E0B,stroke:#B45309,color:#111827,stroke-width:1px
  classDef externalAI fill:#FDBA74,stroke:#C2410C,color:#111827,stroke-width:1px
  classDef frontend fill:#93C5FD,stroke:#1D4ED8,color:#0B1220,stroke-width:1px
  classDef backend fill:#60A5FA,stroke:#1E40AF,color:#0B1220,stroke-width:1px
  classDef service fill:#34D399,stroke:#047857,color:#062016,stroke-width:1px
  classDef storage fill:#D1D5DB,stroke:#374151,color:#111827,stroke-width:1px
  classDef storageLayer fill:#E5E7EB,stroke:#4B5563,color:#111827,stroke-width:1px
  classDef infra fill:#9CA3AF,stroke:#111827,color:#111827,stroke-width:1px
  classDef devtool fill:#C4B5FD,stroke:#5B21B6,color:#0B1220,stroke-width:1px
```
