Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Reader3 AI 配置
# 填入你的 API Key 后保存,重启应用生效
# 免费获取 Gemini Key: https://aistudio.google.com/apikey

GEMINI_API_KEY=""
58 changes: 47 additions & 11 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,14 +1,50 @@
# Python-generated files
__pycache__/
*.py[oc]
build/
dist/
wheels/
*.egg-info
# Book data (extracted images, pkl, etc.)
*_data/

# Virtual environments
.venv
# TTS cache
.tts_cache/

# Custom
*_data/
# Library metadata cache
.library_index.json

# EPUB source files
*.epub
!assets/Meditations by Emperor of Rome Marcus Aurelius.epub

# Dictionary data
dict/

# Test files
test_*.py

# Python
__pycache__/
*.pyc
.venv/

# OS
.DS_Store

# AI config (contains API keys)
ai_config.json

# --- bkit / PDCA metadata ---
docs/.pdca-snapshots/
docs/.pdca-status.json
docs/.bkit-memory.json

# 敏感环境配置文件(截获 .env)
.env
.env.*
!.env.example

# 插件及工具生成的本地配置(截获 settings.local.json)
settings.local.json
.claude/
.gemini/

# 日志文件(截获 server.log)
*.log

# PDCA 状态文件(补全根目录下的路径,截获 .pdca-status.json)
.pdca-status.json
52 changes: 52 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Reader3 — AI 智能电子书阅读器

## 项目简介

本地部署的 AI EPUB 阅读器,集成划词查词、AI 翻译/对话、TTS 朗读、高亮笔记系统。灵感源自 Karpathy 的同名项目,在其基础上深度重构。

## 架构

| 文件 | 职责 |
|------|------|
| `server.py` | FastAPI 后端 — 图书加载、AI 路由(20+ 提供商)、TTS (edge-tts)、Google Translate、ECDICT 词典、EPUB 上传 |
| `reader3.py` | EPUB 解析模块 |
| `templates/reader.html` | 阅读器页面(CSS + HTML + JS 单文件) |
| `templates/library.html` | 图书馆页面(封面墙、上传、Apple Books 扫描) |
| `tools/_md2pdf.py` | 文档转 PDF(Playwright/Chromium),源文件在 `docs/` |

## 常用命令

```bash
# 启动开发服务
uvicorn server:app --host 0.0.0.0 --port 8123 --reload

# 生成文档 PDF
python tools/_md2pdf.py
```

## 开发规范

- **包管理**:始终使用 `uv pip install`,不用 pip
- **语言**:始终用中文回复
- **前端**:reader.html 是单文件架构(CSS + HTML + JS),不拆分
- **数据存储**:图书数据 `{name}_data/book.pkl`(pickle),高亮笔记在浏览器 localStorage
- **AI 配置**:`ai_config.json` 存储提供商设置,`.env` 存储 API Key

## 目录说明

```
reader3/
├── server.py / reader3.py # 后端
├── templates/ # 前端页面
├── docs/ # 源文档 (md)
├── tools/ # 开发工具脚本
├── assets/ # 截图、预置电子书
├── dict/ # 词典文件(应用内下载)
└── books/ # 导入的电子书数据
```

## 隐私约束

- `books/` 下的电子书数据、`.env`、`ai_config.json` 禁止提交
- 词典文件 (`dict/*.db`) 不提交
- 服务器日志 `server.log` 不提交
16 changes: 16 additions & 0 deletions GEMINI.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Project Intelligence: Reader3

一个现代化的、支持 AI 交互的 EPUB 阅读器。

## 🚀 运行环境 (Runtime)
- **后端**: FastAPI
- **音频引擎**: Edge-TTS
- **环境管理**: `uv` (强制)

## 🧠 AI 协作规范 (AI Patterns)
- **模型选型**: 已固定为 **gemini-1.5-flash** (追求极速响应)。
- **核心功能**: 负责全文翻译、内容摘要及 TTS 文本预处理。

## 📁 隔离规范 (Isolation)
- **数据缓存**: `books/` 目录下的解析结果和 `cache/` 音频严禁提交。
- **字典**: `dict/` 下的本地词库不被跟踪。
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Haining Yu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
78 changes: 78 additions & 0 deletions README.en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
English | [简体中文](README.md) | [繁體中文](README.zh-Hant.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | [Español](README.es.md) | [Français](README.fr.md) | [Italiano](README.it.md)

# 🧊 Smoothie Reader (Reader3)

> "When technology is democratized by AI, aesthetics and human-centric design become the ultimate differentiators."

Inspired by Andrej Karpathy's [minimalist reader prototype](https://x.com/karpathy/status/1990577951671509438), Smoothie Reader is a locally deployed AI-powered e-book reader with built-in word lookup, AI translation & chat, TTS reading, and highlight notes — designed for deep reading.

📖 **Built-in sample book**: The repository includes "Meditations" by Marcus Aurelius (via Project Gutenberg), ready to explore after cloning.

<div align="center">
<img src="assets/library.jpg" width="800" alt="Library"><br>
<sub>Your personal library at a glance</sub>
</div>

## ✨ Key Features

- 🔍 **Intuitive Discovery**: Highlight any text to reveal the action bar. Built-in support for **ECDICT** (English) and Chinese offline dictionaries.
- 🤖 **AI-Powered Reading**:
- **Inline Translation**: High-quality, contextual translations elegantly embedded below the original text.
- **AI Companion**: A sidebar AI assistant supporting streaming dialogue and multi-turn memory for deep engagement.
- **Broad Compatibility**: Built-in support for OpenAI, Anthropic, Gemini, DeepSeek, Grok, Alibaba Cloud Bailian, Volcengine, Tencent Hunyuan, MiniMax, Moonshot, SiliconFlow, Cerebras, SambaNova, Groq, Mistral, DeepInfra, Together AI, OpenRouter, Zhipu AI, and ModelScope — 20 AI providers in total, plus custom OpenAI-compatible endpoints.

<div align="center">
<img src="assets/reader_AItools.jpg" width="800" alt="AI Tools"><br>
<sub>Selection toolbar · Inline translation · AI companion sidebar</sub>
</div>

- 🔊 **TTS Reading**: Powered by Edge-TTS with multiple high-quality Chinese and English voices.
- ✏️ **Highlights & Notes**: 5-color highlighting, inline annotations, and bookmarks — all stored in your browser's **localStorage**.

<div align="center">
<img src="assets/reader_catelog.jpg" width="800" alt="Reading Layout"><br>
<sub>Three-column reading: TOC navigation · Immersive text · Multi-color highlights</sub>
</div>

- 🎨 **Minimalist Aesthetics**: 6 curated themes and a flexible 3-column layout (TOC / Content / AI), optimized for all devices.

<div align="center">
<img src="assets/reader_setting.jpg" width="800" alt="Settings"><br>
<sub>Themes, typography, dictionaries, AI models — all in one panel</sub>
</div>

## 🚀 Quick Start

This project uses [uv](https://docs.astral.sh/uv/) to manage the Python environment and dependencies.

### 1. Install uv
Ensure Python 3.10+ is available, then install `uv`:
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

### 2. Import a Book & Launch
```bash
# Import an EPUB e-book
uv run reader3.py your_book.epub

# Start the server
uv run server.py
```
Open your browser at: 👉 **http://localhost:8123**

### 3. Configure AI
Enter the reading interface, click **Settings** in the top-left corner, and configure your **AI Provider** and API Key (e.g., [get a free Gemini Key](https://aistudio.google.com/apikey)).

> [!TIP]
> **🚀 Easter Egg**: Anywhere on the page, enter **`↑ ↑ ↓ ↓ ← → ← → B A`** (Konami Code) to unlock the hidden **Advanced AI Routing Panel**.

## 🛡️ Privacy
- **Local First**: No data leaves your device unless you explicitly trigger an AI or TTS request.
- **No Account Required**: Your data is stored only in your browser's `localStorage`.

## 📚 User Guide
For detailed configuration (offline dictionaries, multi-device access, port settings), see the [User Guide](docs/GUIDE.md).

## 📄 License
[MIT License](LICENSE)
78 changes: 78 additions & 0 deletions README.es.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
[English](README.en.md) | [简体中文](README.md) | [繁體中文](README.zh-Hant.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | Español | [Français](README.fr.md) | [Italiano](README.it.md)

# 🧊 Smoothie Reader (Reader3)

> "Cuando la tecnología es democratizada por la IA, la estética y el diseño centrado en el ser humano se convierten en los diferenciadores definitivos."

Inspirado por el [prototipo de lector minimalista](https://x.com/karpathy/status/1990577951671509438) de Andrej Karpathy, Smoothie Reader es un lector de libros electrónicos con IA que se ejecuta localmente. Integra búsqueda de palabras, traducción y diálogo con IA, lectura TTS y notas de resaltado, diseñado para una lectura profunda.

📖 **Libro de ejemplo incluido**: El repositorio incluye "Meditaciones" de Marco Aurelio (vía Project Gutenberg), listo para explorar tras clonar.

<div align="center">
<img src="assets/library.jpg" width="800" alt="Library"><br>
<sub>Tu biblioteca personal de un vistazo</sub>
</div>

## ✨ Características Principales

- 🔍 **Descubrimiento Intuitivo**: Resalte cualquier texto para revelar la barra de acciones. Soporte integrado para **ECDICT** (Inglés) y diccionarios chinos offline.
- 🤖 **Lectura Potenciada por IA**:
- **Traducción en Línea**: Traducciones contextuales de alta calidad elegantemente incrustadas bajo el texto original.
- **Compañero IA**: Un asistente de IA en la barra lateral que admite diálogos en streaming y memoria de múltiples turnos.
- **Amplia Compatibilidad**: Soporte integrado para OpenAI, Anthropic, Gemini, DeepSeek, Grok, Alibaba Cloud Bailian, Volcengine, Tencent Hunyuan, MiniMax, Moonshot, SiliconFlow, Cerebras, SambaNova, Groq, Mistral, DeepInfra, Together AI, OpenRouter, Zhipu AI y ModelScope — 20 proveedores de IA en total, más endpoints personalizados compatibles con OpenAI.

<div align="center">
<img src="assets/reader_AItools.jpg" width="800" alt="AI Tools"><br>
<sub>Barra de selección · Traducción en línea · Panel lateral del compañero IA</sub>
</div>

- 🔊 **Lectura TTS**: Potenciado por Edge-TTS con múltiples voces de alta calidad en chino e inglés.
- ✏️ **Resaltados y Notas**: Resaltado de 5 colores, anotaciones en línea y marcadores — todo almacenado en el **localStorage** de tu navegador.

<div align="center">
<img src="assets/reader_catelog.jpg" width="800" alt="Reading Layout"><br>
<sub>Lectura en 3 columnas: navegación ToC · Texto inmersivo · Resaltados multicolor</sub>
</div>

- 🎨 **Estética Minimalista**: 6 temas curados y un diseño flexible de 3 columnas (ToC/Contenido/IA), optimizado para todos los dispositivos.

<div align="center">
<img src="assets/reader_setting.jpg" width="800" alt="Settings"><br>
<sub>Temas, tipografía, diccionarios, modelos IA — configuración todo en uno</sub>
</div>

## 🚀 Inicio Rápido

Este proyecto utiliza [uv](https://docs.astral.sh/uv/) para gestionar el entorno Python y las dependencias.

### 1. Instalar uv
Asegúrese de tener Python 3.10+ disponible. Instale `uv`:
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

### 2. Importar un Libro e Iniciar
```bash
# Importar un libro electrónico EPUB
uv run reader3.py your_book.epub

# Iniciar el servidor
uv run server.py
```
Acceda al lector en: 👉 **http://localhost:8123**

### 3. Configurar IA
Entre en la interfaz de lectura, haga clic en **Configuración (Settings)** en la esquina superior izquierda y configure su **Proveedor de IA** y clave API (ej., [obtenga una Gemini Key gratis](https://aistudio.google.com/apikey)).

> [!TIP]
> **🚀 Huevo de Pascua**: En cualquier lugar de la página, ingrese **`↑ ↑ ↓ ↓ ← → ← → B A`** (Código Konami) para desbloquear el **Panel Avanzado de Enrutamiento de IA** oculto.

## 🛡️ Privacidad
- **Local Primero**: Ningún dato sale de su dispositivo a menos que active explícitamente una solicitud de IA o TTS.
- **Sin Cuenta**: Sus datos se almacenan solo en el `localStorage` de su navegador.

## 📚 Guía de Usuario
Para configuraciones detalladas (diccionarios offline, acceso multidispositivo, configuración de puertos), consulte la [Guía de Usuario](docs/GUIDE.md).

## 📄 Licencia
[MIT License](LICENSE)
78 changes: 78 additions & 0 deletions README.fr.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
[English](README.en.md) | [简体中文](README.md) | [繁體中文](README.zh-Hant.md) | [日本語](README.ja.md) | [한국어](README.ko.md) | [Español](README.es.md) | Français | [Italiano](README.it.md)

# 🧊 Smoothie Reader (Reader3)

> "Lorsque la technologie est démocratisée par l'IA, l'esthétique et le design centré sur l'humain deviennent les ultimes différenciateurs."

Inspiré par le [prototype de lecteur minimaliste](https://x.com/karpathy/status/1990577951671509438) d'Andrej Karpathy, Smoothie Reader est un lecteur de livres numériques alimenté par l'IA qui fonctionne localement. Il intègre la recherche de mots, la traduction et le dialogue IA, la lecture TTS et les notes surlignées, conçu pour une lecture approfondie.

📖 **Livre exemple inclus** : Le dépôt contient les « Méditations » de Marc Aurèle (via Project Gutenberg), prêt à explorer après le clonage.

<div align="center">
<img src="assets/library.jpg" width="800" alt="Library"><br>
<sub>Votre bibliothèque personnelle en un coup d'œil</sub>
</div>

## ✨ Fonctionnalités Principales

- 🔍 **Découverte Intuitive** : Surlignez n'importe quel texte pour révéler la barre d'action. Prise en charge intégrée d'**ECDICT** (Anglais) et de dictionnaires chinois hors ligne.
- 🤖 **Lecture Augmentée par l'IA** :
- **Traduction en Ligne** : Traductions contextuelles de haute qualité élégamment intégrées sous le texte original.
- **Compagnon IA** : Un assistant IA en barre latérale prenant en charge le dialogue en streaming et la mémoire multi-tours.
- **Large Compatibilité** : Prise en charge intégrée d'OpenAI, Anthropic, Gemini, DeepSeek, Grok, Alibaba Cloud Bailian, Volcengine, Tencent Hunyuan, MiniMax, Moonshot, SiliconFlow, Cerebras, SambaNova, Groq, Mistral, DeepInfra, Together AI, OpenRouter, Zhipu AI et ModelScope — 20 fournisseurs d'IA au total, plus des endpoints personnalisés compatibles OpenAI.

<div align="center">
<img src="assets/reader_AItools.jpg" width="800" alt="AI Tools"><br>
<sub>Barre de sélection · Traduction en ligne · Panneau latéral du compagnon IA</sub>
</div>

- 🔊 **Lecture TTS** : Propulsé par Edge-TTS avec plusieurs voix de haute qualité en chinois et en anglais.
- ✏️ **Surlignages et Notes** : Surlignage en 5 couleurs, annotations en ligne et signets — le tout stocké dans le **localStorage** de votre navigateur.

<div align="center">
<img src="assets/reader_catelog.jpg" width="800" alt="Reading Layout"><br>
<sub>Lecture en 3 colonnes : navigation ToC · Texte immersif · Surlignages multicolores</sub>
</div>

- 🎨 **Esthétique Minimaliste** : 6 thèmes sélectionnés et une mise en page flexible à 3 colonnes (ToC/Contenu/IA), optimisée pour tous les appareils.

<div align="center">
<img src="assets/reader_setting.jpg" width="800" alt="Settings"><br>
<sub>Thèmes, typographie, dictionnaires, modèles IA — configuration tout-en-un</sub>
</div>

## 🚀 Démarrage Rapide

Ce projet utilise [uv](https://docs.astral.sh/uv/) pour gérer l'environnement Python et les dépendances.

### 1. Installer uv
Assurez-vous que Python 3.10+ est disponible. Installez `uv` :
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

### 2. Importer un Livre et Lancer
```bash
# Importer un livre EPUB
uv run reader3.py your_book.epub

# Démarrer le serveur
uv run server.py
```
Accédez au lecteur sur : 👉 **http://localhost:8123**

### 3. Configurer l'IA
Entrez dans l'interface de lecture, cliquez sur **Paramètres (Settings)** en haut à gauche et configurez votre **Fournisseur d'IA** et clé API (ex. [obtenez une clé Gemini gratuite](https://aistudio.google.com/apikey)).

> [!TIP]
> **🚀 Œuf de Pâques** : N'importe où sur la page, entrez **`↑ ↑ ↓ ↓ ← → ← → B A`** (Code Konami) pour déverrouiller le **Panneau de Routage IA Avancé** caché.

## 🛡️ Confidentialité
- **Local d'Abord** : Aucune donnée ne quitte votre appareil sauf si vous déclenchez explicitement une requête IA ou TTS.
- **Sans Compte** : Vos données restent exclusivement dans le `localStorage` de votre navigateur.

## 📚 Guide Utilisateur
Pour des configurations détaillées (dictionnaires hors ligne, accès multi-appareils, paramètres de port), consultez le [Guide Utilisateur](docs/GUIDE.md).

## 📄 Licence
[MIT License](LICENSE)
Loading