Spaces:
Sleeping
Sleeping
Download src/utils/api_utils.py from utkarsh134/FastAPI-HackathonIn2Mins: direct link, hf CLI and curl.
- Browser
- Download file 6.82 kB
-
https://huggingface.co/spaces/utkarsh134/FastAPI-HackathonIn2Mins/resolve/233222c3d758c8b174a0e3c92bcf9bd266041743/src/utils/api_utils.py
- Command line
-
hf download hf://spaces/utkarsh134/FastAPI-HackathonIn2Mins@233222c3d758c8b174a0e3c92bcf9bd266041743/src/utils/api_utils.py
-
curl -L -o api_utils.py https://huggingface.co/spaces/utkarsh134/FastAPI-HackathonIn2Mins/resolve/233222c3d758c8b174a0e3c92bcf9bd266041743/src/utils/api_utils.py
6.82 kB
| import os | |
| import json | |
| import requests | |
| from datetime import datetime | |
| from typing import Dict, List, Any | |
| from fastapi import HTTPException | |
| from src.constants import subcategory_display_map | |
| def prepare_api_payload(drill_info: dict) -> dict: | |
| """ | |
| Prepare the API payload for event registration. | |
| """ | |
| phase_start_date = datetime.strptime(drill_info["phaseStartDt"], "%d-%m-%Y") | |
| phase_end_date = datetime.strptime(drill_info["phaseEndDt"], "%d-%m-%Y") | |
| registration_start_date = datetime.strptime( | |
| drill_info["drillRegistrationStartDt"], "%d-%m-%Y" | |
| ) | |
| registration_end_date = datetime.strptime( | |
| drill_info["drillRegistrationEndDt"], "%d-%m-%Y" | |
| ) | |
| drill_phase = { | |
| "type": "Single", | |
| "hasIdeaPhase": "", | |
| "isSelfPaced": False, | |
| "schedule": [ | |
| { | |
| "phaseType": drill_info["drillCategory"], | |
| "phaseDesc": "Hackathon Phase", | |
| "dateConfirmed": True, | |
| "phaseStartDt": phase_start_date.strftime("%Y-%m-%dT%H:%M:%S.000Z"), | |
| "phaseEndDt": phase_end_date.strftime("%Y-%m-%dT%H:%M:%S.000Z"), | |
| "phaseSubmissionEndDt": None, | |
| "isSubmissionAllowed": False, | |
| "phaseName": "Phase 1", | |
| "phaseTimezone": "Asia/Kolkata", | |
| "phaseMode": "Online", | |
| "phasePosition": 0, | |
| } | |
| ], | |
| } | |
| partner_id = drill_info.get( | |
| "drillPartnerId", "b886470e-52ac-4d34-8621-ff3e4d8335fb" | |
| ) | |
| partner_name = drill_info.get( | |
| "drillPartnerName", "WUElev8 Innovation services private ltd" | |
| ) | |
| subcategory = drill_info["drillSubCategory"].upper() | |
| if subcategory in subcategory_display_map: | |
| formatted_subcategory = subcategory_display_map[subcategory] | |
| else: | |
| formatted_subcategory = subcategory.capitalize() | |
| return { | |
| "drillCategory": drill_info["drillCategory"], | |
| "drillSubCategory": drill_info["drillSubCategory"], | |
| "drillNature": "", | |
| "drillDescription": drill_info["drillDescription"], | |
| "drillName": drill_info["drillName"], | |
| "drillPurpose": drill_info["drillPurpose"], | |
| "drillTimezone": "Asia/Kolkata", | |
| "drillType": drill_info["drillType"], | |
| "drillScheduleIfNotDateKnown": "", | |
| "drillId": None, | |
| "drillInvitationType": "PUBLIC", | |
| "isDrillPaid": drill_info["isDrillPaid"], | |
| "drillPhase": json.dumps(drill_phase), | |
| "selectedSubCategoryLabel": formatted_subcategory, | |
| "drillPartnerId": partner_id, | |
| "drillPartnerName": partner_name, | |
| "drillRegistrationStartDt": registration_start_date.strftime( | |
| "%Y-%m-%dT%H:%M:%S.000Z" | |
| ), | |
| "drillRegistrationEndDt": registration_end_date.strftime( | |
| "%Y-%m-%dT%H:%M:%S.000Z" | |
| ), | |
| } | |
| def register_event(payload: dict, eligibility_data) -> str: | |
| """ | |
| Register an event with the API and set up FAQs. | |
| Returns the event link URL. | |
| """ | |
| session_id = str(payload.get("session_id", "")) | |
| api_url = os.getenv("DRILL_URL") | |
| headers = {"Content-Type": "application/json", "Accept": "application/json"} | |
| try: | |
| response = requests.post(api_url, json=payload, headers=headers) | |
| response.raise_for_status() | |
| api_response = response.json() | |
| cust_url = api_response.get("drillCustUrl") | |
| drill_id = api_response.get("drillId") | |
| if not cust_url or not drill_id: | |
| raise ValueError( | |
| f"Invalid API response: missing drillCustUrl or drillId. Response: {api_response}" | |
| ) | |
| eligibility_json = process_eligibility_data(eligibility_data) | |
| create_event_overview(drill_id, eligibility_json, payload["drillDescription"], headers) | |
| from .core import get_llm | |
| from .content_generation import generate_faq_answers | |
| drill_info = payload.copy() | |
| drill_info["drillId"] = drill_id | |
| faq_answers = generate_faq_answers(drill_info, get_llm()) | |
| create_event_faqs(faq_answers, headers) | |
| event_link = f"https://dev.whereuelevate.com/drills/{cust_url}" | |
| return event_link | |
| except requests.exceptions.RequestException as e: | |
| print(f"API Error: {str(e)}") | |
| if hasattr(e, "response") and e.response is not None: | |
| print(f"API Error Response: {e.response.text}") | |
| print(f"Status code: {e.response.status_code}") | |
| print(f"Headers: {e.response.headers}") | |
| raise HTTPException( | |
| status_code=500, | |
| detail=f"API Error: {str(e)}\nResponse: {e.response.text if hasattr(e, 'response') and e.response is not None else 'No response'}", | |
| ) | |
| except Exception as e: | |
| print(f"Unexpected error: {str(e)}") | |
| raise HTTPException(status_code=500, detail=f"Unexpected error: {str(e)}") | |
| def process_eligibility_data(eligibility_data) -> str: | |
| """Process eligibility data into a JSON string.""" | |
| if isinstance(eligibility_data, list): | |
| return json.dumps(eligibility_data) | |
| elif isinstance(eligibility_data, str): | |
| try: | |
| json.loads(eligibility_data) | |
| return eligibility_data | |
| except json.JSONDecodeError: | |
| return json.dumps( | |
| [item.strip() for item in eligibility_data.split(",")] | |
| ) | |
| else: | |
| return json.dumps( | |
| ["Graduate", "Working Professionals", "College Students"] | |
| ) | |
| def create_event_overview(drill_id: str, eligibility_json: str, description: str, headers: Dict[str, str]) -> None: | |
| """Create the overview section for an event.""" | |
| overview_api_url = os.getenv("OVERVIEW_URL") | |
| overview_payload = { | |
| "drillId": drill_id, | |
| "eligibility": eligibility_json, | |
| "guidelines": None, | |
| "domain": None, | |
| "industry": None, | |
| "totalPrizeValue": None, | |
| "createdTs": datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] | |
| + "+00:00", | |
| "updatedTs": datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] | |
| + "+00:00", | |
| "createdBy": None, | |
| "updatedBy": None, | |
| "overviewSectionComplete": None, | |
| "drillDescription": description, | |
| } | |
| overview_response = requests.post( | |
| overview_api_url, json=overview_payload, headers=headers | |
| ) | |
| overview_response.raise_for_status() | |
| def create_event_faqs(faq_answers: List[Dict[str, Any]], headers: Dict[str, str]) -> None: | |
| """Create FAQs for an event.""" | |
| faq_api_url = os.getenv("FAQ_URL") | |
| for faq in faq_answers: | |
| faq_response = requests.post(faq_api_url, json=faq, headers=headers) | |
| faq_response.raise_for_status() | |