Ouzhang commited on
Commit
5652a97
·
verified ·
1 Parent(s): 4e26cf6

Upload src/vlm/openrouter.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/vlm/openrouter.py +128 -0
src/vlm/openrouter.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import json
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ import tempfile
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import requests
13
+
14
+
15
+ DEFAULT_OPENROUTER_MODEL = "google/gemini-3.1-pro-preview"
16
+ DEFAULT_OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
17
+ DEFAULT_OPENROUTER_SITE_URL = "http://localhost"
18
+ DEFAULT_OPENROUTER_APP_NAME = "low-high-new"
19
+
20
+
21
+ def extract_frames(video_path: str, *, frame_count: int = 4, width: int = 640) -> list[Path]:
22
+ tmpdir = Path(tempfile.mkdtemp(prefix="openrouter_frames_"))
23
+ out_pattern = tmpdir / "frame_%02d.jpg"
24
+ ffmpeg = shutil.which("ffmpeg")
25
+ if not ffmpeg:
26
+ try:
27
+ import imageio_ffmpeg
28
+
29
+ ffmpeg = imageio_ffmpeg.get_ffmpeg_exe()
30
+ except Exception as exc:
31
+ raise FileNotFoundError(
32
+ "ffmpeg was not found in PATH, and imageio-ffmpeg is not available. "
33
+ "Install ffmpeg or `pip install imageio-ffmpeg`."
34
+ ) from exc
35
+ cmd = [
36
+ ffmpeg,
37
+ "-y",
38
+ "-i",
39
+ video_path,
40
+ "-vf",
41
+ f"fps=1,scale={width}:-1",
42
+ "-frames:v",
43
+ str(frame_count),
44
+ str(out_pattern),
45
+ ]
46
+ subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
47
+ return sorted(tmpdir.glob("frame_*.jpg"))
48
+
49
+
50
+ def _image_to_data_url(path: Path) -> str:
51
+ payload = base64.b64encode(path.read_bytes()).decode("ascii")
52
+ return f"data:image/jpeg;base64,{payload}"
53
+
54
+
55
+ def _extract_json_object(text: str) -> dict[str, Any]:
56
+ stripped = text.strip()
57
+ if stripped.startswith("```"):
58
+ lines = stripped.splitlines()
59
+ if lines and lines[0].startswith("```"):
60
+ lines = lines[1:]
61
+ if lines and lines[-1].startswith("```"):
62
+ lines = lines[:-1]
63
+ stripped = "\n".join(lines).strip()
64
+ start = stripped.find("{")
65
+ end = stripped.rfind("}")
66
+ if start == -1 or end == -1 or end <= start:
67
+ raise ValueError("No JSON object found in model output.")
68
+ return json.loads(stripped[start : end + 1])
69
+
70
+
71
+ class OpenRouterVisionModel:
72
+ def __init__(
73
+ self,
74
+ *,
75
+ model: str = DEFAULT_OPENROUTER_MODEL,
76
+ api_url: str = DEFAULT_OPENROUTER_URL,
77
+ api_key_env: str = "OPENROUTER_API_KEY",
78
+ timeout: int = 300,
79
+ max_tokens: int = 1500,
80
+ site_url: str | None = None,
81
+ app_name: str | None = None,
82
+ ) -> None:
83
+ self.model = model
84
+ self.api_url = api_url
85
+ self.timeout = timeout
86
+ self.max_tokens = max_tokens
87
+ self.site_url = (site_url or os.environ.get("OPENROUTER_SITE_URL") or DEFAULT_OPENROUTER_SITE_URL).strip()
88
+ self.app_name = (app_name or os.environ.get("OPENROUTER_APP_NAME") or DEFAULT_OPENROUTER_APP_NAME).strip()
89
+ self.api_key = os.environ.get(api_key_env, "").strip()
90
+ if not self.api_key:
91
+ raise RuntimeError(f"Missing OpenRouter API key in env var: {api_key_env}")
92
+
93
+ def predict_json(self, *, system_prompt: str, user_text: str, image_paths: list[str]) -> dict[str, Any]:
94
+ content: list[dict[str, Any]] = [{"type": "text", "text": user_text}]
95
+ for image_path in image_paths:
96
+ content.append({"type": "image_url", "image_url": {"url": _image_to_data_url(Path(image_path))}})
97
+ response = requests.post(
98
+ self.api_url,
99
+ headers={
100
+ "Authorization": f"Bearer {self.api_key}",
101
+ "Content-Type": "application/json",
102
+ "HTTP-Referer": self.site_url,
103
+ "X-Title": self.app_name,
104
+ },
105
+ json={
106
+ "model": self.model,
107
+ "messages": [
108
+ {"role": "system", "content": system_prompt},
109
+ {"role": "user", "content": content},
110
+ ],
111
+ "temperature": 0.2,
112
+ "max_tokens": self.max_tokens,
113
+ },
114
+ timeout=self.timeout,
115
+ )
116
+ if not response.ok:
117
+ body = response.text.strip()
118
+ try:
119
+ payload = response.json()
120
+ body = json.dumps(payload, ensure_ascii=False)
121
+ except Exception:
122
+ pass
123
+ raise RuntimeError(
124
+ f"OpenRouter request failed: status={response.status_code}, model={self.model}, body={body}"
125
+ )
126
+ payload = response.json()
127
+ text = payload["choices"][0]["message"]["content"]
128
+ return _extract_json_object(text)