0% found this document useful (0 votes)
31 views

Csp Implementation

The document is a Community Service Project Report on the Smart Pest Control System, developed by students from Vasireddy Venkatadri Institute of Technology under the guidance of Mr. K. Bhushanm. The project aims to utilize deep learning for automated pest detection to enhance agricultural efficiency and reduce pesticide use. It includes an overview of community service projects, benefits, performed activities, and data collection methods related to the initiative.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Csp Implementation

The document is a Community Service Project Report on the Smart Pest Control System, developed by students from Vasireddy Venkatadri Institute of Technology under the guidance of Mr. K. Bhushanm. The project aims to utilize deep learning for automated pest detection to enhance agricultural efficiency and reduce pesticide use. It includes an overview of community service projects, benefits, performed activities, and data collection methods related to the initiative.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

A Community Service Project Report

on
Smart Pest Contol System
By
Rapolu Sravani - 21BQ1A05J5
Syed Suhana Khatun - 21BQ1A05M7
Tadiparthi Jhansi Yasaswini - 21BQ1A05M9
Padavala Tarun - 21BQ1A05P1

Under the Guidance of


Mr. K. Bhushanm

Department of Computer Science & Engineering


VASIREDDY VENKATADRI INSTITUTE OF TECHNOLOGY
An Autonomous Institute affiliated to JNTUK Kakinada,
accredited by NBA and NAAC with A Grade, Approved by
AICTE, ISO 9001:2008 Certified
Nambur, Pedakakani Mandal, Guntur Dt. 522508

1
CERTIFICATE

This is to certify that the Community Service Project report titled


Smart Pest Control System is being submitted by Rapolu Sravani,
Syed Suhana Khatun, Tadiparthi Jhansi Yasaswini, Padavala
Tarun bearing 21BQ1A05J5, 21BQ1A05M7, 21BQ1A05M9,
20BQ1A05P0 in IV B. Tech II semester Computer Science &
Engineering is a record bonafide work carried out by them. The
results embodied in this report have not been submitted to any other
University for the award of any degree.

Mr. K. Bhushanm Dr V Rama Chandran

Internal Guide Head of the Department

Signature of External Examiner with Date

2
DECLARATION FORMAT

We Rapolu Sravani, Syed Suhana Khatun, Tadiparthi Jhansi


Yasaswini, Padavala Tarun hereby declare that the Community
Service Project Report entitled “Smart Pest Control System”
done by me under the guidance of Mr. K. Bhushanm at
Vasireddy Venkatadri Institute of Technology, Nambur is
submitted in partial fulfilment of the requirements for the award of
degree in Bachelor of Technology

DATE :
PLACE :

SIGNATURE OF THE CANDIDATE


1. Rapolu Sravani
2. Syed Suhana Khatun
3. Tadiparthi Jhansi Yasaswini
4. Padavala Tarun

3
ACKNOWLEDGEMENT

With deep sense of gratitude, We acknowledgment the guidance, help & active
cooperation rendered by the following people whose guidance had submitted
the effort, which led to the successful completion of this project.

I express my profound gratitude to Chairman, Sri Vasireddy Vidya Sagar of


the college for providing me the opportunity to do the project work.

I would also like to extend my gratitude to Sri Dr. Y Mallikarjuna Reddy,


Principal, for providing me with all the facility that was required.

I would also like to extend my gratitude to Dr. V Ramachandran, Head of the


department of Computer Science & Engineering (CSE) for providing me with
all the facility that was required.

I would like to thank to Mr. K. Bhushanm project guide in charge who gave
me this opportunity to undergo industrial in this organization.

Our utmost thanks to the NSS Coordinator and all the Faculty members and
Non-Teaching Staff of the Department of Computer science & Engineering for
their support throughout our Community Service Project.

Our Family Members and Friends receive our deepest gratitude and love for
their support throughout our academic year.

Index
4
1. Overview of CSP
2. Problem Statement
3. Constraints/ Civic Policies
4. Performed Activities
5. Data Collection Methods
a. Approaches
b. Sample Data sheets
6. Technology/ Software Used
7. Implementation
8. Output Screens/Screenshots
9. Reflections on the Project
10.Conclusion

References Used (if any)

5
Overview of Community Service Project

Community Service Project Report

Submitted in accordance with the requirement for the degree


of………….

Name of the College : Vasireddy Venkatadri Institute of


Technology
Department : Computer Science and Engineering
Name of the Faculty Guide :
Duration of the CSP : 8 Weeks From: To:
Name of the Student : Rapolu Sravani,
Syed Suhana Khatun,
Tadiparthi Jhansi Yasaswini,
Padavala Tarun
Programmer of Study : B.Tech

Year of Study : IV

Register Number : 21BQ1A05J5

21BQ1A05M7

21BQ1A05M9

21BQ1A05P1

Date of Submission

6
Overview of Community Service Project
A community service project is an initiative undertaken by individuals or
groups to address a specific need or issue within a community. These projects
are typically aimed at improving the well-being, quality of life, or
circumstances of community members. Community service projects can take
various forms and may involve activities such as:

Volunteer Work: Engaging in hands-on activities such as cleaning up parks,


serving meals at homeless shelters, tutoring students, or providing
companionship to elderly residents.

Fundraising: Organizing events or campaigns to raise funds for local charities,


schools, or other community organizations that support important causes.

Awareness Campaigns: Creating and promoting initiatives to raise awareness


about social, environmental, or health issues within the community, such as
mental health awareness campaigns or recycling drives.

Skill-building Workshops: Offering workshops or training sessions to teach


valuable skills to community members, such as financial literacy, job readiness,
or computer skills.

Environmental Initiatives: Undertaking projects to protect and improve the


environment, such as planting trees, cleaning up litter, or promoting recycling
and conservation efforts.

Community Development Projects: Working on projects that aim to enhance the


infrastructure or facilities within the community, such as building playgrounds,
renovating community centers, or improving access to clean water.

Support Services: Providing support services to vulnerable populations within


the community, such as organizing food drives, offering free healthcare clinics,
or assisting with disaster relief efforts.

7
Community service projects can focus upon the following areas:
1. Water facilities and drinking water availability
2. Health and hygiene
3. Stress levels and coping mechanisms
4. Health intervention programmes
5. Horticulture
6. Herbal plants
7. Botanical survey
8. Zoological survey
9. Marine products
10. Aqua culture
11. Inland fisheries
12. Animals and species
13. Nutrition
14. Traditional health care methods
15. Food habits
16. Air pollution
17. Water pollution
18. Pest Detect & Control
19. Soil protection
20. Renewable energy
21. Plant diseases
22. Yoga awareness and practice
23. Health care awareness programmes and their impact
24. Use of chemicals on fruits and vegetables
25. Organic farming
26. Crop rotation
27. Floury culture
28. Access to safe drinking water
29. Geographical survey
30. Geological survey
31. Sericulture
32. Study of species
33. Food adulteration
34. Incidence of Diabetes and other chronic diseases
35. Human genetics
36. Blood groups and blood levels
37. Animal husbandry
38. Mother and child health

8
BENEFITS OF COMMUNITY SERVICE PROJECT
Learning Outcomes
 Positive impact on students’ academic learning in view of the classroom to field and
vice versa experience
 Improves students’ ability to apply what they have learned in “the real world”
 Positive impact on academic outcomes such as demonstrated complexity of
understanding, problem analysis, problem-solving, critical thinking, and cognitive
development
 Improved ability to understand complexity and ambiguity

Personal Outcomes
 Greater sense of personal efficacy, personal identity, compassion, spiritual growth,
and moral development
 Greater interpersonal development, particularly the ability to work well with others,
and build leadership and communication skills

Social Outcomes
 Learning service as a graduate attribute
 Reduced stereotypes and greater inter-cultural understanding
 Improved social responsibility and citizenship skills
 Greater involvement in community service after graduation

Career Development
 Connections with professionals and community members for learning and career
opportunities
 Greater academic learning, leadership skills, and personal efficacy can lead to greater
opportunity Relationship with the Institution
 Stronger relationships with faculty
 Greater satisfaction with college

9
REPORT OF THE MINI PROJECT
Introduction:
Pest infestations are a major challenge in agriculture, often leading to reduce yields and
financial losses for farmers. Traditional pest control methods rely on manual inspection,
which can be time-consuming, labour-intensive, and sometimes inaccurate. By using deep
learning for automated pest detection, we can improve accuracy, speed up identification, and
enable proactive pest management, ultimately supporting more sustainable farming practices.

Problem Statement:
This project aims to develop a Smart Pest Control System powered by deep learning that can
identify different pests affecting crops and suggest effective control measures. The system
will analyse images of crops, detect pests, and provide farmers with targeted pesticide
recommendations, including eco-friendly alternatives. By offering real-time insights, this
project helps farmers reduce crop damage, avoid excessive pesticide use, and enhance overall
farm productivity.

Objective:
Detect Pests Early: Detect Identify pests in their early stages before they spread, allowing
farmers to take preventive measures and minimize crop damage. Reduce the need for
excessive pesticide use by targeting pests before they reach infestation levels.

Classify Pests Accurately: Utilize Convolutional Neural Networks (CNNs) to recognize and
differentiate between various pest species. Ensure high accuracy in pest identification to
avoid misdiagnosis and unnecessary pesticide application

Automate Pest Identification: Develop a system that can analyse crop images and detect
pests based on deep learning models without manual intervention. Use image processing
techniques to enhance image quality and improve detection reliability.

Provide Effective Control Strategies: Provides precise pesticide recommendations based on


the detected pest species, ensuring the most effective treatment. Suggest biological control
methods such as introducing natural predators for eco-friendly pest management. Include
organic solutions for farmers who prefer sustainable farming practices.

Enhance Agricultural Efficiency: Reduce crop losses and increase productivity by enabling
timely and precise pest control. Minimize pesticide overuse, reducing costs for farmers and
promoting a healthier farming environment.

User-Friendly Interface: Design a simple and accessible web interface where farmers can
upload images, receive pest diagnoses, and view recommended treatments. Ensure that the
platform is mobile-friendly, allowing farmers to use it directly from their smartphones while
in the field.

10
Constraints and Policies
1. Data Privacy and Policy: Ensure that all pest-related data collected from farmers,
including crop images and field conditions, is securely stored and handled in compliance
with data privacy regulations. Implement encryption, access controls, and anonymization
techniques to protect sensitive agricultural information.
2. Ethical Use of Data: Obtain explicit user consent before collecting and using their data
for pest detection. Ensure the data is solely used for improving pest management
strategies and not misused for any commercial or unauthorized purposes.
3. Model Accuracy and Reliability: Strive for high accuracy in pest identification and
control recommendations to prevent unnecessary pesticide use or undetected infestations.
Regularly update the model with new pest images, environmental factors, and expert
feedback to enhance decision-making.
4. Resource Constraints: Optimize the AI models for efficient processing on low-end
devices and limited bandwidth networks. Ensure that deep learning algorithms function
smoothly without excessive computational requirements to support accessibility for all
farmers.
5. Regulatory Compliance: Adhere to local, national, and international regulations
governing pesticide usage, environmental safety, and agricultural best practices. Work
closely with agricultural experts and regulatory bodies to ensure compliance with industry
standards.
6. Transparency and Accountability: Clearly communicate how the model works and the
basis for pest identification and control recommendations. Provide farmers with
confidence scores to help them understand the accuracy of predictions and make informed
decisions.
7. Remedies and Recommendations: Ensure that the system offers a balanced approach to
pest management, including chemical, biological, and organic control methods. Avoid
over-reliance on chemical pesticides and encourage eco-friendly solutions.
8. User Education and Training: Provide user-friendly guides, video tutorials, and
interactive tools to help farmers understand pest identification results, apply control
measures correctly, and adopt integrated pest management practices.
9. Feedback Mechanism: Implement a robust feedback system where farmers can report
incorrect pest identifications, ineffective treatments, and system errors. Use this feedback
to improve the AI model, refine recommendations, and enhance user experience.
10. Sustainability and Environmental Impact: Promote sustainable agriculture by
encouraging eco-friendly pest control methods, reducing chemical pesticide usage, and
integrating natural pest predators. Support biodiversity and long-term soil health through
AI-driven sustainable farming insights.

11
Performed Activities
1. The general activities to be done:

a. Preliminary Surveys (Level 1 and 2)


b. Community Awareness Campaigns
c. Community Immersion Programme
d. Community Exit Report

2. Day / Week wise Activity:

Day / Week Activity Done Learning outcome


No

1 We went to the Pedda Kakani village We study how people are involved in
centre and observed the people there are the work and adjusted to help others
doing everyday chores and ask them
about village

2 We visited to other people's house and We learned how people are


asked them how they are do agriculture, efficiently harnessing natural
what they use to farm the land resources to farm the land and they
face problem to identify the plant
diseases occur

3 As we conducted our assessment, we Recognizing healthcare disparities


identified a significant issue: limited led to efforts to enhance medical
access to healthcare facilities and medical services and infrastructure, ensuring
services within the community. equitable access for all community
members.

4 As we surveyed in the village, we came Drainage is not clean which leads to


to know that drainage is not cleaned increase of pests.
regularly.

5 Engaged in cleaning the surroundings of Due to lack of proper knowledge


a local pond where a lot of plastic bottles about keeping the community clean,
and polythene bags were accumulated. people neglected the need for proper
maintenance of the pond.

6 We saw people are meeting at location We learned we’ve to gathering to

12
near the farm to learn how they employ discuss ways to tackle our difficulties
water usage for their crops from pond’s

7 With all the surveys that we have done, If the drainage problem is solved,
we came to know that major problem in growth of mosquitoes will rapidly
the village is improper drainage cleaning, decrease and consequently diseases
Identification of diseases of plants. such as dengue and malaria will
reduce gradually.

3.Data Collection Methods


Data collection is essential for evaluating the effectiveness and impact of community service
projects. Here are some common data collection methods used in community service
projects:

Surveys and Questionnaires: Designing and distributing surveys or questionnaires to


community members, volunteers, beneficiaries, or stakeholders to gather information about
their needs, experiences, feedback, and satisfaction with the project.

Interviews: Conducting structured or semi-structured interviews with key stakeholders,


including community leaders, project participants, volunteers, and beneficiaries, to gain in-
depth insights into their perspectives, challenges, and the impact of the project.

Focus Group Discussions: Organizing focus group discussions with small groups of
community members or stakeholders to facilitate dialogue, explore opinions, and generate
ideas for improvement or expansion of the project.

Observation: Engaging in direct observation of project activities and interactions within the
community to gather qualitative data on participation levels, community engagement, and the
overall implementation of the project.

Document Review: Reviewing project documentation, such as reports, meeting minutes,


attendance records, and financial statements, to assess project progress, adherence to
timelines, and resource utilization.

Community Mapping: Creating maps or diagrams to visually represent community


resources, needs, assets, and relationships, which can help identify gaps, opportunities, and
potential collaborations for the project.

Outcome Measurement Tools: Using standardized tools and indicators to measure specific
project outcomes and impacts, such as changes in knowledge, behavior, or quality of life
among project beneficiaries.

Social Media Monitoring: Monitoring social media platforms and online forums to gather
feedback, track engagement, and assess the reach and visibility of the project within the
community and beyond.

13
Case Studies: Conducting in-depth case studies of individual beneficiaries or success stories
to capture personal experiences, challenges overcome, and the tangible impact of the project
on their lives.

Community Feedback Mechanisms: Establishing feedback mechanisms, such as suggestion


boxes, helplines, or community meetings, to encourage ongoing communication,
participation, and input from community members throughout the project lifecycle.

By utilizing a combination of these data collection methods, community service projects can
gather comprehensive and meaningful data to inform decision-making, improve project
outcomes, and demonstrate accountability to stakeholders.

Sample Copy of Data Collection :

Day 1:

Respondents Name : Sk.Nazeema

Age : 28

Education : Intermediate

Major Source of Income : Electrician

Children : 2 Daughters

Family Details : 1 male and 3 female

Family Income : approx. 3 lakhs

Notable Issues in the village : Stagnant Drainage water

Photo with the Respondent :

14
Respondents Name : Vara Lakshmi

Age : 30

Education : N/A

Major Source of Income : Masonary

Children : 1 Daughter

Family Details : 1 male and 2 female

Family Income : approx. 2 lakhs

Notable Issues in the village : Transportation

Photo with the Respondent :

15
Day 2:

Respondents Name : Mahalakshmi

Age : 60

Education : Third Standard

Major Source of Income : Fruit Business

Children : 1 Son

Family Details : 2 male and 3 female

Family Income : approx. 1 lakh

Notable Issues in the village : Lack of Health Care

Photo with the Respondent :

16
Day 3:

Respondents Name : Nagendram

Age : 50

Education : N/A

Major Source of Income : Farmer

Children : 1 Daughter, 1 son

Family Details : 2 male and 2 female

Family Income : approx. 3 lakhs

Notable Issues in the village : Irrigation Problem

Photo with the Respondent :

17
Respondents Name : K. Siva Kumar

Age : 32

Education : N/A

Major Source of Income : Pest Control Worker

Children : 2 Daughters

Family Details : 1 male and 1 female

Family Income : approx. 3 lakhs

Notable Issues in the village : Stagnant Drainage water

Photo with the Respondent :

18
Respondents Name : Suresh

Age : 45

Education : 10

Major Source of Income : Shop Keeper

Children : 2 Daughters

Family Details : 1 male and 3 female

Family Income : approx. 3 lakhs

Notable Issues in the village : Transportation

Photo with the Respondent :

19
Respondents Name : Sk.Reena

Age : 30

Education : 10

Major Source of Income : House Wife

Children : 1 Son

Family Details : 2 male and 1 female

Family Income : approx. 1 lakhs

Notable Issues in the village : Water Stagnation, Dogs in streets

Photo with the Respondent :

20
Respondents Name : U.Jagadesh

Age : 20

Education : 10

Major Source of Income : Mechanic

Children : 2 Sons

Family Details : 2 male and 1 female

Family Income : approx. 1 lakhs

Notable Issues in the village : Lack of Health Care

Photo with the Respondent :

21
Implementation
Data Collection: Gathered a dataset of images containing various pests and healthy crops.
The dataset includes different types of pests affecting multiple crops to ensure diversity. The
images are labeled to indicate the pest type for accurate classification.

Data Preprocessing: Gathered a dataset of images containing various pests and healthy
crops. The dataset includes different types of pests affecting multiple crops to ensure
diversity. The images are labeled to indicate the pest type for accurate classification.

Model Selection: Chose Convolutional Neural Networks (CNNs) for pest classification
due to their strong feature extraction capabilities.

Model Training: Split the dataset into training, validation, and testing sets. Train the
model on the training data and validate its performance using the validation set. Fine-tune
hyperparameters as necessary to improve performance and prevent overfitting.

Model Evaluation: Assessed the model using accuracy, precision, recall, and F1-score.
Achieved high accuracy in pest classification while minimizing false predictions. Identified
misclassified images and adjusted model parameters accordingly.

22
Deployment: Deploy it for real-world use. This involve integrating it into a web, setting
up an API to handle user requests for pest classification. Developed a frontend interface
where users can upload crop images and receive pest identification results along with pest
control suggestions.

Monitoring and Maintenance: Continuously monitor the performance of the model in


the production environment and update it as needed. As new pest species emerge or
additional data becomes available there is need to retrain the model or fine-tune its
parameters to ensure accurate detection.

Compiled a dataset of images containing healthy crops and pest-affected


crops, covering 10 pest species across 5 different crop types. The dataset consists of 10,000
images, ensuring a well-balanced and diverse representation. To maintain consistency, all
images were resized and normalized for better model performance. A Convolutional Neural
Network (CNN) model was selected for pest classification. The dataset was divided into
training , validation , and testing sets. The model was trained on 8,000 images over 10
epochs, using a batch size of 16 and a learning rate of 0.001. After training, the model
achieved an accuracy of 92.5%, demonstrating reliable pest detection capabilities.

Source code:
from flask import Flask, request, render_template, redirect, url_for, flash, session, jsonify

from flask_pymongo import PyMongo

import numpy as np

import pandas as pd

from PIL import Image

from io import BytesIO

import io

import json

from markupsafe import Markup

from user.utils.pestid import pest_name

from datetime import datetime

23
import torch

import timm

import torch.nn as nn

from torchvision import transforms

import os

from werkzeug.utils import secure_filename

from bson import ObjectId

import albumentations as A

from albumentations.pytorch.transforms import ToTensorV2

app = Flask(__name__)

app.config['MONGO_URI'] = "mongodb://localhost:27017/pest"

mongo = PyMongo(app)

UPLOAD_FOLDER = 'user/static/'

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

username = "officer"

password = "officer123"

app.secret_key = 'pest_detection_key'

# image prediction ..........................................................................................................................

# Define your class labels as a list

pest_classes = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',

'21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39',
'40']

# Load the model

pest_model_path = 'models/pest_model.pth'

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

class InsectModel(nn.Module):

def __init__(self, num_classes):

super(InsectModel, self).__init__()

self.num_classes = num_classes

24
self.model = timm.create_model('vit_base_patch16_224', pretrained=True,
num_classes=num_classes)

def forward(self, image):

return self.model(image)

def train_transform():

return A.Compose([

A.HorizontalFlip(),

A.RandomRotate90(),

A.RandomBrightnessContrast(),

A.Resize(224, 224),

ToTensorV2()])

def valid_transform():

return A.Compose([

A.Resize(224,224),

ToTensorV2()])

model = InsectModel(num_classes=40)

model.load_state_dict(torch.load(pest_model_path, map_location=device))

model.to(device)

model.eval()

def predict_image(img, model=model, classes=pest_classes):

transform = valid_transform()

image = Image.open(io.BytesIO(img))

transformed = transform(image=np.array(image))

img_t = transformed['image']

# Convert PyTorch tensor to NumPy array

img_np = img_t.numpy().astype(np.float32) # Convert image to float32

img_np /= 255.0 # Normalize to [0, 1] range

# Convert NumPy array back to PyTorch tensor

25
img_u = torch.from_numpy(img_np).unsqueeze(0).to(device)

with torch.no_grad():

outputs = model(img_u)

_, preds = torch.max(outputs, dim=1)

prediction = classes[preds.item()]

return prediction

# set path to each webpages..................................................................................................

@app.route('/')

def home():

title = 'Pest - Home'

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

@ app.route('/predict')

def predict():

title = 'Prediction'

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

@ app.route('/user_query')

def user_query():

title = 'User Queries'

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

@app.route('/officer_login', methods=['GET'])

def officer_login():

title = 'Officer - Login'

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

@ app.route('/officer')

def officer():

title = 'Officer - Home'

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

# prediction.................................................................................................................

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

def make_prediction():

title = 'Pest - Detection'

pest_collection = mongo.db.pest_details

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('home.html', title=title)

try:

img = file.read()

prediction = predict_image(img) # Get the prediction

name=pest_name.get(prediction)

pest = pest_collection.find_one({'name': name })

return render_template('result.html', prediction=prediction, pest=pest, title=title)

except Exception as e:

print(f"Prediction error: {str(e)}")

pass # Handle the exception or error accordingly

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

@app.route('/view_query')

def display_data():

data = list(mongo.db.user_query.find().sort('timestamp', -1))

for index, query in enumerate(data, start=1):

query['serial'] = index

# Get the current date and time

current_datetime = datetime.now()

# Format the current date and time as a string

27
formatted_current_datetime = current_datetime.strftime('%Y-%m-%d %H:%M:%S')

# Format the timestamp in your query data with a space between date and time

for query in data:

query['date'] = query['timestamp'].strftime('%Y-%m-%d')

query['time'] = query['timestamp'].strftime('%H:%M:%S')

return render_template('view_query.html', title = 'User Queries', data=data,


current_datetime=formatted_current_datetime)

@app.route('/view_query')

def view_query():

title = 'User Queries'

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

# officer login page validation..............................................................................................

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

def login():

if request.method == 'POST':

uname = request.form['username']

pwd = request.form['password']

if uname == username and pwd == password:

# Successful login - redirect to officer page

return redirect(url_for('officer'))

else:

# Incorrect credentials - redirect back to login page with a flash message

flash('Invalid username or password. Please try again.', 'error')

return redirect(url_for('login'))

return render_template('officer_login.html', title='Officer - Login')

# pest details...............................................................................................................

@app.route('/officer')

def pest_info():

with open("dictionary.json", "r") as f:

28
# Read the dictionary file and convert it to a JSON object

pest_info = list[json.load(f)]

return render_template('officer.html', pest_info=pest_info)

@app.route('/detailed_view/<pest_id>')

def detailed_view(pest_id):

# pest = pest_dic.get(pest_id)

# return render_template('detailed_pestview.html', pest=pest, title="Pest - Description")

id=pest_id

pest_collection = mongo.db.pest_details

name=pest_name.get(pest_id)

try:

pest = pest_collection.find_one({'name': name })

if pest:

return render_template('detailed_pestview.html', pest=pest, pest_id=id, title="Pest -


Description")

else:

return "Pest not found"

except Exception as e:

return f"Error: {str(e)}"

@app.route('/detailed_view/<pest_id>', methods=['GET','POST'])

def edit_pest(pest_id):

id = pest_id

pest_collection = mongo.db.pest_details

name = pest_name.get(pest_id)

query = {'name': name}

if name:

if request.method == 'POST':

# Handle text information update

description = request.form.get('description')

29
prevention = request.form.get('prevention')

pesticides = request.form.get('pesticides')

pest_collection.update_one(query, {'$set': {

'description': description,

'prevention': prevention,

'pesticides': pesticides

}})

# Handle delete images

deleted_images = request.form.getlist('deleted_images')

for image_path in deleted_images:

pest_collection.update_one(query, {'$pull': {'pest_image': image_path}})

# Handle image upload

if 'image' in request.files:

file = request.files['image']

if file:

filename = secure_filename(file.filename)

image_name = "pesticides/" + filename

file_path = os.path.join(app.config['UPLOAD_FOLDER'], image_name)

file.save(file_path)

pest_collection.update_one(query, {'$push': {'pest_image': image_name}})

return redirect(url_for('edit_pest', pest_id=pest_id))

else:

pest_data = pest_collection.find_one(query)

return render_template('detailed_pestview.html', pest=pest_data, pest_id=id)

# submit user query .................................................................................................................

@app.route('/submit_query', methods=['POST'])

def submit_query():

data = {

30
'name': request.form.get('Name'),

'email': request.form.get('Email'),

'message': request.form.get('Message'),

'timestamp': datetime.now()

mongo.db.user_query.insert_one(data)

return render_template('user_query.html')

@app.route('/')

def logout():

# Clear session data

session.clear()

# Redirect to the login page or any other page after logout

return redirect(url_for('home'))

Test Results

fig 1: Dashboard For pest control system

31
fig 2: Pest detection page of the Project

fig 3: Sample output

Reflections on the Project


Data Collection Challenges: One of the initial hurdles in the project is gathering a diverse
and representative dataset of plant images encompassing various species and diseases. This
process likely involved visiting farms, gardens, agricultural research centers, and
coordinating with experts to identify and document different diseases.

Data Preprocessing Complexity: Preprocessing the collected data is intricate than


anticipated. Tasks such as image resizing, normalization, and augmentation are essential for
training a robust model. However, ensuring consistency and quality across a large dataset can
be time-consuming.

Model Selection and Training Iterations: Choosing an appropriate deep learning


architecture and fine-tuning its parameters likely required several iterations. Different

32
architectures are tested, and hyperparameters adjusted to optimize performance. Balancing
model complexity with computational resources and accuracy was likely a key consideration.

Evaluation and Performance Analysis: Evaluating the trained model's performance


involved more than just looking at accuracy metrics. Understanding precision, recall, and F1-
score provided deeper insights into the model's strengths and weaknesses. Analyzing
misclassifications helped identify patterns and areas for improvement.

Deployment Considerations: Deploying the model for real-world use posed its own set of
challenges. Ensuring the model's robustness to variations in lighting, weather conditions, and
plant growth stages was essential for reliable performance.

Ethical and Societal Implications: Throughout the project, ethical considerations regarding
the use of AI in agriculture likely surfaced. Ensuring fairness in model predictions,
transparency in decision-making, and addressing potential biases were important aspects.
Additionally, considering the impact of the technology on farmers' livelihoods and
agricultural practices was crucial.

In summary, reflecting on the project of plant disease detection involves acknowledging the
challenges faced, understanding the lessons learned, and identifying opportunities for further
innovation and improvement in the field. It's a process of continuous learning and adaptation
to address the complex challenges of agricultural sustainability and food security.

Conclusion
The Smart Pest Control System is a step forward in modern agriculture, using deep learning
to make pest detection more accurate and efficient. By leveraging technology, this system
helps farmers identify pests early and take the right measures to protect their crops.

Effective Use of Technology: This project demonstrates the feasibility of using deep
learning and computer vision for accurately identifying pests and recommending suitable
pesticides. By integrating AI-based detection with a user-friendly web interface, farmers can
efficiently monitor pest infestations and take timely action.

33
Challenges and Solutions: During development, we faced challenges like collecting
data, training an accurate model, and making real-time predictions. However, by improving
our CNN model and fine-tuning the system, we created a reliable and efficient pest detection
solution.

Impact on Agriculture: The implementation of this system has the potential to


revolutionize pest management by enabling early detection, reducing excessive pesticide use,
and ultimately improving crop yield and quality. It also provides accurate recommendations,
helping to protect the environment and support sustainable farming.

Continuous Improvement: While this project marks a significant milestone, it also lays
the foundation for future enhancements. Further improvements may include integrating IoT
devices for real-time monitoring, expanding the pest database, and incorporating drone-based
surveillance to enhance accuracy and efficiency.

In conclusion, the Smart Pest Control System combines technology and agriculture to
address a key farming issue. By using AI-driven pest detection, it helps farmers identify pests
early, reduce pesticide use, and improve crop health. This not only boosts food security but
also promotes eco-friendly farming and supports sustainable agriculture, demonstrating how
technology can transform modern farming.

References
[1] Chaudhary, A., Jha, K., & Tripathi, R. (2020). Deep learning-based pest detection and
classification in agricultural crops. Computers and Electronics in Agriculture, 175,
105527.
[2] Mittal, S., Chouhan, R., Agarwal, S., & Dey, A. (2021). A deep learning-based approach
for pest detection in crops using UAV images. Expert Systems with Applications, 182,
115121.

34
[3] Dhaka, V., Meena, S. V., Rani, G., Sinwar, D., Kavita, & Singh, A. (2021). A deep
learning approach for pest detection using convolutional neural networks. Artificial
Intelligence in Agriculture, 5, 24-30.
[4] Chen, J., Zhang, D., Zhao, Y., Chen, L., & Li, Y. (2021). Automatic pest detection and
recognition using deep learning in agricultural fields. Computers and Electronics in
Agriculture, 184, 106081.
[5] Fuentes, A., Yoon, S., Kim, S. C., & Park, D. S. (2017). High-performance deep learning-
based method for real-time insect pest recognition on field crops. Sensors, 17(12), 2932.
[6] Larios, N., Deng, H., Zhang, H., Sarpola, M., Yuen, J., Paasch, R., & Dietterich, T.
(2008). Automated insect identification through concatenated histograms of local
appearance features: A case study of bees. Pattern Recognition, 42(5), 814-824.
[7] Ramesh, D., & Vydeki, D. (2018). Recognition and classification of paddy leaf diseases
using deep learning algorithms. International Journal of Computer Applications, 180(20),
20-25.
[8] Jadhav, P., & Patil, J. (2022). Deep learning approach for pest identification and
classification in agriculture. Applied Artificial Intelligence, 36(1), 204-219.
[9] Ramesh, D., & Vydeki, D. (2018). Recognition and classification of paddy leaf diseases
using deep learning algorithms. International Journal of Computer Applications, 180(20),
20-25.
[10] Kumar, A., Singh, A., & Pandey, A. (2021).* CNN-based automatic pest detection
system for precision agriculture. Multimedia Tools and Applications, 80(5), 7319-7335

35

You might also like