### Clone and install mpxpy in development mode Source: https://github.com/mathpix/mpxpy/blob/master/README.md Commands to clone the repository and install it in development mode using pip. Includes alternative installation via requirements.txt. ```bash # Clone the repository git clone git@github.com:Mathpix/mpxpy.git cd mpxpy # Install in development mode pip install -e . # Or install using the requirements.txt file pip install -r requirements.txt ``` -------------------------------- ### Auth usage example Source: https://github.com/mathpix/mpxpy Example of creating an Auth instance and printing its headers. Resolves credentials from MATHPIX_APP_ID and MATHPIX_APP_KEY environment variables. ```python from mpxpy.auth import Auth auth = Auth() # resolves from MATHPIX_APP_ID / MATHPIX_APP_KEY env print(auth.headers) # {'app_id': ..., 'app_key': ..., 'User-Agent': 'mpxpy/x.y.z'} ``` -------------------------------- ### Install mpxpy with pip Source: https://github.com/mathpix/mpxpy/blob/master/README.md Install the mpxpy package using pip. Run this command in your terminal to install the client library. ```bash pip install mpxpy ``` -------------------------------- ### Install test dependencies and run tests Source: https://github.com/mathpix/mpxpy/blob/master/README.md Commands to install test dependencies and run the test suite with pytest. Requires authentication to be configured. ```bash # Install test dependencies pip install -e ".[dev]" # Or install using the requirements.txt file pip install -r requirements.txt # Run tests pytest ``` -------------------------------- ### Dotenv config file example Source: https://github.com/mathpix/mpxpy Example of a dotenv config file with KEY=VALUE lines. Loaded by Auth.load_config() / MathpixClient() in order: ~/.mpx/config, .env, local.env. First found wins. ```dotenv MATHPIX_APP_ID=your-app-id MATHPIX_APP_KEY=your-app-key MATHPIX_URL=https://api.mathpix.com ``` -------------------------------- ### Example: get with error handling Source: https://github.com/mathpix/mpxpy Shows how to use get from mpxpy.request_handler with try/except for MathpixClientError. Non-2xx status codes are not raised by make_request; callers must call raise_for_status() or inspect resp.ok. ```python from mpxpy.request_handler import get, post from mpxpy.errors import MathpixClientError try: resp = get("https://example.com", headers={"x": "1"}) resp.raise_for_status() except MathpixClientError as e: print("transport failure:", e) ``` -------------------------------- ### wait_for_format usage example Source: https://github.com/mathpix/mpxpy Example of calling wait_for_format for the 'docx' format with a timeout of 90 seconds. ```python file.wait_for_format("docx", timeout=90) ``` -------------------------------- ### wait_until_complete usage example Source: https://github.com/mathpix/mpxpy Example of calling wait_until_complete with a timeout of 120 seconds and printing error details if not done. ```python done = file.wait_until_complete(timeout=120) if not done: print(file.error, file.error_info) ``` -------------------------------- ### File constructor usage example Source: https://github.com/mathpix/mpxpy Shows how to create a File instance via MathpixClient or by seeding with cached status to avoid an extra request. ```python from mpxpy import MathpixClient, File client = MathpixClient() file = client.file_get("00000000-0000-0000-0000-000000000001") # or seed with cached status: file = File(auth=client.auth, file_id="...", status_result={"status": "pending"}) ``` -------------------------------- ### MathpixClient constructor with request_options and extra_options Source: https://github.com/mathpix/mpxpy Example of creating a MathpixClient with request_options (timeout, verify) and passing extra_options to image_new. extra_options are merged into the request body last; reserved keys are rejected with ValidationError. ```python client = MathpixClient( app_id="...", app_key="...", request_options={"timeout": 30, "verify": False}, ) client.image_new(url="https://example.com/i.jpg", extra_options={"custom_opt": True}) ``` -------------------------------- ### MathpixClient.app_token_get Source: https://github.com/mathpix/mpxpy/blob/master/README.md Gets information about an app token. ```APIDOC ## MathpixClient.app_token_get ### Description Gets information about an app token. ### Method N/A (SDK method) ### Endpoint N/A ### Parameters #### Arguments - **app_token** (string) - Required - The app token to query. ### Request Example N/A ### Response #### Success Response Returns information about the app token. #### Response Example N/A ``` -------------------------------- ### GET /files/v1/onboarding/identities Source: https://github.com/mathpix/mpxpy Retrieves onboarding identities for cloud providers. ```APIDOC ## GET /files/v1/onboarding/identities ### Description Retrieves onboarding identities for cloud providers. ### Method GET ### Endpoint /files/v1/onboarding/identities ### Response #### Success Response - **aws** (object) - AWS identity. - **azure** (object) - Azure identity. - **gcp** (object) - GCP identity. ``` -------------------------------- ### Batch usage example Source: https://github.com/mathpix/mpxpy Creates a batch with two images, waits for completion, and prints each result. Uses MathpixClient.batch_new and the Batch methods. ```python from mpxpy import MathpixClient client = MathpixClient() batch = client.batch_new( urls={ "imgA": "https://example.com/a.jpg", "imgB": {"url": "https://example.com/b.jpg", "formats": ["html"]}, }, ocr_behavior="text", ) if batch.wait_until_complete(timeout=180): for key in batch.keys(): result = batch.results().get(key) print(key, result.get("text") if result else None) ``` -------------------------------- ### wait_until_complete usage example Source: https://github.com/mathpix/mpxpy Creates an async image and waits up to 120 seconds for completion, then prints the Mathpix Markdown result. ```python img = client.image_new(url="https://example.com/in.jpg", is_async=True) if img.wait_until_complete(timeout=120): print(img.mmd()) ``` -------------------------------- ### image_new usage example Source: https://github.com/mathpix/mpxpy Shows how to call image_new with a local file and rm_spaces=True, then convert the result to MathML using mmd(). ```python img = client.image_new(file_path="calc.png", rm_spaces=True) img.mmd() ``` -------------------------------- ### file_get method signature Source: https://github.com/mathpix/mpxpy Gets a file by ID via GET {files_api_url}/files/v1/{file_id}. Returns a File seeded with current status (one request). Raises FilesApiError ('not_found', 'forbidden'). ```python def file_get(self, file_id: str) -> File: ``` -------------------------------- ### Example: configure_logging usage Source: https://github.com/mathpix/mpxpy Shows explicit level configuration and env var alternative. MathpixClient.__init__ calls configure_logging() automatically, so the logger is configured by default when constructing a client. ```python import logging from mpxpy import MathpixClient from mpxpy.logger import configure_logging, logger configure_logging(logging.DEBUG) # explicit level logger.debug("my debug message") # or via env var: MATHPIX_LOG_LEVEL=DEBUG client = MathpixClient() # configures the logger as a side effect ``` -------------------------------- ### Example: create, wait, page through files Source: https://github.com/mathpix/mpxpy Shows the full workflow: create a batch, wait for completion, then page through all files using the cursor. Requires a non-production API URL. ```python from mpxpy import MathpixClient client = MathpixClient(api_url="http://localhost:8080") # non-production runtime batch = client.file_batch_new() batch.wait_until_complete(timeout=600) page = batch.files() while True: for pdf in page.files: print(pdf.pdf_id) if not page.has_more: break page = batch.files(cursor=page.cursor) ``` -------------------------------- ### mmd and html usage example Source: https://github.com/mathpix/mpxpy Creates an image from a local file with text and html formats, then prints both the Mathpix Markdown and HTML representations. ```python img = client.image_new(file_path="eq.png", formats=["text", "html"]) print(img.mmd()) print(img.html()) ``` -------------------------------- ### file_new usage example Source: https://github.com/mathpix/mpxpy Submits a document from an S3 URI for async processing, requesting DOCX conversion. Requires a client instance and a registered data source for the destination. ```python f = client.file_new(source_uri="s3://my-bucket/doc.pdf", conversion_formats={"docx": True}) ``` -------------------------------- ### MathpixClient instantiation example Source: https://github.com/mathpix/mpxpy Creates a MathpixClient with explicit app ID and key, disabling SSL verification via request_options. Prints the resolved API URL from the internal Auth instance. ```python from mpxpy import MathpixClient client = MathpixClient( app_id="your-app-id", app_key="your-app-key", request_options={"verify": False}, # disable SSL verification ) print(client.auth.api_url) ``` -------------------------------- ### Example: post with JSON body Source: https://github.com/mathpix/mpxpy Typical post usage with JSON bodies. Checks resp.ok and raises error_from_response(resp) if not ok. ```python resp = post("https://example.com/v3/text", json={"src": "..."}, headers=headers) if not resp.ok: raise error_from_response(resp) ``` -------------------------------- ### ScsFile usage example Source: https://github.com/mathpix/mpxpy Creates a legacy ScsFile via MathpixClient.scs_file_new, waits for completion, and prints the markdown text result. ```python from mpxpy import MathpixClient client = MathpixClient() legacy = client.scs_file_new(url="https://example.com/doc.pdf", conversion_formats={"md": True}) if legacy.wait_until_complete(timeout=120): print(legacy.to_md_text()) ``` -------------------------------- ### GET /files/v1/{file_id}.{format} Source: https://github.com/mathpix/mpxpy Downloads a file in the specified format. Returns 404 if the format is not ready, and 415 if the format is unsupported. ```APIDOC ## GET /files/v1/{file_id}.{format} ### Description Downloads a file in the specified format. Returns 404 if the format is not ready, and 415 if the format is unsupported. ### Method GET ### Endpoint /files/v1/{file_id}.{format} ### Parameters #### Path Parameters - **file_id** (string) - Required - The ID of the file. - **format** (string) - Required - The desired file format. ### Response #### Success Response - **result** (binary) - The file content. #### Error Responses - **404** - `format_not_ready` - The format is not ready. - **415** - `unsupported_format` - The format is unsupported. ``` -------------------------------- ### Initialize MathpixClient using environment variables Source: https://github.com/mathpix/mpxpy/blob/master/README.md Create a MathpixClient instance that automatically reads credentials from ~/.mpx/config or environment variables. No arguments are needed when using this method. ```python from mpxpy.mathpix_client import MathpixClient # Will use ~/.mpx/config or environment variables client = MathpixClient() ``` -------------------------------- ### webhook_config_get method signature and usage Source: https://github.com/mathpix/mpxpy Gets webhook configuration via GET {files_api_url}/files/v1/webhook-config. Mints the signing secret on first call. Returns a WebhookConfig. The example shows retrieving the signing secret. ```python def webhook_config_get(self) -> WebhookConfig: ``` ```python secret = client.webhook_config_get().signing_secret ``` -------------------------------- ### file_by_custom_id method signature and usage example Source: https://github.com/mathpix/mpxpy Performs GET {files_api_url}/files/v1/jobs/{job_id}/files/{custom_id}. Returns a File seeded with status. Available only when the submission had an explicit job_id and per-item custom_id. Raises ValidationError if custom_id empty; FilesApiError ('not_found') for unknown pair. The example retrieves a file with custom_id 'doc-1'. ```python def file_by_custom_id(self, custom_id: str) -> File: ``` ```python f = job.file_by_custom_id("doc-1") ``` -------------------------------- ### Initialize MathpixClient with explicit app credentials Source: https://github.com/mathpix/mpxpy/blob/master/README.md Pass app_id and app_key directly to the constructor. The optional api_url argument sets the base URL, useful for on-premise deployments. ```python from mpxpy.mathpix_client import MathpixClient client = MathpixClient( app_id="your-app-id", app_key="your-app-key" # Optional "api_url" argument sets the base URL. This can be useful for development with on-premise deployments ) ``` -------------------------------- ### pdf_delete usage example Source: https://github.com/mathpix/mpxpy Example call to delete a PDF with ID 'pdf-id-123'. ```python client.pdf_delete("pdf-id-123") ``` -------------------------------- ### Handling ConversionIncompleteError with text_result Source: https://github.com/mathpix/mpxpy Shows how to call `text_result` and catch `ConversionIncompleteError` when the conversion is not yet ready. The example prints "still converting" in that case. ```python try: md = file.text_result("md") except ConversionIncompleteError: print("still converting") ``` -------------------------------- ### Register and verify a cloud data source Source: https://github.com/mathpix/mpxpy/blob/master/README.md Fetches onboarding identities before creating grants, then creates an AWS data source with IAM role authentication and tests it. The probe result includes read/write checks. ```python identities = client.onboarding_identities() # fetch BEFORE creating grants external_id = identities["aws"]["external_id"] # goes in your IAM trust policy data_source = client.data_source_new( provider="aws", bucket="your-bucket", auth_method="iam_role", provider_specific_details={ "iam_role_arn": "arn:aws:iam::123456789012:role/MathpixReader", "aws_external_id": external_id, }, region="us-east-1", ) probe = data_source.test() # {'result': 'ok', 'checks': {'read': True, 'write': True}, ...} ``` -------------------------------- ### Module-level constants Source: https://github.com/mathpix/mpxpy MPXPY_VERSION is set to the installed package version, or 'unknown' if not installed. USER_AGENT is a string combining 'mpxpy/' with the version. ```python MPXPY_VERSION: str = version("mpxpy") # 'unknown' if the package is not installed USER_AGENT: str = f"mpxpy/{MPXPY_VERSION}" ``` -------------------------------- ### Set Mathpix credentials in environment config Source: https://github.com/mathpix/mpxpy/blob/master/README.md Create a config file at ~/.mpx/config or add these environment variables to .env or local.env files. MATHPIX_URL is optional and defaults to https://api.mathpix.com. ```bash MATHPIX_APP_ID=your-app-id MATHPIX_APP_KEY=your-app-key MATHPIX_URL=https://api.mathpix.com # optional, defaults to this value ``` -------------------------------- ### GET /files/v1/scs-jobs/status Source: https://github.com/mathpix/mpxpy Deprecated legacy endpoint to get the status of a specific SCS job. Requires the `scs_job_id` query parameter. ```APIDOC ## GET /files/v1/scs-jobs/status ### Description Deprecated legacy endpoint to get the status of a specific SCS job. Requires the `scs_job_id` query parameter. ### Method GET ### Endpoint /files/v1/scs-jobs/status ### Parameters #### Query Parameters - **scs_job_id** (string) - Required - The SCS job ID ### Notes - Deprecated - Client method: `scs_job_status` ``` -------------------------------- ### Convert MMD to multiple formats with MathpixClient Source: https://github.com/mathpix/mpxpy/blob/master/README.md Creates a MathpixClient with app credentials, submits a new conversion for an MMD string, waits for completion, and retrieves outputs in Markdown, DOCX, MMD ZIP, and PPTX formats. The conversion class takes separate arguments for each conversion format. Output files are written to the specified paths, and text/bytes accessors return the content directly. ```python from mpxpy.mathpix_client import MathpixClient client = MathpixClient( app_id="your-app-id", app_key="your-app-key" ) # Similar to Pdf, Conversion class takes separate arguments for each conversion format conversion = client.conversion_new( mmd="\\frac{1}{2} + \\sqrt{3}", convert_to_docx=True, convert_to_md=True, convert_to_mmd_zip=True, convert_to_pptx=True, ) # Wait for conversion to complete conversion.wait_until_complete(timeout=30) # Get the Markdown outputs md_output_path = conversion.to_md_file(path='output/sample.md') md_text = conversion.to_md_text() # is of type str # Get the DOCX outputs docx_output_path = conversion.to_docx_file(path='output/sample.docx') docx_bytes = conversion.to_docx_bytes() # is of type bytes # Get the Mathpix Markdown ZIP outputs (includes embedded images) mmd_zip_output_path = conversion.to_mmd_zip_file(path='output/sample.mmd.zip') mmd_zip_bytes = conversion.to_mmd_zip_bytes() # is of type bytes # Get the PowerPoint outputs pptx_output_path = conversion.to_pptx_file(path='output/sample.pptx') pptx_bytes = conversion.to_pptx_bytes() # is of type bytes ``` -------------------------------- ### MathpixClient Constructor Source: https://github.com/mathpix/mpxpy/blob/master/README.md Creates a new MathpixClient instance with authentication credentials and optional configuration. ```APIDOC ## MathpixClient Constructor ### Description Initializes a MathpixClient with the provided application ID, key, and optional settings. ### Method Constructor ### Endpoint N/A ### Parameters #### Constructor Arguments - **app_id** (string) - Optional - Mathpix application ID. If None, uses environment variable. - **app_key** (string) - Optional - Mathpix application key. If None, uses environment variable. - **api_url** (string) - Optional - Mathpix API URL. If None, uses environment variable or default production API. - **improve_mathpix** (boolean) - Optional - Enable Mathpix to retain user output. Default is true. - **request_options** (dict) - Optional - Keyword arguments to pass to the requests library. Default is None. ### Request Example ```python client = MathpixClient( app_id="your-app-id", app_key="your-app-key" ) ``` ### Response #### Success Response (200) - **client** (MathpixClient) - The initialized client instance. #### Response Example ```python client = MathpixClient( app_id="your-app-id", app_key="your-app-key" ) ``` ``` -------------------------------- ### file_job_get method signature Source: https://github.com/mathpix/mpxpy Gets a file job by ID via GET {files_api_url}/files/v1/jobs/{job_id}. Returns a FileJob with file_count populated. Raises FilesApiError ('not_found'). ```python def file_job_get(self, job_id: str) -> FileJob: ``` -------------------------------- ### files_iter method signature and usage example Source: https://github.com/mathpix/mpxpy Generator yielding one file entry per iteration, following next_page_token pagination automatically. The example iterates over errored files and prints each file_id. ```python def files_iter( self, status: Optional[str] = None, limit: Optional[int] = None, ) -> Iterator[Dict[str, Any]]: ``` ```python for entry in job.files_iter(status="error"): print(entry["file_id"]) ``` -------------------------------- ### onboarding_identities Source: https://github.com/mathpix/mpxpy Retrieves cloud provider identities for onboarding. Returns AWS, Azure, and GCP account details. ```APIDOC ## GET {files_api_url}/files/v1/onboarding/identities ### Description Returns `{'aws': {'trust_account_id', 'external_id'}, 'azure': {'app_id', 'tenant_id'}, 'gcp': {...}}`. Call before cloud-side grants. ### Method GET ### Endpoint `{files_api_url}/files/v1/onboarding/identities` ### Response #### Success Response (200) - **aws** (object) - Contains `trust_account_id` and `external_id`. - **azure** (object) - Contains `app_id` and `tenant_id`. - **gcp** (object) - Contains GCP-specific details. ``` -------------------------------- ### GET /files/v1/data-sources Source: https://github.com/mathpix/mpxpy Lists all data sources. ```APIDOC ## GET /files/v1/data-sources ### Description Lists all data sources. ### Method GET ### Endpoint /files/v1/data-sources ### Response #### Success Response - **data_sources** (array) - List of data sources. ``` -------------------------------- ### Using convenience format methods Source: https://github.com/mathpix/mpxpy Illustrates using the convenience methods: `wait_until_complete()` ensures the conversion is done, `to_mmd_file` saves to a file, and `to_docx_bytes` returns bytes. These methods call the underlying helpers with a fixed `conversion_format`. ```python file.wait_until_complete() file.to_mmd_file("cv.mmd") docx_bytes = file.to_docx_bytes() ``` -------------------------------- ### GET /files/v1/{file_id} Source: https://github.com/mathpix/mpxpy Retrieves the status of a file. ```APIDOC ## GET /files/v1/{file_id} ### Description Retrieves the status of a file. ### Method GET ### Endpoint /files/v1/{file_id} ### Parameters #### Path Parameters - **file_id** (string) - Required - The ID of the file. ### Response #### Success Response - **status** (object) - The status body (see types.md). ``` -------------------------------- ### GET /files/v1/jobs/{job_id} Source: https://github.com/mathpix/mpxpy Retrieves the status of a file job. ```APIDOC ## GET /files/v1/jobs/{job_id} ### Description Retrieves the status of a file job. ### Method GET ### Endpoint /files/v1/jobs/{job_id} ### Parameters #### Path Parameters - **job_id** (string) - Required - The ID of the job. ### Response #### Success Response - **job_status** (object) - The job status. ``` -------------------------------- ### Handle PDF upload and conversion errors with MathpixClient Source: https://github.com/mathpix/mpxpy/blob/master/README.md Shows how to use MathpixClient to upload a PDF and convert it to DOCX, catching FileNotFoundError, MathpixClientError, and ConversionIncompleteError. Requires valid app_id and app_key. ```python from mpxpy.mathpix_client import MathpixClient from mpxpy.errors import MathpixClientError, ConversionIncompleteError client = MathpixClient(app_id="your-app-id", app_key="your-app-key") try: pdf = client.pdf_new(file_path="example.pdf", convert_to_docx=True) except FileNotFoundError as e: print(f"File not found: {e}") except MathpixClientError as e: print(f"File upload error: {e}") try: pdf.to_docx_file('output/path/example.pdf') except ConversionIncompleteError as e: print(f'Conversions are not complete') ``` -------------------------------- ### Process PDF with MathpixClient Source: https://github.com/mathpix/mpxpy/blob/master/README.md Creates a MathpixClient, submits a PDF for processing with multiple conversion formats (docx, md, pptx, md_zip), waits for completion, and retrieves outputs as files or text/bytes. The timeout argument is optional and defaults to 60 seconds; improve_mathpix is optional and defaults to True. ```python from mpxpy.mathpix_client import MathpixClient client = MathpixClient( app_id="your-app-id", app_key="your-app-key" ) # Process a PDF file with multiple conversion formats and options pdf = client.pdf_new( file_path='/path/to/pdf/sample.pdf', convert_to_docx=True, convert_to_md=True, convert_to_pptx=True, convert_to_md_zip=True, # Optional pdf-level improve_mathpix argument is default True ) # Wait for processing to complete. Optional timeout argument is 60 seconds by default. pdf.wait_until_complete(timeout=30) # Get the Markdown outputs md_output_path = pdf.to_md_file(path='output/sample.md') md_text = pdf.to_md_text() # is type str print(md_text) # Get the DOCX outputs docx_output_path = pdf.to_docx_file(path='output/sample.docx') docx_bytes = pdf.to_docx_bytes() # is type bytes # Get the PowerPoint outputs pptx_output_path = pdf.to_pptx_file(path='output/sample.pptx') pptx_bytes = pdf.to_pptx_bytes() # is type bytes # Get the Markdown ZIP outputs (includes embedded images) md_zip_output_path = pdf.to_md_zip_file(path='output/sample.md.zip') md_zip_bytes = pdf.to_md_zip_bytes() # is type bytes # Get the JSON outputs lines_json_output_path = pdf.to_lines_json_file(path='output/sample.lines.json') lines_json = pdf.to_lines_json() # parses JSON into type Dict ``` -------------------------------- ### finalize method signature and usage example Source: https://github.com/mathpix/mpxpy Performs POST {files_api_url}/files/v1/jobs/{job_id}/finalize. Marks the batch complete so the terminal 'job.completed' webhook can fire. Idempotent (keeps original finalized_at). Returns {'job_id', 'finalized_at', 'message'}. Raises FilesApiError ('not_found'). The example calls finalize() on a job. ```python def finalize(self) -> Dict[str, Any]: ``` ```python job.finalize() ``` -------------------------------- ### GET /files/v1/jobs Source: https://github.com/mathpix/mpxpy Lists file jobs with optional filters and pagination. ```APIDOC ## GET /files/v1/jobs ### Description Lists file jobs with optional filters and pagination. ### Method GET ### Endpoint /files/v1/jobs ### Parameters #### Query Parameters - **start** (string) - Optional - Start date/time filter. - **end** (string) - Optional - End date/time filter. - **limit** (integer) - Optional - Maximum number of jobs to return. - **paging_state** (string) - Optional - Pagination token. ### Response #### Success Response - **jobs** (array) - List of jobs. - **next_page_token** (string) - Token for the next page. ``` -------------------------------- ### file_job_new usage example Source: https://github.com/mathpix/mpxpy Shows how to submit a single file job with a source_uri and request DOCX conversion, then wait for completion with a 300-second timeout. The job is created with accept-and-defer semantics, so wait_until_complete polls until the job finishes. ```python job = client.file_job_new(files=[{"source_uri": "s3://b/1.pdf"}], conversion_formats={"docx": True}) job.wait_until_complete(timeout=300) ``` -------------------------------- ### GET /v3/app-tokens/{app_token} Source: https://github.com/mathpix/mpxpy Retrieves information about an existing application token. ```APIDOC ## GET /v3/app-tokens/{app_token} ### Description Retrieves information about an existing application token. ### Method GET ### Endpoint /v3/app-tokens/{app_token} ### Parameters #### Path Parameters - **app_token** (string) - Required - The application token ### Response #### Success Response (200) - **app_token** (string) - The token - **app_token_expires_at** (string) - Expiration timestamp - **strokes_session_id** (string) - Optional - Strokes session ID ``` -------------------------------- ### MathpixClient.pdf_new Source: https://github.com/mathpix/mpxpy/blob/master/README.md Creates a new Pdf instance for processing a PDF file, either from a local path or a remote URL, with various optional parameters for OCR and output formatting. ```APIDOC ## MathpixClient.pdf_new ### Description Creates a new Pdf instance for processing a PDF file. Accepts either a local file path or a remote URL, along with optional parameters for OCR settings, output formats, and webhook callbacks. ### Method N/A (SDK method) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file_path** (string) - Optional - Path to a local PDF file. - **url** (string) - Optional - URL of a remote PDF file. - **metadata** (dict) - Optional - Dict to attach metadata to a request. - **alphabets_allowed** (dict) - Optional - Dict to list alphabets allowed in the output (see AlphabetsAllowed Object). - **rm_spaces** (boolean) - Optional - Whether extra white space is removed from equations in "latex_styled" and "text" formats. - **rm_fonts** (boolean) - Optional - Whether font commands such as \mathbf and \mathrm are removed from equations in "latex_styled" and "text" formats. - **idiomatic_eqn_arrays** (boolean) - Optional - Whether to use aligned, gathered, or cases instead of an array environment for a list of equations. - **include_equation_tags** (boolean) - Optional - Whether to include equation number tags inside equations LaTeX. When True, sets "idiomatic_eqn_arrays": True. - **include_smiles** (boolean) - Optional - Enable experimental chemistry diagram OCR via RDKIT normalized SMILES. - **include_chemistry_as_image** (boolean) - Optional - Return an image crop containing SMILES in the alt-text for chemical diagrams. - **include_diagram_text** (boolean) - Optional - Enable text extraction from diagrams (for use with "include_line_data": True). - **numbers_default_to_math** (boolean) - Optional - Whether numbers are always math. - **math_inline_delimiters** (array) - Optional - [str, str] tuple to specify begin inline math and end inline math delimiters for "text" outputs. - **math_display_delimiters** (array) - Optional - [str, str] tuple to specify begin display math and end display math delimiters for "text" outputs. - **page_ranges** (string) - Optional - Specifies a page range as a comma-separated string (e.g., "2,4-6"). - **enable_spell_check** (boolean) - Optional - Enable a predictive mode for English handwriting. - **auto_number_sections** (boolean) - Optional - Defaults to False. - **remove_section_numbering** (boolean) - Optional - Whether to remove existing numbering for sections and subsections. Defaults to false. - **preserve_section_numbering** (boolean) - Optional - Whether to keep existing section numbering as is. Defaults to true. - **enable_tables_fallback** (boolean) - Optional - Enable an advanced table processing algorithm that supports very large and complex tables. - **fullwidth_punctuation** (boolean) - Optional - Whether punctuation will be fullwidth Unicode. - **convert_to_docx** (boolean) - Optional - Automatically convert your result to docx. - **convert_to_md** (boolean) - Optional - Automatically convert your result to md. - **convert_to_mmd** (boolean) - Optional - Automatically convert your result to mmd. - **convert_to_tex_zip** (boolean) - Optional - Automatically convert your result to tex.zip. - **convert_to_html** (boolean) - Optional - Automatically convert your result to html. - **convert_to_pdf** (boolean) - Optional - Automatically convert your result to pdf. - **convert_to_md_zip** (boolean) - Optional - Automatically convert your result to md.zip. - **convert_to_mmd_zip** (boolean) - Optional - Automatically convert your result to mmd.zip. - **convert_to_pptx** (boolean) - Optional - Automatically convert your result to pptx. - **convert_to_html_zip** (boolean) - Optional - Automatically convert your result to html.zip. - **improve_mathpix** (boolean) - Optional - Enable Mathpix to retain user output. Default is true. - **file_batch_id** (string) - Optional - Batch ID to associate this file with. - **callback_url** (string) - Optional - HTTPS URL to notify on completion. - **callback_headers** (dict) - Optional - Headers sent on callback delivery (e.g., auth token). - **callback_events** (array) - Optional - Events to deliver, defaulting to ['file.completed', 'file.error'] for one document, with [] turning deliveries off. ### Request Example { "file_path": "/path/to/file.pdf", "url": "https://example.com/file.pdf", "metadata": {}, "alphabets_allowed": {}, "rm_spaces": true, "rm_fonts": false, "idiomatic_eqn_arrays": true, "include_equation_tags": false, "include_smiles": false, "include_chemistry_as_image": false, "include_diagram_text": false, "numbers_default_to_math": false, "math_inline_delimiters": ["$", "$"], "math_display_delimiters": ["$$", "$$"] } ### Response #### Success Response (200) - **pdf** (Pdf) - A new Pdf instance. #### Response Example { "pdf": "" } ### Error Handling No error handling is documented for this method. ``` -------------------------------- ### GET /v3/batch/{batch_id} Source: https://github.com/mathpix/mpxpy Retrieves the status and results of a batch processing job. ```APIDOC ## GET /v3/batch/{batch_id} ### Description Retrieves the status and results of a batch processing job. ### Method GET ### Endpoint /v3/batch/{batch_id} ### Parameters #### Path Parameters - **batch_id** (string) - Required - The batch identifier ### Response #### Success Response (200) - **keys** (array) - List of keys - **callback** (string) - Callback URL - **results** (object) - Batch results ``` -------------------------------- ### ScsFile error handling example Source: https://github.com/mathpix/mpxpy Catches ConversionIncompleteError when the conversion is not yet available. ```python try: legacy.to_md_text() except ConversionIncompleteError as e: print("not yet available:", e) ``` -------------------------------- ### GET /v3/converter-results Source: https://github.com/mathpix/mpxpy Query converter results. Supports filtering by dates and application ID. ```APIDOC ## GET /v3/converter-results ### Description Query converter results. Supports filtering by dates and application ID. ### Method GET ### Endpoint /v3/converter-results ### Parameters #### Query Parameters - **from_date** (string) - Optional - Start date for filtering - **to_date** (string) - Optional - End date for filtering - **app_id** (string) - Optional - Filter by application ID - **page** (integer) - Optional - Page number for pagination - **per_page** (integer) - Optional - Number of results per page ### Response #### Success Response (200) - **documents** (array) - List of converter results ### Notes - Client method: `query_converter_results` - Params are sent as URL query string - Raises `MathpixClientError` on transport failure ``` -------------------------------- ### GET /files/v1/webhook-config Source: https://github.com/mathpix/mpxpy Retrieves the webhook configuration. On first call, it mints a signing secret. ```APIDOC ## GET /files/v1/webhook-config ### Description Retrieves the webhook configuration. On first call, it mints a signing secret. ### Method GET ### Endpoint /files/v1/webhook-config ### Response #### Success Response - **signing_secret** (string) - The signing secret. ``` -------------------------------- ### Pdf.__init__ Source: https://github.com/mathpix/mpxpy Constructor for the Pdf class. Initializes a PDF conversion with authentication and optional conversion format flags. Raises ValidationError if auth is missing or pdf_id is empty. ```APIDOC ## Pdf.__init__ ### Description Constructor for the Pdf class. Initializes a PDF conversion with authentication and optional conversion format flags. Raises ValidationError if auth is missing or pdf_id is empty. ### Method Constructor ### Signature ```python def __init__( self, auth: Auth, pdf_id: str = None, file_path: Optional[str] = None, url: Optional[str] = None, convert_to_docx: Optional[bool] = False, convert_to_md: Optional[bool] = False, convert_to_mmd: Optional[bool] = False, convert_to_tex_zip: Optional[bool] = False, convert_to_html: Optional[bool] = False, convert_to_pdf: Optional[bool] = False, convert_to_md_zip: Optional[bool] = False, convert_to_mmd_zip: Optional[bool] = False, convert_to_pptx: Optional[bool] = False, convert_to_html_zip: Optional[bool] = False, convert_to_xlsx: Optional[bool] = False, convert_to_mmd_overlay_pdf: Optional[bool] = False, improve_mathpix: Optional[bool] = False, file_batch_id: Optional[str] = None, callback_url: Optional[str] = None, callback_headers: Optional[Dict[str, str]] = None, callback_events: Optional[List[str]] = None, request_options: Optional[Dict[str, Any]] = None, ): ``` ### Parameters - **auth** (Auth) - Required - Authentication object. - **pdf_id** (str) - Optional - PDF ID. - **file_path** (Optional[str]) - Optional - Path to the PDF file. - **url** (Optional[str]) - Optional - URL of the PDF. - **convert_to_docx** (Optional[bool]) - Optional - Request DOCX conversion. - **convert_to_md** (Optional[bool]) - Optional - Request Markdown conversion. - **convert_to_mmd** (Optional[bool]) - Optional - Request MMD conversion. - **convert_to_tex_zip** (Optional[bool]) - Optional - Request TeX zip conversion. - **convert_to_html** (Optional[bool]) - Optional - Request HTML conversion. - **convert_to_pdf** (Optional[bool]) - Optional - Request PDF conversion. - **convert_to_md_zip** (Optional[bool]) - Optional - Request Markdown zip conversion. - **convert_to_mmd_zip** (Optional[bool]) - Optional - Request MMD zip conversion. - **convert_to_pptx** (Optional[bool]) - Optional - Request PPTX conversion. - **convert_to_html_zip** (Optional[bool]) - Optional - Request HTML zip conversion. - **convert_to_xlsx** (Optional[bool]) - Optional - Request XLSX conversion. - **convert_to_mmd_overlay_pdf** (Optional[bool]) - Optional - Request MMD overlay PDF conversion. - **improve_mathpix** (Optional[bool]) - Optional - Improve Mathpix processing. - **file_batch_id** (Optional[str]) - Optional - File batch ID. - **callback_url** (Optional[str]) - Optional - Callback URL. - **callback_headers** (Optional[Dict[str, str]]) - Optional - Callback headers. - **callback_events** (Optional[List[str]]) - Optional - Callback events. - **request_options** (Optional[Dict[str, Any]]) - Optional - Additional request options. ### Errors - **ValidationError** - Raised if auth is missing or pdf_id is empty. ``` -------------------------------- ### Send test webhook delivery with MathpixClient.webhook_config_test Source: https://github.com/mathpix/mpxpy/blob/master/README.md Sends one signed test delivery to a callback URL and returns the outcome synchronously. The sample body is a file.completed payload with reserved diagnostic file_id 00000000-0000-0000-0000-000000000000. One attempt, no retries; up to 10 test deliveries per minute. A refused endpoint returns status 'failed' with response_code and detail; only request-level failures raise. ```python outcome = client.webhook_config_test( callback_url="https://your-app.example.com/mathpix-webhook", callback_headers={"Authorization": "Bearer your-token"}, # optional ) # {'status': 'delivered', 'response_code': 200, 'detail': None} ``` -------------------------------- ### GET /v3/file-batches/{file_batch_id} Source: https://github.com/mathpix/mpxpy Retrieves the status of a file batch and checks if it is still processing. ```APIDOC ## GET /v3/file-batches/{file_batch_id} ### Description Retrieves the status of a file batch and checks if it is still processing. ### Method GET ### Endpoint /v3/file-batches/{file_batch_id} ### Parameters #### Path Parameters - **file_batch_id** (string) - Required - The ID of the file batch. ### Response #### Success Response - **file_batch_status** (string) - The status of the file batch. - **file_batch_is_processing** (boolean) - Whether the file batch is still processing. ``` -------------------------------- ### GET /v3/converter/{conversion_id} Source: https://github.com/mathpix/mpxpy Returns the conversion status of a conversion job identified by its conversion_id. ```APIDOC ## GET /v3/converter/{conversion_id} ### Description Returns the conversion status of a conversion job identified by its conversion_id. ### Method GET ### Endpoint /v3/converter/{conversion_id} ### Parameters #### Path Parameters - **conversion_id** (string) - Required - The ID of the conversion job. ### Response #### Success Response (200) Returns conversion status JSON. ``` -------------------------------- ### pdf_new usage example Source: https://github.com/mathpix/mpxpy Shows a minimal call to pdf_new that uploads a local PDF and requests Markdown conversion. The method returns a Pdf object. Throws NotImplementedError if file_batch_id is set with the production API URL, ValidationError for invalid sources or extra_options conflicts, FileNotFoundError for missing local files, and MathpixClientError on API request failure. ```python pdf = client.pdf_new(file_path="paper.pdf", convert_to_md=True) ``` -------------------------------- ### Handle ConversionIncompleteError Source: https://github.com/mathpix/mpxpy Attempts to get markdown text and prints a message if the conversion is incomplete. ```python try: md = conv.to_md_text() except ConversionIncompleteError: print("conversion incomplete") ``` -------------------------------- ### Submit single document and download result Source: https://github.com/mathpix/mpxpy/blob/master/README.md Creates a MathpixClient, submits a PDF from a public HTTPS URL, waits up to 120 seconds for completion, then retrieves the markdown text and saves the docx file. Use when processing a single document asynchronously. ```python from mpxpy.mathpix_client import MathpixClient client = MathpixClient() file = client.file_new( source_uri="https://cdn.mathpix.com/examples/cs229-notes1.pdf", conversion_formats={"docx": True, "md": True}, ) file.wait_until_complete(timeout=120) markdown = file.to_md_text() file.to_docx_file("output.docx") ``` -------------------------------- ### wait_until_complete method signature and usage example Source: https://github.com/mathpix/mpxpy Polls until status 'completed' or deadline. interval is seconds between polls (default 5.0). Per-file failures do not fail the job. Returns bool. Raises ValidationError if timeout is not a positive non-zero integer or interval <= 0. The example shows polling with a 600-second timeout and 10-second interval, then printing errored files. ```python def wait_until_complete(self, timeout: int, interval: float = 5.0) -> bool: ``` ```python if job.wait_until_complete(timeout=600, interval=10): for f in job.files(status="error")["files"]: print(f) ``` -------------------------------- ### GET /files/v1/jobs/{job_id}/files Source: https://github.com/mathpix/mpxpy Lists the files in a job with optional status filter and pagination. ```APIDOC ## GET /files/v1/jobs/{job_id}/files ### Description Lists the files in a job with optional status filter and pagination. ### Method GET ### Endpoint /files/v1/jobs/{job_id}/files ### Parameters #### Path Parameters - **job_id** (string) - Required - The ID of the job. #### Query Parameters - **status** (string) - Optional - Filter by file status. - **limit** (integer) - Optional - Maximum number of files to return. - **paging_state** (string) - Optional - Pagination token. ### Response #### Success Response - **files** (array) - List of files. - **next_page_token** (string) - Token for the next page. ``` -------------------------------- ### MathpixClient.batch_new Source: https://github.com/mathpix/mpxpy/blob/master/README.md Submits multiple images for batch processing and returns a Batch instance. ```APIDOC ## MathpixClient.batch_new ### Description Submits multiple images for batch processing and returns a Batch instance. ### Method N/A (SDK method) ### Endpoint N/A ### Parameters #### Arguments - **urls** (dict) - Required - Dict mapping keys to image sources. Values can be string URLs, data URLs, or objects with per-item options. - **ocr_behavior** (string) - Optional - Processing mode: "latex" (default) or "text". - **callback** (object) - Optional - Callback configuration for async notification. - **metadata** (dict) - Optional - Metadata dict to attach to the request. - **formats** (list) - Optional - List of output formats (applies to all items unless overridden). - **data_options** (dict) - Optional - DataOptions dict for text mode. - **include_detected_alphabets** (boolean) - Optional - Return detected alphabets in results. - **alphabets_allowed** (dict) - Optional - Dict specifying allowed alphabets. - **confidence_threshold** (number) - Optional - File-level confidence threshold (0-1). - **confidence_rate_threshold** (number) - Optional - Symbol-level confidence threshold (0-1). ### Request Example N/A ### Response #### Success Response Returns a Batch instance. #### Response Example N/A ``` -------------------------------- ### GET /v3/pdf/{pdf_id} Source: https://github.com/mathpix/mpxpy Returns the processing status of a PDF conversion job identified by its pdf_id. ```APIDOC ## GET /v3/pdf/{pdf_id} ### Description Returns the processing status of a PDF conversion job identified by its pdf_id. ### Method GET ### Endpoint /v3/pdf/{pdf_id} ### Parameters #### Path Parameters - **pdf_id** (string) - Required - The ID of the PDF conversion job. ### Response #### Success Response (200) Returns processing status JSON. ```