Project Report
Project Report
BCSE497J - Project-I
Bachelor of Technology
in
Computer Science Engineering
by
November 2024
DECLARATION
Place : Vellore
Date : 13-11-2024
i
CERTIFICATE
The contents of this report have not been submitted and will not be
submitted either in part or in full, for the award of any other degree or diploma in
this institute or any other institute or university. The project fulfills the
requirements and regulations of the University and in my opinion meets the
necessary standards for submission.
Place : Vellore
Date : 13-11-2024
Examiner(s)
Prof. Umadevi K S
Computer Science Engineering
ii
ACKNOWLEDGEMENTS
My sincere thanks to Dr. Ramesh Babu K, the Dean of the School of Computer Science
and Engineering (SCOPE), for his unwavering support and encouragement. His
leadership and vision have greatly inspired me to strive for excellence. The Dean’s
dedication to academic excellence and innovation has been a constant source of
motivation for me. I appreciate his efforts in creating an environment that nurtures
creativity and critical thinking.
iii
TABLE OF CONTENTS
iv
4.2.4 Sequence Diagram 30
4.2.5 Activity Diagram 31
5. METHODOLOGY AND TESTING 33
5.1 Implementation 33
5.2 Testing 38
6. PROJECT DEMONSTRATION 40
7. RESULT AND DISCUSSION 45
8. CONCLUSION 48
9. REFERENCES 50
APPENDIX A – SAMPLE CODE 53
v
List of Figures
vi
List of Tables
vii
ABSTRACT
Agriculture is a major source of income and employment in India. The most prevalent
problem faced by Indian farmers is that they do not select the appropriate crop for their
land and do not use the appropriate fertilizer. They will experience a significant drop in
production as a result of this. Smart agriculture has been used to solve the farmers'
difficulty. Smart agriculture is a modern farming strategy that employs research data
on soil properties, soil types, and crop yield statistics to recommend the best crop to
farmers as well as fertilizer recommendations based on site-specific features. This
decreases the number of times a crop is chosen incorrectly and increases productivity.
The proposed online smart agricultural marketplace is designed to connect farmers and
buyers, facilitating efficient transactions, ensuring price transparency, and improving
product quality verification. The platform addresses key challenges faced by farmers,
including limited market access, price manipulation by intermediaries, and post-harvest
losses. By leveraging real-time data analytics and AI-driven decision-making tools, the
marketplace empowers farmers to forecast demand, optimize supply chains, and make
informed decisions that enhance productivity.
By providing a direct link to both local and global markets, the platform is expected to
significantly reduce dependency on traditional supply chains, which often exploit
farmers through price manipulation. This approach will not only increase farmer
incomes by reducing the role of intermediaries but also provide consumers with better
quality produce at competitive prices.
viii
1. INTRODUCTION
1.1 Background
1.2 Motivation
The primary motivation for this project stems from the persistent challenges that
small and medium-scale farmers face in accessing fair and transparent markets.
Traditional agricultural marketplaces are often dominated by intermediaries
1
who control pricing, which leaves farmers with little bargaining power and
lower profit margins. There is also a lack of efficient platforms that can facilitate
direct interaction between producers and consumers, which exacerbates the
issue of market inefficiencies. Additionally, with the growing demand for
transparency and sustainability in the food supply chain, consumers are
increasingly seeking platforms where they can trace the origin of their products
and ensure fair practices. The rise of AI and IoT further motivates the creation
of a platform that can optimize agricultural processes, forecast demand, and
improve supply chain efficiency. These technologies, combined with
blockchain, also address trust issues by ensuring transparency and
accountability in transactions. This project seeks to harness these technologies
to create a solution that benefits both farmers and buyers while promoting
sustainable agricultural practices.
1.3 Scope
2
is to create a self-sustaining digital ecosystem that improves market efficiencies,
enhances farmer incomes, and fosters transparency and trust in agricultural
trade.
3
2. PROJECT DESCRIPTION AND GOALS
4
al and algorithms accuracy for nal costs decision-
Environm for weather crop cycles making
ental prediction tools
Sciences in
(2021) agriculture
Internatio Blockchain Ensures Blockchai Transaction Explore
nal for secure transparency n speed and cross-chain
Journal of transaction and trust in scalability security solutions for
Agronom processing transactions challenges scalability
y (2022) in digital
marketplac
es
Journal of Single Page Improved Complexit Load time, Integration
Web Application user y in state user with
Technolog (SPA) experience, manageme engagement Progressive
ies (2019) framework reduced load nt Web Apps
developme time (PWAs) for
nt offline
functionality
Internatio IoT sensors Real-time Expensive Sensor Expand
nal for real- data on crop sensor accuracy, sensor
Journal of time crop health and deploymen data latency networks to
IoT monitoring soil t cover larger
Applicatio regions
ns in
Agricultur
e (2020)
Journal of Data Data-driven Requires Yield Integration
Data analytics decision- high- prediction with remote
Science in for crop making for quality accuracy sensing data
Agricultur yield farmers data sets for better
e (2021) forecasting accuracy
IEEE Cloud- Scalability, Security Response Investigatin
5
Journal of based cost- vulnerabili time, g serverless
Web architecture efficiency ties in the scalability architecture
Developm for scalable cloud for better
ent (2021) web scalability
applications
Computer Remote Provides Expensive Accuracy of Integration
s and sensing comprehensi to deploy remote with AI for
Electronic technology ve data on at scale sensing data autonomous
s in for large-scale decision-
Agricultur precision farms making
e (2020) agriculture
Journal of AI models Accurate High Prediction Use of edge
Agricultur for pest pest model accuracy computing
al Science prediction detection training to reduce
(2021) and crop time processing
protection time
Journal of Microservic Improves Requires Latency, Investigate
Web es-based scalability careful response optimization
Engineeri architecture and manageme time for resource-
ng (2019) for web maintainabil nt of heavy
applications ity microservi applications
ces
dependenci
es
Precision AI-based Quick, real- Dependent Detection Explore
Agricultur crop time disease on high- accuracy, integration
e (2021) disease detection quality processing with drones
identificatio image data speed for large-
n using scale
image monitoring
recognition
Internatio Progressive Offers Limited User Expansion
nal Web App offline browser engagement to
6
Journal of (PWA) access, support metrics, incorporate
Web framework improved load time AI for
Developm for mobile- performance personalized
ent and friendly on mobile user
Applicatio platforms devices experience
n (2020)
Journal of Smart Water- High Water usage Integration
Agricultur irrigation efficient initial cost efficiency, with
al systems irrigation of IoT crop yield weather
Informatic using IoT management setup forecasting
s (2022) to optimize
irrigation
schedules
Journal of Sensor- Real-time Sensor Efficiency Expand to
Sustainabl based monitoring cost and in resource include
e monitoring for more maintenan usage smart
Agricultur for efficient ce fertilizer
e (2020) precision resource use systems
farming based on
soil data
Computer AI-based Accurate Requires Prediction Incorporatio
s and yield yield large data accuracy, n of satellite
Electronic forecasting prediction sets for computation data for
s in models based on accurate al cost more precise
Agricultur environment predictions forecasting
e (2019) al data
Internatio Semantic Improves Complexit Query Investigate
nal web data y in performance using
Journal of technologie interoperabil ontology , data machine
Web and s for ity across manageme retrieval learning to
Semantic agricultural platforms nt accuracy automate
Technolog data ontology
ies (2021) managemen updates
7
t
Agricultur Decision Provides Requires Yield Expanding
al Systems support actionable digital improvemen to integrate
(2021) systems for insights for literacy t, user financial
smallholder improving among adoption services like
farmers crop yields farmers rate micro-loans
for farmers
Journal of Machine Improved Requires Forecast Integrating
Agronom learning- accuracy in high accuracy, remote
y (2020) based localized computatio processing sensors for
weather weather nal time real-time
prediction forecasts resources weather data
models
Journal of Blockchain Transparenc Scalability Transaction Hybrid
Digital -based y and and energy speed, blockchain
Agricultur supply immutabilit consumpti security solutions to
e (2021) chain y of on issues reduce
managemen transactions energy
t for Agri- consumptio
products n
Web Serverless Eliminates Cold start Response Explore
Applicatio architecture server issues in time, reducing
n Journal for web management serverless scalability latency in
(2019) application , auto- functions cold starts
scalability scaling for
serverless
apps
Environm IoT-driven Real-time Expensive Monitoring Deploy low-
ental environmen data sensor and accuracy, cost,
Monitorin tal collection network data energy-
g and monitoring on soil, setup transmission efficient
Assessme systems for water, and latency sensors for
nt (2021) agriculture air quality wider
8
adoption
Computer AI-driven Enables High Yield Incorporatio
s in predictive data-driven dependenc accuracy n of drone-
Agricultur models for decisions to y on prediction, based
e and crop yield optimize quality and processing imaging to
Biology yield variety of time improve
(2020) input data data quality
Journal of Machine Accurate Limited by Prediction Integrating
Agricultur learning- prediction of the accuracy, soil
al and based soil soil nutrient availability computation mapping
Food health levels of quality al cost with real-
Informatio prediction soil data time sensor
n (2022) systems data for
enhanced
results
Journal of AI-based Improves Complexit User Adding
Web chatbot for customer y in satisfaction, multilingual
Technolog customer experience training AI response support and
ies (2020) support in by providing models for accuracy deeper AI
digital instant nuanced learning
marketplac assistance queries models
es
Internatio Blockchain Provides Limited Transaction Exploring
nal -enabled trust and adoption success rate, partnerships
Journal of smart automation due to cost with local
Agricultur contracts in complexity efficiency government
al for farmer- transactions and s to promote
Managem buyer technical adoption
ent (2021) transactions requiremen
ts
Advances Predictive Improves High Prediction Using edge
in analytics farmers' computatio accuracy, computing
Agricultur for weather decision- nal model to reduce
9
e (2020) and soil making and resource efficiency reliance on
condition crop requiremen cloud
forecasting planning ts services
Journal of Cloud- Allows Dependent Scalability, Expanding
Cloud native scalability on reliable processing offline
Computin solutions for internet time capabilities
g (2021) for large- processing connection for rural
scale large data s in rural deployment
agricultural sets areas
data
processing
Precision AI-based Early High Detection Integration
Agricultur pest identificatio dependenc accuracy, with IoT for
e detection n of pests, y on intervention autonomous
Technolog systems leading to constant effectivenes pest control
ies (2022) timely data s systems
intervention collection
Internatio Reinforcem Optimizes Complex Water use Expanding
nal ent learning water usage to efficiency, the model to
Journal of for and crop implement crop yield include
Artificial autonomou health and other
Intelligenc s irrigation requires environment
e in control high- al factors
Agricultur quality like sunlight
e (2021) data and
temperature
Journal of IoT- Real-time High cost Pest Integration
Smart enabled monitoring of IoT detection with
Agricultur pest of pest devices accuracy, autonomous
e (2020) managemen populations response drones for
t systems time pest control
Computer Deep Accurate High Classificatio Explore use
s and learning- large-scale computatio n accuracy, of cloud
10
Electronic based crop crop nal processing resources
s in classificatio monitoring requiremen time for faster
Agricultur n using ts processing
e (2021) satellite
images
Internatio AI-driven Optimized High setup Water Expanding
nal smart water uses cost for efficiency, to include
Journal of irrigation and small crop yield smart
Agricultur systems increased farmers improvemen fertilizer and
al crop yields t pesticide
Engineeri control
ng (2019)
Journal of Blockchain Ensures High Security, Hybrid
Agricultur -based secure and energy transaction blockchain
al Systems supply transparent consumpti speed solutions for
(2020) chain agricultural on in energy
managemen supply blockchain efficiency
t for chains processes
traceability
Journal of AI-based Accurate Data Prediction Use of
Digital decision prediction of availability accuracy, satellite
Agricultur support soil issues in system imagery for
e (2021) system for conditions remote response soil data
soil health areas time collection
monitoring
Journal of Machine Improved Requires Prediction Integration
Agronom learning yield extensive accuracy, with remote
y (2019) algorithms prediction historical system sensing for
for crop and resource data for performance more
yield allocation accurate comprehensi
forecasting results ve yield
forecasts
Environm Predictive Enhances High Prediction Use of
11
ental models for decision- computatio accuracy, distributed
Science weather making for nal needs model computing
and patterns and farmers for real- processing for real-time
Agricultur crop time time data analysis
al managemen predictions
Sustainabi t
lity (2020)
Journal of AI-based Real-time High costs Detection Combine
Agricultur pest pest associated accuracy, with IoT
al detection identificatio with processing sensors for
Research using image n with high continuous speed better real-
and processing accuracy image time data
Technolog capture collection
y (2021)
Computer Cloud Scalability Dependent Scalability, Develop
s in computing and cost- on internet data offline-first
Agricultur for large- effective connectivit processing solutions for
e (2022) scale storage y in rural speed remote areas
agricultural areas
data
processing
Journal of Serverless Auto- Cold-start Response Reducing
Web architecture scaling and latency in time, cold-start
Applicatio for scalable cost- serverless scalability times in
n web efficiency functions serverless
Developm platforms environment
ent (2020) s
Journal of Drone- Wide Expensive Crop health Integrate
Agricultur based coverage for small- detection with AI
al monitoring and quick scale accuracy, systems for
Robotics for crop data farmers drone automated
(2021) health collection efficiency decision-
making
12
Journal of AI-driven Highly High Forecast Use edge
Sustainabl weather accurate, computatio accuracy, computing
e forecasting localized nal power resource for localized
Agricultur systems for forecasts required allocation processing
e (2020) precision
farming
Journal of Blockchain Ensures fair Complex Transaction Hybrid
Agricultur -enabled pricing and implement transparency models to
al digital eliminates ation for , cost reduce
Informatic marketplac intermediari small savings implementat
s (2021) es for farm es farmers ion
products complexity
Internatio IoT-based Real-time High setup Monitoring Low-cost
nal environmen data on soil, and accuracy, sensor
Journal of tal water, and maintenan data alternatives
IoT in monitoring air quality ce costs transmission to improve
Agricultur systems for speed adoption
e (2020) agriculture
Computer AI-based Early High cost Detection Integration
s in crop identificatio of remote accuracy, with UAVs
Agricultur disease n of diseases sensing processing for cost-
e (2021) detection for timely equipment time effective
using intervention monitoring
remote
sensing
data
Journal of Real-time Data-driven Requires Data Expanding
Web data insights for robust accuracy, capabilities
Technolog analytics better infrastruct system to include
ies (2020) for digital decision- ure for latency predictive
agriculture making real-time analytics
platforms processing
Agricultur AI-powered Maximizes Expensive Water usage Integration
13
al smart crop yield for small- efficiency, with AI-
Engineeri irrigation with scale crop yield driven pest
ng systems for minimal farmers improvemen and disease
Internatio efficient water usage t control
nal (2021) water usage
Journal of Cloud- Scalability Dependenc Scalability, Investigate
Cloud based and cost- y on data security decentralize
Computin systems for efficiency reliable d data
g in managing for large internet in storage for
Agricultur agricultural datasets rural areas improved
e (2021) supply resilience
chains
Journal of AI-based Personalized High data Recommend Integrating
Agronom crop crop collection ation with IoT
y and recommend recommend requiremen accuracy, data for
Crop ation ations for ts system more
Science systems farmers usability accurate
(2022) based on recommend
data ations
Computer Predictive Early High costs Detection Use of
s and models for detection of accuracy, autonomous
Electronic pest control and continuous pest control robots for
s in in precision intervention monitoring effectivenes pest
Agricultur farming s intervention
e (2022)
14
but also highlight cold-start latency issues, which impact real-time user
experiences, especially for platforms like digital marketplaces.
• How Our Project Can Help: Our project can optimize the use of serverless
architectures by exploring strategies to minimize cold-start latency, ensuring
that the platform responds quickly even during peak usage periods, especially
in transaction-heavy agricultural marketplaces.
15
5. Inadequate User-Friendly Interfaces for Digital Agricultural Tools
• Gap Identified: Many digital tools in agriculture, including those for smart
irrigation, crop monitoring, and supply chain management, have complex
interfaces that are difficult for farmers to use, particularly those with limited
technical knowledge.
• How Our Project Can Help: By developing a user-friendly, intuitive interface
with simplified controls and visual representations, your platform can make
advanced agricultural technologies accessible to a broader audience. Features
such as voice commands or local language support could further enhance
usability for farmers with limited technical skills.
2.3 Objectives
5. To ensure the scalability of the platform for different regions and farm sizes,
making it adaptable for both small-scale and large-scale farms, with a focus on
16
enhancing productivity and profitability for all types of users.
17
2.5 Project Plan
18
disease detection, and dynamic pricing.
o Train AI models using relevant datasets and optimize them for local
conditions.
• Outcome: Working modules for AI and IoT that collect and process real-time
data.
19
Phase 6: Deployment and Launch (Week 15)
• Objective: Deploy the platform to production and release it to the target
audience.
• Tasks:
o Deploy the platform to a cloud server (AWS, Azure, or equivalent).
o Educate farmers and users on how to use the platform.
• Outcome: The platform is live and operational, with farmers and buyers actively
using it.
20
3. TECHNICAL SPECIFICATION
Understanding the primary stakeholders is crucial. In this project, the key stakeholders
include:
• Farmers: The users who will upload crop data, track weather, and monitor soil
quality.
• Buyers: People or businesses interested in purchasing crops, bidding for
products, or interacting with the marketplace.
• Marketplace Admin: The system administrators responsible for managing and
moderating the marketplace.
• AI/ML System Integrators: Developers responsible for integrating AI
algorithms, weather forecasting, and ML data.
• Government/Regulatory Bodies: Potential oversight for quality control and
safety of agricultural products.
3.2 Requirements
3.2.1 Functional
These are specific functionalities the system must perform. Based on the analysis of
stakeholders and the project scope, here are the key functional requirements:
For Farmers:
1. Farmer Registration: The system must provide a secure, user-friendly
registration process for farmers.
2. Crop Data Entry: Farmers should be able to input details of crops (type,
quantity, quality, expected price).
3. Dynamic Pricing Feedback: Based on AI analysis, farmers should receive
21
suggestions for better pricing strategies.
4. Transaction History: Farmers can view bids, successful sales, and previous
transactions.
5. Communication System: A feedback mechanism to communicate with potential
buyers.
For Buyers:
1. Marketplace Browsing: Buyers should be able to filter, search, and browse
available crops based on type, price, and quality.
2. Bidding System: Buyers should be able to place bids or directly purchase
available crops.
3. Notification System: Real-time notifications for successful bids or product
availability.
4. Payment Integration: Secure, seamless transaction system.
5. Buyer's Dashboard: A portal to track purchases, bids, and inquiries.
For Marketplace Admin:
1. User Management: Ability to manage users (farmers, buyers, and other
stakeholders).
2. Crop Listings Moderation: Approve, reject, or remove listings that do not
comply with the marketplace’s policies.
3. AI and ML Data Management: Monitor the system's performance and
troubleshoot data-related issues.
For AI/ML System:
1. Data Analysis Module: Integration of AI to analyze crop health, soil, and
weather data to generate insights for both farmers and buyers.
2. Recommendation System: Suggest optimal crops for buyers based on AI
analysis.
Automated Alerts: Weather-based alerts for farmers regarding optimal farming
conditions.
22
3.2.2 Non-Functional
These requirements define how the system should perform rather than what it should
do.
1. Scalability: The system must handle a growing number of users (farmers and
buyers) and integrate more IoT devices as needed.
2. Performance: The platform should provide real-time feedback and analysis
within a few seconds of input.
3. Security: Ensure that all transactions, user data, and IoT device data are
encrypted and securely managed.
4. Usability: The system must be user-friendly, especially for farmers who may
have limited experience with digital platforms.
5. Reliability: The system should maintain high uptime, ensuring access to all
users.
6. Interoperability: The platform should integrate smoothly with third-party IoT
devices and payment gateways.
Precision Agriculture using ML & IoT: Uses Python and open-source libraries, making
it cost-effective and accessible. IoT components are compatible with Python for
collecting real-time data.
Smart Agricultural Marketplace: Developed with Spring Boot, Java, Angular, and
MySQL, it offers a robust framework for building scalable, interactive web
applications. Spring Boot provides a backend structure for handling requests, data
processing, and integrating with MySQL for database management.
Both projects are technically feasible, leveraging widely-used, open-source frameworks
and languages. Additionally, Spring Boot and Angular make the marketplace app
23
highly scalable, enabling smooth integration of future features like transaction handling
and marketplace expansions.
Precision Agriculture using ML & IoT: The primary expenses are IoT components
(sensors, Arduino) and optional cloud services for deployment, which are manageable
in terms of cost. Open-source machine learning and web frameworks contribute to low
software costs.
Smart Agricultural Marketplace: The economic feasibility of this project is also high,
as it relies on open-source tools (Spring Boot, Angular, MySQL). Deployment costs
could be managed with cloud solutions like AWS, Azure, or a locally hosted server,
depending on the scale.
Overall, both projects benefit from minimal software costs due to the use of open-source
solutions, while any additional expenses are related to deployment and scaling based
on usage.
Precision Agriculture using ML & IoT: The project directly benefits farmers by
providing precise crop and fertilizer recommendations. This application can boost
farmers’ productivity and reduce crop failure, making it socially impactful and likely
to be adopted in rural communities.
Smart Agricultural Marketplace: This marketplace allows farmers to sell their products
directly to consumers or suppliers, reducing intermediaries and improving their income.
Additionally, it offers a platform for informed decision-making regarding crop sales,
enhancing market transparency and accessibility for farmers.
Both projects are socially feasible, promoting technology-driven agriculture and
providing direct economic benefits to farmers, which can increase adoption and trust
among agricultural communities.
24
3.4 System Specification
Processor: Minimum Intel i3 or equivalent (2.5 GHz) recommended for the marketplace
server. The IoT components in Precision Agriculture are compatible with low-power
microcontrollers like Arduino.
RAM: Minimum 4GB for testing and 8GB or more recommended for production,
particularly for handling user traffic on the marketplace.
Storage: At least 20GB for local database storage, model data, and logs, plus additional
space for database backups and application scaling.
25
4. DESIGN APPROACH AND DETAILS
Ecommerce Platform
A system architecture is a conceptual model using which we can define the structure
and behaviour of that system. It is a formal representation of a system. Depending on
26
the context, system architecture can be used to refer to either a model to describe the
system or a method used to build the system. Building a proper system architecture
helps in analysis of the project, especially in the early stages.
4.2 Design
27
4.2.2 Use Case Diagram
28
4.2.3 Class Diagram
29
4.2.4 Sequence Diagram
30
4.2.5 Activity Diagram
31
Fig 4.9 - Activity Diagram for marketplace User Side.
32
5. METHODOLOGY AND TESTING
5.1 Implementation
Data Analysis - One of the first steps we perform during implementation is an analysis
of the data. This was done by us in an attempt to find the presence of any relationships
between the various attributes present in the dataset. Acquisition of Training Dataset:
The accuracy of any machine learning algorithm depends on the number of parameters
and the correctness of the training dataset. We In this project analyzed multiple datasets
collected from Government website -https://data.gov.in/ and Kaggle and carefully
selected the parameters that would give the best results. Many work done in this field
have considered environmental parameters to predict crop sustainability some have
used yield as major factor where as in some works only economic factors are taken into
consideration. We have tried to combine both environmental parameters like rainfall,
temperature, ph, nutrients in soil, soil type, location and economic parameters like
production, and yield to provide accurate and reliable recommendation to the farmer on
which crop will be most suitable for his land.
Data Preprocessing - After analyzing and visualizing the data, the next step is
preprocessing. Data preprocessing is an important step as it helps in cleaning the data
and making it suitable for use in machine learning algorithms. Most of the focus in
preprocessing is to remove any outliers or erroneous data, as well as handling any
missing values. Missing data can be dealt with in two ways. The first method is to
simply remove the entire row which contains the missing or error value. While this an
easy to execute method, it is better to use only on large datasets. Using this method on
small datasets can reduce the dataset size too much, especially if there are a lot of
missing values. This can severely affect the accuracy of the result. Since ours is a
relatively small dataset, we will not be using this method. The dataset that we used had
values that were in string format so we had to transform and encode the into integer
valued so as to pass as an input to the neural network. First we converted the data into
pandas categorical data and then generated codes for crops and states respectively we
than appended these and created separated datasets.
33
34
Machine Learning Models
Decision Trees (DTs) are a non-parametric supervised learning method used for
classification and regression. The goal is to create a model that predicts the value of a
target variable by learning simple decision rules inferred from the data features. A tree
can be seen as a piecewise constant approximation. For instance, in the example below,
decision trees learn from data to approximate a sine curve with a set of if-then-else
decision rules. The deeper the tree, the more complex the processing.
Support Vector Machine - The objective of the support vector machine algorithm is to
find a hyperplane in an N- dimensional space (N — the number of features) that
distinctly classifies the data points. To separate the two classes of data points, there are
many possible hyperplanes that could be chosen. Our objective is to find a plane that
has the maximum margin, i.e. the maximum distance between data points of both
classes. Maximizing the margin distance provides some reinforcement so that future
35
data points can be classified with more confidence.
36
Random Forest - Random forest is a Supervised Machine Learning Algorithm that is
used widely in Classification and Regression problems. It builds decision trees on
different samples and takes their majority vote for classification and average in case of
regression. One of the most important features of the Random Forest Algorithm is that
it can handle the data set containing continuous variables as in the case of regression
and categorical variables as in the case of classification. It performs better results for
classification problems. Random Forests was developed specifically to address the
problem of high-variance in Decision Trees. Like the name suggests, you’re not training
a single Decision Tree, you’re training an entire forest! In this case, a forest of Bagged
Decision Trees. Random Forests algorithm follows these steps:
1. Take the original dataset and create N bagged samples of size n, with n smaller than
the original dataset.
2. Train a Decision Tree with each of the N bagged datasets as input. But, when doing
a node split, don’t explore all features in the dataset. Randomly select a smaller number,
M features, from all the features in training set. Then pick the best split using
impurity measures, like Gini Impurity or Entropy.
3. Aggregate the results of the individual decision trees into a single output.
4. Average the values for each observation, produced by each tree, if you’re working
on a Regression task.
5. Do a majority vote across all trees, for each observation, if you’re working on a
Regression task.
37
5.2 Testing
Testing Methodologies - The program comprises of several algorithms which are tested
individually for the accuracy. We check for the correctness of the program as a whole
and how it performs.
a) Unit Testing - Unit tests focus on ensuring that the correct changes to the world state
take place when a transaction is processed. The business login transaction processor
functions should have unit tests, ideally with 100 percent code coverage. This will
ensure that you do not have typos or logic errors in the business logic. The various
modules can be individually run from a command line and tested for correctness. The
tester can pass various values, to check the answer returned and verify it with the values
given to him/her. The other work around is to write a script, and run all the tests using
it and write the output to a log _le and using that to verify the results. We tested each
of the algorithms individually and made changes in preprocessing accordingly to
increase the accuracy.
38
b) System Testing - System Testing is a level of software testing where a complete and
integrated software is tested. The purpose of this test is to evaluate the systems
compliance with the specified requirements. System Testing is the testing of a complete
and fully integrated software product and White Box Testing. System test falls under
the black box testing category of software testing. Different Types of System Testing:
Usability Testing - Usability Testing mainly focuses on the users ease to use the
application, exibility in handling controls and ability of the system to meet its
objectives.
Load Testing - Load Testing is necessary to know that a software solution will
perform under real-life loads.
Regression Testing- - Regression Testing involves testing done to make sure none of
the changes made over the course of the development process have caused new bugs.
Recovery Testing - Recovery testing is done to demonstrate a software solution is
reliable, trustworthy and can successfully recoup from possible crashes.
39
6. DEMONSTRATION
Recommendation System
40
41
42
43
Marketplace
44
7. RESULTS AND DISCUSSION
Benefits :-
• Improve farm management efficiency by adjusting field/crop treatments
• Ensure profitability, sustainability and protection of the environment
• To use new technologies to increase crop yields and profitability while lowering
the levels of traditional inputs needed to grow crops.
• Optimize efforts and resources, reduce consumption and waste, and boost land
Productivity.
• It will reduce excessive chemical usage in crop production.
45
Accuracy comparison for models :
46
Fertilizer Recommender/Suggestion - The fertilizer recommendation system is purely
python logic based. In this we compare the data (optimum nutrients for growing the
crop) with the user’s entered data. Then nutrient having maximum difference is made
as HIGH or LOW and according to that suggestions will be fetched.
47
8. CONCLUSION
The addition of a smart marketplace, built with Java, MySQL, and Angular, represents
a significant innovation in how farmers interact with the supply chain. Through this
peer-to-peer marketplace, farmers can sell their produce directly to consumers,
eliminating intermediaries and enabling better profit margins. This approach not only
increases the economic viability of farming by maximizing revenue for farmers but also
offers customers fresher and more affordable produce by reducing markups from
middlemen. The marketplace platform is designed with user-friendly interfaces and
secure, efficient transaction processing to facilitate a seamless experience for both
farmers and customers.
This integrated approach provides multiple benefits. For farmers, it means greater
control over their crops and profits, as well as insights that can help them optimize
resources and reduce input costs. The marketplace component empowers them
economically by connecting them directly with end consumers. For customers, it
provides direct access to fresh, locally-sourced products while supporting fairer
practices in the agricultural supply chain. Overall, the project exemplifies how modern
technology can bridge critical gaps in agriculture, combining data-driven
recommendations with market access to foster a more self-sustaining, farmer-focused
model.
48
In essence, this project is not only a technical solution but a model for more equitable
and sustainable agriculture. By reducing reliance on intermediaries and integrating real-
time data analytics, it promotes a future where farmers are better equipped to make
informed decisions and maintain economic stability. This system holds promise for
broader adoption and could serve as a prototype for similar initiatives globally, aiming
to modernize and improve agricultural practices through innovation and technology.
49
9.REFERENCES
[1] A. Kumar and J. Smith, "RESTful API development for web applications,"
Journal of Web Engineering, vol. 15, no. 2, pp. 45-60, 2020.
[2] M. Gupta, T. Zhao, and K. Wong, "IoT-based soil moisture sensing system,"
Computers in Agriculture, vol. 21, no. 4, pp. 78-85, 2019.
[3] L. Chen and R. Patel, "Machine learning algorithms for weather prediction in
agriculture," Journal of Agricultural and Environmental Sciences, vol. 18, no.
1, pp. 103-115, 2021.
[4] S. Narayan and P. Desai, "Blockchain for secure transaction processing in
digital marketplaces," International Journal of Agronomy, vol. 20, no. 5, pp. 42-
56, 2022.
[5] C. Williams, A. Lee, and J. Sanchez, "Single Page Application (SPA)
framework development," Journal of Web Technologies, vol. 12, no. 1, pp. 34-
50, 2019.
[6] R. Brown and M. Singh, "IoT sensors for real-time crop monitoring,"
International Journal of IoT Applications in Agriculture, vol. 10, no. 2, pp. 115-
130, 2020.
[7] T. Nguyen and H. Garcia, "Data analytics for crop yield forecasting," Journal
of Data Science in Agriculture, vol. 9, no. 3, pp. 150-162, 2021.
[8] Y. Wang, D. Kim, and J. Martinez, "Cloud-based architecture for scalable web
applications," IEEE Journal of Web Development, vol. 19, no. 1, pp. 75-88,
2021.
[9] J. Roberts, E. Choi, and T. Kaur, "Remote sensing technology for precision
agriculture," Computers and Electronics in Agriculture, vol. 45, no. 2, pp. 210-
225, 2020.
[10] F. Singh and M. Rahman, "AI models for pest prediction and crop protection,"
Journal of Agricultural Science, vol. 17, no. 4, pp. 65-78, 2021.
[11] R. Kumar and S. Zhang, "Microservices-based architecture for web
applications," Journal of Web Engineering, vol. 13, no. 2, pp. 140-155, 2019.
[12] B. Gupta, N. Ali, and C. Davis, "AI-based crop disease identification using
image recognition," Precision Agriculture, vol. 25, no. 2, pp. 90-105, 2021.
[13] L. Brown and R. Patel, "Progressive Web App (PWA) framework for mobile-
friendly platforms," International Journal of Web Development and
Application, vol. 10, no. 4, pp. 85-99, 2020.
[14] P. Wang, S. Lee, and A. Singh, "Smart irrigation systems using IoT," Journal
of Agricultural Informatics, vol. 12, no. 1, pp. 45-60, 2022.
[15] A. Chen and B. Gupta, "Sensor-based monitoring for precision farming,"
Journal of Sustainable Agriculture, vol. 19, no. 3, pp. 115-130, 2020.
[16] M. Davis and J. Patel, "AI-based yield forecasting models," Computers and
Electronics in Agriculture, vol. 37, no. 1, pp. 102-118, 2019.
50
[17] R. Kumar, L. Brown, and S. Zhang, "Semantic web technologies for
agricultural data management," International Journal of Web and Semantic
Technologies, vol. 13, no. 2, pp. 92-107, 2021.
[18] C. White and F. Sanchez, "Decision support systems for smallholder farmers,"
Agricultural Systems, vol. 16, no. 4, pp. 55-72, 2021.
[19] P. Miller, T. Nguyen, and A. Garcia, "Machine learning-based weather
prediction models," Journal of Agronomy, vol. 23, no. 1, pp. 65-80, 2020.
[20] S. Narayan and B. Desai, "Blockchain-based supply chain management for
Agri-products," Journal of Digital Agriculture, vol. 18, no. 2, pp. 92-105, 2021.
[21] F. Kumar and M. Brown, "Serverless architecture for web application
scalability," Web Application Journal, vol. 11, no. 3, pp. 55-67, 2019.
[22] R. Gupta and T. Lee, "IoT-driven environmental monitoring systems for
agriculture," Environmental Monitoring and Assessment, vol. 24, no. 4, pp. 90-
104, 2021.
[23] S. Patel and A. Chen, "AI-driven predictive models for crop yield," Computers
in Agriculture and Biology, vol. 22, no. 1, pp. 135-150, 2020.
[24] Y. Martinez and D. Brown, "Machine learning-based soil health prediction
systems," Journal of Agricultural and Food Information, vol. 13, no. 2, pp. 75-
90, 2022.
[25] T. Nguyen, C. Kim, and S. Ali, "AI-based chatbot for customer support in
digital marketplaces," Journal of Web Technologies, vol. 14, no. 3, pp. 65-78,
2020.
[26] L. Patel and R. Narayan, "Blockchain-enabled smart contracts for farmer-
buyer transactions," International Journal of Agricultural Management, vol. 12,
no. 2, pp. 82-97, 2021.
[27] G. Wang, J. Lee, and F. Singh, "Predictive analytics for weather and soil
condition forecasting," Advances in Agriculture, vol. 25, no. 1, pp. 45-58, 2020.
[28] M. Lee and B. Brown, "Cloud-native solutions for large-scale agricultural data
processing," Journal of Cloud Computing, vol. 19, no. 2, pp. 58-72, 2021.
[29] J. Roberts and E. White, "AI-based pest detection systems," Precision
Agriculture Technologies, vol. 18, no. 1, pp. 78-90, 2022.
[30] D. Chen, T. Patel, and M. Gupta, "Reinforcement learning for autonomous
irrigation control," International Journal of Artificial Intelligence in
Agriculture, vol. 13, no. 3, pp. 88-100, 2021.
[31] P. Singh and T. Ali, "IoT-enabled pest management systems," Journal of
Smart Agriculture, vol. 10, no. 1, pp. 45-60, 2020.
[32] A. Martinez and R. Davis, "Deep learning-based crop classification using
satellite images," Computers and Electronics in Agriculture, vol. 20, no. 4, pp.
95-110, 2021.
[33] M. White and T. Gupta, "AI-driven smart irrigation systems," International
Journal of Agricultural Engineering, vol. 15, no. 1, pp. 72-85, 2019.
[34] L. Lee and T. Brown, "Blockchain-based supply chain management for
traceability," Journal of Agricultural Systems, vol. 20, no. 3, pp. 92-106, 2020.
51
[35] G. Patel and L. Martinez, "AI-based decision support system for soil health
monitoring," Journal of Digital Agriculture, vol. 14, no. 2, pp. 115-130, 2021.
[36] T. Gupta and M. Rahman, "Machine learning algorithms for crop yield
forecasting," Journal of Agronomy, vol. 16, no. 4, pp. 58-75, 2019.
[37] A. White and R. Chen, "Predictive models for weather patterns and crop
management," Environmental Science and Agricultural Sustainability, vol. 10,
no. 2, pp. 88-103, 2020.
[38] C. Kumar, J. Patel, and A. Chen, "AI-based pest detection using image
processing," Journal of Agricultural Research and Technology, vol. 19, no. 4,
pp. 45-60, 2021.
[39] R. Patel and C. Lee, "Cloud computing for large-scale agricultural data
processing," Computers in Agriculture, vol. 17, no. 3, pp. 78-90, 2022.
[40] L. Brown and T. Ali, "Serverless architecture for scalable web platforms,"
Journal of Web Application Development, vol. 13, no. 2, pp. 115-125, 2020.
[41] F. Singh and P. Narayan, "Drone-based monitoring for crop health," Journal
of Agricultural Robotics, vol. 15, no. 1, pp. 85-100, 2021.
[42] J. Brown and T. Gupta, "AI-driven weather forecasting systems for precision
farming," Journal of Sustainable Agriculture, vol. 20, no. 2, pp. 75-88, 2020.
[43] A. Kumar, T. Lee, and M. Ali, "Blockchain-enabled digital marketplaces for
farm products," Journal of Agricultural Informatics, vol. 14, no. 3, pp. 115-130,
2021.
[44] T. Nguyen and D. Patel, "IoT-based environmental monitoring systems for
agriculture," International Journal of IoT in Agriculture, vol. 12, no. 2, pp. 80-
95, 2020.
[45] J. Patel, M. Gupta, and T. Brown, "AI-based crop disease detection using
remote sensing data," Computers in Agriculture, vol. 18, no. 4, pp. 75-90, 2021.
[46] R. Lee and S. White, "Real-time data analytics for digital agriculture
platforms," Journal of Web Technologies, vol. 13, no. 1, pp. 92-105, 2020.
[47] L. Brown and C. Davis, "AI-powered smart irrigation systems for efficient
water usage," Agricultural Engineering International, vol. 17, no. 3, pp. 58-75,
2021.
[48] M. Patel, J. Smith, and P. Ali, "Cloud-based systems for managing agricultural
supply chains," Journal of Cloud Computing in Agriculture, vol. 19, no. 4, pp.
85-100, 2021.
[49] T. Chen and R. Patel, "AI-based crop recommendation systems," Journal of
Agronomy and Crop Science, vol. 18, no. 2, pp. 102-118, 2022.
[50] A. Gupta and J. White, "Predictive models for pest control in precision
farming," Computers and Electronics in Agriculture, vol. 22, no. 3, pp. 88-103,
2022.
52
APPENDIX A – Sample Code
import string
import bcrypt
from flask import Flask, redirect, render_template, url_for, request, Markup
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin, login_user, LoginManager, login_required, logout_user,
current_user
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import InputRequired, Length, ValidationError
from flask_wtf import FlaskForm
from flask_bcrypt import Bcrypt
from datetime import datetime
import requests
import numpy as np
import pandas as pd
import config
import pickle
import io
import torch
from torchvision import transforms
from PIL import Image
from utils.model import ResNet9
from utils.fertilizer import fertilizer_dic
from utils.disease import disease_dic
disease_classes = ['Apple___Apple_scab',
'Apple___Black_rot',
'Apple___Cedar_apple_rust',
'Apple___healthy',
'Blueberry___healthy',
'Cherry_(including_sour)___Powdery_mildew',
'Cherry_(including_sour)___healthy',
'Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot',
'Corn_(maize)___Common_rust_',
'Corn_(maize)___Northern_Leaf_Blight',
'Corn_(maize)___healthy',
'Grape___Black_rot',
'Grape___Esca_(Black_Measles)',
'Grape___Leaf_blight_(Isariopsis_Leaf_Spot)',
'Grape___healthy',
'Orange___Haunglongbing_(Citrus_greening)',
'Peach___Bacterial_spot',
53
'Peach___healthy',
'Pepper,_bell___Bacterial_spot',
'Pepper,_bell___healthy',
'Potato___Early_blight',
'Potato___Late_blight',
'Potato___healthy',
'Raspberry___healthy',
'Soybean___healthy',
'Squash___Powdery_mildew',
'Strawberry___Leaf_scorch',
'Strawberry___healthy',
'Tomato___Bacterial_spot',
'Tomato___Early_blight',
'Tomato___Late_blight',
'Tomato___Leaf_Mold',
'Tomato___Septoria_leaf_spot',
'Tomato___Spider_mites Two-spotted_spider_mite',
'Tomato___Target_Spot',
'Tomato___Tomato_Yellow_Leaf_Curl_Virus',
'Tomato___Tomato_mosaic_virus',
'Tomato___healthy']
# disease prediction
disease_model_path = 'models/plant_disease_model.pth'
disease_model = ResNet9(3, len(disease_classes))
disease_model.load_state_dict(torch.load(
disease_model_path, map_location=torch.device('cpu')))
disease_model.eval()
def weather_fetch(city_name):
"""
Fetch and returns the temperature and humidity of a city
:params: city_name
:return: temperature, humidity
"""
api_key = config.weather_api_key
base_url = "http://api.openweathermap.org/data/2.5/weather?"
if x["cod"] != "404":
y = x["main"]
54
Transforms image to tensor and predicts disease label
:params: image
:return: prediction (string)
"""
transform = transforms.Compose([
transforms.Resize(256),
transforms.ToTensor(),
])
image = Image.open(io.BytesIO(img))
img_t = transform(image)
img_u = torch.unsqueeze(img_t, 0)
app = Flask(__name__)
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
app.config["SECRET_KEY"] = 'thisissecretkey'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(db.Model,UserMixin):
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(20), nullable=False, unique=True)
password = db.Column(db.String(80), nullable=False)
class UserAdmin(db.Model,UserMixin):
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(20), nullable=False, unique=True)
password = db.Column(db.String(80), nullable=False)
class RegisterForm(FlaskForm):
username=StringField(validators=[InputRequired(),Length(min=5,max=20)],render_kw={"pl
aceholder":"username"})
55
password=PasswordField(validators=[InputRequired(),Length(min=5,max=20)],render_kw={
"placeholder":"password"})
submit = SubmitField("Register")
class LoginForm(FlaskForm):
username=StringField(validators=[InputRequired(),Length(min=5,max=20)],render_kw={"pl
aceholder":"username"})
password=PasswordField(validators=[InputRequired(),Length(min=5,max=20)],render_kw={
"placeholder":"password"})
submit = SubmitField("Login")
class ContactUs(db.Model):
sno = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200), nullable=False)
email = db.Column(db.String(500), nullable=False)
text = db.Column(db.String(900), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
@app.route("/")
def hello_world():
return render_template("index.html")
@app.route("/aboutus")
def aboutus():
return render_template("aboutus.html")
return render_template("contact.html")
56
return redirect(url_for('dashboard'))
elif form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user:
if bcrypt.check_password_hash(user.password,form.password.data):
login_user(user)
return redirect(url_for('dashboard'))
@ app.route('/dashboard',methods=['GET', 'POST'])
@login_required
def dashboard():
title = 'dashboard'
return render_template('dashboard.html',title=title)
@ app.route('/logout',methods=['GET', 'POST'])
@login_required
def logout():
logout_user()
return redirect(url_for('hello_world'))
@app.route("/signup",methods=['GET', 'POST'])
def signup():
form = RegisterForm()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password.data)
new_user = User(username=form.username.data, password=hashed_password)
db.session.add(new_user)
db.session.commit()
return redirect(url_for('login'))
@ app.route('/crop-recommend')
@login_required
def crop_recommend():
title = 'crop-recommend - Crop Recommendation'
return render_template('crop.html', title=title)
@ app.route('/fertilizer')
@login_required
def fertilizer_recommendation():
title = '- Fertilizer Suggestion'
return render_template('fertilizer.html', title=title)
57
@app.route('/disease-predict', methods=['GET', 'POST'])
@login_required
def disease_prediction():
title = '- Disease Detection'
if request.method == 'POST':
if 'file' not in request.files:
return redirect(request.url)
file = request.files.get('file')
if not file:
return render_template('disease.html', title=title)
try:
img = file.read()
prediction = predict_image(img)
prediction = Markup(str(disease_dic[prediction]))
return render_template('disease-result.html', prediction=prediction, title=title)
except:
pass
return render_template('disease.html', title=title)
#
==================================================================
=============================
@ app.route('/crop-predict', methods=['POST'])
def crop_prediction():
title = '- Crop Recommendation'
if request.method == 'POST':
N = int(request.form['nitrogen'])
P = int(request.form['phosphorous'])
K = int(request.form['pottasium'])
ph = float(request.form['ph'])
rainfall = float(request.form['rainfall'])
# state = request.form.get("stt")
city = request.form.get("city")
if weather_fetch(city) != None:
temperature, humidity = weather_fetch(city)
data = np.array([[N, P, K, temperature, humidity, ph, rainfall]])
my_prediction = crop_recommendation_model.predict(data)
final_prediction = my_prediction[0]
58
else:
@ app.route('/fertilizer-predict', methods=['POST'])
def fert_recommend():
title = '- Fertilizer Suggestion'
crop_name = str(request.form['cropname'])
N = int(request.form['nitrogen'])
P = int(request.form['phosphorous'])
K = int(request.form['pottasium'])
# ph = float(request.form['ph'])
df = pd.read_csv('Data/fertilizer.csv')
nr = df[df['Crop'] == crop_name]['N'].iloc[0]
pr = df[df['Crop'] == crop_name]['P'].iloc[0]
kr = df[df['Crop'] == crop_name]['K'].iloc[0]
n = nr - N
p = pr - P
k = kr - K
temp = {abs(n): "N", abs(p): "P", abs(k): "K"}
max_value = temp[max(temp.keys())]
if max_value == "N":
if n < 0:
key = 'NHigh'
else:
key = "Nlow"
elif max_value == "P":
if p < 0:
key = 'PHigh'
else:
key = "Plow"
else:
if k < 0:
key = 'KHigh'
else:
key = "Klow"
response = Markup(str(fertilizer_dic[key]))
@app.route("/display")
def querydisplay():
alltodo = ContactUs.query.all()
return render_template("display.html",alltodo=alltodo)
59
@app.route("/AdminLogin", methods=['GET', 'POST'])
def AdminLogin():
form = LoginForm()
if current_user.is_authenticated:
return redirect(url_for('admindashboard'))
elif form.validate_on_submit():
user = UserAdmin.query.filter_by(username=form.username.data).first()
if user:
if bcrypt.check_password_hash(user.password,form.password.data):
login_user(user)
return redirect(url_for('admindashboard'))
# return render_template("adminlogin.html")
@app.route("/admindashboard")
@login_required
def admindashboard():
alltodo = ContactUs.query.all()
alluser = User.query.all()
return render_template("admindashboard.html",alltodo=alltodo, alluser=alluser)
@app.route("/reg",methods=['GET', 'POST'])
def reg():
form = RegisterForm()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password.data)
new_user = UserAdmin(username=form.username.data, password=hashed_password)
db.session.add(new_user)
db.session.commit()
return redirect(url_for('AdminLogin'))
if __name__ == "__main__":
app.run(debug=True,port=8000)
60