Spaces:
Sleeping
Sleeping
File size: 5,741 Bytes
940c98a 5dff670 6f3d059 db22a62 979aaae db22a62 f4738b1 940c98a 5dff670 dd42eb1 8c242c9 ea99c1e 5dff670 db22a62 5dff670 8c242c9 940c98a db22a62 8c242c9 db22a62 558f5d1 9a053ad 052e52f 558f5d1 b72fe34 558f5d1 a8f0234 5dff670 f76692c 4749d72 f76692c a6765a2 9a053ad a1c7c07 ca95c4e 9a053ad bc82e06 8d025bc bc82e06 37364bc d6bcd10 bc82e06 8d025bc 37364bc 949f071 a2da878 949f071 1d239e0 5dff670 b410aca 5dff670 dfe1176 a37f551 5dff670 9bdc6ad 5dff670 ab84141 b410aca ec0595a 558f5d1 979aaae 558f5d1 c36a14b fa7d405 5dff670 979aaae 5dff670 979aaae 0c84d9c 979aaae d3d3acb c316d7b d3d3acb 05b09c6 d3890e4 4749d72 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
import os
from mistralai import Mistral
import requests
from requests.auth import HTTPBasicAuth
app = Flask(__name__)
account_sid = 'AC7f8c344c6593572a0c925ab4c1b66cc6'
auth_token ='01a62fe8d92f27552632527b6513bd4a'
client= Client(account_sid, auth_token)
from_whatsapp_number = 'whatsapp:+14155238886'
PROMPT_TEMPLATE = """
Answer the question based only on the following context:
{context}
---
Answer the question based on the above context: {question}
"""
model = "mistral-large-latest"
api_key='xQ2Zhfsp4cLar4lvBRDWZKljvp0Ej427'
client1 = Mistral(api_key=api_key)
def generate_response(query,chat_history):
chat_response = client1.chat.complete(
model= model,
messages = [
{
"role": "user",
"content": f"{query}? provide response within 2 sentence",
},
]
)
return chat_response.choices[0].message.content
@app.route('/whatsapp', methods=['POST'])
def whatsapp_webhook():
global bookdata
incoming_msg = request.values.get('Body', '').lower()
sender = request.values.get('From')
num_media = int(request.values.get('NumMedia', 0))
chat_history = 0
if num_media > 0:
media_url = request.values.get('MediaUrl0')
content_type = request.values.get('MediaContentType0')
if content_type.startswith('image/'):
# Handle image processing (disease/pest detection)
if 1==1:
filepath = convert_img(media_url, account_sid, auth_token)
bd=extract_text_from_image(filepath)
if bd!='':
bookdata=booktask(bd)
response_text="Your report for bookkeeping saved successfully."
elif 'none' not in filepath:
if predict_pest(filepath):
res=predict_pest(filepath)
if res=='x' or res=='X':
response_text ='APHIDS'
else:
response_text = predict_pest(filepath)
elif predict_disease(filepath):
res=predict_disease(filepath)
if res=='x' or res=='X':
response_text ='APHIDS'
else:
response_text = predict_disease(filepath)
else:
response_text = "Please upload other image with good quality."
else:
response_text = 'no data'
else:
# Handle PDF processing
filepath = download_and_save_as_txt(media_url, account_sid, auth_token)
response_text = 'PDF uploaded successfully'
elif ('weather' in incoming_msg.lower()) or ('climate' in incoming_msg.lower()) or (
'temperature' in incoming_msg.lower()):
weather = get_weather(incoming_msg.lower())
response_text = generate_response(incoming_msg + ' data is ' + weather+"convert to celcius.Make sure you return only answer.", chat_history)
elif 'bookkeeping' in incoming_msg:
response_text = '''1. General Information Farmer: John Doe | Farm: Green Valley Farms | Size: 50 acres Location: XYZ Village, State, Country | Period: Jan 1, 2024 - Dec 31, 2024 \n2. Income Crop Sales (Wheat): $2,000 | Livestock Sales (Cattle): $7,500 Subsidies: $1,000 | Equipment Rental: $500 \n3. Expenses & Assets Expenses: Seeds/Fertilizers: $1,000 | Labor: $2,000 | Maintenance: $300 | Fuel: $600 | Feed: $2,000 | Insurance: $800 | Utilities: $400 Assets: Tractor: $25,000 (Depreciation: $2,500) | Land: $100,000 (Market Value: $120,000) | Cattle: 50 head (Value: $75,000)'''
elif ('rates' in incoming_msg.lower()) or ('price' in incoming_msg.lower()) or (
'market' in incoming_msg.lower()) or ('rate' in incoming_msg.lower()) or ('prices' in incoming_msg.lower()):
rates = get_rates()
response_text = generate_response(incoming_msg + ' data is ' + rates, chat_history)
elif ('news' in incoming_msg.lower()) or ('information' in incoming_msg.lower()):
news = get_news()
response_text = generate_response('Summarise and provide the top 5 news in india as bullet points' + ' Data is ' + str(news), chat_history)
elif ('pdf' in incoming_msg.lower()):
response_text =respond_pdf(incoming_msg)
elif ('farm data' in incoming_msg.lower()):
response_text =' Click the link to monitor your farm.\n https://huggingface.co/spaces/Neurolingua/Smart-Agri-system'
else:
response_text = generate_response(incoming_msg, chat_history)
send_message(sender, response_text)
return '', 204
def process_and_query_pdf(filepath):
# Read and process the PDF
reader = PdfReader(filepath)
text = ''
for page in reader.pages:
text += page.extract_text()
if not text:
return "Sorry, the PDF content could not be extracted."
# Generate response based on extracted PDF content
response_text = generate_response(f"The PDF content is {text}", "")
return response_text
def send_message(recipient, message):
client.messages.create(
body=message,
from_=from_whatsapp_number,
to='whatsapp:+919342540825'
)
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 may get real-time information from me!!'
)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=7860,debug=1==1) |