Release 2.8.1: pptx-wizard slide editor + fixes

- Fix pptx-wizard slide editor modal opening off-screen (header clipped)
  when a saved drag position is restored on a fresh page load: clear the
  CSS centering transform and clamp coordinates into the viewport.
- Add pptx-wizard.html and python-runner.html web UIs.
- Bump version to 2.8.1.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Opus 4.8 committed 2026-05-30 20:14:01 +09:00
1 parent 22bfc3ac27
commit 957a13f98c
17 files changed
+4867 -103

No files matched your search

+3 -4
View File
@@ -107,7 +107,7 @@
"ppt": {
"engine": "python",
"template": "business",
"skin": "coral",
"skin": "cream",
"unsplash_key": "env:UNSPLASH_ACCESS_KEY",
"pexels_key": "env:PEXELS_API_KEY",
"pixabay_key": ""
@@ -169,7 +169,7 @@
}
},
"orchestration": {
"enabled": true,
"enabled": false,
"secondary": {
"provider": "ollama",
"model": "mistral-large-3:675b-cloud"
@@ -217,8 +217,7 @@
"max_preempts_per_turn": 1,
"max_preempts_per_session": 3,
"restart_mode": "detached_hidden"
},
"subagent_mode": false
}
},
"hooks": {
"enabled": false,
+113 -10
View File
@@ -172,6 +172,54 @@ model: mistral-large-3:675b-cloud
---
### 이미지 효과 (`img_filter`)
슬라이드 이미지에 Pillow 기반 효과를 적용할 수 있습니다. `img_filter` 파라미터를 슬라이드 spec에 추가하세요.
| `img_filter` | 효과 | 추가 파라미터 |
|---|---|---|
| `"grayscale"` | 흑백 변환 | — |
| `"blur"` | 가우시안 블러 | `img_blur_radius` (기본: 5, 범위: 1–20) |
| `"contrast"` | 대비 강화 (1.6×) + 채도 증가 (1.2×) | — |
| `"bright"` | 밝게 (1.4×) | — |
| `"round"` | 둥근 모서리 (투명 배경) | `img_corner_radius` (기본: 15%, 범위: 5–50%) |
| `"none"` | 효과 없음 (기본값) | — |
```json
{
"type": "content",
"title": "과거의 기술",
"image_search": "vintage camera",
"img_filter": "grayscale"
}
```
```json
{
"type": "content",
"title": "포커스 아웃 효과",
"image_search": "city skyline",
"img_filter": "blur",
"img_blur_radius": 8
}
```
```json
{
"type": "image",
"title": "프로필",
"image_search": "professional portrait",
"img_filter": "round",
"img_corner_radius": 30
}
```
- 효과는 이미지가 PPTX에 삽입되기 전 Pillow로 처리됩니다
- `img_filter` 없으면 원본 이미지 그대로 사용
- `layout: "fullscreen"` + `"blur"` 조합으로 배경 블러 효과 가능
---
### image_search 활용 팁
- 영어 키워드가 더 좋은 결과: `"business meeting"` > `"비즈니스 미팅"`
@@ -234,29 +282,42 @@ model: mistral-large-3:675b-cloud
PDF 논문을 슬라이드로 만들 때 반드시 아래 순서를 따르세요.
**0단계: PDF 파일 위치 확인** ← 반드시 먼저 실행
```
list_files("pubmed") → pubmed_fulltext로 받은 PDF (pubmed/<PMCID>.pdf)
list_files("uploads") → 사용자가 업로드한 PDF (uploads/<filename>.pdf)
```
- PDF가 없으면 `pubmed_fulltext(pmcid, format:"pdf")` → `pubmed/<PMCID>.pdf`에 저장됨
- **절대 경로를 추측하지 말 것 — list_files 결과에서 확인한 경로만 사용**
**1단계: 텍스트 추출**
```
pdf_read(path) → 논문 내용 파악
```
**2단계: figure 추출 + 필터링** ← 반드시 실행
**2단계: figure 추출** ← 반드시 실행
```
pdf_extract_images(path, mode:"figures") → figure_* 경로 수집
→ 바로 python_eval로 필터링:
pdf_extract_images(path, mode:"figures", out_dir:"uploads/<basename>_images")
```
- `path`: 0단계에서 확인한 정확한 경로 (예: `"uploads/sinus_lift_pmc8273047.pdf"`)
- `out_dir`: 반드시 `"uploads/<basename>_images"` 형식 사용 (예: `"uploads/sinus_lift_pmc8273047_images"`)
- 반환값 예시: `[figure_p04_1.png](/api/files/uploads/sinus_lift_pmc8273047_images/figure_p04_1.png)`
추출 후 python_eval로 소형 이미지 필터링:
```python
from PIL import Image; import os
img_dir = "/abs/path/to/uploads/sinus_lift_pmc8273047_images"
figs = []
for f in sorted(os.listdir("<abs_img_dir>")):
for f in sorted(os.listdir(img_dir)):
if not f.startswith("figure_"): continue
try:
w, h = Image.open(os.path.join("<abs_img_dir>", f)).size
if w < 250 or h < 200: continue # 수식·헤더 등 소형 제거
if h > 0 and w / h > 8: continue # 가로 길쭉한 수식 줄 제거
w, h = Image.open(os.path.join(img_dir, f)).size
if w < 250 or h < 200: continue
if h > 0 and w / h > 8: continue
figs.append(f)
except: pass
print(figs)
```
→ **필터 통과한 figure_* 파일만** 슬라이드에 사용. 미통과 파일 사용 금지.
**3단계: 도표(표) 추출**
```
@@ -265,8 +326,50 @@ pdf_extract_tables(path) → 마크다운 표로 반환
→ 수치 데이터는 type:"chart" 슬라이드로 시각화
```
**4단계: 슬라이드 작성 규칙**
- `image_url` = pdf_extract_images가 반환한 **정확한 워크스페이스 상대 경로** 사용 (폴더 포함)
**4단계: 아웃라인 출력 (PPTX 워크플로 모드)**
메시지에 `[PPTX 워크플로 시작]`이 포함된 경우 **create_presentation을 즉시 호출하지 말고** 아래처럼 아웃라인을 먼저 출력하세요:
```pptx-outline
{
"project": "주제_폴더명",
"template": "dark",
"slides": [
{"type": "title", "title": "슬라이드 제목", "subtitle": "부제목"},
{"type": "section", "title": "섹션명"},
{"type": "content", "title": "슬라이드 제목", "bullets": ["항목1", "항목2"], "image_url": "/api/files/..."},
{"type": "table", "title": "표 제목", "headers": ["열1","열2"], "rows": [["값1","값2"]]},
{"type": "chart", "title": "차트 제목", "chart_type": "column", "categories": [], "series": []}
]
}
```
- `image_url`은 pdf_extract_images 반환값의 `/api/files/...` URL 그대로 사용
- 아웃라인 출력 후 **"아웃라인을 확인해주세요. 수정이 필요하면 알려주시고, 그대로 생성하시려면 '생성' 버튼을 클릭하거나 '확인'이라고 말씀해주세요."** 라고 안내 후 대기
- 사용자가 "확인" / "생성" / "네" 라고 하면 그때 create_presentation 호출
**[필수] source_files — PDF 논문과 추출 이미지를 프로젝트 폴더에 함께 저장**
PDF 논문으로 PPTX를 만들 때 **반드시** `spec.source_files`에 사용한 파일 목록을 포함하세요.
그러면 원본 PDF와 추출 이미지 폴더가 PPTX 프로젝트 폴더에 자동 복사됩니다.
```json
{
"source_files": [
"pubmed/PMC8940982.pdf",
"uploads/PMC8940982_images"
]
}
```
- PDF 파일: `pubmed/<PMCID>.pdf` 또는 `uploads/<filename>.pdf` (0단계에서 확인한 경로)
- 이미지 폴더: `uploads/<basename>_images` (pdf_extract_images의 out_dir)
- 여러 논문을 사용한 경우 모두 포함 (`"pubmed/A.pdf"`, `"pubmed/B.pdf"`, ...)
**일반 모드 (워크플로 없이 직접 요청 시)**
- `image_url` = pdf_extract_images 반환값의 **`/api/files/...` URL을 그대로** 사용
- ✅ 올바른 예: `"image_url": "/api/files/uploads/sinus_lift_pmc8273047_images/figure_p04_1.png"`
- ❌ 잘못된 예: 경로 직접 조합, `상악동 거상술 최신 동향/...` 같은 프로젝트 폴더 경로 사용
- `image_path` 대신 반드시 `image_url` 사용
- 표 데이터는 figure 이미지 대신 `type:"table"` 슬라이드로
- figure가 명백히 수식·다이어그램·OUTPUT 박스인 경우 → `image_search`로 임상 사진 대체
+1 -1
View File
@@ -1,5 +1,5 @@
{
"multi-agent-orchestrator": true,
"multi-agent-orchestrator": false,
"lawyer": false,
"psychiatrist": false,
"musician": false,
@@ -11,7 +11,7 @@
- Language: Match user's language every message.
## identity
- Name: 딸랑이 (assigned 2026-05-09)
- Name: (not yet assigned)
- "I am SmallClaw, your local AI assistant."
## limits
@@ -11,18 +11,8 @@
- Stack: TypeScript / Node.js
- Version control: Git
- Name: Papa [2026-05-04]
## task
- python-pptx library installed (v1.0.2) for creating PowerPoint presentations [2026-04-25]
## goal
## api_keys
- PubMed (NCBI) API Key: 8640a3585292307d30ebe2a5325ad6dce908 [2026-05-01]
---
*No other categories yet — SmallClaw will add them as it learns more.*
*No other categories yet — SmallClaw will add them as it learns more.*
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "smallclaw",
"version": "2.8.0",
"version": "2.8.1",
"description": "Local AI agent framework powered by Ollama - OpenClaw alternative",
"main": "dist/index.js",
"bin": {
+275 -39
View File
@@ -51,6 +51,9 @@ from pptx import Presentation
from pptx.util import Inches, Pt, Emu
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN, MSO_ANCHOR, MSO_AUTO_SIZE
from pptx.oxml.ns import qn
from pptx.oxml import parse_xml
from lxml import etree
# ─── Paths ──────────────────────────────────────────────────────────────────────
@@ -109,6 +112,7 @@ DARK_SKINS = {
'Cave', 'Deep Sea', 'Dream', 'Galaxy', 'Imagination', 'Metal', 'Space', 'Universe',
'charcoal', 'midnight', 'ocean', 'sunset', 'forest_green', 'mint',
'navy', 'slate', 'burgundy', 'moss', 'plum', 'deep_red',
'teal', 'emerald', # luminance <140 → JS detects dark but were missing here
'Skin_film', 'Skin_theater',
'Skin_slate', 'Skin_navy', 'Skin_burgundy', 'Skin_moss', 'Skin_plum', 'Skin_deep_red',
}
@@ -228,6 +232,76 @@ def is_dark_skin(name):
# ─── Helpers ────────────────────────────────────────────────────────────────────
def clean_text(text) -> str:
"""Remove control characters / OOXML escape artifacts from text.
Handles two cases:
1. Actual control chars (U+000B etc.) → space or stripped
2. Literal '_x000B_' strings from PDF extraction → stripped
"""
if not isinstance(text, str):
text = str(text) if text is not None else ""
# Strip literal OOXML hex-escape patterns like _x000B_, _x000D_, _x000A_ etc.
# Also catch fragments like x000B_ (missing leading _ after prior removal)
text = re.sub(r'_?x[0-9A-Fa-f]{4}_', ' ', text)
# Strip actual control characters
result = []
for ch in text:
cp = ord(ch)
if cp in (0x0B, 0x0C, 0x0D): # VT, FF, CR → space
result.append(' ')
elif cp < 0x20 and cp not in (0x09, 0x0A): # other C0 except HT/LF
pass # strip
elif 0x7F <= cp <= 0x9F: # DEL + C1 controls
pass # strip
else:
result.append(ch)
return re.sub(r' +', ' ', ''.join(result)).strip()
def apply_img_filter(image_path: str, slide_spec: dict) -> str:
"""Apply image filter (blur/grayscale/contrast/bright/round) using Pillow.
Returns the path to the processed image (temp file next to original).
Returns original path if Pillow unavailable or no filter set.
"""
img_filter = slide_spec.get("img_filter") or ""
if not img_filter or img_filter == "none":
return image_path
try:
from PIL import Image, ImageFilter, ImageEnhance, ImageDraw
import tempfile, os as _os
img = Image.open(image_path).convert("RGBA")
if img_filter == "grayscale":
img = img.convert("L").convert("RGBA")
elif img_filter == "blur":
radius = max(1, int(slide_spec.get("img_blur_radius") or 5))
img = img.filter(ImageFilter.GaussianBlur(radius=radius))
elif img_filter == "contrast":
img = ImageEnhance.Contrast(img.convert("RGB")).enhance(1.6)
img = ImageEnhance.Color(img).enhance(1.2)
img = img.convert("RGBA")
elif img_filter == "bright":
img = ImageEnhance.Brightness(img.convert("RGB")).enhance(1.4)
img = img.convert("RGBA")
elif img_filter == "round":
pct = max(5, min(50, int(slide_spec.get("img_corner_radius") or 15)))
radius_px = int(min(img.width, img.height) * pct / 100)
mask = Image.new("L", img.size, 0)
draw = ImageDraw.Draw(mask)
draw.rounded_rectangle([0, 0, img.width - 1, img.height - 1],
radius=radius_px, fill=255)
img.putalpha(mask)
# Save to temp file (PNG to support transparency)
base = _os.path.splitext(image_path)[0]
out_path = base + "_fx.png"
img.save(out_path, "PNG")
return out_path
except Exception as e:
print(f"[pptx_gen] img_filter '{img_filter}' failed: {e}", file=sys.stderr, flush=True)
return image_path
def slugify(text: str) -> str:
"""Convert a title to a safe folder name (matches TypeScript projectSlug logic)."""
s = str(text or "presentation").strip()
@@ -252,19 +326,34 @@ def get_font() -> str:
def add_text_box(slide, left, top, width, height, text, font_size=Pt(16),
color_hex="2D3748", bold=False, alignment=PP_ALIGN.LEFT,
font_name=None):
"""Add a text box with a single paragraph."""
"""Add a text box. Multi-line text (\n) uses <a:br/> for consistent alignment."""
txBox = slide.shapes.add_textbox(left, top, width, height)
tf = txBox.text_frame
tf.word_wrap = True
tf.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE
p = tf.paragraphs[0]
p.alignment = alignment
run = p.add_run()
run.text = text
run.font.size = font_size
run.font.bold = bold
run.font.color.rgb = hex_to_rgb(color_hex)
run.font.name = font_name or get_font()
def _make_run(para, txt):
r = para.add_run()
r.text = txt
r.font.size = font_size
r.font.bold = bold
r.font.color.rgb = hex_to_rgb(color_hex)
r.font.name = font_name or get_font()
return r
lines = text.split('\n')
_make_run(p, lines[0])
for line in lines[1:]:
# <a:br/> keeps the same paragraph (and its alignment) for each visual line
br = etree.SubElement(p._p, qn('a:br'))
rPr = etree.SubElement(br, qn('a:rPr'))
rPr.set('lang', 'ko-KR')
rPr.set('sz', str(int(font_size.pt * 100)))
rPr.set('b', '1' if bold else '0')
rPr.set('dirty', '0')
_make_run(p, line)
return txBox
@@ -276,8 +365,12 @@ def _fit_bullet_font_size(items, width_emu, height_emu, max_pt):
space_after = min(8, max(4, fs // 3))
line_h = fs * 1.35 + space_after
chars_per_line = max(1, int(col_w_pt / (fs * 0.52)))
total = sum(max(1, math.ceil((len(str(it)) + 2) / chars_per_line)) * line_h
for it in items)
# Items may contain \n (soft breaks) — count each visual line separately
total = 0
for it in items:
sub_lines = str(it).split('\n')
for sl in sub_lines:
total += max(1, math.ceil((len(sl) + 2) / chars_per_line)) * line_h
if total <= col_h_pt:
return fs
return 9
@@ -285,15 +378,18 @@ def _fit_bullet_font_size(items, width_emu, height_emu, max_pt):
def add_bullet_list(slide, left, top, width, height, items, font_size=Pt(16),
color_hex="2D3748", bullet_color_hex="1668E3", font_name=None):
"""Add a text box with bullet points."""
"""Add a text box with bullet points. Empty items become line spacers (no bullet)."""
txBox = slide.shapes.add_textbox(left, top, width, height)
tf = txBox.text_frame
tf.word_wrap = True
tf.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE
fitted_pt = _fit_bullet_font_size(items, width, height, font_size.pt)
# Fit font size using only non-empty items
real_items = [it for it in items if str(it).strip()]
fitted_pt = _fit_bullet_font_size(real_items or items, width, height, font_size.pt)
fitted_fs = Pt(fitted_pt)
space_after_pt = min(8, max(4, fitted_pt // 3))
hang_emu = int(min(254000, max(152400, fitted_pt * 12700)))
for i, item in enumerate(items):
if i == 0:
@@ -301,22 +397,76 @@ def add_bullet_list(slide, left, top, width, height, items, font_size=Pt(16),
else:
p = tf.add_paragraph()
is_spacer = not str(item).strip()
if is_spacer:
# 빈 줄 → bullet 없는 spacer 단락
p.space_after = Pt(fitted_pt * 0.6)
pPr = p._p.get_or_add_pPr()
etree.SubElement(pPr, qn('a:buNone'))
r = p.add_run()
r.text = ''
r.font.size = Pt(max(6, fitted_pt // 2))
continue
# Detect sub-bullet: lines starting with "- " or "– " or "— "
raw_text = str(item)
_sub_match = re.match(r'^[-–—]\s+(.*)', raw_text)
is_sub = _sub_match is not None
display_text = _sub_match.group(1) if is_sub else raw_text
# Split display_text by \n for soft line breaks within same bullet
_lines = display_text.split('\n')
p.space_after = Pt(space_after_pt)
p.level = 0
# Add bullet character manually for reliable rendering
bullet_run = p.add_run()
bullet_run.text = "● "
bullet_run.font.size = fitted_fs
bullet_run.font.color.rgb = hex_to_rgb(bullet_color_hex)
bullet_run.font.name = font_name or get_font()
if is_sub:
# Level 1 sub-bullet (○) with larger left margin
p.level = 1
sub_hang = int(min(254000, max(152400, fitted_pt * 12700)))
pPr = p._p.get_or_add_pPr()
pPr.set('marL', str(hang_emu + sub_hang))
pPr.set('indent', str(-sub_hang))
buClr = etree.SubElement(pPr, qn('a:buClr'))
srgbClr = etree.SubElement(buClr, qn('a:srgbClr'))
srgbClr.set('val', bullet_color_hex.upper().replace('#', '').zfill(6))
buChar = etree.SubElement(pPr, qn('a:buChar'))
buChar.set('char', '–')
else:
# Level 0 main bullet (●)
p.level = 0
# Hanging indent: wrapped lines align with text start after bullet
pPr = p._p.get_or_add_pPr()
pPr.set('marL', str(hang_emu))
pPr.set('indent', str(-hang_emu))
# Native PPTX bullet character (color + char)
buClr = etree.SubElement(pPr, qn('a:buClr'))
srgbClr = etree.SubElement(buClr, qn('a:srgbClr'))
srgbClr.set('val', bullet_color_hex.upper().replace('#', '').zfill(6))
buChar = etree.SubElement(pPr, qn('a:buChar'))
buChar.set('char', '●')
# First line as normal run, subsequent lines as <a:br/> soft breaks
text_run = p.add_run()
text_run.text = str(item)
text_run.text = _lines[0]
text_run.font.size = fitted_fs
text_run.font.color.rgb = hex_to_rgb(color_hex)
text_run.font.name = font_name or get_font()
for _ln in _lines[1:]:
br = etree.SubElement(p._p, qn('a:br'))
rPr = etree.SubElement(br, qn('a:rPr'))
rPr.set('lang', 'ko-KR')
rPr.set('sz', str(int(fitted_fs.pt * 100)))
rPr.set('dirty', '0')
text_run = p.add_run()
text_run.text = _ln
text_run.font.size = fitted_fs
text_run.font.color.rgb = hex_to_rgb(color_hex)
text_run.font.name = font_name or get_font()
return txBox
@@ -339,6 +489,11 @@ def set_slide_bg_image(slide, image_path: str):
)
# Tag so pptx_preview.py can distinguish skin backgrounds from content images
pic.name = "background_skin"
# Move to back: add_picture appends to end (top layer) — move behind all content
sp_tree = slide.shapes._spTree
pic_elem = pic._element
sp_tree.remove(pic_elem)
sp_tree.insert(2, pic_elem) # index 2 = after nvGrpSpPr + grpSpPr
def add_shape_rect(slide, left, top, width, height, color_hex: str):
@@ -519,10 +674,18 @@ def _text_weight(slide_spec: dict):
def _auto_text_ratio(slide_spec: dict) -> float:
"""Compute text column share (0–1) based on content volume.
img_scale (20–80) overrides auto: text_ratio = (100 - img_scale) / 100
≤2 bullets / ≤120 chars → 0.32 image-dominant
3–4 bullets / ≤280 chars → 0.44 balanced
5+ bullets / >280 chars → 0.56 text-dominant
"""
img_scale = slide_spec.get("img_scale")
if img_scale is not None:
try:
pct = max(20, min(80, int(img_scale)))
return round((100 - pct) / 100, 2)
except (TypeError, ValueError):
pass
n_bullets, n_chars = _text_weight(slide_spec)
if n_bullets <= 2 and n_chars <= 120:
return 0.32
@@ -544,17 +707,21 @@ def make_title_slide(prs, slide_spec, spec, colors, is_dark, fs, bg_image=None):
elif is_dark:
set_slide_bg(slide, colors["background"])
_title_font = slide_spec.get("_font_override") or None
title = slide_spec.get("title") or spec.get("title") or "Untitled"
title_pt = slide_spec.get("title_size") or fs["title"]
y_pos = Inches(2.8) if bg_image else Inches(2.5)
add_text_box(slide, Inches(0.8), y_pos, Inches(11.7), Inches(1.2),
title, font_size=Pt(fs["title"]), color_hex=colors["title"],
bold=True, alignment=PP_ALIGN.CENTER)
title_lines = len(title.split('\n'))
title_h = Inches(max(1.2, title_lines * title_pt * 1.5 / 72))
add_text_box(slide, Inches(0.8), y_pos, Inches(11.7), title_h,
title, font_size=Pt(title_pt), color_hex=colors["title"],
bold=True, alignment=PP_ALIGN.CENTER, font_name=_title_font)
subtitle = slide_spec.get("subtitle")
if subtitle:
add_text_box(slide, Inches(1.5), y_pos + Inches(1.3), Inches(10.3), Inches(0.7),
add_text_box(slide, Inches(1.5), y_pos + title_h + Inches(0.15), Inches(10.3), Inches(0.7),
subtitle, font_size=Pt(fs["subtitle"]), color_hex=colors["subtitle"],
alignment=PP_ALIGN.CENTER)
alignment=PP_ALIGN.CENTER, font_name=_title_font)
return slide
@@ -594,6 +761,14 @@ def make_content_slide(prs, slide_spec, project_dir, workspace_path, colors, is_
has_title = bool(slide_spec.get("title"))
has_image = bool(slide_spec.get("image_path")) and layout != "text"
_slide_font = slide_spec.get("_font_override") or None
# text_y: 내용 블록 Y 위치 (슬라이드 높이 비율, 0~1). 편집창 드래그로 설정.
_text_y = slide_spec.get("text_y")
if _text_y is not None:
content_y_override = SLIDE_H * float(_text_y)
else:
content_y_override = None
# ── Fullscreen layout: image fills slide, text/title overlaid ─────────────
if layout == "fullscreen" and has_image:
@@ -609,9 +784,10 @@ def make_content_slide(prs, slide_spec, project_dir, workspace_path, colors, is_
bar_shape.fill.fore_color.rgb = hex_to_rgb("000000")
bar_shape.fill.transparency = 0.45
# Title and body overlaid on dark bar
fs_title_pt = slide_spec.get("title_size") or fs["slide_title"]
if has_title:
add_text_box(slide, Inches(0.6), bar_y + Inches(0.15), Inches(12.0), Inches(0.7),
slide_spec["title"], font_size=Pt(fs["slide_title"]),
slide_spec["title"], font_size=Pt(fs_title_pt),
color_hex="FFFFFF", bold=True)
body_text = slide_spec.get("body") or slide_spec.get("content")
bullets = slide_spec.get("bullets") or slide_spec.get("bullet_points")
@@ -622,13 +798,17 @@ def make_content_slide(prs, slide_spec, project_dir, workspace_path, colors, is_
body_text, font_size=Pt(fs["body"]), color_hex="E0E0E0")
return slide
content_y = Inches(1.5) if has_title else Inches(0.5)
if content_y_override is not None:
content_y = content_y_override
else:
content_y = Inches(1.5) if has_title else Inches(0.5)
content_h = SLIDE_H - content_y - Inches(0.4)
slide_title_pt = slide_spec.get("title_size") or fs["slide_title"]
if has_title:
add_text_box(slide, L_MARGIN, Inches(0.4), SLIDE_W - L_MARGIN - R_MARGIN, Inches(0.8),
slide_spec["title"], font_size=Pt(fs["slide_title"]),
color_hex=colors["title"], bold=True)
slide_spec["title"], font_size=Pt(slide_title_pt),
color_hex=colors["title"], bold=True, font_name=_slide_font)
add_shape_rect(slide, L_MARGIN, Inches(1.15), Inches(2), Inches(0.04),
colors["accent"])
@@ -698,17 +878,33 @@ def make_content_slide(prs, slide_spec, project_dir, workspace_path, colors, is_
add_bullet_list(slide, text_col_x, content_y, text_col_w, content_h,
bullet_items, font_size=bullet_fs,
color_hex=colors["body"],
bullet_color_hex=colors["accent"])
bullet_color_hex=colors["accent"],
font_name=_slide_font)
elif body_text:
add_text_box(slide, text_col_x, content_y, text_col_w, content_h,
body_text, font_size=body_fs, color_hex=colors["body"])
body_text, font_size=body_fs, color_hex=colors["body"],
font_name=_slide_font)
# ── Image column ──────────────────────────────────────────────────────────
if has_image and img_col_x is not None:
# ── Image column / free position ─────────────────────────────────────────
if has_image:
resolved = resolve_image_path(slide_spec["image_path"], project_dir, workspace_path)
add_image_or_placeholder(slide, resolved,
img_col_x, content_y, img_col_w, content_h,
warnings, color_hex=colors["body"])
# Free positioning: img_x/img_y/img_w/img_h as fractions (0-1) of slide
fx = slide_spec.get("img_x")
fy = slide_spec.get("img_y")
fw = slide_spec.get("img_w")
fh = slide_spec.get("img_h")
if fx is not None and fy is not None:
abs_x = SLIDE_W * float(fx)
abs_y = SLIDE_H * float(fy)
abs_w = SLIDE_W * float(fw) if fw is not None else img_col_w or SLIDE_W * 0.45
abs_h = SLIDE_H * float(fh) if fh is not None else content_h
add_image_or_placeholder(slide, resolved,
abs_x, abs_y, abs_w, abs_h,
warnings, color_hex=colors["body"])
elif img_col_x is not None:
add_image_or_placeholder(slide, resolved,
img_col_x, content_y, img_col_w, content_h,
warnings, color_hex=colors["body"])
return slide
@@ -1226,22 +1422,33 @@ def generate(spec: dict, workspace_path: str) -> dict:
slide_spec["bullets"] = [str(b) for b in slide_spec["content"]]
slide_spec.pop("content", None)
# 5. Sanitize text fields — remove control chars (VT→space, etc.)
for _tf in ("title", "subtitle", "body", "content", "notes"):
if _tf in slide_spec and slide_spec[_tf]:
slide_spec[_tf] = clean_text(slide_spec[_tf])
if "bullets" in slide_spec and isinstance(slide_spec["bullets"], list):
slide_spec["bullets"] = [clean_text(b) for b in slide_spec["bullets"]]
slide_type = slide_spec.get("type") or "content"
try:
# Resolve background skin/image for this slide
bg_name = slide_spec.get("background") or default_skin or ""
bg_img_path = slide_spec.get("bg_image") or "" # workspace-relative image path
bg_image = None
slide_is_dark = is_dark
if bg_name:
if bg_img_path:
# Explicit image background from editor picker (workspace-relative path)
bg_path, bg_dark = resolve_skin_bg(bg_img_path, project_dir, workspace_path)
if bg_path:
bg_image = bg_path
slide_is_dark = bg_dark or is_dark
elif bg_name:
bg_path, bg_dark = resolve_skin_bg(bg_name, project_dir, workspace_path)
if bg_path:
bg_image = bg_path
slide_is_dark = bg_dark or is_dark
else:
# Not a skin name — might be a file path already resolved
pass
# Inherit background image from existing presentation if none specified
if not bg_image and inherited_bg_image and os.path.exists(inherited_bg_image):
@@ -1256,6 +1463,35 @@ def generate(spec: dict, workspace_path: str) -> dict:
else:
slide_colors = colors
# Apply per-slide custom font / text colors
_title_color = slide_spec.get("title_color") or ""
_body_color = slide_spec.get("body_color") or ""
_font_family = slide_spec.get("font_family") or ""
if _title_color or _body_color or _font_family:
slide_colors = dict(slide_colors) # shallow copy — don't mutate global
if _title_color:
slide_colors["title"] = _title_color.lstrip("#")
slide_colors["subtitle"] = _title_color.lstrip("#")
if _body_color:
slide_colors["body"] = _body_color.lstrip("#")
if _font_family:
slide_spec = dict(slide_spec)
slide_spec["_font_override"] = _font_family
# Apply image filter (blur / grayscale / contrast / round)
_dbg_filter = slide_spec.get("img_filter")
_dbg_ipath = slide_spec.get("image_path")
print(f"[pptx_gen] slide img_filter={_dbg_filter!r} image_path={_dbg_ipath!r}", file=sys.stderr, flush=True)
if _dbg_filter and _dbg_ipath:
_resolved_for_fx = resolve_image_path(slide_spec["image_path"], project_dir, workspace_path)
if os.path.exists(_resolved_for_fx):
_fx_path = apply_img_filter(_resolved_for_fx, slide_spec)
if _fx_path != _resolved_for_fx:
slide_spec = dict(slide_spec)
slide_spec["image_path"] = _fx_path
else:
print(f"[pptx_gen] img_filter SKIP: resolved path not found: {_resolved_for_fx!r}", file=sys.stderr, flush=True)
if slide_type == "section":
slide = make_section_slide(prs, slide_spec, slide_colors, fs, bg_image)
elif slide_type == "title":
+323
View File
@@ -0,0 +1,323 @@
#!/usr/bin/env python3
"""
세 모델에 동일한 프레젠테이션 요청을 보내고 결과를 비교하는 스크립트.
각 모델이 create_presentation 도구를 호출하면 spec을 추출해 PPTX를 생성한다.
"""
import json, os, re, sys, time, subprocess
import urllib.request, urllib.error
# .env에서 API 키 로드
def _load_env(path="/home/kim/homeclaw/.env"):
env = {}
try:
for line in open(path):
line = line.strip()
if line and not line.startswith("#") and "=" in line:
k, _, v = line.partition("=")
env[k.strip()] = v.strip()
except FileNotFoundError:
pass
return env
_env = _load_env()
PEXELS_KEY = os.environ.get("PEXELS_API_KEY") or _env.get("PEXELS_API_KEY", "")
UNSPLASH_KEY = os.environ.get("UNSPLASH_ACCESS_KEY") or _env.get("UNSPLASH_ACCESS_KEY", "")
OLLAMA_URL = "http://localhost:11434/api/chat"
WORKSPACE = "/home/kim/homeclaw/.smallclaw/users/papa/workspace"
REPORT_TITLE = "한반도_기후_변화_100년_보고서" # 모든 모델 출력 폴더 고정
PPTX_GEN = "/home/kim/homeclaw/scripts/pptx_gen.py"
PREVIEW = "/home/kim/homeclaw/scripts/pptx_preview.py"
MODELS = [
"mistral-large-3:675b-cloud",
"kimi-k2.6:cloud",
"deepseek-v4-pro:cloud",
]
USER_PROMPT = "한반도 기후 변화 100년 보고서를 10슬라이드로 만들어줘. 표 슬라이드와 차트 슬라이드를 반드시 포함하고, 사진이 어울리는 슬라이드에는 image_search 필드로 영문 검색어를 넣어줘. dark 테마로."
SYSTEM_PROMPT = """\
당신은 발표 자료 전문가입니다. `create_presentation` 도구를 사용해 전문적이고 시각적으로 설득력 있는 PowerPoint 자료를 만드세요.
[필수] 언어 규칙: 사용자가 한국어로 말하면 반드시 한국어로만 답변하세요.
핵심 원칙:
1. 구조가 먼저: 목적·청중·핵심 메시지를 파악한 후 슬라이드 구성을 결정하세요
2. ONE CALL 원칙: 모든 슬라이드를 단 1번의 create_presentation 호출로 작성하세요
3. 7±2 원칙: 슬라이드당 글머리 기호 5~7개 이하
4. 차트 슬라이드는 반드시 categories와 series 데이터를 채워넣으세요 (비워두면 빈 슬라이드가 됩니다)
5. 사진 슬라이드: layout="split-right" 또는 "fullscreen"과 함께 image_search에 영문 검색어를 넣으세요
"""
TOOL_SCHEMA = {
"type": "function",
"function": {
"name": "create_presentation",
"description": "PPTX 프레젠테이션을 생성합니다.",
"parameters": {
"type": "object",
"properties": {
"spec": {
"type": "object",
"properties": {
"filename": {"type": "string"},
"title": {"type": "string"},
"template": {"type": "string", "description": "business, minimal, creative, dark, pastel, warm"},
"theme": {"type": "string", "description": "dark or light"},
"slides": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": {"type": "string", "description": "title|content|section|image|table|chart|timeline"},
"layout": {"type": "string", "description": "split-right|split-left|text|fullscreen|compare"},
"title": {"type": "string"},
"subtitle": {"type": "string"},
"bullets": {"type": "array", "items": {"type": "string"}},
"body": {"type": "string"},
"image_search": {"type": "string"},
"headers": {"type": "array", "items": {"type": "string"}},
"rows": {"type": "array", "items": {"type": "array", "items": {"type": "string"}}},
"chart_type": {"type": "string"},
"categories": {"type": "array", "items": {"type": "string"}},
"series": {"type": "array", "items": {"type": "object"}},
"events": {"type": "array", "items": {"type": "object"}},
}
}
}
},
"required": ["slides"]
}
},
"required": ["spec"]
}
}
}
def call_model(model: str, timeout: int = 180) -> dict | None:
"""Ollama chat API 호출 → tool call spec 반환"""
payload = {
"model": model,
"stream": False,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": USER_PROMPT},
],
"tools": [TOOL_SCHEMA],
}
data = json.dumps(payload).encode()
req = urllib.request.Request(OLLAMA_URL, data=data,
headers={"Content-Type": "application/json"})
print(f"\n[{model}] 요청 중...", flush=True)
t0 = time.time()
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
result = json.loads(resp.read())
except Exception as e:
print(f"[{model}] 오류: {e}", flush=True)
return None
elapsed = time.time() - t0
print(f"[{model}] 응답 완료 ({elapsed:.1f}초)", flush=True)
msg = result.get("message", {})
# tool_calls 방식
for tc in (msg.get("tool_calls") or []):
fn = tc.get("function", {})
if fn.get("name") == "create_presentation":
args = fn.get("arguments") or fn.get("parameters") or {}
if isinstance(args, str):
try:
args = json.loads(args)
except Exception:
pass
spec = args.get("spec") if isinstance(args, dict) else None
if isinstance(spec, str):
try:
spec = json.loads(spec)
except Exception:
pass
if isinstance(spec, dict) and spec:
return spec
# content 안에 JSON 블록으로 spec을 반환하는 경우 fallback
content = msg.get("content") or ""
m = re.search(r'```(?:json)?\s*(\{.*?"slides".*?\})\s*```', content, re.DOTALL)
if m:
try:
parsed = json.loads(m.group(1))
if "spec" in parsed:
return parsed["spec"]
if "slides" in parsed:
return parsed
except Exception:
pass
print(f"[{model}] tool call을 찾을 수 없음. content 미리보기:\n{content[:300]}", flush=True)
return None
def _search_pexels(query: str) -> str | None:
if not PEXELS_KEY:
return None
url = f"https://api.pexels.com/v1/search?query={urllib.request.quote(query)}&per_page=3&orientation=landscape"
req = urllib.request.Request(url, headers={"Authorization": PEXELS_KEY})
try:
with urllib.request.urlopen(req, timeout=10) as r:
data = json.loads(r.read())
photos = data.get("photos") or []
if photos:
return photos[0].get("src", {}).get("large2x") or photos[0].get("src", {}).get("large")
except Exception:
pass
return None
def _search_unsplash(query: str) -> str | None:
if not UNSPLASH_KEY:
return None
url = f"https://api.unsplash.com/search/photos?query={urllib.request.quote(query)}&per_page=3&orientation=landscape"
req = urllib.request.Request(url, headers={"Authorization": f"Client-ID {UNSPLASH_KEY}"})
try:
with urllib.request.urlopen(req, timeout=10) as r:
data = json.loads(r.read())
results = data.get("results") or []
if results:
return results[0].get("urls", {}).get("regular")
except Exception:
pass
return None
def download_image(query: str, dest_path: str) -> bool:
"""Pexels → Unsplash 순으로 이미지 검색 후 다운로드. 성공 시 True."""
img_url = _search_pexels(query) or _search_unsplash(query)
if not img_url:
return False
try:
req = urllib.request.Request(img_url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=15) as r:
data = r.read()
if len(data) < 100:
return False
with open(dest_path, "wb") as f:
f.write(data)
return True
except Exception:
return False
def resolve_images(spec: dict, project_dir: str, model_tag: str) -> None:
"""spec 슬라이드의 image_search 필드를 image_path로 변환."""
for i, slide in enumerate(spec.get("slides", [])):
query = slide.get("image_search")
if not query or slide.get("image_path"):
continue
ext = ".jpg"
fname = f"slide{i+1}_image{ext}"
dest = os.path.join(project_dir, fname)
print(f"[{model_tag}] 슬라이드 {i+1} 이미지 검색: {query!r}", flush=True)
if download_image(query, dest):
slide["image_path"] = fname
print(f"[{model_tag}] 슬라이드 {i+1} 이미지 저장: {fname}", flush=True)
else:
print(f"[{model_tag}] 슬라이드 {i+1} 이미지 실패", flush=True)
slide.pop("image_search", None)
def build_pptx(spec: dict, model_tag: str, username: str = "papa") -> str | None:
"""spec → 이미지 다운로드 → PPTX 생성 → 경로 반환"""
safe_tag = re.sub(r'[^a-zA-Z0-9_-]', '_', model_tag.split(":")[0])
spec["filename"] = f"climate_compare_{safe_tag}"
spec["username"] = username
spec["title"] = REPORT_TITLE # 모든 모델이 동일 폴더에 저장되도록 고정
spec.setdefault("template", "dark")
spec.setdefault("theme", "dark")
# 프로젝트 폴더 미리 생성 후 이미지 다운로드
title_slug = re.sub(r'[^a-zA-Z0-9가-힣_\-]', '_', REPORT_TITLE).strip("_")[:60] or "presentation"
project_dir = os.path.join(WORKSPACE, title_slug)
os.makedirs(project_dir, exist_ok=True)
resolve_images(spec, project_dir, model_tag)
spec_path = f"/tmp/compare_spec_{safe_tag}.json"
with open(spec_path, "w", encoding="utf-8") as f:
json.dump(spec, f, ensure_ascii=False, indent=2)
print(f"[{model_tag}] PPTX 생성 중...", flush=True)
r = subprocess.run(
["python3", PPTX_GEN, spec_path, WORKSPACE],
capture_output=True, text=True, cwd="/home/kim/homeclaw"
)
try:
out = json.loads(r.stdout)
except Exception:
print(f"[{model_tag}] pptx_gen 오류:\n{r.stderr[-500:]}", flush=True)
return None
if not out.get("success"):
print(f"[{model_tag}] 실패: {out.get('error')}", flush=True)
return None
pptx_path = out["path"]
print(f"[{model_tag}] 완료: {pptx_path}", flush=True)
if out.get("warnings"):
print(f"[{model_tag}] 경고: {out['warnings']}", flush=True)
return pptx_path
def make_preview(pptx_path: str) -> list[str]:
# LibreOffice requires .pptx extension to recognize format
if not pptx_path.endswith(".pptx"):
pptx_path = pptx_path + ".pptx"
stem = os.path.splitext(os.path.basename(pptx_path))[0]
prev_dir = os.path.join(os.path.dirname(pptx_path), f"preview_{stem}")
os.makedirs(prev_dir, exist_ok=True)
r = subprocess.run(
["python3", PREVIEW, pptx_path, prev_dir],
capture_output=True, text=True, cwd="/home/kim/homeclaw"
)
try:
# MuPDF error messages may appear before the JSON line
last_line = r.stdout.strip().rsplit("\n", 1)[-1]
out = json.loads(last_line)
return [os.path.join(prev_dir, img) for img in out.get("images", [])]
except Exception:
return []
if __name__ == "__main__":
results = {}
total_start = time.time()
for model in MODELS:
t0 = time.time()
spec = call_model(model)
llm_elapsed = time.time() - t0
if spec is None:
print(f"[{model}] spec 없음, 건너뜀\n")
continue
pptx_path = build_pptx(spec, model)
if pptx_path is None:
continue
total_elapsed = time.time() - t0
previews = make_preview(pptx_path)
image_count = sum(1 for s in spec.get("slides", []) if s.get("image_search") or s.get("image_path"))
results[model] = {
"pptx": pptx_path, "previews": previews, "spec": spec,
"llm_sec": round(llm_elapsed, 1), "total_sec": round(total_elapsed, 1),
"image_count": image_count,
}
print(f"[{model}] 프리뷰 {len(previews)}장 생성 완료 (LLM {llm_elapsed:.1f}s / 전체 {total_elapsed:.1f}s)\n")
print("\n===== 비교 결과 =====")
for model, info in results.items():
slide_types = [s.get("type","?") for s in info["spec"].get("slides", [])]
img_slides = [i+1 for i,s in enumerate(info["spec"].get("slides",[])) if s.get("image_search") or s.get("image_path")]
print(f"{model}:")
print(f" 슬라이드: {len(slide_types)}장 {slide_types}")
print(f" 사진슬라이드: {len(img_slides)}장 (슬라이드 {img_slides})")
print(f" 응답시간: LLM {info['llm_sec']}s / 전체(PPTX포함) {info['total_sec']}s")
print(f" PPTX: {info['pptx']}")
print(f" 미리보기: {info['previews'][:2]}{'...' if len(info['previews'])>2 else ''}")
+502 -8
View File
@@ -5367,11 +5367,13 @@ BROWSER RULE: NEVER call browser_open, browser_snapshot, browser_click, browser_
// execution — skip preflight entirely to prevent recursive task spawning loops.
const isTaskRunnerSession = sessionId.startsWith('task_');
const isDirectCall = callerContext?.includes('no_preflight');
if (
preflightCfg?.enabled &&
!isBootStartupTurn &&
!skipGenericPreflightForFileOp &&
!isTaskRunnerSession &&
!isDirectCall &&
shouldRunPreflight(message, preflightCfg.preflight.mode) &&
orchestrationStats.assistCount < preflightCfg.limits.max_assists_per_session
) {
@@ -7307,9 +7309,6 @@ RULES:
});
continue;
}
if (!allowRepeatedTool) {
seenToolCalls.add(callKey);
}
if (
fileOpV2Active
@@ -7663,7 +7662,10 @@ RULES:
logToolCall(workspacePath, toolName, toolArgs, toolResult.result, toolResult.error);
trackFileOpMutation(toolName, toolArgs, toolResult, 'primary');
if (fileOpV2Active && toolResult.error) fileOpHadToolFailure = true;
if (!toolResult.error) roundHadProgress = true;
if (!toolResult.error) {
roundHadProgress = true;
if (!allowRepeatedTool) seenToolCalls.add(callKey);
}
orchestrationState.recordToolResult(round, toolName, toolArgs, toolResult.error);
orchestrationLog.push(
@@ -9081,7 +9083,8 @@ app.get('/api/pptx/preview', async (req: express.Request, res: express.Response)
if (oldestPreview >= pptxMtime) {
const relPreviewDir = path.join(path.dirname(relPath), 'preview').replace(/\\/g, '/');
const encodedPreviewDir = relPreviewDir.split('/').map(s => encodeURIComponent(s)).join('/');
const images = previewFiles.map(f => `/api/files/${encodedPreviewDir}/${encodeURIComponent(f)}`);
const ts = Math.floor(pptxMtime / 1000);
const images = previewFiles.map(f => `/api/files/${encodedPreviewDir}/${encodeURIComponent(f)}?t=${ts}`);
res.json({ success: true, images, count: images.length });
return;
}
@@ -9124,7 +9127,8 @@ app.get('/api/pptx/preview', async (req: express.Request, res: express.Response)
const relPreviewDir = path.join(path.dirname(relPath), 'preview').replace(/\\/g, '/');
const encodedPreviewDir = relPreviewDir.split('/').map(s => encodeURIComponent(s)).join('/');
const images = (result.images || []).map(f => `/api/files/${encodedPreviewDir}/${encodeURIComponent(f)}`);
const ts = Math.floor(Date.now() / 1000);
const images = (result.images || []).map(f => `/api/files/${encodedPreviewDir}/${encodeURIComponent(f)}?t=${ts}`);
res.json({ success: true, images, count: result.count || images.length });
} catch (err: any) {
res.status(500).json({ error: `Preview error: ${err.message}` });
@@ -9148,6 +9152,495 @@ function resolveUploadName(uploadsDir: string, originalName: string): string {
return `${stem}_${Date.now()}${ext}`;
}
// ── PPTX Wizard API ──────────────────────────────────────────────────────────
// Latest PPTX in user workspace (for wizard fallback)
app.get('/api/pptx/latest', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const session = getSessionUser(req);
const username = session?.username;
const workspacePath = username ? getUserWorkspace(username) : getConfig().getWorkspacePath();
const { execFile } = await import('child_process');
const { promisify } = await import('util');
const execFileAsync = promisify(execFile);
const { stdout } = await execFileAsync('find', [workspacePath, '-name', '*.pptx', '-not', '-path', '*/preview/*', '-printf', '%T@ %p\n'], { timeout: 10000 });
const lines = stdout.trim().split('\n').filter(Boolean)
.map(l => { const [ts, ...rest] = l.split(' '); return { ts: parseFloat(ts), p: rest.join(' ') }; })
.sort((a, b) => b.ts - a.ts);
if (!lines.length) { res.json({ found: false }); return; }
const absPath = lines[0].p;
const relPath = absPath.slice(workspacePath.length).replace(/^[\\/]/, '').replace(/\\/g, '/');
const encodedUrl = '/api/files/' + relPath.split('/').map(s => encodeURIComponent(s)).join('/');
res.json({ found: true, relPath, url: encodedUrl, mtime: lines[0].ts });
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
app.get('/api/pptx/list', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const session = getSessionUser(req);
const username = session?.username;
const workspacePath = username ? getUserWorkspace(username) : getConfig().getWorkspacePath();
const { execFile } = await import('child_process');
const { promisify } = await import('util');
const execFileAsync = promisify(execFile);
const { stdout } = await execFileAsync('find', [workspacePath, '-name', '*.pptx', '-not', '-path', '*/preview/*', '-printf', '%T@ %p\n'], { timeout: 10000 });
const items = stdout.trim().split('\n').filter(Boolean)
.map(l => { const [ts, ...rest] = l.split(' '); return { ts: parseFloat(ts), absPath: rest.join(' ') }; })
.sort((a, b) => b.ts - a.ts)
.slice(0, 30)
.map(({ ts, absPath }) => {
const relPath = absPath.slice(workspacePath.length).replace(/^[\\/]/, '').replace(/\\/g, '/');
const parts = relPath.split('/');
const project = parts[0];
const filename = parts[parts.length - 1];
const url = '/api/files/' + relPath.split('/').map(s => encodeURIComponent(s)).join('/');
return { relPath, project, filename, url, mtime: ts };
});
res.json({ items });
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
app.get('/api/pptx/read-outline', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
let relPath = String(req.query.path || '').trim().replace(/^\/api\/files\/?/, '').replace(/\\/g, '/').replace(/^\/+/, '');
if (!relPath || relPath.includes('..')) { res.status(400).json({ error: 'Invalid path' }); return; }
const session = getSessionUser(req);
const username = session?.username;
const workspacePath = username ? getUserWorkspace(username) : getConfig().getWorkspacePath();
const pptxPath = path.resolve(workspacePath, relPath);
if (!pptxPath.startsWith(workspacePath)) { res.status(403).json({ error: 'Access denied' }); return; }
if (!fs.existsSync(pptxPath)) { res.status(404).json({ error: 'File not found' }); return; }
const pythonCmd = process.platform === 'win32' ? 'python' : 'python3';
const script = `
import sys, json
from pptx import Presentation
from pptx.dml.color import RGBColor
def detect_bg(slide):
try:
fill = slide.background.fill
ft = fill.type
if ft is not None and str(ft) != 'NOT_DEFINED (0)':
try:
rgb = fill.fore_color.rgb
r,g,b = rgb[0],rgb[1],rgb[2]
if r+g+b < 300: # dark
if b > r and b > g: return 'navy'
return 'charcoal'
# light solid
if r > 250 and g > 245 and b > 220: return 'cream'
except: pass
# blip fill (skin image) - check for background_skin shape
for shape in slide.shapes:
if 'background' in (shape.name or '').lower():
return 'cream'
except: pass
return 'cream' # safe default
prs = Presentation(sys.argv[1])
slides = []
bg_skin = detect_bg(prs.slides[0]) if prs.slides else 'cream'
for i, slide in enumerate(prs.slides):
shapes = [s for s in slide.shapes if s.has_text_frame]
texts = [s.text_frame.text.strip() for s in shapes if s.text_frame.text.strip()]
title = texts[0] if texts else ''
rest = texts[1:]
spec = {'type': 'content', 'title': title, 'background': bg_skin}
if i == 0: spec['type'] = 'title'
if rest:
if i == 0:
spec['subtitle'] = rest[0]
else:
spec['bullets'] = [b for line in rest for b in line.split('\\n') if b.strip()][:10]
# 프로젝트 폴더의 slide{N}_image.* 파일 감지
import os
proj_dir = os.path.dirname(sys.argv[1])
for ext in ['.jpg', '.jpeg', '.png', '.webp']:
img_candidate = os.path.join(proj_dir, f'slide{i+1}_image{ext}')
if os.path.exists(img_candidate):
spec['image_path'] = f'slide{i+1}_image{ext}'
break
slides.append(spec)
project = sys.argv[1].split('/')[-2] if '/' in sys.argv[1] else 'presentation'
print(json.dumps({'project': project, 'background': bg_skin, 'slides': slides}))
`;
const { execFile: execFileCb } = await import('child_process');
const result = await new Promise<string>((resolve, reject) => {
execFileCb(pythonCmd, ['-c', script, pptxPath], { timeout: 15000 }, (err, stdout, stderr) => {
if (err) reject(new Error(err.message + '\n' + stderr));
else resolve(stdout);
});
});
const outline = JSON.parse(result.trim());
res.json({ success: true, outline });
} catch (err: any) {
res.status(500).json({ error: String(err.message || err) });
}
});
// POST /api/pptx/create — LLM 없이 직접 pptx_gen.py 호출 (wizard 재생성용)
app.post('/api/pptx/create', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const spec = req.body?.spec;
if (!spec || !Array.isArray(spec.slides) || spec.slides.length === 0) {
res.status(400).json({ success: false, error: 'spec.slides required' }); return;
}
const session = getSessionUser(req);
const username = session?.username;
const workspacePath = username ? getUserWorkspace(username) : getConfig().getWorkspacePath();
const pptxTool = getToolRegistry().get('create_presentation');
if (!pptxTool) { res.status(500).json({ success: false, error: 'PPTX tool not available' }); return; }
const result = await pptxTool.execute({ spec, _workspacePath: workspacePath });
res.json(result);
} catch (err: any) {
res.status(500).json({ success: false, error: String(err.message || err) });
}
});
app.get('/api/pubmed/fetch', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const pmids = String(req.query.pmids || req.query.pmid || '').trim();
if (!pmids) { res.status(400).json({ error: 'pmids parameter required' }); return; }
const { pubmedFetchTool } = await import('../tools/pubmed.js');
const result = await pubmedFetchTool.execute({ pmids });
res.json(result);
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
app.post('/api/pptx/read-pdf', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const session = getSessionUser(req);
const username = session?.username;
const pdfPath = String(req.body?.pdf_path || '').trim();
if (!pdfPath) { res.status(400).json({ error: 'pdf_path required' }); return; }
const workspacePath = username ? getUserWorkspace(username) : getConfig().getWorkspacePath();
const { pdfReadTool } = await import('../tools/pdf.js');
const result = await pdfReadTool.execute({ path: pdfPath, max_chars: 4000, _workspacePath: workspacePath });
res.json(result);
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
app.get('/api/pubmed/search', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const query = String(req.query.q || req.query.query || '').trim();
const maxResults = Math.min(Number(req.query.max || 20), 50);
const minYear = req.query.min_year ? Number(req.query.min_year) : undefined;
const sort = req.query.sort === 'date' ? 'date' : 'relevance';
if (!query) { res.status(400).json({ error: 'q parameter required' }); return; }
const { pubmedSearchTool } = await import('../tools/pubmed.js');
const result = await pubmedSearchTool.execute({ query, max_results: maxResults, sort, min_year: minYear });
res.json(result);
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
app.get('/api/openalex/search', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const query = String(req.query.q || req.query.query || '').trim();
const maxResults = Math.min(Number(req.query.max || 20), 50);
const minYear = req.query.min_year ? Number(req.query.min_year) : undefined;
const sort = req.query.sort === 'date' ? 'publication_date' : 'relevance';
if (!query) { res.status(400).json({ error: 'q parameter required' }); return; }
const { openalexSearchTool } = await import('../tools/scholar.js');
const result = await openalexSearchTool.execute({ query, max_results: maxResults, sort, min_year: minYear });
res.json(result);
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
app.get('/api/semantic/search', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const query = String(req.query.q || req.query.query || '').trim();
const maxResults = Math.min(Number(req.query.max || 20), 50);
const minYear = req.query.min_year ? Number(req.query.min_year) : undefined;
if (!query) { res.status(400).json({ error: 'q parameter required' }); return; }
const { semanticSearchTool } = await import('../tools/scholar.js');
const result = await semanticSearchTool.execute({ query, max_results: maxResults, year_from: minYear });
res.json(result);
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
app.post('/api/pptx/download-pdf', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const session = getSessionUser(req);
const username = session?.username;
const workspacePath = username ? getUserWorkspace(username) : getConfig().getWorkspacePath();
// If project slug provided, save PDF directly into project folder
const projectSlug = String(req.body?.project || '').trim()
.replace(/[^a-zA-Z0-9가-힣_\-]/g, '_').replace(/_+/g, '_').replace(/^_+|_+$/g, '').toLowerCase().slice(0, 60);
const pdfBaseDir = projectSlug || 'pubmed';
const directUrl = String(req.body?.url || '').trim();
if (directUrl) {
const doi = String(req.body?.doi || '').trim();
console.log(`[download-pdf] url=${directUrl} doi=${doi} project=${projectSlug}`);
// 랜딩페이지 호스트 — PDF 직접 링크가 아님
const landingHosts = ['doaj.org', 'doi.org', 'dx.doi.org', 'europepmc.org', 'pubmed.ncbi.nlm.nih.gov'];
const urlHost = (() => { try { return new URL(directUrl).hostname; } catch { return ''; } })();
const isLandingPage = landingHosts.some(h => urlHost === h || urlHost.endsWith('.'+h));
// 1) DOI → Europe PMC PMCID 조회 (항상 먼저 시도)
if (doi) {
try {
const epmc = await fetch(`https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=DOI:${encodeURIComponent(doi)}&format=json&resulttype=core`);
const epmcData: any = await epmc.json();
const hit = (epmcData?.resultList?.result || []).find((r: any) => r.inPMC === 'Y' && r.pmcid);
if (hit?.pmcid) {
console.log(`[download-pdf] DOI→PMC: ${hit.pmcid}`);
const { pubmedFulltextTool } = await import('../tools/pubmed.js');
const savePath = projectSlug ? `${projectSlug}/${hit.pmcid}.pdf` : undefined;
const result = await pubmedFulltextTool.execute({ pmcid: hit.pmcid, format: 'pdf', save_path: savePath, _workspacePath: workspacePath });
res.json(result);
return;
}
} catch (_) { /* Europe PMC 실패 시 직접 다운로드로 폴백 */ }
}
// 2) 랜딩페이지 URL이면 직접 다운로드 불가
if (isLandingPage) {
res.json({ success: false, error: `PDF 직접 링크 없음 — PMC에도 없습니다. PDF를 직접 다운로드 후 업로드해 주세요.` });
return;
}
// 3) 직접 curl 시도
const safeName = (doi || Date.now().toString()).replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 80);
const outPath = `${pdfBaseDir}/${safeName}.pdf`;
const fs = await import('fs');
const path = await import('path');
const outAbs = path.join(workspacePath, outPath);
const outDir = path.dirname(outAbs);
if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
const { spawnSync } = await import('child_process');
const curlResult = spawnSync('curl', [
'-L', '--silent', '--fail',
'--user-agent', 'Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0',
'--max-time', '30', '--retry', '1',
'-o', outAbs, directUrl
], { timeout: 60000 });
if (curlResult.status === 0) {
const fd = fs.openSync(outAbs, 'r');
const hdr = Buffer.alloc(5);
fs.readSync(fd, hdr, 0, 5, 0);
fs.closeSync(fd);
if (hdr.toString() !== '%PDF-') {
fs.unlinkSync(outAbs);
res.json({ success: false, error: `출판사 서버가 차단했습니다 (페이월/Cloudflare). PDF를 직접 다운로드 후 업로드해 주세요.\n${directUrl}` });
return;
}
res.json({ success: true, path: outPath, stdout: outPath });
} else {
res.json({ success: false, error: `출판사 서버가 차단했습니다. PDF를 직접 다운로드 후 업로드해 주세요.\n${directUrl}` });
}
return;
}
const pmcid = String(req.body?.pmcid || '').trim();
if (!pmcid) { res.status(400).json({ error: 'pmcid or url required' }); return; }
const { pubmedFulltextTool } = await import('../tools/pubmed.js');
const savePath = projectSlug ? `${projectSlug}/${pmcid}.pdf` : undefined;
const result = await pubmedFulltextTool.execute({ pmcid, format: 'pdf', save_path: savePath, _workspacePath: workspacePath });
res.json(result);
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
app.post('/api/pptx/extract-images', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const session = getSessionUser(req);
const username = session?.username;
const pdfPath = String(req.body?.pdf_path || '').trim();
const projectSlugEx = String(req.body?.project || '').trim()
.replace(/[^a-zA-Z0-9가-힣_\-]/g, '_').replace(/_+/g, '_').replace(/^_+|_+$/g, '').toLowerCase().slice(0, 60);
// If project given and no explicit out_dir, put extracted images inside project folder
const explicitOutDir = String(req.body?.out_dir || '').trim();
let outDir = explicitOutDir;
if (!outDir && projectSlugEx && pdfPath) {
const pdfBase = path.basename(pdfPath, path.extname(pdfPath));
outDir = `${projectSlugEx}/${pdfBase}_images`;
}
if (!pdfPath) { res.status(400).json({ error: 'pdf_path required' }); return; }
const workspacePath = username ? getUserWorkspace(username) : getConfig().getWorkspacePath();
const { pdfExtractImagesTool } = await import('../tools/pdf-extract.js');
const result = await pdfExtractImagesTool.execute({ path: pdfPath, mode: 'figures', out_dir: outDir || undefined, _workspacePath: workspacePath });
res.json(result);
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
// GET /api/pptx/project-pdfs?project=<slug> — list PDF files in project folder
app.get('/api/pptx/project-pdfs', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const session = getSessionUser(req);
const username = session?.username;
const workspacePath = username ? getUserWorkspace(username) : getConfig().getWorkspacePath();
const project = String(req.query.project || '').trim().replace(/\.\./g, '');
if (!project) { res.status(400).json({ error: 'project required' }); return; }
const projectDir = path.join(workspacePath, project);
if (!fs.existsSync(projectDir)) { res.json({ pdfs: [] }); return; }
const pdfs = fs.readdirSync(projectDir)
.filter(f => f.toLowerCase().endsWith('.pdf'))
.map(f => ({ path: `${project}/${f}`, name: f.replace(/\.pdf$/i, '') }));
res.json({ pdfs });
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
// GET /api/pptx/project-images?project=...
// Lists image files inside a project folder (jpg/jpeg/png/gif/webp)
app.get('/api/pptx/project-images', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const session = getSessionUser(req);
const username = session?.username;
const workspacePath = username ? getUserWorkspace(username) : getConfig().getWorkspacePath();
const project = String(req.query.project || '').trim().replace(/\.\./g, '');
if (!project) { res.status(400).json({ error: 'project required' }); return; }
const projectDir = path.join(workspacePath, project);
if (!fs.existsSync(projectDir)) { res.json({ images: [] }); return; }
const IMG_EXT = /\.(jpe?g|png|gif|webp)$/i;
const images: { path: string; name: string }[] = [];
const scan = (dir: string, rel: string) => {
for (const f of fs.readdirSync(dir)) {
const abs = path.join(dir, f);
const relF = rel ? `${rel}/${f}` : f;
try {
if (fs.statSync(abs).isDirectory()) { scan(abs, relF); continue; }
} catch { continue; }
if (IMG_EXT.test(f)) images.push({ path: `${project}/${relF}`, name: f });
}
};
scan(projectDir, '');
res.json({ images });
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
// GET /api/pptx/pdf-page?path=...&page=...&dpi=...
// Renders a single PDF page as PNG, returns inline image + X-Page-Count header
app.get('/api/pptx/pdf-page', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const session = getSessionUser(req);
const username = session?.username;
const relPath = String(req.query.path || '').trim().replace(/^\/api\/files\/?/, '').replace(/\\/g, '/').replace(/^\/+/, '');
const pageNum = Math.max(0, parseInt(String(req.query.page || '0'), 10));
const dpi = Math.min(200, Math.max(72, parseInt(String(req.query.dpi || '150'), 10)));
if (!relPath || relPath.includes('..')) { res.status(400).json({ error: 'Invalid path' }); return; }
const workspacePath = username ? getUserWorkspace(username) : getConfig().getWorkspacePath();
const absPath = path.resolve(workspacePath, relPath);
if (!absPath.startsWith(workspacePath)) { res.status(403).json({ error: 'Access denied' }); return; }
if (!fs.existsSync(absPath)) { res.status(404).json({ error: 'File not found' }); return; }
const { execFile: ef } = await import('child_process');
const tmpOut = path.join(require('os').tmpdir(), `pdfpage_${Date.now()}_${pageNum}.png`);
const pyCode = `
import sys, json
try:
import fitz
doc = fitz.open(sys.argv[1])
total = len(doc)
p = int(sys.argv[2])
if p >= total: print(json.dumps({'error': 'page out of range', 'total': total})); sys.exit(1)
mat = fitz.Matrix(float(sys.argv[4])/72.0, float(sys.argv[4])/72.0)
pix = doc[p].get_pixmap(matrix=mat)
pix.save(sys.argv[3])
print(json.dumps({'ok': True, 'total': total}))
except Exception as e:
print(json.dumps({'error': str(e)}))
sys.exit(1)
`;
await new Promise<void>((resolve, reject) => {
ef('python3', ['-c', pyCode, absPath, String(pageNum), tmpOut, String(dpi)], { timeout: 20000 }, (err, stdout) => {
try {
const r = JSON.parse((stdout || '').trim().split('\n').pop() || '{}');
if (r.error) return reject(new Error(r.error));
res.setHeader('X-Page-Count', String(r.total || 1));
resolve();
} catch { reject(err || new Error('render failed')); }
});
});
if (fs.existsSync(tmpOut)) {
res.setHeader('Content-Type', 'image/png');
res.setHeader('Cache-Control', 'private, max-age=60');
const data = fs.readFileSync(tmpOut);
fs.unlinkSync(tmpOut);
res.end(data);
} else { res.status(500).json({ error: 'Render output not found' }); }
} catch (err: any) { res.status(500).json({ error: String(err?.message || err) }); }
});
// POST /api/pptx/pdf-crop { pdf_path, page, fx, fy, fw, fh }
// fx/fy/fw/fh: fractional crop rect (0–1 relative to page size)
// Returns saved image URL in uploads/
app.post('/api/pptx/pdf-crop', requireGatewayAuth, async (req: express.Request, res: express.Response) => {
try {
const session = getSessionUser(req);
const username = session?.username;
const relPath = String(req.body?.pdf_path || '').trim().replace(/^\/api\/files\/?/, '').replace(/\\/g, '/').replace(/^\/+/, '');
const pageNum = Math.max(0, parseInt(String(req.body?.page ?? 0), 10));
const fx = parseFloat(String(req.body?.fx ?? 0)); const fy = parseFloat(String(req.body?.fy ?? 0));
const fw = parseFloat(String(req.body?.fw ?? 1)); const fh = parseFloat(String(req.body?.fh ?? 1));
if (!relPath || relPath.includes('..')) { res.status(400).json({ error: 'Invalid path' }); return; }
const workspacePath = username ? getUserWorkspace(username) : getConfig().getWorkspacePath();
const absPath = path.resolve(workspacePath, relPath);
if (!absPath.startsWith(workspacePath)) { res.status(403).json({ error: 'Access denied' }); return; }
if (!fs.existsSync(absPath)) { res.status(404).json({ error: 'File not found' }); return; }
const uploadsDir = path.join(workspacePath, 'uploads');
fs.mkdirSync(uploadsDir, { recursive: true });
const outName = `capture_${Date.now()}_p${pageNum}.png`;
const outPath = path.join(uploadsDir, outName);
const { execFile: ef } = await import('child_process');
const pyCode = `
import sys, json
try:
import fitz
doc = fitz.open(sys.argv[1])
p = int(sys.argv[2])
fx,fy,fw,fh = float(sys.argv[4]),float(sys.argv[5]),float(sys.argv[6]),float(sys.argv[7])
page = doc[p]
r = page.rect
clip = fitz.Rect(r.x0+fx*r.width, r.y0+fy*r.height, r.x0+(fx+fw)*r.width, r.y0+(fy+fh)*r.height)
mat = fitz.Matrix(2.0, 2.0)
pix = page.get_pixmap(matrix=mat, clip=clip)
pix.save(sys.argv[3])
print(json.dumps({'ok': True}))
except Exception as e:
print(json.dumps({'error': str(e)}))
sys.exit(1)
`;
await new Promise<void>((resolve, reject) => {
ef('python3', ['-c', pyCode, absPath, String(pageNum), outPath, String(fx), String(fy), String(fw), String(fh)],
{ timeout: 20000 }, (err, stdout) => {
try {
const r = JSON.parse((stdout || '').trim().split('\n').pop() || '{}');
if (r.error) return reject(new Error(r.error));
resolve();
} catch { reject(err || new Error('crop failed')); }
});
});
const relOut = `uploads/${outName}`;
res.json({ success: true, path: relOut, url: `/api/files/${relOut}`, filename: outName });
} catch (err: any) { res.status(500).json({ error: String(err?.message || err) }); }
});
app.post('/api/upload/image', (req: express.Request, res: express.Response) => {
const contentType = String(req.headers['content-type'] || '');
if (!contentType.includes('multipart/form-data')) {
@@ -9638,7 +10131,7 @@ app.get('/api/status', async (_req, res) => {
});
app.post('/api/chat', async (req, res) => {
const { message, sessionId = 'default', pinnedMessages, model: reqModel } = req.body;
const { message, sessionId = 'default', pinnedMessages, model: reqModel, direct } = req.body;
if (!message || typeof message !== 'string') { res.status(400).json({ error: 'Message required' }); return; }
const user = (req as any).user;
@@ -9754,7 +10247,8 @@ app.post('/api/chat', async (req, res) => {
}
const pins = Array.isArray(pinnedMessages) ? pinnedMessages.slice(0, 3) : [];
const modelOverride = reqModel ? String(reqModel).trim() || undefined : undefined;
const result = await handleChat(message, sessionId, sendSSE, pins.length > 0 ? pins : undefined, abortSignal, undefined, modelOverride, 'interactive', user?.username);
const callerCtx = direct ? 'no_preflight' : undefined;
const result = await handleChat(message, sessionId, sendSSE, pins.length > 0 ? pins : undefined, abortSignal, callerCtx, modelOverride, 'interactive', user?.username);
if (!abortSignal.aborted) {
result.text = await validateLinksInText(result.text);
console.log(`[v2] ASSISTANT [${userTag}]: ${result.text}`);
-2
View File
@@ -272,8 +272,6 @@ export function shouldRunPreflight(userMessage: string, mode: PreflightMode): bo
// Pure image upload (no actual text question): skip preflight, let primary handle it directly
const textWithoutImages = text.replace(/!\[([^\]]*)\]\([^)]+\)/g, '').replace(/\[([^\]]+)\]\([^)]+\)/g, '').trim();
if (textWithoutImages.length < 5 && /\.(jpg|jpeg|png|gif|webp|bmp|tiff|tif)/i.test(lower)) return false;
if (text.includes('\n')) return true;
return /\b(plan|spec|checklist|refactor|debug|fix|error|stack|search|web|browse|tool|edit|file|code|implement|oauth|api|endpoint|config|settings|migration)\b/i.test(lower);
}
+68 -9
View File
@@ -179,7 +179,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, 3000)}`);
console.debug(`[pptx] Python stderr: ${stderr.slice(0, 3000)}`);
}
if (err) {
console.error(`[pptx] Python process failed: ${err.message}`);
@@ -265,6 +265,10 @@ interface SlideSpec {
right_body?: string;
// Timeline slide
events?: { year?: string; label?: string; text?: string; description?: string }[];
// Image effects (Pillow-based post-processing)
img_filter?: string;
img_blur_radius?: number;
img_corner_radius?: number;
// Edit mode: 1-based slide number to replace (used with edit_presentation)
replace_index?: number;
}
@@ -305,6 +309,11 @@ async function downloadImageByUrl(url: string, dest: string): Promise<boolean> {
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';
// Reject HTML responses (e.g. PMC figure page URLs like .../bin/Fig1_HTM)
if (actualFmt === 'unknown' && (ct.includes('text/html') || buffer.slice(0, 15).toString('ascii').toLowerCase().includes('<!doc'))) {
console.log(`[pptx] downloadImageByUrl: HTML response rejected for ${url.slice(0, 80)}`);
return false;
}
console.log(`[pptx] downloadImageByUrl: ${buffer.length} bytes, ct="${ct}", magic=${actualFmt}, dest=${path.basename(dest)}`);
fs.writeFileSync(dest, buffer);
return true;
@@ -578,10 +587,12 @@ interface FontSizes {
interface PresentationSpec {
filename?: string;
title?: string;
project?: string;
theme?: string;
template?: string;
default_skin?: string;
font_sizes?: FontSizes;
source_files?: string[];
slides: SlideSpec[];
}
@@ -591,7 +602,7 @@ export const pptxTool: import('./registry.js').Tool = {
name: 'create_presentation',
description: 'Generate a PowerPoint (.pptx) file with slides. Slide types: "title", "content", "section", "image", "table", "chart", "timeline", "blank". Content layouts: "split-right" (default), "split-left", "text", "fullscreen", "compare". Use image_search to auto-find images. Put ALL slides in ONE call — never split. NEVER write Python scripts to create PPTX.',
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 }] }',
spec: 'JSON object: { filename, title, template, theme, font_sizes, slides: [{ type, title, subtitle, bullets, body, content, font_size, image_path, image_url, image_search, img_filter, img_blur_radius, img_corner_radius, background, template }] }',
},
jsonSchema: {
type: 'object',
@@ -602,9 +613,11 @@ export const pptxTool: import('./registry.js').Tool = {
properties: {
filename: { type: 'string', description: 'Output filename (default: presentation.pptx)' },
title: { type: 'string', description: 'Presentation title — used to name the project folder' },
project: { type: 'string', description: 'Project folder name (alternative to title — use this to save into an existing folder)' },
template: { type: 'string', description: `Template: ${TEMPLATE_NAMES.join(', ')}` },
theme: { type: 'string', description: 'Override: "dark" or "light"' },
font_sizes: { type: 'object', description: 'Override default font sizes (pt). Keys: title(40), subtitle(20), slide_title(28), body(18), bullets(18), section(36), image_title(24)' },
source_files: { type: 'array', items: { type: 'string' }, description: 'Workspace-relative paths of source files (PDFs, extracted image dirs) to copy into the project folder. E.g. ["pubmed/PMC123.pdf", "uploads/PMC123_images"]' },
slides: {
type: 'array',
description: 'Array of slide specifications',
@@ -623,6 +636,9 @@ export const pptxTool: import('./registry.js').Tool = {
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 into the project folder. Overrides image_path if both provided. Supports http/https URLs.' },
image_search: { type: 'string', description: 'Search keyword to find an image automatically (e.g. "golden retriever", "mountain sunset"). Overrides image_url if both provided. Images are downloaded before slides are created.' },
img_filter: { type: 'string', description: 'Image effect filter: "grayscale" (흑백), "blur" (블러), "contrast" (대비 강화), "bright" (밝게), "round" (둥근 모서리), or "none". Applied to the slide image via Pillow before embedding.' },
img_blur_radius: { type: 'number', description: 'Blur radius when img_filter="blur" (default: 5, range: 1-20)' },
img_corner_radius: { type: 'number', description: 'Corner radius % when img_filter="round" (default: 15, range: 5-50)' },
background: { type: 'string', description: `Skin name (${SKIN_NAMES.join(', ')}) or image file path (relative to project folder)` },
template: { type: 'string', description: `Per-slide template override: ${TEMPLATE_NAMES.join(', ')}` },
notes: { type: 'string', description: 'Speaker notes' },
@@ -680,7 +696,7 @@ export const pptxTool: import('./registry.js').Tool = {
}
// ── Phase 1: Create project directory ──
const projectSlug = (spec.title || 'presentation')
const projectSlug = (spec.title || spec.project || 'presentation')
.replace(/\.pptx$/i, '')
.replace(/[^a-zA-Z0-9가-힣_\-]/g, '_')
.replace(/_+/g, '_')
@@ -722,14 +738,21 @@ export const pptxTool: import('./registry.js').Tool = {
}
}
if (slide.image_url && !slide.image_path) {
const url = slide.image_url;
let url = slide.image_url;
// /api/files/<relative-path> is a server API alias for workspace/<relative-path>
if (url.startsWith('/api/files/')) {
url = path.join(workspacePath, decodeURIComponent(url.slice('/api/files/'.length)));
}
if (!url.startsWith('http://') && !url.startsWith('https://')) {
// Local workspace-relative path — copy to project folder
const srcPath = path.isAbsolute(url) ? url : path.join(workspacePath, url);
if (fs.existsSync(srcPath)) {
const ext = path.extname(srcPath) || '.png';
// Try original path, then spaces→underscores variant
const srcPathAlt = srcPath.replace(/ /g, '_');
const resolvedSrc = fs.existsSync(srcPath) ? srcPath : fs.existsSync(srcPathAlt) ? srcPathAlt : null;
if (resolvedSrc) {
const ext = path.extname(resolvedSrc) || '.png';
const fname = `slide${i + 1}_image${ext}`;
fs.copyFileSync(srcPath, path.join(projectDir, fname));
fs.copyFileSync(resolvedSrc, path.join(projectDir, fname));
slide.image_path = fname;
console.log(`[pptx] slide ${i + 1} image_url local copy -> ${fname}`);
} else {
@@ -826,6 +849,39 @@ export const pptxTool: import('./registry.js').Tool = {
}
}
// ── Phase 2.5: Copy source files (PDFs, image dirs) into project folder ──
const sourceFiles: string[] = Array.isArray(spec.source_files) ? spec.source_files : [];
for (const srcRel of sourceFiles) {
const srcAbs = path.isAbsolute(srcRel) ? srcRel : path.join(workspacePath, srcRel);
if (!fs.existsSync(srcAbs)) {
console.log(`[pptx] source_files: not found, skipping: ${srcRel}`);
continue;
}
const stat = fs.statSync(srcAbs);
if (stat.isDirectory()) {
// Copy entire directory (e.g., uploads/PMC123_images → projectDir/PMC123_images)
const destDir = path.join(projectDir, path.basename(srcAbs));
if (!fs.existsSync(destDir)) fs.mkdirSync(destDir, { recursive: true });
for (const f of fs.readdirSync(srcAbs)) {
try {
fs.copyFileSync(path.join(srcAbs, f), path.join(destDir, f));
} catch (e) {
console.log(`[pptx] source_files: could not copy ${f}: ${e}`);
}
}
console.log(`[pptx] source_files: copied dir ${path.basename(srcAbs)} -> ${destDir}`);
} else {
// Copy single file (e.g., pubmed/PMC123.pdf → projectDir/PMC123.pdf)
const dest = path.join(projectDir, path.basename(srcAbs));
try {
fs.copyFileSync(srcAbs, dest);
console.log(`[pptx] source_files: copied ${path.basename(srcAbs)} -> ${dest}`);
} catch (e) {
console.log(`[pptx] source_files: could not copy ${srcAbs}: ${e}`);
}
}
}
// ── Phase 3: Generate PPTX ──
return await generateWithPython(spec, workspacePath);
},
@@ -833,10 +889,10 @@ export const pptxTool: import('./registry.js').Tool = {
export const editPptxTool: import('./registry.js').Tool = {
name: 'edit_presentation',
description: 'Append slides to an existing .pptx file. Supports all slide types: title, content, section, image, table, chart, timeline. Use image_search to auto-find images. Do NOT use this to split a single presentation — use create_presentation for all slides at once.',
description: 'Append slides to an existing .pptx file. Supports all slide types: title, content, section, image, table, chart, timeline. Use image_search to auto-find images. Supports img_filter for image effects (grayscale, blur, contrast, bright, round). Do NOT use this to split a single presentation — use create_presentation for all slides at once.',
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 }] }',
spec: 'JSON object: { slides: [{ type, title, subtitle, bullets, body, content, font_size, image_path, image_url, image_search, img_filter, img_blur_radius, img_corner_radius, background, template }] }',
},
jsonSchema: {
type: 'object',
@@ -865,6 +921,9 @@ export const editPptxTool: import('./registry.js').Tool = {
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 into the project folder. Overrides image_path if both provided. Supports http/https URLs.' },
image_search: { type: 'string', description: 'Search keyword to find an image automatically (e.g. "golden retriever", "mountain sunset"). Overrides image_url if both provided. Images are downloaded before slides are created.' },
img_filter: { type: 'string', description: 'Image effect filter: "grayscale" (흑백), "blur" (블러), "contrast" (대비 강화), "bright" (밝게), "round" (둥근 모서리), or "none". Applied to the slide image via Pillow before embedding.' },
img_blur_radius: { type: 'number', description: 'Blur radius when img_filter="blur" (default: 5, range: 1-20)' },
img_corner_radius: { type: 'number', description: 'Corner radius % when img_filter="round" (default: 15, range: 5-50)' },
background: { type: 'string', description: `Skin name (${SKIN_NAMES.join(', ')}) or image file path (relative to project folder)` },
template: { type: 'string', description: `Per-slide template override: ${TEMPLATE_NAMES.join(', ')}` },
notes: { type: 'string', description: 'Speaker notes' },
+42 -12
View File
@@ -348,8 +348,7 @@ export const pubmedFulltextTool = {
};
}
// Download PDF
const config = getConfig().getConfig();
// Download PDF — try Unpaywall URL first, then Europe PMC as fallback
const workspaceDir = getWorkspacePath(args);
const pdfDir = path.join(workspaceDir, 'pubmed');
fs.mkdirSync(pdfDir, { recursive: true });
@@ -358,16 +357,47 @@ export const pubmedFulltextTool = {
? path.join(workspaceDir, args.save_path)
: path.join(pdfDir, `${pmcid}.pdf`);
const pdfRes = await fetch(pdfUrl, {
signal: AbortSignal.timeout(60_000),
headers: { 'User-Agent': 'Mozilla/5.0 (compatible; SmallClaw/1.0; PubMed research bot)' },
});
if (!pdfRes.ok) {
return { success: false, error: `PDF download failed: HTTP ${pdfRes.status} from ${pdfUrl}` };
}
const pdfBuf = Buffer.from(await pdfRes.arrayBuffer());
fs.writeFileSync(pdfDest, pdfBuf);
const europePmcUrl = `https://europepmc.org/api/getPdf?pmcid=${pmcid}`;
const urlsToTry = [pdfUrl, europePmcUrl].filter(Boolean);
let pdfBuf: Buffer | null = null;
let usedUrl = '';
for (const tryUrl of urlsToTry) {
try {
const res = await fetch(tryUrl, {
signal: AbortSignal.timeout(60_000),
headers: {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
'Accept': 'application/pdf,*/*',
'Accept-Language': 'en-US,en;q=0.9',
'Referer': 'https://europepmc.org/',
},
});
if (!res.ok) continue;
const buf = Buffer.from(await res.arrayBuffer());
// Reject HTML responses (PMC sometimes returns HTML instead of PDF)
if (!buf.slice(0, 5).toString('ascii').startsWith('%PDF')) {
console.log(`[pubmed] ${tryUrl} returned non-PDF content (HTML?), trying next`);
continue;
}
pdfBuf = buf;
usedUrl = tryUrl;
break;
} catch {}
}
if (!pdfBuf) {
return {
success: false,
error: [
`PDF download failed for ${pmcid}: all sources returned non-PDF content.`,
`Tried: ${urlsToTry.join(', ')}`,
`Try format "text" to get the plain-text version instead.`,
].join('\n'),
};
}
fs.writeFileSync(pdfDest, pdfBuf);
const sizeKb = (pdfBuf.length / 1024).toFixed(1);
const relPath = path.relative(workspaceDir, pdfDest);
return {
@@ -378,7 +408,7 @@ export const pubmedFulltextTool = {
`Saved to: ${relPath} (${sizeKb} KB)`,
`File link: /api/files/${relPath}`,
].filter(Boolean).join('\n'),
data: { pmcid, doi, pdf_url: pdfUrl, save_path: pdfDest, size_kb: Number(sizeKb) },
data: { pmcid, doi, pdf_url: usedUrl, save_path: pdfDest, size_kb: Number(sizeKb) },
};
}
} catch (oaErr: any) {
+5 -3
View File
@@ -81,7 +81,7 @@ export const openalexSearchTool = {
'per-page': String(limit),
sort: sortKey,
filter: filters.join(','),
select: 'id,doi,display_name,publication_year,cited_by_count,open_access,authorships,abstract_inverted_index,primary_location',
select: 'id,doi,display_name,publication_year,cited_by_count,open_access,best_oa_location,authorships,abstract_inverted_index,primary_location',
mailto: POLITE_EMAIL,
});
@@ -111,7 +111,7 @@ export const openalexSearchTool = {
.join(', ') + ((r.authorships || []).length > 6 ? ' et al.' : '');
const citations = r.cited_by_count ?? 0;
const isOa = r.open_access?.is_oa ?? false;
const oaUrl = r.open_access?.oa_url || '';
const oaUrl = r.best_oa_location?.pdf_url || r.open_access?.oa_url || '';
const abstract = reconstructAbstract(r.abstract_inverted_index).slice(0, 400);
lines.push(`[${i + 1}] ${title}`);
@@ -132,7 +132,8 @@ export const openalexSearchTool = {
doi: r.doi ? String(r.doi).replace('https://doi.org/', '') : '',
citations: r.cited_by_count,
is_oa: r.open_access?.is_oa,
oa_url: r.open_access?.oa_url,
oa_url: r.best_oa_location?.pdf_url || null,
abstract: reconstructAbstract(r.abstract_inverted_index).slice(0, 2000),
authors: (r.authorships || []).slice(0, 6).map((a: any) => a?.author?.display_name).filter(Boolean),
})) },
};
@@ -243,6 +244,7 @@ export const semanticSearchTool = {
citations: p.citationCount,
inf_citations: p.influentialCitationCount,
oa_pdf: p.openAccessPdf?.url,
abstract: String(p.abstract || '').slice(0, 2000),
authors: (p.authors || []).slice(0, 6).map((a: any) => a.name),
})) },
};
+217 -2
View File
@@ -560,9 +560,11 @@ function setSidebarTab(tab) {
document.getElementById('tab-jobs').classList.toggle('active', tab === 'jobs');
document.getElementById('tab-skills').classList.toggle('active', tab === 'skills');
document.getElementById('tab-code').classList.toggle('active', tab === 'code');
document.getElementById('tab-pptx').classList.toggle('active', tab === 'pptx');
document.getElementById('sidebar-jobs').style.display = tab === 'jobs' ? 'flex' : 'none';
document.getElementById('sidebar-skills').style.display = tab === 'skills' ? 'flex' : 'none';
document.getElementById('sidebar-code').style.display = tab === 'code' ? 'flex' : 'none';
document.getElementById('sidebar-pptx').style.display = tab === 'pptx' ? 'flex' : 'none';
if (tab === 'skills') { initSkillsUserSelector(); loadInstalledSkills(); }
if (tab === 'code') { codeSbRefresh(); csbLoadModels(); csbLoadCodeDir(); }
}
@@ -1420,6 +1422,8 @@ async function sendChat(queuedMessage = null) {
`${stepNum ? `Step ${stepNum}: ` : ''}${action || 'tool'}${syntheticTag} => ${text || '(no output)'}`,
);
loadAgentSessionContext();
// PPTX: capture extracted images
if (ok && action === 'pdf_extract_images') pptxCaptureImages(text);
// Auto-open file in code editor when agent writes a code file
// (via create_file OR shell/run_command redirect captured at tool_call).
if (ok && (action === 'create_file' || action === 'shell' || action === 'run_command')) {
@@ -1724,6 +1728,14 @@ async function sendChat(queuedMessage = null) {
}
persistActiveChat();
// PPTX: detect pptx-outline block in final reply
if (finalReply) {
const outlineMatch = finalReply.match(/```pptx-outline\s*\n([\s\S]*?)```/);
if (outlineMatch) {
try { pptxSetOutline(JSON.parse(outlineMatch[1])); } catch {}
}
}
// Auto-open code blocks from final reply in the editor
if (finalReply && typeof codeAiRenderMarkdown === 'function') {
const codeBlockRe = /```([\w\-]*)[ \t]*\r?\n([\s\S]*?)```/g;
@@ -3263,7 +3275,7 @@ async function loadContextViewerTab() {
}
function escHtml(s) {
return String(s || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
return String(s || '').replace(/&/g,'&amp;').replace(/\\/g,'&#92;').replace(/`/g,'&#96;').replace(/\$/g,'&#36;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
// --- PPT Template & Skin Tab ---------------------------------------------------
@@ -5013,7 +5025,7 @@ function log(text, type = 'log') {
// ---- Helpers ----
function escHtml(str) {
if (!str) return '';
return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
return String(str).replace(/&/g,'&amp;').replace(/\\/g,'&#92;').replace(/`/g,'&#96;').replace(/\$/g,'&#36;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function _normalizeFileUrl(url) {
@@ -9901,3 +9913,206 @@ function setupCodeVResize() {
}
}
// ── PPTX Workflow Sidebar ─────────────────────────────────────────────────────
let _pptxImages = []; // {url, thumb, label}
let _pptxOutline = null; // parsed pptx-outline JSON
let _pptxOutlineEdits = {}; // {index: {title, bullets}}
function setPptxSbTab(tab) {
['setup','images','outline'].forEach(t => {
document.getElementById('psb-tab-' + t).classList.toggle('active', t === tab);
const el = document.getElementById('psb-' + t);
if (el) el.style.display = t === tab ? (t === 'outline' ? 'flex' : (t === 'images' ? 'block' : 'flex')) : 'none';
});
}
function pptxSetStatus(msg) {
const el = document.getElementById('psb-status');
if (el) el.textContent = msg;
}
function pptxStartWorkflow() {
const topic = (document.getElementById('psb-topic').value || '').trim();
const pmcidsRaw = (document.getElementById('psb-pmcids').value || '').trim();
const template = document.getElementById('psb-template').value || 'dark';
const slideCount = parseInt(document.getElementById('psb-slide-count').value) || 0;
if (!topic) { pptxSetStatus('주제를 입력하세요.'); return; }
const pmcids = pmcidsRaw
.split(/[\n,]+/)
.map(s => s.trim().replace(/^PMC/i, 'PMC'))
.filter(Boolean);
_pptxImages = [];
_pptxOutline = null;
_pptxOutlineEdits = {};
pptxRenderImageGrid();
const cardsEl = document.getElementById('psb-outline-cards');
if (cardsEl) cardsEl.innerHTML = '<div style="color:var(--muted);font-size:11px;padding:8px;text-align:center">아웃라인 생성 중...</div>';
const genBtn = document.getElementById('psb-gen-btn');
if (genBtn) { genBtn.disabled = true; genBtn.style.opacity = '.5'; }
// Build workflow message
const pmcLine = pmcids.length
? `\nPMCIDs: ${pmcids.join(', ')}`
: '';
const slideLine = slideCount ? `\n슬라이드 수: ${slideCount}장` : '';
const msg = `[PPTX 워크플로 시작]\n주제: ${topic}${pmcLine}\n템플릿: ${template}${slideLine}\n\n아래 순서로 진행해주세요:\n1. 작업 폴더 생성 (주제 기반)\n2. PDF 다운로드 (pubmed_fulltext, 위 PMCIDs)\n3. 이미지 추출 (pdf_extract_images, 각 PDF)\n4. 소형 이미지 필터링 (python_eval)\n5. 슬라이드 구성을 \`\`\`pptx-outline 블록으로 출력 (JSON 형식)\n6. 확인 대기 (create_presentation은 아직 호출하지 마세요)`;
pptxSetStatus('워크플로 시작...');
setSidebarTab('pptx');
setPptxSbTab('setup');
// Send via main chat
const input = document.getElementById('chat-input');
if (input) {
input.value = msg;
sendChat();
}
}
function pptxCaptureImages(toolResultText) {
// Parse image links from pdf_extract_images output: [label](/api/files/...)
const re = /\[([^\]]*)\]\((\/api\/files\/[^)]+\.(?:png|jpg|jpeg|gif|webp))\)/gi;
let m;
while ((m = re.exec(toolResultText)) !== null) {
const label = m[1];
const url = m[2];
if (!_pptxImages.some(i => i.url === url)) {
_pptxImages.push({ url, label });
}
}
if (_pptxImages.length) {
pptxRenderImageGrid();
const countEl = document.getElementById('psb-img-count');
if (countEl) countEl.textContent = `(${_pptxImages.length})`;
// Auto-switch to images tab if PPTX tab is active
if (sidebarTab === 'pptx') setPptxSbTab('images');
pptxSetStatus(`이미지 ${_pptxImages.length}개 추출됨`);
}
}
function pptxRenderImageGrid() {
const grid = document.getElementById('psb-image-grid');
if (!grid) return;
if (!_pptxImages.length) {
grid.innerHTML = '<div style="grid-column:1/-1;color:var(--muted);font-size:11px;padding:8px;text-align:center">이미지 추출 후 표시됩니다</div>';
return;
}
grid.innerHTML = _pptxImages.map((img, idx) => `
<div style="position:relative;border:1px solid var(--line);border-radius:6px;overflow:hidden;cursor:pointer;aspect-ratio:4/3;background:var(--panel-2)"
onclick="pptxImageClick(${idx})" title="${escHtml(img.label)}">
<img src="${escHtml(img.url)}" style="width:100%;height:100%;object-fit:cover" loading="lazy"
onerror="this.parentNode.style.background='var(--panel)';this.style.display='none'">
<div style="position:absolute;bottom:0;left:0;right:0;background:rgba(0,0,0,.5);color:#fff;font-size:9px;padding:2px 4px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${escHtml(img.label)}</div>
</div>`).join('');
}
function pptxImageClick(idx) {
const img = _pptxImages[idx];
if (!img) return;
window.open(img.url, '_blank', 'noopener');
}
function pptxSetOutline(data) {
_pptxOutline = data;
_pptxOutlineEdits = {};
pptxRenderOutlineCards();
const genBtn = document.getElementById('psb-gen-btn');
if (genBtn) { genBtn.disabled = false; genBtn.style.opacity = '1'; }
if (sidebarTab === 'pptx') setPptxSbTab('outline');
pptxSetStatus(`아웃라인 준비 (${(data.slides || []).length}장)`);
}
const SLIDE_TYPE_ICON = { title:'🏷', section:'📂', content:'📝', image:'🖼', table:'📊', chart:'📈', timeline:'⏳', compare:'⚖' };
function pptxRenderOutlineCards() {
const container = document.getElementById('psb-outline-cards');
if (!container || !_pptxOutline) return;
const slides = _pptxOutline.slides || [];
if (!slides.length) {
container.innerHTML = '<div style="color:var(--muted);font-size:11px;padding:8px">슬라이드가 없습니다</div>';
return;
}
container.innerHTML = slides.map((s, i) => {
const icon = SLIDE_TYPE_ICON[s.type] || '📄';
const imgThumb = s.image_url
? `<img src="${escHtml(s.image_url)}" style="width:40px;height:30px;object-fit:cover;border-radius:4px;flex-shrink:0" loading="lazy">`
: `<div style="width:40px;height:30px;border-radius:4px;background:var(--panel);flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:14px">🖼</div>`;
const bulletsPreview = Array.isArray(s.bullets) && s.bullets.length
? `<div style="font-size:10px;color:var(--muted);margin-top:3px;overflow:hidden;max-height:32px">${s.bullets.slice(0,2).map(b => `• ${b}`).join('<br>')}</div>`
: '';
return `<div class="psb-slide-card" style="border:1px solid var(--line);border-radius:8px;padding:7px 8px;background:var(--panel-2);cursor:pointer" onclick="pptxToggleEdit(${i})">
<div style="display:flex;align-items:center;gap:7px">
<span style="font-size:10px;color:var(--muted);flex-shrink:0;width:18px;text-align:right">${i+1}</span>
${imgThumb}
<div style="flex:1;min-width:0">
<div style="font-size:12px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${icon} ${escHtml(s.title || '(제목 없음)')}</div>
<div style="font-size:10px;color:var(--muted)">${s.type}</div>
${bulletsPreview}
</div>
</div>
<div id="psb-edit-${i}" style="display:none;margin-top:7px;border-top:1px solid var(--line);padding-top:7px">
<input type="text" value="${escHtml(s.title || '')}" oninput="pptxEditTitle(${i}, this.value)"
style="width:100%;box-sizing:border-box;font-size:12px;padding:4px 6px;background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:6px;margin-bottom:4px">
${Array.isArray(s.bullets) ? `<textarea rows="3" oninput="pptxEditBullets(${i}, this.value)"
style="width:100%;box-sizing:border-box;font-size:11px;padding:4px 6px;background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:6px;resize:vertical;font-family:'IBM Plex Mono',monospace">${escHtml((s.bullets||[]).join('\n\n'))}</textarea>` : ''}
</div>
</div>`;
}).join('');
}
function pptxToggleEdit(idx) {
const el = document.getElementById('psb-edit-' + idx);
if (el) el.style.display = el.style.display === 'none' ? 'block' : 'none';
}
function pptxEditTitle(idx, val) {
if (!_pptxOutlineEdits[idx]) _pptxOutlineEdits[idx] = {};
_pptxOutlineEdits[idx].title = val;
}
function pptxEditBullets(idx, val) {
if (!_pptxOutlineEdits[idx]) _pptxOutlineEdits[idx] = {};
_pptxOutlineEdits[idx].bullets = val.split(/\n\n+/).map(g => g.replace(/^\n+|\n+$/g, '')).filter(g => g.trim() !== '');
}
function pptxGenerate() {
if (!_pptxOutline) return;
// Apply edits to outline
const slides = (_pptxOutline.slides || []).map((s, i) => {
const ed = _pptxOutlineEdits[i];
if (!ed) return s;
return Object.assign({}, s, ed.title !== undefined ? { title: ed.title } : {}, ed.bullets !== undefined ? { bullets: ed.bullets } : {});
});
const edited = Object.assign({}, _pptxOutline, { slides });
const hasEdits = Object.keys(_pptxOutlineEdits).length > 0;
const msg = hasEdits
? `아웃라인을 수정했습니다. 수정된 아웃라인으로 create_presentation을 호출해주세요:\n\`\`\`json\n${JSON.stringify(edited, null, 2)}\n\`\`\``
: `아웃라인 확인했습니다. create_presentation으로 슬라이드를 생성해주세요.`;
const genBtn = document.getElementById('psb-gen-btn');
if (genBtn) { genBtn.disabled = true; genBtn.style.opacity = '.5'; }
pptxSetStatus('생성 중...');
const input = document.getElementById('chat-input');
if (input) { input.value = msg; sendChat(); }
}
function pptxResetWorkflow() {
_pptxImages = [];
_pptxOutline = null;
_pptxOutlineEdits = {};
pptxRenderImageGrid();
const cardsEl = document.getElementById('psb-outline-cards');
if (cardsEl) cardsEl.innerHTML = '<div style="color:var(--muted);font-size:11px;padding:8px;text-align:center">아웃라인 생성 후 표시됩니다</div>';
const genBtn = document.getElementById('psb-gen-btn');
if (genBtn) { genBtn.disabled = true; genBtn.style.opacity = '.5'; }
const countEl = document.getElementById('psb-img-count');
if (countEl) countEl.textContent = '';
pptxSetStatus('');
setPptxSbTab('setup');
}
+71
View File
@@ -110,6 +110,7 @@
<button class="sidebar-tab active" id="tab-jobs" onclick="setSidebarTab('jobs')">세션</button>
<button class="sidebar-tab" id="tab-skills" onclick="setSidebarTab('skills')">🧩 스킬</button>
<button class="sidebar-tab" id="tab-code" onclick="setSidebarTab('code')">💻 코드</button>
<button class="sidebar-tab" id="tab-pptx" onclick="window.open('/pptx-wizard.html','_blank')" title="슬라이드 제작 마법사">📊 슬라이드</button>
</div>
<!-- SESSIONS TAB -->
@@ -236,6 +237,76 @@
</div>
</div>
<!-- PPTX SIDEBAR -->
<div id="sidebar-pptx" style="display:none;flex-direction:column;flex:1;min-height:0;overflow:hidden">
<!-- inner tabs -->
<div style="display:flex;border-bottom:1px solid var(--line);flex-shrink:0;background:var(--panel-2)">
<button class="code-sb-tab active" id="psb-tab-setup" onclick="setPptxSbTab('setup')">설정</button>
<button class="code-sb-tab" id="psb-tab-images" onclick="setPptxSbTab('images')">이미지 <span id="psb-img-count"></span></button>
<button class="code-sb-tab" id="psb-tab-outline" onclick="setPptxSbTab('outline')">아웃라인</button>
</div>
<!-- 설정 탭 -->
<div id="psb-setup" style="flex:1;overflow-y:auto;padding:14px 12px;display:flex;flex-direction:column;gap:10px">
<div>
<div style="font-size:10px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin-bottom:5px">주제</div>
<input type="text" id="psb-topic" placeholder="예: 상악동 거상술 최신 동향"
style="width:100%;box-sizing:border-box;font-size:12px;padding:6px 8px;background:var(--panel-2);color:var(--text);border:1px solid var(--line);border-radius:8px">
</div>
<div>
<div style="font-size:10px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin-bottom:5px">PMCIDs <span style="font-weight:400;text-transform:none">(줄바꿈 또는 쉼표)</span></div>
<textarea id="psb-pmcids" rows="4" placeholder="PMC8273047&#10;PMC10340512"
style="width:100%;box-sizing:border-box;font-size:12px;padding:6px 8px;background:var(--panel-2);color:var(--text);border:1px solid var(--line);border-radius:8px;font-family:'IBM Plex Mono',monospace;resize:vertical"></textarea>
</div>
<div>
<div style="font-size:10px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin-bottom:5px">템플릿</div>
<select id="psb-template"
style="width:100%;font-size:12px;padding:6px 8px;background:var(--panel-2);color:var(--text);border:1px solid var(--line);border-radius:8px;cursor:pointer">
<option value="dark">dark</option>
<option value="business">business</option>
<option value="minimal">minimal</option>
<option value="creative">creative</option>
<option value="pastel">pastel</option>
<option value="warm">warm</option>
</select>
</div>
<div>
<div style="font-size:10px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin-bottom:5px">슬라이드 수 (선택)</div>
<input type="number" id="psb-slide-count" min="5" max="30" placeholder="자동"
style="width:100%;box-sizing:border-box;font-size:12px;padding:6px 8px;background:var(--panel-2);color:var(--text);border:1px solid var(--line);border-radius:8px">
</div>
<button onclick="pptxStartWorkflow()" id="psb-start-btn"
style="padding:9px;background:var(--brand);color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:13px;font-weight:700">
▶ 시작
</button>
<div id="psb-status" style="font-size:11px;color:var(--muted);min-height:16px"></div>
</div>
<!-- 이미지 탭 -->
<div id="psb-images" style="display:none;flex:1;overflow-y:auto;padding:10px">
<div id="psb-image-grid" style="display:grid;grid-template-columns:repeat(2,1fr);gap:5px">
<div style="grid-column:1/-1;color:var(--muted);font-size:11px;padding:8px;text-align:center">이미지 추출 후 표시됩니다</div>
</div>
</div>
<!-- 아웃라인 탭 -->
<div id="psb-outline" style="display:none;flex-direction:column;flex:1;min-height:0">
<div id="psb-outline-cards" style="flex:1;overflow-y:auto;padding:10px;display:flex;flex-direction:column;gap:5px">
<div style="color:var(--muted);font-size:11px;padding:8px;text-align:center">아웃라인 생성 후 표시됩니다</div>
</div>
<div style="padding:8px 10px;border-top:1px solid var(--line);flex-shrink:0;display:flex;gap:6px">
<button onclick="pptxGenerate()" id="psb-gen-btn" disabled
style="flex:1;padding:8px;background:var(--brand);color:#fff;border:none;border-radius:8px;cursor:pointer;font-size:12px;font-weight:700;opacity:.5">
✅ 슬라이드 생성
</button>
<button onclick="pptxResetWorkflow()" title="초기화"
style="padding:8px 10px;background:var(--panel-2);color:var(--muted);border:1px solid var(--line);border-radius:8px;cursor:pointer;font-size:12px">
↺
</button>
</div>
</div>
</div>
<!-- SERVER LOG PANEL -->
<div id="sidebar-log-panel">
<div id="sidebar-log-header" onclick="toggleLogPanel()" style="cursor:pointer">
File diff suppressed because it is too large. Load diff
+149
View File
@@ -0,0 +1,149 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Python Runner</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&display=swap');
:root { --bg: #0c0c0c; --panel: #1a1a2e; --accent: #3b82f6; --green: #22c55e; --red: #ef4444; --muted: #6b7280; }
* { margin:0; padding:0; box-sizing:border-box; }
body { background:var(--bg); color:#e5e7eb; font-family:'IBM Plex Mono',monospace; height:100vh; display:flex; flex-direction:column; }
.header { display:flex; align-items:center; gap:12px; padding:10px 16px; background:var(--panel); border-bottom:1px solid #2d2d4a; flex-shrink:0; }
.header h1 { font-size:14px; font-weight:600; color:#e5e7eb; }
.header .file { font-size:12px; color:var(--accent); }
.status { font-size:11px; padding:2px 8px; border-radius:4px; font-weight:600; }
.status.loading { background:#1e3a5f; color:#60a5fa; }
.status.ready { background:#1a3a2a; color:var(--green); }
.status.running { background:#3a3a1a; color:#fbbf24; }
.status.error { background:#3a1a1a; color:var(--red); }
.toolbar { display:flex; gap:8px; margin-left:auto; }
.toolbar button { background:#252540; border:1px solid #3a3a5a; color:#e5e7eb; border-radius:6px; padding:6px 14px; font-size:12px; cursor:pointer; font-family:inherit; transition:all .15s; }
.toolbar button:hover { background:#353555; border-color:#4a4a7a; }
.toolbar button:disabled { opacity:.4; cursor:not-allowed; }
.toolbar button.run { background:#1a3a2a; border-color:#2d5a3a; color:var(--green); }
.toolbar button.run:hover { background:#224a3a; }
.output { flex:1; overflow:auto; padding:16px; font-size:13px; line-height:1.6; white-space:pre-wrap; word-break:break-all; }
.output .stdout { color:#e5e7eb; }
.output .stderr { color:var(--red); }
.output .info { color:var(--muted); font-style:italic; }
.footer { padding:8px 16px; border-top:1px solid #2d2d4a; font-size:11px; color:var(--muted); background:var(--panel); flex-shrink:0; display:flex; justify-content:space-between; }
</style>
</head>
<body>
<div class="header">
<h1>🐍 Python</h1>
<span class="file" id="filename"></span>
<span class="status loading" id="status">Pyodide 로딩중...</span>
<div class="toolbar">
<button class="run" id="btn-run" disabled onclick="runCode()">▶ 실행</button>
</div>
</div>
<div class="output" id="output"><span class="info">Pyodide를 로딩하고 있습니다...</span></div>
<div class="footer">
<span id="footer-info">Pyodide (WebAssembly Python)</span>
<span id="exec-time"></span>
</div>
<script src="https://cdn.jsdelivr.net/pyodide/v0.27.3/full/pyodide.js"></script>
<script>
let pyodide = null;
let code = sessionStorage.getItem('py_run_code') || '';
const fileName = sessionStorage.getItem('py_run_name') || 'script.py';
sessionStorage.removeItem('py_run_code');
sessionStorage.removeItem('py_run_name');
document.getElementById('filename').textContent = fileName;
document.title = fileName + ' — Python Runner';
function setStatus(text, cls) {
const el = document.getElementById('status');
el.textContent = text;
el.className = 'status ' + cls;
}
function appendOutput(text, cls = 'stdout') {
const el = document.getElementById('output');
const span = document.createElement('span');
span.className = cls;
span.textContent = text;
el.appendChild(span);
el.scrollTop = el.scrollHeight;
}
function clearOutput() {
document.getElementById('output').innerHTML = '';
}
async function initPyodide() {
try {
pyodide = await loadPyodide();
setStatus('준비', 'ready');
document.getElementById('btn-run').disabled = false;
const pyVer = pyodide.runPython('import sys; sys.version.split()[0]');
document.getElementById('footer-info').textContent = `Pyodide ${pyodide.version} (Python ${pyVer})`;
clearOutput();
if (code) {
appendOutput(`${fileName} 로드 완료 (${(new TextEncoder().encode(code).length / 1024).toFixed(1)}KB). ▶ 실행을 누르세요.\n`, 'info');
} else {
appendOutput('코드가 전달되지 않았습니다.\n', 'stderr');
setStatus('코드 없음', 'error');
}
} catch (e) {
setStatus('로딩 실패', 'error');
clearOutput();
appendOutput('Pyodide 로딩 실패:\n' + (e.stack || e.message || e) + '\n', 'stderr');
}
}
async function runCode() {
if (!pyodide) return;
if (!code) { appendOutput('실행할 코드가 없습니다.\n', 'stderr'); return; }
document.getElementById('btn-run').disabled = true;
clearOutput();
setStatus('실행중', 'running');
const t0 = performance.now();
try {
// Capture stdout/stderr
pyodide.runPython(`
import sys, io
_stdout_capture = io.StringIO()
_stderr_capture = io.StringIO()
sys.stdout = _stdout_capture
sys.stderr = _stderr_capture
`);
pyodide.runPython(code);
const stdout = pyodide.runPython('_stdout_capture.getvalue()');
const stderr = pyodide.runPython('_stderr_capture.getvalue()');
if (stdout) appendOutput(stdout);
if (stderr) appendOutput(stderr, 'stderr');
setStatus('완료', 'ready');
} catch (e) {
// Show full Python traceback
const tb = e.stack || e.message || String(e);
appendOutput(tb + '\n', 'stderr');
setStatus('오류', 'error');
} finally {
// Safely restore stdout
try {
pyodide.runPython(`
try:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
except:
sys.stdout = io.StringIO()
sys.stderr = io.StringIO()
`);
} catch {}
const elapsed = ((performance.now() - t0) / 1000).toFixed(2);
document.getElementById('exec-time').textContent = `${elapsed}s`;
document.getElementById('btn-run').disabled = false;
}
}
initPyodide();
</script>
</body>
</html>