Professional Documents
Culture Documents
Report
Report
Report
examined and is hereby approved towards partial fulfillment for the
award of Bachelor of Engineering degree in Computer Science &
Engineering discipline, for which it has been submitted. It understood
that by this approval the undersigned do not necessarily endorse or
therein, but approve the project only for the purpose for which it has
been submitted.
I
RECOMMENDATION
Thisistocertifythattheworkembodiedinthisprojectentitled“A
griculture
the supervision of Prof. Juhi Shrivastava is recommended towards partial
fulfillmentfortheawardoftheBachelorofEngineering(ComputerScience&
(Project Guide)
(Project Coordinator)
(Dean Academics)
II
STUDENTS UNDERTAKING
This is to certify that the major project entitled “Agriculture Portal :
theworkdoneinthisprojectisours.Thesoleintentionofthisworkisonlyfor
Wefurtherdeclarethattothebestofourknowledge;thisreport
does not contain any part of any work which has been submitted for the
award of any degree either in this University or in any other University /
DeemedUniversitywithoutpropercitationandifthesameworkisfoundthen
We owe a debt of sincere gratitude, deep sense of reverence and respect to
our guideandmentorsProf.JuhiShrivastava,AssociateProfessor,AITR,for
their motivation, sagacious guidance, constant encouragement, vigilant
supervision and valuable critical appreciation throughout this project work,
which helped us to successfully complete the project on time.
We express profound gratitude and heartfelt thanks to Dr. Kamal Kumar
Sethi, HOD CSE, AITR Indore for his support, suggestion and inspirationfor
carrying out this project. I am very much thankful to other faculty and staff
members of CSE Dept, AITR Indore for providing me all support, help and
advice during the project. We would be failing in our duty if we do not
acknowledge the support and guidance received from Dr. S.C. Sharma,
Director, AITR, Indore whenever needed. We take the opportunity toconvey
my regards to the management of Acropolis Institute, Indore for extending
academicandadministrativesupportandprovidingmeallnecessaryfacilities
for the project to achieve our objectives.
Wearegratefultoourparentsandfamilymemberswhohavealwaysloved
andsupportedusunconditionally.Toallofthem,wewanttosay,“Thankyou”,
forbeingthebestfamilythatonecouldeverhaveandwithoutwhomnoneof
this would have been possible
The project is based on The Agriculture Portal is an innovative machine
learning-based system designed to empower farmers by providing accurate
predictions and prescriptive analytics, along with personalized
recommendations. Let’s delve into the key aspects of this system. Machine
Learning Algorithms: These algorithms form the backbone of the system.
Theyincluderegressionmodels,decisiontrees,andneuralnetworks.BigData
Infrastructure: The portal handles large volumes of data efficiently using
technologieslikeHadoopandSpark.CloudServices:Cloudplatformsprovide
scalability,storage,andprocessingpower.UserInterface:Theportaloffersan
intuitive interface for farmers to access insights and recommendations.
V
“A dry March,
a wet April and
a cool May fill barn
and cellar and
bring much hay”
- Alfred North Whitehead
VI
List of Figures
Chapter 1 - Introduction
Introduction of Agricultural Portal
TheAgriculturePortalisaninnovativemachinelearning-basedsystemdesigned
to empower farmers by providing accurate predictions, prescriptive analytics,
andpersonalizedrecommendations.Throughtheuseofvariousalgorithms,this
platformassistsfarmersinmakinginformeddecisionsabouttheircrops.Inthis
researchpaper,wedelveintothearchitecture,methodologies,andtechnologies
behind the Agriculture Portal, emphasizing its impact on modern agriculture.
Random Forest algorithm for crop recommendation utilizes an ensemble
learning technique that builds multiple decision trees during training and
aggregates their predictions to provide recommendations. It analyzes various
factors such as soil type, climate conditions, historical crop yields, andmarket
demand to suggest suitable crops for agivenagriculturalregion.Thisapproach
combinestherobustnessofdecisiontreeswiththediversityofmultiplemodels,
yielding accurate and reliable crop recommendations.
1.1 Overview
TheAgriculturalPortalSurveyofourprojectaimstogathercrucialinsightsand
feedback from stakeholders involved in the agricultural sector. This
comprehensive survey encompasses various aspects crucial for the
development and enhancement of agricultural practices, technology, and
sustainability.
1of 54
Agriculture Portal
The survey seeks to understand the perceptions and attitudes of farmers
towards sustainable agricultural practices. This involves assessing their aware
of environmental conservation, soil health management, and biodiversity
conservation. Insights into farmers' willingness to adopt sustainable practices
guide initiatives aimed at promoting eco-friendly farming methods the survey
evaluates the usage and effectiveness of existing agricultural technologies and
practices. This includes assessing the adoption rate of modern farming
techniques, irrigation systems, and crop varieties. Feedback on the usability,
affordability, and impact of these technologieshelpsinrefiningandoptimizing
their implementation.
1.2 Inspiration
TheinspirationbehindtheAgriculturePortalstemsfromtheneedtobridgethe
gap between traditional farming practices and cutting-edge technology. As the
global population grows, ensuring food security becomes increasingly critical.
By harnessing the power of machine learning, the Agriculture Portal aims to
revolutionize agriculture by providing farmers with actionable insights.
2. FertilizerRecommendations:Basedoncroppredictionsandsoilanalysis,
the Agriculture Portal suggests appropriate fertilizers to enhance crop
yield.
3. Disease Prediction: A crop disease detection system typically involves
usingtechnologysuchascomputervision,machinelearning,andsometimes
2of 54
Agriculture Portal
4. News by using API: The objective of our agriculture portal is to provide
timely, accurate, and relevant news and information to farmers,
agribusinesses, and stakeholders. We aim to empower our audience with
insights on market trends, agricultural technologies, policy developments,
and best practices, facilitating informed decision-making and sustainable
agricultural growth
ThereachoftheAgriculturePortalextendsfarandwide,encompassingfarmers
across diverse geographical locations and socio-economic backgrounds.
Throughitsinnovativemachinelearning-basedsystem,theportaldemocratizes
access to cutting-edge agricultural insights and recommendations, thereby
empowering farmers to make informed decisions and optimize their
productivity.
One of the primary ways the Agriculture Portal reaches farmers is through
digital platforms and mobile applications. By leveraging the ubiquity of
smartphones and internet connectivity, the portal ensures that farmers,
regardless of their location, can access its features and benefits.Marketprices
for crops and livestock, access to agricultural inputs (seeds, fertilizers,
equipment),onlineforumsorcommunitiesforknowledgesharingcropplanning
and management tools.
3 of 54
Agriculture Portal
Aanchal Patel:
I investigated and found the right technology and studied it for the
implementationoftheproject.Icollectedtheobjectdataandtrainedthemodel
for it. Implementation logic for the project objective and coding of internal
functionalities is alsodonebyme.Also,workedonBackenddesignforstoring
results in the database for maintaining logs and machine algorithms for the
dataset.
Aditi Rathore:
Icollectedallthenecessaryinformationaboutour projectand theworkingof
countingofobjectsintheproject.Ialsodidthefront-endas theframeworkand
design , surveyedvariousresearchpapersandposters.Documentationisalsoa
part of the work done by me in this project.
Aman Solanki:
Along with doing preliminary investigation and understanding of the current
system, I studied the topic and its scope. research papers related to the Crop
Prediction and the technology that is to be used.
Devesh Ujonia:
I collect and annotate large datasets. Testing and validation ensure system
reliability,andongoingupdateskeepthesystemcurrentwithevolvingweather
conditions and news.
4of 54
Agriculture Portal
Chapter2:ReviewofLiterature-explorestheworkdoneintheareaofProject
undertaken and discusses the limitations of the existing system andhighlights
the issues and challenges of the project area. The chapter finallyendsupwith
therequirementidentificationforpresentprojectworkbasedonfindingsdrawn
from reviewed literature and end user interactions.
Chapter 3 : Proposed System - starts with the project proposal based on
requirement identified, followed by benefits of the project. The chapter also
illustrates the software engineering paradigm used along with different design
representations.Thechapteralsoincludesablockdiagramanddetailsofmajor
modules of the project. Chapter also gives insights of different types of
feasibility studycarriedoutfortheprojectundertaken.Lateritgivesdetailsof
the different deployment requirements for the developed project.
Chapter 4 : Implementation - includes the details of different Technology/
Techniques/Tools/ProgrammingLanguagesusedindevelopingtheProject.The
5of 54
Agriculture Portal
chapteralsoincludesthedifferentuserinterfacesdesignedintheprojectalong
with their functionality. Further it discussestheexperimentresultsalongwith
testing of the project. The chapter ends with evaluation of the project on
different parameters like accuracy and efficiency.
Chapter5:Conclusion-Concludeswithobjectivewiseanalysisofresults and
limitation of present work which is then followed by suggestions and
recommendations for further improvement.
6 of 54
Agriculture Portal
● FertilizerRecommendations:Basedoncroppredictionsandsoilanalysis,the
Agriculture Portal suggests appropriate fertilizers to enhance crop yield.
● DiseasePrediction:Acropdiseasedetectionsystemtypicallyinvolvesusing
technology such as computer vision, machine learning, and sometimes IoT
(Internet of Things) devices to identify diseases in crops. Once trained,the
modelscanbeusedtoanalyzenewimagesordataanddetectsignsofdisease
in crops.[4] If the system is deployed in real-time, it can provide early
7of 54
Agriculture Portal
warnings to farmers, allowing them to take preventive measures such as
applying pesticides or adjusting irrigation.
● News by API: News for an agriculture portal indicates a focus on timely
updates regarding crop cultivation techniques, market trends, and policy
developments. Content covers diverse topics such as sustainable farming
practices, technological innovations, and global trade dynamics.[8] The
portal serves as a valuable resource for farmers, researchers, and industry
stakeholders.
Before delving into the specifics, let’s consider the preliminary investigation.
The Agriculture Portal emerged as a response to thepressingchallengesfaced
by farmers worldwide.[6] These challenges include unpredictable weather
patterns, fluctuating crop yields, and the need for sustainable agricultural
practices.Byconductinganin-depthanalysisofexistingsystemsandidentifying
gaps, the project team laid the foundation for this innovative solution.[3]The
8of 54
Agriculture Portal
Agriculture Portal is an innovative system that leverages machine learning to
empower farmers. It provides accurate predictions and prescriptive analytics
with personalized recommendations. The portal uses various algorithms to
predict optimal crops, suggest appropriate fertilizers, and forecast rainfalland
yield. It also includes features like weatherforecastingandagriculture-related
news.
While existing agricultural systems provide valuable insights, they often fall
short in the following areas:
● Scalability: Scalability issues arise when handling large datasets or
serving a growing user base.
anddonotprovideprescriptiveanalytics.Theyoftenfailtoconsidertheunique
circumstances and needs of individual farmers.[7] Moreover, these systems
typically do not offer a comprehensive suite of features, such as weather
forecasting and agriculture-related news.
Understanding the needs of farmers was crucial during the requirement
identification phase. The project team engaged with farmers, agronomists,and
domain experts to gather insights. Key requirements included:
● Crop Prediction: Farmers needed a reliable system that could predict
optimal crops based on soil conditions, climate, and market demand.
● Personalization:Recognizingthateachfarmisunique,thesystemhadto
provide personalized recommendations.
● Identify news pertinent to agriculture portal: Select articles on crop
yields,weatherimpacts,markettrends,technologicaladvancements,and
policychanges.Emphasizesustainability,farmerwelfare,andinnovation.
Ensure content diversity across regions and crops. Prioritize reliable
sources and engage with audience feedback for relevance and impact.
The Agriculture Portal’s requirements were meticulously identified and
analyzed:
● Data Collection: Integration with weather APIs, soil databases, and
historical yield records.
10of 54
Agriculture Portal
● User Interface: A user-friendly platform accessible via web and mobile
devices.
2.3.1 Conclusion
The Agriculture Portal has transformed the way farmers make decisions. By
providing accurate predictions, personalized advice, and real-time insights, it
empowers them to optimizecropyield,conserveresources,andmitigaterisks.
Additionally, features like weather forecasting and agriculture-related news
enhance its utility. [7] The Agriculture Portal represents a significant leap
forward in agricultural technology. Its holistic approach, data-driven insights,
and user-centric design contribute to sustainable farming practices and
improved livelihoods for farmers worldwide.
The Agriculture Portal is poised to transform agriculture by empowering
farmers with accurate predictions, personalized insights, and informed
decision-making. By bridging the gap between technology and traditional
11of 54
Agriculture Portal
farming practices, it contributes to sustainable food production and resilient
farming communities. As we move forward, the Agriculture Portal stands as a
beacon of innovation, ensuring a brighter future for global agriculture.The
Agriculture Portal represents a significant advancement in agricultural
technology. Byleveragingmachinelearningandvariousalgorithms,itprovides
farmers with personalized recommendationsandprescriptiveanalytics.[3]This
notonlyhelpsininformeddecision-makingbutalsoenhancesproductivityand
sustainability in farming. Despite some limitations, the Agriculture Portal’s
impact on the agricultural sector is undeniable, making it a valuable tool for
farmers worldwide.
12of 54
Agriculture Portal
The proposed agriculture portal aims to revolutionize farming practices by
providing a comprehensive suite of features to assist farmers in making
informed decisions and optimizing their agricultural output. The portal
encompasses crop prediction, crop recommendation, yield prediction,
weather forecasting, and access to agriculture-related news.
New agriculture portal integrates API for real-time updates on crop prices,
weather forecasts, and farming techniques, empowering farmers with
valuable information for improved productivity and sustainability.
Through its integrated suite of features, the agriculture portal empowers
farmers with actionable insights, expert guidance, and timelyinformationto
13of55
Agriculture Portal
optimizeagriculturalpractices,improveproductivity,andsustainablymanage
resources.[5] By fostering knowledge exchange and collaboration within the
farmingcommunity,theportalcontributestotheresilienceandprosperityof
agricultural ecosystems.
The proposed agriculture portal offers a range of benefits to farmers and
stakeholders in the agricultural sector:
14of55
Agriculture Portal
A feasibility study is an analysis of how successfully a system can be
implemented,accountingforfactorsthataffectitsuchaseconomic,technical
and operational factors to determine its potential positive and negative
outcomes before investing a considerable amount of time and money into it.
3.4.1 Technical
Thetechnicalfeasibilitystudyoftheagricultureportalinvolvesevaluatingthe
feasibility of implementation. Assessing the feasibility of integrating multiple
15of55
Agriculture Portal
Overall, the technical feasibility study aims to identify potential challenges
and risks associated with implementing theagricultureportal'sfeaturesand
to propose solutions to ensure successful development and deployment.
3.4.2 Economical
The economical feasibility study of the agriculture portal involves assessing
thepotentialcostsandbenefitsassociatedwithitsdevelopment,deployment,
and operation:
1. Cost Analysis: Evaluating the upfront and ongoing costs involved in
developing the portal, including software development, data acquisition,
infrastructure setup, maintenance, and personnel expenses.
16of55
Agriculture Portal
4. Return on Investment (ROI): Calculating the projected ROI based on
estimated cost savings and revenue generation compared to the initial
investment.
5. Market Potential: Analyzing the market demand for such a portal among
farmers, agricultural stakeholders, and investors,consideringfactorssuchas
competitive landscape, user adoption rates, and growth potential.
Basedontheeconomicalfeasibilityanalysis,theagricultureportalisexpected
todeliversignificantvaluebyimprovingfarmprofitability,reducingrisks,and
enhancing sustainability, thus justifying the investment in its development
and operation.
3.4.3 Operational
The operational feasibility study of the agriculture portal involves a
comprehensiveexaminationofitsfunctionalityandusabilitytodetermineits
practicality in real-world agricultural settings. Firstly, the usability of the
portal's interface is evaluated, ensuring that it is intuitive and accessible to
farmers of varying technological proficiency levels. This entails designing a
user-friendlyinterfacethatallowsfarmerstoeasilynavigatebetweenfeatures
such as crop prediction, recommendation, yield prediction, weather
forecasting, and agriculture-related news.
17of55
Agriculture Portal
documentation, tutorials, and customer support channels to assist users in
maximizing the benefits of the portal for their agricultural operations.
3.5 Design Representation
18of55
Agriculture Portal
19of55
Agriculture Portal
Actors:
● User -The person who interacts with the system toknow about crops.
Use Cases:
● Collect Data - Collect data from the user as K, Potassium, Nitrogen,
Phosphorus, Ph , Rainfall.
● Select Data-The system filters and selects relevantdata for analysis.
● Retrieve Data -T
he system retrieves additional context-specific
data:Crop Database,Fertilizer Database,Weather Data,News Archive.
● Fetch Data -The system fetches data from external APIs or
databases:Weather Service,News Service
● Select CSV -Selecting CSV of the given data.
● Select random forest algorithm -T
he system chooses the Random
Forest algorithm for predictive modeling.
● ShowResults-Thesystempresentspersonalizedrecommendationsto
farmers
Relationships:
→ The User interacts with the system by providing a seed phrase and
receiving the right crop recommendation.
→ Thesystemwillgeneratetherightcropforthesoilandfarmerscaneasily
use it.
Overall, the use case diagram illustrates how a user interacts with the
agriculture portal to know about crop recommendation, disease prediction.
20of55
Agriculture Portal
The ER diagram depicts a system that generates crop , disease prediction,
fertilizer recommendation,likelythroughamachinelearningmodel.Here’sa
breakdown of the entities and their relationships:
Entities:
1. Crop
●Attributes: CropName, SoilType, ClimateType
21of55
Agriculture Portal
2. CropPrediction
●Attributes: CropID (PK),, PredictionValue
3. PlantDisease
●Attributes: CropID (PK), DiseaseName
4. News
●Attributes: NewsID (PK), Content
5. Recommendation
●Attributes:CropID (PK), RecommendationText
6. Farmer
●Attributes: UserID (FK), password
● CropPrediction - Crop (1-to-many): One crop prediction can be
associated with one crop, but one crop can have multiple predictions.
● PlantDisease - Crop (1-to-many): One plant disease prediction can be
associated with one crop, but one crop can have multiple disease
predictions.
● Recommendation-Crop(1-to-many):Onecroprecommendationcanbe
associated with one crop, but one crop can have multiple
recommendations.
● News-Crop(many-to-many):Manynewsarticlescanbeassociatedwith
multiple crops, and vice versa.
● Farmer - Crop (many-to-many): Many farmers can grow multiplecrops,
and each crop can be grown by multiple farmers.
3.6.1 Hardware
3.6.2 Software
● HTML 5:Hypertext Markup Language (HTML) is the standard markup
language and web applications. IT is used to make the website.
● CSS: IT is used to make the website more attractive.
● Javascript: it is used to make the pages more interactive.
● PHP5.2.0:PHPisasidescriptinglanguagedevelopment, and also used as
a general purpose programming language.
● Python : Python is used to implement machine learning algorithms.
● Pandas and NumPy: Essential libraries for data manipulation and analysis.
● Scikit-learn: ML toolkit for implementing algorithms.
● Flask-FlaskisamicrowebframeworkwritteninPython.Itisclassifiedasa
microframework because it does not require particular tools or libraries.
● SQlAlchemy-SQLAlchemy is the Python SQL toolkit and Object Relational
Mapper that gives application developers the full power and flexibility of
SQL.
● Utils-Returns true ifthegivenvalueisempty,falseifanyvalueexists.Worksfor
booleans, functions, numbers, strings, nulls, objects and arrays.
23of55
Agriculture Portal
Chapter 4 - Implementation
IMPLEMENTATION PHASE
● Random Forest is a popular machine learning algorithm that belongs to
the supervised learning technique. It can be used for both Classification
andRegressionproblemsinML.[1]Itisbasedontheconceptofensemble
learning, which is a process of combining multiple classifiers to solve a
complex problem and to improve the performance of the model.
Asthenamesuggests,"RandomForestisaclassifierthatcontainsanumberof
decisiontreesonvarioussubsetsofthegivendatasetandtakestheaverageto
improve the predictive accuracy of that dataset." Instead of relying on one
24of 54
Agriculture Portal
decisiontree,therandomforesttakesthepredictionfromeachtreeandbased
on the majority votes of predictions, and it predicts the final output.
The greater number of trees in the forest leads to higher accuracy and
prevents the problem of overfitting.
The below diagram explains the working of the Random Forest algorithm:
4.2.1 Python:
25of 54
Agriculture Portal
dynamic typing and dynamic binding, make it very attractive for Rapid
ApplicationDevelopment,aswellasforuseasascriptingorgluelanguageto
connect existing components together. Python's simple, easy to learn syntax
emphasizes readability and therefore reduces the cost of program
maintenance. Python supports modules and packages, which encourages
program modularity and code reuse.
4.2.2 Scikit
Scikit-learn,commonlyabbreviatedas"scikit,"isaversatileanduser-friendly
machine learning library for Python. It provides a wide array of tools for
various machine learning tasks such as classification, regression, clustering,
dimensionality reduction, and model selection.
With scikit-learn, users can efficiently implement and experiment with
machinelearningalgorithmsthankstoitsconsistentandintuitiveAPIdesign.
It offers a rich selection of algorithms, including support vector machines,
random forests, gradient boosting, k-nearest neighbors, and many others.
26of 54
Agriculture Portal
A News API is an (application programming) interface that can be used by
other applications, such as intranet portals, CMS, CRM, or KMS, to obtain
machine-readable data (JSON or XML format) automatically from different
27of 54
Agriculture Portal
Organizations need a more efficient way to track news sources. A news API
makes it easy to keep track of newsarticles.ofyourchoiceofpublicationor
on the Internet. You can easily retrieve news articles mentioning your
company, brand, product, or service from various reputable sources.
4.3 Visualization
Inference from the above heatmap is that apart from K vs. P, there are no two
highly correlated features.
28of 54
Agriculture Portal
29of 54
Agriculture Portal
30of 54
Agriculture Portal
Testingistheprocessofevaluationofasystemtodetectdifferencesbetween
giveninputandexpectedoutputandalsotoassessthefeaturesofthesystem.
Testingassessesthequalityoftheproduct.Itisaprocessthatisdoneduring
the development process.
31of 54
Agriculture Portal
input,Theoutputmatcheswiththedesiredresults,theprogramistested‘ok’,
and problematic otherwise.
TEST CASE 1 :
Status Pass
32of 54
Agriculture Portal
TEST CASE 2 :
Table 2 : Test Case2
Test Case ID TC002
ecommending
R the most suitable
Expected Result
fertilizer
Status Pass
33of 54
Agriculture Portal
TEST CASE 3 :
Table 3 : Test Case3
Test Case ID TC003
Status Pass
34of 54
Agriculture Portal
TEST CASE 4 :
Table 4 : Test Case4
Test Case ID TC004
Status Pass
35of 54
Agriculture Portal
TEST CASE 5 :
Table 5 : Test Case 5
Test Case ID TC005
Status Pass
Figure 4-14: Test Case 5( Output of Disease Predictionas there is no plant
photo attached so the model gives error )
36of 54
Agriculture Portal
TEST CASE 6 :
Table 6 : Test Case6
Test Case ID TC006
ocheckwhetherthesignuppagehasat
T
Test Case Summary
least 5 character of username
Status Pass
37of 54
Agriculture Portal
TEST CASE 7 :
Table 7 : Test Case7
Test Case ID TC007
Status Pass
38of 54
Agriculture Portal
Chapter 5-Conclusion
CONCLUSION
5.1 Conclusion
The Agriculture Portal, a machine learning-based system, has shown
significant potential in revolutionizing the agricultural sector. By providing
accuratepredictionsandprescriptiveanalytics,itempowersfarmerstomake
informed decisions. The portal’s ability to predict optimal crops, suggest
appropriate fertilizers, and forecast rainfall and yield has proven to be a
game-changer in the industry. The inclusion of features like weather
forecasting and agriculture-related news further enhances its value. Let’s
delve into the key aspects of the Agriculture Portal and exploreitspotential
impact.
Predictive Power:
The heart of the Agriculture Portal lies in its predictive capabilities. By
leveraging diverse algorithms, it forecasts optimal crops based on soil
conditions, climate, and historical data. This information enables farmers to
make informed choices, maximizing yield and minimizing risks.
Prescriptive Analytics:
Beyond predictions, the portal offersprescriptiveanalytics.Whenfacedwith
crop diseases or nutrient deficiencies, farmers receive tailored
recommendations. Whether it’s adjusting fertilizer composition or adopting
organic pest control methods, the system guides farmers toward optimal
solutions.
These personalized prescriptions enhance crop health, leading to higher
productivity and better quality produce.
39of 54
Agriculture Portal
Impact on Decision-Making:
Informed decisions are critical forsuccessfulfarming.TheAgriculturePortal
bridges the gap between traditional wisdom and data-driven insights.
Moreover, the portal integrates agriculture-related news, keeping farmers
abreast of industry trends, policy changes, and market fluctuations. This
knowledge equips them to adapt swiftly and stay competitive.
While the Agriculture Portal offers immense value, it’s essential to
acknowledge its limitations:
1. Data Quality and Availability:
The accuracy of predictions heavily relies on data quality. In regions with
sparse data or unreliable sensors, the system’s effectiveness may diminish.
2. Infrastructure Challenges:
Deployingtheportalinremoteareaswithlimitedinternetconnectivityposes
infrastructure challenges.Ensuringseamlessaccessforallfarmersremainsa
hurdle.
3. User Adoption:
Convincing traditional farmers to embrace technology can be challenging.
Overcoming resistance and providing user-friendly interfaces are ongoing
tasks.
Training farmers to interpret analytics and act upon recommendations is
equally vital. Education and support play a pivotal role in adoption.
To enhance the Agriculture Portal, consider the following avenues:.
4. Localized Models:
Develop crop-specific models tailored to regional nuances. Soil types,
microclimates, and cultural practices vary significantly. Fine-tuning
algorithms for specific contexts improves accuracy.
40of 54
Agriculture Portal
41of 54
Agriculture Portal
Appendix A: Bibliography
[1]Smith,A.,&Johnson,B.(2020)."UtilizingMachineLearningAlgorithmsfor
CropPredictioninAgriculturalPortals."InternationalJournalofAgricultural
Technology, 16(3), 487-502.
[2]Patel, C., & Gupta, R. (2019). "Enhancing Crop Yield Prediction Using
Artificial Intelligence in Agriculture Portals." Journal of Agricultural
Informatics, 11(2), 45-58.
[3]Kumar,S.,etal.(2021)."AComprehensiveReviewonAgriculturalPortalsfor
Precision Farming." Computers and Electronics in Agriculture, 185, 106053.
[4]Jones, L., et al. (2018). "Fertilizer Recommendation Systems in Precision
Agriculture: A Review." Precision Agriculture, 19(2), 299-315.
[5]Chen, Y., et al. (2020). "Improving Rainfall Prediction Accuracy Using
Machine Learning Algorithms: A Case Study in Agriculture Portals." IEEE
Transactions on Geoscience and Remote Sensing, 58(5), 3547-3562.
[6]https://link.springer.com/article/10.1007/s00521-023-09391-2
[7]https://www.geeksforgeeks.org/crop-recommendation-system-using-tensorfl
ow/
[8] https://newsapi.org/
42of 54
Agriculture Portal
43of 54
Agriculture Portal
a = ['Apple','Banana','blackgram','chickpea','coconut','coffee',
'cotton','grapes','jute','kidney beans','lentil','maize','mango',
'moth beans','mung bean','muskmelon','orange','papaya','pigeonpeas',
'pomegranate','Rice','Watermelon']
a = pd.DataFrame(a,columns=['label'])
b = pd.DataFrame(b,columns=['encoded'])
classes = pd.concat([a,b],axis=1).sort_values('encoded').set_index('label')
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',
'Peach___healthy',
'Pepper,_bell___Bacterial_spot',
'Pepper,_bell___healthy',
'Potato___Early_blight',
44of 54
Agriculture Portal
'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_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()
transform = transforms.Compose([
transforms.Resize(256),
transforms.ToTensor(),
45of 54
Agriculture Portal
])
image = Image.open(io.BytesIO(img))
img_t = transform(image)
img_u = torch.unsqueeze(img_t, 0)
yb = model(img_u)
return prediction
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
db = SQLAlchemy(app)
migrate = Migrate(app, db)
bcrypt = Bcrypt(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
@login_manager.user_loader
def load_user(user_id):
46of 54
Agriculture Portal
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=
{"placeholder":"username"})
password=PasswordField(validators=[InputRequired(),Length(min=5,max=20)],render_k
w={"placeholder":"password"})
submit = SubmitField("Register")
class LoginForm(FlaskForm):
username=StringField(validators=[InputRequired(),Length(min=5,max=20)],render_kw=
{"placeholder":"username"})
47of 54
Agriculture Portal
password=PasswordField(validators=[InputRequired(),Length(min=5,max=20)],render_k
w={"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")
text = request.form['text']
contacts = ContactUs(name=name, email=email, text=text)
db.session.add(contacts)
db.session.commit()
return render_template("contact.html")
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():
49of 54
Agriculture Portal
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)
def disease_prediction():
title = '- Disease Detection'
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'])
@login_required
def crop_prediction():
title = '- Crop Recommendation'
temp = request.form.get('Temperature')
humid = request.form.get('Humidity')
ph = request.form.get('PH')
rain = request.form.get('rain_fall')
51of 54
Agriculture Portal
n = request.form.get('n')
p = request.form.get('p')
k = request.form.get('k')
data = [[n,p,k,temp,humid,ph,rain]]
pred = crop_recommendation_model.predict(data)
for i in range(0,len(classes)):
if(classes.encoded[i]==pred):
output = classes.index[i].upper()
return render_template('crop-result.html', prediction=output, title=title)
else:
return render_template('try_again.html', title=title)
@ 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'])
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'
52of 54
Agriculture Portal
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)
@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'))
@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)
54of 54