Spaces:
Lakshay3605
/
Sleeping

HowToTellWildAnimals's picture
feat: add autonomous pipeline orchestrator with scheduled Instagram posting
c50284e
Raw History Blame Contribute Delete
29.5 kB
import fetch from 'node-fetch';
import express from 'express';
import cors from 'cors';
import fs from 'fs/promises';
import fsSync from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { randomUUID } from 'crypto';
import { exec } from 'child_process';
import util from 'util';
const execPromise = util.promisify(exec);
const PORT = 3000;
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const HISTORY_FILE = path.join(__dirname, 'posting_history.json');
// Local cache directory for downloaded HF images β€” served as static files
const OUTPUTS_DIR = path.join(__dirname, 'outputs');
fsSync.mkdirSync(OUTPUTS_DIR, { recursive: true });
// Path to Python CLI and CWD
const INSTAGRAM_CWD = path.join(__dirname, '..', 'INSTAGRAM', 'INSTAGRAM');
const PYTHON_EXE = process.platform === 'win32'
? path.join(INSTAGRAM_CWD, '.venv', 'Scripts', 'python.exe')
: path.join(INSTAGRAM_CWD, '.venv', 'bin', 'python');
function loadEnv() {
try {
const envPath = path.join(INSTAGRAM_CWD, '.env');
if (fsSync.existsSync(envPath)) {
const content = fsSync.readFileSync(envPath, 'utf-8');
content.split('\n').forEach(line => {
const parts = line.split('=');
if (parts.length >= 2) {
const key = parts[0].trim();
const val = parts.slice(1).join('=').trim().replace(/^["']|["']$/g, '');
process.env[key] = val;
}
});
}
} catch (err) {
console.error('Failed to load .env file:', err);
}
}
loadEnv();
async function readHistory() {
try {
const raw = await fs.readFile(HISTORY_FILE, 'utf-8');
const data = JSON.parse(raw);
return Array.isArray(data) ? data : [];
} catch (err) {
if (err.code === 'ENOENT') return [];
throw err;
}
}
async function writeHistory(posts) {
await fs.writeFile(HISTORY_FILE, JSON.stringify(posts, null, 2), 'utf-8');
}
async function appendHistory(entry) {
const posts = await readHistory();
posts.unshift(entry);
await writeHistory(posts);
}
function isHttpUrl(str) {
try {
const u = new URL(str.trim());
return u.protocol === 'http:' || u.protocol === 'https:';
} catch {
return false;
}
}
const PROBE_HEADERS = {
'User-Agent':
'Mozilla/5.0 (compatible; FashionAI-Bot/1.0; +https://github.com/sharjilsharma)',
Accept: 'image/*,*/*;q=0.8',
};
async function fetchImageProbe(url) {
// Hugging Face /file= paths are short-lived, auth-gated, and often return 404
// on probe requests even when valid. Trust them without probing.
if (url.includes('hf.space') || url.includes('huggingface.co')) {
console.log(`[probe] Skipping probe for HF URL (trusted): ${url}`);
return { ok: true, status: 200 };
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10000);
try {
const headers = { ...PROBE_HEADERS };
// Hugging Face proxy returns 200 OK for HEAD even on 404 paths.
// Use GET with Range by default to fetch only the start of the image.
let res = await fetch(url, {
method: 'GET',
redirect: 'follow',
headers: { ...headers, Range: 'bytes=0-1023' },
signal: controller.signal,
});
if (res.status === 405 || res.status === 501) {
res = await fetch(url, {
method: 'GET',
redirect: 'follow',
headers: headers,
signal: controller.signal,
});
}
if (!res.ok) {
return { ok: false, status: res.status, error: `URL returned HTTP ${res.status}` };
}
return { ok: true, status: res.status };
} finally {
clearTimeout(timer);
}
}
async function validateImageUrl(url) {
const trimmed = url.trim();
if (!trimmed) {
return { url: trimmed, ok: false, error: 'URL is empty' };
}
if (trimmed.startsWith('data:image/') || trimmed.includes(';base64,')) {
return { url: '[Local File]', ok: true };
}
if (!isHttpUrl(trimmed)) {
return { url: trimmed, ok: false, error: 'Invalid URL β€” must start with http:// or https://' };
}
try {
return { url: trimmed, ...(await fetchImageProbe(trimmed)) };
} catch (err) {
if (err.name === 'AbortError') {
return { url: trimmed, ok: true, warning: 'URL check timed out β€” proceeding anyway' };
}
return { url: trimmed, ok: false, error: err.message };
}
}
async function validateImageUrls(urls) {
const unique = [...new Set(urls.map((u) => u.trim()).filter(Boolean))];
const results = await Promise.all(unique.map((url) => validateImageUrl(url)));
return results;
}
// Shared helper: download an HF image server-side and save it to the local
// outputs cache. Returns a stable localhost URL that never expires.
async function cacheHfImageLocally(remoteUrl, prefix = 'img') {
if (!remoteUrl) return null;
try {
const hfToken = (process.env.HF_TOKEN || '').trim();
const dlHeaders = { ...PROBE_HEADERS };
if ((remoteUrl.includes('hf.space') || remoteUrl.includes('huggingface.co')) && hfToken) {
dlHeaders['Authorization'] = `Bearer ${hfToken}`;
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 30000);
let dlRes;
try {
dlRes = await fetch(remoteUrl, { method: 'GET', redirect: 'follow', headers: dlHeaders, signal: controller.signal });
} finally {
clearTimeout(timer);
}
if (!dlRes.ok) {
console.warn(`[cache] Download failed HTTP ${dlRes.status} for ${remoteUrl}`);
return null;
}
const contentType = dlRes.headers.get('content-type') || 'image/jpeg';
const extMap = { 'image/jpeg': '.jpg', 'image/png': '.png', 'image/webp': '.webp', 'image/gif': '.gif' };
const ext = extMap[contentType.split(';')[0].trim()] || '.jpg';
const filename = `${prefix}_${randomUUID()}${ext}`;
const localPath = path.join(OUTPUTS_DIR, filename);
const buf = await dlRes.arrayBuffer();
await fs.writeFile(localPath, Buffer.from(buf));
const localUrl = `http://localhost:${PORT}/outputs/${filename}`;
console.log(`[cache] Saved ${remoteUrl} β†’ ${localUrl}`);
return { filename, localUrl };
} catch (err) {
console.warn(`[cache] Failed to cache ${remoteUrl}: ${err.message}`);
return null;
}
}
const app = express();
app.use(cors());
app.use(express.json({ limit: '50mb' }));
// Serve locally cached try-on images β€” stable URLs that never expire
app.use('/outputs', express.static(OUTPUTS_DIR));
app.get('/', async (_req, res) => {
try {
const htmlPath = path.join(__dirname, 'index.html');
const html = await fs.readFile(htmlPath, 'utf-8');
res.type('html').send(html);
} catch (err) {
res.status(500).send(`Failed to load UI: ${err.message}`);
}
});
// Proxy endpoint: downloads an image from a remote URL (e.g. HF Space) server-side
// and streams it back to the client. Avoids CORS issues and browser auth restrictions.
app.get('/api/proxy-image', async (req, res) => {
const { url } = req.query;
if (!url || !isHttpUrl(url)) {
return res.status(400).json({ error: 'Missing or invalid url query parameter' });
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 30000);
try {
const headers = { ...PROBE_HEADERS };
const hfToken = process.env.HF_TOKEN;
if ((url.includes('hf.space') || url.includes('huggingface.co')) && hfToken) {
headers['Authorization'] = `Bearer ${hfToken}`;
}
const upstream = await fetch(url, {
method: 'GET',
redirect: 'follow',
headers,
signal: controller.signal,
});
clearTimeout(timer);
if (!upstream.ok) {
return res.status(upstream.status).json({ error: `Upstream returned HTTP ${upstream.status}` });
}
const contentType = upstream.headers.get('content-type') || 'image/jpeg';
res.setHeader('Content-Type', contentType);
res.setHeader('Cache-Control', 'no-store');
// Stream the body directly to the client
upstream.body.pipe(res);
} catch (err) {
clearTimeout(timer);
if (err.name === 'AbortError') {
return res.status(504).json({ error: 'Proxy request timed out' });
}
console.error('[proxy-image] Error:', err);
res.status(500).json({ error: err.message });
}
});
app.get('/api/status', async (_req, res) => {
const sessionPath = path.join(INSTAGRAM_CWD, 'session.json');
let token_valid = false;
try {
await fs.access(sessionPath);
token_valid = true;
} catch {}
res.json({
status: 'ok',
token_valid,
});
});
app.get('/api/fetch-latest', async (req, res) => {
try {
const hfSpaceUrl = process.env.HF_SPACE_URL || 'https://lakshay3605-automatic-uploader.hf.space';
const hfToken = (process.env.HF_TOKEN || '').trim();
const headers = {};
if (hfToken) headers['Authorization'] = `Bearer ${hfToken}`;
const apiEndpoint = `${hfSpaceUrl.replace(/\/$/, '')}/api/latest-image`;
console.log(`[fetch-latest] Requesting latest image from: ${apiEndpoint}`);
const response = await fetch(apiEndpoint, { method: 'GET', headers });
if (!response.ok) {
const errText = await response.text();
return res.status(response.status).json({
success: false,
error: `Hugging Face space returned HTTP ${response.status}: ${errText}`
});
}
const data = await response.json();
let finalUrl, filename;
if (data.image_data) {
// New protocol: HF Space returns base64 image data directly β€” write to local cache
const base64Data = data.image_data.includes(',') ? data.image_data.split(',')[1] : data.image_data;
filename = `latest_${randomUUID()}.jpg`;
const localPath = path.join(OUTPUTS_DIR, filename);
await fs.writeFile(localPath, Buffer.from(base64Data, 'base64'));
finalUrl = `http://localhost:${PORT}/outputs/${filename}`;
console.log(`[fetch-latest] Saved base64 image to: ${localPath}`);
} else if (data.image_url) {
// Legacy protocol: try to cache the URL (may fail if Space restarted)
const cached = await cacheHfImageLocally(data.image_url, 'latest');
finalUrl = cached?.localUrl || data.image_url;
filename = cached?.filename || data.output_filename;
} else {
return res.status(500).json({ success: false, error: 'No image data returned from Space' });
}
console.log(`[fetch-latest] Serving cached image at: ${finalUrl}`);
res.json({
success: true,
image_url: finalUrl,
output_filename: filename || data.output_filename
});
} catch (err) {
console.error('[fetch-latest] Failed to retrieve latest image:', err);
res.status(500).json({ success: false, error: err.message });
}
});
app.post('/api/generate-tryon', async (req, res) => {
try {
const { human_image, garment_image, garment_description } = req.body ?? {};
if (!human_image || !garment_image || !garment_description) {
return res.status(400).json({ success: false, error: 'human_image, garment_image, and garment_description are required' });
}
const hfSpaceUrl = (process.env.HF_SPACE_URL || 'https://lakshay3605-automatic-uploader.hf.space').replace(/\/$/, '');
const hfToken = process.env.HF_TOKEN;
const authHeaders = {};
if (hfToken) {
authHeaders['Authorization'] = `Bearer ${hfToken}`;
}
// --- Helper: convert data URI to a Blob for upload ---
function dataUriToBlob(dataUri) {
const parts = dataUri.split(',');
const meta = parts[0]; // e.g. "data:image/jpeg;base64"
const raw = parts[1];
const mime = meta.match(/:(.*?);/)?.[1] || 'image/jpeg';
const ext = mime.split('/')[1] || 'jpg';
const buffer = Buffer.from(raw, 'base64');
return { buffer, mime, ext };
}
// --- Helper: upload a single image to Gradio's /upload endpoint ---
async function uploadToGradio(dataUri, filename) {
const { buffer, mime, ext } = dataUriToBlob(dataUri);
const fname = filename || `upload.${ext}`;
const blob = new Blob([buffer], { type: mime });
const formData = new FormData();
formData.append('files', blob, fname);
console.log(`[generate-tryon] Uploading ${fname} (${buffer.length} bytes, ${mime}) to ${hfSpaceUrl}/upload`);
const uploadRes = await fetch(`${hfSpaceUrl}/upload`, {
method: 'POST',
headers: { ...authHeaders },
body: formData
});
if (!uploadRes.ok) {
const errText = await uploadRes.text();
throw new Error(`Upload failed HTTP ${uploadRes.status}: ${errText}`);
}
const uploadResult = await uploadRes.json();
console.log(`[generate-tryon] Upload result:`, JSON.stringify(uploadResult));
// Returns array of file paths, e.g. ["/tmp/gradio/abc/image.jpg"]
if (Array.isArray(uploadResult) && uploadResult.length > 0) {
return uploadResult[0];
}
throw new Error(`Unexpected upload response: ${JSON.stringify(uploadResult)}`);
}
// Step 1: Upload both images to the Gradio server
console.log(`[generate-tryon] Step 1: Uploading images to Gradio...`);
const [humanPath, garmentPath] = await Promise.all([
uploadToGradio(human_image, 'human.jpg'),
uploadToGradio(garment_image, 'garment.jpg')
]);
console.log(`[generate-tryon] Human path: ${humanPath}, Garment path: ${garmentPath}`);
// Step 2: POST to /call/tryon with file paths
const callEndpoint = `${hfSpaceUrl}/call/tryon`;
console.log(`[generate-tryon] Step 2: Calling ${callEndpoint} with uploaded file paths...`);
// Gradio 4.x /call/ format: image inputs as {path: "...", meta: {_type: "gradio.FileData"}}
const humanFileData = { path: humanPath, meta: { _type: "gradio.FileData" } };
const garmentFileData = { path: garmentPath, meta: { _type: "gradio.FileData" } };
// start_tryon_wrapper inputs: [imgs, garm_img, prompt, is_checked, is_checked_crop, denoise_steps, seed, auto_post_instagram, instagram_caption]
const gradioPayload = {
data: [
// imgs (ImageEditor): dict with background, layers, composite
{ background: humanFileData, layers: [], composite: null },
// garm_img (Image)
garmentFileData,
// garment_des (Textbox)
garment_description,
// is_checked (Checkbox)
true,
// is_checked_crop (Checkbox)
false,
// denoise_steps (Number)
30,
// seed (Number)
42,
// auto_post_instagram (Checkbox)
false,
// instagram_caption (Textbox)
""
]
};
const callResponse = await fetch(callEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...authHeaders },
body: JSON.stringify(gradioPayload)
});
if (!callResponse.ok) {
const errText = await callResponse.text();
return res.status(callResponse.status).json({
success: false,
error: `Gradio /call/ initiation failed HTTP ${callResponse.status}: ${errText}`
});
}
const callResult = await callResponse.json();
const eventId = callResult.event_id;
if (!eventId) {
return res.status(500).json({
success: false,
error: `Gradio /call/ did not return event_id: ${JSON.stringify(callResult)}`
});
}
console.log(`[generate-tryon] Step 3: Got event_id=${eventId}, polling SSE stream...`);
// Step 3: GET /call/tryon/<event_id> as SSE stream
const sseEndpoint = `${callEndpoint}/${eventId}`;
const sseController = new AbortController();
const sseTimer = setTimeout(() => sseController.abort(), 300000); // 5 min timeout
let sseResponse;
try {
sseResponse = await fetch(sseEndpoint, {
method: 'GET',
headers: { ...authHeaders },
signal: sseController.signal
});
} catch (fetchErr) {
clearTimeout(sseTimer);
if (fetchErr.name === 'AbortError') {
return res.status(504).json({ success: false, error: 'Try-on generation timed out (5 min). The Space may be overloaded.' });
}
throw fetchErr;
}
if (!sseResponse.ok) {
clearTimeout(sseTimer);
const errText = await sseResponse.text();
return res.status(sseResponse.status).json({
success: false,
error: `Gradio SSE stream failed HTTP ${sseResponse.status}: ${errText}`
});
}
// Parse SSE stream to get the final result
const sseText = await sseResponse.text();
clearTimeout(sseTimer);
// Log raw SSE for debugging
console.log(`[generate-tryon] Raw SSE response (first 2000 chars):\n${sseText.substring(0, 2000)}`);
// Parse SSE events into a map of { eventType -> dataStr }
const sseEvents = [];
const lines = sseText.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line.startsWith('event:')) {
const eventType = line.substring(6).trim();
const dataLine = lines[i + 1]?.trim() ?? '';
const dataStr = dataLine.startsWith('data:') ? dataLine.substring(5).trim() : '';
console.log(`[generate-tryon] SSE event: ${eventType}, data preview: ${dataStr.substring(0, 300)}`);
sseEvents.push({ eventType, dataStr });
}
}
const errorEvent = sseEvents.find(e => e.eventType === 'error');
const completeEvent = sseEvents.find(e => e.eventType === 'complete');
if (errorEvent) {
// Try to extract a meaningful message from the error data
let errMsg = 'Gradio job failed';
if (errorEvent.dataStr && errorEvent.dataStr !== 'null') {
try {
const parsed = JSON.parse(errorEvent.dataStr);
errMsg = parsed?.message || parsed?.error || JSON.stringify(parsed);
} catch {
errMsg = errorEvent.dataStr;
}
} else {
// data: null means Gradio killed the job (ZeroGPU timeout, OOM, Space restart, etc.)
// Check if there's a useful message in any other event
const anyMsg = sseEvents.find(e => e.dataStr && e.dataStr !== 'null' && e.eventType !== 'heartbeat');
errMsg = anyMsg
? `Gradio job failed (data: null). Last event data: ${anyMsg.dataStr.substring(0, 300)}`
: 'Gradio job failed: the Space returned a null error β€” this usually means a ZeroGPU timeout, out-of-memory, or the Space restarted. Try again.';
}
return res.status(500).json({ success: false, error: errMsg });
}
let gradioData = null;
if (completeEvent) {
try {
gradioData = JSON.parse(completeEvent.dataStr);
} catch (parseErr) {
console.error('[generate-tryon] Failed to parse SSE complete data:', parseErr);
}
}
if (!gradioData || !Array.isArray(gradioData)) {
return res.status(500).json({
success: false,
error: `Gradio returned no complete event. Raw SSE: ${sseText.substring(0, 500)}`
});
}
// gradioData is a list of outputs: [image_out, masked_img, instagram_status, last_output_path_state]
const imageOut = gradioData[0];
const maskedImg = gradioData[1];
// Extract image URL from Gradio output
let imageUrl = null;
if (imageOut) {
if (typeof imageOut === 'string') {
imageUrl = imageOut;
} else if (imageOut.url) {
imageUrl = imageOut.url;
} else if (imageOut.path) {
imageUrl = `${hfSpaceUrl}/file=${imageOut.path}`;
}
}
if (!imageUrl) {
return res.status(500).json({
success: false,
error: `Could not extract image URL from Gradio response: ${JSON.stringify(gradioData).substring(0, 500)}`
});
}
// If the URL is relative, make it absolute
if (imageUrl.startsWith('/')) {
imageUrl = `${hfSpaceUrl}${imageUrl}`;
}
let maskUrl = null;
if (maskedImg) {
if (typeof maskedImg === 'string') {
maskUrl = maskedImg;
} else if (maskedImg.url) {
maskUrl = maskedImg.url;
} else if (maskedImg.path) {
maskUrl = `${hfSpaceUrl}/file=${maskedImg.path}`;
}
}
if (maskUrl && maskUrl.startsWith('/')) {
maskUrl = `${hfSpaceUrl}${maskUrl}`;
}
console.log(`[generate-tryon] Success! Remote image URL: ${imageUrl}`);
// Cache both images immediately using the shared helper
const [cachedMain, cachedMask] = await Promise.all([
cacheHfImageLocally(imageUrl, 'tryon'),
cacheHfImageLocally(maskUrl, 'mask'),
]);
const finalImageUrl = cachedMain?.localUrl || imageUrl;
const finalMaskUrl = cachedMask?.localUrl || maskUrl;
const outputFilename = cachedMain?.filename ||
(imageOut?.path ? imageOut.path.split('/').pop() : 'tryon_output.jpg');
console.log(`[generate-tryon] Serving cached image at: ${finalImageUrl}`);
res.json({
success: true,
image_url: finalImageUrl,
mask_url: finalMaskUrl,
output_filename: outputFilename
});
} catch (err) {
console.error('[generate-tryon] Failed to generate try-on:', err);
res.status(500).json({ success: false, error: err.message });
}
});
app.get('/api/history', async (_req, res) => {
try {
const posts = await readHistory();
res.json({ total: posts.length, posts });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
app.post('/api/validate-images', async (req, res) => {
try {
const { urls } = req.body ?? {};
const startedAt = Date.now();
if (!Array.isArray(urls)) {
return res.status(400).json({ success: false, error: 'urls must be an array' });
}
const results = await validateImageUrls(urls);
const all_ok = results.every((r) => r.ok);
console.log(
`[validate-images] urls=${urls.length} all_ok=${all_ok} elapsed_ms=${Date.now() - startedAt}`
);
res.json({ success: true, all_ok, results });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
app.post('/api/post', async (req, res) => {
const startedAt = Date.now();
const { images, caption, thumbnail_url } = req.body ?? {};
if (!Array.isArray(images) || images.length === 0) {
return res.status(400).json({
success: false,
error: 'images must be a non-empty array',
});
}
if (typeof caption !== 'string' || !caption.trim()) {
return res.status(400).json({
success: false,
error: 'caption is required',
});
}
const validImages = images.filter((u) => typeof u === 'string' && u.trim());
if (validImages.length === 0) {
return res.status(400).json({
success: false,
error: 'images must contain at least one valid URL or Base64 file',
});
}
// Prepare images list including optional thumbnail
let finalImages = [...validImages];
if (thumbnail_url?.trim() && !finalImages.includes(thumbnail_url.trim())) {
finalImages.unshift(thumbnail_url.trim());
}
if (finalImages.length > 10) {
return res.status(400).json({
success: false,
error: 'maximum 10 images allowed',
});
}
// Pre-validate images
const validation = await validateImageUrls(finalImages);
const failed = validation.filter((r) => !r.ok);
if (failed.length) {
const details = failed.map((r) => `${r.url}: ${r.error}`).join('; ');
return res.status(400).json({
success: false,
error: `One or more image URLs are not reachable: ${details}`,
failed_urls: failed,
});
}
// Write payload to a temporary JSON file to avoid command-line arg limit and encoding issues
const tempFilename = `upload_request_${randomUUID()}.json`;
const tempDownloadsDir = path.join(INSTAGRAM_CWD, 'tmp_downloads');
const tempFilePath = path.join(tempDownloadsDir, tempFilename);
const filePaths = [];
const localTempFiles = [];
try {
// Ensure tmp_downloads exists
await fs.mkdir(tempDownloadsDir, { recursive: true });
// Helper: download a remote URL server-side and save to a local temp file.
// Used for HF Space URLs which are short-lived and auth-gated.
async function downloadRemoteImage(url) {
const hfToken = (process.env.HF_TOKEN || '').trim();
const dlHeaders = { ...PROBE_HEADERS };
if ((url.includes('hf.space') || url.includes('huggingface.co')) && hfToken) {
dlHeaders['Authorization'] = `Bearer ${hfToken}`;
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 30000);
try {
const dlRes = await fetch(url, { method: 'GET', redirect: 'follow', headers: dlHeaders, signal: controller.signal });
if (!dlRes.ok) throw new Error(`Remote image download failed HTTP ${dlRes.status} for ${url}`);
const contentType = dlRes.headers.get('content-type') || 'image/jpeg';
const extMap = { 'image/jpeg': '.jpg', 'image/png': '.png', 'image/webp': '.webp', 'image/gif': '.gif' };
const ext = extMap[contentType.split(';')[0].trim()] || '.jpg';
const tempPath = path.join(tempDownloadsDir, `hf_download_${randomUUID()}${ext}`);
const arrayBuffer = await dlRes.arrayBuffer();
await fs.writeFile(tempPath, Buffer.from(arrayBuffer));
console.log(`[post] Pre-downloaded HF image to: ${tempPath}`);
return tempPath;
} finally {
clearTimeout(timer);
}
}
// Process images: write Base64 data or HF URLs to local files; leave other URLs as-is
for (let i = 0; i < finalImages.length; i++) {
const img = finalImages[i];
if (img.startsWith('data:image/') || img.includes(';base64,')) {
// Base64 encoded image β†’ decode and write to disk
const matches = img.match(/^data:image\/([A-Za-z+]+);base64,(.+)$/);
let base64Data = img;
let ext = '.jpg';
if (matches && matches.length === 3) {
ext = '.' + matches[1];
base64Data = matches[2];
} else {
const parts = img.split(';base64,');
if (parts.length === 2) {
base64Data = parts[1];
}
}
const buffer = Buffer.from(base64Data, 'base64');
const tempPath = path.join(tempDownloadsDir, `local_upload_${randomUUID()}${ext}`);
await fs.writeFile(tempPath, buffer);
filePaths.push(tempPath);
localTempFiles.push(tempPath);
} else if (img.includes('hf.space') || img.includes('huggingface.co')) {
// HF Space URL β†’ pre-download server-side so Python gets a stable local path
const tempPath = await downloadRemoteImage(img);
filePaths.push(tempPath);
localTempFiles.push(tempPath);
} else {
filePaths.push(img);
}
}
// Write JSON payload
await fs.writeFile(tempFilePath, JSON.stringify({ urls: filePaths, caption }, null, 2), 'utf-8');
// Run Python CLI uploader
let pythonCmd = 'python';
if (fsSync.existsSync(PYTHON_EXE)) {
pythonCmd = PYTHON_EXE;
}
console.log(`[post] Spawning python process inside: ${INSTAGRAM_CWD}`);
console.log(`[post] Command: ${pythonCmd} cli.py --json ${tempFilePath}`);
const { stdout, stderr } = await execPromise(`"${pythonCmd}" cli.py --json "${tempFilePath}"`, {
cwd: INSTAGRAM_CWD,
env: { ...process.env }
});
const stdoutStr = stdout.toString();
const stderrStr = stderr.toString();
console.log(`[post] stdout:\n${stdoutStr}`);
if (stderrStr.trim()) {
console.error(`[post] stderr:\n${stderrStr}`);
}
// Find the JSON block printed by cli.py
const jsonMarker = '--- JSON Output ---';
const jsonIndex = stdoutStr.indexOf(jsonMarker);
if (jsonIndex === -1) {
throw new Error(`Uploader CLI did not return structured output. Details:\n${stdoutStr}\n${stderrStr}`);
}
const jsonPart = stdoutStr.substring(jsonIndex + jsonMarker.length).trim();
const result = JSON.parse(jsonPart);
const type = finalImages.length === 1 ? 'single' : 'carousel';
const entry = {
id: randomUUID(),
posted_at: new Date().toISOString(),
instagram_post_id: result.media_id,
type: type,
images: finalImages.map(img => (img.startsWith('data:image/') || img.includes(';base64,')) ? '[Local File]' : img),
caption,
};
await appendHistory(entry);
console.log(
`[post] type=${type} ig_post_id=${result.media_id} elapsed_ms=${Date.now() - startedAt}`
);
res.json({
success: true,
post_id: result.media_id,
type: type,
post_url: result.post_url
});
} catch (err) {
console.error('[post] Upload failed with error:', err);
res.status(500).json({ success: false, error: err.message || 'Internal uploader error' });
} finally {
// Clean up temporary JSON file
try {
if (fsSync.existsSync(tempFilePath)) {
await fs.unlink(tempFilePath);
}
} catch (cleanupErr) {
console.error(`[post] Failed to clean up temp request file: ${cleanupErr.message}`);
}
// Clean up temporary decoded base64 image files
for (const tempPath of localTempFiles) {
try {
if (fsSync.existsSync(tempPath)) {
await fs.unlink(tempPath);
console.log(`[post] Cleaned up temporary local image: ${tempPath}`);
}
} catch (cleanupErr) {
console.error(`[post] Failed to clean up temporary local image: ${cleanupErr.message}`);
}
}
}
});
app.listen(PORT, () => {
console.log(`FashionAI server running at http://localhost:${PORT}`);
});