Skip to content

About

AI-powered library management system with separate librarian and member portals — FastAPI backend, Vue 3 frontend, AI book recommendations (Sentence Transformers), and a Gemini-powered library assistant chatbot.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

6 Commits

Folders and files

Repository files navigation

📚 LibStack

Intelligent Library Management System

A full-stack, AI-powered community library platform with separate Librarian and Member portals.

FastAPI Vue 3 Vite Python Redis Celery

Sentence Transformers Google Gemini


📖 Table of Contents


🌟 Overview

LibStack is a modern, full-stack library management system designed for community and institutional libraries. It provides separate, specialized workflows for Librarians (Admins) and Members (Users), featuring real-time catalog management, automated loan tracking, intelligent fine calculations, AI-powered book recommendations, automated email notifications, and an integrated agentic AI library assistant.

The application is fully containerized with Docker for one-command deployment.


🚀 Key Features

👨‍💼 Librarian (Admin) Portal

Feature Description
Dashboard Analytics Real-time metrics for total books, availability, active loans, overdue items, member count, pending renewals, and fine collections
Catalog Management Add, edit, soft-delete, and search books with unique codes, shelf numbers, sections, and copy tracking
Book Issuance Issue books to members with automatic due date calculation
Return Processing Process returns with automatic fine computation for overdue books
Renewal Management Review, approve, or reject member renewal requests with optional custom due dates
Member Directory Manage registered members, view borrowing statuses, and soft-delete accounts
Automated Reminders Trigger due-date and overdue email notifications to members
Activity History Comprehensive, timestamped audit logs of all library transactions

👤 Member (User) Portal

Feature Description
Catalog Discovery Browse and search book availability by title, author, section, shelf, or book code
Active Borrowings View current loans, due dates, and overdue status at a glance
Borrow History Complete history of all past borrowings with fine details
Book Renewals Request loan extensions directly from the dashboard
🤖 AI Recommendations Personalized book suggestions powered by Sentence Transformer embeddings and cosine similarity
🤖 AI Library Assistant Conversational chat assistant (Google Gemini) that can search the catalog and answer library queries
Notifications Alerts for upcoming due dates, overdue reminders, and renewal status updates
Profile Management Update personal information and change password

🛠️ Technology Stack

Layer Technologies
Frontend Vue 3 (Composition API, <script setup>), Vite 8, Pinia 3, Vue Router 4, Vanilla CSS
Backend Python 3.11, FastAPI, Uvicorn, SQLAlchemy 2.0, Pydantic v2
AI / ML Sentence-Transformers (all-MiniLM-L6-v2), Scikit-Learn (Cosine Similarity), Google Gemini API
Database SQLite (default) with PostgreSQL support via psycopg2
Caching Redis (with automatic FakeRedis fallback for local development)
Task Queue Celery with Redis broker and Celery Beat for scheduled tasks
Email SMTP (Gmail) for automated notifications and reminders
Security Bcrypt password hashing, HttpOnly session cookies, CSRF tokens, OWASP headers, Rate limiting (SlowAPI)
DevOps Docker, Docker Compose

🏗️ Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        Docker Compose                           │
│                                                                 │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────────┐   │
│  │   Frontend    │    │   Backend    │    │      Redis       │   │
│  │  (Vue 3 +    │───▶│  (FastAPI +  │───▶│   (Cache +       │   │
│  │   Vite)      │    │  Uvicorn)    │    │    Message       │   │
│  │  Port 5173   │    │  Port 8000   │    │    Broker)       │   │
│  └──────────────┘    └──────┬───────┘    │   Port 6379      │   │
│                             │            └────────┬─────────┘   │
│                             │                     │             │
│                      ┌──────▼───────┐    ┌────────▼─────────┐   │
│                      │   SQLite DB  │    │  Celery Worker   │   │
│                      │  (libstack   │    │  + Celery Beat   │   │
│                      │     .db)     │    │  (Background     │   │
│                      └──────────────┘    │   Tasks)         │   │
│                                          └──────────────────┘   │
└─────────────────────────────────────────────────────────────────┘

⚡ Getting Started

Prerequisites

Choose one of the two setup methods below:

Method Requirements
Docker (Recommended) Docker Desktop with Docker Compose
Manual Python 3.10+, Node.js 18+, npm, Redis (optional)

🐳 Docker Setup (Recommended)

This is the easiest way to get the entire stack running with a single command.

1. Clone the Repository

git clone https://github.com/22f3001340/MAY2026-Team-032.git
cd MAY2026-Team-032

2. Configure Environment Variables

Create a .env file inside the backend/ directory:

# backend/.env

DATABASE_URL=sqlite:///./libstack.db
CORS_ORIGINS=http://localhost:3000,http://localhost:5173,http://127.0.0.1:3000,http://127.0.0.1:5173
FINE_PER_DAY=5.0

# Redis (use 'redis' as hostname inside Docker network)
REDIS_URL=redis://redis:6379/0
CELERY_BROKER_URL=redis://redis:6379/0

# Google Gemini API Key (required for AI Chat Assistant)
GEMINI_API_KEY=your_gemini_api_key_here

# Gmail SMTP (required for email notifications)
SMTP_EMAIL=your_email@gmail.com
SMTP_PASSWORD=your_gmail_app_password

Note: For Gmail SMTP, you need to generate an App Password from your Google Account settings.

3. Build and Run

docker compose up --build

This launches 5 containers:

Container Service Port
frontend Vue 3 + Vite dev server http://localhost:5173
backend FastAPI + Uvicorn http://localhost:8000
redis Redis cache & message broker localhost:6379
celery_worker Background task processor —
celery_beat Scheduled task scheduler —

4. Seed the Database (First Run Only)

In a separate terminal, run the seed script to populate the database with demo data:

docker compose exec backend python seed.py

This creates demo admin/member accounts and 11 starter books across various sections.

5. Access the Application

Interface URL
Web Application http://localhost:5173
API Documentation (Swagger) http://localhost:8000/docs
API Documentation (ReDoc) http://localhost:8000/redoc

Stopping the Application

# Stop all containers (preserves data)
docker compose down

# Stop and remove all data (volumes)
docker compose down -v

Rebuilding After Code Changes

docker compose up --build

🔧 Manual Setup

For local development without Docker.

1. Clone the Repository

git clone https://github.com/22f3001340/MAY2026-Team-032.git
cd MAY2026-Team-032

2. Backend Setup

# Create and activate a virtual environment
# Linux / macOS
python3 -m venv backend/.venv
source backend/.venv/bin/activate

# Windows (PowerShell)
python -m venv backend\.venv
.\backend\.venv\Scripts\Activate.ps1
# Install dependencies (include fakeredis for local dev without Redis)
pip install -r backend/requirements.txt fakeredis

Create the environment file at backend/.env:

# backend/.env

DATABASE_URL=sqlite:///./libstack.db
CORS_ORIGINS=http://localhost:5173,http://localhost:3000,http://127.0.0.1:5173,http://127.0.0.1:3000
FINE_PER_DAY=5.0
REDIS_URL=redis://localhost:6379/0
CELERY_BROKER_URL=redis://localhost:6379/0

# Optional: AI features
GEMINI_API_KEY=your_gemini_api_key_here
SMTP_EMAIL=your_email@gmail.com
SMTP_PASSWORD=your_gmail_app_password

Note: If Redis is not installed locally, the backend will automatically fall back to an in-memory FakeRedis instance. Celery workers require a running Redis instance.

# Seed the database with demo data
cd backend
python seed.py

# Start the backend server
uvicorn main:app --host 127.0.0.1 --port 8000 --reload

The API will be available at http://127.0.0.1:8000 with Swagger docs at http://127.0.0.1:8000/docs.

3. Frontend Setup

Open a new terminal in the project root:

cd frontend
npm install
npm run dev

The frontend will be available at http://localhost:5173.

4. Celery Workers (Optional — for background tasks)

Requires a running Redis instance. In separate terminals:

# Terminal 1: Celery Worker
cd backend
celery -A tasks.celery_app worker --loglevel=info

# Terminal 2: Celery Beat (Scheduler)
cd backend
celery -A tasks.celery_app beat --loglevel=info

🔑 Demo Credentials

After running the seed script (python seed.py), the following accounts are available:

Role Email Password Access
Librarian admin@example.com Password!123 Full admin portal — books, members, loans, logs
Librarian (alt) admin@library.com admin123! Same admin access
Member member@example.com Password!123 Member portal — catalog, loans, AI features

Password Policy: All passwords must be at least 8 characters and contain at least one special character.

The seed script also creates 11 starter books across sections: Fiction, Science, History, Technology, Self-Help, Psychology, and Biography.


📡 API Reference

All endpoints are served under the /api prefix. Full interactive documentation is available at /docs (Swagger UI).

Authentication (/api/auth)

Method Endpoint Description Auth
POST /api/auth/register Register a new member Public
POST /api/auth/login Login and receive session cookie Public
POST /api/auth/logout Logout and invalidate session 🔒
GET /api/auth/me Get current user profile 🔒
PATCH /api/auth/me Update profile (name, contact) 🔒
PUT /api/auth/password Change password 🔒
GET /api/auth/users List all users 🔒 Admin
DELETE /api/auth/users/{id} Soft-delete a member 🔒 Admin

Books (/api/books)

Method Endpoint Description Auth
GET /api/books/ Paginated catalog with search & filter 🔒
GET /api/books/{id} Get single book details 🔒
POST /api/books/ Add a new book 🔒 Admin
PUT /api/books/{id} Update book metadata/copies 🔒 Admin
DELETE /api/books/{id} Soft-delete a book 🔒 Admin
GET /api/books/recommendations AI-powered book recommendations 🔒

Circulation (/api/borrows)

Method Endpoint Description Auth
POST /api/borrows/issue Issue a book to a member 🔒 Admin
POST /api/borrows/return/{id} Process a book return 🔒 Admin
GET /api/borrows/all List all borrow records 🔒 Admin
GET /api/borrows/member/{id} Get a member's borrow records 🔒

Renewal Requests (/api/borrows/renewals)

Method Endpoint Description Auth
POST /api/borrows/renewals/request Submit a renewal request 🔒
GET /api/borrows/renewals/ List all renewal requests 🔒 Admin
POST /api/borrows/renewals/{id}/approve Approve a renewal 🔒 Admin
POST /api/borrows/renewals/{id}/reject Reject a renewal 🔒 Admin

AI Chat (/api/chat)

Method Endpoint Description Auth
POST /api/chat Send a message to the AI library assistant Public

Audit Logs (/api/logs)

Method Endpoint Description Auth
GET /api/logs/ Retrieve activity log entries 🔒 Admin

Services (/api/services)

Method Endpoint Description Auth
GET /api/services/notifications/{member_id} Get member notifications 🔒
POST /api/services/reminders Trigger manual reminders 🔒 Admin

⏰ Background Tasks — Celery

LibStack uses Celery with Redis as the message broker and Celery Beat for periodic scheduling.

Task Schedule Description
process_overdue_fines Daily at 00:00 UTC Scans all active loans, marks overdue ones, and calculates fines (days × ₹5/day)
trigger_reminders Daily at 08:00 UTC Sends due-soon notifications (≤ 2 days) and creates in-app alerts
daily_overdue_reminders_task Daily at 08:00 UTC Emails overdue and due-tomorrow reminders to members via Gmail SMTP
send_email_task On demand Asynchronous email delivery worker (Gmail SMTP with STARTTLS)

🤖 AI & ML Features

Book Recommendations Engine

The recommendation system uses a hybrid content-based filtering approach:

  1. Embedding Model: all-MiniLM-L6-v2 from Sentence Transformers — generates 384-dimensional dense vector embeddings
  2. User Profile: Computes a centroid embedding from the user's borrowing history (mean of all borrowed book vectors)
  3. Similarity: Ranks candidate books by cosine similarity against the user profile vector
  4. Cold-Start Handling: Users with no borrow history receive the newest available books as fallback recommendations
  5. Caching: Embeddings are cached in-memory to avoid redundant model inference

AI Library Assistant (Agentic Chatbot)

The conversational assistant is powered by Google Gemini with function-calling capabilities:

  • Model: gemini-3.5-flash (with gemini-2.5-flash fallback)
  • Agentic Tools:
    • search_library_catalog(query) — Searches the database for books by title, author, or section
    • check_book_availability(book_id) — Checks real-time copy availability for a specific book
  • Behavior: The AI automatically invokes these tools to provide grounded, catalog-aware responses rather than hallucinating book information

🔒 Security

Feature Implementation
Password Hashing Bcrypt via passlib
Session Management Cryptographically secure hex tokens, SHA-256 hashed in DB, cached in Redis with 24h TTL
Cookie Security HttpOnly session cookies + non-HttpOnly CSRF cookies, SameSite=Strict
CSRF Protection Token-based CSRF validation on all state-changing requests (POST, PUT, DELETE, PATCH)
Rate Limiting SlowAPI — 5 requests/minute on login and registration endpoints
Security Headers X-Content-Type-Options: nosniff, X-Frame-Options: DENY, X-XSS-Protection, Strict-Transport-Security
Soft Deletion Users and books are flagged inactive rather than hard-deleted, preserving audit trails
Input Validation Pydantic v2 schema enforcement on all API inputs

📁 Project Structure

MAY2026-Team-032-02/
│
├── docker-compose.yml          # Multi-container orchestration (5 services)
├── README.md
│
├── backend/
│   ├── Dockerfile              # Python 3.11-slim based image
│   ├── .dockerignore
│   ├── .env                    # Environment variables (not committed)
│   ├── requirements.txt        # Python dependencies
│   ├── main.py                 # FastAPI entry point, middleware, CORS
│   ├── config.py               # Pydantic Settings configuration
│   ├── database.py             # SQLAlchemy engine & session management
│   ├── models.py               # ORM models (User, Book, BorrowRecord, etc.)
│   ├── schemas.py              # Pydantic request/response schemas
│   ├── auth_dependency.py      # Authentication guards & RBAC
│   ├── cache.py                # Redis client with FakeRedis fallback
│   ├── rate_limiter.py         # SlowAPI rate limiting configuration
│   ├── seed.py                 # Database seeder (demo users + books)
│   ├── tasks.py                # Celery tasks & beat schedule
│   ├── crud/
│   │   └── books.py            # Recommendation engine (SentenceTransformers)
│   └── routers/
│       ├── auth.py             # Authentication & user management
│       ├── books.py            # Book catalog CRUD & recommendations
│       ├── borrows.py          # Circulation, returns & renewals
│       ├── chat.py             # Agentic AI chat assistant
│       ├── logs.py             # Audit log retrieval
│       └── services.py         # Notifications & reminder triggers
│
└── frontend/
    ├── Dockerfile              # Node 20-alpine based image
    ├── .dockerignore
    ├── package.json
    ├── vite.config.js          # Vite dev server configuration
    ├── index.html              # SPA entry point
    └── src/
        ├── main.js             # Vue app initialization
        ├── App.vue             # Root component with data loading
        ├── assets/
        │   └── styles/
        │       └── main.css    # Global CSS variables & design system
        ├── components/
        │   └── common/         # Reusable components (Navbar, Sidebar, Modal, etc.)
        ├── composables/
        │   ├── api.js          # API client (fetch wrapper with cookies & CSRF)
        │   ├── useLoanHelpers.js
        │   └── useLookupHelpers.js
        ├── layouts/
        │   ├── AdminLayout.vue # Admin portal layout (sidebar + navbar)
        │   └── UserLayout.vue  # Member portal layout
        ├── router/
        │   └── index.js        # Vue Router with navigation guards
        ├── stores/
        │   ├── auth.js         # Authentication state (Pinia)
        │   ├── books.js        # Book catalog & recommendations
        │   ├── borrows.js      # Borrow records & renewals
        │   ├── notifications.js
        │   └── activityLog.js
        └── views/
            ├── HomeView.vue
            ├── NotFoundView.vue
            ├── auth/           # Login & Register
            ├── admin/          # 9 admin views (Dashboard, Catalog, Issue, etc.)
            └── user/           # 9 member views (Dashboard, Catalog, Chat, etc.)

About

AI-powered library management system with separate librarian and member portals — FastAPI backend, Vue 3 frontend, AI book recommendations (Sentence Transformers), and a Gemini-powered library assistant chatbot.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages