Spaces:
Running
Running
File size: 3,219 Bytes
bd41292 |
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 |
import streamlit as st
import requests
import google.generativeai as genai
from streamlit_js_eval import get_geolocation
import os
# Configure Google Gemini API
GEMINI_API_KEY = os.getenv('GEMINI')
genai.configure(api_key=GEMINI_API_KEY)
# Streamlit UI
st.set_page_config(page_title="Weather-Based Farming Insights", layout="wide")
st.title("π¦οΈ Weather-Based Farming Insights")
st.write("Fetching your location to provide farming recommendations!")
# Fetch User Location
location = get_geolocation()
latitude, longitude = None, None
if location:
latitude = location["coords"]["latitude"]
longitude = location["coords"]["longitude"]
st.success(f"π Detected Location: Latitude {latitude}, Longitude {longitude}")
else:
st.warning("Could not fetch location. Please enable location access.")
# Optional Crop Input
crop_name = st.text_input("πΎ Enter the crop you're growing (optional):", "")
# Fetch Weather Data
def fetch_weather_data(lat, lon):
url = f"https://api.ambeedata.com/weather/latest/by-lat-lng?lat={lat}&lng={lon}"
headers = {
"x-api-key": os.getenv('WEATHER'),
"Content-type": "application/json"
}
response = requests.get(url, headers=headers)
return response.json() if response.status_code == 200 else None
# Generate Farming Report
def generate_farming_report(weather_json, crop):
model = genai.GenerativeModel("gemini-1.5-flash")
# Adjust prompt based on crop input
if crop:
prompt = f"""
Analyze the given weather data and generate a **farmer-friendly** report in simple terms.
Provide insights on:
- **Impact of Current Weather on {crop}**: Any risks or benefits.
- **Precautions for Farmers Growing {crop}**: How to protect against weather-related risks.
- **Market Price Trends**: Whether the weather may affect future crop prices.
**Weather Data:**
{weather_json}
"""
else:
prompt = f"""
Analyze the given weather data and generate a **farmer-friendly** report in simple terms.
Provide guidance on:
- **Impact on Crops**: How current weather affects growing crops.
- **Best Crops to Grow**: Based on temperature, air quality, and humidity.
- **Precautions for Farmers**: Weather-related risks and farming safety measures.
**Weather Data:**
{weather_json}
"""
response = model.generate_content(prompt)
return response.text if response else "Could not generate report."
# Fetch and Process Weather Data
report_text = None # Initialize variable
if latitude and longitude and st.button("Get Farming Report"):
with st.spinner("Fetching weather data... β³"):
weather_data = fetch_weather_data(latitude, longitude)
if weather_data:
report_text = generate_farming_report(weather_data, crop_name)
st.subheader("π Weather-Based Farming Report")
st.write(report_text)
# Option to download report
st.download_button("Download Report", report_text, file_name="Farming_Report.txt")
else:
st.error("Failed to fetch weather data. Please try again later.")
|