File size: 2,091 Bytes
7402d25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os, orjson
import re

cur_dir = os.path.dirname(os.path.abspath(__file__))

txt_dir = cur_dir + "/text"

# read folder names in /txt
categories = os.listdir(txt_dir)

def parse_speech(text):
    # This pattern matches speaker tags and extracts ID and NAME attributes
    speaker_pattern = re.compile(r'<SPEAKER ID=\"\d+\" NAME=\"(.*?)\"')
    # Initialize variables
    output = []
    speaker_name = ""

    for line in text.split('\n'):
        # Check for speaker tag
        if '<SPEAKER' in line:
            # Extract speaker name
            match = speaker_pattern.search(line)
            if match:
                speaker_name = match.group(1)
        # Check for paragraph tag or chapter id tag and skip it
        elif '<P>' in line or '<CHAPTER ID=' in line:
            continue
        # Process normal text lines
        else:
            # Append speaker name before the speech if it's not empty
            if speaker_name:
                formatted_line = f"\n{speaker_name}: {line}"
                # Reset speaker name to avoid repeating it for subsequent lines of the same speaker
                speaker_name = ""
            else:
                formatted_line = line
            output.append(formatted_line)

    return "\n".join(output)

for category in categories:
    # list txt files in each folder
    files = os.listdir(txt_dir + category)
    
    jsonl_docs = []
    for file in files:
        # read each txt file
        with open(txt_dir + category + "/" + file, "r") as f:
            # try to read content
            try:
                content = f.read()
                
                parsed_content = parse_speech(content)
                
                jsonl_docs.append({"text": parsed_content, "lang": category})
            except:
                print("Error reading file:", file)
                continue
            
    # write to jsonl file in jsonl folder
    with open(cur_dir + "/jsonl/" + category + ".jsonl", "wb") as f:
        for doc in jsonl_docs:
            f.write(orjson.dumps(doc) + b"\n")