airAware2 / app.py
asghani's picture
Update app.py
fc51606 verified
import gradio as gr
import requests
import os
import groq
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Define API keys from environment variables
WAQI_API_KEY = os.getenv("WAQI_API_KEY")
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
# Set the base URL for WAQI API
WAQI_BASE_URL = "https://api.waqi.info/feed/{}/?token={}"
# Function to get AQI data from WAQI API
def get_aqi(location: str):
location = location.strip() # Clean the city name in case there are extra spaces
url = WAQI_BASE_URL.format(location, WAQI_API_KEY)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if data["status"] == "ok":
aqi = data["data"]["aqi"]
return aqi
else:
return None
return None
# Function to get health suggestions based on AQI using the Groq API (LLaMA model)
def get_health_suggestions(aqi: int, health_conditions: str):
# Create a prompt for the LLaMA model
prompt = f"Given an AQI of {aqi}, provide health advice for someone with the following conditions: {health_conditions}."
# Initialize the Groq client with the API key
client = groq.Groq(api_key=GROQ_API_KEY)
try:
# Request health suggestions using the Groq API
chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
model="llama-3.3-70b-versatile", # Adjust the model if needed
)
# Parse and return the health advice from the response
health_advice = chat_completion.choices[0].message.content.strip()
return health_advice
except Exception as e:
return f"Error fetching advice: {e}"
# Function to handle user input and provide responses (combining AQI and health suggestions)
def chatbot(city_name, health_conditions):
# Fetch AQI data based on location
aqi = get_aqi(city_name)
if aqi:
# Get health suggestions based on AQI and user health conditions
health_advice = get_health_suggestions(aqi, health_conditions)
return f"Current AQI in {city_name}: {aqi}\nHealth Suggestions: {health_advice}"
else:
return f"Could not retrieve AQI data for {city_name}. Please check the location name and try again."
# Define the list of cities for dropdown
city_list = ["Lahore", "Karachi", "Islamabad", "Peshawar", "Faisalabad"]
# Create Gradio interface with city dropdown, text input for health conditions
gr.Interface(
fn=chatbot,
inputs=[
gr.Dropdown(choices=city_list, label="Select Your City"), # City dropdown
gr.Textbox(placeholder="Enter health conditions (e.g., asthma, allergies)", label="Health Conditions") # Health conditions input
],
outputs="text", # Outputs AQI and health advice
live=True
).launch()