Datasets:
CZLC
/

Modalities:
Text
Formats:
json
Languages:
Czech
Libraries:
Datasets
pandas
License:
File size: 2,548 Bytes
8d80dc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import re
import subprocess
from docx import Document

FILE_PATH = ".data/AKCES/AKCES 1/kontroly-RTF/"
OUTPUT_FILE = ".data/hf_dataset/cnc_skript2012/test.jsonl"


def convert_to_docx(file_path):
    """Convert a given file to DOCX using LibreOffice."""
    new_file_path = file_path + 'x'
    command = ['libreoffice', '--headless', '--convert-to', 'docx', '--outdir', os.path.dirname(file_path), file_path]
    subprocess.run(command, check=True)
    return new_file_path


def read_docx_file(file_path):
    """Extract text from a DOCX file."""
    doc = Document(file_path)
    text = "\n".join([para.text for para in doc.paragraphs])
    return text


def main():
    # Step 1: Convert all RTF and DOC files to DOCX
    for root, dirs, files in os.walk(FILE_PATH):
        for file in files:
            file_path = os.path.join(root, file)
            if file.endswith('.rtf') or file.endswith('.doc'):
                # if the docx file already exists, skip the conversion
                docx_file_path = file_path[:-3] + 'docx'
                if os.path.exists(docx_file_path):
                    continue
                try:
                    convert_to_docx(file_path)
                except subprocess.CalledProcessError as e:
                    raise ValueError(f"Error converting {file_path}: {e}")

    # Step 2: Process all DOCX files to extract text
    output_data = []
    for root, dirs, files in os.walk(FILE_PATH):
        for file in files:
            file_path = os.path.join(root, file)
            if file.endswith('.docx'):
                try:
                    text = read_docx_file(file_path)

                    # postprocessing
                    text = text.replace("\xa0", " ")
                    text = text.replace("\n \n", "\n\n")
                    text = re.sub(r' +\n', '\n', text)
                    text = re.sub(r' +', ' ', text)
                    text = text.strip()

                    output_data.append({
                        "text": text,
                        "original_file": file[:-5],  # remove the extension
                    })
                except Exception as e:
                    print(f"Error reading {file_path}: {e}")

    os.makedirs(os.path.dirname(OUTPUT_FILE), exist_ok=True)
    # Write the output data to a JSONL file
    with open(OUTPUT_FILE, 'w', encoding='utf-8') as jsonl_file:
        for entry in output_data:
            jsonl_file.write(json.dumps(entry, ensure_ascii=False) + '\n')


if __name__ == "__main__":
    main()