|
| 1 | +""" |
| 2 | +LLM-First Chart Extraction using Pixtral Vision. |
| 3 | +
|
| 4 | +Direct image → JSON extraction without complex CV pipeline. |
| 5 | +""" |
| 6 | + |
| 7 | +import os |
| 8 | +import base64 |
| 9 | +import json |
| 10 | +import re |
| 11 | +from typing import Dict, Any, List, Optional, Tuple |
| 12 | +import cv2 |
| 13 | +import numpy as np |
| 14 | + |
| 15 | +try: |
| 16 | + from mistralai import Mistral |
| 17 | + MISTRAL_AVAILABLE = True |
| 18 | +except ImportError: |
| 19 | + MISTRAL_AVAILABLE = False |
| 20 | + |
| 21 | + |
| 22 | +def encode_image_base64(image: np.ndarray) -> str: |
| 23 | + """Encode OpenCV image to base64 data URL.""" |
| 24 | + success, buffer = cv2.imencode('.png', image) |
| 25 | + if not success: |
| 26 | + raise ValueError("Failed to encode image to PNG") |
| 27 | + return f"data:image/png;base64,{base64.b64encode(buffer).decode('utf-8')}" |
| 28 | + |
| 29 | + |
| 30 | +def extract_chart_llm( |
| 31 | + image_path: str, |
| 32 | + model: str = "pixtral-12b-2409" |
| 33 | +) -> Tuple[Dict[str, Any], float]: |
| 34 | + """ |
| 35 | + Extract chart data using LLM vision in a single API call. |
| 36 | + |
| 37 | + Args: |
| 38 | + image_path: Path to chart image |
| 39 | + model: Mistral vision model to use |
| 40 | + |
| 41 | + Returns: |
| 42 | + Tuple of (result_dict, confidence) |
| 43 | + result_dict: { |
| 44 | + "chart_type": str, |
| 45 | + "x_label": str, |
| 46 | + "y_label": str, |
| 47 | + "data": [{"x": float, "y": float}, ...] |
| 48 | + } |
| 49 | + """ |
| 50 | + api_key = os.environ.get("MISTRAL_API_KEY") |
| 51 | + if not api_key: |
| 52 | + raise ValueError("MISTRAL_API_KEY not set") |
| 53 | + |
| 54 | + if not MISTRAL_AVAILABLE: |
| 55 | + raise ImportError("mistralai package not installed") |
| 56 | + |
| 57 | + # Load and encode image |
| 58 | + image = cv2.imread(image_path) |
| 59 | + if image is None: |
| 60 | + raise ValueError(f"Could not load image: {image_path}") |
| 61 | + |
| 62 | + image_b64 = encode_image_base64(image) |
| 63 | + |
| 64 | + # Create Mistral client |
| 65 | + client = Mistral(api_key=api_key) |
| 66 | + |
| 67 | + # Craft extraction prompt |
| 68 | + prompt = """Analyze this chart image and extract ALL data points. |
| 69 | +
|
| 70 | +IMPORTANT INSTRUCTIONS: |
| 71 | +1. Read the axis labels and scale carefully |
| 72 | +2. For each visible data point (dot, bar, or line vertex), estimate its X and Y values |
| 73 | +3. Use the actual axis values, not pixel positions |
| 74 | +4. Be precise - read tick marks and interpolate between them |
| 75 | +
|
| 76 | +Return ONLY valid JSON in this exact format: |
| 77 | +{ |
| 78 | + "chart_type": "line" or "bar" or "scatter", |
| 79 | + "x_label": "label from X axis or empty string", |
| 80 | + "y_label": "label from Y axis or empty string", |
| 81 | + "x_min": minimum X axis value, |
| 82 | + "x_max": maximum X axis value, |
| 83 | + "y_min": minimum Y axis value, |
| 84 | + "y_max": maximum Y axis value, |
| 85 | + "data": [ |
| 86 | + {"x": 0, "y": 10}, |
| 87 | + {"x": 1, "y": 20}, |
| 88 | + ... |
| 89 | + ] |
| 90 | +} |
| 91 | +
|
| 92 | +Extract ALL visible data points. Do not skip any.""" |
| 93 | + |
| 94 | + try: |
| 95 | + response = client.chat.complete( |
| 96 | + model=model, |
| 97 | + messages=[ |
| 98 | + { |
| 99 | + "role": "user", |
| 100 | + "content": [ |
| 101 | + {"type": "text", "text": prompt}, |
| 102 | + {"type": "image_url", "image_url": image_b64} |
| 103 | + ] |
| 104 | + } |
| 105 | + ], |
| 106 | + max_tokens=4096, |
| 107 | + temperature=0.1 # Low temperature for precision |
| 108 | + ) |
| 109 | + |
| 110 | + content = response.choices[0].message.content.strip() |
| 111 | + |
| 112 | + # Parse JSON from response (handle markdown code blocks) |
| 113 | + content = content.replace("```json", "").replace("```", "").strip() |
| 114 | + |
| 115 | + # Try to extract JSON object |
| 116 | + json_match = re.search(r'\{.*\}', content, re.DOTALL) |
| 117 | + if json_match: |
| 118 | + content = json_match.group() |
| 119 | + |
| 120 | + result = json.loads(content) |
| 121 | + |
| 122 | + # Validate required fields |
| 123 | + if "data" not in result or not isinstance(result["data"], list): |
| 124 | + return {"error": "No data extracted", "raw": content}, 0.0 |
| 125 | + |
| 126 | + # Calculate confidence based on data quality |
| 127 | + data_points = len(result.get("data", [])) |
| 128 | + has_labels = bool(result.get("x_label") or result.get("y_label")) |
| 129 | + has_range = all(k in result for k in ["x_min", "x_max", "y_min", "y_max"]) |
| 130 | + |
| 131 | + confidence = 0.5 |
| 132 | + if data_points > 0: |
| 133 | + confidence += 0.2 |
| 134 | + if data_points > 5: |
| 135 | + confidence += 0.1 |
| 136 | + if has_labels: |
| 137 | + confidence += 0.1 |
| 138 | + if has_range: |
| 139 | + confidence += 0.1 |
| 140 | + |
| 141 | + confidence = min(confidence, 1.0) |
| 142 | + |
| 143 | + return result, confidence |
| 144 | + |
| 145 | + except json.JSONDecodeError as e: |
| 146 | + return {"error": f"JSON parse error: {e}", "raw": content}, 0.0 |
| 147 | + except Exception as e: |
| 148 | + return {"error": str(e)}, 0.0 |
| 149 | + |
| 150 | + |
| 151 | +def llm_result_to_array(result: Dict[str, Any]) -> np.ndarray: |
| 152 | + """Convert LLM extraction result to Nx2 numpy array.""" |
| 153 | + data = result.get("data", []) |
| 154 | + if not data: |
| 155 | + return np.array([]).reshape(0, 2) |
| 156 | + |
| 157 | + points = [] |
| 158 | + for point in data: |
| 159 | + try: |
| 160 | + x = float(point.get("x", 0)) |
| 161 | + y = float(point.get("y", 0)) |
| 162 | + points.append([x, y]) |
| 163 | + except (TypeError, ValueError): |
| 164 | + continue |
| 165 | + |
| 166 | + return np.array(points) if points else np.array([]).reshape(0, 2) |
| 167 | + |
| 168 | + |
| 169 | +def llm_result_to_csv(result: Dict[str, Any]) -> str: |
| 170 | + """Convert LLM extraction result to CSV string.""" |
| 171 | + data = result.get("data", []) |
| 172 | + |
| 173 | + x_label = result.get("x_label", "x") or "x" |
| 174 | + y_label = result.get("y_label", "y") or "y" |
| 175 | + |
| 176 | + lines = [f"{x_label},{y_label}"] |
| 177 | + |
| 178 | + for point in data: |
| 179 | + try: |
| 180 | + x = point.get("x", "") |
| 181 | + y = point.get("y", "") |
| 182 | + lines.append(f"{x},{y}") |
| 183 | + except: |
| 184 | + continue |
| 185 | + |
| 186 | + return "\n".join(lines) |
0 commit comments