File size: 11,145 Bytes
49e08ff
1a0d7ed
982a413
4603e82
 
 
 
82f5b03
39e1cdd
0106da9
f93d920
c1dd32f
ee22d8a
82f5b03
f8ef4e3
4603e82
 
44041d6
4603e82
 
49e08ff
 
 
ca3edd3
af9a9df
 
e011e39
49e08ff
0106da9
06154c7
4603e82
988c7cc
4603e82
 
72f8142
c1dd32f
 
 
 
 
 
4603e82
d7ccc91
 
79a0805
 
 
132bff0
d7ccc91
132bff0
79a0805
132bff0
79a0805
 
 
 
132bff0
49e08ff
79a0805
 
 
 
 
e011e39
4603e82
598dbf3
d7ccc91
 
 
 
 
1bd6aca
d7ccc91
 
 
 
 
 
 
1bd6aca
d7ccc91
 
 
 
 
 
 
 
 
 
 
49e08ff
d7ccc91
4603e82
49e08ff
4603e82
 
 
1cf1e40
 
 
 
aea32c9
 
1cf1e40
 
 
 
 
 
 
 
 
 
8baa78f
 
b35bb2a
c744b6e
8baa78f
1cf1e40
 
 
ee22d8a
847d253
 
 
 
e28bfe5
 
847d253
 
 
 
 
 
 
 
 
1cf1e40
 
22f4c37
 
0082bf7
22f4c37
847d253
22f4c37
 
1cf1e40
 
24eb598
 
aea32c9
4870971
8baa78f
 
 
 
39e1cdd
8baa78f
 
 
 
 
39e1cdd
8baa78f
 
 
 
 
 
 
 
 
39e1cdd
 
 
 
 
 
8baa78f
1cf1e40
 
 
 
8baa78f
 
 
 
aea32c9
 
 
 
 
 
 
 
a45eecb
aea32c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8baa78f
4603e82
 
0e81608
 
 
 
 
 
 
 
 
 
 
 
49e08ff
0e81608
 
 
49e08ff
 
 
66dfad9
 
8baa78f
a45eecb
8baa78f
3e35f54
8baa78f
 
1cf1e40
1bd6aca
49e08ff
66dfad9
 
 
 
 
 
 
 
edea827
b51478b
 
1cf1e40
24eb598
 
1cf1e40
cb6bdf2
 
 
 
 
db02afa
aea32c9
 
 
 
49e08ff
cb6bdf2
49e08ff
8baa78f
4603e82
0e81608
4603e82
 
f93d920
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
from flask import Flask, request, make_response
import os
from datetime import datetime
import logging
from dotenv import load_dotenv
from heyoo import WhatsApp
import assemblyai as aai
import openai
from utility import generateResponse, parse_multiple_transactions, create_inventory, create_sale, read_datalake, delete_transaction
from google.cloud import firestore
import ast
import base64
import requests


# load env data
load_dotenv()

# messenger object
messenger = WhatsApp(
    os.environ["whatsapp_token"],
    phone_number_id=os.environ["phone_number_id"]
)

aai.settings.api_key = os.environ["aai_key"]
transcriber = aai.Transcriber()

# Authenticate to Firestore with the JSON account key
db = firestore.Client.from_service_account_json("firestore-key.json")

app = Flask(__name__)

VERIFY_TOKEN = "30cca545-3838-48b2-80a7-9e43b1ae8ce4"


img_ID = "344744a88ad1098"
img_secret = "3c542a40c215327045d7155bddfd8b8bc84aebbf"

url = "https://api.imgur.com/3/image"
headers = {"Authorization": f"Client-ID {img_ID}"}


# Interactive button
def messenger_button(recipient_phone, message, header='Transaction Confirmation', footer='', btn_name='Confirm Details'):
    messenger.send_button(
        recipient_id=recipient_phone,
        button={
            "header": f"{header}",
            "body": f"{message}",
            "footer": f"{footer}",
            "action": {
                "button": f"{btn_name}",
                "sections": [
                    {
                        "title": "iBank",
                        "rows": [
                            {"id": "confirm", "title": "Record Transaction", "description": ""},
                            {"id": "cancel", "title": "Cancel Transaction", "description": ""},
                        ],
                    }
                ],
            },
        },
    )

def messenger_reply_button(recipient_phone, message, header_message = "*Please confirm the details below before we proceed*:\n\n"):
    messenger.send_reply_button(
        recipient_id=f"{recipient_phone}",
        button={
            "type": "button",
            "body": {
                "text": f"{header_message} {message}"
            },
            "action": {
                "buttons": [
                    {
                        "type": "reply",
                        "reply": {
                            "id": "confirm",
                            "title": "Confirm"
                        }
                    },
                    {
                        "type": "reply",
                        "reply": {
                            "id": "cancel",
                            "title": "Cancel"
                        }
                    }
                ]
            }
        },
    )

def respond(query_str: str):
    response = "hello, I don't have a brain yet"
    return response

def persist_temporary_transaction(transactions, mobile):
    """
    Persists the transaction data temporarily in Firestore.
    """
    # intent = transactions[0]['intent'].lower()
    temp_ref = db.collection("users").document(mobile).collection("temp_transactions").document('pending-user-action')
    data = {
        "transactions": transactions,
        "status": "pending",
        "created_at": datetime.now().isoformat()
    }
    temp_ref.set(data)
    return True
    

def process_user_msg(message, mobile):
    response = str(generateResponse(message))
    parsed_trans_data = parse_multiple_transactions(response)
    # messenger.send_message(f"{response} \n\n {parsed_trans_data}", mobile)
    
    logging.info(f"\nAnswer: {response}\n")
    intent = parsed_trans_data[0]['intent'].lower()
    if intent == 'read':
        response2 = str(read_datalake(mobile, message))
        # Check if response is a string and represents a valid image path
        if isinstance(response2, str) and os.path.isfile(os.path.join(response2)):
            image_path = os.path.join(response2)
            print("My image path:", image_path)
            with open(image_path, "rb") as file:
                data = file.read()
                base64_data = base64.b64encode(data)

            # Upload image to Imgur and get URL
            response2 = requests.post(url, headers=headers, data={"image": base64_data})
            url1= response2.json()["data"]["link"]
            print(url1)
        
            messenger.send_image(image=url1, recipient_id=mobile)
        else:
            messenger.send_message(f"{response} \n\n {response2}", recipient_id=mobile)
    else: 
        # Persist transaction data temporarily for Create, Update, or Delete operations
        persist = persist_temporary_transaction(parsed_trans_data, mobile)
        if persist:
            # messenger.send_message(f"{response} \n\n {parsed_trans_data}", mobile)
            # Give user the chance to confirm/cancel transaction before processing other intents
            messenger_reply_button(mobile, f"{response} \n \n{parsed_trans_data}")
        else:
            messenger.send_message("Please try again!", mobile)

    return True 
    

def process_intent(parsed_trans_data, mobile):
    
    intent = parsed_trans_data[0]['intent'].lower()
    trans_type = parsed_trans_data[0]['transaction_type'].lower()
    
    if intent == 'create':
        if trans_type in ('purchase', 'purchases', 'inventory'):
            if create_inventory(mobile, parsed_trans_data):
                firestore_msg = "Transaction recorded successfully!"
            else:
                firestore_msg = "Sorry, could not record transaction!"
                
        elif trans_type in ('sale', 'sales'):
            if create_sale(mobile, parsed_trans_data):
                firestore_msg = "Transaction recorded successfully!"
            else:
                firestore_msg = "Sorry, could not record transaction!"
                
    elif intent == 'update':
        pass
            
    elif intent == 'delete':
        item = parsed_trans_data[0]['details']['item']
        item_deleted = delete_transaction(mobile, parsed_trans_data)
        if item_deleted:
            firestore_msg = f"You successfully deleted {item} from {trans_type}!"
        else:
            firestore_msg = f"Sorry, could not delete the {item} from {trans_type}!"
            
    # elif intent == 'read':
    #     response = str(read_datalake(mobile, message))
    #     parsed_trans_data = ""
    #     firestore_msg = response
                    
    else:
        firestore_msg = f'The detected intent, {intent}, is not currently supported!'

    # return firestore_msg, parsed_trans_data, response
    return firestore_msg

def handle_interactive_response(mobile, button_id):
    """
    Handles the user's button response (Confirm or Cancel).
    """
    doc_id = 'pending-user-action'
    temp_ref = db.collection("users").document(mobile).collection("temp_transactions").document(doc_id)
    transaction = temp_ref.get()

    if transaction.exists:
        transaction_data = transaction.to_dict()
        
        if button_id == "confirm":
            # Move to the appropriate collection
            transactions = transaction_data["transactions"]
            msg = process_intent(transactions, mobile)
            # Mark as confirmed or delete temporary record
            temp_ref.delete()
            messenger.send_message(f"{msg}", recipient_id = mobile)
        
        elif button_id == "cancel":
            # Delete the temporary record
            temp_ref.delete()
            messenger.send_message("Transaction has been canceled.", recipient_id = mobile)
        
        else:
            messenger.send_message("Invalid action. Please try again.", recipient_id = mobile)
    else:
        messenger.send_message("No pending transaction found.", recipient_id = mobile)



@app.route("/", methods=["GET", "POST"])
def hook():
    if request.method == "GET":
        if request.args.get("hub.verify_token") == VERIFY_TOKEN:
            logging.info("Verified webhook")
            response = make_response(request.args.get("hub.challenge"), 200)
            response.mimetype = "text/plain"
            return response
        logging.error("Webhook Verification failed")
        return "Invalid verification token"

    # get message update..
    data = request.get_json()
    changed_field = messenger.changed_field(data)

    if changed_field == "messages":
        new_message = messenger.get_mobile(data)
        if new_message:
            mobile = messenger.get_mobile(data)
            message_type = messenger.get_message_type(data)
            
            if message_type == "text":
                message = messenger.get_message(data)
                # Handle greetings
                if message.lower() in ("hi", "hello", "hola", "help", "how are you"):
                    response = "Hi there! My name is SmartLedger. How can I help you today?"
                    
                    messenger.send_message(message=f"{response}", recipient_id=mobile)
                else:
                    process_user_msg(message, mobile)
                    # messenger.send_message(message=f"User message processed!", recipient_id=mobile)

            elif message_type == "audio":
                audio = messenger.get_audio(data)
                audio_id, mime_type = audio["id"], audio["mime_type"]
                audio_url = messenger.query_media_url(audio_id)
                audio_filename = messenger.download_media(audio_url, mime_type)
                transcript = transcriber.transcribe(audio_filename)
                print(audio_filename)
                print(transcript.text)
                transcribed_message = transcript.text
            
                # logging.info(f"\nAudio: {audio}\n")
                process_user_msg(transcribed_message, mobile)
                # firestore_msg1, parsed_trans_data1, response1 = process_user_msg(transcribed_message, mobile)
                # messenger.send_message(message=f"Raw Response: {response1}, \n \n Parsed Response: {parsed_trans_data1}, \n \n Final Response: {firestore_msg1}", recipient_id=mobile)
                
            elif message_type == "interactive":
                message_response = messenger.get_interactive_response(data)
                interactive_type = message_response.get("type")
                message_id = message_response[interactive_type]["id"]
                message_text = message_response[interactive_type]["title"]
                logging.info(f"Interactive Message: {interactive_type} {message_id}: {message_text}")
                # messenger.send_message(message = f"Interactive type: {interactive_type}\n Message ID: {message_id} \n Message body: {message_body}", recipient_id=mobile)

                # Handle either create, update, or delete operation based on user action 
                handle_interactive_response(mobile, message_id)
            else:
                messenger.send_message(message=f"Please send me text or audio messages", recipient_id=mobile)

            

    return "ok"

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=7860)