Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -14,8 +14,12 @@ from langchain.chains import LLMChain
|
|
14 |
# Set persistent storage path
|
15 |
PERSISTENT_DIR = "vector_db"
|
16 |
|
|
|
|
|
|
|
|
|
|
|
17 |
def initialize_vector_db():
|
18 |
-
# Check if vector database already exists in persistent storage
|
19 |
if os.path.exists(PERSISTENT_DIR) and os.listdir(PERSISTENT_DIR):
|
20 |
embeddings = HuggingFaceEmbeddings()
|
21 |
vector_db = Chroma(persist_directory=PERSISTENT_DIR, embedding_function=embeddings)
|
@@ -38,15 +42,10 @@ def initialize_vector_db():
|
|
38 |
texts = text_splitter.split_documents(documents)
|
39 |
|
40 |
embeddings = HuggingFaceEmbeddings()
|
41 |
-
vector_db = Chroma.from_documents(
|
42 |
-
texts,
|
43 |
-
embeddings,
|
44 |
-
persist_directory=PERSISTENT_DIR
|
45 |
-
)
|
46 |
vector_db.persist()
|
47 |
return documents, vector_db
|
48 |
|
49 |
-
# System instructions for the LLM
|
50 |
system_prompt = """You are an expert organic farming consultant with specialization in Agro-Homeopathy. When providing suggestions and remedies:
|
51 |
1. Always specify medicine potency as 6c unless the uploaded text mentions some other value explicitly
|
52 |
3. Provide comprehensive diagnosis and treatment advice along with organic farming best practices applicable in the given context
|
@@ -55,48 +54,43 @@ system_prompt = """You are an expert organic farming consultant with specializat
|
|
55 |
|
56 |
api_key1 = os.getenv("api_key")
|
57 |
|
58 |
-
|
59 |
-
st.set_page_config(page_title="Dr. Radha: The Agro-Homeopath", page_icon="🚀", layout="wide")
|
60 |
|
61 |
-
#
|
62 |
-
st.
|
63 |
-
<style>
|
64 |
-
/* Set background color for entire app */
|
65 |
-
.stApp {
|
66 |
-
background-color: #1B4D3E !important;
|
67 |
-
color: white !important;
|
68 |
-
}
|
69 |
-
|
70 |
-
/* Style input fields */
|
71 |
-
.stTextInput>div>div>input {
|
72 |
-
color: black !important;
|
73 |
-
background-color: rgba(255,255,255,0.1) !important;
|
74 |
-
}
|
75 |
-
|
76 |
-
/* Style buttons */
|
77 |
-
.stButton>button {
|
78 |
-
color: black !important;
|
79 |
-
background-color: yellow !important;
|
80 |
-
}
|
81 |
-
|
82 |
-
}
|
83 |
-
</style>
|
84 |
-
""", unsafe_allow_html=True)
|
85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
st.markdown("""
|
87 |
<style>
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
</style>
|
94 |
""", unsafe_allow_html=True)
|
95 |
|
96 |
-
st.title("🌿 Dr. Radha: AI-Powered Organic Farming Consultant")
|
97 |
-
st.subheader("Specializing in Agro-Homeopathy | Free Consultation")
|
98 |
-
|
99 |
-
# Add information request message
|
100 |
st.markdown("""
|
101 |
Please provide complete details about the issue, including:
|
102 |
- Detailed description of plant problem
|
@@ -106,7 +100,6 @@ Please provide complete details about the issue, including:
|
|
106 |
human_image = "human.png"
|
107 |
robot_image = "bot.jpg"
|
108 |
|
109 |
-
# Set up Groq API with temperature 0.7
|
110 |
llm = ChatGroq(
|
111 |
api_key=api_key1,
|
112 |
max_tokens=None,
|
@@ -117,8 +110,6 @@ llm = ChatGroq(
|
|
117 |
)
|
118 |
|
119 |
embeddings = HuggingFaceEmbeddings()
|
120 |
-
end_time = time.time()
|
121 |
-
print(f"Setting up Groq LLM & Embeddings took {end_time - start_time:.4f} seconds")
|
122 |
|
123 |
# Initialize session state
|
124 |
if "documents" not in st.session_state:
|
@@ -127,8 +118,7 @@ if "vector_db" not in st.session_state:
|
|
127 |
st.session_state["vector_db"] = None
|
128 |
if "query" not in st.session_state:
|
129 |
st.session_state["query"] = ""
|
130 |
-
|
131 |
-
start_time = time.time()
|
132 |
if st.session_state["documents"] is None or st.session_state["vector_db"] is None:
|
133 |
with st.spinner("Loading data..."):
|
134 |
documents, vector_db = initialize_vector_db()
|
@@ -138,12 +128,12 @@ else:
|
|
138 |
documents = st.session_state["documents"]
|
139 |
vector_db = st.session_state["vector_db"]
|
140 |
|
141 |
-
end_time = time.time()
|
142 |
-
print(f"Loading and processing PDFs & vector database took {end_time - start_time:.4f} seconds")
|
143 |
-
|
144 |
-
start_time = time.time()
|
145 |
retriever = vector_db.as_retriever()
|
146 |
|
|
|
|
|
|
|
|
|
147 |
prompt_template = """As an expert organic farming consultant with specialization in Agro-Homeopathy, analyze the following context and question to provide a clear, structured response.
|
148 |
|
149 |
Context: {context}
|
@@ -181,20 +171,7 @@ Remember to maintain a professional, clear tone and ensure all medicine recommen
|
|
181 |
|
182 |
Answer:"""
|
183 |
|
184 |
-
# Create the QA chain with correct variables
|
185 |
-
qa = RetrievalQA.from_chain_type(
|
186 |
-
llm=llm,
|
187 |
-
chain_type="stuff",
|
188 |
-
retriever=retriever,
|
189 |
-
chain_type_kwargs={
|
190 |
-
"prompt": PromptTemplate(
|
191 |
-
template=prompt_template,
|
192 |
-
input_variables=["context", "question"]
|
193 |
-
)
|
194 |
-
}
|
195 |
-
)
|
196 |
|
197 |
-
# Create a separate LLMChain for fallback
|
198 |
fallback_template = """As an expert organic farming consultant with specialization in Agro-Homeopathy, analyze the following context and question to provide a clear, structured response.
|
199 |
|
200 |
Question: {question}
|
@@ -230,33 +207,31 @@ Maintain a professional tone and ensure all medicine recommendations include spe
|
|
230 |
|
231 |
Answer:"""
|
232 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
233 |
fallback_prompt = PromptTemplate(template=fallback_template, input_variables=["question"])
|
234 |
fallback_chain = LLMChain(llm=llm, prompt=fallback_prompt)
|
235 |
|
236 |
chat_container = st.container()
|
237 |
|
238 |
-
st.markdown("""
|
239 |
-
<style>
|
240 |
-
.stButton>button {
|
241 |
-
color: black !important;
|
242 |
-
background-color: yellow !important;
|
243 |
-
}
|
244 |
-
</style>
|
245 |
-
""", unsafe_allow_html=True)
|
246 |
-
|
247 |
with st.form(key='query_form'):
|
248 |
query = st.text_input("Ask your question:", value="")
|
249 |
submit_button = st.form_submit_button(label='Submit')
|
250 |
|
251 |
-
end_time = time.time()
|
252 |
-
#print(f"Setting up retrieval chain took {end_time - start_time:.4f} seconds")
|
253 |
-
start_time = time.time()
|
254 |
-
|
255 |
if submit_button and query:
|
256 |
with st.spinner("Generating response..."):
|
257 |
result = qa({"query": query})
|
258 |
if result['result'].strip() == "":
|
259 |
-
# If no result from PDF, use fallback chain
|
260 |
fallback_result = fallback_chain.run(query)
|
261 |
response = fallback_result
|
262 |
else:
|
@@ -274,8 +249,4 @@ if submit_button and query:
|
|
274 |
st.markdown(f"{response}")
|
275 |
|
276 |
st.markdown("---")
|
277 |
-
|
278 |
st.session_state["query"] = ""
|
279 |
-
|
280 |
-
end_time = time.time()
|
281 |
-
print(f"Actual query took {end_time - start_time:.4f} seconds")
|
|
|
14 |
# Set persistent storage path
|
15 |
PERSISTENT_DIR = "vector_db"
|
16 |
|
17 |
+
# Define image paths
|
18 |
+
HEADER_IMAGE = "i1.jpg" # Organic farming landscape
|
19 |
+
SIDE_IMAGE = "i2.JPG" # Medicinal plants/herbs
|
20 |
+
FOOTER_IMAGE = "i3.JPG" # Sustainable farming practices
|
21 |
+
|
22 |
def initialize_vector_db():
|
|
|
23 |
if os.path.exists(PERSISTENT_DIR) and os.listdir(PERSISTENT_DIR):
|
24 |
embeddings = HuggingFaceEmbeddings()
|
25 |
vector_db = Chroma(persist_directory=PERSISTENT_DIR, embedding_function=embeddings)
|
|
|
42 |
texts = text_splitter.split_documents(documents)
|
43 |
|
44 |
embeddings = HuggingFaceEmbeddings()
|
45 |
+
vector_db = Chroma.from_documents(texts, embeddings, persist_directory=PERSISTENT_DIR)
|
|
|
|
|
|
|
|
|
46 |
vector_db.persist()
|
47 |
return documents, vector_db
|
48 |
|
|
|
49 |
system_prompt = """You are an expert organic farming consultant with specialization in Agro-Homeopathy. When providing suggestions and remedies:
|
50 |
1. Always specify medicine potency as 6c unless the uploaded text mentions some other value explicitly
|
51 |
3. Provide comprehensive diagnosis and treatment advice along with organic farming best practices applicable in the given context
|
|
|
54 |
|
55 |
api_key1 = os.getenv("api_key")
|
56 |
|
57 |
+
st.set_page_config(page_title="Dr. Radha: The Agro-Homeopath", page_icon="🌿", layout="wide")
|
|
|
58 |
|
59 |
+
# Add header image
|
60 |
+
st.image(HEADER_IMAGE, use_column_width=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
+
# Create main layout columns
|
63 |
+
left_col, right_col = st.columns([3, 1])
|
64 |
+
|
65 |
+
with left_col:
|
66 |
+
st.title("🌿 Dr. Radha: AI-Powered Organic Farming Consultant")
|
67 |
+
st.subheader("Specializing in Agro-Homeopathy | Free Consultation")
|
68 |
+
|
69 |
+
with right_col:
|
70 |
+
st.image(SIDE_IMAGE, width=250, caption="Natural Healing Solutions")
|
71 |
+
|
72 |
+
# CSS styling
|
73 |
st.markdown("""
|
74 |
<style>
|
75 |
+
.stApp {
|
76 |
+
background-color: #1B4D3E !important;
|
77 |
+
color: white !important;
|
78 |
+
}
|
79 |
+
.stTextInput>div>div>input {
|
80 |
+
color: black !important;
|
81 |
+
background-color: rgba(255,255,255,0.1) !important;
|
82 |
+
}
|
83 |
+
.stButton>button {
|
84 |
+
color: black !important;
|
85 |
+
background-color: yellow !important;
|
86 |
+
}
|
87 |
+
.stImage {
|
88 |
+
border-radius: 10px;
|
89 |
+
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
|
90 |
+
}
|
91 |
</style>
|
92 |
""", unsafe_allow_html=True)
|
93 |
|
|
|
|
|
|
|
|
|
94 |
st.markdown("""
|
95 |
Please provide complete details about the issue, including:
|
96 |
- Detailed description of plant problem
|
|
|
100 |
human_image = "human.png"
|
101 |
robot_image = "bot.jpg"
|
102 |
|
|
|
103 |
llm = ChatGroq(
|
104 |
api_key=api_key1,
|
105 |
max_tokens=None,
|
|
|
110 |
)
|
111 |
|
112 |
embeddings = HuggingFaceEmbeddings()
|
|
|
|
|
113 |
|
114 |
# Initialize session state
|
115 |
if "documents" not in st.session_state:
|
|
|
118 |
st.session_state["vector_db"] = None
|
119 |
if "query" not in st.session_state:
|
120 |
st.session_state["query"] = ""
|
121 |
+
|
|
|
122 |
if st.session_state["documents"] is None or st.session_state["vector_db"] is None:
|
123 |
with st.spinner("Loading data..."):
|
124 |
documents, vector_db = initialize_vector_db()
|
|
|
128 |
documents = st.session_state["documents"]
|
129 |
vector_db = st.session_state["vector_db"]
|
130 |
|
|
|
|
|
|
|
|
|
131 |
retriever = vector_db.as_retriever()
|
132 |
|
133 |
+
# Add footer image before the form
|
134 |
+
st.image(FOOTER_IMAGE, use_column_width=True, caption="Sustainable Farming Practices")
|
135 |
+
|
136 |
+
# Rest of your prompt templates and chain setup remains the same
|
137 |
prompt_template = """As an expert organic farming consultant with specialization in Agro-Homeopathy, analyze the following context and question to provide a clear, structured response.
|
138 |
|
139 |
Context: {context}
|
|
|
171 |
|
172 |
Answer:"""
|
173 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
174 |
|
|
|
175 |
fallback_template = """As an expert organic farming consultant with specialization in Agro-Homeopathy, analyze the following context and question to provide a clear, structured response.
|
176 |
|
177 |
Question: {question}
|
|
|
207 |
|
208 |
Answer:"""
|
209 |
|
210 |
+
qa = RetrievalQA.from_chain_type(
|
211 |
+
llm=llm,
|
212 |
+
chain_type="stuff",
|
213 |
+
retriever=retriever,
|
214 |
+
chain_type_kwargs={
|
215 |
+
"prompt": PromptTemplate(
|
216 |
+
template=prompt_template,
|
217 |
+
input_variables=["context", "question"]
|
218 |
+
)
|
219 |
+
}
|
220 |
+
)
|
221 |
+
|
222 |
fallback_prompt = PromptTemplate(template=fallback_template, input_variables=["question"])
|
223 |
fallback_chain = LLMChain(llm=llm, prompt=fallback_prompt)
|
224 |
|
225 |
chat_container = st.container()
|
226 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
227 |
with st.form(key='query_form'):
|
228 |
query = st.text_input("Ask your question:", value="")
|
229 |
submit_button = st.form_submit_button(label='Submit')
|
230 |
|
|
|
|
|
|
|
|
|
231 |
if submit_button and query:
|
232 |
with st.spinner("Generating response..."):
|
233 |
result = qa({"query": query})
|
234 |
if result['result'].strip() == "":
|
|
|
235 |
fallback_result = fallback_chain.run(query)
|
236 |
response = fallback_result
|
237 |
else:
|
|
|
249 |
st.markdown(f"{response}")
|
250 |
|
251 |
st.markdown("---")
|
|
|
252 |
st.session_state["query"] = ""
|
|
|
|
|
|