Spaces:
Sleeping
Sleeping
| from fastapi import APIRouter, HTTPException , Body,Query | |
| from models.location_models import BodyData,ErrorResponse | |
| from services.location_service import LocationService | |
| from concurrent.futures import ThreadPoolExecutor | |
| import core.init_supabase as sp | |
| import asyncio | |
| import json | |
| import concurrent.futures | |
| router = APIRouter() | |
| async def get_coordinates_v1(cord): | |
| try: | |
| # Assuming LocationService.get_coordinates is an async function | |
| result = await LocationService.get_coordinates(cord) | |
| # If the result is a coroutine, await it | |
| if asyncio.iscoroutine(result): | |
| result = await result | |
| # Ensure the result is JSON serializable | |
| json.dumps(result) # This will raise an error if result is not JSON serializable | |
| return result | |
| except json.JSONDecodeError: | |
| print(f'Coordinate {cord} result is not JSON serializable') | |
| return None | |
| except Exception as exc: | |
| print(f'Coordinate {cord} generated an exception: {exc}') | |
| return None | |
| async def process_coordinates(supabase_user_data, max_concurrency=15): | |
| coords=[] | |
| with ThreadPoolExecutor(max_workers=15) as executor: | |
| futures = [executor.submit(LocationService.get_lat_lng,cord) for cord in supabase_user_data] | |
| for future in concurrent.futures.as_completed(futures): | |
| try: | |
| result = future.result() | |
| coords.append(result) | |
| except Exception as exc: | |
| print(f"error : {exc}") | |
| # coords = await asyncio.gather(*[bounded_get_coordinates(cord) for cord in supabase_user_data]) | |
| return [coord for coord in coords if coord is not None] | |
| async def get_coordinates_route(user_id: str = Query(..., description="User's hush ID")): | |
| print(user_id) | |
| supabase_user_data = sp.fetch_data(user_id) | |
| print("supabase data") | |
| print(supabase_user_data) | |
| print(len(supabase_user_data)) | |
| # coords=[] | |
| # for cord in supabase_user_data: | |
| # coords.append(LocationService.get_coordinates(cord)) | |
| coords = await process_coordinates(supabase_user_data) | |
| if not coords: | |
| return {"message": "An unexpected error occurred please try again!"} | |
| print(coords) | |
| return {"data": coords} | |
| async def get_coordinates_v2(data: BodyData = Body(...)): | |
| token = data.jwt_token | |
| user_id = sp.authenticate_user(token) | |
| if user_id == "Exceptional error": | |
| return {"User not Authenticated!"} | |
| else: | |
| print(user_id) | |
| try: | |
| supabase_card_data = sp.fetch_cards_data(user_id) | |
| print("supabase data") | |
| print(supabase_card_data) | |
| except Exception as e: | |
| print(HTTPException(status_code=400, detail=e)) | |
| return {"message":"An unexpected error occured please try again !!"} | |
| print("Returning the data") | |
| return {"data":supabase_card_data} | |