Chandima Prabhath commited on
Commit
df706dd
·
1 Parent(s): cff8a81
Files changed (1) hide show
  1. app.py +26 -36
app.py CHANGED
@@ -1,13 +1,16 @@
1
  import os
2
  import threading
3
  import requests
 
4
  from fastapi import FastAPI, Request, HTTPException
5
  from fastapi.responses import PlainTextResponse, JSONResponse
6
  from FLUX import generate_image
7
  from VoiceReply import generate_voice_reply
8
-
9
  from llm import generate_llm
10
 
 
 
 
11
  GREEN_API_URL = os.getenv("GREEN_API_URL")
12
  GREEN_API_MEDIA_URL = os.getenv("GREEN_API_MEDIA_URL", "https://api.green-api.com")
13
  GREEN_API_TOKEN = os.getenv("GREEN_API_TOKEN")
@@ -23,11 +26,7 @@ if not all([GREEN_API_URL, GREEN_API_TOKEN, GREEN_API_ID_INSTANCE, WEBHOOK_AUTH_
23
  app = FastAPI()
24
 
25
  def send_message(message_id, to_number, message, retries=3):
26
- if to_number.endswith('@g.us'):
27
- chat_id = to_number
28
- else:
29
- chat_id = to_number
30
-
31
  url = f"{GREEN_API_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendMessage/{GREEN_API_TOKEN}"
32
  payload = {
33
  "chatId": chat_id,
@@ -46,11 +45,7 @@ def send_message(message_id, to_number, message, retries=3):
46
  return {"error": str(e)}
47
 
48
  def send_image(message_id, to_number, image_path, retries=3):
49
- if to_number.endswith('@g.us'):
50
- chat_id = to_number
51
- else:
52
- chat_id = to_number
53
-
54
  url = f"{GREEN_API_MEDIA_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendFileByUpload/{GREEN_API_TOKEN}"
55
  payload = {'chatId': chat_id, 'caption': 'Here you go!', 'quotedMessageId': message_id}
56
  files = [('file', ('image.jpg', open(image_path, 'rb'), 'image/jpeg'))]
@@ -69,14 +64,11 @@ def send_audio(message_id, to_number, audio_path, retries=3):
69
  """
70
  Send an audio file using the Green API similar to send_image.
71
  """
72
- print("DEBUG: Entering send_audio")
73
- if to_number.endswith('@g.us'):
74
- chat_id = to_number
75
- else:
76
- chat_id = to_number
77
 
78
  if not os.path.exists(audio_path):
79
- print(f"DEBUG: Audio file does not exist: {audio_path}")
80
 
81
  url = f"{GREEN_API_MEDIA_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendFileByUpload/{GREEN_API_TOKEN}"
82
  payload = {'chatId': chat_id, 'caption': 'Here is your voice reply!', 'quotedMessageId': message_id}
@@ -85,18 +77,18 @@ def send_audio(message_id, to_number, audio_path, retries=3):
85
  files = [('file', ('audio.mp3', audio_file, 'audio/mpeg'))]
86
  for attempt in range(retries):
87
  try:
88
- print(f"DEBUG: Attempt {attempt + 1} to send audio")
89
  response = requests.post(url, data=payload, files=files)
90
- print("DEBUG: Response from send_audio:", response.status_code, response.text)
91
  response.raise_for_status()
92
  return response.json()
93
  except requests.RequestException as e:
94
- print(f"DEBUG: Exception on attempt {attempt + 1} in send_audio: {e}")
95
  if attempt < retries - 1:
96
  continue
97
  return {"error": str(e)}
98
  except Exception as e:
99
- print("DEBUG: Failed to open audio file:", e)
100
  return {"error": str(e)}
101
 
102
  def response_text(message_id, chat_id, prompt):
@@ -107,22 +99,22 @@ def response_text(message_id, chat_id, prompt):
107
  send_message(message_id, chat_id, "There was an error processing your request.")
108
 
109
  def response_audio(message_id, chat_id, prompt):
110
- print("DEBUG: Entering response_audio with prompt:", prompt)
111
  try:
112
  result = generate_voice_reply(prompt, model="openai-audio", voice="coral", audio_dir=audio_dir)
113
- print("DEBUG: Result from generate_voice_reply:", result)
114
  if result:
115
  audio_file_path, audio_data = result
116
- print("DEBUG: Audio file path generated:", audio_file_path)
117
  send_result = send_audio(message_id, chat_id, audio_file_path)
118
- print("DEBUG: Result from send_audio:", send_result)
119
  os.remove(audio_file_path) # Clean up the file after sending
120
- print("DEBUG: Removed audio file:", audio_file_path)
121
  else:
122
- print("DEBUG: generate_voice_reply returned None, falling back to response_text")
123
  response_text(message_id, chat_id, prompt=prompt)
124
  except Exception as e:
125
- print("DEBUG: Exception in response_audio:", e)
126
  send_message(message_id, chat_id, "There was an error generating the audio. Please try again later.")
127
 
128
  def handle_image_generation(message_id, chat_id, prompt):
@@ -130,7 +122,11 @@ def handle_image_generation(message_id, chat_id, prompt):
130
  image, image_path, returned_prompt, image_url = generate_image(prompt, message_id, message_id, image_dir)
131
  if image:
132
  send_image(message_id, chat_id, image_path)
133
- send_message(message_id, chat_id, f"Image generated successfully! You can view it here: {image_url}. \nPrompt: > _{returned_prompt}_")
 
 
 
 
134
  else:
135
  send_message(message_id, chat_id, "Failed to generate image. Please try again later.")
136
  except Exception as e:
@@ -145,20 +141,16 @@ async def whatsapp_webhook(request: Request):
145
  auth_header = request.headers.get('Authorization', '').strip()
146
  if auth_header != f"Bearer {WEBHOOK_AUTH_TOKEN}":
147
  raise HTTPException(status_code=403, detail="Unauthorized")
148
-
149
  try:
150
  data = await request.json()
151
  except Exception:
152
  return JSONResponse(content={"error": "Invalid JSON"}, status_code=400)
153
-
154
  if data.get('typeWebhook') != 'incomingMessageReceived':
155
  return {"success": True}
156
-
157
  try:
158
  chat_id = data['senderData']['chatId']
159
  message_id = data['idMessage']
160
  message_data = data.get('messageData', {})
161
-
162
  if 'textMessageData' in message_data:
163
  body = message_data['textMessageData']['textMessage'].strip()
164
  elif 'extendedTextMessageData' in message_data:
@@ -167,7 +159,6 @@ async def whatsapp_webhook(request: Request):
167
  return {"success": True}
168
  except KeyError as e:
169
  return JSONResponse(content={"error": f"Missing key in data: {e}"}, status_code=200)
170
-
171
  if body.lower().startswith('/imagine'):
172
  prompt = body.replace('/imagine', '').strip()
173
  if not prompt:
@@ -177,12 +168,11 @@ async def whatsapp_webhook(request: Request):
177
  threading.Thread(target=handle_image_generation, args=(message_id, chat_id, prompt)).start()
178
  else:
179
  threading.Thread(target=response_text, args=(message_id, chat_id, body)).start()
180
-
181
  return {"success": True}
182
 
183
  def main():
184
  import uvicorn
185
- uvicorn.run(app, host="0.0.0.0", port=PORT, debug=True)
186
 
187
  if __name__ == '__main__':
188
  main()
 
1
  import os
2
  import threading
3
  import requests
4
+ import logging
5
  from fastapi import FastAPI, Request, HTTPException
6
  from fastapi.responses import PlainTextResponse, JSONResponse
7
  from FLUX import generate_image
8
  from VoiceReply import generate_voice_reply
 
9
  from llm import generate_llm
10
 
11
+ # Configure logging for debugging
12
+ logging.basicConfig(level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(message)s")
13
+
14
  GREEN_API_URL = os.getenv("GREEN_API_URL")
15
  GREEN_API_MEDIA_URL = os.getenv("GREEN_API_MEDIA_URL", "https://api.green-api.com")
16
  GREEN_API_TOKEN = os.getenv("GREEN_API_TOKEN")
 
26
  app = FastAPI()
27
 
28
  def send_message(message_id, to_number, message, retries=3):
29
+ chat_id = to_number if to_number.endswith('@g.us') else to_number
 
 
 
 
30
  url = f"{GREEN_API_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendMessage/{GREEN_API_TOKEN}"
31
  payload = {
32
  "chatId": chat_id,
 
45
  return {"error": str(e)}
46
 
47
  def send_image(message_id, to_number, image_path, retries=3):
48
+ chat_id = to_number if to_number.endswith('@g.us') else to_number
 
 
 
 
49
  url = f"{GREEN_API_MEDIA_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendFileByUpload/{GREEN_API_TOKEN}"
50
  payload = {'chatId': chat_id, 'caption': 'Here you go!', 'quotedMessageId': message_id}
51
  files = [('file', ('image.jpg', open(image_path, 'rb'), 'image/jpeg'))]
 
64
  """
65
  Send an audio file using the Green API similar to send_image.
66
  """
67
+ logging.debug("Entering send_audio")
68
+ chat_id = to_number if to_number.endswith('@g.us') else to_number
 
 
 
69
 
70
  if not os.path.exists(audio_path):
71
+ logging.debug(f"Audio file does not exist: {audio_path}")
72
 
73
  url = f"{GREEN_API_MEDIA_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendFileByUpload/{GREEN_API_TOKEN}"
74
  payload = {'chatId': chat_id, 'caption': 'Here is your voice reply!', 'quotedMessageId': message_id}
 
77
  files = [('file', ('audio.mp3', audio_file, 'audio/mpeg'))]
78
  for attempt in range(retries):
79
  try:
80
+ logging.debug(f"Attempt {attempt + 1} to send audio")
81
  response = requests.post(url, data=payload, files=files)
82
+ logging.debug(f"Response from send_audio: {response.status_code} {response.text}")
83
  response.raise_for_status()
84
  return response.json()
85
  except requests.RequestException as e:
86
+ logging.debug(f"Exception on attempt {attempt + 1} in send_audio: {e}")
87
  if attempt < retries - 1:
88
  continue
89
  return {"error": str(e)}
90
  except Exception as e:
91
+ logging.debug(f"Failed to open audio file: {e}")
92
  return {"error": str(e)}
93
 
94
  def response_text(message_id, chat_id, prompt):
 
99
  send_message(message_id, chat_id, "There was an error processing your request.")
100
 
101
  def response_audio(message_id, chat_id, prompt):
102
+ logging.debug(f"Entering response_audio with prompt: {prompt}")
103
  try:
104
  result = generate_voice_reply(prompt, model="openai-audio", voice="coral", audio_dir=audio_dir)
105
+ logging.debug(f"Result from generate_voice_reply: {result}")
106
  if result:
107
  audio_file_path, audio_data = result
108
+ logging.debug(f"Audio file path generated: {audio_file_path}")
109
  send_result = send_audio(message_id, chat_id, audio_file_path)
110
+ logging.debug(f"Result from send_audio: {send_result}")
111
  os.remove(audio_file_path) # Clean up the file after sending
112
+ logging.debug(f"Removed audio file: {audio_file_path}")
113
  else:
114
+ logging.debug("generate_voice_reply returned None, falling back to response_text")
115
  response_text(message_id, chat_id, prompt=prompt)
116
  except Exception as e:
117
+ logging.debug(f"Exception in response_audio: {e}")
118
  send_message(message_id, chat_id, "There was an error generating the audio. Please try again later.")
119
 
120
  def handle_image_generation(message_id, chat_id, prompt):
 
122
  image, image_path, returned_prompt, image_url = generate_image(prompt, message_id, message_id, image_dir)
123
  if image:
124
  send_image(message_id, chat_id, image_path)
125
+ send_message(
126
+ message_id,
127
+ chat_id,
128
+ f"Image generated successfully! You can view it here: {image_url}.\n>{chr(8203)} _{returned_prompt}_"
129
+ )
130
  else:
131
  send_message(message_id, chat_id, "Failed to generate image. Please try again later.")
132
  except Exception as e:
 
141
  auth_header = request.headers.get('Authorization', '').strip()
142
  if auth_header != f"Bearer {WEBHOOK_AUTH_TOKEN}":
143
  raise HTTPException(status_code=403, detail="Unauthorized")
 
144
  try:
145
  data = await request.json()
146
  except Exception:
147
  return JSONResponse(content={"error": "Invalid JSON"}, status_code=400)
 
148
  if data.get('typeWebhook') != 'incomingMessageReceived':
149
  return {"success": True}
 
150
  try:
151
  chat_id = data['senderData']['chatId']
152
  message_id = data['idMessage']
153
  message_data = data.get('messageData', {})
 
154
  if 'textMessageData' in message_data:
155
  body = message_data['textMessageData']['textMessage'].strip()
156
  elif 'extendedTextMessageData' in message_data:
 
159
  return {"success": True}
160
  except KeyError as e:
161
  return JSONResponse(content={"error": f"Missing key in data: {e}"}, status_code=200)
 
162
  if body.lower().startswith('/imagine'):
163
  prompt = body.replace('/imagine', '').strip()
164
  if not prompt:
 
168
  threading.Thread(target=handle_image_generation, args=(message_id, chat_id, prompt)).start()
169
  else:
170
  threading.Thread(target=response_text, args=(message_id, chat_id, body)).start()
 
171
  return {"success": True}
172
 
173
  def main():
174
  import uvicorn
175
+ uvicorn.run(app, host="0.0.0.0", port=PORT)
176
 
177
  if __name__ == '__main__':
178
  main()