Spaces:
Running on Zero
Running on Zero
Download scripts/fetch_sss.py from denizkaya2022/IPARD-Vectorless-RAG: direct link, hf CLI and curl.
- Browser
- Download file 5.22 kB
-
https://huggingface.co/spaces/denizkaya2022/IPARD-Vectorless-RAG/resolve/main/scripts/fetch_sss.py
- Command line
-
hf download hf://spaces/denizkaya2022/IPARD-Vectorless-RAG/scripts/fetch_sss.py
-
curl -L -o fetch_sss.py https://huggingface.co/spaces/denizkaya2022/IPARD-Vectorless-RAG/resolve/main/scripts/fetch_sss.py
5.22 kB
| #!/usr/bin/env python3 | |
| """ | |
| fetch_sss.py — TKDK Sıkça Sorulan Sorular (SSS) sayfasını çekip tree_index.json'a | |
| bir "belge" olarak ekler. Her soru = bir düğüm, cevap metni düğüme gömülü (text). | |
| Kullanım: | |
| python fetch_sss.py # sss_tree.json uretir (inceleme icin) | |
| python fetch_sss.py --merge tree_index.json # dogrudan tree_index.json'a ekler (idempotent) | |
| Gerekli: requests, beautifulsoup4 | |
| """ | |
| from __future__ import annotations | |
| import argparse, json, re, sys, time | |
| from pathlib import Path | |
| import requests | |
| from bs4 import BeautifulSoup | |
| URLS = ["https://www.tkdk.gov.tr/SSS", "https://www.tkdk.gov.tr/SSS/", | |
| "https://www.tkdk.gov.tr/sikcasorulansorular"] | |
| UA = "TKDK-IPARD-RAG-sss/1.0 (+internal knowledge base)" | |
| SESSION = requests.Session() | |
| SESSION.headers.update({"User-Agent": UA, "Connection": "close"}) | |
| try: | |
| from requests.adapters import HTTPAdapter | |
| from urllib3.util.retry import Retry | |
| _r = Retry(total=5, connect=5, backoff_factor=2, status_forcelist=[429,500,502,503,504]) | |
| SESSION.mount("https://", HTTPAdapter(max_retries=_r)) | |
| except Exception: | |
| pass | |
| def clean(t: str) -> str: | |
| t = re.sub(r"[ \t]+", " ", t or "") | |
| t = re.sub(r"\n{3,}", "\n\n", t) | |
| return t.strip() | |
| def category_of(q: str, a: str) -> str: | |
| t = (q + " " + a).lower() | |
| if "ötp" in t or "ödeme talep" in t or "otp" in t: | |
| return "Ödeme Talep Paketi (ÖTP)" | |
| if "yerinde kontrol" in t: | |
| return "Yerinde Kontroller" | |
| if "tahakkuk" in t: | |
| return "Tahakkuk" | |
| if "itiraz" in t or "ödeme" in t or "para" in t or "avans" in t or "sigorta" in t: | |
| return "Ödeme İşlemleri" | |
| return "Genel" | |
| def parse_qa(html: str): | |
| soup = BeautifulSoup(html, "html.parser") | |
| qas, seen = [], set() | |
| # Strateji 1: Bootstrap accordion -> soru linki #collapseN, cevap div#collapseN | |
| for link in soup.find_all("a", href=re.compile(r"#collapse\w+", re.I)): | |
| q = clean(link.get_text()) | |
| cid = link["href"].lstrip("#") | |
| ans = soup.find(id=cid) | |
| a = clean(ans.get_text("\n")) if ans else "" | |
| if q and a and len(a) > 5 and q not in seen: | |
| seen.add(q); qas.append((q, a)) | |
| # Strateji 2 (fallback): data-toggle="collapse" veya .card yapisi | |
| if len(qas) < 3: | |
| for card in soup.select(".card, .accordion-item, .panel"): | |
| head = card.find(["a", "button", "h3", "h4", "h5"]) | |
| body = card.select_one(".collapse, .card-body, .panel-body, .accordion-body") | |
| if head and body: | |
| q, a = clean(head.get_text()), clean(body.get_text("\n")) | |
| if q and a and len(a) > 5 and q not in seen: | |
| seen.add(q); qas.append((q, a)) | |
| return qas | |
| def build_doc(qas): | |
| # kategoriye gore grupla | |
| cats = {} | |
| for q, a in qas: | |
| c = category_of(q, a) | |
| cats.setdefault(c, []).append((q, a)) | |
| nodes = [] | |
| for cat, items in cats.items(): | |
| children = [{ | |
| "title": q, "level": 2, "start_page": None, "end_page": None, | |
| "text": a, "nodes": [], | |
| } for q, a in items] | |
| nodes.append({ | |
| "title": cat, "level": 1, "start_page": None, "end_page": None, | |
| "text": "", "nodes": children, | |
| }) | |
| return { | |
| "source_file": "TKDK_SSS", | |
| "doc_id": "tkdk-sss", | |
| "measure": "", | |
| "doc_type": "sss", | |
| "url": "https://www.tkdk.gov.tr/SSS", | |
| "method": "sss_html", | |
| "page_count": 0, | |
| "nodes": nodes, | |
| } | |
| def fetch(): | |
| last = None | |
| for u in URLS: | |
| try: | |
| r = SESSION.get(u, timeout=30) | |
| r.raise_for_status() | |
| qas = parse_qa(r.text) | |
| if qas: | |
| print(f"Kaynak: {u} -> {len(qas)} soru-cevap") | |
| return qas | |
| last = f"{u}: 0 Q&A parse edildi" | |
| except requests.RequestException as e: | |
| last = f"{u}: {type(e).__name__}" | |
| time.sleep(1) | |
| sys.exit(f"SSS parse edilemedi. Son durum: {last}") | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--merge", default=None, help="tree_index.json yolu (ekle, idempotent)") | |
| ap.add_argument("--out", default="sss_tree.json") | |
| args = ap.parse_args() | |
| qas = fetch() | |
| doc = build_doc(qas) | |
| # ozet | |
| from collections import Counter | |
| cc = Counter(category_of(q, a) for q, a in qas) | |
| print("Kategori dagilimi:", dict(cc)) | |
| print("\nOrnek (ilk 3):") | |
| for q, a in qas[:3]: | |
| print(f" S: {q[:70]}") | |
| print(f" C: {a[:90]}...\n") | |
| if args.merge: | |
| p = Path(args.merge) | |
| tree = json.loads(p.read_text(encoding="utf-8")) | |
| tree["docs"] = [d for d in tree["docs"] if d.get("doc_id") != "tkdk-sss"] # idempotent | |
| tree["docs"].append(doc) | |
| p.write_text(json.dumps(tree, ensure_ascii=False, indent=2), encoding="utf-8") | |
| print(f"\n{p} icine eklendi. Toplam belge: {len(tree['docs'])}") | |
| else: | |
| Path(args.out).write_text(json.dumps({"docs": [doc]}, ensure_ascii=False, indent=2), encoding="utf-8") | |
| print(f"\n{args.out} yazildi. (Ana agaca eklemek icin: --merge tree_index.json)") | |
| if __name__ == "__main__": | |
| main() | |