scriptinghelpers-archive / data_to_parquet.py
densenet's picture
Upload folder using huggingface_hub
7febd01 verified
Raw
History Blame Contribute Delete
4.68 kB
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
import sys
import json
import time
from questions_tar_extract import extract_articles
from brute import prepare_with_ripgrep
file_structure_schema = pa.schema([
('path', pa.string()),
('content', pa.large_string())
])
extracted_schema = pa.schema([
('question_score', pa.string()),
('title', pa.string()),
('question_userid', pa.string()),
('question_user', pa.string()),
('question_user_score', pa.string()),
('question_datetime', pa.string()),
('question', pa.string()),
('question_id', pa.string()),
('answer_count', pa.string()),
('answer_id', pa.string()),
('answer_score', pa.string()),
('answer_userid', pa.string()),
('answer_user', pa.string()),
('answer_user_score', pa.string()),
('answer_datetime', pa.string()),
('answer', pa.string())
])
extracted_src_key_order = ["qscore","title","quserid","quser","quserscore","qdatetime","question","qid","answercount","aid","ascore","auserid","auser","auserscore","adatetime","answer"]
script_dir = Path(__file__).resolve().parent
if __name__ == '__main__':
articles = extract_articles()
scraped_files_root = articles.name + "_raw"
article_pq_inputs = [[],[]]
for a in articles.iterdir():
a = next(next(a.iterdir()).iterdir())
with open(a, "r") as f:
content = f.read()
article_pq_inputs[0].append(str(a))
article_pq_inputs[1].append(content)
article_table = pa.Table.from_arrays(article_pq_inputs, schema=file_structure_schema)
pq.write_table(article_table, f"{scraped_files_root}.snappy.parquet", compression='Snappy')
article_pq_file = Path(f"{scraped_files_root}.snappy.parquet")
print(f"wrote to cwd: {scraped_files_root}.snappy.parquet ({article_pq_file.stat().st_size / (1024 * 1024):.2f} MiB)")
extract_file_path = script_dir / "data.jsonl"
extract_pq_inputs: list[dict[str, str]] | list[list[str]] | None = None
if not extract_file_path.is_file():
try:
rem_attempts = 2
while rem_attempts > 0:
user_input = input(f"extracted data not found at {extract_file_path}. run extraction (need ripgrep)? [y/N] ").strip().lower()
if not user_input or user_input in ['n', 'no']:
print("warning: parquet conversion only partially completed because extracted data could not be prepared.")
sys.exit(0)
elif user_input in ['y', 'yes']:
chunk_array = prepare_with_ripgrep()
with open(script_dir / "data.jsonl", 'w', encoding='utf-8') as f:
f.write("\n".join(chunk_array))
extract_pq_inputs = list(map(json.loads, chunk_array))
break
else:
print(f"warning: unknown response '{user_input if len(user_input) < 4 else f"{user_input[:3]}..."}'. remaining attempts: {rem_attempts}")
time.sleep(0.5)
rem_attempts -= 1
if rem_attempts == 0:
print("fatal: failed to move on after a few attempts")
sys.exit(1)
except KeyboardInterrupt:
print("fatal: received KeyboardInterrupt")
sys.exit(1)
else:
with open(extract_file_path, 'r', encoding='utf-8') as f:
extract_pq_inputs = list(map(json.loads, f))
assert extract_pq_inputs is not None
_extract_pq_inputs = [[] for k in extracted_src_key_order]
for j, k_j in enumerate(extracted_src_key_order):
for i in range(len(extract_pq_inputs)):
_extract_pq_inputs[j].append(extract_pq_inputs[i][k_j])
extract_pq_inputs = _extract_pq_inputs
extract_table = pa.Table.from_arrays(extract_pq_inputs, schema=extracted_schema)
pq.write_table(extract_table, "data.snappy.parquet", compression='Snappy')
extract_pq_file = Path("data.snappy.parquet")
print(f"wrote to cwd: data.snappy.parquet ({extract_pq_file.stat().st_size / (1024 * 1024):.2f} MiB)")