densenet's picture
Upload folder using huggingface_hub
7febd01 verified
Raw
History Blame Contribute Delete
2.7 kB
import re
from re import Match
import subprocess
from tqdm import tqdm
from questions_tar_extract import extract_articles
import shutil
import os
from pathlib import Path
import stat
blockregex = re.compile(r'<<<(.*?)<<<', flags=re.MULTILINE | re.DOTALL)
tr = str.maketrans({
"\"": "\\\"",
"\\": "\\\\",
"\n": "\\n"
})
def render_block(mo: Match) -> str:
block = mo.group(1)
block = block.translate(tr)
return f'"{block}"'
def prepare_with_ripgrep() -> list[str]:
articles = extract_articles()
pbar = tqdm(total=5129, desc="Extracting and formatting scriptinghelpers posts")
rg_exec: str | None = None
if 'RIPGREP_PATH' in os.environ:
rg_exec_p = Path(os.path.normpath(os.environ['RIPGREP_PATH'].strip()))
if rg_exec_p.is_dir():
rg_exec = shutil.which("rg", path=rg_exec_p)
else:
rg_exec_mode = rg_exec_p.stat().st_mode
if bool(rg_exec_mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)):
rg_exec = str(rg_exec_p)
else:
rg_exec = shutil.which("rg")
if rg_exec is None:
raise RuntimeError(f"ripgrep executable `{rg_exec}` is not installed or not visible in this environment")
process = subprocess.Popen([rg_exec, "-U", "-uuu", "-o", "--multiline-dotall", "-N", "--color=never", "-I", "-f", "qa_regex4.txt", str(articles),
"-r", """{"qscore": "$1", "title": "$2", "quserid": "$3", "quser": "$4", "quserscore": "$5", "qdatetime": "$6", "question": <<<$7<<<, "qid": "$8", "answercount": "$9", "aid": "$10", "ascore": "$11", "auserid": "$12", "auser": "$13", "auserscore": "$14", "adatetime": "$15", "answer": <<<$16<<<}"""], stdout=subprocess.PIPE, text=True, bufsize=1)
chunk_array = []
latest_chunk_part = []
while True:
line = process.stdout.readline()
if not line:
break
line = line.rstrip()
if line[-4:] == '<<<}':
latest_chunk = line if len(latest_chunk_part) == 0 else "\n".join(latest_chunk_part) + f"\n{line}"
latest_chunk = blockregex.sub(render_block, latest_chunk)
chunk_array.append(latest_chunk)
latest_chunk_part.clear()
pbar.update(1)
else:
latest_chunk_part.append(line)
pbar.total = len(chunk_array)
pbar.refresh()
pbar.close()
return chunk_array
if __name__=='__main__':
chunk_array = "\n".join(prepare_with_ripgrep())
with open('data.jsonl', 'w') as f:
f.write(chunk_array)
# with open('extract5.txt', 'w') as f:
# f.write(f'[{",\n".join(chunk_array)}]')