File size: 5,577 Bytes
ec21fa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Small OpenRouter JSON client used by the public PosterEval scripts."""

import base64
import hashlib
import json
import os
import re
import threading
from io import BytesIO
from pathlib import Path
from typing import Any, Dict, Optional

from PIL import Image


OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
MODEL_MAP = {
    "qwen3-vl-235b": "qwen/qwen3-vl-235b-a22b-instruct",
    "gpt-4o": "openai/gpt-4o",
    "claude-3.5-sonnet": "anthropic/claude-3.5-sonnet",
}

_CACHE_LOCK = threading.Lock()


def resolve_model(model: str) -> str:
    return MODEL_MAP.get(model, model)


def clean_json_string(text: str) -> str:
    text = (text or "").strip()
    if "```json" in text:
        match = re.search(r"```json\s*([\s\S]*?)\s*```", text)
        if match:
            text = match.group(1)
    elif text.startswith("```"):
        text = re.sub(r"^```\w*\n?", "", text)
        text = re.sub(r"\n?```$", "", text)

    start = text.find("{")
    end = text.rfind("}")
    if start != -1 and end != -1 and end > start:
        text = text[start : end + 1]

    text = text.replace("\r", " ").replace("\n", " ")
    text = re.sub(r"[\x00-\x1f]", " ", text)
    return re.sub(r"\s+", " ", text).strip()


def parse_json_response(text: str) -> Dict[str, Any]:
    try:
        payload = json.loads(clean_json_string(text))
        if isinstance(payload, dict):
            return payload
    except json.JSONDecodeError:
        pass
    return {
        "parse_error": True,
        "raw_response": text,
        "error": "Could not parse a JSON object from the model response.",
    }


def encode_image_data_url(
    image_path: Path,
    max_edge: int = 1600,
    jpeg_quality: int = 85,
) -> str:
    image = Image.open(image_path)
    width, height = image.size
    if max(width, height) > max_edge:
        ratio = max_edge / float(max(width, height))
        image = image.resize(
            (max(1, int(width * ratio)), max(1, int(height * ratio))),
            Image.LANCZOS,
        )
    if image.mode != "RGB":
        image = image.convert("RGB")

    buffer = BytesIO()
    image.save(buffer, format="JPEG", quality=jpeg_quality)
    encoded = base64.b64encode(buffer.getvalue()).decode("utf-8")
    return "data:image/jpeg;base64," + encoded


def _cache_path(model: str, prompt: str, image_path: Optional[Path]) -> Optional[Path]:
    cache_dir = os.getenv("POSTEREVAL_LLM_CACHE_DIR", "").strip()
    if not cache_dir:
        return None

    digest = hashlib.sha256()
    digest.update(model.encode("utf-8"))
    digest.update(b"\0")
    digest.update(prompt.encode("utf-8"))
    if image_path is not None:
        digest.update(b"\0")
        digest.update(str(image_path.name).encode("utf-8"))
        try:
            digest.update(image_path.read_bytes())
        except OSError:
            digest.update(str(image_path).encode("utf-8"))
    return Path(cache_dir) / (digest.hexdigest() + ".json")


def _read_cache(path: Optional[Path]) -> Optional[Dict[str, Any]]:
    if path is None or not path.exists():
        return None
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return None
    return payload if isinstance(payload, dict) else None


def _write_cache(path: Optional[Path], payload: Dict[str, Any]) -> None:
    if path is None or payload.get("parse_error"):
        return
    path.parent.mkdir(parents=True, exist_ok=True)
    temp_path = path.with_suffix("." + str(threading.get_ident()) + ".tmp")
    with _CACHE_LOCK:
        if path.exists():
            return
        temp_path.write_text(
            json.dumps(payload, ensure_ascii=False) + "\n",
            encoding="utf-8",
        )
        os.replace(temp_path, path)


def call_openrouter_json(
    prompt: str,
    model: str = "qwen3-vl-235b",
    image_path: Optional[Path] = None,
    max_tokens: int = 16384,
    temperature: float = 0.0,
    response_format_json: bool = True,
) -> Dict[str, Any]:
    """Call OpenRouter and parse a JSON response.

    Set `OPENROUTER_API_KEY` in the environment. `POSTEREVAL_LLM_CACHE_DIR` is
    optional and stores parsed JSON responses keyed by model, prompt, and image.
    """

    from openai import OpenAI

    model_name = resolve_model(model)
    cache_path = _cache_path(model_name, prompt, image_path)
    cached = _read_cache(cache_path)
    if cached is not None:
        return cached

    api_key = os.getenv("OPENROUTER_API_KEY", "").strip()
    if not api_key:
        raise RuntimeError("OPENROUTER_API_KEY is not set.")

    content: Any
    if image_path is None:
        content = prompt
    else:
        content = [
            {"type": "image_url", "image_url": {"url": encode_image_data_url(image_path)}},
            {"type": "text", "text": prompt},
        ]

    client = OpenAI(
        base_url=os.getenv("OPENROUTER_BASE_URL", OPENROUTER_BASE_URL),
        api_key=api_key,
        default_headers={
            "HTTP-Referer": "https://postereval.local",
            "X-Title": "PosterEval",
        },
    )
    kwargs: Dict[str, Any] = {
        "model": model_name,
        "messages": [{"role": "user", "content": content}],
        "temperature": temperature,
        "max_tokens": max_tokens,
    }
    if response_format_json:
        kwargs["response_format"] = {"type": "json_object"}

    response = client.chat.completions.create(**kwargs)
    raw_text = response.choices[0].message.content or ""
    payload = parse_json_response(raw_text)
    _write_cache(cache_path, payload)
    return payload