imseldrith commited on
Commit
51112b8
·
verified ·
1 Parent(s): d11ac2c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -41
app.py CHANGED
@@ -4,7 +4,7 @@ from dotenv import load_dotenv
4
  import os
5
  import re
6
  import json
7
- from helper.openai_api import chat_completion
8
 
9
  # Load environment variables from .env file
10
  load_dotenv()
@@ -16,6 +16,10 @@ VERIFY_TOKEN = os.getenv('VERIFY_TOKEN')
16
  PAGE_ACCESS_TOKEN = os.getenv('PAGE_ACCESS_TOKEN')
17
  OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
18
 
 
 
 
 
19
  # Debugging: Print the loaded environment variables (remove in production)
20
  print(f"VERIFY_TOKEN: {VERIFY_TOKEN}")
21
  print(f"PAGE_ACCESS_TOKEN: {PAGE_ACCESS_TOKEN}")
@@ -71,41 +75,23 @@ def webhook():
71
  # Get response with possible image URLs
72
  response_data = chat_completion(message_text, sender_id)
73
  print("ChatBot Response:\n", response_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- # Ensure response_data is a dictionary
76
- if isinstance(response_data, str):
77
- try:
78
- response_data = json.loads(response_data)
79
- except json.JSONDecodeError:
80
- # Extract text and URLs from the string
81
- response_text, image_urls = extract_text_and_urls(response_data)
82
- print(f"Extracted Text: {response_text}")
83
- print(f"Extracted Image URLs: {image_urls}")
84
-
85
- # Send text and/or images
86
- if response_text:
87
- send_message(sender_id, response_text)
88
- if image_urls:
89
- for url in image_urls:
90
- send_image(sender_id, url)
91
- response_data = {}
92
-
93
- if isinstance(response_data, dict):
94
- response_text = response_data.get('msg', '')
95
- image_urls = response_data.get('image_urls', [])
96
-
97
- print(f"ChatBot Response Text: {response_text}")
98
- print(f"ChatBot Response Image URLs: {image_urls}")
99
-
100
- # Send text and/or images
101
- if response_text:
102
- send_message(sender_id, response_text)
103
- if image_urls:
104
- for url in image_urls:
105
- send_image(sender_id, url)
106
- else:
107
- print("Error: ChatBot response is not a dictionary.")
108
- send_message(sender_id, "Sorry, I couldn't process your request.")
109
  except Exception as e:
110
  print(f"Exception occurred: {e}")
111
  send_message(sender_id, "Sorry, something went wrong. Please try again later.")
@@ -117,14 +103,46 @@ def webhook():
117
 
118
  return jsonify({'status': 'ok'})
119
 
120
- def extract_text_and_urls(input_string):
121
  # Regex pattern to find URLs
122
  url_pattern = re.compile(r'https?://\S+|www\.\S+')
123
- # Find all URLs using the pattern
124
  urls = re.findall(url_pattern, input_string)
125
- # Remove URLs from the input string to get the remaining text
126
- text = re.sub(url_pattern, '', input_string).strip()
127
- return text, urls
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
  def send_message(recipient_id, message_text):
130
  url = f'https://graph.facebook.com/v12.0/me/messages?access_token={PAGE_ACCESS_TOKEN}'
@@ -205,4 +223,4 @@ def mark_seen(recipient_id):
205
  print(f"Mark seen response: {response.status_code}, {response.text}")
206
 
207
  if __name__ == '__main__':
208
- app.run(host="0.0.0.0", port=7860, debug=True)
 
4
  import os
5
  import re
6
  import json
7
+ from helper.openai_api import chat_completion # Ensure this import is correct
8
 
9
  # Load environment variables from .env file
10
  load_dotenv()
 
16
  PAGE_ACCESS_TOKEN = os.getenv('PAGE_ACCESS_TOKEN')
17
  OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
18
 
19
+ # Check if environment variables are set
20
+ if not all([VERIFY_TOKEN, PAGE_ACCESS_TOKEN, OPENAI_API_KEY]):
21
+ raise EnvironmentError("Some environment variables are missing. Please check your .env file.")
22
+
23
  # Debugging: Print the loaded environment variables (remove in production)
24
  print(f"VERIFY_TOKEN: {VERIFY_TOKEN}")
25
  print(f"PAGE_ACCESS_TOKEN: {PAGE_ACCESS_TOKEN}")
 
75
  # Get response with possible image URLs
76
  response_data = chat_completion(message_text, sender_id)
77
  print("ChatBot Response:\n", response_data)
78
+ response_data = parse_response(response_data)
79
+ print("#"*10)
80
+ print("Parsed Response:\n", response_data)
81
+ print("#"*10)
82
+ response_text = response_data.get('msg', '')
83
+ image_urls = response_data.get('image_urls', [])
84
+
85
+ print(f"ChatBot Response Text: {response_text}")
86
+ print(f"ChatBot Response Image URLs: {image_urls}")
87
+
88
+ # Send text and/or images
89
+ if response_text:
90
+ send_message(sender_id, response_text)
91
+ if image_urls:
92
+ for url in image_urls:
93
+ send_image(sender_id, url)
94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  except Exception as e:
96
  print(f"Exception occurred: {e}")
97
  send_message(sender_id, "Sorry, something went wrong. Please try again later.")
 
103
 
104
  return jsonify({'status': 'ok'})
105
 
106
+ def parse_response(input_string):
107
  # Regex pattern to find URLs
108
  url_pattern = re.compile(r'https?://\S+|www\.\S+')
 
109
  urls = re.findall(url_pattern, input_string)
110
+
111
+ # Clean URLs by removing unwanted characters
112
+ cleaned_urls = [re.sub(r'[(){}"\']', '', url) for url in urls]
113
+
114
+ # Extract JSON-like dictionaries from the input string
115
+ json_pattern = re.compile(r'\{.*?\}')
116
+ json_matches = json_pattern.findall(input_string)
117
+ extracted_text = input_string
118
+
119
+ for json_str in json_matches:
120
+ try:
121
+ json_data = json.loads(json_str)
122
+ if isinstance(json_data, dict):
123
+ extracted_text = json_data.get('msg', extracted_text)
124
+ image_urls = json_data.get('image_url', [])
125
+ if isinstance(image_urls, str):
126
+ cleaned_urls.append(re.sub(r'[(){}"\']', '', image_urls))
127
+ elif isinstance(image_urls, list):
128
+ cleaned_urls.extend([re.sub(r'[(){}"\']', '', url) for url in image_urls])
129
+ except json.JSONDecodeError:
130
+ continue
131
+
132
+ # Remove URLs from the extracted text
133
+ text = re.sub(url_pattern, '', extracted_text).strip()
134
+
135
+ # Further clean the text from any leftover JSON artifacts and unwanted parts
136
+ text = re.sub(r'[\)\{\}\[\]\"\(\']', '', text).strip()
137
+ text = re.sub(r'msg:', '', text).strip()
138
+ text = re.sub(r'image_url:', '', text).strip()
139
+ text = text.replace('\n', '').strip()
140
+ text = text.replace(" ", " ")
141
+
142
+ return {
143
+ 'msg': text,
144
+ 'image_urls': list(set(cleaned_urls))
145
+ }
146
 
147
  def send_message(recipient_id, message_text):
148
  url = f'https://graph.facebook.com/v12.0/me/messages?access_token={PAGE_ACCESS_TOKEN}'
 
223
  print(f"Mark seen response: {response.status_code}, {response.text}")
224
 
225
  if __name__ == '__main__':
226
+ app.run(host="0.0.0.0", port=7860, debug=True)