import requests import json from flask import Flask, render_template, request, jsonify, Response from google import genai import markdown import os app = Flask(__name__) api_key = os.getenv('GEMINI_API_KEY') # Replace with your actual Gemini API key client = genai.Client(api_key=api_key) def validate_coordinates(lat, lon): """Validate and convert latitude and longitude to float.""" try: return float(lat), float(lon) except (TypeError, ValueError): return None, None @app.route('/') def index(): return render_template('index.html') @app.route('/get_weather_data', methods=['GET']) def get_weather_data(): """ Fetch weather data using Open-Meteo's forecast endpoint: - daily: temperature_2m_max (max_temp), temperature_2m_min (min_temp), precipitation_sum (rain) - hourly: relative_humidity_2m, soil_moisture_3_to_9cm, cloudcover, windspeed_10m - current_weather: for current temperature and wind speed """ lat = request.args.get('lat') lon = request.args.get('lon') lat, lon = validate_coordinates(lat, lon) if lat is None or lon is None: return jsonify({"error": "Invalid coordinates"}), 400 try: forecast_url = "https://api.open-meteo.com/v1/forecast" forecast_params = { "latitude": lat, "longitude": lon, "current_weather": "true", "daily": "temperature_2m_max,temperature_2m_min,precipitation_sum", "hourly": "relative_humidity_2m,soil_moisture_3_to_9cm,cloudcover,windspeed_10m", "timezone": "auto" } resp = requests.get(forecast_url, params=forecast_params) resp.raise_for_status() data = resp.json() daily = data.get("daily", {}) hourly = data.get("hourly", {}) current = data.get("current_weather", {}) # Daily data max_temp = daily.get("temperature_2m_max", [None])[0] min_temp = daily.get("temperature_2m_min", [None])[0] rain = daily.get("precipitation_sum", [None])[0] # Hourly data (averages) humidity_list = hourly.get("relative_humidity_2m", []) soil_list = hourly.get("soil_moisture_3_to_9cm", []) cloud_list = hourly.get("cloudcover", []) wind_list = hourly.get("windspeed_10m", []) avg_humidity = sum(humidity_list)/len(humidity_list) if humidity_list else None avg_soil_moisture = sum(soil_list)/len(soil_list) if soil_list else None avg_cloud_cover = sum(cloud_list)/len(cloud_list) if cloud_list else None # Current weather current_temp = current.get("temperature") wind_speed = current.get("windspeed") weather = { "max_temp": max_temp, "min_temp": min_temp, "rainfall": rain, "humidity": avg_humidity, "soil_moisture": avg_soil_moisture, "current_temp": current_temp, "wind_speed": wind_speed, "cloud_cover": avg_cloud_cover } return jsonify(weather) except Exception as e: return jsonify({"error": str(e)}), 500 def call_gemini_api(input_data,language): """ Enhanced prompt: We request a visually appealing Markdown report WITHOUT showing raw CSS code blocks. Instead, we want a descriptive layout. NOTE: We instruct the model to produce headings, paragraphs, and a table in a color-rich, well-spaced manner, but NOT to display raw CSS code. """ prompt = f""" Create a visually appealing, farmer-friendly pest outbreak report in Markdown with the following:Please generate the following soil report analysis entirely in {language}. 1. A large, centered heading: "Pest Outbreak Dashboard Report". 2. A short paragraph indicating location (latitude: {input_data.get('latitude')}, longitude: {input_data.get('longitude')}), location as per lat,long(like just ex dont consider it as hardoced nagpur,india so kike fetch from lat,long) and the crop/farm context. 3. Several subheadings (e.g., "Agricultural Inputs", "Pest Outbreak Analysis", "Best Agricultural Practices", "Insights") with short paragraphs. 4. A colorfully styled table (no raw CSS code blocks) with: - Pest Name - Predicted Outbreak Month(s) - Severity - Precautionary Measures 5. Provide bullet points for best practices. 6. Use a friendly color scheme, with subtle hovers or highlights for rows, and consistent fonts. 7. Avoid printing any raw code blocks. 8. Incorporate the weather, soil, and agricultural data (like sowing date, irrigation method) into the narrative but do not list them as raw parameters. 9. do not give off topic insitruction only pest outbreka report i want okay, and dotn use special characters and justified text Important details from the user: - Crop Type: {input_data.get('crop_type')} - Sowing Date: {input_data.get('sowing_date')} - Harvest Date: {input_data.get('harvest_date')} - Current Growth Stage: {input_data.get('growth_stage')} - Irrigation Frequency: {input_data.get('irrigation_freq')} - Irrigation Method: {input_data.get('irrigation_method')} - Max Temp: {input_data.get('max_temp')} - Min Temp: {input_data.get('min_temp')} - Current Temp: {input_data.get('current_temp')} - Humidity: {input_data.get('humidity')} - Rainfall: {input_data.get('rain')} - Soil Moisture: {input_data.get('soil_moisture')} - Wind Speed: {input_data.get('wind_speed')} - Cloud Cover: {input_data.get('cloud_cover')} 10. also i want specific reocmmendation on pest control (seprate than precuatuonary measure below it in bullet pooints),best agriculktual practices,not generlaized one , but speicifc as perstudiyng each input paprmaetenrindetial okay,poepr sltying tbale should be rendered porpelry etc.. porper bold heaidng ,big fotn,left allgiemnd jsutified text, hihglight the imp points by yellow highlighter 11.again order first title the lat,long,location derive form lat long(ex : nagpur,india) then below it agiruclturla oinput parmeter analysis, then pest tbale then pest avidnaces practice in dpeth 10-12 with bueet pint safter that spciific agrficulturla best practices as per input parameters, after the damage of predicted pest some contnest and more dept contnext this shoudl be order. also render the report in ppeor format,proper rendering of tables etc in eveyr attmept ok,in all languages formatting should be proper """ response = client.models.generate_content( model="gemini-2.0-flash", contents=prompt, ) return response.text @app.route('/predict', methods=['POST']) def predict(): form_data = request.form.to_dict() language = form_data.get("language", "English") report_md = call_gemini_api(form_data,language) # Convert raw markdown to HTML report_html = markdown.markdown(report_md) # Inject advanced, colorful styling into the final HTML html_output = f""" Pest Outbreak Dashboard Report
{report_html}
""" return Response(html_output, mimetype="text/html") if __name__ == '__main__': app.run(debug=True)