This commit is contained in:
kim committed 2026-04-29 17:34:36 +09:00
1 parent ee10549c5a
commit 4324985508
5 files changed
+108 -45

No files matched your search

Binary file not shown.
+46 -14
View File
@@ -355,30 +355,33 @@ def fit_dimensions(img_w, img_h, max_w, max_h, mode="contain"):
def _ensure_compatible_image(image_path: str) -> str:
"""Convert WebP or other unsupported formats to PNG for python-pptx compatibility.
"""Convert unsupported image formats to PNG for python-pptx compatibility.
python-pptx relies on PIL for image analysis, and PowerPoint/OOXML does not
reliably support WebP. Converting to PNG before embedding avoids silent failures.
PowerPoint only supports JPEG, PNG, GIF, BMP, TIFF, EMF, WMF.
AVIF, WebP, and other formats must be converted. We check the actual
format via PIL rather than trusting the file extension, since downloaded
images often have mismatched extensions (e.g. AVIF data saved as .jpg).
"""
ext = os.path.splitext(image_path)[1].lower()
supported = {'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff', '.emf', '.wmf'}
if ext in supported:
return image_path
# Formats that PowerPoint can embed directly
PPTX_SUPPORTED = {'JPEG', 'PNG', 'GIF', 'BMP', 'TIFF'}
# Attempt PIL conversion to PNG
try:
from PIL import Image as PILImage
with PILImage.open(image_path) as img:
# RGBA or P mode can cause issues with some PowerPoint viewers; convert to RGB
actual_format = img.format # e.g. 'AVIF', 'WEBP', 'JPEG', 'PNG'
if actual_format and actual_format.upper() in PPTX_SUPPORTED:
return image_path
# Unsupported format (AVIF, WEBP, etc.) — convert to PNG
if img.mode in ('RGBA', 'P', 'LA', 'L'):
rgb_img = img.convert('RGB')
else:
rgb_img = img
new_path = image_path + '.converted.png'
rgb_img.save(new_path, 'PNG')
print(f"[pptx_gen] Converted {actual_format} image to PNG: {os.path.basename(image_path)} -> {os.path.basename(new_path)}", file=sys.stderr, flush=True)
return new_path
except Exception:
# If conversion fails, return original and let downstream handle the failure
# PIL can't open it — return as-is and let downstream handle the failure
return image_path
@@ -392,18 +395,23 @@ def add_image_or_placeholder(slide, image_path, left, top, max_width, max_height
"""
if os.path.exists(image_path):
converted_path = _ensure_compatible_image(image_path)
print(f"[pptx_gen] add_image: {os.path.basename(image_path)} exists, converted={os.path.basename(converted_path) if converted_path != image_path else 'same'}", file=sys.stderr, flush=True)
try:
# Read native dimensions and compute aspect-ratio-preserving size
from PIL import Image as PILImage
with PILImage.open(converted_path) as img:
img_w, img_h = img.size
img_fmt = getattr(img, 'format', 'unknown')
print(f"[pptx_gen] add_image: {img_fmt} {img_w}x{img_h} -> fit_mode={fit_mode}", file=sys.stderr, flush=True)
fit_w, fit_h = fit_dimensions(img_w, img_h, max_width, max_height, mode=fit_mode)
# Center within the bounding box both horizontally and vertically
center_x = left + (max_width - fit_w) / 2
center_y = top + (max_height - fit_h) / 2
slide.shapes.add_picture(converted_path, center_x, center_y, fit_w, fit_h)
print(f"[pptx_gen] add_image: OK, embedded at ({int(center_x)},{int(center_y)})", file=sys.stderr, flush=True)
return
except Exception:
except Exception as e:
print(f"[pptx_gen] add_image: FAILED to embed {os.path.basename(image_path)}: {e}", file=sys.stderr, flush=True)
# If image dimension reading fails, try with native size (no stretching)
try:
pic = slide.shapes.add_picture(converted_path, left, top)
@@ -423,9 +431,13 @@ def add_image_or_placeholder(slide, image_path, left, top, max_width, max_height
center_y = top + (max_height - native_h) / 2
pic.left = int(center_x)
pic.top = int(center_y)
print(f"[pptx_gen] add_image: fallback native size OK", file=sys.stderr, flush=True)
return
except Exception:
except Exception as e2:
print(f"[pptx_gen] add_image: fallback also FAILED: {e2}", file=sys.stderr, flush=True)
pass
else:
print(f"[pptx_gen] add_image: file NOT FOUND: {image_path}", file=sys.stderr, flush=True)
# Draw a subtle gray placeholder instead of red error text
add_shape_rect(slide, left, top, max_width, max_height, "E8E8E8")
warnings.append(f"Image missing or unsupported: {image_path}")
@@ -434,20 +446,28 @@ def add_image_or_placeholder(slide, image_path, left, top, max_width, max_height
def resolve_image_path(image_path: str, project_dir: str, workspace_path: str) -> str:
"""Resolve image path: check absolute, then project_dir, then workspace, then search by filename."""
if os.path.isabs(image_path):
return image_path
if os.path.exists(image_path):
print(f"[pptx_gen] resolve_image_path: {image_path} (absolute, exists)", file=sys.stderr, flush=True)
return image_path
else:
print(f"[pptx_gen] resolve_image_path: {image_path} (absolute, NOT FOUND)", file=sys.stderr, flush=True)
candidates = [
os.path.join(project_dir, image_path),
os.path.join(workspace_path, image_path),
]
for c in candidates:
if os.path.exists(c):
print(f"[pptx_gen] resolve_image_path: {image_path} -> {c} (found)", file=sys.stderr, flush=True)
return c
# Fallback: search by filename in all subdirectories
basename = os.path.basename(image_path).lower()
for root, dirs, files in os.walk(workspace_path):
for f in files:
if f.lower() == basename:
return os.path.join(root, f)
resolved = os.path.join(root, f)
print(f"[pptx_gen] resolve_image_path: {image_path} -> {resolved} (found by filename search)", file=sys.stderr, flush=True)
return resolved
print(f"[pptx_gen] resolve_image_path: {image_path} NOT FOUND in {project_dir} or {workspace_path}", file=sys.stderr, flush=True)
return candidates[0] # return first even if missing (placeholder will show)
@@ -820,6 +840,9 @@ def generate(spec: dict, workspace_path: str) -> dict:
theme = spec.get("theme") or "light"
is_dark = theme == "dark"
print(f"[pptx_gen] generate: title='{title}' slug='{project_slug}' slides={len(slides_spec)}", file=sys.stderr, flush=True)
print(f"[pptx_gen] generate: workspace='{workspace_path}' theme='{theme}'", file=sys.stderr, flush=True)
if not slides_spec:
return {"success": False, "error": "spec.slides must be a non-empty array"}
@@ -833,6 +856,15 @@ def generate(spec: dict, workspace_path: str) -> dict:
project_dir = os.path.join(workspace_path, project_slug)
os.makedirs(project_dir, exist_ok=True)
print(f"[pptx_gen] generate: project_dir='{project_dir}'", file=sys.stderr, flush=True)
# Log slide specs with image info before processing
for i, s in enumerate(slides_spec):
ip = s.get("image_path")
iu = s.get("image_url")
if ip or iu:
print(f"[pptx_gen] slide {i+1}: type={s.get('type','?')} image_path='{ip}' image_url='{iu[:60] if iu else ''}'", file=sys.stderr, flush=True)
# Download image_url slides into project_dir
_download_images(slides_spec, project_dir, warnings)
+12 -10
View File
@@ -1569,7 +1569,7 @@ function buildTools() {
type: 'function',
function: {
name: 'create_presentation',
description: 'Generate a PowerPoint (.pptx) file. Creates a project folder named after the title. Use image_url on slides to auto-download images into the project folder. Put ALL slides in a single call — never create multiple presentations for the same topic. Missing images become red placeholders. NEVER write Python scripts to create PPTX — use this tool instead.',
description: 'Generate a PowerPoint (.pptx) file. Creates a project folder named after the title. Use image_search on slides to find images by keyword (e.g. "golden retriever", "mountain sunset"). Use image_url for direct image URLs. For very long presentations (10+ slides), consider splitting across multiple calls using edit_presentation. NEVER write Python scripts to create PPTX — use this tool instead.',
parameters: {
type: 'object',
required: ['spec'],
@@ -1584,7 +1584,7 @@ function buildTools() {
font_sizes: { type: 'object', description: 'Override default font sizes (pt). Keys: title(36), subtitle(18), slide_title(24), body(16), bullets(16), section(32), image_title(22)' },
slides: {
type: 'array',
description: 'Array of slide specifications',
description: 'Array of slide specifications (max 6 recommended)',
items: {
type: 'object',
properties: {
@@ -1596,9 +1596,10 @@ function buildTools() {
body: { type: 'string', description: 'Body text (alternative to bullets)' },
content: { type: 'string', description: 'Body text (alias for body — use either)' },
font_size: { type: 'number', description: 'Per-slide body/bullet font size override (pt)' },
image_path: { type: 'string', description: 'Image path relative to project folder (e.g. "photo.jpg"). Missing images become red placeholders.' },
image_url: { type: 'string', description: 'Auto-download this image URL into the project folder. Overrides image_path if both provided. Supports http/https URLs.' },
background: { type: 'string', description: 'Template background name' },
image_path: { type: 'string', description: 'Image file path relative to project folder (e.g. "photo.jpg"). Missing images become light-gray placeholders.' },
image_url: { type: 'string', description: 'Auto-download this image URL. Overrides image_path.' },
image_search: { type: 'string', description: 'Search keyword to auto-find an image (e.g. "cute dog", "sunset"). Overrides image_url. Best way to add images!' },
background: { type: 'string', description: 'Template background name or image file path' },
notes: { type: 'string', description: 'Speaker notes' },
},
},
@@ -1614,7 +1615,7 @@ function buildTools() {
type: 'function',
function: {
name: 'edit_presentation',
description: 'Append slides to an existing PowerPoint (.pptx) file. Provide the path to the existing .pptx and the new slides to add. Use image_url on new slides to auto-download images.',
description: 'Append slides to an existing .pptx file. Use image_search on slides to auto-find images by keyword. For very long additions (10+ slides), consider splitting across multiple calls.',
parameters: {
type: 'object',
required: ['path', 'spec'],
@@ -1627,7 +1628,7 @@ function buildTools() {
font_sizes: { type: 'object', description: 'Override default font sizes (pt). Keys: title(36), subtitle(18), slide_title(24), body(16), bullets(16), section(32), image_title(22)' },
slides: {
type: 'array',
description: 'Array of slide specifications to append',
description: 'Array of slide specifications to append (max 6 recommended)',
items: {
type: 'object',
properties: {
@@ -1639,9 +1640,10 @@ function buildTools() {
body: { type: 'string', description: 'Body text (alternative to bullets)' },
content: { type: 'string', description: 'Body text (alias for body — use either)' },
font_size: { type: 'number', description: 'Per-slide body/bullet font size override (pt)' },
image_path: { type: 'string', description: 'Image path relative to project folder. Missing images become red placeholders.' },
image_url: { type: 'string', description: 'Auto-download this image URL into the project folder. Overrides image_path if both provided. Supports http/https URLs.' },
background: { type: 'string', description: 'Template background name' },
image_path: { type: 'string', description: 'Image file path relative to project folder. Missing images become light-gray placeholders.' },
image_url: { type: 'string', description: 'Auto-download this image URL. Overrides image_path.' },
image_search: { type: 'string', description: 'Search keyword to auto-find an image (e.g. "cute dog", "sunset"). Overrides image_url. Best way to add images!' },
background: { type: 'string', description: 'Template background name or image file path' },
notes: { type: 'string', description: 'Speaker notes' },
},
},
+48 -10
View File
@@ -131,6 +131,12 @@ async function generateWithPython(spec: PresentationSpec, workspacePath: string)
try {
// Write spec to temp file
fs.writeFileSync(tmpSpecPath, JSON.stringify(spec), 'utf-8');
console.log(`[pptx] generateWithPython: workspace=${workspacePath} slides=${spec.slides.length} title="${spec.title}"`);
for (const [i, s] of spec.slides.entries()) {
if (s.image_path || s.image_url) {
console.log(`[pptx] generateWithPython: slide ${i + 1} type=${s.type} image_path="${s.image_path}" image_url="${s.image_url?.slice(0, 60) || ''}"`);
}
}
const result = await new Promise<{ success: boolean; path?: string; folder?: string; filename?: string; slides?: number; warnings?: string[]; stdout?: string; error?: string; download_url?: string; preview_url?: string }>((resolve, reject) => {
const pythonCmd = process.platform === 'win32' ? 'python' : 'python3';
@@ -142,7 +148,7 @@ async function generateWithPython(spec: PresentationSpec, workspacePath: string)
env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
}, (err, stdout, stderr) => {
if (stderr) {
console.error(`[pptx] Python stderr: ${stderr.slice(0, 800)}`);
console.error(`[pptx] Python stderr: ${stderr.slice(0, 3000)}`);
}
if (err) {
console.error(`[pptx] Python process failed: ${err.message}`);
@@ -230,7 +236,8 @@ async function downloadImageByUrl(url: string, dest: string): Promise<boolean> {
const resp = await fetch(url, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Accept': 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
// Prefer JPEG/PNG over WebP/AVIF — PowerPoint doesn't support WebP/AVIF
'Accept': 'image/jpeg,image/png,image/gif,image/*,*/*;q=0.8',
'Sec-Fetch-Dest': 'image',
'Sec-Fetch-Mode': 'no-cors',
'Sec-Fetch-Site': 'cross-site',
@@ -239,12 +246,28 @@ async function downloadImageByUrl(url: string, dest: string): Promise<boolean> {
signal: controller.signal,
});
clearTimeout(timeout);
if (!resp.ok) return false;
if (!resp.ok) {
console.log(`[pptx] downloadImageByUrl: HTTP ${resp.status} for ${url.slice(0, 80)}`);
return false;
}
const buffer = Buffer.from(await resp.arrayBuffer());
if (buffer.length < 100) return false;
if (buffer.length < 100) {
console.log(`[pptx] downloadImageByUrl: too small (${buffer.length} bytes) for ${url.slice(0, 80)}`);
return false;
}
const ct = resp.headers.get('content-type') || '';
// Detect actual format from magic bytes
let actualFmt = 'unknown';
if (buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[2] === 0xFF) actualFmt = 'jpeg';
else if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47) actualFmt = 'png';
else if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46) actualFmt = 'gif';
else if (buffer.length > 8 && buffer.slice(4, 12).toString('ascii') === 'ftypavif') actualFmt = 'avif';
else if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46) actualFmt = 'webp';
console.log(`[pptx] downloadImageByUrl: ${buffer.length} bytes, ct="${ct}", magic=${actualFmt}, dest=${path.basename(dest)}`);
fs.writeFileSync(dest, buffer);
return true;
} catch {
} catch (e: any) {
console.log(`[pptx] downloadImageByUrl: failed: ${e.message} for ${url.slice(0, 80)}`);
return false;
}
}
@@ -338,6 +361,7 @@ const FREE_IMAGE_APIS = [
];
async function searchAndDownloadImage(query: string, projectDir: string, slideIndex: number, sendSSE?: SSESender): Promise<string | null> {
console.log(`[pptx] searchAndDownloadImage: slide ${slideIndex + 1}, query="${query}", dir=${projectDir}`);
sendSSE?.('info', { message: `🖼 Slide ${slideIndex + 1}: searching for "${query}"...` });
// Strategy 1: Browser search (most reliable — handles JS, anti-bot, etc.)
@@ -348,10 +372,11 @@ async function searchAndDownloadImage(query: string, projectDir: string, slideIn
const dest = path.join(projectDir, fname);
sendSSE?.('info', { message: `📥 Slide ${slideIndex + 1}: downloading from browser result...` });
if (await downloadImageByUrl(browserUrl, dest)) {
console.log(`[pptx] Downloaded browser image for slide ${slideIndex + 1}: ${browserUrl.slice(0, 80)}`);
console.log(`[pptx] searchAndDownloadImage: slide ${slideIndex + 1} browser OK, fname=${fname}`);
sendSSE?.('info', { message: `✅ Slide ${slideIndex + 1}: image downloaded (browser)` });
return fname;
}
console.log(`[pptx] searchAndDownloadImage: slide ${slideIndex + 1} browser download failed`);
sendSSE?.('info', { message: `⚠️ Slide ${slideIndex + 1}: browser download failed, trying API...` });
}
@@ -364,10 +389,11 @@ async function searchAndDownloadImage(query: string, projectDir: string, slideIn
const fname = `slide${slideIndex + 1}_image.jpg`;
const dest = path.join(projectDir, fname);
if (await downloadImageByUrl(url, dest)) {
console.log(`[pptx] Downloaded picsum image for slide ${slideIndex + 1}`);
console.log(`[pptx] searchAndDownloadImage: slide ${slideIndex + 1} picsum OK`);
sendSSE?.('info', { message: `✅ Slide ${slideIndex + 1}: image downloaded (picsum)` });
return fname;
}
console.log(`[pptx] searchAndDownloadImage: slide ${slideIndex + 1} picsum failed`);
sendSSE?.('info', { message: `⚠️ Slide ${slideIndex + 1}: picsum download failed` });
continue;
}
@@ -397,10 +423,11 @@ async function searchAndDownloadImage(query: string, projectDir: string, slideIn
const dest = path.join(projectDir, fname);
sendSSE?.('info', { message: `📥 Slide ${slideIndex + 1}: downloading from ${api.name}...` });
if (await downloadImageByUrl(imageUrl, dest)) {
console.log(`[pptx] Downloaded ${api.name} image for slide ${slideIndex + 1}`);
console.log(`[pptx] searchAndDownloadImage: slide ${slideIndex + 1} ${api.name} OK, fname=${fname}`);
sendSSE?.('info', { message: `✅ Slide ${slideIndex + 1}: image downloaded (${api.name})` });
return fname;
}
console.log(`[pptx] searchAndDownloadImage: slide ${slideIndex + 1} ${api.name} download failed`);
sendSSE?.('info', { message: `⚠️ Slide ${slideIndex + 1}: ${api.name} download failed` });
} catch (e: any) {
console.log(`[pptx] ${api.name} search failed for "${query}": ${e.message}`);
@@ -438,7 +465,7 @@ interface PresentationSpec {
export const pptxTool: import('./registry.js').Tool = {
name: 'create_presentation',
description: 'Generate a PowerPoint (.pptx) file with slides. Use image_search on slides to auto-find images by keyword (e.g. "golden retriever"). Use image_url for direct URLs. Keep slides to 6 or fewer per call. NEVER write Python scripts to create PPTX. Missing images become light-gray placeholders.',
description: 'Generate a PowerPoint (.pptx) file with slides. Use image_search on slides to auto-find images by keyword (e.g. "golden retriever"). Use image_url for direct URLs. For very long presentations (10+ slides), consider splitting across multiple calls using edit_presentation. NEVER write Python scripts to create PPTX. Missing images become light-gray placeholders.',
schema: {
spec: 'JSON object: { filename, title, template, theme, font_sizes, slides: [{ type, title, subtitle, bullets, body, content, font_size, image_path, image_url, image_search, background, template }] }',
},
@@ -515,6 +542,7 @@ export const pptxTool: import('./registry.js').Tool = {
if (slidesNeedingImages.length > 0) {
const projectSlug = (spec.title || 'presentation').replace(/[^a-zA-Z0-9가-힣_\-]/g, '_').toLowerCase().slice(0, 60);
const projectDir = path.join(workspacePath, projectSlug);
console.log(`[pptx] image_search: resolving ${slidesNeedingImages.length} slides, projectDir=${projectDir}`);
if (!fs.existsSync(projectDir)) {
fs.mkdirSync(projectDir, { recursive: true });
}
@@ -523,20 +551,30 @@ export const pptxTool: import('./registry.js').Tool = {
const idx = spec.slides.indexOf(slide);
const sendSSE = (args as any)?._sendSSE as SSESender | undefined;
const localPath = await searchAndDownloadImage(slide.image_search, projectDir, idx, sendSSE);
console.log(`[pptx] image_search: slide ${idx + 1} keyword="${slide.image_search}" -> localPath="${localPath}"`);
if (localPath) {
const fullPath = path.join(projectDir, localPath);
console.log(`[pptx] image_search: file exists=${fs.existsSync(fullPath)} size=${fs.statSync(fullPath).size} at ${fullPath}`);
slide.image_path = localPath;
}
delete slide.image_search;
}
}
// Debug: log final slide specs for image slides
for (const [i, s] of spec.slides.entries()) {
if (s.image_path || s.image_url || s.image_search) {
console.log(`[pptx] slide ${i + 1}: type=${s.type} image_path="${s.image_path}" image_url="${s.image_url}"`);
}
}
return await generateWithPython(spec, workspacePath);
},
};
export const editPptxTool: import('./registry.js').Tool = {
name: 'edit_presentation',
description: 'Append slides to an existing .pptx file. Provide the path and new slides. Use image_search to auto-find images. Keep slides to 6 or fewer per call.',
description: 'Append slides to an existing .pptx file. Provide the path and new slides. Use image_search to auto-find images. For very long additions (10+ slides), consider splitting across multiple calls.',
schema: {
path: 'Path to existing .pptx file (relative to workspace or absolute)',
spec: 'JSON object: { slides: [{ type, title, subtitle, bullets, body, content, font_size, image_path, image_url, image_search, background, template }] }',
+2 -11
View File
@@ -4166,7 +4166,7 @@ function renderFileDownloads(steps, processEntries) {
return urls;
}
// Collect /api/files/ URLs from all available sources
// Collect /api/files/ URLs from this message's own data only (not global log)
const allUrls = [];
// 1. msg.steps (legacy step events)
@@ -4185,16 +4185,7 @@ function renderFileDownloads(steps, processEntries) {
}
}
// 3. Global processLogEntries (current session's live log)
try {
const entries = (typeof processLogEntries !== 'undefined' && Array.isArray(processLogEntries)) ? processLogEntries : [];
for (const e of entries) {
const txt = String(e.content || '');
if (txt.indexOf('/api/files/') !== -1) allUrls.push(...extractUrls(txt));
}
} catch {}
// 4. msg.content itself (LLM may include the link in its reply)
// 3. msg.content itself (LLM may include the link in its reply)
if (arguments.length > 2 && arguments[2]) {
const contentText = String(arguments[2]);
if (contentText.indexOf('/api/files/') !== -1) allUrls.push(...extractUrls(contentText));