Document Comparison Part 2
This part contains the four scripts referenced throughout Part 1. They're fixed, tested, and meant to be reused unchanged for every run of this workflow — you don't edit them, and no AI is involved in what they do. Each one handles a purely mechanical step: reading a file, stacking tables together, splitting a large table, or formatting a spreadsheet.
Save all four into a scripts/ folder inside your workspace, as
described in Part 1.
extract_reader.py
Purpose: Reads a single document (PDF, PowerPoint, Word, or Excel)
and prints its text content to the terminal, with a location marker
before each chunk (e.g. [LOCATION: slide 3] or
[LOCATION: Sheet1, row 5]) so every piece of text can be traced back
to exactly where it came from. It does not interpret or classify
anything — that's done afterward by Cline, reading this script's output.
#!/usr/bin/env python3
"""
extract_reader.py — Mechanical text extraction, no interpretation.
Reads ONE file (.pptx, .docx, .xlsx, .pdf) and prints its text content to
stdout, with a "[LOCATION: ...]" marker before each chunk so a human or an
AI reading the output afterward can trace every piece of text back to
exactly where it came from in the source file.
This script does NOT classify, summarize, or interpret anything — that is
a separate, later step (done by an AI reading this script's output).
Usage:
python3 extract_reader.py <path-to-file>
Supported file types (by extension): .pptx, .docx, .xlsx, .pdf
No external document-conversion tools (libreoffice, unoconv, pandoc) are
required. .pptx and .docx are read directly as ZIP archives using only the
Python standard library. .xlsx uses openpyxl. .pdf uses pdfplumber.
Location marker formats:
PPTX: [LOCATION: slide 3]
DOCX: [LOCATION: paragraph 12]
XLSX: [LOCATION: Sheet1, row 5]
PDF: [LOCATION: page 4]
The very first line of output is always:
[SOURCE FILE: <exact filename, as it exists on disk>]
This is the authoritative filename for this run. Anything reading this
script's output should copy that value verbatim into a "file" column,
rather than retyping the filename from the path used to invoke the
script — retyping is error-prone (e.g. "C&A" vs "CA") and causes the same
physical file to appear as two different sources downstream.
"""
import sys
import os
import zipfile
import re
from xml.etree import ElementTree as ET
DRAWINGML_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
WORDML_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
def die(message: str) -> None:
print(f"ERROR: {message}", file=sys.stderr)
sys.exit(1)
def extract_pptx(path: str) -> None:
"""Read a .pptx (a ZIP archive) and print text per slide, in slide order."""
try:
with zipfile.ZipFile(path) as z:
slide_files = [
n for n in z.namelist()
if re.match(r"ppt/slides/slide\d+\.xml$", n)
]
slide_files.sort(key=lambda n: int(re.search(r"(\d+)", n).group(1)))
if not slide_files:
die(f"No slides found inside {path} — is this really a .pptx file?")
for slide_file in slide_files:
slide_num = int(re.search(r"slide(\d+)\.xml", slide_file).group(1))
try:
root = ET.fromstring(z.read(slide_file))
except ET.ParseError as e:
print(f"[LOCATION: slide {slide_num}]")
print(f"[EXTRACTION ERROR on this slide: {e}]\n")
continue
lines = []
for para in root.iter(f"{{{DRAWINGML_NS}}}p"):
parts = [
t.text.strip()
for t in para.iter(f"{{{DRAWINGML_NS}}}t")
if t.text and t.text.strip()
]
if parts:
lines.append(" ".join(parts))
if lines:
print(f"[LOCATION: slide {slide_num}]")
print("\n".join(lines))
print()
except zipfile.BadZipFile:
die(f"{path} is not a valid ZIP archive — a .pptx file should be one internally.")
def extract_docx(path: str) -> None:
"""Read a .docx (a ZIP archive) and print text per paragraph."""
try:
with zipfile.ZipFile(path) as z:
if "word/document.xml" not in z.namelist():
die(f"No word/document.xml found inside {path} — is this really a .docx file?")
root = ET.fromstring(z.read("word/document.xml"))
except zipfile.BadZipFile:
die(f"{path} is not a valid ZIP archive — a .docx file should be one internally.")
para_num = 0
for para in root.iter(f"{{{WORDML_NS}}}p"):
parts = [
t.text.strip()
for t in para.iter(f"{{{WORDML_NS}}}t")
if t.text and t.text.strip()
]
if parts:
para_num += 1
print(f"[LOCATION: paragraph {para_num}]")
print(" ".join(parts))
print()
def extract_xlsx(path: str) -> None:
"""Read an .xlsx and print text per sheet, one location marker per row."""
try:
import openpyxl
except ImportError:
die("openpyxl is required to read .xlsx files. Install with: "
"pip install openpyxl --break-system-packages")
try:
wb = openpyxl.load_workbook(path, data_only=True)
except Exception as e:
die(f"Could not open {path} as an Excel workbook: {e}")
for sheet_name in wb.sheetnames:
ws = wb[sheet_name]
for row_idx, row in enumerate(
ws.iter_rows(min_row=1, max_row=ws.max_row, values_only=True), start=1
):
values = [str(v).strip() for v in row if v is not None and str(v).strip()]
if values:
print(f"[LOCATION: {sheet_name}, row {row_idx}]")
print(" | ".join(values))
print()
def extract_pdf(path: str) -> None:
"""Read a .pdf and print text per page."""
try:
import pdfplumber
except ImportError:
die("pdfplumber is required to read .pdf files. Install with: "
"pip install pdfplumber --break-system-packages")
try:
with pdfplumber.open(path) as pdf:
if not pdf.pages:
die(f"{path} has no pages, or could not be read as a PDF.")
for page_num, page in enumerate(pdf.pages, start=1):
text = page.extract_text() or ""
text = text.strip()
if text:
print(f"[LOCATION: page {page_num}]")
print(text)
print()
except Exception as e:
die(f"Could not open {path} as a PDF: {e}")
def main() -> None:
if len(sys.argv) != 2:
die("Usage: python3 extract_reader.py <path-to-file>")
path = sys.argv[1]
if not os.path.isfile(path):
die(f"File not found: {path}")
# Print the real, on-disk filename as the very first line, before any
# content. This is the single source of truth for "which file was this."
# Downstream steps (classification) must copy this value verbatim into
# their "file" column instead of retyping the filename from the path
# they were given — retyping is what caused the same file to end up
# labeled two different ways across two separate runs.
print(f"[SOURCE FILE: {os.path.basename(path)}]")
print()
ext = os.path.splitext(path)[1].lower()
if ext == ".pptx":
extract_pptx(path)
elif ext == ".docx":
extract_docx(path)
elif ext == ".xlsx":
extract_xlsx(path)
elif ext == ".pdf":
extract_pdf(path)
else:
die(f"Unsupported file extension '{ext}'. Supported: .pptx, .docx, .xlsx, .pdf")
if __name__ == "__main__":
try:
main()
except BrokenPipeError:
# Happens harmlessly when output is piped into something like `head`
# that closes the pipe early. Exit quietly instead of a traceback.
devnull = os.open(os.devnull, os.O_WRONLY)
os.dup2(devnull, sys.stdout.fileno())
sys.exit(0)
combine.py
Purpose: Stacks every CSV file in a given folder into one combined
output CSV. Used twice in this workflow: once to combine all the
per-file extraction results into master-claims.csv, and again to merge
flagged comparison batches back into one file.
#!/usr/bin/env python3
"""
combine.py — Stack every CSV in a folder into one CSV. No interpretation.
Reads every CSV file matching a pattern inside a given folder, and stacks
all their rows into a single output CSV. All input files must share the
same columns (same header row). Files that contain only a header row (no
data) are skipped without failing the run.
Used for:
- Phase 1.4: combining extracted/*.csv into master-claims.csv
- Phase 3 merge: combining compare-batches/*-flagged.csv into
flagged-inconsistencies.csv
Usage:
python3 combine.py <input-folder> <output-csv-path> [--pattern "*.csv"]
Examples:
python3 combine.py Z_position-mgmt-analysis/extracted Z_position-mgmt-analysis/master-claims.csv
python3 combine.py Z_position-mgmt-analysis/compare-batches Z_position-mgmt-analysis/flagged-inconsistencies.csv --pattern "*-flagged.csv"
"""
import sys
import os
import glob
import argparse
import pandas as pd
def die(message: str) -> None:
print(f"ERROR: {message}", file=sys.stderr)
sys.exit(1)
def main() -> None:
parser = argparse.ArgumentParser(description="Combine all CSVs in a folder into one.")
parser.add_argument("input_folder", help="Folder containing the CSV files to combine")
parser.add_argument("output_csv", help="Path to write the combined CSV")
parser.add_argument(
"--pattern",
default="*.csv",
help='Glob pattern to match input files (default: "*.csv")',
)
args = parser.parse_args()
if not os.path.isdir(args.input_folder):
die(f"Input folder not found: {args.input_folder}")
search_path = os.path.join(args.input_folder, args.pattern)
input_files = sorted(glob.glob(search_path))
if not input_files:
die(f"No files matched pattern '{args.pattern}' inside {args.input_folder}")
frames = []
expected_columns = None
skipped = []
for file_path in input_files:
try:
df = pd.read_csv(file_path, dtype=str, keep_default_na=False)
except pd.errors.EmptyDataError:
skipped.append((file_path, "completely empty file"))
continue
except Exception as e:
die(f"Could not read {file_path}: {e}")
if df.empty:
skipped.append((file_path, "header only, no data rows"))
continue
if expected_columns is None:
expected_columns = list(df.columns)
elif list(df.columns) != expected_columns:
die(
f"Column mismatch in {file_path}.\n"
f"Expected: {expected_columns}\n"
f"Found: {list(df.columns)}"
)
frames.append(df)
if not frames:
die("Every matched file was empty — nothing to combine.")
combined = pd.concat(frames, ignore_index=True)
os.makedirs(os.path.dirname(os.path.abspath(args.output_csv)) or ".", exist_ok=True)
combined.to_csv(args.output_csv, index=False)
print(f"Combined {len(frames)} file(s) into {args.output_csv}")
print(f"Total rows written: {len(combined)}")
if skipped:
print(f"Skipped {len(skipped)} empty file(s):")
for file_path, reason in skipped:
print(f" - {file_path} ({reason})")
if __name__ == "__main__":
main()
split_by_topic.py
Purpose: Only needed if your topic-groups.csv file is large.
Sorts the file by its topic column and splits it into batch files of
roughly equal size — without ever cutting a single topic across two
batches, since comparing a topic's statements requires seeing all of
them at once.
#!/usr/bin/env python3
"""
split_by_topic.py — Split a topic-grouped CSV into batches, never cutting
a topic across two batch files. No interpretation.
Reads a CSV that has a "topic" column (as produced by the grouping step),
sorts it so all rows sharing a topic are adjacent, then packs whole topics
into batch files aiming for roughly --rows-per-batch rows each. A topic is
never split across two files — if a single topic's claims already exceed
the target size on their own, that topic becomes its own (larger) batch.
Used for:
- Phase 3, only if topic-groups.csv is too large to compare in one pass
Usage:
python3 split_by_topic.py <input-csv> <output-folder> [--rows-per-batch 120]
Example:
python3 split_by_topic.py Z_position-mgmt-analysis/topic-groups.csv Z_position-mgmt-analysis/compare-batches
"""
import sys
import os
import argparse
import pandas as pd
def die(message: str) -> None:
print(f"ERROR: {message}", file=sys.stderr)
sys.exit(1)
def main() -> None:
parser = argparse.ArgumentParser(
description="Split a topic-grouped CSV into batches without cutting a topic across files."
)
parser.add_argument("input_csv", help="Path to topic-groups.csv (must have a 'topic' column)")
parser.add_argument("output_folder", help="Folder to write compare-batch-N.csv files into")
parser.add_argument(
"--rows-per-batch",
type=int,
default=120,
help="Target rows per batch (default: 120). Actual batch sizes will vary to respect topic boundaries.",
)
args = parser.parse_args()
if not os.path.isfile(args.input_csv):
die(f"Input file not found: {args.input_csv}")
try:
df = pd.read_csv(args.input_csv, dtype=str, keep_default_na=False)
except Exception as e:
die(f"Could not read {args.input_csv}: {e}")
if "topic" not in df.columns:
die(f"Input file has no 'topic' column. Columns found: {list(df.columns)}")
if df.empty:
die(f"{args.input_csv} has no data rows to split.")
# Sort so that all rows sharing a topic are adjacent. Preserve first-seen
# topic order rather than alphabetical, so related topics that were
# already near each other stay near each other.
first_seen_order = df["topic"].drop_duplicates().tolist()
topic_order = {topic: i for i, topic in enumerate(first_seen_order)}
df = df.assign(_topic_order=df["topic"].map(topic_order))
df = df.sort_values("_topic_order", kind="stable").drop(columns="_topic_order")
os.makedirs(args.output_folder, exist_ok=True)
target = args.rows_per_batch
batches = []
current_topics = []
current_row_count = 0
grouped = list(df.groupby("topic", sort=False))
for topic, topic_df in grouped:
topic_size = len(topic_df)
# Start a new batch if adding this topic would exceed the target
# AND the current batch already has at least one topic in it.
# (A single oversized topic still gets its own batch, alone.)
if current_topics and (current_row_count + topic_size > target):
batches.append(pd.concat(current_topics, ignore_index=True))
current_topics = []
current_row_count = 0
current_topics.append(topic_df)
current_row_count += topic_size
if current_topics:
batches.append(pd.concat(current_topics, ignore_index=True))
written = []
for i, batch_df in enumerate(batches, start=1):
out_path = os.path.join(args.output_folder, f"compare-batch-{i}.csv")
batch_df.to_csv(out_path, index=False)
written.append((out_path, len(batch_df), batch_df["topic"].nunique()))
print(f"Split {args.input_csv} ({len(df)} rows, {len(grouped)} topics) into {len(batches)} batch(es):")
for path, row_count, topic_count in written:
print(f" - {path}: {row_count} rows, {topic_count} topics")
# Sanity check: confirm no topic appears in more than one batch file.
topic_to_batches = {}
for i, batch_df in enumerate(batches, start=1):
for topic in batch_df["topic"].unique():
topic_to_batches.setdefault(topic, []).append(i)
split_topics = {t: b for t, b in topic_to_batches.items() if len(b) > 1}
if split_topics:
print("WARNING: the following topics ended up in more than one batch "
"(this should not happen — please report this):", file=sys.stderr)
for topic, batch_list in split_topics.items():
print(f" - '{topic}' in batches {batch_list}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
to_excel.py
Purpose: Converts the final flagged-inconsistencies.csv into a
formatted .xlsx file — bold header row, column widths auto-fit to
content — ready to download and review.
#!/usr/bin/env python3
"""
to_excel.py — Convert a CSV into a formatted Excel file. No interpretation.
Reads a CSV and writes it out as a .xlsx file with a bold header row and
column widths auto-fit to their content, so the result is readable without
any manual resizing. All columns and rows are kept exactly as they are in
the source CSV.
Used for:
- Phase 3.3: converting flagged-inconsistencies.csv into
results/inconsistency-report.xlsx
Usage:
python3 to_excel.py <input-csv> <output-xlsx>
Example:
python3 to_excel.py Z_position-mgmt-analysis/flagged-inconsistencies.csv Z_position-mgmt-analysis/results/inconsistency-report.xlsx
"""
import sys
import os
import pandas as pd
from openpyxl.styles import Font
from openpyxl.utils import get_column_letter
MAX_COLUMN_WIDTH = 80
MIN_COLUMN_WIDTH = 10
WRAP_SAMPLE_LEN = 200 # only used to estimate width; text itself is never truncated
def die(message: str) -> None:
print(f"ERROR: {message}", file=sys.stderr)
sys.exit(1)
def main() -> None:
if len(sys.argv) != 3:
die("Usage: python3 to_excel.py <input-csv> <output-xlsx>")
input_csv, output_xlsx = sys.argv[1], sys.argv[2]
if not os.path.isfile(input_csv):
die(f"Input file not found: {input_csv}")
try:
df = pd.read_csv(input_csv, dtype=str, keep_default_na=False)
except Exception as e:
die(f"Could not read {input_csv}: {e}")
os.makedirs(os.path.dirname(os.path.abspath(output_xlsx)) or ".", exist_ok=True)
with pd.ExcelWriter(output_xlsx, engine="openpyxl") as writer:
sheet_name = "Inconsistencies"
df.to_excel(writer, index=False, sheet_name=sheet_name)
ws = writer.sheets[sheet_name]
# Bold header row
for cell in ws[1]:
cell.font = Font(bold=True)
# Auto-fit column widths based on the longest value in each column
# (capped so a single huge quote doesn't blow the column out).
for col_idx, column in enumerate(df.columns, start=1):
longest = len(str(column))
for value in df[column]:
sample = str(value)[:WRAP_SAMPLE_LEN]
longest = max(longest, len(sample))
width = max(MIN_COLUMN_WIDTH, min(MAX_COLUMN_WIDTH, longest + 2))
ws.column_dimensions[get_column_letter(col_idx)].width = width
print(f"Wrote {len(df)} row(s), {len(df.columns)} column(s) to {output_xlsx}")
if __name__ == "__main__":
main()
Building Your Own Scripts for a Different Project
These four scripts cover a general version of this workflow, but your next project might need something slightly different. When that happens, follow the same approach described in Part 1: discuss with clearxx Assistant what mechanical steps your project needs and what each script should do. If a script turns out to be short and simple, clearxx Assistant can often write it directly for you in the chat. For anything longer or more involved, the Assistant hands the task to Cline, which can build and test larger scripts on its own.