File size: 8,125 Bytes
5b6e956
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
276
277
278
279
280
281
282
283
284
285
"""
Enhanced Base Plugin

Location-agnostic backend plugin that supports:
- Local backends (running in project)
- Network backends (running on LAN)
- Cloud backends (commercial APIs)

Uses prompt transformation layer for backend format abstraction.
"""

from abc import ABC, abstractmethod
from typing import List, Optional
from pathlib import Path
import requests
from PIL import Image

from .backend_config import BackendConnectionConfig, BackendLocation, BackendProtocol
from .prompt_transformer import (
    StandardGenerationRequest,
    PromptTransformer,
    get_transformer
)


class EnhancedBackendPlugin(ABC):
    """
    Enhanced base class for all backend plugins.

    Supports three deployment scenarios:
    1. Local: Backend runs in project structure
    2. Network: Backend runs on LAN (IP:PORT)
    3. Cloud: Commercial API over internet

    The application NEVER directly imports backends.
    Everything goes through this abstraction layer.
    """

    def __init__(self, config: BackendConnectionConfig):
        """
        Initialize plugin with connection configuration.

        Args:
            config: Backend connection configuration
        """
        self.config = config
        self.name = config.name
        self.backend_type = config.backend_type
        self.location = config.location
        self.protocol = config.protocol

        # Get prompt transformer for this backend type
        self.transformer = get_transformer(config.backend_type)

        # Backend-specific client (set by subclass)
        self._client = None

    @abstractmethod
    def _initialize_local(self) -> None:
        """
        Initialize local backend.

        Subclasses implement this to set up local backend.
        Example: Import and instantiate local Python module.
        """
        pass

    @abstractmethod
    def _initialize_network(self) -> None:
        """
        Initialize network backend.

        Subclasses implement this to set up network connection.
        Example: Create HTTP client with endpoint.
        """
        pass

    @abstractmethod
    def _initialize_cloud(self) -> None:
        """
        Initialize cloud backend.

        Subclasses implement this to set up cloud API client.
        Example: Configure API client with credentials.
        """
        pass

    def initialize(self) -> None:
        """
        Initialize backend based on location.

        Automatically calls the appropriate initialization method.
        """
        if self.location == BackendLocation.LOCAL:
            self._initialize_local()
        elif self.location == BackendLocation.NETWORK:
            self._initialize_network()
        elif self.location == BackendLocation.CLOUD:
            self._initialize_cloud()

    def health_check(self) -> bool:
        """
        Check if backend is available and healthy.

        Works for local, network, and cloud backends.
        """
        if self.location == BackendLocation.LOCAL:
            # Local: Check if client is initialized
            return self._client is not None

        elif self.location in [BackendLocation.NETWORK, BackendLocation.CLOUD]:
            # Network/Cloud: Send health check request
            try:
                health_url = self.config.get_full_endpoint(
                    self.config.health_check_endpoint or '/health'
                )

                response = requests.get(
                    health_url,
                    timeout=5,
                    headers=self._get_auth_headers()
                )

                return response.status_code == 200

            except Exception as e:
                print(f"Health check failed for {self.name}: {e}")
                return False

        return False

    def generate_image(
        self,
        request: StandardGenerationRequest
    ) -> List[Image.Image]:
        """
        Generate image using this backend.

        This is the ONLY method the application calls.
        It handles:
        1. Transform standard request → backend format
        2. Send to backend (local/network/cloud)
        3. Transform backend response → standard format

        Args:
            request: Standard generation request

        Returns:
            List of generated images
        """

        # Step 1: Transform request to backend-specific format
        backend_request = self.transformer.transform_request(request)

        # Step 2: Send to backend based on location
        if self.location == BackendLocation.LOCAL:
            backend_response = self._generate_local(backend_request)

        elif self.location == BackendLocation.NETWORK:
            backend_response = self._generate_network(backend_request)

        elif self.location == BackendLocation.CLOUD:
            backend_response = self._generate_cloud(backend_request)

        else:
            raise ValueError(f"Unknown backend location: {self.location}")

        # Step 3: Transform response to standard format
        images = self.transformer.transform_response(backend_response)

        return images

    @abstractmethod
    def _generate_local(self, backend_request: dict) -> any:
        """
        Generate using local backend.

        Args:
            backend_request: Backend-specific request format

        Returns:
            Backend-specific response
        """
        pass

    @abstractmethod
    def _generate_network(self, backend_request: dict) -> any:
        """
        Generate using network backend.

        Args:
            backend_request: Backend-specific request format

        Returns:
            Backend-specific response
        """
        pass

    @abstractmethod
    def _generate_cloud(self, backend_request: dict) -> any:
        """
        Generate using cloud backend.

        Args:
            backend_request: Backend-specific request format

        Returns:
            Backend-specific response
        """
        pass

    def _get_auth_headers(self) -> dict:
        """Get authentication headers for API requests."""
        headers = {}

        if self.config.api_key:
            # Common auth header patterns
            if self.backend_type == 'gemini':
                headers['x-goog-api-key'] = self.config.api_key
            else:
                headers['Authorization'] = f'Bearer {self.config.api_key}'

        return headers

    def _send_http_request(
        self,
        endpoint: str,
        data: dict,
        method: str = 'POST'
    ) -> any:
        """
        Send HTTP request to backend.

        Helper method for network/cloud backends.
        """
        url = self.config.get_full_endpoint(endpoint)

        headers = self._get_auth_headers()
        headers['Content-Type'] = 'application/json'

        try:
            if method == 'POST':
                response = requests.post(
                    url,
                    json=data,
                    headers=headers,
                    timeout=self.config.timeout
                )
            elif method == 'GET':
                response = requests.get(
                    url,
                    params=data,
                    headers=headers,
                    timeout=self.config.timeout
                )

            response.raise_for_status()
            return response.json()

        except requests.exceptions.RequestException as e:
            raise RuntimeError(f"Backend request failed: {e}")

    def get_capabilities(self) -> dict:
        """
        Report backend capabilities.

        Returns capabilities from configuration.
        """
        return {
            'name': self.name,
            'backend_type': self.backend_type,
            'location': self.location.value,
            'protocol': self.protocol.value,
            'endpoint': self.config.endpoint,
            **self.config.capabilities
        }

    def __repr__(self):
        return (
            f"{self.__class__.__name__}("
            f"name={self.name}, "
            f"location={self.location.value}, "
            f"endpoint={self.config.endpoint})"
        )