Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import logging
|
3 |
+
import os
|
4 |
+
from langchain_community.vectorstores import FAISS
|
5 |
+
from langchain_community.document_loaders import CSVLoader
|
6 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
7 |
+
from langchain.prompts import PromptTemplate
|
8 |
+
from langchain.llms import HuggingFaceHub
|
9 |
+
import dotenv
|
10 |
+
import yaml
|
11 |
+
|
12 |
+
# Load environment variables from .env file
|
13 |
+
dotenv.load_dotenv()
|
14 |
+
|
15 |
+
# Load configuration from YAML
|
16 |
+
def load_config():
|
17 |
+
with open("yaml-editor-online.yaml", "r") as f:
|
18 |
+
config = yaml.safe_load(f)
|
19 |
+
return config
|
20 |
+
|
21 |
+
import os
|
22 |
+
# Securely fetch Hugging Face API key
|
23 |
+
hf_token = os.getenv('HUGGING') # Set this in your environment
|
24 |
+
|
25 |
+
# Load configuration
|
26 |
+
config = load_config()
|
27 |
+
logging.basicConfig(level=logging.INFO)
|
28 |
+
|
29 |
+
# Initialize Embeddings Model
|
30 |
+
instructor_embeddings = HuggingFaceEmbeddings(model_name=config["embedding_model"])
|
31 |
+
|
32 |
+
# Initialize FAISS Vector Database
|
33 |
+
def create_vector_db():
|
34 |
+
try:
|
35 |
+
loader = CSVLoader(file_path="plant_biodata.csv", source_column="Information about the disease")
|
36 |
+
data = loader.load()
|
37 |
+
|
38 |
+
# Create FAISS vector store
|
39 |
+
vectordb = FAISS.from_documents(documents=data, embedding=instructor_embeddings)
|
40 |
+
vectordb.save_local(config["vector_db_path"])
|
41 |
+
logging.info("Vector database successfully created and saved.")
|
42 |
+
except Exception as e:
|
43 |
+
logging.error("Error creating vector database:", exc_info=e)
|
44 |
+
|
45 |
+
# Load FAISS and retrieve relevant documents
|
46 |
+
import textwrap
|
47 |
+
|
48 |
+
def get_qa_chain(query):
|
49 |
+
try:
|
50 |
+
if not os.path.exists(config["vector_db_path"]):
|
51 |
+
logging.error(f"FAISS index path does not exist: {config['vector_db_path']}")
|
52 |
+
return "Error: No data found."
|
53 |
+
|
54 |
+
vectordb = FAISS.load_local(
|
55 |
+
config["vector_db_path"], instructor_embeddings, allow_dangerous_deserialization=True
|
56 |
+
)
|
57 |
+
retriever = vectordb.as_retriever(score_threshold=config["score_threshold"])
|
58 |
+
|
59 |
+
# Retrieve top-k relevant documents
|
60 |
+
relevant_docs = retriever.get_relevant_documents(query)[:3]
|
61 |
+
|
62 |
+
if not relevant_docs:
|
63 |
+
return "No relevant information found."
|
64 |
+
|
65 |
+
# Summarizing relevant documents
|
66 |
+
summarized_context = " ".join(doc.page_content for doc in relevant_docs)
|
67 |
+
summarized_context = textwrap.shorten(summarized_context, width=600, placeholder="...")
|
68 |
+
|
69 |
+
# Refined prompt enforcing bullet-point output
|
70 |
+
prompt_template = """Given the following context and a question, generate a structured answer in bullet points.
|
71 |
+
QUESTION: {query}
|
72 |
+
|
73 |
+
Ensure the response is simple, clear, and formatted as bullet points avoiding complex terms.
|
74 |
+
"""
|
75 |
+
prompt = PromptTemplate(input_variables=["query"], template=prompt_template).format(query=query)
|
76 |
+
|
77 |
+
# Call LLM
|
78 |
+
llm = HuggingFaceHub(
|
79 |
+
repo_id=config["model_name"],
|
80 |
+
model_kwargs={
|
81 |
+
"temperature": config["temperature"],
|
82 |
+
"max_length": 150,
|
83 |
+
"top_p": config["top_p"],
|
84 |
+
"top_k": config["top_k"]
|
85 |
+
},
|
86 |
+
huggingfacehub_api_token=hf_token
|
87 |
+
)
|
88 |
+
|
89 |
+
response = llm(prompt)
|
90 |
+
return response.strip()
|
91 |
+
|
92 |
+
except Exception as e:
|
93 |
+
logging.error("Error getting response:", exc_info=e)
|
94 |
+
return "Sorry, there was an error processing your request."
|
95 |
+
|
96 |
+
# Streamlit UI with Dark Mode
|
97 |
+
def main():
|
98 |
+
st.set_page_config(page_title="Crop Disease Assistant", page_icon="🌱", layout="centered")
|
99 |
+
|
100 |
+
# Custom CSS for Dark Mode
|
101 |
+
dark_theme_css = """
|
102 |
+
<style>
|
103 |
+
body {
|
104 |
+
background-color: #121212;
|
105 |
+
color: #ffffff;
|
106 |
+
}
|
107 |
+
.stTextInput, .stButton>button {
|
108 |
+
background-color: #1e1e1e;
|
109 |
+
color: white;
|
110 |
+
border-radius: 5px;
|
111 |
+
border: 1px solid #444;
|
112 |
+
}
|
113 |
+
.stMarkdown {
|
114 |
+
background-color: #1e1e1e;
|
115 |
+
padding: 10px;
|
116 |
+
border-radius: 5px;
|
117 |
+
}
|
118 |
+
</style>
|
119 |
+
"""
|
120 |
+
st.markdown(dark_theme_css, unsafe_allow_html=True)
|
121 |
+
|
122 |
+
st.title("🌾 Crop Disease Assistant")
|
123 |
+
st.write("Enter a crop disease-related question, and get simplified information.")
|
124 |
+
|
125 |
+
# Text input for the user query
|
126 |
+
query = st.text_input("Enter your query:")
|
127 |
+
|
128 |
+
# Display response on clicking the button
|
129 |
+
if st.button("Get Information"):
|
130 |
+
if query:
|
131 |
+
response = get_qa_chain(query)
|
132 |
+
st.markdown(f"**📌 Response:**\n\n{response}")
|
133 |
+
else:
|
134 |
+
st.write("Please enter a query to get a response.")
|
135 |
+
|
136 |
+
if __name__ == "__main__":
|
137 |
+
if not os.path.exists(config["vector_db_path"]):
|
138 |
+
logging.info(f"Vector database not found at {config['vector_db_path']}, creating it now.")
|
139 |
+
create_vector_db()
|
140 |
+
main()
|