Zenaight commited on
Commit
ccab90f
Β·
verified Β·
1 Parent(s): 2cd03d6

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +15 -15
main.py CHANGED
@@ -10,7 +10,7 @@ app = FastAPI()
10
  VERIFY_TOKEN = os.getenv("VERIFY_TOKEN", "") # set in HF Secrets
11
  PHONE_NUMBER_ID = os.getenv("PHONE_NUMBER_ID", "")
12
  WHATSAPP_API_TOKEN = os.getenv("WHATSAPP_API_TOKEN", "")
13
- RUMAS_API_URL = os.getenv("RUMAS_API_URL", "")
14
 
15
  # Add task tracking at the top
16
  active_tasks = {}
@@ -33,8 +33,8 @@ def save_processed_id(msg_id):
33
 
34
  processed_message_ids = load_processed_ids()
35
 
36
- async def forward_to_rumas(b64_str: str, wa_id: str, task_id: str):
37
- """Fire-and-forget call to RUMAS /api/process_id."""
38
  payload = {
39
  "data": [b64_str],
40
  "configurations": {
@@ -46,19 +46,19 @@ async def forward_to_rumas(b64_str: str, wa_id: str, task_id: str):
46
  }
47
  short = b64_str[:40] # first 40 chars for reference
48
  try:
49
- print(f"[RUMAS] ➜ sending image ({len(b64_str)} bytes) "
50
  f"preview='{short}…'")
51
 
52
- print("Payload to RUMAS:", json.dumps(payload)[:300], "…")
53
 
54
  async with httpx.AsyncClient(timeout=60) as client:
55
- resp = await client.post(RUMAS_API_URL, json=payload)
56
  resp.raise_for_status()
57
  # ── log the full JSON response (truncated to 300 chars for brevity) ──
58
  data = resp.json()
59
- print(f"[RUMAS] βœ” 200 {json.dumps(data)[:300]}…")
60
  body = data
61
- print(f"[RUMAS] βœ” {resp.status_code}")
62
  pretty_print_dict(body)
63
 
64
  # ── send parsed ID back to WhatsApp or error message ──
@@ -83,10 +83,10 @@ async def forward_to_rumas(b64_str: str, wa_id: str, task_id: str):
83
  print(f"[TASK] Completed and removed task {task_id}")
84
  elif "error" in data:
85
  error_msg = data["error"]
86
- print(f"[TASK] RUMAS error for task {task_id}: {error_msg}")
87
  send_whatsapp_message(wa_id, f"❌ {error_msg}")
88
  else:
89
- print(f"[TASK] RUMAS response not successful for task {task_id}")
90
  send_whatsapp_message(wa_id, "❌ Sorry, we could not process your ID. Please try again with a clearer image.")
91
  # Remove task from active list
92
  active_tasks.pop(task_id, None)
@@ -94,7 +94,7 @@ async def forward_to_rumas(b64_str: str, wa_id: str, task_id: str):
94
  print(f"[TASK] Ignoring response for inactive task {task_id}")
95
 
96
  except Exception as e:
97
- print(f"[RUMAS] ✘ error while sending '{short}…' β†’", e)
98
  # Remove task from active list on error
99
  active_tasks.pop(task_id, None)
100
 
@@ -152,7 +152,7 @@ def send_welcome_buttons(wa_id: str):
152
  "interactive": {
153
  "type": "button",
154
  "body": {
155
- "text": "Welcome to RUMAS.\nPlease send an image of your South African ID document."
156
  },
157
  "action": {
158
  "buttons": [
@@ -201,7 +201,7 @@ async def receive_update(req: Request):
201
  if msg.get("type") == "text":
202
  send_whatsapp_message(
203
  wa_id,
204
- "Welcome to RUMAS! πŸ“‹\n\n"
205
  "Please send an image of your South African ID document for processing."
206
  )
207
  return JSONResponse({"status": "welcome_sent"})
@@ -225,11 +225,11 @@ async def receive_update(req: Request):
225
  full_b64 = base64.b64encode(media_bytes).decode("utf-8")
226
  preview = full_b64[:10]
227
 
228
- # 4) forward full string to RUMAS (non-blocking)
229
  task_id = str(msg_id) # Use msg_id as task_id
230
  active_tasks[task_id] = True # Add task to active list
231
  print(f"[TASK] Created task {task_id} for message {msg_id}")
232
- asyncio.create_task(forward_to_rumas(full_b64, wa_id, task_id))
233
 
234
  # 5) echo preview to the user
235
  return JSONResponse({"status": "image_preview_sent", "preview": preview})
 
10
  VERIFY_TOKEN = os.getenv("VERIFY_TOKEN", "") # set in HF Secrets
11
  PHONE_NUMBER_ID = os.getenv("PHONE_NUMBER_ID", "")
12
  WHATSAPP_API_TOKEN = os.getenv("WHATSAPP_API_TOKEN", "")
13
+ CLIENT_API_URL = os.getenv("CLIENT_API_URL", "")
14
 
15
  # Add task tracking at the top
16
  active_tasks = {}
 
33
 
34
  processed_message_ids = load_processed_ids()
35
 
36
+ async def forward_to_client(b64_str: str, wa_id: str, task_id: str):
37
+ """Fire-and-forget call to CLIENT /api/process_id."""
38
  payload = {
39
  "data": [b64_str],
40
  "configurations": {
 
46
  }
47
  short = b64_str[:40] # first 40 chars for reference
48
  try:
49
+ print(f"[CLIENT] ➜ sending image ({len(b64_str)} bytes) "
50
  f"preview='{short}…'")
51
 
52
+ print("Payload to CLIENT:", json.dumps(payload)[:300], "…")
53
 
54
  async with httpx.AsyncClient(timeout=60) as client:
55
+ resp = await client.post(CLIENT_API_URL, json=payload)
56
  resp.raise_for_status()
57
  # ── log the full JSON response (truncated to 300 chars for brevity) ──
58
  data = resp.json()
59
+ print(f"[CLIENT] βœ” 200 {json.dumps(data)[:300]}…")
60
  body = data
61
+ print(f"[CLIENT] βœ” {resp.status_code}")
62
  pretty_print_dict(body)
63
 
64
  # ── send parsed ID back to WhatsApp or error message ──
 
83
  print(f"[TASK] Completed and removed task {task_id}")
84
  elif "error" in data:
85
  error_msg = data["error"]
86
+ print(f"[TASK] CLIENT error for task {task_id}: {error_msg}")
87
  send_whatsapp_message(wa_id, f"❌ {error_msg}")
88
  else:
89
+ print(f"[TASK] CLIENT response not successful for task {task_id}")
90
  send_whatsapp_message(wa_id, "❌ Sorry, we could not process your ID. Please try again with a clearer image.")
91
  # Remove task from active list
92
  active_tasks.pop(task_id, None)
 
94
  print(f"[TASK] Ignoring response for inactive task {task_id}")
95
 
96
  except Exception as e:
97
+ print(f"[CLIENT] ✘ error while sending '{short}…' β†’", e)
98
  # Remove task from active list on error
99
  active_tasks.pop(task_id, None)
100
 
 
152
  "interactive": {
153
  "type": "button",
154
  "body": {
155
+ "text": "Welcome to CLIENT.\nPlease send an image of your South African ID document."
156
  },
157
  "action": {
158
  "buttons": [
 
201
  if msg.get("type") == "text":
202
  send_whatsapp_message(
203
  wa_id,
204
+ "Welcome to CLIENT! πŸ“‹\n\n"
205
  "Please send an image of your South African ID document for processing."
206
  )
207
  return JSONResponse({"status": "welcome_sent"})
 
225
  full_b64 = base64.b64encode(media_bytes).decode("utf-8")
226
  preview = full_b64[:10]
227
 
228
+ # 4) forward full string to CLIENT (non-blocking)
229
  task_id = str(msg_id) # Use msg_id as task_id
230
  active_tasks[task_id] = True # Add task to active list
231
  print(f"[TASK] Created task {task_id} for message {msg_id}")
232
+ asyncio.create_task(forward_to_client(full_b64, wa_id, task_id))
233
 
234
  # 5) echo preview to the user
235
  return JSONResponse({"status": "image_preview_sent", "preview": preview})