[Instagram Reels] Phase 2 완성 - instagram_bot.py: publish_reels() 추가 (MP4 → Reels API) - upload_video_container(), wait_for_video_ready() 구현 - 로컬 경로 → 공개 URL 자동 변환 (image_host.get_public_video_url()) - scheduler.py: job_distribute_instagram_reels() 추가 (10:30) - image_host.py: get_public_video_url() + 로컬 비디오 서버 추가 - VIDEO_HOST_BASE_URL 환경변수 지원 (Tailscale/CDN) [writer_bot.py] 신규 — 독립 실행형 글쓰기 봇 - api_content.py manual-write 엔드포인트에서 subprocess 호출 가능 - run_pending(): 오늘 날짜 미처리 글감 자동 처리 - run_from_topic(): 직접 주제 지정 - run_from_file(): JSON 파일 지정 - CLI: python bots/writer_bot.py [--topic "..." | --file path.json | --limit N] [보조 시스템 신규] v3.1 CLI + Assist 모드 - blog.cmd: venv Python 경유 Windows 런처 - blog_runtime.py + runtime_guard.py: 실행 진입점 + venv 검증 - blog_engine_cli.py: 대시보드 API 기반 CLI (blog status, blog review 등) - bots/assist_bot.py: URL 기반 수동 어시스트 파이프라인 - dashboard/backend/api_assist.py + frontend/Assist.jsx: 수동모드 탭 [engine_loader.py] v3.1 개선 - OpenClawWriter: --json 플래그 + payloads 파싱 + plain text 폴백 - ClaudeWebWriter: Playwright 쿠키 세션 (Cloudflare 차단으로 현재 비활성) - GeminiWebWriter: gemini-webapi 비공식 클라이언트 [scheduler.py] v3.1 개선 - _call_openclaw(): 플레이스홀더 → EngineLoader 실제 호출 - _build_openclaw_prompt(): 구조화된 HTML 원고 프롬프트 - data/originals/: 원본 article JSON 저장 경로 추가 [설정/환경] 정비 - .env.example: SEEDANCE/ELEVENLABS/GEMINI/RUNWAY 복원 + VIDEO_HOST_BASE_URL, GEMINI_WEB_* , REMOTE_CLAUDE_POLLING_ENABLED 추가 - scripts/setup.bat: data/originals, outputs, assist, novels, config/novels 디렉토리 생성 + 폰트 다운로드 + blog.cmd 기반 Task Scheduler 등록 - requirements.txt: fastapi, uvicorn, python-multipart 추가 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
186 lines
6.6 KiB
Python
186 lines
6.6 KiB
Python
"""
|
|
dashboard/backend/api_content.py
|
|
Content 탭 API — 칸반 보드, 승인/거부, 수동 트리거
|
|
"""
|
|
import json
|
|
import subprocess
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
from fastapi import APIRouter, HTTPException
|
|
from pydantic import BaseModel
|
|
|
|
from runtime_guard import project_python_path, run_with_project_python
|
|
|
|
BASE_DIR = Path(__file__).parent.parent.parent
|
|
DATA_DIR = BASE_DIR / "data"
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
class WriteRequest(BaseModel):
|
|
topic: str = ""
|
|
|
|
|
|
def _read_folder_cards(folder: Path, status: str) -> list:
|
|
"""폴더에서 JSON 파일을 읽어 칸반 카드 목록 반환"""
|
|
cards = []
|
|
if not folder.exists():
|
|
return cards
|
|
|
|
for f in sorted(folder.glob("*.json"), key=lambda x: x.stat().st_mtime, reverse=True):
|
|
try:
|
|
data = json.loads(f.read_text(encoding="utf-8"))
|
|
cards.append({
|
|
"id": f.stem,
|
|
"file": str(f),
|
|
"title": data.get("title", f.stem),
|
|
"corner": data.get("corner", ""),
|
|
"source": data.get("source", ""),
|
|
"quality_score": data.get("quality_score", data.get("score", 0)),
|
|
"created_at": data.get("created_at", data.get("collected_at", "")),
|
|
"status": status,
|
|
"summary": data.get("summary", data.get("body", "")[:200] if data.get("body") else ""),
|
|
})
|
|
except Exception:
|
|
pass
|
|
return cards
|
|
|
|
|
|
@router.get("/content")
|
|
async def get_content():
|
|
"""칸반 4열 데이터 반환"""
|
|
queue = _read_folder_cards(DATA_DIR / "topics", "queue")
|
|
queue += _read_folder_cards(DATA_DIR / "collected", "queue")
|
|
|
|
writing = _read_folder_cards(DATA_DIR / "drafts", "writing")
|
|
|
|
review = _read_folder_cards(DATA_DIR / "pending_review", "review")
|
|
|
|
published = _read_folder_cards(DATA_DIR / "published", "published")
|
|
|
|
return {
|
|
"columns": {
|
|
"queue": {"label": "글감큐", "cards": queue},
|
|
"writing": {"label": "작성중", "cards": writing},
|
|
"review": {"label": "검수대기", "cards": review},
|
|
"published": {"label": "발행완료", "cards": published[:20]}, # 최근 20개만
|
|
}
|
|
}
|
|
|
|
|
|
@router.post("/content/{item_id}/approve")
|
|
async def approve_content(item_id: str):
|
|
"""검수 승인 — pending_review → published로 이동"""
|
|
src = DATA_DIR / "pending_review" / f"{item_id}.json"
|
|
if not src.exists():
|
|
raise HTTPException(status_code=404, detail="파일을 찾을 수 없습니다.")
|
|
|
|
try:
|
|
data = json.loads(src.read_text(encoding="utf-8"))
|
|
data["approved_at"] = datetime.now().isoformat()
|
|
data["status"] = "approved"
|
|
|
|
dst = DATA_DIR / "published" / f"{item_id}.json"
|
|
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
dst.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
src.unlink(missing_ok=True)
|
|
|
|
return {"success": True, "message": f"{item_id} 승인 완료"}
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.post("/content/{item_id}/reject")
|
|
async def reject_content(item_id: str):
|
|
"""검수 거부 — pending_review → discarded로 이동"""
|
|
src = DATA_DIR / "pending_review" / f"{item_id}.json"
|
|
if not src.exists():
|
|
raise HTTPException(status_code=404, detail="파일을 찾을 수 없습니다.")
|
|
|
|
try:
|
|
data = json.loads(src.read_text(encoding="utf-8"))
|
|
data["rejected_at"] = datetime.now().isoformat()
|
|
data["status"] = "rejected"
|
|
|
|
dst = DATA_DIR / "discarded" / f"{item_id}.json"
|
|
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
dst.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
src.unlink(missing_ok=True)
|
|
|
|
return {"success": True, "message": f"{item_id} 거부 완료"}
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.post("/manual-write")
|
|
async def manual_write(req: WriteRequest):
|
|
"""collector_bot + writer_bot 수동 트리거"""
|
|
bots_dir = BASE_DIR / "bots"
|
|
python = project_python_path()
|
|
|
|
if not python.exists():
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail=(
|
|
f"프로젝트 가상환경 Python이 없습니다: {python}. "
|
|
"venv 생성 후 requirements.txt를 설치하세요."
|
|
),
|
|
)
|
|
|
|
results = []
|
|
|
|
# collector_bot 실행
|
|
collector = bots_dir / "collector_bot.py"
|
|
if collector.exists():
|
|
try:
|
|
result = run_with_project_python(
|
|
[str(collector)],
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=120,
|
|
cwd=str(BASE_DIR),
|
|
encoding="utf-8",
|
|
)
|
|
results.append({
|
|
"step": "collector",
|
|
"success": result.returncode == 0,
|
|
"python": str(python),
|
|
"output": result.stdout[-500:] if result.stdout else "",
|
|
"error": result.stderr[-300:] if result.stderr else "",
|
|
})
|
|
except subprocess.TimeoutExpired:
|
|
results.append({"step": "collector", "success": False, "python": str(python), "error": "타임아웃"})
|
|
except Exception as e:
|
|
results.append({"step": "collector", "success": False, "python": str(python), "error": str(e)})
|
|
else:
|
|
results.append({"step": "collector", "success": False, "python": str(python), "error": "파일 없음"})
|
|
|
|
# writer_bot 실행
|
|
writer = bots_dir / "writer_bot.py"
|
|
if writer.exists():
|
|
try:
|
|
result = run_with_project_python(
|
|
[str(writer)],
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=300,
|
|
cwd=str(BASE_DIR),
|
|
encoding="utf-8",
|
|
)
|
|
results.append({
|
|
"step": "writer",
|
|
"success": result.returncode == 0,
|
|
"python": str(python),
|
|
"output": result.stdout[-500:] if result.stdout else "",
|
|
"error": result.stderr[-300:] if result.stderr else "",
|
|
})
|
|
except subprocess.TimeoutExpired:
|
|
results.append({"step": "writer", "success": False, "python": str(python), "error": "타임아웃"})
|
|
except Exception as e:
|
|
results.append({"step": "writer", "success": False, "python": str(python), "error": str(e)})
|
|
else:
|
|
results.append({"step": "writer", "success": False, "python": str(python), "error": "파일 없음"})
|
|
|
|
return {"python": str(python), "results": results}
|