import base64
from itertools import cycle
import time
import streamlit as st
from streamlit_carousel import carousel
import os
from dotenv import load_dotenv
import time
from langchain.vectorstores import Chroma
from langchain.embeddings import HuggingFaceEmbeddings
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
from langchain_groq import ChatGroq
from langchain.chains import RetrievalQA
from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.chains import LLMChain
# Set persistent storage path
PERSISTENT_DIR = "vector_db"
# Define image paths
HEADER_IMAGE = "i1.jpg" # Organic farming landscape
SIDE_IMAGE = "i2.JPG" # Medicinal plants/herbs
FOOTER_IMAGE = "i3.JPG" # Sustainable farming practices
images = [
dict(
title="Image 1",
text="",
img="i1.jpg"
),
dict(
title="Image 2",
text="",
img="i2.JPG"
),
dict(
title="Image 3",
text="",
img="i3.JPG"
),
dict(
title="Image 4",
text="",
img="i4.jpg"
),
dict(
title="Image 5",
text="",
img="i5.JPG"
)
]
carousel(items=images)
def initialize_vector_db():
if os.path.exists(PERSISTENT_DIR) and os.listdir(PERSISTENT_DIR):
embeddings = HuggingFaceEmbeddings()
vector_db = Chroma(persist_directory=PERSISTENT_DIR, embedding_function=embeddings)
return None, vector_db
base_dir = os.path.dirname(os.path.abspath(__file__))
pdf_files = [f for f in os.listdir(base_dir) if f.endswith('.pdf')]
loaders = [PyPDFLoader(os.path.join(base_dir, fn)) for fn in pdf_files]
documents = []
for loader in loaders:
documents.extend(loader.load())
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200,
length_function=len,
separators=["\n\n", "\n", " ", ""]
)
texts = text_splitter.split_documents(documents)
embeddings = HuggingFaceEmbeddings()
vector_db = Chroma.from_documents(texts, embeddings, persist_directory=PERSISTENT_DIR)
vector_db.persist()
return documents, vector_db
system_prompt = """You are an expert organic farming consultant with specialization in Agro-Homeopathy. When providing suggestions and remedies:
1. Always specify medicine potency as 6c unless the uploaded text mentions some other value explicitly
3. Provide comprehensive diagnosis and treatment advice along with organic farming best practices applicable in the given context
4. Base recommendations on homeopathic and organic farming principles
"""
api_key1 = os.getenv("api_key")
st.set_page_config(page_title="Dr. Radha: The Agro-Homeopath", page_icon="🌿", layout="wide")
# Add custom CSS for image styling
st.markdown("""
""", unsafe_allow_html=True)
st.title("🌿 Dr. Radha: AI-Powered Organic Farming Consultant")
st.subheader("Specializing in Agro-Homeopathy | Free Consultation")
st.markdown("""
Please provide complete details about the issue, including:
- Detailed description of plant problem
- Current location, temperature & weather conditions
""")
human_image = "human.png"
robot_image = "bot.jpg"
llm = ChatGroq(
api_key=api_key1,
max_tokens=None,
timeout=None,
max_retries=2,
temperature=0.7,
model="llama-3.1-70b-versatile"
)
embeddings = HuggingFaceEmbeddings()
# Initialize session state
if "documents" not in st.session_state:
st.session_state["documents"] = None
if "vector_db" not in st.session_state:
st.session_state["vector_db"] = None
if "query" not in st.session_state:
st.session_state["query"] = ""
if st.session_state["documents"] is None or st.session_state["vector_db"] is None:
with st.spinner("Loading data..."):
documents, vector_db = initialize_vector_db()
st.session_state["documents"] = documents
st.session_state["vector_db"] = vector_db
else:
documents = st.session_state["documents"]
vector_db = st.session_state["vector_db"]
retriever = vector_db.as_retriever()
# Add footer image before the form
#st.image(FOOTER_IMAGE, use_container_width=True)
# Rest of your prompt templates and chain setup remains the same
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.
Context: {context}
Question: {question}
Provide your response in the following format:
Analysis: Analyze the described plant condition
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.
Instructions for Use:
Small Plots or Gardens: Make sure your dispensing equipment is not contaminated with
other chemicals or fertilisers as these may antidote the energetic effects of the treatment—
rinse well with hot water before use if necessary. Add one pill to each 200 ml of water, shake
vigorously, and then spray or water your plants. Avoid using other chemicals or fertilisers for
10 days following treatment so that the energetic effects of the treatment are not antidoted.
(One vial of 100 pills makes 20 litres. Plants remain insect or disease free for up to 3 months
following one treatment.)
Large Plots or Farms: Add the remedy to water and apply with the dispensing device of
your choice: watering can, backpack sprayer, boomspray, reticulation systems (add to tanks
or pumps). Make sure your dispensing equipment is not contaminated with other chemicals
or fertilisers as these may antidote the energetic effects of the treatment—rinse with hot
water or steam clean before use if necessary. Avoid using other chemicals or fertilisers for
10 days following treatment.
Dosage rates are approximate and may vary according to different circumstances and
experiences. Suggested doses are:
10 pills or 10ml/10 litre on small areas,
500 pills or 125ml/500l per hectare,
1000 pills or 250ml/500l per hectare,
2500 pills or 500ml/500l per hectare,
Add pills or liquid to your water and mix (with a stick if necessary for large containers).
Recommendations: Provide couple of key pertinent recommendations based on the query
Remember to maintain a professional, clear tone and ensure all medicine recommendations include specific potency.
Answer:"""
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.
Question: {question}
Format your response as follows:
Analysis: Analyze the described plant condition
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.
Instructions for Use:
Small Plots or Gardens: Make sure your dispensing equipment is not contaminated with
other chemicals or fertilisers as these may antidote the energetic effects of the treatment—
rinse well with hot water before use if necessary. Add one pill to each 200 ml of water, shake
vigorously, and then spray or water your plants. Avoid using other chemicals or fertilisers for
10 days following treatment so that the energetic effects of the treatment are not antidoted.
(One vial of 100 pills makes 20 litres. Plants remain insect or disease free for up to 3 months
following one treatment.)
Large Plots or Farms: Add the remedy to water and apply with the dispensing device of
your choice: watering can, backpack sprayer, boomspray, reticulation systems (add to tanks
or pumps). Make sure your dispensing equipment is not contaminated with other chemicals
or fertilisers as these may antidote the energetic effects of the treatment—rinse with hot
water or steam clean before use if necessary. Avoid using other chemicals or fertilisers for
10 days following treatment.
Dosage rates are approximate and may vary according to different circumstances and
experiences. Suggested doses are:
10 pills or 10ml/10 litre on small areas
500 pills or 125ml/500l per hectare
1000 pills or 250ml/500l per hectare
2500 pills or 500ml/500l per hectare
Add pills or liquid to your water and mix (with a stick if necessary for large containers).
Recommendations: Provide couple of key pertinent recommendations based on the query
Maintain a professional tone and ensure all medicine recommendations include specific potency.
Answer:"""
qa = RetrievalQA.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=retriever,
chain_type_kwargs={
"prompt": PromptTemplate(
template=prompt_template,
input_variables=["context", "question"]
)
}
)
fallback_prompt = PromptTemplate(template=fallback_template, input_variables=["question"])
fallback_chain = LLMChain(llm=llm, prompt=fallback_prompt)
chat_container = st.container()
st.markdown("""
""", unsafe_allow_html=True)
with st.form(key='query_form'):
query = st.text_input("Ask your question:", value="")
submit_button = st.form_submit_button(label='Submit')
if submit_button and query:
with st.spinner("Generating response..."):
result = qa({"query": query})
if result['result'].strip() == "":
fallback_result = fallback_chain.run(query)
response = fallback_result
else:
response = result['result']
col1, col2 = st.columns([1, 10])
with col1:
st.image(human_image, width=80)
with col2:
st.markdown(f"{query}")
col1, col2 = st.columns([1, 10])
with col1:
st.image(robot_image, width=80)
with col2:
st.markdown(f"{response}")
st.markdown("---")
st.session_state["query"] = ""
# Add this before the form section in your main code
st.markdown("---")
# Define your image paths
carousel_images = [
"i1.jpg",
"i2.JPG",
"i3.JPG",
]
# Add CSS for carousel styling
st.markdown("""
""", unsafe_allow_html=True)
# def create_auto_rotating_carousel(image_paths, interval=3):
# if 'carousel_time' not in st.session_state:
# st.session_state.carousel_time = time.time()
# st.session_state.carousel_idx = 0
# # Check if interval has passed
# current_time = time.time()
# if current_time - st.session_state.carousel_time > interval:
# st.session_state.carousel_idx = (st.session_state.carousel_idx + 1) % len(image_paths)
# st.session_state.carousel_time = current_time
# # Create three columns
# cols = st.columns(3)
# # Calculate indices for three images
# num_images = len(image_paths)
# indices = [
# (st.session_state.carousel_idx + i) % num_images
# for i in range(3)
# ]
# # Display images
# for idx, col in enumerate(cols):
# with col:
# st.image(
# image_paths[indices[idx]],
# use_container_width=True,
# caption=f"Image {indices[idx]+1}"
# )
# # Replace the previous carousel call with:
# create_auto_rotating_carousel(carousel_images, interval=3)