Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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
|
|
|
6 |
|
7 |
# Configure Google Gemini API
|
8 |
-
GEMINI_API_KEY =
|
9 |
genai.configure(api_key=GEMINI_API_KEY)
|
10 |
|
11 |
# Streamlit UI
|
12 |
-
st.set_page_config(page_title="
|
13 |
-
st.title("
|
14 |
-
st.write("
|
15 |
|
16 |
-
#
|
17 |
-
|
18 |
-
latitude, longitude = None, None
|
19 |
|
20 |
-
|
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 |
-
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
|
48 |
-
#
|
49 |
-
def
|
50 |
-
url = f"https://
|
51 |
-
headers = {
|
|
|
|
|
|
|
52 |
response = requests.get(url, headers=headers)
|
53 |
return response.json() if response.status_code == 200 else None
|
54 |
|
55 |
-
#
|
56 |
-
def
|
57 |
model = genai.GenerativeModel("gemini-1.5-flash")
|
|
|
58 |
prompt = f"""
|
59 |
-
Analyze the given
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
{soil_json}
|
69 |
"""
|
|
|
70 |
response = model.generate_content(prompt)
|
71 |
-
return response.text if response else "
|
72 |
|
73 |
-
# Fetch and Process
|
74 |
-
|
75 |
-
|
76 |
-
|
|
|
|
|
77 |
|
78 |
-
if
|
79 |
-
|
80 |
-
|
81 |
-
st.
|
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
|
89 |
-
st.download_button("Download
|
90 |
else:
|
91 |
-
st.error("Failed to fetch
|
|
|
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.")
|