File size: 16,612 Bytes
233222c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import uuid
from typing import Any, Dict, List, Optional

import urllib3
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

from src.constants import CATEGORY_SUBCATEGORY_MAP, DEFAULT_DRILL_INFO
from src.utils import (DatabaseHandler, DateHandler, create_naming_assistant,
                       extract_partner_info, find_partner_by_url,
                       generate_drill_description, get_llm, infer_drill_type,
                       infer_eligibility, infer_purpose, infer_subcategory,
                       infer_user_uncertainty, infer_yes_no,
                       prepare_api_payload, register_event, register_partner,
                       save_to_database, validate_partner_url)

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

load_dotenv()
app = FastAPI()

date_handler = DateHandler(default_timezone="Asia/Kolkata")
db_handler = DatabaseHandler()
llm = get_llm()


class SessionInput(BaseModel):
    session_id: Optional[str] = None
    message: str
    current_question: Optional[str] = None


class SessionResponse(BaseModel):
    session_id: str
    message: str
    event_link: Optional[str] = None
    current_question: Optional[str] = None
    registration_complete: bool = False


session_store: Dict[str, Dict[str, Any]] = {}


@app.post("/chat", response_model=SessionResponse)
async def chat_endpoint(chat_input: SessionInput):
    try:
        session_id = chat_input.session_id or str(uuid.uuid4())

        if session_id not in session_store:
            session_store[session_id] = {
                "context": {"hackathon_details": DEFAULT_DRILL_INFO.copy()},
                "current_question": None,
            }

        session_data = session_store[session_id]
        message = chat_input.message
        context = session_data["context"]
        current_question = (
            chat_input.current_question or session_data["current_question"]
        )

        if not current_question:
            session_data.update({"current_question": "drillSubCategory"})
            return SessionResponse(
                session_id=session_id,
                message="What type of event you want to host : Workshop, Webinar, Masterclass, Innovation Hackathon, Squad Program, Case Study, Hiring Hackathon, Innovation, Tech Conferences, Bootcamp, Startup, Conclave, Contractual, Ideathon, Internal Hackathon, Smart India Hackathon?",
                current_question="drillSubCategory",
            )

        if current_question == "drillSubCategory":
            subcategory = infer_subcategory(message, CATEGORY_SUBCATEGORY_MAP, llm)
            if not subcategory:
                return SessionResponse(
                    session_id=session_id,
                    message="Could not determine a valid subcategory. Please try again.",
                    current_question="drillSubCategory",
                )
            context["hackathon_details"]["drillSubCategory"] = subcategory
            context["hackathon_details"]["drillCategory"] = CATEGORY_SUBCATEGORY_MAP[
                subcategory
            ]

            session_data.update({"current_question": "drillName"})
            return SessionResponse(
                session_id=session_id,
                message="What name do you want to give to your event?",
                current_question="drillName",
            )

        if current_question == "drillName":
            # Check if user is uncertain or needs help
            if infer_user_uncertainty(message, llm) or session_store[session_id].get(
                "in_naming_conversation"
            ):
                # Initialize naming conversation if not exists
                if "naming_assistant" not in session_store[session_id]:
                    naming_assistant = create_naming_assistant(llm)
                    session_store[session_id]["naming_assistant"] = naming_assistant
                    session_store[session_id]["in_naming_conversation"] = True
                    session_store[session_id]["naming_history"] = []

                    # Start the conversation
                    response = naming_assistant.invoke(
                        {
                            "input": "I need help naming my event. It's a "
                            + context["hackathon_details"]["drillSubCategory"],
                            "history": [],
                        }
                    )

                    session_store[session_id]["naming_history"].append(
                        {"user": message, "assistant": response}
                    )

                    return SessionResponse(
                        session_id=session_id,
                        message=response,
                        current_question="drillName",
                    )

                # Continue naming conversation
                naming_assistant = session_store[session_id]["naming_assistant"]
                history = session_store[session_id]["naming_history"]

                # Format history for the prompt
                formatted_history = "\n".join(
                    [f"User: {h['user']}\nAssistant: {h['assistant']}" for h in history]
                )

                response = naming_assistant.invoke(
                    {"input": message, "history": formatted_history}
                )

                # Update conversation history
                history.append({"user": message, "assistant": response})

                # Check if a name was selected
                if "SELECTED_NAME:" in response:
                    selected_name = response.split("SELECTED_NAME:")[1].strip()
                    context["hackathon_details"]["drillName"] = selected_name

                    # Clean up naming conversation
                    session_store[session_id].pop("naming_assistant", None)
                    session_store[session_id].pop("in_naming_conversation", None)
                    session_store[session_id].pop("naming_history", None)

                    session_data.update({"current_question": "phaseStartDt"})

                    return SessionResponse(
                        session_id=session_id,
                        message=f"Perfect! Your event name is set to {selected_name}. When do you want to organize it?",
                        current_question="phaseStartDt",
                    )

                return SessionResponse(
                    session_id=session_id,
                    message=response,
                    current_question="drillName",
                )

            # Direct name input
            else:
                context["hackathon_details"]["drillName"] = message
                session_data.update({"current_question": "phaseStartDt"})
                return SessionResponse(
                    session_id=session_id,
                    message=f"Great! Your event name is set to {message}. When do you want to organize it?",
                    current_question="phaseStartDt",
                )

        elif current_question == "phaseStartDt":
            parsed_date = date_handler.parse_date_string(message)

            if parsed_date is None:
                return SessionResponse(
                    session_id=session_id,
                    message="I couldn't understand that date format. Please provide a date in DD-MM-YYYY format.",
                    current_question="phaseStartDt",
                )

            formatted_date = parsed_date.strftime("%d-%m-%Y")

            is_valid, transformed_date, error_message = date_handler.validate_date(
                formatted_date
            )
            if not is_valid:
                return SessionResponse(
                    session_id=session_id,
                    message=error_message,
                    current_question="phaseStartDt",
                )

            phase_dates = date_handler.get_phase_dates(transformed_date, "Asia/Kolkata")
            context["hackathon_details"].update(phase_dates)

            return SessionResponse(
                session_id=session_id,
                message="Do you want submissions based on specific themes or solutions to problems? (Problems Based or Theme Based)",
                current_question="drillType",
            )

        elif current_question == "drillType":
            drill_type = infer_drill_type(message, llm)
            context["hackathon_details"]["drillType"] = drill_type
            return SessionResponse(
                session_id=session_id,
                message="Will this event be paid? (Yes/No)",
                current_question="isDrillPaid",
            )

        elif current_question == "isDrillPaid":
            is_paid = infer_yes_no(message, llm)
            context["hackathon_details"]["isDrillPaid"] = is_paid == "Yes"
            return SessionResponse(
                session_id=session_id,
                message="What is the purpose of this event? (Provide a one-liner answer)",
                current_question="drillPurpose",
            )

        elif current_question == "drillPurpose":
            purpose = infer_purpose(context, message, llm)
            context["hackathon_details"]["drillPurpose"] = purpose

            session_data.update({"current_question": "eligibility"})
            return SessionResponse(
                session_id=session_id,
                message="Who can participate in this event? (Options: Graduate, College Students, Working Professionals)",
                current_question="eligibility",
            )

        elif current_question == "eligibility":
            eligibility = infer_eligibility(message, llm)
            if not eligibility:
                return SessionResponse(
                    session_id=session_id,
                    message="Could not determine eligibility. Please specify who can participate (Graduate, College Students, Working Professionals)",
                    current_question="eligibility",
                )
            context["hackathon_details"]["eligibility"] = eligibility

            session_data.update({"current_question": "hasPartner"})
            return SessionResponse(
                session_id=session_id,
                message="Do you want to add a partner organization for this event? (Yes/No)",
                current_question="hasPartner",
            )

        elif current_question == "hasPartner":
            has_partner = infer_yes_no(message, llm)
            context["has_partner"] = has_partner == "Yes"

            if context["has_partner"]:
                session_data.update({"current_question": "partnerUrl"})
                return SessionResponse(
                    session_id=session_id,
                    message="Please provide the website URL of the partner organization:",
                    current_question="partnerUrl",
                )
            else:
                context["hackathon_details"].update(
                    {
                        "drillPartnerId": "b886470e-52ac-4d34-8621-ff3e4d8335fb",
                        "drillPartnerName": "WUElev8 Innovation services private ltd",
                    }
                )

                try:
                    drill_info = context["hackathon_details"]
                    drill_info["drillDescription"] = generate_drill_description(
                        drill_info, llm
                    )

                    api_payload = prepare_api_payload(drill_info)
                    event_link = register_event(api_payload, drill_info["eligibility"])

                    save_to_database(drill_info, db_handler)
                    session_store.pop(session_id, None)

                    return SessionResponse(
                        session_id=session_id,
                        message="Your event has been successfully registered!",
                        event_link=event_link,
                        registration_complete=True,
                    )
                except Exception as e:
                    print(f"Registration error: {str(e)}")
                    return SessionResponse(
                        session_id=session_id,
                        message=f"An error occurred during registration: {str(e)}",
                        current_question=current_question,
                    )

        elif current_question == "partnerUrl":
            partner_url = message.strip()

            try:
                if not validate_partner_url(partner_url):
                    return SessionResponse(
                        session_id=session_id,
                        message="The provided URL seems to be invalid or inaccessible. Please provide a valid URL.",
                        current_question="partnerUrl",
                    )

                existing_partner = find_partner_by_url(partner_url)

                if existing_partner and "partnerId" in existing_partner:
                    partner_id = existing_partner["partnerId"]
                    partner_name = (
                        existing_partner.get("partnerDisplayName")
                        or existing_partner.get("partnerName")
                        or partner_url.split("/")[2]
                        .replace("www.", "")
                        .split(".")[0]
                        .title()
                    )

                    print(f"Using existing partner: {partner_name} (ID: {partner_id})")
                else:
                    try:
                        partner_info = extract_partner_info(partner_url, llm)

                        partner_response = register_partner(partner_info)

                        if not partner_response or "partnerId" not in partner_response:
                            raise ValueError("Failed to register partner")

                        partner_id = partner_response["partnerId"]
                        partner_name = (
                            partner_response.get("partnerDisplayName")
                            or partner_response.get("partnerName")
                            or partner_url.split("/")[2]
                            .replace("www.", "")
                            .split(".")[0]
                            .title()
                        )

                        print(
                            f"Registered new partner: {partner_name} (ID: {partner_id})"
                        )
                    except Exception as e:
                        print(f"Partner extraction error: {str(e)}")
                        raise ValueError(
                            f"Failed to extract partner information: {str(e)}"
                        )

                context["hackathon_details"].update(
                    {"drillPartnerId": partner_id, "drillPartnerName": partner_name}
                )

                drill_info = context["hackathon_details"]
                drill_info["drillDescription"] = generate_drill_description(
                    drill_info, llm
                )

                api_payload = prepare_api_payload(drill_info)
                event_link = register_event(api_payload, drill_info["eligibility"])

                save_to_database(drill_info, db_handler)
                session_store.pop(session_id, None)

                return SessionResponse(
                    session_id=session_id,
                    message=f"Event successfully registered with partner {partner_name}!",
                    event_link=event_link,
                    registration_complete=True,
                )

            except Exception as e:
                print(f"Partner registration error: {str(e)}")
                return SessionResponse(
                    session_id=session_id,
                    message="There was an issue with the partner registration. Please try again with a different URL.",
                    current_question="partnerUrl",
                )

    except Exception as e:
        print(f"Chat endpoint error: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/sessions/{session_id}/status")
async def get_session_status(session_id: str): 
    """Get the current status of a session."""
    if session_id not in session_store:
        raise HTTPException(status_code=404, detail="Session not found")
    return session_store[session_id]


@app.delete("/sessions/{session_id}")
async def clear_session(session_id: str):
    """Clear a session from memory."""
    if session_id in session_store:
        session_store.pop(session_id)
    return {"message": "Session cleared"}