tuik 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tuik/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ """Unofficial Python client for TÜİK (Turkish Statistical Institute) data."""
2
+
3
+ from tuik import _cache
4
+ from tuik._version import __version__
5
+ from tuik.cite import cite
6
+ from tuik.errors import (
7
+ ProvinceNotFoundError,
8
+ TuikConnectionError,
9
+ TuikDataWarning,
10
+ TuikError,
11
+ TuikResponseError,
12
+ )
13
+ from tuik.migration import migration
14
+ from tuik.population import population, population_by_age
15
+ from tuik.provinces import provinces
16
+
17
+
18
+ def clear_cache() -> None:
19
+ """Delete all cached TÜİK downloads."""
20
+ _cache.clear()
21
+
22
+
23
+ __all__ = [ # noqa: RUF022 - order is part of the documented public API
24
+ "migration",
25
+ "population",
26
+ "population_by_age",
27
+ "provinces",
28
+ "cite",
29
+ "clear_cache",
30
+ "__version__",
31
+ "TuikError",
32
+ "TuikConnectionError",
33
+ "TuikResponseError",
34
+ "ProvinceNotFoundError",
35
+ "TuikDataWarning",
36
+ ]
tuik/_cache.py ADDED
@@ -0,0 +1,91 @@
1
+ """Small on-disk cache: one JSON file per key (never pickle)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import tempfile
9
+ from dataclasses import dataclass
10
+ from datetime import datetime, timedelta, timezone
11
+ from pathlib import Path
12
+
13
+ from platformdirs import user_cache_dir
14
+
15
+ _FORMAT = 1
16
+ _KEY_RE = re.compile(r"[a-z0-9-]+")
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class CacheEntry:
21
+ payload: str
22
+ retrieved_at: datetime # tz-aware UTC
23
+
24
+
25
+ def cache_dir() -> Path:
26
+ """Cache directory, resolved at call time (``TUIK_CACHE_DIR`` overrides)."""
27
+ env = os.environ.get("TUIK_CACHE_DIR")
28
+ return Path(env) if env else Path(user_cache_dir("tuik"))
29
+
30
+
31
+ def _path(key: str) -> Path:
32
+ if not _KEY_RE.fullmatch(key):
33
+ raise ValueError(f"invalid cache key {key!r}: only [a-z0-9-] allowed")
34
+ return cache_dir() / f"{key}.json"
35
+
36
+
37
+ def read(key: str) -> CacheEntry | None:
38
+ """Return the cached entry, or None if missing or unusable."""
39
+ path = _path(key)
40
+ try:
41
+ data = json.loads(path.read_text(encoding="utf-8"))
42
+ if not isinstance(data, dict) or data.get("format") != _FORMAT:
43
+ return None
44
+ payload = data.get("payload")
45
+ stamp = data.get("retrieved_at")
46
+ if not isinstance(payload, str) or not isinstance(stamp, str):
47
+ return None
48
+ retrieved_at = datetime.fromisoformat(stamp)
49
+ except (OSError, ValueError): # includes JSONDecodeError, UnicodeDecodeError
50
+ return None
51
+ if retrieved_at.tzinfo is None:
52
+ return None
53
+ return CacheEntry(payload, retrieved_at.astimezone(timezone.utc))
54
+
55
+
56
+ def is_fresh(entry: CacheEntry, max_age: timedelta = timedelta(days=7)) -> bool:
57
+ return datetime.now(timezone.utc) - entry.retrieved_at <= max_age
58
+
59
+
60
+ def write(key: str, payload: str, retrieved_at: datetime) -> None:
61
+ """Atomically write an entry (temp file in the same directory + replace)."""
62
+ path = _path(key)
63
+ path.parent.mkdir(parents=True, exist_ok=True)
64
+ body = json.dumps(
65
+ {"format": _FORMAT, "retrieved_at": retrieved_at.isoformat(), "payload": payload},
66
+ ensure_ascii=False,
67
+ )
68
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".tuik-", suffix=".tmp")
69
+ try:
70
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
71
+ fh.write(body)
72
+ os.replace(tmp, path)
73
+ except BaseException:
74
+ try:
75
+ os.unlink(tmp)
76
+ except OSError:
77
+ pass
78
+ raise
79
+
80
+
81
+ def clear() -> None:
82
+ """Remove this package's cache files; leave anything else alone."""
83
+ directory = cache_dir()
84
+ if not directory.is_dir():
85
+ return
86
+ for path in directory.glob("*.json"):
87
+ if _KEY_RE.fullmatch(path.stem):
88
+ try:
89
+ path.unlink()
90
+ except OSError:
91
+ pass
tuik/_fetch.py ADDED
@@ -0,0 +1,123 @@
1
+ """Cached fetching, result attributes and year filtering."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numbers
6
+ from collections.abc import Callable, Iterable
7
+ from datetime import datetime, timezone
8
+ from typing import TypeVar
9
+
10
+ import pandas as pd
11
+
12
+ from tuik import _cache
13
+ from tuik._http import NipClient
14
+ from tuik._version import __version__
15
+ from tuik._warn import warn
16
+ from tuik.errors import TuikConnectionError
17
+
18
+ _SOURCE = "TÜİK – Nüfus İstatistikleri Portalı"
19
+ _CLIENT: NipClient | None = None
20
+ _T = TypeVar("_T")
21
+
22
+
23
+ def _client() -> NipClient:
24
+ """Lazily created shared HTTP client."""
25
+ global _CLIENT
26
+ if _CLIENT is None:
27
+ _CLIENT = NipClient()
28
+ return _CLIENT
29
+
30
+
31
+ def get_raw(
32
+ key: str,
33
+ download: Callable[[], str],
34
+ refresh: bool = False,
35
+ validate: Callable[[str], object] | None = None,
36
+ ) -> tuple[str, datetime]:
37
+ """Return ``(payload, retrieved_at)``, using the cache when fresh.
38
+
39
+ If the download fails with a connection error and any cached copy exists,
40
+ that copy is returned with a warning. Response-format errors always propagate.
41
+ A freshly downloaded payload is passed to ``validate`` before it is cached;
42
+ if ``validate`` raises, nothing is written and any existing entry is kept.
43
+ """
44
+ entry = _cache.read(key)
45
+ if entry is not None and not refresh and _cache.is_fresh(entry):
46
+ return entry.payload, entry.retrieved_at
47
+ try:
48
+ payload = download()
49
+ except TuikConnectionError:
50
+ if entry is None:
51
+ raise
52
+ warn(
53
+ f"Could not reach TÜİK; using cached data from {entry.retrieved_at.date().isoformat()}",
54
+ UserWarning,
55
+ )
56
+ return entry.payload, entry.retrieved_at
57
+ if validate is not None:
58
+ validate(payload)
59
+ retrieved_at = datetime.now(timezone.utc)
60
+ try:
61
+ _cache.write(key, payload, retrieved_at)
62
+ except (OSError, ValueError) as exc:
63
+ warn(f"could not write cache: {exc}", UserWarning)
64
+ return payload, retrieved_at
65
+
66
+
67
+ def get_parsed(
68
+ key: str,
69
+ download: Callable[[], str],
70
+ parse: Callable[[str], _T],
71
+ refresh: bool = False,
72
+ ) -> tuple[_T, datetime]:
73
+ """Like :func:`get_raw`, but return ``parse(payload)``.
74
+
75
+ A fresh download is parsed before it is cached (so an unparsable response is
76
+ never cached) and that result is reused; a cached payload is parsed once here.
77
+ """
78
+ parsed: list[_T] = []
79
+
80
+ def validate(payload: str) -> None:
81
+ parsed.append(parse(payload))
82
+
83
+ payload, retrieved_at = get_raw(key, download, refresh=refresh, validate=validate)
84
+ return (parsed[0] if parsed else parse(payload)), retrieved_at
85
+
86
+
87
+ def attach_attrs(df: pd.DataFrame, source_url: str, retrieved_at: datetime) -> pd.DataFrame:
88
+ """Record provenance on ``df.attrs`` and return the same frame."""
89
+ df.attrs["source"] = _SOURCE
90
+ df.attrs["source_url"] = source_url
91
+ df.attrs["retrieved_at"] = retrieved_at.isoformat()
92
+ df.attrs["tuik_version"] = __version__
93
+ return df
94
+
95
+
96
+ def is_int(x: object) -> bool:
97
+ """True for Python and NumPy integers, False for ``bool``."""
98
+ return isinstance(x, numbers.Integral) and not isinstance(x, bool)
99
+
100
+
101
+ def filter_years(df: pd.DataFrame, year: None | int | Iterable[int]) -> pd.DataFrame:
102
+ """Keep rows whose ``year`` is requested; ``None`` returns ``df`` unchanged."""
103
+ if year is None:
104
+ return df
105
+ wanted: set[int]
106
+ req: object
107
+ if is_int(year):
108
+ req = int(year) # type: ignore[arg-type]
109
+ wanted = {req}
110
+ elif isinstance(year, (bool, str, bytes)) or not isinstance(year, Iterable):
111
+ raise TypeError("year must be an int, an iterable of ints, or None")
112
+ else:
113
+ items = list(year)
114
+ if not all(is_int(i) for i in items):
115
+ raise TypeError("year must contain only ints")
116
+ wanted = {int(i) for i in items}
117
+ req = sorted(wanted)
118
+ out = df[df["year"].isin(wanted)]
119
+ if out.empty:
120
+ available = sorted(int(y) for y in df["year"].unique())
121
+ raise ValueError(f"No data for year(s) {req}. Available years: {available}")
122
+ result: pd.DataFrame = out.reset_index(drop=True)
123
+ return result
tuik/_http.py ADDED
@@ -0,0 +1,140 @@
1
+ """Polite HTTP client for the TÜİK population portal (nip.tuik.gov.tr)."""
2
+
3
+ import json
4
+ import os
5
+ import time
6
+ from typing import Any
7
+
8
+ import requests
9
+ from tqdm import tqdm
10
+
11
+ from tuik._version import __version__
12
+ from tuik.errors import TuikConnectionError, TuikResponseError
13
+
14
+ BASE = "https://nip.tuik.gov.tr"
15
+ MIGRATION_PAGE = BASE + "/?value=IllerArasiGoc"
16
+ MIGRATION_URL = BASE + "/Home/IlYilIcGocIllerArasiForTable"
17
+ INFO_URL = BASE + "/Home/GetInformation"
18
+ PAGE_SIZE = 10000
19
+ TIMEOUT = (10, 180)
20
+ USER_AGENT = f"tuik-python/{__version__} (+https://github.com/ardaggec17-byte/tuik)"
21
+ _ISSUES = "TÜİK may have changed this service; please open an issue at https://github.com/ardaggec17-byte/tuik/issues"
22
+
23
+
24
+ def _bad(url: str, problem: str) -> TuikResponseError:
25
+ return TuikResponseError(f"{problem} (from {url}). {_ISSUES}")
26
+
27
+
28
+ class NipClient:
29
+ """Sequential, retrying client; never issues parallel requests."""
30
+
31
+ def __init__(
32
+ self,
33
+ session: requests.Session | None = None,
34
+ retries: int = 5,
35
+ page_delay: float = 1.0,
36
+ backoff: tuple[float, ...] = (1, 2, 4, 8),
37
+ ) -> None:
38
+ self._session = session or requests.Session()
39
+ self._session.headers.update(
40
+ {"X-Requested-With": "XMLHttpRequest", "User-Agent": USER_AGENT}
41
+ )
42
+ self._retries = max(1, retries)
43
+ self._page_delay = page_delay
44
+ self._backoff = backoff
45
+ self._visited: set[str] = set()
46
+
47
+ def _wait(self, attempt: int) -> None:
48
+ if not self._backoff:
49
+ return
50
+ time.sleep(self._backoff[min(attempt, len(self._backoff) - 1)])
51
+
52
+ def _request(self, method: str, url: str, data: dict[str, Any] | None = None) -> str:
53
+ last: Exception | None = None
54
+ for attempt in range(self._retries):
55
+ if attempt:
56
+ self._wait(attempt - 1)
57
+ try:
58
+ resp = self._session.request(method, url, data=data, timeout=TIMEOUT)
59
+ except requests.RequestException as exc:
60
+ last = exc
61
+ continue
62
+ if resp.status_code >= 500:
63
+ last = requests.HTTPError(f"HTTP {resp.status_code}")
64
+ continue
65
+ if resp.status_code >= 400:
66
+ raise _bad(url, f"HTTP {resp.status_code}")
67
+ if "charset" not in resp.headers.get("Content-Type", "").lower():
68
+ resp.encoding = "utf-8"
69
+ return resp.text
70
+ raise TuikConnectionError(f"Could not reach {url} after {self._retries} attempts: {last}")
71
+
72
+ def _visit(self, page: str) -> None:
73
+ if page not in self._visited:
74
+ self._request("GET", page)
75
+ self._visited.add(page)
76
+
77
+ def fetch_migration(self, progress: bool = True) -> list[dict[str, Any]]:
78
+ """Download every row of the inter-provincial migration table."""
79
+ self._visit(MIGRATION_PAGE)
80
+ disabled = (not progress) or os.environ.get("TUIK_PROGRESS") == "0"
81
+ rows: list[dict[str, Any]] = []
82
+ total: int | None = None
83
+ bar = tqdm(total=None, disable=disabled, unit="page", desc="TÜİK migration")
84
+ try:
85
+ while total is None or len(rows) < total:
86
+ if rows:
87
+ time.sleep(self._page_delay)
88
+ payload = self._migration_page(len(rows))
89
+ if total is not None and payload["recordsTotal"] != total:
90
+ raise _bad(
91
+ MIGRATION_URL,
92
+ f"recordsTotal changed between pages ({total} -> "
93
+ f"{payload['recordsTotal']})",
94
+ )
95
+ total = payload["recordsTotal"]
96
+ data = payload["data"]
97
+ if not data and len(rows) < total:
98
+ raise _bad(MIGRATION_URL, "Empty page before reaching recordsTotal")
99
+ rows.extend(data)
100
+ bar.total = -(-total // PAGE_SIZE)
101
+ bar.update(1)
102
+ finally:
103
+ bar.close()
104
+ if len(rows) != total:
105
+ raise _bad(MIGRATION_URL, f"Received {len(rows)} rows but recordsTotal is {total}")
106
+ return rows
107
+
108
+ def _migration_page(self, start: int) -> dict[str, Any]:
109
+ text = self._request(
110
+ "POST",
111
+ MIGRATION_URL,
112
+ data={
113
+ "draw": 1,
114
+ "start": start,
115
+ "length": PAGE_SIZE,
116
+ "alanIlAdi": "Hepsi",
117
+ "verenIlAdi": "Hepsi",
118
+ "search[value]": "",
119
+ },
120
+ )
121
+ try:
122
+ payload = json.loads(text)
123
+ except ValueError:
124
+ raise _bad(MIGRATION_URL, "Response is not JSON") from None
125
+ if (
126
+ not isinstance(payload, dict)
127
+ or not isinstance(payload.get("data"), list)
128
+ or not isinstance(payload.get("recordsTotal"), int)
129
+ or isinstance(payload.get("recordsTotal"), bool)
130
+ ):
131
+ raise _bad(MIGRATION_URL, "JSON lacks a list 'data' or integer 'recordsTotal'")
132
+ return payload
133
+
134
+ def fetch_table(self, page: str, value: str = "") -> str:
135
+ """Return the raw HTML fragment for a population table."""
136
+ self._visit(f"{BASE}/?value={page}")
137
+ html = self._request("POST", INFO_URL, data={"status": 1, "name": page, "value": value})
138
+ if "<table" not in html.lower():
139
+ raise _bad(INFO_URL, f"Response for {page!r} contains no <table>")
140
+ return html
tuik/_text.py ADDED
@@ -0,0 +1,45 @@
1
+ """Turkish-aware text helpers (case folding, title casing, number parsing)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import unicodedata
7
+
8
+ _INT_RE = re.compile(r"[0-9]{1,3}(\.[0-9]{3})*")
9
+ _FOLD_TABLE = str.maketrans("ığüşöçâîû", "igusocaiu")
10
+
11
+
12
+ def _lower_tr(s: str) -> str:
13
+ return s.replace("İ", "i").replace("I", "ı").lower()
14
+
15
+
16
+ def tr_fold(s: str) -> str:
17
+ """Lowercase with Turkish rules, strip diacritics, collapse whitespace.
18
+
19
+ For matching only; the result is not meant for display.
20
+ """
21
+ folded = _lower_tr(unicodedata.normalize("NFC", s)).translate(_FOLD_TABLE)
22
+ return " ".join(folded.split())
23
+
24
+
25
+ def _title_word(word: str) -> str:
26
+ if not word:
27
+ return word
28
+ first = word[0].replace("i", "İ").replace("ı", "I").upper()
29
+ return first + _lower_tr(word[1:])
30
+
31
+
32
+ def title_tr(s: str) -> str:
33
+ """Title-case each whitespace-separated word using Turkish rules."""
34
+ return " ".join(_title_word(w) for w in s.split())
35
+
36
+
37
+ def parse_tr_int(s: str) -> int:
38
+ """Parse an integer with Turkish thousands separators, e.g. ``"2.283.609"``.
39
+
40
+ Raises ``ValueError`` for anything that is not such a number.
41
+ """
42
+ text = s.strip()
43
+ if not _INT_RE.fullmatch(text):
44
+ raise ValueError(f"not a Turkish-formatted integer: {s!r}")
45
+ return int(text.replace(".", ""))
tuik/_validate.py ADDED
@@ -0,0 +1,102 @@
1
+ """Numeric consistency checks on parsed TÜİK data.
2
+
3
+ Inconsistencies in TÜİK's own data are reported with ``TuikDataWarning``;
4
+ data is never altered. Known source errors are listed and stay silent.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Mapping
10
+ from typing import Any
11
+
12
+ import pandas as pd
13
+
14
+ from tuik._warn import warn
15
+ from tuik.errors import TuikDataWarning
16
+
17
+ __all__ = [
18
+ "KNOWN_EXCEPTIONS",
19
+ "check_age_total",
20
+ "check_male_female",
21
+ "check_migration_symmetry",
22
+ "check_provinces_sum",
23
+ ]
24
+
25
+ _COUNTRY = "Türkiye"
26
+ _MAX_LISTED = 5
27
+
28
+ # (check name, year, province or "Türkiye"): known errors in TÜİK's source data.
29
+ KNOWN_EXCEPTIONS: frozenset[tuple[str, int, str]] = frozenset(
30
+ {("total_equals_male_female", 1960, "Amasya")}
31
+ )
32
+
33
+
34
+ def _report(check: str, violations: list[tuple[int, str]]) -> list[tuple[int, str]]:
35
+ kept = sorted(v for v in violations if (check, v[0], v[1]) not in KNOWN_EXCEPTIONS)
36
+ if kept:
37
+ listed = ", ".join(f"{y} {label}" for y, label in kept[:_MAX_LISTED])
38
+ extra = len(kept) - _MAX_LISTED
39
+ if extra > 0:
40
+ listed += f" and {extra} more"
41
+ warn(f"TÜİK source data inconsistency ({check}): {listed}", TuikDataWarning)
42
+ return kept
43
+
44
+
45
+ def check_male_female(df: pd.DataFrame) -> list[tuple[int, str]]:
46
+ """Return ``(year, province)`` rows where ``total != male + female``."""
47
+ bad = df[df["total"] != df["male"] + df["female"]]
48
+ found = [(int(y), str(p)) for y, p in zip(bad["year"], bad["province"])]
49
+ return _report("total_equals_male_female", found)
50
+
51
+
52
+ def check_provinces_sum(
53
+ provinces_df: pd.DataFrame, country_df: pd.DataFrame
54
+ ) -> list[tuple[int, str]]:
55
+ """Return years where the provinces' totals do not sum to the country total."""
56
+ sums = provinces_df.groupby("year")["total"].sum()
57
+ country = country_df.groupby("year")["total"].sum()
58
+ both = sums.index.intersection(country.index)
59
+ found = [(int(y), _COUNTRY) for y in both if sums[y] != country[y]]
60
+ return _report("provinces_sum", found)
61
+
62
+
63
+ def check_age_total(
64
+ groups_df: pd.DataFrame, totals: dict[int, tuple[int, int, int]]
65
+ ) -> list[tuple[int, str]]:
66
+ """Return years where age-group sums differ from the TOPLAM (total, male, female)."""
67
+ sums = groups_df.groupby("year")[["total", "male", "female"]].sum()
68
+ by_year = {
69
+ int(y): (int(t), int(m), int(f))
70
+ for y, t, m, f in zip(sums.index, sums["total"], sums["male"], sums["female"], strict=True)
71
+ }
72
+ found: list[tuple[int, str]] = []
73
+ for year, expected in totals.items():
74
+ actual = by_year.get(int(year))
75
+ if actual is not None and actual != tuple(int(v) for v in expected):
76
+ found.append((int(year), _COUNTRY))
77
+ return _report("age_total", found)
78
+
79
+
80
+ def check_migration_symmetry(
81
+ raw_rows: list[dict[str, Any]], names: Mapping[int, str] | None = None
82
+ ) -> list[tuple[int, str]]:
83
+ """Check that A→B ``VerdigiGoc`` equals B→A ``AldigiGoc`` in the same year.
84
+
85
+ Violations are labelled ``"origin→destination"`` using ``names`` (plate code
86
+ to display name) when given, otherwise TÜİK's raw province spelling.
87
+ """
88
+ labels = names or {}
89
+ index = {(int(r["Yil"]), int(r["AlanIlKodu"]), int(r["VerenIlKodu"])): r for r in raw_rows}
90
+ found: dict[tuple[int, int, int], tuple[int, str]] = {}
91
+ for (year, alan, veren), row in index.items():
92
+ reverse = index.get((year, veren, alan))
93
+ if reverse is not None and int(row["VerdigiGoc"]) == int(reverse["AldigiGoc"]):
94
+ continue
95
+ # report each unordered pair once, labelled from the lower-code veren
96
+ # direction (or the only row present) so output ignores row order
97
+ key = (year, min(alan, veren), max(alan, veren))
98
+ canonical = row if reverse is None or veren < alan else reverse
99
+ origin = labels.get(int(canonical["VerenIlKodu"]), canonical["VerenIlAdi"])
100
+ destination = labels.get(int(canonical["AlanIlKodu"]), canonical["AlanIlAdi"])
101
+ found[key] = (year, f"{origin}→{destination}")
102
+ return _report("migration_symmetry", list(found.values()))
tuik/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
tuik/_warn.py ADDED
@@ -0,0 +1,20 @@
1
+ """Warnings that point at the user's code, not at tuik internals."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import warnings
7
+
8
+
9
+ def _internal(module: object) -> bool:
10
+ return isinstance(module, str) and (module == "tuik" or module.startswith("tuik."))
11
+
12
+
13
+ def warn(message: str, category: type[Warning]) -> None:
14
+ """Issue ``message`` attributed to the first stack frame outside the tuik package."""
15
+ frame = sys._getframe(1)
16
+ level = 2 # stacklevel of ``frame`` as seen from warnings.warn below
17
+ while frame.f_back is not None and _internal(frame.f_globals.get("__name__")):
18
+ frame = frame.f_back
19
+ level += 1
20
+ warnings.warn(message, category, stacklevel=level)
tuik/cite.py ADDED
@@ -0,0 +1,39 @@
1
+ """Plain-text citation of the package and of the data it returned."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pandas as pd
6
+
7
+ from tuik._version import __version__
8
+
9
+ _RELEASE_YEAR = 2026
10
+ _REPO_URL = "https://github.com/ardaggec17-byte/tuik"
11
+
12
+
13
+ def _package_citation() -> str:
14
+ return (
15
+ f"Canpolat, A. E. ({_RELEASE_YEAR}). tuik: Unofficial Python client for TÜİK "
16
+ f"population and migration data (Version {__version__}) [Computer software]. "
17
+ f"{_REPO_URL}"
18
+ )
19
+
20
+
21
+ def cite(df: pd.DataFrame | None = None) -> str:
22
+ """Return a plain-text, APA-style citation.
23
+
24
+ Without ``df`` the citation is for the ``tuik`` package. With a DataFrame
25
+ returned by this package, a line crediting the data source (with its URL and
26
+ retrieval date) is placed before the package citation.
27
+
28
+ Raises ``ValueError`` if ``df.attrs`` has no ``"source"`` entry.
29
+ """
30
+ package = _package_citation()
31
+ if df is None:
32
+ return package
33
+ attrs = df.attrs
34
+ if "source" not in attrs:
35
+ raise ValueError("df.attrs has no 'source'; pass a DataFrame returned by tuik")
36
+ retrieved = str(attrs.get("retrieved_at", ""))[:10]
37
+ version = attrs.get("tuik_version", __version__)
38
+ line = f"{attrs['source']}. {attrs.get('source_url', '')}. Retrieved {retrieved}, via tuik {version}."
39
+ return f"{line}\n\n{package}"
@@ -0,0 +1,8 @@
1
+ raw,code,name
2
+ ELAZIĞ (ELAZİZ),23,Elazığ
3
+ ŞANLIURFA (URFA),63,Şanlıurfa
4
+ İÇEL (İÇEL ve MERSİN),33,Mersin
5
+ İÇEL,33,Mersin
6
+ BAYAZIT,,Bayazıt
7
+ CEBELİBEREKET,,Cebelibereket
8
+ ŞEBİNKARAHİSAR,,Şebinkarahisar