Dooratre commited on
Commit
20beebd
·
verified ·
1 Parent(s): 2a694b5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -12
app.py CHANGED
@@ -9,11 +9,14 @@ from upload import upload_image_to_cdn # Import the new upload function
9
 
10
  app = Flask(__name__)
11
 
 
 
 
12
  # Fetch page credentials from GitHub on startup
13
  try:
14
  github_response = fetch_json_from_github()
15
  if github_response["success"]:
16
- PAGE_CREDENTIALS = {page['page_id']: page['page_token'] for page in github_response["data"]["pages"]}
17
  print("Successfully loaded page credentials from GitHub.")
18
  else:
19
  print(f"Error loading page credentials: {github_response['message']}")
@@ -25,10 +28,6 @@ except Exception as e:
25
  AI_SERVICE_URL = "https://aoamrnuwara.pythonanywhere.com/send-message"
26
  AI_SERVICE_TOKEN = "123400"
27
 
28
- # Qwen CDN Upload Configuration
29
- BASE_URL = "https://chat.qwen.ai"
30
- AUTH_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImRjOGQyYzY4LWZjNmEtNDEwYy05NWZjLWQ5MDBmNTM4ZTMwMiIsImV4cCI6MTc0NjM1OTExMH0.ms8Agbit2ObnTMJyeW_dUbk-tV_ON_dc-RjDKCDLAwA"
31
-
32
  @app.route("/webhook", methods=["GET"])
33
  def verify_webhook():
34
  mode = request.args.get("hub.mode")
@@ -45,8 +44,10 @@ def handle_message():
45
  body = request.get_json()
46
 
47
  for entry in body["entry"]:
48
- page_id = entry["id"] # Extract page_id from the incoming message
49
- page_token = PAGE_CREDENTIALS.get(page_id)
 
 
50
 
51
  if not page_token:
52
  print(f"Page ID {page_id} not found in credentials. Skipping...")
@@ -56,6 +57,16 @@ def handle_message():
56
  if "message" in messaging_event:
57
  sender_id = messaging_event["sender"]["id"]
58
  message = messaging_event["message"]
 
 
 
 
 
 
 
 
 
 
59
  text_content = message.get("text", "")
60
  attachments = message.get("attachments", [])
61
  image_cdn_urls = []
@@ -69,10 +80,10 @@ def handle_message():
69
  img_response = requests.get(image_url)
70
  img_response.raise_for_status()
71
  temp_path = f"temp_{uuid.uuid4()}.jpg"
72
-
73
  with open(temp_path, "wb") as f:
74
  f.write(img_response.content)
75
-
76
  # Upload to Qwen CDN
77
  cdn_url = upload_image_to_cdn(BASE_URL, AUTH_TOKEN, temp_path)
78
  if cdn_url:
@@ -83,6 +94,17 @@ def handle_message():
83
  if os.path.exists(temp_path):
84
  os.remove(temp_path)
85
 
 
 
 
 
 
 
 
 
 
 
 
86
  # Build message content for Qwen
87
  user_content = []
88
  if text_content:
@@ -91,8 +113,17 @@ def handle_message():
91
  user_content.append({"type": "image", "image": cdn_url})
92
 
93
  if user_content:
94
- ai_response = get_qwen_response(user_content)
95
-
 
 
 
 
 
 
 
 
 
96
  # Send response back to user
97
  headers = {
98
  "Authorization": f"Bearer {AI_SERVICE_TOKEN}",
@@ -101,7 +132,7 @@ def handle_message():
101
  payload = {
102
  "recipient_id": sender_id,
103
  "message_text": ai_response,
104
- "page_access_token": page_token # Include page-specific token
105
  }
106
  requests.post(AI_SERVICE_URL, json=payload, headers=headers)
107
 
 
9
 
10
  app = Flask(__name__)
11
 
12
+ # In-memory chat history storage (for demonstration - use database in production)
13
+ chat_histories = {}
14
+
15
  # Fetch page credentials from GitHub on startup
16
  try:
17
  github_response = fetch_json_from_github()
18
  if github_response["success"]:
19
+ PAGE_CREDENTIALS = {page['page_id']: page for page in github_response["data"]["pages"]}
20
  print("Successfully loaded page credentials from GitHub.")
21
  else:
22
  print(f"Error loading page credentials: {github_response['message']}")
 
28
  AI_SERVICE_URL = "https://aoamrnuwara.pythonanywhere.com/send-message"
29
  AI_SERVICE_TOKEN = "123400"
30
 
 
 
 
 
31
  @app.route("/webhook", methods=["GET"])
32
  def verify_webhook():
33
  mode = request.args.get("hub.mode")
 
44
  body = request.get_json()
45
 
46
  for entry in body["entry"]:
47
+ page_id = entry["id"]
48
+ page_config = PAGE_CREDENTIALS.get(page_id, {})
49
+ page_token = page_config.get('page_token')
50
+ system_prompt = page_config.get('system', 'Default system prompt')
51
 
52
  if not page_token:
53
  print(f"Page ID {page_id} not found in credentials. Skipping...")
 
57
  if "message" in messaging_event:
58
  sender_id = messaging_event["sender"]["id"]
59
  message = messaging_event["message"]
60
+
61
+ # Get or create chat history for this user
62
+ user_history = chat_histories.setdefault(sender_id, {
63
+ 'history': [],
64
+ 'system_prompt': system_prompt
65
+ })
66
+
67
+ # Update system prompt if changed
68
+ user_history['system_prompt'] = system_prompt
69
+
70
  text_content = message.get("text", "")
71
  attachments = message.get("attachments", [])
72
  image_cdn_urls = []
 
80
  img_response = requests.get(image_url)
81
  img_response.raise_for_status()
82
  temp_path = f"temp_{uuid.uuid4()}.jpg"
83
+
84
  with open(temp_path, "wb") as f:
85
  f.write(img_response.content)
86
+
87
  # Upload to Qwen CDN
88
  cdn_url = upload_image_to_cdn(BASE_URL, AUTH_TOKEN, temp_path)
89
  if cdn_url:
 
94
  if os.path.exists(temp_path):
95
  os.remove(temp_path)
96
 
97
+ # Add user message to history if it's text
98
+ if text_content:
99
+ user_history['history'].append({
100
+ "role": "user",
101
+ "content": text_content
102
+ })
103
+
104
+ # Keep only last 5 messages (3 user + 2 assistant to maintain context)
105
+ while len(user_history['history']) > 5:
106
+ user_history['history'].pop(0)
107
+
108
  # Build message content for Qwen
109
  user_content = []
110
  if text_content:
 
113
  user_content.append({"type": "image", "image": cdn_url})
114
 
115
  if user_content:
116
+ ai_response = get_qwen_response(
117
+ system_prompt=user_history['system_prompt'],
118
+ chat_history=user_history['history']
119
+ )
120
+
121
+ # Add AI response to history
122
+ user_history['history'].append({
123
+ "role": "assistant",
124
+ "content": ai_response
125
+ })
126
+
127
  # Send response back to user
128
  headers = {
129
  "Authorization": f"Bearer {AI_SERVICE_TOKEN}",
 
132
  payload = {
133
  "recipient_id": sender_id,
134
  "message_text": ai_response,
135
+ "page_access_token": page_token
136
  }
137
  requests.post(AI_SERVICE_URL, json=payload, headers=headers)
138