Spaces:
Runtime error
Runtime error
File size: 5,167 Bytes
cb845aa 0003d01 a4fad62 0003d01 cb845aa 0003d01 39c0413 0003d01 cb845aa 0003d01 10a3bb1 0003d01 cb845aa 0003d01 10a3bb1 cb845aa d3811ea 10a3bb1 d3811ea 0003d01 cb845aa 84b7dfc cb845aa 39c0413 10a3bb1 cb845aa 10a3bb1 0003d01 10a3bb1 cb845aa 10a3bb1 4c62b79 10a3bb1 84b7dfc 0003d01 84b7dfc d3811ea 0003d01 d3811ea 0003d01 3858c90 cb845aa 0003d01 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
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() |