### Install dependencies Source: https://jtrecenti.github.io/txtcaptcha/notebooks/train_unified_model.html Commands to synchronize the environment and install the kernel for the notebook. ```bash uv sync --extra dev --extra notebook uv run python -m ipykernel install --user --name txtcaptcha ``` -------------------------------- ### Install txtcaptcha Source: https://jtrecenti.github.io/txtcaptcha Install the library using pip. ```bash pip install txtcaptcha ``` -------------------------------- ### Download status output Source: https://jtrecenti.github.io/txtcaptcha/notebooks/eval_per_dataset_live.html Example console output showing the status of the download process for specific sources. ```text [cadesp] already has 16 files — skipping download [esaj] fetching up to 16 ``` ```text C:\Users\jtrec\Documents\jtrecenti\txtcaptcha\src\txtcaptcha\download\_base.py:145: UserWarning: [esaj] fetch failed (DownloadError): esaj: non-JSON response warnings.warn(f"[{source}] fetch failed ({type(e).__name__}): {e}") ``` ```text [esaj] saved 0 [jucesp] already has 16 files — skipping download [rfb] fetching up to 16 ``` ```text C:\Users\jtrec\Documents\jtrecenti\txtcaptcha\src\txtcaptcha\download\_base.py:145: UserWarning: [rfb] fetch failed (DownloadError): rfb session: HTTP 404 warnings.warn(f"[{source}] fetch failed ({type(e).__name__}): {e}") C:\Users\jtrec\Documents\jtrecenti\txtcaptcha\src\txtcaptcha\download\_base.py:145: UserWarning: [rfb] fetch failed (ConnectionError): ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')) warnings.warn(f"[{source}] fetch failed ({type(e).__name__}): {e}") ``` ```text [rfb] saved 0 [sei] fetching up to 16 ``` ```text C:\Users\jtrec\Documents\jtrecenti\txtcaptcha\src\txtcaptcha\download\_base.py:145: UserWarning: [sei] fetch failed (DownloadError): sei start: HTTP 404 warnings.warn(f"[{source}] fetch failed ({type(e).__name__}): {e}") ``` ```text [sei] saved 0 [tjmg] already has 16 files — skipping download [tjpe] already has 16 files — skipping download [tjrs] fetching up to 16 ``` ```text C:\Users\jtrec\Documents\jtrecenti\txtcaptcha\src\txtcaptcha\download\_base.py:145: UserWarning: [tjrs] fetch failed (DownloadError): tjrs captcha: HTTP 404 warnings.warn(f"[{source}] fetch failed ({type(e).__name__}): {e}") ``` ```text [tjrs] saved 0 [trf5] already has 16 files — skipping download [trt] fetching up to 16 ``` ```text C:\Users\jtrec\Documents\jtrecenti\txtcaptcha\src\txtcaptcha\download\_base.py:145: UserWarning: [trt] fetch failed (DownloadError): trt captcha: HTTP 405 warnings.warn(f"[{source}] fetch failed ({type(e).__name__}): {e}") ``` ```text [trt] saved 0 ``` -------------------------------- ### Initialize environment and model Source: https://jtrecenti.github.io/txtcaptcha/notebooks/eval_per_dataset.html Imports necessary libraries, sets configuration constants, and loads the pre-trained model. ```python import random from pathlib import Path import matplotlib.pyplot as plt import pandas as pd from txtcaptcha import ( Captcha, available_datasets, decrypt, load_model, read_captcha, sequence_accuracy, ) from txtcaptcha.dataset import _label_from_path, _list_files MODEL_PATH = Path('txtcaptcha_unified.pt') DATA_ROOT = Path('data') SAMPLE_SIZE = 200 SEED = 0 random.seed(SEED) ``` ```python model = load_model(MODEL_PATH) model.eval() print(f'Loaded model with vocab size {len(model.vocab)}') ``` -------------------------------- ### Initialize environment and imports Source: https://jtrecenti.github.io/txtcaptcha/notebooks/train_unified_model.html Imports necessary modules and verifies CUDA availability for GPU acceleration. ```python import shutil from pathlib import Path import torch from txtcaptcha import ( available_datasets, download_dataset, fit_model, save_model, decrypt, ) print('CUDA available:', torch.cuda.is_available()) if torch.cuda.is_available(): print('Device:', torch.cuda.get_device_name(0)) ``` -------------------------------- ### Load the model Source: https://jtrecenti.github.io/txtcaptcha/notebooks/eval_per_dataset_live.html Initializes the model from a specified path and sets it to evaluation mode. ```python from txtcaptcha import load_model, read_captcha, decrypt MODEL_PATH = Path('txtcaptcha_unified.pt') model = load_model(MODEL_PATH) model.eval() print(f'Loaded model with vocab size {len(model.vocab)}') ``` -------------------------------- ### Download live captchas Source: https://jtrecenti.github.io/txtcaptcha/get-started.html Use the CLI to fetch fresh, unlabeled samples from supported sources. ```bash download_captchas --source tjmg --n 16 --out captchas/ ``` -------------------------------- ### Initialize CaptchaDataset Source: https://jtrecenti.github.io/txtcaptcha/reference/CaptchaDataset.html Instantiate the dataset with a root directory, vocabulary, image height, and case sensitivity settings. ```python CaptchaDataset(root, vocab=DEFAULT_VOCAB, height=32, case_sensitive=True) ``` -------------------------------- ### from_pretrained(repo_id, *, revision, token, cache_dir) Source: https://jtrecenti.github.io/txtcaptcha/reference/from_pretrained.html Downloads and loads a txtcaptcha CRNN model from the Hugging Face Hub. ```APIDOC ## from_pretrained ### Description Downloads and loads a txtcaptcha CRNN from the Hugging Face Hub. Downloaded files are cached in the global `huggingface_hub` cache. ### Signature `from_pretrained(repo_id=DEFAULT_REPO_ID, *, revision=None, token=None, cache_dir=None)` ### Parameters - **repo_id** (str) - Optional - The repository ID on the Hugging Face Hub. Defaults to `DEFAULT_REPO_ID`. - **revision** (str) - Optional - A branch, tag, or commit SHA. Defaults to `main`. - **token** (str) - Optional - Authentication token for the Hugging Face Hub. - **cache_dir** (str) - Optional - Path to the directory where files should be cached. ``` -------------------------------- ### Train a custom model Source: https://jtrecenti.github.io/txtcaptcha/get-started.html Download a dataset and train a new model using the fit_model function. ```python from txtcaptcha import fit_model, save_model, download_dataset data_dir = download_dataset("tjmg", "data") model, history = fit_model( data_dir, epochs=30, batch_size=64, case_sensitive=False, ) save_model(model, "tjmg.pt") ``` -------------------------------- ### Initialize DownloadError Source: https://jtrecenti.github.io/txtcaptcha/reference/DownloadError.html Instantiate the DownloadError exception class. ```python DownloadError() ``` -------------------------------- ### Publish and load models Source: https://jtrecenti.github.io/txtcaptcha/get-started.html Push a trained model to the Hugging Face Hub and load it for later use. ```python from txtcaptcha import push_to_hub push_to_hub( model, repo_id="your-username/your-captcha-model", model_card="# My captcha model\n\n...", tag="v0.1.0", ) ``` ```python from txtcaptcha import from_pretrained, decrypt, read_captcha model = from_pretrained("your-username/your-captcha-model", revision="v0.1.0") decrypt(read_captcha("captcha.png"), model=model) ``` -------------------------------- ### download_captchas(source, n, dest_dir, *, sleep=0.0, timeout=30.0, max_attempts=None, on_error='skip') Source: https://jtrecenti.github.io/txtcaptcha/reference/download_captchas.html Downloads up to n captchas from the specified source into the destination directory. Returns a list of the successfully written file paths. ```APIDOC ## download_captchas ### Description Downloads up to `n` captchas from `source` into `dest_dir`. Each successful fetch is saved with a unique filename format. ### Parameters - **source** (string) - Required - The source from which to download captchas. - **n** (integer) - Required - The target number of captchas to download. - **dest_dir** (string) - Required - The local directory where files will be saved. - **sleep** (float) - Optional - Time in seconds to sleep between requests. Default is 0.0. - **timeout** (float) - Optional - Request timeout in seconds. Default is 30.0. - **max_attempts** (integer) - Optional - Maximum number of failed attempts before stopping. Default is max(10, n * 3). - **on_error** (string) - Optional - Error handling strategy: 'skip' (default) or 'raise'. ### Returns - **list** - A list of strings representing the paths of the written files. ``` -------------------------------- ### CaptchaDataset(root, vocab=DEFAULT_VOCAB, height=32, case_sensitive=True) Source: https://jtrecenti.github.io/txtcaptcha/reference/CaptchaDataset.html Initializes the dataset for loading captcha images. The dataset expects files in the root directory to follow the naming convention _