File size: 8,967 Bytes
0191ae7
 
 
 
 
 
 
 
 
22ced1b
0191ae7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22ced1b
0191ae7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22ced1b
 
0191ae7
22ced1b
 
0191ae7
22ced1b
0191ae7
22ced1b
 
 
0191ae7
 
22ced1b
 
 
0191ae7
 
22ced1b
 
 
 
0191ae7
 
22ced1b
 
 
 
 
 
0191ae7
 
22ced1b
 
 
 
 
 
 
 
0191ae7
 
22ced1b
 
 
 
 
 
 
 
 
 
0191ae7
 
22ced1b
 
 
 
 
 
 
 
 
 
 
0191ae7
 
22ced1b
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
"""
ai_interpretation.py
--------------------
AI-powered chart interpretation using OpenAI GPT-5.2 vision with
Pydantic structured output.

Provides:
    - Pydantic models for structured chart analysis results
    - Vision-based chart interpretation via OpenAI's GPT-5.2 model
    - Markdown rendering of interpretation results (framework-agnostic)
"""

from __future__ import annotations

import base64
import json
import os
from typing import Literal

import openai
from pydantic import BaseModel, ConfigDict


# ---------------------------------------------------------------------------
# Pydantic models
# ---------------------------------------------------------------------------

class TrendInfo(BaseModel):
    """Describes the overall trend detected in the chart."""

    model_config = ConfigDict(extra="forbid")

    direction: Literal["upward", "downward", "flat", "mixed"]
    description: str


class SeasonalityInfo(BaseModel):
    """Describes any seasonality detected in the chart."""

    model_config = ConfigDict(extra="forbid")

    detected: bool
    period: str | None
    description: str


class StationarityInfo(BaseModel):
    """Describes whether the series appears stationary."""

    model_config = ConfigDict(extra="forbid")

    likely_stationary: bool
    description: str


class AnomalyItem(BaseModel):
    """A single anomaly or outlier observation."""

    model_config = ConfigDict(extra="forbid")

    approximate_location: str
    description: str
    severity: Literal["low", "medium", "high"]


class ChartInterpretation(BaseModel):
    """Complete structured interpretation of a time-series chart."""

    model_config = ConfigDict(extra="forbid")

    chart_type_detected: str
    trend: TrendInfo
    seasonality: SeasonalityInfo
    stationarity: StationarityInfo
    anomalies: list[AnomalyItem]
    key_observations: list[str]
    summary: str
    recommendations: list[str]


# ---------------------------------------------------------------------------
# API key check
# ---------------------------------------------------------------------------

def check_api_key_available() -> bool:
    """Return ``True`` if the ``OPENAI_API_KEY`` environment variable is set
    and non-empty."""
    key = os.environ.get("OPENAI_API_KEY", "")
    return bool(key.strip())


# ---------------------------------------------------------------------------
# Chart interpretation
# ---------------------------------------------------------------------------

_SYSTEM_PROMPT = (
    "You are a careful time-series analyst helping business analytics "
    "students. Analyze the chart image and provide a structured "
    "interpretation. Be precise about what the data shows; flag anything "
    "noteworthy. Use plain language suitable for students."
)


def interpret_chart(
    png_bytes: bytes,
    metadata: dict,
) -> ChartInterpretation:
    """Send a chart image to GPT-5.2 vision and return a structured
    interpretation.

    Parameters
    ----------
    png_bytes:
        Raw PNG image bytes of the chart to analyse.
    metadata:
        Context about the chart.  Expected keys:

        * ``chart_type`` -- e.g. ``"line"``, ``"bar"``, ``"decomposition"``
        * ``frequency_label`` -- e.g. ``"Monthly"``, ``"Daily"``
        * ``date_range`` -- human-readable date range string
        * ``y_column`` -- name of the value column being plotted
    """
    try:
        client = openai.OpenAI()

        # Encode the PNG as a base64 data URI
        b64 = base64.b64encode(png_bytes).decode("utf-8")
        image_data_uri = f"data:image/png;base64,{b64}"

        chart_type = metadata.get("chart_type", "time-series")
        metadata_str = json.dumps(metadata, default=str)

        response = client.beta.chat.completions.parse(
            model="gpt-5.2-2025-12-11",
            response_format=ChartInterpretation,
            messages=[
                {"role": "system", "content": _SYSTEM_PROMPT},
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image_url",
                            "image_url": {"url": image_data_uri},
                        },
                        {
                            "type": "text",
                            "text": (
                                f"Analyze this {chart_type} chart. "
                                f"Metadata: {metadata_str}"
                            ),
                        },
                    ],
                },
            ],
        )

        # Prefer the parsed structured output
        parsed = response.choices[0].message.parsed
        if parsed is not None:
            return parsed

        # Fallback: try to manually parse the raw content
        raw_content = response.choices[0].message.content or ""
        data = json.loads(raw_content)
        return ChartInterpretation(**data)

    except Exception as exc:  # noqa: BLE001
        # Return a minimal interpretation that surfaces the error
        return ChartInterpretation(
            chart_type_detected="unknown",
            trend=TrendInfo(direction="mixed", description="Unable to determine."),
            seasonality=SeasonalityInfo(
                detected=False, period=None, description="Unable to determine."
            ),
            stationarity=StationarityInfo(
                likely_stationary=False, description="Unable to determine."
            ),
            anomalies=[],
            key_observations=["AI interpretation failed; see summary for details."],
            summary=f"Error during AI interpretation: {exc}",
            recommendations=["Check that your OPENAI_API_KEY is set and valid."],
        )


# ---------------------------------------------------------------------------
# Markdown rendering (framework-agnostic)
# ---------------------------------------------------------------------------

_DIRECTION_EMOJI = {
    "upward": "\u2197\ufe0f",    # arrow upper-right
    "downward": "\u2198\ufe0f",  # arrow lower-right
    "flat": "\u27a1\ufe0f",      # arrow right
    "mixed": "\u2194\ufe0f",     # left-right arrow
}

_SEVERITY_COLOR = {
    "low": "green",
    "medium": "orange",
    "high": "red",
}


def render_interpretation_markdown(interp: ChartInterpretation) -> str:
    """Render a :class:`ChartInterpretation` as a Markdown string.

    Returns a formatted multi-section Markdown document suitable for
    display in ``gr.Markdown`` or any other Markdown renderer.
    """
    lines: list[str] = []

    lines.append("### AI Chart Interpretation")
    lines.append(f"**Detected chart type:** {interp.chart_type_detected}")
    lines.append("")

    # ---- Summary ----------------------------------------------------------
    lines.append("---")
    lines.append(f"**Summary:** {interp.summary}")
    lines.append("")

    # ---- Key observations -------------------------------------------------
    lines.append("#### Key Observations")
    for obs in interp.key_observations:
        lines.append(f"- {obs}")
    lines.append("")

    # ---- Trend ------------------------------------------------------------
    lines.append("#### Trend Analysis")
    arrow = _DIRECTION_EMOJI.get(interp.trend.direction, "")
    lines.append(f"**Direction:** {interp.trend.direction.capitalize()} {arrow}")
    lines.append("")
    lines.append(interp.trend.description)
    lines.append("")

    # ---- Seasonality ------------------------------------------------------
    lines.append("#### Seasonality")
    status = "Detected" if interp.seasonality.detected else "Not detected"
    lines.append(f"**Status:** {status}")
    if interp.seasonality.period:
        lines.append(f"**Period:** {interp.seasonality.period}")
    lines.append("")
    lines.append(interp.seasonality.description)
    lines.append("")

    # ---- Stationarity -----------------------------------------------------
    lines.append("#### Stationarity")
    label = (
        "Likely stationary"
        if interp.stationarity.likely_stationary
        else "Likely non-stationary"
    )
    lines.append(f"**Assessment:** {label}")
    lines.append("")
    lines.append(interp.stationarity.description)
    lines.append("")

    # ---- Anomalies --------------------------------------------------------
    lines.append("#### Anomalies")
    if not interp.anomalies:
        lines.append("No anomalies detected.")
    else:
        for anomaly in interp.anomalies:
            lines.append(
                f"- **[{anomaly.approximate_location}]** "
                f"*{anomaly.severity.upper()}* "
                f"-- {anomaly.description}"
            )
    lines.append("")

    # ---- Recommendations --------------------------------------------------
    lines.append("#### Recommended Next Steps")
    for i, rec in enumerate(interp.recommendations, 1):
        lines.append(f"{i}. {rec}")

    return "\n".join(lines)