-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
129 lines (101 loc) · 3.81 KB
/
app.py
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
import os
from twilio.rest import Client
from twilio.twiml.messaging_response import MessagingResponse
from flask import Flask, request
# from dotenv import load_dotenv
import openai
from weather import Weather
# Load the environment variables
# load_dotenv()
# Twilio variables
TWILIO_ACCOUNT_SID = os.environ["TWILIO_ACCOUNT_SID"]
TWILIO_AUTH_TOKEN = os.environ["TWILIO_AUTH_TOKEN"]
TWILIO_PHONE_NUMBER = os.environ["TWILIO_PHONE_NUMBER"]
TWILIO_MESSAGING_SERVICE_ID = os.environ["TWILIO_MESSAGING_SERVICE_ID"]
# Initilize the twilio client
client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
# Initialize the OpenAI API
openai.api_key = os.environ["OPENAI_API_KEY"]
# Sample data
sample_data = [{
"phone": "+12899716341",
"location": "goias",
"crop": "wheat",
"acres": "100",
"irrigation_type": "drip",
}]
# Initialize the flask app
app = Flask(__name__)
@app.route('/healthcheck')
def healthcheck():
return {"status": 200}
@app.route('/sms', methods=['POST'])
def sms():
message_body = request.form['Body']
from_number = request.form['From']
# Check if the user wants an update
if message_body.lower() == "update":
send_recommendations()
return "Recommendations sent!"
# Parse the message body to get the crop and acres
msg = message_body.split(", ")
if len(msg) != 4:
response = MessagingResponse()
response.message("Invalid message format. Please send the message in the following format: location, crop, acres, irrigation_type")
return str(response)
else:
location, crop, acres, irrigation_type = msg
# Store the data in a database
farmer = {}
# Process and store the crop data in the database
farmer["phone"] = from_number
farmer["location"] = location
farmer["crop"] = crop
farmer["acres"] = acres
farmer["irrigation_type"] = irrigation_type
# Add the data to the db
sample_data.append(farmer)
response = MessagingResponse()
response.message("Crop data received. You'll get irrigation recommendations soon.")
return str(response)
@app.route('/send-recommendations', methods=['POST'])
def send_recommendations():
for farmer in sample_data:
# Retrieve the data from the database for the farmers
monitor = Weather(farmer["location"])
required_irrigation = monitor.get_total_irrigation(farmer["crop"], farmer["acres"])
# Generate irrigation recommendations using OpenAI API
prompt = f"""
Generate irrigation recommendations for {farmer['crop']} on {farmer['acres']} acres.
Include that the total irrigation for the week is {required_irrigation} mm.
Make sure the recommendations are for {farmer['irrigation_type']} irrigation and specific
to the location of the farm, which is {farmer['location']}.
"""
response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens=50,
n=1,
stop=None,
temperature=0.7,
)
recommendation = response.choices[0].text.strip()
# Send SMS with the recommendations
client.messages.create(
body=recommendation,
from_=TWILIO_PHONE_NUMBER,
to=farmer["phone"],
)
return "Recommendations sent!"
@app.route('/stop-messaging', methods=['POST'])
def stop_messaging():
from_number = request.form['From']
# Remove farmer's number from the database
for farmer in sample_data:
if farmer["phone"] == from_number:
sample_data.remove(farmer)
response = MessagingResponse()
response.message("You have been unsubscribed from the irrigation recommendations.")
return str(response)
if __name__ == '__main__':
app.run(debug=True, port=os.getenv("PORT", default=5000))