File size: 4,564 Bytes
9fb523b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# /// script
# requires-python = ">=3.10"
# dependencies = ["mcp>=1.0", "openai>=1.0", "requests>=2.31"]
# ///
import os
import base64
import tempfile
import requests
from urllib.parse import urlparse
from mcp.server.fastmcp import FastMCP
from openai import OpenAI

mcp = FastMCP("Robust-Vision-Server")


def is_valid_url(url: str) -> bool:
    """Return True iff the input is a syntactically valid http/https URL."""
    try:
        result = urlparse(url)
        return all([result.scheme in ['http', 'https'], result.netloc])
    except ValueError:
        return False


def get_base64_from_local_file(file_path: str) -> str:
    """Read a local image file and encode it as a base64 data URI."""
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"local file not found: {file_path}")

    with open(file_path, "rb") as f:
        encoded = base64.b64encode(f.read()).decode('utf-8')

    # OpenRouter accepts a generic image/jpeg URI; the API infers the real format.
    return f"data:image/jpeg;base64,{encoded}"


@mcp.tool()
def analyze_image_with_openrouter(
    image_source: str,
    prompt: str = "Describe the image in detail and extract any salient text or information.",
    model_name: str = "bytedance-seed/seed-2.0-lite",
) -> str:
    """
    Analyze an image with an OpenRouter vision model. Accepts both local file
    paths and remote http/https URLs. Remote images are downloaded to a
    temporary directory before being sent to the API.

    Args:
        image_source: absolute local path or http/https URL.
        prompt: instruction passed to the vision model.
        model_name: OpenRouter model id.
    """
    api_key = os.getenv("OPENROUTER_API_KEY")
    if not api_key:
        return "Error: OPENROUTER_API_KEY is not set."

    client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=api_key)

    # Branch A: remote URL — download to a temp dir, then call the API.
    if is_valid_url(image_source):
        with tempfile.TemporaryDirectory() as temp_dir:
            temp_file_path = os.path.join(temp_dir, "downloaded_image.tmp")

            try:
                headers = {
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
                    "Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
                }
                response = requests.get(image_source, headers=headers, stream=True, timeout=15)
                response.raise_for_status()

                content_type = response.headers.get('Content-Type', '')
                if not content_type.startswith('image/'):
                    return f"Download failed: target URL did not return an image (Content-Type: {content_type})."

                with open(temp_file_path, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        f.write(chunk)

                image_data_uri = get_base64_from_local_file(temp_file_path)

            except requests.exceptions.Timeout:
                return "Download failed: request timed out (>15s)."
            except requests.exceptions.HTTPError as err:
                return f"Download failed: HTTP error {err.response.status_code}."
            except requests.exceptions.RequestException as err:
                return f"Download failed: network error: {err}"
            except Exception as err:
                return f"Temp-file processing failed: {err}"

            # Call inside the `with` block so the temp file outlives the request.
            return _call_openrouter_api(client, model_name, prompt, image_data_uri)

    # Branch B: local file path.
    try:
        image_data_uri = get_base64_from_local_file(image_source)
        return _call_openrouter_api(client, model_name, prompt, image_data_uri)
    except Exception as err:
        return f"Local file processing failed: {err}"


def _call_openrouter_api(client: OpenAI, model: str, prompt: str, image_data_uri: str) -> str:
    try:
        response = client.chat.completions.create(
            model=model,
            messages=[
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": prompt},
                        {"type": "image_url", "image_url": {"url": image_data_uri}},
                    ],
                }
            ],
        )
        return response.choices[0].message.content
    except Exception as err:
        return f"OpenRouter API call failed: {err}"


if __name__ == "__main__":
    mcp.run()