import streamlit as st from groq import Groq import requests import pandas as pd from datetime import datetime, timedelta import pycountry from fpdf import FPDF import io import base64 from geopy.geocoders import Nominatim from geopy.exc import GeocoderTimedOut import plotly.express as px import plotly.graph_objects as go import unicodedata import os from dotenv import load_dotenv # Load environment variables load_dotenv() # Get API keys from environment variables GROQ_API_KEY = os.getenv("GROQ_API_KEY") AIRVISUAL_API_KEY = os.getenv("AIRVISUAL_API_KEY") DEFAULT_MODEL = "llama3-70b-8192" # === INIT Groq CLIENT === client = Groq(api_key=GROQ_API_KEY) # === PAGE CONFIG === st.set_page_config( page_title="🌱 AI Climate & Smart Farming Assistant", page_icon="🌾", layout="wide", initial_sidebar_state="expanded" ) # === CSS STYLING === st.markdown( """ """, unsafe_allow_html=True ) # === HEADER === st.markdown("
Real-time AI insights + live weather data
", unsafe_allow_html=True) st.markdown("---") # === SYSTEM PROMPTS === system_prompts = { "Track Pollution": ( "You are an expert environmental scientist. " "Help users understand pollution levels in air, water, or soil using scientific reasoning. " "Provide actionable recommendations for improvement." ), "Carbon Emissions": ( "You are a sustainability advisor. " "Estimate and explain carbon emissions, suggest reductions and eco-friendly alternatives. " "Include cost-benefit analysis and ROI calculations." ), "Predict Climate Patterns": ( "You are a climate researcher. Predict or explain regional climate changes using current and historical data. " "Include statistical analysis and confidence intervals." ), "Smart Farming Advice": ( "You are an AI-powered farming assistant. Help users with crop selection, irrigation, pest control, and yield optimization. " "Focus on sustainable practices and resource efficiency." ), } # === EXAMPLE QUERIES === example_queries = { "Track Pollution": "e.g., What's the air quality near Lahore right now?", "Carbon Emissions": "e.g., How can a factory reduce CO2 output sustainably?", "Predict Climate Patterns": "e.g., What climate changes are expected in sub-Saharan Africa?", "Smart Farming Advice": "e.g., Best crops to grow in dry conditions in Uganda?", } # === UTILS: API CALLS === def get_weather(location: str): try: # First, get coordinates for the location geocoding_url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1" geo_resp = requests.get(geocoding_url, timeout=10) geo_resp.raise_for_status() geo_data = geo_resp.json() if not geo_data.get('results'): return None lat = geo_data['results'][0]['latitude'] lon = geo_data['results'][0]['longitude'] location_name = geo_data['results'][0]['name'] # Then get weather data for those coordinates weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t=temperature_2m,relative_humidity_2m,wind_speed_10m,weather_code" weather_resp = requests.get(weather_url, timeout=10) weather_resp.raise_for_status() weather_data = weather_resp.json() # Weather code to description mapping weather_codes = { 0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast", 45: "Foggy", 48: "Depositing rime fog", 51: "Light drizzle", 53: "Moderate drizzle", 55: "Dense drizzle", 61: "Slight rain", 63: "Moderate rain", 65: "Heavy rain", 71: "Slight snow", 73: "Moderate snow", 75: "Heavy snow", 77: "Snow grains", 80: "Slight rain showers", 81: "Moderate rain showers", 82: "Violent rain showers", 85: "Slight snow showers", 86: "Heavy snow showers", 95: "Thunderstorm", 96: "Thunderstorm with slight hail", 99: "Thunderstorm with heavy hail" } current = weather_data['current'] weather_code = current['weather_code'] weather_desc = weather_codes.get(weather_code, "Unknown") return { "location": location_name, "description": weather_desc, "temperature_C": current['temperature_2m'], "humidity_%": current['relative_humidity_2m'], "wind_speed_m/s": current['wind_speed_10m'] } except Exception as e: return None def get_historical_weather(location: str, days: int = 7): try: # Get coordinates geocoding_url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1" geo_resp = requests.get(geocoding_url, timeout=10) geo_resp.raise_for_status() geo_data = geo_resp.json() if not geo_data.get('results'): return None lat = geo_data['results'][0]['latitude'] lon = geo_data['results'][0]['longitude'] # Get historical data end_date = datetime.now() start_date = end_date - timedelta(days=days) weather_url = ( f"https://api.open-meteo.com/v1/forecast" f"?latitude={lat}&longitude={lon}" f"&start_date={start_date.strftime('%Y-%m-%d')}" f"&end_date={end_date.strftime('%Y-%m-%d')}" f"&daily=temperature_2m_max,temperature_2m_min,precipitation_sum,wind_speed_10m_max" ) weather_resp = requests.get(weather_url, timeout=10) weather_resp.raise_for_status() return weather_resp.json() except Exception as e: return None def get_air_quality(location: str): try: # First, get coordinates for the location geocoding_url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1" geo_resp = requests.get(geocoding_url, timeout=10) geo_resp.raise_for_status() geo_data = geo_resp.json() if not geo_data.get('results'): return None lat = geo_data['results'][0]['latitude'] lon = geo_data['results'][0]['longitude'] # Try Open-Meteo API first aq_url = f"https://air-quality-api.open-meteo.com/v1/air-quality?latitude={lat}&longitude={lon}¤t=pm10,pm2_5,ozone,nitrogen_dioxide,sulphur_dioxide" aq_resp = requests.get(aq_url, timeout=10) if aq_resp.status_code == 200: aq_data = aq_resp.json() if 'current' in aq_data: return aq_data # If Open-Meteo fails, try AirVisual API airvisual_url = f"http://api.airvisual.com/v2/nearest_city?lat={lat}&lon={lon}&key={AIRVISUAL_API_KEY}" airvisual_resp = requests.get(airvisual_url, timeout=10) if airvisual_resp.status_code == 200: airvisual_data = airvisual_resp.json() if 'data' in airvisual_data and 'current' in airvisual_data['data']: current = airvisual_data['data']['current']['pollution'] return { 'current': { 'pm10': current.get('p1'), 'pm2_5': current.get('p2'), 'ozone': current.get('o3'), 'nitrogen_dioxide': None, 'sulphur_dioxide': None } } return None except Exception as e: print(f"Air quality error: {str(e)}") return None # === UTILS: PDF Generation === def clean_text_for_pdf(text): """Clean text to be PDF-safe by removing or replacing problematic characters""" # Normalize Unicode characters text = unicodedata.normalize('NFKD', text) # Replace common problematic characters replacements = { 'μ': 'micro', '°': ' degrees', '℃': 'C', '±': '+/-', '×': 'x', '÷': '/', '≤': '<=', '≥': '>=', '≠': '!=', '∞': 'infinity', '→': '->', '←': '<-', '↑': 'up', '↓': 'down', '↔': '<->', '≈': '~=', '∑': 'sum', '∏': 'product', '√': 'sqrt', '∫': 'integral', '∆': 'delta', '∇': 'nabla', '∂': 'partial', '∝': 'proportional to', '∞': 'infinity', '∅': 'empty set', '∈': 'in', '∉': 'not in', '⊂': 'subset', '⊃': 'superset', '∪': 'union', '∩': 'intersection', '∀': 'for all', '∃': 'exists', '∄': 'does not exist', '∴': 'therefore', '∵': 'because' } for char, replacement in replacements.items(): text = text.replace(char, replacement) return text def generate_pdf(chat_history, title="AI Climate & Farming Advice"): pdf = FPDF() pdf.add_page() # Use built-in font pdf.set_font("helvetica", "B", 16) pdf.cell(0, 10, clean_text_for_pdf(title), ln=True, align='C') pdf.ln(10) # Chat history for chat in chat_history: # User message pdf.set_font("helvetica", "B", 12) pdf.cell(0, 10, "User:", ln=True) pdf.set_font("helvetica", "", 12) # Clean and wrap text user_text = clean_text_for_pdf(chat["user"]) pdf.multi_cell(0, 10, user_text) pdf.ln(5) # AI response pdf.set_font("helvetica", "B", 12) pdf.cell(0, 10, "AI Response:", ln=True) pdf.set_font("helvetica", "", 12) # Clean and wrap text ai_text = clean_text_for_pdf(chat["ai"]) pdf.multi_cell(0, 10, ai_text) pdf.ln(10) return pdf.output(dest="S").encode("latin-1", "replace") # === UTILS: Get Country List === def get_country_list(): countries = [country.name for country in pycountry.countries] return sorted(countries) # === SIDEBAR === st.sidebar.header("🌟 Features") page = st.sidebar.radio( "Choose your tool:", [ "AI Assistant Chat", "Weather Data", "Smart Farming CSV Analysis", ] ) # === MULTI-TURN CHAT === if page == "AI Assistant Chat": st.subheader("🧠 AI Climate & Farming Chat Assistant") option = st.selectbox( "Choose a use case:", list(system_prompts.keys()) ) st.markdown(f"💡 *Example*: {example_queries[option]}") user_input = st.text_area("Enter your question or describe your situation:") if "chat_history" not in st.session_state: st.session_state.chat_history = [] if st.button("Send to AI") and user_input.strip(): with st.spinner("Thinking..."): messages = [ {"role": "system", "content": system_prompts[option]}, ] # Append chat history for multi-turn for chat in st.session_state.chat_history: messages.append({"role": "user", "content": chat["user"]}) messages.append({"role": "assistant", "content": chat["ai"]}) # Add current user input messages.append({"role": "user", "content": user_input}) response = client.chat.completions.create( model=DEFAULT_MODEL, messages=messages, ) ai_response = response.choices[0].message.content # Save chat st.session_state.chat_history.append({"user": user_input, "ai": ai_response}) # Clear input box st.rerun() if st.session_state.chat_history: st.markdown("### 🕘 Conversation History") for chat in reversed(st.session_state.chat_history): st.markdown(f"