Datasets:
CZLC
/

Modalities:
Text
Formats:
json
Languages:
Czech
Libraries:
Datasets
pandas
License:
CNC_skript12 / convert_AKCES.py
mfajcik's picture
Upload 2 files
8d80dc0 verified
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()