qums-fetch 0.4.4.dev2__tar.gz → 0.5.0__tar.gz
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.
- {qums_fetch-0.4.4.dev2 → qums_fetch-0.5.0}/PKG-INFO +15 -14
- qums_fetch-0.5.0/README.md +54 -0
- {qums_fetch-0.4.4.dev2 → qums_fetch-0.5.0}/pyproject.toml +4 -3
- {qums_fetch-0.4.4.dev2 → qums_fetch-0.5.0}/pyproject.toml.orig +4 -3
- {qums_fetch-0.4.4.dev2 → qums_fetch-0.5.0}/src/qums_fetch/__init__.py +2 -1
- qums_fetch-0.5.0/src/qums_fetch/_internal/login.py +66 -0
- qums_fetch-0.5.0/src/qums_fetch/_internal/responses.py +28 -0
- qums_fetch-0.5.0/src/qums_fetch/attendance.py +86 -0
- qums_fetch-0.5.0/src/qums_fetch/captcha.py +85 -0
- qums_fetch-0.5.0/src/qums_fetch/client.py +153 -0
- qums_fetch-0.5.0/src/qums_fetch/exceptions.py +26 -0
- qums_fetch-0.5.0/src/qums_fetch/py.typed +0 -0
- qums_fetch-0.5.0/src/qums_fetch/student.py +85 -0
- qums_fetch-0.4.4.dev2/README.md +0 -52
- qums_fetch-0.4.4.dev2/src/qums_fetch/captcha.py +0 -108
- qums_fetch-0.4.4.dev2/src/qums_fetch/client.py +0 -435
- qums_fetch-0.4.4.dev2/src/qums_fetch/exceptions.py +0 -40
- /qums_fetch-0.4.4.dev2/src/qums_fetch/py.typed → /qums_fetch-0.5.0/src/qums_fetch/_internal/__init__.py +0 -0
|
@@ -1,18 +1,17 @@
|
|
|
1
1
|
Metadata-Version: 2.3
|
|
2
2
|
Name: qums-fetch
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.0
|
|
4
4
|
Summary: Login and fetch data from QUMS-ERP Dashboard
|
|
5
5
|
Author: Ishaan Gupta
|
|
6
6
|
Author-email: Ishaan Gupta <ishaan.ishu@proton.me>
|
|
7
7
|
Requires-Dist: beautifulsoup4>=4.15.0
|
|
8
8
|
Requires-Dist: pillow>=12.3.0
|
|
9
9
|
Requires-Dist: pytesseract>=0.3.13
|
|
10
|
-
Requires-Dist: python-dotenv>=1.2.2
|
|
11
10
|
Requires-Dist: requests>=2.34.2
|
|
12
11
|
Requires-Python: >=3.14
|
|
13
12
|
Description-Content-Type: text/markdown
|
|
14
13
|
|
|
15
|
-
# qums
|
|
14
|
+
# qums-fetch
|
|
16
15
|
|
|
17
16
|
Automatically fetch student data from QUMS
|
|
18
17
|
|
|
@@ -33,14 +32,7 @@ scoop install tesseract
|
|
|
33
32
|
|
|
34
33
|
## Quick start
|
|
35
34
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
```env
|
|
39
|
-
QUMS_USERNAME=your_username
|
|
40
|
-
QUMS_PASSWORD=your_password
|
|
41
|
-
```
|
|
42
|
-
|
|
43
|
-
Then install the package:
|
|
35
|
+
Install the package:
|
|
44
36
|
|
|
45
37
|
```bash
|
|
46
38
|
pip install qums-fetch
|
|
@@ -48,14 +40,23 @@ pip install qums-fetch
|
|
|
48
40
|
|
|
49
41
|
## Usage
|
|
50
42
|
|
|
43
|
+
> [!NOTE]
|
|
44
|
+
> Captchas are solved with Tesseract by default. To use a different engine, pass `ocr=your_callable` to `Client`. The callable accepts a Pillow image and returns a string.
|
|
45
|
+
|
|
51
46
|
```python
|
|
52
47
|
from qums_fetch import Client
|
|
53
48
|
|
|
54
|
-
client = Client(
|
|
55
|
-
print(client.
|
|
56
|
-
print(client.
|
|
49
|
+
client = Client("your_username", "your_password")
|
|
50
|
+
print(client.student.details)
|
|
51
|
+
print(client.attendance.today)
|
|
57
52
|
```
|
|
58
53
|
|
|
54
|
+
Data endpoints are grouped under `client.student` (`details`, `tile_data`, and `photo`) and `client.attendance` (`today`, `month`, and `semester`). To migrate from the flat API, use `client.student.get_details()` instead of `client.get_student_details()`, or `client.attendance.get_today()` instead of `client.get_today_attendance()`.
|
|
55
|
+
|
|
56
|
+
Data properties fetch on first access and cache the result. Call the corresponding `get_*` method to refresh and return the data. The photo is loaded along with the student details.
|
|
57
|
+
|
|
58
|
+
An explicit month or semester, such as `client.attendance.get_month(month=4)`, returns that period's data without replacing the default property's cache.
|
|
59
|
+
|
|
59
60
|
## Development
|
|
60
61
|
|
|
61
62
|
See [CONTRIBUTING.md](CONTRIBUTING.md) for setup instructions.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# qums-fetch
|
|
2
|
+
|
|
3
|
+
Automatically fetch student data from QUMS
|
|
4
|
+
|
|
5
|
+
## Prerequisites
|
|
6
|
+
|
|
7
|
+
[Tesseract OCR](https://github.com/tesseract-ocr/tesseract) must be installed on your system for captcha solving:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
# Ubuntu/Debian
|
|
11
|
+
sudo apt-get install tesseract-ocr
|
|
12
|
+
|
|
13
|
+
# macOS
|
|
14
|
+
brew install tesseract
|
|
15
|
+
|
|
16
|
+
# Windows
|
|
17
|
+
scoop install tesseract
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Quick start
|
|
21
|
+
|
|
22
|
+
Install the package:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install qums-fetch
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Usage
|
|
29
|
+
|
|
30
|
+
> [!NOTE]
|
|
31
|
+
> Captchas are solved with Tesseract by default. To use a different engine, pass `ocr=your_callable` to `Client`. The callable accepts a Pillow image and returns a string.
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from qums_fetch import Client
|
|
35
|
+
|
|
36
|
+
client = Client("your_username", "your_password")
|
|
37
|
+
print(client.student.details)
|
|
38
|
+
print(client.attendance.today)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Data endpoints are grouped under `client.student` (`details`, `tile_data`, and `photo`) and `client.attendance` (`today`, `month`, and `semester`). To migrate from the flat API, use `client.student.get_details()` instead of `client.get_student_details()`, or `client.attendance.get_today()` instead of `client.get_today_attendance()`.
|
|
42
|
+
|
|
43
|
+
Data properties fetch on first access and cache the result. Call the corresponding `get_*` method to refresh and return the data. The photo is loaded along with the student details.
|
|
44
|
+
|
|
45
|
+
An explicit month or semester, such as `client.attendance.get_month(month=4)`, returns that period's data without replacing the default property's cache.
|
|
46
|
+
|
|
47
|
+
## Development
|
|
48
|
+
|
|
49
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for setup instructions.
|
|
50
|
+
Check [TODO.md](TODO.md) for open tasks and API coverage.
|
|
51
|
+
|
|
52
|
+
## Credits
|
|
53
|
+
|
|
54
|
+
The captcha solving approach in this project is based on [Kyun-UMS](https://github.com/24kaushik/Kyun-UMS) by [24kaushik](https://github.com/24kaushik).
|
|
@@ -4,7 +4,7 @@ build-backend = "uv_build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "qums-fetch"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.5.0"
|
|
8
8
|
description = "Login and fetch data from QUMS-ERP Dashboard"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.14"
|
|
@@ -12,7 +12,6 @@ dependencies = [
|
|
|
12
12
|
"beautifulsoup4>=4.15.0",
|
|
13
13
|
"pillow>=12.3.0",
|
|
14
14
|
"pytesseract>=0.3.13",
|
|
15
|
-
"python-dotenv>=1.2.2",
|
|
16
15
|
"requests>=2.34.2",
|
|
17
16
|
]
|
|
18
17
|
|
|
@@ -23,8 +22,10 @@ email = "ishaan.ishu@proton.me"
|
|
|
23
22
|
[dependency-groups]
|
|
24
23
|
dev = [
|
|
25
24
|
"pytest>=9.1.1",
|
|
25
|
+
"python-dotenv>=1.2.3",
|
|
26
26
|
"ruff>=0.16.5",
|
|
27
|
+
"ty>=0.0.78",
|
|
27
28
|
]
|
|
28
29
|
|
|
29
30
|
[tool.pytest.ini_options]
|
|
30
|
-
testpaths = ["
|
|
31
|
+
testpaths = ["tests/unit"]
|
|
@@ -4,7 +4,7 @@ build-backend = "uv_build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "qums-fetch"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.5.0"
|
|
8
8
|
description = "Login and fetch data from QUMS-ERP Dashboard"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
authors = [
|
|
@@ -15,15 +15,16 @@ dependencies = [
|
|
|
15
15
|
"beautifulsoup4>=4.15.0",
|
|
16
16
|
"pillow>=12.3.0",
|
|
17
17
|
"pytesseract>=0.3.13",
|
|
18
|
-
"python-dotenv>=1.2.2",
|
|
19
18
|
"requests>=2.34.2",
|
|
20
19
|
]
|
|
21
20
|
|
|
22
21
|
[dependency-groups]
|
|
23
22
|
dev = [
|
|
24
23
|
"pytest>=9.1.1",
|
|
24
|
+
"python-dotenv>=1.2.3",
|
|
25
25
|
"ruff>=0.16.5",
|
|
26
|
+
"ty>=0.0.78",
|
|
26
27
|
]
|
|
27
28
|
|
|
28
29
|
[tool.pytest.ini_options]
|
|
29
|
-
testpaths = ["
|
|
30
|
+
testpaths = ["tests/unit"]
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import re
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from bs4 import BeautifulSoup
|
|
6
|
+
|
|
7
|
+
from ..exceptions import (
|
|
8
|
+
CaptchaError,
|
|
9
|
+
CredentialsError,
|
|
10
|
+
LoginFailedError,
|
|
11
|
+
LoginPageParseError,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
CAPTCHA_IMG_SELECTOR = "#imgPhoto"
|
|
15
|
+
TOKEN_INPUT_NAME = "__RequestVerificationToken"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class CaptchaChallenge:
|
|
20
|
+
token: str
|
|
21
|
+
image_bytes: bytes
|
|
22
|
+
image_mime: str
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def parse_challenge(html: str) -> CaptchaChallenge:
|
|
26
|
+
page = BeautifulSoup(html, "html.parser")
|
|
27
|
+
token_input = page.find("input", attrs={"name": TOKEN_INPUT_NAME})
|
|
28
|
+
if not token_input or not token_input.get("value"):
|
|
29
|
+
raise LoginPageParseError(f"Missing login input {TOKEN_INPUT_NAME!r}.")
|
|
30
|
+
|
|
31
|
+
image = page.select_one(CAPTCHA_IMG_SELECTOR)
|
|
32
|
+
if not image or not image.get("src"):
|
|
33
|
+
raise LoginPageParseError(f"Missing captcha image {CAPTCHA_IMG_SELECTOR!r}.")
|
|
34
|
+
|
|
35
|
+
match = re.fullmatch(r"data:(image/\w+);base64,(.+)", str(image["src"]), re.DOTALL)
|
|
36
|
+
if not match:
|
|
37
|
+
raise LoginPageParseError("Captcha image is not a base64 data URI.")
|
|
38
|
+
|
|
39
|
+
mime, encoded = match.groups()
|
|
40
|
+
try:
|
|
41
|
+
image_bytes = base64.b64decode("".join(encoded.split()), validate=True)
|
|
42
|
+
except ValueError as exc:
|
|
43
|
+
raise LoginPageParseError("Captcha image contains invalid base64.") from exc
|
|
44
|
+
if not image_bytes:
|
|
45
|
+
raise LoginPageParseError("Captcha image is empty.")
|
|
46
|
+
return CaptchaChallenge(str(token_input["value"]), image_bytes, mime)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def check_login_response(html: str) -> None:
|
|
50
|
+
page = BeautifulSoup(html, "html.parser")
|
|
51
|
+
errors = page.select(".validation-summary-errors, .field-validation-error")
|
|
52
|
+
messages = []
|
|
53
|
+
for validation in errors:
|
|
54
|
+
message = validation.get_text(" ", strip=True)
|
|
55
|
+
if not message:
|
|
56
|
+
continue
|
|
57
|
+
messages.append(message)
|
|
58
|
+
normalized = message.casefold()
|
|
59
|
+
if "captcha" in normalized:
|
|
60
|
+
raise CaptchaError(message)
|
|
61
|
+
if "incorrect" in normalized and (
|
|
62
|
+
"password" in normalized or "username" in normalized
|
|
63
|
+
):
|
|
64
|
+
raise CredentialsError(message)
|
|
65
|
+
if errors or page.select_one(CAPTCHA_IMG_SELECTOR):
|
|
66
|
+
raise LoginFailedError(" ".join(messages) or "The server rejected the login.")
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from requests import Response
|
|
5
|
+
|
|
6
|
+
from ..exceptions import InvalidResponseError
|
|
7
|
+
|
|
8
|
+
type Row = dict[str, Any]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def read_rows(response: Response, field: str = "state") -> list[Row]:
|
|
12
|
+
try:
|
|
13
|
+
rows = json.loads(response.json()[field])
|
|
14
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
15
|
+
raise InvalidResponseError(
|
|
16
|
+
f"Could not decode {field!r} in the response."
|
|
17
|
+
) from exc
|
|
18
|
+
|
|
19
|
+
if not isinstance(rows, list) or not all(isinstance(row, dict) for row in rows):
|
|
20
|
+
raise InvalidResponseError(f"Expected a list of records in {field!r}.")
|
|
21
|
+
return rows
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def read_first_row(response: Response, field: str = "state") -> Row:
|
|
25
|
+
rows = read_rows(response, field)
|
|
26
|
+
if not rows:
|
|
27
|
+
raise InvalidResponseError(f"Expected a record in {field!r}.")
|
|
28
|
+
return rows[0]
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
from datetime import UTC, datetime
|
|
2
|
+
from typing import TYPE_CHECKING, TypedDict
|
|
3
|
+
|
|
4
|
+
from ._internal.responses import Row, read_first_row, read_rows
|
|
5
|
+
from .exceptions import InvalidResponseError
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from .client import Client
|
|
9
|
+
|
|
10
|
+
ACADEMIC_PATH = "Web_StudentAcademic"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class MonthAttendance(TypedDict):
|
|
14
|
+
overview: Row
|
|
15
|
+
details: list[Row]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Attendance:
|
|
19
|
+
def __init__(self, client: Client):
|
|
20
|
+
self._client = client
|
|
21
|
+
self._clear_cache()
|
|
22
|
+
|
|
23
|
+
def _clear_cache(self) -> None:
|
|
24
|
+
self._today: list[Row] | None = None
|
|
25
|
+
self._month: MonthAttendance | None = None
|
|
26
|
+
self._semester: list[Row] | None = None
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def today(self) -> list[Row]:
|
|
30
|
+
if self._today is None:
|
|
31
|
+
return self.get_today()
|
|
32
|
+
return self._today
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def month(self) -> MonthAttendance:
|
|
36
|
+
if self._month is None:
|
|
37
|
+
return self.get_month()
|
|
38
|
+
return self._month
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def semester(self) -> list[Row]:
|
|
42
|
+
if self._semester is None:
|
|
43
|
+
return self.get_semester()
|
|
44
|
+
return self._semester
|
|
45
|
+
|
|
46
|
+
def get_today(self) -> list[Row]:
|
|
47
|
+
details = self._client.student._ensure_details()
|
|
48
|
+
response = self._client._post(
|
|
49
|
+
f"{ACADEMIC_PATH}/GetTodayAttendance",
|
|
50
|
+
{
|
|
51
|
+
"RegID": details["RegID"],
|
|
52
|
+
"date": datetime.now(tz=UTC).strftime("%d/%m/%Y"),
|
|
53
|
+
},
|
|
54
|
+
)
|
|
55
|
+
self._today = read_rows(response)
|
|
56
|
+
return self._today
|
|
57
|
+
|
|
58
|
+
def get_month(self, month: int | None = None) -> MonthAttendance:
|
|
59
|
+
details = self._client.student._ensure_details()
|
|
60
|
+
response = self._client._post(
|
|
61
|
+
f"{ACADEMIC_PATH}/GetMonthRegister",
|
|
62
|
+
{
|
|
63
|
+
"RegID": details["RegID"],
|
|
64
|
+
"Month": datetime.now(tz=UTC).month if month is None else month,
|
|
65
|
+
},
|
|
66
|
+
)
|
|
67
|
+
result = MonthAttendance(
|
|
68
|
+
overview=read_first_row(response, "data"), details=read_rows(response)
|
|
69
|
+
)
|
|
70
|
+
if month is None:
|
|
71
|
+
self._month = result
|
|
72
|
+
return result
|
|
73
|
+
|
|
74
|
+
def get_semester(self, sem: int | None = None) -> list[Row]:
|
|
75
|
+
details = self._client.student._ensure_details()
|
|
76
|
+
year_sem = details.get("YearSem") if sem is None else sem
|
|
77
|
+
if not isinstance(year_sem, int):
|
|
78
|
+
raise InvalidResponseError("Student details lack a valid YearSem.")
|
|
79
|
+
response = self._client._post(
|
|
80
|
+
f"{ACADEMIC_PATH}/GetYearSemWiseAttendance",
|
|
81
|
+
{"RegID": details["RegID"], "YearSem": year_sem},
|
|
82
|
+
)
|
|
83
|
+
result = read_rows(response, "data")
|
|
84
|
+
if sem is None:
|
|
85
|
+
self._semester = result
|
|
86
|
+
return result
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from collections.abc import Callable
|
|
3
|
+
from io import BytesIO
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import pytesseract
|
|
7
|
+
from PIL import Image
|
|
8
|
+
|
|
9
|
+
from .exceptions import BlankCaptchaError, CaptchaError
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CaptchaSolver:
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
image_bytes: bytes,
|
|
18
|
+
img_path: str | None = None,
|
|
19
|
+
ocr: Callable[[Image.Image], str] | None = None,
|
|
20
|
+
):
|
|
21
|
+
self.psm: int = 7
|
|
22
|
+
self.allowed_chars: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
23
|
+
self.threshold: int = 128
|
|
24
|
+
self.bg_frac: float = 0.001
|
|
25
|
+
self.image_bytes: bytes = image_bytes
|
|
26
|
+
self.ocr: Callable[[Image.Image], str] | None = ocr
|
|
27
|
+
self.img_dump_path: Path | None = Path(img_path) if img_path else None
|
|
28
|
+
self.bw_dump_path: Path | None = (
|
|
29
|
+
self.img_dump_path.with_name(f"bw_{self.img_dump_path.name}")
|
|
30
|
+
if self.img_dump_path
|
|
31
|
+
else None
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def config(self) -> str:
|
|
36
|
+
return f"--psm {self.psm} -c tessedit_char_whitelist={self.allowed_chars}"
|
|
37
|
+
|
|
38
|
+
def _preprocess(self, image_bytes: bytes) -> Image.Image:
|
|
39
|
+
with Image.open(BytesIO(image_bytes)) as image:
|
|
40
|
+
return image.convert("L").point(
|
|
41
|
+
lambda pixel: 255 if pixel > self.threshold else 0
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
def _looks_blank(self, bw_image: Image.Image) -> bool:
|
|
45
|
+
histogram = bw_image.histogram()
|
|
46
|
+
total_pixels = bw_image.width * bw_image.height
|
|
47
|
+
if total_pixels == 0:
|
|
48
|
+
return True
|
|
49
|
+
dark_fraction = histogram[0] / total_pixels
|
|
50
|
+
non_background_fraction = min(dark_fraction, 1 - dark_fraction)
|
|
51
|
+
return non_background_fraction < self.bg_frac
|
|
52
|
+
|
|
53
|
+
def _solve_captcha(self) -> str:
|
|
54
|
+
if self.img_dump_path:
|
|
55
|
+
self.img_dump_path.parent.mkdir(parents=True, exist_ok=True)
|
|
56
|
+
self.img_dump_path.write_bytes(self.image_bytes)
|
|
57
|
+
logger.info("Saved captcha image to '%s'", self.img_dump_path)
|
|
58
|
+
|
|
59
|
+
bw = self._preprocess(self.image_bytes)
|
|
60
|
+
|
|
61
|
+
if self.bw_dump_path:
|
|
62
|
+
bw.save(self.bw_dump_path)
|
|
63
|
+
logger.info("Saved preprocessed captcha to '%s'", self.bw_dump_path)
|
|
64
|
+
|
|
65
|
+
if self._looks_blank(bw):
|
|
66
|
+
raise BlankCaptchaError(
|
|
67
|
+
"Captcha image appears blank/placeholder after thresholding — "
|
|
68
|
+
"skipping OCR. Fetch a fresh challenge and try again."
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
if self.ocr is not None:
|
|
72
|
+
text = self.ocr(bw)
|
|
73
|
+
else:
|
|
74
|
+
text = pytesseract.image_to_string(bw, config=self.config)
|
|
75
|
+
|
|
76
|
+
return text.strip()
|
|
77
|
+
|
|
78
|
+
def guess(self) -> str:
|
|
79
|
+
try:
|
|
80
|
+
return self._solve_captcha()
|
|
81
|
+
except BlankCaptchaError:
|
|
82
|
+
raise
|
|
83
|
+
except Exception as e:
|
|
84
|
+
logger.error("%s", e)
|
|
85
|
+
raise CaptchaError("Could not solve captcha.") from e
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from collections.abc import Callable, Mapping
|
|
3
|
+
|
|
4
|
+
import requests
|
|
5
|
+
from PIL import Image
|
|
6
|
+
|
|
7
|
+
from ._internal.login import (
|
|
8
|
+
TOKEN_INPUT_NAME,
|
|
9
|
+
CaptchaChallenge,
|
|
10
|
+
check_login_response,
|
|
11
|
+
parse_challenge,
|
|
12
|
+
)
|
|
13
|
+
from ._internal.responses import Row
|
|
14
|
+
from .attendance import Attendance
|
|
15
|
+
from .captcha import CaptchaSolver
|
|
16
|
+
from .exceptions import (
|
|
17
|
+
BlankCaptchaError,
|
|
18
|
+
CredentialsError,
|
|
19
|
+
LoginFailedError,
|
|
20
|
+
)
|
|
21
|
+
from .student import Student
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
BASE_URL = "https://qums.quantumuniversity.edu.in"
|
|
26
|
+
DEFAULT_HEADERS = {
|
|
27
|
+
"User-Agent": (
|
|
28
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
|
29
|
+
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
|
30
|
+
"Chrome/124.0 Safari/537.36"
|
|
31
|
+
),
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Client:
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
username: str,
|
|
39
|
+
password: str,
|
|
40
|
+
auto_login: bool = True,
|
|
41
|
+
login_retries: int = 3,
|
|
42
|
+
cookies: Mapping[str, str | None] | None = None,
|
|
43
|
+
ocr: Callable[[Image.Image], str] | None = None,
|
|
44
|
+
):
|
|
45
|
+
if not username or not password:
|
|
46
|
+
raise ValueError("Username and password are required.")
|
|
47
|
+
if login_retries < 1:
|
|
48
|
+
raise ValueError("login_retries must be greater than 0.")
|
|
49
|
+
|
|
50
|
+
self.username = username
|
|
51
|
+
self._password = password
|
|
52
|
+
self._login_retries = login_retries
|
|
53
|
+
self._ocr = ocr
|
|
54
|
+
self._session = requests.Session()
|
|
55
|
+
self._session.headers.update(DEFAULT_HEADERS)
|
|
56
|
+
self._logged_in = False
|
|
57
|
+
self.student = Student(self)
|
|
58
|
+
self.attendance = Attendance(self)
|
|
59
|
+
|
|
60
|
+
if cookies:
|
|
61
|
+
for name, value in cookies.items():
|
|
62
|
+
self._session.cookies.set(name, value)
|
|
63
|
+
if auto_login:
|
|
64
|
+
if cookies and self.student._check_session() is not None:
|
|
65
|
+
self._logged_in = True
|
|
66
|
+
logger.info("Session restored from cookies.")
|
|
67
|
+
else:
|
|
68
|
+
self.login()
|
|
69
|
+
|
|
70
|
+
def _clear_cached_data(self) -> None:
|
|
71
|
+
self.student._clear_cache()
|
|
72
|
+
self.attendance._clear_cache()
|
|
73
|
+
|
|
74
|
+
def _ensure_session(self) -> Row | None:
|
|
75
|
+
if self._logged_in:
|
|
76
|
+
details = self.student._check_session()
|
|
77
|
+
if details is not None:
|
|
78
|
+
return details
|
|
79
|
+
logger.info("Session expired, re-logging in.")
|
|
80
|
+
self.login()
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
def login(self, max_attempts: int | None = None) -> bool:
|
|
84
|
+
if max_attempts is None:
|
|
85
|
+
max_attempts = self._login_retries
|
|
86
|
+
if max_attempts < 1:
|
|
87
|
+
raise ValueError("max_attempts must be greater than 0.")
|
|
88
|
+
|
|
89
|
+
self._logged_in = False
|
|
90
|
+
self._clear_cached_data()
|
|
91
|
+
last_error: Exception | None = None
|
|
92
|
+
for attempt in range(1, max_attempts + 1):
|
|
93
|
+
try:
|
|
94
|
+
challenge = self.fetch_login_challenge()
|
|
95
|
+
solver = CaptchaSolver(challenge.image_bytes, ocr=self._ocr)
|
|
96
|
+
return self.submit_login(challenge, solver.guess())
|
|
97
|
+
except CredentialsError:
|
|
98
|
+
raise
|
|
99
|
+
except (BlankCaptchaError, LoginFailedError) as exc:
|
|
100
|
+
last_error = exc
|
|
101
|
+
logger.warning(
|
|
102
|
+
"Login attempt %d/%d failed: %s", attempt, max_attempts, exc
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
raise LoginFailedError(
|
|
106
|
+
f"Login failed after {max_attempts} attempts."
|
|
107
|
+
) from last_error
|
|
108
|
+
|
|
109
|
+
def fetch_login_challenge(self) -> CaptchaChallenge:
|
|
110
|
+
response = self._session.get(BASE_URL, timeout=15)
|
|
111
|
+
response.raise_for_status()
|
|
112
|
+
return parse_challenge(response.text)
|
|
113
|
+
|
|
114
|
+
def submit_login(self, challenge: CaptchaChallenge, captcha_value: str) -> bool:
|
|
115
|
+
response = self._session.post(
|
|
116
|
+
BASE_URL,
|
|
117
|
+
data={
|
|
118
|
+
"hdnMsg": "QGC",
|
|
119
|
+
"checkOnline": "0",
|
|
120
|
+
TOKEN_INPUT_NAME: challenge.token,
|
|
121
|
+
"UserName": self.username,
|
|
122
|
+
"Password": self._password,
|
|
123
|
+
"clientIP": "~~~~~",
|
|
124
|
+
"captcha": captcha_value,
|
|
125
|
+
},
|
|
126
|
+
timeout=5,
|
|
127
|
+
allow_redirects=False,
|
|
128
|
+
)
|
|
129
|
+
response.raise_for_status()
|
|
130
|
+
check_login_response(response.text)
|
|
131
|
+
|
|
132
|
+
self._clear_cached_data()
|
|
133
|
+
self._logged_in = True
|
|
134
|
+
logger.info("Login succeeded.")
|
|
135
|
+
return True
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
def is_logged_in(self) -> bool:
|
|
139
|
+
return self._logged_in
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def get_cookies(self) -> dict[str, str | None]:
|
|
143
|
+
return self._session.cookies.get_dict()
|
|
144
|
+
|
|
145
|
+
def _post(
|
|
146
|
+
self, path: str, data: dict[str, str | int] | None = None
|
|
147
|
+
) -> requests.Response:
|
|
148
|
+
response = self._session.post(
|
|
149
|
+
f"{BASE_URL}/{path}", data=data, timeout=5, allow_redirects=False
|
|
150
|
+
)
|
|
151
|
+
logger.info("POST [%d] %s", response.status_code, response.url)
|
|
152
|
+
response.raise_for_status()
|
|
153
|
+
return response
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
class Error(Exception):
|
|
2
|
+
"""Base exception for all client errors."""
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class LoginPageParseError(Error):
|
|
6
|
+
"""The login page did not contain a usable token and captcha image."""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class LoginFailedError(Error):
|
|
10
|
+
"""The server rejected the login or the client ran out of attempts."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CaptchaError(LoginFailedError):
|
|
14
|
+
"""The client could not solve the captcha or the server rejected its answer."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CredentialsError(LoginFailedError):
|
|
18
|
+
"""The server rejected the username or password."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class InvalidResponseError(Error):
|
|
22
|
+
"""The server returned data in an unexpected format."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class BlankCaptchaError(Error):
|
|
26
|
+
"""The captcha image appeared blank."""
|
|
File without changes
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
from typing import TYPE_CHECKING
|
|
3
|
+
|
|
4
|
+
import requests
|
|
5
|
+
|
|
6
|
+
from ._internal.responses import Row, read_first_row, read_rows
|
|
7
|
+
from .exceptions import InvalidResponseError
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from .client import Client
|
|
11
|
+
|
|
12
|
+
STUDENT_DETAILS_PATH = "Account/GetStudentDetail"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Student:
|
|
16
|
+
def __init__(self, client: Client):
|
|
17
|
+
self._client = client
|
|
18
|
+
self._clear_cache()
|
|
19
|
+
|
|
20
|
+
def _clear_cache(self) -> None:
|
|
21
|
+
self._details: Row | None = None
|
|
22
|
+
self._tile_data: list[Row] | None = None
|
|
23
|
+
self.photo: bytes | None = None
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def details(self) -> Row:
|
|
27
|
+
if self._details is None:
|
|
28
|
+
return self.get_details()
|
|
29
|
+
return self._details
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def tile_data(self) -> list[Row]:
|
|
33
|
+
if self._tile_data is None:
|
|
34
|
+
return self.get_tile_data()
|
|
35
|
+
return self._tile_data
|
|
36
|
+
|
|
37
|
+
def get_details(self) -> Row:
|
|
38
|
+
return self._load_details(self._client._ensure_session())
|
|
39
|
+
|
|
40
|
+
def get_tile_data(self) -> list[Row]:
|
|
41
|
+
details = self._ensure_details()
|
|
42
|
+
response = self._client._post(
|
|
43
|
+
"Web_StudentAcademic/GetStudentTileData", {"RegID": details["RegID"]}
|
|
44
|
+
)
|
|
45
|
+
self._tile_data = read_rows(response)
|
|
46
|
+
return self._tile_data
|
|
47
|
+
|
|
48
|
+
def _check_session(self) -> Row | None:
|
|
49
|
+
try:
|
|
50
|
+
return self._fetch_details()
|
|
51
|
+
except requests.RequestException, InvalidResponseError:
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
def _ensure_details(self) -> Row:
|
|
55
|
+
details = self._client._ensure_session()
|
|
56
|
+
if self._details is None:
|
|
57
|
+
return self._load_details(details)
|
|
58
|
+
return self._details
|
|
59
|
+
|
|
60
|
+
def _load_details(self, details: Row | None) -> Row:
|
|
61
|
+
if details is None:
|
|
62
|
+
details = self._fetch_details()
|
|
63
|
+
self.photo = _decode_photo(details.pop("Photo", None))
|
|
64
|
+
self._details = details
|
|
65
|
+
return details
|
|
66
|
+
|
|
67
|
+
def _fetch_details(self) -> Row:
|
|
68
|
+
response = self._client._post(STUDENT_DETAILS_PATH)
|
|
69
|
+
if response.status_code != 200:
|
|
70
|
+
raise InvalidResponseError("Expected a student details response.")
|
|
71
|
+
details = read_first_row(response)
|
|
72
|
+
if not isinstance(details.get("RegID"), int):
|
|
73
|
+
raise InvalidResponseError("Student details lack a valid RegID.")
|
|
74
|
+
return details
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _decode_photo(value: object) -> bytes | None:
|
|
78
|
+
if value is None or value == "":
|
|
79
|
+
return None
|
|
80
|
+
if not isinstance(value, str):
|
|
81
|
+
raise InvalidResponseError("Expected a base64 string for the student photo.")
|
|
82
|
+
try:
|
|
83
|
+
return base64.b64decode("".join(value.split()), validate=True)
|
|
84
|
+
except ValueError as exc:
|
|
85
|
+
raise InvalidResponseError("Student photo contains invalid base64.") from exc
|
qums_fetch-0.4.4.dev2/README.md
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
# qums.py
|
|
2
|
-
|
|
3
|
-
Automatically fetch student data from QUMS
|
|
4
|
-
|
|
5
|
-
## Prerequisites
|
|
6
|
-
|
|
7
|
-
[Tesseract OCR](https://github.com/tesseract-ocr/tesseract) must be installed on your system for captcha solving:
|
|
8
|
-
|
|
9
|
-
```bash
|
|
10
|
-
# Ubuntu/Debian
|
|
11
|
-
sudo apt-get install tesseract-ocr
|
|
12
|
-
|
|
13
|
-
# macOS
|
|
14
|
-
brew install tesseract
|
|
15
|
-
|
|
16
|
-
# Windows
|
|
17
|
-
scoop install tesseract
|
|
18
|
-
```
|
|
19
|
-
|
|
20
|
-
## Quick start
|
|
21
|
-
|
|
22
|
-
Create a `.env` file with:
|
|
23
|
-
|
|
24
|
-
```env
|
|
25
|
-
QUMS_USERNAME=your_username
|
|
26
|
-
QUMS_PASSWORD=your_password
|
|
27
|
-
```
|
|
28
|
-
|
|
29
|
-
Then install the package:
|
|
30
|
-
|
|
31
|
-
```bash
|
|
32
|
-
pip install qums-fetch
|
|
33
|
-
```
|
|
34
|
-
|
|
35
|
-
## Usage
|
|
36
|
-
|
|
37
|
-
```python
|
|
38
|
-
from qums_fetch import Client
|
|
39
|
-
|
|
40
|
-
client = Client(USERNAME, PASSWORD)
|
|
41
|
-
print(client.student_details)
|
|
42
|
-
print(client.today_attendance)
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
## Development
|
|
46
|
-
|
|
47
|
-
See [CONTRIBUTING.md](CONTRIBUTING.md) for setup instructions.
|
|
48
|
-
Check [TODO.md](TODO.md) for open tasks and API coverage.
|
|
49
|
-
|
|
50
|
-
## Credits
|
|
51
|
-
|
|
52
|
-
The captcha solving approach in this project is based on [Kyun-UMS](https://github.com/24kaushik/Kyun-UMS) by [24kaushik](https://github.com/24kaushik).
|
|
@@ -1,108 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Captcha OCR — ports the exact preprocessing used by the Kyun-UMS Chrome
|
|
3
|
-
extension (github.com/24kaushik/Kyun-UMS), which was built and tested
|
|
4
|
-
against this same ERP's captcha, to Python + pytesseract.
|
|
5
|
-
|
|
6
|
-
Pipeline (must stay in sync with the extension if the site's captcha
|
|
7
|
-
style ever changes):
|
|
8
|
-
1. Grayscale via standard luminosity weights (0.299R + 0.587G + 0.114B)
|
|
9
|
-
2. Hard binary threshold at 128 — no gray, pure black/white
|
|
10
|
-
3. Tesseract with an alphanumeric whitelist and PSM 7 (treat the whole
|
|
11
|
-
image as a single line of text, not a page of paragraphs)
|
|
12
|
-
"""
|
|
13
|
-
|
|
14
|
-
from __future__ import annotations
|
|
15
|
-
|
|
16
|
-
import logging
|
|
17
|
-
from io import BytesIO
|
|
18
|
-
from pathlib import Path
|
|
19
|
-
|
|
20
|
-
import pytesseract
|
|
21
|
-
from PIL import Image
|
|
22
|
-
|
|
23
|
-
from .exceptions import BlankCaptchaError, CaptchaError
|
|
24
|
-
|
|
25
|
-
logger = logging.getLogger(__name__)
|
|
26
|
-
|
|
27
|
-
# Same constraint the extension applies: captchas on this site are
|
|
28
|
-
# alphanumeric only (confirmed against a real sample: "AXRNKZ").
|
|
29
|
-
#
|
|
30
|
-
# Threshold cutoff from the extension's JS (`gray > 128 ? 255 : 0`).
|
|
31
|
-
# BINARY_THRESHOLD = 128
|
|
32
|
-
#
|
|
33
|
-
# The ERP sometimes serves a blank placeholder image instead of a real
|
|
34
|
-
# captcha (the extension checks for this via a specific placeholder
|
|
35
|
-
# URL — we can't check the URL since we only ever see raw bytes, so we
|
|
36
|
-
# instead detect "effectively blank" by looking at pixel variance after
|
|
37
|
-
# thresholding: a real captcha has both black and white pixels, a blank
|
|
38
|
-
# one collapses to nearly all one color). Set low deliberately — a real
|
|
39
|
-
# captcha's text can legitimately cover under 1% of a wide image, and a
|
|
40
|
-
# false "blank" verdict (skipping OCR on a real captcha) is worse than
|
|
41
|
-
# an occasional wasted OCR attempt on a genuinely blank one.
|
|
42
|
-
# MIN_NON_BACKGROUND_FRACTION = 0.001
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
class CaptchaSolver:
|
|
46
|
-
def __init__(self, image_bytes: bytes, img_path: str | None = None):
|
|
47
|
-
self.psm: int = 7
|
|
48
|
-
self.allowed_chars: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
49
|
-
self.threshold: int = 128
|
|
50
|
-
self.bg_frac: float = 0.001
|
|
51
|
-
self.image_bytes: bytes = image_bytes
|
|
52
|
-
self.img_dump_path: Path | None = Path(img_path) if img_path else None
|
|
53
|
-
self.bw_dump_path: Path | None = (
|
|
54
|
-
Path(f"{self.img_dump_path.parent}/bw_{self.img_dump_path.name}")
|
|
55
|
-
if self.img_dump_path
|
|
56
|
-
else None
|
|
57
|
-
)
|
|
58
|
-
|
|
59
|
-
@property
|
|
60
|
-
def config(self) -> str:
|
|
61
|
-
return f"--psm {self.psm} -c tessedit_char_whitelist={self.allowed_chars}"
|
|
62
|
-
|
|
63
|
-
def _preprocess(self, image_bytes: bytes) -> Image.Image:
|
|
64
|
-
img = Image.open(BytesIO(image_bytes)).convert("L") # "L" = grayscale
|
|
65
|
-
bw = img.point(lambda p: 255 if p > self.threshold else 0)
|
|
66
|
-
return bw
|
|
67
|
-
|
|
68
|
-
def _looks_blank(self, bw_image: Image.Image) -> bool:
|
|
69
|
-
histogram = bw_image.histogram()
|
|
70
|
-
total_pixels = bw_image.width * bw_image.height
|
|
71
|
-
if total_pixels == 0:
|
|
72
|
-
return True
|
|
73
|
-
dark_pixels = histogram[0] # count of 0-value (black) pixels
|
|
74
|
-
dark_fraction = dark_pixels / total_pixels
|
|
75
|
-
non_background_fraction = min(dark_fraction, 1 - dark_fraction)
|
|
76
|
-
return non_background_fraction < self.bg_frac
|
|
77
|
-
|
|
78
|
-
def _solve_captcha(self) -> str:
|
|
79
|
-
if self.img_dump_path:
|
|
80
|
-
self.img_dump_path.parent.mkdir(parents=True, exist_ok=True)
|
|
81
|
-
with open(self.img_dump_path, "wb") as image_file:
|
|
82
|
-
image_file.write(self.image_bytes)
|
|
83
|
-
logger.info("Saved captcha image to '%s'", self.img_dump_path)
|
|
84
|
-
|
|
85
|
-
bw = self._preprocess(self.image_bytes)
|
|
86
|
-
|
|
87
|
-
if self.bw_dump_path:
|
|
88
|
-
bw.save(self.bw_dump_path)
|
|
89
|
-
logger.info("Saved preprocessed captcha to '%s'", self.bw_dump_path)
|
|
90
|
-
|
|
91
|
-
if self._looks_blank(bw):
|
|
92
|
-
raise BlankCaptchaError(
|
|
93
|
-
"Captcha image appears blank/placeholder after thresholding — "
|
|
94
|
-
"skipping OCR. Fetch a fresh challenge and try again."
|
|
95
|
-
)
|
|
96
|
-
|
|
97
|
-
text = pytesseract.image_to_string(bw, config=self.config).strip()
|
|
98
|
-
logger.info("OCR result: %r", text)
|
|
99
|
-
return text
|
|
100
|
-
|
|
101
|
-
def guess(self) -> str:
|
|
102
|
-
try:
|
|
103
|
-
return self._solve_captcha()
|
|
104
|
-
except BlankCaptchaError:
|
|
105
|
-
raise
|
|
106
|
-
except Exception as e:
|
|
107
|
-
logger.error("%s", e)
|
|
108
|
-
raise CaptchaError("Could not solve captcha.") from e
|
|
@@ -1,435 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
QUMS ERP client — handles the login flow using a persistent
|
|
3
|
-
requests.Session so cookies (ASP.NET_SessionId, the CSRF cookie half,
|
|
4
|
-
etc.) are stored and replayed automatically, same as a browser would.
|
|
5
|
-
"""
|
|
6
|
-
|
|
7
|
-
from __future__ import annotations
|
|
8
|
-
|
|
9
|
-
import base64
|
|
10
|
-
import json
|
|
11
|
-
import logging
|
|
12
|
-
import re
|
|
13
|
-
from dataclasses import dataclass
|
|
14
|
-
from datetime import UTC, datetime
|
|
15
|
-
|
|
16
|
-
import requests
|
|
17
|
-
from bs4 import BeautifulSoup
|
|
18
|
-
|
|
19
|
-
from .captcha import CaptchaSolver
|
|
20
|
-
from .exceptions import (
|
|
21
|
-
BlankCaptchaError,
|
|
22
|
-
CaptchaError,
|
|
23
|
-
CredentialsError,
|
|
24
|
-
InvalidResponseError,
|
|
25
|
-
LoginFailedError,
|
|
26
|
-
LoginPageParseError,
|
|
27
|
-
)
|
|
28
|
-
|
|
29
|
-
logger = logging.getLogger(__name__)
|
|
30
|
-
|
|
31
|
-
BASE_URL = "https://qums.quantumuniversity.edu.in"
|
|
32
|
-
FEEDBACK_PATH = "IQAC/Cyborg_CO_FeedBack"
|
|
33
|
-
|
|
34
|
-
CAPTCHA_IMG_SELECTOR = "#imgPhoto"
|
|
35
|
-
TOKEN_INPUT_NAME = "__RequestVerificationToken"
|
|
36
|
-
|
|
37
|
-
DEFAULT_HEADERS = {
|
|
38
|
-
"User-Agent": (
|
|
39
|
-
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
|
40
|
-
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
|
41
|
-
"Chrome/124.0 Safari/537.36"
|
|
42
|
-
),
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
@dataclass
|
|
47
|
-
class CaptchaChallenge:
|
|
48
|
-
token: str
|
|
49
|
-
image_bytes: bytes
|
|
50
|
-
image_mime: str
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
class Client:
|
|
54
|
-
def __init__(
|
|
55
|
-
self,
|
|
56
|
-
username: str,
|
|
57
|
-
password: str,
|
|
58
|
-
auto_login: bool = True,
|
|
59
|
-
login_retries: int = 3,
|
|
60
|
-
):
|
|
61
|
-
self._validate_credentials(username, password)
|
|
62
|
-
self._validate_retries(login_retries)
|
|
63
|
-
self.username = username
|
|
64
|
-
self._password = password
|
|
65
|
-
self._session = requests.Session()
|
|
66
|
-
self._session.headers.update(DEFAULT_HEADERS)
|
|
67
|
-
self._logged_in = False
|
|
68
|
-
self._details: dict | None = None
|
|
69
|
-
self._tile_data: list[dict] | None = None
|
|
70
|
-
self._today_attendance: list[dict] | None = None
|
|
71
|
-
self._month_attendance: dict | None = None
|
|
72
|
-
self._sem_attendance: list[dict] | None = None
|
|
73
|
-
|
|
74
|
-
if auto_login:
|
|
75
|
-
if self._load_session() and self._is_session_valid():
|
|
76
|
-
self._logged_in = True
|
|
77
|
-
logger.info("Session restored, login skipped.")
|
|
78
|
-
else:
|
|
79
|
-
self.login(max_attempts=login_retries)
|
|
80
|
-
|
|
81
|
-
@property
|
|
82
|
-
def _cookie_path(self) -> str:
|
|
83
|
-
return f"cookies_{self.username}.json"
|
|
84
|
-
|
|
85
|
-
# Save session cookies
|
|
86
|
-
def _save_session(self) -> None:
|
|
87
|
-
with open(self._cookie_path, "w") as f:
|
|
88
|
-
cookies = self._session.cookies.get_dict()
|
|
89
|
-
json.dump(cookies, f)
|
|
90
|
-
logger.info("Session saved to %s", self._cookie_path)
|
|
91
|
-
|
|
92
|
-
# Load session cookies
|
|
93
|
-
def _load_session(self) -> bool:
|
|
94
|
-
try:
|
|
95
|
-
with open(self._cookie_path) as f:
|
|
96
|
-
data = json.load(f)
|
|
97
|
-
cookies = data
|
|
98
|
-
self._session.cookies.update(cookies)
|
|
99
|
-
return True
|
|
100
|
-
except FileNotFoundError, json.JSONDecodeError, KeyError:
|
|
101
|
-
return False
|
|
102
|
-
|
|
103
|
-
# Check if the session is valid
|
|
104
|
-
def _is_session_valid(self) -> bool:
|
|
105
|
-
try:
|
|
106
|
-
resp = self._session.post(f"{BASE_URL}/Account/GetStudentDetail", timeout=5)
|
|
107
|
-
data = resp.json()
|
|
108
|
-
json.loads(data["state"])
|
|
109
|
-
return True
|
|
110
|
-
except requests.RequestException, json.JSONDecodeError, KeyError:
|
|
111
|
-
return False
|
|
112
|
-
|
|
113
|
-
# Re-login if session is expired
|
|
114
|
-
def _ensure_session(self) -> None:
|
|
115
|
-
if self._logged_in and self._is_session_valid():
|
|
116
|
-
return
|
|
117
|
-
logger.info("Session expired, re-logging in.")
|
|
118
|
-
self._clear_cached_data()
|
|
119
|
-
self.login()
|
|
120
|
-
|
|
121
|
-
# Clear saved data
|
|
122
|
-
def _clear_cached_data(self) -> None:
|
|
123
|
-
self._details = None
|
|
124
|
-
self._tile_data = None
|
|
125
|
-
self._today_attendance = None
|
|
126
|
-
self._month_attendance = None
|
|
127
|
-
self._sem_attendance = None
|
|
128
|
-
|
|
129
|
-
@staticmethod
|
|
130
|
-
def _validate_credentials(username: str, password: str) -> None:
|
|
131
|
-
if not username or not password:
|
|
132
|
-
raise ValueError("Username and password are required.")
|
|
133
|
-
|
|
134
|
-
@staticmethod
|
|
135
|
-
def _validate_retries(login_retries: int) -> None:
|
|
136
|
-
if login_retries < 1:
|
|
137
|
-
raise ValueError("login_retries must be greater than 0.")
|
|
138
|
-
|
|
139
|
-
# Automated login flow
|
|
140
|
-
def login(self, max_attempts: int = 3) -> bool:
|
|
141
|
-
self._validate_retries(max_attempts)
|
|
142
|
-
|
|
143
|
-
last_error: Exception | None = None
|
|
144
|
-
for attempt in range(1, max_attempts + 1):
|
|
145
|
-
try:
|
|
146
|
-
challenge = self.fetch_login_challenge()
|
|
147
|
-
solver = CaptchaSolver(challenge.image_bytes)
|
|
148
|
-
captcha_value = solver.guess()
|
|
149
|
-
return self.submit_login(challenge, captcha_value)
|
|
150
|
-
|
|
151
|
-
# User error
|
|
152
|
-
except CredentialsError:
|
|
153
|
-
raise
|
|
154
|
-
|
|
155
|
-
# Server error
|
|
156
|
-
except (BlankCaptchaError, CaptchaError, LoginFailedError) as err:
|
|
157
|
-
last_error = err
|
|
158
|
-
logger.warning(
|
|
159
|
-
"Login attempt %d/%d failed: %s",
|
|
160
|
-
attempt,
|
|
161
|
-
max_attempts,
|
|
162
|
-
err,
|
|
163
|
-
)
|
|
164
|
-
|
|
165
|
-
raise LoginFailedError(
|
|
166
|
-
f"Auto login failed after {max_attempts} attempts."
|
|
167
|
-
) from last_error
|
|
168
|
-
|
|
169
|
-
# Load the login page, extract CSRF token and captcha image
|
|
170
|
-
def fetch_login_challenge(self) -> CaptchaChallenge:
|
|
171
|
-
resp = self._session.get(BASE_URL, timeout=15)
|
|
172
|
-
resp.raise_for_status()
|
|
173
|
-
|
|
174
|
-
soup = BeautifulSoup(resp.text, "html.parser")
|
|
175
|
-
|
|
176
|
-
token_input = soup.find("input", {"name": TOKEN_INPUT_NAME})
|
|
177
|
-
if not token_input or not token_input.get("value"):
|
|
178
|
-
raise LoginPageParseError(
|
|
179
|
-
f"Could not find hidden input '{TOKEN_INPUT_NAME}' on the login page. "
|
|
180
|
-
"The site's markup may have changed."
|
|
181
|
-
)
|
|
182
|
-
token = token_input["value"]
|
|
183
|
-
|
|
184
|
-
img_tag = soup.select_one(CAPTCHA_IMG_SELECTOR)
|
|
185
|
-
if not img_tag or not img_tag.get("src"):
|
|
186
|
-
raise LoginPageParseError(
|
|
187
|
-
f"Could not find captcha image at selector '{CAPTCHA_IMG_SELECTOR}'. "
|
|
188
|
-
"The site's markup may have changed."
|
|
189
|
-
)
|
|
190
|
-
|
|
191
|
-
src = img_tag["src"]
|
|
192
|
-
match = re.match(r"data:(image/\w+);base64,(.+)", src, re.DOTALL)
|
|
193
|
-
if not match:
|
|
194
|
-
raise LoginPageParseError(
|
|
195
|
-
"Captcha image src wasn't a base64 data URI as expected. "
|
|
196
|
-
f"Got: {src[:60]}..."
|
|
197
|
-
)
|
|
198
|
-
image_mime, b64_data = match.groups()
|
|
199
|
-
image_bytes = base64.b64decode(b64_data)
|
|
200
|
-
|
|
201
|
-
logger.info(
|
|
202
|
-
"Fetched login challenge: token acquired, %s captcha image (%d KBs)",
|
|
203
|
-
image_mime,
|
|
204
|
-
len(image_bytes) // 1024,
|
|
205
|
-
)
|
|
206
|
-
|
|
207
|
-
return CaptchaChallenge(
|
|
208
|
-
token=token, image_bytes=image_bytes, image_mime=image_mime
|
|
209
|
-
)
|
|
210
|
-
|
|
211
|
-
# Submit the login form with a solved captcha
|
|
212
|
-
def submit_login(self, challenge: CaptchaChallenge, captcha_value: str) -> bool:
|
|
213
|
-
payload = {
|
|
214
|
-
"hdnMsg": "QGC",
|
|
215
|
-
"checkOnline": "0",
|
|
216
|
-
"__RequestVerificationToken": challenge.token,
|
|
217
|
-
"UserName": self.username,
|
|
218
|
-
"Password": self._password,
|
|
219
|
-
"clientIP": "~~~~~",
|
|
220
|
-
"captcha": captcha_value,
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
resp = self._session.post(
|
|
224
|
-
BASE_URL,
|
|
225
|
-
data=payload,
|
|
226
|
-
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
|
227
|
-
timeout=5,
|
|
228
|
-
allow_redirects=False,
|
|
229
|
-
)
|
|
230
|
-
resp.raise_for_status()
|
|
231
|
-
|
|
232
|
-
if self._looks_like_login_success(resp):
|
|
233
|
-
logger.info("Login succeeded, landed on %s", resp.url)
|
|
234
|
-
if FEEDBACK_PATH in resp.url:
|
|
235
|
-
logger.info("Skipped the course feedback survey")
|
|
236
|
-
self._logged_in = True
|
|
237
|
-
self._save_session()
|
|
238
|
-
return True
|
|
239
|
-
|
|
240
|
-
soup = BeautifulSoup(resp.text, "html.parser")
|
|
241
|
-
error_text = self._extract_error_message(soup)
|
|
242
|
-
raise LoginFailedError(
|
|
243
|
-
error_text or "Login failed for an unknown reason — try again."
|
|
244
|
-
)
|
|
245
|
-
|
|
246
|
-
# Check if login was successful
|
|
247
|
-
def _looks_like_login_success(self, resp: requests.Response) -> bool:
|
|
248
|
-
if resp.url.rstrip("/") == BASE_URL:
|
|
249
|
-
soup = BeautifulSoup(resp.text, "html.parser")
|
|
250
|
-
still_has_captcha = soup.select_one(CAPTCHA_IMG_SELECTOR) is not None
|
|
251
|
-
return not still_has_captcha
|
|
252
|
-
|
|
253
|
-
return True
|
|
254
|
-
|
|
255
|
-
# Extract error message from the login page
|
|
256
|
-
@staticmethod
|
|
257
|
-
def _extract_error_message(soup: BeautifulSoup) -> str | None:
|
|
258
|
-
error_div = soup.select_one(".validation-summary-errors")
|
|
259
|
-
if error_div:
|
|
260
|
-
error_text = error_div.select_one("li").get_text(strip=True)
|
|
261
|
-
if "password" and "incorrect" in error_text:
|
|
262
|
-
raise CredentialsError(error_text)
|
|
263
|
-
else:
|
|
264
|
-
raise CaptchaError(error_text)
|
|
265
|
-
|
|
266
|
-
return None
|
|
267
|
-
|
|
268
|
-
@property
|
|
269
|
-
def is_logged_in(self) -> bool:
|
|
270
|
-
return self._logged_in
|
|
271
|
-
|
|
272
|
-
@property
|
|
273
|
-
def student_details(self) -> dict:
|
|
274
|
-
if not self._details:
|
|
275
|
-
self.get_student_details()
|
|
276
|
-
return self._details
|
|
277
|
-
|
|
278
|
-
@property
|
|
279
|
-
def tile_data(self) -> list[dict]:
|
|
280
|
-
if not self._tile_data:
|
|
281
|
-
if not self._details:
|
|
282
|
-
self.get_student_details()
|
|
283
|
-
self.get_tile_data()
|
|
284
|
-
return self._tile_data
|
|
285
|
-
|
|
286
|
-
@property
|
|
287
|
-
def today_attendance(self) -> list[dict]:
|
|
288
|
-
if not self._today_attendance:
|
|
289
|
-
if not self._details:
|
|
290
|
-
self.get_student_details()
|
|
291
|
-
self.get_today_attendance()
|
|
292
|
-
return self._today_attendance
|
|
293
|
-
|
|
294
|
-
@property
|
|
295
|
-
def month_attendance(self) -> dict:
|
|
296
|
-
if not self._month_attendance:
|
|
297
|
-
if not self._details:
|
|
298
|
-
self.get_student_details()
|
|
299
|
-
self.get_month_attendance()
|
|
300
|
-
return self._month_attendance
|
|
301
|
-
|
|
302
|
-
@property
|
|
303
|
-
def sem_attendance(self) -> list[dict]:
|
|
304
|
-
if not self._sem_attendance:
|
|
305
|
-
if not self._details:
|
|
306
|
-
self.get_student_details()
|
|
307
|
-
self.get_sem_attendance()
|
|
308
|
-
return self._sem_attendance
|
|
309
|
-
|
|
310
|
-
# Authenticated data fetches
|
|
311
|
-
def get_student_details(self) -> int:
|
|
312
|
-
self._ensure_session()
|
|
313
|
-
resp = self._session.post(f"{BASE_URL}/Account/GetStudentDetail", timeout=5)
|
|
314
|
-
resp.raise_for_status()
|
|
315
|
-
|
|
316
|
-
logger.info("POST [%d] %s", resp.status_code, resp.url)
|
|
317
|
-
|
|
318
|
-
try:
|
|
319
|
-
data = resp.json()
|
|
320
|
-
details = json.loads(data["state"])[0]
|
|
321
|
-
except json.JSONDecodeError:
|
|
322
|
-
raise InvalidResponseError("Failed to parse student details.")
|
|
323
|
-
|
|
324
|
-
self.photo = base64.b64decode(details.get("Photo"))
|
|
325
|
-
details.pop("Photo", None)
|
|
326
|
-
|
|
327
|
-
self._details = details
|
|
328
|
-
return 0
|
|
329
|
-
|
|
330
|
-
def get_tile_data(self) -> int:
|
|
331
|
-
self._ensure_session()
|
|
332
|
-
payload = {
|
|
333
|
-
"RegID": self._details.get("RegID"),
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
resp = self._session.post(
|
|
337
|
-
f"{BASE_URL}/Web_StudentAcademic/GetStudentTileData",
|
|
338
|
-
data=payload,
|
|
339
|
-
timeout=5,
|
|
340
|
-
)
|
|
341
|
-
resp.raise_for_status()
|
|
342
|
-
|
|
343
|
-
logger.info("POST [%d] %s", resp.status_code, resp.url)
|
|
344
|
-
|
|
345
|
-
try:
|
|
346
|
-
data = resp.json()
|
|
347
|
-
tile_data = json.loads(data["state"])
|
|
348
|
-
except json.JSONDecodeError:
|
|
349
|
-
raise InvalidResponseError("Failed to parse tile data.")
|
|
350
|
-
|
|
351
|
-
self._tile_data = tile_data
|
|
352
|
-
return 0
|
|
353
|
-
|
|
354
|
-
def get_today_attendance(self) -> int:
|
|
355
|
-
self._ensure_session()
|
|
356
|
-
today = datetime.now(tz=UTC).strftime("%d/%m/%Y")
|
|
357
|
-
payload = {
|
|
358
|
-
"RegID": self._details.get("RegID"),
|
|
359
|
-
"date": today,
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
resp = self._session.post(
|
|
363
|
-
f"{BASE_URL}/Web_StudentAcademic/GetTodayAttendance",
|
|
364
|
-
data=payload,
|
|
365
|
-
timeout=5,
|
|
366
|
-
)
|
|
367
|
-
resp.raise_for_status()
|
|
368
|
-
|
|
369
|
-
logger.info("POST [%d] %s", resp.status_code, resp.url)
|
|
370
|
-
|
|
371
|
-
try:
|
|
372
|
-
data = resp.json()
|
|
373
|
-
attendance = json.loads(data["state"])
|
|
374
|
-
except json.JSONDecodeError:
|
|
375
|
-
raise InvalidResponseError("Failed to parse attendance data.")
|
|
376
|
-
|
|
377
|
-
self._today_attendance = attendance
|
|
378
|
-
return 0
|
|
379
|
-
|
|
380
|
-
def get_month_attendance(self, month: int | None = None) -> int:
|
|
381
|
-
self._ensure_session()
|
|
382
|
-
if month is None:
|
|
383
|
-
month = datetime.now(tz=UTC).month
|
|
384
|
-
payload = {
|
|
385
|
-
"RegID": self._details.get("RegID"),
|
|
386
|
-
"Month": month,
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
resp = self._session.post(
|
|
390
|
-
f"{BASE_URL}/Web_StudentAcademic/GetMonthRegister",
|
|
391
|
-
data=payload,
|
|
392
|
-
timeout=5,
|
|
393
|
-
)
|
|
394
|
-
resp.raise_for_status()
|
|
395
|
-
|
|
396
|
-
logger.info("POST [%d] %s", resp.status_code, resp.url)
|
|
397
|
-
|
|
398
|
-
try:
|
|
399
|
-
data = resp.json()
|
|
400
|
-
month_attendance = {
|
|
401
|
-
"overview": json.loads(data["data"])[0],
|
|
402
|
-
"details": json.loads(data["state"]),
|
|
403
|
-
}
|
|
404
|
-
except json.JSONDecodeError:
|
|
405
|
-
raise InvalidResponseError("Failed to parse month attendance data.")
|
|
406
|
-
|
|
407
|
-
self._month_attendance = month_attendance
|
|
408
|
-
return 0
|
|
409
|
-
|
|
410
|
-
def get_sem_attendance(self, sem: int | None = None) -> int:
|
|
411
|
-
self._ensure_session()
|
|
412
|
-
if sem is None:
|
|
413
|
-
sem = self._details.get("YearSem")
|
|
414
|
-
payload = {
|
|
415
|
-
"RegID": self._details.get("RegID"),
|
|
416
|
-
"YearSem": sem,
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
resp = self._session.post(
|
|
420
|
-
f"{BASE_URL}/Web_StudentAcademic/GetYearSemWiseAttendance",
|
|
421
|
-
data=payload,
|
|
422
|
-
timeout=5,
|
|
423
|
-
)
|
|
424
|
-
resp.raise_for_status()
|
|
425
|
-
|
|
426
|
-
logger.info("POST [%d] %s", resp.status_code, resp.url)
|
|
427
|
-
|
|
428
|
-
try:
|
|
429
|
-
data = resp.json()
|
|
430
|
-
sem_attendance = json.loads(data["data"])
|
|
431
|
-
except json.JSONDecodeError:
|
|
432
|
-
raise InvalidResponseError("Failed to parse semester attendance data.")
|
|
433
|
-
|
|
434
|
-
self._sem_attendance = sem_attendance
|
|
435
|
-
return 0
|
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
class Error(Exception):
|
|
2
|
-
"""Base exception for all client errors."""
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
class LoginPageParseError(Error):
|
|
6
|
-
"""The login page's HTML didn't contain what we expected (token or
|
|
7
|
-
captcha image). Usually means the site's markup changed."""
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
class LoginFailedError(Error):
|
|
11
|
-
"""The login POST didn't land on the student menu, for a reason we
|
|
12
|
-
couldn't attribute to a specific field. Prefer CaptchaError or
|
|
13
|
-
CredentialsError below when the page tells us which — this is the
|
|
14
|
-
fallback for anything else (ERP-side error, unexpected markup)."""
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
class CaptchaError(LoginFailedError):
|
|
18
|
-
"""The captcha reading was wrong (page showed a
|
|
19
|
-
'field-validation-error' element). Retry with a fresh captcha —
|
|
20
|
-
this tells you nothing about whether the credentials were correct,
|
|
21
|
-
since the ERP validates captcha before it ever checks credentials
|
|
22
|
-
and won't report a credentials error while captcha is wrong."""
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
class CredentialsError(LoginFailedError):
|
|
26
|
-
"""Username/password were rejected (page showed a
|
|
27
|
-
'validation-summary-errors' element) while the captcha itself was
|
|
28
|
-
accepted. Retrying with a new captcha won't help — the credentials
|
|
29
|
-
need to change."""
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
class InvalidResponseError(Error):
|
|
33
|
-
"""The server returned a response we couldn't parse (e.g. JSON
|
|
34
|
-
expected but got HTML). Usually means the site's markup changed or
|
|
35
|
-
the ERP is down."""
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
class BlankCaptchaError(Error):
|
|
39
|
-
"""The image looked like an empty/placeholder captcha rather than
|
|
40
|
-
real text — retry with a fresh fetch rather than trying to OCR it."""
|
|
File without changes
|