Metadata-Version: 2.4
Name: pexams
Version: 0.16.0
Summary: A Python library for generating and correcting exams using Playwright and OpenCV.
Author: Oscar J. Pellicer-Valero
Project-URL: Homepage, https://github.com/OscarPellicer/pexams
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: openai>=1.0.0
Requires-Dist: anthropic>=1.0.0
Requires-Dist: opencv-python
Requires-Dist: numpy
Requires-Dist: pdf2image
Requires-Dist: pydantic
Requires-Dist: Markdown
Requires-Dist: Faker
Requires-Dist: Pillow
Requires-Dist: playwright
Requires-Dist: matplotlib
Requires-Dist: pandas
Requires-Dist: tabulate
Requires-Dist: pymdown-extensions
Requires-Dist: python-Levenshtein
Requires-Dist: pypdf
Requires-Dist: openpyxl
Requires-Dist: pytest
Requires-Dist: python-dotenv
Provides-Extra: trocr
Requires-Dist: torch; extra == "trocr"
Requires-Dist: torchvision; extra == "trocr"
Requires-Dist: transformers; extra == "trocr"
Requires-Dist: timm; extra == "trocr"
Dynamic: license-file

# Pexams: Python Exam Generation and Correction

Pexams is a library for generating beautiful multiple-choice exam sheets and automatically correcting them from scans using computer vision. It is similar to R/exams, but written in Python and using [Playwright](https://playwright.dev/python/) for high-fidelity PDF generation instead of LaTeX. It has the following advantages: it has more features, is faster, is easier to install, easier to customize, and it is much less prone to compilation errors than R/exams.

NOTE: This library is still in development and is not yet ready for production use. Although everything should work, there may be some bugs, missing features, or breaking changes in future versions.

## AI4Exams

Pexams is used together with `ptestgen` (writing and reviewing questions, the main entry point) and `pevaluate` (grading open answers and lab submissions with an LLM). Agents should start from the ptestgen skill (`ptestgen skill install`), which covers the whole workflow.

## Visual examples

You can view an example of a fully generated exam PDF [here](https://github.com/OscarPellicer/pexams/blob/main/media/exam_model_1.pdf).

Below is an example of a simulated answer sheet and the annotated, corrected version that the library produces.

| Simulated Scan | Corrected Scan |
| :---: | :---: |
| <img src="https://raw.githubusercontent.com/OscarPellicer/pexams/refs/heads/main/media/simulated_scan_model_1_1.png" width="400"> | <img src="https://raw.githubusercontent.com/OscarPellicer/pexams/refs/heads/main/media/WKAWA8P3.png" width="400"> |

The analysis module generates a detailed statistical report (PDF) including answer distributions and mark histograms.

![Answer Distribution](https://raw.githubusercontent.com/OscarPellicer/pexams/refs/heads/main/media/answer_distribution.png) 

![Mark Distribution](https://raw.githubusercontent.com/OscarPellicer/pexams/refs/heads/main/media/mark_distribution_0_10.png)



## Features

### Exam generation and Export

- **Multiple exam models**: Generate multiple unique exam models from a single source file, with automatic shuffling of questions and answers.
- **Formats support**:
  - **Input**: Write questions in Markdown (preferred) or JSON.
  - **Export**: Export questions to `rexams`, `wooclap`, `gift`, `moodle` (xml), or `md` formats.
- **Rich content support**: Write questions in Markdown and include:
  - **LaTeX equations**: Seamlessly render math formulas using MathJax (`$...$`).
  - **Images**: Embed images in your questions from local files.
  - **Code snippets**: Include code snippets (\`...\`).
- **Customizable layout**:
  - Arrange questions in one, two, or three columns.
  - Adjust the base font size to fit your needs.
- **Customizable answer sheet**:
  - Student ID field is a single box for the handwritten ID, read by a vision LLM (or TrOCR).
  - Internationalization support for exam labels (supported: `en`, `es`, `ca`, `de`, `fr`, `it`, `nl`, `pt`, `ru`, `zh`, `ja`).
- **High-fidelity PDFs**: Uses Playwright to produce clean, modern, and reliable PDF documents from HTML/CSS.

### Correction & analysis

- **Automated correction**: Correct exams from a single PDF containing all scans or from a folder of individual images.
- **Online platform results**: Ingest student answers exported from **Wooclap** or **Moodle** (CSV or XLSX) with `pexams correct-online`, without needing any scanned sheets. Fuzzy question and answer matching ensures robustness against minor text differences.
- **Robust image processing**: Uses `OpenCV` with fiducial markers for reliable, automatic perspective correction and alignment, a vision LLM (default) or the local `TrOCR` model to read the student ID, name and model ID, and custom position detection for the answers.
- **Detailed reports**:
  - `correction_results.csv`: Detailed scores and answers for each student.
  - `question_stats.csv`: Answer distribution statistics and original question IDs.
  - `stats_report.pdf`: A comprehensive, beautifully formatted PDF report containing:
    - Summary statistics (Mean, Median, Pass Rate, etc.).
    - Score distribution histogram.
    - Detailed item analysis for each question with bar charts showing response distribution (correct / incorrect 1 / incorrect 2 / ... / blank).
- **Insightful visualizations**: Automatically produces plots for:
  - **Mark distribution**: A histogram to assess overall student performance.
  - **Answer distribution**: A horizontal bar plot to analyze performance on each question and identify potential issues.
- **Flexible scoring**: Easily void specific questions during the analysis if needed, either by removing it from the score calculation completely or by voiding it "nicely" (can only increase the score if the question is correct, otherwise the question is removed from the score calculation).
- **Mark Filling & Fuzzy Matching**: Automatically fill an input CSV/Excel file with student marks, matching students by ID with fuzzy matching (Levenshtein distance) support for robustness against OCR errors.

### Development & testing

- **Simulated scans**: Automatically generate a set of fake, filled-in answer sheets to test the full correction and analysis pipeline.
- **End-to-end testing**: A simple `pexams test` command runs a full generate-correct-analyze cycle using bundled sample data and testing exports/fuzzy matching.
- **Easy debugging**: Keep the intermediate HTML files to inspect the exam content and layout before PDF conversion, by setting the `--log-level DEBUG` flag.

## Installation

The library has been tested on Python 3.11.

### 1. Install the library

You can install the library from PyPI:

```bash
pip install pexams
```

Alternatively, you can clone the repository and install it in editable mode, which is useful for development:

```bash
git clone https://github.com/OscarPellicer/pexams.git
cd pexams
pip install -e .
```

### 2. Install Playwright browsers

`pexams` uses Playwright to convert HTML to PDF. You need to download the necessary browser binaries by running:

```bash
playwright install chromium
```

This command only needs to be run once.

### 3. Install Poppler

You may also need to install Poppler, which is needed to convert PDFs to images during the correction phase and for generating simulated scans:

- **Windows**: `conda install -c conda-forge poppler` (alternatively, you can download the Poppler binaries from [the Poppler Windows repository](https://github.com/oschwartz10612/poppler-windows/releases/tag/v25.12.0-0))
- **macOS**: `brew install poppler`
- **Debian/Ubuntu**: `sudo apt-get install poppler-utils`

## Quick start

The `pexams test` command provides a simple way to run a full cycle and see the library in action. It uses a bundled sample file and media to generate, correct, and analyze a sample exam.

```bash
pexams test --output-dir ./my_test_output
```

This will create a `my_test_output` directory containing the generated exams, simulated scans, correction results, and analysis plots.

## Usage

### 1. The questions file (Markdown)

The preferred input format is a Markdown file (`.md`) with the following structure:

```markdown
## question_id
Question text, with any images: ![w:60mm|Caption](image.png)
 * Correct answer
 * Wrong answer 1
 * Wrong answer 2

**Explanation:**
Optional explanation text...
```

**Notes:**
- The **first answer** in the list is treated as the correct one (it will be shuffled during exam generation). The first `* `, `- ` or `1. ` line starts the options, so a multiple-choice question cannot contain a list in its text (an open-answer question can).
- Question IDs must be unique; they can be strings or integers.
- Per-question points can be set in the header with `{points=2.5}`. In mixed exams, or when questions have different values, they are printed after the question number, e.g. **3.** **[2.5 pt]** (see `--show-points`).
- Per-question font size can be set with `{font_size=8pt}`.
- `<!-- comments -->` are ignored (a commented-out question is skipped).
- The question text, the options and the custom header (`--custom-header`) are Markdown:

| Feature | Syntax | Notes |
|---|---|---|
| Emphasis | `*italic*`, `_italic_`, `**bold**` | Underscores inside words (`snake_case`) stay literal. |
| Line breaks | a single newline | In the question text a newline is a line break; a blank line starts a new paragraph. |
| Code | `` `inline` ``, fenced blocks ```` ```python ```` … ```` ``` ```` | Fenced blocks only in the question text and header; options are one line, so inline code only. Lines inside a fence are never read as headers, options or sections. |
| Math | `$x_1$`, `$$\sum_i x_i$$` (also across lines), `\$` for a literal dollar | Rendered with MathJax; `_`, `*` and newlines inside math are kept. `$5` alone is not math. Needs internet (MathJax CDN). |
| Images | `![alt](fig.png)` anywhere, several per question | Paths are relative to the `.md` file. |

Image layout goes in the alt text, `![spec|caption](img.png)` or `![spec](img.png)`: `w:<size>` and/or `h:<size>` (`px`, `mm`, `cm` or `%`; a plain number is px) and `left`, `right` (float, text wraps around it) or `center`. The caption is kept as the alt text (not printed). An alt that is not a valid spec, like `![left ventricle](lv.png)`, is just alt text.

````markdown
## ecg_1 {type=open lines=6}
![w:60mm right|ECG lead II](figs/ecg.png) What is the heart rate in this ECG?
Justify it with the RR interval, $HR = 60 / RR$.

```python
rr = np.diff(peaks) / fs
```
````

Images are ordinary Markdown images and can go anywhere. The older form, a `> ![...](img.png)` line right after the header, still works: it becomes an image below the question text (at the start of the text if its alt has a layout spec). In a JSON questions file, `max_image_width`/`max_image_height` limit every image of the question, and a legacy `image_source` is added below the text. Open-answer boxes always start below floated images. Moodle XML and GIFT exports (`--to moodle`, `--to gift`) render the text the same way and embed every image with its layout as inline styles; R/exams gets the images of the question text below it; Wooclap takes no images (questions with one are skipped).

### Mixed exams with open-answer questions

Open-answer questions are declared in the question header. The `lines` value reserves vertical space (7 mm per line, fractional values such as `lines=8.5` are allowed); guide lines are hidden by default and can be enabled per question with `show_lines=true`. The `**Expected answer:**` and `**Rubric:**` sections are not printed (they are used for grading); everything before them is the printed question text.

```markdown
## mc_1 {points=2 font_size=9pt}
What is the main purpose of regularization?
* To reduce overfitting
* To increase the number of parameters

## open_1 {type=open points=4 lines=10 show_lines=false font_size=10pt}
Explain why regularization can improve generalization.

**Expected answer:**
Regularization discourages overly complex models and can reduce overfitting.

**Rubric:**
2 points for model complexity, 1 for overfitting/generalization, 1 for train/validation contrast.
```

If an exam has no multiple-choice questions, there is nothing to mark on an answer sheet: the student header (title, model, ID, name and signature) is printed at the top of the first question page instead, which saves the answer sheet and the blank page after it. The header keeps the answer-sheet coordinates, so correction works in the same way.

Questions are laid out page by page with any number of columns (`--columns 1|2|3`): a question or open-answer box never crosses a page break, and every page carries its own four fiducial markers.

When correcting scans, `pexams` writes `open_responses_index.csv` and cropped open-answer images under `open_responses/`. These artifacts are intended for `pevaluate exam-open`.

### 2. CLI commands

#### `pexams generate`

Generates exam PDFs or exports questions to other formats.

```bash
pexams generate <input_file> --to <format> --output-dir <path> [OPTIONS]
```

**Arguments:**

- `input_file`: (Positional) Path to the input file (Markdown or JSON).
- `--to <format>`: Output format. Options: `pexams` (default, PDF generation), `rexams`, `wooclap`, `gift`, `md`, or `moodle` (xml).
- `--output-dir <path>`: Directory to save the output.

**Common Options (for all formats):**
- `--log-level <level>`: Set the logging level (DEBUG, INFO, WARNING, ERROR).
- `--shuffle-questions <int>`: Seed for shuffling the order of questions (default: 42). If not set, questions keep their original order.
- `--shuffle-answers <int>`: Seed for shuffling the order of answers/options (default: 42).

**Options for `pexams` format:**
- `--num-models <int>`: Number of different exam models to generate (default: 4).
- `--exam-title <str>`: Title of the exam (default: "Final Exam").
- `--exam-course <str>`: Course name for the exam (optional).
- `--exam-date <str>`: Date of the exam (optional).
- `--columns <int>`: Number of columns for the questions (1, 2, or 3; default: 1).
- `--font-size <str>`: Base font size for the exam (e.g., '10pt', '12px'; default: '10pt').
- `--total-students <int>`: Total number of students for mass PDF generation (default: 0).
- `--extra-model-templates <int>`: Number of extra template sheets (answer sheet only) to generate per model (default: 0).
- `--lang <str>`: Language for the answer sheet labels (e.g., 'en', 'es'; default: 'en').
- `--keep-html`: If set, keeps the intermediate HTML files used for PDF generation.
- `--generate-fakes <int>`: Generates a number of simulated scans with fake answers for testing the correction process (default: 0).
- `--generate-references`: If set, generates a reference scan with the correct answers marked for each model.
- `--custom-header <str>`: Markdown string or path to a Markdown file to insert before the questions (e.g., instructions).
- `--mc-total-points <float>`: Assign a total value to all multiple-choice questions and distribute it evenly. Do not combine this with per-question non-default MC points.
- `--fill-answer-space`: Grow the open-answer boxes of each page so they use the free space left at its bottom. Boxes with an explicit `height_mm` keep their size.
- `--show-points {auto,always,never}`: Print each question's points after its number, e.g. `[1.5 pt]` (`[1,5 pt]` with a decimal-comma `--lang`). `auto` (default) prints them only when the exam has open-answer questions or questions of different value; a test where every question is worth the same shows none. The printed value is the question's own `points` (after `--mc-total-points`), not rescaled, so choose points that add up to the total you announce.

### Comprehensive Example

```bash
pexams generate my_questions.md --output-dir ./generated_exam \
    --exam-title "Computer Systems - Midterm Exam" \
    --exam-course "Master in Computer Engineering" \
    --exam-date "2025-12-19" \
    --num-models 4 \
    --font-size "9pt" \
    --lang "es" \
    --columns 2 \
    --total-students 22 \
    --extra-model-templates 2 \
    --generate-fakes 1 \
    --generate-references \
    --keep-html \
    --custom-header "**Instructions:** Incorrect answers will be penalized by **-0.25 points** (a correct answer is +1 point). You are only allowed to have a pen, corrector fluid, and your ID card on top of the table."
```

#### `pexams correct`

Corrects scanned exams, runs analysis, and optionally fills marks into a student list.

```bash
pexams correct --input-path <path> --exam-dir <path> --output-dir <path> [OPTIONS]
```

**Comprehensive Example:**

```bash
pexams correct \
    --input-path ./generated_exam/simulated_scans \
    --exam-dir ./generated_exam \
    --output-dir ./generated_exam/correction_results \
    --input-csv ./grades.csv \
    --id-column "Student ID" \
    --mark-column "Midterm Mark" \
    --fuzzy-id-match 80 \
    --penalty 0.25 \
    --input-encoding "utf-8"
```

- The `--input-path` can be a PDF file or a folder of images (PNG, JPG) or PDFs. If the batch was scanned into several PDFs, pass them all (`--input-path scan1.pdf scan2.pdf scan3.pdf`) or their folder: pages are read in the order given (files in a folder sorted by name) as one batch, so an exam may even be split between two PDFs.
- The `--exam-dir` must contain the `exam_model_*_questions.json` files generated alongside the exam PDFs.

**Mark Filling Arguments:**

- `--input-csv <path>`: Path to an input CSV/XLSX/TSV file containing student IDs.
- `--id-column <name>`: Column name in input file containing student IDs.
- `--mark-column <name>`: Column name to fill with marks (will be created if missing).
- `--fuzzy-id-match <0-100>`: Threshold for fuzzy matching of IDs (default 100 = exact match only).
- `--name-match-threshold <0-100>`: When `--input-csv` and `--name-column` are provided, scanned exams are matched to the roster by OCR'd student name before analysis. If any scan cannot be matched, `pexams` writes `student_matches.csv` and stops before producing named artifacts or reports.
- `--id-reader {llm,trocr}`: How to read the model, student-ID and name boxes. `llm` (default) sends the three box crops of each answer sheet to a vision LLM in one call; `trocr` uses the local TrOCR model, which is also the fallback when no API key is set or a call fails. Without `--input-csv`, each exam is identified by the ID and name read from it.
- `--id-reader-model <model>`: Model for `--id-reader llm` (default `claude-opus-5-5` at low effort, about $0.002 per exam: it misread the fewest IDs and names in our tests, ahead of `claude-sonnet-5-5` and `claude-haiku-5-5`). Bare `claude-...` ids use the Anthropic API (`ANTHROPIC_API_KEY`); any other name (e.g. `google/gemini-3.8-flash`) uses OpenRouter (`OPENROUTER_API_KEY`).
- `--id-reader-effort <low|medium|high>`: Reasoning effort (default `low`).
- `--api-key-env <VAR>`: Read the API key from another environment variable.
- `--use-llm-name-ocr`, `--openrouter-name-model`: Deprecated aliases of `--id-reader llm --id-reader-model <model>`.
- `--input-encoding <str>`: Encoding of the input CSV file (default `utf-8`). Useful if you encounter encoding errors, in which case you can try `latin1` or `utf-8-sig`.
- `--input-sep <str>`: Separator for the input CSV file (default `,`). If your CSV uses semicolons (common in Europe), pass `--input-sep semi` or `--input-sep ";"`.
- `--output-decimal-sep <str>`: Decimal separator for the output marks (default `.`). Use `,` if your locale requires comma decimals (e.g., `--output-decimal-sep ","`).
- `--simplify-csv`: If set, the output CSV (`*_with_marks.csv`) will only keep the columns specified by `--id-column`, `--name-column`, and `--mark-column`. This is useful for creating a clean file for importing into a gradebook.
- `--name-column <name>`: Column name in input file containing student names. Required if `--simplify-csv` is used.

**Scoring Arguments:**

- `--penalty <float>`: Penalty for each wrong answer, as a fraction of that question's points (e.g., `0.33333` subtracts a third of the question's value). Default is `0.0`. With 1-point questions: `score = correct_answers - (wrong_answers * penalty)`. Blank/unanswered questions are not penalized.

**Other Arguments:**

- `--void-questions <str>`: Comma-separated list of question numbers to exclude from scoring.
- `--void-questions-nicely <str>`: Comma-separated list of question IDs to void "nicely".
- `--only-analysis`: Skip the image processing step (OCR/OMR) and proceed directly to the analysis and grading phase using an existing `correction_results.csv`. The annotated sheets in `scanned_pages/` are redrawn from it (from the unannotated sheets kept in `scanned_pages/.raw/`), so a misread answer fixed by hand, or a voided question, also shows on the sheet the student gets.
- `--lang <code>`: Language of the labels drawn on the annotated sheets (e.g. `es`: voided questions are labelled "ANULADA"). Default `en`.

**Layout check.** Each open-answer crop is checked against the printed box borders. If the borders are not where `open_answer_areas.json` expects them (typically because `--exam-dir` is not the exact version that was printed), pexams logs a warning and marks the crop with `layout_check=box_not_found` in `open_responses_index.csv`.

**Writing outside the answer box.** Each scanned page is compared with the blank page of `exam_model_N.pdf` (in `--exam-dir`): what is on the scan and not printed is handwriting. When an answer has more than 6 mm² of it below its box (down to the next box, at most 30 mm) or in the side margins, the index gets `ink_outside_box=yes` (with `ink_outside_mm2`), and `open_responses/context/` a crop of the box with its surroundings (`context_crop_path`, the box within it in `context_box`). `pevaluate exam-open` grades those answers from the context crop.

**How a box is read.** A box counts as marked when more than 30% of its inside (0.5 mm in from the printed border) is dark. The border itself is left out because it alone fills 20-30% of the box, and a border redrawn by hand after correction fluid even more; in a real exam, unmarked boxes stayed below 10% inside and marked ones (light pencil included) above 50%.

**Two boxes filled in one question.** Students sometimes cross out a filled box instead of using correction fluid, which makes the crossed-out box the darkest. A question with more than one filled box is therefore not decided by fill level: the vision LLM used for the headers is shown the row and asked which option is the final answer. The `multiple_marks` column of `correction_results.csv` records it (`5:B+C->B`); without an LLM, or if it cannot be decided (`->?`), the question stays blank. Review those rows, fix `answer_N` if needed and rerun with `--only-analysis`.

**Traceability.** With `--id-reader llm`, the output folder also contains `run_manifest.json` (command, package versions and git commits, model, effort, SHA-256 of the inputs) and `llm_calls.jsonl` (one line per LLM call: model requested and served, effort, request id, tokens, latency and hashes of the prompt, images and response).

### Manual Correction Workflow

If you find errors in the automatic correction (e.g., an incorrect student ID or a misread answer), you can manually fix them without re-running the time-consuming image processing.

1.  Open the `correction_results.csv` file in the output directory.
2.  Manually edit the values (e.g., correct a student ID or change an answer from 'A' to 'B' or 'NA').
3.  Save the CSV file.
4.  Run the `correct` command again with the `--only-analysis` flag.

```bash
pexams correct \
    --exam-dir ./generated_exam \
    --output-dir ./generated_exam/correction_results \
    --only-analysis \
    --penalty 0.25
```

This will re-read the corrected CSV, recalculate all scores (applying penalties, void questions, etc.), regenerate the plots, and update the final marks.

#### `pexams moodle-feedback-zip`

Creates a Moodle Assignment feedback-file ZIP from the corrected scans in `scanned_pages/` plus the marks in `final_marks.csv`.
Upload the resulting ZIP in Moodle with **Upload multiple feedback files in a zip** / **Penja múltiples fitxers de retroacció en un zip**.

The assignment needs the **Feedback files** feedback type enabled (Settings → Feedback types); the upload is in **Submissions → Actions → Upload feedback files in a zip**:

![Moodle: Submissions → Actions](https://raw.githubusercontent.com/OscarPellicer/pevaluate/refs/heads/main/media/moodle_submissions_actions.png)

```bash
pexams moodle-feedback-zip \
    --moodle-csv "./Qualificacions-assignacio.csv" \
    --correction-dir ./generated_exam/correction_results \
    --feedback-mode zip \
    --output-zip ./generated_exam/moodle_feedback.zip
```

By default, ZIP mode generates one PDF feedback file per matched student. Pass `--feedback-file-format png` if you prefer the older PNG files.

You can also try an experimental CSV workflow that embeds the same PNG as a base64 `data:image/png` inside the Moodle feedback-comments column:

```bash
pexams moodle-feedback-zip \
    --moodle-csv "./Qualificacions-assignacio.csv" \
    --correction-dir ./generated_exam/correction_results \
    --feedback-mode csv \
    --output-csv ./generated_exam/moodle_feedback_base64.csv
```

Or generate both candidates at once:

```bash
pexams moodle-feedback-zip \
    --moodle-csv "./Qualificacions-assignacio.csv" \
    --correction-dir ./generated_exam/correction_results \
    --feedback-mode both \
    --output-zip ./generated_exam/moodle_feedback.zip \
    --output-csv ./generated_exam/moodle_feedback_base64.csv
```

The Moodle grading-table export is used to map students to Moodle's internal participant identifiers. `pexams` accepts explicit column names and also resolves common Catalan, Spanish, and English Moodle headers automatically. In Catalan Moodle exports, the usual columns are:

- `--participant-column "Identificador"`: values like `Participant12744381`; pexams extracts the numeric id.
- `--id-column "Número ID"`: the real student ID, matched against `final_marks.csv`.
- `--name-column "Nom complet"`: shown in the generated feedback filename/header.

The ZIP entries are named like:

```text
Full Name_12744381_assignfeedback_file_pexams_feedback_STUDENTID.pdf
```

That filename pattern is what Moodle's assignment feedback-file importer expects: it extracts the numeric participant id and the `assignfeedback_file` plugin name from the path. The command also writes `<output>_manifest.csv` so you can inspect which students were added, unmatched, or missing an image before uploading.

**Important:** this Moodle action uploads feedback files only. Grades still need to be uploaded through Moodle's grading worksheet or filled/imported separately, unless your Moodle workflow combines those steps.

**Experimental CSV note:** the base64 CSV mode writes HTML into `Comentaris de retroacció.` and fills `Qualificació` by default. Some Moodle sites strip `data:` image URLs from comments for security, so treat this as a trial path. If Moodle removes the image or rejects the CSV, use the ZIP mode for feedback files and the grading worksheet for marks.

**Arguments:**

- `--moodle-csv <path>`: CSV/XLSX exported from the Moodle assignment grading table. **Required.**
- `--correction-dir <path>`: Directory containing `final_marks.csv` and `scanned_pages/`. **Required.**
- `--feedback-mode <zip|csv|both>`: Which output(s) to create. Default: `zip`.
- `--output-zip <path>`: ZIP file to create. Required for `zip` and `both`.
- `--output-csv <path>`: CSV file to create for base64 mode. Default: `<correction-dir>/moodle_feedback_base64.csv`.
- `--feedback-file-format <pdf|png>`: File type inside the ZIP. Default: `pdf`.
- `--images-dir <path>`: Override the annotated images directory. Default: `<correction-dir>/scanned_pages`.
- `--marks-csv <path>`: Override the marks CSV. Default: `<correction-dir>/final_marks.csv`.
- `--feedback-column <name>`: Feedback comments column for CSV mode. Default: `Comentaris de retroacció.`.
- `--grade-column <name>`: Grade column for CSV mode. Default: `Qualificació`; pass `--grade-column ""` to skip grade filling.
- `--moodle-sep <str>` and `--moodle-encoding <str>`: CSV separator and encoding. Use `--moodle-sep semi` for semicolon CSVs.
- `--overwrite`: Replace an existing output ZIP.

### Recommended Scan Settings

For best results with the automatic correction, please use the following settings when scanning the answer sheets:

-   **Resolution**: **300 DPI** is recommended. Lower resolutions (e.g., 150 DPI) might work but are less reliable for OCR.
-   **Color Mode**: **Grayscale** is highly recommended. **Do NOT use "Black and White" (1-bit / Threshold)** mode, as it destroys the details needed for accurate bubble detection and OCR. Color scans also work but produce larger files without significant benefit.
-   **Format**: PDF (multi-page) or images (PNG/JPG).

#### `pexams correct-online`

Ingests student answers exported from an online platform (Wooclap or Moodle) and runs the same analysis and PDF report pipeline as `pexams correct`, without needing any scanned sheets.

```bash
pexams correct-online {wooclap,moodle} --input-file <questions.md> \
    --results <results.xlsx> \
    --output-dir <path> [OPTIONS]
```

**How matching works:**  
For both platforms, answer text is matched to stored options via exact match first (case-insensitive), then Levenshtein fuzzy match as a fallback. A message is printed whenever fuzzy matching is used so you can verify mappings. For Wooclap, question column headers (`Q1 - <text> (N pts)`) are also matched to questions by text (exact then fuzzy).

---

##### `pexams correct-online wooclap`

Parses a Wooclap "Export to Excel" results file. Column headers must follow the format `Q1 - <question text> (N pts)`. Answer cells are prefixed with `V - ` (correct chosen) or `X - ` (wrong chosen).

```bash
pexams correct-online wooclap \
    --input-file my_questions.md \
    --results wooclap_export.xlsx \
    --output-dir ./results \
    --fuzzy-threshold 80 \
    --penalty 0.0
```

**Arguments:**

- `--input-file <path>`: Questions file (`.md` or `.json`) used when exporting to Wooclap. **Required.**
- `--results <path>`: Wooclap results CSV or XLSX. **Required.**
- `--output-dir <path>`: Output directory. **Required.**
- `--fuzzy-threshold <0–100>`: Minimum similarity for fuzzy question matching. Default: `80`.
- `--penalty <float>`: Score penalty per wrong answer. Default: `0.0`.
- `--encoding <str>`: File encoding. Default: auto-detect.
- `--sep <str>`: CSV separator. Default: auto-detect.

---

##### `pexams correct-online moodle`

Parses a Moodle quiz "Responses" CSV or XLSX export. Answer columns are detected by locale-flexible regex (`Resposta N`, `Respuesta N`, `Response N`, etc.) and mapped positionally to questions by default.

```bash
pexams correct-online moodle \
    --input-file my_questions.md \
    --results moodle_responses.csv \
    --output-dir ./results \
    --penalty 0.0
```

**Arguments:**

- `--input-file <path>`: Questions file (`.md` or `.json`) used when exporting to Moodle. **Required.**
- `--results <path>`: Moodle results CSV or XLSX. **Required.**
- `--output-dir <path>`: Output directory. **Required.**
- `--question-order <str>`: Comma-separated 1-based question indices that maps `Resposta 1` to `questions[index-1]`, etc. Default: sequential order.
- `--penalty <float>`: Score penalty per wrong answer. Default: `0.0`.
- `--encoding <str>`: File encoding. Default: auto-detect.
- `--sep <str>`: CSV separator. Default: auto-detect.

---

**Output files (same as `pexams correct`):**

| File | Description |
|---|---|
| `correction_results.csv` | Per-student answer matrix |
| `question_stats.csv` | Per-question per-option answer counts |
| `final_marks.csv` | Student marks on a 0–10 scale |
| `mark_distribution_0_10.png` | Score histogram |
| `stats_report.pdf` | Full PDF report with per-question answer distribution |

---

#### `pexams test`

Runs a full generate/correct/analyze cycle using bundled sample data, and tests exports and fuzzy matching.

```bash
pexams test [OPTIONS]
```

## Python API Usage

In addition to the CLI, you can use `pexams` as a Python library.

### 1. Generating Exams

To generate exams, use the `pexams.generate_exams.generate_exams` function.

```python
from pexams import generate_exams
from pexams.schemas import PexamQuestion, PexamExam
from pexams.main import _load_and_prepare_questions

# You can load questions from a MD file
# questions = _load_and_prepare_questions("path/to/your/questions.md")

# Or define them manually
questions = [
    PexamQuestion(
        id="q1",
        text="What is 2+2?",
        options=[
            {"text": "4", "is_correct": True}, # First is correct
            {"text": "3", "is_correct": False},
        ]
    )
]

# Generate 2 exam models and save them in the ./my_exams directory
generate_exams.generate_exams(
    questions=questions,
    output_dir="./my_exams",
    num_models=2,
    exam_title="Quiz 1"
)
```

### 2. Correcting Exams

To correct exams, you first need to load the solutions that were generated, then call `pexams.correct_exams.correct_exams`.

```python
from pexams import correct_exams, utils

exam_dir = "./my_exams" # The output from generate_exams
solutions_full, solutions_simple, max_score = utils.load_solutions(exam_dir)

correct_exams.correct_exams(
    input_path="./my_exams/simulated_scans", # Path to PDF or folder of images
    solutions_per_model=solutions_simple,
    output_dir="./correction_output",
    questions_dir=exam_dir
)
```

### 3. Analyzing Results

After correction, you can run the analysis using `pexams.analysis.analyze_results`.

```python
from pexams import analysis

analysis.analyze_results(
    csv_filepath="./correction_output/correction_results.csv",
    exam_dir="./my_exams", # Automatically loads solutions
    output_dir="./correction_output"
)
```

### 4. Ingesting Online Platform Results (Wooclap / Moodle)

For online quizzes you can parse the platform export directly — no scanned sheets needed.
Use `create_solutions_from_questions` to build the solutions structure from the question list
instead of loading `exam_model_*_questions.json` files from disk.

```python
from pexams import analysis, utils
from pexams.io.loader import load_and_prepare_questions
from pexams.io.online_results import parse_wooclap_results, parse_moodle_results

# Load the same questions file you used when exporting to Wooclap / Moodle
questions = load_and_prepare_questions("my_questions.md")

# Build the solutions structures (no JSON files required)
solutions_full, solutions_simple, max_score = utils.create_solutions_from_questions(questions)

# --- Wooclap ---
results_df = parse_wooclap_results(
    results_path="wooclap_export.xlsx",
    questions=questions,
    fuzzy_threshold=0.80,   # 0–1 ratio; a message is printed for fuzzy matches
)

# --- Moodle ---
# results_df = parse_moodle_results(
#     results_path="moodle_responses.csv",
#     questions=questions,
# )

import os
os.makedirs("./online_results", exist_ok=True)

# Save in the standard correction_results.csv format
results_df.to_csv("./online_results/correction_results.csv", index=False)

# Run the full analysis & PDF report pipeline
analysis.analyze_results(
    csv_filepath="./online_results/correction_results.csv",
    max_score=max_score,
    output_dir="./online_results",
    solutions_per_model=solutions_full,
)
```

## Contributing

Pull requests are welcome! Please feel free to submit an issue or pull request.

## Contact

`oscar.pellicer at uv dot es`

## TODO

- Create a set of layouts allowing for more answers per question, or overall more questions (more compact), etc.
- Add cli argument to change the scoring system, such as using German grading (1-6) instead of the default 0-10, or using a 100-point scale instead of the default 0-10.
