AgriChatbot / app.py
Neurolingua's picture
Update app.py
d3d3acb verified
raw
history blame
3.47 kB
from flask import Flask, request
import os
from langchain.vectorstores import Chroma
from langchain.document_loaders import PyPDFLoader
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
import requests
from twilio.rest import Client
# Flask app
app = Flask(__name__)
# ChromaDB path
CHROMA_PATH = '/code/chroma_db'
if not os.path.exists(CHROMA_PATH):
os.makedirs(CHROMA_PATH)
# Initialize ChromaDB
def initialize_chroma():
try:
embedding_function = HuggingFaceEmbeddings()
db = Chroma(persist_directory=CHROMA_PATH, embedding_function=embedding_function)
# Perform an initial operation to ensure the database is correctly initialized
db.similarity_search_with_score("test query", k=1)
print("Chroma initialized successfully.")
except Exception as e:
print(f"Error initializing Chroma: {e}")
initialize_chroma()
# Set AI71 API key
AI71_API_KEY = os.environ.get('AI71_API_KEY')
account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
client = Client(account_sid, auth_token)
from_whatsapp_number = 'whatsapp:+14155238886'
# Download file utility
def download_file(url, ext):
local_filename = f'/code/uploaded_file{ext}'
with requests.get(url, stream=True) as r:
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
return local_filename
# Process PDF and return text
def extract_text_from_pdf(pdf_filepath):
try:
document_loader = PyPDFLoader(pdf_filepath)
documents = document_loader.load()
text = "\n\n".join([doc.page_content for doc in documents])
return text
except Exception as e:
print(f"Error processing PDF: {e}")
return "Error extracting text from PDF."
# Flask route to handle WhatsApp webhook
@app.route('/whatsapp', methods=['POST'])
def whatsapp_webhook():
incoming_msg = request.values.get('Body', '').lower()
sender = request.values.get('From')
num_media = int(request.values.get('NumMedia', 0))
if num_media > 0:
media_url = request.values.get('MediaUrl0')
content_type = request.values.get('MediaContentType0')
if content_type == 'application/pdf':
filepath = download_file(media_url, ".pdf")
extracted_text = extract_text_from_pdf(filepath)
response_text = f"Here is the content of the PDF:\n\n{extracted_text}"
else:
response_text = "Unsupported file type. Please upload a PDF document."
else:
response_text = "Please upload a PDF document."
send_message(sender, response_text)
return '', 204
# Function to send message
def send_message(to, body):
try:
message = client.messages.create(
from_=from_whatsapp_number,
body=body,
to=to
)
print(f"Message sent with SID: {message.sid}")
except Exception as e:
print(f"Error sending message: {e}")
def send_initial_message(to_number):
send_message(
f'whatsapp:{to_number}',
'Welcome to the Agri AI Chatbot! How can I assist you today? You can send an image with "pest" or "disease" to classify it.'
)
if __name__ == "__main__":
send_initial_message('919080522395')
send_initial_message('916382792828')
app.run(host='0.0.0.0', port=7860)