Spaces:
Running
Running
Fix relative image path handling in HF API
Browse files- app/api/hf-process/route.ts +27 -15
app/api/hf-process/route.ts
CHANGED
|
@@ -185,24 +185,36 @@ export async function POST(req: NextRequest) {
|
|
| 185 |
|
| 186 |
// Handle different image formats
|
| 187 |
let parsed: { mimeType: string; data: string } | null = null;
|
|
|
|
| 188 |
|
| 189 |
// Try parsing as Data URL first
|
| 190 |
-
parsed = parseDataUrl(
|
| 191 |
-
|
| 192 |
-
// If not a data URL,
|
| 193 |
-
if (!parsed
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
const
|
| 197 |
-
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
}
|
| 200 |
-
const imageBuffer = await imageResponse.arrayBuffer();
|
| 201 |
-
const contentType = imageResponse.headers.get('content-type') || 'image/png';
|
| 202 |
-
const base64 = Buffer.from(imageBuffer).toString('base64');
|
| 203 |
-
parsed = { mimeType: contentType, data: base64 };
|
| 204 |
-
} catch (fetchErr) {
|
| 205 |
-
console.error('[HF-API] Failed to fetch image URL:', fetchErr);
|
| 206 |
}
|
| 207 |
}
|
| 208 |
|
|
|
|
| 185 |
|
| 186 |
// Handle different image formats
|
| 187 |
let parsed: { mimeType: string; data: string } | null = null;
|
| 188 |
+
let imageUrl = body.image;
|
| 189 |
|
| 190 |
// Try parsing as Data URL first
|
| 191 |
+
parsed = parseDataUrl(imageUrl);
|
| 192 |
+
|
| 193 |
+
// If not a data URL, handle various URL formats
|
| 194 |
+
if (!parsed) {
|
| 195 |
+
// Convert relative paths to absolute URLs
|
| 196 |
+
if (imageUrl.startsWith('/')) {
|
| 197 |
+
const spaceHost = process.env.SPACE_HOST || 'localhost:3000';
|
| 198 |
+
const protocol = spaceHost.includes('localhost') ? 'http' : 'https';
|
| 199 |
+
imageUrl = `${protocol}://${spaceHost}${imageUrl}`;
|
| 200 |
+
console.log('[HF-API] Converted relative path to:', imageUrl);
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
// Fetch from HTTP(S) URL
|
| 204 |
+
if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
|
| 205 |
+
try {
|
| 206 |
+
console.log('[HF-API] Fetching image from URL:', imageUrl.substring(0, 100));
|
| 207 |
+
const imageResponse = await fetch(imageUrl);
|
| 208 |
+
if (!imageResponse.ok) {
|
| 209 |
+
throw new Error(`Failed to fetch image: ${imageResponse.status}`);
|
| 210 |
+
}
|
| 211 |
+
const imageBuffer = await imageResponse.arrayBuffer();
|
| 212 |
+
const contentType = imageResponse.headers.get('content-type') || 'image/png';
|
| 213 |
+
const base64 = Buffer.from(imageBuffer).toString('base64');
|
| 214 |
+
parsed = { mimeType: contentType, data: base64 };
|
| 215 |
+
} catch (fetchErr) {
|
| 216 |
+
console.error('[HF-API] Failed to fetch image URL:', fetchErr);
|
| 217 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
}
|
| 219 |
}
|
| 220 |
|