plant_search / app.py
AhmadRAZA23's picture
Update app.py
10a3bb1 verified
import streamlit as st
import requests
from transformers import pipeline
# Cache the AI models to avoid reloading them on every interaction
@st.cache_resource
def load_qa_model():
try:
return pipeline("question-answering", model="distilbert-base-cased-distilled-squad", framework="pt")
except Exception as e:
st.error(f"Error loading QA model: {e}")
return None
@st.cache_resource
def load_text_generation_model():
try:
return pipeline("text-generation", model="gpt2", framework="pt")
except Exception as e:
st.error(f"Error loading text generation model: {e}")
return None
# Initialize the AI models
qa_pipeline = load_qa_model()
text_generation_pipeline = load_text_generation_model()
# Cache the plant data fetching function to avoid redundant API calls
@st.cache_data(ttl=3600) # Cache for 1 hour
def fetch_plant_data(plant_name):
url = f"https://openfarm.cc/api/v1/crops?filter={plant_name}"
try:
response = requests.get(url)
response.raise_for_status() # Raise an error for bad status codes
data = response.json()
if data.get("data"):
# Get the first result (most likely match)
plant_info = data["data"][0]["attributes"]
return {
"name": plant_info.get("name", plant_name),
"description": plant_info.get("description", "No description available."),
"image_url": plant_info.get("main_image_path", None),
"sun_requirements": plant_info.get("sun_requirements", "No information available."),
"watering": plant_info.get("watering", "No specific instructions available."),
"growth_rate": plant_info.get("growth_rate", "No information available."),
"spacing": plant_info.get("spacing", "No information available."),
"sowing_method": plant_info.get("sowing_method", "No information available."),
}
else:
st.warning(f"No data found for the plant: {plant_name}")
return None
except requests.exceptions.RequestException as e:
st.error(f"Error fetching plant data: {e}")
return None
# Function to generate watering instructions using AI
def refine_watering_instructions(plant_name, basic_instructions=None):
prompt = (
f"Provide detailed watering instructions for the plant '{plant_name}'. "
f"Base your response on the following basic instructions: '{basic_instructions}'. "
"Include information on how often to water, the amount of water needed, and any seasonal variations."
)
try:
result = text_generation_pipeline(prompt, max_length=200, num_return_sequences=1)
return result[0]["generated_text"]
except Exception as e:
st.error(f"Error generating watering instructions: {e}")
return "Unable to generate watering instructions at this time."
# Function to check if the image URL is valid
def is_valid_image_url(url):
if url is None:
return False
try:
response = requests.head(url)
return response.status_code == 200
except requests.exceptions.RequestException:
return False
# Streamlit app
def main():
st.title("🌱 AI-Powered Plant Care Guide")
# Section 1: Search for plant care information
st.header("Search for Plant Care Information")
user_input = st.text_input("Enter the name of a plant", "")
if st.button("Search"):
if user_input.strip():
with st.spinner("Fetching plant data..."):
plant_info = fetch_plant_data(user_input)
if plant_info:
st.success(f"Found information for {plant_info['name']}!")
# Refine or generate AI-based watering instructions
with st.spinner("Generating detailed watering instructions..."):
plant_info["watering"] = refine_watering_instructions(user_input, basic_instructions=plant_info["watering"])
st.subheader(f"Care Instructions for {plant_info['name']}")
st.write(f"**Description:** {plant_info['description']}")
st.write(f"**Sun Requirements:** {plant_info['sun_requirements']}")
st.write(f"**Growth Rate:** {plant_info['growth_rate']}")
st.write(f"**Spacing:** {plant_info['spacing']}")
st.write(f"**Sowing Method:** {plant_info['sowing_method']}")
st.write(f"**Watering Instructions:** {plant_info['watering']}")
# Display the image if the URL is valid
if plant_info["image_url"] and is_valid_image_url(plant_info["image_url"]):
st.image(plant_info["image_url"], caption=plant_info["name"], width=300)
else:
st.warning("No valid image available for this plant.")
else:
st.warning("No information found for the specified plant. Please try another name.")
else:
st.warning("Please enter a plant name to search.")
if __name__ == "__main__":
main()