rairo commited on
Commit
959ee63
·
verified ·
1 Parent(s): f7f47ee

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +16 -148
main.py CHANGED
@@ -6,21 +6,14 @@ from heyoo import WhatsApp
6
  import random
7
  import shutil
8
  from tempfile import NamedTemporaryFile
9
- import assemblyai as aai
10
- from pandasai.llm import GoogleGemini
11
- from pandasai import SmartDataframe
12
- from pandasai import Agent
13
- from pandasai.responses.response_parser import ResponseParser
14
  from langchain_experimental.agents import create_pandas_dataframe_agent
15
  import pandas as pd
16
  from langchain_google_genai import GoogleGenerativeAI
17
  from langchain_google_genai.chat_models import ChatGoogleGenerativeAI
18
  import requests
19
  import base64
20
- from pandasai.helpers import path
21
  import uuid
22
- import pandasai as pai
23
- import pymysql
24
 
25
  # load env data
26
  load_dotenv()
@@ -28,66 +21,9 @@ load_dotenv()
28
 
29
  import re
30
 
31
- def replace_country_code(mobile_number):
32
- # Define a dictionary of country codes
33
- country_codes = {
34
- "27": "0", # South Africa
35
- "263": "07" # Zimbabwe
36
- }
37
-
38
- # Iterate over the country codes and replace if found
39
- for code, replacement in country_codes.items():
40
- pattern = r'^' + re.escape(code)
41
- if re.match(pattern, mobile_number):
42
- updated_number = re.sub(pattern, replacement, mobile_number)
43
- return updated_number
44
-
45
- # Return the original number if no replacement is made
46
- return mobile_number
47
-
48
-
49
- '''
50
- def modify_file_path(file_path):
51
- guid = uuid.uuid4()
52
- print(guid)
53
- guid = str(uuid.uuid4())
54
- new_filename = f"{guid}temp_chart.png"
55
- new_file_path = os.path.join("/home/runner/Flasktestrairo/plots/", new_filename)
56
- # Copy the file
57
- shutil.copy2(file_path, new_file_path)
58
- return new_file_path
59
- '''
60
-
61
-
62
-
63
- guid = uuid.uuid4()
64
- new_filename = f"{guid}"
65
- user_defined_path = os.path.join("/plots/", new_filename)
66
-
67
-
68
- class FlaskResponse(ResponseParser):
69
- def __init__(self, context) -> None:
70
- super().__init__(context)
71
-
72
- def format_dataframe(self, result):
73
- return result['value'].to_html()
74
-
75
- def format_plot(self, result):
76
- # Save the plot using savefig
77
- try:
78
-
79
- img_path = result['value']
80
-
81
-
82
- except ValueError:
83
- img_path = str(result['value'])
84
- print("value error!", img_path)
85
-
86
- print("response_class_path:", img_path)
87
- return img_path
88
-
89
- def format_other(self, result):
90
- return str(result['value'])
91
 
92
 
93
  # messenger object
@@ -101,36 +37,13 @@ transcriber = aai.Transcriber()
101
  g_api_key = os.environ["google_api_key"]
102
 
103
 
104
- dbport = 3306 # Default port for MySQL
105
-
106
- # Connect to the db
107
- # Create a cursor object
108
-
109
- connection = pymysql.connect(
110
- host=os.environ["dbhost"],
111
- user=os.environ["dbuser"],
112
- password=os.environ["dbpassword"],
113
- database=os.environ["dbname"],
114
- port=dbport
115
- )
116
-
117
-
118
-
119
 
120
- app = Flask(__name__)
121
-
122
- VERIFY_TOKEN = "30cca545-3838-48b2-80a7-9e43b1ae8ce4"
123
-
124
- #df = pd.read_excel("craig.xlsx")
125
- #df = pd.read_csv("small_business_data2.csv")
126
 
127
 
128
  llm = ChatGoogleGenerativeAI(model="gemini-pro", google_api_key=g_api_key, temperature=0.2)
129
 
130
- def generateResponse(prompt, df):
131
- llm = GoogleGemini(api_key=g_api_key)
132
- pandas_agent = Agent(df,config={"llm":llm, "save_charts_path": user_defined_path,"save_charts": False,"response_parser":FlaskResponse, "enable_cache": False, "conversational":True})
133
- answer = pandas_agent.chat(prompt)
134
  return answer
135
 
136
  img_ID = "344744a88ad1098"
@@ -167,53 +80,16 @@ def hook():
167
  message_type = messenger.get_message_type(data)
168
  cursor = connection.cursor()
169
 
170
- # Execute a SELECT
171
-
172
- query = f"SELECT companyname FROM reg WHERE mobile = '{mobile_x}'"
173
- try:
174
- cursor.execute(query)
175
- except pymysql.err.InterfaceError:
176
- connection.ping(reconnect=True)
177
- cursor.execute(query)
178
-
179
- # Fetch all rows
180
-
181
- rows = cursor.fetchall()
182
- if not rows:
183
- response = "Your mobile number is not registered with Quantilytix"
184
- print(response)
185
- messenger.send_message(message=f"{response}, phone:{mobile}",recipient_id=mobile)
186
- cursor.close()
187
- connection.close()
188
-
189
- else:
190
- print(rows[0][0])
191
-
192
-
193
- company_name = rows[0][0]
194
- query2 = f"SELECT * FROM fin1 WHERE companyname = '{company_name}'"
195
- cursor.execute(query2)
196
-
197
- rows2 = cursor.fetchall()
198
-
199
- column_names = [desc[0] for desc in cursor.description]
200
-
201
- data_frame = pd.DataFrame(rows2, columns = column_names)
202
-
203
- print("Dataframe!!!:", data_frame.head())
204
 
205
- # Close the cursor and connection
206
- cursor.close()
207
- connection.close()
208
 
209
  if message_type == "text":
210
  message = messenger.get_message(data)
211
  # Handle greetings
212
  if message.lower() in ("hi", "hello", "help", "how are you"):
213
- response = "Hi there! My name is BuzyHelper. How can I help you today?"
214
  messenger.send_message(message=f"{response}, phone:{mobile}",recipient_id=mobile)
215
  else:
216
- response = str(generateResponse(message, data_frame))
217
  print("Response:", response)
218
  logging.info(f"\nAnswer: {response}\n")
219
  # Check if response is a string and represents a valid image path
@@ -234,24 +110,16 @@ def hook():
234
  # Handle cases where response is not a valid image path
235
  messenger.send_message(message=f"{response}", recipient_id=mobile)
236
 
237
- elif message_type == "audio":
238
- audio = messenger.get_audio(data)
239
- audio_id, mime_type = audio["id"], audio["mime_type"]
240
- audio_url = messenger.query_media_url(audio_id)
241
- audio_filename = messenger.download_media(audio_url, mime_type)
242
- transcript =transcriber.transcribe(audio_filename)
243
- print(audio_filename)
244
- print(transcript.text)
245
- res = transcript.text
246
- logging.info(f"\nAudio: {audio}\n")
247
- response = str(generateResponse(res, data_frame))
248
- if isinstance(response, str):
249
- messenger.send_message(message=f"{response}", recipient_id=mobile)
250
- elif isinstance(response, str) and os.path.isfile(response):
251
- messenger.send_image(image_path=response, recipient_id=mobile)
252
 
253
  else:
254
- messenger.send_message(message="Please send me text or audio messages",recipient_id=mobile)
255
 
256
  #else:messenger.send_message(message="Your mobile number is not registered with Quantilytix",recipient_id=mobile)
257
 
 
6
  import random
7
  import shutil
8
  from tempfile import NamedTemporaryFile
 
 
 
 
 
9
  from langchain_experimental.agents import create_pandas_dataframe_agent
10
  import pandas as pd
11
  from langchain_google_genai import GoogleGenerativeAI
12
  from langchain_google_genai.chat_models import ChatGoogleGenerativeAI
13
  import requests
14
  import base64
 
15
  import uuid
16
+
 
17
 
18
  # load env data
19
  load_dotenv()
 
21
 
22
  import re
23
 
24
+
25
+
26
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
 
29
  # messenger object
 
37
  g_api_key = os.environ["google_api_key"]
38
 
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
 
 
 
 
 
 
41
 
42
 
43
  llm = ChatGoogleGenerativeAI(model="gemini-pro", google_api_key=g_api_key, temperature=0.2)
44
 
45
+ def generateResponse(prompt):
46
+ answer = "I only understand images of receipts"
 
 
47
  return answer
48
 
49
  img_ID = "344744a88ad1098"
 
80
  message_type = messenger.get_message_type(data)
81
  cursor = connection.cursor()
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
 
 
 
84
 
85
  if message_type == "text":
86
  message = messenger.get_message(data)
87
  # Handle greetings
88
  if message.lower() in ("hi", "hello", "help", "how are you"):
89
+ response = "Hi there! My name is Petty Cash assistant. Upload an image of a receipt for me to record"
90
  messenger.send_message(message=f"{response}, phone:{mobile}",recipient_id=mobile)
91
  else:
92
+ response = str(generateResponse(message))
93
  print("Response:", response)
94
  logging.info(f"\nAnswer: {response}\n")
95
  # Check if response is a string and represents a valid image path
 
110
  # Handle cases where response is not a valid image path
111
  messenger.send_message(message=f"{response}", recipient_id=mobile)
112
 
113
+ elif message_type == "image":
114
+ image = messenger.get_image(data)
115
+ image_id, mime_type = image["id"], image["mime_type"]
116
+ image_url = await messenger.query_media_url(image_id)
117
+ image_filename = await messenger.download_media(image_url, mime_type)
118
+ print(f"{mobile} sent image {image_filename}")
119
+ logging.info(f"{mobile} sent image {image_filename}")
 
 
 
 
 
 
 
 
120
 
121
  else:
122
+ messenger.send_message(message="Please send me only images of receipts",recipient_id=mobile)
123
 
124
  #else:messenger.send_message(message="Your mobile number is not registered with Quantilytix",recipient_id=mobile)
125