Spaces:
Build error
Build error
File size: 10,197 Bytes
4e44b6c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | import streamlit as st
from PIL import Image
import google.generativeai as genai
from geopy.geocoders import Nominatim
from deep_translator import GoogleTranslator
import requests
import io
import datetime
import pandas as pd
import matplotlib.pyplot as plt
# Get the current date
current_date = datetime.datetime.now()
cur_date = f"{current_date.day}/{current_date.month}/{current_date.year}"
# Configure Google Generative AI
genai.configure(api_key="AIzaSyAXCVMFirOACW80v3w4lNEruWBAskWbeiw") # Replace with your API key
weather_model = genai.GenerativeModel('gemini-1.5-flash')
farming_model = genai.GenerativeModel('gemini-pro')
# Initialize session state
if 'location' not in st.session_state:
st.session_state['location'] = ""
if 'crops' not in st.session_state:
st.session_state['crops'] = ""
if 'section' not in st.session_state:
st.session_state['section'] = "Weather Update"
if 'weather_data' not in st.session_state:
st.session_state['weather_data'] = None
if 'farming_plan' not in st.session_state:
st.session_state['farming_plan'] = None
if 'url' not in st.session_state:
st.session_state['url'] = None
# Sidebar navigation
st.sidebar.title("Menu")
st.sidebar.radio(
"Choose a section:",
["Edit Information", "Weather Update", "Disease Prediction", "Price Plots"],
key='section'
)
# Function to get location coordinates
def get_location_coordinates(location_name):
loc = Nominatim(user_agent="GetLoc")
getLoc = loc.geocode(location_name)
if getLoc:
return getLoc.latitude, getLoc.longitude
else:
return None, None
# Function to fetch HTML content from a weather website
def get_html(url):
try:
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
else:
st.error(f"Failed to fetch the page. Status code: {response.status_code}")
return None
except Exception as e:
st.error(f"An error occurred: {e}")
return None
# Function to analyze weather data using AI
def analyze_weather_data(raw_data):
st.info("π Crunching the weather data... Hang tight, farmer!")
prompt = f"""
I have the following text,
{raw_data}
This is a 15-day weather forecast. Today's date is `{cur_date}` in DD/MM/YYYY format.
Please analyze the data and format it correctly in this structure:
Date: {{date}}
Highest Temperature: {{highest_temperature}}
Lowest Temperature: {{lowest_temperature}}
Humidity: {{humidity}}
Percentage of Rain: {{rain_percentage}}
Wind Speed: {{wind_speed}}
Climate: {{climate}}
"""
response = weather_model.generate_content(prompt)
return response.text
# Function to generate a farming plan
def generate_farming_plan(analyzed_data, crops):
st.info("πΎ Mapping out a smart farming plan for you... Stay tuned!")
prompt = f"""
Here is the text from a weather report of next 15 days:
{analyzed_data}
The user is actually a farmer and has these crops: {crops}.
Analyse the data completely and give me a concise farming plan for the next 15 days.
Focus on the varying weather reports, highlight if the farmer wants to undergo any precautions before anything unexpected happens.
Provide it with the actual date.
"""
response = farming_model.generate_content(prompt)
return response.text
# Function to analyze plant disease using AI
def analyze_plant_disease(image_description, image):
st.info("π§ Investigating plant health... This will just take a moment!")
prompt = """
Analyze the provided image of a plant and determine the type of disease it is affected by.
Follow the structure outlined below:
Template for Response:
```
Plant Name: {plant_name}
Disease Name: {disease_name}
Disease Severity: {severity_level}
Suggestions to Overcome: {suggestions}
```
Guidelines:
- Identify the type of disease in the image of the plant.
- If unclear, provide an approximate answer.
- Ensure the response is concise, accurate, and aligned with the template.
"""
if image_description:
prompt += f"""
Here is a description of the image from the user:
```
{image_description}
```
Consider this information carefully in your response.
"""
img_buffer = io.BytesIO()
image.save(img_buffer, format="PNG")
img_buffer.seek(0)
response = weather_model.generate_content([prompt, Image.open(img_buffer)])
return response.text.strip("```")
# Function to translate text to Tamil
def translate_to_tamil(text):
translator = GoogleTranslator(source='auto', target='ta')
return translator.translate(text)
def bold_text_before_colon(text):
# Split the input text into lines
lines = text.split('\n')
# Process each line to add bold formatting before the colon
formatted_lines = []
for line in lines:
if ':' in line:
# Split the line at the first colon
before_colon, after_colon = line.split(':', 1)
# Add bold formatting to the part before the colon
formatted_line = f"**{before_colon.strip()}**: {after_colon.strip()}"
else:
# If no colon is present, keep the line unchanged
formatted_line = line.strip()
formatted_lines.append(formatted_line)
# Join all the formatted lines back together
return '\n'.join(formatted_lines)
def clear_weather_data():
st.session_state['weather_data'] = None
st.session_state['farming_plan'] = None
# Function to plot individual datasets
def plot_data(data, x_col, y_col, xlabel, ylabel, title):
fig, ax = plt.subplots()
ax.plot(data[x_col], data[y_col])
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_title(title)
st.pyplot(fig)
# Main application logic
if st.session_state['section'] == "Edit Information":
st.title("Edit Information")
location = st.text_input("Enter the location:", st.session_state['location'])
crops = st.text_input("Enter your crops (comma-separated):", st.session_state['crops'])
if st.button("Save"):
st.session_state['location'] = location
st.session_state['crops'] = crops
st.success("Information saved! π")
clear_weather_data()
elif st.session_state['section'] == "Weather Update":
st.title("15-Day Weather Forecast")
if not st.session_state['location'] or not st.session_state['crops']:
st.error("Please enter your location and crops in the 'Edit Information' section.")
else:
if not st.session_state['weather_data']:
lat, long = get_location_coordinates(st.session_state['location'])
if lat and long:
st.session_state['url'] = f"https://weather.com/en-IN/weather/tenday/l/{lat},{long}?par=google"
html_content = get_html(st.session_state['url'])
if html_content:
st.markdown("β‘ **Analyzing weather trends with cutting-edge AI...**")
weather_data = analyze_weather_data(html_content)
farming_plan = generate_farming_plan(weather_data, st.session_state['crops'])
st.session_state['weather_data'] = weather_data
st.session_state['farming_plan'] = farming_plan
else:
st.error("Location not found. Please enter a valid location.")
st.markdown(st.session_state['farming_plan'])
st.markdown(f"[For more weather updates, click here]({st.session_state['url']})")
elif st.session_state['section'] == "Disease Prediction":
st.title("Plant Disease Detection System")
uploaded_image = st.file_uploader("Upload a plant image", type=["jpg", "jpeg", "png"])
if uploaded_image:
image = Image.open(uploaded_image)
st.image(image, caption="Uploaded Image", use_column_width=True)
image_description = st.text_area("Enter a brief description of the plant and symptoms (optional):", "")
if st.button("Analyze"):
with st.spinner("Analyzing the plant disease..."):
original_response = bold_text_before_colon(analyze_plant_disease(image_description, image))
st.success("Analysis Complete! π―")
st.subheader("**Analysis Report (English):**")
original_response = original_response.replace("\n"," \n").replace("\n\n"," \n")
st.markdown(original_response)
tamil_translation = translate_to_tamil(original_response)
st.subheader("**Analysis Report (Tamil):**")
tamil_translation = tamil_translation.replace("\n"," \n").replace("\n\n"," \n")
st.markdown(tamil_translation)
elif st.session_state['section'] == "Price Plots":
st.title("Crop Price Trends")
col1, col2 = st.columns(2)
with col1:
df = pd.read_csv("content/retail_prices.csv")
st.subheader("Rice Prices")
if not df.empty:
plot_data(df, 'date', 'pricw', 'Date', 'Price of Rice', 'Date vs Price of Rice')
else:
st.write("No data available for Rice.")
with col2:
df1 = pd.read_csv("content/Tomato.csv")
st.subheader("Tomato Prices")
if not df1.empty:
plot_data(df1, 'Date', 'Price', 'Date', 'Price of Tomato', 'Date vs Price of Tomato')
else:
st.write("No data available for Tomato.")
col3, col4 = st.columns(2)
with col3:
df3 = pd.read_csv("content/turmeric_price_6_months_with_dates.csv")
st.subheader("Turmeric Prices")
if not df3.empty:
plot_data(df3, 'Date', 'Price', 'Date', 'Price of Turmeric', 'Date vs Price of Turmeric')
else:
st.write("No data available for Turmeric.")
with col4:
df4 = pd.read_csv("content/44444.csv")
st.subheader("Wheat Prices")
if not df4.empty:
plot_data(df4, 'date', 'pricw', 'Date', 'Price of Wheat', 'Date vs Price of Wheat')
else:
st.write("No data available for Wheat.") |