openapi: 3.1.0
info:
  title: MkPDF API
  version: "1.0"
  description: >
    Конвертация HTML/URL/DOCX-XLSX-PPTX в PDF, слияние PDF и распознавание
    текста (OCR). Источник правды по параметрам — docs/api.md в репозитории;
    этот файл сгенерирован из того же контракта и не должен расходиться с ним.
  contact:
    email: support@mkpdf.ru
servers:
  - url: https://api.mkpdf.ru
    description: Production
  - url: https://api.lt.mkpdf.ru
    description: Reserve — the same API through a proxy in Latvia; use it when the main host is unreachable (same paths, same API key)
security:
  - bearerAuth: []
tags:
  - name: convert
    description: HTML/URL/Office → PDF
  - name: merge
    description: Слияние PDF
  - name: pdf
    description: Конвертация из PDF (Word, PNG, JPG, HTML, текст) и операции над PDF (разделить, повернуть, сжать, защитить, водяной знак, PDF/A)
  - name: ocr
    description: Распознавание текста
  - name: jobs
    description: Статус асинхронных задач

paths:
  /v1/convert/html:
    post:
      tags: [convert]
      summary: HTML → PDF
      description: Конвертирует HTML-разметку в PDF через Chromium — CSS, кастомные шрифты, кириллица из коробки.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ConvertHtmlRequest' }
      responses:
        '200': { $ref: '#/components/responses/PdfOrUrl' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/convert/url:
    post:
      tags: [convert]
      summary: URL → PDF
      description: Рендерит реальную веб-страницу (вместе с JS и динамическим контентом) в PDF.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ConvertUrlRequest' }
      responses:
        '200': { $ref: '#/components/responses/PdfOrUrl' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/convert/office:
    post:
      tags: [convert]
      summary: DOCX / XLSX / PPTX → PDF
      description: Конвертирует офисные документы (docx/doc, xlsx/xls, pptx/ppt, odt/ods/odp, rtf, txt, csv) в PDF через LibreOffice. Лимит 50 МБ. Другие форматы (в том числе изображения — для них есть /v1/convert/image) и пустые файлы отклоняются с 400.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'Один документ: docx/doc, xlsx/xls, pptx/ppt, odt/ods/odp, rtf, txt или csv' }
                password: { type: string, maxLength: 128, description: 'Пароль на открытие, если документ защищён' }
      responses:
        '200':
          description: PDF в теле ответа
          content:
            application/pdf: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422':
          description: Документ повреждён или защищён паролем, а пароль не передан или неверен
          content:
            application/json: { schema: { $ref: '#/components/schemas/Error' } }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/merge:
    post:
      tags: [merge]
      summary: Объединить PDF
      description: >
        Склеивает 2 и более PDF в один, в порядке загрузки. Лимит 50 МБ суммарно.
        PDF распознаётся по содержимому, расширение имени не важно. Если среди файлов есть
        не-PDF или пустой файл — 400 с его именем (файлы не пропускаются молча);
        повреждённый или защищённый паролем PDF — 422.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [files]
              properties:
                files:
                  type: array
                  minItems: 2
                  items: { type: string, format: binary }
                  description: Повторяющееся поле `files`, минимум 2 PDF
      responses:
        '200':
          description: Объединённый PDF в теле ответа
          content:
            application/pdf: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/convert/image:
    post:
      tags: [convert]
      summary: Изображения → PDF
      description: JPG/PNG/GIF/BMP/TIFF в один PDF, по странице на изображение, в порядке загрузки. До 30 файлов, до 50 МБ суммарно. Формат определяется по содержимому, а не по расширению; пустой файл или файл, не являющийся изображением, отклоняется с 400.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [files]
              properties:
                files:
                  type: array
                  minItems: 1
                  maxItems: 30
                  items: { type: string, format: binary }
      responses:
        '200':
          description: PDF в теле ответа
          content:
            application/pdf: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/to-word:
    post:
      tags: [pdf]
      summary: PDF → Word
      description: Редактируемый .docx. Для PDF с текстовым слоем; до 100 страниц.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
      responses:
        '200':
          description: DOCX в теле ответа
          content:
            application/vnd.openxmlformats-officedocument.wordprocessingml.document: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '413': { $ref: '#/components/responses/TooManyPages' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/to-png:
    post:
      tags: [pdf]
      summary: PDF → PNG
      description: Страницы как PNG. Одна страница — image/png, несколько — ZIP (page-1.png, …).
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
                dpi: { type: integer, minimum: 72, maximum: 300, default: 150 }
      responses:
        '200':
          description: PNG или ZIP
          content:
            image/png: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '413': { $ref: '#/components/responses/TooManyPages' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/to-jpg:
    post:
      tags: [pdf]
      summary: PDF → JPG
      description: Страницы как JPG (качество 90%). Одна страница — image/jpeg, несколько — ZIP.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
                dpi: { type: integer, minimum: 72, maximum: 300, default: 150 }
      responses:
        '200':
          description: JPEG или ZIP
          content:
            image/jpeg: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '413': { $ref: '#/components/responses/TooManyPages' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/to-html:
    post:
      tags: [pdf]
      summary: PDF → HTML
      description: Один самодостаточный HTML-файл с встроенными изображениями.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
      responses:
        '200':
          description: HTML в теле ответа
          content:
            text/html: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '413': { $ref: '#/components/responses/TooManyPages' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/to-text:
    post:
      tags: [pdf]
      summary: PDF → TXT
      description: >
        Текстовый слой документа (UTF-8) с сохранением расположения. Текст извлекается в порядке
        чтения, поэтому поворот страниц (/Rotate) на результат не влияет. У скана или PDF из одних
        картинок текстового слоя нет — ответ 200 с пустым или почти пустым текстом; для таких
        файлов используйте OCR (`/v1/ocr/document`).
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
      responses:
        '200':
          description: Текст в теле ответа
          content:
            text/plain: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '413': { $ref: '#/components/responses/TooManyPages' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/split:
    post:
      tags: [pdf]
      summary: Разделить PDF
      description: >
        mode=pages — извлечь страницы (span, например 1-3, 7) в один PDF; mode=intervals — разделить
        на части по span страниц (ZIP с частями report-pages-1-3.pdf, …; если span не меньше числа страниц — один PDF).
        Номера страниц начинаются с 1, в диапазоне a-b нужно a ≤ b (иначе 400); страница за
        пределами документа — 422 с её номером. Повреждённый или защищённый PDF — 422.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file, span]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
                mode: { type: string, enum: [pages, intervals], default: pages }
                span: { type: string, description: 'pages: диапазоны 1-3, 7 (страницы с 1 до числа страниц документа); intervals: целое число страниц в части, от 1' }
      responses:
        '200':
          description: PDF или ZIP
          content:
            application/pdf: { schema: { type: string, format: binary } }
            application/zip: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/rotate:
    post:
      tags: [pdf]
      summary: Повернуть PDF
      description: Поворот всех страниц по часовой стрелке. Повреждённый или защищённый паролем PDF — 422.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
                angle: { type: integer, enum: [90, 180, 270], default: 90 }
      responses:
        '200':
          description: PDF в теле ответа
          content:
            application/pdf: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/compress:
    post:
      tags: [pdf]
      summary: Сжать PDF
      description: >
        Пересохраняет растровые изображения внутри PDF (JPEG, PNG и другие) как JPEG с качеством
        quality: меньше — сильнее сжатие. Изображение заменяется, только если новый вариант меньше
        исходного, поэтому файл не растёт. Маски, CMYK, индексированные цвета и изображения не 8 бит
        на канал не трогаются; текст и вектор не меняются, поэтому на документах без картинок
        выигрыш небольшой. Повреждённый или защищённый паролем PDF — 422.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
                quality: { type: integer, minimum: 10, maximum: 95, default: 70, description: 'Качество JPEG' }
      responses:
        '200':
          description: PDF в теле ответа
          content:
            application/pdf: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '413': { $ref: '#/components/responses/TooManyPages' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/protect:
    post:
      tags: [pdf]
      summary: Защитить PDF паролем
      description: Шифрует PDF; пароль не сохраняется и не логируется. Повреждённый или уже защищённый паролем PDF — 422.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file, password]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
                password: { type: string, minLength: 1, maxLength: 128, format: password }
      responses:
        '200':
          description: PDF в теле ответа
          content:
            application/pdf: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/watermark:
    post:
      tags: [pdf]
      summary: Водяной знак
      description: Текст на каждой странице (латиница и кириллица) — одной крупной надписью или мозаикой, под 45°, горизонтально или вертикально.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file, text]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
                text: { type: string, maxLength: 60 }
                opacity: { type: number, minimum: 0.05, maximum: 1, default: 0.3 }
                orientation: { type: string, enum: [diagonal, horizontal, vertical], default: diagonal, description: 'Направление надписи: под 45°, горизонтально, вертикально' }
                layout: { type: string, enum: [single, tiled], default: single, description: 'single — одна крупная надпись по центру; tiled — много маленьких по всей странице' }
      responses:
        '200':
          description: PDF в теле ответа
          content:
            application/pdf: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '413': { $ref: '#/components/responses/TooManyPages' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/unlock:
    post:
      tags: [pdf]
      summary: Снять пароль с PDF
      description: Снимает пароль с файла, который вы можете открыть; пароль владельца (ограничения на копирование/печать) снимается и без пароля. Пароли не подбираются.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
                password: { type: string, maxLength: 128, format: password }
      responses:
        '200':
          description: PDF в теле ответа
          content:
            application/pdf: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '413': { $ref: '#/components/responses/TooManyPages' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/page-numbers:
    post:
      tags: [pdf]
      summary: Номера страниц
      description: >
        Проставляет номера страниц. При skip_first=true первая страница остаётся без номера, но
        учитывается в нумерации (вторая получает «2»); одностраничный документ тогда возвращается
        без номеров.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
                position: { type: string, enum: [bl, bc, br, tl, tc, tr], default: bc }
                format: { type: string, enum: [n, n_of_total, page_n, page_n_ru, dash_n], default: n }
                skip_first: { type: boolean, default: false, description: 'Строго true или false; другие значения (1, 0, yes…) — 400' }
      responses:
        '200':
          description: PDF в теле ответа
          content:
            application/pdf: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '413': { $ref: '#/components/responses/TooManyPages' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/crop:
    post:
      tags: [pdf]
      summary: Обрезать PDF
      description: >
        Обрезает видимую область; содержимое за границей остаётся в файле. Каждое поле — 0–90%,
        а сумма противоположных (top + bottom, left + right) должна быть меньше 95%, иначе 400.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
                top: { type: number, minimum: 0, maximum: 90, default: 0, description: 'процент от высоты страницы' }
                right: { type: number, minimum: 0, maximum: 90, default: 0 }
                bottom: { type: number, minimum: 0, maximum: 90, default: 0 }
                left: { type: number, minimum: 0, maximum: 90, default: 0 }
      responses:
        '200':
          description: PDF в теле ответа
          content:
            application/pdf: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '413': { $ref: '#/components/responses/TooManyPages' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/edit:
    post:
      tags: [pdf]
      summary: Наложить текст, изображения и прямоугольники
      description: >
        JSON-массив `ops` (1–300 элементов, см. схему EditOp); координаты — доли страницы от левого
        верхнего угла. Значения за пределами диапазонов не отклоняются, а приводятся к границам
        (например x=1.5 → 1, size=10000 → 200). Графическое наложение, не электронная подпись.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file, ops]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
                ops:
                  type: string
                  contentMediaType: application/json
                  contentSchema:
                    type: array
                    minItems: 1
                    maxItems: 300
                    items: { $ref: '#/components/schemas/EditOp' }
                  description: 'JSON-массив элементов EditOp (строка, до 40 МБ вместе с картинками в base64)'
                  example: '[{"type":"text","page":1,"x":0.1,"y":0.1,"text":"Одобрено","size":18,"color":"#0a7d33"},{"type":"rect","page":1,"x":0.1,"y":0.3,"w":0.3,"h":0.05,"color":"#ffff00","opacity":0.4}]'
      responses:
        '200':
          description: PDF в теле ответа
          content:
            application/pdf: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '413': { $ref: '#/components/responses/TooManyPages' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/pdf/to-pdfa:
    post:
      tags: [pdf]
      summary: PDF → PDF/A
      description: Формат долговременного хранения.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'Один PDF, до 50 МБ; несколько файлов в поле file — 400' }
                level: { type: string, enum: ['1b', '2b', '3b'], default: '2b' }
      responses:
        '200':
          description: PDF/A в теле ответа
          content:
            application/pdf: { schema: { type: string, format: binary } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/ocr/image:
    post:
      tags: [ocr]
      summary: Распознать текст с изображения (синхронно)
      description: >
        Одно изображение или PDF ≤10 МБ — ответ сразу. Для больших/многостраничных файлов см. `/v1/ocr/document`.
        Формат определяется по содержимому: не PNG/JPEG/WEBP/PDF, пустой файл или несколько файлов в поле
        file — 400; повреждённый или защищённый паролем PDF — 422. Без поворота (`auto_rotate`)
        текст на изображении, повёрнутом на 90/180/270°, не распознаётся или распознаётся с ошибками.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'PNG, JPEG, WEBP или PDF, до 10 МБ; один файл' }
                auto_rotate: { type: boolean, default: false, description: "'true' — повернуть страницу, снятую под 90/180/270°, перед распознаванием (для фото и сканов; на скриншотах может ошибаться). Координаты box тогда даются для повёрнутой страницы. По умолчанию false; другие значения — 400" }
      responses:
        '200':
          description: Распознанный текст
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OcrImageResult' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/ocr/document:
    post:
      tags: [ocr]
      summary: Распознать текст в документе (асинхронно)
      description: >
        Многостраничный PDF или файл больше 10 МБ (один файл) — асинхронно: сразу
        возвращается `job_id`, результат забирается через `GET /v1/jobs/{id}`. Лимит 50 МБ.
        Те же форматы и проверки, что у `/v1/ocr/image`: не PNG/JPEG/WEBP/PDF, пустой файл или
        несколько файлов — 400; повреждённый или защищённый PDF — 422.
        Квота списывается только при успешном завершении задачи, не при постановке в очередь.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file]
              properties:
                file: { type: string, format: binary, description: 'PDF или изображение (PNG, JPEG, WEBP), до 50 МБ; один файл' }
                auto_rotate: { type: boolean, default: false, description: "'true' — повернуть страницу, снятую под 90/180/270°, перед распознаванием (для фото и сканов; на скриншотах может ошибаться). Координаты box тогда даются для повёрнутой страницы. По умолчанию false; другие значения — 400" }
      responses:
        '202':
          description: Задача поставлена в очередь
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OcrJobAccepted' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '502': { $ref: '#/components/responses/EngineError' }

  /v1/jobs/{id}:
    get:
      tags: [jobs]
      summary: Статус и результат асинхронной OCR-задачи
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      responses:
        '200':
          description: Статус задачи (queued/processing/done/failed)
          content:
            application/json:
              schema: { $ref: '#/components/schemas/OcrJob' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404':
          description: Задача не найдена или принадлежит другому аккаунту
          content:
            application/json: { schema: { $ref: '#/components/schemas/Error' } }

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: 'API-ключ из личного кабинета, в заголовке `Authorization: Bearer <ключ>`'

  schemas:
    EditOp:
      description: Элемент для /v1/pdf/edit; поля, не относящиеся к type, игнорируются.
      oneOf:
        - $ref: '#/components/schemas/EditOpText'
        - $ref: '#/components/schemas/EditOpImage'
        - $ref: '#/components/schemas/EditOpRect'
      discriminator: { propertyName: type }
    EditOpBase:
      type: object
      required: [type, page]
      properties:
        page: { type: integer, minimum: 1, description: 'Номер страницы с 1; за пределами документа — 400' }
        x: { type: number, default: 0, description: 'Левый край, доля ширины страницы 0–1 (вне диапазона приводится к границе)' }
        y: { type: number, default: 0, description: 'Верхний край, доля высоты страницы 0–1 от верха (вне диапазона приводится к границе)' }
        opacity: { type: number, default: 1, description: 'Непрозрачность 0.05–1; 0 или отсутствие — 1' }
    EditOpText:
      allOf:
        - $ref: '#/components/schemas/EditOpBase'
        - type: object
          required: [text]
          properties:
            type: { type: string, const: text }
            text: { type: string, minLength: 1, maxLength: 200, description: 'Непустой текст, латиница и кириллица' }
            size: { type: number, minimum: 4, maximum: 200, default: 4, description: 'Кегль в пунктах; дробное значение округляется до целого, вне 4–200 приводится к границе' }
            bold: { type: boolean, default: false }
            color: { type: string, pattern: '^#[0-9a-fA-F]{6}$', default: '#000000' }
    EditOpImage:
      allOf:
        - $ref: '#/components/schemas/EditOpBase'
        - type: object
          required: [image]
          properties:
            type: { type: string, const: image }
            image: { type: string, contentEncoding: base64, description: 'PNG или JPEG в base64 (можно data:image/png;base64,…), до 8 МБ после декодирования' }
            w: { type: number, description: 'Ширина, доля ширины страницы 0.005–1 (вне диапазона и без значения — приводится к границе, задавайте явно); высота следует из пропорций картинки' }
    EditOpRect:
      allOf:
        - $ref: '#/components/schemas/EditOpBase'
        - type: object
          properties:
            type: { type: string, const: rect }
            w: { type: number, description: 'Ширина, доля страницы 0.005–1' }
            h: { type: number, description: 'Высота, доля страницы 0.002–1' }
            color: { type: string, pattern: '^#[0-9a-fA-F]{6}$', default: '#ffff00' }
    ConvertOptions:
      type: object
      properties:
        format: { type: string, enum: [A4, Letter, Legal], default: A4 }
        margin: { type: string, example: 16mm }
        landscape: { type: boolean, default: false }

    ConvertHtmlRequest:
      type: object
      required: [html]
      properties:
        html: { type: string, description: 'HTML-разметка страницы' }
        options: { $ref: '#/components/schemas/ConvertOptions' }
        deliver:
          type: string
          enum: [inline, url]
          default: inline
          description: 'inline — PDF в теле ответа; url — ссылка на S3 (если настроен бэкенд)'

    ConvertUrlRequest:
      type: object
      required: [url]
      properties:
        url: { type: string, format: uri }
        options: { $ref: '#/components/schemas/ConvertOptions' }
        deliver: { type: string, enum: [inline, url], default: inline }

    DeliverUrlResponse:
      type: object
      properties:
        url: { type: string, format: uri }
        expires_in: { type: string, example: 1h }

    OcrBox:
      type: array
      items: { type: number }
      minItems: 4
      maxItems: 4
      description: '[xMin, yMin, xMax, yMax] в пикселях исходного изображения'

    OcrLine:
      type: object
      properties:
        text: { type: string }
        score: { type: number, format: float }
        box: { $ref: '#/components/schemas/OcrBox' }

    OcrImageResult:
      type: object
      properties:
        text: { type: string, description: 'Строки, соединённые переводом строки' }
        lines:
          type: array
          description: 'Пустой массив, если текста не найдено (не null)'
          items: { $ref: '#/components/schemas/OcrLine' }

    OcrJobAccepted:
      type: object
      properties:
        job_id: { type: string }
        status: { type: string, enum: [queued] }

    OcrPage:
      type: object
      properties:
        page: { type: integer }
        text: { type: string }
        lines:
          type: array
          items: { $ref: '#/components/schemas/OcrLine' }

    OcrJob:
      type: object
      properties:
        id: { type: string }
        status: { type: string, enum: [queued, processing, done, failed] }
        result:
          type: object
          properties:
            pages:
              type: array
              items: { $ref: '#/components/schemas/OcrPage' }
        error: { type: string, description: 'Присутствует только при status=failed' }

    Error:
      type: object
      properties:
        error: { type: string }

  responses:
    PdfOrUrl:
      description: 'PDF в теле ответа (`deliver: inline`, по умолчанию) или JSON-ссылка (`deliver: url`)'
      content:
        application/pdf: { schema: { type: string, format: binary } }
        application/json: { schema: { $ref: '#/components/schemas/DeliverUrlResponse' } }
    BadRequest:
      description: Некорректный запрос — в том числе файл больше 50 МБ («Файл слишком большой (максимум 50 МБ)»), не PDF или параметры вне диапазона
      content:
        application/json: { schema: { $ref: '#/components/schemas/Error' } }
    Unauthorized:
      description: Неверный или отсутствующий API-ключ
      content:
        application/json: { schema: { $ref: '#/components/schemas/Error' } }
    RateLimited:
      description: Превышен rate limit (5 req/s, burst 20) или месячная квота
      headers:
        X-RateLimit-Limit: { schema: { type: integer } }
        X-RateLimit-Remaining: { schema: { type: integer } }
      content:
        application/json: { schema: { $ref: '#/components/schemas/Error' } }
    Unprocessable:
      description: PDF защищён паролем или повреждён (или, для split, запрошена страница за пределами документа)
      content:
        application/json: { schema: { $ref: '#/components/schemas/Error' } }
    TooManyPages:
      description: В PDF слишком много страниц — больше 100 для конвертации (to-word/png/jpg/html/text), больше 500 для правок
      content:
        application/json: { schema: { $ref: '#/components/schemas/Error' } }
    EngineError:
      description: Сбой на стороне движка рендеринга/распознавания
      content:
        application/json: { schema: { $ref: '#/components/schemas/Error' } }
