File size: 3,814 Bytes
027bddb
 
f8dc831
 
 
eac488b
 
f8dc831
eac488b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8dc831
 
eac488b
 
 
 
f8dc831
 
eac488b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
027bddb
eac488b
 
 
f8dc831
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eac488b
f8dc831
eac488b
 
027bddb
 
 
 
 
 
 
eac488b
f8dc831
 
 
 
 
 
 
 
 
 
 
 
 
eac488b
f8dc831
eac488b
f8dc831
eac488b
 
f8dc831
eac488b
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
"""Module to generate a JSON Lines file from intro.txt and qa.txt files in a given directory."""

import logging
import os
import json


OUTPUT_DIR = os.path.join('.', 'output')

def generate_jsonlines(directory, output_filename):
    """
    Generate a JSON Lines file from intro.txt and qa.txt files in the given directory.

    Args:
        directory (str): The directory path containing the intro.txt and qa.txt files.
        output_filename (str): The name of the output JSON Lines file to be generated.

    Raises:
        FileNotFoundError: If intro.txt or qa.txt is not found in the given directory.
        ValueError: If qa.txt is not in the correct format.

    """

    if not os.path.exists(os.path.join(directory, 'intro.txt')) or not os.path.exists(os.path.join(directory, 'qa.txt')):
        logging.info("Ignoring %s", directory)
        return

    if not verify_file(os.path.join(directory, 'qa.txt')):
        raise ValueError('qa.txt is not in the correct format')

    logging.info("Processing %s", directory)

    with open(os.path.join(directory, 'intro.txt'), 'r', encoding='utf-8') as intro_file:
        intro_content = intro_file.read().strip()

    messages = []

    with open(os.path.join(directory, 'qa.txt'), 'r', encoding='utf-8') as qa_file:
        lines = qa_file.readlines()

    for line in lines:
        line = line.strip()
        if line.startswith('Q:'):
            question = line[2:].strip()
        elif line.startswith('A:'):
            messages.append([
                {'role': 'system', 'content': intro_content},
                {'role': 'user', 'content': question},
                {'role': 'assistant', 'content': line[2:].strip()}
            ])

    with open(output_filename, 'w', encoding='utf-8') as jsonl_file:
        for message in messages:
            jsonl_file.write(json.dumps({'messages': message}) + '\n')

def verify_file(file_path):
    """
    Verify if the lines in a file have the correct prefix.

    Args:
        file_path (str): The path to the file to be verified.

    Returns:
        bool: True if all lines have the correct prefix, False otherwise.
    """

    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    for i, line in enumerate(lines):
        if i % 2 == 0:
            if not line.startswith('Q:'):
                return False
        else:
            if not line.startswith('A:'):
                return False

    return True

def main():
    """
    Main function to generate JSON Lines files from intro.txt and qa.txt files in the current directory.

    It creates an output directory if it doesn't exist and processes each subdirectory in the current directory.
    For each subdirectory, it generates a JSON Lines file with the same name as the subdirectory.

    """

    os.makedirs(OUTPUT_DIR, exist_ok=True)

    for directory_name in os.listdir('.'):
        directory_path = os.path.join('.', directory_name)
        if os.path.isdir(directory_path) and directory_path != OUTPUT_DIR:
            if os.path.isdir(directory_path):
                output_filename = f"{directory_name}.txt"
                generate_jsonlines(directory_path, os.path.join(OUTPUT_DIR, output_filename))


    # parser = argparse.ArgumentParser(description='Generate a jsonlines file from intro.txt and qa.txt in a given directory.')
    # parser.add_argument('directory', type=str, help='The directory where intro.txt and qa.txt are located.')
    # parser.add_argument('output_filename', type=str, help='The name of the output jsonlines file.')

    # args = parser.parse_args()

    # generate_jsonlines(args.directory, args.output_filename)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
    main()