ASTRALK commited on
Commit
08dce3d
Β·
verified Β·
1 Parent(s): 4875128

Upload comic/backends.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. comic/backends.py +58 -0
comic/backends.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Swappable model backends behind two tiny interfaces.
2
+
3
+ WriterBackend.chat(messages) -> str # Gemma: returns the full reply text
4
+ ArtistBackend.render(prompt, seed) -> bytes # FLUX: returns JPEG/PNG image bytes
5
+
6
+ Selected by COMIC_BACKEND (or an explicit arg):
7
+ "mock" -> offline stand-ins (no GPU, no cost) for building/testing the whole flow.
8
+ "modal" -> the real Gemma vLLM OpenAI endpoint + the resident FLUX endpoint on Modal.
9
+
10
+ The app, engine and tests only ever see these two interfaces, so deploying real
11
+ models is a config flip, not a code change.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ from abc import ABC, abstractmethod
18
+
19
+
20
+ class WriterBackend(ABC):
21
+ @abstractmethod
22
+ def chat(self, messages: list) -> str:
23
+ """Return the model's full text reply for an OpenAI-style message list."""
24
+ raise NotImplementedError
25
+
26
+ def warm(self) -> bool:
27
+ """Best-effort: nudge the backend so a later call is warm. Never raises."""
28
+ return True
29
+
30
+
31
+ class ArtistBackend(ABC):
32
+ @abstractmethod
33
+ def render(self, prompt: str, seed: int = 0) -> bytes:
34
+ """Return image bytes (JPEG/PNG) for a text-free image prompt."""
35
+ raise NotImplementedError
36
+
37
+ def render_batch(self, prompts: list, seeds: list) -> list:
38
+ """Render several prompts. Default: one at a time. Real backends override to
39
+ batch through the GPU in a single pass for much higher throughput."""
40
+ seeds = list(seeds) + [0] * (len(prompts) - len(seeds))
41
+ return [self.render(p, s) for p, s in zip(prompts, seeds)]
42
+
43
+ def warm(self) -> bool:
44
+ return True
45
+
46
+
47
+ # ── factory ──────────────────────────────────────────────────────────────────
48
+
49
+ def make_backends(kind: str | None = None):
50
+ """(writer, artist) pair. kind defaults to $COMIC_BACKEND or 'mock'."""
51
+ kind = (kind or os.environ.get("COMIC_BACKEND", "mock")).lower()
52
+ if kind == "modal":
53
+ from .modal_backend import ModalWriter, ModalArtist
54
+ return ModalWriter(), ModalArtist()
55
+ if kind == "mock":
56
+ from .mock_backend import MockWriter, MockArtist
57
+ return MockWriter(), MockArtist()
58
+ raise ValueError(f"Unknown COMIC_BACKEND: {kind!r} (expected 'mock' or 'modal')")