File size: 4,348 Bytes
3f212ad
 
 
 
ad903ce
 
7bf4742
3f212ad
ad903ce
3f212ad
 
 
ad903ce
 
 
3f212ad
ad903ce
 
3f212ad
ad903ce
7bf4742
ad903ce
7bf4742
 
 
 
 
 
ad903ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f212ad
ad903ce
 
 
 
 
 
 
 
3f212ad
ad903ce
 
 
 
 
 
 
3f212ad
 
 
ad903ce
 
3f212ad
ad903ce
3f212ad
ad903ce
 
 
 
 
 
 
 
 
3f212ad
ad903ce
3f212ad
ad903ce
3f212ad
ad903ce
 
 
 
 
 
3f212ad
ad903ce
 
 
 
3f212ad
ad903ce
 
3f212ad
ad903ce
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
import streamlit as st
import requests
import google.generativeai as genai
from streamlit_js_eval import get_geolocation
import pandas as pd
import json

# Configure Google Gemini API
GEMINI_API_KEY = "AIzaSyCA2xyVFZNvWAnGA-vZXq_g_LT-gchY0S4"
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("Select your location input method to get farming recommendations!")

# Location Input Options
location_option = st.radio("Choose a method to input your location:", ["Current Location", "Select on Map", "Enter Coordinates"])

latitude, longitude = None, None

if location_option == "Current Location":
    location = get_geolocation()
    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.")

elif location_option == "Select on Map":
    st.write("Click on the map to select a location (Limited to India).")
    india_bounds = {
        "north": 35.513327,
        "south": 6.4626999,
        "west": 68.1097,
        "east": 97.395358
    }
    selected_point = st.map(pd.DataFrame({'lat': [20.5937], 'lon': [78.9629]}), zoom=4)
    manual_coords = st.text_input("Enter Selected Coordinates (Latitude, Longitude):")
    
    if manual_coords:
        try:
            lat, lon = map(float, manual_coords.split(","))
            if india_bounds["south"] <= lat <= india_bounds["north"] and india_bounds["west"] <= lon <= india_bounds["east"]:
                latitude, longitude = lat, lon
                st.success(f"πŸ“ Selected Location: Latitude {latitude}, Longitude {longitude}")
            else:
                st.error("Selected location is outside India. Please choose a valid location.")
        except ValueError:
            st.error("Invalid coordinates format. Use 'Latitude, Longitude'.")

elif location_option == "Enter Coordinates":
    latitude = st.number_input("Enter Latitude:", format="%.6f")
    longitude = st.number_input("Enter Longitude:", format="%.6f")
    if latitude and longitude:
        st.success(f"πŸ“ Entered Location: Latitude {latitude}, Longitude {longitude}")

# 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": "248a9eaf9b598539543c3b3c79709a62f326c24d53df0e6d951becf4fa58cc15",
        "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")
    
    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 if crop else 'general crops'}*: Any risks or benefits.
    - *Precautions for Farmers*: How to protect against weather-related risks.
    - *Best Crops to Grow*: Based on temperature, air quality, and humidity.
    - *Market Price Trends*: Whether the weather may affect future crop prices.

    *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

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.")