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