ariansyahdedy commited on
Commit
a4e11b2
·
1 Parent(s): 99723c5

Edit webhook

Browse files
Files changed (3) hide show
  1. app/main.py +16 -108
  2. app/services/message.py +2 -2
  3. indexed_links.txt +15 -0
app/main.py CHANGED
@@ -18,7 +18,7 @@ from sentence_transformers import SentenceTransformer
18
  from app.search.rag_pipeline import RAGSystem
19
  from contextlib import asynccontextmanager
20
  # from app.db.database import create_indexes, init_db
21
- from app.services.webhook_handler import verify_webhook
22
  from app.handlers.message_handler import MessageHandler
23
  from app.handlers.webhook_handler import WebhookHandler
24
  from app.handlers.media_handler import WhatsAppMediaHandler
@@ -39,7 +39,6 @@ logging.basicConfig(
39
 
40
  logger = logging.getLogger(__name__)
41
 
42
-
43
  # Initialize handlers at startup
44
  message_handler = None
45
  webhook_handler = None
@@ -183,9 +182,18 @@ async def webhook(request: Request, background_tasks: BackgroundTasks):
183
  content={"status": "error", "detail": str(e)},
184
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
185
  )
186
-
187
- app.get("/webhook")(verify_webhook)
188
 
 
 
 
 
 
 
 
 
 
 
 
189
  @app.post("/load_file")
190
  async def load_file_with_markitdown(file_path:str, llm_client:str=None, model:str=None):
191
 
@@ -198,11 +206,13 @@ async def load_file_with_markitdown(file_path:str, llm_client:str=None, model:st
198
 
199
  print(f"documents: {documents}")
200
  return documents
 
201
  # Add a route for Prometheus metrics (optional, if not using a separate Prometheus server)
202
  @app.get("/metrics")
203
  async def metrics():
204
  from prometheus_client import generate_latest
205
  return Response(content=generate_latest(), media_type="text/plain")
 
206
  # In-memory cache with timestamp cleanup
207
  # class MessageCache:
208
  # def __init__(self, max_age_hours: int = 24):
@@ -228,107 +238,5 @@ async def metrics():
228
  # message_cache = MessageCache()
229
  # user_chats = {}
230
 
231
- # @app.post("/webhook")
232
- # async def webhook(request: Request):
233
- # request_id = f"req_{int(time.time()*1000)}"
234
- # logger.info(f"Processing webhook request {request_id}")
235
- # payload = await request.json()
236
-
237
- # print("Webhook received:", payload)
238
-
239
- # processed_count = 0
240
- # error_count = 0
241
- # results = []
242
-
243
- # entries = payload.get("entry", [])
244
-
245
- # for entry in entries:
246
- # entry_id = entry.get("id")
247
- # logger.info(f"Processing entry_id: {entry_id}")
248
-
249
- # changes = entry.get("changes", [])
250
- # for change in changes:
251
- # messages = change.get("value", {}).get("messages", [])
252
- # for message in messages:
253
- # message_id = message.get("id")
254
- # timestamp = message.get("timestamp")
255
- # content = message.get("text", {}).get("body")
256
- # sender_id = message.get("from")
257
- # msg_type = message.get('type')
258
-
259
- # # Deduplicate messages based on message_id
260
- # if message_cache.exists(message_id):
261
- # logger.info(f"Duplicate message detected and skipped: {message_id}")
262
- # continue
263
-
264
- # if sender_id not in user_chats:
265
- # user_chats[sender_id] = []
266
- # user_chats[sender_id].append({
267
-
268
- # "role": "user",
269
- # "content": content
270
- # })
271
-
272
- # history = "".join([f"{item['role']}: {item['content']}\n" for item in user_chats[sender_id]])
273
- # print(f"history: {history}")
274
-
275
- # try:
276
- # # Process message with retry logic
277
- # result = await process_message_with_retry(
278
- # sender_id,content,
279
- # history,
280
- # timestamp,
281
- # )
282
- # user_chats[sender_id].append({
283
-
284
- # "role": "assistant",
285
- # "content": result
286
- # })
287
-
288
- # # Add the message ID to the cache
289
- # message_cache.add(message_id)
290
- # processed_count += 1
291
- # results.append(result)
292
- # except Exception as e:
293
- # error_count += 1
294
- # logger.error(
295
- # f"Failed to process message {message_id}: {str(e)}",
296
- # exc_info=True
297
- # )
298
- # results.append({
299
- # "status": "error",
300
- # "message_id": message_id,
301
- # "error": str(e)
302
- # })
303
-
304
- # response_data = {
305
- # "request_id": request_id,
306
- # "processed": processed_count,
307
- # "errors": error_count,
308
- # "results": results
309
- # }
310
-
311
- # logger.info(
312
- # f"Webhook processing completed - "
313
- # f"Processed: {processed_count}, Errors: {error_count}"
314
- # )
315
-
316
- # return JSONResponse(
317
- # content=response_data,
318
- # status_code=status.HTTP_200_OK
319
- # )
320
-
321
-
322
-
323
- # @app.get("/webhook")
324
- # async def verify_webhook(request: Request):
325
- # mode = request.query_params.get('hub.mode')
326
- # token = request.query_params.get('hub.verify_token')
327
- # challenge = request.query_params.get('hub.challenge')
328
-
329
- # # Replace 'your_verification_token' with the token you set in Facebook Business Manager
330
- # if mode == 'subscribe' and token == 'test':
331
- # # Return the challenge as plain text
332
- # return Response(content=challenge, media_type="text/plain")
333
- # else:
334
- # raise HTTPException(status_code=403, detail="Verification failed")
 
18
  from app.search.rag_pipeline import RAGSystem
19
  from contextlib import asynccontextmanager
20
  # from app.db.database import create_indexes, init_db
21
+ # from app.services.webhook_handler import verify_webhook
22
  from app.handlers.message_handler import MessageHandler
23
  from app.handlers.webhook_handler import WebhookHandler
24
  from app.handlers.media_handler import WhatsAppMediaHandler
 
39
 
40
  logger = logging.getLogger(__name__)
41
 
 
42
  # Initialize handlers at startup
43
  message_handler = None
44
  webhook_handler = None
 
182
  content={"status": "error", "detail": str(e)},
183
  status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
184
  )
 
 
185
 
186
+ @app.get("/webhook")
187
+ async def verify_webhook(request: Request):
188
+ mode = request.query_params.get('hub.mode')
189
+ token = request.query_params.get('hub.verify_token')
190
+ challenge = request.query_params.get('hub.challenge')
191
+
192
+ if mode == 'subscribe' and token == 'test':
193
+ return Response(content=challenge, media_type="text/plain")
194
+ else:
195
+ raise HTTPException(status_code=403, detail="Verification failed")
196
+
197
  @app.post("/load_file")
198
  async def load_file_with_markitdown(file_path:str, llm_client:str=None, model:str=None):
199
 
 
206
 
207
  print(f"documents: {documents}")
208
  return documents
209
+
210
  # Add a route for Prometheus metrics (optional, if not using a separate Prometheus server)
211
  @app.get("/metrics")
212
  async def metrics():
213
  from prometheus_client import generate_latest
214
  return Response(content=generate_latest(), media_type="text/plain")
215
+
216
  # In-memory cache with timestamp cleanup
217
  # class MessageCache:
218
  # def __init__(self, max_age_hours: int = 24):
 
238
  # message_cache = MessageCache()
239
  # user_chats = {}
240
 
241
+
242
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/services/message.py CHANGED
@@ -142,8 +142,8 @@ async def generate_response_from_gemini(
142
  logger.info(f"Generating response for sender: {sender}")
143
 
144
  # Initialize the model
145
- model = genai.GenerativeModel("gemini-1.5-pro-002", system_instruction= system_prompt)
146
- # model = genai.GenerativeModel("gemini-1.5-flash", system_instruction= system_prompt)
147
  # model = genai.GenerativeModel("gemini-exp-1206", system_instruction= system_prompt)
148
 
149
  # Start chat with history
 
142
  logger.info(f"Generating response for sender: {sender}")
143
 
144
  # Initialize the model
145
+ # model = genai.GenerativeModel("gemini-1.5-pro-002", system_instruction= system_prompt)
146
+ model = genai.GenerativeModel("gemini-1.5-flash", system_instruction= system_prompt)
147
  # model = genai.GenerativeModel("gemini-exp-1206", system_instruction= system_prompt)
148
 
149
  # Start chat with history
indexed_links.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2025-02-14 17:07:18,730 - INFO - 88247d7d-6925-4060-8be1-a268e112b0f6_https://sswalfa.surabaya.go.id/info/detail/izin-pengumpulan-sumbangan-bencana
2
+ 2025-02-14 17:07:19,044 - INFO - b70bd12c-66a5-4ee1-a52b-9263caf4801c_https://sswalfa.surabaya.go.id/info/detail/izin-pemakaian-ruang-terbuka-hijau
3
+ 2025-02-14 17:07:19,503 - INFO - a35b102d-269b-4532-8755-6206ba7c727a_https://sswalfa.surabaya.go.id/info/detail/pengganti-ipt
4
+ 2025-02-14 17:07:19,816 - INFO - 10dc5c2a-5817-48cb-a076-54292f0856f7_https://sswalfa.surabaya.go.id/info/detail/arahan-sistem-drainase
5
+ 2025-02-14 17:07:20,200 - INFO - 3e3cf77d-fba6-4edc-bd40-78e0276a44e4_https://sswalfa.surabaya.go.id/info/detail/rangkaian-pelayanan-surat-pernyataan-belum-menikah-lagi-bagi-jandaduda
6
+ 2025-02-14 17:12:33,533 - INFO - 639989ff-d5ca-4d6e-bbb1-380c638ae8b1_https://sswalfa.surabaya.go.id/info/detail/izin-pengumpulan-sumbangan-bencana
7
+ 2025-02-14 17:12:35,176 - INFO - 04ec2486-4fe0-40bb-b14f-5963a14df747_https://sswalfa.surabaya.go.id/info/detail/izin-pemakaian-ruang-terbuka-hijau
8
+ 2025-02-14 17:12:35,485 - INFO - e2663390-1328-4e97-9ee7-f3381600131c_https://sswalfa.surabaya.go.id/info/detail/pengganti-ipt
9
+ 2025-02-14 17:12:36,861 - INFO - b722b446-4b4e-4f94-9b1b-02b2591c359f_https://sswalfa.surabaya.go.id/info/detail/arahan-sistem-drainase
10
+ 2025-02-14 17:12:37,155 - INFO - d9877c2b-b74c-4f71-8492-e114d1f2510b_https://sswalfa.surabaya.go.id/info/detail/rangkaian-pelayanan-surat-pernyataan-belum-menikah-lagi-bagi-jandaduda
11
+ 2025-02-22 21:41:45,691 - INFO - a134264b-71fc-42d4-bbd2-fa7af5939a43_https://sswalfa.surabaya.go.id/info/detail/izin-pengumpulan-sumbangan-bencana
12
+ 2025-02-22 21:41:46,002 - INFO - 8581dd3e-86f7-41b1-9540-446cbd135e2a_https://sswalfa.surabaya.go.id/info/detail/izin-pemakaian-ruang-terbuka-hijau
13
+ 2025-02-22 21:41:46,472 - INFO - f45fc1f2-5ead-4a94-b3f2-eca2a7e6b851_https://sswalfa.surabaya.go.id/info/detail/pengganti-ipt
14
+ 2025-02-22 21:41:46,795 - INFO - 80b46ca9-480b-4651-8074-56861488c2e5_https://sswalfa.surabaya.go.id/info/detail/arahan-sistem-drainase
15
+ 2025-02-22 21:41:47,152 - INFO - 617438e3-472e-4896-8492-4f52d783a401_https://sswalfa.surabaya.go.id/info/detail/rangkaian-pelayanan-surat-pernyataan-belum-menikah-lagi-bagi-jandaduda