moodlesolver 1.0.0__tar.gz → 2.1.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.
Files changed (33) hide show
  1. moodlesolver-2.1.0/LICENSE +21 -0
  2. moodlesolver-2.1.0/PKG-INFO +121 -0
  3. moodlesolver-2.1.0/README.md +104 -0
  4. moodlesolver-2.1.0/moodlesolver/__init__.py +11 -0
  5. moodlesolver-2.1.0/moodlesolver/aipreview.py +26 -0
  6. moodlesolver-2.1.0/moodlesolver/airunner.py +90 -0
  7. moodlesolver-2.1.0/moodlesolver/cdn.py +13 -0
  8. moodlesolver-2.1.0/moodlesolver/client.py +418 -0
  9. moodlesolver-2.1.0/moodlesolver/ctx.py +126 -0
  10. moodlesolver-2.1.0/moodlesolver/errors.py +6 -0
  11. moodlesolver-2.1.0/moodlesolver/jsonapi.py +235 -0
  12. moodlesolver-2.1.0/moodlesolver/mcp_server.py +149 -0
  13. moodlesolver-2.1.0/moodlesolver/parse.py +34 -0
  14. moodlesolver-2.1.0/moodlesolver/quizapi.py +124 -0
  15. moodlesolver-2.1.0/moodlesolver/schema/quiz_protocol.json +44 -0
  16. moodlesolver-2.1.0/moodlesolver/vision.py +69 -0
  17. moodlesolver-2.1.0/moodlesolver.egg-info/PKG-INFO +121 -0
  18. moodlesolver-2.1.0/moodlesolver.egg-info/SOURCES.txt +22 -0
  19. moodlesolver-2.1.0/moodlesolver.egg-info/entry_points.txt +2 -0
  20. moodlesolver-2.1.0/moodlesolver.egg-info/requires.txt +8 -0
  21. moodlesolver-2.1.0/pyproject.toml +26 -0
  22. moodlesolver-1.0.0/PKG-INFO +0 -106
  23. moodlesolver-1.0.0/README.md +0 -93
  24. moodlesolver-1.0.0/moodlesolver/__init__.py +0 -6
  25. moodlesolver-1.0.0/moodlesolver/client.py +0 -406
  26. moodlesolver-1.0.0/moodlesolver/parse.py +0 -42
  27. moodlesolver-1.0.0/moodlesolver.egg-info/PKG-INFO +0 -106
  28. moodlesolver-1.0.0/moodlesolver.egg-info/SOURCES.txt +0 -10
  29. moodlesolver-1.0.0/moodlesolver.egg-info/requires.txt +0 -1
  30. moodlesolver-1.0.0/pyproject.toml +0 -21
  31. {moodlesolver-1.0.0 → moodlesolver-2.1.0}/moodlesolver.egg-info/dependency_links.txt +0 -0
  32. {moodlesolver-1.0.0 → moodlesolver-2.1.0}/moodlesolver.egg-info/top_level.txt +0 -0
  33. {moodlesolver-1.0.0 → moodlesolver-2.1.0}/setup.cfg +0 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 i-execute
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: moodlesolver
3
+ Version: 2.1.0
4
+ Summary: Moodle quiz automation library and MCP server with local OCR
5
+ Author: i-execute
6
+ License: MIT
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: aiohttp
11
+ Requires-Dist: mcp
12
+ Provides-Extra: ocr
13
+ Requires-Dist: pix2tex; extra == "ocr"
14
+ Requires-Dist: pillow; extra == "ocr"
15
+ Provides-Extra: vision
16
+ Dynamic: license-file
17
+
18
+ # moodlesolver
19
+
20
+ Асинхронная Python-библиотека и MCP-сервер для автоматизации прохождения тестов на платформе Moodle через браузерный API (camofox).
21
+
22
+ ## Возможности
23
+
24
+ - **Авторизация и сессии** — вход по логину/паролю, реанимация попытки после обрыва (`resume_attempt`)
25
+ - **Навигация по курсам** — список курсов, секций, ресурсов, тестов; полная выгрузка курса в JSON; скачивание файлов и картинок
26
+ - **Прохождение тестов** — все типы вопросов: одиночный выбор, множественный (чекбоксы), выпадающие списки, ввод текста, вопросы с картинками и формулами
27
+ - **JSON-протокол** — `JsonAPI` и MCP-тул `quiz_command` принимают команды JSON и возвращают состояние вопроса: текст, варианты, что реально отмечено, остаток таймера
28
+ - **OCR без внешних API** — локально: tesseract (текст ru/en) и pix2tex (формулы LaTeX); параллельно, результаты в том же JSON
29
+ - **Картинки в ответе** — base64 или HTTP-ссылки (встроенный файл-сервер `serve_dumps`)
30
+ - **Коды ошибок** — структурированные `E_*` вместо тихих падений
31
+ - **MCP-сервер** — 27 инструментов для подключения любой LLM-моделью
32
+
33
+ ## Установка
34
+
35
+ ```bash
36
+ pip install moodlesolver
37
+ ```
38
+
39
+ Зависимости для OCR (опционально, но рекомендуются):
40
+
41
+ ```bash
42
+ apt-get install tesseract-ocr tesseract-ocr-rus
43
+ pip install pix2tex
44
+ ```
45
+
46
+ Требуется запущенный camofox-browser (API по умолчанию `http://localhost:9377`).
47
+
48
+ ## Быстрый старт
49
+
50
+ ```python
51
+ import asyncio
52
+ from moodlesolver import AsyncMoodle, QuizAPI, JsonAPI
53
+
54
+ async def main():
55
+ m = AsyncMoodle(site="https://moodle.example.com")
56
+ await m.open_session("login", "password")
57
+
58
+ from moodlesolver import CtxAPI
59
+ ctx = CtxAPI(m)
60
+ quizzes = await ctx.get_quizzes(42)
61
+
62
+ q = QuizAPI(m)
63
+ api = JsonAPI(q)
64
+
65
+ st = await api.handle({"action": "state"})
66
+ print(st["question"], st["options"], st["timeleft"])
67
+
68
+ await api.handle({"action": "select", "answers": [{"index": 2}]})
69
+ st = await api.handle({"action": "confirm"})
70
+ print(st["question"])
71
+
72
+ await api.handle({"action": "submit"})
73
+ print(await api.handle({"action": "result"}))
74
+
75
+ asyncio.run(main())
76
+ ```
77
+
78
+ ## JSON-протокол
79
+
80
+ Каждый ответ содержит: `page`, `question`, `question_hash`, `qtype`, `options`, `checked` (что реально отмечено на сервере), `selects`, `text_inputs`, `timeleft`, `buttons`, а также:
81
+
82
+ - `question_image_b64` / `option_images_b64` — картинки в base64 (или ссылки при `image_mode="url"`)
83
+ - `ocr` — локальное превью каждой картинки: `{"formula": "…", "ru": "…", "en": "…"}`, а при `ai_preview=True` ещё `ai_preview` — описание картинок vision-моделью OpenCode (mimo-v2.6-flash-free по умолчанию)
84
+
85
+ ```python
86
+ api = JsonAPI(q, ai_preview=True) # включить AI-описание картинок
87
+ api = JsonAPI(q, ai_preview=True, ai_model="opencode/longcat-2.5-preview-free")
88
+ ```
89
+
90
+ Подробная схема: `moodlesolver/schema/quiz_protocol.json`.
91
+
92
+ ## MCP-сервер
93
+
94
+ ```json
95
+ {
96
+ "mcpServers": {
97
+ "moodlesolver": {
98
+ "command": "python",
99
+ "args": ["-m", "moodlesolver.mcp_server"]
100
+ }
101
+ }
102
+ }
103
+ ```
104
+
105
+ Инструменты: connect, get_courses, get_quizzes, get_course, dump_course, download_images, download_resource, search_courses, resume_attempt, start_attempt, get_state, get_options, get_images, set_answer, set_text, set_select, next_page, submit_all, get_result, quiz_command, see_image и другие.
106
+
107
+ ## AIRunner
108
+
109
+ Полный автопрогон теста одним процессом с решением через внешнюю LLM:
110
+
111
+ ```python
112
+ from moodlesolver import AIRunner
113
+
114
+ r = AIRunner(api_key="...", base_url="https://api.example.com/v1",
115
+ model="model-name").bind(q)
116
+ await r.loop(quiz_id)
117
+ ```
118
+
119
+ ## Лицензия
120
+
121
+ MIT
@@ -0,0 +1,104 @@
1
+ # moodlesolver
2
+
3
+ Асинхронная Python-библиотека и MCP-сервер для автоматизации прохождения тестов на платформе Moodle через браузерный API (camofox).
4
+
5
+ ## Возможности
6
+
7
+ - **Авторизация и сессии** — вход по логину/паролю, реанимация попытки после обрыва (`resume_attempt`)
8
+ - **Навигация по курсам** — список курсов, секций, ресурсов, тестов; полная выгрузка курса в JSON; скачивание файлов и картинок
9
+ - **Прохождение тестов** — все типы вопросов: одиночный выбор, множественный (чекбоксы), выпадающие списки, ввод текста, вопросы с картинками и формулами
10
+ - **JSON-протокол** — `JsonAPI` и MCP-тул `quiz_command` принимают команды JSON и возвращают состояние вопроса: текст, варианты, что реально отмечено, остаток таймера
11
+ - **OCR без внешних API** — локально: tesseract (текст ru/en) и pix2tex (формулы LaTeX); параллельно, результаты в том же JSON
12
+ - **Картинки в ответе** — base64 или HTTP-ссылки (встроенный файл-сервер `serve_dumps`)
13
+ - **Коды ошибок** — структурированные `E_*` вместо тихих падений
14
+ - **MCP-сервер** — 27 инструментов для подключения любой LLM-моделью
15
+
16
+ ## Установка
17
+
18
+ ```bash
19
+ pip install moodlesolver
20
+ ```
21
+
22
+ Зависимости для OCR (опционально, но рекомендуются):
23
+
24
+ ```bash
25
+ apt-get install tesseract-ocr tesseract-ocr-rus
26
+ pip install pix2tex
27
+ ```
28
+
29
+ Требуется запущенный camofox-browser (API по умолчанию `http://localhost:9377`).
30
+
31
+ ## Быстрый старт
32
+
33
+ ```python
34
+ import asyncio
35
+ from moodlesolver import AsyncMoodle, QuizAPI, JsonAPI
36
+
37
+ async def main():
38
+ m = AsyncMoodle(site="https://moodle.example.com")
39
+ await m.open_session("login", "password")
40
+
41
+ from moodlesolver import CtxAPI
42
+ ctx = CtxAPI(m)
43
+ quizzes = await ctx.get_quizzes(42)
44
+
45
+ q = QuizAPI(m)
46
+ api = JsonAPI(q)
47
+
48
+ st = await api.handle({"action": "state"})
49
+ print(st["question"], st["options"], st["timeleft"])
50
+
51
+ await api.handle({"action": "select", "answers": [{"index": 2}]})
52
+ st = await api.handle({"action": "confirm"})
53
+ print(st["question"])
54
+
55
+ await api.handle({"action": "submit"})
56
+ print(await api.handle({"action": "result"}))
57
+
58
+ asyncio.run(main())
59
+ ```
60
+
61
+ ## JSON-протокол
62
+
63
+ Каждый ответ содержит: `page`, `question`, `question_hash`, `qtype`, `options`, `checked` (что реально отмечено на сервере), `selects`, `text_inputs`, `timeleft`, `buttons`, а также:
64
+
65
+ - `question_image_b64` / `option_images_b64` — картинки в base64 (или ссылки при `image_mode="url"`)
66
+ - `ocr` — локальное превью каждой картинки: `{"formula": "…", "ru": "…", "en": "…"}`, а при `ai_preview=True` ещё `ai_preview` — описание картинок vision-моделью OpenCode (mimo-v2.6-flash-free по умолчанию)
67
+
68
+ ```python
69
+ api = JsonAPI(q, ai_preview=True) # включить AI-описание картинок
70
+ api = JsonAPI(q, ai_preview=True, ai_model="opencode/longcat-2.5-preview-free")
71
+ ```
72
+
73
+ Подробная схема: `moodlesolver/schema/quiz_protocol.json`.
74
+
75
+ ## MCP-сервер
76
+
77
+ ```json
78
+ {
79
+ "mcpServers": {
80
+ "moodlesolver": {
81
+ "command": "python",
82
+ "args": ["-m", "moodlesolver.mcp_server"]
83
+ }
84
+ }
85
+ }
86
+ ```
87
+
88
+ Инструменты: connect, get_courses, get_quizzes, get_course, dump_course, download_images, download_resource, search_courses, resume_attempt, start_attempt, get_state, get_options, get_images, set_answer, set_text, set_select, next_page, submit_all, get_result, quiz_command, see_image и другие.
89
+
90
+ ## AIRunner
91
+
92
+ Полный автопрогон теста одним процессом с решением через внешнюю LLM:
93
+
94
+ ```python
95
+ from moodlesolver import AIRunner
96
+
97
+ r = AIRunner(api_key="...", base_url="https://api.example.com/v1",
98
+ model="model-name").bind(q)
99
+ await r.loop(quiz_id)
100
+ ```
101
+
102
+ ## Лицензия
103
+
104
+ MIT
@@ -0,0 +1,11 @@
1
+ from .client import AsyncMoodle, AsyncTab, CamofoxError
2
+ from .parse import parse_page
3
+ from .quizapi import QuizAPI
4
+ from .ctx import CtxAPI
5
+ from .airunner import AIRunner
6
+ from .jsonapi import JsonAPI
7
+ from .vision import ocr_file, make_on_ocr
8
+ from .aipreview import ai_preview, opencode_available
9
+ from .cdn import serve_dumps
10
+ from .mcp_server import main as mcp_main
11
+ __all__ = ['AsyncMoodle', 'AsyncTab', 'CamofoxError', 'parse_page', 'QuizAPI', 'CtxAPI', 'AIRunner', 'JsonAPI', 'mcp_main', 'ai_preview', 'opencode_available', 'serve_dumps', 'ocr_file', 'make_on_ocr']
@@ -0,0 +1,26 @@
1
+ import shutil
2
+ import subprocess
3
+
4
+ OC_DEFAULT_MODEL = "opencode/mimo-v2.6-flash-free"
5
+
6
+
7
+ def opencode_available():
8
+ return shutil.which("opencode") is not None
9
+
10
+
11
+ def ai_preview(paths, prompt="Опиши что на картинке, весь текст перепиши",
12
+ model=OC_DEFAULT_MODEL, timeout=120):
13
+ if not opencode_available() or not paths:
14
+ return None
15
+ cmd = ["opencode", "run", prompt, "--model", model]
16
+ for p in paths:
17
+ cmd += ["-f", p]
18
+ try:
19
+ out = subprocess.run(cmd, capture_output=True, text=True,
20
+ timeout=timeout).stdout.strip()
21
+ except Exception:
22
+ return None
23
+ if not out or "Error" in out.splitlines()[0]:
24
+ return None
25
+ lines = [ln for ln in out.splitlines() if not ln.startswith(">")]
26
+ return "\n".join(lines).strip() or None
@@ -0,0 +1,90 @@
1
+ import asyncio
2
+ import json
3
+ import urllib.request
4
+
5
+ class AIRunner:
6
+
7
+ def __init__(self, api_key=None, base_url=None, model=None):
8
+ self.key = api_key
9
+ self.base = base_url or 'https://integrate.api.nvidia.com/v1'
10
+ self.model = model or 'meta/llama-3.2-90b-vision-instruct'
11
+ self.qapi = None
12
+
13
+ def bind(self, quizapi):
14
+ self.qapi = quizapi
15
+ return self
16
+
17
+ def ocr(self, file, prompt=None):
18
+ from .vision import ocr_file
19
+ d = getattr(self.qapi.m, 'dumps_dir', None) if self.qapi else None
20
+ return ocr_file(file, prompt, d)
21
+
22
+ def send_ai_request(self, messages, images=None, max_tokens=400):
23
+ content = [{'type': 'text', 'text': json.dumps(messages, ensure_ascii=False)}] if isinstance(messages, (dict, list)) else [{'type': 'text', 'text': messages}]
24
+ for b64 in images or []:
25
+ content.append({'type': 'image_url', 'image_url': {'url': f'data:image/png;base64,{b64}'}})
26
+ body = json.dumps({'model': self.model, 'max_tokens': max_tokens, 'temperature': 0, 'messages': [{'role': 'user', 'content': content}]}).encode()
27
+ req = urllib.request.Request(f'{self.base}/chat/completions', data=body, headers={'Authorization': f'Bearer {self.key}', 'Content-Type': 'application/json'})
28
+ r = json.load(urllib.request.urlopen(req, timeout=120))
29
+ return r['choices'][0]['message']['content']
30
+
31
+ def receive_ai_response(self, text):
32
+ try:
33
+ return json.loads(text.strip().strip('`').removeprefix('json').strip())
34
+ except Exception:
35
+ return {'action': None, 'raw': text}
36
+
37
+ async def execute_ai_response(self, resp):
38
+ a = resp.get('action')
39
+ if a == 'answer':
40
+ for l in resp.get('labels') or ([resp['label']] if resp.get('label') else []):
41
+ await self.qapi.set_answer(label=l)
42
+ if resp.get('index') is not None:
43
+ await self.qapi.set_answer(index=resp['index'])
44
+ elif a == 'text':
45
+ await self.qapi.set_text(resp['value'], resp.get('index', 0))
46
+ elif a == 'select':
47
+ for v, i in zip(resp.get('values', [resp.get('value')]), range(99)):
48
+ await self.qapi.set_select(v, i)
49
+ elif a == 'next':
50
+ return await self.qapi.next_page()
51
+ elif a == 'submit':
52
+ return await self.qapi.submit_all()
53
+ return resp.get('action')
54
+
55
+ async def loop(self, quiz_id, max_steps=60, answer_bank=None):
56
+ info = await self.qapi.get_quiz_info(quiz_id)
57
+ if info.get('can_start'):
58
+ await self.qapi.start_attempt(quiz_id)
59
+ from .jsonapi import JsonAPI
60
+ j = JsonAPI(self.qapi, on_ocr=self.ocr)
61
+ for _ in range(max_steps):
62
+ st = await j.handle({'action': 'state', 'quiz_id': quiz_id})
63
+ if st.get('error') and 'summary' not in st.get('url', ''):
64
+ return st
65
+ if 'summary' in st.get('url', ''):
66
+ return await j.handle({'action': 'submit'})
67
+ bank = None
68
+ if answer_bank:
69
+ bank = answer_bank(st.get('question') or '', st.get('options') or [])
70
+ if bank is not None:
71
+ cmd = {'action': 'select', 'answers': [{'index': bank}]}
72
+ if st.get('qtype') == 'text':
73
+ cmd = {'action': 'text', 'values': [bank]}
74
+ await j.handle(cmd)
75
+ await j.handle({'action': 'confirm'})
76
+ continue
77
+ prompt = 'You are solving a Moodle quiz question. Question: ' + json.dumps({'page': st.get('page'), 'question_hash': st.get('question_hash'), 'timeleft': st.get('timeleft'), 'q': st.get('question'), 'options': st.get('options'), 'checked': st.get('checked'), 'images': st.get('images')}, ensure_ascii=False) + ' Reply ONLY JSON: {"action": "answer|text|select|next|submit", "label": "...", "labels": [...], "index": 0, "value": "...", "values": [...]}'
78
+ if st.get('images'):
79
+ try:
80
+ from .vision import ocr_file
81
+ ocrs = await asyncio.to_thread(lambda: [ocr_file(f) for f in st['images']])
82
+ prompt += '\nOCR of option images: ' + json.dumps(ocrs, ensure_ascii=False)
83
+ except Exception:
84
+ pass
85
+ txt = await asyncio.to_thread(self.send_ai_request, prompt, st.get('option_images_b64') or ([st['question_image_b64']] if st.get('question_image_b64') else None))
86
+ resp = self.receive_ai_response(txt)
87
+ act = await self.execute_ai_response(resp)
88
+ if act in ('submit', None):
89
+ await j.handle({'action': 'confirm'})
90
+ return await self.qapi.get_result(quiz_id)
@@ -0,0 +1,13 @@
1
+ import http.server
2
+ import os
3
+ import socketserver
4
+
5
+ def serve_dumps(dumps_dir, port=8931):
6
+ os.chdir(dumps_dir)
7
+
8
+ class H(http.server.SimpleHTTPRequestHandler):
9
+
10
+ def log_message(self, *a):
11
+ pass
12
+ with socketserver.TCPServer(('0.0.0.0', port), H) as httpd:
13
+ httpd.serve_forever()