KEMBAR78
Project Report | PDF | Agriculture | Internet Of Things
0% found this document useful (0 votes)
14 views69 pages

Project Report

The document outlines a project titled 'Smart Agricultural Marketplace' submitted by Aditya Raj Katoch and Priyesh Kumar Singh for their Bachelor of Technology in Computer Science Engineering. The project aims to create an online platform that connects farmers with buyers, leveraging technologies like AI and IoT to enhance market access, optimize supply chains, and improve decision-making for farmers. The project includes a recommendation system for crop selection and fertilizer usage based on site-specific parameters, addressing key challenges faced by farmers in India.

Uploaded by

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

Project Report

The document outlines a project titled 'Smart Agricultural Marketplace' submitted by Aditya Raj Katoch and Priyesh Kumar Singh for their Bachelor of Technology in Computer Science Engineering. The project aims to create an online platform that connects farmers with buyers, leveraging technologies like AI and IoT to enhance market access, optimize supply chains, and improve decision-making for farmers. The project includes a recommendation system for crop selection and fertilizer usage based on site-specific parameters, addressing key challenges faced by farmers in India.

Uploaded by

singhsuman0812
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

B.Tech.

BCSE497J - Project-I

Smart Agricultural Marketplace

Submitted in partial fulfillment of the requirements for the degree of

Bachelor of Technology
in
Computer Science Engineering
by

21BCE3985 Aditya Raj Katoch


21BCE4000 Priyesh Kumar Singh

Under the Supervision of


Prof. Jabanjalin Hilda J
Sr. Assistant Professor
School of Computer Science and Engineering (SCOPE)

November 2024
DECLARATION

I hereby declare that the project entitled Smart Agricultural Marketplace


submitted by me, for the award of the degree of Bachelor of Technology in
Computer Science and Engineering to VIT is a record of bonafide work carried
out by me under the supervision of Prof. Jabanjalin Hilda J.
I further declare that the work reported in this project has not been submitted and
will not be submitted, either in part or in full, for the award of any other degree
ordiploma in this institute or any other institute or university.

Place : Vellore
Date : 13-11-2024

Signature of the Candidate

i
CERTIFICATE

This is to certify that the project entitled Smart Agricultural


Marketplace submitted by Aditya Raj Katoch (21BCE3985) and Priyesh
Kumar Singh (21BCE4000), School of Computer Science and Engineering,
VIT, for the award of the degree of Bachelor of Technology in Computer Science
and Engineering, is a record of bonafide work carried out by him / her under my
supervision during Fall Semester 2024-2025, as per the VIT code of academic
and research ethics.

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

Signature of the Guide

Examiner(s)

Prof. Umadevi K S
Computer Science Engineering

ii
ACKNOWLEDGEMENTS

I am deeply grateful to the management of Vellore Institute of Technology (VIT) for


providing me with the opportunity and resources to undertake this project. Their
commitment to fostering a conducive learning environment has been instrumental in
my academic journey. The support and infrastructure provided by VIT have enabled
me to explore and develop my ideas to their fullest potential.

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.

I express my profound appreciation to Prof. Umadevi K S, the Head of the Computer


Science Engineering, for her insightful guidance and continuous support. Her expertise
and advice have been crucial in shaping the direction of my project. The Head of
Department’s commitment to fostering a collaborative and supportive atmosphere has
greatly enhanced my learning experience. His/her constructive feedback and
encouragement have been invaluable in overcoming challenges and achieving my
project goals.

I am immensely thankful to my project supervisor, Prof. Jabanjalin Hilda J, for her


dedicated mentorship and invaluable feedback. Her patience, knowledge, and
encouragement have been pivotal in the successful completion of this project. My
supervisor’s willingness to share her expertise and provide thoughtful guidance has
been instrumental in refining my ideas and methodologies. Her support has not only
contributed to the success of this project but has also enriched my overall academic
experience.

Thank you all for your contributions and support.


Aditya Raj Katoch
Priyesh Kumar Singh

iii
TABLE OF CONTENTS

Sl.No Contents Page No.


Abstract i
1. INTRODUCTION 1
1.1 Background 1
1.2 Motivations 1
1.3 Scope of the Project 2
2. PROJECT DESCRIPTION AND GOALS 4
2.1 Literature Review 4
2.2 Research Gap 14
2.3 Objectives 16
2.4 Problem Statement 17
2.5 Project Plan 18
3. TECHNICAL SPECIFICATION 21
3.1 Stakeholder Analysis 21
3.2 Requirements 21
3.2.1 Functional 21
3.2.2 Non-Functional 23
3.3 Feasibility Study 23
3.3.1 Technical Feasibility 23
3.3.2 Economic Feasibility 24
3.3.2 Social Feasibility 24
3.4 System Specification 25
3.4.1 Hardware Specification 25
3.4.2 Software Specification 25
4. DESIGN APPROACH AND DETAILS 26
4.1 System Architecture 26
4.2 Design 27
4.2.1 Data Flow Diagram 27
4.2.2 Use Case Diagram 28
4.2.3 Class Diagram 29

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

Figure No. Title Page No.


4.1 Architecture of Ecommerce Website 26
4.2 Architecture of AI Model 26
4.3 DFD Level 0 27
4.4 DFD Level 1 27
4.5 Use Case Diagram 28
4.6 Class Diagram 29
4.7 Sequence Diagram 30
4.8 Activity Diagram for Seller side 31
4.9 Activity Diagram for Buyer side 32
5.1 Support Vector Machine 36
7.1 Algorithms Accuracy plot 46
7.2 Crop Recommendation Code Snippet 46

vi
List of Tables

Table No. Title Page No


1 Summary of 50 papers reviewed for project 4
2 Algorithm Accuracy 45

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.

In this project, this problem is solved by proposing a recommendation system through


ML models with majority voting technique using Random Forest, Naive Bayes, Support
Vector Machine (SVM), Logistic Regression and Random Forest, as learners to
recommend a crop for the site specific parameters with high accuracy and efficiency.
In Addition to that we are performing real time testing using IOT system .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.

Keywords: Smart agriculture, Recommendation system, Random Forest, Support


Vector Machine (SVM), Logistic Regression.

viii
1. INTRODUCTION

1.1 Background

The agricultural sector forms the backbone of many economies, particularly in


developing regions, where a significant portion of the population relies on
farming as their primary source of income. However, despite its importance,
agriculture is plagued by several inefficiencies, including a lack of access to fair
markets, price manipulation by intermediaries, and inadequate technological
support for farmers. These issues result in lower incomes for farmers and
increased food prices for consumers. With the rise of digital technologies, there
is a growing opportunity to address these problems through the creation of
online platforms that directly connect farmers with buyers, reducing
dependence on middlemen. Furthermore, the incorporation of emerging
technologies like Artificial Intelligence (AI), Blockchain, and the Internet of
Things (IoT) offers transformative potential for improving market efficiency,
enhancing product traceability, and optimizing agricultural practices. This
project aims to leverage these technologies to create a smart agricultural
marketplace that can empower farmers by providing better market access and
decision-making tools.

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

The scope of the project encompasses the development of an online smart


agricultural marketplace with integrated smart functionalities. The platform will
provide farmers with real-time data analytics on market prices, crop health
monitoring, and supply chain optimization. Blockchain technology will be used
to ensure traceability and transparency in the transaction process, enabling both
farmers and buyers to have confidence in the fairness of the trade. IoT devices
will be used to gather data on environmental conditions, crop health, and
inventory management, providing farmers with the tools to make data-driven
decisions. Additionally, the platform will include a mobile-friendly interface to
ensure accessibility for farmers in rural areas. The project will also explore
partnerships with financial institutions to provide farmers with access to credit
and insurance services. Although initially targeted at small and medium-scale
farmers, the platform can be scaled to accommodate larger agricultural
enterprises and expanded to cover more markets over time. The long-term goal

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

2.1 Literature Review

Agriculture has witnessed a digital transformation in recent years, with several


innovations aimed at improving market access, enhancing efficiency, and increasing
profitability for farmers. Online marketplaces, integrated with smart technologies, have
emerged as a potential solution to address the challenges faced by farmers, including
fragmented markets, lack of real-time pricing information, and middlemen. This review
examines the findings of 50 research papers, categorizing them by the impact of digital
platforms, real-time data integration, supply chain transparency, and mobile
accessibility in agriculture.

Table 1: Summary of 50 Papers reviewed for the Project

Journal Methodolo Advantage Disadvant Performanc Future


gies age e Metric Scope
Used
Journal of RESTful Scalable, Limited to Response Expansion
Web API efficient HTTP- time, API to
Engineeri developme web based efficiency microservic
ng (2020) nt for web interaction interaction es
applications architecture
Computer IoT-based Real-time Requires Accuracy of Integration
s in soil soil constant moisture with
Agricultur moisture monitoring connectivit readings predictive
e (2019) sensing y analytics
system
Journal of Machine Enhanced High Prediction Integration
Agricultur learning predictive computatio accuracy of AI-driven

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)

2.2 Research Gap

1. Cold-Start Issues in Serverless Architectures


• Gap Identified: Several papers mention the efficiency of serverless architectures

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.

2. Lack of Comprehensive AI Integration for Predictive Decision-Making


• Gap Identified: While AI is being used for specific tasks like pest detection,
disease identification, and crop yield prediction, there is a lack of
comprehensive integration where AI can provide actionable insights across
multiple aspects (weather, soil, pest, and market conditions) in a single platform.
• How Our Project Can Help: Our platform can serve as a holistic decision-
making tool by integrating AI-driven analytics across various data sources—
weather forecasts, soil conditions, market prices, and pest alerts—allowing
farmers to make better-informed decisions in real-time.

3. Insufficient Real-Time Data Processing for Crop and Weather Forecasting


• Gap Identified: Many predictive models for crop yield and weather forecasting
require significant computational resources and are often not performed in real-
time, limiting their utility for immediate decision-making by farmers.
• How Our Project Can Help: Our platform can leverage real-time data processing
and predictive analytics, possibly through edge computing or cloud services, to
provide immediate insights on weather conditions, soil health, and crop growth,
allowing farmers to make quick, data-driven decisions.

4. Lack of Personalized Crop Recommendations Based on Local Data


• Gap Identified: Although AI-driven crop recommendation systems exist, they
often rely on generalized data, lacking personalization based on local soil,
weather, and market conditions, which are crucial for optimizing crop selection.
• How Our Project Can Help: Our platform can offer personalized crop
recommendations using localized data on soil conditions, weather patterns, and
current market demand. This would enable farmers to make more profitable and
sustainable choices for their specific geographic and market conditions.

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

1. To develop a user-friendly online marketplace that connects farmers directly


with buyers, enabling them to sell their produce without relying on
intermediaries, ensuring fair pricing and reducing transaction costs.

2. To provide personalized crop recommendations based on real-time data analysis


of local soil conditions, weather forecasts, and market demand, empowering
farmers to select the most profitable and sustainable crops for their specific
regions.

3. To provide real-time weather forecasting and automated decision support tools


for irrigation and planting schedules, helping farmers optimize water use and
crop timing, ultimately improving yields and resource efficiency.
4. To create a seamless and intuitive user interface that simplifies the adoption of
digital tools for farmers with minimal technical skills, offering local language
support and easy navigation for a better user experience.

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.

6. To promote sustainable agricultural practices by providing data-driven insights


and recommendations that encourage efficient use of resources like water,
fertilizers, and pesticides, reducing environmental impact while increasing
profitability.

2.4 Problem Statement

In today's agricultural landscape, farmers, especially small and medium-scale, face


numerous challenges, including limited access to real-time data, market volatility,
inefficient supply chains, and lack of affordable technologies for crop monitoring and
decision-making. Traditional marketplaces often involve intermediaries who reduce
farmers' profits, while technological solutions like IoT, AI, and blockchain, though
promising, remain expensive and difficult to adopt for most rural farmers. Furthermore,
rural areas suffer from unreliable internet connectivity, limiting the utility of many
digital tools that rely on constant access to the web. These challenges lead to suboptimal
farming practices, reduced crop yields, and income instability for farmers, highlighting
the need for an accessible, affordable, and integrated solution that empowers farmers to
make data-driven decisions, access fair markets, and increase productivity sustainably.
This problem demands a solution that integrates modern technologies into a simple,
cost-effective platform that can be adopted by farmers with varying levels of technical
skill and resources.

17
2.5 Project Plan

Phase 1: Research and Requirement Gathering (Weeks 1-2)


• Objective: Identify key functionalities, technologies, and stakeholders for the
platform.
• Tasks:
o Research affordable IoT devices for soil and crop monitoring, and AI
models for crop and pest prediction.
o Identify key datasets for weather forecasting, soil analysis, and market
prices.
o Analyze existing digital agricultural platforms for inspiration and gaps.
• Outcome: A clear understanding of the requirements, target audience, and
potential challenges.

Phase 2: Platform Design and Architecture (Weeks 3-4)


• Objective: Develop a blueprint of the platform's architecture and user interface.
• Tasks:
o Design the platform’s architecture, including front-end (UI/UX) and
back-end (server, database, cloud services).
o Choose AI models for crop recommendations and pest detection.
o Ensure the design is scalable, secure, and user-friendly with offline-first
capabilities.
o Design database structures for storing user data, crop and market
information.
• Outcome: Wireframes, technical architecture, and design specifications ready
for development.

Phase 3: ML and AI Integration (Weeks 5-8)


• Objective: Implement and integrate ML and AI into the platform.
• Tasks:
o Develop a real-time data collection system that syncs data to the cloud.
o Implement AI models for personalized crop recommendations, pest and

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.

Phase 4: Core Development and Platform Functionality (Weeks 9-12)


• Objective: Develop core functionalities of the platform, including the
marketplace and farmer tools.
• Tasks:
o Build the web-based platform, including user authentication,
dashboards, and farmer profiles.
o Develop marketplace features for listing and buying agricultural
products.
o Integrate AI-powered decision-making tools (crop recommendations,
dynamic pricing).
• Outcome: Fully functioning platform with key features implemented.

Phase 5: Testing and Quality Assurance (Weeks 13-14)


• Objective: Test all platform components for functionality, usability, and
performance.
• Tasks:
o Perform unit testing on each feature (marketplace, AI models, ML
integration).
o Conduct user testing with farmers to assess the platform’s usability.
o Test offline features and ensure seamless synchronization once online.
o Run security and scalability tests on blockchain transactions and cloud
infrastructure.
o Fix any bugs or performance issues identified during testing.
• Outcome: A stable, secure platform that performs reliably across various
environments.

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.

Phase 7: Post-Launch Support and Continuous Improvement (Future Scope)


• Objective: Monitor the platform, address any issues, and improve based on user
feedback.
• Tasks:
o Provide technical support to users and resolve any issues.
o Regularly monitor AI models for accuracy and IoT systems for
performance.
o Gather user feedback and implement updates to improve the user
experience.
o Add new features such as financial services (micro-loans, insurance) or
additional crop/pest data.
• Outcome: A continuously improving platform that adapts to users’ needs and
technological advancements.

20
3. TECHNICAL SPECIFICATION

3.1 Stakeholder Analysis

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.

3.3 Feasibility Study

3.3.1 Technical Feasibility

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.

3.3.2 Economic Feasibility

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.

3.3.3 Social Feasibility

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

3.4.1 Hardware 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.

3.4.2 Software Specification

AI Algorithms: Machine learning models for price adjustment, crop recommendation,


and soil condition analysis.
Database System: The platform requires a robust database system to store user data,
transaction data, and IoT data.
Web Application Framework: A secure, scalable framework for the web-based
marketplace.
Cloud Infrastructure: For data storage, scalability, and AI computation, leveraging
cloud-based services like AWS, Azure, or Google Cloud.

25
4. DESIGN APPROACH AND DETAILS

4.1 System Architecture

Ecommerce Platform

Fig 4.1 – Architecture of Ecommerce website.

Fig 4.2 – Architecture of AI Model.

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

4.2.1 Data Flow Diagram

Fig 4.3 – DFD Level 0

Fig 4.4 – DFD Level 1

27
4.2.2 Use Case Diagram

Fig 4.5 – Use Case Diagram

28
4.2.3 Class Diagram

Fig 4.6 – Recommendation System Class Diagram.

29
4.2.4 Sequence Diagram

Fig 4.7 – Sequence Diagram for Recommendation System.

30
4.2.5 Activity Diagram

For the marketplace –

Fig 4.8 – Activity Diagram for marketplace Seller Side.

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.

Fig. 5.1 – Support Vector Machine.

Logistic Regression - Logistic regression is a classification algorithm used to assign


observations to a discrete set of classes. Some of the examples of classification
problems are Email spam or not spam, Online transactions Fraud or not Fraud, Tumor
Malignant or Benign. Logistic regression transforms its output using the logistic
sigmoid function to return a probability value. There are two types of logistic
regression:
1. Binary (eg. Tumor Malignant or Benign)
2. Multi-linear functions failsClass (eg. Cats, dogs or Sheep's)
Logistic Regression is a Machine Learning algorithm which is used for the
classification problems, it is a predictive analysis algorithm and based on the concept
of probability.

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.

c) Quality Assurance - Quality Assurance is popularly known as QA Testing, is defined


as an activity to ensure that an organization is providing the best possible product or
service to customers. QA focuses on improving the processes to deliver Quality
Products to the customer. An organization has to ensure, that processes are efficient and
effective as per the quality standards defined for software products.

d) Functional Test - Functional Testing is also known as functional completeness


testing, Functional Testing involves trying to think of any possible missing functions.
As chat-bot evolves into new application areas, functional testing of essential chatbot
components. Functional testing evaluates use-case scenarios and related business
processes, such as the behavior of smart contracts.

39
6. DEMONSTRATION

Recommendation System

40
41
42
43
Marketplace

Admin Home after login.

User Home after login.

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.

Algorithms and Their Accuracy


For the purposes of this project we have used four popular algorithms: Decision Trees,
Logistic regression, Support Vector Machine and Random Forest. All the algorithms
are based on supervised learning. Our overall system is divided into two modules:
1. Crop recommender
2. Fertilizer Recommender/Suggestion

Table 2 – Algorithm Accuracy.

45
Accuracy comparison for models :

Fig 7.1 – Algorithms accuracy plot.


Hence, Random Forest is our Final efficient model.

Output for Crop recommender:

Fig 7.2 – Crop Recommendation code snippet.

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

In conclusion, this project has successfully developed a precision agriculture solution


that integrates machine learning, IoT, and a peer-to-peer marketplace, enabling a
holistic approach to supporting farmers and improving agricultural productivity. The
precision agriculture system addresses key challenges in crop and fertilizer selection by
analyzing soil, environmental data, and specific crop requirements. With machine
learning models such as Random Forest, SVM, and Logistic Regression, the system
recommends optimal crops and fertilizers based on soil nutrients, temperature, and
moisture levels. This guidance helps farmers make more informed decisions, reduce
risks of crop failure, and increase productivity, contributing to the sustainability and
resilience of the agriculture sector.

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

# -------------------------LOADING THE TRAINED MODELS --------------------------------------


---------

# Loading crop recommendation model


crop_recommendation_model_path = 'models/RandomForest.pkl'
crop_recommendation_model = pickle.load(
open(crop_recommendation_model_path, 'rb'))

# Loading plant disease classification model

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?"

complete_url = base_url + "appid=" + api_key + "&q=" + city_name


response = requests.get(complete_url)
x = response.json()

if x["cod"] != "404":
y = x["main"]

temperature = round((y["temp"] - 273.15), 2)


humidity = y["humidity"]
return temperature, humidity
else:
return None

def predict_image(img, model=disease_model):


"""

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)

# Get predictions from model


yb = model(img_u)
# Pick index with highest probability
_, preds = torch.max(yb, dim=1)
prediction = disease_classes[preds[0].item()]
# Retrieve the class label
return prediction

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")

def validate_username(self, username):


existing_user_username = User.query.filter_by(username=username.data).first()
if existing_user_username:
raise ValidationError("That username already exist. please choose different one.")

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)

def __repr__(self) -> str:


return f"{self.sno} - {self.title}"

@app.route("/")
def hello_world():
return render_template("index.html")

@app.route("/aboutus")
def aboutus():
return render_template("aboutus.html")

@app.route("/contact", methods=['GET', 'POST'])


def contact():
if request.method=='POST':
name = request.form['name']
email = request.form['email']
text = request.form['text']
contacts = ContactUs(name=name, email=email, text=text)
db.session.add(contacts)
db.session.commit()

return render_template("contact.html")

@app.route("/login", methods=['GET', 'POST'])


def login():
form = LoginForm()
if current_user.is_authenticated:

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'))

return render_template("login.html", form=form)

@ 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'))

return render_template("signup.html", form=form)

@ 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)

# @app.route('/disease-predict', methods=['GET', 'POST'])


# @login_required
# def disease_prediction():
# title = '- Disease Detection'
# return render_template('disease.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)

#
==================================================================
=============================

# RENDER PREDICTION PAGES

# render crop recommendation result page

@ 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]

return render_template('crop-result.html', prediction=final_prediction, title=title)

58
else:

return render_template('try_again.html', title=title)

# render fertilizer recommendation result page

# render fertilizer recommendation result page

@ 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]))

return render_template('fertilizer-result.html', recommendation=response, title=title)

@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", form=form)

# 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'))

return render_template("reg.html", form=form)

if __name__ == "__main__":
app.run(debug=True,port=8000)

60

You might also like