denizkaya20
Agentic vectorless RAG for IPARD III documents (English UI)
b110ac6
Raw History Blame Contribute Delete
22.5 kB
#!/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 <iframe>/<embed> or referenced from JS
# (e.g. cagri ilani detail pages), not just <a href> links.
_PDF_RE = re.compile(r'Content/File/[^\s"\'<>()\\]+?\.pdf', re.IGNORECASE)
def pdfs_in_html(html: str) -> set[str]:
return {normalize_pdf_url(f"{BASE}/{m.lstrip('/')}") for m in _PDF_RE.findall(html)}
def _segments(url: str) -> list[str]:
return [s for s in urlparse(url).path.split("/") if s]
def normalize_pdf_url(url: str) -> str:
"""All real docs live under /Content/File/... . Rewrite to canonical root form
(fixes broken relative links, dedupes version dirs)."""
url, _ = urldefrag(url)
path = urlparse(url).path
i = path.find("/Content/File/")
if i != -1:
path = path[i:]
return f"{BASE}{path}"
def local_name_for(pdf_url: str) -> str:
"""Unique filename from the FULL path (so .../9.0/101.pdf and .../3.0/101.pdf differ)."""
path = urlparse(pdf_url).path
if "/Content/File/" in path:
path = path.split("/Content/File/", 1)[1]
slug = path.strip("/").replace("/", "__")
if not slug.lower().endswith(".pdf"):
slug += ".pdf" # /Dokuman/{slug}-{id} serves a PDF without .pdf in the URL
if len(slug) > 180:
h = hashlib.sha1(slug.encode()).hexdigest()[:8]
slug = slug[:150] + "__" + h + ".pdf"
return slug
def sha256_of(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 16), b""):
h.update(chunk)
return h.hexdigest()
def in_scope(url: str) -> bool:
p = urlparse(url)
if p.netloc and p.netloc != urlparse(BASE).netloc:
return False
return any(p.path.startswith(pref) for pref in ALLOW_PREFIXES)
# --- Curation ---------------------------------------------------------------
def is_noise(url: str) -> bool:
u = url.lower()
return any(s.lower() in u for s in DENY_SUBSTRINGS)
def guide_key(url: str):
"""For IPARD III guide PDFs return (measure_stem, version_tuple), else None.
Path form: .../BasvuruCagriRehberi/IPARDIII/{ver}/{measure}.pdf"""
segs = _segments(url)
if "BasvuruCagriRehberi" not in segs or "IPARDIII" not in segs:
return None
try:
i = segs.index("IPARDIII")
ver = segs[i + 1]
measure = segs[i + 2].rsplit(".pdf", 1)[0]
except (ValueError, IndexError):
return None
vt = tuple(int(x) for x in re.findall(r"\d+", ver)) or (0,)
return measure, vt
def doc_type_of(url: str) -> str:
u = url.lower()
if "basvurucagrirehberi" in u:
return "rehber"
if "cagri-ilani" in u or "basvurucagriilani" in u or "cagriilan" in u:
return "cagri-ilani"
if any(k in u for k in ("kanun", "yonetmelik", "antlasma", "kararname",
"-programi-", "mevzuat", "cetveli", "etik")):
return "mevzuat"
if any(k in u for k in ("kontrol", "ikame", "-poz", "maliyet", "on-kontrol")):
return "operasyon"
if "ukks" in u or "politika" in u:
return "politika"
if "odeme" in u:
return "odeme"
return "diger"
def curate(pdf_urls: list[str]):
"""Return (kept_urls, dropped[(url, reason)]) applying curation rules."""
dropped = []
survivors = []
for u in pdf_urls:
if is_noise(u):
dropped.append((u, "noise"))
continue
segs = _segments(u)
if "BasvuruCagriRehberi" in segs:
# guides: keep only IPARD III
if "IPARDIII" not in segs:
dropped.append((u, "old-guide (not IPARD III)"))
continue
else:
slug = segs[-1].lower() if segs else ""
# old program via path segment (IPARDI/IPARDII) OR /Dokuman/ slug
# (ipard-i-… / ipard-ii-…, but NOT ipard-iii-…)
if any(s in DROP_PROGRAM_SEGMENTS for s in segs) or slug.startswith(("ipard-i-", "ipard-ii-")):
dropped.append((u, "old-program"))
continue
survivors.append(u)
# keep only the latest version per IPARD III guide measure
latest: dict[str, tuple[str, tuple]] = {}
kept = []
for u in survivors:
k = guide_key(u)
if k is None:
kept.append(u) # non-guide (cagri ilani, mevzuat, operational) -> keep
continue
measure, vt = k
if measure not in latest or vt > latest[measure][1]:
latest[measure] = (u, vt)
kept.extend(v[0] for v in latest.values())
kept_set = set(kept)
for u in survivors:
if u not in kept_set and guide_key(u):
dropped.append((u, "superseded-guide-version"))
return sorted(kept_set), dropped
def load_manifest() -> dict:
if MANIFEST_PATH.exists():
return json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
return {}
def save_manifest(m: dict) -> None:
DATA_DIR.mkdir(parents=True, exist_ok=True)
MANIFEST_PATH.write_text(json.dumps(m, ensure_ascii=False, indent=2), encoding="utf-8")
def write_discovered_csv(kept, dropped):
"""Write discovered.csv. Preserves any prior manual `keep` edits for URLs that
were already present, so re-crawling for updates doesn't clobber curation."""
DATA_DIR.mkdir(parents=True, exist_ok=True)
prior = {}
if DISCOVERED_CSV.exists():
with open(DISCOVERED_CSV, newline="", encoding="utf-8-sig") as f:
for row in csv.DictReader(f):
prior[row["url"]] = str(row.get("keep", "")).strip()
def keep_flag(url, auto):
return prior.get(url, "1" if auto else "0")
with open(DISCOVERED_CSV, "w", newline="", encoding="utf-8-sig") as f:
w = csv.writer(f)
w.writerow(["keep", "doc_type", "reason", "url"])
for u in kept:
tag = "kept" if u not in prior else "kept (prior edit honored)"
w.writerow([keep_flag(u, True), doc_type_of(u), tag, u])
for u, reason in dropped:
w.writerow([keep_flag(u, False), doc_type_of(u), reason, u])
def read_kept_from_csv() -> list[str] | None:
if not DISCOVERED_CSV.exists():
return None
kept = []
with open(DISCOVERED_CSV, newline="", encoding="utf-8-sig") as f:
for row in csv.DictReader(f):
if str(row.get("keep", "")).strip() in ("1", "true", "True"):
kept.append(row["url"])
return kept
# ----------------------------------------------------------------------------
# Network stages
# ----------------------------------------------------------------------------
def _robots():
if not RESPECT_ROBOTS:
return None
rp = RobotFileParser()
try:
r = SESSION.get(urljoin(BASE, "/robots.txt"), timeout=TIMEOUT)
rp.parse(r.text.splitlines() if r.status_code == 200 else [])
except requests.RequestException:
rp.parse([])
return rp
def crawl() -> set[str]:
"""BFS from SEEDS within scope; return a set of normalized PDF URLs."""
rp = _robots()
seen: set[str] = set()
pdfs: set[str] = set()
queue: list[tuple[str, int]] = [(urljoin(BASE, s), 0) for s in SEEDS]
while queue:
url, depth = queue.pop(0)
if url in seen:
continue
seen.add(url)
if rp is not None and not rp.can_fetch(USER_AGENT, url):
continue
resp = None
for attempt in range(2): # one retry (transient timeouts happen)
try:
resp = SESSION.get(url, timeout=TIMEOUT, stream=True)
resp.raise_for_status()
break
except requests.RequestException as e:
if attempt == 0:
time.sleep(2)
continue
print(f" [warn] {url} -> {e}")
if resp is None:
continue
time.sleep(REQUEST_DELAY)
# Many TKDK docs are served straight from /Dokuman/{slug}-{id} as a PDF
# (no .pdf in the URL, nothing in the HTML). Detect by Content-Type.
ctype = resp.headers.get("Content-Type", "").lower()
if "pdf" in ctype:
resp.close()
pdfs.add(normalize_pdf_url(url))
print(f" d{depth} {url} (PDF response; pdfs: {len(pdfs)})")
continue
html = resp.text # reads body only for HTML pages
# 1) grab PDFs from raw HTML (robust to embeds/JS)
pdfs |= pdfs_in_html(html)
# 2) parse links for navigation; one bad page must not kill the crawl
try:
soup = BeautifulSoup(html, "html.parser")
for a in soup.find_all("a", href=True):
link, _ = urldefrag(urljoin(url, a["href"]))
if is_pdf_url(link):
pdfs.add(normalize_pdf_url(link))
elif depth < MAX_DEPTH and in_scope(link) and link not in seen:
queue.append((link, depth + 1))
except Exception as e: # noqa: BLE001
print(f" [warn] parse skipped {url} -> {type(e).__name__}")
print(f" d{depth} {url} (pdfs: {len(pdfs)}, queue: {len(queue)})")
return pdfs
def do_crawl_and_curate() -> list[str]:
print("Crawling...")
raw = sorted(crawl())
kept, dropped = curate(raw)
write_discovered_csv(kept, dropped)
print(f"\nDiscovered {len(raw)} PDFs -> keep {len(kept)}, drop {len(dropped)}.")
print(f"Review/edit: {DISCOVERED_CSV}")
by_type: dict[str, int] = {}
for u in kept:
by_type[doc_type_of(u)] = by_type.get(doc_type_of(u), 0) + 1
print("Kept by type:", ", ".join(f"{k}={v}" for k, v in sorted(by_type.items())))
return kept
def download(limit: int | None = None) -> None:
"""Download curated PDFs. Uses data/discovered.csv keep=1 if present, else crawl+curate.
No HEAD pre-check (TKDK blocks HEAD); each response is validated as PDF by magic bytes."""
PDF_DIR.mkdir(parents=True, exist_ok=True)
manifest = load_manifest()
urls = read_kept_from_csv()
if urls is None:
urls = do_crawl_and_curate()
else:
print(f"Using {len(urls)} kept rows from {DISCOVERED_CSV}")
if limit:
urls = urls[:limit]
new = changed = unchanged = failed = 0
for i, url in enumerate(urls, 1):
entry = manifest.get(url, {})
fname = entry.get("filename") or local_name_for(url)
fpath = PDF_DIR / fname
headers = {}
if entry.get("etag"):
headers["If-None-Match"] = entry["etag"]
if entry.get("last_modified"):
headers["If-Modified-Since"] = entry["last_modified"]
r = None
for attempt in range(4):
try:
r = SESSION.get(url, timeout=DL_TIMEOUT, headers=headers, stream=True)
break
except requests.RequestException as e:
if attempt < 3:
time.sleep(2 * (attempt + 1))
continue
print(f"[{i}/{len(urls)}] error: {url} -> {type(e).__name__}")
if r is None:
failed += 1
continue
time.sleep(REQUEST_DELAY)
if r.status_code == 304 and fpath.exists():
unchanged += 1
print(f"[{i}/{len(urls)}] 304 unchanged: {fname}")
continue
try:
r.raise_for_status()
except requests.RequestException as e:
print(f"[{i}/{len(urls)}] http error: {url} -> {e}")
failed += 1
continue
tmp = fpath.with_suffix(fpath.suffix + ".part")
first = b""
try:
with open(tmp, "wb") as f:
for chunk in r.iter_content(chunk_size=1 << 15):
if chunk:
if not first:
first = chunk[:5]
f.write(chunk)
except requests.RequestException as e:
tmp.unlink(missing_ok=True)
print(f"[{i}/{len(urls)}] interrupted: {type(e).__name__} -> {fname}")
failed += 1
continue
ctype = r.headers.get("Content-Type", "").lower()
if "pdf" not in ctype and first != b"%PDF-":
tmp.unlink(missing_ok=True)
print(f"[{i}/{len(urls)}] skip (not a pdf: {ctype or 'no type'}): {url}")
failed += 1
continue
digest = sha256_of(tmp)
etag = r.headers.get("ETag")
last_modified = r.headers.get("Last-Modified")
if entry.get("sha256") == digest and fpath.exists():
tmp.unlink(missing_ok=True)
entry.update(etag=etag, last_modified=last_modified)
manifest[url] = entry
unchanged += 1
print(f"[{i}/{len(urls)}] same content: {fname}")
continue
tmp.replace(fpath)
status = "changed" if entry.get("sha256") else "new"
if status == "new":
new += 1
else:
changed += 1
entry["doc_id"] = None
entry.update(url=url, filename=fname, doc_type=doc_type_of(url), sha256=digest,
etag=etag, last_modified=last_modified,
index_state="pending", downloaded_at=now_iso(),
discovered_at=entry.get("discovered_at") or now_iso())
manifest[url] = entry
save_manifest(manifest)
print(f"[{i}/{len(urls)}] {status.upper()}: {fname} ({fpath.stat().st_size // 1024} KB)")
save_manifest(manifest)
print(f"\nDownload done. new={new} changed={changed} unchanged={unchanged} failed={failed}")
pending = sum(1 for e in manifest.values() if e.get("index_state") == "pending")
print(f"Pending to index: {pending} (run: python sync.py index)")
def index(limit: int | None = None) -> None:
try:
sys.path.insert(0, str(ROOT))
from pageindex import PageIndexClient
except Exception as e: # noqa: BLE001
print(f"Could not import PageIndex ({e}). Run from the repo root with the venv active.")
return
manifest = load_manifest()
client = PageIndexClient(workspace=str(WORKSPACE))
pending = [(u, e) for u, e in manifest.items() if e.get("index_state") == "pending"]
if limit:
pending = pending[:limit]
if not pending:
print("Nothing to index.")
return
print(f"Indexing {len(pending)} document(s)...")
for i, (url, entry) in enumerate(pending, 1):
fpath = PDF_DIR / entry["filename"]
if not fpath.exists():
print(f"[{i}/{len(pending)}] missing file, skip: {entry['filename']}")
continue
try:
doc_id = client.index(str(fpath))
except Exception as e: # noqa: BLE001
print(f"[{i}/{len(pending)}] index failed: {entry['filename']} -> {e}")
continue
entry.update(doc_id=doc_id, index_state="indexed", indexed_at=now_iso())
manifest[url] = entry
save_manifest(manifest)
print(f"[{i}/{len(pending)}] indexed: {entry['filename']} -> {doc_id}")
print("Indexing done.")
def status() -> None:
manifest = load_manifest()
if not manifest:
print("Manifest empty. Run: python sync.py crawl")
return
total = len(manifest)
indexed = sum(1 for e in manifest.values() if e.get("index_state") == "indexed")
pending = sum(1 for e in manifest.values() if e.get("index_state") == "pending")
by_type: dict[str, int] = {}
for e in manifest.values():
t = e.get("doc_type", "?")
by_type[t] = by_type.get(t, 0) + 1
print(f"Documents: {total} | indexed: {indexed} | pending: {pending}")
print("By type:", ", ".join(f"{k}={v}" for k, v in sorted(by_type.items())))
print(f"Manifest: {MANIFEST_PATH}")
def main() -> None:
ap = argparse.ArgumentParser(description="TKDK PDF knowledge-base sync")
ap.add_argument("stage", nargs="?", default="fetch",
choices=["crawl", "fetch", "index", "all", "status"],
help="crawl=discover+curate->CSV, fetch=download kept (default), "
"index=PageIndex, all=fetch+index")
ap.add_argument("--limit", type=int, default=None, help="process at most N docs (testing)")
args = ap.parse_args()
if args.stage == "crawl":
do_crawl_and_curate()
elif args.stage == "fetch":
download(limit=args.limit)
elif args.stage == "index":
index(limit=args.limit)
elif args.stage == "all":
download(limit=args.limit)
index(limit=args.limit)
elif args.stage == "status":
status()
if __name__ == "__main__":
main()