AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Configuring Qwen-VL on Alibaba Cloud Bailian for Complex Financial Tables and Dense Diagram Extraction: An Engineering Guide

Kyle Muscato · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Extracting reliable structured records from complex financial reports, multi-column balance sheets, nested procurement orders, and dense engineering diagrams remains a major bottleneck in enterprise data pipelines. Traditional optical character recognition (OCR) and layout-analysis engines typically process documents line by line. When faced with merged cells, borderless grids, multi-page breaks, or vector charts, conventional OCR collapses: text across columns gets scrambled, table hierarchies disappear, and diagram semantics are lost.

Alibaba Cloud Model Studio (Bailian) exposes Tongyi Qianwen's flagship vision-language models—specifically Qwen-VL-Max and Qwen-VL-Plus—through an OpenAI-compatible API and the native DashScope SDK. These multimodal models integrate spatial perception with visual reasoning, allowing backend engineers to bypass fragile geometric heuristics and extract structured JSON directly from document images.

At 365Finds, our testing across commercial invoice databases and corporate SEC/HKEX filings reveals a clear operating rule: for financial statement extraction and visual auditability, prioritize Qwen-VL-Max with strict JSON formatting and normalized bounding box anchoring. While Qwen-VL-Plus is faster and more cost-effective for uniform documents, Qwen-VL-Max provides superior disambiguation for nested headers, multi-currency annotations, and split-page continuation rows.

This guide walks through configuring the Bailian multimodal API, formatting image inputs, crafting structured prompts with spatial coordinate constraints, and building a resilient multi-page stitching pipeline.


Technical Architecture & Ingestion Standards

Building a production-grade extraction pipeline with Qwen-VL requires standardizing how documents are rendered, encoded, and passed to the model.

+--------------------------------------------------------------------------------+
|                         Production Extraction Pipeline                          |
+--------------------------------------------------------------------------------+
  [ Multi-Page PDF / Scans ]
              |
              v  (PyMuPDF / pdf2image @ 200-300 DPI)
  [ High-Resolution Page Images ]
              |
              +---> [ Page Classification & Windowing ]
              |          |
              |          +--> Single / Two-Page Burst
              |          +--> Rolling Multi-Page Accumulator
              v
  [ Base64 Data URI or OSS Signed URL ]
              |
              v
  [ Bailian MultiModal API (Qwen-VL-Max) ]
    - Structured Prompt (Cell schema, Merged span, [ymin, xmin, ymax, xmax])
    - response_format: {"type": "json_object"}
              |
              v
  [ JSON Deserializer & Backoff Retry ]
              |
              v
  [ Coordinate Remapping & Financial Balance Hook ]
              |
              v
  [ Normalized Audit-Ready Database / ERP ]

1. Image Resolution and DPI Sweet Spot

Do not pass raw full-resolution 600 DPI scans without resizing, nor downscaled thumbnails below 150 DPI.

2. Payload Transport: Base64 vs. Public URL

The Bailian API supports two input modes:


Configuring the API Client and Environment

You can access Bailian multimodal models using either the official dashscope library or the standard openai Python SDK. We recommend the openai client because it provides unified connection pooling, standard timeout handling, and drop-in compatibility with existing LLM orchestration layers.

pip install openai pillow pymupdf pydantic

Set your API key obtained from Alibaba Cloud Model Studio:

export DASHSCOPE_API_KEY="sk-your-bailian-api-key"

The standard Beijing region endpoint is https://dashscope.aliyuncs.com/compatible-mode/v1. If your Model Studio workspace is hosted in Singapore or other international regions, use https://dashscope-intl.aliyuncs.com/compatible-mode/v1.


Extracting Complex Tables with Spatial Bounding Boxes

To verify financial data and allow human reviewers to audit extracted numbers, your pipeline must capture spatial grounding coordinates for every line item and cell.

Qwen-VL models use normalized integer coordinates on a [0, 1000] scale, where [0, 0] represents the top-left corner and [1000, 1000] corresponds to the bottom-right corner. We instruct the model to return coordinates as [ymin, xmin, ymax, xmax], mapping directly to standard computer vision crop boundaries.

Python Implementation: Structured Financial Table Extraction

import os
import io
import json
import base64
from typing import Dict, Any, List
from openai import OpenAI
from PIL import Image

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

def encode_pil_image_to_base64(image: Image.Image) -> str:
    """Encode PIL Image to standard Base64 Data URI."""
    buffer = io.BytesIO()
    image.save(buffer, format="PNG")
    b64_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
    return f"data:image/png;base64,{b64_str}"

def extract_financial_table(image_input: str) -> Dict[str, Any]:
    """
    Parses complex financial tables with merged cells and spatial coordinates.
    image_input can be a public URL or a data:image/png;base64,... URI.
    """
    system_instruction = (
        "You are an expert financial document parser. Extract all tables from the image "
        "into a valid, well-structured JSON object. Follow these strict rules:\n"
        "1. Identify multi-level and hierarchical headers.\n"
        "2. Record cell values accurately, preserving currency symbols, minus signs, and parenthetical values.\n"
        "3. Handle merged cells explicitly using 'rowspan' and 'colspan' properties.\n"
        "4. Provide the spatial bounding box for each row and key financial cells in normalized coordinates "
        "[ymin, xmin, ymax, xmax] scaled between 0 and 1000.\n"
        "5. Return pure JSON without conversational commentary or markdown fencing."
    )

    user_prompt = (
        "Analyze the attached financial statement page. Return a JSON object matching this schema:\n"
        "{\n"
        '  "statement_name": "string",\n'
        '  "reported_currency": "string",\n'
        '  "scale_unit": "string",\n'
        '  "tables": [\n'
        "    {\n"
        '      "table_index": 0,\n'
        '      "bounding_box": [ymin, xmin, ymax, xmax],\n'
        '      "columns": ["Col A", "Col B", ...],\n'
        '      "rows": [\n'
        "        {\n"
        '          "row_type": "header | data | subtotal | total",\n'
        '          "line_item": "string",\n'
        '          "row_bounding_box": [ymin, xmin, ymax, xmax],\n'
        '          "cells": [\n'
        '            {"col_index": 0, "value": "text", "numeric_val": float_or_null, "box_2d": [ymin, xmin, ymax, xmax]}\n'
        "          ]\n"
        "        }\n"
        "      ]\n"
        "    }\n"
        "  ]\n"
        "}"
    )

    response = client.chat.completions.create(
        model="qwen-vl-max",
        messages=[
            {"role": "system", "content": system_instruction},
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_input}},
                    {"type": "text", "text": user_prompt},
                ],
            },
        ],
        response_format={"type": "json_object"},
        temperature=0.01,  # Lowest temperature for deterministic financial output
    )

    raw_content = response.choices[0].message.content
    return json.loads(raw_content)

def convert_normalized_box_to_pixels(box: List[int], img_width: int, img_height: int) -> Dict[str, int]:
    """
    Converts [ymin, xmin, ymax, xmax] (0-1000) to absolute pixel bounding box.
    """
    ymin, xmin, ymax, xmax = box
    return {
        "top": int((ymin / 1000.0) * img_height),
        "left": int((xmin / 1000.0) * img_width),
        "bottom": int((ymax / 1000.0) * img_height),
        "right": int((xmax / 1000.0) * img_width),
    }

Why Spatial Grounding Matters in Production

When a downstream ERP flags a reconciliation discrepancy—such as Total Operating Expenses failing to match the sum of detailed sub-accounts—having normalized coordinates allows the user interface to instantly crop and display the exact source box on the original scan. This turns a slow, manual reconciliation process into a five-second human verification step.


Parsing Dense Diagram Images and Engineering Charts

Financial reports, investor decks, and industrial assets often present numerical metrics in bar charts, breakdown donuts, and trendlines rather than plain grids. Traditional OCR reads loose axis numbers as disconnected floating words.

Qwen-VL-Max solves this by pairing visual chart understanding with trend deconstruction.

def extract_chart_data(image_input: str) -> Dict[str, Any]:
    """Extracts data series, axes, and underlying metrics from visual diagrams."""
    chart_prompt = (
        "Extract the structured numerical data from the charts/diagrams in this image. "
        "Return a JSON object structured as follows:\n"
        "{\n"
        '  "charts": [\n'
        "    {\n"
        '      "chart_type": "bar | line | pie | area | waterfall",\n'
        '      "title": "string",\n'
        '      "x_axis_title": "string",\n'
        '      "y_axis_title": "string",\n'
        '      "unit": "string",\n'
        '      "series": [\n'
        "        {\n"
        '          "name": "string",\n'
        '          "data_points": [{"label": "string", "value": float, "box_2d": [ymin, xmin, ymax, xmax]}]\n'
        "        }\n"
        "      ],\n"
        '      "trend_summary": "Concise factual statement of trajectory and key inflection points."\n'
        "    }\n"
        "  ]\n"
        "}"
    )

    response = client.chat.completions.create(
        model="qwen-vl-max",
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_input}},
                    {"type": "text", "text": chart_prompt},
                ],
            }
        ],
        response_format={"type": "json_object"},
        temperature=0.01,
    )
    return json.loads(response.choices[0].message.content)

Multi-Page Table Stitching Pipeline

A persistent headache in automated parsing is the multi-page financial statement: a single consolidated balance sheet or inventory ledger that begins on page 24, runs through page 26, repeats headers on intermediate pages, and only displays totals at the end of page 26.

There are two primary stitching strategies:

StrategyApplicable ScenarioMechanicsPros & Cons
Burst Multi-Image RequestShort splits (2 to 3 contiguous pages)Pass images sequentially in one API message arrayModel sees boundary transitions directly; risk of token truncation if document contains hundreds of rows
Stateful Rolling AccumulatorLong ledgers (4+ pages or heavy audit schedules)Extract page 1, pass established schema and partial state into page 2 promptHighly reliable, deterministic memory; requires orchestrating state logic in Python

Production Implementation: Multi-Page Stitcher

The following code demonstrates a resilient stitching routine that renders consecutive PDF pages, passes them together to Qwen-VL-Max, and removes repetitive headers across page cuts.

import fitz  # PyMuPDF
from typing import List

def render_pdf_range_to_data_urls(pdf_path: str, page_numbers: List[int], dpi: int = 220) -> List[str]:
    """Renders specific 1-indexed pages of a PDF to Base64 data URLs."""
    doc = fitz.open(pdf_path)
    urls = []
    zoom = dpi / 72.0
    mat = fitz.Matrix(zoom, zoom)

    for p_num in page_numbers:
        page = doc.load_page(p_num - 1)
        pix = page.get_pixmap(matrix=mat)
        img_bytes = pix.tobytes("png")
        b64 = base64.b64encode(img_bytes).decode("utf-8")
        urls.append(f"data:image/png;base64,{b64}")
    doc.close()
    return urls

def stitch_multipage_financial_table(pdf_path: str, target_pages: List[int]) -> Dict[str, Any]:
    """
    Submits consecutive pages to Qwen-VL-Max to merge broken table segments
    into one coherent dataset without duplicate headers.
    """
    image_urls = render_pdf_range_to_data_urls(pdf_path, target_pages)

    # Build multimodal content payload with images in strict sequence
    content_payload = []
    for idx, url in enumerate(image_urls, start=1):
        content_payload.append({"type": "image_url", "image_url": {"url": url}})

    stitching_instruction = (
        f"The {len(image_urls)} attached images represent sequential pages of a continuous financial statement. "
        "Perform structural table stitching with these requirements:\n"
        "1. Identify the master table schema established on the first page.\n"
        "2. Strip out repeated column header rows on subsequent pages.\n"
        "3. If a line item description is split across page boundaries, merge the text into a single coherent entry.\n"
        "4. Maintain running sequential row indices.\n"
        "5. Consolidate everything into a single JSON response with a top-level 'stitched_table' object.\n"
        "Output format:\n"
        '{"statement_title": "string", "currency": "string", "columns": [...], "rows": [{"index": int, "line_item": "string", "values": [...]}]}'
    )
    content_payload.append({"type": "text", "text": stitching_instruction})

    response = client.chat.completions.create(
        model="qwen-vl-max",
        messages=[{"role": "user", "content": content_payload}],
        response_format={"type": "json_object"},
        temperature=0.01,
    )

    return json.loads(response.choices[0].message.content)

Production Resilience: Fallbacks, Retries, and Validation Hooks

Production visual pipelines encounter three recurring operational issues: HTTP 429 rate limits, partial JSON cutoffs caused by token caps, and internal arithmetic inconsistencies.

1. Robust Retry with Exponential Backoff

Alibaba Cloud Bailian enforces concurrency limits depending on your tier. Wrap API calls with standard exponential backoff:

import time
import random
from openai import APIError, RateLimitError

def robust_qwen_call(messages: List[Dict[str, Any]], max_retries: int = 5) -> Dict[str, Any]:
    delay = 2.0
    for attempt in range(max_retries):
        try:
            response = client.chat.completions.create(
                model="qwen-vl-max",
                messages=messages,
                response_format={"type": "json_object"},
                temperature=0.01,
            )
            return json.loads(response.choices[0].message.content)
        except (RateLimitError, APIError) as e:
            if attempt == max_retries - 1:
                raise e
            sleep_duration = delay * (2 ** attempt) + random.uniform(0.1, 1.0)
            time.sleep(sleep_duration)
        except json.JSONDecodeError:
            # Fallback for minor formatting hiccups
            if attempt == max_retries - 1:
                raise ValueError("Model failed to emit parseable JSON after retries.")
            time.sleep(delay)

2. Post-Extraction Financial Validation Hooks

A foundational practice in 365Finds engineering pipelines is attaching automated mathematical sanity checks to model outputs. For example, in an extracted Balance Sheet:

$$\text{Total Assets} \stackrel{?}{=} \text{Total Liabilities} + \text{Total Equity}$$

If the extracted numbers deviate beyond a defined tolerance threshold ($\Delta > 0.01$), the system flags the record for localized cropping. Rather than re-running the entire document, the pipeline cuts the specific bounding box region and submits it as an isolated zoom-in prompt to re-evaluate blurred digits.


Model Selection Trade-offs: Qwen-VL-Max vs. Qwen-VL-Plus

Selecting between Bailian’s vision models depends on document density and accuracy tolerances:

Evaluation DimensionQwen-VL-MaxQwen-VL-Plus
Best Used ForSEC/HKEX filings; dense schematics; borderless financial tablesStandard shipping invoices; utility bills; clean digital receipts
Merged Cell FidelityHigh; accurately reconstructs multi-tier header relationshipsMedium; occasional row-drift when grid lines are omitted
Diagram UnderstandingStrong; extracts trends, dual-axes, and numeric data seriesBasic; identifies chart presence and broad categories
Grounding PrecisionPrecise normalized box boundariesGeneral area bounding; slight padding around text runs
Latency & CostHigher latency; premium token pricingLow latency; approximately 30-50% lower cost per request

365Finds Institutional Verdict

For back-office automation in financial services, asset management, and accounting workflows, we recommend deploying Qwen-VL-Max as your baseline model. The incremental API cost is negligible compared to the downstream manual labor required to clean corrupted financial tables. Reserve Qwen-VL-Plus for pre-filtering steps, document classification, or processing standard forms with fixed tabular layouts.


References