Question about the last field "latex"
#4
by yangninghua - opened
Question about the last field:
latex
large_string
The parsed, compiled LaTeX source code from the paper. All source files (.tex, .bib, .sty, etc.) are bundled into a single readable Markdown-style tree structure.
How can I restore this to a .tar.gz file or reconstruct it as directories and files?
It would be great to have a .tar version if WebDataset is used for packaging data in the future. That would be much more convenient.
import json
import webdataset as wds
from pathlib import Path
# Ensure output directory exists
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
writer = wds.ShardWriter(
str(output_path / f"arxiv-{subdir_safe}-%06d.tar"),
maxcount=options.shard_maxcount,
verbose=0,
)
# Loop through all samples in your dataset
for sample in dataset:
# 1. Build metadata dictionary
meta_dict = {
"id": sample["id"],
"yymm_id": sample["yymm_id"],
"submitter": sample["submitter"],
"authors": sample["authors"],
"title": sample["title"],
"comments": sample.get("comments", ""),
"journal_ref": sample.get("journal-ref", ""),
"doi": sample.get("doi", ""),
"report_no": sample.get("report-no", ""),
"categories": sample["categories"],
"license": sample.get("license", ""),
"abstract": sample["abstract"],
"update_date": sample["update_date"],
"versions": sample.get("versions", []),
"authors_parsed": sample.get("authors_parsed", []),
}
# 2. Prepare sample data (assuming latex.tar.gz bytes are pre-existing)
sample_data = {
"__key__": sample["id"].replace("/", "_"),
"meta.json": meta_dict,
"latex.txt": sample.get("latex", ""), # Plain text tree structure
"latex.tar.gz": sample.get("latex_tar_gz"), # Pre-compressed archive bytes
}
writer.write(sample_data)
writer.close()
Thanks again for your amazing work for the community. It means a lot to us!
You can use this below code for converting the latex back into tar file.
Still you won't be able to successfully compile the latex, since the images are missing. The dataset only contains text content.
import os
import re
import io
import time
import tarfile
import argparse
def parse_gitingest_content(text):
# Regex to match the header:
# 48 equals signs, a newline, "FILE: <path>", a newline, 48 equals signs, a newline
pattern = re.compile(
r"^={48}\r?\nFILE:\s*(.*?)\r?\n={48}\r?\n",
re.MULTILINE
)
matches = list(pattern.finditer(text))
if not matches:
# Fallback: if the header has minor spacing/format differences
pattern_fallback = re.compile(
r"^=+\r?\nFILE:\s*(.*?)\r?\n=+\r?\n",
re.MULTILINE
)
matches = list(pattern_fallback.finditer(text))
if not matches:
return []
files = []
for i, match in enumerate(matches):
filepath = match.group(1).strip()
start_idx = match.end()
# The content ends where the next match starts, or at the end of the text
if i + 1 < len(matches):
end_idx = matches[i + 1].start()
else:
end_idx = len(text)
content = text[start_idx:end_idx]
# Clean up any trailing newline/spacing that format_gitingest appends
if content.endswith("\n"):
content = content[:-1]
if content.endswith("\r"):
content = content[:-1]
files.append((filepath, content))
return files
def main():
parser = argparse.ArgumentParser(description="Convert gitingest-formatted LaTeX text back to a TAR archive.")
parser.add_argument("--input", default="sample.txt", help="Path to the input text file (default: sample.txt)")
parser.add_argument("--output", default="sample.tar", help="Path to the output TAR file (default: sample.tar)")
args = parser.parse_args()
if not os.path.exists(args.input):
print(f"Error: Input file '{args.input}' not found.")
return
print(f"Reading input file '{args.input}'...")
with open(args.input, "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
print("Parsing gitingest structure...")
extracted_files = parse_gitingest_content(content)
if not extracted_files:
print("Error: No file blocks found in the input text. Please make sure the format matches gitingest output.")
return
print(f"Parsed {len(extracted_files)} files. Packaging into TAR archive '{args.output}'...")
# Determine tar open mode based on output extension (e.g. .tar.gz or .tar)
mode = "w"
if args.output.endswith(".gz"):
mode = "w:gz"
try:
with tarfile.open(args.output, mode) as tar:
for filepath, file_data in extracted_files:
data_bytes = file_data.encode("utf-8")
# Create TarInfo metadata entry
tarinfo = tarfile.TarInfo(name=filepath)
tarinfo.size = len(data_bytes)
tarinfo.mtime = int(time.time())
tarinfo.mode = 0o644 # Read/write for user, read for others
# Package bytes directly into tar
tar.addfile(tarinfo, io.BytesIO(data_bytes))
print(f" + Added: {filepath} ({len(data_bytes)} bytes)")
print(f"\nSUCCESS! Reconstructed TAR archive created successfully: {args.output}")
except Exception as e:
print(f"Error creating TAR archive: {e}")
if __name__ == "__main__":
main()