euracle commited on
Commit
b2b61a4
·
verified ·
1 Parent(s): b9a4b24

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -198
app.py CHANGED
@@ -1,8 +1,4 @@
1
- import base64
2
- from itertools import cycle
3
- import time
4
  import streamlit as st
5
- from streamlit_carousel import carousel
6
  import os
7
  from dotenv import load_dotenv
8
  import time
@@ -15,124 +11,11 @@ from langchain.document_loaders import PyPDFLoader
15
  from langchain.text_splitter import RecursiveCharacterTextSplitter
16
  from langchain.chains import LLMChain
17
 
18
- st.set_page_config(page_title="Dr. Radha: The Agro-Homeopath", page_icon="🌿")
19
-
20
  # Set persistent storage path
21
  PERSISTENT_DIR = "vector_db"
22
 
23
-
24
- # Add custom CSS to maintain consistent image height
25
- st.markdown("""
26
- <style>
27
- .stApp {
28
- background-color: #1B4D3E !important;
29
- color: white !important;
30
- max-width: 100%;
31
- padding: 1rem;
32
- }
33
-
34
- /* Make carousel images equal size */
35
- .carousel {
36
- width: 100%;
37
- height: 400px;
38
- }
39
-
40
- .carousel img {
41
- width: 100%;
42
- height: 400px;
43
- object-fit: cover;
44
- object-position: center;
45
- }
46
-
47
- /* Style the form and button */
48
- .stButton > button {
49
- color: black !important;
50
- background-color: yellow !important;
51
- width: 100%;
52
- padding: 0.5rem;
53
- }
54
-
55
- /* Make text input and output full width */
56
- .stTextInput > div > div > input {
57
- color: black !important;
58
- background-color: rgba(255,255,255,0.1) !important;
59
- width: 100%;
60
- }
61
-
62
- /* Style the chat container */
63
- .chat-container {
64
- width: 100%;
65
- max-width: 1200px;
66
- margin: 0 auto;
67
- padding: 1rem;
68
- }
69
-
70
- /* Make title and headers full width */
71
- .stTitle, .stHeader {
72
- width: 100%;
73
- text-align: center;
74
- margin: 1rem 0;
75
- }
76
- </style>
77
- """, unsafe_allow_html=True)
78
-
79
- # Define image paths
80
- HEADER_IMAGE = "i1.jpg" # Organic farming landscape
81
- SIDE_IMAGE = "i2.JPG" # Medicinal plants/herbs
82
- FOOTER_IMAGE = "i3.JPG" # Sustainable farming practices
83
-
84
- # Define the images list before using the carousel
85
- images = [
86
- dict(
87
- title="",
88
- text="",
89
- img="i1.jpg",
90
- imgStyle={
91
- "width": "100%",
92
- "height": "400px",
93
- "objectFit": "cover",
94
- "objectPosition": "center"
95
- }
96
- ),
97
- dict(
98
- title="",
99
- text="",
100
- img="i2.JPG",
101
- imgStyle={
102
- "width": "100%",
103
- "height": "400px",
104
- "objectFit": "cover",
105
- "objectPosition": "center"
106
- }
107
- ),dict(
108
- title="",
109
- text="",
110
- img="i3.JPG",
111
- imgStyle={
112
- "width": "100%",
113
- "height": "400px",
114
- "objectFit": "cover",
115
- "objectPosition": "center"
116
- }
117
- ),
118
- dict(
119
- title="",
120
- text="",
121
- img="i5.JPG",
122
- imgStyle={
123
- "width": "100%",
124
- "height": "400px",
125
- "objectFit": "cover",
126
- "objectPosition": "center"
127
- }
128
- )
129
- ]
130
-
131
- carousel_container = st.container()
132
- with carousel_container:
133
- carousel(items=images)
134
-
135
  def initialize_vector_db():
 
136
  if os.path.exists(PERSISTENT_DIR) and os.listdir(PERSISTENT_DIR):
137
  embeddings = HuggingFaceEmbeddings()
138
  vector_db = Chroma(persist_directory=PERSISTENT_DIR, embedding_function=embeddings)
@@ -155,21 +38,65 @@ def initialize_vector_db():
155
  texts = text_splitter.split_documents(documents)
156
 
157
  embeddings = HuggingFaceEmbeddings()
158
- vector_db = Chroma.from_documents(texts, embeddings, persist_directory=PERSISTENT_DIR)
 
 
 
 
159
  vector_db.persist()
160
  return documents, vector_db
161
 
 
162
  system_prompt = """You are an expert organic farming consultant with specialization in Agro-Homeopathy. When providing suggestions and remedies:
163
  1. Always specify medicine potency as 6c unless the uploaded text mentions some other value explicitly
164
- 2. Provide comprehensive diagnosis and treatment advice along with organic farming best practices applicable in the given context
165
- 3. Base recommendations on homeopathic and organic farming principles
166
  """
167
 
168
  api_key1 = os.getenv("api_key")
169
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  st.title("🌿 Dr. Radha: AI-Powered Organic Farming Consultant")
171
  st.subheader("Specializing in Agro-Homeopathy | Free Consultation")
172
 
 
173
  st.markdown("""
174
  Please provide complete details about the issue, including:
175
  - Detailed description of plant problem
@@ -179,6 +106,7 @@ Please provide complete details about the issue, including:
179
  human_image = "human.png"
180
  robot_image = "bot.jpg"
181
 
 
182
  llm = ChatGroq(
183
  api_key=api_key1,
184
  max_tokens=None,
@@ -189,6 +117,8 @@ llm = ChatGroq(
189
  )
190
 
191
  embeddings = HuggingFaceEmbeddings()
 
 
192
 
193
  # Initialize session state
194
  if "documents" not in st.session_state:
@@ -197,7 +127,8 @@ if "vector_db" not in st.session_state:
197
  st.session_state["vector_db"] = None
198
  if "query" not in st.session_state:
199
  st.session_state["query"] = ""
200
-
 
201
  if st.session_state["documents"] is None or st.session_state["vector_db"] is None:
202
  with st.spinner("Loading data..."):
203
  documents, vector_db = initialize_vector_db()
@@ -207,18 +138,15 @@ else:
207
  documents = st.session_state["documents"]
208
  vector_db = st.session_state["vector_db"]
209
 
210
- retriever = vector_db.as_retriever()
 
211
 
212
- # Add footer image before the form
213
- #st.image(FOOTER_IMAGE, use_container_width=True)
214
 
215
- # Rest of your prompt templates and chain setup remains the same
216
  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.
217
-
218
  Context: {context}
219
-
220
  Question: {question}
221
-
222
  Provide your response in the following format:
223
  Analysis: Analyze the described plant condition
224
  Treatment: Recommend relevant organic farming principles and specific homeopathic medicine(s) with exact potency and repetition frequency. Suggest a maximum of 4 medicines in the order of relevance for any single problem.
@@ -243,18 +171,26 @@ experiences. Suggested doses are:
243
  1000 pills or 250ml/500l per hectare,
244
  2500 pills or 500ml/500l per hectare,
245
  Add pills or liquid to your water and mix (with a stick if necessary for large containers).
246
-
247
  Recommendations: Provide couple of key pertinent recommendations based on the query
248
-
249
  Remember to maintain a professional, clear tone and ensure all medicine recommendations include specific potency.
250
-
251
  Answer:"""
252
 
 
 
 
 
 
 
 
 
 
 
 
 
253
 
 
254
  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.
255
-
256
  Question: {question}
257
-
258
  Format your response as follows:
259
  Analysis: Analyze the described plant condition
260
  Treatment: Recommend relevant organic farming principles and specific homeopathic medicine(s) with exact potency and repetition frequency. Suggest a maximum of 4 medicines in the order of relevance for any single problem.
@@ -279,80 +215,55 @@ experiences. Suggested doses are:
279
  1000 pills or 250ml/500l per hectare
280
  2500 pills or 500ml/500l per hectare
281
  Add pills or liquid to your water and mix (with a stick if necessary for large containers).
282
-
283
  Recommendations: Provide couple of key pertinent recommendations based on the query
284
-
285
  Maintain a professional tone and ensure all medicine recommendations include specific potency.
286
-
287
  Answer:"""
288
 
289
- qa = RetrievalQA.from_chain_type(
290
- llm=llm,
291
- chain_type="stuff",
292
- retriever=retriever,
293
- chain_type_kwargs={
294
- "prompt": PromptTemplate(
295
- template=prompt_template,
296
- input_variables=["context", "question"]
297
- )
298
- }
299
- )
300
-
301
  fallback_prompt = PromptTemplate(template=fallback_template, input_variables=["question"])
302
  fallback_chain = LLMChain(llm=llm, prompt=fallback_prompt)
303
 
304
- st.markdown("""
305
- <style>
306
- .stTextArea label {
307
- color: white !important;
308
- font-size: 1rem !important;
309
- }
310
- .stButton button {
311
- color: black !important;
312
- }
313
- </style>
314
- """, unsafe_allow_html=True)
315
-
316
  chat_container = st.container()
 
317
  st.markdown("""
318
- <style>
319
- .stButton button {
320
- color: red !important;
321
- background-color: transparent;
322
- border: 1px solid red;
323
- }
324
- .stButton button:hover {
325
- color: red !important;
326
- border-color: red;
327
- }
328
- </style>
329
  """, unsafe_allow_html=True)
330
- with st.form(key='query_form', clear_on_submit=True):
331
- query = st.text_area("Ask your question:", height=100)
332
- col1, col2, col3 = st.columns([1,6,1])
333
- with col2:
334
- submit_button = st.form_submit_button(label='Submit')
335
 
 
 
 
 
 
 
 
336
 
337
  if submit_button and query:
338
- chat_container = st.container()
339
- with chat_container:
340
- with st.spinner("Generating response..."):
341
- result = qa({"query": query})
342
- if result['result'].strip() == "":
343
- response = fallback_chain.run(query)
344
- else:
345
- response = result['result']
346
-
347
- st.markdown("---")
348
- cols = st.columns([1,10])
349
- with cols[0]:
350
- st.image(human_image, width=80)
351
- with cols[1]:
352
- st.markdown(f"**Question:** {query}")
353
-
354
- cols = st.columns([1,10])
355
- with cols[0]:
356
- st.image(robot_image, width=80)
357
- with cols[1]:
358
- st.markdown(f"**Answer:** {response}")
 
 
 
 
 
 
 
 
1
  import streamlit as st
 
2
  import os
3
  from dotenv import load_dotenv
4
  import time
 
11
  from langchain.text_splitter import RecursiveCharacterTextSplitter
12
  from langchain.chains import LLMChain
13
 
 
 
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
  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
53
+ 4. Base recommendations on homeopathic and organic farming principles
54
  """
55
 
56
  api_key1 = os.getenv("api_key")
57
 
58
+ start_time = time.time()
59
+ st.set_page_config(page_title="Dr. Radha: The Agro-Homeopath", page_icon="🚀", layout="wide")
60
+
61
+ # CSS for dark green background and white text
62
+ st.markdown("""
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
+ #the-title {
89
+ text-align: center;
90
+ font-size: 24px;
91
+ color: white;
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
  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
  )
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
  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
  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
  Context: {context}
 
149
  Question: {question}
 
150
  Provide your response in the following format:
151
  Analysis: Analyze the described plant condition
152
  Treatment: Recommend relevant organic farming principles and specific homeopathic medicine(s) with exact potency and repetition frequency. Suggest a maximum of 4 medicines in the order of relevance for any single problem.
 
171
  1000 pills or 250ml/500l per hectare,
172
  2500 pills or 500ml/500l per hectare,
173
  Add pills or liquid to your water and mix (with a stick if necessary for large containers).
 
174
  Recommendations: Provide couple of key pertinent recommendations based on the query
 
175
  Remember to maintain a professional, clear tone and ensure all medicine recommendations include specific potency.
 
176
  Answer:"""
177
 
178
+ # Create the QA chain with correct variables
179
+ qa = RetrievalQA.from_chain_type(
180
+ llm=llm,
181
+ chain_type="stuff",
182
+ retriever=retriever,
183
+ chain_type_kwargs={
184
+ "prompt": PromptTemplate(
185
+ template=prompt_template,
186
+ input_variables=["context", "question"]
187
+ )
188
+ }
189
+ )
190
 
191
+ # Create a separate LLMChain for fallback
192
  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.
 
193
  Question: {question}
 
194
  Format your response as follows:
195
  Analysis: Analyze the described plant condition
196
  Treatment: Recommend relevant organic farming principles and specific homeopathic medicine(s) with exact potency and repetition frequency. Suggest a maximum of 4 medicines in the order of relevance for any single problem.
 
215
  1000 pills or 250ml/500l per hectare
216
  2500 pills or 500ml/500l per hectare
217
  Add pills or liquid to your water and mix (with a stick if necessary for large containers).
 
218
  Recommendations: Provide couple of key pertinent recommendations based on the query
 
219
  Maintain a professional tone and ensure all medicine recommendations include specific potency.
 
220
  Answer:"""
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
  st.markdown("""
228
+ <style>
229
+ .stButton>button {
230
+ color: black !important;
231
+ background-color: yellow !important;
232
+ }
233
+ </style>
 
 
 
 
 
234
  """, unsafe_allow_html=True)
 
 
 
 
 
235
 
236
+ with st.form(key='query_form'):
237
+ query = st.text_input("Ask your question:", value="")
238
+ submit_button = st.form_submit_button(label='Submit')
239
+
240
+ end_time = time.time()
241
+ #print(f"Setting up retrieval chain took {end_time - start_time:.4f} seconds")
242
+ start_time = time.time()
243
 
244
  if submit_button and query:
245
+ with st.spinner("Generating response..."):
246
+ result = qa({"query": query})
247
+ if result['result'].strip() == "":
248
+ # If no result from PDF, use fallback chain
249
+ fallback_result = fallback_chain.run(query)
250
+ response = fallback_result
251
+ else:
252
+ response = result['result']
253
+
254
+ col1, col2 = st.columns([1, 10])
255
+ with col1:
256
+ st.image(human_image, width=80)
257
+ with col2:
258
+ st.markdown(f"{query}")
259
+ col1, col2 = st.columns([1, 10])
260
+ with col1:
261
+ st.image(robot_image, width=80)
262
+ with col2:
263
+ st.markdown(f"{response}")
264
+
265
+ st.markdown("---")
266
+
267
+ st.session_state["query"] = ""
268
+
269
+ end_time = time.time()