-
Notifications
You must be signed in to change notification settings - Fork 456
Expand file tree
/
Copy pathserver.py
More file actions
144 lines (118 loc) · 4.75 KB
/
server.py
File metadata and controls
144 lines (118 loc) · 4.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import os
import pickle
from functools import lru_cache
from typing import Optional
from groq import Groq
from pydantic import BaseModel
import dotenv
dotenv.load_dotenv()
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import StreamingResponse
from reader3 import Book, BookMetadata, ChapterContent, TOCEntry
app = FastAPI()
templates = Jinja2Templates(directory="templates")
class ChatRequest(BaseModel):
message: str
client = Groq(api_key=os.getenv("GROQ_KEY"))
@app.post("/chat-stream")
async def chat_stream(req: ChatRequest):
def generate():
stream = client.chat.completions.create(
model="llama-3.1-8b-instant",
stream=True,
messages=[{"role": "user", "content": req.message}],
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta:
delta = chunk.choices[0].delta.content
if delta:
# Groq may return list or string
if isinstance(delta, list):
for item in delta:
if "text" in item:
yield item["text"]
else:
yield delta
return StreamingResponse(generate(), media_type="text/plain")
# Where are the book folders located?
BOOKS_DIR = "."
@lru_cache(maxsize=10)
def load_book_cached(folder_name: str) -> Optional[Book]:
"""
Loads the book from the pickle file.
Cached so we don't re-read the disk on every click.
"""
file_path = os.path.join(BOOKS_DIR, folder_name, "book.pkl")
if not os.path.exists(file_path):
return None
try:
with open(file_path, "rb") as f:
book = pickle.load(f)
return book
except Exception as e:
print(f"Error loading book {folder_name}: {e}")
return None
@app.get("/", response_class=HTMLResponse)
async def library_view(request: Request):
"""Lists all available processed books."""
books = []
# Scan directory for folders ending in '_data' that have a book.pkl
if os.path.exists(BOOKS_DIR):
for item in os.listdir(BOOKS_DIR):
if item.endswith("_data") and os.path.isdir(item):
# Try to load it to get the title
book = load_book_cached(item)
if book:
books.append({
"id": item,
"title": book.metadata.title,
"author": ", ".join(book.metadata.authors),
"chapters": len(book.spine)
})
return templates.TemplateResponse("library.html", {"request": request, "books": books})
@app.get("/read/{book_id}", response_class=HTMLResponse)
async def redirect_to_first_chapter(book_id: str):
"""Helper to just go to chapter 0."""
return await read_chapter(book_id=book_id, chapter_index=0)
@app.get("/read/{book_id}/{chapter_index}", response_class=HTMLResponse)
async def read_chapter(request: Request, book_id: str, chapter_index: int):
"""The main reader interface."""
book = load_book_cached(book_id)
if not book:
raise HTTPException(status_code=404, detail="Book not found")
if chapter_index < 0 or chapter_index >= len(book.spine):
raise HTTPException(status_code=404, detail="Chapter not found")
current_chapter = book.spine[chapter_index]
# Calculate Prev/Next links
prev_idx = chapter_index - 1 if chapter_index > 0 else None
next_idx = chapter_index + 1 if chapter_index < len(book.spine) - 1 else None
return templates.TemplateResponse("reader.html", {
"request": request,
"book": book,
"current_chapter": current_chapter,
"chapter_index": chapter_index,
"book_id": book_id,
"prev_idx": prev_idx,
"next_idx": next_idx
})
@app.get("/read/{book_id}/images/{image_name}")
async def serve_image(book_id: str, image_name: str):
"""
Serves images specifically for a book.
The HTML contains <img src="images/pic.jpg">.
The browser resolves this to /read/{book_id}/images/pic.jpg.
"""
# Security check: ensure book_id is clean
safe_book_id = os.path.basename(book_id)
safe_image_name = os.path.basename(image_name)
img_path = os.path.join(BOOKS_DIR, safe_book_id, "images", safe_image_name)
if not os.path.exists(img_path):
raise HTTPException(status_code=404, detail="Image not found")
return FileResponse(img_path)
if __name__ == "__main__":
import uvicorn
print("Starting server at http://127.0.0.1:8123")
uvicorn.run(app, host="127.0.0.1", port=8123)