#!/usr/bin/env python3 """ sync.py — TKDK PDF knowledge-base sync for the PageIndex RAG. Crawls TKDK's document sections, discovers PDF links (hub -> detail -> .pdf), CURATES them (keep current IPARD III + operational docs, drop old programs and applicant/contract lists), downloads only new/changed files (conditional GET + sha256), records provenance in a manifest, and optionally indexes with PageIndex. Workflow (manual trigger): python sync.py crawl # crawl + curate -> writes data/discovered.csv (review this!) # (open data/discovered.csv, flip the `keep` column: 1 keep / 0 skip) python sync.py # download rows with keep=1 -> data/pdfs + manifest.json python sync.py index # index new/changed PDFs with PageIndex (spends tokens) python sync.py all # crawl + download + index python sync.py status # manifest summary Idempotency: re-download only on ETag/Last-Modified change; re-index only on sha256 change. discovered.csv lets you curate before spending anything. Requires: requests, beautifulsoup4 (+ pageindex for the `index` stage) """ from __future__ import annotations import argparse import csv import hashlib import json import re import sys import time from datetime import datetime, timezone from pathlib import Path from urllib.parse import urljoin, urlparse, urldefrag from urllib.robotparser import RobotFileParser import warnings import requests from bs4 import BeautifulSoup try: # noisy when TKDK serves the odd XML/sitemap page through the HTML parser from bs4 import XMLParsedAsHTMLWarning warnings.filterwarnings("ignore", category=XMLParsedAsHTMLWarning) except Exception: # noqa: BLE001 pass # ---------------------------------------------------------------------------- # CONFIG # ---------------------------------------------------------------------------- BASE = "https://www.tkdk.gov.tr" # Hub pages to start from (core IPARD knowledge + operational docs). SEEDS = [ "/Ipard/BasvuruCagriRehberleri", # application call guides "/ProjeIslemleri/CagriIlanArsiv", # call announcements "/Mevzuat", # laws / regulations / agreements / program docs "/Ipard/ABStandartlariRehberler", # EU standards guides "/Kurumsal/PolitikaBelgeleri", # policy documents "/ProjeIslemleri/BasvuruIslemleri", # application process hub "/ProjeIslemleri/YerindeKontrolIslemleri", # on-site control "/ProjeIslemleri/OdemeTalepIslemleri", # payment-claim docs "/SikcaSorulanSorular", # FAQ # measure pages -> sub-measure pages -> application-package & helper docs "/Tedbir/tarimsal-isletmelerin-fiziki-varliklarina-yonelik-yatirimlar-1", "/Tedbir/tarim-ve-balikcilik-urunlerinin-islenmesi-ve-pazarlanmasi-ile-ilgili-fiziki-varliklara-yonelik-yatirimlar-3", "/Tedbir/tarim-cevre-iklim-ve-organik-tarim-16", "/Tedbir/leader-yaklasimi-yerel-kalkinma-stratejilerinin-uygulanmasi-tedbiri-6", "/Tedbir/ciftlik-faaliyetlerinin-cesitlendirilmesi-ve-is-gelistirme-4", ] # Follow HTML links under these detail-page routes (they lead to /Content/File PDFs). ALLOW_PREFIXES = [ "/BasvuruCagriRehberi/", # guide detail pages (versioned) "/Dokuman/", # single-doc pages: cagri ilanlari, mevzuat, program docs "/Tedbir/", # measure pages "/AltTedbir/", # sub-measure pages: application-package & helper docs "/ProjeIslemleri/BasvuruIslemleri", "/ProjeIslemleri/YerindeKontrolIslemleri", "/ProjeIslemleri/OdemeTalepIslemleri", "/SikcaSorulanSorular", ] MAX_DEPTH = 3 # Tedbir -> AltTedbir -> detail -> pdf can be 3+ hops. REQUEST_DELAY = 1.0 TIMEOUT = 30 # crawl (connect+read) DL_TIMEOUT = (15, 180) # download: 15s connect, 180s read (big PDFs are slow) RESPECT_ROBOTS = True USER_AGENT = "TKDK-IPARD-RAG-sync/1.0 (+internal knowledge base; contact: you@example.com)" # --- Curation rules --------------------------------------------------------- # Applicant/contract lists and other non-knowledge PDFs -> always drop. DENY_SUBSTRINGS = [ "ImzalananSozlesmeler", "FesihEdilen", "MaliKapanis", "Protokol", "DanismanFirma", "UyariciLevha", ] # Old program path segments to drop (IPARD III kept; matched as exact segments, # so "IPARDIII" never matches "IPARDII"). DROP_PROGRAM_SEGMENTS = {"IPARDI", "IPARDII"} # Paths (relative to this script's folder) ROOT = Path(__file__).resolve().parent DATA_DIR = ROOT / "data" PDF_DIR = DATA_DIR / "pdfs" WORKSPACE = DATA_DIR / "workspace" MANIFEST_PATH = DATA_DIR / "manifest.json" DISCOVERED_CSV = DATA_DIR / "discovered.csv" SESSION = requests.Session() # Connection: close -> a fresh TLS connection per request (avoids stale keep-alive # SSL "UNEXPECTED_EOF" from TKDK). Retry adapter recovers from transient TLS/5xx. SESSION.headers.update({"User-Agent": USER_AGENT, "Connection": "close"}) try: from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry _retry = Retry(total=5, connect=5, read=3, backoff_factor=2, status_forcelist=[429, 500, 502, 503, 504], allowed_methods=frozenset(["GET"]), raise_on_status=False) SESSION.mount("https://", HTTPAdapter(max_retries=_retry)) SESSION.mount("http://", HTTPAdapter(max_retries=_retry)) except Exception: # noqa: BLE001 pass # ---------------------------------------------------------------------------- # Pure helpers (unit-tested) # ---------------------------------------------------------------------------- def now_iso() -> str: return datetime.now(timezone.utc).isoformat(timespec="seconds") def is_pdf_url(url: str) -> bool: return urlparse(url).path.lower().endswith(".pdf") # All real TKDK docs live under /Content/File/... . Scanning raw HTML for this # pattern catches PDFs embedded via