Zenaight commited on
Commit
5e663c0
·
verified ·
1 Parent(s): ccab90f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +37 -219
main.py CHANGED
@@ -1,121 +1,16 @@
1
- import os, json
2
  from fastapi import FastAPI, Request, HTTPException, Query
3
  from fastapi.responses import PlainTextResponse, JSONResponse
4
  import httpx
5
- import base64
6
- import asyncio
7
 
8
  app = FastAPI()
9
 
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 = {}
17
-
18
- # Persistent deduplication using a file
19
- DEDUP_FILE = "/tmp/processed_message_ids.txt"
20
- def load_processed_ids():
21
- try:
22
- with open(DEDUP_FILE, "r") as f:
23
- return set(line.strip() for line in f if line.strip())
24
- except FileNotFoundError:
25
- return set()
26
-
27
- def save_processed_id(msg_id):
28
- try:
29
- with open(DEDUP_FILE, "a") as f:
30
- f.write(msg_id + "\n")
31
- except Exception as e:
32
- print(f"Error saving msg_id {msg_id}: {e}")
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": {
41
- "iddetectionconfidence": "80",
42
- "smartidconfidence": "50",
43
- "greenidconfidence": "50",
44
- "binaryString": "1111111011110011"
45
- }
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 ──
65
- if wa_id and task_id in active_tasks:
66
- if data.get("status") == "success":
67
- print(f"[TASK] Sending response for active task {task_id}")
68
- det = data["results"][0]["detections"][0]
69
- reply = (
70
- "✅ *ID processed*\n"
71
- f"*Name*: {det.get('name','?')} {det.get('surname','')}\n"
72
- f"*ID No.*: {det.get('id_num','?')}\n"
73
- f"*DOB*: {det.get('date_of_birth','?')}\n"
74
- f"*Gender*: {det.get('gender','?')}\n"
75
- f"*ID Type*: {det.get('id_type','?')}\n"
76
- f"*Country of Birth*: {det.get('cob','?')}\n"
77
- f"*Citizen*: {det.get('citizen','?')}\n"
78
- f"*Citizen Status*: {det.get('citizen_status','?')}\n"
79
- f"*Date Issued*: {det.get('date_issued','?')}\n"
80
- f"*Age*: {det.get('age','?')}"
81
- )
82
- send_whatsapp_message(wa_id, reply)
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)
93
- elif task_id not in active_tasks:
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
-
101
- def pretty_print_dict(d, indent=0):
102
- for k, v in d.items():
103
- if isinstance(v, dict):
104
- print(' ' * indent + f"{k}:")
105
- pretty_print_dict(v, indent + 2)
106
- elif isinstance(v, list):
107
- print(' ' * indent + f"{k}: [")
108
- for item in v:
109
- if isinstance(item, dict):
110
- pretty_print_dict(item, indent + 2)
111
- else:
112
- print(' ' * (indent + 2) + str(item))
113
- print(' ' * indent + "]")
114
- else:
115
- print(' ' * indent + f"{k}: {v}")
116
-
117
- @app.get("/webhook") # verification
118
- def verify(
119
  hub_mode: str = Query(None, alias="hub.mode"),
120
  hub_token: str = Query(None, alias="hub.verify_token"),
121
  hub_challenge: str = Query(None, alias="hub.challenge")
@@ -124,127 +19,50 @@ def verify(
124
  return PlainTextResponse(hub_challenge)
125
  raise HTTPException(status_code=403, detail="Invalid token")
126
 
127
- def send_whatsapp_message(wa_id, reply):
128
- url = f"https://graph.facebook.com/v23.0/{PHONE_NUMBER_ID}/messages"
129
- headers = {
130
- "Authorization": f"Bearer {WHATSAPP_API_TOKEN}",
131
- "Content-Type": "application/json"
132
- }
133
- payload = {
134
- "messaging_product": "whatsapp",
135
- "to": wa_id,
136
- "type": "text",
137
- "text": {"body": reply}
138
- }
139
- httpx.post(url, headers=headers, json=payload)
140
-
141
- def send_welcome_buttons(wa_id: str):
142
- """Send an in-session Interactive button message with 2 reply options."""
143
- url = f"https://graph.facebook.com/v23.0/{PHONE_NUMBER_ID}/messages"
144
- headers = {
145
- "Authorization": f"Bearer {WHATSAPP_API_TOKEN}",
146
- "Content-Type": "application/json",
147
- }
148
- payload = {
149
- "messaging_product": "whatsapp",
150
- "to": wa_id,
151
- "type": "interactive",
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": [
159
- {
160
- "type": "reply",
161
- "reply": {"id": "open_gallery", "title": "📎"}
162
- },
163
- {
164
- "type": "reply",
165
- "reply": {"id": "open_camera", "title": "📷"}
166
- }
167
- ]
168
- }
169
- }
170
- }
171
- resp = httpx.post(url, headers=headers, json=payload)
172
- # debug log
173
- print(f"[BUTTON] POST → {resp.status_code}, body: {resp.text}")
174
 
175
- @app.post("/webhook") # incoming WhatsApp updates
176
- async def receive_update(req: Request):
177
- data = await req.json()
178
  try:
179
- change = data["entry"][0]["changes"][0]["value"]
180
  contacts = change.get("contacts")
181
  messages = change.get("messages")
182
  if not contacts or not messages:
183
- # Missing expected payload—ignore
184
- print("Ignoring update, no contacts or messages field")
185
  return JSONResponse({"status": "ignored", "reason": "no contacts/messages"})
186
 
187
  wa_id = contacts[0]["wa_id"]
188
- msg = messages[0]
189
- except (KeyError, IndexError, TypeError) as e:
190
- print("Malformed webhook payload:", e)
191
- return JSONResponse({"status": "ignored", "reason": "malformed payload"})
192
-
193
- msg_id = msg.get("id")
194
- if msg_id in processed_message_ids:
195
- print(f"Duplicate message {msg_id}, skipping.")
196
- return JSONResponse({"status": "duplicate", "id": msg_id})
197
- processed_message_ids.add(msg_id)
198
- save_processed_id(msg_id) # Save to file
199
 
200
- # TEXT: send welcome message
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"})
208
 
209
- # IMAGE: if user sent an image, convert to Base64 preview
210
- if msg["type"] == "image":
211
- media_id = msg["image"]["id"]
212
- # 1) get media URL
213
- media_resp = httpx.get(
214
- f"https://graph.facebook.com/v23.0/{media_id}",
215
- headers={"Authorization": f"Bearer {WHATSAPP_API_TOKEN}"}
216
- )
217
- media_resp.raise_for_status()
218
- media_url = media_resp.json()["url"]
219
- # 2) download bytes with auth
220
- media_bytes = httpx.get(
221
- media_url,
222
- headers={"Authorization": f"Bearer {WHATSAPP_API_TOKEN}"}
223
- ).content
224
- # 3) encode full & preview
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})
236
 
237
- # OTHER: ignore
238
- return JSONResponse({"status": "ignored", "type": msg["type"]})
239
 
240
- # health-check endpoint for token
241
- @app.post("/send")
242
- async def check_token():
243
- token = os.getenv("WHATSAPP_API_TOKEN", "")
244
- if token:
245
- return {"token_loaded": True}
246
- raise HTTPException(status_code=400, detail="Token not found")
 
 
 
 
 
 
 
 
 
 
247
 
248
- @app.get("/ping") # health check
249
  def ping():
250
- return {"pong": True}
 
1
+ import os
2
  from fastapi import FastAPI, Request, HTTPException, Query
3
  from fastapi.responses import PlainTextResponse, JSONResponse
4
  import httpx
 
 
5
 
6
  app = FastAPI()
7
 
8
+ VERIFY_TOKEN = os.getenv("VERIFY_TOKEN", "")
9
  PHONE_NUMBER_ID = os.getenv("PHONE_NUMBER_ID", "")
10
  WHATSAPP_API_TOKEN = os.getenv("WHATSAPP_API_TOKEN", "")
 
11
 
12
+ @app.get("/webhook")
13
+ def verify_webhook(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  hub_mode: str = Query(None, alias="hub.mode"),
15
  hub_token: str = Query(None, alias="hub.verify_token"),
16
  hub_challenge: str = Query(None, alias="hub.challenge")
 
19
  return PlainTextResponse(hub_challenge)
20
  raise HTTPException(status_code=403, detail="Invalid token")
21
 
22
+ @app.post("/webhook")
23
+ async def receive_message(req: Request):
24
+ body = await req.json()
25
+ print("Incoming webhook:", body)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
 
 
 
27
  try:
28
+ change = body["entry"][0]["changes"][0]["value"]
29
  contacts = change.get("contacts")
30
  messages = change.get("messages")
31
  if not contacts or not messages:
 
 
32
  return JSONResponse({"status": "ignored", "reason": "no contacts/messages"})
33
 
34
  wa_id = contacts[0]["wa_id"]
35
+ msg = messages[0]
 
 
 
 
 
 
 
 
 
 
36
 
37
+ if msg.get("type") == "text":
38
+ reply_text = "Hello 👋 from PropAgent!"
39
+ await send_whatsapp_message(wa_id, reply_text)
40
+ return JSONResponse({"status": "replied"})
 
 
 
 
41
 
42
+ except Exception as e:
43
+ print("Error processing message:", e)
44
+ return JSONResponse({"status": "error", "message": str(e)})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ return JSONResponse({"status": "ignored"})
 
47
 
48
+ async def send_whatsapp_message(wa_id: str, message: str):
49
+ url = f"https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}/messages"
50
+ headers = {
51
+ "Authorization": f"Bearer {WHATSAPP_API_TOKEN}",
52
+ "Content-Type": "application/json"
53
+ }
54
+ payload = {
55
+ "messaging_product": "whatsapp",
56
+ "to": wa_id,
57
+ "type": "text",
58
+ "text": {"body": message}
59
+ }
60
+ try:
61
+ resp = await httpx.post(url, headers=headers, json=payload)
62
+ print(f"Sent message → {resp.status_code}: {resp.text}")
63
+ except Exception as e:
64
+ print(f"Failed to send message: {e}")
65
 
66
+ @app.get("/ping")
67
  def ping():
68
+ return {"pong": True}