|
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(): |
|
|
|
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'): |
|
|
|
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}") |
|
|
|
|
|
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) |
|
|
|
|
|
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], |
|
}) |
|
except Exception as e: |
|
print(f"Error reading {file_path}: {e}") |
|
|
|
os.makedirs(os.path.dirname(OUTPUT_FILE), exist_ok=True) |
|
|
|
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() |
|
|