File size: 3,789 Bytes
2a1ec59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
import json
import sys

def generate_student_answers(record_file, data_df, output_file):
    """
    Generates an answer JSONL file from a record file and a student data DataFrame.

    Args:
        record_file (str): The path to the record_file.jsonl.
        data_df (pd.DataFrame): The DataFrame containing student data.
        output_file (str): The name for the output JSONL file.
    """
    
    # Step 1: Read all valid question_ids from the record file
    print(f"Reading question IDs from '{record_file}'...")
    try:
        with open(record_file, 'r', encoding='utf-8') as f:
            # Use a set for efficient lookup
            valid_question_ids = {json.loads(line)['question_id'] for line in f}
        print(f"Found {len(valid_question_ids)} valid question IDs.")
    except FileNotFoundError:
        print(f"Error: The file '{record_file}' was not found. Please check the path.")
        sys.exit(1)
    except (json.JSONDecodeError, KeyError):
        print(f"Error: The file '{record_file}' is not a valid JSONL or is missing 'question_id' keys.")
        sys.exit(1)

    # Step 2: Identify the columns to process in the DataFrame
    student_id_col = 'STU_ID'
    if student_id_col not in data_df.columns:
        print(f"Error: The required student identifier column '{student_id_col}' was not found in the DataFrame.")
        sys.exit(1)

    # Get the intersection of DataFrame columns and valid question IDs
    columns_to_process = [col for col in data_df.columns if col in valid_question_ids]
    print(f"Will process {len(columns_to_process)} question columns found in the DataFrame.")
    
    # Step 3: Iterate through each row of the DataFrame and write to the JSONL file
    print(f"Generating answer file '{output_file}'...")
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            # Using to_dict('records') is an efficient way to iterate over rows
            for record in data_df.to_dict('records'):
                student_answer = {
                    # Add the student ID
                    'student_id': record.get(student_id_col)
                }
                
                # Add the answers for all relevant questions
                for col_name in columns_to_process:
                    student_answer[col_name] = record.get(col_name)
                
                # Write the student's complete answer dictionary to the file
                f.write(json.dumps(student_answer, ensure_ascii=False) + '\n')
    except IOError:
        print(f"Error: Could not write to file '{output_file}'. Check permissions or path.")
        sys.exit(1)
            
    print(f"\n✅ Success! Processing is complete.")
    print(f"Generated records for {len(data_df)} students in '{output_file}'.")


if __name__ == '__main__':
    # --- Configuration ---
    # 1. Record file (codebook) path
    record_filename = "record_file.jsonl"

    # 2. Raw student data file path
    data_filename = "hsls_17_student_pets_sr_v1_0.csv"

    # 3. Desired name for the final output file
    output_filename = "student_answers.jsonl"
    
    # --- Load Data ---
    print(f"Loading data from '{data_filename}'...")
    try:
        # Using the CSV reader for your specified file
        data = pd.read_csv(data_filename)
        
        print(f"Successfully loaded {len(data)} rows and {len(data.columns)} columns.")
    except FileNotFoundError:
        print(f"Error: The data file '{data_filename}' was not found. Make sure it's in the same directory.")
        sys.exit(1)
    except Exception as e:
        print(f"An error occurred while loading the data: {e}")
        sys.exit(1)
        
    # --- Run the main function ---
    generate_student_answers(record_filename, data, output_filename)