Bookly AI is an AI-powered study assistant that lets you upload PDFs, chat with retrieval-augmented answers, generate quizzes, review progress, and explore related YouTube content. It uses Supabase for authentication and persistence, Google Gemini for generation, and a lightweight RAG pipeline for grounded responses.
- Chat with RAG: Ask questions; answers cite relevant PDF pages when available.
- PDF ingestion: Upload, parse, embed, and search your documents.
- Quizzes and progress: Generate quizzes, track attempts, view weaknesses and dashboard.
- YouTube suggestions: Surface related topics and recommended videos.
- Auth & sessions: Supabase auth with middleware-protected routes.
graph TD
Start([Student Opens App]) --> Auth{Authenticated?}
Auth -->|No| Login[Login/Signup Page]
Login --> Dashboard
Auth -->|Yes| Dashboard[Main Dashboard]
Dashboard --> LeftPanel[Left Sidebar]
Dashboard --> CenterPanel[Center Chat Area]
Dashboard --> RightPanel[Right PDF Preview]
%% Left Sidebar Flow
LeftPanel --> NewChat[New Chat Button]
LeftPanel --> UploadedFiles[Uploaded Files Section]
LeftPanel --> ProgressDash[Progress Dashboard]
LeftPanel --> ChatHistory[Chat History List]
NewChat --> CreateNewChat[Create New Chat]
CreateNewChat --> CenterPanel
UploadedFiles --> ViewFiles[View All PDFs]
ViewFiles --> SelectPDF[Select PDF]
SelectPDF --> LoadPDF[Load PDF in Right Panel]
SelectPDF --> SetContext[Set as Chat Context]
ProgressDash --> ViewStats[View Statistics]
ViewStats --> QuizScores[Quiz Scores & History]
ViewStats --> Strengths[Strength Areas]
ViewStats --> Weaknesses[Weak Areas]
ViewStats --> AIAnalysis[AI-Generated Analysis]
ViewStats --> Activity[Activity Timeline]
ChatHistory --> SwitchChat[Click Chat]
SwitchChat --> LoadChat[Load Chat Context]
LoadChat --> CenterPanel
%% Center Chat Area Flow
CenterPanel --> InputBox[Chat Input Box]
InputBox --> TextInput{Input Type}
TextInput -->|Text| TypeMessage[Type Question/Message]
TextInput -->|Voice| VoiceInput[Voice Input]
TextInput -->|PDF Upload| UploadPDF[Upload New PDF]
TypeMessage --> SendMessage[Send Message]
VoiceInput --> TranscribeVoice[Transcribe Audio]
TranscribeVoice --> SendMessage
UploadPDF --> ProcessPDF[Process & Store PDF]
ProcessPDF --> ExtractText[Extract Text Content]
ExtractText --> ChunkEmbed[Chunk & Embed Text]
ChunkEmbed --> StoreVectors[Store in pgvector]
StoreVectors --> ShowUpload[Show in Uploaded Files]
ShowUpload --> LoadPDF
SendMessage --> QuizOption{Quiz Generation?}
QuizOption -->|Checkbox Selected| GenerateQuiz[Generate Quiz Immediately]
QuizOption -->|Not Selected| NormalChat[Process as Chat Message]
NormalChat --> RAGQuery[RAG Query Process]
RAGQuery --> EmbedQuery[Embed User Query]
EmbedQuery --> VectorSearch[Search Similar Chunks]
VectorSearch --> RetrieveContext[Retrieve Relevant Context]
RetrieveContext --> LLMResponse[Generate LLM Response]
LLMResponse --> CitedAnswer[Answer with Citations]
CitedAnswer --> DisplayAnswer[Display in Chat]
DisplayAnswer --> ShowCitations[Show Page Numbers & Quotes]
%% Quiz Generation Flow
GenerateQuiz --> QuizType[Select Quiz Type]
QuizType --> MCQ[MCQ Generator]
QuizType --> SAQ[SAQ Generator]
QuizType --> LAQ[LAQ Generator]
QuizType --> Mixed[Mixed Quiz]
MCQ --> GenMCQ[Generate MCQ Questions]
SAQ --> GenSAQ[Generate SAQ Questions]
LAQ --> GenLAQ[Generate LAQ Questions]
Mixed --> GenMixed[Generate Mixed Questions]
GenMCQ --> RenderQuiz[Render Quiz UI]
GenSAQ --> RenderQuiz
GenLAQ --> RenderQuiz
GenMixed --> RenderQuiz
RenderQuiz --> TakeQuiz[Student Takes Quiz]
TakeQuiz --> AnswerQs[Answer Questions]
AnswerQs --> SubmitQuiz[Submit Quiz]
SubmitQuiz --> EvaluateQuiz[Evaluate Answers]
EvaluateQuiz --> MCQScore[Auto-Score MCQs]
EvaluateQuiz --> AIScore[AI Score SAQs/LAQs]
MCQScore --> CalcScore[Calculate Total Score]
AIScore --> CalcScore
CalcScore --> ShowResults[Show Results]
ShowResults --> DetailedFeedback[Detailed Feedback]
DetailedFeedback --> CorrectAnswers[Show Correct Answers]
DetailedFeedback --> Explanations[Provide Explanations]
DetailedFeedback --> ConceptReview[Concept Review Links]
ShowResults --> StoreAttempt[Store Quiz Attempt]
StoreAttempt --> UpdateProgress[Update Progress Data]
UpdateProgress --> AnalyzePerformance[Analyze Performance]
AnalyzePerformance --> IdentifyWeakness[Identify Weak Topics]
AnalyzePerformance --> IdentifyStrength[Identify Strong Topics]
AnalyzePerformance --> UpdateDashboard[Update Dashboard Stats]
ShowResults --> RegenerateOption{Regenerate Quiz?}
RegenerateOption -->|Yes| GenerateQuiz
RegenerateOption -->|No| ContinueChat[Continue Chat Session]
%% Additional Features
DisplayAnswer --> YouTubeRec[YouTube Recommendations]
YouTubeRec --> FetchVideos[Fetch Related Videos]
FetchVideos --> DisplayVideos[Display Video Cards]
DisplayVideos --> WatchVideo[Student Watches Video]
%% Right Panel Flow
RightPanel --> PDFDisplay[PDF Display Component]
PDFDisplay --> TogglePDF{Toggle Visibility}
TogglePDF -->|Hide| CollapsePDF[Collapse Panel]
TogglePDF -->|Show| ExpandPDF[Expand Panel]
PDFDisplay --> ResizePanel[Resize Panel Width]
ResizePanel --> DragResize[Drag to Resize]
PDFDisplay --> NavigatePDF[Navigate PDF]
NavigatePDF --> PageControls[Page Navigation]
NavigatePDF --> SearchPDF[Search in PDF]
NavigatePDF --> JumpToPage[Jump to Cited Page]
ShowCitations -.->|Click Citation| JumpToPage
ContinueChat --> InputBox
WatchVideo --> ContinueChat
UpdateDashboard --> ProgressDash
style Start fill:#e1f5e1
style Dashboard fill:#e3f2fd
style GenerateQuiz fill:#fff3e0
style ShowResults fill:#f3e5f5
style StoreAttempt fill:#fce4ec
- Framework: Next.js 15 (App Router), React 19
- Styling/UI: Tailwind CSS v4, shadcn/ui components, Radix UI primitives,
lucide-react - State: Zustand
- Auth/DB: Supabase (
@supabase/ssr,@supabase/supabase-js) - LLM: Google Gemini (
@google/generative-ai) - PDF:
pdf-parse,@react-pdf-viewer/*
app/— Next.js routes (App Router) and API routes underapp/api/*components/— UI components (layout, chat, files, quiz, progress)lib/— Server/client utilities: auth, env, RAG, quiz, Supabase clientsstore/— Zustand stores (auth, chat, pdf, quiz, ui)db/migrations/— SQL migrations for Supabase schema and features
- Node.js 18+ (LTS recommended)
- npm (comes with Node) or yarn/pnpm
- A Supabase project (free tier is fine)
- API keys for Google Gemini and optionally YouTube Data API v3
# Clone the repository and enter the project
git clone https://github.com/<your-org>/<your-repo>.git
cd <your-repo>/bookly- Create a new project at
https://supabase.com. - In your project settings, locate:
Project URL(Supabase URL)anonpublic key (Client)service_rolekey (Server; keep private, server-only)
- Apply the SQL migrations from /testDB/dbSchema.sql using the Supabase SQL Editor.
Note: Some features (RAG, quizzes, recommendations) require the later migrations.
Create a .env.local file in bookly/ with:
# Google Gemini (required for chat and quizzes)
GEMINI_API=your_gemini_api_key
# YouTube Data API (optional; enables recommendations)
YT_API_KEY=your_youtube_api_key
# Server-side Supabase (service role used by API routes)
SUPABASE_URL=https://your-project-id.supabase.co
SUPABASE_ANON_API_KEY=your_anon_public_key
SUPABASE_SERVICE_KEY=your_service_role_key
# Public (browser) Supabase
NEXT_PUBLIC_SUPABASE_URL=https://your-project-id.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_public_keyEnvironment resolution:
- Server utilities use
SUPABASE_URL,SUPABASE_ANON_API_KEY,SUPABASE_SERVICE_KEY. - Browser client prefers
NEXT_PUBLIC_*and falls back to server vars in dev.
npm installnpm run devOpen http://localhost:3000.
- Sign in/up pages:
/signin,/signup. - Middleware (
middleware.ts) allows public paths and protects the rest by checking Supabase session cookies. - Server APIs use
@supabase/ssrto read/write session cookies and get the user.
If auth is not configured, protected routes will redirect to /signin.
-
Source selector: It has been implemented to allow choosing across all uploaded PDFs or a specific PDF, with file uploads supported. The upload flow and file listing are provided via
app/upload/page.tsx,app/files/page.tsx, and thecomponents/files/*andcomponents/shell/*panels. -
PDF viewer: It has been implemented to display the selected PDF alongside the chat. The right panel provides page navigation, search, and resizing controls (see
components/shell/pdf/*and the resizable layout incomponents/ui/resizable.tsx). -
Quiz Generator Engine (MCQ, SAQ, LAQ): It has been implemented to generate and render quizzes, capture answers, score submissions, store attempts, and provide explanations. Generation and evaluation routes exist under
app/api/quiz/*, with UI incomponents/quiz/*and progress storage inquiz_attempts/answerstables. -
Progress tracking: It has been implemented to persist strengths/weaknesses and surface a dashboard. APIs live under
app/api/progress/*, UI undercomponents/progress/*, and storage inuser_progressanduser_weaknessestables. -
Chat UI (ChatGPT-inspired): It has been implemented with a left drawer for chats, a main chat area, and an input box, supporting new chat creation and switching. The layout is responsive across devices (see
components/shell/*andcomponents/layout/MainLayout.tsx). -
RAG answers with citations: It has been implemented with PDF ingestion (chunk + embed), similarity search, and citation surfaces in responses. The pipeline lives in
lib/rag.tsand related API routes (app/api/pdf/*,app/api/chat), returning cited page numbers and quotes when available. -
YouTube Videos Recommender: It has been implemented to recommend educational videos relevant to context and detected weaknesses. Endpoints are under
app/api/youtube/*, with UI incomponents/youtube/*and persistence inyoutube_recommendations.
- Chat with Retrieval:
POST /api/chat— Session is validated, user provisioned, optional rate limiting applied. When apdfIdis provided and ready, the query is embedded, top chunks are retrieved, and a response is streamed from Gemini with citations; messages are persisted inmessages. - Messages History:
GET /api/messages?chatId=...— Chat ownership is enforced and ordered messages are returned. - PDFs: Uploading, parsing, embedding, and search are performed via
app/api/pdf/*, with status tracked inpdfsand chunk vectors inchunks. - Quizzes & Progress: Quiz generation/evaluation under
app/api/quiz/*; dashboard and history powered byapp/api/progress/*and visualized incomponents/progress/*. - YouTube Recommendations: Recommendation APIs live under
app/api/youtube/*and are driven by content/topics and weaknesses, gated byYT_API_KEY.
npm run dev— Start Next.js dev servernpm run build— Build for productionnpm run start— Start production servernpm run lint— Run ESLint
-
"Authentication required" on protected pages:
- Confirm
.env.localhas validNEXT_PUBLIC_SUPABASE_URLandNEXT_PUBLIC_SUPABASE_ANON_KEY. - Ensure your Supabase Auth providers are enabled and redirect URLs include
http://localhost:3000.
- Confirm
-
Chat returns 500 "GEMINI_API missing":
- Set
GEMINI_APIin.env.local.
- Set
-
Missing data or SQL errors:
- Verify all migrations in
db/migrations/were applied in order.
- Verify all migrations in
-
Windows or local TLS/cookie oddities:
- The middleware and server helpers will try to decode the Supabase access token from cookies as a fallback.
- Make sure third-party cookies are not blocked in the browser during local testing.
-
PDF viewer issues (canvas/pdfjs):
- The app stubs
canvasinnext.config.ts; ensure you’re not bundlingcanvason the client.
- The app stubs
- Never expose
SUPABASE_SERVICE_KEYto the browser or commit it to VCS. - Use separate environment files or secrets for production vs. development.
Proprietary. All rights reserved.
