0% found this document useful (0 votes)
5 views70 pages

Invent Ree

The document presents a project report on 'InvenTree: Smart Inventory Management,' developed by a group of Bachelor of Computer Applications students to address inventory management challenges faced by small retailers in India. The system utilizes AI and Natural Language Processing to automate stock tracking, improve forecasting, and provide real-time insights, thus empowering small businesses to optimize their operations. The report outlines the project's objectives, methodology, system design, and potential impact on the retail sector.

Uploaded by

Sambhav Makhija
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views70 pages

Invent Ree

The document presents a project report on 'InvenTree: Smart Inventory Management,' developed by a group of Bachelor of Computer Applications students to address inventory management challenges faced by small retailers in India. The system utilizes AI and Natural Language Processing to automate stock tracking, improve forecasting, and provide real-time insights, thus empowering small businesses to optimize their operations. The report outlines the project's objectives, methodology, system design, and potential impact on the retail sector.

Uploaded by

Sambhav Makhija
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

InvenTree: Smart Inventory Management

A
MAJOR PROJECT REPORT

Submitted in partial fulfilment of the requirements for the re-


ward of the degree of Bachelor of Computer Applications
(Session2023-26)

By

Aarushi Yadav
(01714902023)

Maanik Khattar
(01814902023)

Angad Singh Chhabra


(35614902023)

Sambhav Makhija
(35814902023)

Maharaja Surajmal Institute


C-4, Janakpuri, New Delhi-110058

1
SELF CERTIFICATE

This is to certify that the dissertation/project report entitled “InvenTree: Smart Inventory

Management”, done by us is an authentic work carried out for the partial fulfilment of the

requirements for the award of the degree of Bachelor of Computer Applications under the

guidance of Dr. Ravinder Singh. The matter embodied in this project work has not been sub-

mitted earlier for award of any degree or diploma to the best of my knowledge and belief.

Signature: Signature of the Guide:


Aarushi Yadav Dr. Ravinder Singh
(01714902023) Assistant Professor
Department of Computer Applications

Signature:
Maanik Khattar
(01814902023)

Signature:
Sambhav Makhija
(35814902023)

Signature:
Angad Singh Chhabra
(35614902023)

2
ACKNOWLEDGEMENT

With gratitude and pleasure, we extend our heartfelt thanks to our esteemed guide, Dr.

Ravinder Singh whose valuable guidance, unwavering support, and cooperation made the

completion of the project, “InvenTree: Smart Inventory Management”, possible. His ex-

pertise and encouragement were instrumental in every step of this journey. We are also thank-

ful to the staff members of our college for providing us with the essential resources and a

supportive environment that facilitated our work. Lastly, we express our sincere appreciation

to everyone who contributed with their suggestions to improve the project. A special thanks

to our family for their encouragement and patience, and to the Almighty, whose blessings

have been our source of strength throughout.

Signature:
Aarushi Yadav
(01714902023)

Signature:
Maanik Khattar
(01814902023)

Signature:
Sambhav Makhija
(35614902023)

Signature:
Angad Singh Chhabra
(35814902023)

3
BONAFIDE CERTIFICATE
This is to certify that this project entitled "InvenTree: Smart Inventory Management” submit-

ted in the partial fulfilment of the degree of Bachelor of Computer Applications to the Guru

Gobind

Singh Indraprastha University (GGSIPU) through Maharaja Surajmal Institute done by

Aarushi Yadav (01714902023) is an authentic work carried out by him/her at under my

guidance. The matter embodied in this project work has not been submitted earlier for award

of any degree to the best of my knowledge and belief.

Signature: Signature of the Guide:


Aarushi Yadav Dr Ravinder Singh
(01714902023) Assistant Professor
Department of Computer Applications

Signature:
Maanik Khattar
(01814902023)

Signature:
Sambhav Makhija
(35814902023)

Signature:
Angad Singh Chhabra
(35614902023)

4
TABLE OF CONTENTS

1. SYNOPSIS ..............................................................................................................6

2. MAIN REPORT ................................................................................................... 8-35

2.1. Objective & Scope of the Project.............................................................................. 8

2.2. Theoretical Background (Definition of Problem) .................................................... 10

2.3. System Analysis & Design ....................................................................................... 11

2.4. System Planning........................................................................................................ 14

2.5. Methodology ............................................................................................................ 19

2.6. System Implementation ........................................................................................... 23

2.7. Hardware & Software Used .................................................................................... 26

2.8. System Evaluation .................................................................................................. 35

3. CODING & SCREENSHOTS OF THE PROJECT ............................. 38

4. CONCLUSION & FUTURE SCOPE ......................................................... 70

5. REFERENCES.......................................................................................................73

5
1. SYNOPSIS

In India, a vast majority of small-scale retailers and neighborhood kirana stores face signifi-

cant operational hurdles such as manual inventory tracking, recurring stockouts of essential

items, and heavy financial losses due to expired goods. Despite their critical role in the econ -

omy, these retailers often struggle with the complexity of modern POS systems, high costs of

enterprise software, and a lack of data-driven insights into consumer purchasing patterns.

Without accurate sales forecasting and real-time monitoring, store owners find themselves ei-

ther overstocking slow-moving products—locking up precious capital—or failing to meet de-

mand for high-velocity goods. This digital divide leaves them vulnerable to competition from

large organized retail chains, as they lack the tools to bridge the gap between their daily oper -

ations and strategic inventory optimization.

To address these pressing needs, the InvenTree Smart Inventory Management project was

conceptualized as a localized, AI-powered solution designed specifically for the Indian retail

landscape. InvenTree transforms raw sales data into actionable business intelligence. The sys-

tem acts as a virtual warehouse manager, providing 24/7 visibility into stock levels and au-

tomating the tedious process of inventory auditing. By integrating Natural Language Process-

ing (NLP), the platform allows non-technical users to query their business data through a

smart assistant, making complex analytics as simple as sending a text. Whether it’s identify-

ing which dairy products are nearing expiry or predicting next week's demand for grains, the

app serves as a bridge between traditional retail and modern intelligence.

The main objectives of the project are to design an intelligent dashboard that simplifies stock

management, reduces wastage, and empowers small business owners with professional-grade

6
forecasting tools. Key features include an AI Business Assistant for instant data queries, Real-

time Notifications for low-stock and expiry alerts, and Automated Sales Forecasting that

identifies monthly and weekly trends. The system also supports Professional PDF Reporting,

allowing users to generate detailed inventory and sales summaries for financial auditing with

a single click. Through its intuitive interface, offline-first database approach, and AI-driven

recommendations, InvenTree ensures that high-tech retail tools become affordable and acces-

sible to even the smallest neighborhood stores.

By democratizing access to artificial intelligence and data analytics, InvenTree empowers In-

dian retailers to minimize losses, maximize profits, and scale their businesses in a rapidly

evolving digital marketplace.

7
2. MAIN REPORT

2.1. OBJECTIVE & SCOPE OF THE PROJECT:

The InvenTree Smart Inventory Management System is designed to solve the common
inventory management problems faced by small retailers, kirana stores, grocery shops, and
medium-sized businesses in India. Traditional methods such as manual stock registers,
notebooks, and spreadsheets often lead to stock mismanagement, delayed updates, product
expiry losses, overstocking, understocking, and poor business decisions. These issues directly
affect profitability and customer satisfaction.

The main objective of this project is to develop an AI-powered inventory management


platform that automates stock tracking, improves forecasting accuracy, and provides real-time
business insights through an easy-to-use digital system. The project aims to replace outdated
manual processes with a smart, scalable, and cost-effective solution.

The system helps users manage products, monitor stock levels, track expiry dates, analyze
sales trends, and generate professional reports. One of the major goals is to provide intelligent
recommendations using Artificial Intelligence through the integration of the Google Gemini
API. This allows users to interact with the system using natural language queries such as
checking low-stock items, sales predictions, or expiry alerts without requiring technical
knowledge.

Another important objective is to reduce wastage caused by expired products and prevent
revenue loss due to stock shortages. The forecasting feature helps business owners plan
inventory purchases based on sales patterns, ensuring better financial management and
optimized stock investment.

The scope of the project includes frontend development using React and TypeScript for a
modern and responsive user interface, backend development using [Link] and [Link] for
handling server operations, SQLite for secure local database storage, and AI integration for
smart decision-making support.

The system is suitable for grocery stores, medical shops, dairy shops, wholesalers, and other
retail businesses that require daily stock monitoring. It supports report generation in PDF
format, interactive dashboards, graphical sales analysis, and notification systems for better
operational control.

Thus, InvenTree is not only an inventory management software but also a complete smart
business assistant that improves efficiency, saves time, reduces losses, and helps small
businesses compete in the modern digital market.

8
2.2. THEORETICAL BACKGROUND:

Inventory management is the process of ordering, storing, tracking, and controlling goods and
materials in a business. It ensures that the right products are available at the right time in the
right quantity. Effective inventory management helps businesses reduce operational costs,
avoid product shortages, and improve customer satisfaction.

Traditional inventory systems used by small retailers are mostly manual, where stock records
are maintained using registers, notebooks, or spreadsheets. These methods are time-
consuming, error-prone, and inefficient for handling real-time business operations. They do
not provide forecasting capabilities, expiry monitoring, or analytical insights.

Modern inventory management systems use digital platforms to automate stock updates,
monitor transactions, and generate reports. These systems improve accuracy and reduce
dependency on manual labor. However, many enterprise-level solutions are expensive and
too complex for small businesses.

The concept behind InvenTree is based on combining inventory management with Artificial
Intelligence and data analytics. AI helps transform raw business data into meaningful insights
that support better decision-making. By analyzing sales patterns and stock movement, the
system can forecast future demand, detect unusual trends, and recommend actions.

Natural Language Processing (NLP) plays a major role in this project through the AI
Business Assistant. NLP enables users to communicate with the system using simple human
language instead of technical commands. For example, users can ask questions like “Which
products are low in stock?” or “Show sales prediction for next week,” and receive instant
responses.

The frontend of the project is built using React, which supports Single Page Application
(SPA) architecture for faster performance and better user experience. TypeScript improves
code reliability and maintainability. Tailwind CSS is used for responsive and efficient styling.

The backend uses [Link] with [Link] to handle API requests, user operations, and
system logic. SQLite is selected as the database because it is lightweight, fast, offline-first,
and suitable for local business applications without requiring expensive server infrastructure.

Data visualization using Recharts helps users understand inventory performance through
charts and graphs. PDF reporting tools such as jsPDF and jsPDF-AutoTable provide
professional business reports for auditing and financial review.

Therefore, the theoretical foundation of InvenTree lies in inventory control systems, database
management, artificial intelligence, forecasting techniques, natural language processing, and
full-stack web application development.

9
2.3. SYSTEM ANALYSIS AND DESIGN:

2.3.1. System Analysis


System analysis is the process of studying the existing system, identifying its problems,
understanding user requirements, and designing a better solution. In the case of InvenTree,
the analysis focuses on improving traditional inventory handling methods used by small
businesses.

Understanding the Problem

Small retailers often face difficulties in maintaining proper inventory records due to
dependence on manual systems. Common problems include:

• Inaccurate stock counting


• Frequent stockouts of fast-selling products
• Overstocking of slow-moving products
• Financial losses due to expired goods
• Lack of sales forecasting
• No real-time inventory visibility
• Difficulty in generating reports
• Poor decision-making due to lack of analytics

These issues reduce profitability and increase operational inefficiency.

User Needs and Expectations

Users of the system mainly include shop owners, store managers, and inventory staff. Their
expectations from the system are:

• Easy product addition and stock updates


• Real-time monitoring of available inventory
• Low-stock alerts and expiry notifications
• Sales trend analysis and forecasting
• Simple and user-friendly dashboard
• AI assistant for instant business insights
• Secure data storage and quick report generation
• Affordable and easy-to-maintain software

The system must be simple enough for non-technical users while providing advanced
business intelligence.

10
Functional Requirements

Functional requirements define what the system should do.

Main Functional Requirements:

• Product Management
Add, update, delete, and search products.
• Inventory Tracking
Monitor stock quantity, stock movement, and product availability.
• Expiry Management
Identify products nearing expiry and generate alerts.
• Low-Stock Notifications
Notify users when stock reaches below minimum threshold.
• Sales Recording
Store and manage sales transaction data.
• Sales Forecasting
Predict future demand based on historical sales patterns.
• AI Business Assistant
Answer inventory-related questions using Gemini AI integration.
• Dashboard Analytics
Display charts, graphs, and summary cards for quick insights.
• PDF Report Generation
Export inventory and sales reports in professional PDF format.
• User-Friendly Interface
Provide easy navigation and responsive design.

Non-Functional Requirements

▪Non-functional requirements define how the system should perform.

Main Non-Functional Requirements:

• Performance
Fast loading speed and quick data retrieval.
• Reliability
Accurate data storage and stable system operations.
• Security
Safe handling of inventory and sales records.
• Scalability
Ability to manage increasing products and transactions.
• Usability
Simple interface for users with limited technical knowledge.
• Maintainability
Easy to update and improve system features.

11
• Compatibility
Smooth functioning across desktop and modern browsers.
• Availability
System should work efficiently even in offline-first environments.

2.3.2. System Design:

System design defines how the system will be structured and how different components
interact to perform required operations.

• System Architecture:

The InvenTree system follows a Full-Stack Three-Tier Architecture:

1. Presentation Layer (Frontend)

Built using React, TypeScript, Tailwind CSS, and Recharts.

Functions:

• User interface
• Dashboard display
• Forms for inventory management
• Charts and reports
• AI assistant interaction

2. Application Layer (Backend)

Built using [Link] and [Link].

Functions:

• Business logic processing


• API handling
• User requests processing
• AI query handling
• Report generation
3. Data Layer (Database)

Built using SQLite.

Functions:

• Product storage
• Sales records
• Inventory history

12
• Forecasting data
• System reports
This architecture ensures modularity, maintainability, and efficient
performance.

• DFD:
Level 0 DFD

External Entity: User

Processes:

• Manage Inventory
• Generate Reports
• AI Query Processing
• Forecast Sales
Data Store:

• Product Database
• Sales Database
Flow:

User →

Inventory
Input → System → Database
Database → Processed Information → User

Figure 1: DFD of the Model

13
• Use Case Diagram:

Actors:

• Admin
• Store Owner
• Inventory Staff
Use Cases:

• Login
• Add Product
• Update Product
• Delete Product
• Check Stock
• Receive Notifications
• View Dashboard
• Generate
PDF
Report
• Ask AI

Assistant
• View Sales Forecast
All actors interact with the central inventory management system according to permissions.

14
Figure 2: Use Case Diagram of the Model

• Activity Diagram:

Process Flow:

Start

User Login

Dashboard Access

Choose Operation

Manage Inventory / Check Forecast / Generate Report / Ask AI

System Processes Request

Display Results

Logout

End

This shows the step-by-step workflow of


user interaction.

15
Figure 3: Activity Diagram of the Model

• Sequence Diagram:

Example: Product Stock Update

User → Frontend → Backend → Database

1. User selects product update


2. Frontend sends request to backend
3. Backend validates request
4. Backend updates SQLite database
5. Database confirms update
6. Backend sends success response
7. Frontend displays updated stock information
This sequence ensures proper
communication between
system layers and reliable
transaction handling.

16
Figure 4: Sequence Diagram of the Model

17
2.4. SYSTEM PLANNING:

Tasks Involved in System Development:

2.4.1. Requirement Gathering and Analysis:

The first phase involved understanding the needs of users who frequently face legal issues re-

lated to tenancy, consumer rights, workplace disputes, traffic laws, and cybercrime. The anal-

ysis identified the essential system features such as natural-language query handling, step-by-

step legal guidance, citation of applicable laws, and generation of legal document templates.

This stage also reviewed user expectations, including easy accessibility, clarity of responses,

and 24/7 availability. The legal domains to be covered and the procedures to be supported

were finalized during this phase.

2.4.2. Data Collection:

Relevant legal information was collected from verified sources such as government websites,

legal acts, public legal resources, and existing online complaint portals. This includes sec-

tions from applicable Indian laws, helpline numbers, procedures for filing complaints, and

formats of commonly used legal documents. Additionally, frequently asked legal questions

from online legal forums were analyzed to understand common user issues. This assembled

data forms the foundational knowledge required by the chatbot.

2.4.3. Data Preprocessing:

The collected data was cleaned, simplified, and organized to ensure consistent and accurate

responses. Complex legal language was rewritten in simple, citizen-friendly terms so users

can understand their rights without difficulty. Duplicate or outdated information was re-

moved, and laws were arranged into categories like tenancy, cybercrime, workplace issues,

etc. The information was then structured into prompt formats suitable for the pre-trained NLP

18
models used through the API. Preprocessing ensures that the chatbot provides accurate and

easy-to-understand legal assistance.

2.4.4. Prompt Engineering :

Since the system uses pre-trained models through the Hugging Face API, no model training

was required. Instead, detailed prompt engineering was performed to instruct the AI model to

behave as an expert Indian legal advisor. The system prompt was designed to enforce rules

such as summarizing the user's problem, citing laws, providing documents, and giving step-

by-step guidance. Multiple prompts were tested with real-world questions to ensure clarity,

accuracy, and consistency. This phase ensures that the AI produces high-quality legal an-

swers even without training.

2.4.5. Web Application Development:

The user interface of the chatbot was developed using Streamlit to provide a clean and inter-

active experience. Custom CSS was added to create a professional legal theme. Features such

as chat display boxes, conversation history, example questions, emergency helplines, and

message formatting were developed. The interface was intentionally designed to be simple so

that even users with minimal technical skill can access legal guidance easily.

2.4.6. Integration of AI Model and SQLite Database:

The chatbot system was integrated with the Hugging Face InferenceClient API to generate

real-time responses based on user messages. Environment variables were used to secure the

API token. Additionally, Firebase-style persistent conversation support was implemented

through an SQLite database, allowing each message—user and assistant—to be stored along

with timestamps and user roles. This enables viewing chat history and supports future en-

hancements such as exporting or sharing conversations. The integration ensures smooth inter-

action between frontend, backend AI, and database storage.

19
2.4.7. Testing and Debugging:

Comprehensive testing was performed to verify the chatbot's accuracy, interface usability,

and error handling. Functional testing ensured correct responses across all legal categories.

Scenario testing checked how the chatbot responds to vague or incomplete queries. Interface

testing verified that text formatting, buttons, scroll areas, and warnings displayed correctly.

Bugs identified during testing were fixed, and prompts were refined to improve accuracy.

This ensures the system performs reliably in real-world situations.

2.4.8. PERT Chart:

A PERT (Program Evaluation and Review Technique) chart was created to visualize the se-

quence of development activities, dependencies, and critical path of the Legal Advice Chat-

bot project. It helped plan execution flow from requirement gathering to deployment, identify

necessary parallel tasks, and minimize project delays. The chart represents major phases in-

cluding requirement analysis, data preparation, UI creation, AI integration, database setup us-

ing SQLite, and final testing.

Task Task Name Depen- Description


ID dent On

T1 Requirement Gath- Start Identify legal chatbot


ering & Analysis needs, features & scope

T2 Data Collection T1 Gather legal laws, acts,


complaints procedures

T3 Data Preprocessing T2 Clean, organize and cate-


gorize legal data

T4 Prompt Engineer- T3 Design structured conver-


ing sation prompts

T5 Web UI Develop- T4 Build chat layout and user

20
ment (Streamlit + interface
CSS)

T6 SQLite Database T5 Store chat history mes-


Integration sages & timestamps

T7 AI Model Integra- T6 Connect AI model, gener-


tion (HuggingFace ate responses, rerun
API) mechanism

T8 Testing & Debug- T7 Fix UI issues, timestamp


ging errors, performance

T9 Deployment & Final T8 Final version, hosting


Review plans, documentation

21
2.5. METHODOLOGY:

The methodology adopted for the development of the AI-powered Legal Advice Chatbot fol-

lows a systematic and iterative approach to ensure accuracy, usability, and effective legal as-

sistance. The process is divided into several structured steps that guide the development from

conceptualization to deployment.

2.5.1. Data Collection:

The first step involved gathering relevant and authentic legal information from official and

publicly available sources. This included Indian laws such as the Consumer Protection Act,

Rent Control Acts, Motor Vehicles Act, IT Act, labour laws, and family law guidelines. Ad-

ditional resources such as government helplines, complaint procedures, legal templates, and

FAQs were collected to build a strong and reliable knowledge base. Common citizen ques-

tions were also studied from online legal forums to understand real-world user needs.

2.5.2. Data Preprocessing:

After collecting the information, the data underwent preprocessing to ensure clarity and con-

sistency. This process included simplifying legal language into easy, understandable terms

and organizing the content into different legal categories such as tenancy, consumer com-

plaints, workplace issues, traffic laws, and cybercrime. Outdated information was removed,

and all content was structured into prompt-friendly formats. Sample responses, templates, and

conversational examples were cleaned and refined to help the chatbot generate clear and ac-

curate answers.

2.5.3. Prompt Engineering and Response Design:

Since the system uses pre-trained models (such as DeepSeek and Qwen) through API calls,

no model training was required. Instead, prompt engineering formed the core methodology

22
for generating accurate legal responses. A detailed system prompt was designed that instructs

the AI on how to behave like an Indian legal advisor, what laws to cite, how to present infor-

mation, and how to maintain conversation context. Various prompt formats were tested and

refined to ensure step-by-step guidance, accuracy of laws, question summarization, and clar-

ity of explanation. This step ensures that the chatbot behaves consistently and provides high-

quality legal guidance.

2.5.4. System Development:

The web interface of the chatbot was developed using Streamlit, chosen for its simplicity and

ability to create interactive UI elements. Custom CSS was applied to create a professional

and visually appealing legal theme. Features such as chat history display, message format-

ting, legal categories in the sidebar, emergency helplines, and conversation clearing were im-

plemented. The interface was designed to be intuitive, enabling users to ask questions effort-

lessly and receive responses instantly.

2.5.5. Database Integration (SQLite)

To enable chat history storage and retrieval, SQLite database integration was implemented.

A database named chat_history.db was created, and a table was designed to store role-based

conversations (user / assistant) along with timestamps. The datetime library with Asia/

Kolkata timezone was used to save and convert timestamps into IST format. Every message

sent or generated is automatically inserted into the database. The “Show Chat History” side -

bar feature allows users to view previous messages stored in SQLite. This ensures persistent

and organized conversation records for legal tracking and project demonstration.

2.5.5. Integration:

23
Once the system prompt and interface were ready, the chatbot was integrated with the Hug -

ging Face Inference API using the InferenceClient. API tokens were securely stored using en-

vironment variables. Each user query is sent to the selected AI model along with the conver-

sation history, and the model-generated response is displayed on the interface. Multiple fall-

back models were configured to ensure uninterrupted functioning even if one model becomes

unavailable. Error handling mechanisms were added to manage failures, slow responses, or

connectivity issues.

2.5.6. Testing and Evaluation:

Extensive testing was conducted to ensure the chatbot delivers accurate and reliable legal as-

sistance. Functional testing checked whether the chatbot correctly responded to questions

across different legal domains. Scenario testing evaluated its performance with incomplete,

unclear, or multi-step questions. Usability testing ensured that the interface is simple, read-

able, and beginner-friendly. The chatbot was evaluated based on accuracy of legal informa-

tion, clarity of stepwise guidance, response speed, and overall user experience. Improvements

were made based on test results to refine prompts, enhance context retention, and ensure con-

sistent performance.

24
2.6. SYSTEM IMPLEMENTATION:

The implementation of the AI-powered Legal Advice Chatbot consists of multiple compo-

nents, including the front-end user interface, the integration with pre-trained AI models

through APIs, and the backend logic that manages conversation flow and data processing.

Each layer is designed to ensure that users receive accurate, easy-to-understand, and timely

legal guidance. The system focuses on accessibility, simplicity, and high responsiveness so

that even individuals with no legal background can interact with it easily.

2.6.1. Front-End Implementation

The front-end implementation focuses on creating a clean, professional, and user-friendly in-

terface that allows users to ask legal questions and receive AI-generated responses smoothly.

The chatbot interface was built using Streamlit, supported by custom HTML and CSS ele-

ments to provide a polished legal theme.

Technologies Used:

1. Streamlit

Streamlit serves as the primary framework for building the interactive web interface. It han-

dles UI components such as chat messages, input fields, sidebars, buttons, containers, and

session management. Streamlit's simplicity allows rapid development while maintaining an

organized structure. It provides built-in components like st.chat_input, [Link], and [Link] to

make the interface interactive and responsive.

2. HTML Components

25
HTML structures inside [Link]() were used to create formatted chat bubbles, headings,

badges, and custom sections like emergency helplines and coverage areas. HTML helps de-

fine the layout of user messages and assistant messages, improving readability and visual

flow.

3. CSS (Custom Styling)

Custom CSS embedded through [Link]() enhances the visual appeal of the interface. CSS

is used to:

· Style chat bubbles for user and assistant messages

· Add a legal color theme (dark blue, light grey, white)

· Customize buttons, headers, sidebars, and badges

· Apply borders, padding, margin spacing, and shadow effects

This contributes to a professional and trustworthy appearance, suitable for a legal

guidance platform.

4. Streamlit Session State (st.session_state)

Session state is used to manage:

· Chat history

· Conversation context

· Message persistence across reruns

This ensures a continuous, uninterrupted chat experience, mimicking a real conversa-

tion.

The combination of Streamlit + HTML + CSS creates a responsive, clean, and modern UI

that supports real-time interaction and smooth communication.

26
2.6.2. AI Model Integration

Unlike systems that train their own model, this chatbot uses pre-trained Large Language

Models hosted on Hugging Face, accessed through the InferenceClient API. This ensures

high accuracy and advanced language understanding without requiring training or maintain-

ing ML infrastructure.

Key Components:

Hugging Face InferenceClient

The chatbot uses:

from huggingface_hub import InferenceClient

to connect to multiple LLMs. These models are selected based on availability and perfor-

mance, including:

· DeepSeek V3

· Qwen2.5 Instruct

· Llama 3.2 Instruct

A fallback system is implemented:

· If one model is unavailable

· The chatbot automatically retries with the next model

This ensures uninterrupted service.

API Token Management

Environment variables were used to securely store the Hugging Face API key:

from dotenv import load_dotenv

27
This prevents hardcoding sensitive credentials in the code.

Prompt Engineering Instead of Model Training

Because the project uses pre-trained models:

· No training

· No datasets

· No CNNs

· No TensorFlow

Instead, a highly detailed system prompt is engineered to guide the model's behavior.

The system prompt instructs the AI to:

· Summarize the problem

· Cite laws

· Provide step-by-step guidance

· Provide helplines and portals

· Maintain conversational context

This replaces the need for dataset-based training.

Conversation Context Management

The chatbot stores the last few interactions to maintain continuity:

st.session_state.conversation_history

This allows the model to answer follow-up questions intelligently.

28
2.6.3. Backend Implementation

The backend controls the core logical flow between the UI, AI, and database.

1. Backend Logic (Python-Controlled Processing)

Python manages:

· Input processing

· System prompt generation

· Real-time message rendering

· Error handling & model switching

· Database interaction

2. SQLite Database Integration

The chatbot uses SQLite for storing and retrieving chat history. A database file chat_histo-

[Link] is created automatically, containing:

· role (user/assistant)

· message (content)

· timestamp stored in IST timezone

Table creation:

CREATE TABLE IF NOT EXISTS chat_history (

id INTEGER PRIMARY KEY AUTOINCREMENT,

role TEXT,

message TEXT,

timestamp TEXT

29
Saving data to DB

save_message("user", user_input)

save_message("assistant", answer)

Display history

Users can view previous chats via:

[Link]("SELECT role, message, timestamp FROM chat_history ORDER BY id")

3. API Communication Workflow

Step-by-step processing:

1. User enters a question

2. Stored in session history & database

3. System prompt is constructed

4. AI model processes input & returns a response

5. Response stored in database

6. Interface refreshes to show messages

4. Error Handling & Fail-safe Design

· Model failure fallback logic

· Clear error messages instead of crashing

· Rerun trigger using [Link]() ensures smooth UI refresh

5. No Local Machine Learning Required

· No training, dataset handling or GPU use

· Fully dependent on inference API response

30
31
2.7. HARDWARE & SOFTWARE USED:

2.7.1. Hardware Used:

• Operating System: Windows 11

• System Architecture: 64-bit operating system, x64-based processor with Windows

• CPU: 12th Gen Intel(R) Core(TM) i5-12450H 2.00 GHz

• RAM: 8.00 GB

2.7.2. Software Used:

· Front-End / Interface Layer:

o Streamlit: A Python-based web framework used to design and deploy the ap-

plication's user interface, including chat layout, buttons, and interactive com-

ponents.

· Back-End & Core Dependencies:

o Python: The primary programming language used for backend logic, API

handling, database operations, and application workflow.

o HuggingFace InferenceClient: A cloud-based API service used to connect

with and generate responses from large language models hosted on Hugging-

Face Hub.

o SQLite3: A lightweight relational database used to store and retrieve chat his-

tory, timestamps, and session information.

o dotenv (python-dotenv): A configuration library used to securely load API

keys and environment variables from a .env file.

o OS (Python Standard Library): Used to access system environment vari-

ables and file paths.

32
o Datetime / Timezone Libraries: Used for generating accurate timestamps

and converting them to IST (Indian Standard Time) for chat storage and dis-

play.

o ZoneInfo / pytz: Libraries used to handle timezone-aware datetime conver-

sions for consistent log formatting.

33
2.8. SYSTEM EVALUATION

The AI-powered Legal Advice Chatbot was evaluated based on functional performance,

response quality, interface usability, and database efficiency, rather than classification

metrics, since the system does not involve model training or dataset-based classification. The

evaluation focused on real-world usage scenarios to determine the reliability, responsiveness,

and legal usefulness of the chatbot for Indian citizens seeking legal guidance.

2.8.1. Classification Metrics:

· Accuracy:

Accuracy measures the proportion of correct predictions made by the model across all

predictions. It provides an overall understanding of the model’s performance, though

it may not always be reliable for imbalanced datasets. Correct predictions include

True Positives (TP) and True Negatives (TN), while total predictions consist of TP,

TN, False Positives (FP), and False Negatives (FN).

It is calculated as:

Accuracy = (TP + TN) / (TP + TN + FP + FN)

· Precision:

Precision evaluates the model’s ability to correctly identify only positive instances.

High precision indicates that when the model predicts a positive class, it is more

likely to be correct. It is computed as the ratio of True Positives to the sum of True

Positives and False Positives:

Precision = TP / (TP + FP)

34
· Recall (Sensitivity):

Recall measures the model's ability to identify all actual positive instances in the

dataset. High recall ensures that most positive samples are correctly detected, reduc-

ing the risk of missing important instances. It is calculated as:

Recall = TP / (TP + FN)

· F1-Score:

The F1-score is the harmonic mean of precision and recall. It provides a balanced

measure, especially useful when dealing with imbalanced classes. A high F1-score in-

dicates a good balance between precision and recall, making the model reliable for

classification tasks.

The formula for F1-score is:

F1-Score = 2 × (Precision × Recall) / (Precision + Recall)

2.8.2. Results:

The evaluation results demonstrate that the chatbot performs effectively as a legal guidance

tool:

· High accuracy and relevance of legal responses across multiple categories (tenancy,

consumer law, workplace disputes, cybercrime, etc.)

· Fast response time averaging under 4 seconds

· Strong reliability & availability due to model fallback strategy

· Clear and accessible explanation style suitable for general users

· Excellent database consistency with successful saving and retrieval of timestamped

chats

· Smooth UI interaction supported by Streamlit’s session management

35
User feedback indicated that the platform provides helpful, structured legal instructions and

makes legal information easy to understand without technical or legal expertise. The ability to

access past chats contributes to a more personalised guidance experience.

Overall, the evaluation confirms that the developed system is efficient, responsive, and ready

for practical deployment. It successfully meets its objectives of offering accessible, step-by-

step legal support, with opportunities for future enhancement such as multilingual support,

live lawyer integration, and automated document generation.

3. CODING & SCREENSHOTS OF THE PROJECT

[Link]

36
import streamlit as st

from huggingface_hub import InferenceClient

from dotenv import load_dotenv

import os

import sqlite3

conn = [Link]("chat_history.db",

check_same_thread=False)

cursor = [Link]()

from datetime import datetime, timezone

try:

from zoneinfo import ZoneInfo

KOLKATA = ZoneInfo("Asia/Kolkata")

except Exception:

import pytz

KOLKATA = [Link]("Asia/Kolkata")

[Link]("""

CREATE TABLE IF NOT EXISTS chat_history (

id INTEGER PRIMARY KEY AUTOINCREMENT,

role TEXT,

37
message TEXT,

timestamp TEXT

""")

[Link]()

# Save helper that writes IST timestamp into DB

def save_message(role, message):

try:

now_ist = [Link](KOLKATA)

except Exception:

now_ist =

[Link]([Link]).astimezone(KOLKATA)

ts = now_ist.strftime("%Y-%m-%d %H:%M:%S %z") # e.g.

"2025-11-19 17:18:05 +0530"

[Link](

"INSERT INTO chat_history (role, message, timestamp)

VALUES (?, ?, ?)",

(role, message, ts)

[Link]()

38
# Robust parser to convert stored timestamps to IST display

format

def parse_to_ist(ts_str):

"""

Accepts various timestamp formats stored in DB and returns

IST string "YYYY-MM-DD HH:MM:SS".

If parsing fails, returns original string.

"""

if not ts_str:

return ""

# Try with explicit offset first: "YYYY-MM-DD HH:MM:SS

+0530"

try:

if ("+" in ts_str and ts_str.strip()[-

5:].lstrip("+").isdigit()) or ("-" in ts_str and

ts_str.strip()[-5:].lstrip("-").isdigit()):

dt = [Link](ts_str, "%Y-%m-%d %H:%M:%S

%z")

ist_dt = [Link](KOLKATA)

return ist_dt.strftime("%Y-%m-%d %H:%M:%S")

39
except Exception:

pass

# Try naive datetime (assume UTC)

try:

dt = [Link](ts_str, "%Y-%m-%d %H:%M:%S")

dt = [Link](tzinfo=[Link])

ist_dt = [Link](KOLKATA)

return ist_dt.strftime("%Y-%m-%d %H:%M:%S")

except Exception:

pass

# Try ISO formats

try:

dt = [Link](ts_str)

if [Link] is None:

dt = [Link](tzinfo=[Link])

ist_dt = [Link](KOLKATA)

return ist_dt.strftime("%Y-%m-%d %H:%M:%S")

except Exception:

pass

return ts_str # fallback: show original

40
load_dotenv()

HFTOKEN= [Link]("HFTOKEN")

# Page configuration

st.set_page_config(

page_title="Legal Advice Chatbot - India",

page_icon="⚖️",

layout="centered"

# Custom CSS for professional legal theme with chat interface

[Link]("""

<style>

.stButton > button {

width: 100%;

background-color: #1e3a8a;

color: white;

font-weight: bold;

border-radius: 8px;

41
padding: 0.7rem;

font-size: 1.1rem;

.stButton > button:hover {

background-color: #1e40af;

box-shadow: 0 4px 6px rgba(0,0,0,0.1);

.error-box {

background-color: #fef2f2;

padding: 1.5rem;

border-radius: 10px;

border-left: 4px solid #dc2626;

.disclaimer-box {

background-color: #fffbeb;

padding: 1.2rem;

border-radius: 8px;

border-left: 4px solid #f59e0b;

margin: 1.5rem 0;

42
font-size: 0.9rem;

.category-badge {

display: inline-block;

padding: 0.3rem 0.8rem;

background: #9D9D9D;

border: 1px solid #9D9D9D;

color: black;

border-radius: 15px;

font-size: 0.85rem;

margin: 0.2rem;

font-weight: 600;

width: 180px;

display:flex;

text-align: center;

border: 1px solid black !important;

[Link] > button[kind="secondary"] {

43
background-color: rgba(16, 163, 127, 0.35) !important; /*

transparent #10A37F */

color: white !important; /* text color */

border: 1px solid #10A37F !important;

border-radius: 10px !important;

padding: 10px 14px !important;

font-weight: 600 !important;

[Link] > button[kind="secondary"]:hover {

background-color: rgba(16, 163, 127, 0.55) !important;

color: white !important;

border: 1px solid #0E8F70 !important;

[Link] {

border: 1px solid #30377D !important;

border-radius: 10px !important;

font-weight: 600 !important;

44
.main-header {

text-align: center;

color: #1e3a8a;

padding: 1rem 0;

font-size: 2.5rem;

font-weight: 700;

.sub-header {

text-align: center;

color: #D8D0D0;

font-size: 1.2rem;

margin-bottom: 2rem;

line-height: 1.6;

.chat-wrapper {

max-width: 800px;

margin: 0 auto;

background: #10A37F;

padding: 10px;

45
}

.message {

padding: 12px 16px;

margin: 10px 0;

border-radius: 14px;

font-size: 1.05rem;

line-height: 1.5;

max-width: 80%;

.user {

margin-left: auto;

background: #10A37F;

border: 1px solid #0E8F70;

color: black;

46
.assistant {

margin-right: auto;

background: #9D9D9D;

border: 1px solid #565869;

color: black;

.avatar {

width: 36px;

height: 36px;

border-radius: 50%;

background: #e5e5e5;

display: inline-block;

margin-right: 8px;

.message-row {

display: flex;

47
align-items: flex-start;

margin-top: 18px;

.message-text {

flex: 1;

</style>

""", unsafe_allow_html=True)

# Initialize session state

if 'messages' not in st.session_state:

st.session_state.messages = []

if 'conversation_history' not in st.session_state:

st.session_state.conversation_history = []

# Header

[Link]("<h1 class='main-header'>⚖️ LawPilot: Legal Advice

Bot</h1>", unsafe_allow_html=True)

48
[Link]("<p class='sub-header'>Free AI-Powered Legal

Guidance for Indian Citizens<br>Get instant answers on

tenancy, consumer rights, workplace issues & traffic

laws</p>", unsafe_allow_html=True)

# Sidebar

with [Link]:

[Link]("### 📋 Coverage Areas:")

[Link]("""

<div class='sidebar-info'>

<span class='category-badge'> Tenancy Disputes</span>

<span class='category-badge'> Consumer Rights </span>

<span class='category-badge'> Workplace Issues</span>

<span class='category-badge'> Copyright Issues </span>

<span class='category-badge'> Cyber Crime </span>

<span class='category-badge'> Divorce Issues </span>

</div>

""", unsafe_allow_html=True)

[Link]("")

[Link]("### 📞 Emergency Helplines:")

49
[Link]("""

- **Police:** 100

- **Women Helpline:** 1091

- **Consumer Helpline:** 1915

- **Cyber Crime:** 1930

""")

# Clear conversation button

if [Link]("🗑️ Clear Conversation"):

st.session_state.messages = []

st.session_state.conversation_history = []

[Link]()

# Display chat messages

chat_container = [Link]()

with chat_container:

for message in st.session_state.messages:

if message["role"] == "user":

[Link](f"""

50
<div class="message-row" style="justify-content:

flex-end;">

<div class="message user">

{message['content']}

</div>

</div>

""", unsafe_allow_html=True)

else:

[Link](f"""

<div class="message-row" style="justify-content:

flex-start;">

<div class="message assistant">

{message['content']}

</div>

</div>

""", unsafe_allow_html=True)

# Chat input

51
[Link]("---")

# Use chat_input which supports Enter key

user_input = st.chat_input("Type your legal question here and

press Enter...")

# Process the message when user sends it

if user_input:

# Add user message to chat

st.session_state.[Link]({"role": "user",

"content": user_input})

with [Link]("🔍 Analyzing your legal query"):

try:

# Initialize the client

client = InferenceClient(token=HFTOKEN)

# Build conversation history for context

conversation_context = ""

if len(st.session_state.conversation_history) > 0:

52
conversation_context = "\n\n**PREVIOUS

CONVERSATION CONTEXT:**\n"

for msg in

st.session_state.conversation_history[-6:]: # Last 3

exchanges

conversation_context +=

f"{msg['role'].upper()}: {msg['content']}\n"

# Prepare the comprehensive legal prompt with

conversation context

system_prompt = f"""You are an expert Indian legal

advisor AI assistant with comprehensive knowledge of Indian

laws, acts, and legal procedures. Your role is to provide

accurate, helpful, and accessible legal guidance to Indian

citizens.

**CRITICAL INSTRUCTIONS:**

1. NEVER use LaTeX formatting or mathematical symbols

2. Write in clear, plain language that ordinary citizens can

understand

3. Always cite relevant Indian laws, acts, and sections when

applicable

53
4. Provide step-by-step actionable guidance

5. Include relevant helpline numbers and government portals

6. Be empathetic and professional in tone

7. If the query is not legal in nature, politely redirect the

user

8. Maintain conversation context and refer to previous

questions when relevant

9. If user asks follow-up questions, provide additional

details or clarifications based on the conversation history

**SCOPE OF EXPERTISE:**

- Tenancy disputes and Rent Control Acts

- Consumer Protection Act, 2019

- Workplace rights and Labour Laws

- Motor Vehicles Act, 1988 and traffic violations

- Cyber crime and IT Act, 2000

- Family law matters (divorce, maintenance, custody)

- Property disputes and laws

- Civil and criminal procedure basics

- Government complaint mechanisms

54
{conversation_context}

**CURRENT USER QUERY:**

{user_input}

**RESPONSE FORMAT (Use this for NEW questions, adapt for

follow-ups):**

[Summarize the user's problem in 2-3 lines and do not enter

what you are responding to for eg

user wrote: "Hello"

just respond with the summary first and follow the rest dont

specify what you are responding to]

**Applicable Laws:**

[List the relevant Indian laws, acts, and sections that apply

to this situation]

**Your Legal Rights:**

[Clearly explain what rights the user has under Indian law]

55
**Step-by-Step Action Plan:**

**Step 1:** [First action to take]

- Explanation: [Why this step is important]

- Timeline: [Expected timeframe]

**Step 2:** [Second action to take]

- Explanation: [Why this step is important]

- Timeline: [Expected timeframe]

[Continue for all necessary steps]

**Required Documents:**

[List all documents the user needs to gather]

**Where to File/Approach:**

[Specify the exact authority, court, or portal where action

should be taken]

- Portal/Office: [Name and link if applicable]

- Location: [Where to go physically if needed]

56
**Estimated Costs:**

[Provide approximate costs for court fees, stamp duties, etc.

if applicable]

**Important Deadlines:**

[Mention any limitation periods or time-sensitive

requirements]

**Helpline Numbers & Resources:**

[Provide relevant government helplines and official portals]

**Legal Precedents/Judgments (if relevant):**

[Mention any important Supreme Court or High Court judgments

related to this issue]

**Sample Document Template (if applicable):**

[Provide a basic template for complaint letter, notice, or

application if relevant]

**Important Warnings:**

57
[Any pitfalls to avoid or critical considerations]

**Next Steps if This Doesn't Work:**

[Alternative options or escalation paths]

**Recommendation:**

[Final advice including when to consult a lawyer]

---

**Note:** This is general legal information. For specific

legal advice tailored to your exact circumstances, please

consult a qualified lawyer.

**SPECIAL HANDLING:**

- If query is non-legal: Politely inform them this chatbot is

specifically for legal matters under Indian law

- If query requires immediate legal action: Clearly mark as

URGENT and recommend immediate lawyer consultation

- If query involves criminal matters: Advise consulting a

criminal lawyer and provide police contact

58
- If information is insufficient: Ask specific clarifying

questions

- For follow-up questions: Provide direct, concise answers

that build on previous context

Provide your response now:"""

messages = [{"role": "user", "content":

system_prompt}]

# List of models to try (in order of preference)

models_to_try = [

"deepseek-ai/DeepSeek-V3-0324",

"Qwen/Qwen2.5-7B-Instruct",

"meta-llama/Llama-3.2-3B-Instruct",

success = False

for model in models_to_try:

try:

59
response = client.chat_completion(

messages=messages,

model=model,

max_tokens=2500,

answer =

[Link][0].[Link]

success = True

# Add assistant response to chat

st.session_state.[Link]({"role":

"assistant", "content": answer})

# Update conversation history

st.session_state.conversation_history.append({"role": "user",

"content": user_input})

save_message("user", user_input)

60
st.session_state.conversation_history.append({"role":

"assistant", "content": answer})

save_message("assistant", answer)

# Rerun to display the new message

[Link]()

break

except Exception as e:

continue

if not success:

error_message = "❌ Unable to generate response

at the moment. Please try again in a few moments or rephrase

your question."

st.session_state.[Link]({"role":

"assistant", "content": error_message})

[Link]()

except Exception as e:

error_message = f"❌ An error occurred: {str(e)

[:100]}"

st.session_state.[Link]({"role":

"assistant", "content": error_message})

61
[Link]()

# Show helpful tips if no conversation yet

if len(st.session_state.messages) == 0:

[Link]("""

👋 **Welcome to the Legal Advice Chatbot!**

Start by asking a legal question. You can:

- Ask about your rights in any situation

- Request step-by-step guidance for legal procedures

- Ask follow-up questions to get more details

- Request document templates or complaint formats

Just type your question below and press **Enter** to

begin!

""")

# Footer

62
Project Interface

63
Project Working

64
65
66
4. CONCLUSION AND FUTURE SCOPE

4.1 Conclusion

The LawPilot project successfully demonstrates the potential of artificial intelligence to rev-

olutionize the legal consulting domain. By integrating a user-friendly interface with a legal

knowledge base (implemented via [Link]), the project achieves the following:

· Democratization of Law: It bridges the gap between complex legal terminology and

the common user, making legal information more accessible and affordable to the

general public.

· 24/7 Availability: The bot functions as a virtual assistant available round-the-clock to

answer queries regarding rights, laws (e.g., IPC sections), and legal procedures.

· Initial Guidance: While not a replacement for a human lawyer, it effectively handles

preliminary legal inquiries, allowing users to understand their situation before seeking

professional counsel.

· Efficiency: It reduces the time and effort required for basic legal research, benefiting

both laypeople and legal professionals.

4.2 Future Scope

The project has significant potential for expansion and technical enhancement. The following

areas represent the future trajectory of the LawPilot:

67
1. Integration of Large Language Models (LLMs):

o Moving beyond rule-based or retrieval-based responses to utilize advanced

LLMs (like GPT) can improve the bot's ability to understand context, handle

nuanced queries, and generate more human-like explanations.

2. Legal Document Drafting & Review:

o The system can be upgraded to assist users in drafting legal documents such

as wills, lease agreements, and affidavits by guiding them through a structured

questionnaire.

o It could also offer automated review services for simple contracts (e.g., NDAs)

to highlight potential risks.

3. Multilingual Support:

o To truly democratize access in diverse regions (especially India), the bot

should support regional languages, allowing users to interact in their native

tongue.

4. Voice-Enabled Interaction:

o Implementing Speech-to-Text and Text-to-Speech capabilities will make the

application accessible to users with lower literacy rates or visual impairments.

5. Real-Time Lawyer Connection:

o The platform can be expanded to include a robust booking and referral sys-

tem, connecting users directly with specialized lawyers (Criminal, Civil, Cor-

porate) based on their specific case details and location.

68
6. Jurisdictional Expansion:

o Currently focused on specific laws (e.g., Indian Penal Code), the knowledge

base can be expanded to cover international law, corporate compliance, and

taxation laws to serve a broader audience.

69
5. REFERENCES

1. Python Software Foundation – Python Programming Language

Python documentation.

Available at: [Link]

2. OpenAI – Natural Language Processing Models (if used for legal text processing)

Available at: [Link]

3. spaCy – Industrial-strength NLP Library in Python (if used/required for future de-

velopment)

Available at: [Link]

4. HuggingFace – Legal/BERT NLP Models (optional for future upgrades)

Available at: [Link]

5. Blackstone NLP – Legal-domain NLP Toolkit (recommended for legal AI extensions)

Available at: [Link]

6. IEEE – Ethical Considerations in Legal AI Systems

IEEE Global Initiative on Ethics of Autonomous and Intelligent Systems.

Available at: [Link]

70

You might also like