0% found this document useful (0 votes)
43 views94 pages

CPP Final Elite Squad

The Smart Farming Website project report outlines the development of an application aimed at enhancing agricultural practices through technology. It focuses on providing farmers with real-time data, personalized recommendations, and tools for optimizing crop management, thereby addressing challenges like resource wastage and limited access to technology. The project incorporates features such as an AI engine for disease detection, weather advisories, and a chatbot for user support, ultimately aiming to improve productivity and sustainability in farming.

Uploaded by

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

CPP Final Elite Squad

The Smart Farming Website project report outlines the development of an application aimed at enhancing agricultural practices through technology. It focuses on providing farmers with real-time data, personalized recommendations, and tools for optimizing crop management, thereby addressing challenges like resource wastage and limited access to technology. The project incorporates features such as an AI engine for disease detection, weather advisories, and a chatbot for user support, ultimately aiming to improve productivity and sustainability in farming.

Uploaded by

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

SMART FARMING WEBSITE

A PROJECT REPORT ON

SMART FARMING WEBSITE

SUBMITTED IN PARTIAL FULFILLMENT OF THE


REQUIREMENT FOR THE DIPLOMA IN

INFORMATION TECHNOLOGY

BY

Roll no Name
49 Tanishq Sanas
24 Onkar Shelke
57 Sandesh Lendave
22 Avinash Pansare

UNDER THE GUIDENCE OF

Mrs. Rutuja Goradkar

VPM’S POLYTECHNIC, THANE


College Campus Building, 1, Chendani Bunder Road, Thane West, Maharashtra (400601)

Website: www.vpmthane.org.in Email ID : [email protected]

Phone: (91-22) 2536 4494

INFORMATION TECHNOLOGY 1 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

CERTIFICATE

This is to certify that following third year computer engineering students have
successfully and satisfactorily completed their project work, entitled “SMART
FARMING WEBSITE”, in partial fulfilment of the requirement for the diploma in
Information Technology for the academic year 2024-2025

Roll no Name
49 Tanishq Sanas
24 Onkar Shelke
57 Sandesh Lendave
22 Avinash Pansare

PROJECT GUIDE H.O.D.


(Mrs. Rutuja Goradkar) (Mrs. Usha Raghavan)

Principal
External Examiner (Dr. D K NAYAK)

INFORMATION TECHNOLOGY 2 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

ACKNOWLEDGEMENT

A successful project is a fruitful estimation of efforts by many people, some


were involved, and some others, quietly encourage and supported from the background.
I express my deep and sincere gratitude of department of Information
Technology, which provided me an opportunity in fulfilment by most cherished desired
of reaching my goals.
I am very thankful to Mrs. Usha Raghavan, Head Of Department, Computer
Engineering for helping me to finalize the nature and the site of the project work and for
her valuable guidance and her constant co- operation and support.
Foremost, I would like to sincerely thank to Mrs. Rutuja Goradkar,
Lecturer, Department of Computer Engineering for helping me to finalize the native and
the site of my project work and for her valuable guidance and her constant co-operation
and support and suggestions improvement.
I am very thankful to respected principal Mr. D.K. Nayak for providing us with
the necessary infrastructure to carry out this project.
I also acknowledgement gratitude for the efforts of all our friends who have
helped us directly or indirectly through their invaluable suggestion and advices.

Enrollment No. Name


2200070241 Tanishq Sanas
2200070210 Onkar Shelke
2200070250 Sandesh Lendave
2200070208 Avinash Pansare

INFORMATION TECHNOLOGY 3 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

Certificate Of Python:

INFORMATION TECHNOLOGY 4 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

ABSTRACT

Smart farming applications are transforming the agricultural industry by


improving farming practices and increasing efficiency. This project aims to
develop a smart farming application that will assist farmers in making
informed decisions regarding crop practices, provide relevant news and
updates, offer real-time weather information, and enable early detection of
diseases. The application will help farmers to optimize their farming
operations, reduce labour costs, and increase productivity.
By providing real-time data and insights through advanced analytics,
the application will enable farmers to make informed decisions about their
farming operations. The project focuses on creating and using knowledge
through technology, rather than just bringing information technology to
agriculture. The smart farm application will be accessible to farmers with
little or no technical expertise.
The crop practices feature of the application will provide farmers with
personalized recommendations for planting, fertilizing, and harvesting crops
INFORMATION TECHNOLOGY 5 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

based on soil analysis and historical data. The news feature will provide users
with relevant agricultural news and updates from trusted sources. The
weather feature will allow farmers to monitor real-time weather conditions,
including temperature, humidity, rainfall, and wind speed. Finally, the
disease detection feature will use machine learning algorithms to identify
potential diseases and provide suggestions for appropriate action.
Overall, this smart farming application has the potential to
revolutionize farming practices and provide farmers with valuable insights
that can increase crop yield and reduce losses.

CHAPTER 1
INTRODUCTION

INFORMATION TECHNOLOGY 6 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

INTRODUCTION
Welcome to our Smart Farming website, where technology meets agriculture to
revolutionize the way we grow, manage, and harvest crops. Smart farming, or precision
agriculture, uses cutting-edge technologies such as IoT (Internet of Things), data
analytics, sensors, and AI-driven solutions to optimize farming practices, improve crop
yield, and reduce environmental impact.
Features of the project:

Management Side:
Secure Login and
Logout
Package Management
Bookings Management
Additional Features
User Interface (UI)
Design
Navigation Menu

Public-Side:
Home Page/Display Welcome
Message List Active packages
'About Us' Content
View Management Contact
Information Send Inquiries

Client-Side:
Update booking
details Cancel
booking Profile
Page
Update System
Information/Credentials Logout

INFORMATION TECHNOLOGY 7 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

PROBLEM DEFINITION
Problem Statement:
Modern agriculture faces significant challenges, including inefficient resource use
(water, fertilizers, and energy), unpredictable weather patterns, labor shortages,
and the need to increase crop yields to meet growing global food demand.
Traditional farming methods often lack real-time data and actionable insights,
leading to suboptimal decision-making, reduced productivity, and environmental
degradation. Farmers, especially small-scale ones, struggle to access affordable,
user-friendly tools that integrate advanced technologies like IoT, AI, and data
analytics into their daily operations.

Key Issues:
1. Lack of Real-Time Monitoring: Farmers often rely on manual observation or
outdated systems, making it difficult to monitor soil conditions, crop health, or
weather changes effectively.
2. Resource Wastage: Over-irrigation, excessive fertilizer use, and poor energy
management increase costs and harm the environment.
3. Limited Access to Technology: Many farmers lack the knowledge, funds, or
infrastructure to adopt smart farming solutions.
4. Data Overload: Even when data is available, it’s often fragmented or
overwhelming, leaving farmers unsure how to act on it.
5. Scalability Challenges: Solutions designed for large farms may not suit
smallholders, creating a gap in accessibility and applicability.

Objective:
A smart farming website aims to address these issues by providing an accessible,
centralized platform that delivers real-time data, actionable insights, and affordable
tools to optimize farming practices, improve yields, reduce waste, and promote
sustainable agriculture for farmers of all scales.

INFORMATION TECHNOLOGY 8 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

CHAPTER 2
LITERATURE SURVEY

INFORMATION TECHNOLOGY 9 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

LITERATURE SURVEY

Concise Literature Survey on AGRO-SETU and Related Agricultural Technology


1. Introduction
AGRO-SETU, as depicted in the image, is an AI-driven platform developed by the "Elite Squad" to
revolutionize agriculture by enhancing productivity, sustainability, and food security. This aligns with
the growing field of Agriculture 4.0, which integrates AI, data analytics, and real-time insights into
farming practices (Liakos et al., 2018).
2. AI Engine and Personalized Recommendations
The "AI Engine" feature, offering personalized farming recommendations, builds on precision
agriculture research. AI models, such as machine learning, optimize crop management based on soil,
weather, and historical data (Kamilaris & Prenafeta-Boldú, 2018), a trend AGRO-SETU appears to
adopt.
3. Soil Predictor and Crop Suggestions
The "Soil Predictor" feature leverages soil health analysis, a focus of modern agriculture using IoT and
spectroscopic tools to tailor crop choices (Viscarra Rossel et al., 2016). This reflects AGRO-SETU's
commitment to data-driven sustainability.
4. Weather Advisor
The "Weather Advisor" provides real-time updates and advisories, aligning with studies on weather-
based decision support systems to mitigate climate risks (Challinor et al., 2018), a critical need in
adaptive farming.
5. Fertilizer Optimization
The "Fertilizer Optimization" feature aims to maximize yield while minimizing environmental impact,
echoing research on AI-based fertilizer management to reduce runoff and emissions (Zhang et al., 2020).
6. Yojana Awareness and Chatbot Support
The "Yojana Awareness" and "Chatbot Support" features address socio-economic and educational gaps.
Literature highlights the role of extension services and NLP-based chatbots in improving farmer access
to schemes and knowledge (Birner et al., 2009; Mishra et al., 2021).
7. Conclusion
AGRO-SETU integrates cutting-edge agricultural technologies, aligning with precision farming trends.
Its success will hinge on practical implementation and farmer adoption, positioning it as a potential
leader in smart agriculture.

INFORMATION TECHNOLOGY 10 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

CHAPTER 3
SCOPE OF PROJECT

INFORMATION TECHNOLOGY 11 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

SCOPE OF PROJECT

Scope of Project for AGRO-SETU

1. Objective

The primary objective of AGRO-SETU is to empower farmers by revolutionizing agriculture through


the integration of artificial intelligence (AI), data analytics, and real-time insights. The platform aims to
enhance productivity, promote sustainability, and improve food security, bridging the gap between
traditional farming practices and modern technology.

Key Features and Functional Scope

The project encompasses the development and deployment of the following features, as outlined in the
image:

 AI Engine: Development of AI models to deliver personalized farming recommendations and


insights based on soil data, weather patterns, and crop performance. This includes predictive
analytics for crop selection and management.
 Soil Predictor: Implementation of tools to analyze soil health (e.g., nutrient levels, pH) and
provide tailored crop suggestions, potentially using IoT sensors or remote sensing technologies.
 Weather Advisor: Integration of real-time weather data and forecasting models to offer
advisories for planting, irrigation, and pest management.
 Fertilizer Optimization: Creation of algorithms to optimize fertilizer use, maximizing yield
while minimizing environmental impact through precision application techniques.
 Yojana Awareness: A module to provide farmers with updated information on government
schemes, subsidies, and agricultural policies, enhancing access to financial and technical support.
 Chatbot Support: Development of an AI-powered chatbot to offer instant responses to farming
queries, supporting education and troubleshooting in local languages.

Sustainability and Impact Goals

 Productivity: Increase crop yields by 10-20% through precision farming techniques, based on
trends observed in similar platforms.
 Sustainability: Reduce water and fertilizer usage by 15-30% through optimized resource
management, aligning with global sustainable agriculture goals.
 Food Security: Contribute to local and regional food security by improving farmer income and
reducing post-harvest losses through better decision-making.
 Environmental Impact: Minimize soil degradation and chemical runoff, supporting long-term
ecological balance.

INFORMATION TECHNOLOGY 12 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

REQURIMENT ANALYSIS

We have developed this project using the following technology: -

 Python – Serves as the primary programming language for backend logic and data
processing.

 Flask – A lightweight web framework used to build the backend and handle HTTP
requests

 Jinja2 – A templating engine in Flask for rendering dynamic HTML content.

 OpenWeather API – Provides real-time weather data for integration into the web
application.

 Appwrite – A backend-as-a-service (BaaS) platform used for authentication,


database, and storage management.

 HTML – Structures the web application's content and elements.

 CSS – Styles the web pages to enhance their visual appearance.

 JavaScript – Adds interactivity and dynamic behavior to the frontend.

 GSAP – A JavaScript library for creating smooth animations and transitions.

 PyTorch (Plant Disease Detection) – A deep learning framework used to train and
deploy models for identifying plant diseases.

 NumPy – Provides numerical computing support, especially for handling large


arrays and matrices.

 Pandas – Used for data manipulation and analysis, particularly when processing
datasets related to plant diseases.

INFORMATION TECHNOLOGY 13 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

CHAPTER 4
DETAILS OF DESIGN

INFORMATION TECHNOLOGY 14 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

DETAILS OF DESIGN

1. DFD Diagram:

1.1) ZERO LEVEL DFD:

1.2) FIRST LEVEL DFD:

INFORMATION TECHNOLOGY 15 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

1.3) SECOND LEVEL DFD:

2. ER-DIAGRAM:

INFORMATION TECHNOLOGY 16 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

3. USE CASE DIAGRAM:

INFORMATION TECHNOLOGY 17 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

CHAPTER 5
RESULT

INFORMATION TECHNOLOGY 18 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

OUTPUT

 Home:
It is the home page or the starting interface of the website from where user can see all the
features of user interface.

 Registration:
It is registration page of the website that is a compulsory for the user before the perform
any operation like(using AI Engine, Weather Advisor)

INFORMATION TECHNOLOGY 19 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

 Login:
It is the login page which the user will use to go inside the website after the registration is
done.

 Landing Page:

INFORMATION TECHNOLOGY 20 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

 AI Engine:
It is the AI Engine page which used for disease detection of various plants, fruits and
vegetables.

 Chatbot(With AI and Voice Assistant):


This is the Farm AI Assistant which helps farmers to get location of crops suitable according to area
and it also has a voice assistant which is convenient for hands free use.

INFORMATION TECHNOLOGY 21 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

 About Us:
This page gives the user information about who we are and our mission.

 Crop Soil Recoomender:


This is the crop soil recommender which will recommend suitable for the given crop.

INFORMATION TECHNOLOGY 22 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

 Yojana:
This is the yojana page which will support various initiaves for Indian agriculture

 Weather Advisor:
This is the Weather Advisor page which will give crop advisory for specific location

INFORMATION TECHNOLOGY 23 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

 Fertilizer Recommender:
This is the fertilizer recommender which gives fertilizer after putting crop and soil type.

INFORMATION TECHNOLOGY 24 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

 Database:
This is the database page which shows users which have registered time to time.

INFORMATION TECHNOLOGY 25 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

CHAPTER 6
SAMPLE CODING

INFORMATION TECHNOLOGY 26 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

 Register.html:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FarmFresh - Register</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Arial', sans-serif;
}

body {
min-height: 100vh;
background: linear-gradient(135deg, #81C784, #A5D6A7);
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}

.container {
background: rgba(255, 255, 255, 0.95);
padding: 2rem 3rem;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
width: 100%;
max-width: 450px;
animation: fadeIn 0.7s ease-out;
}

@keyframes fadeIn {
from { opacity: 0; scale: 0.9; }
to { opacity: 1; scale: 1; }
}

h1 {
text-align: center;
INFORMATION TECHNOLOGY 27 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

color: #2E7D32;
margin-bottom: 2rem;
font-size: 2rem;
}

.form-group {
margin-bottom: 1.5rem;
position: relative;
}

input {
width: 100%;
padding: 12px;
border: 2px solid #81C784;
border-radius: 25px;
outline: none;
font-size: 1rem;
transition: all 0.3s ease;
}

input:focus {
border-color: #4CAF50;
box-shadow: 0 0 8px rgba(76, 175, 80, 0.3);
}

label {
position: absolute;
left: 15px;
top: 50%;
transform: translateY(-50%);
color: #666;
transition: all 0.3s ease;
pointer-events: none;
}

input:focus + label,
input:not(:placeholder-shown) + label {
top: -10px;
font-size: 0.8rem;
color: #4CAF50;
background: white;
padding: 0 5px;

INFORMATION TECHNOLOGY 28 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

button {
width: 100%;
padding: 12px;
background: #4CAF50;
border: none;
border-radius: 25px;
color: white;
font-size: 1.1rem;
cursor: pointer;
transition: all 0.3s ease;
}

button:hover {
background: #388E3C;
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.login-link {
text-align: center;
margin-top: 1rem;
color: #666;
}

.login-link a {
color: #4CAF50;
text-decoration: none;
}

@media (max-width: 480px) {


.container {
margin: 1rem;
padding: 1.5rem;
}
}
</style>
</head>
<body>
<div class="container">
<h1>FarmFresh Register</h1>

INFORMATION TECHNOLOGY 29 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

<form id="registerForm">
<div class="form-group">
<input type="text" id="name" placeholder=" " required>
<label for="name">Full Name</label>
</div>
<div class="form-group">
<input type="email" id="email" placeholder=" " required>
<label for="email">Email</label>
</div>
<div class="form-group">
<input type="password" id="password" placeholder=" " required>
<label for="password">Password</label>
</div>
<button type="submit">Register</button>
<div class="login-link">
Already have an account? <a href="login.html">Login</a>
</div>
</form>
</div>

<script>
document.getElementById('registerForm').addEventListener('submit', async (e) => {
e.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;

// Appwrite registration integration (example)


try {
const response = await fetch('/api/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, email, password })
});
const data = await response.json();
if (data.success) {
window.location.href = '/login.html';
} else {
alert('Registration failed!');
}
} catch (error) {
console.error('Error:', error);

INFORMATION TECHNOLOGY 30 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

}
});
</script>
</body>
</html>
 Home:
{% extends 'base.html' %}
{% block pagetitle %}
Plant Disease Detection
{% endblock pagetitle %}
{% block body %}
<style>
body {
overflow-x: hidden;
background: linear-gradient(135deg, #93E9BE 0%, #40E0D0 100%); /* Seafoam Green to Turquoise
gradient */
margin: 0;
font-family: 'Poppins', sans-serif;
}

/* Responsive Adjustments */
@media only screen and (max-width: 600px) {
.bento-grid {
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
padding: 20px;
}
.bento-item img {
height: 150px;
}
h1.display-4 {
font-size: 2.5rem;
}
.lead {
font-size: 1rem;
}
}

/* Animation Keyframes */
@keyframes float {
0% { transform: translateY(0px) rotateX(0deg); }
50% { transform: translateY(-20px) rotateX(5deg); }
100% { transform: translateY(0px) rotateX(0deg); }
}

INFORMATION TECHNOLOGY 31 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}

/* Bento Grid Styling */


.bento-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
padding: 40px;
max-width: 1400px;
margin: 0 auto;
}

.bento-item {
background: rgba(255, 255, 255, 0.9);
border-radius: 20px;
padding: 20px;
transition: all 0.3s ease;
transform-style: preserve-3d;
backdrop-filter: blur(10px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
cursor: pointer;
}

.bento-item:hover {
transform: translateY(-10px) rotateX(5deg) rotateY(5deg);
box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
}

.bento-item img {
border-radius: 15px;
transition: transform 0.3s ease;
transform: perspective(1000px);
width: 100%;
height: 250px;
object-fit: cover;
}

.bento-item:hover img {
transform: scale(1.05) rotate(2deg);
}

INFORMATION TECHNOLOGY 32 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

/* Scroll Animation */
.scroll-reveal {
opacity: 0;
transition: all 0.8s ease-out;
}

.scroll-reveal.visible {
opacity: 1;
transform: translateY(0);
}
</style>

<!-- Main Content -->


<div class="main-content">
<!-- Header Section -->
<div class="row mb-5 text-center" style="padding: 40px 0; animation: fadeIn 1s ease-in">
<div class="col-12 mx-auto">
<h1 class="display-4" style="color: #4682B4; font-weight: 700; text-shadow: 0 2px 4px
rgba(0,0,0,0.1);">
🍁 AGRO-SETU 🍁
</h1>
<p class="lead" style="color: #444; font-size: 1.3em; margin-top: 20px;">
Discover plant health with our advanced AI detection system,<br>Also provides cool features for
farmers
</p>
</div>
</div>

<!-- AI Engine Button -->


<center style="margin-bottom: 40px;">
<a href="/index">
<button class="bttn-pill bttn-lg" style="
background: #4682B4; /* Darker sky blue for contrast */
border: none;
padding: 15px 40px;
border-radius: 50px;
color: white;
font-weight: 600;
transition: all 0.3s ease;
box-shadow: 0 5px 15px rgba(70, 130, 180, 0.4);" /* Shadow with darker sky blue tint */
onmouseover="this.style.transform='scale(1.05)'; this.style.boxShadow='0 8px 25px rgba(70, 130,
180, 0.6)'"
onmouseout="this.style.transform='scale(1)'; this.style.boxShadow='0 5px 15px rgba(70, 130, 180,
0.4)'">
AI Engine
INFORMATION TECHNOLOGY 33 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

</button>
</a>
</center>

<!-- Bento Grid with Wikipedia Links -->


<div class="bento-grid">
<!-- Apple -->
<a href="https://en.wikipedia.org/wiki/Apple" target="_blank" class="bento-item scroll-reveal"
style="text-decoration: none;">
<img
src="https://post.healthline.com/wp-content/uploads/2020/09/Do_Apples_Affect_Diabetes_and_Blood_
Sugar_Levels-732x549-thumbnail-1-732x549.jpg" alt="Apple">
<center><p class="lead" style="color: #333; margin-top: 15px; font-weight:
500;">Apple</p></center>
</a>

<!-- Blueberry -->


<a href="https://en.wikipedia.org/wiki/Blueberry" target="_blank" class="bento-item scroll-reveal"
style="text-decoration: none;">
<img src="https://www.supermarketperimeter.com/ext/resources/0430-blueberries.png?
t=1588260305&width=1080" alt="Blueberry">
<center><p class="lead" style="color: #333; margin-top: 15px; font-weight:
500;">Blueberry</p></center>
</a>

<!-- Cherry -->


<a href="https://en.wikipedia.org/wiki/Cherry" target="_blank" class="bento-item scroll-reveal"
style="text-decoration: none;">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/
article_thumbnails/slideshows/health_benefits_of_cherries_slideshow/
1800x1200_health_benefits_of_cherries_slideshow.jpg" alt="Cherry">
<center><p class="lead" style="color: #333; margin-top: 15px; font-weight:
500;">Cherry</p></center>
</a>

<!-- Corn -->


<a href="https://en.wikipedia.org/wiki/Maize" target="_blank" class="bento-item scroll-reveal"
style="text-decoration: none;">
<img src="https://cdn.britannica.com/36/167236-050-BF90337E/Ears-corn.jpg" alt="Corn">
<center><p class="lead" style="color: #333; margin-top: 15px; font-weight:
500;">Corn</p></center>
</a>

<!-- Grape -->


<a href="https://en.wikipedia.org/wiki/Grape" target="_blank" class="bento-item scroll-reveal"
style="text-decoration: none;">

INFORMATION TECHNOLOGY 34 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

<img src="https://i.ndtvimg.com/i/2015-09/grapes_625x350_61443376353.jpg" alt="Grape">


<center><p class="lead" style="color: #333; margin-top: 15px; font-weight:
500;">Grape</p></center>
</a>

<!-- Orange -->


<a href="https://en.wikipedia.org/wiki/Orange_(fruit)" target="_blank" class="bento-item scroll-
reveal" style="text-decoration: none;">
<img src="https://www.jiomart.com/images/product/original/590000025/orange-imported-1-kg-
product-images-o590000025-p590000025-0-202410011652.jpg?im=Resize=(420,420)" alt="Orange">
<center><p class="lead" style="color: #333; margin-top: 15px; font-weight:
500;">Orange</p></center>
</a>

<!-- Peach -->


<a href="https://en.wikipedia.org/wiki/Peach" target="_blank" class="bento-item scroll-reveal"
style="text-decoration: none;">
<img src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/articles/
health_tools/the_health_benefits_of_peaches_slideshow/thinkstock_rf_peaches.jpg?resize=650px:*"
alt="Peach">
<center><p class="lead" style="color: #333; margin-top: 15px; font-weight:
500;">Peach</p></center>
</a>

<!-- Pepper Bell -->


<a href="https://en.wikipedia.org/wiki/Bell_pepper" target="_blank" class="bento-item scroll-reveal"
style="text-decoration: none;">
<img src="https://www.chilipeppermadness.com/wp-content/uploads/2024/02/Bell-Peppers1.jpg"
alt="Pepper Bell">
<center><p class="lead" style="color: #333; margin-top: 15px; font-weight: 500;">Pepper
Bell</p></center>
</a>

<!-- Potato -->


<a href="https://en.wikipedia.org/wiki/Potato" target="_blank" class="bento-item scroll-reveal"
style="text-decoration: none;">
<img src="https://m.economictimes.com/thumb/height-450,width-600,imgsize-111140,msid-
72862126/potato-getty.jpg" alt="Potato">
<center><p class="lead" style="color: #333; margin-top: 15px; font-weight:
500;">Potato</p></center>
</a>

<!-- Raspberry -->


<a href="https://en.wikipedia.org/wiki/Raspberry" target="_blank" class="bento-item scroll-reveal"
style="text-decoration: none;">
<img src="https://i0.wp.com/cdn-prod.medicalnewstoday.com/content/images/articles/326/326272/
raspberries-with-ketones-in-a-bowl.jpg?w=1155&h=1541" alt="Raspberry">
INFORMATION TECHNOLOGY 35 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

<center><p class="lead" style="color: #333; margin-top: 15px; font-weight:


500;">Raspberry</p></center>
</a>

<!-- Soybean -->


<a href="https://en.wikipedia.org/wiki/Soybean" target="_blank" class="bento-item scroll-reveal"
style="text-decoration: none;">
<img src="https://m.economictimes.com/thumb/msid-66988154,width-1200,height-900,resizemode-
4,imgsize-211276/soyabean-agencies.jpg" alt="Soybean">
<center><p class="lead" style="color: #333; margin-top: 15px; font-weight:
500;">Soybean</p></center>
</a>

<!-- Squash -->


<a href="https://en.wikipedia.org/wiki/Squash_(plant)" target="_blank" class="bento-item scroll-
reveal" style="text-decoration: none;">
<img src="https://post.healthline.com/wp-content/uploads/2020/08/squash-fruit-or-vegetable-
732x549-thumbnail-732x549.jpg" alt="Squash">
<center><p class="lead" style="color: #333; margin-top: 15px; font-weight:
500;">Squash</p></center>
</a>

<!-- Strawberry -->


<a href="https://en.wikipedia.org/wiki/Strawberry" target="_blank" class="bento-item scroll-reveal"
style="text-decoration: none;">
<img src="https://images.indianexpress.com/2020/02/strawberry-1200.jpg" alt="Strawberry">
<center><p class="lead" style="color: #333; margin-top: 15px; font-weight:
500;">Strawberry</p></center>
</a>

<!-- Tomato -->


<a href="https://en.wikipedia.org/wiki/Tomato" target="_blank" class="bento-item scroll-reveal"
style="text-decoration: none;">
<img src="https://images-prod.healthline.com/hlcmsresource/images/AN_images/tomatoes-
1296x728-feature.jpg" alt="Tomato">
<center><p class="lead" style="color: #333; margin-top: 15px; font-weight:
500;">Tomato</p></center>
</a>
</div>
</div>

<!-- JavaScript for Scroll Effects -->


<script>
document.addEventListener('DOMContentLoaded', () => {
const reveals = document.querySelectorAll('.scroll-reveal');

INFORMATION TECHNOLOGY 36 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

const observer = new IntersectionObserver((entries) => {


entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
observer.unobserve(entry.target);
}
});
}, {
threshold: 0.1,
rootMargin: '0px 0px -50px 0px'
});

reveals.forEach(reveal => observer.observe(reveal));


});
</script>

{% endblock body %}

 Index.html:-
<html lang="hi">
{% extends 'base.html' %}
{% block pagetitle %}
AI Engine
{% endblock pagetitle %}

{% block body %}
<style>
body {
overflow-x: hidden;
background: linear-gradient(135deg, #93E9BE 0%, #40E0D0 100%);
margin: 0;
font-family: 'Poppins', sans-serif;
}

.bento-item {
background: rgba(255, 255, 255, 0.9);
border-radius: 20px;
backdrop-filter: blur(10px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.btn-custom-primary {
background: #4682B4;
border: none;
INFORMATION TECHNOLOGY 37 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

color: white;
font-weight: 600;
transition: all 0.3s ease;
box-shadow: 0 5px 15px rgba(70, 130, 180, 0.4);
}

.btn-custom-primary:hover {
transform: scale(1.05);
box-shadow: 0 8px 25px rgba(70, 130, 180, 0.6);
}

.btn-outline-primary {
border-color: #4682B4;
color: #4682B4;
margin: 5px;
}

.btn-outline-primary:hover {
background-color: #4682B4;
color: white;
}

#camera-feed {
max-width: 100%;
height: auto;
}

#preview {
max-width: 100%;
height: auto;
}
</style>

<div>
<div class="container">
<!-- Header -->
<div class="row mb-5 text-center" style="padding: 40px 0;">
<div class="col-lg-10 mx-auto">
<h1 class="display-4" style="color: #4682B4; font-weight: 700; text-shadow: 0 2px 4px
rgba(0,0,0,0.1);"><b>🍀AI Engine🍀</b></h1>
<p class="lead" style="color: #444; font-size: 1.3em; margin-top: 20px;">Let AI Engine Help You
To Detect Plant Health</p>
</div>
</div>

INFORMATION TECHNOLOGY 38 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

<!-- Main Content -->


<div class="row">
<div class="col-12 col-md-4 mx-auto">
<div class="p-5 bento-item" style="height: 95%;">
<h5><b>Why is it necessary to monitor plant health?</b></h5>
<p>Monitoring plant health helps identify diseases or stress early, ensuring proper growth and
yield. Accurate detection prevents unnecessary treatments, saves resources, and reduces plant
losses.</p>
</div>
</div>
<div class="col-12 col-md-4 mx-auto">
<div class="p-5 bento-item" style="height: 95%;">
<img src="https://miro.medium.com/v2/resize:fit:1400/1*IbJF_6mRTMsG9gL0j8uz5Q.jpeg"
height="300" alt="" width="200" class="d-block mx-auto mb-4 rounded-pill">

<!-- File Upload and Camera Form -->


<form action="/submit" method="POST" enctype="multipart/form-data">
<div class="custom-file overflow-hidden mb-4">
<input type="file" id="actual-btn" hidden name="image" accept="image/*" />
<label for="actual-btn" class="btn btn-outline-primary">Upload Image</label>
<label id="camera-btn" class="btn btn-outline-primary">Use Camera</label>
<br>
<span id="file-chosen">No file chosen</span>
</div>

<!-- Camera Feed Container -->


<div id="camera-container" style="display: none; text-align: center;">
<video id="camera-feed" width="320" height="240" autoplay></video>
<br>
<button type="button" id="capture-btn" class="btn btn-secondary">Capture Photo</button>
</div>

<!-- Preview Image -->


<img id="preview" src="#" alt="Camera Photo Preview" style="display: none; max-width:
100%; height: auto;" />

<h6 class="text-center mb-4 text-muted">


Upload a plant image or capture one to analyze its health with AI.
</h6>

<center>
<button type="submit" class="btn btn-custom-primary">Analyze</button>
</center>
</form>
</div>
INFORMATION TECHNOLOGY 39 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

</div>
<div class="col-12 col-md-4 mx-auto">
<div class="p-5 bento-item" style="height: 95%;">
<h5><b>General Plant Care Tips:</b></h5>
<ol>
<li>Ensure proper watering based on plant needs.</li>
<li>Use well-draining soil to prevent root rot.</li>
<li>Provide adequate sunlight or shade as required.</li>
<li>Prune regularly to remove dead or diseased parts.</li>
<li>Rotate crops to maintain soil health.</li>
<li>Monitor for pests and diseases frequently.</li>
<li>Use mulch to retain moisture and reduce weeds.</li>
</ol>
<a target="_blank" href="https://www.thespruce.com/prevent-plant-diseases-in-your-garden-
2539511" class="mx-2">
<button type="button" class="btn btn-outline-primary">More Info</button>
</a>
</div>
</div>
</div>
</div>
</div>

<script>
const actualBtn = document.getElementById('actual-btn');
const fileChosen = document.getElementById('file-chosen');

// Update file input label when a file is chosen


actualBtn.addEventListener('change', function () {
fileChosen.textContent = this.files[0].name;
document.getElementById('preview').style.display = 'none';
});

// Open camera when "Use Camera" is clicked


document.getElementById('camera-btn').addEventListener('click', function () {
const cameraContainer = document.getElementById('camera-container');
cameraContainer.style.display = 'block';
startCamera();
});

// Start the camera feed with back camera preference


async function startCamera() {
const videoElement = document.getElementById('camera-feed');
try {

INFORMATION TECHNOLOGY 40 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

const stream = await navigator.mediaDevices.getUserMedia({


video: { facingMode: "environment" } // Prefer back camera
});
videoElement.srcObject = stream;
console.log("Back camera started successfully");
} catch (err) {
console.error('Error accessing the camera: ', err);
alert('Could not access the back camera. Falling back to default or ensure permissions are granted
and you’re using a secure connection (HTTPS or localhost).');
// Fallback to default camera if back camera fails
try {
const fallbackStream = await navigator.mediaDevices.getUserMedia({ video: true });
videoElement.srcObject = fallbackStream;
console.log("Fallback to default camera successful");
} catch (fallbackErr) {
console.error('Fallback error: ', fallbackErr);
alert('Could not access any camera. Please check permissions.');
}
}
}

// Capture photo from the camera feed


document.getElementById('capture-btn').addEventListener('click', function () {
const video = document.getElementById('camera-feed');
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');

// Set canvas size to match video


canvas.width = video.videoWidth;
canvas.height = video.videoHeight;

// Draw the video frame onto the canvas


context.drawImage(video, 0, 0, canvas.width, canvas.height);

// Convert to data URL and display preview


const dataUrl = canvas.toDataURL('image/jpeg');
const preview = document.getElementById('preview');
preview.src = dataUrl;
preview.style.display = 'block';

// Update file-chosen text


fileChosen.textContent = 'Image Captured';

// Convert data URL to file and attach to input for form submission

INFORMATION TECHNOLOGY 41 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

const imageBlob = dataURItoBlob(dataUrl);


const capturedFile = new File([imageBlob], "camera_image.jpg", { type: 'image/jpeg' });
const dataTransfer = new DataTransfer();
dataTransfer.items.add(capturedFile);
actualBtn.files = dataTransfer.files;

// Stop the camera stream and hide the feed


const stream = video.srcObject;
stream.getTracks().forEach(track => track.stop());
document.getElementById('camera-container').style.display = 'none';
});

// Helper function to convert data URL to Blob


function dataURItoBlob(dataURI) {
const byteString = atob(dataURI.split(',')[1]);
const arrayBuffer = new ArrayBuffer(byteString.length);
const uintArray = new Uint8Array(arrayBuffer);
for (let i = 0; i < byteString.length; i++) {
uintArray[i] = byteString.charCodeAt(i);
}
return new Blob([arrayBuffer], { type: 'image/jpeg' });
}
</script>

{% endblock body %}
</html>
 Landing.html:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Agro Setu - Empowering Farmers</title>
<!-- Tailwind CSS CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap"
rel="stylesheet">
<!-- Font Awesome for Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/
all.min.css">
<style>
body {
font-family: 'Poppins', sans-serif;
margin: 0;
padding: 0;
background: linear-gradient(135deg, #e0eafc 0%, #cfdef3 100%);
overflow-x: hidden;
INFORMATION TECHNOLOGY 42 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

transition: background 0.3s ease;


}
.hero-text {
opacity: 0;
}
.btn-hover:hover {
transform: scale(1.05) rotate(2deg);
transition: all 0.3s ease;
}
#canvas-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100vh;
z-index: -1;
}
/* Dark Mode Styles */
.dark-mode {
background: linear-gradient(135deg, #2c3e50 0%, #1a252f 100%);
}
.dark-mode nav {
background: rgba(0, 0, 0, 0.8);
color: white;
}
.dark-mode .text-gray-800 {
color: #e5e7eb;
}
.dark-mode .text-gray-600 {
color: #d1d5db;
}
.dark-mode #services {
background: rgba(255, 255, 255, 0.1);
}
.dark-mode .bg-white {
background: #1f2937;
}
.dark-mode footer {
background: #111827;
}
/* Toggle Switch Styles */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
INFORMATION TECHNOLOGY 43 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
border-radius: 50%;
box-shadow: 0 0 8px rgba(255, 215, 0, 0.6); /* Sun glow */
}
input:checked + .slider {
background-color: #22c55e;
box-shadow: 0 0 15px rgba(34, 197, 94, 0.6); /* Green glow in dark mode */
}
input:checked + .slider:before {
transform: translateX(26px);
box-shadow: 0 0 8px rgba(255, 255, 255, 0.8); /* Moon glow */
}
.sun-icon, .moon-icon {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 18px;
transition: opacity 0.3s ease;
}
.sun-icon {
left: 8px;
color: #ffd700;
opacity: 1;
}
.moon-icon {
right: 8px;
color: #f0f0f0;
opacity: 0;
}
input:checked + .slider .sun-icon {
opacity: 0;
}
input:checked + .slider .moon-icon {
opacity: 1;
INFORMATION TECHNOLOGY 44 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

}
</style>
</head>
<body>
<!-- Canvas for 3D Background -->
<div id="canvas-container"></div>

<!-- Navbar -->


<nav class="flex items-center justify-between p-6 bg-white/80 backdrop-blur-md shadow-md">
<div class="text-3xl font-bold text-green-600">Agro Setu</div>
<div class="flex items-center space-x-4">
<!-- Dark Mode Toggle -->
<label class="switch">
<input type="checkbox" id="darkModeToggle">
<span class="slider">
<i class="fas fa-sun sun-icon"></i>
<i class="fas fa-moon moon-icon"></i>
</span>
</label>
<a href="https://agrosetu-123.authui.site/"
class="px-6 py-2 bg-green-600 text-white rounded-full btn-hover shadow-lg">
Sign In
</a>
</div>
</nav>

<!-- Hero Section -->


<section class="min-h-screen flex items-center justify-center px-6">
<div class="max-w-4xl text-center">
<h1 class="text-5xl md:text-6xl font-bold text-gray-800 hero-text mb-6">
Empowering Farmers with Smart Solutions
</h1>
<p class="text-xl text-gray-600 hero-text mb-8">
Discover advanced plant disease detection and agricultural services tailored for modern farming.
</p>
<div class="space-x-4">
<a href="https://agrosetu-123.authui.site/"
class="inline-block px-8 py-4 bg-green-600 text-white rounded-full text-lg font-semibold btn-
hover shadow-xl">
Get Started
</a>
<a href="#services"
class="inline-block px-8 py-4 bg-white text-green-600 rounded-full text-lg font-semibold btn-
hover shadow-xl">
Explore Services
</a>
</div>
</div>
</section>

<!-- Services Section -->


<section id="services" class="py-20 bg-white/50 backdrop-blur-sm">
<div class="max-w-6xl mx-auto px-6">
INFORMATION TECHNOLOGY 45 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

<h2 class="text-4xl font-bold text-center text-gray-800 mb-12">Our Services</h2>


<div class="grid md:grid-cols-3 gap-8">
<div class="p-6 bg-white rounded-xl shadow-lg hover:shadow-2xl transition-all duration-300
transform hover:-translate-y-2">
<h3 class="text-2xl font-semibold text-green-600 mb-4">Plant Disease Detection</h3>
<p class="text-gray-600">AI-powered disease identification for healthier crops and better
yields.</p>
</div>
<div class="p-6 bg-white rounded-xl shadow-lg hover:shadow-2xl transition-all duration-300
transform hover:-translate-y-2">
<h3 class="text-2xl font-semibold text-green-600 mb-4">Farm Management</h3>
<p class="text-gray-600">Tools and insights to optimize your farming operations.</p>
</div>
<div class="p-6 bg-white rounded-xl shadow-lg hover:shadow-2xl transition-all duration-300
transform hover:-translate-y-2">
<h3 class="text-2xl font-semibold text-green-600 mb-4">Expert Consultation</h3>
<p class="text-gray-600">Connect with agricultural experts for personalized advice.</p>
</div>
</div>
</div>
</section>

<!-- Footer -->


<footer class="py-8 bg-gray-800 text-white text-center">
<p>© 2025 Agro Setu. All rights reserved.</p>
</footer>

<!-- Scripts -->


<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.4/gsap.min.js"></script>
<script>
// GSAP Animations
gsap.to(".hero-text", {
opacity: 1,
y: 0,
duration: 1.5,
stagger: 0.3,
ease: "power3.out",
delay: 0.2
});

// Dark Mode Toggle


const toggle = document.getElementById('darkModeToggle');
toggle.addEventListener('change', () => {
document.body.classList.toggle('dark-mode');
particles.material.color.set(toggle.checked ? 0x00ff00 : 0x00ff00);
});
// Three.js 3D Background
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1,
1000);
const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
INFORMATION TECHNOLOGY 46 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

document.getElementById('canvas-container').appendChild(renderer.domElement);

// Create 3D particles
const geometry = new THREE.BufferGeometry();
const vertices = [];
for (let i = 0; i < 1000; i++) {
vertices.push(
Math.random() * 2000 - 1000,
Math.random() * 2000 - 1000,
Math.random() * 2000 - 1000
);
}
geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
const material = new THREE.PointsMaterial({
color: 0x00ff00,
size: 2,
transparent: true,
opacity: 0.5
});
const particles = new THREE.Points(geometry, material);
scene.add(particles);

camera.position.z = 500;

function animate() {
requestAnimationFrame(animate);
particles.rotation.x += 0.001;
particles.rotation.y += 0.002;
renderer.render(scene, camera);
}
animate();

// Responsive canvas
window.addEventListener('resize', () => {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
});
</script>
</body>
</html>
 Chatbot.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FarmAI Assistant</title>
<style>
:root {

INFORMATION TECHNOLOGY 47 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

--bg: transparent;
--primary: #2B7A78;
--secondary: #3AAFA9;
--accent: #DEF2F1;
--message-bot: #f0f4f8;
--input-background: white;
--input-text: black;
--input-border: #ddd;
--button-background: var(--primary);
--button-text: white;
--button-hover-background: var(--secondary);
--card-bg: rgba(255, 255, 255, 0.1);
--card-border: rgba(255, 255, 255, 0.2);
}

.dark-mode {
--bg: transparent;
--primary: #46A908;
--secondary: #91D956;
--accent: #91D956;
--message-bot: #46A908;
--input-background: #334433;
--input-text: white;
--input-border: #556655;
--button-background: #91D956;
--button-text: black;
--button-hover-background: #46A908;
--card-bg: rgba(43, 96, 30, 0.1);
--card-border: rgba(255, 255, 255, 0.2);
}

*{
box-sizing: border-box;
margin: 0;
padding: 0;
}

body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
url('https://images.unsplash.com/photo-1560493676-04071c5f467b?
q=80&w=1974&auto=format&fit=crop&ixlib=rb-
4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D') no-repeat
center center fixed;
background-size: cover;
INFORMATION TECHNOLOGY 48 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

min-height: 100vh;
display: flex;
flex-direction: column;
transition: all 0.3s ease;
}

.chat-container {
max-width: 1200px;
margin: 1rem auto;
width: 95%;
background: var(--card-bg);
backdrop-filter: blur(10px);
border-radius: 15px;
box-shadow: 0 5px 30px rgba(0,0,0,0.2);
border: 1px solid var(--card-border);
flex: 1;
display: flex;
flex-direction: column;
}

.chat-header {
background: linear-gradient(135deg, var(--primary), var(--secondary));
color: white;
padding: 1rem;
border-radius: 15px 15px 0 0;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
gap: 0.5rem;
}

.chat-header h1 {
font-size: clamp(1.2rem, 4vw, 1.8rem);
text-shadow: 0 0 5px rgba(18, 36, 18, 0.8), 0 0 10px rgba(51, 68, 51, 0.6);
display: flex;
align-items: center;
gap: 0.5rem;
}

.chat-header img {
width: clamp(20px, 5vw, 30px);
height: auto;
transition: transform 0.3s ease;
INFORMATION TECHNOLOGY 49 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

.chat-header img:hover {
transform: scale(1.1);
}

.chat-header .header-buttons {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}

.homeLink, #themeToggleBtn {
color: var(--button-text);
text-decoration: none;
font-size: clamp(0.8rem, 2.5vw, 1rem);
padding: 0.5rem 1rem;
border-radius: 50px;
background: var(--button-background);
transition: all 0.3s ease;
border: none;
cursor: pointer;
}

.homeLink:hover, #themeToggleBtn:hover {
background: var(--button-hover-background);
transform: scale(1.05);
}

.chat-messages {
flex: 1;
padding: 1rem;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 0.75rem;
background: transparent;
}

.message {
max-width: 85%;
padding: 0.75rem 1rem;
border-radius: 20px;
animation: fadeIn 0.3s ease;
INFORMATION TECHNOLOGY 50 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

color: black;
position: relative;
white-space: pre-wrap;
font-size: clamp(0.9rem, 2.5vw, 1rem);
}

@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}

.user-message {
background: var(--accent);
align-self: flex-end;
border-radius: 20px 20px 0 20px;
}

.bot-message {
background: var(--message-bot);
align-self: flex-start;
border-radius: 20px 20px 20px 0;
position: relative;
}

.bot-message::before {
content: '';
position: absolute;
left: -10px;
top: 0;
width: 0;
height: 0;
border: 10px solid transparent;
border-right-color: var(--message-bot);
}

.copy-btn {
position: absolute;
bottom: 5px;
right: 10px;
background: none;
border: none;
cursor: pointer;
color: red;
font-size: clamp(0.7rem, 2vw, 0.9rem);
INFORMATION TECHNOLOGY 51 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

text-decoration: underline;
opacity: 0.7;
transition: opacity 0.3s ease, transform 0.3s ease;
}

.copy-btn:hover {
opacity: 1;
transform: scale(1.05);
}

.copy-btn::after {
content: 'Copied!';
position: absolute;
bottom: 20px;
right: 0;
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 5px 10px;
border-radius: 5px;
font-size: 12px;
opacity: 0;
pointer-events: none;
transition: opacity 0.3s ease;
}

.copy-btn.copied::after {
opacity: 1;
background: var(--secondary);
}

.input-container {
padding: 1rem;
border-top: 1px solid var(--input-border);
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
background: transparent;
align-items: center;
}

.chat-input {
flex: 1;
padding: 0.75rem;
border: 2px solid var(--input-border);
INFORMATION TECHNOLOGY 52 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

border-radius: 12px;
font-size: clamp(0.9rem, 2.5vw, 1rem);
background: var(--input-background);
color: var(--input-text);
transition: all 0.3s ease;
min-width: 0; /* Prevents overflow */
}

.chat-input:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 10px rgba(70, 169, 8, 0.2);
}

.send-btn, .voice-btn {
background: var(--button-background);
color: var(--button-text);
border: none;
padding: 0.75rem 1.5rem;
border-radius: 50px;
cursor: pointer;
transition: all 0.3s ease;
font-size: clamp(0.8rem, 2.5vw, 1rem);
}

.send-btn:hover, .voice-btn:hover {
background: var(--button-hover-background);
transform: scale(1.05);
}

.voice-btn img {
width: clamp(15px, 3vw, 20px);
height: auto;
vertical-align: middle;
}

.loading-dots {
display: none;
padding: 1rem;
justify-content: center;
gap: 5px;
background: transparent;
}

INFORMATION TECHNOLOGY 53 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

.dot {
width: 8px;
height: 8px;
background: var(--secondary);
border-radius: 50%;
animation: bounce 1.4s infinite;
}

@keyframes bounce {
0%, 80%, 100% { transform: translateY(0); }
40% { transform: translateY(-10px); }
}

.dot:nth-child(2) { animation-delay: 0.2s; }


.dot:nth-child(3) { animation-delay: 0.4s; }

.voice-recording {
animation: pulse 1.5s infinite;
}

@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}

/* Media Queries for Mobile Responsiveness */


@media (max-width: 768px) {
.chat-container {
margin: 0.5rem;
width: 98%;
height: auto;
}

.chat-header {
flex-direction: column;
align-items: flex-start;
padding: 0.75rem;
}

.chat-header .header-buttons {
width: 100%;
justify-content: space-between;
}
INFORMATION TECHNOLOGY 54 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

.input-container {
flex-direction: column;
align-items: stretch;
}

.send-btn, .voice-btn {
width: 100%;
margin: 0.25rem 0;
}

.chat-input {
width: 100%;
}

.message {
max-width: 95%;
}

.bot-message::before {
border-width: 8px;
left: -8px;
}
}

@media (max-width: 480px) {


.chat-header h1 {
font-size: 1rem;
}

.homeLink, #themeToggleBtn {
padding: 0.4rem 0.8rem;
}

.message {
padding: 0.5rem 0.75rem;
}

.copy-btn {
font-size: 0.7rem;
bottom: 2px;
right: 5px;
}
}
INFORMATION TECHNOLOGY 55 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

</style>
</head>
<body class="dark-mode">
<div class="chat-container">
<div class="chat-header">
<h1>
<img src="https://cdn-icons-png.flaticon.com/128/15236/15236586.png" alt="Farm Icon">
FarmAI Assistant
</h1>
<div class="header-buttons">
<a href="/home" class="homeLink">Home</a>
<button id="themeToggleBtn">Toggle Theme</button>
</div>
</div>
<div class="chat-messages" id="chat-messages">
<div class="message bot-message">
Hello! I'm your farming assistant. Ask me anything about crops, soil, diseases, or farming
techniques using text or voice!
<button class="copy-btn" onclick="copyToClipboard(this)">Copy to Clipboard</button>
</div>
</div>
<div class="loading-dots" id="loading">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
<div class="input-container">
<input type="text" class="chat-input" id="user-input" placeholder="Type your farming question
or use voice...">
<button class="send-btn" onclick="sendMessage()">Send</button>
<button class="voice-btn" id="voice-btn" onclick="startVoiceRecognition()">
<img src="https://cdn-icons-png.flaticon.com/128/665/665909.png" alt="Voice Icon">
</button>
</div>
</div>

<script>
const chatMessages = document.getElementById('chat-messages');
const userInput = document.getElementById('user-input');
const loading = document.getElementById('loading');
const themeToggleBtn = document.getElementById('themeToggleBtn');
const voiceBtn = document.getElementById('voice-btn');

let recognition = null;

INFORMATION TECHNOLOGY 56 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) {


const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
recognition = new SpeechRecognition();
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.maxAlternatives = 1;

recognition.onresult = (event) => {


const transcript = event.results[0][0].transcript;
userInput.value = transcript;
sendMessage();
voiceBtn.classList.remove('voice-recording');
};

recognition.onerror = (event) => {


console.error('Speech recognition error:', event.error);
addMessage('Sorry, there was an error with voice recognition. Please try again or type your
message.');
voiceBtn.classList.remove('voice-recording');
};

recognition.onend = () => {
voiceBtn.classList.remove('voice-recording');
};
} else {
addMessage('Sorry, voice recognition is not supported in your browser.');
voiceBtn.disabled = true;
}

function startVoiceRecognition() {
if (recognition) {
voiceBtn.classList.add('voice-recording');
recognition.start();
}
}

function addMessage(message, isUser = false) {


const messageDiv = document.createElement('div');
messageDiv.className = `message ${isUser ? 'user-message' : 'bot-message'}`;
messageDiv.innerHTML = formatMessage(message);

if (!isUser) {
const copyBtn = document.createElement('button');
INFORMATION TECHNOLOGY 57 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

copyBtn.className = 'copy-btn';
copyBtn.textContent = 'Copy to Clipboard';
copyBtn.onclick = () => copyToClipboard(copyBtn, message);
messageDiv.appendChild(copyBtn);
}

chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}

function formatMessage(message) {
let formatted = message
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/(\d+)\.\s+/g, '<ol><li>$1. </li></ol>')
.replace(/-\s+/g, '<ul><li>- </li></ul>');
formatted = formatted.replace(/\n/g, '<br>');
return formatted;
}

function copyToClipboard(button, text) {


navigator.clipboard.writeText(text).then(() => {
button.classList.add('copied');
setTimeout(() => button.classList.remove('copied'), 2000);
}).catch(err => {
console.error('Failed to copy text:', err);
});
}

async function sendMessage() {


const message = userInput.value.trim();
if (!message) return;

addMessage(message, true);
userInput.value = '';

loading.style.display = 'flex';

try {
const response = await fetch('/get_gemini_response', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: message }),
INFORMATION TECHNOLOGY 58 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

});

if (!response.ok) throw new Error('Network response was not ok');

const data = await response.json();


addMessage(data.response);
} catch (error) {
addMessage('Sorry, I encountered an error. Please try again.');
console.error('Error:', error);
} finally {
loading.style.display = 'none';
}
}

userInput.addEventListener('keypress', (e) => {


if (e.key === 'Enter') sendMessage();
});

themeToggleBtn.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
});
</script>
</body>
</html>

 Soil Predictor.html
{% extends 'base.html' %}
{% block pagetitle %}
Government Schemes for Farmers
{% endblock pagetitle %}
{% block body %}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crop Soil Recommender</title>
<style>
body {
font-family: 'Poppins', sans-serif;
max-width: 900px;
margin: 0 auto;
padding: clamp(1rem, 5vw, 2.5rem) 1rem;
background: linear-gradient(135deg, #93E9BE, #40E0D0);
min-height: 100vh;
}

INFORMATION TECHNOLOGY 59 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

.container {
margin-top: 5%;
margin-bottom: 10%;
background: rgba(255, 255, 255, 0.95);
padding: clamp(1.5rem, 5vw, 2.5rem);
border-radius: 20px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
animation: fadeIn 1s ease-in-out;
}

@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}

h1 {
color: #2c3e50;
text-align: center;
margin-bottom: clamp(1.5rem, 4vw, 2.5rem);
font-size: clamp(1.5rem, 5vw, 2.5em);
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}

.input-section {
display: flex;
flex-direction: column;
gap: 1rem;
margin-bottom: 1.5rem;
position: relative;
}

input {
padding: clamp(0.75rem, 2vw, 1rem);
border: 2px solid #bdc3c7;
border-radius: 10px;
font-size: clamp(0.9rem, 2.5vw, 1rem);
transition: all 0.3s ease;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
width: 100%;
}

input:focus {
border-color: #27ae60;
box-shadow: 0 0 10px rgba(39, 174, 96, 0.3);
outline: none;
}

button {
background: linear-gradient(45deg, #93E9BE, #40E0D0);
color: white;
padding: clamp(0.75rem, 2vw, 1rem) clamp(1.5rem, 3vw, 2rem);
border: none;

INFORMATION TECHNOLOGY 60 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

border-radius: 10px;
cursor: pointer;
font-size: clamp(0.9rem, 2.5vw, 1.125rem);
transition: transform 0.3s ease, box-shadow 0.3s ease;
box-shadow: 0 5px 15px rgba(39, 174, 96, 0.4);
width: 100%;
}

button:hover {
transform: translateY(-3px);
box-shadow: 0 8px 20px rgba(39, 174, 96, 0.6);
}

#result {
margin-top: 1.5rem;
padding: clamp(1rem, 3vw, 1.5rem);
border-radius: 15px;
opacity: 0;
transition: opacity 0.5s ease;
}

#result.show {
opacity: 1;
}

.suggestion {
color: #777;
font-size: clamp(0.75rem, 2vw, 0.875rem);
margin-top: 0.75rem;
animation: slideUp 0.5s ease;
}

#suggestionsList {
list-style: none;
padding: 0;
margin: 0.25rem 0 0 0;
border: 2px solid #ddd;
border-radius: 10px;
background: white;
position: absolute;
top: clamp(3rem, 10vw, 4rem);
width: 100%;
max-height: 200px;
overflow-y: auto;
display: none;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
z-index: 10;
}

#suggestionsList li {
padding: clamp(0.6rem, 2vw, 0.75rem) 0.75rem;
cursor: pointer;

INFORMATION TECHNOLOGY 61 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

transition: all 0.3s ease;


}

#suggestionsList li:hover {
background: #e8f5e9;
color: #27ae60;
}

.loading {
display: none;
margin: 1rem 0;
color: #3498db;
font-size: clamp(0.9rem, 2.5vw, 1rem);
text-align: center;
animation: pulse 1.5s infinite;
}

@keyframes pulse {
0% { opacity: 0.5; }
50% { opacity: 1; }
100% { opacity: 0.5; }
}

@keyframes slideUp {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}

.soil-info {
margin-top: 1.25rem;
padding: 1rem;
background: #f8f9fa;
border-radius: 10px;
animation: slideUp 0.5s ease;
}

.soil-characteristics {
margin: 0.75rem 0;
padding: 0.75rem;
background: white;
border-radius: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.soil-characteristics dl {
display: grid;
grid-template-columns: max-content auto;
gap: 0.5rem 1rem;
}

.soil-characteristics dt {
font-weight: 600;

INFORMATION TECHNOLOGY 62 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

color: #2c3e50;
}

.crop-examples {
margin: 0.75rem 0;
font-style: italic;
color: #666;
}

/* Media Queries for Responsiveness */


@media (max-width: 768px) {
body {
padding: 1rem;
}

.container {
margin-top: 2%;
margin-bottom: 5%;
padding: 1rem;
}

.input-section {
gap: 0.75rem;
}

button {
width: 100%;
}

#suggestionsList {
top: clamp(2.5rem, 8vw, 3rem);
max-height: 150px;
}
}

@media (max-width: 480px) {


h1 {
font-size: 1.25rem;
}

input, button {
padding: 0.5rem;
font-size: 0.875rem;
}

.soil-info, .soil-characteristics {
padding: 0.5rem;
}

.soil-characteristics dl {
grid-template-columns: 1fr; /* Stack terms and definitions */
gap: 0.25rem;

INFORMATION TECHNOLOGY 63 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

#result {
padding: 0.75rem;
}

#suggestionsList li {
padding: 0.5rem;
}
}
</style>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap"
rel="stylesheet">
</head>
<body>
<div class="container">
<h1>🌱 Crop Soil Recommender</h1>
<div class="input-section">
<input type="text" id="cropInput" placeholder="Enter crop name (e.g., wheat, rice, potatoes)">
<ul id="suggestionsList"></ul>
<button onclick="recommendSoil()">Get Soil Recommendation</button>
<div class="loading" id="loading">Analyzing...</div>
</div>
<div id="result"></div>
</div>

<script>
const soilDescriptions = {
"Loamy Soil": {
characteristics: {
Texture: "Balanced sand-silt-clay mixture",
Drainage: "Excellent water retention and drainage",
pH: "6.0-7.0 (neutral)",
Nutrients: "High organic matter content"
},
crops: ["Wheat", "Cotton", "Sugarcane", "Vegetables"],
description: "The ideal agricultural soil combining benefits of all soil types. Perfect for most
crops due to its balanced water retention and drainage."
},
"Clay Soil": {
characteristics: {
Texture: "Fine-grained, compact",
Drainage: "Poor drainage",
pH: "5.5-7.5",
Nutrients: "High mineral content"
},
crops: ["Rice", "Cabbage", "Lettuce"],
description: "Retains moisture well but hardens when dry. Excellent for flood-tolerant crops."
},
"Well-drained Sandy Loam": {
characteristics: {
Texture: "Gritty, loose structure",

INFORMATION TECHNOLOGY 64 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

Drainage: "Rapid drainage",


pH: "5.5-6.5",
Nutrients: "Low natural fertility"
},
crops: ["Maize", "Carrots", "Potatoes"],
description: "Warms quickly in spring, ideal for early planting. Requires regular fertilization."
},
"Black Soil (Regur)": {
characteristics: {
Texture: "Clay-rich, cracks when dry",
Drainage: "Slow permeability",
pH: "7.5-8.5",
Nutrients: "High calcium/magnesium"
},
crops: ["Cotton", "Soybeans", "Citrus"],
description: "Highly fertile volcanic soil with exceptional moisture retention."
},
"Heavy Clay Soil": {
characteristics: {
Texture: ">50% clay particles",
Drainage: "Very poor drainage",
pH: "6.5-7.5",
Nutrients: "High cation exchange capacity"
},
crops: ["Sugarcane", "Willow", "Bog plants"],
description: "Challenging soil requiring careful management. Excellent nutrient retention."
},
"Volcanic Soil": {
characteristics: {
Texture: "Loamy with mineral fragments",
Drainage: "Variable drainage",
pH: "5.0-6.5",
Nutrients: "Rich in minerals"
},
crops: ["Coffee", "Banana", "Tropical fruits"],
description: "Highly fertile soil from volcanic ash. Ideal for acid-loving crops."
},
"Sandy Loam Soil": {
characteristics: {
Texture: "60-70% sand, 10-20% clay",
Drainage: "Excellent drainage",
pH: "6.0-7.0",
Nutrients: "Moderate fertility"
},
crops: ["Potato", "Garlic", "Watermelon"],
description: "Lightweight soil that's easy to work. Requires organic amendments."
},
"Clay Loam Soil": {
characteristics: {
Texture: "30-40% clay",
Drainage: "Moderate drainage",
pH: "6.5-7.5",

INFORMATION TECHNOLOGY 65 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

Nutrients: "High fertility"


},
crops: ["Soybean", "Cabbage", "Broccoli"],
description: "Balanced clay-rich soil with good structure. Ideal for heavy feeders."
},
"Gravelly or Stony Soil": {
characteristics: {
Texture: "Rocky composition",
Drainage: "Excellent drainage",
pH: "6.5-8.0",
Nutrients: "Low fertility"
},
crops: ["Grapes", "Olives", "Lavender"],
description: "Well-draining soil that prevents waterlogging."
},
"Acidic Peat Soil": {
characteristics: {
Texture: "Spongy organic matter",
Drainage: "Poor drainage",
pH: "3.5-5.0",
Nutrients: "Low mineral content"
},
crops: ["Blueberry", "Cranberry", "Azaleas"],
description: "Organic-rich soil with high acidity. Perfect for acid-loving plants."
},
"Rich Volcanic Soil": {
characteristics: {
Texture: "Dark and crumbly",
Drainage: "Well-draining",
pH: "5.5-6.5",
Nutrients: "Exceptional fertility"
},
crops: ["Banana", "Pineapple", "Taro"],
description: "Mineral-rich soil from volcanic ash deposits."
},
"Well-drained Loamy Soil": {
characteristics: {
Texture: "Balanced mixture",
Drainage: "Perfect drainage",
pH: "6.0-7.0",
Nutrients: "High organic content"
},
crops: ["Apple", "Pear", "Stone fruits"],
description: "Ideal for fruit trees, providing good anchorage."
},
"Sandy Clay Loam": {
characteristics: {
Texture: "40-50% sand, 25-35% clay",
Drainage: "Moderate drainage",
pH: "6.0-7.5",
Nutrients: "Medium fertility"
},

INFORMATION TECHNOLOGY 66 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

crops: ["Turmeric", "Ginger", "Root crops"],


description: "Warm soil with good water retention. Excellent for rhizome crops."
},
"Moist Clay Loam": {
characteristics: {
Texture: "High clay content",
Drainage: "Slow drainage",
pH: "6.0-7.0",
Nutrients: "High fertility"
},
crops: ["Lettuce", "Spinach", "Celery"],
description: "Retains moisture well for leafy greens."
},
"Humus-rich Volcanic Soil": {
characteristics: {
Texture: "Dark and porous",
Drainage: "Excellent drainage",
pH: "5.0-6.0",
Nutrients: "Exceptional organic content"
},
crops: ["Vanilla", "Coffee", "Tropical orchids"],
description: "Ultra-fertile soil for sensitive tropical plants."
},
"Red Sandy Soil": {
characteristics: {
Texture: "Sandy with iron oxide",
Drainage: "Good drainage",
pH: "5.5-6.5",
Nutrients: "Moderate fertility"
},
crops: ["Groundnut", "Millets", "Ragi"],
description: "Well-drained soil common in southern India, suitable for drought-tolerant crops."
},
"Alluvial Soil": {
characteristics: {
Texture: "Silty loam",
Drainage: "Moderate to good",
pH: "6.0-7.5",
Nutrients: "High fertility"
},
crops: ["Rice", "Wheat", "Jute"],
description: "Fertile soil deposited by rivers, ideal for a variety of crops."
},
"Laterite Soil": {
characteristics: {
Texture: "Clayey with iron/aluminum oxides",
Drainage: "Good drainage",
pH: "4.5-6.0",
Nutrients: "Low fertility"
},
crops: ["Cashew", "Tea", "Tapioca"],
description: "Acidic soil common in hilly areas, needs nutrient management."

INFORMATION TECHNOLOGY 67 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

},
"Saline Soil": {
characteristics: {
Texture: "Variable, often clayey",
Drainage: "Poor drainage",
pH: "7.5-8.5",
Nutrients: "Low due to salt content"
},
crops: ["Barley", "Date palm", "Salt-tolerant greens"],
description: "High salt content soil requiring leaching for cultivation."
}
};

const cropSoilData = {
"wheat": "Loamy Soil",
"rice": "Clay Soil",
"maize": "Well-drained Sandy Loam",
"cotton": "Black Soil (Regur)",
"sugarcane": "Heavy Clay Soil",
"coffee": "Volcanic Soil",
"tea": "Acidic Peat Soil",
"potato": "Sandy Loam Soil",
"soybean": "Clay Loam Soil",
"barley": "Well-drained Loamy Soil",
"tomato": "Sandy Loam Soil",
"apple": "Well-drained Loamy Soil",
"banana": "Rich Volcanic Soil",
"grapes": "Gravelly or Stony Soil",
"citrus": "Sandy Clay Loam",
"oats": "Well-drained Loamy Soil",
"rye": "Sandy Loam Soil",
"quinoa": "Sandy Loam Soil",
"carrots": "Well-drained Sandy Loam",
"spinach": "Moist Clay Loam",
"lettuce": "Moist Clay Loam",
"onion": "Sandy Loam Soil",
"garlic": "Sandy Loam Soil",
"cucumber": "Well-drained Loamy Soil",
"pumpkin": "Sandy Loam Soil",
"eggplant": "Well-drained Loamy Soil",
"sunflower": "Well-drained Loamy Soil",
"peanut": "Sandy Loam Soil",
"lentils": "Well-drained Loamy Soil",
"chickpeas": "Sandy Clay Loam",
"mustard": "Well-drained Loamy Soil",
"sesame": "Sandy Loam Soil",
"millet": "Sandy Loam Soil",
"sorghum": "Clay Loam Soil",
"pineapple": "Rich Volcanic Soil",
"mango": "Well-drained Loamy Soil",
"papaya": "Sandy Loam Soil",
"watermelon": "Sandy Loam Soil",

INFORMATION TECHNOLOGY 68 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

"strawberry": "Sandy Loam Soil",


"blueberry": "Acidic Peat Soil",
"raspberry": "Well-drained Loamy Soil",
"cabbage": "Moist Clay Loam",
"broccoli": "Clay Loam Soil",
"cauliflower": "Well-drained Loamy Soil",
"peas": "Well-drained Loamy Soil",
"asparagus": "Sandy Loam Soil",
"artichoke": "Well-drained Loamy Soil",
"ginger": "Sandy Clay Loam",
"turmeric": "Sandy Clay Loam",
"vanilla": "Humus-rich Volcanic Soil",
"okra": "Sandy Loam Soil",
"brinjal": "Well-drained Loamy Soil",
"bitter gourd": "Sandy Loam Soil",
"ridge gourd": "Well-drained Sandy Loam",
"bottle gourd": "Sandy Loam Soil",
"drumstick": "Sandy Clay Loam",
"jackfruit": "Well-drained Loamy Soil",
"guava": "Well-drained Loamy Soil",
"pomegranate": "Sandy Loam Soil",
"sapota": "Sandy Clay Loam",
"custard apple": "Well-drained Loamy Soil",
"amla": "Sandy Loam Soil",
"lady finger": "Sandy Loam Soil",
"green peas": "Well-drained Loamy Soil",
"radish": "Sandy Loam Soil",
"beetroot": "Sandy Loam Soil",
"sweet potato": "Sandy Loam Soil",
"tapioca": "Laterite Soil",
"jute": "Alluvial Soil",
"groundnut": "Red Sandy Soil"
};

const suggestions = Object.keys(cropSoilData);

function recommendSoil() {
const cropInput = document.getElementById('cropInput').value.toLowerCase();
const resultDiv = document.getElementById('result');
const loading = document.getElementById('loading');

resultDiv.style.display = 'none';
resultDiv.classList.remove('show');
loading.style.display = 'block';

setTimeout(() => {
loading.style.display = 'none';
if (cropSoilData.hasOwnProperty(cropInput)) {
const soilType = cropSoilData[cropInput];
const soilInfo = soilDescriptions[soilType] || {};

let soilHTML = '';

INFORMATION TECHNOLOGY 69 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

if (soilInfo.description) {
soilHTML = `
<div class="soil-info">
<h4>About ${soilType}</h4>
<div class="soil-characteristics">
<dl>
${Object.entries(soilInfo.characteristics).map(([key, value]) => `
<dt>${key}:</dt>
<dd>${value}</dd>
`).join('')}
</dl>
</div>
${soilInfo.crops ? `
<div class="crop-examples">
Common crops: ${soilInfo.crops.join(', ')}
</div>` : ''}
<p>${soilInfo.description}</p>
</div>
`;
}

resultDiv.innerHTML = `
<div style="background: linear-gradient(45deg, #e8f5e9, #d4edda); padding:
clamp(1rem, 3vw, 1.5rem); border-radius: 15px;">
<h3 style="color: #2e7d32; margin-top: 0;">
${cropInput.charAt(0).toUpperCase() + cropInput.slice(1)}
</h3>
<p>Recommended Soil Type: <strong>${soilType}</strong></p>
${soilHTML}
</div>
`;
} else {
resultDiv.innerHTML = `
<div style="background: linear-gradient(45deg, #ffebee, #ffcdd2); padding: clamp(1rem,
3vw, 1.5rem); border-radius: 15px;">
<h3 style="color: #c62828; margin-top: 0;">Crop not found</h3>
<p>Try these common crops: ${suggestions.slice(0, 5).join(', ')}</p>
</div>
`;
}
resultDiv.style.display = 'block';
setTimeout(() => resultDiv.classList.add('show'), 10);
}, 800);
}

const cropInput = document.getElementById('cropInput');


const suggestionsList = document.getElementById('suggestionsList');

cropInput.addEventListener('input', function(e) {
const inputVal = e.target.value.toLowerCase();
suggestionsList.innerHTML = '';

INFORMATION TECHNOLOGY 70 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

if (inputVal.length > 0) {
const filteredSuggestions = suggestions.filter(crop =>
crop.startsWith(inputVal)
).slice(0, 5);

if (filteredSuggestions.length > 0) {
filteredSuggestions.forEach(crop => {
const li = document.createElement('li');
li.textContent = crop;
li.addEventListener('click', () => {
cropInput.value = crop;
suggestionsList.style.display = 'none';
recommendSoil();
});
suggestionsList.appendChild(li);
});
suggestionsList.style.display = 'block';
} else {
suggestionsList.style.display = 'none';
}
} else {
suggestionsList.style.display = 'none';
}
});

cropInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
recommendSoil();
}
});
</script>
</body>
</html>
{% endblock body %}

 Weather Advisor.html

{% extends 'base.html' %}
{% block pagetitle %}
Weather and Crop Advisory
{% endblock pagetitle %}
{% block body %}
<!-- CSS for Weather, Nature Theme, and Glassmorphism -->
<style>
.container {
max-width: 1200px;
margin: 60px auto 0; /* Added top margin to prevent overlap with header */
padding: 40px;
background: rgba(255, 255, 255, 0.15); /* Glassmorphism: translucent white */
border-radius: 15px;
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
backdrop-filter: blur(10px); /* Glassmorphism: blur effect */

INFORMATION TECHNOLOGY 71 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

border: 1px solid rgba(255, 255, 255, 0.2); /* Glassmorphism: subtle border */
overflow: hidden;
position: relative;
z-index: 1;
}

.header {
text-align: center;
margin-bottom: 40px;
color: #1a3c34;
font-weight: 700;
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.form-group {
margin-bottom: 20px;
opacity: 1; /* Ensure form groups are visible */
transform: translateY(0); /* Reset any transform hiding the elements */
}

.form-label {
color: #333;
font-weight: 600;
margin-bottom: 5px;
display: block; /* Ensure labels are visible */
background: transparent; /* Remove any background color (e.g., green) */
}

.form-control, .form-select {
width: 100%;
padding: 12px;
border: 1px solid rgba(255, 255, 255, 0.3); /* Glassmorphism: subtle border */
border-radius: 8px;
background: rgba(255, 255, 255, 0.3); /* Lighter translucent background for better readability */
backdrop-filter: blur(5px); /* Glassmorphism: subtle blur */
color: #333;
font-size: 1rem;
transition: border-color 0.3s ease, box-shadow 0.3s ease;
appearance: none; /* Remove default browser styling for select */
-webkit-appearance: none; /* For Safari */
-moz-appearance: none; /* For Firefox */
}

.form-control:focus, .form-select:focus {
outline: none;
border-color: #2a9d8f;
box-shadow: 0 0 5px rgba(42, 157, 143, 0.5);
}

/* Custom arrow for select (since appearance: none removes default) */


.form-select {
background-image:

INFORMATION TECHNOLOGY 72 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iOCIgdmlld0JveD0iMC
AwIDEyIDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI
+PHBhdGggZD0iTTExLjI2NjcgMC41NDMzN0wxLjczMzMzIDYuMDc2NjciIHN0cm9rZT0iIzM
zMyIgc3Ryb2tlLXdpZHRoPSIyIi8+PC9zdmc+');
background-repeat: no-repeat;
background-position: right 10px center;
padding-right: 30px; /* Space for the arrow */
}

.result-card {
background: rgba(255, 255, 255, 0.2); /* Glassmorphism for result card */
border-radius: 10px;
padding: 20px;
margin-top: 20px;
border: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
backdrop-filter: blur(8px);
transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.result-card:hover {
transform: translateY(-5px);
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.crop-option {
background: rgba(241, 244, 233, 0.3); /* Glassmorphism for crop options */
border-radius: 8px;
padding: 10px;
margin: 10px 0;
cursor: pointer;
transition: background 0.3s ease, transform 0.3s ease;
}

.crop-option:hover {
background: rgba(224, 230, 216, 0.5);
transform: translateY(-3px);
}

/* Weather-Inspired Nature Background Image */


.weather-bg {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: url('https://images.unsplash.com/photo-1475116127127-e3ce09ee84e1?
q=80&w=2070&auto=format&fit=crop&ixlib=rb-
4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D') no-repeat
center center/cover; /* Nature image of a field with clouds */
z-index: -1;
opacity: 0.8;

INFORMATION TECHNOLOGY 73 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

/* Ensure form visibility and override any hidden styles */


form {
display: block !important;
opacity: 1 !important;
visibility: visible !important;
}

.btn-success {
background: #2a9d8f;
border: none;
padding: 12px 35px;
border-radius: 25px;
color: white;
font-weight: 600;
transition: background 0.3s ease;
box-shadow: 0 4px 12px rgba(42, 157, 143, 0.3);
}

.btn-success:hover {
background: #1f7a6b;
}

/* Error message styling */


.error-message {
display: none;
background: rgba(255, 165, 0, 0.1); /* Light orange with transparency */
color: #d35400;
padding: 10px;
border-radius: 8px;
margin-bottom: 15px;
border: 1px solid rgba(255, 165, 0, 0.3);
backdrop-filter: blur(5px);
text-align: center;
}

.error-message.show {
display: block;
}

/* Styling for Crop Advisory Section */


.crop-advisory {
background: rgba(152, 216, 167, 0.3); /* Light green glassmorphism for crop data */
border-radius: 10px;
padding: 15px;
margin-top: 10px;
border: 1px solid rgba(152, 216, 167, 0.5);
backdrop-filter: blur(5px);
}

.crop-advisory h4 {

INFORMATION TECHNOLOGY 74 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

color: #2d6a4f; /* Darker green for headers */


font-weight: 700;
margin-bottom: 10px;
}

.crop-advisory p {
color: #333;
font-size: 1.1rem;
line-height: 1.5;
margin: 5px 0;
white-space: pre-wrap; /* Preserve newlines and spaces for emojis */
}

.crop-advisory strong {
color: #1a3c34; /* Earthy teal for emphasis */
font-weight: 600;
}

/* Ensure emojis render correctly */


.emoji-support {
font-family: 'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Color Emoji', 'Android Emoji', sans-serif;
/* Fallback fonts for emojis */
}
</style>

<!-- GSAP Library -->


<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollTrigger.min.js"></script>

<div class="weather-bg"></div>
<div class="container">
<h1 class="header" style="font-size: 2.5rem;">
🌱 Weather & Crop Advisory for Farmers
</h1>

<!-- Form Section with Location Input and Geolocation Button -->
<form method="POST" class="mt-4" id="advisoryForm">
<div class="mb-3 form-group">
<label for="location" class="form-label">Enter Location (Pincode or District) or Use Current
Location:</label>
<div style="display: flex; align-items: center; gap: 10px;">
<input type="text" class="form-control" id="location" name="location" placeholder="E.g.,
110001 or Delhi" required>
<button type="button" class="btn btn-success" id="getLocationBtn" style="padding: 12px
20px;">
📍 Get Current Location
</button>
</div>
</div>
<div class="mb-3 form-group">
<label for="crop" class="form-label">Select Crop:</label>
<select class="form-select" id="crop" name="crop" required>

INFORMATION TECHNOLOGY 75 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

{% if crops %}
{% for crop in crops %}
<option value="{{ crop.name }}">{{ crop.name }}</option>
{% endfor %}
{% else %}
<option value="" disabled selected>No crops available</option>
{% endif %}
</select>
</div>
<div class="error-message" id="errorMessage">Please fill out all fields or fetch your
location.</div>
<button type="submit" class="btn btn-success" style="margin-top: 20px;">
Get Advisory
</button>
</form>

{% if temperature %}
<div class="result-card mt-5">
<h3 class="text-center" style="color: #1a3c34;">Weather & Crop Advisory for {{ location
}}</h3>
<div class="row mt-3">
<div class="col-md-6">
<h4>Weather Data</h4>
<p><strong>Temperature:</strong> {{ temperature }}°C</p>
<p><strong>Humidity:</strong> {{ humidity }}%</p>
<p><strong>Conditions:</strong> {{ description }}</p>
</div>
<div class="col-md-6">
<h4>Crop Advisory for {{ crop }}</h4>
<div class="crop-advisory emoji-support">
<p>{{ crop_advice }}</p>
<p><strong>Optimal Temperature:</strong> {{ optimal_temp }}</p>
<p><strong>Yield Impact:</strong> {{ yield_impact }}</p>
</div>
</div>
</div>
</div>
{% endif %}
</div>

<!-- GSAP Animations and Form Validation -->


<script>
// GSAP Animation Initialization
gsap.registerPlugin(ScrollTrigger);

// Animate form groups on page load


gsap.utils.toArray('.form-group').forEach((element, i) => {
gsap.from(element, {
duration: 1,
opacity: 0,
y: 50,
delay: i * 0.2,

INFORMATION TECHNOLOGY 76 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

ease: "power3.out"
});
});

// Animate Result Card on Appear


gsap.from('.result-card', {
duration: 1.2,
opacity: 0,
y: 80,
ease: "power3.out",
scrollTrigger: {
trigger: '.result-card',
start: "top 85%"
}
});

// Hover Animation for Crop Options (if expanded later)


gsap.utils.toArray('.crop-option').forEach(option => {
option.addEventListener('mouseenter', () => {
gsap.to(option, { duration: 0.3, scale: 1.03, background: 'rgba(224, 230, 216, 0.5)', ease:
"power2.out" });
});
option.addEventListener('mouseleave', () => {
gsap.to(option, { duration: 0.3, scale: 1, background: 'rgba(241, 244, 233, 0.3)', ease:
"power2.out" });
});
});

// Handle Get Current Location button


document.getElementById('getLocationBtn').addEventListener('click', function() {
const locationInput = document.getElementById('location');
const errorMessage = document.getElementById('errorMessage');

if (navigator.geolocation) {
this.disabled = true; // Disable button while fetching
this.textContent = 'Fetching...';

navigator.geolocation.getCurrentPosition(
function(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;

// Use OpenWeatherMap reverse geocoding to get city/district


fetch(`https://api.openweathermap.org/geo/1.0/reverse?lat=${lat}&lon=$
{lon}&limit=1&appid=6fd2379bf8a902745a4b6579fba2bddf`)
.then(response => response.json())
.then(data => {
if (data && data.length > 0) {
const locationName = data[0].name; // City or district name
locationInput.value = locationName;
errorMessage.classList.remove('show');
} else {

INFORMATION TECHNOLOGY 77 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

errorMessage.textContent = 'Unable to determine location name.';


errorMessage.classList.add('show');
}
})
.catch(error => {
console.error('Geocoding error:', error);
errorMessage.textContent = 'Error fetching location name.';
errorMessage.classList.add('show');
})
.finally(() => {
document.getElementById('getLocationBtn').disabled = false;
document.getElementById('getLocationBtn').textContent = '📍 Get Current Location';
});
},
function(error) {
console.error('Geolocation error:', error);
let errorText = 'Unable to fetch location. ';
switch(error.code) {
case error.PERMISSION_DENIED:
errorText += 'Permission denied.';
break;
case error.POSITION_UNAVAILABLE:
errorText += 'Location unavailable.';
break;
case error.TIMEOUT:
errorText += 'Request timed out.';
break;
default:
errorText += 'Unknown error.';
}
errorMessage.textContent = errorText;
errorMessage.classList.add('show');
document.getElementById('getLocationBtn').disabled = false;
document.getElementById('getLocationBtn').textContent = '📍 Get Current Location';
}
);
} else {
errorMessage.textContent = 'Geolocation is not supported by your browser.';
errorMessage.classList.add('show');
}
});

// Updated Form Validation


document.getElementById('advisoryForm').addEventListener('submit', function(e) {
const location = document.getElementById('location').value;
const crop = document.getElementById('crop').value;
const errorMessage = document.getElementById('errorMessage');

if (!location || !crop) {
e.preventDefault();
errorMessage.textContent = 'Please enter a location or fetch your current location, and select a
crop.';

INFORMATION TECHNOLOGY 78 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

errorMessage.classList.add('show');
gsap.from(errorMessage, { duration: 0.5, opacity: 0, y: 10, ease: "power3.out" });
return false;
} else {
errorMessage.classList.remove('show');
}
});
</script>
{% endblock body %}

 APP.PY
import os
import base64
import requests
from flask import Flask, redirect, render_template, request, jsonify
import json
from dotenv import load_dotenv

load_dotenv()
# Load crop data from JSON
with open('crop_data.json', 'r', encoding='utf-8') as file:
crop_data = json.load(file)

app = Flask(__name__, template_folder='templates')


app.config['JSON_AS_ASCII'] = False # Ensure JSON outputs non-ASCII characters (like emojis)

# Configure Gemini API


GEMINI_API_KEY = os.getenv('GEMINI_API_KEY')
GEMINI_API_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-
flash:generateContent?key={GEMINI_API_KEY}"

# Landing page
@app.route('/')
def landing():
return render_template('landing.html')

# Home page
@app.route('/home')
def home_page():
return render_template('home.html')

# Login page
@app.route('/login')
def login():
return render_template('login.html')

# Register page
@app.route('/register')
def register():
return render_template('register.html')
# Register page
@app.route('/about')

INFORMATION TECHNOLOGY 79 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

def about():
return render_template('about.html')

# AI Engine page (index)


@app.route('/index')
def ai_engine_page():
return render_template('index.html')

# Mobile device detected page


@app.route('/mobile-device')
def mobile_device_detected_page():
return render_template('mobile-device.html')

# Soil predictor page


@app.route('/soil-predictor')
def soil_predictor():
return render_template('soil-predictor.html')

# Yojana (schemes) page


@app.route('/yojana')
def yojana():
data_file_path = os.path.join(app.root_path, 'yojana.json')
with open(data_file_path, 'r', encoding='utf-8') as file:
schemes = json.load(file)
return render_template('yojana.html', schemes=schemes)

# Submit route for plant health analysis using Gemini API


@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
if 'image' not in request.files:
return render_template('submit.html', error="No image uploaded")

image = request.files['image']
image_data = image.read()
encoded_image = base64.b64encode(image_data).decode('utf-8')

# Enhanced prompt for Gemini API to ensure detailed and structured responses
prompt = (
"Analyze the provided plant image (fruit, vegetable, or leaf) and respond in the exact format
below, with detailed and specific information:\n\n"
"Disease Name: [If the plant is healthy, say 'Healthy'. If no plant, fruit, or vegetable is detected,
say 'No plant detected. Please provide an image of a fruit, vegetable, or leaf.']\n"
"Description: [Provide a detailed description of the plant's health, disease (if any), or why no
plant was detected.]\n"
"Prevention: [Provide specific prevention tips to maintain plant health or avoid diseases. If no
plant is detected or the plant is healthy, suggest general prevention tips for healthy plants.]\n"
"Solutions/Tips: [Offer practical solutions or tips to address any detected disease or maintain
plant health. If no plant is detected or the plant is healthy, suggest general care tips.]\n"
"Fertilizer Recommendation: [Recommend a specific fertilizer or nutrient plan to support the
plant’s health, even if it’s healthy. If no plant is detected, say 'Not applicable.']\n\n"
"Ensure all fields are filled with meaningful, specific information relevant to the image."

INFORMATION TECHNOLOGY 80 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

# Prepare payload for Gemini API


payload = {
"contents": [
{
"parts": [
{
"text": prompt
},
{
"inlineData": {
"mimeType": "image/jpeg",
"data": encoded_image
}
}
]
}
]
}

# Send request to Gemini API


try:
response = requests.post(GEMINI_API_URL, json=payload)
response.raise_for_status()
result = response.json()
if 'candidates' in result and result['candidates']:
analysis_text = result['candidates'][0]['content']['parts'][0]['text']
# Parse the analysis text based on the expected format
data = {}
for line in analysis_text.split('\n'):
if ':' in line:
key, value = line.split(':', 1)
data[key.strip()] = value.strip()

# Extract fields with default values if not present


title = data.get('Disease Name', 'Error: No analysis available')
description = data.get('Description', 'No description available.')
prevention = data.get('Prevention', 'No prevention tips available.')
solutions = data.get('Solutions/Tips', 'No solutions available.')
fertilizer = data.get('Fertilizer Recommendation', 'No fertilizer recommendation available.')

# Handle special cases


if "No plant detected" in title:
description = "Please provide an image of a fruit, vegetable, or leaf for analysis."
prevention = ""
solutions = ""
fertilizer = "Not applicable."

elif title == 'Healthy':


# Ensure meaningful responses for healthy plants
if not description or "No description" in description:

INFORMATION TECHNOLOGY 81 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

description = "The plant appears healthy with no visible signs of disease or stress. It has
vibrant green leaves and no abnormalities."
if not prevention or "No prevention" in prevention:
prevention = "To maintain plant health, ensure proper watering, adequate sunlight, well-
draining soil, and regular monitoring for pests or diseases."
if not solutions or "No solutions" in solutions:
solutions = "Continue regular care, including pruning dead leaves, rotating crops, and
using mulch to retain moisture."
if not fertilizer or "No fertilizer" in fertilizer:
fertilizer = "Use a balanced fertilizer like 10-10-10 (NPK) every 4-6 weeks during the
growing season to support healthy growth."

else:
title = "Error"
description = "No analysis available from the API."
prevention = ""
solutions = ""
fertilizer = ""

except requests.RequestException as e:
title = "Error"
description = f"API request failed: {str(e)}"
prevention = ""
solutions = ""
fertilizer = ""

# Encode image for display in the template


image_base64 = base64.b64encode(image_data).decode('utf-8')
image_url = f"data:image/jpeg;base64,{image_base64}"

return render_template('submit.html',
title=title,
description=description,
prevention=prevention,
solutions=solutions,
fertilizer=fertilizer,
image_url=image_url)

return redirect('/index')

# Chatbot page
@app.route('/chatbot')
def chatbot():
return render_template('chatbot.html')

# Gemini API response for chatbot


@app.route('/get_gemini_response', methods=['POST'])
def get_gemini_response():
try:
data = request.json
user_message = data.get('message', '').strip()

INFORMATION TECHNOLOGY 82 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

if not user_message:
return jsonify({'error': 'No message provided'}), 400

# Enhanced prompt for formatted responses (e.g., for "I want to warm potatoes")
prompt = (
f"Respond to the user's query: '{user_message}'. Provide a detailed, formatted response using
bold headings (e.g., **Oven:**, **Microwave:**) and numbered or bulleted lists for clarity. For
example, if the query is about warming potatoes, structure the response like this:\n\n"
"**Oven:**\n"
"1. Wrap leftover baked potatoes in foil and bake at 350°F (175°C) for 15-20 minutes, or until
heated through. This is the best method for restoring crispiness to the skin.\n\n"
"**Microwave:**\n"
"1. Pierce the potato several times with a fork to prevent exploding. Microwave on high for 1-3
minutes, depending on the size of the potato. This is fast but might make the potato slightly less
crispy.\n\n"
"Ensure the response is concise, professional, and easy to read with clear headings and lists."
)

payload = {
"contents": [{
"parts": [{"text": prompt}]
}]
}

headers = {'Content-Type': 'application/json'}


response = requests.post(GEMINI_API_URL, json=payload, headers=headers)
response_data = response.json()

if 'candidates' in response_data and response_data['candidates']:


ai_response_parts = response_data['candidates'][0]['content']['parts']
formatted_response = "\n".join(part["text"] for part in ai_response_parts if "text" in part)
else:
formatted_response = "Sorry, I couldn't generate a response."

return jsonify({
'status': 'success',
'query': user_message,
'response': formatted_response
})

except Exception as e:
return jsonify({'status': 'error', 'message': str(e)}), 500

# Weather advisory page


@app.route('/weather-advisory', methods=['GET', 'POST'])
def weather_advisory():
try:
if request.method == 'POST':
location = request.form['location'].strip()
crop = request.form['crop'].strip()

WEATHER_API_KEY= os.getenv('WEATHER_API_KEY')

INFORMATION TECHNOLOGY 83 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

weather_url = f'http://api.openweathermap.org/data/2.5/weather?
q={location},in&units=metric&appid={WEATHER_API_KEY}'

try:
response = requests.get(weather_url)
response.raise_for_status()
weather_data = response.json()
if weather_data['cod'] == 200:
temperature = weather_data['main']['temp']
humidity = weather_data['main']['humidity']
description = weather_data['weather'][0]['description']
else:
temperature, humidity, description = None, None, "Weather data unavailable"
except requests.RequestException as e:
temperature, humidity, description = None, None, f"Error fetching weather data: {str(e)}"

crop_info = next((c for c in crop_data['crops'] if c['name'].lower() == crop.lower()), None)


if crop_info:
crop_advice = f"{crop_info['weather_advice']} Current temperature: {temperature}°C,
Humidity: {humidity}%, Conditions: {description}."
optimal_temp = crop_info['optimal_temp']
yield_impact = crop_info['yield_impact']
else:
crop_advice = f"Crop advice not available for {crop}. Current temperature: {temperature}°C,
Humidity: {humidity}%, Conditions: {description}."
optimal_temp = "N/A"
yield_impact = "N/A"

return render_template('weather-advisory.html',
temperature=temperature,
humidity=humidity,
description=description,
crop_advice=crop_advice,
location=location,
crop=crop,
optimal_temp=optimal_temp,
yield_impact=yield_impact,
crops=crop_data['crops'])

return render_template('weather-advisory.html', crops=crop_data['crops'])

except Exception as e:
return render_template('weather-advisory.html', error=f"An error occurred: {str(e)}",
crops=crop_data['crops'])

# AI-Driven Fertilizer Optimization page


@app.route('/fertilizer-optimization', methods=['GET', 'POST'])
def fertilizer_optimization():
if request.method == 'POST':
crop = request.form['crop'].strip()
soil_type = request.form['soil_type'].strip()
soil_ph = request.form.get('soil_ph', '').strip() or 'unknown'

INFORMATION TECHNOLOGY 84 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

soil_nutrients = request.form.get('soil_nutrients', '').strip() or 'unknown'


weather_conditions = request.form.get('weather_conditions', '').strip() or 'unknown'

# Use Gemini API to check crop-soil compatibility


compatibility_prompt = (
f"Determine if the crop '{crop}' can grow well in '{soil_type}' soil. Respond in this exact
format:\n\n"
"Compatibility: [Yes or No]\n"
"Reason: [Brief explanation, e.g., 'Loamy soil is ideal for wheat due to its balanced drainage and
nutrient retention' or 'Sandy soil is not suitable for rice due to poor water retention']\n\n"
"Provide a concise, accurate response based on agricultural knowledge."
)

compatibility_payload = {
"contents": [{
"parts": [{"text": compatibility_prompt}]
}]
}

try:
compatibility_response = requests.post(GEMINI_API_URL, json=compatibility_payload)
compatibility_response.raise_for_status()
compatibility_result = compatibility_response.json()
if 'candidates' in compatibility_result and compatibility_result['candidates']:
compatibility_text = compatibility_result['candidates'][0]['content']['parts'][0]['text']
# Parse the compatibility response
compatibility_data = {}
for line in compatibility_text.split('\n'):
if ':' in line:
key, value = line.split(':', 1)
compatibility_data[key.strip()] = value.strip()

compatibility = compatibility_data.get('Compatibility', 'Unknown').lower() == 'yes'


reason = compatibility_data.get('Reason', '')

if not compatibility:
error = f"'{crop}' does not grow well in '{soil_type}' soil. {reason}"
return render_template('fertilizer-optimization.html', error=error)
else:
error = "Unable to determine crop-soil compatibility. Please try again."
return render_template('fertilizer-optimization.html', error=error)
except requests.RequestException as e:
error = f"Error checking compatibility: {str(e)}"
return render_template('fertilizer-optimization.html', error=error)

# Prepare prompt for Gemini API with fertilizer recommendations


fertilizer_prompt = (
f"Provide AI-driven fertilizer optimization recommendations for the following inputs, focusing
on limited, specific, and practical details, formatted exactly as shown below:\n"
f"- Crop: {crop}\n"
f"- Soil Type: {soil_type}\n"
f"- Soil pH: {soil_ph}\n"

INFORMATION TECHNOLOGY 85 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

f"- Soil Nutrients: {soil_nutrients}\n"


f"- Weather Conditions: {weather_conditions}\n\n"
"Respond in this exact format with concise, specific, and modern recommendations, ensuring
subheadings are bold and bulleted:\n\n"
"- **Type of Fertilizer:** [e.g., NPK (Balanced)]\n"
"- **Fertilizer Name:** [e.g., NPK 15-15-15]\n"
"- **Brands:** [e.g., Osmocote, Haifa, GrowMore – list 2-3 common brands]\n"
"- **Details:** [e.g., composition (N-P-K ratio), application rate (kg/acre or kg/ha), benefits for
the crop and soil]\n\n"
"Ensure the response is concise, professional, user-friendly, and optimized for resource
efficiency. Do not include the heading 'Fertilizer Optimization Results' in the response—only the
bulleted list with bold subheadings."
)

# Prepare payload for Gemini API


fertilizer_payload = {
"contents": [{
"parts": [{"text": fertilizer_prompt}]
}]
}

# Send request to Gemini API for fertilizer recommendations


try:
fertilizer_response = requests.post(GEMINI_API_URL, json=fertilizer_payload)
fertilizer_response.raise_for_status()
fertilizer_result = fertilizer_response.json()
if 'candidates' in fertilizer_result and fertilizer_result['candidates']:
analysis_text = fertilizer_result['candidates'][0]['content']['parts'][0]['text']
# Parse the response if needed, but for now, return it as is
fertilizer_recommendation = analysis_text
else:
fertilizer_recommendation = "Sorry, I couldn't generate a fertilizer recommendation."
except requests.RequestException as e:
fertilizer_recommendation = f"Error: API request failed - {str(e)}"

return render_template('fertilizer-optimization.html',
fertilizer_recommendation=fertilizer_recommendation,
crop=crop, soil_type=soil_type, soil_ph=soil_ph,
soil_nutrients=soil_nutrients, weather_conditions=weather_conditions)

return render_template('fertilizer-optimization.html')

@app.route("/health", methods=["GET", "HEAD"])


def health_check():
return "", 200

if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
 CNN.PY
import pandas as pd
import torch.nn as nn

INFORMATION TECHNOLOGY 86 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

class CNN(nn.Module):
def __init__(self, K):
super(CNN, self).__init__()
self.conv_layers = nn.Sequential(
# conv1
nn.Conv2d(in_channels=3, out_channels=32,
kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(32),
nn.Conv2d(in_channels=32, out_channels=32,
kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(32),
nn.MaxPool2d(2),
# conv2
nn.Conv2d(in_channels=32, out_channels=64,
kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(64),
nn.Conv2d(in_channels=64, out_channels=64,
kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(64),
nn.MaxPool2d(2),
# conv3
nn.Conv2d(in_channels=64, out_channels=128,
kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(128),
nn.Conv2d(in_channels=128, out_channels=128,
kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(128),
nn.MaxPool2d(2),
# conv4
nn.Conv2d(in_channels=128, out_channels=256,
kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(256),
nn.Conv2d(in_channels=256, out_channels=256,
kernel_size=3, padding=1),
nn.ReLU(),
nn.BatchNorm2d(256),
nn.MaxPool2d(2),
)
INFORMATION TECHNOLOGY 87 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

self.dense_layers = nn.Sequential(
nn.Dropout(0.4),
nn.Linear(50176, 1024),
nn.ReLU(),
nn.Dropout(0.4),
nn.Linear(1024, K),
)

def forward(self, X):


out = self.conv_layers(X)

# Flatten
out = out.view(-1, 50176)

# Fully connected
out = self.dense_layers(out)

return out

idx_to_classes = {0: 'Apple___Apple_scab',


1: 'Apple___Black_rot',
2: 'Apple___Cedar_apple_rust',
3: 'Apple___healthy',
4: 'Background_without_leaves',
5: 'Blueberry___healthy',
6: 'Cherry___Powdery_mildew',
7: 'Cherry___healthy',
8: 'Corn___Cercospora_leaf_spot Gray_leaf_spot',
9: 'Corn___Common_rust',
10: 'Corn___Northern_Leaf_Blight',
11: 'Corn___healthy',
12: 'Grape___Black_rot',
13: 'Grape___Esca_(Black_Measles)',
14: 'Grape___Leaf_blight_(Isariopsis_Leaf_Spot)',
15: 'Grape___healthy',
16: 'Orange___Haunglongbing_(Citrus_greening)',
17: 'Peach___Bacterial_spot',
18: 'Peach___healthy',
19: 'Pepper,_bell___Bacterial_spot',
20: 'Pepper,_bell___healthy',
21: 'Potato___Early_blight',
22: 'Potato___Late_blight',
23: 'Potato___healthy',
INFORMATION TECHNOLOGY 88 VPM’s POLYTECHNIC,THANE
SMART FARMING WEBSITE

24: 'Raspberry___healthy',
25: 'Soybean___healthy',
26: 'Squash___Powdery_mildew',
27: 'Strawberry___Leaf_scorch',
28: 'Strawberry___healthy',
29: 'Tomato___Bacterial_spot',
30: 'Tomato___Early_blight',
31: 'Tomato___Late_blight',
32: 'Tomato___Leaf_Mold',
33: 'Tomato___Septoria_leaf_spot',
34: 'Tomato___Spider_mites Two-spotted_spider_mite',
35: 'Tomato___Target_Spot',
36: 'Tomato___Tomato_Yellow_Leaf_Curl_Virus',
37: 'Tomato___Tomato_mosaic_virus',
38: 'Tomato___healthy'}

INFORMATION TECHNOLOGY 89 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

CHAPTER 7
CONCLUSION AND FUTURE SCOPE

INFORMATION TECHNOLOGY 90 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

CONCLUSION

Based on the information presented in the provided image and the inferred context as of 10:05 AM PST
on Friday, March 07, 2025, the AGRO-SETU website represents a promising initiative by the "Elite
Squad" to transform agriculture through technology. The platform’s mission to empower farmers with
AI-driven tools, personalized recommendations, and real-time insights aligns with the global shift
toward precision agriculture and sustainable farming practices. Features such as the AI Engine, Soil
Predictor, Weather Advisor, Fertilizer Optimization, Yojana Awareness, and Chatbot Support
demonstrate a comprehensive approach to addressing productivity, environmental sustainability, and
food security challenges. The website’s user-friendly design and focus on bridging traditional and
modern farming methods suggest potential to enhance farmer livelihoods, particularly in regions with
significant agricultural activity, such as India.
However, the lack of specific operational details, including an official registration page or live platform,
indicates that AGRO-SETU may still be in the development or pilot phase. Its success will depend on
effective implementation, ensuring accessibility for farmers with limited digital literacy, and integrating
robust data sources. If executed well, AGRO-SETU has the potential to serve as a model for agritech
platforms, fostering collaboration between farmers, governments, and technology providers to meet the
growing demand for sustainable food production.

FUTURE SCOPE

The future scope of the AGRO-SETU website is expansive, with opportunities to evolve and expand its
impact in the agricultural sector. The following areas highlight potential directions for growth and
innovation:
1. Geographical Expansion:
o Extend the platform’s reach beyond its initial target regions (e.g., India) to other
agricultural hubs in Asia, Africa, and Latin America, adapting features to local crops,
languages, and climates.
o Partner with international organizations like the FAO or CGIAR to facilitate global
scalability.
2. Enhanced Features:
o Integrate advanced technologies such as drone-based crop monitoring, blockchain for
supply chain transparency, and IoT sensors for real-time field data.
o Develop predictive models for pest and disease management, leveraging AI to provide
early warnings and treatment plans.
o Introduce a marketplace feature to connect farmers directly with buyers, enhancing
market access and income opportunities.
3. User Engagement and Training:
o Offer offline capabilities and localized training programs to bridge the digital divide,
ensuring accessibility for farmers in remote areas.
o Create a community forum or virtual workshops where farmers can share experiences and
learn from experts, fostering a knowledge-sharing ecosystem.
4. Data and Analytics Improvement:
o Build a comprehensive database integrating satellite imagery, weather forecasts, and
farmer-generated data to improve the accuracy of recommendations.
o Use machine learning to analyze long-term trends, providing insights into climate
adaptation and crop diversification strategies.

INFORMATION TECHNOLOGY 91 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

CHAPTER 8
REFERENCE

INFORMATION TECHNOLOGY 92 VPM’s POLYTECHNIC,THANE


SMART FARMING WEBSITE

REFERENCE:
 https://ijarcce.com/
 http://www.gofrugal.com/
 http://www.w3school.com/what-is-php-first-program.html
 https://www.geeksforgeeks.org
 https://www.javatpoint.com

INFORMATION TECHNOLOGY 93 VPM’s POLYTECHNIC,THANE


NOORI HALL BOOKING SYSTEM

INFORMATION TECHNOLOGY VPM’s POLYTECHNIC,THANE

You might also like