AhmadRAZA23 commited on
Commit
10a3bb1
·
verified ·
1 Parent(s): 4c62b79

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -64
app.py CHANGED
@@ -1,11 +1,6 @@
1
  import streamlit as st
2
  import requests
3
  from transformers import pipeline
4
- import logging
5
-
6
- # Configure logging
7
- logging.basicConfig(level=logging.INFO)
8
- logger = logging.getLogger(__name__)
9
 
10
  # Cache the AI models to avoid reloading them on every interaction
11
  @st.cache_resource
@@ -13,7 +8,6 @@ def load_qa_model():
13
  try:
14
  return pipeline("question-answering", model="distilbert-base-cased-distilled-squad", framework="pt")
15
  except Exception as e:
16
- logger.error(f"Error loading QA model: {e}")
17
  st.error(f"Error loading QA model: {e}")
18
  return None
19
 
@@ -22,7 +16,6 @@ def load_text_generation_model():
22
  try:
23
  return pipeline("text-generation", model="gpt2", framework="pt")
24
  except Exception as e:
25
- logger.error(f"Error loading text generation model: {e}")
26
  st.error(f"Error loading text generation model: {e}")
27
  return None
28
 
@@ -39,25 +32,22 @@ def fetch_plant_data(plant_name):
39
  response.raise_for_status() # Raise an error for bad status codes
40
  data = response.json()
41
  if data.get("data"):
42
- # Return all results for the user to choose from
43
- return [
44
- {
45
- "name": plant["attributes"].get("name", plant_name),
46
- "description": plant["attributes"].get("description", "No description available."),
47
- "image_url": plant["attributes"].get("main_image_path", None),
48
- "sun_requirements": plant["attributes"].get("sun_requirements", "No information available."),
49
- "watering": plant["attributes"].get("watering", "No specific instructions available."),
50
- "growth_rate": plant["attributes"].get("growth_rate", "No information available."),
51
- "spacing": plant["attributes"].get("spacing", "No information available."),
52
- "sowing_method": plant["attributes"].get("sowing_method", "No information available."),
53
- }
54
- for plant in data["data"]
55
- ]
56
  else:
57
  st.warning(f"No data found for the plant: {plant_name}")
58
  return None
59
  except requests.exceptions.RequestException as e:
60
- logger.error(f"Error fetching plant data: {e}")
61
  st.error(f"Error fetching plant data: {e}")
62
  return None
63
 
@@ -66,14 +56,12 @@ def refine_watering_instructions(plant_name, basic_instructions=None):
66
  prompt = (
67
  f"Provide detailed watering instructions for the plant '{plant_name}'. "
68
  f"Base your response on the following basic instructions: '{basic_instructions}'. "
69
- "Include information on how often to water, the amount of water needed, and any seasonal variations. "
70
- "Also, mention signs of overwatering or underwatering."
71
  )
72
  try:
73
- result = text_generation_pipeline(prompt, max_length=250, num_return_sequences=1)
74
  return result[0]["generated_text"]
75
  except Exception as e:
76
- logger.error(f"Error generating watering instructions: {e}")
77
  st.error(f"Error generating watering instructions: {e}")
78
  return "Unable to generate watering instructions at this time."
79
 
@@ -91,11 +79,6 @@ def is_valid_image_url(url):
91
  def main():
92
  st.title("🌱 AI-Powered Plant Care Guide")
93
 
94
- # Sidebar for additional options
95
- with st.sidebar:
96
- st.header("Options")
97
- st.write("Here you can add additional settings or features in the future.")
98
-
99
  # Section 1: Search for plant care information
100
  st.header("Search for Plant Care Information")
101
  user_input = st.text_input("Enter the name of a plant", "")
@@ -103,50 +86,28 @@ def main():
103
  if st.button("Search"):
104
  if user_input.strip():
105
  with st.spinner("Fetching plant data..."):
106
- plant_data = fetch_plant_data(user_input)
107
 
108
- if plant_data:
109
- st.success(f"Found {len(plant_data)} result(s) for '{user_input}'!")
110
 
111
- # Let the user choose the correct plant if there are multiple results
112
- if len(plant_data) > 1:
113
- selected_plant = st.selectbox(
114
- "Multiple plants found. Select the correct one:",
115
- options=[plant["name"] for plant in plant_data],
116
- index=0,
117
- )
118
- plant_info = next(plant for plant in plant_data if plant["name"] == selected_plant)
119
- else:
120
- plant_info = plant_data[0]
121
-
122
  # Refine or generate AI-based watering instructions
123
  with st.spinner("Generating detailed watering instructions..."):
124
- plant_info["watering"] = refine_watering_instructions(plant_info["name"], basic_instructions=plant_info["watering"])
125
 
126
- # Display plant information
127
  st.subheader(f"Care Instructions for {plant_info['name']}")
128
- st.markdown(f"**Description:** {plant_info['description']}")
129
- st.markdown(f"**Sun Requirements:** {plant_info['sun_requirements']}")
130
- st.markdown(f"**Growth Rate:** {plant_info['growth_rate']}")
131
- st.markdown(f"**Spacing:** {plant_info['spacing']}")
132
- st.markdown(f"**Sowing Method:** {plant_info['sowing_method']}")
133
-
134
- # Expandable section for watering instructions
135
- with st.expander("View Detailed Watering Instructions"):
136
- st.markdown(f"{plant_info['watering']}")
137
 
138
- # Feedback mechanism for watering instructions
139
- st.write("Was this information helpful?")
140
- feedback = st.radio("Feedback", ["Yes", "No"], index=None)
141
- if feedback:
142
- st.write(f"Thank you for your feedback! You selected: {feedback}")
143
-
144
- # Display the image if the URL is valid, otherwise use a placeholder
145
  if plant_info["image_url"] and is_valid_image_url(plant_info["image_url"]):
146
  st.image(plant_info["image_url"], caption=plant_info["name"], width=300)
147
  else:
148
  st.warning("No valid image available for this plant.")
149
- st.image("https://via.placeholder.com/300x200.png?text=No+Image+Available", caption="Placeholder Image", width=300)
150
  else:
151
  st.warning("No information found for the specified plant. Please try another name.")
152
  else:
 
1
  import streamlit as st
2
  import requests
3
  from transformers import pipeline
 
 
 
 
 
4
 
5
  # Cache the AI models to avoid reloading them on every interaction
6
  @st.cache_resource
 
8
  try:
9
  return pipeline("question-answering", model="distilbert-base-cased-distilled-squad", framework="pt")
10
  except Exception as e:
 
11
  st.error(f"Error loading QA model: {e}")
12
  return None
13
 
 
16
  try:
17
  return pipeline("text-generation", model="gpt2", framework="pt")
18
  except Exception as e:
 
19
  st.error(f"Error loading text generation model: {e}")
20
  return None
21
 
 
32
  response.raise_for_status() # Raise an error for bad status codes
33
  data = response.json()
34
  if data.get("data"):
35
+ # Get the first result (most likely match)
36
+ plant_info = data["data"][0]["attributes"]
37
+ return {
38
+ "name": plant_info.get("name", plant_name),
39
+ "description": plant_info.get("description", "No description available."),
40
+ "image_url": plant_info.get("main_image_path", None),
41
+ "sun_requirements": plant_info.get("sun_requirements", "No information available."),
42
+ "watering": plant_info.get("watering", "No specific instructions available."),
43
+ "growth_rate": plant_info.get("growth_rate", "No information available."),
44
+ "spacing": plant_info.get("spacing", "No information available."),
45
+ "sowing_method": plant_info.get("sowing_method", "No information available."),
46
+ }
 
 
47
  else:
48
  st.warning(f"No data found for the plant: {plant_name}")
49
  return None
50
  except requests.exceptions.RequestException as e:
 
51
  st.error(f"Error fetching plant data: {e}")
52
  return None
53
 
 
56
  prompt = (
57
  f"Provide detailed watering instructions for the plant '{plant_name}'. "
58
  f"Base your response on the following basic instructions: '{basic_instructions}'. "
59
+ "Include information on how often to water, the amount of water needed, and any seasonal variations."
 
60
  )
61
  try:
62
+ result = text_generation_pipeline(prompt, max_length=200, num_return_sequences=1)
63
  return result[0]["generated_text"]
64
  except Exception as e:
 
65
  st.error(f"Error generating watering instructions: {e}")
66
  return "Unable to generate watering instructions at this time."
67
 
 
79
  def main():
80
  st.title("🌱 AI-Powered Plant Care Guide")
81
 
 
 
 
 
 
82
  # Section 1: Search for plant care information
83
  st.header("Search for Plant Care Information")
84
  user_input = st.text_input("Enter the name of a plant", "")
 
86
  if st.button("Search"):
87
  if user_input.strip():
88
  with st.spinner("Fetching plant data..."):
89
+ plant_info = fetch_plant_data(user_input)
90
 
91
+ if plant_info:
92
+ st.success(f"Found information for {plant_info['name']}!")
93
 
 
 
 
 
 
 
 
 
 
 
 
94
  # Refine or generate AI-based watering instructions
95
  with st.spinner("Generating detailed watering instructions..."):
96
+ plant_info["watering"] = refine_watering_instructions(user_input, basic_instructions=plant_info["watering"])
97
 
 
98
  st.subheader(f"Care Instructions for {plant_info['name']}")
99
+ st.write(f"**Description:** {plant_info['description']}")
100
+ st.write(f"**Sun Requirements:** {plant_info['sun_requirements']}")
101
+ st.write(f"**Growth Rate:** {plant_info['growth_rate']}")
102
+ st.write(f"**Spacing:** {plant_info['spacing']}")
103
+ st.write(f"**Sowing Method:** {plant_info['sowing_method']}")
104
+ st.write(f"**Watering Instructions:** {plant_info['watering']}")
 
 
 
105
 
106
+ # Display the image if the URL is valid
 
 
 
 
 
 
107
  if plant_info["image_url"] and is_valid_image_url(plant_info["image_url"]):
108
  st.image(plant_info["image_url"], caption=plant_info["name"], width=300)
109
  else:
110
  st.warning("No valid image available for this plant.")
 
111
  else:
112
  st.warning("No information found for the specified plant. Please try another name.")
113
  else: