File size: 2,716 Bytes
3208104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
utils.py
--------
Utility functions for the NORA Admissions Agent project.

Responsibilities:
- parse_response: Safely parse JSON from Gemini’s response
- rank_applicants: Sort applicants by total score
- clean_json_text: Sanitize malformed JSON text (e.g., remove code fences)
"""

import json
from typing import List, Dict

def parse_response(response_text: str) -> Dict:
    """
    Safely parse the JSON output from Gemini.

    The LLM is instructed to return strict JSON, but in case of formatting
    issues (extra text, markdown, etc.), this function attempts to handle errors
    gracefully.

    Parameters
    ----------
    response_text : str
        The raw response text from Gemini.

    Returns
    -------
    dict
        A parsed JSON dictionary, or an error dictionary if parsing fails.

    Example
    -------
    >>> parse_response('{"name": "Anna", "total_score": 9.2}')
    {'name': 'Anna', 'total_score': 9.2}
    """
    # Handle None or empty input
    if response_text is None:
        return {"error": "Could not parse JSON", "raw_response": None}
    
    if not response_text.strip():
        return {"error": "Could not parse JSON", "raw_response": ""}
    
    try:
        return json.loads(response_text)
    except json.JSONDecodeError:
        cleaned = clean_json_text(response_text)
        try:
            return json.loads(cleaned)
        except json.JSONDecodeError:
            return {"error": "Could not parse JSON", "raw_response": response_text}

def rank_applicants(reviews: List[Dict]) -> List[Dict]:
    """
    Rank all applicants based on their total_score from highest to lowest.

    Parameters
    ----------
    reviews : list of dict
        List of applicant review dictionaries with 'total_score' key.

    Returns
    -------
    list of dict
        Sorted list of applicants.

    Example
    -------
    >>> rank_applicants([{"name": "A", "total_score": 8.5}, {"name": "B", "total_score": 9.0}])
    [{'name': 'B', 'total_score': 9.0}, {'name': 'A', 'total_score': 8.5}]
    """
    return sorted(reviews, key=lambda x: x.get("total_score", 0), reverse=True)

def clean_json_text(text: str) -> str:
    """
    Attempt to clean up malformed JSON text by:
    - Removing markdown code fences
    - Stripping extraneous whitespace

    Parameters
    ----------
    text : str
        The raw text from Gemini.

    Returns
    -------
    str
        A cleaned string that is more likely to parse as JSON.
    """
    cleaned = text.strip()
    # Remove triple backticks and 'json' code block indicators if present
    if cleaned.startswith("```"):
        cleaned = cleaned.replace("```json", "").replace("```", "")
    return cleaned.strip()