from fastapi import Request,APIRouter import requests from controllers import ner_ai_controller as ai from services.chat_client_NER import ChatClient import logging router = APIRouter(prefix="/gmail") @router.post("/total_messages") async def get_total_messages(request:Request): body = await request.json() access_token = body.get('access_token',None) if access_token is None : return {"message":"Access token Invalid ! Try Again!"} user_query = body.get('brand_name') if body.get('brand_name') is not None else None # access_token = await websocket.receive_text() brand_name = None logging.info(f"brand_name: {user_query}") logging.info(f"access_token : {access_token}") if user_query is not None: chat = ChatClient().create(conversation=[]) response = chat.send_message(content=f"{user_query}", stream=False) if response.text == 'others': brand_name = None else: brand_name = response.text search_query = f'(subject:"your order" OR subject:receipts OR subject:receipt OR subject:aankoopbon OR subject:reçu OR subject:invoice OR subject:invoices OR category:purchases) has:attachment' if brand_name is not None: search_query = f'(subject:"your order" OR subject:receipts OR subject:receipt OR subject: aankoopbon OR subject:reçu OR subject:invoice OR subject:invoices OR category:purchases) AND ({brand_name}) has:attachment' total_messages = 0 page_token = None while True: gmail_url = f"https://www.googleapis.com/gmail/v1/users/me/messages?q={search_query}" if page_token: gmail_url += f"&pageToken={page_token}" gmail_response = requests.get(gmail_url, headers={"Authorization": f"Bearer {access_token}"}) gmail_data = gmail_response.json() if "messages" in gmail_data: total_messages += len(gmail_data["messages"]) if "nextPageToken" in gmail_data: page_token = gmail_data["nextPageToken"] else: break pass return {"total_messages":total_messages}