Skip to content
suman6517Public

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

AI DOCUMENT INTELLIGENCE · RETRIEVAL-AUGMENTED GENERATION · SEMANTIC SEARCH

DocReader

Turn your documents into intelligent conversations

Upload a document. Ask a question. Get a grounded answer with sources, semantic search, and conversation memory.

Java 21 Spring Boot 4.1.1 Spring AI 2.0.1 React 19.2 Vite 8.2 Tailwind CSS 4.3 PostgreSQL 16 plus pgvector License to be confirmed


Problem — useful information is trapped inside PDFs, reports, notes, and documentation. Keyword search misses phrasing you did not think of, and reading everything manually is slow.

Solution — DocReader splits documents into chunks, converts them into embeddings, stores them in PostgreSQL with pgvector, and lets an AI model answer questions from the most relevant chunks, with citations you can inspect.

Contents

Start here

How it works

Setup and configuration

Reference

Overview

DocReader is a full-stack retrieval-augmented generation (RAG) application that turns uploaded documents into a searchable, conversational knowledge base.

Built from

  • a React 19 + TypeScript + Vite 8 single-page dashboard with a dark, responsive interface;
  • a Spring Boot 4.1.1 REST backend built on Spring AI 2.0.1;
  • PostgreSQL 16 + pgvector for relational data and vector similarity search;
  • OpenAI models for chat (gpt-4o-mini by default) and embeddings (text-embedding-3-small, 1536 dimensions).

Built for

  • students and researchers working through PDF notes and papers;
  • developers exploring large documentation sets;
  • knowledge workers who need answers from reports, contracts, and internal files.

What you can do

  1. Upload documents once and index them automatically.
  2. Ask natural-language questions and get answers grounded in those documents.
  3. Search by meaning instead of exact keywords.
  4. Inspect the exact chunks and similarity scores behind each result.
  5. Keep separate, user-scoped workspaces with JWT-based authentication.

Why the pieces matter together

  • Chunking + embeddings make documents searchable by meaning.
  • RAG makes the model answer from your content instead of only its training data.
  • Citations + chunk inspection make each answer auditable.

Application preview

Real screenshots of the current UI. Image files live in frontend/screenshots/.

DocReader dashboard with document sidebar and AI-generated summary
Document management + AI summary
AI chat explaining an SQL query with syntax-highlighted code blocks
AI chat + code explanation
Drag and drop document upload dialog
Drag-and-drop upload
Vector chunk explorer showing chunks and similarity scores
Vector chunk explorer
Semantic search interface with search categories
Semantic search
Semantic search filters for top results and minimum similarity
Search filters and similarity controls

Key features

Document intelligence

Feature What it does Why it matters
Multi-format ingestion PDFs use Spring AI's PagePdfDocumentReader; other formats go through TikaDocumentReader. The upload dialog accepts PDF, DOCX, TXT, MD, and CSV. Multiple files are supported. One pipeline for notes, reports, specs, and papers.
Token-aware chunking TokenTextSplitter uses a 700-token chunk size, 350-character minimum chunk size, 5-character minimum to embed, and a 10,000-chunk cap. Large documents become retrievable pieces without overwhelming the model.
Metadata enrichment Every chunk carries documentId, userId, fileName, contentType, chunkIndex, and page number when available. Null characters are stripped before embedding. Enables filtering, citation display, and clean vector content.
Vector similarity search Spring AI's pgvector store uses a 1536-dimension vector column, HNSW index, and cosine distance. Finds passages by meaning, not just exact words.
Grounded AI chat Retrieved chunks are injected into the system prompt as doc_context; the chat model answers with Markdown. Non-streaming and SSE streaming modes are both implemented. Answers are based on your documents, and streaming feels responsive.
Source citations Each answer returns the matched chunks with file name, page, snippet, similarity score, and metadata. You can verify where an answer came from.
Semantic search Natural-language queries with adjustable topK (1–25) and minimum similarity (0–100%). Result cards show scores, snippets, and metadata pills. Dial precision vs. recall for each search.
Vector chunk explorer Loads up to 50 chunks for the selected document (or all chunks), supports a free-text filter, expandable metadata, and copy-to-clipboard. See exactly what the AI can see.

Workspace and interface

Feature What it does Why it matters
User authentication /api/v1/auth/signup and /login issue a JWT; the frontend stores it with Zustand and sends Authorization: Bearer <token> on every request. A 401 response logs the user out. Each person gets a private workspace.
Document-focused conversations Selecting a document in the sidebar scopes both search and chat to that document. Clearing the selection searches all of the user's documents. Ask about one file or the whole library.
Chat history UI The sidebar lists, groups, searches, renames, and deletes conversations; messages and preferences live in browser localStorage. The backend separately persists chat memory in JPA tables. Pick up where you left off.
Rich response rendering react-markdown + GFM, Prism syntax highlighting for JS/TS/JSX/TSX/Java/Python/JSON/SQL/Bash/YAML/CSS/Markdown, copy buttons, and tables. Technical answers remain readable.
Prompt templates Built-in categories for summarization, legal/compliance, and analysis (e.g. executive summary, key clauses, data points, timeline). Useful starting points for new users.
Streaming controls Toggle streaming on/off, watch token-by-token output, and stop generation mid-stream. Faster feedback and control over long answers.
Document lifecycle Statuses UPLOADING → PROCESSING → INDEXED (or FAILED), error messages, metadata display, and deletion that also purges matching vectors. You always know what happened to a file.
Polished dark UI Tailwind CSS 4, Framer Motion animations, Lucide icons, toast notifications, skeletons, an error boundary, and responsive layouts with a collapsible sidebar. A dashboard that feels finished.
API docs Springdoc OpenAPI exposes Swagger UI at /swagger-ui.html and JSON at /v3/api-docs. Easy API exploration.

Technology stack

Versions below are taken from pom.xml, package.json, package-lock.json, and the application configuration.

Frontend stack

Location: frontend/docreader-frontend/

Technology Version Role
React 19.2.8 UI component model
TypeScript 6.0.x (~6.0.2; lockfile 6.0.3) Static typing for API DTOs and state
Vite 8.2.2 (lockfile) Dev server on port 3000, /api proxy to port 8050
Tailwind CSS 4.3.3 (@tailwindcss/vite) Utility-first dark theme
React Router 7.18.2 Public /login, /register; protected / route
Zustand 5.0.15 Auth, document, and conversation state; persisted auth
Axios 1.19.0 REST client with JWT and 401 interceptors
react-dropzone 20.1.1 Multi-file drag-and-drop upload
react-markdown + remark-gfm 10.1.0 / 4.0.1 Markdown and GFM rendering
PrismJS 1.30.0 Syntax-highlighted code blocks
Framer Motion 13.1.0 List and dialog animations
Lucide React 1.33.0 Icons
react-hot-toast 2.6.0 Notifications
clsx 2.1.1 Conditional class names
Oxlint 1.75.0 Linting

Backend stack

Technology Version Role
Java 21 target (<java.version>21</java.version>) Runtime/language level
Spring Boot 4.1.1 Application framework
Spring AI 2.0.1 (BOM) Chat client, document readers, splitter, vector store abstraction
Spring Data JPA / Hibernate from Boot 4.1.1 (Hibernate 7.4.5 at runtime) Relational persistence
Spring Security from Boot 4.1.1 Stateless security chain, roles, BCrypt
JJWT 0.13.0 HMAC JWT creation and validation
ModelMapper 3.2.8 Entity → DTO mapping
PostgreSQL driver from Boot 4.1.1 JDBC connectivity
springdoc-openapi 3.1.1 Swagger UI / OpenAPI
Lombok from Boot 4.1.1 Boilerplate reduction
Maven Wrapper 3.10.0 distribution Reproducible builds

AI, database, security, and build

Layer Technology Configuration
AI OpenAI chat model gpt-4o-mini, temperature 0.2
AI OpenAI embedding model text-embedding-3-small, 1536 dimensions
AI Spring AI advisors SimpleLoggerAdvisor, MessageChatMemoryAdvisor
Database PostgreSQL pgvector/pgvector:pg16 in Docker Compose, database docread
Database pgvector vector_store table, vector(1536), HNSW index, cosine distance
Database extensions vector, uuid-ossp, hstore init.sql creates vector and uuid-ossp; Spring AI creates hstore when initializing its schema
Security JWT (HMAC via JJWT) + BCrypt 1-hour token expiry (jwt.expiration: 3600000)
Build tools Maven Wrapper, npm, Docker Compose See Development commands

Key terms

  • LLM (large language model): the text generator. Here, gpt-4o-mini writes the answer in natural language and Markdown.
  • Embedding model: turns text into a long list of numbers (a vector) so that semantically similar passages land near each other. Here, text-embedding-3-small.
  • Vector database: a store that can quickly find the nearest vectors to a query vector. Here, PostgreSQL extended with pgvector — not a separate service.
  • RAG (retrieval-augmented generation): retrieve relevant chunks first, then give them to the LLM as context so the answer is grounded in your documents. It reduces guessing but does not eliminate it.

System architecture

flowchart LR
  Browser["React 19 SPA<br/>localhost:3000"]
  Proxy["Vite dev proxy<br/>/api → localhost:8050"]
  Security["Spring Security<br/>JWT filter · BCrypt · roles"]
  API["REST controllers<br/>/api/v1"]
  DocSvc["Document pipeline<br/>parse → split → enrich"]
  RagSvc["RAG service<br/>retrieve → prompt → answer"]
  Memory["JPA chat memory<br/>last 10 messages"]
  Jpa["Spring Data JPA<br/>Hibernate"]
  Vector["Spring AI VectorStore<br/>pgvector"]
  ChatModel["OpenAI Chat<br/>gpt-4o-mini"]
  EmbedModel["OpenAI Embeddings<br/>text-embedding-3-small"]
  PG[("PostgreSQL 16<br/>database: docread")]

  Browser --> Proxy --> Security --> API
  API --> DocSvc
  API --> RagSvc
  API --> Jpa
  DocSvc --> EmbedModel
  DocSvc --> Vector
  RagSvc --> Vector
  RagSvc --> ChatModel
  RagSvc --> Memory
  Memory --> Jpa
  Vector --> PG
  Jpa --> PG
Loading
  • The browser never calls OpenAI directly — all model calls happen in the backend.
  • The same PostgreSQL database holds relational tables and the vector table.
  • Conversation messages are persisted through Spring AI's ChatMemory contract, implemented by JpaChatMemory.

RAG pipeline

flowchart TD
  subgraph ING["1 · Document ingestion (synchronous on upload)"]
    U["User uploads PDF / DOCX / TXT / MD / CSV"] --> V["Save document_metadata<br/>status: UPLOADING"]
    V --> P["Parse<br/>PagePdfDocumentReader or TikaDocumentReader"]
    P --> S["TokenTextSplitter<br/>700 tokens per chunk"]
    S --> E["Attach userId, documentId, fileName,<br/>chunkIndex, pageNumber; strip null chars"]
    E --> EM["OpenAI embeddings"]
    EM --> VS[("vector_store<br/>HNSW + cosine")]
    VS --> ST["Status: INDEXED<br/>totalChunks saved"]
  end

  subgraph ASK["2 · Question answering"]
    Q["Question + optional documentId"] --> F["Filter by userId<br/>and optionally documentId"]
    F --> SIM["Similarity search<br/>topK + min similarity"]
    SIM --> C["Build context:<br/>source file, page, chunk text"]
    C --> CC["ChatClient: system doc_context + question"]
    CC --> LLM["OpenAI chat model"]
    LLM --> A["Markdown answer + citation list"]
    A --> H[("JPA chat memory +<br/>browser localStorage")]
  end
Loading

During upload, the file is parsed, split into token-sized pieces, labelled with ownership information, embedded, and inserted into pgvector.

During a question, DocReader searches only vectors belonging to the current user (and optionally one document), injects the best matches into the system prompt, asks the chat model to answer, and returns both the answer and the matched sources. The last ten messages of a conversation are stored in PostgreSQL and reused as chat memory.

Project structure

DocReader/
├── pom.xml                         # Spring Boot 4.1.1 / Spring AI 2.0.1 build
├── mvnw, mvnw.cmd                  # Maven Wrapper 3.10.0
├── docker-compose.yml              # pgvector PostgreSQL 16 on host port 5434
├── init.sql                        # CREATE EXTENSION vector / uuid-ossp
├── .env.example                    # Safe configuration template
├── src/main/java/com/docReader/backend/DocReader/
│   ├── DocReaderApplication.java
│   ├── config/                     # AppProperties, CorsConfig, ProjectConfig (beans, OpenAPI, system prompt)
│   ├── Security/                   # JWT filter, UserDetailsService, SecurityConfig
│   ├── controller/                 # AuthController, DocumentController, ChatController
│   ├── service/
│   │   ├── DocumentMataDataService.java
│   │   └── Implimentation/         # Parser, ingestion, RAG, JWT, JPA chat memory, user service
│   ├── repository/                 # JPA repositories incl. native "last N messages" query
│   ├── entity/                     # User, DocumentMataData, Conversation, ChatMessages, enums
│   ├── dto/                        # Request/response records and classes
│   └── exception/                  # GlobalExceptionHandler and custom exceptions
├── src/main/resources/
│   ├── application.yaml            # Active profile: dev; server port 8050
│   └── application-dev.yml         # DB, OpenAI, pgvector, RAG, CORS, JWT settings
├── src/test/java/...               # Spring Boot context-load test
└── frontend/
    ├── screenshots/                # README screenshots
    └── docreader-frontend/
        ├── package.json, package-lock.json
        ├── vite.config.ts          # Port 3000 and /api → :8050 proxy
        ├── src/
        │   ├── App.tsx             # Routes, dashboard shell, toasts
        │   ├── components/         # Navbar, Sidebar, ChatsPanel, ChatView, SearchView, ChunksView, UploadDialog, guards
        │   ├── pages/              # Login, Register
        │   ├── services/           # Axios API clients and localStorage conversation store
        │   ├── store/              # Zustand auth, document, and conversation stores
        │   ├── types/              # TypeScript mirrors of backend DTOs
        │   └── index.css           # Tailwind theme, animations, scrollbars
        └── public/                 # Favicon and icons

The Java spelling Implimentation and the class name DocumentMataData are intentional — they match the actual source.

Prerequisites

Backend prerequisites

Requirement Version / detail Official guide
JDK 21 or newer (project targets Java 21; verified with JDK 24) OpenJDK
Maven Not required — use the included ./mvnw wrapper (Maven 3.10.0) Maven Wrapper

Frontend prerequisites

Requirement Version / detail Official guide
Node.js ^20.19.0 or >=22.12.0 (required by Vite 8) nodejs.org
npm Ships with Node.js (verified with npm 11.5.1) npm docs

Services and tools

Requirement Version / detail Official guide
PostgreSQL 16 with pgvector. Easiest: Docker Compose (pgvector/pgvector:pg16) pgvector
Docker + Compose Optional, but the simplest way to start the database Docker Desktop
OpenAI API key Required for real embeddings and answers OpenAI API keys
Git Any recent version git-scm.com

Complete installation guide

Run the backend and frontend in two separate terminals. Start the database first.

Step 1 — Clone the repository

git clone https://github.com/suman6517/docreader.git
cd docreader

Step 2 — Configure PostgreSQL

Option A — Docker Compose (recommended):

docker compose up -d
docker compose ps

This starts doc-reader-postgres using pgvector/pgvector:pg16.

  • Database: docread
  • Host port: 5434
  • First-run script: init.sql enables vector and uuid-ossp
  • Data volume: docreaddata

Option B — an existing PostgreSQL server:

CREATE DATABASE docread;
\c docread
CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

Hibernate (ddl-auto: update) creates users, document_metadata, conversations, and chatmessages. Spring AI creates vector_store and the hstore extension because initialize-schema: true is configured. No separate migration tool is used.

Step 3 — Configure environment variables

Copy the template and export your own values. Spring Boot reads these directly from the environment; it does not automatically load a .env file.

cp .env.example .env
# Edit .env with your own values, then for example:
set -a && source .env && set +a

Generate a strong JWT secret:

openssl rand -base64 48

Minimum required values:

export OPENAI_API_KEY="your-openai-api-key-here"
export JWT_SECRET="replace-with-a-32-plus-character-random-secret"
  • If you kept the bundled Compose defaults, DB_* overrides are optional.
  • If you changed the database name, user, password, host, or port, export DB_HOST, DB_PORT, DB_NAME, DB_USER, and DB_PASSWORD to match.
  • Set OPENAI_CHAT_MODEL / OPENAI_EMBEDDING_MODEL only to override the defaults.

application-dev.yml contains development fallback values (including a demo-key placeholder and a hardcoded JWT secret). Always override both before exposing the service to anyone else.

Step 4 — Start the backend

From the repository root:

./mvnw spring-boot:run
  • API base URL: http://localhost:8050/api/v1
  • Swagger UI: http://localhost:8050/swagger-ui.html
  • OpenAPI JSON: http://localhost:8050/v3/api-docs

The active profile is dev (set in application.yaml). Wait for Started DocReaderApplication and a successful HikariCP connection to jdbc:postgresql://localhost:5434/docread in the log.

Step 5 — Start the frontend

In a second terminal, from the repository root:

cd frontend/docreader-frontend
npm install
npm run dev
  • Frontend: http://localhost:3000
  • The Vite proxy forwards /api/v1/* to http://localhost:8050, so no frontend environment file is needed.

Step 6 — Open and use the application

  1. Open http://localhost:3000. Protected routes redirect to /login when no JWT is present.
  2. Choose Create a new account, enter a username, email, and a password of at least 6 characters. Registration automatically signs you in.
  3. Click Upload Documents, drag in a PDF/DOCX/TXT/MD/CSV file (max 25 MB per file), and click Upload.
  4. Wait for the document badge to become Indexed; the sidebar shows page and chunk counts.
  5. Click a document to focus the conversation on it, or clear the filter to use all documents.
  6. Type a question in the chat and press Enter. Streaming is on by default; toggle to Normal for a single JSON response, or use the stop button to cancel a stream.
  7. Open Search for semantic retrieval, adjust Filters (top results / minimum similarity), and open Chunks to inspect the underlying vectors.

Step 7 — Verify everything works

# 1. Backend is up (expect HTTP 200)
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8050/v3/api-docs

# 2. Authentication issues a JWT (replace with the credentials you created in Step 6)
TOKEN=$(curl -s -X POST http://localhost:8050/api/v1/auth/login \
  -H 'Content-Type: application/json' \
  -d '{"username":"demo","password":"your-password"}' \
  | python3 -c 'import sys, json; print(json.load(sys.stdin)["accessToken"])')
echo "${TOKEN:0:20}..."

# 3. Database tables and stored vectors exist
docker exec doc-reader-postgres psql -U root -d docread -c \
  'SELECT (SELECT count(*) FROM users) AS users, (SELECT count(*) FROM document_metadata) AS documents, (SELECT count(*) FROM vector_store) AS vectors;'

# 4. Semantic search returns matches (use a documentId from GET /api/v1/user)
curl -s -X POST http://localhost:8050/api/v1/search/similarity \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"query":"database normalization","topK":5,"similaritySearch":0.0}'

A healthy setup shows:

  • backend logs with Hibernate and pgvector initialization and no errors;
  • non-zero counts after an upload in the database query;
  • matches in the search response;
  • a Markdown answer with citations from the chat endpoint.

Embeddings and chat calls require a valid OPENAI_API_KEY. Without it, uploads fail with FAILED status and an error message in the sidebar.

Configuration reference

Environment variables

Variable Purpose Required Safe example
OPENAI_API_KEY Authenticates Spring AI calls to OpenAI Yes for real use your-openai-api-key-here
OPENAI_CHAT_MODEL Overrides chat model No gpt-4o-mini
OPENAI_EMBEDDING_MODEL Overrides embedding model No text-embedding-3-small
DB_HOST PostgreSQL host No (default localhost) localhost
DB_PORT PostgreSQL host port No (default 5434) 5434
DB_NAME Database name No (default docread) docread
DB_USER Database user No (default root) your-db-user
DB_PASSWORD Database password No (default matches Compose) your-db-password
JWT_SECRET HMAC signing key for JWTs Yes in any shared environment long random string from openssl rand -base64 48

Spring properties

Defined in src/main/resources/application-dev.yml unless noted.

Property Purpose Default
server.port Backend HTTP port (in application.yaml) 8050
spring.datasource.url JDBC URL composed from DB_* jdbc:postgresql://localhost:5434/docread
spring.jpa.hibernate.ddl-auto Schema management update
spring.jpa.show-sql Log SQL statements true
spring.ai.openai.chat.temperature Answer randomness 0.2
spring.ai.vectorstore.pgvector.index-type ANN index HNSW
spring.ai.vectorstore.pgvector.distance-type Similarity metric COSINE_DISTANCE
spring.ai.vectorstore.pgvector.dimensions Embedding dimensions 1536
spring.ai.vectorstore.pgvector.table-name Vector table vector_store
spring.ai.vectorstore.pgvector.initialize-schema Auto-create vector schema true
spring.servlet.multipart.max-file-size Per-file upload limit 25MB
spring.servlet.multipart.max-request-size Whole-request limit 50MB
app.rag.chunk-size Splitter chunk size in tokens 700
app.rag.top-k Default retrieval count 5
app.rag.similarity-threshold Default minimum similarity 0.0
app.cors.allowed-origins Allowed origin patterns for /api/** *
app.cors.allowed-methods Allowed HTTP methods GET,POST,PUT,DELETE,OPTIONS
jwt.expiration Token lifetime in milliseconds 3600000 (1 hour)

Frontend configuration

Setting Location Value
Dev server port vite.config.ts 3000
API proxy target vite.config.ts http://localhost:8050
API base path src/services/api.ts /api/v1

API documentation

All application endpoints are under /api/v1. Except authentication, they require Authorization: Bearer <JWT> and the USER role. Swagger UI is available at http://localhost:8050/swagger-ui.html.

Authentication

Method Endpoint Purpose Authentication
POST /api/v1/auth/signup Register a user (username, email, password); returns UserDto Public
POST /api/v1/auth/login Authenticate; returns { accessToken, userDto } Public

Documents

Method Endpoint Purpose Authentication
POST /api/v1/upload Upload and index one file (multipart/form-data, field file) USER
POST /api/v1/upload-multiple Upload and index several files (field files) USER
GET /api/v1/user List the logged-in user's documents USER
GET /api/v1 List all documents; guarded by @PreAuthorize("hasRole('ADMIN')") ADMIN
GET /api/v1/{id} Get metadata for a document UUID USER
DELETE /api/v1/{id} Delete metadata and purge vectors with matching documentId USER

Chat and conversations

Method Endpoint Purpose Authentication
POST /api/v1/chat Answer a question; returns answer, citations, conversation ID, response time USER
POST /api/v1/stream Stream answer tokens via SSE USER

There are no REST endpoints for listing, renaming, or deleting conversations; the chat sidebar manages its history in localStorage.

Semantic search and vector chunks

Method Endpoint Purpose Authentication
POST /api/v1/search/similarity Search stored vectors; also used by the Chunks view USER

There is no separate chunk endpoint — both Search and Chunks call the same similarity API with different parameters.

Other available APIs

Method Endpoint Purpose Authentication
GET /swagger-ui.html Interactive API documentation Public
GET /v3/api-docs OpenAPI JSON Public

Request examples

Register and log in:

curl -s -X POST http://localhost:8050/api/v1/auth/signup \
  -H 'Content-Type: application/json' \
  -d '{"username":"demo","email":"demo@example.com","password":"change-me"}'

TOKEN=$(curl -s -X POST http://localhost:8050/api/v1/auth/login \
  -H 'Content-Type: application/json' \
  -d '{"username":"demo","password":"change-me"}' \
  | python3 -c 'import sys, json; print(json.load(sys.stdin)["accessToken"])')

Upload a document and list your documents:

curl -s -X POST http://localhost:8050/api/v1/upload \
  -H "Authorization: Bearer $TOKEN" \
  -F 'file=@./notes.pdf'

curl -s http://localhost:8050/api/v1/user -H "Authorization: Bearer $TOKEN"

Ask a question (omit documentId to search all of your documents):

curl -s -X POST http://localhost:8050/api/v1/chat \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{
        "question": "Summarize the key findings with page references.",
        "documentId": "PASTE_DOCUMENT_UUID_HERE",
        "topK": 5,
        "minSimilarity": 0.3,
        "conversationId": "PASTE_CONVERSATION_UUID_HERE"
      }'

Stream a response and run a semantic search:

curl -N -X POST http://localhost:8050/api/v1/stream \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"question":"What does the document say about indexing?","topK":5}'

curl -s -X POST http://localhost:8050/api/v1/search/similarity \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"query":"database normalization","topK":10,"similaritySearch":0.3}'

Database design

One PostgreSQL database serves two purposes:

  • Relational tables store users, document status/metadata, and conversations — structured data with foreign keys.
  • pgvector adds a vector column type and ANN index, allowing SQL to answer “which chunks are closest in meaning to this query?” without a separate vector service.
  • Embeddings are stored in the vector_store.embedding column; the original text lives in content and ownership/source details in metadata JSON.
erDiagram
  USERS ||--o{ DOCUMENT_METADATA : owns
  USERS ||--o{ CONVERSATIONS : owns
  CONVERSATIONS ||--o{ CHATMESSAGES : contains
  USERS }o..o{ VECTOR_STORE : "logical userId filter"
  DOCUMENT_METADATA }o..o{ VECTOR_STORE : "logical documentId filter"

  USERS {
    bigint id PK
    varchar username UK
    varchar email UK
    varchar password
    varchar role
  }
  DOCUMENT_METADATA {
    uuid id PK
    bigint user_id FK
    varchar file_name
    varchar content_type
    bigint file_size
    integer total_pages
    integer total_chunks
    varchar status
    varchar error_message
    timestamp created_at
    timestamp updated_at
  }
  CONVERSATIONS {
    varchar id PK
    bigint user_id FK
    varchar title
    timestamp created_at
    timestamp updated_at
  }
  CHATMESSAGES {
    bigint id PK
    varchar conversation_id FK
    varchar message_type
    text content
    timestamp created_at
  }
  VECTOR_STORE {
    uuid id PK
    text content
    json metadata
    vector embedding
  }
Loading

Tables

Table Notes
users Unique username and email; BCrypt password hash; role is USER or ADMIN.
document_metadata UUID primary key, owning user_id, file metadata, status enum, page/chunk counts, error message, timestamps.
conversations String (UUID) primary key generated by the client, owning user_id, title, timestamps.
chatmessages Identity ID, "conversation-id" foreign key, message_type (USER/ASSISTANT/SYSTEM), text content, created_at. The repository's native query fetches the last 10 messages in descending order and reverses them in Java.
vector_store Created by Spring AI: id uuid, content text, metadata json, embedding vector(1536); primary key and an HNSW vector_cosine_ops index named spring_ai_vector_index.

How search works

  • Chunk metadata keys observed in vector_store.metadata include documentId, userId, fileName, contentType, chunkIndex, pageNumber, plus reader-provided snake_case variants such as page_number and file_name.
  • The link from a vector row to a document/user is logical metadata filtering, not a SQL foreign key.
  • Semantic search builds a filter expression on userId (always) and documentId (when selected), then runs a cosine similarity query with the requested topK and optional similarity threshold.
  • The metadata distance returned by pgvector is converted to a display score as 1 - distance.

Schema creation

  • Hibernate ddl-auto: update creates JPA tables.
  • init.sql enables vector and uuid-ossp.
  • Spring AI's initialize-schema: true creates vector_store.
  • There are no Flyway or Liquibase migrations.

How to use DocReader

  1. Register or sign in. New accounts are created with the USER role and signed in automatically.
  2. Upload a document. Use the Upload button in the navbar or sidebar. PDF, DOCX, TXT, MD, and CSV are shown as accepted; several files can be queued at once.
  3. Wait for processing. Watch the status pill change from Uploading → Processing → Indexed. Expand a document card to see chunk count, page count, upload date, and any error message.
  4. Select a document. Click it in the sidebar to show the Focused badge in chat. Click again or use Clear document filter to return to all documents.
  5. Start a conversation. Use New chat in the sidebar or chat header. Conversations are grouped by date and can be searched, renamed, or removed in the UI.
  6. Ask questions. Useful first prompts:
    • “Give me an executive summary of the key points.”
    • “What are the most important clauses and provisions?”
    • “List all action items, tasks, and next steps.”
    • “Explain the difference between X and Y using examples from this document.”
    • “Create a chronological timeline of all dates mentioned.”
  7. Inspect sources. Expand N sources under an answer to see each matching file, page, similarity bar, and snippet. Copy any code block with its Copy button.
  8. Explore semantic search. Try a concept such as “liability cap” or “database isolation levels”, open Filters, and change top results or minimum similarity.
  9. Inspect vector chunks. Open the Chunks tab, optionally enter a vector query, click Load, then filter by text and expand a chunk to view its full metadata.
  10. Review earlier chats. Switch the sidebar to Chats, pick a conversation, and continue asking follow-up questions.

Example use cases

  • Studying from PDF notes: ask for summaries, definitions, timelines, and interview-style questions from lecture sheets.
  • Technical interviews: query notes for concepts such as ACID properties, normalization, indexing, or isolation levels and get explanations backed by your own material.
  • Understanding SQL and code: the chat renders fenced SQL/Java/Python with syntax highlighting — useful for asking “explain this query step by step”.
  • Large documentation sets: search across all indexed files by meaning instead of remembering an exact heading.
  • Contract and policy review: look for clauses, obligations, risks, and governing-law language, then inspect the matched chunk.
  • Reporting: extract data points, statistics, action items, and deadlines into readable Markdown.
  • Follow-up conversations: ask a broad question, then narrow it — chat memory keeps the last ten messages in context.

Security

Implemented in the code:

  • Stateless JWT authentication: JJWT signs tokens with HMAC; JwtAuthenticationFilter extracts the Bearer token, validates username and expiry, and sets the security context. Sessions are disabled and CSRF is off because the API is token-based.
  • Password hashing: BCryptPasswordEncoder hashes passwords before saving users; raw passwords are never stored.
  • Role-based access: /api/v1/auth/**, Swagger, and OpenAPI are public; /api/v1/** requires ROLE_USER; /api/v1/admin/** requires ROLE_ADMIN; the all-documents method also has @PreAuthorize.
  • User-scoped retrieval: vector similarity searches always filter on the authenticated user's userId, and "my documents" uses findByUserOrderByCreatedAtDesc.
  • Frontend protection: ProtectedRoute redirects unauthenticated users; an Axios interceptor attaches the token and clears auth state on 401; logout clears local chat data.
  • Configurable CORS: /api/** mappings are built from app.cors.* properties.
  • Consistent errors: GlobalExceptionHandler maps validation, not-found, processing, upload-size, and unexpected errors to an ApiResponse envelope.

This is the implemented application security setup, not a production hardening audit.

Troubleshooting

Startup and configuration

Symptom Likely cause Fix
Connection refused to localhost:5434 Database container not running docker compose up -d; check docker compose ps and the healthcheck.
relation "vector_store" does not exist or type "vector" does not exist pgvector extension missing Run init.sql in your database or use the bundled Compose image; confirm SELECT extname FROM pg_extension; lists vector.
extension "hstore" is not available Restricted PostgreSQL installation Use pgvector/pgvector:pg16, or install postgresql-contrib and create the extension with a privileged role.
Backend port 8050 already in use Another process holds the port Stop that process or override SERVER_PORT and update vite.config.ts proxy target.
CORS error in the browser Origin not allowed or credentials mismatch Set APP_CORS_ALLOWED_ORIGINS (e.g. http://localhost:3000) and restart; the dev proxy normally avoids this issue.
Frontend shows an empty document list Wrong API target or different user account Confirm the Vite proxy target http://localhost:8050, then check GET /api/v1/user with your token.
npm install / Vite fails on Node version Node older than 20.19 or 22.12 Upgrade Node to a supported LTS release and reinstall dependencies.
Maven build fails Wrong JDK or corrupt local cache Use JDK 21+ and try ./mvnw clean compile -U.

Upload, search, and chat

Symptom Likely cause Fix
Uploads become FAILED immediately Invalid or missing OPENAI_API_KEY, wrong embedding model dimensions, or unsupported content Export a valid key; keep the default text-embedding-3-small with 1536 dimensions; expand the document card to read errorMessage.
401 Unauthorized on all API calls Missing/expired JWT, or token not sent Sign in again; confirm the browser sends Authorization: Bearer ...; tokens expire after 1 hour.
JWT signature errors after restart Secret changed between runs Use the same strong JWT_SECRET consistently; restart the backend after changing it.
413 or upload rejected File over 25 MB or request over 50 MB Reduce file size; limits are in application-dev.yml.
Chat returns no citations No matching chunks, or a very high similarity threshold Lower Min Similarity, confirm the document is INDEXED, and check vector_store row count.
Conversation disappears after refresh Browser storage cleared Chat history UI is localStorage-based; logging out intentionally clears docreader:* keys.

Development commands

Task Command Location
Start database docker compose up -d Repository root
Stop database docker compose down Repository root
Start backend ./mvnw spring-boot:run Repository root
Build backend ./mvnw clean package Repository root
Run backend tests ./mvnw test Repository root (database must be reachable)
Start frontend npm run dev frontend/docreader-frontend
Build frontend npm run build frontend/docreader-frontend (runs tsc -b && vite build)
Lint frontend npm run lint frontend/docreader-frontend (Oxlint; currently reports warnings, no errors)
Preview production build npm run preview frontend/docreader-frontend

Verified in this repository: ./mvnw -DskipTests compile, ./mvnw test, npm run lint, and npm run build all complete successfully (with two non-blocking lint warnings and a Vite bundle-size advisory).

Credits and licensing

  • Project metadata: the OpenAPI configuration in ProjectConfig.java names Substring Technologies and sumanbaral55@gmail.com as the API contact. This attribution is preserved from the source.
  • Development history: the repository's commit history records that the frontend was vibe-coded with OpenCode and Claude Code; backend work includes CORS, authentication, document APIs, and JPA chat memory commits.
  • Third-party projects: Spring Boot, Spring AI, Spring Security, PostgreSQL, pgvector, OpenAI, React, Vite, Tailwind CSS, Zustand, and the other libraries listed above remain under their respective licenses. No third-party license has been bundled or replaced here.
  • License: no LICENSE file, copyright notice, or license field is present in pom.xml or the repository. The license is therefore unknown and must be clarified before public distribution or recruitment use. Do not assume this code is MIT-licensed.

DocReader — your documents, searchable by meaning and explainable by source.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages