| import argparse | |
| import os | |
| import json | |
| 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 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')): | |
| raise FileNotFoundError('intro.txt or qa.txt not found in the given directory') | |
| if not verify_file(os.path.join(directory, 'qa.txt')): | |
| raise ValueError('qa.txt is not in the correct format') | |
| 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(os.path.join(directory, output_filename), 'w', encoding='utf-8') as jsonl_file: | |
| for message in messages: | |
| jsonl_file.write(json.dumps({'messages': message}) + '\n') | |
| def main(): | |
| 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__': | |
| main() |