ShellyMimo/agrigrow
0
1import pandas as pd
2from sentence_transformers import SentenceTransformer
3import faiss
4import os
5
6class AgricultureBot:
7 def __init__(self):
8 # Load agricultural data from CSV
9 if not os.path.exists('agriculture_data.csv'):
10 raise FileNotFoundError("The file 'agriculture_data.csv' was not found. Please make sure it exists in the directory.")
11
12 self.agriculture_data = pd.read_csv('agriculture_data.csv')
13
14 # Initialize SentenceTransformer model for encoding advice texts
15 self.model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
16 self.index = self.create_faiss_index()
17
18 def create_faiss_index(self):
19 # Convert advice texts to vectors
20 advice_vectors = self.model.encode(self.agriculture_data['advice_text'].tolist())
21 # Create a FAISS index
22 index = faiss.IndexFlatL2(advice_vectors.shape[1])
23 index.add(advice_vectors)
24 return index # Return the newly created index
25
26 def get_agricultural_advice(self, user_input):
27 # Convert user input to a vector
28 user_vector = self.model.encode([user_input])
29 # Search the FAISS index
30 _, advice_ids = self.index.search(user_vector, k=1)
31 # Retrieve the most relevant advice
32 most_relevant_advice = self.agriculture_data.iloc[advice_ids[0][0]]['advice_text']
33
34 # Additional processing to make the response more precise
35 precise_advice = self.process_advice(most_relevant_advice)
36
37 return precise_advice
38
39 def process_advice(self, advice):
40 # Example of processing to make the advice more precise
41 if "Rotate crops to prevent soil depletion and improve yield." in advice:
42 advice += "\nConsider integrating cover crops like legumes to enhance soil fertility."
43
44 return advice
45 