Files

363 lines
13 KiB
Python

import argparse
import json
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from pipeline_utils import (
crawl_state_dir,
generated_entities_path,
get_entity,
load_config,
reset_entity_run,
run_dir,
resolve_path,
warc_dir,
)
_active_process: subprocess.Popen | None = None
_stop_requested = False
def _handle_stop_signal(signum: int, _frame) -> None:
"""Forward SIGTERM to the running stage's process group and remember the request.
The handler must not block: the main loop keeps draining the child's output
until the stage has shut down (Scrapy saves its JOBDIR on the first SIGTERM).
If the container's stop timeout is shorter than the shutdown, Docker kills it.
"""
global _stop_requested
_stop_requested = True
process = _active_process
if process is not None and process.poll() is None:
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
pass
def _exit_if_stopped() -> None:
if _stop_requested:
print(
"Interrupted. Progress saved; the next run with --auto-resume continues here.",
flush=True,
)
raise SystemExit(143)
def run_command(command: str, cwd: str | None = None, log=None) -> None:
"""Run a stage in its own process group; stream output to stdout and the log file."""
global _active_process
_exit_if_stopped()
process = subprocess.Popen(
command,
shell=True,
cwd=cwd,
text=True,
encoding="utf-8",
errors="replace",
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=1,
start_new_session=True,
)
_active_process = process
try:
if _stop_requested: # signal arrived between Popen and the assignment above
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
pass
for line in process.stdout:
sys.stdout.write(line)
sys.stdout.flush()
if log is not None:
log.write(line)
log.flush()
return_code = process.wait()
finally:
_active_process = None
if return_code != 0:
_exit_if_stopped() # a non-zero exit caused by our stop is not a failure
raise subprocess.CalledProcessError(return_code, command)
def _write_state(path: str, state: dict) -> None:
directory = os.path.dirname(path)
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", dir=directory, delete=False
) as handle:
json.dump(state, handle, indent=2)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
temporary_path = handle.name
os.replace(temporary_path, path)
def _read_state(path: str) -> dict | None:
try:
with open(path, encoding="utf-8") as handle:
state = json.load(handle)
except (OSError, ValueError):
return None
return state if isinstance(state, dict) else None
def _new_state(signature: dict) -> dict:
return {"done": [], "completed": False, "signature": signature}
def _prepare_run(
config: dict, entity_name: str, signature: dict, fresh: bool, auto_resume: bool
) -> tuple[str, dict]:
"""Return (run folder, state).
--fresh wipe the entity's run folder and start over.
--auto-resume continue the existing run without deleting data,
regardless of its signature or completion status.
neither keep existing data (so --skip-crawl and
--skip-entity-generation still work) and start a new state.
"""
if fresh:
print(f"Removing all generated data for entity '{entity_name}'...")
return reset_entity_run(config, entity_name), _new_state(signature)
entity_run_dir = resolve_path(
config, os.path.join(config.get("runs_dir", "runs"), entity_name)
)
if os.path.isdir(entity_run_dir):
with os.scandir(entity_run_dir) as entries:
has_previous_data = any(entries)
else:
has_previous_data = False
entity_run_dir = run_dir(config, entity_name)
if auto_resume:
state = _read_state(os.path.join(entity_run_dir, "pipeline_state.json"))
if state is not None and isinstance(state.get("done"), list):
if state.get("completed"):
print("Previous run completed. Starting a new run.")
return reset_entity_run(config, entity_name), _new_state(signature)
if state.get("signature") != signature:
print("Warning: flags differ from the interrupted run; resuming anyway.")
print(f"Resuming. Completed steps: {', '.join(state['done']) or 'none'}")
return entity_run_dir, state
if has_previous_data:
print("No pipeline state found. Continuing with existing data.")
else:
print("No previous data found. Starting fresh.")
return entity_run_dir, _new_state(signature)
return entity_run_dir, _new_state(signature)
def _run_step(
name: str,
state: dict,
state_path: str,
command: str,
cwd: str,
log,
) -> None:
if name in state["done"]:
print(f"Skipping '{name}' (already done).")
return
print(f"Running {name}...", flush=True)
try:
run_command(command, cwd=cwd, log=log)
except subprocess.CalledProcessError as error:
print(f"Step '{name}' failed with exit code {error.returncode}.", flush=True)
raise
state["done"].append(name)
_write_state(state_path, state)
_exit_if_stopped()
def main() -> int:
parser = argparse.ArgumentParser(
description="Run the full organization-crawling pipeline for one entity."
)
parser.add_argument(
"--skip-entity-generation",
action="store_true",
help="Skip generation of runs/<entity>/entities.json and reuse an existing seed file",
)
parser.add_argument(
"--entity", required=True, help="Entity name as defined in pipeline_config.json"
)
parser.add_argument("--config", default=None, help="Path to pipeline_config.json")
parser.add_argument(
"--fresh",
action="store_true",
help="Wipe this entity's run folder before starting",
)
parser.add_argument(
"--auto-resume",
action="store_true",
help="Resume an unfinished run with the same pipeline signature",
)
parser.add_argument(
"--skip-crawl",
action="store_true",
help="Skip the Scrapy crawl step (reuse an existing warc/ directory)",
)
parser.add_argument(
"--crawl-limit",
type=int,
default=None,
help="Stop the Scrapy crawl gracefully after about N pages (smoke test)",
)
parser.add_argument(
"--upload-limit",
type=int,
default=None,
help="Only upload the first N pages to Elasticsearch",
)
args = parser.parse_args()
for signum in (signal.SIGTERM, signal.SIGINT):
signal.signal(signum, _handle_stop_signal)
start_time = time.time()
base_dir = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.abspath(
args.config or os.path.join(base_dir, "pipeline_config.json")
)
config = load_config(config_path)
entity = get_entity(config, args.entity)
signature = {
"entity": args.entity,
"upload_limit": args.upload_limit,
"crawl_limit": args.crawl_limit,
}
entity_run_dir, state = _prepare_run(
config, args.entity, signature, args.fresh, args.auto_resume
)
state_path = os.path.join(entity_run_dir, "pipeline_state.json")
_write_state(state_path, state)
out_dir = os.path.join(entity_run_dir, "out")
entity_warc_dir = warc_dir(config, args.entity)
entity_crawl_state_dir = crawl_state_dir(config, args.entity)
warc_directory = os.path.join(entity_run_dir, "warc")
common_args = f'--entity {args.entity} --config "{config_path}"'
with open(os.path.join(entity_run_dir, "pipeline.log"), "a", encoding="utf-8") as log:
if "entities" not in state["done"]:
if not args.skip_entity_generation:
_run_step(
"entities",
state,
state_path,
f"{sys.executable} generate_entities.py {common_args}",
base_dir,
log,
)
else:
seed_file = generated_entities_path(config, args.entity)
if not os.path.exists(seed_file):
raise SystemExit(
f"--skip-entity-generation was requested but seed file is missing: {seed_file}"
)
state["done"].append("entities")
_write_state(state_path, state)
if "crawl" not in state["done"]:
if not args.skip_crawl:
crawl = entity.get("crawl", {})
depth_limit = crawl.get("depth_limit", 6)
warc_config_path = os.path.join(entity_run_dir, "warc.yml")
with open(warc_config_path, "w", encoding="utf-8") as handle:
json.dump(
{
"warc_spec": "https://iipc.github.io/warc-specifications/specifications/warc-format/warc-1.0/",
"max_warc_size": 5000000000,
"collection": args.entity,
"description": f"A crawl of {entity.get('display_name', args.entity)}",
"operator": crawl.get("operator", "unknown"),
"robots": "obey",
"user_agent": crawl.get("user_agent", "inse-crawler"),
"warc_prefix": f"{args.entity}_depth{depth_limit}",
"warc_dest": entity_warc_dir,
},
handle,
indent=2,
)
crawl_limit_flag = (
f" -s CLOSESPIDER_PAGECOUNT={args.crawl_limit}"
if args.crawl_limit is not None
else ""
)
_run_step(
"crawl",
state,
state_path,
f'SCRAPY_WARCIO_SETTINGS="{warc_config_path}" scrapy crawl organization '
f'-a entity="{args.entity}" -a config="{config_path}" '
f'-s JOBDIR="{entity_crawl_state_dir}" -s LOG_LEVEL=INFO'
f"{crawl_limit_flag}",
resolve_path(config, entity["crawler_dir"]),
log,
)
else:
if not os.path.isdir(entity_warc_dir) or not os.listdir(entity_warc_dir):
raise SystemExit(
f"--skip-crawl was requested but no WARC files exist in {entity_warc_dir}"
)
state["done"].append("crawl")
_write_state(state_path, state)
limit_flag = f" --limit {args.upload_limit}" if args.upload_limit is not None else ""
steps = (
(
"redirections",
f"{sys.executable} 00_redirections/0_get_redirections.py {warc_directory} {common_args}",
),
(
"upload",
f"{sys.executable} 01_upload/1_upload_pages.py {warc_directory} "
f"{os.path.join(out_dir, entity['output']['redirections_file'])} {common_args}{limit_flag}",
),
(
"hierarchy",
f"{sys.executable} 02_hierarchy/create_hierarchy.py {common_args}",
),
(
"classify",
f"{sys.executable} 03_url_classifier/links_classifier.py {common_args}",
),
(
"extract",
f"{sys.executable} 04_content_extractor/content_extractor_pydantic.py {common_args}",
),
(
"keywords",
f"{sys.executable} 05_keyword_extraction/extract_content_keywords.py {common_args}",
),
)
for name, command in steps:
_run_step(name, state, state_path, command, base_dir, log)
state["completed"] = True
_write_state(state_path, state)
# Scrapy's JOBDIR remembers every seen URL; keeping it would make the next crawl fetch nothing.
crawl_state = os.path.join(entity_run_dir, "crawl-state")
if os.path.isdir(crawl_state):
shutil.rmtree(crawl_state)
runtime_hours = (time.time() - start_time) / 3600
print(f"Final runtime: {runtime_hours:.2f} hours")
print(f"Finished running the '{args.entity}' organization pipeline.")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except subprocess.CalledProcessError as error:
raise SystemExit(error.returncode)