File size: 14,729 Bytes
a8cac7f
 
 
 
 
 
 
 
 
 
071fe94
a8cac7f
 
 
 
 
 
071fe94
37a62fe
a8cac7f
 
 
 
 
 
 
 
 
 
071fe94
a8cac7f
 
 
 
 
071fe94
a8cac7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
071fe94
a8cac7f
 
071fe94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8cac7f
 
 
 
 
071fe94
 
 
 
 
 
 
 
 
 
 
 
a8cac7f
 
37a62fe
a8cac7f
071fe94
a8cac7f
37a62fe
a8cac7f
 
 
 
071fe94
37a62fe
071fe94
a8cac7f
 
071fe94
 
 
 
 
 
37a62fe
071fe94
a8cac7f
37a62fe
071fe94
a8cac7f
071fe94
a8cac7f
 
071fe94
 
 
 
 
a8cac7f
 
071fe94
a8cac7f
071fe94
a8cac7f
071fe94
 
 
 
 
 
a8cac7f
071fe94
a8cac7f
071fe94
 
 
a8cac7f
071fe94
 
 
 
a8cac7f
071fe94
a8cac7f
37a62fe
071fe94
 
 
 
a8cac7f
 
071fe94
 
 
 
 
a8cac7f
 
 
071fe94
 
 
 
 
 
 
 
 
 
 
a8cac7f
071fe94
 
 
d7318ee
a8cac7f
071fe94
a8cac7f
071fe94
 
 
 
 
 
 
 
 
a8cac7f
 
 
071fe94
 
 
 
 
 
 
 
 
 
 
 
 
 
a8cac7f
 
071fe94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8cac7f
071fe94
a8cac7f
071fe94
 
 
 
 
 
 
 
 
a8cac7f
071fe94
a8cac7f
071fe94
a8cac7f
071fe94
 
 
 
 
 
a8cac7f
 
071fe94
a8cac7f
 
 
071fe94
 
 
 
 
 
 
 
 
 
a8cac7f
071fe94
 
a8cac7f
071fe94
 
a8cac7f
 
071fe94
 
 
 
 
 
 
 
 
 
 
a8cac7f
071fe94
 
 
 
 
 
 
d7318ee
071fe94
a8cac7f
d7318ee
a8cac7f
 
 
071fe94
a8cac7f
 
071fe94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7318ee
 
071fe94
 
 
 
 
37a62fe
071fe94
a8cac7f
071fe94
37a62fe
071fe94
a8cac7f
071fe94
a8cac7f
071fe94
 
 
 
a8cac7f
071fe94
 
a8cac7f
 
071fe94
 
 
37a62fe
071fe94
a8cac7f
37a62fe
071fe94
37a62fe
071fe94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8cac7f
37a62fe
071fe94
a8cac7f
071fe94
 
 
 
a8cac7f
071fe94
 
 
 
 
 
 
 
 
d7318ee
 
071fe94
d7318ee
071fe94
d7318ee
071fe94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7318ee
071fe94
d7318ee
071fe94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7318ee
 
 
 
071fe94
 
 
 
 
 
 
 
a8cac7f
071fe94
 
 
 
a8cac7f
071fe94
a8cac7f
 
071fe94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8cac7f
071fe94
 
 
a8cac7f
 
071fe94
 
 
 
 
a8cac7f
 
 
071fe94
 
 
 
 
a8cac7f
071fe94
 
 
a8cac7f
071fe94
a8cac7f
071fe94
 
 
 
 
 
 
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
# =========================================
# 1. IMPORTS
# =========================================
import asyncio
import os
import json
import uuid
import cloudinary
import cloudinary.uploader
import firebase_admin

from firebase_admin import credentials, firestore
from fastapi import FastAPI, HTTPException, BackgroundTasks
from pydantic import BaseModel
from gradio_client import Client
from google.cloud.firestore_v1.base_query import FieldFilter
import edge_tts

from typing import Optional, List
from dotenv import load_dotenv
from contextlib import asynccontextmanager

# =========================================
# 2. INITIALIZATIONS & CONFIG
# =========================================
load_dotenv()

if not firebase_admin._apps:
    fb_json = os.getenv("FIREBASE_JSON")

    if fb_json:
        cred_dict = json.loads(fb_json)
        cred = credentials.Certificate(cred_dict)
    else:
        cred = credentials.Certificate("serviceAccountKey.json")

    firebase_admin.initialize_app(cred)

db = firestore.client()

cloudinary.config(
    cloud_name=os.getenv("CLOUD_NAME"),
    api_key=os.getenv("API_KEY"),
    api_secret=os.getenv("API_SECRET"),
    secure=True
)

HF_SPACE = "Fayza38/Question_and_answer_model"
client = None

# =========================================
# 3. CONSTANTS & MODELS
# =========================================
TECH_CATEGORIES = {
    0: "Security",
    1: "BackEnd",
    2: "Networking",
    3: "FrontEnd",
    4: "DataEngineering",
    5: "WebDevelopment",
    6: "FullStack",
    7: "VersionControl",
    8: "SystemDesign",
    9: "MachineLearning",
    10: "LanguagesAndFrameworks",
    11: "DatabaseSystems",
    12: "ArtificialIntelligence",
    13: "SoftwareTesting",
    14: "DistributedSystems",
    15: "DevOps",
    16: "LowLevelSystems",
    17: "DatabaseAndSql",
    18: "GeneralProgramming",
    19: "DataStructures",
    20: "Algorithms"
}

DIFFICULTY_MAP = {
    0: "Easy",
    1: "Intermediate",
    2: "Hard"
}


class GenerateSessionRequest(BaseModel):
    sessionId: str

    # 0 = Behavioral
    # 1 = Technical
    sessionType: int

    # IMPORTANT:
    # difficultyLevel is ONLY used for technical sessions
    difficultyLevel: Optional[int] = None

    # ONLY required for technical sessions
    trackName: Optional[int] = None


class CleanupRequest(BaseModel):
    audioUrls: List[str]


# =========================================
# 4. LIFESPAN MANAGEMENT
# =========================================
@asynccontextmanager
async def lifespan(app: FastAPI):
    global client

    print("Connecting to Hugging Face Model...")

    try:
        loop = asyncio.get_event_loop()

        client = await loop.run_in_executor(
            None,
            lambda: Client(HF_SPACE)
        )

        print("Model Connected Successfully!")

    except Exception as e:
        print(f"Model Connection Failed: {e}")

    yield

    print("Shutting down Intervision Service...")


app = FastAPI(
    title="Intervision AI Question Service",
    lifespan=lifespan
)

# =========================================
# 5. HELPER FUNCTIONS
# =========================================
async def generate_audio(text: str, filename: str):
    try:
        communicate = edge_tts.Communicate(
            text,
            "en-US-GuyNeural",
            rate="-15%"
        )

        await communicate.save(filename)

        upload_result = cloudinary.uploader.upload(
            filename,
            resource_type="video",
            folder="interview_audio"
        )

        if os.path.exists(filename):
            os.remove(filename)

        return upload_result["secure_url"]

    except Exception as e:
        print(f"Audio Generation Error: {e}")

        if os.path.exists(filename):
            os.remove(filename)

        return None


async def safe_generate(prompt: str, retries: int = 5):
    if client is None:
        raise Exception("AI Client is not initialized.")

    for attempt in range(retries):
        try:
            loop = asyncio.get_running_loop()

            result = await loop.run_in_executor(
                None,
                lambda: client.predict(
                    prompt=prompt,
                    api_name="/generate_questions"
                )
            )

            return result

        except Exception as e:
            if attempt == retries - 1:
                raise e

            await asyncio.sleep(5)


def parse_question_output(raw_output: str):
    if not raw_output:
        return None, None

    text = (
        raw_output.split("assistant")[-1].strip()
        if "assistant" in raw_output
        else raw_output
    )

    if "Q:" in text and "A:" in text:
        try:
            parts = text.split("A:")

            question = parts[0].replace("Q:", "").strip()

            answer = (
                parts[1]
                .split("<|im_end|>")[0]
                .strip()
            )

            return question, answer

        except Exception:
            return None, None

    return None, None


# =========================================
# 6. REFILL QUESTION POOLS
# =========================================
async def refill_specific_pool(
    track_id: Optional[int],
    difficulty: Optional[int],
    count: int,
    session_type: int
):
    while client is None:
        await asyncio.sleep(5)

    # =====================================
    # Behavioral Questions
    # =====================================
    if session_type == 0:

        track_text = "Behavioral"

        prompt = (
            "Generate ONE unique behavioral interview question. "
            "Format: Q: [Question] A: [Answer]"
        )

    # =====================================
    # Technical Questions
    # =====================================
    else:

        track_text = TECH_CATEGORIES.get(track_id)

        level_text = DIFFICULTY_MAP.get(difficulty)

        prompt = (
            f"Generate ONE unique {track_text} "
            f"question for {level_text} level. "
            f"Format: Q: [Question] A: [Answer]"
        )

    success_count = 0

    while success_count < count:
        try:
            raw_output = await safe_generate(prompt)

            question, answer = parse_question_output(raw_output)

            if question and answer:

                audio_url = await generate_audio(
                    question,
                    f"{uuid.uuid4()}.mp3"
                )

                if audio_url:

                    question_data = {
                        "session_type": session_type,
                        "questionText": question,
                        "questionIdealAnswer": answer,
                        "audio_url": audio_url,
                        "created_at": firestore.SERVER_TIMESTAMP
                    }

                    # =================================
                    # Technical ONLY
                    # =================================
                    if session_type == 1:
                        question_data["track_id"] = track_id
                        question_data["difficulty"] = difficulty

                    db.collection("questions_pool").add(question_data)

                    success_count += 1

                    print(
                        f"Successfully added "
                        f"{track_text} question "
                        f"{success_count}/{count}"
                    )

                    await asyncio.sleep(2)

        except Exception as e:
            print(f"Refill error: {e}")
            await asyncio.sleep(5)

# =========================================
# 7. API ENDPOINTS
# =========================================
@app.post("/generate-session")
async def generate_session(
    request: GenerateSessionRequest,
    background_tasks: BackgroundTasks
):
    session_type = request.sessionType
    track_id = request.trackName

    # =====================================
    # Behavioral Session
    # =====================================
    if session_type == 0:

        query = db.collection("questions_pool").where(
            filter=FieldFilter("session_type", "==", 0)
        )

    # =====================================
    # Technical Session
    # =====================================
    elif session_type == 1:

        if track_id is None:
            raise HTTPException(
                status_code=400,
                detail="trackName is required for technical sessions."
            )

        if request.difficultyLevel is None:
            raise HTTPException(
                status_code=400,
                detail="difficultyLevel is required for technical sessions."
            )

        difficulty = request.difficultyLevel

        query = (
            db.collection("questions_pool")
            .where(filter=FieldFilter("session_type", "==", 1))
            .where(filter=FieldFilter("track_id", "==", track_id))
            .where(filter=FieldFilter("difficulty", "==", difficulty))
        )

    else:
        raise HTTPException(
            status_code=400,
            detail="Invalid sessionType."
        )

    docs = query.limit(10).get()

    final_questions = []

    for index, doc in enumerate(docs, start=1):

        data = doc.to_dict()

        final_questions.append({
            "question_id": index,
            "text": data["questionText"],
            "expected_answer": data["questionIdealAnswer"],
            "audio_url": data.get("audio_url", "")
        })

        # remove used question
        db.collection("questions_pool").document(doc.id).delete()

    # =====================================
    # BACKGROUND REFILL
    # =====================================
    async def check_and_refill_background():

        snap = query.count().get()
        current_count = snap[0][0].value

        if current_count < 50:

            if session_type == 0:

                print(
                    f"Behavioral stock low "
                    f"({current_count}) -> refilling..."
                )

                await refill_specific_pool(
                    track_id=None,
                    difficulty=None,
                    count=50 - current_count,
                    session_type=0
                )

            else:

                print(
                    f"{TECH_CATEGORIES[track_id]} stock low "
                    f"({current_count}) -> refilling..."
                )

                await refill_specific_pool(
                    track_id=track_id,
                    difficulty=difficulty,
                    count=50 - current_count,
                    session_type=1
                )

    background_tasks.add_task(check_and_refill_background)

    if not final_questions:
        raise HTTPException(
            status_code=503,
            detail="The question pool is empty. Please try again in a few minutes."
        )

    return {
        "session_id": request.sessionId,
        "questions": final_questions
    }


# =========================================
# 8. ADMIN PREFILL
# =========================================
@app.get("/admin/prefill-all")
async def prefill_all(background_tasks: BackgroundTasks):

    async def run_sync():

        print("Starting Global Smart Prefill...")

        # =================================
        # Behavioral Questions
        # =================================
        behavioral_query = (
            db.collection("questions_pool")
            .where(filter=FieldFilter("session_type", "==", 0))
        )

        behavioral_snap = behavioral_query.count().get()

        behavioral_count = behavioral_snap[0][0].value

        if behavioral_count < 50:

            needed = 50 - behavioral_count

            print(f"Syncing Behavioral: adding {needed}")

            await refill_specific_pool(
                track_id=None,
                difficulty=None,
                count=needed,
                session_type=0
            )

        # =================================
        # Technical Questions
        # =================================
        for track_id, track_name in TECH_CATEGORIES.items():

            for diff_id, diff_name in DIFFICULTY_MAP.items():

                technical_query = (
                    db.collection("questions_pool")
                    .where(filter=FieldFilter("session_type", "==", 1))
                    .where(filter=FieldFilter("track_id", "==", track_id))
                    .where(filter=FieldFilter("difficulty", "==", diff_id))
                )

                snap = technical_query.count().get()

                current = snap[0][0].value

                if current < 50:

                    needed = 50 - current

                    print(
                        f"Syncing {track_name} "
                        f"({diff_name}): adding {needed}"
                    )

                    await refill_specific_pool(
                        track_id=track_id,
                        difficulty=diff_id,
                        count=needed,
                        session_type=1
                    )

        print("Global Smart Prefill Completed!")

    background_tasks.add_task(run_sync)

    return {
        "message": "Global prefill process started in the background."
    }


# =========================================
# 9. CLEANUP AUDIO
# =========================================
@app.post("/cleanup-audio")
async def cleanup_audio(
    request: CleanupRequest,
    background_tasks: BackgroundTasks
):
    def delete_job(urls):

        for url in urls:
            try:
                public_id = (
                    "interview_audio/"
                    + url.split("/")[-1].split(".")[0]
                )

                cloudinary.uploader.destroy(
                    public_id,
                    resource_type="video"
                )

            except Exception:
                pass

    background_tasks.add_task(
        delete_job,
        request.audioUrls
    )

    return {
        "message": "Cloudinary cleanup process initiated."
    }


# =========================================
# 10. HEALTH CHECK
# =========================================
@app.get("/health")
async def health():
    return {
        "status": "active",
        "ai_model_connected": client is not None
    }


@app.get("/")
async def root():
    return {
        "app": "Intervision AI Engine",
        "status": "Running"
    }


# =========================================
# 11. RUN SERVER
# =========================================
if __name__ == "__main__":

    import uvicorn

    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True
    )