williamagyapong commited on
Commit
e011e39
·
verified ·
1 Parent(s): 7509df8
Files changed (1) hide show
  1. main.py +74 -88
main.py CHANGED
@@ -25,59 +25,18 @@ import pandasai as pai
25
  load_dotenv()
26
 
27
 
28
- '''
29
- def modify_file_path(file_path):
30
- guid = uuid.uuid4()
31
- print(guid)
32
- guid = str(uuid.uuid4())
33
- new_filename = f"{guid}temp_chart.png"
34
- new_file_path = os.path.join("/home/runner/Flasktestrairo/plots/", new_filename)
35
- # Copy the file
36
- shutil.copy2(file_path, new_file_path)
37
- return new_file_path
38
- '''
39
 
40
 
41
 
42
- guid = uuid.uuid4()
43
- new_filename = f"{guid}"
44
- user_defined_path = os.path.join("/plots/", new_filename)
45
-
46
-
47
- class FlaskResponse(ResponseParser):
48
- def __init__(self, context) -> None:
49
- super().__init__(context)
50
-
51
- def format_dataframe(self, result):
52
- return result['value'].to_html()
53
-
54
- def format_plot(self, result):
55
- # Save the plot using savefig
56
- try:
57
-
58
- img_path = result['value']
59
-
60
-
61
- except ValueError:
62
- img_path = str(result['value'])
63
- print("value error!", img_path)
64
-
65
- print("response_class_path:", img_path)
66
- return img_path
67
-
68
- def format_other(self, result):
69
- return str(result['value'])
70
-
71
-
72
  # messenger object
73
  messenger = WhatsApp(
74
  os.environ["whatsapp_token"],
75
  phone_number_id=os.environ["phone_number_id"] )
76
 
77
- aai.settings.api_key = os.environ["aai_key"]
78
- transcriber = aai.Transcriber()
 
79
 
80
- g_api_key = os.environ["google_api_key"]
81
 
82
 
83
 
@@ -85,23 +44,64 @@ app = Flask(__name__)
85
 
86
  VERIFY_TOKEN = "30cca545-3838-48b2-80a7-9e43b1ae8ce4"
87
 
88
- #df = pd.read_excel("craig.xlsx")
89
- df = pd.read_csv("small_business_data2.csv")
90
 
91
-
92
- llm = ChatGoogleGenerativeAI(model="gemini-pro", google_api_key=g_api_key, temperature=0.2)
 
 
93
 
94
  def generateResponse(prompt):
95
- llm = GoogleGemini(api_key=g_api_key)
96
- pandas_agent = Agent(df,config={"llm":llm, "save_charts_path": user_defined_path,"save_charts": False,"response_parser":FlaskResponse, "enable_cache": False, "conversational":True})
97
- answer = pandas_agent.chat(prompt)
98
- return answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
- img_ID = "344744a88ad1098"
101
- img_secret = "3c542a40c215327045d7155bddfd8b8bc84aebbf"
102
 
103
- url = "https://api.imgur.com/3/image"
104
- headers = {"Authorization": f"Client-ID {img_ID}"}
105
 
106
  def respond(query_str:str):
107
  response = "hello, I don't have a brain yet"
@@ -139,39 +139,25 @@ def hook():
139
  response = str(generateResponse(message))
140
  print("Response:", response)
141
  logging.info(f"\nAnswer: {response}\n")
142
- # Check if response is a string and represents a valid image path
143
- if isinstance(response, str) and os.path.isfile(os.path.join(response)):
144
- image_path = os.path.join(response)
145
- print("My image path:", image_path)
146
- with open(image_path, "rb") as file:
147
- data = file.read()
148
- base64_data = base64.b64encode(data)
149
-
150
- # Upload image to Imgur and get URL
151
- response = requests.post(url, headers=headers, data={"image": base64_data})
152
- url1= response.json()["data"]["link"]
153
- print(url1)
154
-
155
- messenger.send_image(image=url1, recipient_id=mobile)
156
- else:
157
- # Handle cases where response is not a valid image path
158
- messenger.send_message(message=f"{response}", recipient_id=mobile)
159
-
160
- elif message_type == "audio":
161
- audio = messenger.get_audio(data)
162
- audio_id, mime_type = audio["id"], audio["mime_type"]
163
- audio_url = messenger.query_media_url(audio_id)
164
- audio_filename = messenger.download_media(audio_url, mime_type)
165
- transcript =transcriber.transcribe(audio_filename)
166
- print(audio_filename)
167
- print(transcript.text)
168
- res = transcript.text
169
- logging.info(f"\nAudio: {audio}\n")
170
- response = str(generateResponse(res))
171
- if isinstance(response, str):
172
  messenger.send_message(message=f"{response}", recipient_id=mobile)
173
- elif isinstance(response, str) and os.path.isfile(response):
174
- messenger.send_image(image_path=response, recipient_id=mobile)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
  else:
177
  messenger.send_message(message="Please send me text or audio messages",recipient_id=mobile)
 
25
  load_dotenv()
26
 
27
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
 
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  # messenger object
32
  messenger = WhatsApp(
33
  os.environ["whatsapp_token"],
34
  phone_number_id=os.environ["phone_number_id"] )
35
 
36
+ # aai.settings.api_key = os.environ["aai_key"]
37
+ # transcriber = aai.Transcriber()
38
+
39
 
 
40
 
41
 
42
 
 
44
 
45
  VERIFY_TOKEN = "30cca545-3838-48b2-80a7-9e43b1ae8ce4"
46
 
 
 
47
 
48
+ client = openai.OpenAI(
49
+ api_key=os.environ.get("sambanova_api_key"),
50
+ base_url="https://api.sambanova.ai/v1",
51
+ )
52
 
53
  def generateResponse(prompt):
54
+ #----- Call API to classify and extract relevant transaction information
55
+ # These templates help provide a unified response format for use as context clues when
56
+ # parsing the AI generated response into a structured data format
57
+ relevant_info_template = """
58
+ Intent: The CRUD operation
59
+ Transaction Type: The type of transaction
60
+ Details: as a sublist of the key details like name of item, amount, description, among other details you are able to extract.
61
+ """
62
+ sample_response_template = """
63
+ The information provided indicates that you want to **create/record** a new transaction.
64
+
65
+ **Extracted Information**:
66
+
67
+ **Intent**: Create
68
+
69
+ Transaction 1:
70
+
71
+ **Transaction Type**: Purchase
72
+ **Details**:
73
+ - Item: Car
74
+ - Purpose: Business
75
+ - Amount: 1000
76
+ - Tax: 200
77
+ - Note: A new car for business
78
+
79
+ Transaction 2:
80
+
81
+ **Transaction Type**: Expense
82
+ **Details**:
83
+ - Item: Office Chair
84
+ - Amount: 300 USD
85
+ - Category: Furniture
86
+ """
87
+ response = client.chat.completions.create(
88
+ model='Meta-Llama-3.1-70B-Instruct',
89
+ messages=[
90
+ {"role": "system", "content": f"You are a helpful assistant that classifies transactions written in natural language into CRUD operations (Create, Read, Update, and Delete) and extracts relevant information. Format the relevant information extracted from the transaction text in this format: {relevant_info_template}. You can use markdown syntax to present a nicely formated and readable response to the user, but make sure the user does not see the markdown keyword. Keywords and field names must be in bold face. A sample response could look like this: {sample_response_template}. Delineate multiple transactions with the label 'Transaction 1' before the start of the relevant information for each transaction. There should be only one intent even in the case of multiple transactions."},
91
+ {"role": "user", "content": prompt}
92
+ ]
93
+ )
94
+ #----- Process response
95
+ try:
96
+ response = response.choices[0].message.content
97
+ except Exception as e:
98
+ print(f'An error occurred: {str(e)}')
99
+ response = None
100
+
101
+ return response
102
+
103
 
 
 
104
 
 
 
105
 
106
  def respond(query_str:str):
107
  response = "hello, I don't have a brain yet"
 
139
  response = str(generateResponse(message))
140
  print("Response:", response)
141
  logging.info(f"\nAnswer: {response}\n")
142
+ # Handle cases where response is not a valid image path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  messenger.send_message(message=f"{response}", recipient_id=mobile)
144
+
145
+
146
+ # elif message_type == "audio":
147
+ # audio = messenger.get_audio(data)
148
+ # audio_id, mime_type = audio["id"], audio["mime_type"]
149
+ # audio_url = messenger.query_media_url(audio_id)
150
+ # audio_filename = messenger.download_media(audio_url, mime_type)
151
+ # transcript =transcriber.transcribe(audio_filename)
152
+ # print(audio_filename)
153
+ # print(transcript.text)
154
+ # res = transcript.text
155
+ # logging.info(f"\nAudio: {audio}\n")
156
+ # response = str(generateResponse(res))
157
+ # if isinstance(response, str):
158
+ # messenger.send_message(message=f"{response}", recipient_id=mobile)
159
+ # elif isinstance(response, str) and os.path.isfile(response):
160
+ # messenger.send_image(image_path=response, recipient_id=mobile)
161
 
162
  else:
163
  messenger.send_message(message="Please send me text or audio messages",recipient_id=mobile)