返回 ppt-master
backend_replicate.py
根目录 / skills / ppt-master / scripts / image_backends / backend_replicate.py
1 #!/usr/bin/env python3
2 """
3 Replicate image generation backend.
4
5 Configuration keys:
6 REPLICATE_API_KEY / REPLICATE_API_TOKEN (required)
7 REPLICATE_BASE_URL (optional)
8 REPLICATE_MODEL (optional)
9 """
10
11 import sys
12 from pathlib import Path
13
14 _SCRIPTS_DIR = Path(__file__).resolve().parents[1]
15 if str(_SCRIPTS_DIR) not in sys.path:
16 sys.path.insert(0, str(_SCRIPTS_DIR))
17
18 from console_encoding import configure_utf8_stdio # noqa: E402
19
20 configure_utf8_stdio()
21
22 if __name__ == "__main__":
23 print(__doc__)
24 print("Use via: python3 skills/ppt-master/scripts/image_gen.py \"prompt\" --backend replicate")
25 raise SystemExit(0 if any(arg in {"-h", "--help", "help"} for arg in sys.argv[1:]) else 1)
26
27 import os
28 import time
29
30 import requests
31
32 from image_backends.backend_common import (
33 MAX_RETRIES,
34 download_image,
35 http_error,
36 is_rate_limit_error,
37 poll_json,
38 require_api_key,
39 resolve_output_path,
40 retry_delay,
41 )
42
43
44 VALID_ASPECT_RATIOS = ["1:1", "16:9", "9:16", "3:4", "4:3", "3:2", "2:3", "4:5", "5:4", "21:9"]
45 DEFAULT_BASE_URL = "https://api.replicate.com/v1"
46 DEFAULT_MODEL = "black-forest-labs/flux-1.1-pro"
47
48
49 def _split_model(model: str) -> tuple[str, str]:
50 """Split a Replicate model reference into owner and name."""
51 parts = [part for part in model.strip().split("/") if part]
52 if len(parts) != 2:
53 raise ValueError(
54 f"Replicate model must be in 'owner/name' format, got '{model}'."
55 )
56 return parts[0], parts[1]
57
58
59 def _extract_output_url(payload: dict) -> str | None:
60 """Extract an output URL from a Replicate prediction payload."""
61 output = payload.get("output")
62 if isinstance(output, str):
63 return output
64 if isinstance(output, list) and output:
65 first = output[0]
66 if isinstance(first, str):
67 return first
68 if isinstance(first, dict):
69 return first.get("url")
70 if isinstance(output, dict):
71 return output.get("url")
72 return None
73
74
75 def _generate_image(api_key: str, prompt: str,
76 aspect_ratio: str = "1:1", image_size: str = "1K",
77 output_dir: str = None, filename: str = None,
78 model: str = DEFAULT_MODEL, base_url: str = DEFAULT_BASE_URL) -> str:
79 """Generate one image with the Replicate backend."""
80 del image_size
81
82 if aspect_ratio not in VALID_ASPECT_RATIOS:
83 raise ValueError(
84 f"Unsupported aspect ratio '{aspect_ratio}' for Replicate backend. "
85 f"Supported: {VALID_ASPECT_RATIOS}"
86 )
87
88 owner, name = _split_model(model)
89 url = f"{base_url.rstrip('/')}/models/{owner}/{name}/predictions"
90 headers = {
91 "Authorization": f"Bearer {api_key}",
92 "Content-Type": "application/json",
93 "Prefer": "wait=60",
94 }
95
96 payload = {
97 "input": {
98 "prompt": prompt,
99 "aspect_ratio": aspect_ratio,
100 "output_format": "png",
101 }
102 }
103
104 print("[Replicate]")
105 print(f" Model: {model}")
106 print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
107 print(f" Aspect Ratio: {aspect_ratio}")
108 print()
109 print(" [..] Generating...", end="", flush=True)
110 start = time.time()
111 response = requests.post(url, headers=headers, json=payload, timeout=180)
112 elapsed = time.time() - start
113 print(f"\n [DONE] Initial response received ({elapsed:.1f}s)")
114
115 if response.status_code not in (200, 201):
116 raise http_error(response, "Replicate generation request")
117
118 data = response.json()
119 status = str(data.get("status", "")).lower()
120 if status != "succeeded":
121 poll_url = ((data.get("urls") or {}).get("get"))
122 if not poll_url:
123 prediction_id = data.get("id")
124 if prediction_id:
125 poll_url = f"{base_url.rstrip('/')}/predictions/{prediction_id}"
126 if not poll_url:
127 raise RuntimeError(f"Replicate response missing poll URL: {data}")
128
129 print(" [..] Polling result...")
130 data = poll_json(
131 poll_url,
132 {"Authorization": f"Bearer {api_key}"},
133 status_label="status",
134 ready_values=["succeeded"],
135 failed_values=["failed", "canceled"],
136 )
137
138 image_url = _extract_output_url(data)
139 if not image_url:
140 raise RuntimeError(f"Replicate response missing output URL: {data}")
141
142 path = resolve_output_path(prompt, output_dir, filename, ".png")
143 return download_image(image_url, path)
144
145
146 def generate(prompt: str,
147 aspect_ratio: str = "1:1", image_size: str = "1K",
148 output_dir: str = None, filename: str = None,
149 model: str = None, max_retries: int = MAX_RETRIES) -> str:
150 """Generate an image with retries using the Replicate backend."""
151 api_key = require_api_key(
152 "REPLICATE_API_KEY",
153 "REPLICATE_API_TOKEN",
154 message="No API key found. Set REPLICATE_API_KEY or REPLICATE_API_TOKEN in the current environment or a .env file.",
155 )
156 base_url = os.environ.get("REPLICATE_BASE_URL") or DEFAULT_BASE_URL
157 resolved_model = model or os.environ.get("REPLICATE_MODEL") or DEFAULT_MODEL
158
159 last_error = None
160 for attempt in range(max_retries + 1):
161 try:
162 return _generate_image(
163 api_key=api_key,
164 prompt=prompt,
165 aspect_ratio=aspect_ratio,
166 image_size=image_size,
167 output_dir=output_dir,
168 filename=filename,
169 model=resolved_model,
170 base_url=base_url,
171 )
172 except Exception as exc:
173 last_error = exc
174 if attempt >= max_retries:
175 break
176 limited = is_rate_limit_error(exc)
177 delay = retry_delay(attempt, rate_limited=limited)
178 label = "Rate limit hit" if limited else f"Error: {exc}"
179 print(f"\n [WARN] {label}. Retrying in {delay}s...")
180 time.sleep(delay)
181
182 raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
183
183 lines PYTHON