urp-tools 0.2.3.3__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.
File without changes
@@ -0,0 +1,4 @@
1
+ from .api import fetch_tasks, get_this_semester_timetable
2
+ from .session import AsyncJWSSession
3
+
4
+ __all__ = ["AsyncJWSSession", "fetch_tasks", "get_this_semester_timetable"]
@@ -0,0 +1,19 @@
1
+ """api"""
2
+
3
+ from .session import AsyncJWSSession
4
+
5
+
6
+ async def get_this_semester_timetable(jws: AsyncJWSSession) -> dict:
7
+ """获取本学期课表"""
8
+ return await jws.request_json(
9
+ "GET",
10
+ "/student/courseSelect/thisSemesterCurriculum/callback",
11
+ )
12
+
13
+
14
+ async def fetch_tasks(jws: AsyncJWSSession) -> dict:
15
+ """获取评教列表"""
16
+ return await jws.request_json(
17
+ "GET",
18
+ "/student/teachingEvaluation/teachingEvaluation/search",
19
+ )
@@ -0,0 +1,451 @@
1
+ """登录会话"""
2
+
3
+ import asyncio
4
+ import hashlib
5
+ import json
6
+ import logging
7
+ import random
8
+ import re
9
+ from collections import Counter
10
+ from dataclasses import dataclass
11
+ from io import BytesIO
12
+ from types import TracebackType
13
+
14
+ import aiohttp
15
+ import ddddocr
16
+ from PIL import Image, ImageSequence
17
+
18
+ BASE_URL = "https://jws.qgxy.cn"
19
+ LOGIN_PAGE = f"{BASE_URL}/login"
20
+ LOGIN_URL = f"{BASE_URL}/j_spring_security_check"
21
+ CAPTCHA_URL = f"{BASE_URL}/img/captcha.jpg"
22
+ INDEX_URL = f"{BASE_URL}/index.jsp"
23
+
24
+ CODE_LEN = 4
25
+ HTTP_STATUS_OK = 200
26
+ MAX_RETRY = 100
27
+ ASCII_CODE_RE = re.compile(r"^[A-Za-z0-9]{4}$")
28
+ TOKEN_RE = re.compile(r'name="tokenValue"\s+value="([^"]+)"', re.IGNORECASE)
29
+
30
+ log = logging.getLogger(__name__)
31
+
32
+
33
+ @dataclass
34
+ class RetryPolicy:
35
+ max_retry: int = 10
36
+ base_sleep: float = 0.15
37
+ max_sleep: float = 1.2
38
+ jitter: float = 0.2
39
+
40
+
41
+ class AuthError(Exception): ...
42
+
43
+
44
+ class ServiceError(Exception): ...
45
+
46
+
47
+ class SessionExpiredError(Exception): ...
48
+
49
+
50
+ class AsyncJWSSession:
51
+ def __init__(
52
+ self,
53
+ timeout_total: float = 6.0,
54
+ timeout_connect: float = 2.0,
55
+ connector_limit: int = 50,
56
+ retry: RetryPolicy = RetryPolicy(),
57
+ jitter_range: tuple[float, float] = (0.0, 0.15),
58
+ ) -> None:
59
+ self._timeout = aiohttp.ClientTimeout(
60
+ total=timeout_total,
61
+ connect=timeout_connect,
62
+ )
63
+ self._connector = aiohttp.TCPConnector(limit=connector_limit, ttl_dns_cache=300)
64
+ self._session: aiohttp.ClientSession | None = None
65
+
66
+ self.headers = {
67
+ "User-Agent": (
68
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) "
69
+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36"
70
+ ),
71
+ "Referer": LOGIN_PAGE,
72
+ }
73
+ self.retry = retry
74
+ self.jitter_range = jitter_range
75
+
76
+ self._username = None
77
+ self._password = None
78
+ self._ocr = ddddocr.DdddOcr(show_ad=False, beta=True)
79
+
80
+ async def __aenter__(self) -> "AsyncJWSSession": # noqa: PYI034
81
+ self._session = aiohttp.ClientSession(
82
+ timeout=self._timeout,
83
+ connector=self._connector,
84
+ headers=self.headers,
85
+ raise_for_status=False,
86
+ )
87
+ return self
88
+
89
+ async def __aexit__(
90
+ self,
91
+ exc_type: type[BaseException] | None,
92
+ exc: BaseException | None,
93
+ tb: TracebackType | None,
94
+ ) -> None:
95
+ if self._session is not None:
96
+ await self._session.close()
97
+ self._session = None
98
+
99
+ @staticmethod
100
+ def _md5(text: str) -> str:
101
+ """明文密码 MD5 加密"""
102
+ return hashlib.md5(text.encode("utf-8")).hexdigest()
103
+
104
+ @staticmethod
105
+ def _extract_token(html: str) -> str:
106
+ """获取tokenValue"""
107
+ m: re.Match[str] | None = TOKEN_RE.search(html or "")
108
+ if not m:
109
+ msg = "tokenValue not found"
110
+ raise AuthError(msg)
111
+ return m.group(1)
112
+
113
+ async def _sleep_jitter(self) -> None:
114
+ """随机等待,防止请求过快"""
115
+ lo, hi = self.jitter_range
116
+ if hi > 0:
117
+ await asyncio.sleep(random.uniform(lo, hi)) # noqa: S311
118
+
119
+ def check_login_page(self, text: str) -> bool:
120
+ """检查是否为登录页面"""
121
+ t: str = (text or "").lower()
122
+ return (
123
+ ("tokenvalue" in t and "j_spring_security_check" in t)
124
+ or ("gotologin" in t)
125
+ or ("/login" in t)
126
+ )
127
+
128
+ async def is_logged_in(self) -> bool:
129
+ """检查是否已登录"""
130
+ if not self._session:
131
+ log.error("session not started")
132
+ msg = "session not started "
133
+ raise RuntimeError(msg)
134
+
135
+ try:
136
+ async with self._session.get(INDEX_URL, allow_redirects=False) as r:
137
+ if r.status == HTTP_STATUS_OK:
138
+ txt = await r.text(errors="ignore")
139
+ return not self.check_login_page(txt)
140
+ if r.status in (301, 302, 303, 307, 308):
141
+ loc = (r.headers.get("Location") or "").lower()
142
+ return not ("gotologin" in loc or "/login" in loc)
143
+ return False
144
+ except (aiohttp.ClientError, asyncio.TimeoutError):
145
+ return False
146
+
147
+ async def login(self, username: str, password: str) -> None:
148
+ """登录教务系统,保存会话状态"""
149
+ if not self._session:
150
+ msg = "session not started"
151
+ raise RuntimeError(msg)
152
+
153
+ self._username = username
154
+ self._password = password
155
+
156
+ for i in range(MAX_RETRY):
157
+ log.info("✨ 第 %d 次尝试登录:", i + 1)
158
+ try:
159
+ async with self._session.get(LOGIN_PAGE) as r:
160
+ if r.status != HTTP_STATUS_OK:
161
+ await self._sleep_jitter()
162
+ continue
163
+ html = await r.text(errors="ignore")
164
+ token = self._extract_token(html)
165
+ log.info("tokenValue: %s", token)
166
+ except (aiohttp.ClientError, asyncio.TimeoutError, AuthError):
167
+ log.exception("获取登录页异常,请检查账号密码是否正确")
168
+ await self._sleep_jitter()
169
+ continue
170
+
171
+ # 验证码
172
+ try:
173
+ img_bytes = await self._fetch_captcha_image(max_retry=5)
174
+ except Exception:
175
+ log.exception("获取验证码异常")
176
+ await self._sleep_jitter()
177
+ continue
178
+
179
+ # OCR
180
+ captcha = await self.parse_captcha(img_bytes)
181
+ if not captcha or not ASCII_CODE_RE.fullmatch(captcha):
182
+ await self._sleep_jitter()
183
+ continue
184
+
185
+ data = {
186
+ "tokenValue": token,
187
+ "j_username": username,
188
+ "j_password": self._md5(password),
189
+ "j_captcha": captcha,
190
+ }
191
+ try:
192
+ async with self._session.post(
193
+ LOGIN_URL,
194
+ data=data,
195
+ allow_redirects=True,
196
+ ) as _:
197
+ pass
198
+ except (aiohttp.ClientError, asyncio.TimeoutError):
199
+ log.exception("登录提交失败")
200
+ await self._sleep_jitter()
201
+ continue
202
+
203
+ if await self.is_logged_in():
204
+ log.info("✅ 登录成功")
205
+ return
206
+ log.warning("❌ 登录失败,重试中...")
207
+ await self._sleep_jitter()
208
+ log.error("❌ 登录失败,达到最大重试次数")
209
+ msg = "login failed"
210
+ raise AuthError(msg)
211
+
212
+ async def _ensure_login(self) -> None:
213
+ """确保已登录,未登录则自动重登"""
214
+ if await self.is_logged_in():
215
+ return
216
+ if not self._username or not self._password:
217
+ log.error("未登录且未保存账号密码,无法自动重登")
218
+ msg = "not logged in and no saved credentials"
219
+ raise SessionExpiredError(msg)
220
+ log.info("session已过期,自动重登…")
221
+ await self.login(self._username, self._password)
222
+
223
+ async def _fetch_captcha_image(self, max_retry: int = 5) -> bytes:
224
+ """获取验证码图片"""
225
+ if not self._session:
226
+ log.error("验证码未正常加载")
227
+ msg = "session not started"
228
+ raise RuntimeError(msg)
229
+
230
+ for _ in range(max_retry):
231
+ try:
232
+ async with self._session.get(CAPTCHA_URL, allow_redirects=True) as r:
233
+ if r.status != HTTP_STATUS_OK:
234
+ await self._sleep_jitter()
235
+ continue
236
+
237
+ ct = (r.headers.get("Content-Type") or "").lower()
238
+ content = await r.read()
239
+
240
+ if "image" not in ct:
241
+ # 疑似被踢回登录:刷新一次登录页
242
+ try:
243
+ async with self._session.get(LOGIN_PAGE) as _:
244
+ pass
245
+ except Exception:
246
+ log.exception("刷新登录页出错")
247
+ await self._sleep_jitter()
248
+ continue
249
+
250
+ ok = await self._verify_image(content)
251
+ if ok:
252
+ return content
253
+
254
+ except (aiohttp.ClientError, asyncio.TimeoutError):
255
+ log.exception("获取验证码请求异常")
256
+ await self._sleep_jitter()
257
+ log.error("验证码获取失败")
258
+ msg = "captcha fetch failed"
259
+ raise AuthError(msg)
260
+
261
+ async def _verify_image(self, img_bytes: bytes) -> bool:
262
+ """校验验证码合法性"""
263
+ loop = asyncio.get_running_loop()
264
+
265
+ def _verify() -> bool:
266
+ try:
267
+ img = Image.open(BytesIO(img_bytes))
268
+ img.verify()
269
+ except Exception:
270
+ log.exception("验证码图片校验失败")
271
+ return False
272
+ else:
273
+ return True
274
+
275
+ return await loop.run_in_executor(None, _verify)
276
+
277
+ async def parse_captcha(self, img_bytes: bytes) -> str:
278
+ loop = asyncio.get_running_loop()
279
+ return await loop.run_in_executor(None, self._parse_captcha, img_bytes)
280
+
281
+ def _parse_captcha(self, img_bytes: bytes) -> str: # noqa: C901
282
+ """
283
+ 验证码解析策略:
284
+ - full OCR
285
+ - split OCR
286
+ - full 和 split 都是 4 位 → 优先 full
287
+ - 否则 → 优先 split
288
+ """
289
+
290
+ def normalize(s: str) -> str:
291
+ if not s:
292
+ return ""
293
+ s = s.strip().replace(" ", "")
294
+ s = s.replace("y", "7").replace("9", "r").replace("E", "F")
295
+ s = "".join(
296
+ ch
297
+ for ch in s
298
+ if ("0" <= ch <= "9") or ("A" <= ch <= "Z") or ("a" <= ch <= "z")
299
+ )
300
+ return s.lower()
301
+
302
+ def ocr_img(pil_img: Image.Image) -> str:
303
+ pil_img = pil_img.resize(
304
+ (pil_img.width * 2, pil_img.height * 2),
305
+ Image.NEAREST,
306
+ )
307
+ buf = BytesIO()
308
+ pil_img.save(buf, format="PNG")
309
+ return self._ocr.classification(buf.getvalue())
310
+
311
+ img = Image.open(BytesIO(img_bytes))
312
+ frames = [f.convert("L") for f in ImageSequence.Iterator(img)]
313
+ if not frames:
314
+ return ""
315
+
316
+ base = frames[0]
317
+ norm_full = normalize(ocr_img(base))
318
+ log.info("Full OCR result: '%s'", norm_full)
319
+
320
+ if sum(1 for ch in norm_full if ch.isalnum()) < 3: # noqa: PLR2004
321
+ log.warning("Full OCR 非4位ASCII字母数字/非数字答案,重试中...")
322
+ return ""
323
+
324
+ w, h = base.size
325
+ char_w = w // 4
326
+ split_chars = []
327
+ for i in range(4):
328
+ crop = base.crop((i * char_w, 0, (i + 1) * char_w, h))
329
+ norm = normalize(ocr_img(crop))
330
+ split_chars.append(norm[:1] if norm else "")
331
+
332
+ if not split_chars[0]:
333
+ candidates = []
334
+ for frame in frames[:3]:
335
+ w2, h2 = frame.size
336
+ for ratio in (4, 3):
337
+ crop = frame.crop((0, 0, w2 // ratio, h2))
338
+ norm = normalize(ocr_img(crop))
339
+ if norm:
340
+ candidates.append(norm[0])
341
+ if candidates:
342
+ split_chars[0] = Counter(candidates).most_common(1)[0][0]
343
+ log.info("尝试补全首字符 '%s'->'%s'", candidates, split_chars[0])
344
+
345
+ split_code = "".join(split_chars)
346
+ log.info("split_chars -> split_code: '%s' -> '%s'", split_chars, split_code)
347
+
348
+ full_ok = len(norm_full) == CODE_LEN and ASCII_CODE_RE.fullmatch(norm_full)
349
+ split_ok = len(split_code) == CODE_LEN and ASCII_CODE_RE.fullmatch(split_code)
350
+
351
+ if full_ok and split_ok:
352
+ log.info("使用 full='%s'", norm_full)
353
+ return norm_full
354
+ if split_ok:
355
+ log.info("使用 split='%s'", split_code)
356
+ return split_code
357
+ if full_ok:
358
+ log.info("使用 full='%s'", norm_full)
359
+ return norm_full
360
+ return ""
361
+
362
+ async def request_text( # noqa: C901, PLR0913
363
+ self,
364
+ method: str,
365
+ path: str,
366
+ *,
367
+ params: dict | None = None,
368
+ data: dict | None = None,
369
+ json: dict | None = None,
370
+ allow_redirects: bool = True,
371
+ retry: RetryPolicy | None = None,
372
+ ) -> str:
373
+ """自动处理重试和登录过期"""
374
+
375
+ def _raise_session_expired() -> None:
376
+ msg = "looks like login page"
377
+ raise SessionExpiredError(msg)
378
+
379
+ def _raise_retryable_service_error(status: int) -> None:
380
+ msg = f"retryable status {status}"
381
+ raise ServiceError(msg)
382
+
383
+ def _raise_service_error(status: int) -> None:
384
+ msg = f"status {status}"
385
+ raise ServiceError(msg)
386
+
387
+ await self._ensure_login()
388
+ if not self._session:
389
+ log.error("session not started")
390
+ msg = "session not started"
391
+ raise RuntimeError(msg)
392
+
393
+ url = (
394
+ path
395
+ if path.startswith("http")
396
+ else (BASE_URL + (path if path.startswith("/") else f"/{path}"))
397
+ )
398
+ pol = retry or self.retry
399
+
400
+ for attempt in range(1, pol.max_retry + 1):
401
+ try:
402
+ async with self._session.request(
403
+ method,
404
+ url,
405
+ params=params,
406
+ data=data,
407
+ json=json,
408
+ allow_redirects=allow_redirects,
409
+ ) as r:
410
+ txt = await r.text(errors="ignore")
411
+
412
+ if self.check_login_page(txt):
413
+ log.info("looks like login page")
414
+ _raise_session_expired()
415
+
416
+ if r.status in (429, 502, 503, 504):
417
+ log.warning("retryable status %d", r.status)
418
+ _raise_retryable_service_error(r.status)
419
+
420
+ if r.status >= 400: # noqa: PLR2004
421
+ log.error("non-retryable status %d", r.status)
422
+ _raise_service_error(r.status)
423
+
424
+ return txt
425
+
426
+ except SessionExpiredError: # noqa: PERF203
427
+ if self._username and self._password:
428
+ await self.login(self._username, self._password)
429
+ else:
430
+ raise
431
+ except (aiohttp.ClientError, asyncio.TimeoutError, ServiceError):
432
+ if attempt == pol.max_retry:
433
+ log.exception("达到最大重试次数, 已放弃请求登录")
434
+ raise
435
+ sleep = min(
436
+ pol.max_sleep,
437
+ pol.base_sleep * (2 ** (attempt - 1)),
438
+ ) + random.uniform(0, pol.jitter) # noqa: S311
439
+ await asyncio.sleep(sleep)
440
+
441
+ msg = "unreachable"
442
+ raise ServiceError(msg)
443
+
444
+ async def request_json(self, method: str, path: str, **kwargs) -> dict: # noqa: ANN003
445
+ """发送请求并解析 JSON 响应"""
446
+ txt = await self.request_text(method, path, **kwargs)
447
+ try:
448
+ return json.loads(txt)
449
+ except ValueError:
450
+ msg = "response is not json"
451
+ raise ServiceError(msg) from None
@@ -0,0 +1,10 @@
1
+ """配置文件"""
2
+
3
+ # 此处填入学号
4
+ USERNAME = ""
5
+ # 此处填入密码
6
+ PASSWORD = ""
7
+ # True = 仅测试 False = 提交
8
+ DRY_RUN = True
9
+ # 默认满分
10
+ DEFAULT_CHOICE = "A"
@@ -0,0 +1,3 @@
1
+ from .excel import export_timetable_excel
2
+
3
+ __all__ = ["export_timetable_excel"]
@@ -0,0 +1,75 @@
1
+ """导出课表到 Excel 文件"""
2
+
3
+ import asyncio
4
+ from typing import Any
5
+
6
+ from openpyxl import Workbook
7
+ from openpyxl.styles import Alignment, Font
8
+ from openpyxl.utils import get_column_letter
9
+
10
+
11
+ def _export_xlsx(courses: list[dict[str, Any]], filename: str) -> None:
12
+ wb = Workbook()
13
+ ws = wb.active
14
+ ws = wb.active
15
+ if ws is None:
16
+ return
17
+ ws.title = "本学期课表"
18
+
19
+ headers = ["课程名称", "任课教师", "学分", "星期", "节次", "周次", "教学楼", "教室"]
20
+ ws.append(headers)
21
+
22
+ header_style = Font(bold=True)
23
+ align_center = Alignment(horizontal="center", vertical="center", wrap_text=True)
24
+
25
+ for col in range(1, len(headers) + 1):
26
+ cell = ws.cell(row=1, column=col)
27
+ cell.font = header_style
28
+ cell.alignment = align_center
29
+ ws.column_dimensions[get_column_letter(col)].width = 16
30
+
31
+ weekday = {
32
+ 1: "周一",
33
+ 2: "周二",
34
+ 3: "周三",
35
+ 4: "周四",
36
+ 5: "周五",
37
+ 6: "周六",
38
+ 7: "周日",
39
+ }
40
+
41
+ for item in courses:
42
+ day_raw = item.get("day")
43
+ day = weekday.get(day_raw, "") if isinstance(day_raw, int) else ""
44
+
45
+ start = item.get("start_session")
46
+ duration = item.get("duration")
47
+ section = (
48
+ f"{start}-{start + duration - 1}节"
49
+ if isinstance(start, int) and isinstance(duration, int)
50
+ else ""
51
+ )
52
+
53
+ ws.append(
54
+ [
55
+ item.get("course_name", ""),
56
+ (item.get("teacher") or "").replace("*", "").strip(),
57
+ item.get("credit", ""),
58
+ day,
59
+ section,
60
+ item.get("week_desc") or item.get("weeks") or "",
61
+ item.get("building") or item.get("teachingBuildingName") or "",
62
+ item.get("classroom") or item.get("classroomName") or "",
63
+ ],
64
+ )
65
+
66
+ for row in ws.iter_rows(min_row=2):
67
+ for cell in row:
68
+ cell.alignment = align_center
69
+
70
+ wb.save(filename)
71
+
72
+
73
+ async def export_timetable_excel(courses: list[dict[str, Any]], filename: str) -> None:
74
+ """导出课表到 Excel"""
75
+ await asyncio.to_thread(_export_xlsx, courses, filename)
@@ -0,0 +1,74 @@
1
+ """入口文件 main"""
2
+
3
+ import asyncio
4
+ import logging
5
+
6
+ import aioconsole
7
+
8
+ from client import AsyncJWSSession, fetch_tasks, get_this_semester_timetable
9
+ from config import PASSWORD, USERNAME
10
+ from export import export_timetable_excel
11
+ from parser import TeachingEvaluationClient, parse_timetable
12
+
13
+ logging.basicConfig(
14
+ level=logging.INFO,
15
+ format="%(asctime)s | %(levelname)-7s | %(name)s | %(message)s",
16
+ datefmt="%Y-%m-%d %H:%M:%S",
17
+ force=True,
18
+ )
19
+ log = logging.getLogger(__name__)
20
+
21
+
22
+ def menu() -> None:
23
+ log.info("========================")
24
+ log.info("欢迎使用教务系统工具")
25
+ log.info("1. 抢课(开发中)")
26
+ log.info("2. 导出课表")
27
+ log.info("3. 教学评估")
28
+ log.info("0. 退出")
29
+ log.info("========================\n")
30
+
31
+
32
+ async def handle_view_timetable(jws: AsyncJWSSession) -> None:
33
+ raw = await get_this_semester_timetable(jws)
34
+ courses = parse_timetable(raw)
35
+ if not courses:
36
+ log.warning("未查询到任何课程")
37
+ return
38
+ out = "本学期课表.xlsx"
39
+ await export_timetable_excel(courses, out)
40
+ log.info(f"本学期课表已导出:{out}")
41
+
42
+
43
+ async def handle_teaching_evaluation(jws: AsyncJWSSession) -> None:
44
+ data = await fetch_tasks(jws)
45
+ await TeachingEvaluationClient().run(jws, data)
46
+ log.info("评教结束")
47
+
48
+
49
+ async def main() -> None:
50
+ async with AsyncJWSSession() as jws:
51
+ await jws.login(USERNAME, PASSWORD)
52
+
53
+ while True:
54
+ menu()
55
+ choice = (await aioconsole.ainput("请输入选项:")).strip()
56
+
57
+ if choice == "1":
58
+ log.warning("抢课功能尚未实现")
59
+
60
+ elif choice == "2":
61
+ await handle_view_timetable(jws)
62
+
63
+ elif choice == "3":
64
+ await handle_teaching_evaluation(jws)
65
+
66
+ elif choice == "0":
67
+ break
68
+
69
+ else:
70
+ log.warning("无效选项")
71
+
72
+
73
+ if __name__ == "__main__":
74
+ asyncio.run(main())
@@ -0,0 +1,4 @@
1
+ from .evaluation import TeachingEvaluationClient
2
+ from .timetable import parse_timetable
3
+
4
+ __all__ = ["TeachingEvaluationClient", "parse_timetable"]
@@ -0,0 +1,138 @@
1
+ """教学评估"""
2
+
3
+ import logging
4
+ import re
5
+
6
+ from client.session import AsyncJWSSession
7
+ from config import DEFAULT_CHOICE, DRY_RUN
8
+
9
+ BASE_USL = "https://jws.qgxy.cn/student/teachingEvaluation"
10
+ SUBMIT_URL = f"{BASE_USL}/teachingEvaluation/assessment"
11
+ EVA_INDEX_URL = f"{BASE_USL}/evaluation/index"
12
+ EVA_PAGE_URL = f"{BASE_USL}/evaluationPage"
13
+
14
+ TOKEN_RE = re.compile(r'name="tokenValue"\s+value="([^"]+)"', re.IGNORECASE)
15
+ CONFIRM_PHRASE = "我确认提交评教不可撤销"
16
+
17
+ SCORE_MAP_A: dict[str, str] = {
18
+ "A": "10_1",
19
+ "B": "10_0.8",
20
+ "C": "10_0.6",
21
+ "D": "10_0.4",
22
+ "E": "10_0.2",
23
+ }
24
+
25
+ SCORE_MAP_B: dict[str, str] = {
26
+ "A": "10_1",
27
+ "B": "10_0.6",
28
+ "C": "10_0.5",
29
+ "D": "10_0.2",
30
+ "E": "10_0",
31
+ }
32
+
33
+ log = logging.getLogger(__name__)
34
+
35
+
36
+ class TeachingEvaluationClient:
37
+ @staticmethod
38
+ def extract_token(html: str) -> str:
39
+ """获取toeknValue"""
40
+ m = TOKEN_RE.search(html or "")
41
+ if not m:
42
+ msg = "tokenValue not found"
43
+ raise RuntimeError(msg)
44
+ return m.group(1)
45
+
46
+ def open_evaluation_page(self, task: dict, token: str) -> dict[str, str]:
47
+ return {
48
+ "evaluatedPeople": task["evaluatedPeople"],
49
+ "evaluatedPeopleNumber": task["id"]["evaluatedPeople"],
50
+ "questionnaireCode": task["id"]["questionnaireCoding"],
51
+ "questionnaireName": task["questionnaire"]["questionnaireName"],
52
+ "coureSequenceNumber": task["id"]["coureSequenceNumber"],
53
+ "evaluationContentNumber": task["id"]["evaluationContentNumber"],
54
+ "evaluationContentContent": task["evaluationContent"],
55
+ "tokenValue": token,
56
+ }
57
+
58
+ def build_assessment_payload(
59
+ self,
60
+ task: dict,
61
+ token: str,
62
+ answers: dict[str, str],
63
+ ) -> dict[str, str]:
64
+ """构造assessment payload"""
65
+ payload: dict[str, str] = {
66
+ "optType": "submit",
67
+ "tokenValue": token,
68
+ "questionnaireCode": task["id"]["questionnaireCoding"],
69
+ "evaluationContent": task["id"]["evaluationContentNumber"],
70
+ "evaluatedPeopleNumber": task["id"]["evaluatedPeople"],
71
+ "count": "",
72
+ }
73
+ for qid, choice in answers.items():
74
+ payload[qid] = SCORE_MAP_A[choice]
75
+ payload["zgpj"] = "老师教学认真课程收获较大"
76
+ return payload
77
+
78
+ def final_confirm(self, tasks: list[dict], not_finished_num: int) -> None:
79
+ """最终确认"""
80
+ log.info(f"🚨 共 {not_finished_num} 门课程,一旦提交无法修改。\n")
81
+ log.info("你将评教以下课程:")
82
+ for t in tasks:
83
+ log.info(f" - {t['evaluatedPeople']} | {t['evaluationContent']}")
84
+
85
+ log.info("\n如果你确认继续,请完整输入下面这句话:")
86
+ log.info(f"⌈{CONFIRM_PHRASE}⌋")
87
+
88
+ user_input: str = input("\n请输入确认语句:").strip()
89
+ if user_input != CONFIRM_PHRASE:
90
+ log.error("\n❌ 验证错误,已中止提交。")
91
+ raise SystemExit(1)
92
+ log.info("\n✅ 验证通过,开始提交评教。\n")
93
+
94
+ async def run(self, jws: AsyncJWSSession, data: dict) -> None:
95
+ """获取评教任务并执行评教"""
96
+ tasks_list: list[dict] = data.get("data", [])
97
+ not_finished_num: int = data["notFinishedNum"]
98
+ log.info(f"共有 {not_finished_num} 门课程待评教。\n")
99
+ if not_finished_num == 0:
100
+ log.info("✅ 无待评教任务,退出评教流程")
101
+ pending = [t for t in tasks_list if t.get("isEvaluated") == "否"]
102
+ if not pending:
103
+ return
104
+
105
+ answers = {
106
+ "0000000014": DEFAULT_CHOICE,
107
+ "0000000016": DEFAULT_CHOICE,
108
+ "0000000018": DEFAULT_CHOICE,
109
+ "0000000015": DEFAULT_CHOICE,
110
+ "0000000017": DEFAULT_CHOICE,
111
+ "0000000044": DEFAULT_CHOICE,
112
+ "0000000048": DEFAULT_CHOICE,
113
+ "0000000053": DEFAULT_CHOICE,
114
+ "0000000042": DEFAULT_CHOICE,
115
+ "0000000049": DEFAULT_CHOICE,
116
+ }
117
+
118
+ for task in pending:
119
+ html = await jws.request_text("GET", EVA_INDEX_URL)
120
+ token: str = self.extract_token(html)
121
+
122
+ page_form = self.open_evaluation_page(task, token)
123
+ await jws.request_text(
124
+ "POST",
125
+ EVA_PAGE_URL,
126
+ data=page_form,
127
+ allow_redirects=True,
128
+ )
129
+
130
+ payload = self.build_assessment_payload(task, token, answers)
131
+ if not DRY_RUN:
132
+ self.final_confirm(tasks_list, not_finished_num)
133
+ await jws.request_text(
134
+ "POST",
135
+ SUBMIT_URL,
136
+ data=payload,
137
+ allow_redirects=True,
138
+ )
@@ -0,0 +1,46 @@
1
+ """获取并解析课表数据的模块"""
2
+
3
+ from typing import Any
4
+
5
+
6
+ def parse_timetable(data: dict[str, Any]) -> list[dict[str, Any]]:
7
+ """
8
+ 从教务系统返回的 JSON中解析出课表明细
9
+ """
10
+ result: list[dict[str, Any]] = []
11
+
12
+ xkxx_list = data.get("xkxx", [])
13
+ if not xkxx_list:
14
+ return result
15
+
16
+ for course_map in xkxx_list:
17
+ if not isinstance(course_map, dict):
18
+ continue
19
+
20
+ for course in course_map.values():
21
+ course_name = course.get("courseName", "")
22
+ teacher = course.get("attendClassTeacher", "").strip()
23
+ credit = course.get("unit", 0)
24
+
25
+ time_list = course.get("timeAndPlaceList", [])
26
+ if not time_list:
27
+ continue
28
+
29
+ result.extend(
30
+ {
31
+ "course_name": course_name,
32
+ "teacher": teacher,
33
+ "day": t.get("classDay"),
34
+ "start_session": t.get("classSessions"),
35
+ "duration": t.get("continuingSession"),
36
+ "weeks": t.get("classWeek"),
37
+ "week_desc": t.get("weekDescription"),
38
+ "campus": t.get("campusName"),
39
+ "building": t.get("teachingBuildingName"),
40
+ "classroom": t.get("classroomName"),
41
+ "credit": credit,
42
+ }
43
+ for t in time_list
44
+ )
45
+
46
+ return result
@@ -0,0 +1,228 @@
1
+ Metadata-Version: 2.4
2
+ Name: urp-tools
3
+ Version: 0.2.3.3
4
+ Summary: URP Academic Affairs System Course Snatching Tool
5
+ License: Apache License
6
+ Version 2.0, January 2004
7
+ http://www.apache.org/licenses/
8
+
9
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
10
+
11
+ 1. Definitions.
12
+
13
+ "License" shall mean the terms and conditions for use, reproduction,
14
+ and distribution as defined by Sections 1 through 9 of this document.
15
+
16
+ "Licensor" shall mean the copyright owner or entity authorized by
17
+ the copyright owner that is granting the License.
18
+
19
+ "Legal Entity" shall mean the union of the acting entity and all
20
+ other entities that control, are controlled by, or are under common
21
+ control with that entity. For the purposes of this definition,
22
+ "control" means (i) the power, direct or indirect, to cause the
23
+ direction or management of such entity, whether by contract or
24
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
25
+ outstanding shares, or (iii) beneficial ownership of such entity.
26
+
27
+ "You" (or "Your") shall mean an individual or Legal Entity
28
+ exercising permissions granted by this License.
29
+
30
+ "Source" form shall mean the preferred form for making modifications,
31
+ including but not limited to software source code, documentation
32
+ source, and configuration files.
33
+
34
+ "Object" form shall mean any form resulting from mechanical
35
+ transformation or translation of a Source form, including but
36
+ not limited to compiled object code, generated documentation,
37
+ and conversions to other media types.
38
+
39
+ "Work" shall mean the work of authorship, whether in Source or
40
+ Object form, made available under the License, as indicated by a
41
+ copyright notice that is included in or attached to the work
42
+ (an example is provided in the Appendix below).
43
+
44
+ "Derivative Works" shall mean any work, whether in Source or Object
45
+ form, that is based on (or derived from) the Work and for which the
46
+ editorial revisions, annotations, elaborations, or other modifications
47
+ represent, as a whole, an original work of authorship. For the purposes
48
+ of this License, Derivative Works shall not include works that remain
49
+ separable from, or merely link (or bind by name) to the interfaces of,
50
+ the Work and Derivative Works thereof.
51
+
52
+ "Contribution" shall mean any work of authorship, including
53
+ the original version of the Work and any modifications or additions
54
+ to that Work or Derivative Works thereof, that is intentionally
55
+ submitted to Licensor for inclusion in the Work by the copyright owner
56
+ or by an individual or Legal Entity authorized to submit on behalf of
57
+ the copyright owner. For the purposes of this definition, "submitted"
58
+ means any form of electronic, verbal, or written communication sent
59
+ to the Licensor or its representatives, including but not limited to
60
+ communication on electronic mailing lists, source code control systems,
61
+ and issue tracking systems that are managed by, or on behalf of, the
62
+ Licensor for the purpose of discussing and improving the Work, but
63
+ excluding communication that is conspicuously marked or otherwise
64
+ designated in writing by the copyright owner as "Not a Contribution."
65
+
66
+ "Contributor" shall mean Licensor and any individual or Legal Entity
67
+ on behalf of whom a Contribution has been received by Licensor and
68
+ subsequently incorporated within the Work.
69
+
70
+ 2. Grant of Copyright License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ copyright license to reproduce, prepare Derivative Works of,
74
+ publicly display, publicly perform, sublicense, and distribute the
75
+ Work and such Derivative Works in Source or Object form.
76
+
77
+ 3. Grant of Patent License. Subject to the terms and conditions of
78
+ this License, each Contributor hereby grants to You a perpetual,
79
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
80
+ (except as stated in this section) patent license to make, have made,
81
+ use, offer to sell, sell, import, and otherwise transfer the Work,
82
+ where such license applies only to those patent claims licensable
83
+ by such Contributor that are necessarily infringed by their
84
+ Contribution(s) alone or by combination of their Contribution(s)
85
+ with the Work to which such Contribution(s) was submitted. If You
86
+ institute patent litigation against any entity (including a
87
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
88
+ or a Contribution incorporated within the Work constitutes direct
89
+ or contributory patent infringement, then any patent licenses
90
+ granted to You under this License for that Work shall terminate
91
+ as of the date such litigation is filed.
92
+
93
+ 4. Redistribution. You may reproduce and distribute copies of the
94
+ Work or Derivative Works thereof in any medium, with or without
95
+ modifications, and in Source or Object form, provided that You
96
+ meet the following conditions:
97
+
98
+ (a) You must give any other recipients of the Work or
99
+ Derivative Works a copy of this License; and
100
+
101
+ (b) You must cause any modified files to carry prominent notices
102
+ stating that You changed the files; and
103
+
104
+ (c) You must retain, in the Source form of any Derivative Works
105
+ that You distribute, all copyright, patent, trademark, and
106
+ attribution notices from the Source form of the Work,
107
+ excluding those notices that do not pertain to any part of
108
+ the Derivative Works; and
109
+
110
+ (d) If the Work includes a "NOTICE" text file as part of its
111
+ distribution, then any Derivative Works that You distribute must
112
+ include a readable copy of the attribution notices contained
113
+ within such NOTICE file, excluding those notices that do not
114
+ pertain to any part of the Derivative Works, in at least one
115
+ of the following places: within a NOTICE text file distributed
116
+ as part of the Derivative Works; within the Source form or
117
+ documentation, if provided along with the Derivative Works; or,
118
+ within a display generated by the Derivative Works, if and
119
+ wherever such third-party notices normally appear. The contents
120
+ of the NOTICE file are for informational purposes only and
121
+ do not modify the License. You may add Your own attribution
122
+ notices within Derivative Works that You distribute, alongside
123
+ or as an addendum to the NOTICE text from the Work, provided
124
+ that such additional attribution notices cannot be construed
125
+ as modifying the License.
126
+
127
+ You may add Your own copyright statement to Your modifications and
128
+ may provide additional or different license terms and conditions
129
+ for use, reproduction, or distribution of Your modifications, or
130
+ for any such Derivative Works as a whole, provided Your use,
131
+ reproduction, and distribution of the Work otherwise complies with
132
+ the conditions stated in this License.
133
+
134
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
135
+ any Contribution intentionally submitted for inclusion in the Work
136
+ by You to the Licensor shall be under the terms and conditions of
137
+ this License, without any additional terms or conditions.
138
+ Notwithstanding the above, nothing herein shall supersede or modify
139
+ the terms of any separate license agreement you may have executed
140
+ with Licensor regarding such Contributions.
141
+
142
+ 6. Trademarks. This License does not grant permission to use the trade
143
+ names, trademarks, service marks, or product names of the Licensor,
144
+ except as required for reasonable and customary use in describing the
145
+ origin of the Work and reproducing the content of the NOTICE file.
146
+
147
+ 7. Disclaimer of Warranty. Unless required by applicable law or
148
+ agreed to in writing, Licensor provides the Work (and each
149
+ Contributor provides its Contributions) on an "AS IS" BASIS,
150
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
151
+ implied, including, without limitation, any warranties or conditions
152
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
153
+ PARTICULAR PURPOSE. You are solely responsible for determining the
154
+ appropriateness of using or redistributing the Work and assume any
155
+ risks associated with Your exercise of permissions under this License.
156
+
157
+ 8. Limitation of Liability. In no event and under no legal theory,
158
+ whether in tort (including negligence), contract, or otherwise,
159
+ unless required by applicable law (such as deliberate and grossly
160
+ negligent acts) or agreed to in writing, shall any Contributor be
161
+ liable to You for damages, including any direct, indirect, special,
162
+ incidental, or consequential damages of any character arising as a
163
+ result of this License or out of the use or inability to use the
164
+ Work (including but not limited to damages for loss of goodwill,
165
+ work stoppage, computer failure or malfunction, or any and all
166
+ other commercial damages or losses), even if such Contributor
167
+ has been advised of the possibility of such damages.
168
+
169
+ 9. Accepting Warranty or Additional Liability. While redistributing
170
+ the Work or Derivative Works thereof, You may choose to offer,
171
+ and charge a fee for, acceptance of support, warranty, indemnity,
172
+ or other liability obligations and/or rights consistent with this
173
+ License. However, in accepting such obligations, You may act only
174
+ on Your own behalf and on Your sole responsibility, not on behalf
175
+ of any other Contributor, and only if You agree to indemnify,
176
+ defend, and hold each Contributor harmless for any liability
177
+ incurred by, or claims asserted against, such Contributor by reason
178
+ of your accepting any such warranty or additional liability.
179
+
180
+ END OF TERMS AND CONDITIONS
181
+
182
+ APPENDIX: How to apply the Apache License to your work.
183
+
184
+ To apply the Apache License to your work, attach the following
185
+ boilerplate notice, with the fields enclosed by brackets "[]"
186
+ replaced with your own identifying information. (Don't include
187
+ the brackets!) The text should be enclosed in the appropriate
188
+ comment syntax for the file format. We also recommend that a
189
+ file or class name and description of purpose be included on the
190
+ same "printed page" as the copyright notice for easier
191
+ identification within third-party archives.
192
+
193
+ Copyright 2026 Reversedeer
194
+
195
+ Licensed under the Apache License, Version 2.0 (the "License");
196
+ you may not use this file except in compliance with the License.
197
+ You may obtain a copy of the License at
198
+
199
+ http://www.apache.org/licenses/LICENSE-2.0
200
+
201
+ Unless required by applicable law or agreed to in writing, software
202
+ distributed under the License is distributed on an "AS IS" BASIS,
203
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
204
+ See the License for the specific language governing permissions and
205
+ limitations under the License.
206
+ License-File: LICENSE
207
+ Author: Reversedeer
208
+ Author-email: ysjvillmark@gmail.com
209
+ Requires-Python: >=3.10,<3.11
210
+ Classifier: License :: Other/Proprietary License
211
+ Classifier: Programming Language :: Python :: 3
212
+ Classifier: Programming Language :: Python :: 3.10
213
+ Requires-Dist: aioconsole (>=0.8.2,<0.9.0)
214
+ Requires-Dist: aiofiles (>=25.1.0,<26.0.0)
215
+ Requires-Dist: aiohttp (>=3.13.3,<4.0.0)
216
+ Requires-Dist: ddddocr (==1.4.7)
217
+ Requires-Dist: onnxruntime (==1.23.2)
218
+ Requires-Dist: openpyxl (>=3.1.5,<4.0.0)
219
+ Requires-Dist: pillow (==9.5.0)
220
+ Project-URL: Homepage, https://github.com/Reversedeer/urp-academic-affairs-tools
221
+ Project-URL: Issues, https://github.com/Reversedeer/urp-academic-affairs-tools/issues
222
+ Project-URL: Repository, https://github.com/Reversedeer/urp-academic-affairs-tools.git
223
+ Description-Content-Type: text/markdown
224
+
225
+ # URP综合教务管理系统
226
+
227
+ version 4.1.0
228
+
@@ -0,0 +1,15 @@
1
+ urp_academic_affairs_tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ urp_academic_affairs_tools/client/__init__.py,sha256=FFwC8Romq0Qc91JeSE8YZ30nDn7BtzQjtF5eUftvt5A,172
3
+ urp_academic_affairs_tools/client/api.py,sha256=MOk390FrB3ZAxq7D7e7mfg5ubnZUxgoYapJyICoY5b0,477
4
+ urp_academic_affairs_tools/client/session.py,sha256=778po8z7X1HgClVaglLbG-sVkiN_pTttrk-8MjJ8aKI,15485
5
+ urp_academic_affairs_tools/config.py,sha256=A18K8WEP_ck7Rlhr_Fz_6ulORf-v2D-i_2OniCiDT5U,176
6
+ urp_academic_affairs_tools/export/__init__.py,sha256=vpLcfBcPxGMpGFQAUXsDNIgHaAnCWEBRRhw5H_cvT5U,80
7
+ urp_academic_affairs_tools/export/excel.py,sha256=8itCLJm156p6D5CKHVaCTKoDlMqznLn51yXkhLWLL0Q,2218
8
+ urp_academic_affairs_tools/main.py,sha256=1Z4Y6DXMyP6Ey7UFl48BlhwsoWfvTPBGKOKNIZdQ6xE,1977
9
+ urp_academic_affairs_tools/parser/__init__.py,sha256=AZBwwuT93pBNLrPLrfBiK7fgAnBKj3QvS71jiTGFwEA,147
10
+ urp_academic_affairs_tools/parser/evaluation.py,sha256=TO2Wfs-OZ5RXDH3XH72s4UknOOTFFk5l1hFMgvSqMRY,4839
11
+ urp_academic_affairs_tools/parser/timetable.py,sha256=TiEQLW7uslzd80bqeQRLg8mPhcvhb-H_fviwHi2O_ak,1458
12
+ urp_tools-0.2.3.3.dist-info/METADATA,sha256=p0AonvQXyh9_pcbeJ7Ay0WEPocIGF7P4TmixqRaSMCE,14099
13
+ urp_tools-0.2.3.3.dist-info/WHEEL,sha256=kJCRJT_g0adfAJzTx2GUMmS80rTJIVHRCfG0DQgLq3o,88
14
+ urp_tools-0.2.3.3.dist-info/licenses/LICENSE,sha256=0WXPTAQsBJfkLUU4c2U1_BGRd4mxyOznKL5b7woPmCc,11341
15
+ urp_tools-0.2.3.3.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.3.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Reversedeer
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.