sikeaditya commited on
Commit
ad903ce
Β·
verified Β·
1 Parent(s): 7bf4742

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -60
app.py CHANGED
@@ -2,90 +2,105 @@ import streamlit as st
2
  import requests
3
  import google.generativeai as genai
4
  from streamlit_js_eval import get_geolocation
5
- import os
 
6
 
7
  # Configure Google Gemini API
8
- GEMINI_API_KEY = os.getenv("GEMINI")
9
  genai.configure(api_key=GEMINI_API_KEY)
10
 
11
  # Streamlit UI
12
- st.set_page_config(page_title="Soil Report Analyzer", layout="wide")
13
- st.title("🌱 Soil Report Analyzer")
14
- st.write("Fetching your current location or enter an address to generate soil insights!")
15
 
16
- # User Input for Address
17
- manual_address = st.text_input("🌍 Enter your location (or leave blank to use device location):", "")
18
- latitude, longitude = None, None
19
 
20
- # Function to get coordinates from address
21
- def get_coordinates_from_address(address):
22
- url = f"https://nominatim.openstreetmap.org/search?q={address}&format=json&limit=1"
23
- response = requests.get(url)
24
- if response.status_code == 200 and response.json():
25
- location_data = response.json()[0]
26
- return float(location_data["lat"]), float(location_data["lon"])
27
- return None, None
28
 
29
- # Fetch User Location if no manual address is provided
30
- if manual_address:
31
- latitude, longitude = get_coordinates_from_address(manual_address)
32
- if latitude and longitude:
33
- st.success(f"πŸ“ Detected Location: {manual_address} (Lat: {latitude}, Lon: {longitude})")
34
- else:
35
- st.error("Could not fetch coordinates for the given address. Try refining your input.")
36
- else:
37
  location = get_geolocation()
38
  if location:
39
  latitude = location["coords"]["latitude"]
40
  longitude = location["coords"]["longitude"]
41
  st.success(f"πŸ“ Detected Location: Latitude {latitude}, Longitude {longitude}")
42
  else:
43
- st.warning("Could not fetch location. Please enable location access or enter an address.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- # User Input for Crop
46
- crop_planted = st.text_input("🌾 Enter the crop you are currently growing:", "")
 
 
 
 
 
 
47
 
48
- # API Call Function
49
- def fetch_soil_data(lat, lon):
50
- url = f"https://rest.isric.org/soilgrids/v2.0/properties/query?lon={lon}&lat={lat}&property=bdod&property=cfvo&property=clay&property=nitrogen&property=ocd&property=ocs&property=phh2o&property=sand&property=silt&property=soc&property=wv0010&property=wv0033&property=wv1500&depth=5-15cm&depth=15-30cm&value=Q0.05&value=mean"
51
- headers = {'accept': 'application/json'}
 
 
 
52
  response = requests.get(url, headers=headers)
53
  return response.json() if response.status_code == 200 else None
54
 
55
- # Summarize Soil Data using Gemini Flash
56
- def summarize_soil_report(soil_json, crop):
57
  model = genai.GenerativeModel("gemini-1.5-flash")
 
58
  prompt = f"""
59
- Analyze the given soil data and generate a **farmer-friendly** soil analysis report. Also, evaluate the suitability of growing '{crop}' based on the soil conditions and suggest better crops if needed.
60
- ### **Key Insights to Include:**
61
- 1. **Soil pH Level** - Determine if the soil is acidic, neutral, or alkaline and suggest corrections.
62
- 2. **Nutrient Content** - Assess nitrogen, organic carbon, and other nutrients; suggest improvements if needed.
63
- 3. **Soil Texture & Water Retention** - Use clay, sand, and silt content to determine water retention.
64
- 4. **Moisture Content & Irrigation Needs** - Provide irrigation best practices based on soil type.
65
- 5. **Crop Suitability Analysis** - Determine if '{crop}' is a good fit and suggest better alternatives if necessary.
66
- 6. **Soil Improvement Tips** - Offer actionable suggestions for farmers.
67
- ### **Soil Data Input:**
68
- {soil_json}
69
  """
 
70
  response = model.generate_content(prompt)
71
- return response.text if response else "Summary could not be generated."
72
 
73
- # Fetch and Process Soil Data
74
- if latitude and longitude and st.button("Get Soil Report"):
75
- with st.spinner("Fetching soil data... ⏳"):
76
- soil_data = fetch_soil_data(latitude, longitude)
 
 
77
 
78
- if soil_data:
79
- summary = summarize_soil_report(soil_data, crop_planted)
80
-
81
- st.subheader("πŸ“Œ Simplified Soil Report Summary")
82
- filtered_summary = "\n".join(
83
- line for line in summary.split("\n")
84
- if "Coordinates:" not in line # Exclude lines containing 'Coordinates:'
85
- )
86
- st.write(filtered_summary)
87
 
88
- # Option to download summary
89
- st.download_button("Download Summary as Text", filtered_summary, file_name="Soil_Report.txt")
90
  else:
91
- st.error("Failed to fetch soil data. Please try again later.")
 
2
  import requests
3
  import google.generativeai as genai
4
  from streamlit_js_eval import get_geolocation
5
+ import pandas as pd
6
+ import json
7
 
8
  # Configure Google Gemini API
9
+ GEMINI_API_KEY = "AIzaSyCA2xyVFZNvWAnGA-vZXq_g_LT-gchY0S4"
10
  genai.configure(api_key=GEMINI_API_KEY)
11
 
12
  # Streamlit UI
13
+ st.set_page_config(page_title="Weather-Based Farming Insights", layout="wide")
14
+ st.title("🌦 Weather-Based Farming Insights")
15
+ st.write("Select your location input method to get farming recommendations!")
16
 
17
+ # Location Input Options
18
+ location_option = st.radio("Choose a method to input your location:", ["Current Location", "Select on Map", "Enter Coordinates"])
 
19
 
20
+ latitude, longitude = None, None
 
 
 
 
 
 
 
21
 
22
+ if location_option == "Current Location":
 
 
 
 
 
 
 
23
  location = get_geolocation()
24
  if location:
25
  latitude = location["coords"]["latitude"]
26
  longitude = location["coords"]["longitude"]
27
  st.success(f"πŸ“ Detected Location: Latitude {latitude}, Longitude {longitude}")
28
  else:
29
+ st.warning("Could not fetch location. Please enable location access.")
30
+
31
+ elif location_option == "Select on Map":
32
+ st.write("Click on the map to select a location (Limited to India).")
33
+ india_bounds = {
34
+ "north": 35.513327,
35
+ "south": 6.4626999,
36
+ "west": 68.1097,
37
+ "east": 97.395358
38
+ }
39
+ selected_point = st.map(pd.DataFrame({'lat': [20.5937], 'lon': [78.9629]}), zoom=4)
40
+ manual_coords = st.text_input("Enter Selected Coordinates (Latitude, Longitude):")
41
+
42
+ if manual_coords:
43
+ try:
44
+ lat, lon = map(float, manual_coords.split(","))
45
+ if india_bounds["south"] <= lat <= india_bounds["north"] and india_bounds["west"] <= lon <= india_bounds["east"]:
46
+ latitude, longitude = lat, lon
47
+ st.success(f"πŸ“ Selected Location: Latitude {latitude}, Longitude {longitude}")
48
+ else:
49
+ st.error("Selected location is outside India. Please choose a valid location.")
50
+ except ValueError:
51
+ st.error("Invalid coordinates format. Use 'Latitude, Longitude'.")
52
 
53
+ elif location_option == "Enter Coordinates":
54
+ latitude = st.number_input("Enter Latitude:", format="%.6f")
55
+ longitude = st.number_input("Enter Longitude:", format="%.6f")
56
+ if latitude and longitude:
57
+ st.success(f"πŸ“ Entered Location: Latitude {latitude}, Longitude {longitude}")
58
+
59
+ # Optional Crop Input
60
+ crop_name = st.text_input("🌾 Enter the crop you're growing (optional):", "")
61
 
62
+ # Fetch Weather Data
63
+ def fetch_weather_data(lat, lon):
64
+ url = f"https://api.ambeedata.com/weather/latest/by-lat-lng?lat={lat}&lng={lon}"
65
+ headers = {
66
+ "x-api-key": "248a9eaf9b598539543c3b3c79709a62f326c24d53df0e6d951becf4fa58cc15",
67
+ "Content-type": "application/json"
68
+ }
69
  response = requests.get(url, headers=headers)
70
  return response.json() if response.status_code == 200 else None
71
 
72
+ # Generate Farming Report
73
+ def generate_farming_report(weather_json, crop):
74
  model = genai.GenerativeModel("gemini-1.5-flash")
75
+
76
  prompt = f"""
77
+ Analyze the given weather data and generate a *farmer-friendly* report in simple terms.
78
+ Provide insights on:
79
+ - *Impact of Current Weather on {crop if crop else 'general crops'}*: Any risks or benefits.
80
+ - *Precautions for Farmers*: How to protect against weather-related risks.
81
+ - *Best Crops to Grow*: Based on temperature, air quality, and humidity.
82
+ - *Market Price Trends*: Whether the weather may affect future crop prices.
83
+
84
+ *Weather Data:*
85
+ {weather_json}
 
86
  """
87
+
88
  response = model.generate_content(prompt)
89
+ return response.text if response else "Could not generate report."
90
 
91
+ # Fetch and Process Weather Data
92
+ report_text = None
93
+
94
+ if latitude and longitude and st.button("Get Farming Report"):
95
+ with st.spinner("Fetching weather data... ⏳"):
96
+ weather_data = fetch_weather_data(latitude, longitude)
97
 
98
+ if weather_data:
99
+ report_text = generate_farming_report(weather_data, crop_name)
100
+ st.subheader("πŸ“„ Weather-Based Farming Report")
101
+ st.write(report_text)
 
 
 
 
 
102
 
103
+ # Option to download report
104
+ st.download_button("Download Report", report_text, file_name="Farming_Report.txt")
105
  else:
106
+ st.error("Failed to fetch weather data. Please try again later.")