ACADEMIC PROJECT REPORT
LIBRARY MANAGEMENT SYSTEM AND AUDIO BOOKS
Submitted by: Lt. Sonittya Ou and Lt. Min Htet Kyaw
Department: Information Technology School
Institution: INS Valsura
ABSTRACT
The Smart Library Management System is a Flask-based web application
designed to modernize and automate library operations in educational
institutions. Traditional library systems often rely on manual tracking or static
digital catalogs that lack user engagement and accessibility. This project
addresses these limitations by integrating Machine Learning (ML) for
personalized content-based book recommendations and Natural Language
Processing (NLP) for automated text-to-speech audio generation.
The system features a robust, role-based architecture serving Students,
Teachers, and Librarians. It streamlines core functionalities such as book
inventory management, borrowing transactions with automatic due date
tracking (14-day loan periods), and real-time notifications. Differentiating itself
from standard solutions, the system utilizes TF-IDF (Term Frequency-Inverse
Document Frequency) and Cosine Similarity algorithms to analyze user
borrowing history and suggest relevant academic materials. Furthermore, it
incorporates an accessibility layer using Edge-TTS and PyPDF2 to convert
PDF textbooks into streaming audiobooks, making education more inclusive.
The application is built using Flask 3.1.2, SQLAlchemy 2.0.44, and Bootstrap
5, ensuring a responsive, secure, and scalable solution.
2
TABLE OF CONTENTS
1. Chapter 1: Introduction
○ 1.1 Background
○ 1.2 Problem Statement
○ 1.3 Objectives
○ 1.4 Scope of the Project
2. Chapter 2: Literature Review
○ 2.1 Evolution of Library Systems
○ 2.2 Gap Analysis
3. Chapter 3: System Analysis and Design
○ 3.1 Functional Requirements (User Roles)
○ 3.2 System Architecture
○ 3.3 Database Design (ER Schema)
○ 3.4 System Flow Diagrams
4. Chapter 4: Implementation Details
○ 4.1 Technologies and Libraries
○ 4.2 Algorithm Implementation (Machine Learning)
○ 4.3 Audio Processing Pipeline
○ 4.4 Key Routes and API Endpoints
5. Chapter 5: Results and Discussion
○ 5.1 Performance Optimization
○ 5.2 Testing and Validation
6. Chapter 6: Conclusion and Future Scope
7. References
3
CHAPTER 1: INTRODUCTION
1.1 Background
In the digital age, educational institutions require efficient systems to manage
their vast repositories of knowledge. Traditional physical libraries struggle with
manual record-keeping, misplaced books, and a lack of mechanisms to actively
engage students. The shift towards e-learning necessitates a "Smart Library"
that not only stores books but actively assists users in finding relevant content
and accessing it in various formats.
1.2 Problem Statement
Existing library management solutions often suffer from the following issues:
● Manual Inefficiency: High dependency on manual data entry for
borrowing and returning, leading to errors.
● Static Content: Users must know exactly what they are looking for; the
system does not aid in discovery.
● Accessibility Barriers: Standard digital libraries provide only PDF text,
which may not be suitable for auditory learners or visually impaired
students.
● Lack of Role Separation: Simple systems often fail to distinguish between
Student access and restricted Teacher resources.
1.3 Objectives
The primary objectives of this project are:
1. To Automate Operations: Streamline the borrowing/returning process,
including due date tracking and status updates.
2. To Enhance Discovery: Implement a Machine Learning recommendation
engine to suggest books based on reading habits.
3. To Improve Accessibility: Implement innovative PDF-to-Audio
conversion to generate audiobooks automatically.
4
4. To Ensure Security: Implement role-based access control (RBAC) for
Students, Teachers, and Librarians.
1.4 Scope
The scope includes the development of a web application handling:
● User Management: Registration, Login, and Role Management.
● Inventory Control: Uploading PDFs, managing cover images, and tracking
book status (Available/Borrowed/Maintenance).
● Transaction Processing: 14-day borrowing cycles with automatic overdue
detection.
● Notifications: Real-time alerts for reminders and overdue items.
5
CHAPTER 2: LITERATURE REVIEW
2.1 Evolution of Library Systems
Library systems have evolved from manual card catalogs (Gen 1) to Integrated
Library Systems (ILS) using barcode scanning (Gen 2). While Gen 2 systems
handle inventory well, they lack "intelligence."
2.2 Gap Analysis
Most current educational systems lack personalized recommendation engines
found in commercial platforms like Amazon or Netflix. Furthermore, while
text-to-speech exists as standalone software, it is rarely integrated directly into
the library database pipeline. This project bridges this gap by embedding ML
and Audio processing directly into the Flask application logic.
6
CHAPTER 3: SYSTEM ANALYSIS AND DESIGN
3.1 Functional Requirements (User Roles)
The system is designed with three distinct actors:
Fig (3.1) Registration Page
Fig (3.2) Login Page
7
1. Student:
● Browse & Search: Access dashboard with pagination (24 books/page) and
filtering by Title, Author, or Genre.
● Borrow: Borrow available books (max limit applied).
● Personalization: View top 6 ML-generated book recommendations.
● Audio: Stream generated audiobooks.
Fig (3.3) Student Dashboard
2. Teacher:
● All Student Features: Inherits all student capabilities.
● Restricted Access: Access to "Teacher-only" books (e.g., answer keys,
advanced research) unavailable to students.
3. Librarian (Administrator):
● Inventory Control: Full CRUD (Create, Read, Update, Delete) on books
and users.
● Borrowing Management: View all active borrowings, track overdue items,
8
and force-return books.
● Notification System: Send individual or bulk reminders for overdue books.
● Audio Generation: Trigger the PDF-to-Audio conversion process.
Fig (3.4) Admin Dashboard
3.2 System Architecture
The application follows a Model-View-Controller (MVC) pattern adapted for
Flask.
Request Flow:
1. User Request hits a Flask Route.
2. Flask-Login verifies authentication and current_user.role.
3. SQLAlchemy queries [Link].
4. Business Logic (e.g., ML calculation) processes data.
5. Jinja2 renders the HTML response using Bootstrap 5.
3.3 Database Design
The database is implemented using SQLite and SQLAlchemy ORM. The
schema consists of four primary normalized tables.
9
1. User Model
● id: Integer (Primary Key)
● username: String (Unique, Not Null)
● email: String (Unique, Not Null)
● password_hash: String (Not Null)
● role: String (student/teacher/librarian)
2. Book Model
● id: Integer (Primary Key)
● title: String (Not Null)
● author: String (Not Null)
● genre: String
● pdf_path: String (Not Null)
● cover_image_path: String (Custom image with default fallback)
● content_text: Text (Extracted text for ML analysis)
● audio_path: String (Generated audio file path)
● is_teacher_only: Boolean (Default: False)
● status: String (Available/Borrowed/Unavailable/Maintenance)
3. Transaction Model
● id: Integer (Primary Key)
● user_id: Integer (ForeignKey → User)
● book_id: Integer (ForeignKey → Book)
● transaction_type: String (Borrow/Return)
● borrow_date: DateTime (Not Null)
● return_date: DateTime (Nullable)
● due_date: DateTime (Nullable)
● status: String (Active/Completed)
● notes: Text (Nullable)
10
4. Notification Model
● id: Integer (Primary Key)
● user_id: Integer (ForeignKey → User)
● message: Text (Not Null)
● notification_type: String (reminder, return_due, overdue, general)
● is_read: Boolean (Default: False)
● related_book_id: Integer (ForeignKey → Book)
● related_transaction_id: Integer (ForeignKey → Transaction)
● created_at: DateTime (Default: Current Time)
Entity-Relationship (ER) Diagram
Fig (3.5) ER Diagram
11
3.4 System Flow Diagrams
Use Case Diagram
This diagram visualizes the interaction between the different actors (Student,
Teacher, Librarian) and the system modules.
Fig (3.5) Use Case Diagram
12
Sequence Diagram (Borrowing Process)
The sequential flow of logic when a user attempts to borrow a book
Fig (3.6) Sequence Diagram
13
CHAPTER 4: IMPLEMENTATION DETAILS
4.1 Technologies and Libraries Used
● Core Framework: Flask 3.1.2
● Database: SQLAlchemy 2.0.44, Flask-SQLAlchemy 3.1.1
● Security: Werkzeug 3.1.4 (Hashing), Flask-Login 0.6.3
● Frontend: Bootstrap 5.3.0, Bootstrap Icons 1.11.0, Jinja2 3.1.6
● ML & Math: scikit-learn 1.7.2, numpy 2.3.5, scipy 1.16.3, joblib 1.5.2
● File Processing: PyPDF2 3.0.1 (PDF Extraction), [Link]
● Audio Processing: Edge-TTS 6.1.0+ (Primary), gTTS 2.5.4 (Fallback),
pydub 0.25.1+
4.2 Algorithm Implementation (Machine Learning)
The recommendation engine uses a Content-Based Filtering approach.
Step 1: User Profile Creation
The system analyzes the books a user has previously borrowed. It concatenates
the title, author, and genre of these books into a single text profile.
Step 2: TF-IDF Vectorization
We use TF-IDF (Term Frequency-Inverse Document Frequency) to convert
book descriptions into numerical vectors. This technique highlights unique
terms (like specific genres) while downweighting common words.
● Library Used: scikit-learn TfidfVectorizer.
Step 3: Similarity Calculation
We calculate the Cosine Similarity between the user's profile vector and the
vectors of all books in the library.
● Recommendation Logic: The system returns the top 6 books with the
highest similarity scores that the user has not yet borrowed.
● Fallback: If a user has no history, the system displays the most popular
books.
14
Code Snippet for Audio Generation(Python)
def get_recommended_books(user, limit=6):
"""
Simple ML-based book recommendations using TF-IDF (Term Frequency-
Inverse Document Frequency).
This finds books similar to what the user has borrowed before.
How it works:
1. Look at books user has borrowed
2. Create a "profile" from those books (title + author + genre)
3. Compare all available books to this profile
4. Recommend the most similar books
Args:
user: Current user object
limit: Maximum number of recommendations to return
Returns:
List of Book objects
"""
try:
from sklearn.feature_extraction.text import TfidfVectorizer
from [Link] import cosine_similarity
if [Link] == 'student':
available_books = [Link].filter_by(
is_teacher_only=False, status='Available').all()
else:
available_books =
[Link].filter_by(status='Available').all()
if not available_books:
return []
user_transactions = [Link].filter_by(
user_id=[Link],
transaction_type='Borrow'
).all()
if not user_transactions:
return get_popular_books(user, available_books, limit)
borrowed_books = []
for transaction in user_transactions:
book = [Link](transaction.book_id)
if book:
borrowed_books.append(book)
if not borrowed_books:
return get_popular_books(user, available_books, limit)
def create_book_text(book):
"""Create a text description of a book"""
15
text_parts = []
if [Link]:
text_parts.append([Link]())
if [Link]:
text_parts.append([Link]())
if [Link]:
text_parts.append([Link]())
return " ".join(text_parts)
# Create text for all available books
all_book_texts = [create_book_text(book) for book in
available_books]
# Create text for user's borrowed books
borrowed_texts = [create_book_text(book) for book in
borrowed_books]
# Step 6: Use TF-IDF to convert text to numbers (vectors)
# TF-IDF finds important words in the text
vectorizer = TfidfVectorizer(
max_features=50, # Use top 50 most important words
stop_words='english' # Remove common words like "the", "a",
etc.
)
# Convert all books to vectors
all_vectors = vectorizer.fit_transform(all_book_texts)
# Convert user's borrowed books to vectors
borrowed_vectors = [Link](borrowed_texts)
# Step 7: Create user profile (average of all borrowed books)
user_profile = borrowed_vectors.mean(axis=0)
# Step 8: Calculate similarity between user profile and all books
# Cosine similarity: 1.0 = very similar, 0.0 = not similar
similarities = cosine_similarity(user_profile, all_vectors)[0]
# Step 9: Get book indices sorted by similarity (highest first)
book_indices = sorted(
range(len(available_books)),
key=lambda i: similarities[i],
reverse=True
)
# Step 10: Filter out books user already borrowed
borrowed_ids = {[Link] for book in borrowed_books}
recommended = []
for idx in book_indices:
book = available_books[idx]
if [Link] not in borrowed_ids:
[Link](book)
if len(recommended) >= limit:
break
16
# If not enough recommendations, add popular books
if len(recommended) < limit:
popular = get_popular_books(
user, available_books, limit - len(recommended))
[Link](popular)
return recommended[:limit]
except ImportError:
# Fallback if scikit-learn not available
return get_popular_books(user,
[Link].filter_by(status='Available').all(), limit)
except Exception as e:
# If ML fails, use fallback
print(f"ML recommendation error: {e}")
return get_popular_books(user,
[Link].filter_by(status='Available').all(), limit)
Fig (4.1) Recommendation Section
4.3 Audio Processing Pipeline
1. Extraction: PyPDF2 extracts text from the uploaded PDF. To optimize
performance, extraction is limited to the first 50 pages.
2. Cleaning: Regex is used to remove code symbols and non-text artifacts.
3. Chunking: Text is split into chunks of ~4000 characters to fit API limits.
4. Generation: Edge-TTS (Microsoft Edge Text-to-Speech) converts chunks
to audio using neural voices.
17
5. Merging: pydub merges chunks into a single MP3, inserting a 300ms pause
between chunks for natural pacing.
Code Snippet for Audio Generation(Python)
def text_to_audio(text, output_path, voice='en-US-AriaNeural',
rate='+0%'):
"""
Convert text to audio using Edge-TTS (Microsoft) for natural-sounding
speech.
Edge-TTS provides much better quality than gTTS with natural voices.
Args:
text: Text to convert
output_path: Path to save audio file (will be saved as MP3)
voice: Voice to use (default: 'en-US-AriaNeural' - natural female
voice)
Other options: 'en-US-JennyNeural', 'en-US-GuyNeural', 'en-
GB-SoniaNeural'
rate: Speech rate adjustment (default: '+0%', can be '-50%' to
'+100%')
Returns:
True if successful, False otherwise
"""
try:
import edge_tts
import asyncio
import tempfile
import os
print(f"INFO: Using Edge-TTS with voice: {voice}")
# Clean text for better audio quality
text = clean_text_for_audio(text)
# Edge-TTS works better with smaller chunks
# Split text into sentences for better natural pauses
import re
sentences = [Link](r'([.!?]\s+)', text)
chunks = []
current_chunk = ""
for i in range(0, len(sentences), 2):
sentence = sentences[i] + \
(sentences[i+1] if i+1 < len(sentences) else "")
# Edge-TTS can handle up to ~5000 characters, but we'll use
smaller chunks for better quality
18
if len(current_chunk) + len(sentence) < 4000:
current_chunk += sentence
else:
if current_chunk:
[Link](current_chunk.strip())
current_chunk = sentence
if current_chunk:
[Link](current_chunk.strip())
if not chunks:
return False
async def generate_audio():
"""Async function to generate audio"""
audio_files = []
for i, chunk in enumerate(chunks):
try:
# Create temporary file for this chunk
temp_file = [Link](
delete=False, suffix='.mp3')
temp_path = temp_file.name
temp_file.close()
# Generate audio for chunk
communicate = edge_tts.Communicate(chunk, voice,
rate=rate)
await [Link](temp_path)
audio_files.append(temp_path)
except Exception as e:
print(f"Error generating audio chunk {i}: {e}")
# Clean up temp files on error
for f in audio_files:
try:
[Link](f)
except:
pass
raise # Re-raise to trigger fallback to gTTS
# Merge all chunks into one file
if len(audio_files) == 1:
# Single chunk, just move it
import shutil
[Link](audio_files[0], output_path)
else:
# Multiple chunks, merge them
19
try:
from pydub import AudioSegment
combined = [Link]()
for audio_file in audio_files:
audio = AudioSegment.from_mp3(audio_file)
combined += audio
# Add small pause between chunks
# 300ms pause
combined += [Link](duration=300)
# Export combined audio
[Link](output_path, format="mp3")
# Clean up temporary files
for f in audio_files:
try:
[Link](f)
except:
pass
except (ImportError, Exception) as merge_error:
# pydub not available or ffmpeg issue, use first chunk
only
print(
f"Warning: Could not merge audio chunks
({merge_error}). Using first chunk only.")
import shutil
[Link](audio_files[0], output_path)
# Clean up other temp files
for f in audio_files[1:]:
try:
[Link](f)
except:
pass
# Don't fail - we have at least one chunk
return True
# Run async function
result = [Link](generate_audio())
if result:
print(
f"SUCCESS: Edge-TTS audio generated successfully:
{output_path}")
return result
except (ImportError, Exception) as e:
# Fallback to gTTS if Edge-TTS is not available or fails
20
print(
f"ERROR: Edge-TTS not available or failed ({e}). Falling back
to gTTS.")
print(f"ERROR DETAILS: {type(e).__name__}: {str(e)}")
import traceback
traceback.print_exc()
try:
from gtts import gTTS
text = clean_text_for_audio(text)
max_chunk_length = 4500
chunk = text[:max_chunk_length] if len(
text) > max_chunk_length else text
# Use 'en-us' for US accent, not 'en' (which defaults to
Indian English)
tts = gTTS(text=chunk, lang='en-us', slow=False)
[Link](output_path)
return True
except Exception as fallback_error:
print(f"Error with gTTS fallback: {fallback_error}")
return False
Fig (4.2) Audio interface
21
4.4 Key Routes & API Endpoints
User Routes:
● GET/POST /register, /login, /logout
● GET /dashboard (Student/Teacher Home)
Book Routes:
● GET /view_book/<id>, /read_book/<id>
● POST /borrow_book/<id>, /return_book/<id>
● GET /play_audio/<id>
Admin Routes:
● GET /admin_dashboard
● POST /add_book, /update_book/<id>, /delete_book/<id>
● GET /generate_audio/<id>
● POST /send_reminder/<id>, /send_bulk_reminders
Notification Routes:
● GET /notifications, /api/notifications/count
● POST /mark_notification_read/<id>
Fig (4.3) Notification Panels
22
CHAPTER 5: RESULTS AND DISCUSSION
5.1 Performance Optimization
Several techniques were used to ensure the system remains fast:
● Pagination: Implemented via SQLAlchemy paginate() to load only 24
books per page, reducing load times for large collections.
● Efficient Querying: Genre filtering uses DISTINCT SQL queries to avoid
scanning the entire table.
● Lazy Loading: Database relationships are loaded lazily, meaning
transaction history is only fetched when specifically requested.
● Audio Chunking: Splitting text ensures the TTS engine does not time out
on large books.
5.2 Testing
● Unit Testing: Verified password hashing and due date calculations (14
days from borrow date).
● Integration Testing: Tested the complete flow: Register -> Login ->
Browse -> Borrow -> Recommendation Update -> Return.
● Role Testing: Confirmed that Students cannot access /admin_dashboard
and cannot see is_teacher_only books.
23
CHAPTER 6: CONCLUSION AND FUTURE SCOPE
The Smart Library Management System successfully achieves its goal of
automating library tasks while introducing modern AI features. By combining
Flask's robust backend with scikit-learn's analysis capabilities, the system
provides a personalized experience for students and reduces the workload for
librarians.
Future Scope:
● Mobile App: Development of a native app (Flutter/React Native).
● Physical Integration: Adding barcode scanning support for physical
checkouts.
● Collaborative Filtering: Expanding the ML model to compare users with
similar tastes.
REFERENCES
1. Flask Documentation (v3.1.x)
2. Scikit-learn User Guide (TF-IDF and Cosine Similarity)
3. Microsoft Edge TTS Documentation
4. Bootstrap 5.3 Components Documentation
24